UNPKG

641 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 // Split the content into individual lines but capture the newline sequence
57 // that separated each line. This is important because the actual sequence is
58 // needed to properly take into account the full line length for offset
59 // comparison
60 let lines = source.split(/(\r?\n)/);
61 // Separate the lines and newline sequences into separate arrays for easier referencing
62 const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
63 lines = lines.filter((_, idx) => idx % 2 === 0);
64 let count = 0;
65 const res = [];
66 for (let i = 0; i < lines.length; i++) {
67 count +=
68 lines[i].length +
69 ((newlineSequences[i] && newlineSequences[i].length) || 0);
70 if (count >= start) {
71 for (let j = i - range; j <= i + range || end > count; j++) {
72 if (j < 0 || j >= lines.length)
73 continue;
74 const line = j + 1;
75 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
76 const lineLength = lines[j].length;
77 const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
78 if (j === i) {
79 // push underline
80 const pad = start - (count - (lineLength + newLineSeqLength));
81 const length = Math.max(1, end > count ? lineLength - pad : end - start);
82 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
83 }
84 else if (j > i) {
85 if (end > count) {
86 const length = Math.max(Math.min(end - count, lineLength), 1);
87 res.push(` | ` + '^'.repeat(length));
88 }
89 count += lineLength + newLineSeqLength;
90 }
91 }
92 break;
93 }
94 }
95 return res.join('\n');
96 }
97
98 /**
99 * On the client we only need to offer special cases for boolean attributes that
100 * have different names from their corresponding dom properties:
101 * - itemscope -> N/A
102 * - allowfullscreen -> allowFullscreen
103 * - formnovalidate -> formNoValidate
104 * - ismap -> isMap
105 * - nomodule -> noModule
106 * - novalidate -> noValidate
107 * - readonly -> readOnly
108 */
109 const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
110 const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
111 /**
112 * Boolean attributes should be included if the value is truthy or ''.
113 * e.g. `<select multiple>` compiles to `{ multiple: '' }`
114 */
115 function includeBooleanAttr(value) {
116 return !!value || value === '';
117 }
118
119 function normalizeStyle(value) {
120 if (isArray(value)) {
121 const res = {};
122 for (let i = 0; i < value.length; i++) {
123 const item = value[i];
124 const normalized = isString(item)
125 ? parseStringStyle(item)
126 : normalizeStyle(item);
127 if (normalized) {
128 for (const key in normalized) {
129 res[key] = normalized[key];
130 }
131 }
132 }
133 return res;
134 }
135 else if (isString(value)) {
136 return value;
137 }
138 else if (isObject(value)) {
139 return value;
140 }
141 }
142 const listDelimiterRE = /;(?![^(]*\))/g;
143 const propertyDelimiterRE = /:(.+)/;
144 function parseStringStyle(cssText) {
145 const ret = {};
146 cssText.split(listDelimiterRE).forEach(item => {
147 if (item) {
148 const tmp = item.split(propertyDelimiterRE);
149 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
150 }
151 });
152 return ret;
153 }
154 function normalizeClass(value) {
155 let res = '';
156 if (isString(value)) {
157 res = value;
158 }
159 else if (isArray(value)) {
160 for (let i = 0; i < value.length; i++) {
161 const normalized = normalizeClass(value[i]);
162 if (normalized) {
163 res += normalized + ' ';
164 }
165 }
166 }
167 else if (isObject(value)) {
168 for (const name in value) {
169 if (value[name]) {
170 res += name + ' ';
171 }
172 }
173 }
174 return res.trim();
175 }
176 function normalizeProps(props) {
177 if (!props)
178 return null;
179 let { class: klass, style } = props;
180 if (klass && !isString(klass)) {
181 props.class = normalizeClass(klass);
182 }
183 if (style) {
184 props.style = normalizeStyle(style);
185 }
186 return props;
187 }
188
189 // These tag configs are shared between compiler-dom and runtime-dom, so they
190 // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
191 const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
192 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
193 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
194 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
195 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
196 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
197 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
198 'option,output,progress,select,textarea,details,dialog,menu,' +
199 'summary,template,blockquote,iframe,tfoot';
200 // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
201 const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
202 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
203 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
204 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
205 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
206 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
207 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
208 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
209 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
210 'text,textPath,title,tspan,unknown,use,view';
211 const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
212 /**
213 * Compiler only.
214 * Do NOT use in runtime code paths unless behind `true` flag.
215 */
216 const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
217 /**
218 * Compiler only.
219 * Do NOT use in runtime code paths unless behind `true` flag.
220 */
221 const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
222 /**
223 * Compiler only.
224 * Do NOT use in runtime code paths unless behind `true` flag.
225 */
226 const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
227
228 function looseCompareArrays(a, b) {
229 if (a.length !== b.length)
230 return false;
231 let equal = true;
232 for (let i = 0; equal && i < a.length; i++) {
233 equal = looseEqual(a[i], b[i]);
234 }
235 return equal;
236 }
237 function looseEqual(a, b) {
238 if (a === b)
239 return true;
240 let aValidType = isDate(a);
241 let bValidType = isDate(b);
242 if (aValidType || bValidType) {
243 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
244 }
245 aValidType = isSymbol(a);
246 bValidType = isSymbol(b);
247 if (aValidType || bValidType) {
248 return a === b;
249 }
250 aValidType = isArray(a);
251 bValidType = isArray(b);
252 if (aValidType || bValidType) {
253 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
254 }
255 aValidType = isObject(a);
256 bValidType = isObject(b);
257 if (aValidType || bValidType) {
258 /* istanbul ignore if: this if will probably never be called */
259 if (!aValidType || !bValidType) {
260 return false;
261 }
262 const aKeysCount = Object.keys(a).length;
263 const bKeysCount = Object.keys(b).length;
264 if (aKeysCount !== bKeysCount) {
265 return false;
266 }
267 for (const key in a) {
268 const aHasKey = a.hasOwnProperty(key);
269 const bHasKey = b.hasOwnProperty(key);
270 if ((aHasKey && !bHasKey) ||
271 (!aHasKey && bHasKey) ||
272 !looseEqual(a[key], b[key])) {
273 return false;
274 }
275 }
276 }
277 return String(a) === String(b);
278 }
279 function looseIndexOf(arr, val) {
280 return arr.findIndex(item => looseEqual(item, val));
281 }
282
283 /**
284 * For converting {{ interpolation }} values to displayed strings.
285 * @private
286 */
287 const toDisplayString = (val) => {
288 return isString(val)
289 ? val
290 : val == null
291 ? ''
292 : isArray(val) ||
293 (isObject(val) &&
294 (val.toString === objectToString || !isFunction(val.toString)))
295 ? JSON.stringify(val, replacer, 2)
296 : String(val);
297 };
298 const replacer = (_key, val) => {
299 // can't use isRef here since @vue/shared has no deps
300 if (val && val.__v_isRef) {
301 return replacer(_key, val.value);
302 }
303 else if (isMap(val)) {
304 return {
305 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
306 entries[`${key} =>`] = val;
307 return entries;
308 }, {})
309 };
310 }
311 else if (isSet(val)) {
312 return {
313 [`Set(${val.size})`]: [...val.values()]
314 };
315 }
316 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
317 return String(val);
318 }
319 return val;
320 };
321
322 const EMPTY_OBJ = Object.freeze({})
323 ;
324 const EMPTY_ARR = Object.freeze([]) ;
325 const NOOP = () => { };
326 /**
327 * Always return false.
328 */
329 const NO = () => false;
330 const onRE = /^on[^a-z]/;
331 const isOn = (key) => onRE.test(key);
332 const isModelListener = (key) => key.startsWith('onUpdate:');
333 const extend = Object.assign;
334 const remove = (arr, el) => {
335 const i = arr.indexOf(el);
336 if (i > -1) {
337 arr.splice(i, 1);
338 }
339 };
340 const hasOwnProperty = Object.prototype.hasOwnProperty;
341 const hasOwn = (val, key) => hasOwnProperty.call(val, key);
342 const isArray = Array.isArray;
343 const isMap = (val) => toTypeString(val) === '[object Map]';
344 const isSet = (val) => toTypeString(val) === '[object Set]';
345 const isDate = (val) => toTypeString(val) === '[object Date]';
346 const isFunction = (val) => typeof val === 'function';
347 const isString = (val) => typeof val === 'string';
348 const isSymbol = (val) => typeof val === 'symbol';
349 const isObject = (val) => val !== null && typeof val === 'object';
350 const isPromise = (val) => {
351 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
352 };
353 const objectToString = Object.prototype.toString;
354 const toTypeString = (value) => objectToString.call(value);
355 const toRawType = (value) => {
356 // extract "RawType" from strings like "[object RawType]"
357 return toTypeString(value).slice(8, -1);
358 };
359 const isPlainObject = (val) => toTypeString(val) === '[object Object]';
360 const isIntegerKey = (key) => isString(key) &&
361 key !== 'NaN' &&
362 key[0] !== '-' &&
363 '' + parseInt(key, 10) === key;
364 const isReservedProp = /*#__PURE__*/ makeMap(
365 // the leading comma is intentional so empty string "" is also included
366 ',key,ref,ref_for,ref_key,' +
367 'onVnodeBeforeMount,onVnodeMounted,' +
368 'onVnodeBeforeUpdate,onVnodeUpdated,' +
369 'onVnodeBeforeUnmount,onVnodeUnmounted');
370 const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
371 const cacheStringFunction = (fn) => {
372 const cache = Object.create(null);
373 return ((str) => {
374 const hit = cache[str];
375 return hit || (cache[str] = fn(str));
376 });
377 };
378 const camelizeRE = /-(\w)/g;
379 /**
380 * @private
381 */
382 const camelize = cacheStringFunction((str) => {
383 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
384 });
385 const hyphenateRE = /\B([A-Z])/g;
386 /**
387 * @private
388 */
389 const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
390 /**
391 * @private
392 */
393 const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
394 /**
395 * @private
396 */
397 const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
398 // compare whether a value has changed, accounting for NaN.
399 const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
400 const invokeArrayFns = (fns, arg) => {
401 for (let i = 0; i < fns.length; i++) {
402 fns[i](arg);
403 }
404 };
405 const def = (obj, key, value) => {
406 Object.defineProperty(obj, key, {
407 configurable: true,
408 enumerable: false,
409 value
410 });
411 };
412 const toNumber = (val) => {
413 const n = parseFloat(val);
414 return isNaN(n) ? val : n;
415 };
416 let _globalThis;
417 const getGlobalThis = () => {
418 return (_globalThis ||
419 (_globalThis =
420 typeof globalThis !== 'undefined'
421 ? globalThis
422 : typeof self !== 'undefined'
423 ? self
424 : typeof window !== 'undefined'
425 ? window
426 : typeof global !== 'undefined'
427 ? global
428 : {}));
429 };
430
431 function warn(msg, ...args) {
432 console.warn(`[Vue warn] ${msg}`, ...args);
433 }
434
435 let activeEffectScope;
436 class EffectScope {
437 constructor(detached = false) {
438 /**
439 * @internal
440 */
441 this.active = true;
442 /**
443 * @internal
444 */
445 this.effects = [];
446 /**
447 * @internal
448 */
449 this.cleanups = [];
450 if (!detached && activeEffectScope) {
451 this.parent = activeEffectScope;
452 this.index =
453 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
454 }
455 }
456 run(fn) {
457 if (this.active) {
458 const currentEffectScope = activeEffectScope;
459 try {
460 activeEffectScope = this;
461 return fn();
462 }
463 finally {
464 activeEffectScope = currentEffectScope;
465 }
466 }
467 else {
468 warn(`cannot run an inactive effect scope.`);
469 }
470 }
471 /**
472 * This should only be called on non-detached scopes
473 * @internal
474 */
475 on() {
476 activeEffectScope = this;
477 }
478 /**
479 * This should only be called on non-detached scopes
480 * @internal
481 */
482 off() {
483 activeEffectScope = this.parent;
484 }
485 stop(fromParent) {
486 if (this.active) {
487 let i, l;
488 for (i = 0, l = this.effects.length; i < l; i++) {
489 this.effects[i].stop();
490 }
491 for (i = 0, l = this.cleanups.length; i < l; i++) {
492 this.cleanups[i]();
493 }
494 if (this.scopes) {
495 for (i = 0, l = this.scopes.length; i < l; i++) {
496 this.scopes[i].stop(true);
497 }
498 }
499 // nested scope, dereference from parent to avoid memory leaks
500 if (this.parent && !fromParent) {
501 // optimized O(1) removal
502 const last = this.parent.scopes.pop();
503 if (last && last !== this) {
504 this.parent.scopes[this.index] = last;
505 last.index = this.index;
506 }
507 }
508 this.active = false;
509 }
510 }
511 }
512 function effectScope(detached) {
513 return new EffectScope(detached);
514 }
515 function recordEffectScope(effect, scope = activeEffectScope) {
516 if (scope && scope.active) {
517 scope.effects.push(effect);
518 }
519 }
520 function getCurrentScope() {
521 return activeEffectScope;
522 }
523 function onScopeDispose(fn) {
524 if (activeEffectScope) {
525 activeEffectScope.cleanups.push(fn);
526 }
527 else {
528 warn(`onScopeDispose() is called when there is no active effect scope` +
529 ` to be associated with.`);
530 }
531 }
532
533 const createDep = (effects) => {
534 const dep = new Set(effects);
535 dep.w = 0;
536 dep.n = 0;
537 return dep;
538 };
539 const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
540 const newTracked = (dep) => (dep.n & trackOpBit) > 0;
541 const initDepMarkers = ({ deps }) => {
542 if (deps.length) {
543 for (let i = 0; i < deps.length; i++) {
544 deps[i].w |= trackOpBit; // set was tracked
545 }
546 }
547 };
548 const finalizeDepMarkers = (effect) => {
549 const { deps } = effect;
550 if (deps.length) {
551 let ptr = 0;
552 for (let i = 0; i < deps.length; i++) {
553 const dep = deps[i];
554 if (wasTracked(dep) && !newTracked(dep)) {
555 dep.delete(effect);
556 }
557 else {
558 deps[ptr++] = dep;
559 }
560 // clear bits
561 dep.w &= ~trackOpBit;
562 dep.n &= ~trackOpBit;
563 }
564 deps.length = ptr;
565 }
566 };
567
568 const targetMap = new WeakMap();
569 // The number of effects currently being tracked recursively.
570 let effectTrackDepth = 0;
571 let trackOpBit = 1;
572 /**
573 * The bitwise track markers support at most 30 levels of recursion.
574 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
575 * When recursion depth is greater, fall back to using a full cleanup.
576 */
577 const maxMarkerBits = 30;
578 let activeEffect;
579 const ITERATE_KEY = Symbol('iterate' );
580 const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
581 class ReactiveEffect {
582 constructor(fn, scheduler = null, scope) {
583 this.fn = fn;
584 this.scheduler = scheduler;
585 this.active = true;
586 this.deps = [];
587 this.parent = undefined;
588 recordEffectScope(this, scope);
589 }
590 run() {
591 if (!this.active) {
592 return this.fn();
593 }
594 let parent = activeEffect;
595 let lastShouldTrack = shouldTrack;
596 while (parent) {
597 if (parent === this) {
598 return;
599 }
600 parent = parent.parent;
601 }
602 try {
603 this.parent = activeEffect;
604 activeEffect = this;
605 shouldTrack = true;
606 trackOpBit = 1 << ++effectTrackDepth;
607 if (effectTrackDepth <= maxMarkerBits) {
608 initDepMarkers(this);
609 }
610 else {
611 cleanupEffect(this);
612 }
613 return this.fn();
614 }
615 finally {
616 if (effectTrackDepth <= maxMarkerBits) {
617 finalizeDepMarkers(this);
618 }
619 trackOpBit = 1 << --effectTrackDepth;
620 activeEffect = this.parent;
621 shouldTrack = lastShouldTrack;
622 this.parent = undefined;
623 if (this.deferStop) {
624 this.stop();
625 }
626 }
627 }
628 stop() {
629 // stopped while running itself - defer the cleanup
630 if (activeEffect === this) {
631 this.deferStop = true;
632 }
633 else if (this.active) {
634 cleanupEffect(this);
635 if (this.onStop) {
636 this.onStop();
637 }
638 this.active = false;
639 }
640 }
641 }
642 function cleanupEffect(effect) {
643 const { deps } = effect;
644 if (deps.length) {
645 for (let i = 0; i < deps.length; i++) {
646 deps[i].delete(effect);
647 }
648 deps.length = 0;
649 }
650 }
651 function effect(fn, options) {
652 if (fn.effect) {
653 fn = fn.effect.fn;
654 }
655 const _effect = new ReactiveEffect(fn);
656 if (options) {
657 extend(_effect, options);
658 if (options.scope)
659 recordEffectScope(_effect, options.scope);
660 }
661 if (!options || !options.lazy) {
662 _effect.run();
663 }
664 const runner = _effect.run.bind(_effect);
665 runner.effect = _effect;
666 return runner;
667 }
668 function stop(runner) {
669 runner.effect.stop();
670 }
671 let shouldTrack = true;
672 const trackStack = [];
673 function pauseTracking() {
674 trackStack.push(shouldTrack);
675 shouldTrack = false;
676 }
677 function resetTracking() {
678 const last = trackStack.pop();
679 shouldTrack = last === undefined ? true : last;
680 }
681 function track(target, type, key) {
682 if (shouldTrack && activeEffect) {
683 let depsMap = targetMap.get(target);
684 if (!depsMap) {
685 targetMap.set(target, (depsMap = new Map()));
686 }
687 let dep = depsMap.get(key);
688 if (!dep) {
689 depsMap.set(key, (dep = createDep()));
690 }
691 const eventInfo = { effect: activeEffect, target, type, key }
692 ;
693 trackEffects(dep, eventInfo);
694 }
695 }
696 function trackEffects(dep, debuggerEventExtraInfo) {
697 let shouldTrack = false;
698 if (effectTrackDepth <= maxMarkerBits) {
699 if (!newTracked(dep)) {
700 dep.n |= trackOpBit; // set newly tracked
701 shouldTrack = !wasTracked(dep);
702 }
703 }
704 else {
705 // Full cleanup mode.
706 shouldTrack = !dep.has(activeEffect);
707 }
708 if (shouldTrack) {
709 dep.add(activeEffect);
710 activeEffect.deps.push(dep);
711 if (activeEffect.onTrack) {
712 activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo));
713 }
714 }
715 }
716 function trigger(target, type, key, newValue, oldValue, oldTarget) {
717 const depsMap = targetMap.get(target);
718 if (!depsMap) {
719 // never been tracked
720 return;
721 }
722 let deps = [];
723 if (type === "clear" /* CLEAR */) {
724 // collection being cleared
725 // trigger all effects for target
726 deps = [...depsMap.values()];
727 }
728 else if (key === 'length' && isArray(target)) {
729 depsMap.forEach((dep, key) => {
730 if (key === 'length' || key >= newValue) {
731 deps.push(dep);
732 }
733 });
734 }
735 else {
736 // schedule runs for SET | ADD | DELETE
737 if (key !== void 0) {
738 deps.push(depsMap.get(key));
739 }
740 // also run for iteration key on ADD | DELETE | Map.SET
741 switch (type) {
742 case "add" /* ADD */:
743 if (!isArray(target)) {
744 deps.push(depsMap.get(ITERATE_KEY));
745 if (isMap(target)) {
746 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
747 }
748 }
749 else if (isIntegerKey(key)) {
750 // new index added to array -> length changes
751 deps.push(depsMap.get('length'));
752 }
753 break;
754 case "delete" /* DELETE */:
755 if (!isArray(target)) {
756 deps.push(depsMap.get(ITERATE_KEY));
757 if (isMap(target)) {
758 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
759 }
760 }
761 break;
762 case "set" /* SET */:
763 if (isMap(target)) {
764 deps.push(depsMap.get(ITERATE_KEY));
765 }
766 break;
767 }
768 }
769 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
770 ;
771 if (deps.length === 1) {
772 if (deps[0]) {
773 {
774 triggerEffects(deps[0], eventInfo);
775 }
776 }
777 }
778 else {
779 const effects = [];
780 for (const dep of deps) {
781 if (dep) {
782 effects.push(...dep);
783 }
784 }
785 {
786 triggerEffects(createDep(effects), eventInfo);
787 }
788 }
789 }
790 function triggerEffects(dep, debuggerEventExtraInfo) {
791 // spread into array for stabilization
792 const effects = isArray(dep) ? dep : [...dep];
793 for (const effect of effects) {
794 if (effect.computed) {
795 triggerEffect(effect, debuggerEventExtraInfo);
796 }
797 }
798 for (const effect of effects) {
799 if (!effect.computed) {
800 triggerEffect(effect, debuggerEventExtraInfo);
801 }
802 }
803 }
804 function triggerEffect(effect, debuggerEventExtraInfo) {
805 if (effect !== activeEffect || effect.allowRecurse) {
806 if (effect.onTrigger) {
807 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
808 }
809 if (effect.scheduler) {
810 effect.scheduler();
811 }
812 else {
813 effect.run();
814 }
815 }
816 }
817
818 const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
819 const builtInSymbols = new Set(
820 /*#__PURE__*/
821 Object.getOwnPropertyNames(Symbol)
822 // ios10.x Object.getOwnPropertyNames(Symbol) can enumerate 'arguments' and 'caller'
823 // but accessing them on Symbol leads to TypeError because Symbol is a strict mode
824 // function
825 .filter(key => key !== 'arguments' && key !== 'caller')
826 .map(key => Symbol[key])
827 .filter(isSymbol));
828 const get = /*#__PURE__*/ createGetter();
829 const shallowGet = /*#__PURE__*/ createGetter(false, true);
830 const readonlyGet = /*#__PURE__*/ createGetter(true);
831 const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
832 const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
833 function createArrayInstrumentations() {
834 const instrumentations = {};
835 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
836 instrumentations[key] = function (...args) {
837 const arr = toRaw(this);
838 for (let i = 0, l = this.length; i < l; i++) {
839 track(arr, "get" /* GET */, i + '');
840 }
841 // we run the method using the original args first (which may be reactive)
842 const res = arr[key](...args);
843 if (res === -1 || res === false) {
844 // if that didn't work, run it again using raw values.
845 return arr[key](...args.map(toRaw));
846 }
847 else {
848 return res;
849 }
850 };
851 });
852 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
853 instrumentations[key] = function (...args) {
854 pauseTracking();
855 const res = toRaw(this)[key].apply(this, args);
856 resetTracking();
857 return res;
858 };
859 });
860 return instrumentations;
861 }
862 function createGetter(isReadonly = false, shallow = false) {
863 return function get(target, key, receiver) {
864 if (key === "__v_isReactive" /* IS_REACTIVE */) {
865 return !isReadonly;
866 }
867 else if (key === "__v_isReadonly" /* IS_READONLY */) {
868 return isReadonly;
869 }
870 else if (key === "__v_isShallow" /* IS_SHALLOW */) {
871 return shallow;
872 }
873 else if (key === "__v_raw" /* RAW */ &&
874 receiver ===
875 (isReadonly
876 ? shallow
877 ? shallowReadonlyMap
878 : readonlyMap
879 : shallow
880 ? shallowReactiveMap
881 : reactiveMap).get(target)) {
882 return target;
883 }
884 const targetIsArray = isArray(target);
885 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
886 return Reflect.get(arrayInstrumentations, key, receiver);
887 }
888 const res = Reflect.get(target, key, receiver);
889 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
890 return res;
891 }
892 if (!isReadonly) {
893 track(target, "get" /* GET */, key);
894 }
895 if (shallow) {
896 return res;
897 }
898 if (isRef(res)) {
899 // ref unwrapping - skip unwrap for Array + integer key.
900 return targetIsArray && isIntegerKey(key) ? res : res.value;
901 }
902 if (isObject(res)) {
903 // Convert returned value into a proxy as well. we do the isObject check
904 // here to avoid invalid value warning. Also need to lazy access readonly
905 // and reactive here to avoid circular dependency.
906 return isReadonly ? readonly(res) : reactive(res);
907 }
908 return res;
909 };
910 }
911 const set = /*#__PURE__*/ createSetter();
912 const shallowSet = /*#__PURE__*/ createSetter(true);
913 function createSetter(shallow = false) {
914 return function set(target, key, value, receiver) {
915 let oldValue = target[key];
916 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
917 return false;
918 }
919 if (!shallow && !isReadonly(value)) {
920 if (!isShallow(value)) {
921 value = toRaw(value);
922 oldValue = toRaw(oldValue);
923 }
924 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
925 oldValue.value = value;
926 return true;
927 }
928 }
929 const hadKey = isArray(target) && isIntegerKey(key)
930 ? Number(key) < target.length
931 : hasOwn(target, key);
932 const result = Reflect.set(target, key, value, receiver);
933 // don't trigger if target is something up in the prototype chain of original
934 if (target === toRaw(receiver)) {
935 if (!hadKey) {
936 trigger(target, "add" /* ADD */, key, value);
937 }
938 else if (hasChanged(value, oldValue)) {
939 trigger(target, "set" /* SET */, key, value, oldValue);
940 }
941 }
942 return result;
943 };
944 }
945 function deleteProperty(target, key) {
946 const hadKey = hasOwn(target, key);
947 const oldValue = target[key];
948 const result = Reflect.deleteProperty(target, key);
949 if (result && hadKey) {
950 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
951 }
952 return result;
953 }
954 function has(target, key) {
955 const result = Reflect.has(target, key);
956 if (!isSymbol(key) || !builtInSymbols.has(key)) {
957 track(target, "has" /* HAS */, key);
958 }
959 return result;
960 }
961 function ownKeys(target) {
962 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
963 return Reflect.ownKeys(target);
964 }
965 const mutableHandlers = {
966 get,
967 set,
968 deleteProperty,
969 has,
970 ownKeys
971 };
972 const readonlyHandlers = {
973 get: readonlyGet,
974 set(target, key) {
975 {
976 warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
977 }
978 return true;
979 },
980 deleteProperty(target, key) {
981 {
982 warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
983 }
984 return true;
985 }
986 };
987 const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
988 get: shallowGet,
989 set: shallowSet
990 });
991 // Props handlers are special in the sense that it should not unwrap top-level
992 // refs (in order to allow refs to be explicitly passed down), but should
993 // retain the reactivity of the normal readonly object.
994 const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
995 get: shallowReadonlyGet
996 });
997
998 const toShallow = (value) => value;
999 const getProto = (v) => Reflect.getPrototypeOf(v);
1000 function get$1(target, key, isReadonly = false, isShallow = false) {
1001 // #1772: readonly(reactive(Map)) should return readonly + reactive version
1002 // of the value
1003 target = target["__v_raw" /* RAW */];
1004 const rawTarget = toRaw(target);
1005 const rawKey = toRaw(key);
1006 if (!isReadonly) {
1007 if (key !== rawKey) {
1008 track(rawTarget, "get" /* GET */, key);
1009 }
1010 track(rawTarget, "get" /* GET */, rawKey);
1011 }
1012 const { has } = getProto(rawTarget);
1013 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1014 if (has.call(rawTarget, key)) {
1015 return wrap(target.get(key));
1016 }
1017 else if (has.call(rawTarget, rawKey)) {
1018 return wrap(target.get(rawKey));
1019 }
1020 else if (target !== rawTarget) {
1021 // #3602 readonly(reactive(Map))
1022 // ensure that the nested reactive `Map` can do tracking for itself
1023 target.get(key);
1024 }
1025 }
1026 function has$1(key, isReadonly = false) {
1027 const target = this["__v_raw" /* RAW */];
1028 const rawTarget = toRaw(target);
1029 const rawKey = toRaw(key);
1030 if (!isReadonly) {
1031 if (key !== rawKey) {
1032 track(rawTarget, "has" /* HAS */, key);
1033 }
1034 track(rawTarget, "has" /* HAS */, rawKey);
1035 }
1036 return key === rawKey
1037 ? target.has(key)
1038 : target.has(key) || target.has(rawKey);
1039 }
1040 function size(target, isReadonly = false) {
1041 target = target["__v_raw" /* RAW */];
1042 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
1043 return Reflect.get(target, 'size', target);
1044 }
1045 function add(value) {
1046 value = toRaw(value);
1047 const target = toRaw(this);
1048 const proto = getProto(target);
1049 const hadKey = proto.has.call(target, value);
1050 if (!hadKey) {
1051 target.add(value);
1052 trigger(target, "add" /* ADD */, value, value);
1053 }
1054 return this;
1055 }
1056 function set$1(key, value) {
1057 value = toRaw(value);
1058 const target = toRaw(this);
1059 const { has, get } = getProto(target);
1060 let hadKey = has.call(target, key);
1061 if (!hadKey) {
1062 key = toRaw(key);
1063 hadKey = has.call(target, key);
1064 }
1065 else {
1066 checkIdentityKeys(target, has, key);
1067 }
1068 const oldValue = get.call(target, key);
1069 target.set(key, value);
1070 if (!hadKey) {
1071 trigger(target, "add" /* ADD */, key, value);
1072 }
1073 else if (hasChanged(value, oldValue)) {
1074 trigger(target, "set" /* SET */, key, value, oldValue);
1075 }
1076 return this;
1077 }
1078 function deleteEntry(key) {
1079 const target = toRaw(this);
1080 const { has, get } = getProto(target);
1081 let hadKey = has.call(target, key);
1082 if (!hadKey) {
1083 key = toRaw(key);
1084 hadKey = has.call(target, key);
1085 }
1086 else {
1087 checkIdentityKeys(target, has, key);
1088 }
1089 const oldValue = get ? get.call(target, key) : undefined;
1090 // forward the operation before queueing reactions
1091 const result = target.delete(key);
1092 if (hadKey) {
1093 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1094 }
1095 return result;
1096 }
1097 function clear() {
1098 const target = toRaw(this);
1099 const hadItems = target.size !== 0;
1100 const oldTarget = isMap(target)
1101 ? new Map(target)
1102 : new Set(target)
1103 ;
1104 // forward the operation before queueing reactions
1105 const result = target.clear();
1106 if (hadItems) {
1107 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1108 }
1109 return result;
1110 }
1111 function createForEach(isReadonly, isShallow) {
1112 return function forEach(callback, thisArg) {
1113 const observed = this;
1114 const target = observed["__v_raw" /* RAW */];
1115 const rawTarget = toRaw(target);
1116 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1117 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1118 return target.forEach((value, key) => {
1119 // important: make sure the callback is
1120 // 1. invoked with the reactive map as `this` and 3rd arg
1121 // 2. the value received should be a corresponding reactive/readonly.
1122 return callback.call(thisArg, wrap(value), wrap(key), observed);
1123 });
1124 };
1125 }
1126 function createIterableMethod(method, isReadonly, isShallow) {
1127 return function (...args) {
1128 const target = this["__v_raw" /* RAW */];
1129 const rawTarget = toRaw(target);
1130 const targetIsMap = isMap(rawTarget);
1131 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1132 const isKeyOnly = method === 'keys' && targetIsMap;
1133 const innerIterator = target[method](...args);
1134 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1135 !isReadonly &&
1136 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1137 // return a wrapped iterator which returns observed versions of the
1138 // values emitted from the real iterator
1139 return {
1140 // iterator protocol
1141 next() {
1142 const { value, done } = innerIterator.next();
1143 return done
1144 ? { value, done }
1145 : {
1146 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1147 done
1148 };
1149 },
1150 // iterable protocol
1151 [Symbol.iterator]() {
1152 return this;
1153 }
1154 };
1155 };
1156 }
1157 function createReadonlyMethod(type) {
1158 return function (...args) {
1159 {
1160 const key = args[0] ? `on key "${args[0]}" ` : ``;
1161 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1162 }
1163 return type === "delete" /* DELETE */ ? false : this;
1164 };
1165 }
1166 function createInstrumentations() {
1167 const mutableInstrumentations = {
1168 get(key) {
1169 return get$1(this, key);
1170 },
1171 get size() {
1172 return size(this);
1173 },
1174 has: has$1,
1175 add,
1176 set: set$1,
1177 delete: deleteEntry,
1178 clear,
1179 forEach: createForEach(false, false)
1180 };
1181 const shallowInstrumentations = {
1182 get(key) {
1183 return get$1(this, key, false, true);
1184 },
1185 get size() {
1186 return size(this);
1187 },
1188 has: has$1,
1189 add,
1190 set: set$1,
1191 delete: deleteEntry,
1192 clear,
1193 forEach: createForEach(false, true)
1194 };
1195 const readonlyInstrumentations = {
1196 get(key) {
1197 return get$1(this, key, true);
1198 },
1199 get size() {
1200 return size(this, true);
1201 },
1202 has(key) {
1203 return has$1.call(this, key, true);
1204 },
1205 add: createReadonlyMethod("add" /* ADD */),
1206 set: createReadonlyMethod("set" /* SET */),
1207 delete: createReadonlyMethod("delete" /* DELETE */),
1208 clear: createReadonlyMethod("clear" /* CLEAR */),
1209 forEach: createForEach(true, false)
1210 };
1211 const shallowReadonlyInstrumentations = {
1212 get(key) {
1213 return get$1(this, key, true, true);
1214 },
1215 get size() {
1216 return size(this, true);
1217 },
1218 has(key) {
1219 return has$1.call(this, key, true);
1220 },
1221 add: createReadonlyMethod("add" /* ADD */),
1222 set: createReadonlyMethod("set" /* SET */),
1223 delete: createReadonlyMethod("delete" /* DELETE */),
1224 clear: createReadonlyMethod("clear" /* CLEAR */),
1225 forEach: createForEach(true, true)
1226 };
1227 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1228 iteratorMethods.forEach(method => {
1229 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1230 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1231 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1232 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1233 });
1234 return [
1235 mutableInstrumentations,
1236 readonlyInstrumentations,
1237 shallowInstrumentations,
1238 shallowReadonlyInstrumentations
1239 ];
1240 }
1241 const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1242 function createInstrumentationGetter(isReadonly, shallow) {
1243 const instrumentations = shallow
1244 ? isReadonly
1245 ? shallowReadonlyInstrumentations
1246 : shallowInstrumentations
1247 : isReadonly
1248 ? readonlyInstrumentations
1249 : mutableInstrumentations;
1250 return (target, key, receiver) => {
1251 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1252 return !isReadonly;
1253 }
1254 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1255 return isReadonly;
1256 }
1257 else if (key === "__v_raw" /* RAW */) {
1258 return target;
1259 }
1260 return Reflect.get(hasOwn(instrumentations, key) && key in target
1261 ? instrumentations
1262 : target, key, receiver);
1263 };
1264 }
1265 const mutableCollectionHandlers = {
1266 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1267 };
1268 const shallowCollectionHandlers = {
1269 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1270 };
1271 const readonlyCollectionHandlers = {
1272 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1273 };
1274 const shallowReadonlyCollectionHandlers = {
1275 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1276 };
1277 function checkIdentityKeys(target, has, key) {
1278 const rawKey = toRaw(key);
1279 if (rawKey !== key && has.call(target, rawKey)) {
1280 const type = toRawType(target);
1281 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1282 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1283 `which can lead to inconsistencies. ` +
1284 `Avoid differentiating between the raw and reactive versions ` +
1285 `of an object and only use the reactive version if possible.`);
1286 }
1287 }
1288
1289 const reactiveMap = new WeakMap();
1290 const shallowReactiveMap = new WeakMap();
1291 const readonlyMap = new WeakMap();
1292 const shallowReadonlyMap = new WeakMap();
1293 function targetTypeMap(rawType) {
1294 switch (rawType) {
1295 case 'Object':
1296 case 'Array':
1297 return 1 /* COMMON */;
1298 case 'Map':
1299 case 'Set':
1300 case 'WeakMap':
1301 case 'WeakSet':
1302 return 2 /* COLLECTION */;
1303 default:
1304 return 0 /* INVALID */;
1305 }
1306 }
1307 function getTargetType(value) {
1308 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1309 ? 0 /* INVALID */
1310 : targetTypeMap(toRawType(value));
1311 }
1312 function reactive(target) {
1313 // if trying to observe a readonly proxy, return the readonly version.
1314 if (isReadonly(target)) {
1315 return target;
1316 }
1317 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1318 }
1319 /**
1320 * Return a shallowly-reactive copy of the original object, where only the root
1321 * level properties are reactive. It also does not auto-unwrap refs (even at the
1322 * root level).
1323 */
1324 function shallowReactive(target) {
1325 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1326 }
1327 /**
1328 * Creates a readonly copy of the original object. Note the returned copy is not
1329 * made reactive, but `readonly` can be called on an already reactive object.
1330 */
1331 function readonly(target) {
1332 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1333 }
1334 /**
1335 * Returns a reactive-copy of the original object, where only the root level
1336 * properties are readonly, and does NOT unwrap refs nor recursively convert
1337 * returned properties.
1338 * This is used for creating the props proxy object for stateful components.
1339 */
1340 function shallowReadonly(target) {
1341 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1342 }
1343 function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1344 if (!isObject(target)) {
1345 {
1346 console.warn(`value cannot be made reactive: ${String(target)}`);
1347 }
1348 return target;
1349 }
1350 // target is already a Proxy, return it.
1351 // exception: calling readonly() on a reactive object
1352 if (target["__v_raw" /* RAW */] &&
1353 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1354 return target;
1355 }
1356 // target already has corresponding Proxy
1357 const existingProxy = proxyMap.get(target);
1358 if (existingProxy) {
1359 return existingProxy;
1360 }
1361 // only specific value types can be observed.
1362 const targetType = getTargetType(target);
1363 if (targetType === 0 /* INVALID */) {
1364 return target;
1365 }
1366 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1367 proxyMap.set(target, proxy);
1368 return proxy;
1369 }
1370 function isReactive(value) {
1371 if (isReadonly(value)) {
1372 return isReactive(value["__v_raw" /* RAW */]);
1373 }
1374 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1375 }
1376 function isReadonly(value) {
1377 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1378 }
1379 function isShallow(value) {
1380 return !!(value && value["__v_isShallow" /* IS_SHALLOW */]);
1381 }
1382 function isProxy(value) {
1383 return isReactive(value) || isReadonly(value);
1384 }
1385 function toRaw(observed) {
1386 const raw = observed && observed["__v_raw" /* RAW */];
1387 return raw ? toRaw(raw) : observed;
1388 }
1389 function markRaw(value) {
1390 def(value, "__v_skip" /* SKIP */, true);
1391 return value;
1392 }
1393 const toReactive = (value) => isObject(value) ? reactive(value) : value;
1394 const toReadonly = (value) => isObject(value) ? readonly(value) : value;
1395
1396 function trackRefValue(ref) {
1397 if (shouldTrack && activeEffect) {
1398 ref = toRaw(ref);
1399 {
1400 trackEffects(ref.dep || (ref.dep = createDep()), {
1401 target: ref,
1402 type: "get" /* GET */,
1403 key: 'value'
1404 });
1405 }
1406 }
1407 }
1408 function triggerRefValue(ref, newVal) {
1409 ref = toRaw(ref);
1410 if (ref.dep) {
1411 {
1412 triggerEffects(ref.dep, {
1413 target: ref,
1414 type: "set" /* SET */,
1415 key: 'value',
1416 newValue: newVal
1417 });
1418 }
1419 }
1420 }
1421 function isRef(r) {
1422 return !!(r && r.__v_isRef === true);
1423 }
1424 function ref(value) {
1425 return createRef(value, false);
1426 }
1427 function shallowRef(value) {
1428 return createRef(value, true);
1429 }
1430 function createRef(rawValue, shallow) {
1431 if (isRef(rawValue)) {
1432 return rawValue;
1433 }
1434 return new RefImpl(rawValue, shallow);
1435 }
1436 class RefImpl {
1437 constructor(value, __v_isShallow) {
1438 this.__v_isShallow = __v_isShallow;
1439 this.dep = undefined;
1440 this.__v_isRef = true;
1441 this._rawValue = __v_isShallow ? value : toRaw(value);
1442 this._value = __v_isShallow ? value : toReactive(value);
1443 }
1444 get value() {
1445 trackRefValue(this);
1446 return this._value;
1447 }
1448 set value(newVal) {
1449 newVal = this.__v_isShallow ? newVal : toRaw(newVal);
1450 if (hasChanged(newVal, this._rawValue)) {
1451 this._rawValue = newVal;
1452 this._value = this.__v_isShallow ? newVal : toReactive(newVal);
1453 triggerRefValue(this, newVal);
1454 }
1455 }
1456 }
1457 function triggerRef(ref) {
1458 triggerRefValue(ref, ref.value );
1459 }
1460 function unref(ref) {
1461 return isRef(ref) ? ref.value : ref;
1462 }
1463 const shallowUnwrapHandlers = {
1464 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1465 set: (target, key, value, receiver) => {
1466 const oldValue = target[key];
1467 if (isRef(oldValue) && !isRef(value)) {
1468 oldValue.value = value;
1469 return true;
1470 }
1471 else {
1472 return Reflect.set(target, key, value, receiver);
1473 }
1474 }
1475 };
1476 function proxyRefs(objectWithRefs) {
1477 return isReactive(objectWithRefs)
1478 ? objectWithRefs
1479 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1480 }
1481 class CustomRefImpl {
1482 constructor(factory) {
1483 this.dep = undefined;
1484 this.__v_isRef = true;
1485 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1486 this._get = get;
1487 this._set = set;
1488 }
1489 get value() {
1490 return this._get();
1491 }
1492 set value(newVal) {
1493 this._set(newVal);
1494 }
1495 }
1496 function customRef(factory) {
1497 return new CustomRefImpl(factory);
1498 }
1499 function toRefs(object) {
1500 if (!isProxy(object)) {
1501 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1502 }
1503 const ret = isArray(object) ? new Array(object.length) : {};
1504 for (const key in object) {
1505 ret[key] = toRef(object, key);
1506 }
1507 return ret;
1508 }
1509 class ObjectRefImpl {
1510 constructor(_object, _key, _defaultValue) {
1511 this._object = _object;
1512 this._key = _key;
1513 this._defaultValue = _defaultValue;
1514 this.__v_isRef = true;
1515 }
1516 get value() {
1517 const val = this._object[this._key];
1518 return val === undefined ? this._defaultValue : val;
1519 }
1520 set value(newVal) {
1521 this._object[this._key] = newVal;
1522 }
1523 }
1524 function toRef(object, key, defaultValue) {
1525 const val = object[key];
1526 return isRef(val)
1527 ? val
1528 : new ObjectRefImpl(object, key, defaultValue);
1529 }
1530
1531 class ComputedRefImpl {
1532 constructor(getter, _setter, isReadonly, isSSR) {
1533 this._setter = _setter;
1534 this.dep = undefined;
1535 this.__v_isRef = true;
1536 this._dirty = true;
1537 this.effect = new ReactiveEffect(getter, () => {
1538 if (!this._dirty) {
1539 this._dirty = true;
1540 triggerRefValue(this);
1541 }
1542 });
1543 this.effect.computed = this;
1544 this.effect.active = this._cacheable = !isSSR;
1545 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1546 }
1547 get value() {
1548 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1549 const self = toRaw(this);
1550 trackRefValue(self);
1551 if (self._dirty || !self._cacheable) {
1552 self._dirty = false;
1553 self._value = self.effect.run();
1554 }
1555 return self._value;
1556 }
1557 set value(newValue) {
1558 this._setter(newValue);
1559 }
1560 }
1561 function computed(getterOrOptions, debugOptions, isSSR = false) {
1562 let getter;
1563 let setter;
1564 const onlyGetter = isFunction(getterOrOptions);
1565 if (onlyGetter) {
1566 getter = getterOrOptions;
1567 setter = () => {
1568 console.warn('Write operation failed: computed value is readonly');
1569 }
1570 ;
1571 }
1572 else {
1573 getter = getterOrOptions.get;
1574 setter = getterOrOptions.set;
1575 }
1576 const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
1577 if (debugOptions && !isSSR) {
1578 cRef.effect.onTrack = debugOptions.onTrack;
1579 cRef.effect.onTrigger = debugOptions.onTrigger;
1580 }
1581 return cRef;
1582 }
1583
1584 const stack = [];
1585 function pushWarningContext(vnode) {
1586 stack.push(vnode);
1587 }
1588 function popWarningContext() {
1589 stack.pop();
1590 }
1591 function warn$1(msg, ...args) {
1592 // avoid props formatting or warn handler tracking deps that might be mutated
1593 // during patch, leading to infinite recursion.
1594 pauseTracking();
1595 const instance = stack.length ? stack[stack.length - 1].component : null;
1596 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1597 const trace = getComponentTrace();
1598 if (appWarnHandler) {
1599 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1600 msg + args.join(''),
1601 instance && instance.proxy,
1602 trace
1603 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1604 .join('\n'),
1605 trace
1606 ]);
1607 }
1608 else {
1609 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1610 /* istanbul ignore if */
1611 if (trace.length &&
1612 // avoid spamming console during tests
1613 !false) {
1614 warnArgs.push(`\n`, ...formatTrace(trace));
1615 }
1616 console.warn(...warnArgs);
1617 }
1618 resetTracking();
1619 }
1620 function getComponentTrace() {
1621 let currentVNode = stack[stack.length - 1];
1622 if (!currentVNode) {
1623 return [];
1624 }
1625 // we can't just use the stack because it will be incomplete during updates
1626 // that did not start from the root. Re-construct the parent chain using
1627 // instance parent pointers.
1628 const normalizedStack = [];
1629 while (currentVNode) {
1630 const last = normalizedStack[0];
1631 if (last && last.vnode === currentVNode) {
1632 last.recurseCount++;
1633 }
1634 else {
1635 normalizedStack.push({
1636 vnode: currentVNode,
1637 recurseCount: 0
1638 });
1639 }
1640 const parentInstance = currentVNode.component && currentVNode.component.parent;
1641 currentVNode = parentInstance && parentInstance.vnode;
1642 }
1643 return normalizedStack;
1644 }
1645 /* istanbul ignore next */
1646 function formatTrace(trace) {
1647 const logs = [];
1648 trace.forEach((entry, i) => {
1649 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1650 });
1651 return logs;
1652 }
1653 function formatTraceEntry({ vnode, recurseCount }) {
1654 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1655 const isRoot = vnode.component ? vnode.component.parent == null : false;
1656 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1657 const close = `>` + postfix;
1658 return vnode.props
1659 ? [open, ...formatProps(vnode.props), close]
1660 : [open + close];
1661 }
1662 /* istanbul ignore next */
1663 function formatProps(props) {
1664 const res = [];
1665 const keys = Object.keys(props);
1666 keys.slice(0, 3).forEach(key => {
1667 res.push(...formatProp(key, props[key]));
1668 });
1669 if (keys.length > 3) {
1670 res.push(` ...`);
1671 }
1672 return res;
1673 }
1674 /* istanbul ignore next */
1675 function formatProp(key, value, raw) {
1676 if (isString(value)) {
1677 value = JSON.stringify(value);
1678 return raw ? value : [`${key}=${value}`];
1679 }
1680 else if (typeof value === 'number' ||
1681 typeof value === 'boolean' ||
1682 value == null) {
1683 return raw ? value : [`${key}=${value}`];
1684 }
1685 else if (isRef(value)) {
1686 value = formatProp(key, toRaw(value.value), true);
1687 return raw ? value : [`${key}=Ref<`, value, `>`];
1688 }
1689 else if (isFunction(value)) {
1690 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1691 }
1692 else {
1693 value = toRaw(value);
1694 return raw ? value : [`${key}=`, value];
1695 }
1696 }
1697
1698 const ErrorTypeStrings = {
1699 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
1700 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1701 ["c" /* CREATED */]: 'created hook',
1702 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1703 ["m" /* MOUNTED */]: 'mounted hook',
1704 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1705 ["u" /* UPDATED */]: 'updated',
1706 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1707 ["um" /* UNMOUNTED */]: 'unmounted hook',
1708 ["a" /* ACTIVATED */]: 'activated hook',
1709 ["da" /* DEACTIVATED */]: 'deactivated hook',
1710 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1711 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1712 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1713 [0 /* SETUP_FUNCTION */]: 'setup function',
1714 [1 /* RENDER_FUNCTION */]: 'render function',
1715 [2 /* WATCH_GETTER */]: 'watcher getter',
1716 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1717 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1718 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1719 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1720 [7 /* VNODE_HOOK */]: 'vnode hook',
1721 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1722 [9 /* TRANSITION_HOOK */]: 'transition hook',
1723 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1724 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1725 [12 /* FUNCTION_REF */]: 'ref function',
1726 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1727 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1728 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
1729 };
1730 function callWithErrorHandling(fn, instance, type, args) {
1731 let res;
1732 try {
1733 res = args ? fn(...args) : fn();
1734 }
1735 catch (err) {
1736 handleError(err, instance, type);
1737 }
1738 return res;
1739 }
1740 function callWithAsyncErrorHandling(fn, instance, type, args) {
1741 if (isFunction(fn)) {
1742 const res = callWithErrorHandling(fn, instance, type, args);
1743 if (res && isPromise(res)) {
1744 res.catch(err => {
1745 handleError(err, instance, type);
1746 });
1747 }
1748 return res;
1749 }
1750 const values = [];
1751 for (let i = 0; i < fn.length; i++) {
1752 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1753 }
1754 return values;
1755 }
1756 function handleError(err, instance, type, throwInDev = true) {
1757 const contextVNode = instance ? instance.vnode : null;
1758 if (instance) {
1759 let cur = instance.parent;
1760 // the exposed instance is the render proxy to keep it consistent with 2.x
1761 const exposedInstance = instance.proxy;
1762 // in production the hook receives only the error code
1763 const errorInfo = ErrorTypeStrings[type] ;
1764 while (cur) {
1765 const errorCapturedHooks = cur.ec;
1766 if (errorCapturedHooks) {
1767 for (let i = 0; i < errorCapturedHooks.length; i++) {
1768 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1769 return;
1770 }
1771 }
1772 }
1773 cur = cur.parent;
1774 }
1775 // app-level handling
1776 const appErrorHandler = instance.appContext.config.errorHandler;
1777 if (appErrorHandler) {
1778 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1779 return;
1780 }
1781 }
1782 logError(err, type, contextVNode, throwInDev);
1783 }
1784 function logError(err, type, contextVNode, throwInDev = true) {
1785 {
1786 const info = ErrorTypeStrings[type];
1787 if (contextVNode) {
1788 pushWarningContext(contextVNode);
1789 }
1790 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1791 if (contextVNode) {
1792 popWarningContext();
1793 }
1794 // crash in dev by default so it's more noticeable
1795 if (throwInDev) {
1796 throw err;
1797 }
1798 else {
1799 console.error(err);
1800 }
1801 }
1802 }
1803
1804 let isFlushing = false;
1805 let isFlushPending = false;
1806 const queue = [];
1807 let flushIndex = 0;
1808 const pendingPreFlushCbs = [];
1809 let activePreFlushCbs = null;
1810 let preFlushIndex = 0;
1811 const pendingPostFlushCbs = [];
1812 let activePostFlushCbs = null;
1813 let postFlushIndex = 0;
1814 const resolvedPromise = /*#__PURE__*/ Promise.resolve();
1815 let currentFlushPromise = null;
1816 let currentPreFlushParentJob = null;
1817 const RECURSION_LIMIT = 100;
1818 function nextTick(fn) {
1819 const p = currentFlushPromise || resolvedPromise;
1820 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1821 }
1822 // #2768
1823 // Use binary-search to find a suitable position in the queue,
1824 // so that the queue maintains the increasing order of job's id,
1825 // which can prevent the job from being skipped and also can avoid repeated patching.
1826 function findInsertionIndex(id) {
1827 // the start index should be `flushIndex + 1`
1828 let start = flushIndex + 1;
1829 let end = queue.length;
1830 while (start < end) {
1831 const middle = (start + end) >>> 1;
1832 const middleJobId = getId(queue[middle]);
1833 middleJobId < id ? (start = middle + 1) : (end = middle);
1834 }
1835 return start;
1836 }
1837 function queueJob(job) {
1838 // the dedupe search uses the startIndex argument of Array.includes()
1839 // by default the search index includes the current job that is being run
1840 // so it cannot recursively trigger itself again.
1841 // if the job is a watch() callback, the search will start with a +1 index to
1842 // allow it recursively trigger itself - it is the user's responsibility to
1843 // ensure it doesn't end up in an infinite loop.
1844 if ((!queue.length ||
1845 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1846 job !== currentPreFlushParentJob) {
1847 if (job.id == null) {
1848 queue.push(job);
1849 }
1850 else {
1851 queue.splice(findInsertionIndex(job.id), 0, job);
1852 }
1853 queueFlush();
1854 }
1855 }
1856 function queueFlush() {
1857 if (!isFlushing && !isFlushPending) {
1858 isFlushPending = true;
1859 currentFlushPromise = resolvedPromise.then(flushJobs);
1860 }
1861 }
1862 function invalidateJob(job) {
1863 const i = queue.indexOf(job);
1864 if (i > flushIndex) {
1865 queue.splice(i, 1);
1866 }
1867 }
1868 function queueCb(cb, activeQueue, pendingQueue, index) {
1869 if (!isArray(cb)) {
1870 if (!activeQueue ||
1871 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1872 pendingQueue.push(cb);
1873 }
1874 }
1875 else {
1876 // if cb is an array, it is a component lifecycle hook which can only be
1877 // triggered by a job, which is already deduped in the main queue, so
1878 // we can skip duplicate check here to improve perf
1879 pendingQueue.push(...cb);
1880 }
1881 queueFlush();
1882 }
1883 function queuePreFlushCb(cb) {
1884 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1885 }
1886 function queuePostFlushCb(cb) {
1887 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1888 }
1889 function flushPreFlushCbs(seen, parentJob = null) {
1890 if (pendingPreFlushCbs.length) {
1891 currentPreFlushParentJob = parentJob;
1892 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1893 pendingPreFlushCbs.length = 0;
1894 {
1895 seen = seen || new Map();
1896 }
1897 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1898 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
1899 continue;
1900 }
1901 activePreFlushCbs[preFlushIndex]();
1902 }
1903 activePreFlushCbs = null;
1904 preFlushIndex = 0;
1905 currentPreFlushParentJob = null;
1906 // recursively flush until it drains
1907 flushPreFlushCbs(seen, parentJob);
1908 }
1909 }
1910 function flushPostFlushCbs(seen) {
1911 // flush any pre cbs queued during the flush (e.g. pre watchers)
1912 flushPreFlushCbs();
1913 if (pendingPostFlushCbs.length) {
1914 const deduped = [...new Set(pendingPostFlushCbs)];
1915 pendingPostFlushCbs.length = 0;
1916 // #1947 already has active queue, nested flushPostFlushCbs call
1917 if (activePostFlushCbs) {
1918 activePostFlushCbs.push(...deduped);
1919 return;
1920 }
1921 activePostFlushCbs = deduped;
1922 {
1923 seen = seen || new Map();
1924 }
1925 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1926 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1927 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1928 continue;
1929 }
1930 activePostFlushCbs[postFlushIndex]();
1931 }
1932 activePostFlushCbs = null;
1933 postFlushIndex = 0;
1934 }
1935 }
1936 const getId = (job) => job.id == null ? Infinity : job.id;
1937 function flushJobs(seen) {
1938 isFlushPending = false;
1939 isFlushing = true;
1940 {
1941 seen = seen || new Map();
1942 }
1943 flushPreFlushCbs(seen);
1944 // Sort queue before flush.
1945 // This ensures that:
1946 // 1. Components are updated from parent to child. (because parent is always
1947 // created before the child so its render effect will have smaller
1948 // priority number)
1949 // 2. If a component is unmounted during a parent component's update,
1950 // its update can be skipped.
1951 queue.sort((a, b) => getId(a) - getId(b));
1952 // conditional usage of checkRecursiveUpdate must be determined out of
1953 // try ... catch block since Rollup by default de-optimizes treeshaking
1954 // inside try-catch. This can leave all warning code unshaked. Although
1955 // they would get eventually shaken by a minifier like terser, some minifiers
1956 // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
1957 const check = (job) => checkRecursiveUpdates(seen, job)
1958 ;
1959 try {
1960 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1961 const job = queue[flushIndex];
1962 if (job && job.active !== false) {
1963 if (true && check(job)) {
1964 continue;
1965 }
1966 // console.log(`running:`, job.id)
1967 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1968 }
1969 }
1970 }
1971 finally {
1972 flushIndex = 0;
1973 queue.length = 0;
1974 flushPostFlushCbs(seen);
1975 isFlushing = false;
1976 currentFlushPromise = null;
1977 // some postFlushCb queued jobs!
1978 // keep flushing until it drains.
1979 if (queue.length ||
1980 pendingPreFlushCbs.length ||
1981 pendingPostFlushCbs.length) {
1982 flushJobs(seen);
1983 }
1984 }
1985 }
1986 function checkRecursiveUpdates(seen, fn) {
1987 if (!seen.has(fn)) {
1988 seen.set(fn, 1);
1989 }
1990 else {
1991 const count = seen.get(fn);
1992 if (count > RECURSION_LIMIT) {
1993 const instance = fn.ownerInstance;
1994 const componentName = instance && getComponentName(instance.type);
1995 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1996 `This means you have a reactive effect that is mutating its own ` +
1997 `dependencies and thus recursively triggering itself. Possible sources ` +
1998 `include component template, render function, updated hook or ` +
1999 `watcher source function.`);
2000 return true;
2001 }
2002 else {
2003 seen.set(fn, count + 1);
2004 }
2005 }
2006 }
2007
2008 /* eslint-disable no-restricted-globals */
2009 let isHmrUpdating = false;
2010 const hmrDirtyComponents = new Set();
2011 // Expose the HMR runtime on the global object
2012 // This makes it entirely tree-shakable without polluting the exports and makes
2013 // it easier to be used in toolings like vue-loader
2014 // Note: for a component to be eligible for HMR it also needs the __hmrId option
2015 // to be set so that its instances can be registered / removed.
2016 {
2017 getGlobalThis().__VUE_HMR_RUNTIME__ = {
2018 createRecord: tryWrap(createRecord),
2019 rerender: tryWrap(rerender),
2020 reload: tryWrap(reload)
2021 };
2022 }
2023 const map = new Map();
2024 function registerHMR(instance) {
2025 const id = instance.type.__hmrId;
2026 let record = map.get(id);
2027 if (!record) {
2028 createRecord(id, instance.type);
2029 record = map.get(id);
2030 }
2031 record.instances.add(instance);
2032 }
2033 function unregisterHMR(instance) {
2034 map.get(instance.type.__hmrId).instances.delete(instance);
2035 }
2036 function createRecord(id, initialDef) {
2037 if (map.has(id)) {
2038 return false;
2039 }
2040 map.set(id, {
2041 initialDef: normalizeClassComponent(initialDef),
2042 instances: new Set()
2043 });
2044 return true;
2045 }
2046 function normalizeClassComponent(component) {
2047 return isClassComponent(component) ? component.__vccOpts : component;
2048 }
2049 function rerender(id, newRender) {
2050 const record = map.get(id);
2051 if (!record) {
2052 return;
2053 }
2054 // update initial record (for not-yet-rendered component)
2055 record.initialDef.render = newRender;
2056 [...record.instances].forEach(instance => {
2057 if (newRender) {
2058 instance.render = newRender;
2059 normalizeClassComponent(instance.type).render = newRender;
2060 }
2061 instance.renderCache = [];
2062 // this flag forces child components with slot content to update
2063 isHmrUpdating = true;
2064 instance.update();
2065 isHmrUpdating = false;
2066 });
2067 }
2068 function reload(id, newComp) {
2069 const record = map.get(id);
2070 if (!record)
2071 return;
2072 newComp = normalizeClassComponent(newComp);
2073 // update initial def (for not-yet-rendered components)
2074 updateComponentDef(record.initialDef, newComp);
2075 // create a snapshot which avoids the set being mutated during updates
2076 const instances = [...record.instances];
2077 for (const instance of instances) {
2078 const oldComp = normalizeClassComponent(instance.type);
2079 if (!hmrDirtyComponents.has(oldComp)) {
2080 // 1. Update existing comp definition to match new one
2081 if (oldComp !== record.initialDef) {
2082 updateComponentDef(oldComp, newComp);
2083 }
2084 // 2. mark definition dirty. This forces the renderer to replace the
2085 // component on patch.
2086 hmrDirtyComponents.add(oldComp);
2087 }
2088 // 3. invalidate options resolution cache
2089 instance.appContext.optionsCache.delete(instance.type);
2090 // 4. actually update
2091 if (instance.ceReload) {
2092 // custom element
2093 hmrDirtyComponents.add(oldComp);
2094 instance.ceReload(newComp.styles);
2095 hmrDirtyComponents.delete(oldComp);
2096 }
2097 else if (instance.parent) {
2098 // 4. Force the parent instance to re-render. This will cause all updated
2099 // components to be unmounted and re-mounted. Queue the update so that we
2100 // don't end up forcing the same parent to re-render multiple times.
2101 queueJob(instance.parent.update);
2102 // instance is the inner component of an async custom element
2103 // invoke to reset styles
2104 if (instance.parent.type.__asyncLoader &&
2105 instance.parent.ceReload) {
2106 instance.parent.ceReload(newComp.styles);
2107 }
2108 }
2109 else if (instance.appContext.reload) {
2110 // root instance mounted via createApp() has a reload method
2111 instance.appContext.reload();
2112 }
2113 else if (typeof window !== 'undefined') {
2114 // root instance inside tree created via raw render(). Force reload.
2115 window.location.reload();
2116 }
2117 else {
2118 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
2119 }
2120 }
2121 // 5. make sure to cleanup dirty hmr components after update
2122 queuePostFlushCb(() => {
2123 for (const instance of instances) {
2124 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
2125 }
2126 });
2127 }
2128 function updateComponentDef(oldComp, newComp) {
2129 extend(oldComp, newComp);
2130 for (const key in oldComp) {
2131 if (key !== '__file' && !(key in newComp)) {
2132 delete oldComp[key];
2133 }
2134 }
2135 }
2136 function tryWrap(fn) {
2137 return (id, arg) => {
2138 try {
2139 return fn(id, arg);
2140 }
2141 catch (e) {
2142 console.error(e);
2143 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
2144 `Full reload required.`);
2145 }
2146 };
2147 }
2148
2149 let buffer = [];
2150 let devtoolsNotInstalled = false;
2151 function emit(event, ...args) {
2152 if (exports.devtools) {
2153 exports.devtools.emit(event, ...args);
2154 }
2155 else if (!devtoolsNotInstalled) {
2156 buffer.push({ event, args });
2157 }
2158 }
2159 function setDevtoolsHook(hook, target) {
2160 var _a, _b;
2161 exports.devtools = hook;
2162 if (exports.devtools) {
2163 exports.devtools.enabled = true;
2164 buffer.forEach(({ event, args }) => exports.devtools.emit(event, ...args));
2165 buffer = [];
2166 }
2167 else if (
2168 // handle late devtools injection - only do this if we are in an actual
2169 // browser environment to avoid the timer handle stalling test runner exit
2170 // (#4815)
2171 typeof window !== 'undefined' &&
2172 // some envs mock window but not fully
2173 window.HTMLElement &&
2174 // also exclude jsdom
2175 !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
2176 const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
2177 target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
2178 replay.push((newHook) => {
2179 setDevtoolsHook(newHook, target);
2180 });
2181 // clear buffer after 3s - the user probably doesn't have devtools installed
2182 // at all, and keeping the buffer will cause memory leaks (#4738)
2183 setTimeout(() => {
2184 if (!exports.devtools) {
2185 target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
2186 devtoolsNotInstalled = true;
2187 buffer = [];
2188 }
2189 }, 3000);
2190 }
2191 else {
2192 // non-browser env, assume not installed
2193 devtoolsNotInstalled = true;
2194 buffer = [];
2195 }
2196 }
2197 function devtoolsInitApp(app, version) {
2198 emit("app:init" /* APP_INIT */, app, version, {
2199 Fragment,
2200 Text,
2201 Comment,
2202 Static
2203 });
2204 }
2205 function devtoolsUnmountApp(app) {
2206 emit("app:unmount" /* APP_UNMOUNT */, app);
2207 }
2208 const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
2209 const devtoolsComponentUpdated =
2210 /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
2211 const devtoolsComponentRemoved =
2212 /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
2213 function createDevtoolsComponentHook(hook) {
2214 return (component) => {
2215 emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
2216 };
2217 }
2218 const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
2219 const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
2220 function createDevtoolsPerformanceHook(hook) {
2221 return (component, type, time) => {
2222 emit(hook, component.appContext.app, component.uid, component, type, time);
2223 };
2224 }
2225 function devtoolsComponentEmit(component, event, params) {
2226 emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
2227 }
2228
2229 function emit$1(instance, event, ...rawArgs) {
2230 if (instance.isUnmounted)
2231 return;
2232 const props = instance.vnode.props || EMPTY_OBJ;
2233 {
2234 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2235 if (emitsOptions) {
2236 if (!(event in emitsOptions) &&
2237 !(false )) {
2238 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2239 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2240 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2241 }
2242 }
2243 else {
2244 const validator = emitsOptions[event];
2245 if (isFunction(validator)) {
2246 const isValid = validator(...rawArgs);
2247 if (!isValid) {
2248 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2249 }
2250 }
2251 }
2252 }
2253 }
2254 let args = rawArgs;
2255 const isModelListener = event.startsWith('update:');
2256 // for v-model update:xxx events, apply modifiers on args
2257 const modelArg = isModelListener && event.slice(7);
2258 if (modelArg && modelArg in props) {
2259 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2260 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2261 if (trim) {
2262 args = rawArgs.map(a => a.trim());
2263 }
2264 if (number) {
2265 args = rawArgs.map(toNumber);
2266 }
2267 }
2268 {
2269 devtoolsComponentEmit(instance, event, args);
2270 }
2271 {
2272 const lowerCaseEvent = event.toLowerCase();
2273 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2274 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2275 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2276 `Note that HTML attributes are case-insensitive and you cannot use ` +
2277 `v-on to listen to camelCase events when using in-DOM templates. ` +
2278 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2279 }
2280 }
2281 let handlerName;
2282 let handler = props[(handlerName = toHandlerKey(event))] ||
2283 // also try camelCase event handler (#2249)
2284 props[(handlerName = toHandlerKey(camelize(event)))];
2285 // for v-model update:xxx events, also trigger kebab-case equivalent
2286 // for props passed via kebab-case
2287 if (!handler && isModelListener) {
2288 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2289 }
2290 if (handler) {
2291 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2292 }
2293 const onceHandler = props[handlerName + `Once`];
2294 if (onceHandler) {
2295 if (!instance.emitted) {
2296 instance.emitted = {};
2297 }
2298 else if (instance.emitted[handlerName]) {
2299 return;
2300 }
2301 instance.emitted[handlerName] = true;
2302 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2303 }
2304 }
2305 function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2306 const cache = appContext.emitsCache;
2307 const cached = cache.get(comp);
2308 if (cached !== undefined) {
2309 return cached;
2310 }
2311 const raw = comp.emits;
2312 let normalized = {};
2313 // apply mixin/extends props
2314 let hasExtends = false;
2315 if (!isFunction(comp)) {
2316 const extendEmits = (raw) => {
2317 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2318 if (normalizedFromExtend) {
2319 hasExtends = true;
2320 extend(normalized, normalizedFromExtend);
2321 }
2322 };
2323 if (!asMixin && appContext.mixins.length) {
2324 appContext.mixins.forEach(extendEmits);
2325 }
2326 if (comp.extends) {
2327 extendEmits(comp.extends);
2328 }
2329 if (comp.mixins) {
2330 comp.mixins.forEach(extendEmits);
2331 }
2332 }
2333 if (!raw && !hasExtends) {
2334 cache.set(comp, null);
2335 return null;
2336 }
2337 if (isArray(raw)) {
2338 raw.forEach(key => (normalized[key] = null));
2339 }
2340 else {
2341 extend(normalized, raw);
2342 }
2343 cache.set(comp, normalized);
2344 return normalized;
2345 }
2346 // Check if an incoming prop key is a declared emit event listener.
2347 // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2348 // both considered matched listeners.
2349 function isEmitListener(options, key) {
2350 if (!options || !isOn(key)) {
2351 return false;
2352 }
2353 key = key.slice(2).replace(/Once$/, '');
2354 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2355 hasOwn(options, hyphenate(key)) ||
2356 hasOwn(options, key));
2357 }
2358
2359 /**
2360 * mark the current rendering instance for asset resolution (e.g.
2361 * resolveComponent, resolveDirective) during render
2362 */
2363 let currentRenderingInstance = null;
2364 let currentScopeId = null;
2365 /**
2366 * Note: rendering calls maybe nested. The function returns the parent rendering
2367 * instance if present, which should be restored after the render is done:
2368 *
2369 * ```js
2370 * const prev = setCurrentRenderingInstance(i)
2371 * // ...render
2372 * setCurrentRenderingInstance(prev)
2373 * ```
2374 */
2375 function setCurrentRenderingInstance(instance) {
2376 const prev = currentRenderingInstance;
2377 currentRenderingInstance = instance;
2378 currentScopeId = (instance && instance.type.__scopeId) || null;
2379 return prev;
2380 }
2381 /**
2382 * Set scope id when creating hoisted vnodes.
2383 * @private compiler helper
2384 */
2385 function pushScopeId(id) {
2386 currentScopeId = id;
2387 }
2388 /**
2389 * Technically we no longer need this after 3.0.8 but we need to keep the same
2390 * API for backwards compat w/ code generated by compilers.
2391 * @private
2392 */
2393 function popScopeId() {
2394 currentScopeId = null;
2395 }
2396 /**
2397 * Only for backwards compat
2398 * @private
2399 */
2400 const withScopeId = (_id) => withCtx;
2401 /**
2402 * Wrap a slot function to memoize current rendering instance
2403 * @private compiler helper
2404 */
2405 function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2406 ) {
2407 if (!ctx)
2408 return fn;
2409 // already normalized
2410 if (fn._n) {
2411 return fn;
2412 }
2413 const renderFnWithContext = (...args) => {
2414 // If a user calls a compiled slot inside a template expression (#1745), it
2415 // can mess up block tracking, so by default we disable block tracking and
2416 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2417 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2418 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2419 if (renderFnWithContext._d) {
2420 setBlockTracking(-1);
2421 }
2422 const prevInstance = setCurrentRenderingInstance(ctx);
2423 const res = fn(...args);
2424 setCurrentRenderingInstance(prevInstance);
2425 if (renderFnWithContext._d) {
2426 setBlockTracking(1);
2427 }
2428 {
2429 devtoolsComponentUpdated(ctx);
2430 }
2431 return res;
2432 };
2433 // mark normalized to avoid duplicated wrapping
2434 renderFnWithContext._n = true;
2435 // mark this as compiled by default
2436 // this is used in vnode.ts -> normalizeChildren() to set the slot
2437 // rendering flag.
2438 renderFnWithContext._c = true;
2439 // disable block tracking by default
2440 renderFnWithContext._d = true;
2441 return renderFnWithContext;
2442 }
2443
2444 /**
2445 * dev only flag to track whether $attrs was used during render.
2446 * If $attrs was used during render then the warning for failed attrs
2447 * fallthrough can be suppressed.
2448 */
2449 let accessedAttrs = false;
2450 function markAttrsAccessed() {
2451 accessedAttrs = true;
2452 }
2453 function renderComponentRoot(instance) {
2454 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2455 let result;
2456 let fallthroughAttrs;
2457 const prev = setCurrentRenderingInstance(instance);
2458 {
2459 accessedAttrs = false;
2460 }
2461 try {
2462 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2463 // withProxy is a proxy with a different `has` trap only for
2464 // runtime-compiled render functions using `with` block.
2465 const proxyToUse = withProxy || proxy;
2466 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2467 fallthroughAttrs = attrs;
2468 }
2469 else {
2470 // functional
2471 const render = Component;
2472 // in dev, mark attrs accessed if optional props (attrs === props)
2473 if (true && attrs === props) {
2474 markAttrsAccessed();
2475 }
2476 result = normalizeVNode(render.length > 1
2477 ? render(props, true
2478 ? {
2479 get attrs() {
2480 markAttrsAccessed();
2481 return attrs;
2482 },
2483 slots,
2484 emit
2485 }
2486 : { attrs, slots, emit })
2487 : render(props, null /* we know it doesn't need it */));
2488 fallthroughAttrs = Component.props
2489 ? attrs
2490 : getFunctionalFallthrough(attrs);
2491 }
2492 }
2493 catch (err) {
2494 blockStack.length = 0;
2495 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2496 result = createVNode(Comment);
2497 }
2498 // attr merging
2499 // in dev mode, comments are preserved, and it's possible for a template
2500 // to have comments along side the root element which makes it a fragment
2501 let root = result;
2502 let setRoot = undefined;
2503 if (result.patchFlag > 0 &&
2504 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2505 [root, setRoot] = getChildRoot(result);
2506 }
2507 if (fallthroughAttrs && inheritAttrs !== false) {
2508 const keys = Object.keys(fallthroughAttrs);
2509 const { shapeFlag } = root;
2510 if (keys.length) {
2511 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2512 if (propsOptions && keys.some(isModelListener)) {
2513 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2514 // prop, it indicates this component expects to handle v-model and
2515 // it should not fallthrough.
2516 // related: #1543, #1643, #1989
2517 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2518 }
2519 root = cloneVNode(root, fallthroughAttrs);
2520 }
2521 else if (!accessedAttrs && root.type !== Comment) {
2522 const allAttrs = Object.keys(attrs);
2523 const eventAttrs = [];
2524 const extraAttrs = [];
2525 for (let i = 0, l = allAttrs.length; i < l; i++) {
2526 const key = allAttrs[i];
2527 if (isOn(key)) {
2528 // ignore v-model handlers when they fail to fallthrough
2529 if (!isModelListener(key)) {
2530 // remove `on`, lowercase first letter to reflect event casing
2531 // accurately
2532 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2533 }
2534 }
2535 else {
2536 extraAttrs.push(key);
2537 }
2538 }
2539 if (extraAttrs.length) {
2540 warn$1(`Extraneous non-props attributes (` +
2541 `${extraAttrs.join(', ')}) ` +
2542 `were passed to component but could not be automatically inherited ` +
2543 `because component renders fragment or text root nodes.`);
2544 }
2545 if (eventAttrs.length) {
2546 warn$1(`Extraneous non-emits event listeners (` +
2547 `${eventAttrs.join(', ')}) ` +
2548 `were passed to component but could not be automatically inherited ` +
2549 `because component renders fragment or text root nodes. ` +
2550 `If the listener is intended to be a component custom event listener only, ` +
2551 `declare it using the "emits" option.`);
2552 }
2553 }
2554 }
2555 }
2556 // inherit directives
2557 if (vnode.dirs) {
2558 if (!isElementRoot(root)) {
2559 warn$1(`Runtime directive used on component with non-element root node. ` +
2560 `The directives will not function as intended.`);
2561 }
2562 // clone before mutating since the root may be a hoisted vnode
2563 root = cloneVNode(root);
2564 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2565 }
2566 // inherit transition data
2567 if (vnode.transition) {
2568 if (!isElementRoot(root)) {
2569 warn$1(`Component inside <Transition> renders non-element root node ` +
2570 `that cannot be animated.`);
2571 }
2572 root.transition = vnode.transition;
2573 }
2574 if (setRoot) {
2575 setRoot(root);
2576 }
2577 else {
2578 result = root;
2579 }
2580 setCurrentRenderingInstance(prev);
2581 return result;
2582 }
2583 /**
2584 * dev only
2585 * In dev mode, template root level comments are rendered, which turns the
2586 * template into a fragment root, but we need to locate the single element
2587 * root for attrs and scope id processing.
2588 */
2589 const getChildRoot = (vnode) => {
2590 const rawChildren = vnode.children;
2591 const dynamicChildren = vnode.dynamicChildren;
2592 const childRoot = filterSingleRoot(rawChildren);
2593 if (!childRoot) {
2594 return [vnode, undefined];
2595 }
2596 const index = rawChildren.indexOf(childRoot);
2597 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2598 const setRoot = (updatedRoot) => {
2599 rawChildren[index] = updatedRoot;
2600 if (dynamicChildren) {
2601 if (dynamicIndex > -1) {
2602 dynamicChildren[dynamicIndex] = updatedRoot;
2603 }
2604 else if (updatedRoot.patchFlag > 0) {
2605 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2606 }
2607 }
2608 };
2609 return [normalizeVNode(childRoot), setRoot];
2610 };
2611 function filterSingleRoot(children) {
2612 let singleRoot;
2613 for (let i = 0; i < children.length; i++) {
2614 const child = children[i];
2615 if (isVNode(child)) {
2616 // ignore user comment
2617 if (child.type !== Comment || child.children === 'v-if') {
2618 if (singleRoot) {
2619 // has more than 1 non-comment child, return now
2620 return;
2621 }
2622 else {
2623 singleRoot = child;
2624 }
2625 }
2626 }
2627 else {
2628 return;
2629 }
2630 }
2631 return singleRoot;
2632 }
2633 const getFunctionalFallthrough = (attrs) => {
2634 let res;
2635 for (const key in attrs) {
2636 if (key === 'class' || key === 'style' || isOn(key)) {
2637 (res || (res = {}))[key] = attrs[key];
2638 }
2639 }
2640 return res;
2641 };
2642 const filterModelListeners = (attrs, props) => {
2643 const res = {};
2644 for (const key in attrs) {
2645 if (!isModelListener(key) || !(key.slice(9) in props)) {
2646 res[key] = attrs[key];
2647 }
2648 }
2649 return res;
2650 };
2651 const isElementRoot = (vnode) => {
2652 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2653 vnode.type === Comment // potential v-if branch switch
2654 );
2655 };
2656 function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2657 const { props: prevProps, children: prevChildren, component } = prevVNode;
2658 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2659 const emits = component.emitsOptions;
2660 // Parent component's render function was hot-updated. Since this may have
2661 // caused the child component's slots content to have changed, we need to
2662 // force the child to update as well.
2663 if ((prevChildren || nextChildren) && isHmrUpdating) {
2664 return true;
2665 }
2666 // force child update for runtime directive or transition on component vnode.
2667 if (nextVNode.dirs || nextVNode.transition) {
2668 return true;
2669 }
2670 if (optimized && patchFlag >= 0) {
2671 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2672 // slot content that references values that might have changed,
2673 // e.g. in a v-for
2674 return true;
2675 }
2676 if (patchFlag & 16 /* FULL_PROPS */) {
2677 if (!prevProps) {
2678 return !!nextProps;
2679 }
2680 // presence of this flag indicates props are always non-null
2681 return hasPropsChanged(prevProps, nextProps, emits);
2682 }
2683 else if (patchFlag & 8 /* PROPS */) {
2684 const dynamicProps = nextVNode.dynamicProps;
2685 for (let i = 0; i < dynamicProps.length; i++) {
2686 const key = dynamicProps[i];
2687 if (nextProps[key] !== prevProps[key] &&
2688 !isEmitListener(emits, key)) {
2689 return true;
2690 }
2691 }
2692 }
2693 }
2694 else {
2695 // this path is only taken by manually written render functions
2696 // so presence of any children leads to a forced update
2697 if (prevChildren || nextChildren) {
2698 if (!nextChildren || !nextChildren.$stable) {
2699 return true;
2700 }
2701 }
2702 if (prevProps === nextProps) {
2703 return false;
2704 }
2705 if (!prevProps) {
2706 return !!nextProps;
2707 }
2708 if (!nextProps) {
2709 return true;
2710 }
2711 return hasPropsChanged(prevProps, nextProps, emits);
2712 }
2713 return false;
2714 }
2715 function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2716 const nextKeys = Object.keys(nextProps);
2717 if (nextKeys.length !== Object.keys(prevProps).length) {
2718 return true;
2719 }
2720 for (let i = 0; i < nextKeys.length; i++) {
2721 const key = nextKeys[i];
2722 if (nextProps[key] !== prevProps[key] &&
2723 !isEmitListener(emitsOptions, key)) {
2724 return true;
2725 }
2726 }
2727 return false;
2728 }
2729 function updateHOCHostEl({ vnode, parent }, el // HostNode
2730 ) {
2731 while (parent && parent.subTree === vnode) {
2732 (vnode = parent.vnode).el = el;
2733 parent = parent.parent;
2734 }
2735 }
2736
2737 const isSuspense = (type) => type.__isSuspense;
2738 // Suspense exposes a component-like API, and is treated like a component
2739 // in the compiler, but internally it's a special built-in type that hooks
2740 // directly into the renderer.
2741 const SuspenseImpl = {
2742 name: 'Suspense',
2743 // In order to make Suspense tree-shakable, we need to avoid importing it
2744 // directly in the renderer. The renderer checks for the __isSuspense flag
2745 // on a vnode's type and calls the `process` method, passing in renderer
2746 // internals.
2747 __isSuspense: true,
2748 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2749 // platform-specific impl passed from renderer
2750 rendererInternals) {
2751 if (n1 == null) {
2752 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2753 }
2754 else {
2755 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2756 }
2757 },
2758 hydrate: hydrateSuspense,
2759 create: createSuspenseBoundary,
2760 normalize: normalizeSuspenseChildren
2761 };
2762 // Force-casted public typing for h and TSX props inference
2763 const Suspense = (SuspenseImpl );
2764 function triggerEvent(vnode, name) {
2765 const eventListener = vnode.props && vnode.props[name];
2766 if (isFunction(eventListener)) {
2767 eventListener();
2768 }
2769 }
2770 function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2771 const { p: patch, o: { createElement } } = rendererInternals;
2772 const hiddenContainer = createElement('div');
2773 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2774 // start mounting the content subtree in an off-dom container
2775 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2776 // now check if we have encountered any async deps
2777 if (suspense.deps > 0) {
2778 // has async
2779 // invoke @fallback event
2780 triggerEvent(vnode, 'onPending');
2781 triggerEvent(vnode, 'onFallback');
2782 // mount the fallback tree
2783 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2784 isSVG, slotScopeIds);
2785 setActiveBranch(suspense, vnode.ssFallback);
2786 }
2787 else {
2788 // Suspense has no async deps. Just resolve.
2789 suspense.resolve();
2790 }
2791 }
2792 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2793 const suspense = (n2.suspense = n1.suspense);
2794 suspense.vnode = n2;
2795 n2.el = n1.el;
2796 const newBranch = n2.ssContent;
2797 const newFallback = n2.ssFallback;
2798 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2799 if (pendingBranch) {
2800 suspense.pendingBranch = newBranch;
2801 if (isSameVNodeType(newBranch, pendingBranch)) {
2802 // same root type but content may have changed.
2803 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2804 if (suspense.deps <= 0) {
2805 suspense.resolve();
2806 }
2807 else if (isInFallback) {
2808 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2809 isSVG, slotScopeIds, optimized);
2810 setActiveBranch(suspense, newFallback);
2811 }
2812 }
2813 else {
2814 // toggled before pending tree is resolved
2815 suspense.pendingId++;
2816 if (isHydrating) {
2817 // if toggled before hydration is finished, the current DOM tree is
2818 // no longer valid. set it as the active branch so it will be unmounted
2819 // when resolved
2820 suspense.isHydrating = false;
2821 suspense.activeBranch = pendingBranch;
2822 }
2823 else {
2824 unmount(pendingBranch, parentComponent, suspense);
2825 }
2826 // increment pending ID. this is used to invalidate async callbacks
2827 // reset suspense state
2828 suspense.deps = 0;
2829 // discard effects from pending branch
2830 suspense.effects.length = 0;
2831 // discard previous container
2832 suspense.hiddenContainer = createElement('div');
2833 if (isInFallback) {
2834 // already in fallback state
2835 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2836 if (suspense.deps <= 0) {
2837 suspense.resolve();
2838 }
2839 else {
2840 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2841 isSVG, slotScopeIds, optimized);
2842 setActiveBranch(suspense, newFallback);
2843 }
2844 }
2845 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2846 // toggled "back" to current active branch
2847 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2848 // force resolve
2849 suspense.resolve(true);
2850 }
2851 else {
2852 // switched to a 3rd branch
2853 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2854 if (suspense.deps <= 0) {
2855 suspense.resolve();
2856 }
2857 }
2858 }
2859 }
2860 else {
2861 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2862 // root did not change, just normal patch
2863 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2864 setActiveBranch(suspense, newBranch);
2865 }
2866 else {
2867 // root node toggled
2868 // invoke @pending event
2869 triggerEvent(n2, 'onPending');
2870 // mount pending branch in off-dom container
2871 suspense.pendingBranch = newBranch;
2872 suspense.pendingId++;
2873 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2874 if (suspense.deps <= 0) {
2875 // incoming branch has no async deps, resolve now.
2876 suspense.resolve();
2877 }
2878 else {
2879 const { timeout, pendingId } = suspense;
2880 if (timeout > 0) {
2881 setTimeout(() => {
2882 if (suspense.pendingId === pendingId) {
2883 suspense.fallback(newFallback);
2884 }
2885 }, timeout);
2886 }
2887 else if (timeout === 0) {
2888 suspense.fallback(newFallback);
2889 }
2890 }
2891 }
2892 }
2893 }
2894 let hasWarned = false;
2895 function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2896 /* istanbul ignore if */
2897 if (!hasWarned) {
2898 hasWarned = true;
2899 // @ts-ignore `console.info` cannot be null error
2900 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2901 }
2902 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2903 const timeout = toNumber(vnode.props && vnode.props.timeout);
2904 const suspense = {
2905 vnode,
2906 parent,
2907 parentComponent,
2908 isSVG,
2909 container,
2910 hiddenContainer,
2911 anchor,
2912 deps: 0,
2913 pendingId: 0,
2914 timeout: typeof timeout === 'number' ? timeout : -1,
2915 activeBranch: null,
2916 pendingBranch: null,
2917 isInFallback: true,
2918 isHydrating,
2919 isUnmounted: false,
2920 effects: [],
2921 resolve(resume = false) {
2922 {
2923 if (!resume && !suspense.pendingBranch) {
2924 throw new Error(`suspense.resolve() is called without a pending branch.`);
2925 }
2926 if (suspense.isUnmounted) {
2927 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2928 }
2929 }
2930 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2931 if (suspense.isHydrating) {
2932 suspense.isHydrating = false;
2933 }
2934 else if (!resume) {
2935 const delayEnter = activeBranch &&
2936 pendingBranch.transition &&
2937 pendingBranch.transition.mode === 'out-in';
2938 if (delayEnter) {
2939 activeBranch.transition.afterLeave = () => {
2940 if (pendingId === suspense.pendingId) {
2941 move(pendingBranch, container, anchor, 0 /* ENTER */);
2942 }
2943 };
2944 }
2945 // this is initial anchor on mount
2946 let { anchor } = suspense;
2947 // unmount current active tree
2948 if (activeBranch) {
2949 // if the fallback tree was mounted, it may have been moved
2950 // as part of a parent suspense. get the latest anchor for insertion
2951 anchor = next(activeBranch);
2952 unmount(activeBranch, parentComponent, suspense, true);
2953 }
2954 if (!delayEnter) {
2955 // move content from off-dom container to actual container
2956 move(pendingBranch, container, anchor, 0 /* ENTER */);
2957 }
2958 }
2959 setActiveBranch(suspense, pendingBranch);
2960 suspense.pendingBranch = null;
2961 suspense.isInFallback = false;
2962 // flush buffered effects
2963 // check if there is a pending parent suspense
2964 let parent = suspense.parent;
2965 let hasUnresolvedAncestor = false;
2966 while (parent) {
2967 if (parent.pendingBranch) {
2968 // found a pending parent suspense, merge buffered post jobs
2969 // into that parent
2970 parent.effects.push(...effects);
2971 hasUnresolvedAncestor = true;
2972 break;
2973 }
2974 parent = parent.parent;
2975 }
2976 // no pending parent suspense, flush all jobs
2977 if (!hasUnresolvedAncestor) {
2978 queuePostFlushCb(effects);
2979 }
2980 suspense.effects = [];
2981 // invoke @resolve event
2982 triggerEvent(vnode, 'onResolve');
2983 },
2984 fallback(fallbackVNode) {
2985 if (!suspense.pendingBranch) {
2986 return;
2987 }
2988 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2989 // invoke @fallback event
2990 triggerEvent(vnode, 'onFallback');
2991 const anchor = next(activeBranch);
2992 const mountFallback = () => {
2993 if (!suspense.isInFallback) {
2994 return;
2995 }
2996 // mount the fallback tree
2997 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2998 isSVG, slotScopeIds, optimized);
2999 setActiveBranch(suspense, fallbackVNode);
3000 };
3001 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
3002 if (delayEnter) {
3003 activeBranch.transition.afterLeave = mountFallback;
3004 }
3005 suspense.isInFallback = true;
3006 // unmount current active branch
3007 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
3008 true // shouldRemove
3009 );
3010 if (!delayEnter) {
3011 mountFallback();
3012 }
3013 },
3014 move(container, anchor, type) {
3015 suspense.activeBranch &&
3016 move(suspense.activeBranch, container, anchor, type);
3017 suspense.container = container;
3018 },
3019 next() {
3020 return suspense.activeBranch && next(suspense.activeBranch);
3021 },
3022 registerDep(instance, setupRenderEffect) {
3023 const isInPendingSuspense = !!suspense.pendingBranch;
3024 if (isInPendingSuspense) {
3025 suspense.deps++;
3026 }
3027 const hydratedEl = instance.vnode.el;
3028 instance
3029 .asyncDep.catch(err => {
3030 handleError(err, instance, 0 /* SETUP_FUNCTION */);
3031 })
3032 .then(asyncSetupResult => {
3033 // retry when the setup() promise resolves.
3034 // component may have been unmounted before resolve.
3035 if (instance.isUnmounted ||
3036 suspense.isUnmounted ||
3037 suspense.pendingId !== instance.suspenseId) {
3038 return;
3039 }
3040 // retry from this component
3041 instance.asyncResolved = true;
3042 const { vnode } = instance;
3043 {
3044 pushWarningContext(vnode);
3045 }
3046 handleSetupResult(instance, asyncSetupResult, false);
3047 if (hydratedEl) {
3048 // vnode may have been replaced if an update happened before the
3049 // async dep is resolved.
3050 vnode.el = hydratedEl;
3051 }
3052 const placeholder = !hydratedEl && instance.subTree.el;
3053 setupRenderEffect(instance, vnode,
3054 // component may have been moved before resolve.
3055 // if this is not a hydration, instance.subTree will be the comment
3056 // placeholder.
3057 parentNode(hydratedEl || instance.subTree.el),
3058 // anchor will not be used if this is hydration, so only need to
3059 // consider the comment placeholder case.
3060 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3061 if (placeholder) {
3062 remove(placeholder);
3063 }
3064 updateHOCHostEl(instance, vnode.el);
3065 {
3066 popWarningContext();
3067 }
3068 // only decrease deps count if suspense is not already resolved
3069 if (isInPendingSuspense && --suspense.deps === 0) {
3070 suspense.resolve();
3071 }
3072 });
3073 },
3074 unmount(parentSuspense, doRemove) {
3075 suspense.isUnmounted = true;
3076 if (suspense.activeBranch) {
3077 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3078 }
3079 if (suspense.pendingBranch) {
3080 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3081 }
3082 }
3083 };
3084 return suspense;
3085 }
3086 function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3087 /* eslint-disable no-restricted-globals */
3088 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3089 // there are two possible scenarios for server-rendered suspense:
3090 // - success: ssr content should be fully resolved
3091 // - failure: ssr content should be the fallback branch.
3092 // however, on the client we don't really know if it has failed or not
3093 // attempt to hydrate the DOM assuming it has succeeded, but we still
3094 // need to construct a suspense boundary first
3095 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3096 if (suspense.deps === 0) {
3097 suspense.resolve();
3098 }
3099 return result;
3100 /* eslint-enable no-restricted-globals */
3101 }
3102 function normalizeSuspenseChildren(vnode) {
3103 const { shapeFlag, children } = vnode;
3104 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
3105 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3106 vnode.ssFallback = isSlotChildren
3107 ? normalizeSuspenseSlot(children.fallback)
3108 : createVNode(Comment);
3109 }
3110 function normalizeSuspenseSlot(s) {
3111 let block;
3112 if (isFunction(s)) {
3113 const trackBlock = isBlockTreeEnabled && s._c;
3114 if (trackBlock) {
3115 // disableTracking: false
3116 // allow block tracking for compiled slots
3117 // (see ./componentRenderContext.ts)
3118 s._d = false;
3119 openBlock();
3120 }
3121 s = s();
3122 if (trackBlock) {
3123 s._d = true;
3124 block = currentBlock;
3125 closeBlock();
3126 }
3127 }
3128 if (isArray(s)) {
3129 const singleChild = filterSingleRoot(s);
3130 if (!singleChild) {
3131 warn$1(`<Suspense> slots expect a single root node.`);
3132 }
3133 s = singleChild;
3134 }
3135 s = normalizeVNode(s);
3136 if (block && !s.dynamicChildren) {
3137 s.dynamicChildren = block.filter(c => c !== s);
3138 }
3139 return s;
3140 }
3141 function queueEffectWithSuspense(fn, suspense) {
3142 if (suspense && suspense.pendingBranch) {
3143 if (isArray(fn)) {
3144 suspense.effects.push(...fn);
3145 }
3146 else {
3147 suspense.effects.push(fn);
3148 }
3149 }
3150 else {
3151 queuePostFlushCb(fn);
3152 }
3153 }
3154 function setActiveBranch(suspense, branch) {
3155 suspense.activeBranch = branch;
3156 const { vnode, parentComponent } = suspense;
3157 const el = (vnode.el = branch.el);
3158 // in case suspense is the root node of a component,
3159 // recursively update the HOC el
3160 if (parentComponent && parentComponent.subTree === vnode) {
3161 parentComponent.vnode.el = el;
3162 updateHOCHostEl(parentComponent, el);
3163 }
3164 }
3165
3166 function provide(key, value) {
3167 if (!currentInstance) {
3168 {
3169 warn$1(`provide() can only be used inside setup().`);
3170 }
3171 }
3172 else {
3173 let provides = currentInstance.provides;
3174 // by default an instance inherits its parent's provides object
3175 // but when it needs to provide values of its own, it creates its
3176 // own provides object using parent provides object as prototype.
3177 // this way in `inject` we can simply look up injections from direct
3178 // parent and let the prototype chain do the work.
3179 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3180 if (parentProvides === provides) {
3181 provides = currentInstance.provides = Object.create(parentProvides);
3182 }
3183 // TS doesn't allow symbol as index type
3184 provides[key] = value;
3185 }
3186 }
3187 function inject(key, defaultValue, treatDefaultAsFactory = false) {
3188 // fallback to `currentRenderingInstance` so that this can be called in
3189 // a functional component
3190 const instance = currentInstance || currentRenderingInstance;
3191 if (instance) {
3192 // #2400
3193 // to support `app.use` plugins,
3194 // fallback to appContext's `provides` if the instance is at root
3195 const provides = instance.parent == null
3196 ? instance.vnode.appContext && instance.vnode.appContext.provides
3197 : instance.parent.provides;
3198 if (provides && key in provides) {
3199 // TS doesn't allow symbol as index type
3200 return provides[key];
3201 }
3202 else if (arguments.length > 1) {
3203 return treatDefaultAsFactory && isFunction(defaultValue)
3204 ? defaultValue.call(instance.proxy)
3205 : defaultValue;
3206 }
3207 else {
3208 warn$1(`injection "${String(key)}" not found.`);
3209 }
3210 }
3211 else {
3212 warn$1(`inject() can only be used inside setup() or functional components.`);
3213 }
3214 }
3215
3216 // Simple effect.
3217 function watchEffect(effect, options) {
3218 return doWatch(effect, null, options);
3219 }
3220 function watchPostEffect(effect, options) {
3221 return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'post' }) ));
3222 }
3223 function watchSyncEffect(effect, options) {
3224 return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'sync' }) ));
3225 }
3226 // initial value for watchers to trigger on undefined initial values
3227 const INITIAL_WATCHER_VALUE = {};
3228 // implementation
3229 function watch(source, cb, options) {
3230 if (!isFunction(cb)) {
3231 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3232 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3233 `supports \`watch(source, cb, options?) signature.`);
3234 }
3235 return doWatch(source, cb, options);
3236 }
3237 function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
3238 if (!cb) {
3239 if (immediate !== undefined) {
3240 warn$1(`watch() "immediate" option is only respected when using the ` +
3241 `watch(source, callback, options?) signature.`);
3242 }
3243 if (deep !== undefined) {
3244 warn$1(`watch() "deep" option is only respected when using the ` +
3245 `watch(source, callback, options?) signature.`);
3246 }
3247 }
3248 const warnInvalidSource = (s) => {
3249 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3250 `a reactive object, or an array of these types.`);
3251 };
3252 const instance = currentInstance;
3253 let getter;
3254 let forceTrigger = false;
3255 let isMultiSource = false;
3256 if (isRef(source)) {
3257 getter = () => source.value;
3258 forceTrigger = isShallow(source);
3259 }
3260 else if (isReactive(source)) {
3261 getter = () => source;
3262 deep = true;
3263 }
3264 else if (isArray(source)) {
3265 isMultiSource = true;
3266 forceTrigger = source.some(s => isReactive(s) || isShallow(s));
3267 getter = () => source.map(s => {
3268 if (isRef(s)) {
3269 return s.value;
3270 }
3271 else if (isReactive(s)) {
3272 return traverse(s);
3273 }
3274 else if (isFunction(s)) {
3275 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
3276 }
3277 else {
3278 warnInvalidSource(s);
3279 }
3280 });
3281 }
3282 else if (isFunction(source)) {
3283 if (cb) {
3284 // getter with cb
3285 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
3286 }
3287 else {
3288 // no cb -> simple effect
3289 getter = () => {
3290 if (instance && instance.isUnmounted) {
3291 return;
3292 }
3293 if (cleanup) {
3294 cleanup();
3295 }
3296 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]);
3297 };
3298 }
3299 }
3300 else {
3301 getter = NOOP;
3302 warnInvalidSource(source);
3303 }
3304 if (cb && deep) {
3305 const baseGetter = getter;
3306 getter = () => traverse(baseGetter());
3307 }
3308 let cleanup;
3309 let onCleanup = (fn) => {
3310 cleanup = effect.onStop = () => {
3311 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3312 };
3313 };
3314 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
3315 const job = () => {
3316 if (!effect.active) {
3317 return;
3318 }
3319 if (cb) {
3320 // watch(source, cb)
3321 const newValue = effect.run();
3322 if (deep ||
3323 forceTrigger ||
3324 (isMultiSource
3325 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3326 : hasChanged(newValue, oldValue)) ||
3327 (false )) {
3328 // cleanup before running cb again
3329 if (cleanup) {
3330 cleanup();
3331 }
3332 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3333 newValue,
3334 // pass undefined as the old value when it's changed for the first time
3335 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3336 onCleanup
3337 ]);
3338 oldValue = newValue;
3339 }
3340 }
3341 else {
3342 // watchEffect
3343 effect.run();
3344 }
3345 };
3346 // important: mark the job as a watcher callback so that scheduler knows
3347 // it is allowed to self-trigger (#1727)
3348 job.allowRecurse = !!cb;
3349 let scheduler;
3350 if (flush === 'sync') {
3351 scheduler = job; // the scheduler function gets called directly
3352 }
3353 else if (flush === 'post') {
3354 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3355 }
3356 else {
3357 // default: 'pre'
3358 scheduler = () => queuePreFlushCb(job);
3359 }
3360 const effect = new ReactiveEffect(getter, scheduler);
3361 {
3362 effect.onTrack = onTrack;
3363 effect.onTrigger = onTrigger;
3364 }
3365 // initial run
3366 if (cb) {
3367 if (immediate) {
3368 job();
3369 }
3370 else {
3371 oldValue = effect.run();
3372 }
3373 }
3374 else if (flush === 'post') {
3375 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
3376 }
3377 else {
3378 effect.run();
3379 }
3380 return () => {
3381 effect.stop();
3382 if (instance && instance.scope) {
3383 remove(instance.scope.effects, effect);
3384 }
3385 };
3386 }
3387 // this.$watch
3388 function instanceWatch(source, value, options) {
3389 const publicThis = this.proxy;
3390 const getter = isString(source)
3391 ? source.includes('.')
3392 ? createPathGetter(publicThis, source)
3393 : () => publicThis[source]
3394 : source.bind(publicThis, publicThis);
3395 let cb;
3396 if (isFunction(value)) {
3397 cb = value;
3398 }
3399 else {
3400 cb = value.handler;
3401 options = value;
3402 }
3403 const cur = currentInstance;
3404 setCurrentInstance(this);
3405 const res = doWatch(getter, cb.bind(publicThis), options);
3406 if (cur) {
3407 setCurrentInstance(cur);
3408 }
3409 else {
3410 unsetCurrentInstance();
3411 }
3412 return res;
3413 }
3414 function createPathGetter(ctx, path) {
3415 const segments = path.split('.');
3416 return () => {
3417 let cur = ctx;
3418 for (let i = 0; i < segments.length && cur; i++) {
3419 cur = cur[segments[i]];
3420 }
3421 return cur;
3422 };
3423 }
3424 function traverse(value, seen) {
3425 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
3426 return value;
3427 }
3428 seen = seen || new Set();
3429 if (seen.has(value)) {
3430 return value;
3431 }
3432 seen.add(value);
3433 if (isRef(value)) {
3434 traverse(value.value, seen);
3435 }
3436 else if (isArray(value)) {
3437 for (let i = 0; i < value.length; i++) {
3438 traverse(value[i], seen);
3439 }
3440 }
3441 else if (isSet(value) || isMap(value)) {
3442 value.forEach((v) => {
3443 traverse(v, seen);
3444 });
3445 }
3446 else if (isPlainObject(value)) {
3447 for (const key in value) {
3448 traverse(value[key], seen);
3449 }
3450 }
3451 return value;
3452 }
3453
3454 function useTransitionState() {
3455 const state = {
3456 isMounted: false,
3457 isLeaving: false,
3458 isUnmounting: false,
3459 leavingVNodes: new Map()
3460 };
3461 onMounted(() => {
3462 state.isMounted = true;
3463 });
3464 onBeforeUnmount(() => {
3465 state.isUnmounting = true;
3466 });
3467 return state;
3468 }
3469 const TransitionHookValidator = [Function, Array];
3470 const BaseTransitionImpl = {
3471 name: `BaseTransition`,
3472 props: {
3473 mode: String,
3474 appear: Boolean,
3475 persisted: Boolean,
3476 // enter
3477 onBeforeEnter: TransitionHookValidator,
3478 onEnter: TransitionHookValidator,
3479 onAfterEnter: TransitionHookValidator,
3480 onEnterCancelled: TransitionHookValidator,
3481 // leave
3482 onBeforeLeave: TransitionHookValidator,
3483 onLeave: TransitionHookValidator,
3484 onAfterLeave: TransitionHookValidator,
3485 onLeaveCancelled: TransitionHookValidator,
3486 // appear
3487 onBeforeAppear: TransitionHookValidator,
3488 onAppear: TransitionHookValidator,
3489 onAfterAppear: TransitionHookValidator,
3490 onAppearCancelled: TransitionHookValidator
3491 },
3492 setup(props, { slots }) {
3493 const instance = getCurrentInstance();
3494 const state = useTransitionState();
3495 let prevTransitionKey;
3496 return () => {
3497 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3498 if (!children || !children.length) {
3499 return;
3500 }
3501 let child = children[0];
3502 if (children.length > 1) {
3503 let hasFound = false;
3504 // locate first non-comment child
3505 for (const c of children) {
3506 if (c.type !== Comment) {
3507 if (hasFound) {
3508 // warn more than one non-comment child
3509 warn$1('<transition> can only be used on a single element or component. ' +
3510 'Use <transition-group> for lists.');
3511 break;
3512 }
3513 child = c;
3514 hasFound = true;
3515 }
3516 }
3517 }
3518 // there's no need to track reactivity for these props so use the raw
3519 // props for a bit better perf
3520 const rawProps = toRaw(props);
3521 const { mode } = rawProps;
3522 // check mode
3523 if (mode &&
3524 mode !== 'in-out' &&
3525 mode !== 'out-in' &&
3526 mode !== 'default') {
3527 warn$1(`invalid <transition> mode: ${mode}`);
3528 }
3529 if (state.isLeaving) {
3530 return emptyPlaceholder(child);
3531 }
3532 // in the case of <transition><keep-alive/></transition>, we need to
3533 // compare the type of the kept-alive children.
3534 const innerChild = getKeepAliveChild(child);
3535 if (!innerChild) {
3536 return emptyPlaceholder(child);
3537 }
3538 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3539 setTransitionHooks(innerChild, enterHooks);
3540 const oldChild = instance.subTree;
3541 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3542 let transitionKeyChanged = false;
3543 const { getTransitionKey } = innerChild.type;
3544 if (getTransitionKey) {
3545 const key = getTransitionKey();
3546 if (prevTransitionKey === undefined) {
3547 prevTransitionKey = key;
3548 }
3549 else if (key !== prevTransitionKey) {
3550 prevTransitionKey = key;
3551 transitionKeyChanged = true;
3552 }
3553 }
3554 // handle mode
3555 if (oldInnerChild &&
3556 oldInnerChild.type !== Comment &&
3557 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3558 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3559 // update old tree's hooks in case of dynamic transition
3560 setTransitionHooks(oldInnerChild, leavingHooks);
3561 // switching between different views
3562 if (mode === 'out-in') {
3563 state.isLeaving = true;
3564 // return placeholder node and queue update when leave finishes
3565 leavingHooks.afterLeave = () => {
3566 state.isLeaving = false;
3567 instance.update();
3568 };
3569 return emptyPlaceholder(child);
3570 }
3571 else if (mode === 'in-out' && innerChild.type !== Comment) {
3572 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3573 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3574 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3575 // early removal callback
3576 el._leaveCb = () => {
3577 earlyRemove();
3578 el._leaveCb = undefined;
3579 delete enterHooks.delayedLeave;
3580 };
3581 enterHooks.delayedLeave = delayedLeave;
3582 };
3583 }
3584 }
3585 return child;
3586 };
3587 }
3588 };
3589 // export the public type for h/tsx inference
3590 // also to avoid inline import() in generated d.ts files
3591 const BaseTransition = BaseTransitionImpl;
3592 function getLeavingNodesForType(state, vnode) {
3593 const { leavingVNodes } = state;
3594 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3595 if (!leavingVNodesCache) {
3596 leavingVNodesCache = Object.create(null);
3597 leavingVNodes.set(vnode.type, leavingVNodesCache);
3598 }
3599 return leavingVNodesCache;
3600 }
3601 // The transition hooks are attached to the vnode as vnode.transition
3602 // and will be called at appropriate timing in the renderer.
3603 function resolveTransitionHooks(vnode, props, state, instance) {
3604 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3605 const key = String(vnode.key);
3606 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3607 const callHook = (hook, args) => {
3608 hook &&
3609 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3610 };
3611 const callAsyncHook = (hook, args) => {
3612 const done = args[1];
3613 callHook(hook, args);
3614 if (isArray(hook)) {
3615 if (hook.every(hook => hook.length <= 1))
3616 done();
3617 }
3618 else if (hook.length <= 1) {
3619 done();
3620 }
3621 };
3622 const hooks = {
3623 mode,
3624 persisted,
3625 beforeEnter(el) {
3626 let hook = onBeforeEnter;
3627 if (!state.isMounted) {
3628 if (appear) {
3629 hook = onBeforeAppear || onBeforeEnter;
3630 }
3631 else {
3632 return;
3633 }
3634 }
3635 // for same element (v-show)
3636 if (el._leaveCb) {
3637 el._leaveCb(true /* cancelled */);
3638 }
3639 // for toggled element with same key (v-if)
3640 const leavingVNode = leavingVNodesCache[key];
3641 if (leavingVNode &&
3642 isSameVNodeType(vnode, leavingVNode) &&
3643 leavingVNode.el._leaveCb) {
3644 // force early removal (not cancelled)
3645 leavingVNode.el._leaveCb();
3646 }
3647 callHook(hook, [el]);
3648 },
3649 enter(el) {
3650 let hook = onEnter;
3651 let afterHook = onAfterEnter;
3652 let cancelHook = onEnterCancelled;
3653 if (!state.isMounted) {
3654 if (appear) {
3655 hook = onAppear || onEnter;
3656 afterHook = onAfterAppear || onAfterEnter;
3657 cancelHook = onAppearCancelled || onEnterCancelled;
3658 }
3659 else {
3660 return;
3661 }
3662 }
3663 let called = false;
3664 const done = (el._enterCb = (cancelled) => {
3665 if (called)
3666 return;
3667 called = true;
3668 if (cancelled) {
3669 callHook(cancelHook, [el]);
3670 }
3671 else {
3672 callHook(afterHook, [el]);
3673 }
3674 if (hooks.delayedLeave) {
3675 hooks.delayedLeave();
3676 }
3677 el._enterCb = undefined;
3678 });
3679 if (hook) {
3680 callAsyncHook(hook, [el, done]);
3681 }
3682 else {
3683 done();
3684 }
3685 },
3686 leave(el, remove) {
3687 const key = String(vnode.key);
3688 if (el._enterCb) {
3689 el._enterCb(true /* cancelled */);
3690 }
3691 if (state.isUnmounting) {
3692 return remove();
3693 }
3694 callHook(onBeforeLeave, [el]);
3695 let called = false;
3696 const done = (el._leaveCb = (cancelled) => {
3697 if (called)
3698 return;
3699 called = true;
3700 remove();
3701 if (cancelled) {
3702 callHook(onLeaveCancelled, [el]);
3703 }
3704 else {
3705 callHook(onAfterLeave, [el]);
3706 }
3707 el._leaveCb = undefined;
3708 if (leavingVNodesCache[key] === vnode) {
3709 delete leavingVNodesCache[key];
3710 }
3711 });
3712 leavingVNodesCache[key] = vnode;
3713 if (onLeave) {
3714 callAsyncHook(onLeave, [el, done]);
3715 }
3716 else {
3717 done();
3718 }
3719 },
3720 clone(vnode) {
3721 return resolveTransitionHooks(vnode, props, state, instance);
3722 }
3723 };
3724 return hooks;
3725 }
3726 // the placeholder really only handles one special case: KeepAlive
3727 // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3728 // placeholder with empty content to avoid the KeepAlive instance from being
3729 // unmounted.
3730 function emptyPlaceholder(vnode) {
3731 if (isKeepAlive(vnode)) {
3732 vnode = cloneVNode(vnode);
3733 vnode.children = null;
3734 return vnode;
3735 }
3736 }
3737 function getKeepAliveChild(vnode) {
3738 return isKeepAlive(vnode)
3739 ? vnode.children
3740 ? vnode.children[0]
3741 : undefined
3742 : vnode;
3743 }
3744 function setTransitionHooks(vnode, hooks) {
3745 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3746 setTransitionHooks(vnode.component.subTree, hooks);
3747 }
3748 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3749 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3750 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3751 }
3752 else {
3753 vnode.transition = hooks;
3754 }
3755 }
3756 function getTransitionRawChildren(children, keepComment = false, parentKey) {
3757 let ret = [];
3758 let keyedFragmentCount = 0;
3759 for (let i = 0; i < children.length; i++) {
3760 let child = children[i];
3761 // #5360 inherit parent key in case of <template v-for>
3762 const key = parentKey == null
3763 ? child.key
3764 : String(parentKey) + String(child.key != null ? child.key : i);
3765 // handle fragment children case, e.g. v-for
3766 if (child.type === Fragment) {
3767 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3768 keyedFragmentCount++;
3769 ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
3770 }
3771 // comment placeholders should be skipped, e.g. v-if
3772 else if (keepComment || child.type !== Comment) {
3773 ret.push(key != null ? cloneVNode(child, { key }) : child);
3774 }
3775 }
3776 // #1126 if a transition children list contains multiple sub fragments, these
3777 // fragments will be merged into a flat children array. Since each v-for
3778 // fragment may contain different static bindings inside, we need to de-op
3779 // these children to force full diffs to ensure correct behavior.
3780 if (keyedFragmentCount > 1) {
3781 for (let i = 0; i < ret.length; i++) {
3782 ret[i].patchFlag = -2 /* BAIL */;
3783 }
3784 }
3785 return ret;
3786 }
3787
3788 // implementation, close to no-op
3789 function defineComponent(options) {
3790 return isFunction(options) ? { setup: options, name: options.name } : options;
3791 }
3792
3793 const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3794 function defineAsyncComponent(source) {
3795 if (isFunction(source)) {
3796 source = { loader: source };
3797 }
3798 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3799 suspensible = true, onError: userOnError } = source;
3800 let pendingRequest = null;
3801 let resolvedComp;
3802 let retries = 0;
3803 const retry = () => {
3804 retries++;
3805 pendingRequest = null;
3806 return load();
3807 };
3808 const load = () => {
3809 let thisRequest;
3810 return (pendingRequest ||
3811 (thisRequest = pendingRequest =
3812 loader()
3813 .catch(err => {
3814 err = err instanceof Error ? err : new Error(String(err));
3815 if (userOnError) {
3816 return new Promise((resolve, reject) => {
3817 const userRetry = () => resolve(retry());
3818 const userFail = () => reject(err);
3819 userOnError(err, userRetry, userFail, retries + 1);
3820 });
3821 }
3822 else {
3823 throw err;
3824 }
3825 })
3826 .then((comp) => {
3827 if (thisRequest !== pendingRequest && pendingRequest) {
3828 return pendingRequest;
3829 }
3830 if (!comp) {
3831 warn$1(`Async component loader resolved to undefined. ` +
3832 `If you are using retry(), make sure to return its return value.`);
3833 }
3834 // interop module default
3835 if (comp &&
3836 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3837 comp = comp.default;
3838 }
3839 if (comp && !isObject(comp) && !isFunction(comp)) {
3840 throw new Error(`Invalid async component load result: ${comp}`);
3841 }
3842 resolvedComp = comp;
3843 return comp;
3844 })));
3845 };
3846 return defineComponent({
3847 name: 'AsyncComponentWrapper',
3848 __asyncLoader: load,
3849 get __asyncResolved() {
3850 return resolvedComp;
3851 },
3852 setup() {
3853 const instance = currentInstance;
3854 // already resolved
3855 if (resolvedComp) {
3856 return () => createInnerComp(resolvedComp, instance);
3857 }
3858 const onError = (err) => {
3859 pendingRequest = null;
3860 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3861 };
3862 // suspense-controlled or SSR.
3863 if ((suspensible && instance.suspense) ||
3864 (false )) {
3865 return load()
3866 .then(comp => {
3867 return () => createInnerComp(comp, instance);
3868 })
3869 .catch(err => {
3870 onError(err);
3871 return () => errorComponent
3872 ? createVNode(errorComponent, {
3873 error: err
3874 })
3875 : null;
3876 });
3877 }
3878 const loaded = ref(false);
3879 const error = ref();
3880 const delayed = ref(!!delay);
3881 if (delay) {
3882 setTimeout(() => {
3883 delayed.value = false;
3884 }, delay);
3885 }
3886 if (timeout != null) {
3887 setTimeout(() => {
3888 if (!loaded.value && !error.value) {
3889 const err = new Error(`Async component timed out after ${timeout}ms.`);
3890 onError(err);
3891 error.value = err;
3892 }
3893 }, timeout);
3894 }
3895 load()
3896 .then(() => {
3897 loaded.value = true;
3898 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3899 // parent is keep-alive, force update so the loaded component's
3900 // name is taken into account
3901 queueJob(instance.parent.update);
3902 }
3903 })
3904 .catch(err => {
3905 onError(err);
3906 error.value = err;
3907 });
3908 return () => {
3909 if (loaded.value && resolvedComp) {
3910 return createInnerComp(resolvedComp, instance);
3911 }
3912 else if (error.value && errorComponent) {
3913 return createVNode(errorComponent, {
3914 error: error.value
3915 });
3916 }
3917 else if (loadingComponent && !delayed.value) {
3918 return createVNode(loadingComponent);
3919 }
3920 };
3921 }
3922 });
3923 }
3924 function createInnerComp(comp, { vnode: { ref, props, children, shapeFlag }, parent }) {
3925 const vnode = createVNode(comp, props, children);
3926 // ensure inner component inherits the async wrapper's ref owner
3927 vnode.ref = ref;
3928 return vnode;
3929 }
3930
3931 const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3932 const KeepAliveImpl = {
3933 name: `KeepAlive`,
3934 // Marker for special handling inside the renderer. We are not using a ===
3935 // check directly on KeepAlive in the renderer, because importing it directly
3936 // would prevent it from being tree-shaken.
3937 __isKeepAlive: true,
3938 props: {
3939 include: [String, RegExp, Array],
3940 exclude: [String, RegExp, Array],
3941 max: [String, Number]
3942 },
3943 setup(props, { slots }) {
3944 const instance = getCurrentInstance();
3945 // KeepAlive communicates with the instantiated renderer via the
3946 // ctx where the renderer passes in its internals,
3947 // and the KeepAlive instance exposes activate/deactivate implementations.
3948 // The whole point of this is to avoid importing KeepAlive directly in the
3949 // renderer to facilitate tree-shaking.
3950 const sharedContext = instance.ctx;
3951 const cache = new Map();
3952 const keys = new Set();
3953 let current = null;
3954 {
3955 instance.__v_cache = cache;
3956 }
3957 const parentSuspense = instance.suspense;
3958 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3959 const storageContainer = createElement('div');
3960 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3961 const instance = vnode.component;
3962 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3963 // in case props have changed
3964 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3965 queuePostRenderEffect(() => {
3966 instance.isDeactivated = false;
3967 if (instance.a) {
3968 invokeArrayFns(instance.a);
3969 }
3970 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3971 if (vnodeHook) {
3972 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3973 }
3974 }, parentSuspense);
3975 {
3976 // Update components tree
3977 devtoolsComponentAdded(instance);
3978 }
3979 };
3980 sharedContext.deactivate = (vnode) => {
3981 const instance = vnode.component;
3982 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3983 queuePostRenderEffect(() => {
3984 if (instance.da) {
3985 invokeArrayFns(instance.da);
3986 }
3987 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3988 if (vnodeHook) {
3989 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3990 }
3991 instance.isDeactivated = true;
3992 }, parentSuspense);
3993 {
3994 // Update components tree
3995 devtoolsComponentAdded(instance);
3996 }
3997 };
3998 function unmount(vnode) {
3999 // reset the shapeFlag so it can be properly unmounted
4000 resetShapeFlag(vnode);
4001 _unmount(vnode, instance, parentSuspense, true);
4002 }
4003 function pruneCache(filter) {
4004 cache.forEach((vnode, key) => {
4005 const name = getComponentName(vnode.type);
4006 if (name && (!filter || !filter(name))) {
4007 pruneCacheEntry(key);
4008 }
4009 });
4010 }
4011 function pruneCacheEntry(key) {
4012 const cached = cache.get(key);
4013 if (!current || cached.type !== current.type) {
4014 unmount(cached);
4015 }
4016 else if (current) {
4017 // current active instance should no longer be kept-alive.
4018 // we can't unmount it now but it might be later, so reset its flag now.
4019 resetShapeFlag(current);
4020 }
4021 cache.delete(key);
4022 keys.delete(key);
4023 }
4024 // prune cache on include/exclude prop change
4025 watch(() => [props.include, props.exclude], ([include, exclude]) => {
4026 include && pruneCache(name => matches(include, name));
4027 exclude && pruneCache(name => !matches(exclude, name));
4028 },
4029 // prune post-render after `current` has been updated
4030 { flush: 'post', deep: true });
4031 // cache sub tree after render
4032 let pendingCacheKey = null;
4033 const cacheSubtree = () => {
4034 // fix #1621, the pendingCacheKey could be 0
4035 if (pendingCacheKey != null) {
4036 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
4037 }
4038 };
4039 onMounted(cacheSubtree);
4040 onUpdated(cacheSubtree);
4041 onBeforeUnmount(() => {
4042 cache.forEach(cached => {
4043 const { subTree, suspense } = instance;
4044 const vnode = getInnerChild(subTree);
4045 if (cached.type === vnode.type) {
4046 // current instance will be unmounted as part of keep-alive's unmount
4047 resetShapeFlag(vnode);
4048 // but invoke its deactivated hook here
4049 const da = vnode.component.da;
4050 da && queuePostRenderEffect(da, suspense);
4051 return;
4052 }
4053 unmount(cached);
4054 });
4055 });
4056 return () => {
4057 pendingCacheKey = null;
4058 if (!slots.default) {
4059 return null;
4060 }
4061 const children = slots.default();
4062 const rawVNode = children[0];
4063 if (children.length > 1) {
4064 {
4065 warn$1(`KeepAlive should contain exactly one component child.`);
4066 }
4067 current = null;
4068 return children;
4069 }
4070 else if (!isVNode(rawVNode) ||
4071 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
4072 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
4073 current = null;
4074 return rawVNode;
4075 }
4076 let vnode = getInnerChild(rawVNode);
4077 const comp = vnode.type;
4078 // for async components, name check should be based in its loaded
4079 // inner component if available
4080 const name = getComponentName(isAsyncWrapper(vnode)
4081 ? vnode.type.__asyncResolved || {}
4082 : comp);
4083 const { include, exclude, max } = props;
4084 if ((include && (!name || !matches(include, name))) ||
4085 (exclude && name && matches(exclude, name))) {
4086 current = vnode;
4087 return rawVNode;
4088 }
4089 const key = vnode.key == null ? comp : vnode.key;
4090 const cachedVNode = cache.get(key);
4091 // clone vnode if it's reused because we are going to mutate it
4092 if (vnode.el) {
4093 vnode = cloneVNode(vnode);
4094 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
4095 rawVNode.ssContent = vnode;
4096 }
4097 }
4098 // #1513 it's possible for the returned vnode to be cloned due to attr
4099 // fallthrough or scopeId, so the vnode here may not be the final vnode
4100 // that is mounted. Instead of caching it directly, we store the pending
4101 // key and cache `instance.subTree` (the normalized vnode) in
4102 // beforeMount/beforeUpdate hooks.
4103 pendingCacheKey = key;
4104 if (cachedVNode) {
4105 // copy over mounted state
4106 vnode.el = cachedVNode.el;
4107 vnode.component = cachedVNode.component;
4108 if (vnode.transition) {
4109 // recursively update transition hooks on subTree
4110 setTransitionHooks(vnode, vnode.transition);
4111 }
4112 // avoid vnode being mounted as fresh
4113 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
4114 // make this key the freshest
4115 keys.delete(key);
4116 keys.add(key);
4117 }
4118 else {
4119 keys.add(key);
4120 // prune oldest entry
4121 if (max && keys.size > parseInt(max, 10)) {
4122 pruneCacheEntry(keys.values().next().value);
4123 }
4124 }
4125 // avoid vnode being unmounted
4126 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4127 current = vnode;
4128 return isSuspense(rawVNode.type) ? rawVNode : vnode;
4129 };
4130 }
4131 };
4132 // export the public type for h/tsx inference
4133 // also to avoid inline import() in generated d.ts files
4134 const KeepAlive = KeepAliveImpl;
4135 function matches(pattern, name) {
4136 if (isArray(pattern)) {
4137 return pattern.some((p) => matches(p, name));
4138 }
4139 else if (isString(pattern)) {
4140 return pattern.split(',').includes(name);
4141 }
4142 else if (pattern.test) {
4143 return pattern.test(name);
4144 }
4145 /* istanbul ignore next */
4146 return false;
4147 }
4148 function onActivated(hook, target) {
4149 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
4150 }
4151 function onDeactivated(hook, target) {
4152 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
4153 }
4154 function registerKeepAliveHook(hook, type, target = currentInstance) {
4155 // cache the deactivate branch check wrapper for injected hooks so the same
4156 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4157 // deactivation check".
4158 const wrappedHook = hook.__wdc ||
4159 (hook.__wdc = () => {
4160 // only fire the hook if the target instance is NOT in a deactivated branch.
4161 let current = target;
4162 while (current) {
4163 if (current.isDeactivated) {
4164 return;
4165 }
4166 current = current.parent;
4167 }
4168 return hook();
4169 });
4170 injectHook(type, wrappedHook, target);
4171 // In addition to registering it on the target instance, we walk up the parent
4172 // chain and register it on all ancestor instances that are keep-alive roots.
4173 // This avoids the need to walk the entire component tree when invoking these
4174 // hooks, and more importantly, avoids the need to track child components in
4175 // arrays.
4176 if (target) {
4177 let current = target.parent;
4178 while (current && current.parent) {
4179 if (isKeepAlive(current.parent.vnode)) {
4180 injectToKeepAliveRoot(wrappedHook, type, target, current);
4181 }
4182 current = current.parent;
4183 }
4184 }
4185 }
4186 function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4187 // injectHook wraps the original for error handling, so make sure to remove
4188 // the wrapped version.
4189 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4190 onUnmounted(() => {
4191 remove(keepAliveRoot[type], injected);
4192 }, target);
4193 }
4194 function resetShapeFlag(vnode) {
4195 let shapeFlag = vnode.shapeFlag;
4196 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4197 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4198 }
4199 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4200 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4201 }
4202 vnode.shapeFlag = shapeFlag;
4203 }
4204 function getInnerChild(vnode) {
4205 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4206 }
4207
4208 function injectHook(type, hook, target = currentInstance, prepend = false) {
4209 if (target) {
4210 const hooks = target[type] || (target[type] = []);
4211 // cache the error handling wrapper for injected hooks so the same hook
4212 // can be properly deduped by the scheduler. "__weh" stands for "with error
4213 // handling".
4214 const wrappedHook = hook.__weh ||
4215 (hook.__weh = (...args) => {
4216 if (target.isUnmounted) {
4217 return;
4218 }
4219 // disable tracking inside all lifecycle hooks
4220 // since they can potentially be called inside effects.
4221 pauseTracking();
4222 // Set currentInstance during hook invocation.
4223 // This assumes the hook does not synchronously trigger other hooks, which
4224 // can only be false when the user does something really funky.
4225 setCurrentInstance(target);
4226 const res = callWithAsyncErrorHandling(hook, target, type, args);
4227 unsetCurrentInstance();
4228 resetTracking();
4229 return res;
4230 });
4231 if (prepend) {
4232 hooks.unshift(wrappedHook);
4233 }
4234 else {
4235 hooks.push(wrappedHook);
4236 }
4237 return wrappedHook;
4238 }
4239 else {
4240 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4241 warn$1(`${apiName} is called when there is no active component instance to be ` +
4242 `associated with. ` +
4243 `Lifecycle injection APIs can only be used during execution of setup().` +
4244 (` If you are using async setup(), make sure to register lifecycle ` +
4245 `hooks before the first await statement.`
4246 ));
4247 }
4248 }
4249 const createHook = (lifecycle) => (hook, target = currentInstance) =>
4250 // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4251 (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
4252 injectHook(lifecycle, hook, target);
4253 const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
4254 const onMounted = createHook("m" /* MOUNTED */);
4255 const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
4256 const onUpdated = createHook("u" /* UPDATED */);
4257 const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
4258 const onUnmounted = createHook("um" /* UNMOUNTED */);
4259 const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
4260 const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
4261 const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
4262 function onErrorCaptured(hook, target = currentInstance) {
4263 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
4264 }
4265
4266 /**
4267 Runtime helper for applying directives to a vnode. Example usage:
4268
4269 const comp = resolveComponent('comp')
4270 const foo = resolveDirective('foo')
4271 const bar = resolveDirective('bar')
4272
4273 return withDirectives(h(comp), [
4274 [foo, this.x],
4275 [bar, this.y]
4276 ])
4277 */
4278 function validateDirectiveName(name) {
4279 if (isBuiltInDirective(name)) {
4280 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
4281 }
4282 }
4283 /**
4284 * Adds directives to a VNode.
4285 */
4286 function withDirectives(vnode, directives) {
4287 const internalInstance = currentRenderingInstance;
4288 if (internalInstance === null) {
4289 warn$1(`withDirectives can only be used inside render functions.`);
4290 return vnode;
4291 }
4292 const instance = getExposeProxy(internalInstance) ||
4293 internalInstance.proxy;
4294 const bindings = vnode.dirs || (vnode.dirs = []);
4295 for (let i = 0; i < directives.length; i++) {
4296 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4297 if (isFunction(dir)) {
4298 dir = {
4299 mounted: dir,
4300 updated: dir
4301 };
4302 }
4303 if (dir.deep) {
4304 traverse(value);
4305 }
4306 bindings.push({
4307 dir,
4308 instance,
4309 value,
4310 oldValue: void 0,
4311 arg,
4312 modifiers
4313 });
4314 }
4315 return vnode;
4316 }
4317 function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4318 const bindings = vnode.dirs;
4319 const oldBindings = prevVNode && prevVNode.dirs;
4320 for (let i = 0; i < bindings.length; i++) {
4321 const binding = bindings[i];
4322 if (oldBindings) {
4323 binding.oldValue = oldBindings[i].value;
4324 }
4325 let hook = binding.dir[name];
4326 if (hook) {
4327 // disable tracking inside all lifecycle hooks
4328 // since they can potentially be called inside effects.
4329 pauseTracking();
4330 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4331 vnode.el,
4332 binding,
4333 vnode,
4334 prevVNode
4335 ]);
4336 resetTracking();
4337 }
4338 }
4339 }
4340
4341 const COMPONENTS = 'components';
4342 const DIRECTIVES = 'directives';
4343 /**
4344 * @private
4345 */
4346 function resolveComponent(name, maybeSelfReference) {
4347 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
4348 }
4349 const NULL_DYNAMIC_COMPONENT = Symbol();
4350 /**
4351 * @private
4352 */
4353 function resolveDynamicComponent(component) {
4354 if (isString(component)) {
4355 return resolveAsset(COMPONENTS, component, false) || component;
4356 }
4357 else {
4358 // invalid types will fallthrough to createVNode and raise warning
4359 return (component || NULL_DYNAMIC_COMPONENT);
4360 }
4361 }
4362 /**
4363 * @private
4364 */
4365 function resolveDirective(name) {
4366 return resolveAsset(DIRECTIVES, name);
4367 }
4368 // implementation
4369 function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
4370 const instance = currentRenderingInstance || currentInstance;
4371 if (instance) {
4372 const Component = instance.type;
4373 // explicit self name has highest priority
4374 if (type === COMPONENTS) {
4375 const selfName = getComponentName(Component, false /* do not include inferred name to avoid breaking existing code */);
4376 if (selfName &&
4377 (selfName === name ||
4378 selfName === camelize(name) ||
4379 selfName === capitalize(camelize(name)))) {
4380 return Component;
4381 }
4382 }
4383 const res =
4384 // local registration
4385 // check instance[type] first which is resolved for options API
4386 resolve(instance[type] || Component[type], name) ||
4387 // global registration
4388 resolve(instance.appContext[type], name);
4389 if (!res && maybeSelfReference) {
4390 // fallback to implicit self-reference
4391 return Component;
4392 }
4393 if (warnMissing && !res) {
4394 const extra = type === COMPONENTS
4395 ? `\nIf this is a native custom element, make sure to exclude it from ` +
4396 `component resolution via compilerOptions.isCustomElement.`
4397 : ``;
4398 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
4399 }
4400 return res;
4401 }
4402 else {
4403 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
4404 `can only be used in render() or setup().`);
4405 }
4406 }
4407 function resolve(registry, name) {
4408 return (registry &&
4409 (registry[name] ||
4410 registry[camelize(name)] ||
4411 registry[capitalize(camelize(name))]));
4412 }
4413
4414 /**
4415 * Actual implementation
4416 */
4417 function renderList(source, renderItem, cache, index) {
4418 let ret;
4419 const cached = (cache && cache[index]);
4420 if (isArray(source) || isString(source)) {
4421 ret = new Array(source.length);
4422 for (let i = 0, l = source.length; i < l; i++) {
4423 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
4424 }
4425 }
4426 else if (typeof source === 'number') {
4427 if (!Number.isInteger(source)) {
4428 warn$1(`The v-for range expect an integer value but got ${source}.`);
4429 }
4430 ret = new Array(source);
4431 for (let i = 0; i < source; i++) {
4432 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
4433 }
4434 }
4435 else if (isObject(source)) {
4436 if (source[Symbol.iterator]) {
4437 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
4438 }
4439 else {
4440 const keys = Object.keys(source);
4441 ret = new Array(keys.length);
4442 for (let i = 0, l = keys.length; i < l; i++) {
4443 const key = keys[i];
4444 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
4445 }
4446 }
4447 }
4448 else {
4449 ret = [];
4450 }
4451 if (cache) {
4452 cache[index] = ret;
4453 }
4454 return ret;
4455 }
4456
4457 /**
4458 * Compiler runtime helper for creating dynamic slots object
4459 * @private
4460 */
4461 function createSlots(slots, dynamicSlots) {
4462 for (let i = 0; i < dynamicSlots.length; i++) {
4463 const slot = dynamicSlots[i];
4464 // array of dynamic slot generated by <template v-for="..." #[...]>
4465 if (isArray(slot)) {
4466 for (let j = 0; j < slot.length; j++) {
4467 slots[slot[j].name] = slot[j].fn;
4468 }
4469 }
4470 else if (slot) {
4471 // conditional single slot generated by <template v-if="..." #foo>
4472 slots[slot.name] = slot.fn;
4473 }
4474 }
4475 return slots;
4476 }
4477
4478 /**
4479 * Compiler runtime helper for rendering `<slot/>`
4480 * @private
4481 */
4482 function renderSlot(slots, name, props = {},
4483 // this is not a user-facing function, so the fallback is always generated by
4484 // the compiler and guaranteed to be a function returning an array
4485 fallback, noSlotted) {
4486 if (currentRenderingInstance.isCE ||
4487 (currentRenderingInstance.parent &&
4488 isAsyncWrapper(currentRenderingInstance.parent) &&
4489 currentRenderingInstance.parent.isCE)) {
4490 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
4491 }
4492 let slot = slots[name];
4493 if (slot && slot.length > 1) {
4494 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
4495 `function. You need to mark this component with $dynamic-slots in the ` +
4496 `parent template.`);
4497 slot = () => [];
4498 }
4499 // a compiled slot disables block tracking by default to avoid manual
4500 // invocation interfering with template-based block tracking, but in
4501 // `renderSlot` we can be sure that it's template-based so we can force
4502 // enable it.
4503 if (slot && slot._c) {
4504 slot._d = false;
4505 }
4506 openBlock();
4507 const validSlotContent = slot && ensureValidVNode(slot(props));
4508 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
4509 ? 64 /* STABLE_FRAGMENT */
4510 : -2 /* BAIL */);
4511 if (!noSlotted && rendered.scopeId) {
4512 rendered.slotScopeIds = [rendered.scopeId + '-s'];
4513 }
4514 if (slot && slot._c) {
4515 slot._d = true;
4516 }
4517 return rendered;
4518 }
4519 function ensureValidVNode(vnodes) {
4520 return vnodes.some(child => {
4521 if (!isVNode(child))
4522 return true;
4523 if (child.type === Comment)
4524 return false;
4525 if (child.type === Fragment &&
4526 !ensureValidVNode(child.children))
4527 return false;
4528 return true;
4529 })
4530 ? vnodes
4531 : null;
4532 }
4533
4534 /**
4535 * For prefixing keys in v-on="obj" with "on"
4536 * @private
4537 */
4538 function toHandlers(obj) {
4539 const ret = {};
4540 if (!isObject(obj)) {
4541 warn$1(`v-on with no argument expects an object value.`);
4542 return ret;
4543 }
4544 for (const key in obj) {
4545 ret[toHandlerKey(key)] = obj[key];
4546 }
4547 return ret;
4548 }
4549
4550 /**
4551 * #2437 In Vue 3, functional components do not have a public instance proxy but
4552 * they exist in the internal parent chain. For code that relies on traversing
4553 * public $parent chains, skip functional ones and go to the parent instead.
4554 */
4555 const getPublicInstance = (i) => {
4556 if (!i)
4557 return null;
4558 if (isStatefulComponent(i))
4559 return getExposeProxy(i) || i.proxy;
4560 return getPublicInstance(i.parent);
4561 };
4562 const publicPropertiesMap =
4563 // Move PURE marker to new line to workaround compiler discarding it
4564 // due to type annotation
4565 /*#__PURE__*/ extend(Object.create(null), {
4566 $: i => i,
4567 $el: i => i.vnode.el,
4568 $data: i => i.data,
4569 $props: i => (shallowReadonly(i.props) ),
4570 $attrs: i => (shallowReadonly(i.attrs) ),
4571 $slots: i => (shallowReadonly(i.slots) ),
4572 $refs: i => (shallowReadonly(i.refs) ),
4573 $parent: i => getPublicInstance(i.parent),
4574 $root: i => getPublicInstance(i.root),
4575 $emit: i => i.emit,
4576 $options: i => (resolveMergedOptions(i) ),
4577 $forceUpdate: i => i.f || (i.f = () => queueJob(i.update)),
4578 $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy)),
4579 $watch: i => (instanceWatch.bind(i) )
4580 });
4581 const isReservedPrefix = (key) => key === '_' || key === '$';
4582 const PublicInstanceProxyHandlers = {
4583 get({ _: instance }, key) {
4584 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
4585 // for internal formatters to know that this is a Vue instance
4586 if (key === '__isVue') {
4587 return true;
4588 }
4589 // prioritize <script setup> bindings during dev.
4590 // this allows even properties that start with _ or $ to be used - so that
4591 // it aligns with the production behavior where the render fn is inlined and
4592 // indeed has access to all declared variables.
4593 if (setupState !== EMPTY_OBJ &&
4594 setupState.__isScriptSetup &&
4595 hasOwn(setupState, key)) {
4596 return setupState[key];
4597 }
4598 // data / props / ctx
4599 // This getter gets called for every property access on the render context
4600 // during render and is a major hotspot. The most expensive part of this
4601 // is the multiple hasOwn() calls. It's much faster to do a simple property
4602 // access on a plain object, so we use an accessCache object (with null
4603 // prototype) to memoize what access type a key corresponds to.
4604 let normalizedProps;
4605 if (key[0] !== '$') {
4606 const n = accessCache[key];
4607 if (n !== undefined) {
4608 switch (n) {
4609 case 1 /* SETUP */:
4610 return setupState[key];
4611 case 2 /* DATA */:
4612 return data[key];
4613 case 4 /* CONTEXT */:
4614 return ctx[key];
4615 case 3 /* PROPS */:
4616 return props[key];
4617 // default: just fallthrough
4618 }
4619 }
4620 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
4621 accessCache[key] = 1 /* SETUP */;
4622 return setupState[key];
4623 }
4624 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
4625 accessCache[key] = 2 /* DATA */;
4626 return data[key];
4627 }
4628 else if (
4629 // only cache other properties when instance has declared (thus stable)
4630 // props
4631 (normalizedProps = instance.propsOptions[0]) &&
4632 hasOwn(normalizedProps, key)) {
4633 accessCache[key] = 3 /* PROPS */;
4634 return props[key];
4635 }
4636 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
4637 accessCache[key] = 4 /* CONTEXT */;
4638 return ctx[key];
4639 }
4640 else if (shouldCacheAccess) {
4641 accessCache[key] = 0 /* OTHER */;
4642 }
4643 }
4644 const publicGetter = publicPropertiesMap[key];
4645 let cssModule, globalProperties;
4646 // public $xxx properties
4647 if (publicGetter) {
4648 if (key === '$attrs') {
4649 track(instance, "get" /* GET */, key);
4650 markAttrsAccessed();
4651 }
4652 return publicGetter(instance);
4653 }
4654 else if (
4655 // css module (injected by vue-loader)
4656 (cssModule = type.__cssModules) &&
4657 (cssModule = cssModule[key])) {
4658 return cssModule;
4659 }
4660 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
4661 // user may set custom properties to `this` that start with `$`
4662 accessCache[key] = 4 /* CONTEXT */;
4663 return ctx[key];
4664 }
4665 else if (
4666 // global properties
4667 ((globalProperties = appContext.config.globalProperties),
4668 hasOwn(globalProperties, key))) {
4669 {
4670 return globalProperties[key];
4671 }
4672 }
4673 else if (currentRenderingInstance &&
4674 (!isString(key) ||
4675 // #1091 avoid internal isRef/isVNode checks on component instance leading
4676 // to infinite warning loop
4677 key.indexOf('__v') !== 0)) {
4678 if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {
4679 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
4680 `character ("$" or "_") and is not proxied on the render context.`);
4681 }
4682 else if (instance === currentRenderingInstance) {
4683 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
4684 `but is not defined on instance.`);
4685 }
4686 }
4687 },
4688 set({ _: instance }, key, value) {
4689 const { data, setupState, ctx } = instance;
4690 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
4691 setupState[key] = value;
4692 return true;
4693 }
4694 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
4695 data[key] = value;
4696 return true;
4697 }
4698 else if (hasOwn(instance.props, key)) {
4699 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
4700 return false;
4701 }
4702 if (key[0] === '$' && key.slice(1) in instance) {
4703 warn$1(`Attempting to mutate public property "${key}". ` +
4704 `Properties starting with $ are reserved and readonly.`, instance);
4705 return false;
4706 }
4707 else {
4708 if (key in instance.appContext.config.globalProperties) {
4709 Object.defineProperty(ctx, key, {
4710 enumerable: true,
4711 configurable: true,
4712 value
4713 });
4714 }
4715 else {
4716 ctx[key] = value;
4717 }
4718 }
4719 return true;
4720 },
4721 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
4722 let normalizedProps;
4723 return (!!accessCache[key] ||
4724 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
4725 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
4726 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
4727 hasOwn(ctx, key) ||
4728 hasOwn(publicPropertiesMap, key) ||
4729 hasOwn(appContext.config.globalProperties, key));
4730 },
4731 defineProperty(target, key, descriptor) {
4732 if (descriptor.get != null) {
4733 // invalidate key cache of a getter based property #5417
4734 target._.accessCache[key] = 0;
4735 }
4736 else if (hasOwn(descriptor, 'value')) {
4737 this.set(target, key, descriptor.value, null);
4738 }
4739 return Reflect.defineProperty(target, key, descriptor);
4740 }
4741 };
4742 {
4743 PublicInstanceProxyHandlers.ownKeys = (target) => {
4744 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
4745 `The keys will be empty in production mode to avoid performance overhead.`);
4746 return Reflect.ownKeys(target);
4747 };
4748 }
4749 const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
4750 get(target, key) {
4751 // fast path for unscopables when using `with` block
4752 if (key === Symbol.unscopables) {
4753 return;
4754 }
4755 return PublicInstanceProxyHandlers.get(target, key, target);
4756 },
4757 has(_, key) {
4758 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
4759 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
4760 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
4761 }
4762 return has;
4763 }
4764 });
4765 // dev only
4766 // In dev mode, the proxy target exposes the same properties as seen on `this`
4767 // for easier console inspection. In prod mode it will be an empty object so
4768 // these properties definitions can be skipped.
4769 function createDevRenderContext(instance) {
4770 const target = {};
4771 // expose internal instance for proxy handlers
4772 Object.defineProperty(target, `_`, {
4773 configurable: true,
4774 enumerable: false,
4775 get: () => instance
4776 });
4777 // expose public properties
4778 Object.keys(publicPropertiesMap).forEach(key => {
4779 Object.defineProperty(target, key, {
4780 configurable: true,
4781 enumerable: false,
4782 get: () => publicPropertiesMap[key](instance),
4783 // intercepted by the proxy so no need for implementation,
4784 // but needed to prevent set errors
4785 set: NOOP
4786 });
4787 });
4788 return target;
4789 }
4790 // dev only
4791 function exposePropsOnRenderContext(instance) {
4792 const { ctx, propsOptions: [propsOptions] } = instance;
4793 if (propsOptions) {
4794 Object.keys(propsOptions).forEach(key => {
4795 Object.defineProperty(ctx, key, {
4796 enumerable: true,
4797 configurable: true,
4798 get: () => instance.props[key],
4799 set: NOOP
4800 });
4801 });
4802 }
4803 }
4804 // dev only
4805 function exposeSetupStateOnRenderContext(instance) {
4806 const { ctx, setupState } = instance;
4807 Object.keys(toRaw(setupState)).forEach(key => {
4808 if (!setupState.__isScriptSetup) {
4809 if (isReservedPrefix(key[0])) {
4810 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
4811 `which are reserved prefixes for Vue internals.`);
4812 return;
4813 }
4814 Object.defineProperty(ctx, key, {
4815 enumerable: true,
4816 configurable: true,
4817 get: () => setupState[key],
4818 set: NOOP
4819 });
4820 }
4821 });
4822 }
4823
4824 function createDuplicateChecker() {
4825 const cache = Object.create(null);
4826 return (type, key) => {
4827 if (cache[key]) {
4828 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
4829 }
4830 else {
4831 cache[key] = type;
4832 }
4833 };
4834 }
4835 let shouldCacheAccess = true;
4836 function applyOptions(instance) {
4837 const options = resolveMergedOptions(instance);
4838 const publicThis = instance.proxy;
4839 const ctx = instance.ctx;
4840 // do not cache property access on public proxy during state initialization
4841 shouldCacheAccess = false;
4842 // call beforeCreate first before accessing other options since
4843 // the hook may mutate resolved options (#2791)
4844 if (options.beforeCreate) {
4845 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
4846 }
4847 const {
4848 // state
4849 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4850 // lifecycle
4851 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4852 // public API
4853 expose, inheritAttrs,
4854 // assets
4855 components, directives, filters } = options;
4856 const checkDuplicateProperties = createDuplicateChecker() ;
4857 {
4858 const [propsOptions] = instance.propsOptions;
4859 if (propsOptions) {
4860 for (const key in propsOptions) {
4861 checkDuplicateProperties("Props" /* PROPS */, key);
4862 }
4863 }
4864 }
4865 // options initialization order (to be consistent with Vue 2):
4866 // - props (already done outside of this function)
4867 // - inject
4868 // - methods
4869 // - data (deferred since it relies on `this` access)
4870 // - computed
4871 // - watch (deferred since it relies on `this` access)
4872 if (injectOptions) {
4873 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
4874 }
4875 if (methods) {
4876 for (const key in methods) {
4877 const methodHandler = methods[key];
4878 if (isFunction(methodHandler)) {
4879 // In dev mode, we use the `createRenderContext` function to define
4880 // methods to the proxy target, and those are read-only but
4881 // reconfigurable, so it needs to be redefined here
4882 {
4883 Object.defineProperty(ctx, key, {
4884 value: methodHandler.bind(publicThis),
4885 configurable: true,
4886 enumerable: true,
4887 writable: true
4888 });
4889 }
4890 {
4891 checkDuplicateProperties("Methods" /* METHODS */, key);
4892 }
4893 }
4894 else {
4895 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4896 `Did you reference the function correctly?`);
4897 }
4898 }
4899 }
4900 if (dataOptions) {
4901 if (!isFunction(dataOptions)) {
4902 warn$1(`The data option must be a function. ` +
4903 `Plain object usage is no longer supported.`);
4904 }
4905 const data = dataOptions.call(publicThis, publicThis);
4906 if (isPromise(data)) {
4907 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
4908 `intend to perform data fetching before component renders, use ` +
4909 `async setup() + <Suspense>.`);
4910 }
4911 if (!isObject(data)) {
4912 warn$1(`data() should return an object.`);
4913 }
4914 else {
4915 instance.data = reactive(data);
4916 {
4917 for (const key in data) {
4918 checkDuplicateProperties("Data" /* DATA */, key);
4919 // expose data on ctx during dev
4920 if (!isReservedPrefix(key[0])) {
4921 Object.defineProperty(ctx, key, {
4922 configurable: true,
4923 enumerable: true,
4924 get: () => data[key],
4925 set: NOOP
4926 });
4927 }
4928 }
4929 }
4930 }
4931 }
4932 // state initialization complete at this point - start caching access
4933 shouldCacheAccess = true;
4934 if (computedOptions) {
4935 for (const key in computedOptions) {
4936 const opt = computedOptions[key];
4937 const get = isFunction(opt)
4938 ? opt.bind(publicThis, publicThis)
4939 : isFunction(opt.get)
4940 ? opt.get.bind(publicThis, publicThis)
4941 : NOOP;
4942 if (get === NOOP) {
4943 warn$1(`Computed property "${key}" has no getter.`);
4944 }
4945 const set = !isFunction(opt) && isFunction(opt.set)
4946 ? opt.set.bind(publicThis)
4947 : () => {
4948 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
4949 }
4950 ;
4951 const c = computed$1({
4952 get,
4953 set
4954 });
4955 Object.defineProperty(ctx, key, {
4956 enumerable: true,
4957 configurable: true,
4958 get: () => c.value,
4959 set: v => (c.value = v)
4960 });
4961 {
4962 checkDuplicateProperties("Computed" /* COMPUTED */, key);
4963 }
4964 }
4965 }
4966 if (watchOptions) {
4967 for (const key in watchOptions) {
4968 createWatcher(watchOptions[key], ctx, publicThis, key);
4969 }
4970 }
4971 if (provideOptions) {
4972 const provides = isFunction(provideOptions)
4973 ? provideOptions.call(publicThis)
4974 : provideOptions;
4975 Reflect.ownKeys(provides).forEach(key => {
4976 provide(key, provides[key]);
4977 });
4978 }
4979 if (created) {
4980 callHook(created, instance, "c" /* CREATED */);
4981 }
4982 function registerLifecycleHook(register, hook) {
4983 if (isArray(hook)) {
4984 hook.forEach(_hook => register(_hook.bind(publicThis)));
4985 }
4986 else if (hook) {
4987 register(hook.bind(publicThis));
4988 }
4989 }
4990 registerLifecycleHook(onBeforeMount, beforeMount);
4991 registerLifecycleHook(onMounted, mounted);
4992 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
4993 registerLifecycleHook(onUpdated, updated);
4994 registerLifecycleHook(onActivated, activated);
4995 registerLifecycleHook(onDeactivated, deactivated);
4996 registerLifecycleHook(onErrorCaptured, errorCaptured);
4997 registerLifecycleHook(onRenderTracked, renderTracked);
4998 registerLifecycleHook(onRenderTriggered, renderTriggered);
4999 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
5000 registerLifecycleHook(onUnmounted, unmounted);
5001 registerLifecycleHook(onServerPrefetch, serverPrefetch);
5002 if (isArray(expose)) {
5003 if (expose.length) {
5004 const exposed = instance.exposed || (instance.exposed = {});
5005 expose.forEach(key => {
5006 Object.defineProperty(exposed, key, {
5007 get: () => publicThis[key],
5008 set: val => (publicThis[key] = val)
5009 });
5010 });
5011 }
5012 else if (!instance.exposed) {
5013 instance.exposed = {};
5014 }
5015 }
5016 // options that are handled when creating the instance but also need to be
5017 // applied from mixins
5018 if (render && instance.render === NOOP) {
5019 instance.render = render;
5020 }
5021 if (inheritAttrs != null) {
5022 instance.inheritAttrs = inheritAttrs;
5023 }
5024 // asset options.
5025 if (components)
5026 instance.components = components;
5027 if (directives)
5028 instance.directives = directives;
5029 }
5030 function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
5031 if (isArray(injectOptions)) {
5032 injectOptions = normalizeInject(injectOptions);
5033 }
5034 for (const key in injectOptions) {
5035 const opt = injectOptions[key];
5036 let injected;
5037 if (isObject(opt)) {
5038 if ('default' in opt) {
5039 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
5040 }
5041 else {
5042 injected = inject(opt.from || key);
5043 }
5044 }
5045 else {
5046 injected = inject(opt);
5047 }
5048 if (isRef(injected)) {
5049 // TODO remove the check in 3.3
5050 if (unwrapRef) {
5051 Object.defineProperty(ctx, key, {
5052 enumerable: true,
5053 configurable: true,
5054 get: () => injected.value,
5055 set: v => (injected.value = v)
5056 });
5057 }
5058 else {
5059 {
5060 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
5061 `and no longer needs \`.value\` in the next minor release. ` +
5062 `To opt-in to the new behavior now, ` +
5063 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
5064 `temporary and will not be needed in the future.)`);
5065 }
5066 ctx[key] = injected;
5067 }
5068 }
5069 else {
5070 ctx[key] = injected;
5071 }
5072 {
5073 checkDuplicateProperties("Inject" /* INJECT */, key);
5074 }
5075 }
5076 }
5077 function callHook(hook, instance, type) {
5078 callWithAsyncErrorHandling(isArray(hook)
5079 ? hook.map(h => h.bind(instance.proxy))
5080 : hook.bind(instance.proxy), instance, type);
5081 }
5082 function createWatcher(raw, ctx, publicThis, key) {
5083 const getter = key.includes('.')
5084 ? createPathGetter(publicThis, key)
5085 : () => publicThis[key];
5086 if (isString(raw)) {
5087 const handler = ctx[raw];
5088 if (isFunction(handler)) {
5089 watch(getter, handler);
5090 }
5091 else {
5092 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
5093 }
5094 }
5095 else if (isFunction(raw)) {
5096 watch(getter, raw.bind(publicThis));
5097 }
5098 else if (isObject(raw)) {
5099 if (isArray(raw)) {
5100 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
5101 }
5102 else {
5103 const handler = isFunction(raw.handler)
5104 ? raw.handler.bind(publicThis)
5105 : ctx[raw.handler];
5106 if (isFunction(handler)) {
5107 watch(getter, handler, raw);
5108 }
5109 else {
5110 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
5111 }
5112 }
5113 }
5114 else {
5115 warn$1(`Invalid watch option: "${key}"`, raw);
5116 }
5117 }
5118 /**
5119 * Resolve merged options and cache it on the component.
5120 * This is done only once per-component since the merging does not involve
5121 * instances.
5122 */
5123 function resolveMergedOptions(instance) {
5124 const base = instance.type;
5125 const { mixins, extends: extendsOptions } = base;
5126 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
5127 const cached = cache.get(base);
5128 let resolved;
5129 if (cached) {
5130 resolved = cached;
5131 }
5132 else if (!globalMixins.length && !mixins && !extendsOptions) {
5133 {
5134 resolved = base;
5135 }
5136 }
5137 else {
5138 resolved = {};
5139 if (globalMixins.length) {
5140 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
5141 }
5142 mergeOptions(resolved, base, optionMergeStrategies);
5143 }
5144 cache.set(base, resolved);
5145 return resolved;
5146 }
5147 function mergeOptions(to, from, strats, asMixin = false) {
5148 const { mixins, extends: extendsOptions } = from;
5149 if (extendsOptions) {
5150 mergeOptions(to, extendsOptions, strats, true);
5151 }
5152 if (mixins) {
5153 mixins.forEach((m) => mergeOptions(to, m, strats, true));
5154 }
5155 for (const key in from) {
5156 if (asMixin && key === 'expose') {
5157 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
5158 `It should only be declared in the base component itself.`);
5159 }
5160 else {
5161 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
5162 to[key] = strat ? strat(to[key], from[key]) : from[key];
5163 }
5164 }
5165 return to;
5166 }
5167 const internalOptionMergeStrats = {
5168 data: mergeDataFn,
5169 props: mergeObjectOptions,
5170 emits: mergeObjectOptions,
5171 // objects
5172 methods: mergeObjectOptions,
5173 computed: mergeObjectOptions,
5174 // lifecycle
5175 beforeCreate: mergeAsArray,
5176 created: mergeAsArray,
5177 beforeMount: mergeAsArray,
5178 mounted: mergeAsArray,
5179 beforeUpdate: mergeAsArray,
5180 updated: mergeAsArray,
5181 beforeDestroy: mergeAsArray,
5182 beforeUnmount: mergeAsArray,
5183 destroyed: mergeAsArray,
5184 unmounted: mergeAsArray,
5185 activated: mergeAsArray,
5186 deactivated: mergeAsArray,
5187 errorCaptured: mergeAsArray,
5188 serverPrefetch: mergeAsArray,
5189 // assets
5190 components: mergeObjectOptions,
5191 directives: mergeObjectOptions,
5192 // watch
5193 watch: mergeWatchOptions,
5194 // provide / inject
5195 provide: mergeDataFn,
5196 inject: mergeInject
5197 };
5198 function mergeDataFn(to, from) {
5199 if (!from) {
5200 return to;
5201 }
5202 if (!to) {
5203 return from;
5204 }
5205 return function mergedDataFn() {
5206 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
5207 };
5208 }
5209 function mergeInject(to, from) {
5210 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
5211 }
5212 function normalizeInject(raw) {
5213 if (isArray(raw)) {
5214 const res = {};
5215 for (let i = 0; i < raw.length; i++) {
5216 res[raw[i]] = raw[i];
5217 }
5218 return res;
5219 }
5220 return raw;
5221 }
5222 function mergeAsArray(to, from) {
5223 return to ? [...new Set([].concat(to, from))] : from;
5224 }
5225 function mergeObjectOptions(to, from) {
5226 return to ? extend(extend(Object.create(null), to), from) : from;
5227 }
5228 function mergeWatchOptions(to, from) {
5229 if (!to)
5230 return from;
5231 if (!from)
5232 return to;
5233 const merged = extend(Object.create(null), to);
5234 for (const key in from) {
5235 merged[key] = mergeAsArray(to[key], from[key]);
5236 }
5237 return merged;
5238 }
5239
5240 function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
5241 isSSR = false) {
5242 const props = {};
5243 const attrs = {};
5244 def(attrs, InternalObjectKey, 1);
5245 instance.propsDefaults = Object.create(null);
5246 setFullProps(instance, rawProps, props, attrs);
5247 // ensure all declared prop keys are present
5248 for (const key in instance.propsOptions[0]) {
5249 if (!(key in props)) {
5250 props[key] = undefined;
5251 }
5252 }
5253 // validation
5254 {
5255 validateProps(rawProps || {}, props, instance);
5256 }
5257 if (isStateful) {
5258 // stateful
5259 instance.props = isSSR ? props : shallowReactive(props);
5260 }
5261 else {
5262 if (!instance.type.props) {
5263 // functional w/ optional props, props === attrs
5264 instance.props = attrs;
5265 }
5266 else {
5267 // functional w/ declared props
5268 instance.props = props;
5269 }
5270 }
5271 instance.attrs = attrs;
5272 }
5273 function updateProps(instance, rawProps, rawPrevProps, optimized) {
5274 const { props, attrs, vnode: { patchFlag } } = instance;
5275 const rawCurrentProps = toRaw(props);
5276 const [options] = instance.propsOptions;
5277 let hasAttrsChanged = false;
5278 if (
5279 // always force full diff in dev
5280 // - #1942 if hmr is enabled with sfc component
5281 // - vite#872 non-sfc component used by sfc component
5282 !((instance.type.__hmrId ||
5283 (instance.parent && instance.parent.type.__hmrId))) &&
5284 (optimized || patchFlag > 0) &&
5285 !(patchFlag & 16 /* FULL_PROPS */)) {
5286 if (patchFlag & 8 /* PROPS */) {
5287 // Compiler-generated props & no keys change, just set the updated
5288 // the props.
5289 const propsToUpdate = instance.vnode.dynamicProps;
5290 for (let i = 0; i < propsToUpdate.length; i++) {
5291 let key = propsToUpdate[i];
5292 // skip if the prop key is a declared emit event listener
5293 if (isEmitListener(instance.emitsOptions, key)) {
5294 continue;
5295 }
5296 // PROPS flag guarantees rawProps to be non-null
5297 const value = rawProps[key];
5298 if (options) {
5299 // attr / props separation was done on init and will be consistent
5300 // in this code path, so just check if attrs have it.
5301 if (hasOwn(attrs, key)) {
5302 if (value !== attrs[key]) {
5303 attrs[key] = value;
5304 hasAttrsChanged = true;
5305 }
5306 }
5307 else {
5308 const camelizedKey = camelize(key);
5309 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
5310 }
5311 }
5312 else {
5313 if (value !== attrs[key]) {
5314 attrs[key] = value;
5315 hasAttrsChanged = true;
5316 }
5317 }
5318 }
5319 }
5320 }
5321 else {
5322 // full props update.
5323 if (setFullProps(instance, rawProps, props, attrs)) {
5324 hasAttrsChanged = true;
5325 }
5326 // in case of dynamic props, check if we need to delete keys from
5327 // the props object
5328 let kebabKey;
5329 for (const key in rawCurrentProps) {
5330 if (!rawProps ||
5331 // for camelCase
5332 (!hasOwn(rawProps, key) &&
5333 // it's possible the original props was passed in as kebab-case
5334 // and converted to camelCase (#955)
5335 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
5336 if (options) {
5337 if (rawPrevProps &&
5338 // for camelCase
5339 (rawPrevProps[key] !== undefined ||
5340 // for kebab-case
5341 rawPrevProps[kebabKey] !== undefined)) {
5342 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
5343 }
5344 }
5345 else {
5346 delete props[key];
5347 }
5348 }
5349 }
5350 // in the case of functional component w/o props declaration, props and
5351 // attrs point to the same object so it should already have been updated.
5352 if (attrs !== rawCurrentProps) {
5353 for (const key in attrs) {
5354 if (!rawProps ||
5355 (!hasOwn(rawProps, key) &&
5356 (!false ))) {
5357 delete attrs[key];
5358 hasAttrsChanged = true;
5359 }
5360 }
5361 }
5362 }
5363 // trigger updates for $attrs in case it's used in component slots
5364 if (hasAttrsChanged) {
5365 trigger(instance, "set" /* SET */, '$attrs');
5366 }
5367 {
5368 validateProps(rawProps || {}, props, instance);
5369 }
5370 }
5371 function setFullProps(instance, rawProps, props, attrs) {
5372 const [options, needCastKeys] = instance.propsOptions;
5373 let hasAttrsChanged = false;
5374 let rawCastValues;
5375 if (rawProps) {
5376 for (let key in rawProps) {
5377 // key, ref are reserved and never passed down
5378 if (isReservedProp(key)) {
5379 continue;
5380 }
5381 const value = rawProps[key];
5382 // prop option names are camelized during normalization, so to support
5383 // kebab -> camel conversion here we need to camelize the key.
5384 let camelKey;
5385 if (options && hasOwn(options, (camelKey = camelize(key)))) {
5386 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
5387 props[camelKey] = value;
5388 }
5389 else {
5390 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
5391 }
5392 }
5393 else if (!isEmitListener(instance.emitsOptions, key)) {
5394 if (!(key in attrs) || value !== attrs[key]) {
5395 attrs[key] = value;
5396 hasAttrsChanged = true;
5397 }
5398 }
5399 }
5400 }
5401 if (needCastKeys) {
5402 const rawCurrentProps = toRaw(props);
5403 const castValues = rawCastValues || EMPTY_OBJ;
5404 for (let i = 0; i < needCastKeys.length; i++) {
5405 const key = needCastKeys[i];
5406 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
5407 }
5408 }
5409 return hasAttrsChanged;
5410 }
5411 function resolvePropValue(options, props, key, value, instance, isAbsent) {
5412 const opt = options[key];
5413 if (opt != null) {
5414 const hasDefault = hasOwn(opt, 'default');
5415 // default values
5416 if (hasDefault && value === undefined) {
5417 const defaultValue = opt.default;
5418 if (opt.type !== Function && isFunction(defaultValue)) {
5419 const { propsDefaults } = instance;
5420 if (key in propsDefaults) {
5421 value = propsDefaults[key];
5422 }
5423 else {
5424 setCurrentInstance(instance);
5425 value = propsDefaults[key] = defaultValue.call(null, props);
5426 unsetCurrentInstance();
5427 }
5428 }
5429 else {
5430 value = defaultValue;
5431 }
5432 }
5433 // boolean casting
5434 if (opt[0 /* shouldCast */]) {
5435 if (isAbsent && !hasDefault) {
5436 value = false;
5437 }
5438 else if (opt[1 /* shouldCastTrue */] &&
5439 (value === '' || value === hyphenate(key))) {
5440 value = true;
5441 }
5442 }
5443 }
5444 return value;
5445 }
5446 function normalizePropsOptions(comp, appContext, asMixin = false) {
5447 const cache = appContext.propsCache;
5448 const cached = cache.get(comp);
5449 if (cached) {
5450 return cached;
5451 }
5452 const raw = comp.props;
5453 const normalized = {};
5454 const needCastKeys = [];
5455 // apply mixin/extends props
5456 let hasExtends = false;
5457 if (!isFunction(comp)) {
5458 const extendProps = (raw) => {
5459 hasExtends = true;
5460 const [props, keys] = normalizePropsOptions(raw, appContext, true);
5461 extend(normalized, props);
5462 if (keys)
5463 needCastKeys.push(...keys);
5464 };
5465 if (!asMixin && appContext.mixins.length) {
5466 appContext.mixins.forEach(extendProps);
5467 }
5468 if (comp.extends) {
5469 extendProps(comp.extends);
5470 }
5471 if (comp.mixins) {
5472 comp.mixins.forEach(extendProps);
5473 }
5474 }
5475 if (!raw && !hasExtends) {
5476 cache.set(comp, EMPTY_ARR);
5477 return EMPTY_ARR;
5478 }
5479 if (isArray(raw)) {
5480 for (let i = 0; i < raw.length; i++) {
5481 if (!isString(raw[i])) {
5482 warn$1(`props must be strings when using array syntax.`, raw[i]);
5483 }
5484 const normalizedKey = camelize(raw[i]);
5485 if (validatePropName(normalizedKey)) {
5486 normalized[normalizedKey] = EMPTY_OBJ;
5487 }
5488 }
5489 }
5490 else if (raw) {
5491 if (!isObject(raw)) {
5492 warn$1(`invalid props options`, raw);
5493 }
5494 for (const key in raw) {
5495 const normalizedKey = camelize(key);
5496 if (validatePropName(normalizedKey)) {
5497 const opt = raw[key];
5498 const prop = (normalized[normalizedKey] =
5499 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
5500 if (prop) {
5501 const booleanIndex = getTypeIndex(Boolean, prop.type);
5502 const stringIndex = getTypeIndex(String, prop.type);
5503 prop[0 /* shouldCast */] = booleanIndex > -1;
5504 prop[1 /* shouldCastTrue */] =
5505 stringIndex < 0 || booleanIndex < stringIndex;
5506 // if the prop needs boolean casting or default value
5507 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
5508 needCastKeys.push(normalizedKey);
5509 }
5510 }
5511 }
5512 }
5513 }
5514 const res = [normalized, needCastKeys];
5515 cache.set(comp, res);
5516 return res;
5517 }
5518 function validatePropName(key) {
5519 if (key[0] !== '$') {
5520 return true;
5521 }
5522 else {
5523 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
5524 }
5525 return false;
5526 }
5527 // use function string name to check type constructors
5528 // so that it works across vms / iframes.
5529 function getType(ctor) {
5530 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
5531 return match ? match[1] : ctor === null ? 'null' : '';
5532 }
5533 function isSameType(a, b) {
5534 return getType(a) === getType(b);
5535 }
5536 function getTypeIndex(type, expectedTypes) {
5537 if (isArray(expectedTypes)) {
5538 return expectedTypes.findIndex(t => isSameType(t, type));
5539 }
5540 else if (isFunction(expectedTypes)) {
5541 return isSameType(expectedTypes, type) ? 0 : -1;
5542 }
5543 return -1;
5544 }
5545 /**
5546 * dev only
5547 */
5548 function validateProps(rawProps, props, instance) {
5549 const resolvedValues = toRaw(props);
5550 const options = instance.propsOptions[0];
5551 for (const key in options) {
5552 let opt = options[key];
5553 if (opt == null)
5554 continue;
5555 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
5556 }
5557 }
5558 /**
5559 * dev only
5560 */
5561 function validateProp(name, value, prop, isAbsent) {
5562 const { type, required, validator } = prop;
5563 // required!
5564 if (required && isAbsent) {
5565 warn$1('Missing required prop: "' + name + '"');
5566 return;
5567 }
5568 // missing but optional
5569 if (value == null && !prop.required) {
5570 return;
5571 }
5572 // type check
5573 if (type != null && type !== true) {
5574 let isValid = false;
5575 const types = isArray(type) ? type : [type];
5576 const expectedTypes = [];
5577 // value is valid as long as one of the specified types match
5578 for (let i = 0; i < types.length && !isValid; i++) {
5579 const { valid, expectedType } = assertType(value, types[i]);
5580 expectedTypes.push(expectedType || '');
5581 isValid = valid;
5582 }
5583 if (!isValid) {
5584 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
5585 return;
5586 }
5587 }
5588 // custom validator
5589 if (validator && !validator(value)) {
5590 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
5591 }
5592 }
5593 const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
5594 /**
5595 * dev only
5596 */
5597 function assertType(value, type) {
5598 let valid;
5599 const expectedType = getType(type);
5600 if (isSimpleType(expectedType)) {
5601 const t = typeof value;
5602 valid = t === expectedType.toLowerCase();
5603 // for primitive wrapper objects
5604 if (!valid && t === 'object') {
5605 valid = value instanceof type;
5606 }
5607 }
5608 else if (expectedType === 'Object') {
5609 valid = isObject(value);
5610 }
5611 else if (expectedType === 'Array') {
5612 valid = isArray(value);
5613 }
5614 else if (expectedType === 'null') {
5615 valid = value === null;
5616 }
5617 else {
5618 valid = value instanceof type;
5619 }
5620 return {
5621 valid,
5622 expectedType
5623 };
5624 }
5625 /**
5626 * dev only
5627 */
5628 function getInvalidTypeMessage(name, value, expectedTypes) {
5629 let message = `Invalid prop: type check failed for prop "${name}".` +
5630 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
5631 const expectedType = expectedTypes[0];
5632 const receivedType = toRawType(value);
5633 const expectedValue = styleValue(value, expectedType);
5634 const receivedValue = styleValue(value, receivedType);
5635 // check if we need to specify expected value
5636 if (expectedTypes.length === 1 &&
5637 isExplicable(expectedType) &&
5638 !isBoolean(expectedType, receivedType)) {
5639 message += ` with value ${expectedValue}`;
5640 }
5641 message += `, got ${receivedType} `;
5642 // check if we need to specify received value
5643 if (isExplicable(receivedType)) {
5644 message += `with value ${receivedValue}.`;
5645 }
5646 return message;
5647 }
5648 /**
5649 * dev only
5650 */
5651 function styleValue(value, type) {
5652 if (type === 'String') {
5653 return `"${value}"`;
5654 }
5655 else if (type === 'Number') {
5656 return `${Number(value)}`;
5657 }
5658 else {
5659 return `${value}`;
5660 }
5661 }
5662 /**
5663 * dev only
5664 */
5665 function isExplicable(type) {
5666 const explicitTypes = ['string', 'number', 'boolean'];
5667 return explicitTypes.some(elem => type.toLowerCase() === elem);
5668 }
5669 /**
5670 * dev only
5671 */
5672 function isBoolean(...args) {
5673 return args.some(elem => elem.toLowerCase() === 'boolean');
5674 }
5675
5676 const isInternalKey = (key) => key[0] === '_' || key === '$stable';
5677 const normalizeSlotValue = (value) => isArray(value)
5678 ? value.map(normalizeVNode)
5679 : [normalizeVNode(value)];
5680 const normalizeSlot = (key, rawSlot, ctx) => {
5681 if (rawSlot._n) {
5682 // already normalized - #5353
5683 return rawSlot;
5684 }
5685 const normalized = withCtx((...args) => {
5686 if (currentInstance) {
5687 warn$1(`Slot "${key}" invoked outside of the render function: ` +
5688 `this will not track dependencies used in the slot. ` +
5689 `Invoke the slot function inside the render function instead.`);
5690 }
5691 return normalizeSlotValue(rawSlot(...args));
5692 }, ctx);
5693 normalized._c = false;
5694 return normalized;
5695 };
5696 const normalizeObjectSlots = (rawSlots, slots, instance) => {
5697 const ctx = rawSlots._ctx;
5698 for (const key in rawSlots) {
5699 if (isInternalKey(key))
5700 continue;
5701 const value = rawSlots[key];
5702 if (isFunction(value)) {
5703 slots[key] = normalizeSlot(key, value, ctx);
5704 }
5705 else if (value != null) {
5706 {
5707 warn$1(`Non-function value encountered for slot "${key}". ` +
5708 `Prefer function slots for better performance.`);
5709 }
5710 const normalized = normalizeSlotValue(value);
5711 slots[key] = () => normalized;
5712 }
5713 }
5714 };
5715 const normalizeVNodeSlots = (instance, children) => {
5716 if (!isKeepAlive(instance.vnode) &&
5717 !(false )) {
5718 warn$1(`Non-function value encountered for default slot. ` +
5719 `Prefer function slots for better performance.`);
5720 }
5721 const normalized = normalizeSlotValue(children);
5722 instance.slots.default = () => normalized;
5723 };
5724 const initSlots = (instance, children) => {
5725 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5726 const type = children._;
5727 if (type) {
5728 // users can get the shallow readonly version of the slots object through `this.$slots`,
5729 // we should avoid the proxy object polluting the slots of the internal instance
5730 instance.slots = toRaw(children);
5731 // make compiler marker non-enumerable
5732 def(children, '_', type);
5733 }
5734 else {
5735 normalizeObjectSlots(children, (instance.slots = {}));
5736 }
5737 }
5738 else {
5739 instance.slots = {};
5740 if (children) {
5741 normalizeVNodeSlots(instance, children);
5742 }
5743 }
5744 def(instance.slots, InternalObjectKey, 1);
5745 };
5746 const updateSlots = (instance, children, optimized) => {
5747 const { vnode, slots } = instance;
5748 let needDeletionCheck = true;
5749 let deletionComparisonTarget = EMPTY_OBJ;
5750 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5751 const type = children._;
5752 if (type) {
5753 // compiled slots.
5754 if (isHmrUpdating) {
5755 // Parent was HMR updated so slot content may have changed.
5756 // force update slots and mark instance for hmr as well
5757 extend(slots, children);
5758 }
5759 else if (optimized && type === 1 /* STABLE */) {
5760 // compiled AND stable.
5761 // no need to update, and skip stale slots removal.
5762 needDeletionCheck = false;
5763 }
5764 else {
5765 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5766 // normalization.
5767 extend(slots, children);
5768 // #2893
5769 // when rendering the optimized slots by manually written render function,
5770 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5771 // i.e. let the `renderSlot` create the bailed Fragment
5772 if (!optimized && type === 1 /* STABLE */) {
5773 delete slots._;
5774 }
5775 }
5776 }
5777 else {
5778 needDeletionCheck = !children.$stable;
5779 normalizeObjectSlots(children, slots);
5780 }
5781 deletionComparisonTarget = children;
5782 }
5783 else if (children) {
5784 // non slot object children (direct value) passed to a component
5785 normalizeVNodeSlots(instance, children);
5786 deletionComparisonTarget = { default: 1 };
5787 }
5788 // delete stale slots
5789 if (needDeletionCheck) {
5790 for (const key in slots) {
5791 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5792 delete slots[key];
5793 }
5794 }
5795 }
5796 };
5797
5798 function createAppContext() {
5799 return {
5800 app: null,
5801 config: {
5802 isNativeTag: NO,
5803 performance: false,
5804 globalProperties: {},
5805 optionMergeStrategies: {},
5806 errorHandler: undefined,
5807 warnHandler: undefined,
5808 compilerOptions: {}
5809 },
5810 mixins: [],
5811 components: {},
5812 directives: {},
5813 provides: Object.create(null),
5814 optionsCache: new WeakMap(),
5815 propsCache: new WeakMap(),
5816 emitsCache: new WeakMap()
5817 };
5818 }
5819 let uid = 0;
5820 function createAppAPI(render, hydrate) {
5821 return function createApp(rootComponent, rootProps = null) {
5822 if (!isFunction(rootComponent)) {
5823 rootComponent = Object.assign({}, rootComponent);
5824 }
5825 if (rootProps != null && !isObject(rootProps)) {
5826 warn$1(`root props passed to app.mount() must be an object.`);
5827 rootProps = null;
5828 }
5829 const context = createAppContext();
5830 const installedPlugins = new Set();
5831 let isMounted = false;
5832 const app = (context.app = {
5833 _uid: uid++,
5834 _component: rootComponent,
5835 _props: rootProps,
5836 _container: null,
5837 _context: context,
5838 _instance: null,
5839 version,
5840 get config() {
5841 return context.config;
5842 },
5843 set config(v) {
5844 {
5845 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
5846 }
5847 },
5848 use(plugin, ...options) {
5849 if (installedPlugins.has(plugin)) {
5850 warn$1(`Plugin has already been applied to target app.`);
5851 }
5852 else if (plugin && isFunction(plugin.install)) {
5853 installedPlugins.add(plugin);
5854 plugin.install(app, ...options);
5855 }
5856 else if (isFunction(plugin)) {
5857 installedPlugins.add(plugin);
5858 plugin(app, ...options);
5859 }
5860 else {
5861 warn$1(`A plugin must either be a function or an object with an "install" ` +
5862 `function.`);
5863 }
5864 return app;
5865 },
5866 mixin(mixin) {
5867 {
5868 if (!context.mixins.includes(mixin)) {
5869 context.mixins.push(mixin);
5870 }
5871 else {
5872 warn$1('Mixin has already been applied to target app' +
5873 (mixin.name ? `: ${mixin.name}` : ''));
5874 }
5875 }
5876 return app;
5877 },
5878 component(name, component) {
5879 {
5880 validateComponentName(name, context.config);
5881 }
5882 if (!component) {
5883 return context.components[name];
5884 }
5885 if (context.components[name]) {
5886 warn$1(`Component "${name}" has already been registered in target app.`);
5887 }
5888 context.components[name] = component;
5889 return app;
5890 },
5891 directive(name, directive) {
5892 {
5893 validateDirectiveName(name);
5894 }
5895 if (!directive) {
5896 return context.directives[name];
5897 }
5898 if (context.directives[name]) {
5899 warn$1(`Directive "${name}" has already been registered in target app.`);
5900 }
5901 context.directives[name] = directive;
5902 return app;
5903 },
5904 mount(rootContainer, isHydrate, isSVG) {
5905 if (!isMounted) {
5906 // #5571
5907 if (rootContainer.__vue_app__) {
5908 warn$1(`There is already an app instance mounted on the host container.\n` +
5909 ` If you want to mount another app on the same host container,` +
5910 ` you need to unmount the previous app by calling \`app.unmount()\` first.`);
5911 }
5912 const vnode = createVNode(rootComponent, rootProps);
5913 // store app context on the root VNode.
5914 // this will be set on the root instance on initial mount.
5915 vnode.appContext = context;
5916 // HMR root reload
5917 {
5918 context.reload = () => {
5919 render(cloneVNode(vnode), rootContainer, isSVG);
5920 };
5921 }
5922 if (isHydrate && hydrate) {
5923 hydrate(vnode, rootContainer);
5924 }
5925 else {
5926 render(vnode, rootContainer, isSVG);
5927 }
5928 isMounted = true;
5929 app._container = rootContainer;
5930 rootContainer.__vue_app__ = app;
5931 {
5932 app._instance = vnode.component;
5933 devtoolsInitApp(app, version);
5934 }
5935 return getExposeProxy(vnode.component) || vnode.component.proxy;
5936 }
5937 else {
5938 warn$1(`App has already been mounted.\n` +
5939 `If you want to remount the same app, move your app creation logic ` +
5940 `into a factory function and create fresh app instances for each ` +
5941 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5942 }
5943 },
5944 unmount() {
5945 if (isMounted) {
5946 render(null, app._container);
5947 {
5948 app._instance = null;
5949 devtoolsUnmountApp(app);
5950 }
5951 delete app._container.__vue_app__;
5952 }
5953 else {
5954 warn$1(`Cannot unmount an app that is not mounted.`);
5955 }
5956 },
5957 provide(key, value) {
5958 if (key in context.provides) {
5959 warn$1(`App already provides property with key "${String(key)}". ` +
5960 `It will be overwritten with the new value.`);
5961 }
5962 context.provides[key] = value;
5963 return app;
5964 }
5965 });
5966 return app;
5967 };
5968 }
5969
5970 /**
5971 * Function for handling a template ref
5972 */
5973 function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
5974 if (isArray(rawRef)) {
5975 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
5976 return;
5977 }
5978 if (isAsyncWrapper(vnode) && !isUnmount) {
5979 // when mounting async components, nothing needs to be done,
5980 // because the template ref is forwarded to inner component
5981 return;
5982 }
5983 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
5984 ? getExposeProxy(vnode.component) || vnode.component.proxy
5985 : vnode.el;
5986 const value = isUnmount ? null : refValue;
5987 const { i: owner, r: ref } = rawRef;
5988 if (!owner) {
5989 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
5990 `A vnode with ref must be created inside the render function.`);
5991 return;
5992 }
5993 const oldRef = oldRawRef && oldRawRef.r;
5994 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
5995 const setupState = owner.setupState;
5996 // dynamic ref changed. unset old ref
5997 if (oldRef != null && oldRef !== ref) {
5998 if (isString(oldRef)) {
5999 refs[oldRef] = null;
6000 if (hasOwn(setupState, oldRef)) {
6001 setupState[oldRef] = null;
6002 }
6003 }
6004 else if (isRef(oldRef)) {
6005 oldRef.value = null;
6006 }
6007 }
6008 if (isFunction(ref)) {
6009 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
6010 }
6011 else {
6012 const _isString = isString(ref);
6013 const _isRef = isRef(ref);
6014 if (_isString || _isRef) {
6015 const doSet = () => {
6016 if (rawRef.f) {
6017 const existing = _isString ? refs[ref] : ref.value;
6018 if (isUnmount) {
6019 isArray(existing) && remove(existing, refValue);
6020 }
6021 else {
6022 if (!isArray(existing)) {
6023 if (_isString) {
6024 refs[ref] = [refValue];
6025 if (hasOwn(setupState, ref)) {
6026 setupState[ref] = refs[ref];
6027 }
6028 }
6029 else {
6030 ref.value = [refValue];
6031 if (rawRef.k)
6032 refs[rawRef.k] = ref.value;
6033 }
6034 }
6035 else if (!existing.includes(refValue)) {
6036 existing.push(refValue);
6037 }
6038 }
6039 }
6040 else if (_isString) {
6041 refs[ref] = value;
6042 if (hasOwn(setupState, ref)) {
6043 setupState[ref] = value;
6044 }
6045 }
6046 else if (_isRef) {
6047 ref.value = value;
6048 if (rawRef.k)
6049 refs[rawRef.k] = value;
6050 }
6051 else {
6052 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
6053 }
6054 };
6055 if (value) {
6056 doSet.id = -1;
6057 queuePostRenderEffect(doSet, parentSuspense);
6058 }
6059 else {
6060 doSet();
6061 }
6062 }
6063 else {
6064 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
6065 }
6066 }
6067 }
6068
6069 let hasMismatch = false;
6070 const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
6071 const isComment = (node) => node.nodeType === 8 /* COMMENT */;
6072 // Note: hydration is DOM-specific
6073 // But we have to place it in core due to tight coupling with core - splitting
6074 // it out creates a ton of unnecessary complexity.
6075 // Hydration also depends on some renderer internal logic which needs to be
6076 // passed in via arguments.
6077 function createHydrationFunctions(rendererInternals) {
6078 const { mt: mountComponent, p: patch, o: { patchProp, createText, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
6079 const hydrate = (vnode, container) => {
6080 if (!container.hasChildNodes()) {
6081 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
6082 `Performing full mount instead.`);
6083 patch(null, vnode, container);
6084 flushPostFlushCbs();
6085 container._vnode = vnode;
6086 return;
6087 }
6088 hasMismatch = false;
6089 hydrateNode(container.firstChild, vnode, null, null, null);
6090 flushPostFlushCbs();
6091 container._vnode = vnode;
6092 if (hasMismatch && !false) {
6093 // this error should show up in production
6094 console.error(`Hydration completed but contains mismatches.`);
6095 }
6096 };
6097 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
6098 const isFragmentStart = isComment(node) && node.data === '[';
6099 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
6100 const { type, ref, shapeFlag, patchFlag } = vnode;
6101 const domType = node.nodeType;
6102 vnode.el = node;
6103 if (patchFlag === -2 /* BAIL */) {
6104 optimized = false;
6105 vnode.dynamicChildren = null;
6106 }
6107 let nextNode = null;
6108 switch (type) {
6109 case Text:
6110 if (domType !== 3 /* TEXT */) {
6111 // #5728 empty text node inside a slot can cause hydration failure
6112 // because the server rendered HTML won't contain a text node
6113 if (vnode.children === '') {
6114 insert((vnode.el = createText('')), parentNode(node), node);
6115 nextNode = node;
6116 }
6117 else {
6118 nextNode = onMismatch();
6119 }
6120 }
6121 else {
6122 if (node.data !== vnode.children) {
6123 hasMismatch = true;
6124 warn$1(`Hydration text mismatch:` +
6125 `\n- Client: ${JSON.stringify(node.data)}` +
6126 `\n- Server: ${JSON.stringify(vnode.children)}`);
6127 node.data = vnode.children;
6128 }
6129 nextNode = nextSibling(node);
6130 }
6131 break;
6132 case Comment:
6133 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
6134 nextNode = onMismatch();
6135 }
6136 else {
6137 nextNode = nextSibling(node);
6138 }
6139 break;
6140 case Static:
6141 if (domType !== 1 /* ELEMENT */ && domType !== 3 /* TEXT */) {
6142 nextNode = onMismatch();
6143 }
6144 else {
6145 // determine anchor, adopt content
6146 nextNode = node;
6147 // if the static vnode has its content stripped during build,
6148 // adopt it from the server-rendered HTML.
6149 const needToAdoptContent = !vnode.children.length;
6150 for (let i = 0; i < vnode.staticCount; i++) {
6151 if (needToAdoptContent)
6152 vnode.children +=
6153 nextNode.nodeType === 1 /* ELEMENT */
6154 ? nextNode.outerHTML
6155 : nextNode.data;
6156 if (i === vnode.staticCount - 1) {
6157 vnode.anchor = nextNode;
6158 }
6159 nextNode = nextSibling(nextNode);
6160 }
6161 return nextNode;
6162 }
6163 break;
6164 case Fragment:
6165 if (!isFragmentStart) {
6166 nextNode = onMismatch();
6167 }
6168 else {
6169 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
6170 }
6171 break;
6172 default:
6173 if (shapeFlag & 1 /* ELEMENT */) {
6174 if (domType !== 1 /* ELEMENT */ ||
6175 vnode.type.toLowerCase() !==
6176 node.tagName.toLowerCase()) {
6177 nextNode = onMismatch();
6178 }
6179 else {
6180 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
6181 }
6182 }
6183 else if (shapeFlag & 6 /* COMPONENT */) {
6184 // when setting up the render effect, if the initial vnode already
6185 // has .el set, the component will perform hydration instead of mount
6186 // on its sub-tree.
6187 vnode.slotScopeIds = slotScopeIds;
6188 const container = parentNode(node);
6189 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
6190 // component may be async, so in the case of fragments we cannot rely
6191 // on component's rendered output to determine the end of the fragment
6192 // instead, we do a lookahead to find the end anchor node.
6193 nextNode = isFragmentStart
6194 ? locateClosingAsyncAnchor(node)
6195 : nextSibling(node);
6196 // #4293 teleport as component root
6197 if (nextNode &&
6198 isComment(nextNode) &&
6199 nextNode.data === 'teleport end') {
6200 nextNode = nextSibling(nextNode);
6201 }
6202 // #3787
6203 // if component is async, it may get moved / unmounted before its
6204 // inner component is loaded, so we need to give it a placeholder
6205 // vnode that matches its adopted DOM.
6206 if (isAsyncWrapper(vnode)) {
6207 let subTree;
6208 if (isFragmentStart) {
6209 subTree = createVNode(Fragment);
6210 subTree.anchor = nextNode
6211 ? nextNode.previousSibling
6212 : container.lastChild;
6213 }
6214 else {
6215 subTree =
6216 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
6217 }
6218 subTree.el = node;
6219 vnode.component.subTree = subTree;
6220 }
6221 }
6222 else if (shapeFlag & 64 /* TELEPORT */) {
6223 if (domType !== 8 /* COMMENT */) {
6224 nextNode = onMismatch();
6225 }
6226 else {
6227 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
6228 }
6229 }
6230 else if (shapeFlag & 128 /* SUSPENSE */) {
6231 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
6232 }
6233 else {
6234 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
6235 }
6236 }
6237 if (ref != null) {
6238 setRef(ref, null, parentSuspense, vnode);
6239 }
6240 return nextNode;
6241 };
6242 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
6243 optimized = optimized || !!vnode.dynamicChildren;
6244 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
6245 // #4006 for form elements with non-string v-model value bindings
6246 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
6247 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
6248 // skip props & children if this is hoisted static nodes
6249 // #5405 in dev, always hydrate children for HMR
6250 {
6251 if (dirs) {
6252 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6253 }
6254 // props
6255 if (props) {
6256 if (forcePatchValue ||
6257 !optimized ||
6258 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
6259 for (const key in props) {
6260 if ((forcePatchValue && key.endsWith('value')) ||
6261 (isOn(key) && !isReservedProp(key))) {
6262 patchProp(el, key, null, props[key], false, undefined, parentComponent);
6263 }
6264 }
6265 }
6266 else if (props.onClick) {
6267 // Fast path for click listeners (which is most often) to avoid
6268 // iterating through props.
6269 patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
6270 }
6271 }
6272 // vnode / directive hooks
6273 let vnodeHooks;
6274 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
6275 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
6276 }
6277 if (dirs) {
6278 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6279 }
6280 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
6281 queueEffectWithSuspense(() => {
6282 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
6283 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6284 }, parentSuspense);
6285 }
6286 // children
6287 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
6288 // skip if element has innerHTML / textContent
6289 !(props && (props.innerHTML || props.textContent))) {
6290 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
6291 let hasWarned = false;
6292 while (next) {
6293 hasMismatch = true;
6294 if (!hasWarned) {
6295 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
6296 `server rendered element contains more child nodes than client vdom.`);
6297 hasWarned = true;
6298 }
6299 // The SSRed DOM contains more nodes than it should. Remove them.
6300 const cur = next;
6301 next = next.nextSibling;
6302 remove(cur);
6303 }
6304 }
6305 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6306 if (el.textContent !== vnode.children) {
6307 hasMismatch = true;
6308 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
6309 `- Client: ${el.textContent}\n` +
6310 `- Server: ${vnode.children}`);
6311 el.textContent = vnode.children;
6312 }
6313 }
6314 }
6315 return el.nextSibling;
6316 };
6317 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
6318 optimized = optimized || !!parentVNode.dynamicChildren;
6319 const children = parentVNode.children;
6320 const l = children.length;
6321 let hasWarned = false;
6322 for (let i = 0; i < l; i++) {
6323 const vnode = optimized
6324 ? children[i]
6325 : (children[i] = normalizeVNode(children[i]));
6326 if (node) {
6327 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
6328 }
6329 else if (vnode.type === Text && !vnode.children) {
6330 continue;
6331 }
6332 else {
6333 hasMismatch = true;
6334 if (!hasWarned) {
6335 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
6336 `server rendered element contains fewer child nodes than client vdom.`);
6337 hasWarned = true;
6338 }
6339 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
6340 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
6341 }
6342 }
6343 return node;
6344 };
6345 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
6346 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
6347 if (fragmentSlotScopeIds) {
6348 slotScopeIds = slotScopeIds
6349 ? slotScopeIds.concat(fragmentSlotScopeIds)
6350 : fragmentSlotScopeIds;
6351 }
6352 const container = parentNode(node);
6353 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
6354 if (next && isComment(next) && next.data === ']') {
6355 return nextSibling((vnode.anchor = next));
6356 }
6357 else {
6358 // fragment didn't hydrate successfully, since we didn't get a end anchor
6359 // back. This should have led to node/children mismatch warnings.
6360 hasMismatch = true;
6361 // since the anchor is missing, we need to create one and insert it
6362 insert((vnode.anchor = createComment(`]`)), container, next);
6363 return next;
6364 }
6365 };
6366 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
6367 hasMismatch = true;
6368 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
6369 ? `(text)`
6370 : isComment(node) && node.data === '['
6371 ? `(start of fragment)`
6372 : ``);
6373 vnode.el = null;
6374 if (isFragment) {
6375 // remove excessive fragment nodes
6376 const end = locateClosingAsyncAnchor(node);
6377 while (true) {
6378 const next = nextSibling(node);
6379 if (next && next !== end) {
6380 remove(next);
6381 }
6382 else {
6383 break;
6384 }
6385 }
6386 }
6387 const next = nextSibling(node);
6388 const container = parentNode(node);
6389 remove(node);
6390 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
6391 return next;
6392 };
6393 const locateClosingAsyncAnchor = (node) => {
6394 let match = 0;
6395 while (node) {
6396 node = nextSibling(node);
6397 if (node && isComment(node)) {
6398 if (node.data === '[')
6399 match++;
6400 if (node.data === ']') {
6401 if (match === 0) {
6402 return nextSibling(node);
6403 }
6404 else {
6405 match--;
6406 }
6407 }
6408 }
6409 }
6410 return node;
6411 };
6412 return [hydrate, hydrateNode];
6413 }
6414
6415 /* eslint-disable no-restricted-globals */
6416 let supported;
6417 let perf;
6418 function startMeasure(instance, type) {
6419 if (instance.appContext.config.performance && isSupported()) {
6420 perf.mark(`vue-${type}-${instance.uid}`);
6421 }
6422 {
6423 devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now());
6424 }
6425 }
6426 function endMeasure(instance, type) {
6427 if (instance.appContext.config.performance && isSupported()) {
6428 const startTag = `vue-${type}-${instance.uid}`;
6429 const endTag = startTag + `:end`;
6430 perf.mark(endTag);
6431 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
6432 perf.clearMarks(startTag);
6433 perf.clearMarks(endTag);
6434 }
6435 {
6436 devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now());
6437 }
6438 }
6439 function isSupported() {
6440 if (supported !== undefined) {
6441 return supported;
6442 }
6443 if (typeof window !== 'undefined' && window.performance) {
6444 supported = true;
6445 perf = window.performance;
6446 }
6447 else {
6448 supported = false;
6449 }
6450 return supported;
6451 }
6452
6453 const queuePostRenderEffect = queueEffectWithSuspense
6454 ;
6455 /**
6456 * The createRenderer function accepts two generic arguments:
6457 * HostNode and HostElement, corresponding to Node and Element types in the
6458 * host environment. For example, for runtime-dom, HostNode would be the DOM
6459 * `Node` interface and HostElement would be the DOM `Element` interface.
6460 *
6461 * Custom renderers can pass in the platform specific types like this:
6462 *
6463 * ``` js
6464 * const { render, createApp } = createRenderer<Node, Element>({
6465 * patchProp,
6466 * ...nodeOps
6467 * })
6468 * ```
6469 */
6470 function createRenderer(options) {
6471 return baseCreateRenderer(options);
6472 }
6473 // Separate API for creating hydration-enabled renderer.
6474 // Hydration logic is only used when calling this function, making it
6475 // tree-shakable.
6476 function createHydrationRenderer(options) {
6477 return baseCreateRenderer(options, createHydrationFunctions);
6478 }
6479 // implementation
6480 function baseCreateRenderer(options, createHydrationFns) {
6481 const target = getGlobalThis();
6482 target.__VUE__ = true;
6483 {
6484 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
6485 }
6486 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
6487 // Note: functions inside this closure should use `const xxx = () => {}`
6488 // style in order to prevent being inlined by minifiers.
6489 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
6490 if (n1 === n2) {
6491 return;
6492 }
6493 // patching & not same type, unmount old tree
6494 if (n1 && !isSameVNodeType(n1, n2)) {
6495 anchor = getNextHostNode(n1);
6496 unmount(n1, parentComponent, parentSuspense, true);
6497 n1 = null;
6498 }
6499 if (n2.patchFlag === -2 /* BAIL */) {
6500 optimized = false;
6501 n2.dynamicChildren = null;
6502 }
6503 const { type, ref, shapeFlag } = n2;
6504 switch (type) {
6505 case Text:
6506 processText(n1, n2, container, anchor);
6507 break;
6508 case Comment:
6509 processCommentNode(n1, n2, container, anchor);
6510 break;
6511 case Static:
6512 if (n1 == null) {
6513 mountStaticNode(n2, container, anchor, isSVG);
6514 }
6515 else {
6516 patchStaticNode(n1, n2, container, isSVG);
6517 }
6518 break;
6519 case Fragment:
6520 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6521 break;
6522 default:
6523 if (shapeFlag & 1 /* ELEMENT */) {
6524 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6525 }
6526 else if (shapeFlag & 6 /* COMPONENT */) {
6527 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6528 }
6529 else if (shapeFlag & 64 /* TELEPORT */) {
6530 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
6531 }
6532 else if (shapeFlag & 128 /* SUSPENSE */) {
6533 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
6534 }
6535 else {
6536 warn$1('Invalid VNode type:', type, `(${typeof type})`);
6537 }
6538 }
6539 // set ref
6540 if (ref != null && parentComponent) {
6541 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
6542 }
6543 };
6544 const processText = (n1, n2, container, anchor) => {
6545 if (n1 == null) {
6546 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
6547 }
6548 else {
6549 const el = (n2.el = n1.el);
6550 if (n2.children !== n1.children) {
6551 hostSetText(el, n2.children);
6552 }
6553 }
6554 };
6555 const processCommentNode = (n1, n2, container, anchor) => {
6556 if (n1 == null) {
6557 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
6558 }
6559 else {
6560 // there's no support for dynamic comments
6561 n2.el = n1.el;
6562 }
6563 };
6564 const mountStaticNode = (n2, container, anchor, isSVG) => {
6565 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
6566 };
6567 /**
6568 * Dev / HMR only
6569 */
6570 const patchStaticNode = (n1, n2, container, isSVG) => {
6571 // static nodes are only patched during dev for HMR
6572 if (n2.children !== n1.children) {
6573 const anchor = hostNextSibling(n1.anchor);
6574 // remove existing
6575 removeStaticNode(n1);
6576 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
6577 }
6578 else {
6579 n2.el = n1.el;
6580 n2.anchor = n1.anchor;
6581 }
6582 };
6583 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
6584 let next;
6585 while (el && el !== anchor) {
6586 next = hostNextSibling(el);
6587 hostInsert(el, container, nextSibling);
6588 el = next;
6589 }
6590 hostInsert(anchor, container, nextSibling);
6591 };
6592 const removeStaticNode = ({ el, anchor }) => {
6593 let next;
6594 while (el && el !== anchor) {
6595 next = hostNextSibling(el);
6596 hostRemove(el);
6597 el = next;
6598 }
6599 hostRemove(anchor);
6600 };
6601 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6602 isSVG = isSVG || n2.type === 'svg';
6603 if (n1 == null) {
6604 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6605 }
6606 else {
6607 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6608 }
6609 };
6610 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6611 let el;
6612 let vnodeHook;
6613 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
6614 {
6615 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
6616 // mount children first, since some props may rely on child content
6617 // being already rendered, e.g. `<select value>`
6618 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6619 hostSetElementText(el, vnode.children);
6620 }
6621 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6622 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
6623 }
6624 if (dirs) {
6625 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6626 }
6627 // props
6628 if (props) {
6629 for (const key in props) {
6630 if (key !== 'value' && !isReservedProp(key)) {
6631 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6632 }
6633 }
6634 /**
6635 * Special case for setting value on DOM elements:
6636 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
6637 * - it needs to be forced (#1471)
6638 * #2353 proposes adding another renderer option to configure this, but
6639 * the properties affects are so finite it is worth special casing it
6640 * here to reduce the complexity. (Special casing it also should not
6641 * affect non-DOM renderers)
6642 */
6643 if ('value' in props) {
6644 hostPatchProp(el, 'value', null, props.value);
6645 }
6646 if ((vnodeHook = props.onVnodeBeforeMount)) {
6647 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6648 }
6649 }
6650 // scopeId
6651 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
6652 }
6653 {
6654 Object.defineProperty(el, '__vnode', {
6655 value: vnode,
6656 enumerable: false
6657 });
6658 Object.defineProperty(el, '__vueParentComponent', {
6659 value: parentComponent,
6660 enumerable: false
6661 });
6662 }
6663 if (dirs) {
6664 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6665 }
6666 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
6667 // #1689 For inside suspense + suspense resolved case, just call it
6668 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
6669 transition &&
6670 !transition.persisted;
6671 if (needCallTransitionHooks) {
6672 transition.beforeEnter(el);
6673 }
6674 hostInsert(el, container, anchor);
6675 if ((vnodeHook = props && props.onVnodeMounted) ||
6676 needCallTransitionHooks ||
6677 dirs) {
6678 queuePostRenderEffect(() => {
6679 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6680 needCallTransitionHooks && transition.enter(el);
6681 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6682 }, parentSuspense);
6683 }
6684 };
6685 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6686 if (scopeId) {
6687 hostSetScopeId(el, scopeId);
6688 }
6689 if (slotScopeIds) {
6690 for (let i = 0; i < slotScopeIds.length; i++) {
6691 hostSetScopeId(el, slotScopeIds[i]);
6692 }
6693 }
6694 if (parentComponent) {
6695 let subTree = parentComponent.subTree;
6696 if (subTree.patchFlag > 0 &&
6697 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
6698 subTree =
6699 filterSingleRoot(subTree.children) || subTree;
6700 }
6701 if (vnode === subTree) {
6702 const parentVNode = parentComponent.vnode;
6703 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6704 }
6705 }
6706 };
6707 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6708 for (let i = start; i < children.length; i++) {
6709 const child = (children[i] = optimized
6710 ? cloneIfMounted(children[i])
6711 : normalizeVNode(children[i]));
6712 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6713 }
6714 };
6715 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6716 const el = (n2.el = n1.el);
6717 let { patchFlag, dynamicChildren, dirs } = n2;
6718 // #1426 take the old vnode's patch flag into account since user may clone a
6719 // compiler-generated vnode, which de-opts to FULL_PROPS
6720 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
6721 const oldProps = n1.props || EMPTY_OBJ;
6722 const newProps = n2.props || EMPTY_OBJ;
6723 let vnodeHook;
6724 // disable recurse in beforeUpdate hooks
6725 parentComponent && toggleRecurse(parentComponent, false);
6726 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6727 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6728 }
6729 if (dirs) {
6730 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6731 }
6732 parentComponent && toggleRecurse(parentComponent, true);
6733 if (isHmrUpdating) {
6734 // HMR updated, force full diff
6735 patchFlag = 0;
6736 optimized = false;
6737 dynamicChildren = null;
6738 }
6739 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6740 if (dynamicChildren) {
6741 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6742 if (parentComponent && parentComponent.type.__hmrId) {
6743 traverseStaticChildren(n1, n2);
6744 }
6745 }
6746 else if (!optimized) {
6747 // full diff
6748 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6749 }
6750 if (patchFlag > 0) {
6751 // the presence of a patchFlag means this element's render code was
6752 // generated by the compiler and can take the fast path.
6753 // in this path old node and new node are guaranteed to have the same shape
6754 // (i.e. at the exact same position in the source template)
6755 if (patchFlag & 16 /* FULL_PROPS */) {
6756 // element props contain dynamic keys, full diff needed
6757 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6758 }
6759 else {
6760 // class
6761 // this flag is matched when the element has dynamic class bindings.
6762 if (patchFlag & 2 /* CLASS */) {
6763 if (oldProps.class !== newProps.class) {
6764 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6765 }
6766 }
6767 // style
6768 // this flag is matched when the element has dynamic style bindings
6769 if (patchFlag & 4 /* STYLE */) {
6770 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6771 }
6772 // props
6773 // This flag is matched when the element has dynamic prop/attr bindings
6774 // other than class and style. The keys of dynamic prop/attrs are saved for
6775 // faster iteration.
6776 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6777 // bail out and go through a full diff because we need to unset the old key
6778 if (patchFlag & 8 /* PROPS */) {
6779 // if the flag is present then dynamicProps must be non-null
6780 const propsToUpdate = n2.dynamicProps;
6781 for (let i = 0; i < propsToUpdate.length; i++) {
6782 const key = propsToUpdate[i];
6783 const prev = oldProps[key];
6784 const next = newProps[key];
6785 // #1471 force patch value
6786 if (next !== prev || key === 'value') {
6787 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6788 }
6789 }
6790 }
6791 }
6792 // text
6793 // This flag is matched when the element has only dynamic text children.
6794 if (patchFlag & 1 /* TEXT */) {
6795 if (n1.children !== n2.children) {
6796 hostSetElementText(el, n2.children);
6797 }
6798 }
6799 }
6800 else if (!optimized && dynamicChildren == null) {
6801 // unoptimized, full diff
6802 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6803 }
6804 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6805 queuePostRenderEffect(() => {
6806 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6807 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6808 }, parentSuspense);
6809 }
6810 };
6811 // The fast path for blocks.
6812 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6813 for (let i = 0; i < newChildren.length; i++) {
6814 const oldVNode = oldChildren[i];
6815 const newVNode = newChildren[i];
6816 // Determine the container (parent element) for the patch.
6817 const container =
6818 // oldVNode may be an errored async setup() component inside Suspense
6819 // which will not have a mounted element
6820 oldVNode.el &&
6821 // - In the case of a Fragment, we need to provide the actual parent
6822 // of the Fragment itself so it can move its children.
6823 (oldVNode.type === Fragment ||
6824 // - In the case of different nodes, there is going to be a replacement
6825 // which also requires the correct parent container
6826 !isSameVNodeType(oldVNode, newVNode) ||
6827 // - In the case of a component, it could contain anything.
6828 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
6829 ? hostParentNode(oldVNode.el)
6830 : // In other cases, the parent container is not actually used so we
6831 // just pass the block element here to avoid a DOM parentNode call.
6832 fallbackContainer;
6833 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6834 }
6835 };
6836 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6837 if (oldProps !== newProps) {
6838 for (const key in newProps) {
6839 // empty string is not valid prop
6840 if (isReservedProp(key))
6841 continue;
6842 const next = newProps[key];
6843 const prev = oldProps[key];
6844 // defer patching value
6845 if (next !== prev && key !== 'value') {
6846 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6847 }
6848 }
6849 if (oldProps !== EMPTY_OBJ) {
6850 for (const key in oldProps) {
6851 if (!isReservedProp(key) && !(key in newProps)) {
6852 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6853 }
6854 }
6855 }
6856 if ('value' in newProps) {
6857 hostPatchProp(el, 'value', oldProps.value, newProps.value);
6858 }
6859 }
6860 };
6861 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6862 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6863 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6864 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6865 if (// #5523 dev root fragment may inherit directives
6866 (isHmrUpdating || patchFlag & 2048 /* DEV_ROOT_FRAGMENT */)) {
6867 // HMR updated / Dev root fragment (w/ comments), force full diff
6868 patchFlag = 0;
6869 optimized = false;
6870 dynamicChildren = null;
6871 }
6872 // check if this is a slot fragment with :slotted scope ids
6873 if (fragmentSlotScopeIds) {
6874 slotScopeIds = slotScopeIds
6875 ? slotScopeIds.concat(fragmentSlotScopeIds)
6876 : fragmentSlotScopeIds;
6877 }
6878 if (n1 == null) {
6879 hostInsert(fragmentStartAnchor, container, anchor);
6880 hostInsert(fragmentEndAnchor, container, anchor);
6881 // a fragment can only have array children
6882 // since they are either generated by the compiler, or implicitly created
6883 // from arrays.
6884 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6885 }
6886 else {
6887 if (patchFlag > 0 &&
6888 patchFlag & 64 /* STABLE_FRAGMENT */ &&
6889 dynamicChildren &&
6890 // #2715 the previous fragment could've been a BAILed one as a result
6891 // of renderSlot() with no valid children
6892 n1.dynamicChildren) {
6893 // a stable fragment (template root or <template v-for>) doesn't need to
6894 // patch children order, but it may contain dynamicChildren.
6895 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6896 if (parentComponent && parentComponent.type.__hmrId) {
6897 traverseStaticChildren(n1, n2);
6898 }
6899 else if (
6900 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6901 // get moved around. Make sure all root level vnodes inherit el.
6902 // #2134 or if it's a component root, it may also get moved around
6903 // as the component is being moved.
6904 n2.key != null ||
6905 (parentComponent && n2 === parentComponent.subTree)) {
6906 traverseStaticChildren(n1, n2, true /* shallow */);
6907 }
6908 }
6909 else {
6910 // keyed / unkeyed, or manual fragments.
6911 // for keyed & unkeyed, since they are compiler generated from v-for,
6912 // each child is guaranteed to be a block so the fragment will never
6913 // have dynamicChildren.
6914 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6915 }
6916 }
6917 };
6918 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6919 n2.slotScopeIds = slotScopeIds;
6920 if (n1 == null) {
6921 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
6922 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6923 }
6924 else {
6925 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6926 }
6927 }
6928 else {
6929 updateComponent(n1, n2, optimized);
6930 }
6931 };
6932 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6933 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6934 if (instance.type.__hmrId) {
6935 registerHMR(instance);
6936 }
6937 {
6938 pushWarningContext(initialVNode);
6939 startMeasure(instance, `mount`);
6940 }
6941 // inject renderer internals for keepAlive
6942 if (isKeepAlive(initialVNode)) {
6943 instance.ctx.renderer = internals;
6944 }
6945 // resolve props and slots for setup context
6946 {
6947 {
6948 startMeasure(instance, `init`);
6949 }
6950 setupComponent(instance);
6951 {
6952 endMeasure(instance, `init`);
6953 }
6954 }
6955 // setup() is async. This component relies on async logic to be resolved
6956 // before proceeding
6957 if (instance.asyncDep) {
6958 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
6959 // Give it a placeholder if this is not hydration
6960 // TODO handle self-defined fallback
6961 if (!initialVNode.el) {
6962 const placeholder = (instance.subTree = createVNode(Comment));
6963 processCommentNode(null, placeholder, container, anchor);
6964 }
6965 return;
6966 }
6967 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
6968 {
6969 popWarningContext();
6970 endMeasure(instance, `mount`);
6971 }
6972 };
6973 const updateComponent = (n1, n2, optimized) => {
6974 const instance = (n2.component = n1.component);
6975 if (shouldUpdateComponent(n1, n2, optimized)) {
6976 if (instance.asyncDep &&
6977 !instance.asyncResolved) {
6978 // async & still pending - just update props and slots
6979 // since the component's reactive effect for render isn't set-up yet
6980 {
6981 pushWarningContext(n2);
6982 }
6983 updateComponentPreRender(instance, n2, optimized);
6984 {
6985 popWarningContext();
6986 }
6987 return;
6988 }
6989 else {
6990 // normal update
6991 instance.next = n2;
6992 // in case the child component is also queued, remove it to avoid
6993 // double updating the same child component in the same flush.
6994 invalidateJob(instance.update);
6995 // instance.update is the reactive effect.
6996 instance.update();
6997 }
6998 }
6999 else {
7000 // no update needed. just copy over properties
7001 n2.el = n1.el;
7002 instance.vnode = n2;
7003 }
7004 };
7005 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
7006 const componentUpdateFn = () => {
7007 if (!instance.isMounted) {
7008 let vnodeHook;
7009 const { el, props } = initialVNode;
7010 const { bm, m, parent } = instance;
7011 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
7012 toggleRecurse(instance, false);
7013 // beforeMount hook
7014 if (bm) {
7015 invokeArrayFns(bm);
7016 }
7017 // onVnodeBeforeMount
7018 if (!isAsyncWrapperVNode &&
7019 (vnodeHook = props && props.onVnodeBeforeMount)) {
7020 invokeVNodeHook(vnodeHook, parent, initialVNode);
7021 }
7022 toggleRecurse(instance, true);
7023 if (el && hydrateNode) {
7024 // vnode has adopted host node - perform hydration instead of mount.
7025 const hydrateSubTree = () => {
7026 {
7027 startMeasure(instance, `render`);
7028 }
7029 instance.subTree = renderComponentRoot(instance);
7030 {
7031 endMeasure(instance, `render`);
7032 }
7033 {
7034 startMeasure(instance, `hydrate`);
7035 }
7036 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
7037 {
7038 endMeasure(instance, `hydrate`);
7039 }
7040 };
7041 if (isAsyncWrapperVNode) {
7042 initialVNode.type.__asyncLoader().then(
7043 // note: we are moving the render call into an async callback,
7044 // which means it won't track dependencies - but it's ok because
7045 // a server-rendered async wrapper is already in resolved state
7046 // and it will never need to change.
7047 () => !instance.isUnmounted && hydrateSubTree());
7048 }
7049 else {
7050 hydrateSubTree();
7051 }
7052 }
7053 else {
7054 {
7055 startMeasure(instance, `render`);
7056 }
7057 const subTree = (instance.subTree = renderComponentRoot(instance));
7058 {
7059 endMeasure(instance, `render`);
7060 }
7061 {
7062 startMeasure(instance, `patch`);
7063 }
7064 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
7065 {
7066 endMeasure(instance, `patch`);
7067 }
7068 initialVNode.el = subTree.el;
7069 }
7070 // mounted hook
7071 if (m) {
7072 queuePostRenderEffect(m, parentSuspense);
7073 }
7074 // onVnodeMounted
7075 if (!isAsyncWrapperVNode &&
7076 (vnodeHook = props && props.onVnodeMounted)) {
7077 const scopedInitialVNode = initialVNode;
7078 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
7079 }
7080 // activated hook for keep-alive roots.
7081 // #1742 activated hook must be accessed after first render
7082 // since the hook may be injected by a child keep-alive
7083 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */ ||
7084 (parent &&
7085 isAsyncWrapper(parent.vnode) &&
7086 parent.vnode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */)) {
7087 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
7088 }
7089 instance.isMounted = true;
7090 {
7091 devtoolsComponentAdded(instance);
7092 }
7093 // #2458: deference mount-only object parameters to prevent memleaks
7094 initialVNode = container = anchor = null;
7095 }
7096 else {
7097 // updateComponent
7098 // This is triggered by mutation of component's own state (next: null)
7099 // OR parent calling processComponent (next: VNode)
7100 let { next, bu, u, parent, vnode } = instance;
7101 let originNext = next;
7102 let vnodeHook;
7103 {
7104 pushWarningContext(next || instance.vnode);
7105 }
7106 // Disallow component effect recursion during pre-lifecycle hooks.
7107 toggleRecurse(instance, false);
7108 if (next) {
7109 next.el = vnode.el;
7110 updateComponentPreRender(instance, next, optimized);
7111 }
7112 else {
7113 next = vnode;
7114 }
7115 // beforeUpdate hook
7116 if (bu) {
7117 invokeArrayFns(bu);
7118 }
7119 // onVnodeBeforeUpdate
7120 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
7121 invokeVNodeHook(vnodeHook, parent, next, vnode);
7122 }
7123 toggleRecurse(instance, true);
7124 // render
7125 {
7126 startMeasure(instance, `render`);
7127 }
7128 const nextTree = renderComponentRoot(instance);
7129 {
7130 endMeasure(instance, `render`);
7131 }
7132 const prevTree = instance.subTree;
7133 instance.subTree = nextTree;
7134 {
7135 startMeasure(instance, `patch`);
7136 }
7137 patch(prevTree, nextTree,
7138 // parent may have changed if it's in a teleport
7139 hostParentNode(prevTree.el),
7140 // anchor may have changed if it's in a fragment
7141 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
7142 {
7143 endMeasure(instance, `patch`);
7144 }
7145 next.el = nextTree.el;
7146 if (originNext === null) {
7147 // self-triggered update. In case of HOC, update parent component
7148 // vnode el. HOC is indicated by parent instance's subTree pointing
7149 // to child component's vnode
7150 updateHOCHostEl(instance, nextTree.el);
7151 }
7152 // updated hook
7153 if (u) {
7154 queuePostRenderEffect(u, parentSuspense);
7155 }
7156 // onVnodeUpdated
7157 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
7158 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
7159 }
7160 {
7161 devtoolsComponentUpdated(instance);
7162 }
7163 {
7164 popWarningContext();
7165 }
7166 }
7167 };
7168 // create reactive effect for rendering
7169 const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(update), instance.scope // track it in component's effect scope
7170 ));
7171 const update = (instance.update = () => effect.run());
7172 update.id = instance.uid;
7173 // allowRecurse
7174 // #1801, #2043 component render effects should allow recursive updates
7175 toggleRecurse(instance, true);
7176 {
7177 effect.onTrack = instance.rtc
7178 ? e => invokeArrayFns(instance.rtc, e)
7179 : void 0;
7180 effect.onTrigger = instance.rtg
7181 ? e => invokeArrayFns(instance.rtg, e)
7182 : void 0;
7183 update.ownerInstance = instance;
7184 }
7185 update();
7186 };
7187 const updateComponentPreRender = (instance, nextVNode, optimized) => {
7188 nextVNode.component = instance;
7189 const prevProps = instance.vnode.props;
7190 instance.vnode = nextVNode;
7191 instance.next = null;
7192 updateProps(instance, nextVNode.props, prevProps, optimized);
7193 updateSlots(instance, nextVNode.children, optimized);
7194 pauseTracking();
7195 // props update may have triggered pre-flush watchers.
7196 // flush them before the render update.
7197 flushPreFlushCbs(undefined, instance.update);
7198 resetTracking();
7199 };
7200 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
7201 const c1 = n1 && n1.children;
7202 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
7203 const c2 = n2.children;
7204 const { patchFlag, shapeFlag } = n2;
7205 // fast path
7206 if (patchFlag > 0) {
7207 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
7208 // this could be either fully-keyed or mixed (some keyed some not)
7209 // presence of patchFlag means children are guaranteed to be arrays
7210 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7211 return;
7212 }
7213 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
7214 // unkeyed
7215 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7216 return;
7217 }
7218 }
7219 // children has 3 possibilities: text, array or no children.
7220 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
7221 // text children fast path
7222 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
7223 unmountChildren(c1, parentComponent, parentSuspense);
7224 }
7225 if (c2 !== c1) {
7226 hostSetElementText(container, c2);
7227 }
7228 }
7229 else {
7230 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
7231 // prev children was array
7232 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7233 // two arrays, cannot assume anything, do full diff
7234 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7235 }
7236 else {
7237 // no new children, just unmount old
7238 unmountChildren(c1, parentComponent, parentSuspense, true);
7239 }
7240 }
7241 else {
7242 // prev children was text OR null
7243 // new children is array OR null
7244 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
7245 hostSetElementText(container, '');
7246 }
7247 // mount new if array
7248 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7249 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7250 }
7251 }
7252 }
7253 };
7254 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
7255 c1 = c1 || EMPTY_ARR;
7256 c2 = c2 || EMPTY_ARR;
7257 const oldLength = c1.length;
7258 const newLength = c2.length;
7259 const commonLength = Math.min(oldLength, newLength);
7260 let i;
7261 for (i = 0; i < commonLength; i++) {
7262 const nextChild = (c2[i] = optimized
7263 ? cloneIfMounted(c2[i])
7264 : normalizeVNode(c2[i]));
7265 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7266 }
7267 if (oldLength > newLength) {
7268 // remove old
7269 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
7270 }
7271 else {
7272 // mount new
7273 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
7274 }
7275 };
7276 // can be all-keyed or mixed
7277 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
7278 let i = 0;
7279 const l2 = c2.length;
7280 let e1 = c1.length - 1; // prev ending index
7281 let e2 = l2 - 1; // next ending index
7282 // 1. sync from start
7283 // (a b) c
7284 // (a b) d e
7285 while (i <= e1 && i <= e2) {
7286 const n1 = c1[i];
7287 const n2 = (c2[i] = optimized
7288 ? cloneIfMounted(c2[i])
7289 : normalizeVNode(c2[i]));
7290 if (isSameVNodeType(n1, n2)) {
7291 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7292 }
7293 else {
7294 break;
7295 }
7296 i++;
7297 }
7298 // 2. sync from end
7299 // a (b c)
7300 // d e (b c)
7301 while (i <= e1 && i <= e2) {
7302 const n1 = c1[e1];
7303 const n2 = (c2[e2] = optimized
7304 ? cloneIfMounted(c2[e2])
7305 : normalizeVNode(c2[e2]));
7306 if (isSameVNodeType(n1, n2)) {
7307 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7308 }
7309 else {
7310 break;
7311 }
7312 e1--;
7313 e2--;
7314 }
7315 // 3. common sequence + mount
7316 // (a b)
7317 // (a b) c
7318 // i = 2, e1 = 1, e2 = 2
7319 // (a b)
7320 // c (a b)
7321 // i = 0, e1 = -1, e2 = 0
7322 if (i > e1) {
7323 if (i <= e2) {
7324 const nextPos = e2 + 1;
7325 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
7326 while (i <= e2) {
7327 patch(null, (c2[i] = optimized
7328 ? cloneIfMounted(c2[i])
7329 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7330 i++;
7331 }
7332 }
7333 }
7334 // 4. common sequence + unmount
7335 // (a b) c
7336 // (a b)
7337 // i = 2, e1 = 2, e2 = 1
7338 // a (b c)
7339 // (b c)
7340 // i = 0, e1 = 0, e2 = -1
7341 else if (i > e2) {
7342 while (i <= e1) {
7343 unmount(c1[i], parentComponent, parentSuspense, true);
7344 i++;
7345 }
7346 }
7347 // 5. unknown sequence
7348 // [i ... e1 + 1]: a b [c d e] f g
7349 // [i ... e2 + 1]: a b [e d c h] f g
7350 // i = 2, e1 = 4, e2 = 5
7351 else {
7352 const s1 = i; // prev starting index
7353 const s2 = i; // next starting index
7354 // 5.1 build key:index map for newChildren
7355 const keyToNewIndexMap = new Map();
7356 for (i = s2; i <= e2; i++) {
7357 const nextChild = (c2[i] = optimized
7358 ? cloneIfMounted(c2[i])
7359 : normalizeVNode(c2[i]));
7360 if (nextChild.key != null) {
7361 if (keyToNewIndexMap.has(nextChild.key)) {
7362 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
7363 }
7364 keyToNewIndexMap.set(nextChild.key, i);
7365 }
7366 }
7367 // 5.2 loop through old children left to be patched and try to patch
7368 // matching nodes & remove nodes that are no longer present
7369 let j;
7370 let patched = 0;
7371 const toBePatched = e2 - s2 + 1;
7372 let moved = false;
7373 // used to track whether any node has moved
7374 let maxNewIndexSoFar = 0;
7375 // works as Map<newIndex, oldIndex>
7376 // Note that oldIndex is offset by +1
7377 // and oldIndex = 0 is a special value indicating the new node has
7378 // no corresponding old node.
7379 // used for determining longest stable subsequence
7380 const newIndexToOldIndexMap = new Array(toBePatched);
7381 for (i = 0; i < toBePatched; i++)
7382 newIndexToOldIndexMap[i] = 0;
7383 for (i = s1; i <= e1; i++) {
7384 const prevChild = c1[i];
7385 if (patched >= toBePatched) {
7386 // all new children have been patched so this can only be a removal
7387 unmount(prevChild, parentComponent, parentSuspense, true);
7388 continue;
7389 }
7390 let newIndex;
7391 if (prevChild.key != null) {
7392 newIndex = keyToNewIndexMap.get(prevChild.key);
7393 }
7394 else {
7395 // key-less node, try to locate a key-less node of the same type
7396 for (j = s2; j <= e2; j++) {
7397 if (newIndexToOldIndexMap[j - s2] === 0 &&
7398 isSameVNodeType(prevChild, c2[j])) {
7399 newIndex = j;
7400 break;
7401 }
7402 }
7403 }
7404 if (newIndex === undefined) {
7405 unmount(prevChild, parentComponent, parentSuspense, true);
7406 }
7407 else {
7408 newIndexToOldIndexMap[newIndex - s2] = i + 1;
7409 if (newIndex >= maxNewIndexSoFar) {
7410 maxNewIndexSoFar = newIndex;
7411 }
7412 else {
7413 moved = true;
7414 }
7415 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7416 patched++;
7417 }
7418 }
7419 // 5.3 move and mount
7420 // generate longest stable subsequence only when nodes have moved
7421 const increasingNewIndexSequence = moved
7422 ? getSequence(newIndexToOldIndexMap)
7423 : EMPTY_ARR;
7424 j = increasingNewIndexSequence.length - 1;
7425 // looping backwards so that we can use last patched node as anchor
7426 for (i = toBePatched - 1; i >= 0; i--) {
7427 const nextIndex = s2 + i;
7428 const nextChild = c2[nextIndex];
7429 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
7430 if (newIndexToOldIndexMap[i] === 0) {
7431 // mount new
7432 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7433 }
7434 else if (moved) {
7435 // move if:
7436 // There is no stable subsequence (e.g. a reverse)
7437 // OR current node is not among the stable sequence
7438 if (j < 0 || i !== increasingNewIndexSequence[j]) {
7439 move(nextChild, container, anchor, 2 /* REORDER */);
7440 }
7441 else {
7442 j--;
7443 }
7444 }
7445 }
7446 }
7447 };
7448 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
7449 const { el, type, transition, children, shapeFlag } = vnode;
7450 if (shapeFlag & 6 /* COMPONENT */) {
7451 move(vnode.component.subTree, container, anchor, moveType);
7452 return;
7453 }
7454 if (shapeFlag & 128 /* SUSPENSE */) {
7455 vnode.suspense.move(container, anchor, moveType);
7456 return;
7457 }
7458 if (shapeFlag & 64 /* TELEPORT */) {
7459 type.move(vnode, container, anchor, internals);
7460 return;
7461 }
7462 if (type === Fragment) {
7463 hostInsert(el, container, anchor);
7464 for (let i = 0; i < children.length; i++) {
7465 move(children[i], container, anchor, moveType);
7466 }
7467 hostInsert(vnode.anchor, container, anchor);
7468 return;
7469 }
7470 if (type === Static) {
7471 moveStaticNode(vnode, container, anchor);
7472 return;
7473 }
7474 // single nodes
7475 const needTransition = moveType !== 2 /* REORDER */ &&
7476 shapeFlag & 1 /* ELEMENT */ &&
7477 transition;
7478 if (needTransition) {
7479 if (moveType === 0 /* ENTER */) {
7480 transition.beforeEnter(el);
7481 hostInsert(el, container, anchor);
7482 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
7483 }
7484 else {
7485 const { leave, delayLeave, afterLeave } = transition;
7486 const remove = () => hostInsert(el, container, anchor);
7487 const performLeave = () => {
7488 leave(el, () => {
7489 remove();
7490 afterLeave && afterLeave();
7491 });
7492 };
7493 if (delayLeave) {
7494 delayLeave(el, remove, performLeave);
7495 }
7496 else {
7497 performLeave();
7498 }
7499 }
7500 }
7501 else {
7502 hostInsert(el, container, anchor);
7503 }
7504 };
7505 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
7506 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
7507 // unset ref
7508 if (ref != null) {
7509 setRef(ref, null, parentSuspense, vnode, true);
7510 }
7511 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
7512 parentComponent.ctx.deactivate(vnode);
7513 return;
7514 }
7515 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
7516 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
7517 let vnodeHook;
7518 if (shouldInvokeVnodeHook &&
7519 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
7520 invokeVNodeHook(vnodeHook, parentComponent, vnode);
7521 }
7522 if (shapeFlag & 6 /* COMPONENT */) {
7523 unmountComponent(vnode.component, parentSuspense, doRemove);
7524 }
7525 else {
7526 if (shapeFlag & 128 /* SUSPENSE */) {
7527 vnode.suspense.unmount(parentSuspense, doRemove);
7528 return;
7529 }
7530 if (shouldInvokeDirs) {
7531 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
7532 }
7533 if (shapeFlag & 64 /* TELEPORT */) {
7534 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
7535 }
7536 else if (dynamicChildren &&
7537 // #1153: fast path should not be taken for non-stable (v-for) fragments
7538 (type !== Fragment ||
7539 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
7540 // fast path for block nodes: only need to unmount dynamic children.
7541 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
7542 }
7543 else if ((type === Fragment &&
7544 patchFlag &
7545 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
7546 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
7547 unmountChildren(children, parentComponent, parentSuspense);
7548 }
7549 if (doRemove) {
7550 remove(vnode);
7551 }
7552 }
7553 if ((shouldInvokeVnodeHook &&
7554 (vnodeHook = props && props.onVnodeUnmounted)) ||
7555 shouldInvokeDirs) {
7556 queuePostRenderEffect(() => {
7557 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
7558 shouldInvokeDirs &&
7559 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
7560 }, parentSuspense);
7561 }
7562 };
7563 const remove = vnode => {
7564 const { type, el, anchor, transition } = vnode;
7565 if (type === Fragment) {
7566 if (vnode.patchFlag > 0 &&
7567 vnode.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */ &&
7568 transition &&
7569 !transition.persisted) {
7570 vnode.children.forEach(child => {
7571 if (child.type === Comment) {
7572 hostRemove(child.el);
7573 }
7574 else {
7575 remove(child);
7576 }
7577 });
7578 }
7579 else {
7580 removeFragment(el, anchor);
7581 }
7582 return;
7583 }
7584 if (type === Static) {
7585 removeStaticNode(vnode);
7586 return;
7587 }
7588 const performRemove = () => {
7589 hostRemove(el);
7590 if (transition && !transition.persisted && transition.afterLeave) {
7591 transition.afterLeave();
7592 }
7593 };
7594 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
7595 transition &&
7596 !transition.persisted) {
7597 const { leave, delayLeave } = transition;
7598 const performLeave = () => leave(el, performRemove);
7599 if (delayLeave) {
7600 delayLeave(vnode.el, performRemove, performLeave);
7601 }
7602 else {
7603 performLeave();
7604 }
7605 }
7606 else {
7607 performRemove();
7608 }
7609 };
7610 const removeFragment = (cur, end) => {
7611 // For fragments, directly remove all contained DOM nodes.
7612 // (fragment child nodes cannot have transition)
7613 let next;
7614 while (cur !== end) {
7615 next = hostNextSibling(cur);
7616 hostRemove(cur);
7617 cur = next;
7618 }
7619 hostRemove(end);
7620 };
7621 const unmountComponent = (instance, parentSuspense, doRemove) => {
7622 if (instance.type.__hmrId) {
7623 unregisterHMR(instance);
7624 }
7625 const { bum, scope, update, subTree, um } = instance;
7626 // beforeUnmount hook
7627 if (bum) {
7628 invokeArrayFns(bum);
7629 }
7630 // stop effects in component scope
7631 scope.stop();
7632 // update may be null if a component is unmounted before its async
7633 // setup has resolved.
7634 if (update) {
7635 // so that scheduler will no longer invoke it
7636 update.active = false;
7637 unmount(subTree, instance, parentSuspense, doRemove);
7638 }
7639 // unmounted hook
7640 if (um) {
7641 queuePostRenderEffect(um, parentSuspense);
7642 }
7643 queuePostRenderEffect(() => {
7644 instance.isUnmounted = true;
7645 }, parentSuspense);
7646 // A component with async dep inside a pending suspense is unmounted before
7647 // its async dep resolves. This should remove the dep from the suspense, and
7648 // cause the suspense to resolve immediately if that was the last dep.
7649 if (parentSuspense &&
7650 parentSuspense.pendingBranch &&
7651 !parentSuspense.isUnmounted &&
7652 instance.asyncDep &&
7653 !instance.asyncResolved &&
7654 instance.suspenseId === parentSuspense.pendingId) {
7655 parentSuspense.deps--;
7656 if (parentSuspense.deps === 0) {
7657 parentSuspense.resolve();
7658 }
7659 }
7660 {
7661 devtoolsComponentRemoved(instance);
7662 }
7663 };
7664 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
7665 for (let i = start; i < children.length; i++) {
7666 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
7667 }
7668 };
7669 const getNextHostNode = vnode => {
7670 if (vnode.shapeFlag & 6 /* COMPONENT */) {
7671 return getNextHostNode(vnode.component.subTree);
7672 }
7673 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
7674 return vnode.suspense.next();
7675 }
7676 return hostNextSibling((vnode.anchor || vnode.el));
7677 };
7678 const render = (vnode, container, isSVG) => {
7679 if (vnode == null) {
7680 if (container._vnode) {
7681 unmount(container._vnode, null, null, true);
7682 }
7683 }
7684 else {
7685 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
7686 }
7687 flushPostFlushCbs();
7688 container._vnode = vnode;
7689 };
7690 const internals = {
7691 p: patch,
7692 um: unmount,
7693 m: move,
7694 r: remove,
7695 mt: mountComponent,
7696 mc: mountChildren,
7697 pc: patchChildren,
7698 pbc: patchBlockChildren,
7699 n: getNextHostNode,
7700 o: options
7701 };
7702 let hydrate;
7703 let hydrateNode;
7704 if (createHydrationFns) {
7705 [hydrate, hydrateNode] = createHydrationFns(internals);
7706 }
7707 return {
7708 render,
7709 hydrate,
7710 createApp: createAppAPI(render, hydrate)
7711 };
7712 }
7713 function toggleRecurse({ effect, update }, allowed) {
7714 effect.allowRecurse = update.allowRecurse = allowed;
7715 }
7716 /**
7717 * #1156
7718 * When a component is HMR-enabled, we need to make sure that all static nodes
7719 * inside a block also inherit the DOM element from the previous tree so that
7720 * HMR updates (which are full updates) can retrieve the element for patching.
7721 *
7722 * #2080
7723 * Inside keyed `template` fragment static children, if a fragment is moved,
7724 * the children will always be moved. Therefore, in order to ensure correct move
7725 * position, el should be inherited from previous nodes.
7726 */
7727 function traverseStaticChildren(n1, n2, shallow = false) {
7728 const ch1 = n1.children;
7729 const ch2 = n2.children;
7730 if (isArray(ch1) && isArray(ch2)) {
7731 for (let i = 0; i < ch1.length; i++) {
7732 // this is only called in the optimized path so array children are
7733 // guaranteed to be vnodes
7734 const c1 = ch1[i];
7735 let c2 = ch2[i];
7736 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
7737 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
7738 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7739 c2.el = c1.el;
7740 }
7741 if (!shallow)
7742 traverseStaticChildren(c1, c2);
7743 }
7744 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7745 // would have received .el during block patch)
7746 if (c2.type === Comment && !c2.el) {
7747 c2.el = c1.el;
7748 }
7749 }
7750 }
7751 }
7752 // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7753 function getSequence(arr) {
7754 const p = arr.slice();
7755 const result = [0];
7756 let i, j, u, v, c;
7757 const len = arr.length;
7758 for (i = 0; i < len; i++) {
7759 const arrI = arr[i];
7760 if (arrI !== 0) {
7761 j = result[result.length - 1];
7762 if (arr[j] < arrI) {
7763 p[i] = j;
7764 result.push(i);
7765 continue;
7766 }
7767 u = 0;
7768 v = result.length - 1;
7769 while (u < v) {
7770 c = (u + v) >> 1;
7771 if (arr[result[c]] < arrI) {
7772 u = c + 1;
7773 }
7774 else {
7775 v = c;
7776 }
7777 }
7778 if (arrI < arr[result[u]]) {
7779 if (u > 0) {
7780 p[i] = result[u - 1];
7781 }
7782 result[u] = i;
7783 }
7784 }
7785 }
7786 u = result.length;
7787 v = result[u - 1];
7788 while (u-- > 0) {
7789 result[u] = v;
7790 v = p[v];
7791 }
7792 return result;
7793 }
7794
7795 const isTeleport = (type) => type.__isTeleport;
7796 const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7797 const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7798 const resolveTarget = (props, select) => {
7799 const targetSelector = props && props.to;
7800 if (isString(targetSelector)) {
7801 if (!select) {
7802 warn$1(`Current renderer does not support string target for Teleports. ` +
7803 `(missing querySelector renderer option)`);
7804 return null;
7805 }
7806 else {
7807 const target = select(targetSelector);
7808 if (!target) {
7809 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7810 `Note the target element must exist before the component is mounted - ` +
7811 `i.e. the target cannot be rendered by the component itself, and ` +
7812 `ideally should be outside of the entire Vue component tree.`);
7813 }
7814 return target;
7815 }
7816 }
7817 else {
7818 if (!targetSelector && !isTeleportDisabled(props)) {
7819 warn$1(`Invalid Teleport target: ${targetSelector}`);
7820 }
7821 return targetSelector;
7822 }
7823 };
7824 const TeleportImpl = {
7825 __isTeleport: true,
7826 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7827 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7828 const disabled = isTeleportDisabled(n2.props);
7829 let { shapeFlag, children, dynamicChildren } = n2;
7830 // #3302
7831 // HMR updated, force full diff
7832 if (isHmrUpdating) {
7833 optimized = false;
7834 dynamicChildren = null;
7835 }
7836 if (n1 == null) {
7837 // insert anchors in the main view
7838 const placeholder = (n2.el = createComment('teleport start')
7839 );
7840 const mainAnchor = (n2.anchor = createComment('teleport end')
7841 );
7842 insert(placeholder, container, anchor);
7843 insert(mainAnchor, container, anchor);
7844 const target = (n2.target = resolveTarget(n2.props, querySelector));
7845 const targetAnchor = (n2.targetAnchor = createText(''));
7846 if (target) {
7847 insert(targetAnchor, target);
7848 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7849 isSVG = isSVG || isTargetSVG(target);
7850 }
7851 else if (!disabled) {
7852 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
7853 }
7854 const mount = (container, anchor) => {
7855 // Teleport *always* has Array children. This is enforced in both the
7856 // compiler and vnode children normalization.
7857 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7858 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7859 }
7860 };
7861 if (disabled) {
7862 mount(container, mainAnchor);
7863 }
7864 else if (target) {
7865 mount(target, targetAnchor);
7866 }
7867 }
7868 else {
7869 // update content
7870 n2.el = n1.el;
7871 const mainAnchor = (n2.anchor = n1.anchor);
7872 const target = (n2.target = n1.target);
7873 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7874 const wasDisabled = isTeleportDisabled(n1.props);
7875 const currentContainer = wasDisabled ? container : target;
7876 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7877 isSVG = isSVG || isTargetSVG(target);
7878 if (dynamicChildren) {
7879 // fast path when the teleport happens to be a block root
7880 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7881 // even in block tree mode we need to make sure all root-level nodes
7882 // in the teleport inherit previous DOM references so that they can
7883 // be moved in future patches.
7884 traverseStaticChildren(n1, n2, true);
7885 }
7886 else if (!optimized) {
7887 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7888 }
7889 if (disabled) {
7890 if (!wasDisabled) {
7891 // enabled -> disabled
7892 // move into main container
7893 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
7894 }
7895 }
7896 else {
7897 // target changed
7898 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7899 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7900 if (nextTarget) {
7901 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
7902 }
7903 else {
7904 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
7905 }
7906 }
7907 else if (wasDisabled) {
7908 // disabled -> enabled
7909 // move into teleport target
7910 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
7911 }
7912 }
7913 }
7914 },
7915 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7916 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7917 if (target) {
7918 hostRemove(targetAnchor);
7919 }
7920 // an unmounted teleport should always remove its children if not disabled
7921 if (doRemove || !isTeleportDisabled(props)) {
7922 hostRemove(anchor);
7923 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7924 for (let i = 0; i < children.length; i++) {
7925 const child = children[i];
7926 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7927 }
7928 }
7929 }
7930 },
7931 move: moveTeleport,
7932 hydrate: hydrateTeleport
7933 };
7934 function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
7935 // move target anchor if this is a target change.
7936 if (moveType === 0 /* TARGET_CHANGE */) {
7937 insert(vnode.targetAnchor, container, parentAnchor);
7938 }
7939 const { el, anchor, shapeFlag, children, props } = vnode;
7940 const isReorder = moveType === 2 /* REORDER */;
7941 // move main view anchor if this is a re-order.
7942 if (isReorder) {
7943 insert(el, container, parentAnchor);
7944 }
7945 // if this is a re-order and teleport is enabled (content is in target)
7946 // do not move children. So the opposite is: only move children if this
7947 // is not a reorder, or the teleport is disabled
7948 if (!isReorder || isTeleportDisabled(props)) {
7949 // Teleport has either Array children or no children.
7950 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7951 for (let i = 0; i < children.length; i++) {
7952 move(children[i], container, parentAnchor, 2 /* REORDER */);
7953 }
7954 }
7955 }
7956 // move main view anchor if this is a re-order.
7957 if (isReorder) {
7958 insert(anchor, container, parentAnchor);
7959 }
7960 }
7961 function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
7962 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
7963 if (target) {
7964 // if multiple teleports rendered to the same target element, we need to
7965 // pick up from where the last teleport finished instead of the first node
7966 const targetNode = target._lpa || target.firstChild;
7967 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
7968 if (isTeleportDisabled(vnode.props)) {
7969 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
7970 vnode.targetAnchor = targetNode;
7971 }
7972 else {
7973 vnode.anchor = nextSibling(node);
7974 // lookahead until we find the target anchor
7975 // we cannot rely on return value of hydrateChildren() because there
7976 // could be nested teleports
7977 let targetAnchor = targetNode;
7978 while (targetAnchor) {
7979 targetAnchor = nextSibling(targetAnchor);
7980 if (targetAnchor &&
7981 targetAnchor.nodeType === 8 &&
7982 targetAnchor.data === 'teleport anchor') {
7983 vnode.targetAnchor = targetAnchor;
7984 target._lpa =
7985 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
7986 break;
7987 }
7988 }
7989 hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
7990 }
7991 }
7992 }
7993 return vnode.anchor && nextSibling(vnode.anchor);
7994 }
7995 // Force-casted public typing for h and TSX props inference
7996 const Teleport = TeleportImpl;
7997
7998 const Fragment = Symbol('Fragment' );
7999 const Text = Symbol('Text' );
8000 const Comment = Symbol('Comment' );
8001 const Static = Symbol('Static' );
8002 // Since v-if and v-for are the two possible ways node structure can dynamically
8003 // change, once we consider v-if branches and each v-for fragment a block, we
8004 // can divide a template into nested blocks, and within each block the node
8005 // structure would be stable. This allows us to skip most children diffing
8006 // and only worry about the dynamic nodes (indicated by patch flags).
8007 const blockStack = [];
8008 let currentBlock = null;
8009 /**
8010 * Open a block.
8011 * This must be called before `createBlock`. It cannot be part of `createBlock`
8012 * because the children of the block are evaluated before `createBlock` itself
8013 * is called. The generated code typically looks like this:
8014 *
8015 * ```js
8016 * function render() {
8017 * return (openBlock(),createBlock('div', null, [...]))
8018 * }
8019 * ```
8020 * disableTracking is true when creating a v-for fragment block, since a v-for
8021 * fragment always diffs its children.
8022 *
8023 * @private
8024 */
8025 function openBlock(disableTracking = false) {
8026 blockStack.push((currentBlock = disableTracking ? null : []));
8027 }
8028 function closeBlock() {
8029 blockStack.pop();
8030 currentBlock = blockStack[blockStack.length - 1] || null;
8031 }
8032 // Whether we should be tracking dynamic child nodes inside a block.
8033 // Only tracks when this value is > 0
8034 // We are not using a simple boolean because this value may need to be
8035 // incremented/decremented by nested usage of v-once (see below)
8036 let isBlockTreeEnabled = 1;
8037 /**
8038 * Block tracking sometimes needs to be disabled, for example during the
8039 * creation of a tree that needs to be cached by v-once. The compiler generates
8040 * code like this:
8041 *
8042 * ``` js
8043 * _cache[1] || (
8044 * setBlockTracking(-1),
8045 * _cache[1] = createVNode(...),
8046 * setBlockTracking(1),
8047 * _cache[1]
8048 * )
8049 * ```
8050 *
8051 * @private
8052 */
8053 function setBlockTracking(value) {
8054 isBlockTreeEnabled += value;
8055 }
8056 function setupBlock(vnode) {
8057 // save current block children on the block vnode
8058 vnode.dynamicChildren =
8059 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
8060 // close block
8061 closeBlock();
8062 // a block is always going to be patched, so track it as a child of its
8063 // parent block
8064 if (isBlockTreeEnabled > 0 && currentBlock) {
8065 currentBlock.push(vnode);
8066 }
8067 return vnode;
8068 }
8069 /**
8070 * @private
8071 */
8072 function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
8073 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
8074 }
8075 /**
8076 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
8077 * A block root keeps track of dynamic nodes within the block in the
8078 * `dynamicChildren` array.
8079 *
8080 * @private
8081 */
8082 function createBlock(type, props, children, patchFlag, dynamicProps) {
8083 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
8084 }
8085 function isVNode(value) {
8086 return value ? value.__v_isVNode === true : false;
8087 }
8088 function isSameVNodeType(n1, n2) {
8089 if (n2.shapeFlag & 6 /* COMPONENT */ &&
8090 hmrDirtyComponents.has(n2.type)) {
8091 // HMR only: if the component has been hot-updated, force a reload.
8092 return false;
8093 }
8094 return n1.type === n2.type && n1.key === n2.key;
8095 }
8096 let vnodeArgsTransformer;
8097 /**
8098 * Internal API for registering an arguments transform for createVNode
8099 * used for creating stubs in the test-utils
8100 * It is *internal* but needs to be exposed for test-utils to pick up proper
8101 * typings
8102 */
8103 function transformVNodeArgs(transformer) {
8104 vnodeArgsTransformer = transformer;
8105 }
8106 const createVNodeWithArgsTransform = (...args) => {
8107 return _createVNode(...(vnodeArgsTransformer
8108 ? vnodeArgsTransformer(args, currentRenderingInstance)
8109 : args));
8110 };
8111 const InternalObjectKey = `__vInternal`;
8112 const normalizeKey = ({ key }) => key != null ? key : null;
8113 const normalizeRef = ({ ref, ref_key, ref_for }) => {
8114 return (ref != null
8115 ? isString(ref) || isRef(ref) || isFunction(ref)
8116 ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
8117 : ref
8118 : null);
8119 };
8120 function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
8121 const vnode = {
8122 __v_isVNode: true,
8123 __v_skip: true,
8124 type,
8125 props,
8126 key: props && normalizeKey(props),
8127 ref: props && normalizeRef(props),
8128 scopeId: currentScopeId,
8129 slotScopeIds: null,
8130 children,
8131 component: null,
8132 suspense: null,
8133 ssContent: null,
8134 ssFallback: null,
8135 dirs: null,
8136 transition: null,
8137 el: null,
8138 anchor: null,
8139 target: null,
8140 targetAnchor: null,
8141 staticCount: 0,
8142 shapeFlag,
8143 patchFlag,
8144 dynamicProps,
8145 dynamicChildren: null,
8146 appContext: null
8147 };
8148 if (needFullChildrenNormalization) {
8149 normalizeChildren(vnode, children);
8150 // normalize suspense children
8151 if (shapeFlag & 128 /* SUSPENSE */) {
8152 type.normalize(vnode);
8153 }
8154 }
8155 else if (children) {
8156 // compiled element vnode - if children is passed, only possible types are
8157 // string or Array.
8158 vnode.shapeFlag |= isString(children)
8159 ? 8 /* TEXT_CHILDREN */
8160 : 16 /* ARRAY_CHILDREN */;
8161 }
8162 // validate key
8163 if (vnode.key !== vnode.key) {
8164 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
8165 }
8166 // track vnode for block tree
8167 if (isBlockTreeEnabled > 0 &&
8168 // avoid a block node from tracking itself
8169 !isBlockNode &&
8170 // has current parent block
8171 currentBlock &&
8172 // presence of a patch flag indicates this node needs patching on updates.
8173 // component nodes also should always be patched, because even if the
8174 // component doesn't need to update, it needs to persist the instance on to
8175 // the next vnode so that it can be properly unmounted later.
8176 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
8177 // the EVENTS flag is only for hydration and if it is the only flag, the
8178 // vnode should not be considered dynamic due to handler caching.
8179 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
8180 currentBlock.push(vnode);
8181 }
8182 return vnode;
8183 }
8184 const createVNode = (createVNodeWithArgsTransform );
8185 function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
8186 if (!type || type === NULL_DYNAMIC_COMPONENT) {
8187 if (!type) {
8188 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
8189 }
8190 type = Comment;
8191 }
8192 if (isVNode(type)) {
8193 // createVNode receiving an existing vnode. This happens in cases like
8194 // <component :is="vnode"/>
8195 // #2078 make sure to merge refs during the clone instead of overwriting it
8196 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
8197 if (children) {
8198 normalizeChildren(cloned, children);
8199 }
8200 if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
8201 if (cloned.shapeFlag & 6 /* COMPONENT */) {
8202 currentBlock[currentBlock.indexOf(type)] = cloned;
8203 }
8204 else {
8205 currentBlock.push(cloned);
8206 }
8207 }
8208 cloned.patchFlag |= -2 /* BAIL */;
8209 return cloned;
8210 }
8211 // class component normalization.
8212 if (isClassComponent(type)) {
8213 type = type.__vccOpts;
8214 }
8215 // class & style normalization.
8216 if (props) {
8217 // for reactive or proxy objects, we need to clone it to enable mutation.
8218 props = guardReactiveProps(props);
8219 let { class: klass, style } = props;
8220 if (klass && !isString(klass)) {
8221 props.class = normalizeClass(klass);
8222 }
8223 if (isObject(style)) {
8224 // reactive state objects need to be cloned since they are likely to be
8225 // mutated
8226 if (isProxy(style) && !isArray(style)) {
8227 style = extend({}, style);
8228 }
8229 props.style = normalizeStyle(style);
8230 }
8231 }
8232 // encode the vnode type information into a bitmap
8233 const shapeFlag = isString(type)
8234 ? 1 /* ELEMENT */
8235 : isSuspense(type)
8236 ? 128 /* SUSPENSE */
8237 : isTeleport(type)
8238 ? 64 /* TELEPORT */
8239 : isObject(type)
8240 ? 4 /* STATEFUL_COMPONENT */
8241 : isFunction(type)
8242 ? 2 /* FUNCTIONAL_COMPONENT */
8243 : 0;
8244 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
8245 type = toRaw(type);
8246 warn$1(`Vue received a Component which was made a reactive object. This can ` +
8247 `lead to unnecessary performance overhead, and should be avoided by ` +
8248 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
8249 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
8250 }
8251 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
8252 }
8253 function guardReactiveProps(props) {
8254 if (!props)
8255 return null;
8256 return isProxy(props) || InternalObjectKey in props
8257 ? extend({}, props)
8258 : props;
8259 }
8260 function cloneVNode(vnode, extraProps, mergeRef = false) {
8261 // This is intentionally NOT using spread or extend to avoid the runtime
8262 // key enumeration cost.
8263 const { props, ref, patchFlag, children } = vnode;
8264 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
8265 const cloned = {
8266 __v_isVNode: true,
8267 __v_skip: true,
8268 type: vnode.type,
8269 props: mergedProps,
8270 key: mergedProps && normalizeKey(mergedProps),
8271 ref: extraProps && extraProps.ref
8272 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
8273 // if the vnode itself already has a ref, cloneVNode will need to merge
8274 // the refs so the single vnode can be set on multiple refs
8275 mergeRef && ref
8276 ? isArray(ref)
8277 ? ref.concat(normalizeRef(extraProps))
8278 : [ref, normalizeRef(extraProps)]
8279 : normalizeRef(extraProps)
8280 : ref,
8281 scopeId: vnode.scopeId,
8282 slotScopeIds: vnode.slotScopeIds,
8283 children: patchFlag === -1 /* HOISTED */ && isArray(children)
8284 ? children.map(deepCloneVNode)
8285 : children,
8286 target: vnode.target,
8287 targetAnchor: vnode.targetAnchor,
8288 staticCount: vnode.staticCount,
8289 shapeFlag: vnode.shapeFlag,
8290 // if the vnode is cloned with extra props, we can no longer assume its
8291 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
8292 // note: preserve flag for fragments since they use the flag for children
8293 // fast paths only.
8294 patchFlag: extraProps && vnode.type !== Fragment
8295 ? patchFlag === -1 // hoisted node
8296 ? 16 /* FULL_PROPS */
8297 : patchFlag | 16 /* FULL_PROPS */
8298 : patchFlag,
8299 dynamicProps: vnode.dynamicProps,
8300 dynamicChildren: vnode.dynamicChildren,
8301 appContext: vnode.appContext,
8302 dirs: vnode.dirs,
8303 transition: vnode.transition,
8304 // These should technically only be non-null on mounted VNodes. However,
8305 // they *should* be copied for kept-alive vnodes. So we just always copy
8306 // them since them being non-null during a mount doesn't affect the logic as
8307 // they will simply be overwritten.
8308 component: vnode.component,
8309 suspense: vnode.suspense,
8310 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
8311 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
8312 el: vnode.el,
8313 anchor: vnode.anchor
8314 };
8315 return cloned;
8316 }
8317 /**
8318 * Dev only, for HMR of hoisted vnodes reused in v-for
8319 * https://github.com/vitejs/vite/issues/2022
8320 */
8321 function deepCloneVNode(vnode) {
8322 const cloned = cloneVNode(vnode);
8323 if (isArray(vnode.children)) {
8324 cloned.children = vnode.children.map(deepCloneVNode);
8325 }
8326 return cloned;
8327 }
8328 /**
8329 * @private
8330 */
8331 function createTextVNode(text = ' ', flag = 0) {
8332 return createVNode(Text, null, text, flag);
8333 }
8334 /**
8335 * @private
8336 */
8337 function createStaticVNode(content, numberOfNodes) {
8338 // A static vnode can contain multiple stringified elements, and the number
8339 // of elements is necessary for hydration.
8340 const vnode = createVNode(Static, null, content);
8341 vnode.staticCount = numberOfNodes;
8342 return vnode;
8343 }
8344 /**
8345 * @private
8346 */
8347 function createCommentVNode(text = '',
8348 // when used as the v-else branch, the comment node must be created as a
8349 // block to ensure correct updates.
8350 asBlock = false) {
8351 return asBlock
8352 ? (openBlock(), createBlock(Comment, null, text))
8353 : createVNode(Comment, null, text);
8354 }
8355 function normalizeVNode(child) {
8356 if (child == null || typeof child === 'boolean') {
8357 // empty placeholder
8358 return createVNode(Comment);
8359 }
8360 else if (isArray(child)) {
8361 // fragment
8362 return createVNode(Fragment, null,
8363 // #3666, avoid reference pollution when reusing vnode
8364 child.slice());
8365 }
8366 else if (typeof child === 'object') {
8367 // already vnode, this should be the most common since compiled templates
8368 // always produce all-vnode children arrays
8369 return cloneIfMounted(child);
8370 }
8371 else {
8372 // strings and numbers
8373 return createVNode(Text, null, String(child));
8374 }
8375 }
8376 // optimized normalization for template-compiled render fns
8377 function cloneIfMounted(child) {
8378 return child.el === null || child.memo ? child : cloneVNode(child);
8379 }
8380 function normalizeChildren(vnode, children) {
8381 let type = 0;
8382 const { shapeFlag } = vnode;
8383 if (children == null) {
8384 children = null;
8385 }
8386 else if (isArray(children)) {
8387 type = 16 /* ARRAY_CHILDREN */;
8388 }
8389 else if (typeof children === 'object') {
8390 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
8391 // Normalize slot to plain children for plain element and Teleport
8392 const slot = children.default;
8393 if (slot) {
8394 // _c marker is added by withCtx() indicating this is a compiled slot
8395 slot._c && (slot._d = false);
8396 normalizeChildren(vnode, slot());
8397 slot._c && (slot._d = true);
8398 }
8399 return;
8400 }
8401 else {
8402 type = 32 /* SLOTS_CHILDREN */;
8403 const slotFlag = children._;
8404 if (!slotFlag && !(InternalObjectKey in children)) {
8405 children._ctx = currentRenderingInstance;
8406 }
8407 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
8408 // a child component receives forwarded slots from the parent.
8409 // its slot type is determined by its parent's slot type.
8410 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
8411 children._ = 1 /* STABLE */;
8412 }
8413 else {
8414 children._ = 2 /* DYNAMIC */;
8415 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
8416 }
8417 }
8418 }
8419 }
8420 else if (isFunction(children)) {
8421 children = { default: children, _ctx: currentRenderingInstance };
8422 type = 32 /* SLOTS_CHILDREN */;
8423 }
8424 else {
8425 children = String(children);
8426 // force teleport children to array so it can be moved around
8427 if (shapeFlag & 64 /* TELEPORT */) {
8428 type = 16 /* ARRAY_CHILDREN */;
8429 children = [createTextVNode(children)];
8430 }
8431 else {
8432 type = 8 /* TEXT_CHILDREN */;
8433 }
8434 }
8435 vnode.children = children;
8436 vnode.shapeFlag |= type;
8437 }
8438 function mergeProps(...args) {
8439 const ret = {};
8440 for (let i = 0; i < args.length; i++) {
8441 const toMerge = args[i];
8442 for (const key in toMerge) {
8443 if (key === 'class') {
8444 if (ret.class !== toMerge.class) {
8445 ret.class = normalizeClass([ret.class, toMerge.class]);
8446 }
8447 }
8448 else if (key === 'style') {
8449 ret.style = normalizeStyle([ret.style, toMerge.style]);
8450 }
8451 else if (isOn(key)) {
8452 const existing = ret[key];
8453 const incoming = toMerge[key];
8454 if (incoming &&
8455 existing !== incoming &&
8456 !(isArray(existing) && existing.includes(incoming))) {
8457 ret[key] = existing
8458 ? [].concat(existing, incoming)
8459 : incoming;
8460 }
8461 }
8462 else if (key !== '') {
8463 ret[key] = toMerge[key];
8464 }
8465 }
8466 }
8467 return ret;
8468 }
8469 function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
8470 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
8471 vnode,
8472 prevVNode
8473 ]);
8474 }
8475
8476 const emptyAppContext = createAppContext();
8477 let uid$1 = 0;
8478 function createComponentInstance(vnode, parent, suspense) {
8479 const type = vnode.type;
8480 // inherit parent app context - or - if root, adopt from root vnode
8481 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8482 const instance = {
8483 uid: uid$1++,
8484 vnode,
8485 type,
8486 parent,
8487 appContext,
8488 root: null,
8489 next: null,
8490 subTree: null,
8491 effect: null,
8492 update: null,
8493 scope: new EffectScope(true /* detached */),
8494 render: null,
8495 proxy: null,
8496 exposed: null,
8497 exposeProxy: null,
8498 withProxy: null,
8499 provides: parent ? parent.provides : Object.create(appContext.provides),
8500 accessCache: null,
8501 renderCache: [],
8502 // local resolved assets
8503 components: null,
8504 directives: null,
8505 // resolved props and emits options
8506 propsOptions: normalizePropsOptions(type, appContext),
8507 emitsOptions: normalizeEmitsOptions(type, appContext),
8508 // emit
8509 emit: null,
8510 emitted: null,
8511 // props default value
8512 propsDefaults: EMPTY_OBJ,
8513 // inheritAttrs
8514 inheritAttrs: type.inheritAttrs,
8515 // state
8516 ctx: EMPTY_OBJ,
8517 data: EMPTY_OBJ,
8518 props: EMPTY_OBJ,
8519 attrs: EMPTY_OBJ,
8520 slots: EMPTY_OBJ,
8521 refs: EMPTY_OBJ,
8522 setupState: EMPTY_OBJ,
8523 setupContext: null,
8524 // suspense related
8525 suspense,
8526 suspenseId: suspense ? suspense.pendingId : 0,
8527 asyncDep: null,
8528 asyncResolved: false,
8529 // lifecycle hooks
8530 // not using enums here because it results in computed properties
8531 isMounted: false,
8532 isUnmounted: false,
8533 isDeactivated: false,
8534 bc: null,
8535 c: null,
8536 bm: null,
8537 m: null,
8538 bu: null,
8539 u: null,
8540 um: null,
8541 bum: null,
8542 da: null,
8543 a: null,
8544 rtg: null,
8545 rtc: null,
8546 ec: null,
8547 sp: null
8548 };
8549 {
8550 instance.ctx = createDevRenderContext(instance);
8551 }
8552 instance.root = parent ? parent.root : instance;
8553 instance.emit = emit$1.bind(null, instance);
8554 // apply custom element special handling
8555 if (vnode.ce) {
8556 vnode.ce(instance);
8557 }
8558 return instance;
8559 }
8560 let currentInstance = null;
8561 const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8562 const setCurrentInstance = (instance) => {
8563 currentInstance = instance;
8564 instance.scope.on();
8565 };
8566 const unsetCurrentInstance = () => {
8567 currentInstance && currentInstance.scope.off();
8568 currentInstance = null;
8569 };
8570 const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8571 function validateComponentName(name, config) {
8572 const appIsNativeTag = config.isNativeTag || NO;
8573 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8574 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
8575 }
8576 }
8577 function isStatefulComponent(instance) {
8578 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
8579 }
8580 let isInSSRComponentSetup = false;
8581 function setupComponent(instance, isSSR = false) {
8582 isInSSRComponentSetup = isSSR;
8583 const { props, children } = instance.vnode;
8584 const isStateful = isStatefulComponent(instance);
8585 initProps(instance, props, isStateful, isSSR);
8586 initSlots(instance, children);
8587 const setupResult = isStateful
8588 ? setupStatefulComponent(instance, isSSR)
8589 : undefined;
8590 isInSSRComponentSetup = false;
8591 return setupResult;
8592 }
8593 function setupStatefulComponent(instance, isSSR) {
8594 var _a;
8595 const Component = instance.type;
8596 {
8597 if (Component.name) {
8598 validateComponentName(Component.name, instance.appContext.config);
8599 }
8600 if (Component.components) {
8601 const names = Object.keys(Component.components);
8602 for (let i = 0; i < names.length; i++) {
8603 validateComponentName(names[i], instance.appContext.config);
8604 }
8605 }
8606 if (Component.directives) {
8607 const names = Object.keys(Component.directives);
8608 for (let i = 0; i < names.length; i++) {
8609 validateDirectiveName(names[i]);
8610 }
8611 }
8612 if (Component.compilerOptions && isRuntimeOnly()) {
8613 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8614 `includes the runtime compiler. Since you are using a runtime-only ` +
8615 `build, the options should be passed via your build tool config instead.`);
8616 }
8617 }
8618 // 0. create render proxy property access cache
8619 instance.accessCache = Object.create(null);
8620 // 1. create public instance / render proxy
8621 // also mark it raw so it's never observed
8622 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8623 {
8624 exposePropsOnRenderContext(instance);
8625 }
8626 // 2. call setup()
8627 const { setup } = Component;
8628 if (setup) {
8629 const setupContext = (instance.setupContext =
8630 setup.length > 1 ? createSetupContext(instance) : null);
8631 setCurrentInstance(instance);
8632 pauseTracking();
8633 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8634 resetTracking();
8635 unsetCurrentInstance();
8636 if (isPromise(setupResult)) {
8637 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8638 if (isSSR) {
8639 // return the promise so server-renderer can wait on it
8640 return setupResult
8641 .then((resolvedResult) => {
8642 handleSetupResult(instance, resolvedResult, isSSR);
8643 })
8644 .catch(e => {
8645 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8646 });
8647 }
8648 else {
8649 // async setup returned Promise.
8650 // bail here and wait for re-entry.
8651 instance.asyncDep = setupResult;
8652 if (!instance.suspense) {
8653 const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
8654 warn$1(`Component <${name}>: setup function returned a promise, but no ` +
8655 `<Suspense> boundary was found in the parent component tree. ` +
8656 `A component with async setup() must be nested in a <Suspense> ` +
8657 `in order to be rendered.`);
8658 }
8659 }
8660 }
8661 else {
8662 handleSetupResult(instance, setupResult, isSSR);
8663 }
8664 }
8665 else {
8666 finishComponentSetup(instance, isSSR);
8667 }
8668 }
8669 function handleSetupResult(instance, setupResult, isSSR) {
8670 if (isFunction(setupResult)) {
8671 // setup returned an inline render function
8672 {
8673 instance.render = setupResult;
8674 }
8675 }
8676 else if (isObject(setupResult)) {
8677 if (isVNode(setupResult)) {
8678 warn$1(`setup() should not return VNodes directly - ` +
8679 `return a render function instead.`);
8680 }
8681 // setup returned bindings.
8682 // assuming a render function compiled from template is present.
8683 {
8684 instance.devtoolsRawSetupState = setupResult;
8685 }
8686 instance.setupState = proxyRefs(setupResult);
8687 {
8688 exposeSetupStateOnRenderContext(instance);
8689 }
8690 }
8691 else if (setupResult !== undefined) {
8692 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8693 }
8694 finishComponentSetup(instance, isSSR);
8695 }
8696 let compile;
8697 let installWithProxy;
8698 /**
8699 * For runtime-dom to register the compiler.
8700 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8701 */
8702 function registerRuntimeCompiler(_compile) {
8703 compile = _compile;
8704 installWithProxy = i => {
8705 if (i.render._rc) {
8706 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8707 }
8708 };
8709 }
8710 // dev only
8711 const isRuntimeOnly = () => !compile;
8712 function finishComponentSetup(instance, isSSR, skipOptions) {
8713 const Component = instance.type;
8714 // template / render function normalization
8715 // could be already set when returned from setup()
8716 if (!instance.render) {
8717 // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
8718 // is done by server-renderer
8719 if (!isSSR && compile && !Component.render) {
8720 const template = Component.template;
8721 if (template) {
8722 {
8723 startMeasure(instance, `compile`);
8724 }
8725 const { isCustomElement, compilerOptions } = instance.appContext.config;
8726 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8727 const finalCompilerOptions = extend(extend({
8728 isCustomElement,
8729 delimiters
8730 }, compilerOptions), componentCompilerOptions);
8731 Component.render = compile(template, finalCompilerOptions);
8732 {
8733 endMeasure(instance, `compile`);
8734 }
8735 }
8736 }
8737 instance.render = (Component.render || NOOP);
8738 // for runtime-compiled render functions using `with` blocks, the render
8739 // proxy used needs a different `has` handler which is more performant and
8740 // also only allows a whitelist of globals to fallthrough.
8741 if (installWithProxy) {
8742 installWithProxy(instance);
8743 }
8744 }
8745 // support for 2.x options
8746 {
8747 setCurrentInstance(instance);
8748 pauseTracking();
8749 applyOptions(instance);
8750 resetTracking();
8751 unsetCurrentInstance();
8752 }
8753 // warn missing template/render
8754 // the runtime compilation of template in SSR is done by server-render
8755 if (!Component.render && instance.render === NOOP && !isSSR) {
8756 /* istanbul ignore if */
8757 if (!compile && Component.template) {
8758 warn$1(`Component provided template option but ` +
8759 `runtime compilation is not supported in this build of Vue.` +
8760 (` Use "vue.global.js" instead.`
8761 ) /* should not happen */);
8762 }
8763 else {
8764 warn$1(`Component is missing template or render function.`);
8765 }
8766 }
8767 }
8768 function createAttrsProxy(instance) {
8769 return new Proxy(instance.attrs, {
8770 get(target, key) {
8771 markAttrsAccessed();
8772 track(instance, "get" /* GET */, '$attrs');
8773 return target[key];
8774 },
8775 set() {
8776 warn$1(`setupContext.attrs is readonly.`);
8777 return false;
8778 },
8779 deleteProperty() {
8780 warn$1(`setupContext.attrs is readonly.`);
8781 return false;
8782 }
8783 }
8784 );
8785 }
8786 function createSetupContext(instance) {
8787 const expose = exposed => {
8788 if (instance.exposed) {
8789 warn$1(`expose() should be called only once per setup().`);
8790 }
8791 instance.exposed = exposed || {};
8792 };
8793 let attrs;
8794 {
8795 // We use getters in dev in case libs like test-utils overwrite instance
8796 // properties (overwrites should not be done in prod)
8797 return Object.freeze({
8798 get attrs() {
8799 return attrs || (attrs = createAttrsProxy(instance));
8800 },
8801 get slots() {
8802 return shallowReadonly(instance.slots);
8803 },
8804 get emit() {
8805 return (event, ...args) => instance.emit(event, ...args);
8806 },
8807 expose
8808 });
8809 }
8810 }
8811 function getExposeProxy(instance) {
8812 if (instance.exposed) {
8813 return (instance.exposeProxy ||
8814 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8815 get(target, key) {
8816 if (key in target) {
8817 return target[key];
8818 }
8819 else if (key in publicPropertiesMap) {
8820 return publicPropertiesMap[key](instance);
8821 }
8822 }
8823 })));
8824 }
8825 }
8826 const classifyRE = /(?:^|[-_])(\w)/g;
8827 const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8828 function getComponentName(Component, includeInferred = true) {
8829 return isFunction(Component)
8830 ? Component.displayName || Component.name
8831 : Component.name || (includeInferred && Component.__name);
8832 }
8833 /* istanbul ignore next */
8834 function formatComponentName(instance, Component, isRoot = false) {
8835 let name = getComponentName(Component);
8836 if (!name && Component.__file) {
8837 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8838 if (match) {
8839 name = match[1];
8840 }
8841 }
8842 if (!name && instance && instance.parent) {
8843 // try to infer the name based on reverse resolution
8844 const inferFromRegistry = (registry) => {
8845 for (const key in registry) {
8846 if (registry[key] === Component) {
8847 return key;
8848 }
8849 }
8850 };
8851 name =
8852 inferFromRegistry(instance.components ||
8853 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8854 }
8855 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8856 }
8857 function isClassComponent(value) {
8858 return isFunction(value) && '__vccOpts' in value;
8859 }
8860
8861 const computed$1 = ((getterOrOptions, debugOptions) => {
8862 // @ts-ignore
8863 return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
8864 });
8865
8866 // dev only
8867 const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8868 `<script setup> of a single file component. Its arguments should be ` +
8869 `compiled away and passing it at runtime has no effect.`);
8870 // implementation
8871 function defineProps() {
8872 {
8873 warnRuntimeUsage(`defineProps`);
8874 }
8875 return null;
8876 }
8877 // implementation
8878 function defineEmits() {
8879 {
8880 warnRuntimeUsage(`defineEmits`);
8881 }
8882 return null;
8883 }
8884 /**
8885 * Vue `<script setup>` compiler macro for declaring a component's exposed
8886 * instance properties when it is accessed by a parent component via template
8887 * refs.
8888 *
8889 * `<script setup>` components are closed by default - i.e. variables inside
8890 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8891 * via `defineExpose`.
8892 *
8893 * This is only usable inside `<script setup>`, is compiled away in the
8894 * output and should **not** be actually called at runtime.
8895 */
8896 function defineExpose(exposed) {
8897 {
8898 warnRuntimeUsage(`defineExpose`);
8899 }
8900 }
8901 /**
8902 * Vue `<script setup>` compiler macro for providing props default values when
8903 * using type-based `defineProps` declaration.
8904 *
8905 * Example usage:
8906 * ```ts
8907 * withDefaults(defineProps<{
8908 * size?: number
8909 * labels?: string[]
8910 * }>(), {
8911 * size: 3,
8912 * labels: () => ['default label']
8913 * })
8914 * ```
8915 *
8916 * This is only usable inside `<script setup>`, is compiled away in the output
8917 * and should **not** be actually called at runtime.
8918 */
8919 function withDefaults(props, defaults) {
8920 {
8921 warnRuntimeUsage(`withDefaults`);
8922 }
8923 return null;
8924 }
8925 function useSlots() {
8926 return getContext().slots;
8927 }
8928 function useAttrs() {
8929 return getContext().attrs;
8930 }
8931 function getContext() {
8932 const i = getCurrentInstance();
8933 if (!i) {
8934 warn$1(`useContext() called without active instance.`);
8935 }
8936 return i.setupContext || (i.setupContext = createSetupContext(i));
8937 }
8938 /**
8939 * Runtime helper for merging default declarations. Imported by compiled code
8940 * only.
8941 * @internal
8942 */
8943 function mergeDefaults(raw, defaults) {
8944 const props = isArray(raw)
8945 ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
8946 : raw;
8947 for (const key in defaults) {
8948 const opt = props[key];
8949 if (opt) {
8950 if (isArray(opt) || isFunction(opt)) {
8951 props[key] = { type: opt, default: defaults[key] };
8952 }
8953 else {
8954 opt.default = defaults[key];
8955 }
8956 }
8957 else if (opt === null) {
8958 props[key] = { default: defaults[key] };
8959 }
8960 else {
8961 warn$1(`props default key "${key}" has no corresponding declaration.`);
8962 }
8963 }
8964 return props;
8965 }
8966 /**
8967 * Used to create a proxy for the rest element when destructuring props with
8968 * defineProps().
8969 * @internal
8970 */
8971 function createPropsRestProxy(props, excludedKeys) {
8972 const ret = {};
8973 for (const key in props) {
8974 if (!excludedKeys.includes(key)) {
8975 Object.defineProperty(ret, key, {
8976 enumerable: true,
8977 get: () => props[key]
8978 });
8979 }
8980 }
8981 return ret;
8982 }
8983 /**
8984 * `<script setup>` helper for persisting the current instance context over
8985 * async/await flows.
8986 *
8987 * `@vue/compiler-sfc` converts the following:
8988 *
8989 * ```ts
8990 * const x = await foo()
8991 * ```
8992 *
8993 * into:
8994 *
8995 * ```ts
8996 * let __temp, __restore
8997 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
8998 * ```
8999 * @internal
9000 */
9001 function withAsyncContext(getAwaitable) {
9002 const ctx = getCurrentInstance();
9003 if (!ctx) {
9004 warn$1(`withAsyncContext called without active current instance. ` +
9005 `This is likely a bug.`);
9006 }
9007 let awaitable = getAwaitable();
9008 unsetCurrentInstance();
9009 if (isPromise(awaitable)) {
9010 awaitable = awaitable.catch(e => {
9011 setCurrentInstance(ctx);
9012 throw e;
9013 });
9014 }
9015 return [awaitable, () => setCurrentInstance(ctx)];
9016 }
9017
9018 // Actual implementation
9019 function h(type, propsOrChildren, children) {
9020 const l = arguments.length;
9021 if (l === 2) {
9022 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
9023 // single vnode without props
9024 if (isVNode(propsOrChildren)) {
9025 return createVNode(type, null, [propsOrChildren]);
9026 }
9027 // props without children
9028 return createVNode(type, propsOrChildren);
9029 }
9030 else {
9031 // omit props
9032 return createVNode(type, null, propsOrChildren);
9033 }
9034 }
9035 else {
9036 if (l > 3) {
9037 children = Array.prototype.slice.call(arguments, 2);
9038 }
9039 else if (l === 3 && isVNode(children)) {
9040 children = [children];
9041 }
9042 return createVNode(type, propsOrChildren, children);
9043 }
9044 }
9045
9046 const ssrContextKey = Symbol(`ssrContext` );
9047 const useSSRContext = () => {
9048 {
9049 warn$1(`useSSRContext() is not supported in the global build.`);
9050 }
9051 };
9052
9053 function initCustomFormatter() {
9054 /* eslint-disable no-restricted-globals */
9055 if (typeof window === 'undefined') {
9056 return;
9057 }
9058 const vueStyle = { style: 'color:#3ba776' };
9059 const numberStyle = { style: 'color:#0b1bc9' };
9060 const stringStyle = { style: 'color:#b62e24' };
9061 const keywordStyle = { style: 'color:#9d288c' };
9062 // custom formatter for Chrome
9063 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
9064 const formatter = {
9065 header(obj) {
9066 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
9067 if (!isObject(obj)) {
9068 return null;
9069 }
9070 if (obj.__isVue) {
9071 return ['div', vueStyle, `VueInstance`];
9072 }
9073 else if (isRef(obj)) {
9074 return [
9075 'div',
9076 {},
9077 ['span', vueStyle, genRefFlag(obj)],
9078 '<',
9079 formatValue(obj.value),
9080 `>`
9081 ];
9082 }
9083 else if (isReactive(obj)) {
9084 return [
9085 'div',
9086 {},
9087 ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
9088 '<',
9089 formatValue(obj),
9090 `>${isReadonly(obj) ? ` (readonly)` : ``}`
9091 ];
9092 }
9093 else if (isReadonly(obj)) {
9094 return [
9095 'div',
9096 {},
9097 ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
9098 '<',
9099 formatValue(obj),
9100 '>'
9101 ];
9102 }
9103 return null;
9104 },
9105 hasBody(obj) {
9106 return obj && obj.__isVue;
9107 },
9108 body(obj) {
9109 if (obj && obj.__isVue) {
9110 return [
9111 'div',
9112 {},
9113 ...formatInstance(obj.$)
9114 ];
9115 }
9116 }
9117 };
9118 function formatInstance(instance) {
9119 const blocks = [];
9120 if (instance.type.props && instance.props) {
9121 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
9122 }
9123 if (instance.setupState !== EMPTY_OBJ) {
9124 blocks.push(createInstanceBlock('setup', instance.setupState));
9125 }
9126 if (instance.data !== EMPTY_OBJ) {
9127 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
9128 }
9129 const computed = extractKeys(instance, 'computed');
9130 if (computed) {
9131 blocks.push(createInstanceBlock('computed', computed));
9132 }
9133 const injected = extractKeys(instance, 'inject');
9134 if (injected) {
9135 blocks.push(createInstanceBlock('injected', injected));
9136 }
9137 blocks.push([
9138 'div',
9139 {},
9140 [
9141 'span',
9142 {
9143 style: keywordStyle.style + ';opacity:0.66'
9144 },
9145 '$ (internal): '
9146 ],
9147 ['object', { object: instance }]
9148 ]);
9149 return blocks;
9150 }
9151 function createInstanceBlock(type, target) {
9152 target = extend({}, target);
9153 if (!Object.keys(target).length) {
9154 return ['span', {}];
9155 }
9156 return [
9157 'div',
9158 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9159 [
9160 'div',
9161 {
9162 style: 'color:#476582'
9163 },
9164 type
9165 ],
9166 [
9167 'div',
9168 {
9169 style: 'padding-left:1.25em'
9170 },
9171 ...Object.keys(target).map(key => {
9172 return [
9173 'div',
9174 {},
9175 ['span', keywordStyle, key + ': '],
9176 formatValue(target[key], false)
9177 ];
9178 })
9179 ]
9180 ];
9181 }
9182 function formatValue(v, asRaw = true) {
9183 if (typeof v === 'number') {
9184 return ['span', numberStyle, v];
9185 }
9186 else if (typeof v === 'string') {
9187 return ['span', stringStyle, JSON.stringify(v)];
9188 }
9189 else if (typeof v === 'boolean') {
9190 return ['span', keywordStyle, v];
9191 }
9192 else if (isObject(v)) {
9193 return ['object', { object: asRaw ? toRaw(v) : v }];
9194 }
9195 else {
9196 return ['span', stringStyle, String(v)];
9197 }
9198 }
9199 function extractKeys(instance, type) {
9200 const Comp = instance.type;
9201 if (isFunction(Comp)) {
9202 return;
9203 }
9204 const extracted = {};
9205 for (const key in instance.ctx) {
9206 if (isKeyOfType(Comp, key, type)) {
9207 extracted[key] = instance.ctx[key];
9208 }
9209 }
9210 return extracted;
9211 }
9212 function isKeyOfType(Comp, key, type) {
9213 const opts = Comp[type];
9214 if ((isArray(opts) && opts.includes(key)) ||
9215 (isObject(opts) && key in opts)) {
9216 return true;
9217 }
9218 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9219 return true;
9220 }
9221 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9222 return true;
9223 }
9224 }
9225 function genRefFlag(v) {
9226 if (isShallow(v)) {
9227 return `ShallowRef`;
9228 }
9229 if (v.effect) {
9230 return `ComputedRef`;
9231 }
9232 return `Ref`;
9233 }
9234 if (window.devtoolsFormatters) {
9235 window.devtoolsFormatters.push(formatter);
9236 }
9237 else {
9238 window.devtoolsFormatters = [formatter];
9239 }
9240 }
9241
9242 function withMemo(memo, render, cache, index) {
9243 const cached = cache[index];
9244 if (cached && isMemoSame(cached, memo)) {
9245 return cached;
9246 }
9247 const ret = render();
9248 // shallow clone
9249 ret.memo = memo.slice();
9250 return (cache[index] = ret);
9251 }
9252 function isMemoSame(cached, memo) {
9253 const prev = cached.memo;
9254 if (prev.length != memo.length) {
9255 return false;
9256 }
9257 for (let i = 0; i < prev.length; i++) {
9258 if (hasChanged(prev[i], memo[i])) {
9259 return false;
9260 }
9261 }
9262 // make sure to let parent block track it when returning cached
9263 if (isBlockTreeEnabled > 0 && currentBlock) {
9264 currentBlock.push(cached);
9265 }
9266 return true;
9267 }
9268
9269 // Core API ------------------------------------------------------------------
9270 const version = "3.2.37";
9271 /**
9272 * SSR utils for \@vue/server-renderer. Only exposed in ssr-possible builds.
9273 * @internal
9274 */
9275 const ssrUtils = (null);
9276 /**
9277 * @internal only exposed in compat builds
9278 */
9279 const resolveFilter = null;
9280 /**
9281 * @internal only exposed in compat builds.
9282 */
9283 const compatUtils = (null);
9284
9285 const svgNS = 'http://www.w3.org/2000/svg';
9286 const doc = (typeof document !== 'undefined' ? document : null);
9287 const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
9288 const nodeOps = {
9289 insert: (child, parent, anchor) => {
9290 parent.insertBefore(child, anchor || null);
9291 },
9292 remove: child => {
9293 const parent = child.parentNode;
9294 if (parent) {
9295 parent.removeChild(child);
9296 }
9297 },
9298 createElement: (tag, isSVG, is, props) => {
9299 const el = isSVG
9300 ? doc.createElementNS(svgNS, tag)
9301 : doc.createElement(tag, is ? { is } : undefined);
9302 if (tag === 'select' && props && props.multiple != null) {
9303 el.setAttribute('multiple', props.multiple);
9304 }
9305 return el;
9306 },
9307 createText: text => doc.createTextNode(text),
9308 createComment: text => doc.createComment(text),
9309 setText: (node, text) => {
9310 node.nodeValue = text;
9311 },
9312 setElementText: (el, text) => {
9313 el.textContent = text;
9314 },
9315 parentNode: node => node.parentNode,
9316 nextSibling: node => node.nextSibling,
9317 querySelector: selector => doc.querySelector(selector),
9318 setScopeId(el, id) {
9319 el.setAttribute(id, '');
9320 },
9321 cloneNode(el) {
9322 const cloned = el.cloneNode(true);
9323 // #3072
9324 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9325 // - normally, elements using `:value` bindings will not be hoisted, but if
9326 // the bound value is a constant, e.g. `:value="true"` - they do get
9327 // hoisted.
9328 // - in production, hoisted nodes are cloned when subsequent inserts, but
9329 // cloneNode() does not copy the custom property we attached.
9330 // - This may need to account for other custom DOM properties we attach to
9331 // elements in addition to `_value` in the future.
9332 if (`_value` in el) {
9333 cloned._value = el._value;
9334 }
9335 return cloned;
9336 },
9337 // __UNSAFE__
9338 // Reason: innerHTML.
9339 // Static content here can only come from compiled templates.
9340 // As long as the user only uses trusted templates, this is safe.
9341 insertStaticContent(content, parent, anchor, isSVG, start, end) {
9342 // <parent> before | first ... last | anchor </parent>
9343 const before = anchor ? anchor.previousSibling : parent.lastChild;
9344 // #5308 can only take cached path if:
9345 // - has a single root node
9346 // - nextSibling info is still available
9347 if (start && (start === end || start.nextSibling)) {
9348 // cached
9349 while (true) {
9350 parent.insertBefore(start.cloneNode(true), anchor);
9351 if (start === end || !(start = start.nextSibling))
9352 break;
9353 }
9354 }
9355 else {
9356 // fresh insert
9357 templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9358 const template = templateContainer.content;
9359 if (isSVG) {
9360 // remove outer svg wrapper
9361 const wrapper = template.firstChild;
9362 while (wrapper.firstChild) {
9363 template.appendChild(wrapper.firstChild);
9364 }
9365 template.removeChild(wrapper);
9366 }
9367 parent.insertBefore(template, anchor);
9368 }
9369 return [
9370 // first
9371 before ? before.nextSibling : parent.firstChild,
9372 // last
9373 anchor ? anchor.previousSibling : parent.lastChild
9374 ];
9375 }
9376 };
9377
9378 // compiler should normalize class + :class bindings on the same element
9379 // into a single binding ['staticClass', dynamic]
9380 function patchClass(el, value, isSVG) {
9381 // directly setting className should be faster than setAttribute in theory
9382 // if this is an element during a transition, take the temporary transition
9383 // classes into account.
9384 const transitionClasses = el._vtc;
9385 if (transitionClasses) {
9386 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9387 }
9388 if (value == null) {
9389 el.removeAttribute('class');
9390 }
9391 else if (isSVG) {
9392 el.setAttribute('class', value);
9393 }
9394 else {
9395 el.className = value;
9396 }
9397 }
9398
9399 function patchStyle(el, prev, next) {
9400 const style = el.style;
9401 const isCssString = isString(next);
9402 if (next && !isCssString) {
9403 for (const key in next) {
9404 setStyle(style, key, next[key]);
9405 }
9406 if (prev && !isString(prev)) {
9407 for (const key in prev) {
9408 if (next[key] == null) {
9409 setStyle(style, key, '');
9410 }
9411 }
9412 }
9413 }
9414 else {
9415 const currentDisplay = style.display;
9416 if (isCssString) {
9417 if (prev !== next) {
9418 style.cssText = next;
9419 }
9420 }
9421 else if (prev) {
9422 el.removeAttribute('style');
9423 }
9424 // indicates that the `display` of the element is controlled by `v-show`,
9425 // so we always keep the current `display` value regardless of the `style`
9426 // value, thus handing over control to `v-show`.
9427 if ('_vod' in el) {
9428 style.display = currentDisplay;
9429 }
9430 }
9431 }
9432 const importantRE = /\s*!important$/;
9433 function setStyle(style, name, val) {
9434 if (isArray(val)) {
9435 val.forEach(v => setStyle(style, name, v));
9436 }
9437 else {
9438 if (val == null)
9439 val = '';
9440 if (name.startsWith('--')) {
9441 // custom property definition
9442 style.setProperty(name, val);
9443 }
9444 else {
9445 const prefixed = autoPrefix(style, name);
9446 if (importantRE.test(val)) {
9447 // !important
9448 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9449 }
9450 else {
9451 style[prefixed] = val;
9452 }
9453 }
9454 }
9455 }
9456 const prefixes = ['Webkit', 'Moz', 'ms'];
9457 const prefixCache = {};
9458 function autoPrefix(style, rawName) {
9459 const cached = prefixCache[rawName];
9460 if (cached) {
9461 return cached;
9462 }
9463 let name = camelize(rawName);
9464 if (name !== 'filter' && name in style) {
9465 return (prefixCache[rawName] = name);
9466 }
9467 name = capitalize(name);
9468 for (let i = 0; i < prefixes.length; i++) {
9469 const prefixed = prefixes[i] + name;
9470 if (prefixed in style) {
9471 return (prefixCache[rawName] = prefixed);
9472 }
9473 }
9474 return rawName;
9475 }
9476
9477 const xlinkNS = 'http://www.w3.org/1999/xlink';
9478 function patchAttr(el, key, value, isSVG, instance) {
9479 if (isSVG && key.startsWith('xlink:')) {
9480 if (value == null) {
9481 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9482 }
9483 else {
9484 el.setAttributeNS(xlinkNS, key, value);
9485 }
9486 }
9487 else {
9488 // note we are only checking boolean attributes that don't have a
9489 // corresponding dom prop of the same name here.
9490 const isBoolean = isSpecialBooleanAttr(key);
9491 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9492 el.removeAttribute(key);
9493 }
9494 else {
9495 el.setAttribute(key, isBoolean ? '' : value);
9496 }
9497 }
9498 }
9499
9500 // __UNSAFE__
9501 // functions. The user is responsible for using them with only trusted content.
9502 function patchDOMProp(el, key, value,
9503 // the following args are passed only due to potential innerHTML/textContent
9504 // overriding existing VNodes, in which case the old tree must be properly
9505 // unmounted.
9506 prevChildren, parentComponent, parentSuspense, unmountChildren) {
9507 if (key === 'innerHTML' || key === 'textContent') {
9508 if (prevChildren) {
9509 unmountChildren(prevChildren, parentComponent, parentSuspense);
9510 }
9511 el[key] = value == null ? '' : value;
9512 return;
9513 }
9514 if (key === 'value' &&
9515 el.tagName !== 'PROGRESS' &&
9516 // custom elements may use _value internally
9517 !el.tagName.includes('-')) {
9518 // store value as _value as well since
9519 // non-string values will be stringified.
9520 el._value = value;
9521 const newValue = value == null ? '' : value;
9522 if (el.value !== newValue ||
9523 // #4956: always set for OPTION elements because its value falls back to
9524 // textContent if no value attribute is present. And setting .value for
9525 // OPTION has no side effect
9526 el.tagName === 'OPTION') {
9527 el.value = newValue;
9528 }
9529 if (value == null) {
9530 el.removeAttribute(key);
9531 }
9532 return;
9533 }
9534 let needRemove = false;
9535 if (value === '' || value == null) {
9536 const type = typeof el[key];
9537 if (type === 'boolean') {
9538 // e.g. <select multiple> compiles to { multiple: '' }
9539 value = includeBooleanAttr(value);
9540 }
9541 else if (value == null && type === 'string') {
9542 // e.g. <div :id="null">
9543 value = '';
9544 needRemove = true;
9545 }
9546 else if (type === 'number') {
9547 // e.g. <img :width="null">
9548 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9549 value = 0;
9550 needRemove = true;
9551 }
9552 }
9553 // some properties perform value validation and throw,
9554 // some properties has getter, no setter, will error in 'use strict'
9555 // eg. <select :type="null"></select> <select :willValidate="null"></select>
9556 try {
9557 el[key] = value;
9558 }
9559 catch (e) {
9560 {
9561 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9562 `value ${value} is invalid.`, e);
9563 }
9564 }
9565 needRemove && el.removeAttribute(key);
9566 }
9567
9568 // Async edge case fix requires storing an event listener's attach timestamp.
9569 const [_getNow, skipTimestampCheck] = /*#__PURE__*/ (() => {
9570 let _getNow = Date.now;
9571 let skipTimestampCheck = false;
9572 if (typeof window !== 'undefined') {
9573 // Determine what event timestamp the browser is using. Annoyingly, the
9574 // timestamp can either be hi-res (relative to page load) or low-res
9575 // (relative to UNIX epoch), so in order to compare time we have to use the
9576 // same timestamp type when saving the flush timestamp.
9577 if (Date.now() > document.createEvent('Event').timeStamp) {
9578 // if the low-res timestamp which is bigger than the event timestamp
9579 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9580 // and we need to use the hi-res version for event listeners as well.
9581 _getNow = performance.now.bind(performance);
9582 }
9583 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9584 // and does not fire microtasks in between event propagation, so safe to exclude.
9585 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9586 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9587 }
9588 return [_getNow, skipTimestampCheck];
9589 })();
9590 // To avoid the overhead of repeatedly calling performance.now(), we cache
9591 // and use the same timestamp for all event listeners attached in the same tick.
9592 let cachedNow = 0;
9593 const p = /*#__PURE__*/ Promise.resolve();
9594 const reset = () => {
9595 cachedNow = 0;
9596 };
9597 const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9598 function addEventListener(el, event, handler, options) {
9599 el.addEventListener(event, handler, options);
9600 }
9601 function removeEventListener(el, event, handler, options) {
9602 el.removeEventListener(event, handler, options);
9603 }
9604 function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9605 // vei = vue event invokers
9606 const invokers = el._vei || (el._vei = {});
9607 const existingInvoker = invokers[rawName];
9608 if (nextValue && existingInvoker) {
9609 // patch
9610 existingInvoker.value = nextValue;
9611 }
9612 else {
9613 const [name, options] = parseName(rawName);
9614 if (nextValue) {
9615 // add
9616 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9617 addEventListener(el, name, invoker, options);
9618 }
9619 else if (existingInvoker) {
9620 // remove
9621 removeEventListener(el, name, existingInvoker, options);
9622 invokers[rawName] = undefined;
9623 }
9624 }
9625 }
9626 const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9627 function parseName(name) {
9628 let options;
9629 if (optionsModifierRE.test(name)) {
9630 options = {};
9631 let m;
9632 while ((m = name.match(optionsModifierRE))) {
9633 name = name.slice(0, name.length - m[0].length);
9634 options[m[0].toLowerCase()] = true;
9635 }
9636 }
9637 return [hyphenate(name.slice(2)), options];
9638 }
9639 function createInvoker(initialValue, instance) {
9640 const invoker = (e) => {
9641 // async edge case #6566: inner click event triggers patch, event handler
9642 // attached to outer element during patch, and triggered again. This
9643 // happens because browsers fire microtask ticks between event propagation.
9644 // the solution is simple: we save the timestamp when a handler is attached,
9645 // and the handler would only fire if the event passed to it was fired
9646 // AFTER it was attached.
9647 const timeStamp = e.timeStamp || _getNow();
9648 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9649 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9650 }
9651 };
9652 invoker.value = initialValue;
9653 invoker.attached = getNow();
9654 return invoker;
9655 }
9656 function patchStopImmediatePropagation(e, value) {
9657 if (isArray(value)) {
9658 const originalStop = e.stopImmediatePropagation;
9659 e.stopImmediatePropagation = () => {
9660 originalStop.call(e);
9661 e._stopped = true;
9662 };
9663 return value.map(fn => (e) => !e._stopped && fn && fn(e));
9664 }
9665 else {
9666 return value;
9667 }
9668 }
9669
9670 const nativeOnRE = /^on[a-z]/;
9671 const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9672 if (key === 'class') {
9673 patchClass(el, nextValue, isSVG);
9674 }
9675 else if (key === 'style') {
9676 patchStyle(el, prevValue, nextValue);
9677 }
9678 else if (isOn(key)) {
9679 // ignore v-model listeners
9680 if (!isModelListener(key)) {
9681 patchEvent(el, key, prevValue, nextValue, parentComponent);
9682 }
9683 }
9684 else if (key[0] === '.'
9685 ? ((key = key.slice(1)), true)
9686 : key[0] === '^'
9687 ? ((key = key.slice(1)), false)
9688 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9689 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9690 }
9691 else {
9692 // special case for <input v-model type="checkbox"> with
9693 // :true-value & :false-value
9694 // store value as dom properties since non-string values will be
9695 // stringified.
9696 if (key === 'true-value') {
9697 el._trueValue = nextValue;
9698 }
9699 else if (key === 'false-value') {
9700 el._falseValue = nextValue;
9701 }
9702 patchAttr(el, key, nextValue, isSVG);
9703 }
9704 };
9705 function shouldSetAsProp(el, key, value, isSVG) {
9706 if (isSVG) {
9707 // most keys must be set as attribute on svg elements to work
9708 // ...except innerHTML & textContent
9709 if (key === 'innerHTML' || key === 'textContent') {
9710 return true;
9711 }
9712 // or native onclick with function values
9713 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9714 return true;
9715 }
9716 return false;
9717 }
9718 // these are enumerated attrs, however their corresponding DOM properties
9719 // are actually booleans - this leads to setting it with a string "false"
9720 // value leading it to be coerced to `true`, so we need to always treat
9721 // them as attributes.
9722 // Note that `contentEditable` doesn't have this problem: its DOM
9723 // property is also enumerated string values.
9724 if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
9725 return false;
9726 }
9727 // #1787, #2840 form property on form elements is readonly and must be set as
9728 // attribute.
9729 if (key === 'form') {
9730 return false;
9731 }
9732 // #1526 <input list> must be set as attribute
9733 if (key === 'list' && el.tagName === 'INPUT') {
9734 return false;
9735 }
9736 // #2766 <textarea type> must be set as attribute
9737 if (key === 'type' && el.tagName === 'TEXTAREA') {
9738 return false;
9739 }
9740 // native onclick with string value, must be set as attribute
9741 if (nativeOnRE.test(key) && isString(value)) {
9742 return false;
9743 }
9744 return key in el;
9745 }
9746
9747 function defineCustomElement(options, hydrate) {
9748 const Comp = defineComponent(options);
9749 class VueCustomElement extends VueElement {
9750 constructor(initialProps) {
9751 super(Comp, initialProps, hydrate);
9752 }
9753 }
9754 VueCustomElement.def = Comp;
9755 return VueCustomElement;
9756 }
9757 const defineSSRCustomElement = ((options) => {
9758 // @ts-ignore
9759 return defineCustomElement(options, hydrate);
9760 });
9761 const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9762 });
9763 class VueElement extends BaseClass {
9764 constructor(_def, _props = {}, hydrate) {
9765 super();
9766 this._def = _def;
9767 this._props = _props;
9768 /**
9769 * @internal
9770 */
9771 this._instance = null;
9772 this._connected = false;
9773 this._resolved = false;
9774 this._numberProps = null;
9775 if (this.shadowRoot && hydrate) {
9776 hydrate(this._createVNode(), this.shadowRoot);
9777 }
9778 else {
9779 if (this.shadowRoot) {
9780 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9781 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9782 }
9783 this.attachShadow({ mode: 'open' });
9784 }
9785 }
9786 connectedCallback() {
9787 this._connected = true;
9788 if (!this._instance) {
9789 this._resolveDef();
9790 }
9791 }
9792 disconnectedCallback() {
9793 this._connected = false;
9794 nextTick(() => {
9795 if (!this._connected) {
9796 render(null, this.shadowRoot);
9797 this._instance = null;
9798 }
9799 });
9800 }
9801 /**
9802 * resolve inner component definition (handle possible async component)
9803 */
9804 _resolveDef() {
9805 if (this._resolved) {
9806 return;
9807 }
9808 this._resolved = true;
9809 // set initial attrs
9810 for (let i = 0; i < this.attributes.length; i++) {
9811 this._setAttr(this.attributes[i].name);
9812 }
9813 // watch future attr changes
9814 new MutationObserver(mutations => {
9815 for (const m of mutations) {
9816 this._setAttr(m.attributeName);
9817 }
9818 }).observe(this, { attributes: true });
9819 const resolve = (def) => {
9820 const { props, styles } = def;
9821 const hasOptions = !isArray(props);
9822 const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
9823 // cast Number-type props set before resolve
9824 let numberProps;
9825 if (hasOptions) {
9826 for (const key in this._props) {
9827 const opt = props[key];
9828 if (opt === Number || (opt && opt.type === Number)) {
9829 this._props[key] = toNumber(this._props[key]);
9830 (numberProps || (numberProps = Object.create(null)))[key] = true;
9831 }
9832 }
9833 }
9834 this._numberProps = numberProps;
9835 // check if there are props set pre-upgrade or connect
9836 for (const key of Object.keys(this)) {
9837 if (key[0] !== '_') {
9838 this._setProp(key, this[key], true, false);
9839 }
9840 }
9841 // defining getter/setters on prototype
9842 for (const key of rawKeys.map(camelize)) {
9843 Object.defineProperty(this, key, {
9844 get() {
9845 return this._getProp(key);
9846 },
9847 set(val) {
9848 this._setProp(key, val);
9849 }
9850 });
9851 }
9852 // apply CSS
9853 this._applyStyles(styles);
9854 // initial render
9855 this._update();
9856 };
9857 const asyncDef = this._def.__asyncLoader;
9858 if (asyncDef) {
9859 asyncDef().then(resolve);
9860 }
9861 else {
9862 resolve(this._def);
9863 }
9864 }
9865 _setAttr(key) {
9866 let value = this.getAttribute(key);
9867 if (this._numberProps && this._numberProps[key]) {
9868 value = toNumber(value);
9869 }
9870 this._setProp(camelize(key), value, false);
9871 }
9872 /**
9873 * @internal
9874 */
9875 _getProp(key) {
9876 return this._props[key];
9877 }
9878 /**
9879 * @internal
9880 */
9881 _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
9882 if (val !== this._props[key]) {
9883 this._props[key] = val;
9884 if (shouldUpdate && this._instance) {
9885 this._update();
9886 }
9887 // reflect
9888 if (shouldReflect) {
9889 if (val === true) {
9890 this.setAttribute(hyphenate(key), '');
9891 }
9892 else if (typeof val === 'string' || typeof val === 'number') {
9893 this.setAttribute(hyphenate(key), val + '');
9894 }
9895 else if (!val) {
9896 this.removeAttribute(hyphenate(key));
9897 }
9898 }
9899 }
9900 }
9901 _update() {
9902 render(this._createVNode(), this.shadowRoot);
9903 }
9904 _createVNode() {
9905 const vnode = createVNode(this._def, extend({}, this._props));
9906 if (!this._instance) {
9907 vnode.ce = instance => {
9908 this._instance = instance;
9909 instance.isCE = true;
9910 // HMR
9911 {
9912 instance.ceReload = newStyles => {
9913 // always reset styles
9914 if (this._styles) {
9915 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9916 this._styles.length = 0;
9917 }
9918 this._applyStyles(newStyles);
9919 // if this is an async component, ceReload is called from the inner
9920 // component so no need to reload the async wrapper
9921 if (!this._def.__asyncLoader) {
9922 // reload
9923 this._instance = null;
9924 this._update();
9925 }
9926 };
9927 }
9928 // intercept emit
9929 instance.emit = (event, ...args) => {
9930 this.dispatchEvent(new CustomEvent(event, {
9931 detail: args
9932 }));
9933 };
9934 // locate nearest Vue custom element parent for provide/inject
9935 let parent = this;
9936 while ((parent =
9937 parent && (parent.parentNode || parent.host))) {
9938 if (parent instanceof VueElement) {
9939 instance.parent = parent._instance;
9940 break;
9941 }
9942 }
9943 };
9944 }
9945 return vnode;
9946 }
9947 _applyStyles(styles) {
9948 if (styles) {
9949 styles.forEach(css => {
9950 const s = document.createElement('style');
9951 s.textContent = css;
9952 this.shadowRoot.appendChild(s);
9953 // record for HMR
9954 {
9955 (this._styles || (this._styles = [])).push(s);
9956 }
9957 });
9958 }
9959 }
9960 }
9961
9962 function useCssModule(name = '$style') {
9963 /* istanbul ignore else */
9964 {
9965 {
9966 warn$1(`useCssModule() is not supported in the global build.`);
9967 }
9968 return EMPTY_OBJ;
9969 }
9970 }
9971
9972 /**
9973 * Runtime helper for SFC's CSS variable injection feature.
9974 * @private
9975 */
9976 function useCssVars(getter) {
9977 const instance = getCurrentInstance();
9978 /* istanbul ignore next */
9979 if (!instance) {
9980 warn$1(`useCssVars is called without current active component instance.`);
9981 return;
9982 }
9983 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9984 watchPostEffect(setVars);
9985 onMounted(() => {
9986 const ob = new MutationObserver(setVars);
9987 ob.observe(instance.subTree.el.parentNode, { childList: true });
9988 onUnmounted(() => ob.disconnect());
9989 });
9990 }
9991 function setVarsOnVNode(vnode, vars) {
9992 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9993 const suspense = vnode.suspense;
9994 vnode = suspense.activeBranch;
9995 if (suspense.pendingBranch && !suspense.isHydrating) {
9996 suspense.effects.push(() => {
9997 setVarsOnVNode(suspense.activeBranch, vars);
9998 });
9999 }
10000 }
10001 // drill down HOCs until it's a non-component vnode
10002 while (vnode.component) {
10003 vnode = vnode.component.subTree;
10004 }
10005 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
10006 setVarsOnNode(vnode.el, vars);
10007 }
10008 else if (vnode.type === Fragment) {
10009 vnode.children.forEach(c => setVarsOnVNode(c, vars));
10010 }
10011 else if (vnode.type === Static) {
10012 let { el, anchor } = vnode;
10013 while (el) {
10014 setVarsOnNode(el, vars);
10015 if (el === anchor)
10016 break;
10017 el = el.nextSibling;
10018 }
10019 }
10020 }
10021 function setVarsOnNode(el, vars) {
10022 if (el.nodeType === 1) {
10023 const style = el.style;
10024 for (const key in vars) {
10025 style.setProperty(`--${key}`, vars[key]);
10026 }
10027 }
10028 }
10029
10030 const TRANSITION = 'transition';
10031 const ANIMATION = 'animation';
10032 // DOM Transition is a higher-order-component based on the platform-agnostic
10033 // base Transition component, with DOM-specific logic.
10034 const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
10035 Transition.displayName = 'Transition';
10036 const DOMTransitionPropsValidators = {
10037 name: String,
10038 type: String,
10039 css: {
10040 type: Boolean,
10041 default: true
10042 },
10043 duration: [String, Number, Object],
10044 enterFromClass: String,
10045 enterActiveClass: String,
10046 enterToClass: String,
10047 appearFromClass: String,
10048 appearActiveClass: String,
10049 appearToClass: String,
10050 leaveFromClass: String,
10051 leaveActiveClass: String,
10052 leaveToClass: String
10053 };
10054 const TransitionPropsValidators = (Transition.props =
10055 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
10056 /**
10057 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
10058 * with custom HOCs.
10059 */
10060 const callHook$1 = (hook, args = []) => {
10061 if (isArray(hook)) {
10062 hook.forEach(h => h(...args));
10063 }
10064 else if (hook) {
10065 hook(...args);
10066 }
10067 };
10068 /**
10069 * Check if a hook expects a callback (2nd arg), which means the user
10070 * intends to explicitly control the end of the transition.
10071 */
10072 const hasExplicitCallback = (hook) => {
10073 return hook
10074 ? isArray(hook)
10075 ? hook.some(h => h.length > 1)
10076 : hook.length > 1
10077 : false;
10078 };
10079 function resolveTransitionProps(rawProps) {
10080 const baseProps = {};
10081 for (const key in rawProps) {
10082 if (!(key in DOMTransitionPropsValidators)) {
10083 baseProps[key] = rawProps[key];
10084 }
10085 }
10086 if (rawProps.css === false) {
10087 return baseProps;
10088 }
10089 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;
10090 const durations = normalizeDuration(duration);
10091 const enterDuration = durations && durations[0];
10092 const leaveDuration = durations && durations[1];
10093 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
10094 const finishEnter = (el, isAppear, done) => {
10095 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
10096 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
10097 done && done();
10098 };
10099 const finishLeave = (el, done) => {
10100 el._isLeaving = false;
10101 removeTransitionClass(el, leaveFromClass);
10102 removeTransitionClass(el, leaveToClass);
10103 removeTransitionClass(el, leaveActiveClass);
10104 done && done();
10105 };
10106 const makeEnterHook = (isAppear) => {
10107 return (el, done) => {
10108 const hook = isAppear ? onAppear : onEnter;
10109 const resolve = () => finishEnter(el, isAppear, done);
10110 callHook$1(hook, [el, resolve]);
10111 nextFrame(() => {
10112 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
10113 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
10114 if (!hasExplicitCallback(hook)) {
10115 whenTransitionEnds(el, type, enterDuration, resolve);
10116 }
10117 });
10118 };
10119 };
10120 return extend(baseProps, {
10121 onBeforeEnter(el) {
10122 callHook$1(onBeforeEnter, [el]);
10123 addTransitionClass(el, enterFromClass);
10124 addTransitionClass(el, enterActiveClass);
10125 },
10126 onBeforeAppear(el) {
10127 callHook$1(onBeforeAppear, [el]);
10128 addTransitionClass(el, appearFromClass);
10129 addTransitionClass(el, appearActiveClass);
10130 },
10131 onEnter: makeEnterHook(false),
10132 onAppear: makeEnterHook(true),
10133 onLeave(el, done) {
10134 el._isLeaving = true;
10135 const resolve = () => finishLeave(el, done);
10136 addTransitionClass(el, leaveFromClass);
10137 // force reflow so *-leave-from classes immediately take effect (#2593)
10138 forceReflow();
10139 addTransitionClass(el, leaveActiveClass);
10140 nextFrame(() => {
10141 if (!el._isLeaving) {
10142 // cancelled
10143 return;
10144 }
10145 removeTransitionClass(el, leaveFromClass);
10146 addTransitionClass(el, leaveToClass);
10147 if (!hasExplicitCallback(onLeave)) {
10148 whenTransitionEnds(el, type, leaveDuration, resolve);
10149 }
10150 });
10151 callHook$1(onLeave, [el, resolve]);
10152 },
10153 onEnterCancelled(el) {
10154 finishEnter(el, false);
10155 callHook$1(onEnterCancelled, [el]);
10156 },
10157 onAppearCancelled(el) {
10158 finishEnter(el, true);
10159 callHook$1(onAppearCancelled, [el]);
10160 },
10161 onLeaveCancelled(el) {
10162 finishLeave(el);
10163 callHook$1(onLeaveCancelled, [el]);
10164 }
10165 });
10166 }
10167 function normalizeDuration(duration) {
10168 if (duration == null) {
10169 return null;
10170 }
10171 else if (isObject(duration)) {
10172 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10173 }
10174 else {
10175 const n = NumberOf(duration);
10176 return [n, n];
10177 }
10178 }
10179 function NumberOf(val) {
10180 const res = toNumber(val);
10181 validateDuration(res);
10182 return res;
10183 }
10184 function validateDuration(val) {
10185 if (typeof val !== 'number') {
10186 warn$1(`<transition> explicit duration is not a valid number - ` +
10187 `got ${JSON.stringify(val)}.`);
10188 }
10189 else if (isNaN(val)) {
10190 warn$1(`<transition> explicit duration is NaN - ` +
10191 'the duration expression might be incorrect.');
10192 }
10193 }
10194 function addTransitionClass(el, cls) {
10195 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10196 (el._vtc ||
10197 (el._vtc = new Set())).add(cls);
10198 }
10199 function removeTransitionClass(el, cls) {
10200 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10201 const { _vtc } = el;
10202 if (_vtc) {
10203 _vtc.delete(cls);
10204 if (!_vtc.size) {
10205 el._vtc = undefined;
10206 }
10207 }
10208 }
10209 function nextFrame(cb) {
10210 requestAnimationFrame(() => {
10211 requestAnimationFrame(cb);
10212 });
10213 }
10214 let endId = 0;
10215 function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10216 const id = (el._endId = ++endId);
10217 const resolveIfNotStale = () => {
10218 if (id === el._endId) {
10219 resolve();
10220 }
10221 };
10222 if (explicitTimeout) {
10223 return setTimeout(resolveIfNotStale, explicitTimeout);
10224 }
10225 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10226 if (!type) {
10227 return resolve();
10228 }
10229 const endEvent = type + 'end';
10230 let ended = 0;
10231 const end = () => {
10232 el.removeEventListener(endEvent, onEnd);
10233 resolveIfNotStale();
10234 };
10235 const onEnd = (e) => {
10236 if (e.target === el && ++ended >= propCount) {
10237 end();
10238 }
10239 };
10240 setTimeout(() => {
10241 if (ended < propCount) {
10242 end();
10243 }
10244 }, timeout + 1);
10245 el.addEventListener(endEvent, onEnd);
10246 }
10247 function getTransitionInfo(el, expectedType) {
10248 const styles = window.getComputedStyle(el);
10249 // JSDOM may return undefined for transition properties
10250 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10251 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10252 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10253 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10254 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10255 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10256 const animationTimeout = getTimeout(animationDelays, animationDurations);
10257 let type = null;
10258 let timeout = 0;
10259 let propCount = 0;
10260 /* istanbul ignore if */
10261 if (expectedType === TRANSITION) {
10262 if (transitionTimeout > 0) {
10263 type = TRANSITION;
10264 timeout = transitionTimeout;
10265 propCount = transitionDurations.length;
10266 }
10267 }
10268 else if (expectedType === ANIMATION) {
10269 if (animationTimeout > 0) {
10270 type = ANIMATION;
10271 timeout = animationTimeout;
10272 propCount = animationDurations.length;
10273 }
10274 }
10275 else {
10276 timeout = Math.max(transitionTimeout, animationTimeout);
10277 type =
10278 timeout > 0
10279 ? transitionTimeout > animationTimeout
10280 ? TRANSITION
10281 : ANIMATION
10282 : null;
10283 propCount = type
10284 ? type === TRANSITION
10285 ? transitionDurations.length
10286 : animationDurations.length
10287 : 0;
10288 }
10289 const hasTransform = type === TRANSITION &&
10290 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10291 return {
10292 type,
10293 timeout,
10294 propCount,
10295 hasTransform
10296 };
10297 }
10298 function getTimeout(delays, durations) {
10299 while (delays.length < durations.length) {
10300 delays = delays.concat(delays);
10301 }
10302 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10303 }
10304 // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10305 // numbers in a locale-dependent way, using a comma instead of a dot.
10306 // If comma is not replaced with a dot, the input will be rounded down
10307 // (i.e. acting as a floor function) causing unexpected behaviors
10308 function toMs(s) {
10309 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10310 }
10311 // synchronously force layout to put elements into a certain state
10312 function forceReflow() {
10313 return document.body.offsetHeight;
10314 }
10315
10316 const positionMap = new WeakMap();
10317 const newPositionMap = new WeakMap();
10318 const TransitionGroupImpl = {
10319 name: 'TransitionGroup',
10320 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10321 tag: String,
10322 moveClass: String
10323 }),
10324 setup(props, { slots }) {
10325 const instance = getCurrentInstance();
10326 const state = useTransitionState();
10327 let prevChildren;
10328 let children;
10329 onUpdated(() => {
10330 // children is guaranteed to exist after initial render
10331 if (!prevChildren.length) {
10332 return;
10333 }
10334 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10335 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10336 return;
10337 }
10338 // we divide the work into three loops to avoid mixing DOM reads and writes
10339 // in each iteration - which helps prevent layout thrashing.
10340 prevChildren.forEach(callPendingCbs);
10341 prevChildren.forEach(recordPosition);
10342 const movedChildren = prevChildren.filter(applyTranslation);
10343 // force reflow to put everything in position
10344 forceReflow();
10345 movedChildren.forEach(c => {
10346 const el = c.el;
10347 const style = el.style;
10348 addTransitionClass(el, moveClass);
10349 style.transform = style.webkitTransform = style.transitionDuration = '';
10350 const cb = (el._moveCb = (e) => {
10351 if (e && e.target !== el) {
10352 return;
10353 }
10354 if (!e || /transform$/.test(e.propertyName)) {
10355 el.removeEventListener('transitionend', cb);
10356 el._moveCb = null;
10357 removeTransitionClass(el, moveClass);
10358 }
10359 });
10360 el.addEventListener('transitionend', cb);
10361 });
10362 });
10363 return () => {
10364 const rawProps = toRaw(props);
10365 const cssTransitionProps = resolveTransitionProps(rawProps);
10366 let tag = rawProps.tag || Fragment;
10367 prevChildren = children;
10368 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10369 for (let i = 0; i < children.length; i++) {
10370 const child = children[i];
10371 if (child.key != null) {
10372 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10373 }
10374 else {
10375 warn$1(`<TransitionGroup> children must be keyed.`);
10376 }
10377 }
10378 if (prevChildren) {
10379 for (let i = 0; i < prevChildren.length; i++) {
10380 const child = prevChildren[i];
10381 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10382 positionMap.set(child, child.el.getBoundingClientRect());
10383 }
10384 }
10385 return createVNode(tag, null, children);
10386 };
10387 }
10388 };
10389 const TransitionGroup = TransitionGroupImpl;
10390 function callPendingCbs(c) {
10391 const el = c.el;
10392 if (el._moveCb) {
10393 el._moveCb();
10394 }
10395 if (el._enterCb) {
10396 el._enterCb();
10397 }
10398 }
10399 function recordPosition(c) {
10400 newPositionMap.set(c, c.el.getBoundingClientRect());
10401 }
10402 function applyTranslation(c) {
10403 const oldPos = positionMap.get(c);
10404 const newPos = newPositionMap.get(c);
10405 const dx = oldPos.left - newPos.left;
10406 const dy = oldPos.top - newPos.top;
10407 if (dx || dy) {
10408 const s = c.el.style;
10409 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10410 s.transitionDuration = '0s';
10411 return c;
10412 }
10413 }
10414 function hasCSSTransform(el, root, moveClass) {
10415 // Detect whether an element with the move class applied has
10416 // CSS transitions. Since the element may be inside an entering
10417 // transition at this very moment, we make a clone of it and remove
10418 // all other transition classes applied to ensure only the move class
10419 // is applied.
10420 const clone = el.cloneNode();
10421 if (el._vtc) {
10422 el._vtc.forEach(cls => {
10423 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10424 });
10425 }
10426 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10427 clone.style.display = 'none';
10428 const container = (root.nodeType === 1 ? root : root.parentNode);
10429 container.appendChild(clone);
10430 const { hasTransform } = getTransitionInfo(clone);
10431 container.removeChild(clone);
10432 return hasTransform;
10433 }
10434
10435 const getModelAssigner = (vnode) => {
10436 const fn = vnode.props['onUpdate:modelValue'] ||
10437 (false );
10438 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10439 };
10440 function onCompositionStart(e) {
10441 e.target.composing = true;
10442 }
10443 function onCompositionEnd(e) {
10444 const target = e.target;
10445 if (target.composing) {
10446 target.composing = false;
10447 target.dispatchEvent(new Event('input'));
10448 }
10449 }
10450 // We are exporting the v-model runtime directly as vnode hooks so that it can
10451 // be tree-shaken in case v-model is never used.
10452 const vModelText = {
10453 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10454 el._assign = getModelAssigner(vnode);
10455 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10456 addEventListener(el, lazy ? 'change' : 'input', e => {
10457 if (e.target.composing)
10458 return;
10459 let domValue = el.value;
10460 if (trim) {
10461 domValue = domValue.trim();
10462 }
10463 if (castToNumber) {
10464 domValue = toNumber(domValue);
10465 }
10466 el._assign(domValue);
10467 });
10468 if (trim) {
10469 addEventListener(el, 'change', () => {
10470 el.value = el.value.trim();
10471 });
10472 }
10473 if (!lazy) {
10474 addEventListener(el, 'compositionstart', onCompositionStart);
10475 addEventListener(el, 'compositionend', onCompositionEnd);
10476 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10477 // switching focus before confirming composition choice
10478 // this also fixes the issue where some browsers e.g. iOS Chrome
10479 // fires "change" instead of "input" on autocomplete.
10480 addEventListener(el, 'change', onCompositionEnd);
10481 }
10482 },
10483 // set value on mounted so it's after min/max for type="range"
10484 mounted(el, { value }) {
10485 el.value = value == null ? '' : value;
10486 },
10487 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10488 el._assign = getModelAssigner(vnode);
10489 // avoid clearing unresolved text. #2302
10490 if (el.composing)
10491 return;
10492 if (document.activeElement === el && el.type !== 'range') {
10493 if (lazy) {
10494 return;
10495 }
10496 if (trim && el.value.trim() === value) {
10497 return;
10498 }
10499 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10500 return;
10501 }
10502 }
10503 const newValue = value == null ? '' : value;
10504 if (el.value !== newValue) {
10505 el.value = newValue;
10506 }
10507 }
10508 };
10509 const vModelCheckbox = {
10510 // #4096 array checkboxes need to be deep traversed
10511 deep: true,
10512 created(el, _, vnode) {
10513 el._assign = getModelAssigner(vnode);
10514 addEventListener(el, 'change', () => {
10515 const modelValue = el._modelValue;
10516 const elementValue = getValue(el);
10517 const checked = el.checked;
10518 const assign = el._assign;
10519 if (isArray(modelValue)) {
10520 const index = looseIndexOf(modelValue, elementValue);
10521 const found = index !== -1;
10522 if (checked && !found) {
10523 assign(modelValue.concat(elementValue));
10524 }
10525 else if (!checked && found) {
10526 const filtered = [...modelValue];
10527 filtered.splice(index, 1);
10528 assign(filtered);
10529 }
10530 }
10531 else if (isSet(modelValue)) {
10532 const cloned = new Set(modelValue);
10533 if (checked) {
10534 cloned.add(elementValue);
10535 }
10536 else {
10537 cloned.delete(elementValue);
10538 }
10539 assign(cloned);
10540 }
10541 else {
10542 assign(getCheckboxValue(el, checked));
10543 }
10544 });
10545 },
10546 // set initial checked on mount to wait for true-value/false-value
10547 mounted: setChecked,
10548 beforeUpdate(el, binding, vnode) {
10549 el._assign = getModelAssigner(vnode);
10550 setChecked(el, binding, vnode);
10551 }
10552 };
10553 function setChecked(el, { value, oldValue }, vnode) {
10554 el._modelValue = value;
10555 if (isArray(value)) {
10556 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10557 }
10558 else if (isSet(value)) {
10559 el.checked = value.has(vnode.props.value);
10560 }
10561 else if (value !== oldValue) {
10562 el.checked = looseEqual(value, getCheckboxValue(el, true));
10563 }
10564 }
10565 const vModelRadio = {
10566 created(el, { value }, vnode) {
10567 el.checked = looseEqual(value, vnode.props.value);
10568 el._assign = getModelAssigner(vnode);
10569 addEventListener(el, 'change', () => {
10570 el._assign(getValue(el));
10571 });
10572 },
10573 beforeUpdate(el, { value, oldValue }, vnode) {
10574 el._assign = getModelAssigner(vnode);
10575 if (value !== oldValue) {
10576 el.checked = looseEqual(value, vnode.props.value);
10577 }
10578 }
10579 };
10580 const vModelSelect = {
10581 // <select multiple> value need to be deep traversed
10582 deep: true,
10583 created(el, { value, modifiers: { number } }, vnode) {
10584 const isSetModel = isSet(value);
10585 addEventListener(el, 'change', () => {
10586 const selectedVal = Array.prototype.filter
10587 .call(el.options, (o) => o.selected)
10588 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10589 el._assign(el.multiple
10590 ? isSetModel
10591 ? new Set(selectedVal)
10592 : selectedVal
10593 : selectedVal[0]);
10594 });
10595 el._assign = getModelAssigner(vnode);
10596 },
10597 // set value in mounted & updated because <select> relies on its children
10598 // <option>s.
10599 mounted(el, { value }) {
10600 setSelected(el, value);
10601 },
10602 beforeUpdate(el, _binding, vnode) {
10603 el._assign = getModelAssigner(vnode);
10604 },
10605 updated(el, { value }) {
10606 setSelected(el, value);
10607 }
10608 };
10609 function setSelected(el, value) {
10610 const isMultiple = el.multiple;
10611 if (isMultiple && !isArray(value) && !isSet(value)) {
10612 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10613 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10614 return;
10615 }
10616 for (let i = 0, l = el.options.length; i < l; i++) {
10617 const option = el.options[i];
10618 const optionValue = getValue(option);
10619 if (isMultiple) {
10620 if (isArray(value)) {
10621 option.selected = looseIndexOf(value, optionValue) > -1;
10622 }
10623 else {
10624 option.selected = value.has(optionValue);
10625 }
10626 }
10627 else {
10628 if (looseEqual(getValue(option), value)) {
10629 if (el.selectedIndex !== i)
10630 el.selectedIndex = i;
10631 return;
10632 }
10633 }
10634 }
10635 if (!isMultiple && el.selectedIndex !== -1) {
10636 el.selectedIndex = -1;
10637 }
10638 }
10639 // retrieve raw value set via :value bindings
10640 function getValue(el) {
10641 return '_value' in el ? el._value : el.value;
10642 }
10643 // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10644 function getCheckboxValue(el, checked) {
10645 const key = checked ? '_trueValue' : '_falseValue';
10646 return key in el ? el[key] : checked;
10647 }
10648 const vModelDynamic = {
10649 created(el, binding, vnode) {
10650 callModelHook(el, binding, vnode, null, 'created');
10651 },
10652 mounted(el, binding, vnode) {
10653 callModelHook(el, binding, vnode, null, 'mounted');
10654 },
10655 beforeUpdate(el, binding, vnode, prevVNode) {
10656 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10657 },
10658 updated(el, binding, vnode, prevVNode) {
10659 callModelHook(el, binding, vnode, prevVNode, 'updated');
10660 }
10661 };
10662 function resolveDynamicModel(tagName, type) {
10663 switch (tagName) {
10664 case 'SELECT':
10665 return vModelSelect;
10666 case 'TEXTAREA':
10667 return vModelText;
10668 default:
10669 switch (type) {
10670 case 'checkbox':
10671 return vModelCheckbox;
10672 case 'radio':
10673 return vModelRadio;
10674 default:
10675 return vModelText;
10676 }
10677 }
10678 }
10679 function callModelHook(el, binding, vnode, prevVNode, hook) {
10680 const modelToUse = resolveDynamicModel(el.tagName, vnode.props && vnode.props.type);
10681 const fn = modelToUse[hook];
10682 fn && fn(el, binding, vnode, prevVNode);
10683 }
10684
10685 const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10686 const modifierGuards = {
10687 stop: e => e.stopPropagation(),
10688 prevent: e => e.preventDefault(),
10689 self: e => e.target !== e.currentTarget,
10690 ctrl: e => !e.ctrlKey,
10691 shift: e => !e.shiftKey,
10692 alt: e => !e.altKey,
10693 meta: e => !e.metaKey,
10694 left: e => 'button' in e && e.button !== 0,
10695 middle: e => 'button' in e && e.button !== 1,
10696 right: e => 'button' in e && e.button !== 2,
10697 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10698 };
10699 /**
10700 * @private
10701 */
10702 const withModifiers = (fn, modifiers) => {
10703 return (event, ...args) => {
10704 for (let i = 0; i < modifiers.length; i++) {
10705 const guard = modifierGuards[modifiers[i]];
10706 if (guard && guard(event, modifiers))
10707 return;
10708 }
10709 return fn(event, ...args);
10710 };
10711 };
10712 // Kept for 2.x compat.
10713 // Note: IE11 compat for `spacebar` and `del` is removed for now.
10714 const keyNames = {
10715 esc: 'escape',
10716 space: ' ',
10717 up: 'arrow-up',
10718 left: 'arrow-left',
10719 right: 'arrow-right',
10720 down: 'arrow-down',
10721 delete: 'backspace'
10722 };
10723 /**
10724 * @private
10725 */
10726 const withKeys = (fn, modifiers) => {
10727 return (event) => {
10728 if (!('key' in event)) {
10729 return;
10730 }
10731 const eventKey = hyphenate(event.key);
10732 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10733 return fn(event);
10734 }
10735 };
10736 };
10737
10738 const vShow = {
10739 beforeMount(el, { value }, { transition }) {
10740 el._vod = el.style.display === 'none' ? '' : el.style.display;
10741 if (transition && value) {
10742 transition.beforeEnter(el);
10743 }
10744 else {
10745 setDisplay(el, value);
10746 }
10747 },
10748 mounted(el, { value }, { transition }) {
10749 if (transition && value) {
10750 transition.enter(el);
10751 }
10752 },
10753 updated(el, { value, oldValue }, { transition }) {
10754 if (!value === !oldValue)
10755 return;
10756 if (transition) {
10757 if (value) {
10758 transition.beforeEnter(el);
10759 setDisplay(el, true);
10760 transition.enter(el);
10761 }
10762 else {
10763 transition.leave(el, () => {
10764 setDisplay(el, false);
10765 });
10766 }
10767 }
10768 else {
10769 setDisplay(el, value);
10770 }
10771 },
10772 beforeUnmount(el, { value }) {
10773 setDisplay(el, value);
10774 }
10775 };
10776 function setDisplay(el, value) {
10777 el.style.display = value ? el._vod : 'none';
10778 }
10779
10780 const rendererOptions = /*#__PURE__*/ extend({ patchProp }, nodeOps);
10781 // lazy create the renderer - this makes core renderer logic tree-shakable
10782 // in case the user only imports reactivity utilities from Vue.
10783 let renderer;
10784 let enabledHydration = false;
10785 function ensureRenderer() {
10786 return (renderer ||
10787 (renderer = createRenderer(rendererOptions)));
10788 }
10789 function ensureHydrationRenderer() {
10790 renderer = enabledHydration
10791 ? renderer
10792 : createHydrationRenderer(rendererOptions);
10793 enabledHydration = true;
10794 return renderer;
10795 }
10796 // use explicit type casts here to avoid import() calls in rolled-up d.ts
10797 const render = ((...args) => {
10798 ensureRenderer().render(...args);
10799 });
10800 const hydrate = ((...args) => {
10801 ensureHydrationRenderer().hydrate(...args);
10802 });
10803 const createApp = ((...args) => {
10804 const app = ensureRenderer().createApp(...args);
10805 {
10806 injectNativeTagCheck(app);
10807 injectCompilerOptionsCheck(app);
10808 }
10809 const { mount } = app;
10810 app.mount = (containerOrSelector) => {
10811 const container = normalizeContainer(containerOrSelector);
10812 if (!container)
10813 return;
10814 const component = app._component;
10815 if (!isFunction(component) && !component.render && !component.template) {
10816 // __UNSAFE__
10817 // Reason: potential execution of JS expressions in in-DOM template.
10818 // The user must make sure the in-DOM template is trusted. If it's
10819 // rendered by the server, the template should not contain any user data.
10820 component.template = container.innerHTML;
10821 }
10822 // clear content before mounting
10823 container.innerHTML = '';
10824 const proxy = mount(container, false, container instanceof SVGElement);
10825 if (container instanceof Element) {
10826 container.removeAttribute('v-cloak');
10827 container.setAttribute('data-v-app', '');
10828 }
10829 return proxy;
10830 };
10831 return app;
10832 });
10833 const createSSRApp = ((...args) => {
10834 const app = ensureHydrationRenderer().createApp(...args);
10835 {
10836 injectNativeTagCheck(app);
10837 injectCompilerOptionsCheck(app);
10838 }
10839 const { mount } = app;
10840 app.mount = (containerOrSelector) => {
10841 const container = normalizeContainer(containerOrSelector);
10842 if (container) {
10843 return mount(container, true, container instanceof SVGElement);
10844 }
10845 };
10846 return app;
10847 });
10848 function injectNativeTagCheck(app) {
10849 // Inject `isNativeTag`
10850 // this is used for component name validation (dev only)
10851 Object.defineProperty(app.config, 'isNativeTag', {
10852 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10853 writable: false
10854 });
10855 }
10856 // dev only
10857 function injectCompilerOptionsCheck(app) {
10858 if (isRuntimeOnly()) {
10859 const isCustomElement = app.config.isCustomElement;
10860 Object.defineProperty(app.config, 'isCustomElement', {
10861 get() {
10862 return isCustomElement;
10863 },
10864 set() {
10865 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10866 `\`compilerOptions.isCustomElement\` instead.`);
10867 }
10868 });
10869 const compilerOptions = app.config.compilerOptions;
10870 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10871 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10872 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10873 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10874 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10875 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10876 `- 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`;
10877 Object.defineProperty(app.config, 'compilerOptions', {
10878 get() {
10879 warn$1(msg);
10880 return compilerOptions;
10881 },
10882 set() {
10883 warn$1(msg);
10884 }
10885 });
10886 }
10887 }
10888 function normalizeContainer(container) {
10889 if (isString(container)) {
10890 const res = document.querySelector(container);
10891 if (!res) {
10892 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10893 }
10894 return res;
10895 }
10896 if (window.ShadowRoot &&
10897 container instanceof window.ShadowRoot &&
10898 container.mode === 'closed') {
10899 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10900 }
10901 return container;
10902 }
10903 /**
10904 * @internal
10905 */
10906 const initDirectivesForSSR = NOOP;
10907
10908 function initDev() {
10909 {
10910 {
10911 console.info(`You are running a development build of Vue.\n` +
10912 `Make sure to use the production build (*.prod.js) when deploying for production.`);
10913 }
10914 initCustomFormatter();
10915 }
10916 }
10917
10918 function defaultOnError(error) {
10919 throw error;
10920 }
10921 function defaultOnWarn(msg) {
10922 console.warn(`[Vue warn] ${msg.message}`);
10923 }
10924 function createCompilerError(code, loc, messages, additionalMessage) {
10925 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
10926 ;
10927 const error = new SyntaxError(String(msg));
10928 error.code = code;
10929 error.loc = loc;
10930 return error;
10931 }
10932 const errorMessages = {
10933 // parse errors
10934 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
10935 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
10936 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
10937 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
10938 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
10939 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
10940 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
10941 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
10942 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
10943 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
10944 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
10945 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
10946 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
10947 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
10948 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
10949 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
10950 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
10951 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
10952 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
10953 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
10954 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
10955 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
10956 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
10957 // Vue-specific parse errors
10958 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
10959 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
10960 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
10961 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
10962 'Note that dynamic directive argument cannot contain spaces.',
10963 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
10964 // transform errors
10965 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
10966 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
10967 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
10968 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
10969 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
10970 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
10971 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
10972 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
10973 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
10974 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
10975 `When there are multiple named slots, all slots should use <template> ` +
10976 `syntax to avoid scope ambiguity.`,
10977 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
10978 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
10979 `default slot. These children will be ignored.`,
10980 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
10981 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
10982 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
10983 [43 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
10984 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
10985 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
10986 // generic errors
10987 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
10988 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
10989 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
10990 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
10991 // just to fulfill types
10992 [50 /* __EXTEND_POINT__ */]: ``
10993 };
10994
10995 const FRAGMENT = Symbol(`Fragment` );
10996 const TELEPORT = Symbol(`Teleport` );
10997 const SUSPENSE = Symbol(`Suspense` );
10998 const KEEP_ALIVE = Symbol(`KeepAlive` );
10999 const BASE_TRANSITION = Symbol(`BaseTransition` );
11000 const OPEN_BLOCK = Symbol(`openBlock` );
11001 const CREATE_BLOCK = Symbol(`createBlock` );
11002 const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11003 const CREATE_VNODE = Symbol(`createVNode` );
11004 const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11005 const CREATE_COMMENT = Symbol(`createCommentVNode` );
11006 const CREATE_TEXT = Symbol(`createTextVNode` );
11007 const CREATE_STATIC = Symbol(`createStaticVNode` );
11008 const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11009 const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11010 const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11011 const RESOLVE_FILTER = Symbol(`resolveFilter` );
11012 const WITH_DIRECTIVES = Symbol(`withDirectives` );
11013 const RENDER_LIST = Symbol(`renderList` );
11014 const RENDER_SLOT = Symbol(`renderSlot` );
11015 const CREATE_SLOTS = Symbol(`createSlots` );
11016 const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11017 const MERGE_PROPS = Symbol(`mergeProps` );
11018 const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11019 const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11020 const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11021 const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11022 const TO_HANDLERS = Symbol(`toHandlers` );
11023 const CAMELIZE = Symbol(`camelize` );
11024 const CAPITALIZE = Symbol(`capitalize` );
11025 const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11026 const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11027 const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11028 const POP_SCOPE_ID = Symbol(`popScopeId` );
11029 const WITH_CTX = Symbol(`withCtx` );
11030 const UNREF = Symbol(`unref` );
11031 const IS_REF = Symbol(`isRef` );
11032 const WITH_MEMO = Symbol(`withMemo` );
11033 const IS_MEMO_SAME = Symbol(`isMemoSame` );
11034 // Name mapping for runtime helpers that need to be imported from 'vue' in
11035 // generated code. Make sure these are correctly exported in the runtime!
11036 // Using `any` here because TS doesn't allow symbols as index type.
11037 const helperNameMap = {
11038 [FRAGMENT]: `Fragment`,
11039 [TELEPORT]: `Teleport`,
11040 [SUSPENSE]: `Suspense`,
11041 [KEEP_ALIVE]: `KeepAlive`,
11042 [BASE_TRANSITION]: `BaseTransition`,
11043 [OPEN_BLOCK]: `openBlock`,
11044 [CREATE_BLOCK]: `createBlock`,
11045 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11046 [CREATE_VNODE]: `createVNode`,
11047 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11048 [CREATE_COMMENT]: `createCommentVNode`,
11049 [CREATE_TEXT]: `createTextVNode`,
11050 [CREATE_STATIC]: `createStaticVNode`,
11051 [RESOLVE_COMPONENT]: `resolveComponent`,
11052 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11053 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11054 [RESOLVE_FILTER]: `resolveFilter`,
11055 [WITH_DIRECTIVES]: `withDirectives`,
11056 [RENDER_LIST]: `renderList`,
11057 [RENDER_SLOT]: `renderSlot`,
11058 [CREATE_SLOTS]: `createSlots`,
11059 [TO_DISPLAY_STRING]: `toDisplayString`,
11060 [MERGE_PROPS]: `mergeProps`,
11061 [NORMALIZE_CLASS]: `normalizeClass`,
11062 [NORMALIZE_STYLE]: `normalizeStyle`,
11063 [NORMALIZE_PROPS]: `normalizeProps`,
11064 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11065 [TO_HANDLERS]: `toHandlers`,
11066 [CAMELIZE]: `camelize`,
11067 [CAPITALIZE]: `capitalize`,
11068 [TO_HANDLER_KEY]: `toHandlerKey`,
11069 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11070 [PUSH_SCOPE_ID]: `pushScopeId`,
11071 [POP_SCOPE_ID]: `popScopeId`,
11072 [WITH_CTX]: `withCtx`,
11073 [UNREF]: `unref`,
11074 [IS_REF]: `isRef`,
11075 [WITH_MEMO]: `withMemo`,
11076 [IS_MEMO_SAME]: `isMemoSame`
11077 };
11078 function registerRuntimeHelpers(helpers) {
11079 Object.getOwnPropertySymbols(helpers).forEach(s => {
11080 helperNameMap[s] = helpers[s];
11081 });
11082 }
11083
11084 // AST Utilities ---------------------------------------------------------------
11085 // Some expressions, e.g. sequence and conditional expressions, are never
11086 // associated with template nodes, so their source locations are just a stub.
11087 // Container types like CompoundExpression also don't need a real location.
11088 const locStub = {
11089 source: '',
11090 start: { line: 1, column: 1, offset: 0 },
11091 end: { line: 1, column: 1, offset: 0 }
11092 };
11093 function createRoot(children, loc = locStub) {
11094 return {
11095 type: 0 /* ROOT */,
11096 children,
11097 helpers: [],
11098 components: [],
11099 directives: [],
11100 hoists: [],
11101 imports: [],
11102 cached: 0,
11103 temps: 0,
11104 codegenNode: undefined,
11105 loc
11106 };
11107 }
11108 function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11109 if (context) {
11110 if (isBlock) {
11111 context.helper(OPEN_BLOCK);
11112 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11113 }
11114 else {
11115 context.helper(getVNodeHelper(context.inSSR, isComponent));
11116 }
11117 if (directives) {
11118 context.helper(WITH_DIRECTIVES);
11119 }
11120 }
11121 return {
11122 type: 13 /* VNODE_CALL */,
11123 tag,
11124 props,
11125 children,
11126 patchFlag,
11127 dynamicProps,
11128 directives,
11129 isBlock,
11130 disableTracking,
11131 isComponent,
11132 loc
11133 };
11134 }
11135 function createArrayExpression(elements, loc = locStub) {
11136 return {
11137 type: 17 /* JS_ARRAY_EXPRESSION */,
11138 loc,
11139 elements
11140 };
11141 }
11142 function createObjectExpression(properties, loc = locStub) {
11143 return {
11144 type: 15 /* JS_OBJECT_EXPRESSION */,
11145 loc,
11146 properties
11147 };
11148 }
11149 function createObjectProperty(key, value) {
11150 return {
11151 type: 16 /* JS_PROPERTY */,
11152 loc: locStub,
11153 key: isString(key) ? createSimpleExpression(key, true) : key,
11154 value
11155 };
11156 }
11157 function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11158 return {
11159 type: 4 /* SIMPLE_EXPRESSION */,
11160 loc,
11161 content,
11162 isStatic,
11163 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11164 };
11165 }
11166 function createCompoundExpression(children, loc = locStub) {
11167 return {
11168 type: 8 /* COMPOUND_EXPRESSION */,
11169 loc,
11170 children
11171 };
11172 }
11173 function createCallExpression(callee, args = [], loc = locStub) {
11174 return {
11175 type: 14 /* JS_CALL_EXPRESSION */,
11176 loc,
11177 callee,
11178 arguments: args
11179 };
11180 }
11181 function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11182 return {
11183 type: 18 /* JS_FUNCTION_EXPRESSION */,
11184 params,
11185 returns,
11186 newline,
11187 isSlot,
11188 loc
11189 };
11190 }
11191 function createConditionalExpression(test, consequent, alternate, newline = true) {
11192 return {
11193 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11194 test,
11195 consequent,
11196 alternate,
11197 newline,
11198 loc: locStub
11199 };
11200 }
11201 function createCacheExpression(index, value, isVNode = false) {
11202 return {
11203 type: 20 /* JS_CACHE_EXPRESSION */,
11204 index,
11205 value,
11206 isVNode,
11207 loc: locStub
11208 };
11209 }
11210 function createBlockStatement(body) {
11211 return {
11212 type: 21 /* JS_BLOCK_STATEMENT */,
11213 body,
11214 loc: locStub
11215 };
11216 }
11217
11218 const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11219 const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11220 function isCoreComponent(tag) {
11221 if (isBuiltInType(tag, 'Teleport')) {
11222 return TELEPORT;
11223 }
11224 else if (isBuiltInType(tag, 'Suspense')) {
11225 return SUSPENSE;
11226 }
11227 else if (isBuiltInType(tag, 'KeepAlive')) {
11228 return KEEP_ALIVE;
11229 }
11230 else if (isBuiltInType(tag, 'BaseTransition')) {
11231 return BASE_TRANSITION;
11232 }
11233 }
11234 const nonIdentifierRE = /^\d|[^\$\w]/;
11235 const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11236 const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11237 const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11238 const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11239 /**
11240 * Simple lexer to check if an expression is a member expression. This is
11241 * lax and only checks validity at the root level (i.e. does not validate exps
11242 * inside square brackets), but it's ok since these are only used on template
11243 * expressions and false positives are invalid expressions in the first place.
11244 */
11245 const isMemberExpressionBrowser = (path) => {
11246 // remove whitespaces around . or [ first
11247 path = path.trim().replace(whitespaceRE, s => s.trim());
11248 let state = 0 /* inMemberExp */;
11249 let stateStack = [];
11250 let currentOpenBracketCount = 0;
11251 let currentOpenParensCount = 0;
11252 let currentStringType = null;
11253 for (let i = 0; i < path.length; i++) {
11254 const char = path.charAt(i);
11255 switch (state) {
11256 case 0 /* inMemberExp */:
11257 if (char === '[') {
11258 stateStack.push(state);
11259 state = 1 /* inBrackets */;
11260 currentOpenBracketCount++;
11261 }
11262 else if (char === '(') {
11263 stateStack.push(state);
11264 state = 2 /* inParens */;
11265 currentOpenParensCount++;
11266 }
11267 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11268 return false;
11269 }
11270 break;
11271 case 1 /* inBrackets */:
11272 if (char === `'` || char === `"` || char === '`') {
11273 stateStack.push(state);
11274 state = 3 /* inString */;
11275 currentStringType = char;
11276 }
11277 else if (char === `[`) {
11278 currentOpenBracketCount++;
11279 }
11280 else if (char === `]`) {
11281 if (!--currentOpenBracketCount) {
11282 state = stateStack.pop();
11283 }
11284 }
11285 break;
11286 case 2 /* inParens */:
11287 if (char === `'` || char === `"` || char === '`') {
11288 stateStack.push(state);
11289 state = 3 /* inString */;
11290 currentStringType = char;
11291 }
11292 else if (char === `(`) {
11293 currentOpenParensCount++;
11294 }
11295 else if (char === `)`) {
11296 // if the exp ends as a call then it should not be considered valid
11297 if (i === path.length - 1) {
11298 return false;
11299 }
11300 if (!--currentOpenParensCount) {
11301 state = stateStack.pop();
11302 }
11303 }
11304 break;
11305 case 3 /* inString */:
11306 if (char === currentStringType) {
11307 state = stateStack.pop();
11308 currentStringType = null;
11309 }
11310 break;
11311 }
11312 }
11313 return !currentOpenBracketCount && !currentOpenParensCount;
11314 };
11315 const isMemberExpression = isMemberExpressionBrowser
11316 ;
11317 function getInnerRange(loc, offset, length) {
11318 const source = loc.source.slice(offset, offset + length);
11319 const newLoc = {
11320 source,
11321 start: advancePositionWithClone(loc.start, loc.source, offset),
11322 end: loc.end
11323 };
11324 if (length != null) {
11325 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11326 }
11327 return newLoc;
11328 }
11329 function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11330 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11331 }
11332 // advance by mutation without cloning (for performance reasons), since this
11333 // gets called a lot in the parser
11334 function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11335 let linesCount = 0;
11336 let lastNewLinePos = -1;
11337 for (let i = 0; i < numberOfCharacters; i++) {
11338 if (source.charCodeAt(i) === 10 /* newline char code */) {
11339 linesCount++;
11340 lastNewLinePos = i;
11341 }
11342 }
11343 pos.offset += numberOfCharacters;
11344 pos.line += linesCount;
11345 pos.column =
11346 lastNewLinePos === -1
11347 ? pos.column + numberOfCharacters
11348 : numberOfCharacters - lastNewLinePos;
11349 return pos;
11350 }
11351 function assert(condition, msg) {
11352 /* istanbul ignore if */
11353 if (!condition) {
11354 throw new Error(msg || `unexpected compiler condition`);
11355 }
11356 }
11357 function findDir(node, name, allowEmpty = false) {
11358 for (let i = 0; i < node.props.length; i++) {
11359 const p = node.props[i];
11360 if (p.type === 7 /* DIRECTIVE */ &&
11361 (allowEmpty || p.exp) &&
11362 (isString(name) ? p.name === name : name.test(p.name))) {
11363 return p;
11364 }
11365 }
11366 }
11367 function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11368 for (let i = 0; i < node.props.length; i++) {
11369 const p = node.props[i];
11370 if (p.type === 6 /* ATTRIBUTE */) {
11371 if (dynamicOnly)
11372 continue;
11373 if (p.name === name && (p.value || allowEmpty)) {
11374 return p;
11375 }
11376 }
11377 else if (p.name === 'bind' &&
11378 (p.exp || allowEmpty) &&
11379 isStaticArgOf(p.arg, name)) {
11380 return p;
11381 }
11382 }
11383 }
11384 function isStaticArgOf(arg, name) {
11385 return !!(arg && isStaticExp(arg) && arg.content === name);
11386 }
11387 function hasDynamicKeyVBind(node) {
11388 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11389 p.name === 'bind' &&
11390 (!p.arg || // v-bind="obj"
11391 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11392 !p.arg.isStatic) // v-bind:[foo]
11393 );
11394 }
11395 function isText(node) {
11396 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11397 }
11398 function isVSlot(p) {
11399 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11400 }
11401 function isTemplateNode(node) {
11402 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11403 }
11404 function isSlotOutlet(node) {
11405 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11406 }
11407 function getVNodeHelper(ssr, isComponent) {
11408 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11409 }
11410 function getVNodeBlockHelper(ssr, isComponent) {
11411 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11412 }
11413 const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11414 function getUnnormalizedProps(props, callPath = []) {
11415 if (props &&
11416 !isString(props) &&
11417 props.type === 14 /* JS_CALL_EXPRESSION */) {
11418 const callee = props.callee;
11419 if (!isString(callee) && propsHelperSet.has(callee)) {
11420 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11421 }
11422 }
11423 return [props, callPath];
11424 }
11425 function injectProp(node, prop, context) {
11426 let propsWithInjection;
11427 /**
11428 * 1. mergeProps(...)
11429 * 2. toHandlers(...)
11430 * 3. normalizeProps(...)
11431 * 4. normalizeProps(guardReactiveProps(...))
11432 *
11433 * we need to get the real props before normalization
11434 */
11435 let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11436 let callPath = [];
11437 let parentCall;
11438 if (props &&
11439 !isString(props) &&
11440 props.type === 14 /* JS_CALL_EXPRESSION */) {
11441 const ret = getUnnormalizedProps(props);
11442 props = ret[0];
11443 callPath = ret[1];
11444 parentCall = callPath[callPath.length - 1];
11445 }
11446 if (props == null || isString(props)) {
11447 propsWithInjection = createObjectExpression([prop]);
11448 }
11449 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11450 // merged props... add ours
11451 // only inject key to object literal if it's the first argument so that
11452 // if doesn't override user provided keys
11453 const first = props.arguments[0];
11454 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11455 first.properties.unshift(prop);
11456 }
11457 else {
11458 if (props.callee === TO_HANDLERS) {
11459 // #2366
11460 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11461 createObjectExpression([prop]),
11462 props
11463 ]);
11464 }
11465 else {
11466 props.arguments.unshift(createObjectExpression([prop]));
11467 }
11468 }
11469 !propsWithInjection && (propsWithInjection = props);
11470 }
11471 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11472 let alreadyExists = false;
11473 // check existing key to avoid overriding user provided keys
11474 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11475 const propKeyName = prop.key.content;
11476 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11477 p.key.content === propKeyName);
11478 }
11479 if (!alreadyExists) {
11480 props.properties.unshift(prop);
11481 }
11482 propsWithInjection = props;
11483 }
11484 else {
11485 // single v-bind with expression, return a merged replacement
11486 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11487 createObjectExpression([prop]),
11488 props
11489 ]);
11490 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11491 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11492 // the `guardReactiveProps` will no longer be needed
11493 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11494 parentCall = callPath[callPath.length - 2];
11495 }
11496 }
11497 if (node.type === 13 /* VNODE_CALL */) {
11498 if (parentCall) {
11499 parentCall.arguments[0] = propsWithInjection;
11500 }
11501 else {
11502 node.props = propsWithInjection;
11503 }
11504 }
11505 else {
11506 if (parentCall) {
11507 parentCall.arguments[0] = propsWithInjection;
11508 }
11509 else {
11510 node.arguments[2] = propsWithInjection;
11511 }
11512 }
11513 }
11514 function toValidAssetId(name, type) {
11515 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11516 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11517 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11518 })}`;
11519 }
11520 function getMemoedVNodeCall(node) {
11521 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11522 return node.arguments[1].returns;
11523 }
11524 else {
11525 return node;
11526 }
11527 }
11528 function makeBlock(node, { helper, removeHelper, inSSR }) {
11529 if (!node.isBlock) {
11530 node.isBlock = true;
11531 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11532 helper(OPEN_BLOCK);
11533 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11534 }
11535 }
11536
11537 const deprecationData = {
11538 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11539 message: `Platform-native elements with "is" prop will no longer be ` +
11540 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11541 `prefixed with "vue:".`,
11542 link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
11543 },
11544 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11545 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11546 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11547 `\`v-model:${key}\`.`,
11548 link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
11549 },
11550 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11551 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11552 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11553 },
11554 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11555 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11556 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11557 `that appears before v-bind in the case of conflict. ` +
11558 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11559 `You can also suppress this warning if the usage is intended.`,
11560 link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
11561 },
11562 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11563 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11564 link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
11565 },
11566 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11567 message: `v-if / v-for precedence when used on the same element has changed ` +
11568 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11569 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11570 `with <template> tags or use a computed property that filters v-for ` +
11571 `data source.`,
11572 link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
11573 },
11574 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11575 message: `<template> with no special directives will render as a native template ` +
11576 `element instead of its inner content in Vue 3.`
11577 },
11578 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11579 message: `"inline-template" has been removed in Vue 3.`,
11580 link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
11581 },
11582 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11583 message: `filters have been removed in Vue 3. ` +
11584 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11585 `Use method calls or computed properties instead.`,
11586 link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
11587 }
11588 };
11589 function getCompatValue(key, context) {
11590 const config = context.options
11591 ? context.options.compatConfig
11592 : context.compatConfig;
11593 const value = config && config[key];
11594 if (key === 'MODE') {
11595 return value || 3; // compiler defaults to v3 behavior
11596 }
11597 else {
11598 return value;
11599 }
11600 }
11601 function isCompatEnabled(key, context) {
11602 const mode = getCompatValue('MODE', context);
11603 const value = getCompatValue(key, context);
11604 // in v3 mode, only enable if explicitly set to true
11605 // otherwise enable for any non-false value
11606 return mode === 3 ? value === true : value !== false;
11607 }
11608 function checkCompatEnabled(key, context, loc, ...args) {
11609 const enabled = isCompatEnabled(key, context);
11610 if (enabled) {
11611 warnDeprecation(key, context, loc, ...args);
11612 }
11613 return enabled;
11614 }
11615 function warnDeprecation(key, context, loc, ...args) {
11616 const val = getCompatValue(key, context);
11617 if (val === 'suppress-warning') {
11618 return;
11619 }
11620 const { message, link } = deprecationData[key];
11621 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11622 const err = new SyntaxError(msg);
11623 err.code = key;
11624 if (loc)
11625 err.loc = loc;
11626 context.onWarn(err);
11627 }
11628
11629 // The default decoder only provides escapes for characters reserved as part of
11630 // the template syntax, and is only used if the custom renderer did not provide
11631 // a platform-specific decoder.
11632 const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11633 const decodeMap = {
11634 gt: '>',
11635 lt: '<',
11636 amp: '&',
11637 apos: "'",
11638 quot: '"'
11639 };
11640 const defaultParserOptions = {
11641 delimiters: [`{{`, `}}`],
11642 getNamespace: () => 0 /* HTML */,
11643 getTextMode: () => 0 /* DATA */,
11644 isVoidTag: NO,
11645 isPreTag: NO,
11646 isCustomElement: NO,
11647 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11648 onError: defaultOnError,
11649 onWarn: defaultOnWarn,
11650 comments: true
11651 };
11652 function baseParse(content, options = {}) {
11653 const context = createParserContext(content, options);
11654 const start = getCursor(context);
11655 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11656 }
11657 function createParserContext(content, rawOptions) {
11658 const options = extend({}, defaultParserOptions);
11659 let key;
11660 for (key in rawOptions) {
11661 // @ts-ignore
11662 options[key] =
11663 rawOptions[key] === undefined
11664 ? defaultParserOptions[key]
11665 : rawOptions[key];
11666 }
11667 return {
11668 options,
11669 column: 1,
11670 line: 1,
11671 offset: 0,
11672 originalSource: content,
11673 source: content,
11674 inPre: false,
11675 inVPre: false,
11676 onWarn: options.onWarn
11677 };
11678 }
11679 function parseChildren(context, mode, ancestors) {
11680 const parent = last(ancestors);
11681 const ns = parent ? parent.ns : 0 /* HTML */;
11682 const nodes = [];
11683 while (!isEnd(context, mode, ancestors)) {
11684 const s = context.source;
11685 let node = undefined;
11686 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11687 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11688 // '{{'
11689 node = parseInterpolation(context, mode);
11690 }
11691 else if (mode === 0 /* DATA */ && s[0] === '<') {
11692 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11693 if (s.length === 1) {
11694 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11695 }
11696 else if (s[1] === '!') {
11697 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11698 if (startsWith(s, '<!--')) {
11699 node = parseComment(context);
11700 }
11701 else if (startsWith(s, '<!DOCTYPE')) {
11702 // Ignore DOCTYPE by a limitation.
11703 node = parseBogusComment(context);
11704 }
11705 else if (startsWith(s, '<![CDATA[')) {
11706 if (ns !== 0 /* HTML */) {
11707 node = parseCDATA(context, ancestors);
11708 }
11709 else {
11710 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11711 node = parseBogusComment(context);
11712 }
11713 }
11714 else {
11715 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11716 node = parseBogusComment(context);
11717 }
11718 }
11719 else if (s[1] === '/') {
11720 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11721 if (s.length === 2) {
11722 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11723 }
11724 else if (s[2] === '>') {
11725 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11726 advanceBy(context, 3);
11727 continue;
11728 }
11729 else if (/[a-z]/i.test(s[2])) {
11730 emitError(context, 23 /* X_INVALID_END_TAG */);
11731 parseTag(context, 1 /* End */, parent);
11732 continue;
11733 }
11734 else {
11735 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11736 node = parseBogusComment(context);
11737 }
11738 }
11739 else if (/[a-z]/i.test(s[1])) {
11740 node = parseElement(context, ancestors);
11741 }
11742 else if (s[1] === '?') {
11743 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11744 node = parseBogusComment(context);
11745 }
11746 else {
11747 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11748 }
11749 }
11750 }
11751 if (!node) {
11752 node = parseText(context, mode);
11753 }
11754 if (isArray(node)) {
11755 for (let i = 0; i < node.length; i++) {
11756 pushNode(nodes, node[i]);
11757 }
11758 }
11759 else {
11760 pushNode(nodes, node);
11761 }
11762 }
11763 // Whitespace handling strategy like v2
11764 let removedWhitespace = false;
11765 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11766 const shouldCondense = context.options.whitespace !== 'preserve';
11767 for (let i = 0; i < nodes.length; i++) {
11768 const node = nodes[i];
11769 if (!context.inPre && node.type === 2 /* TEXT */) {
11770 if (!/[^\t\r\n\f ]/.test(node.content)) {
11771 const prev = nodes[i - 1];
11772 const next = nodes[i + 1];
11773 // Remove if:
11774 // - the whitespace is the first or last node, or:
11775 // - (condense mode) the whitespace is adjacent to a comment, or:
11776 // - (condense mode) the whitespace is between two elements AND contains newline
11777 if (!prev ||
11778 !next ||
11779 (shouldCondense &&
11780 (prev.type === 3 /* COMMENT */ ||
11781 next.type === 3 /* COMMENT */ ||
11782 (prev.type === 1 /* ELEMENT */ &&
11783 next.type === 1 /* ELEMENT */ &&
11784 /[\r\n]/.test(node.content))))) {
11785 removedWhitespace = true;
11786 nodes[i] = null;
11787 }
11788 else {
11789 // Otherwise, the whitespace is condensed into a single space
11790 node.content = ' ';
11791 }
11792 }
11793 else if (shouldCondense) {
11794 // in condense mode, consecutive whitespaces in text are condensed
11795 // down to a single space.
11796 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11797 }
11798 }
11799 // Remove comment nodes if desired by configuration.
11800 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11801 removedWhitespace = true;
11802 nodes[i] = null;
11803 }
11804 }
11805 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11806 // remove leading newline per html spec
11807 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11808 const first = nodes[0];
11809 if (first && first.type === 2 /* TEXT */) {
11810 first.content = first.content.replace(/^\r?\n/, '');
11811 }
11812 }
11813 }
11814 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11815 }
11816 function pushNode(nodes, node) {
11817 if (node.type === 2 /* TEXT */) {
11818 const prev = last(nodes);
11819 // Merge if both this and the previous node are text and those are
11820 // consecutive. This happens for cases like "a < b".
11821 if (prev &&
11822 prev.type === 2 /* TEXT */ &&
11823 prev.loc.end.offset === node.loc.start.offset) {
11824 prev.content += node.content;
11825 prev.loc.end = node.loc.end;
11826 prev.loc.source += node.loc.source;
11827 return;
11828 }
11829 }
11830 nodes.push(node);
11831 }
11832 function parseCDATA(context, ancestors) {
11833 advanceBy(context, 9);
11834 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11835 if (context.source.length === 0) {
11836 emitError(context, 6 /* EOF_IN_CDATA */);
11837 }
11838 else {
11839 advanceBy(context, 3);
11840 }
11841 return nodes;
11842 }
11843 function parseComment(context) {
11844 const start = getCursor(context);
11845 let content;
11846 // Regular comment.
11847 const match = /--(\!)?>/.exec(context.source);
11848 if (!match) {
11849 content = context.source.slice(4);
11850 advanceBy(context, context.source.length);
11851 emitError(context, 7 /* EOF_IN_COMMENT */);
11852 }
11853 else {
11854 if (match.index <= 3) {
11855 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
11856 }
11857 if (match[1]) {
11858 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
11859 }
11860 content = context.source.slice(4, match.index);
11861 // Advancing with reporting nested comments.
11862 const s = context.source.slice(0, match.index);
11863 let prevIndex = 1, nestedIndex = 0;
11864 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
11865 advanceBy(context, nestedIndex - prevIndex + 1);
11866 if (nestedIndex + 4 < s.length) {
11867 emitError(context, 16 /* NESTED_COMMENT */);
11868 }
11869 prevIndex = nestedIndex + 1;
11870 }
11871 advanceBy(context, match.index + match[0].length - prevIndex + 1);
11872 }
11873 return {
11874 type: 3 /* COMMENT */,
11875 content,
11876 loc: getSelection(context, start)
11877 };
11878 }
11879 function parseBogusComment(context) {
11880 const start = getCursor(context);
11881 const contentStart = context.source[1] === '?' ? 1 : 2;
11882 let content;
11883 const closeIndex = context.source.indexOf('>');
11884 if (closeIndex === -1) {
11885 content = context.source.slice(contentStart);
11886 advanceBy(context, context.source.length);
11887 }
11888 else {
11889 content = context.source.slice(contentStart, closeIndex);
11890 advanceBy(context, closeIndex + 1);
11891 }
11892 return {
11893 type: 3 /* COMMENT */,
11894 content,
11895 loc: getSelection(context, start)
11896 };
11897 }
11898 function parseElement(context, ancestors) {
11899 // Start tag.
11900 const wasInPre = context.inPre;
11901 const wasInVPre = context.inVPre;
11902 const parent = last(ancestors);
11903 const element = parseTag(context, 0 /* Start */, parent);
11904 const isPreBoundary = context.inPre && !wasInPre;
11905 const isVPreBoundary = context.inVPre && !wasInVPre;
11906 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
11907 // #4030 self-closing <pre> tag
11908 if (isPreBoundary) {
11909 context.inPre = false;
11910 }
11911 if (isVPreBoundary) {
11912 context.inVPre = false;
11913 }
11914 return element;
11915 }
11916 // Children.
11917 ancestors.push(element);
11918 const mode = context.options.getTextMode(element, parent);
11919 const children = parseChildren(context, mode, ancestors);
11920 ancestors.pop();
11921 element.children = children;
11922 // End tag.
11923 if (startsWithEndTagOpen(context.source, element.tag)) {
11924 parseTag(context, 1 /* End */, parent);
11925 }
11926 else {
11927 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
11928 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
11929 const first = children[0];
11930 if (first && startsWith(first.loc.source, '<!--')) {
11931 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
11932 }
11933 }
11934 }
11935 element.loc = getSelection(context, element.loc.start);
11936 if (isPreBoundary) {
11937 context.inPre = false;
11938 }
11939 if (isVPreBoundary) {
11940 context.inVPre = false;
11941 }
11942 return element;
11943 }
11944 const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
11945 function parseTag(context, type, parent) {
11946 // Tag open.
11947 const start = getCursor(context);
11948 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
11949 const tag = match[1];
11950 const ns = context.options.getNamespace(tag, parent);
11951 advanceBy(context, match[0].length);
11952 advanceSpaces(context);
11953 // save current state in case we need to re-parse attributes with v-pre
11954 const cursor = getCursor(context);
11955 const currentSource = context.source;
11956 // check <pre> tag
11957 if (context.options.isPreTag(tag)) {
11958 context.inPre = true;
11959 }
11960 // Attributes.
11961 let props = parseAttributes(context, type);
11962 // check v-pre
11963 if (type === 0 /* Start */ &&
11964 !context.inVPre &&
11965 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
11966 context.inVPre = true;
11967 // reset context
11968 extend(context, cursor);
11969 context.source = currentSource;
11970 // re-parse attrs and filter out v-pre itself
11971 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
11972 }
11973 // Tag close.
11974 let isSelfClosing = false;
11975 if (context.source.length === 0) {
11976 emitError(context, 9 /* EOF_IN_TAG */);
11977 }
11978 else {
11979 isSelfClosing = startsWith(context.source, '/>');
11980 if (type === 1 /* End */ && isSelfClosing) {
11981 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
11982 }
11983 advanceBy(context, isSelfClosing ? 2 : 1);
11984 }
11985 if (type === 1 /* End */) {
11986 return;
11987 }
11988 let tagType = 0 /* ELEMENT */;
11989 if (!context.inVPre) {
11990 if (tag === 'slot') {
11991 tagType = 2 /* SLOT */;
11992 }
11993 else if (tag === 'template') {
11994 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
11995 tagType = 3 /* TEMPLATE */;
11996 }
11997 }
11998 else if (isComponent(tag, props, context)) {
11999 tagType = 1 /* COMPONENT */;
12000 }
12001 }
12002 return {
12003 type: 1 /* ELEMENT */,
12004 ns,
12005 tag,
12006 tagType,
12007 props,
12008 isSelfClosing,
12009 children: [],
12010 loc: getSelection(context, start),
12011 codegenNode: undefined // to be created during transform phase
12012 };
12013 }
12014 function isComponent(tag, props, context) {
12015 const options = context.options;
12016 if (options.isCustomElement(tag)) {
12017 return false;
12018 }
12019 if (tag === 'component' ||
12020 /^[A-Z]/.test(tag) ||
12021 isCoreComponent(tag) ||
12022 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12023 (options.isNativeTag && !options.isNativeTag(tag))) {
12024 return true;
12025 }
12026 // at this point the tag should be a native tag, but check for potential "is"
12027 // casting
12028 for (let i = 0; i < props.length; i++) {
12029 const p = props[i];
12030 if (p.type === 6 /* ATTRIBUTE */) {
12031 if (p.name === 'is' && p.value) {
12032 if (p.value.content.startsWith('vue:')) {
12033 return true;
12034 }
12035 }
12036 }
12037 else {
12038 // directive
12039 // v-is (TODO Deprecate)
12040 if (p.name === 'is') {
12041 return true;
12042 }
12043 else if (
12044 // :is on plain element - only treat as component in compat mode
12045 p.name === 'bind' &&
12046 isStaticArgOf(p.arg, 'is') &&
12047 false &&
12048 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12049 return true;
12050 }
12051 }
12052 }
12053 }
12054 function parseAttributes(context, type) {
12055 const props = [];
12056 const attributeNames = new Set();
12057 while (context.source.length > 0 &&
12058 !startsWith(context.source, '>') &&
12059 !startsWith(context.source, '/>')) {
12060 if (startsWith(context.source, '/')) {
12061 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12062 advanceBy(context, 1);
12063 advanceSpaces(context);
12064 continue;
12065 }
12066 if (type === 1 /* End */) {
12067 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12068 }
12069 const attr = parseAttribute(context, attributeNames);
12070 // Trim whitespace between class
12071 // https://github.com/vuejs/core/issues/4251
12072 if (attr.type === 6 /* ATTRIBUTE */ &&
12073 attr.value &&
12074 attr.name === 'class') {
12075 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12076 }
12077 if (type === 0 /* Start */) {
12078 props.push(attr);
12079 }
12080 if (/^[^\t\r\n\f />]/.test(context.source)) {
12081 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12082 }
12083 advanceSpaces(context);
12084 }
12085 return props;
12086 }
12087 function parseAttribute(context, nameSet) {
12088 // Name.
12089 const start = getCursor(context);
12090 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12091 const name = match[0];
12092 if (nameSet.has(name)) {
12093 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12094 }
12095 nameSet.add(name);
12096 if (name[0] === '=') {
12097 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12098 }
12099 {
12100 const pattern = /["'<]/g;
12101 let m;
12102 while ((m = pattern.exec(name))) {
12103 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12104 }
12105 }
12106 advanceBy(context, name.length);
12107 // Value
12108 let value = undefined;
12109 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12110 advanceSpaces(context);
12111 advanceBy(context, 1);
12112 advanceSpaces(context);
12113 value = parseAttributeValue(context);
12114 if (!value) {
12115 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12116 }
12117 }
12118 const loc = getSelection(context, start);
12119 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12120 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12121 let isPropShorthand = startsWith(name, '.');
12122 let dirName = match[1] ||
12123 (isPropShorthand || startsWith(name, ':')
12124 ? 'bind'
12125 : startsWith(name, '@')
12126 ? 'on'
12127 : 'slot');
12128 let arg;
12129 if (match[2]) {
12130 const isSlot = dirName === 'slot';
12131 const startOffset = name.lastIndexOf(match[2]);
12132 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12133 let content = match[2];
12134 let isStatic = true;
12135 if (content.startsWith('[')) {
12136 isStatic = false;
12137 if (!content.endsWith(']')) {
12138 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12139 content = content.slice(1);
12140 }
12141 else {
12142 content = content.slice(1, content.length - 1);
12143 }
12144 }
12145 else if (isSlot) {
12146 // #1241 special case for v-slot: vuetify relies extensively on slot
12147 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12148 // supports such usage so we are keeping it consistent with 2.x.
12149 content += match[3] || '';
12150 }
12151 arg = {
12152 type: 4 /* SIMPLE_EXPRESSION */,
12153 content,
12154 isStatic,
12155 constType: isStatic
12156 ? 3 /* CAN_STRINGIFY */
12157 : 0 /* NOT_CONSTANT */,
12158 loc
12159 };
12160 }
12161 if (value && value.isQuoted) {
12162 const valueLoc = value.loc;
12163 valueLoc.start.offset++;
12164 valueLoc.start.column++;
12165 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12166 valueLoc.source = valueLoc.source.slice(1, -1);
12167 }
12168 const modifiers = match[3] ? match[3].slice(1).split('.') : [];
12169 if (isPropShorthand)
12170 modifiers.push('prop');
12171 return {
12172 type: 7 /* DIRECTIVE */,
12173 name: dirName,
12174 exp: value && {
12175 type: 4 /* SIMPLE_EXPRESSION */,
12176 content: value.content,
12177 isStatic: false,
12178 // Treat as non-constant by default. This can be potentially set to
12179 // other values by `transformExpression` to make it eligible for hoisting.
12180 constType: 0 /* NOT_CONSTANT */,
12181 loc: value.loc
12182 },
12183 arg,
12184 modifiers,
12185 loc
12186 };
12187 }
12188 // missing directive name or illegal directive name
12189 if (!context.inVPre && startsWith(name, 'v-')) {
12190 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12191 }
12192 return {
12193 type: 6 /* ATTRIBUTE */,
12194 name,
12195 value: value && {
12196 type: 2 /* TEXT */,
12197 content: value.content,
12198 loc: value.loc
12199 },
12200 loc
12201 };
12202 }
12203 function parseAttributeValue(context) {
12204 const start = getCursor(context);
12205 let content;
12206 const quote = context.source[0];
12207 const isQuoted = quote === `"` || quote === `'`;
12208 if (isQuoted) {
12209 // Quoted value.
12210 advanceBy(context, 1);
12211 const endIndex = context.source.indexOf(quote);
12212 if (endIndex === -1) {
12213 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12214 }
12215 else {
12216 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12217 advanceBy(context, 1);
12218 }
12219 }
12220 else {
12221 // Unquoted
12222 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12223 if (!match) {
12224 return undefined;
12225 }
12226 const unexpectedChars = /["'<=`]/g;
12227 let m;
12228 while ((m = unexpectedChars.exec(match[0]))) {
12229 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12230 }
12231 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12232 }
12233 return { content, isQuoted, loc: getSelection(context, start) };
12234 }
12235 function parseInterpolation(context, mode) {
12236 const [open, close] = context.options.delimiters;
12237 const closeIndex = context.source.indexOf(close, open.length);
12238 if (closeIndex === -1) {
12239 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12240 return undefined;
12241 }
12242 const start = getCursor(context);
12243 advanceBy(context, open.length);
12244 const innerStart = getCursor(context);
12245 const innerEnd = getCursor(context);
12246 const rawContentLength = closeIndex - open.length;
12247 const rawContent = context.source.slice(0, rawContentLength);
12248 const preTrimContent = parseTextData(context, rawContentLength, mode);
12249 const content = preTrimContent.trim();
12250 const startOffset = preTrimContent.indexOf(content);
12251 if (startOffset > 0) {
12252 advancePositionWithMutation(innerStart, rawContent, startOffset);
12253 }
12254 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12255 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12256 advanceBy(context, close.length);
12257 return {
12258 type: 5 /* INTERPOLATION */,
12259 content: {
12260 type: 4 /* SIMPLE_EXPRESSION */,
12261 isStatic: false,
12262 // Set `isConstant` to false by default and will decide in transformExpression
12263 constType: 0 /* NOT_CONSTANT */,
12264 content,
12265 loc: getSelection(context, innerStart, innerEnd)
12266 },
12267 loc: getSelection(context, start)
12268 };
12269 }
12270 function parseText(context, mode) {
12271 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12272 let endIndex = context.source.length;
12273 for (let i = 0; i < endTokens.length; i++) {
12274 const index = context.source.indexOf(endTokens[i], 1);
12275 if (index !== -1 && endIndex > index) {
12276 endIndex = index;
12277 }
12278 }
12279 const start = getCursor(context);
12280 const content = parseTextData(context, endIndex, mode);
12281 return {
12282 type: 2 /* TEXT */,
12283 content,
12284 loc: getSelection(context, start)
12285 };
12286 }
12287 /**
12288 * Get text data with a given length from the current location.
12289 * This translates HTML entities in the text data.
12290 */
12291 function parseTextData(context, length, mode) {
12292 const rawText = context.source.slice(0, length);
12293 advanceBy(context, length);
12294 if (mode === 2 /* RAWTEXT */ ||
12295 mode === 3 /* CDATA */ ||
12296 !rawText.includes('&')) {
12297 return rawText;
12298 }
12299 else {
12300 // DATA or RCDATA containing "&"". Entity decoding required.
12301 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12302 }
12303 }
12304 function getCursor(context) {
12305 const { column, line, offset } = context;
12306 return { column, line, offset };
12307 }
12308 function getSelection(context, start, end) {
12309 end = end || getCursor(context);
12310 return {
12311 start,
12312 end,
12313 source: context.originalSource.slice(start.offset, end.offset)
12314 };
12315 }
12316 function last(xs) {
12317 return xs[xs.length - 1];
12318 }
12319 function startsWith(source, searchString) {
12320 return source.startsWith(searchString);
12321 }
12322 function advanceBy(context, numberOfCharacters) {
12323 const { source } = context;
12324 advancePositionWithMutation(context, source, numberOfCharacters);
12325 context.source = source.slice(numberOfCharacters);
12326 }
12327 function advanceSpaces(context) {
12328 const match = /^[\t\r\n\f ]+/.exec(context.source);
12329 if (match) {
12330 advanceBy(context, match[0].length);
12331 }
12332 }
12333 function getNewPosition(context, start, numberOfCharacters) {
12334 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12335 }
12336 function emitError(context, code, offset, loc = getCursor(context)) {
12337 if (offset) {
12338 loc.offset += offset;
12339 loc.column += offset;
12340 }
12341 context.options.onError(createCompilerError(code, {
12342 start: loc,
12343 end: loc,
12344 source: ''
12345 }));
12346 }
12347 function isEnd(context, mode, ancestors) {
12348 const s = context.source;
12349 switch (mode) {
12350 case 0 /* DATA */:
12351 if (startsWith(s, '</')) {
12352 // TODO: probably bad performance
12353 for (let i = ancestors.length - 1; i >= 0; --i) {
12354 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12355 return true;
12356 }
12357 }
12358 }
12359 break;
12360 case 1 /* RCDATA */:
12361 case 2 /* RAWTEXT */: {
12362 const parent = last(ancestors);
12363 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12364 return true;
12365 }
12366 break;
12367 }
12368 case 3 /* CDATA */:
12369 if (startsWith(s, ']]>')) {
12370 return true;
12371 }
12372 break;
12373 }
12374 return !s;
12375 }
12376 function startsWithEndTagOpen(source, tag) {
12377 return (startsWith(source, '</') &&
12378 source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
12379 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12380 }
12381
12382 function hoistStatic(root, context) {
12383 walk(root, context,
12384 // Root node is unfortunately non-hoistable due to potential parent
12385 // fallthrough attributes.
12386 isSingleElementRoot(root, root.children[0]));
12387 }
12388 function isSingleElementRoot(root, child) {
12389 const { children } = root;
12390 return (children.length === 1 &&
12391 child.type === 1 /* ELEMENT */ &&
12392 !isSlotOutlet(child));
12393 }
12394 function walk(node, context, doNotHoistNode = false) {
12395 const { children } = node;
12396 const originalCount = children.length;
12397 let hoistedCount = 0;
12398 for (let i = 0; i < children.length; i++) {
12399 const child = children[i];
12400 // only plain elements & text calls are eligible for hoisting.
12401 if (child.type === 1 /* ELEMENT */ &&
12402 child.tagType === 0 /* ELEMENT */) {
12403 const constantType = doNotHoistNode
12404 ? 0 /* NOT_CONSTANT */
12405 : getConstantType(child, context);
12406 if (constantType > 0 /* NOT_CONSTANT */) {
12407 if (constantType >= 2 /* CAN_HOIST */) {
12408 child.codegenNode.patchFlag =
12409 -1 /* HOISTED */ + (` /* HOISTED */` );
12410 child.codegenNode = context.hoist(child.codegenNode);
12411 hoistedCount++;
12412 continue;
12413 }
12414 }
12415 else {
12416 // node may contain dynamic children, but its props may be eligible for
12417 // hoisting.
12418 const codegenNode = child.codegenNode;
12419 if (codegenNode.type === 13 /* VNODE_CALL */) {
12420 const flag = getPatchFlag(codegenNode);
12421 if ((!flag ||
12422 flag === 512 /* NEED_PATCH */ ||
12423 flag === 1 /* TEXT */) &&
12424 getGeneratedPropsConstantType(child, context) >=
12425 2 /* CAN_HOIST */) {
12426 const props = getNodeProps(child);
12427 if (props) {
12428 codegenNode.props = context.hoist(props);
12429 }
12430 }
12431 if (codegenNode.dynamicProps) {
12432 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12433 }
12434 }
12435 }
12436 }
12437 else if (child.type === 12 /* TEXT_CALL */ &&
12438 getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
12439 child.codegenNode = context.hoist(child.codegenNode);
12440 hoistedCount++;
12441 }
12442 // walk further
12443 if (child.type === 1 /* ELEMENT */) {
12444 const isComponent = child.tagType === 1 /* COMPONENT */;
12445 if (isComponent) {
12446 context.scopes.vSlot++;
12447 }
12448 walk(child, context);
12449 if (isComponent) {
12450 context.scopes.vSlot--;
12451 }
12452 }
12453 else if (child.type === 11 /* FOR */) {
12454 // Do not hoist v-for single child because it has to be a block
12455 walk(child, context, child.children.length === 1);
12456 }
12457 else if (child.type === 9 /* IF */) {
12458 for (let i = 0; i < child.branches.length; i++) {
12459 // Do not hoist v-if single child because it has to be a block
12460 walk(child.branches[i], context, child.branches[i].children.length === 1);
12461 }
12462 }
12463 }
12464 if (hoistedCount && context.transformHoist) {
12465 context.transformHoist(children, context, node);
12466 }
12467 // all children were hoisted - the entire children array is hoistable.
12468 if (hoistedCount &&
12469 hoistedCount === originalCount &&
12470 node.type === 1 /* ELEMENT */ &&
12471 node.tagType === 0 /* ELEMENT */ &&
12472 node.codegenNode &&
12473 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12474 isArray(node.codegenNode.children)) {
12475 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12476 }
12477 }
12478 function getConstantType(node, context) {
12479 const { constantCache } = context;
12480 switch (node.type) {
12481 case 1 /* ELEMENT */:
12482 if (node.tagType !== 0 /* ELEMENT */) {
12483 return 0 /* NOT_CONSTANT */;
12484 }
12485 const cached = constantCache.get(node);
12486 if (cached !== undefined) {
12487 return cached;
12488 }
12489 const codegenNode = node.codegenNode;
12490 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12491 return 0 /* NOT_CONSTANT */;
12492 }
12493 if (codegenNode.isBlock &&
12494 node.tag !== 'svg' &&
12495 node.tag !== 'foreignObject') {
12496 return 0 /* NOT_CONSTANT */;
12497 }
12498 const flag = getPatchFlag(codegenNode);
12499 if (!flag) {
12500 let returnType = 3 /* CAN_STRINGIFY */;
12501 // Element itself has no patch flag. However we still need to check:
12502 // 1. Even for a node with no patch flag, it is possible for it to contain
12503 // non-hoistable expressions that refers to scope variables, e.g. compiler
12504 // injected keys or cached event handlers. Therefore we need to always
12505 // check the codegenNode's props to be sure.
12506 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12507 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12508 constantCache.set(node, 0 /* NOT_CONSTANT */);
12509 return 0 /* NOT_CONSTANT */;
12510 }
12511 if (generatedPropsType < returnType) {
12512 returnType = generatedPropsType;
12513 }
12514 // 2. its children.
12515 for (let i = 0; i < node.children.length; i++) {
12516 const childType = getConstantType(node.children[i], context);
12517 if (childType === 0 /* NOT_CONSTANT */) {
12518 constantCache.set(node, 0 /* NOT_CONSTANT */);
12519 return 0 /* NOT_CONSTANT */;
12520 }
12521 if (childType < returnType) {
12522 returnType = childType;
12523 }
12524 }
12525 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12526 // type, check if any of the props can cause the type to be lowered
12527 // we can skip can_patch because it's guaranteed by the absence of a
12528 // patchFlag.
12529 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12530 for (let i = 0; i < node.props.length; i++) {
12531 const p = node.props[i];
12532 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12533 const expType = getConstantType(p.exp, context);
12534 if (expType === 0 /* NOT_CONSTANT */) {
12535 constantCache.set(node, 0 /* NOT_CONSTANT */);
12536 return 0 /* NOT_CONSTANT */;
12537 }
12538 if (expType < returnType) {
12539 returnType = expType;
12540 }
12541 }
12542 }
12543 }
12544 // only svg/foreignObject could be block here, however if they are
12545 // static then they don't need to be blocks since there will be no
12546 // nested updates.
12547 if (codegenNode.isBlock) {
12548 // except set custom directives.
12549 for (let i = 0; i < node.props.length; i++) {
12550 const p = node.props[i];
12551 if (p.type === 7 /* DIRECTIVE */) {
12552 constantCache.set(node, 0 /* NOT_CONSTANT */);
12553 return 0 /* NOT_CONSTANT */;
12554 }
12555 }
12556 context.removeHelper(OPEN_BLOCK);
12557 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12558 codegenNode.isBlock = false;
12559 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12560 }
12561 constantCache.set(node, returnType);
12562 return returnType;
12563 }
12564 else {
12565 constantCache.set(node, 0 /* NOT_CONSTANT */);
12566 return 0 /* NOT_CONSTANT */;
12567 }
12568 case 2 /* TEXT */:
12569 case 3 /* COMMENT */:
12570 return 3 /* CAN_STRINGIFY */;
12571 case 9 /* IF */:
12572 case 11 /* FOR */:
12573 case 10 /* IF_BRANCH */:
12574 return 0 /* NOT_CONSTANT */;
12575 case 5 /* INTERPOLATION */:
12576 case 12 /* TEXT_CALL */:
12577 return getConstantType(node.content, context);
12578 case 4 /* SIMPLE_EXPRESSION */:
12579 return node.constType;
12580 case 8 /* COMPOUND_EXPRESSION */:
12581 let returnType = 3 /* CAN_STRINGIFY */;
12582 for (let i = 0; i < node.children.length; i++) {
12583 const child = node.children[i];
12584 if (isString(child) || isSymbol(child)) {
12585 continue;
12586 }
12587 const childType = getConstantType(child, context);
12588 if (childType === 0 /* NOT_CONSTANT */) {
12589 return 0 /* NOT_CONSTANT */;
12590 }
12591 else if (childType < returnType) {
12592 returnType = childType;
12593 }
12594 }
12595 return returnType;
12596 default:
12597 return 0 /* NOT_CONSTANT */;
12598 }
12599 }
12600 const allowHoistedHelperSet = new Set([
12601 NORMALIZE_CLASS,
12602 NORMALIZE_STYLE,
12603 NORMALIZE_PROPS,
12604 GUARD_REACTIVE_PROPS
12605 ]);
12606 function getConstantTypeOfHelperCall(value, context) {
12607 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12608 !isString(value.callee) &&
12609 allowHoistedHelperSet.has(value.callee)) {
12610 const arg = value.arguments[0];
12611 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12612 return getConstantType(arg, context);
12613 }
12614 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12615 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12616 return getConstantTypeOfHelperCall(arg, context);
12617 }
12618 }
12619 return 0 /* NOT_CONSTANT */;
12620 }
12621 function getGeneratedPropsConstantType(node, context) {
12622 let returnType = 3 /* CAN_STRINGIFY */;
12623 const props = getNodeProps(node);
12624 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12625 const { properties } = props;
12626 for (let i = 0; i < properties.length; i++) {
12627 const { key, value } = properties[i];
12628 const keyType = getConstantType(key, context);
12629 if (keyType === 0 /* NOT_CONSTANT */) {
12630 return keyType;
12631 }
12632 if (keyType < returnType) {
12633 returnType = keyType;
12634 }
12635 let valueType;
12636 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12637 valueType = getConstantType(value, context);
12638 }
12639 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12640 // some helper calls can be hoisted,
12641 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12642 // in this case we need to respect the ConstantType of the helper's arguments
12643 valueType = getConstantTypeOfHelperCall(value, context);
12644 }
12645 else {
12646 valueType = 0 /* NOT_CONSTANT */;
12647 }
12648 if (valueType === 0 /* NOT_CONSTANT */) {
12649 return valueType;
12650 }
12651 if (valueType < returnType) {
12652 returnType = valueType;
12653 }
12654 }
12655 }
12656 return returnType;
12657 }
12658 function getNodeProps(node) {
12659 const codegenNode = node.codegenNode;
12660 if (codegenNode.type === 13 /* VNODE_CALL */) {
12661 return codegenNode.props;
12662 }
12663 }
12664 function getPatchFlag(node) {
12665 const flag = node.patchFlag;
12666 return flag ? parseInt(flag, 10) : undefined;
12667 }
12668
12669 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, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
12670 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12671 const context = {
12672 // options
12673 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12674 prefixIdentifiers,
12675 hoistStatic,
12676 cacheHandlers,
12677 nodeTransforms,
12678 directiveTransforms,
12679 transformHoist,
12680 isBuiltInComponent,
12681 isCustomElement,
12682 expressionPlugins,
12683 scopeId,
12684 slotted,
12685 ssr,
12686 inSSR,
12687 ssrCssVars,
12688 bindingMetadata,
12689 inline,
12690 isTS,
12691 onError,
12692 onWarn,
12693 compatConfig,
12694 // state
12695 root,
12696 helpers: new Map(),
12697 components: new Set(),
12698 directives: new Set(),
12699 hoists: [],
12700 imports: [],
12701 constantCache: new Map(),
12702 temps: 0,
12703 cached: 0,
12704 identifiers: Object.create(null),
12705 scopes: {
12706 vFor: 0,
12707 vSlot: 0,
12708 vPre: 0,
12709 vOnce: 0
12710 },
12711 parent: null,
12712 currentNode: root,
12713 childIndex: 0,
12714 inVOnce: false,
12715 // methods
12716 helper(name) {
12717 const count = context.helpers.get(name) || 0;
12718 context.helpers.set(name, count + 1);
12719 return name;
12720 },
12721 removeHelper(name) {
12722 const count = context.helpers.get(name);
12723 if (count) {
12724 const currentCount = count - 1;
12725 if (!currentCount) {
12726 context.helpers.delete(name);
12727 }
12728 else {
12729 context.helpers.set(name, currentCount);
12730 }
12731 }
12732 },
12733 helperString(name) {
12734 return `_${helperNameMap[context.helper(name)]}`;
12735 },
12736 replaceNode(node) {
12737 /* istanbul ignore if */
12738 {
12739 if (!context.currentNode) {
12740 throw new Error(`Node being replaced is already removed.`);
12741 }
12742 if (!context.parent) {
12743 throw new Error(`Cannot replace root node.`);
12744 }
12745 }
12746 context.parent.children[context.childIndex] = context.currentNode = node;
12747 },
12748 removeNode(node) {
12749 if (!context.parent) {
12750 throw new Error(`Cannot remove root node.`);
12751 }
12752 const list = context.parent.children;
12753 const removalIndex = node
12754 ? list.indexOf(node)
12755 : context.currentNode
12756 ? context.childIndex
12757 : -1;
12758 /* istanbul ignore if */
12759 if (removalIndex < 0) {
12760 throw new Error(`node being removed is not a child of current parent`);
12761 }
12762 if (!node || node === context.currentNode) {
12763 // current node removed
12764 context.currentNode = null;
12765 context.onNodeRemoved();
12766 }
12767 else {
12768 // sibling node removed
12769 if (context.childIndex > removalIndex) {
12770 context.childIndex--;
12771 context.onNodeRemoved();
12772 }
12773 }
12774 context.parent.children.splice(removalIndex, 1);
12775 },
12776 onNodeRemoved: () => { },
12777 addIdentifiers(exp) {
12778 },
12779 removeIdentifiers(exp) {
12780 },
12781 hoist(exp) {
12782 if (isString(exp))
12783 exp = createSimpleExpression(exp);
12784 context.hoists.push(exp);
12785 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12786 identifier.hoisted = exp;
12787 return identifier;
12788 },
12789 cache(exp, isVNode = false) {
12790 return createCacheExpression(context.cached++, exp, isVNode);
12791 }
12792 };
12793 return context;
12794 }
12795 function transform(root, options) {
12796 const context = createTransformContext(root, options);
12797 traverseNode(root, context);
12798 if (options.hoistStatic) {
12799 hoistStatic(root, context);
12800 }
12801 if (!options.ssr) {
12802 createRootCodegen(root, context);
12803 }
12804 // finalize meta information
12805 root.helpers = [...context.helpers.keys()];
12806 root.components = [...context.components];
12807 root.directives = [...context.directives];
12808 root.imports = context.imports;
12809 root.hoists = context.hoists;
12810 root.temps = context.temps;
12811 root.cached = context.cached;
12812 }
12813 function createRootCodegen(root, context) {
12814 const { helper } = context;
12815 const { children } = root;
12816 if (children.length === 1) {
12817 const child = children[0];
12818 // if the single child is an element, turn it into a block.
12819 if (isSingleElementRoot(root, child) && child.codegenNode) {
12820 // single element root is never hoisted so codegenNode will never be
12821 // SimpleExpressionNode
12822 const codegenNode = child.codegenNode;
12823 if (codegenNode.type === 13 /* VNODE_CALL */) {
12824 makeBlock(codegenNode, context);
12825 }
12826 root.codegenNode = codegenNode;
12827 }
12828 else {
12829 // - single <slot/>, IfNode, ForNode: already blocks.
12830 // - single text node: always patched.
12831 // root codegen falls through via genNode()
12832 root.codegenNode = child;
12833 }
12834 }
12835 else if (children.length > 1) {
12836 // root has multiple nodes - return a fragment block.
12837 let patchFlag = 64 /* STABLE_FRAGMENT */;
12838 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12839 // check if the fragment actually contains a single valid child with
12840 // the rest being comments
12841 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12842 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12843 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12844 }
12845 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12846 }
12847 else ;
12848 }
12849 function traverseChildren(parent, context) {
12850 let i = 0;
12851 const nodeRemoved = () => {
12852 i--;
12853 };
12854 for (; i < parent.children.length; i++) {
12855 const child = parent.children[i];
12856 if (isString(child))
12857 continue;
12858 context.parent = parent;
12859 context.childIndex = i;
12860 context.onNodeRemoved = nodeRemoved;
12861 traverseNode(child, context);
12862 }
12863 }
12864 function traverseNode(node, context) {
12865 context.currentNode = node;
12866 // apply transform plugins
12867 const { nodeTransforms } = context;
12868 const exitFns = [];
12869 for (let i = 0; i < nodeTransforms.length; i++) {
12870 const onExit = nodeTransforms[i](node, context);
12871 if (onExit) {
12872 if (isArray(onExit)) {
12873 exitFns.push(...onExit);
12874 }
12875 else {
12876 exitFns.push(onExit);
12877 }
12878 }
12879 if (!context.currentNode) {
12880 // node was removed
12881 return;
12882 }
12883 else {
12884 // node may have been replaced
12885 node = context.currentNode;
12886 }
12887 }
12888 switch (node.type) {
12889 case 3 /* COMMENT */:
12890 if (!context.ssr) {
12891 // inject import for the Comment symbol, which is needed for creating
12892 // comment nodes with `createVNode`
12893 context.helper(CREATE_COMMENT);
12894 }
12895 break;
12896 case 5 /* INTERPOLATION */:
12897 // no need to traverse, but we need to inject toString helper
12898 if (!context.ssr) {
12899 context.helper(TO_DISPLAY_STRING);
12900 }
12901 break;
12902 // for container types, further traverse downwards
12903 case 9 /* IF */:
12904 for (let i = 0; i < node.branches.length; i++) {
12905 traverseNode(node.branches[i], context);
12906 }
12907 break;
12908 case 10 /* IF_BRANCH */:
12909 case 11 /* FOR */:
12910 case 1 /* ELEMENT */:
12911 case 0 /* ROOT */:
12912 traverseChildren(node, context);
12913 break;
12914 }
12915 // exit transforms
12916 context.currentNode = node;
12917 let i = exitFns.length;
12918 while (i--) {
12919 exitFns[i]();
12920 }
12921 }
12922 function createStructuralDirectiveTransform(name, fn) {
12923 const matches = isString(name)
12924 ? (n) => n === name
12925 : (n) => name.test(n);
12926 return (node, context) => {
12927 if (node.type === 1 /* ELEMENT */) {
12928 const { props } = node;
12929 // structural directive transforms are not concerned with slots
12930 // as they are handled separately in vSlot.ts
12931 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
12932 return;
12933 }
12934 const exitFns = [];
12935 for (let i = 0; i < props.length; i++) {
12936 const prop = props[i];
12937 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
12938 // structural directives are removed to avoid infinite recursion
12939 // also we remove them *before* applying so that it can further
12940 // traverse itself in case it moves the node around
12941 props.splice(i, 1);
12942 i--;
12943 const onExit = fn(node, prop, context);
12944 if (onExit)
12945 exitFns.push(onExit);
12946 }
12947 }
12948 return exitFns;
12949 }
12950 };
12951 }
12952
12953 const PURE_ANNOTATION = `/*#__PURE__*/`;
12954 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
12955 function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
12956 const context = {
12957 mode,
12958 prefixIdentifiers,
12959 sourceMap,
12960 filename,
12961 scopeId,
12962 optimizeImports,
12963 runtimeGlobalName,
12964 runtimeModuleName,
12965 ssrRuntimeModuleName,
12966 ssr,
12967 isTS,
12968 inSSR,
12969 source: ast.loc.source,
12970 code: ``,
12971 column: 1,
12972 line: 1,
12973 offset: 0,
12974 indentLevel: 0,
12975 pure: false,
12976 map: undefined,
12977 helper(key) {
12978 return `_${helperNameMap[key]}`;
12979 },
12980 push(code, node) {
12981 context.code += code;
12982 },
12983 indent() {
12984 newline(++context.indentLevel);
12985 },
12986 deindent(withoutNewLine = false) {
12987 if (withoutNewLine) {
12988 --context.indentLevel;
12989 }
12990 else {
12991 newline(--context.indentLevel);
12992 }
12993 },
12994 newline() {
12995 newline(context.indentLevel);
12996 }
12997 };
12998 function newline(n) {
12999 context.push('\n' + ` `.repeat(n));
13000 }
13001 return context;
13002 }
13003 function generate(ast, options = {}) {
13004 const context = createCodegenContext(ast, options);
13005 if (options.onContextCreated)
13006 options.onContextCreated(context);
13007 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
13008 const hasHelpers = ast.helpers.length > 0;
13009 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13010 // preambles
13011 // in setup() inline mode, the preamble is generated in a sub context
13012 // and returned separately.
13013 const preambleContext = context;
13014 {
13015 genFunctionPreamble(ast, preambleContext);
13016 }
13017 // enter render function
13018 const functionName = ssr ? `ssrRender` : `render`;
13019 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13020 const signature = args.join(', ');
13021 {
13022 push(`function ${functionName}(${signature}) {`);
13023 }
13024 indent();
13025 if (useWithBlock) {
13026 push(`with (_ctx) {`);
13027 indent();
13028 // function mode const declarations should be inside with block
13029 // also they should be renamed to avoid collision with user properties
13030 if (hasHelpers) {
13031 push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
13032 push(`\n`);
13033 newline();
13034 }
13035 }
13036 // generate asset resolution statements
13037 if (ast.components.length) {
13038 genAssets(ast.components, 'component', context);
13039 if (ast.directives.length || ast.temps > 0) {
13040 newline();
13041 }
13042 }
13043 if (ast.directives.length) {
13044 genAssets(ast.directives, 'directive', context);
13045 if (ast.temps > 0) {
13046 newline();
13047 }
13048 }
13049 if (ast.temps > 0) {
13050 push(`let `);
13051 for (let i = 0; i < ast.temps; i++) {
13052 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13053 }
13054 }
13055 if (ast.components.length || ast.directives.length || ast.temps) {
13056 push(`\n`);
13057 newline();
13058 }
13059 // generate the VNode tree expression
13060 if (!ssr) {
13061 push(`return `);
13062 }
13063 if (ast.codegenNode) {
13064 genNode(ast.codegenNode, context);
13065 }
13066 else {
13067 push(`null`);
13068 }
13069 if (useWithBlock) {
13070 deindent();
13071 push(`}`);
13072 }
13073 deindent();
13074 push(`}`);
13075 return {
13076 ast,
13077 code: context.code,
13078 preamble: ``,
13079 // SourceMapGenerator does have toJSON() method but it's not in the types
13080 map: context.map ? context.map.toJSON() : undefined
13081 };
13082 }
13083 function genFunctionPreamble(ast, context) {
13084 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
13085 const VueBinding = runtimeGlobalName;
13086 // Generate const declaration for helpers
13087 // In prefix mode, we place the const declaration at top so it's done
13088 // only once; But if we not prefixing, we place the declaration inside the
13089 // with block so it doesn't incur the `in` check cost for every helper access.
13090 if (ast.helpers.length > 0) {
13091 {
13092 // "with" mode.
13093 // save Vue in a separate variable to avoid collision
13094 push(`const _Vue = ${VueBinding}\n`);
13095 // in "with" mode, helpers are declared inside the with block to avoid
13096 // has check cost, but hoists are lifted out of the function - we need
13097 // to provide the helper here.
13098 if (ast.hoists.length) {
13099 const staticHelpers = [
13100 CREATE_VNODE,
13101 CREATE_ELEMENT_VNODE,
13102 CREATE_COMMENT,
13103 CREATE_TEXT,
13104 CREATE_STATIC
13105 ]
13106 .filter(helper => ast.helpers.includes(helper))
13107 .map(aliasHelper)
13108 .join(', ');
13109 push(`const { ${staticHelpers} } = _Vue\n`);
13110 }
13111 }
13112 }
13113 genHoists(ast.hoists, context);
13114 newline();
13115 push(`return `);
13116 }
13117 function genAssets(assets, type, { helper, push, newline, isTS }) {
13118 const resolver = helper(type === 'component'
13119 ? RESOLVE_COMPONENT
13120 : RESOLVE_DIRECTIVE);
13121 for (let i = 0; i < assets.length; i++) {
13122 let id = assets[i];
13123 // potential component implicit self-reference inferred from SFC filename
13124 const maybeSelfReference = id.endsWith('__self');
13125 if (maybeSelfReference) {
13126 id = id.slice(0, -6);
13127 }
13128 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13129 if (i < assets.length - 1) {
13130 newline();
13131 }
13132 }
13133 }
13134 function genHoists(hoists, context) {
13135 if (!hoists.length) {
13136 return;
13137 }
13138 context.pure = true;
13139 const { push, newline, helper, scopeId, mode } = context;
13140 newline();
13141 for (let i = 0; i < hoists.length; i++) {
13142 const exp = hoists[i];
13143 if (exp) {
13144 push(`const _hoisted_${i + 1} = ${``}`);
13145 genNode(exp, context);
13146 newline();
13147 }
13148 }
13149 context.pure = false;
13150 }
13151 function isText$1(n) {
13152 return (isString(n) ||
13153 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13154 n.type === 2 /* TEXT */ ||
13155 n.type === 5 /* INTERPOLATION */ ||
13156 n.type === 8 /* COMPOUND_EXPRESSION */);
13157 }
13158 function genNodeListAsArray(nodes, context) {
13159 const multilines = nodes.length > 3 ||
13160 (nodes.some(n => isArray(n) || !isText$1(n)));
13161 context.push(`[`);
13162 multilines && context.indent();
13163 genNodeList(nodes, context, multilines);
13164 multilines && context.deindent();
13165 context.push(`]`);
13166 }
13167 function genNodeList(nodes, context, multilines = false, comma = true) {
13168 const { push, newline } = context;
13169 for (let i = 0; i < nodes.length; i++) {
13170 const node = nodes[i];
13171 if (isString(node)) {
13172 push(node);
13173 }
13174 else if (isArray(node)) {
13175 genNodeListAsArray(node, context);
13176 }
13177 else {
13178 genNode(node, context);
13179 }
13180 if (i < nodes.length - 1) {
13181 if (multilines) {
13182 comma && push(',');
13183 newline();
13184 }
13185 else {
13186 comma && push(', ');
13187 }
13188 }
13189 }
13190 }
13191 function genNode(node, context) {
13192 if (isString(node)) {
13193 context.push(node);
13194 return;
13195 }
13196 if (isSymbol(node)) {
13197 context.push(context.helper(node));
13198 return;
13199 }
13200 switch (node.type) {
13201 case 1 /* ELEMENT */:
13202 case 9 /* IF */:
13203 case 11 /* FOR */:
13204 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13205 `Apply appropriate transforms first.`);
13206 genNode(node.codegenNode, context);
13207 break;
13208 case 2 /* TEXT */:
13209 genText(node, context);
13210 break;
13211 case 4 /* SIMPLE_EXPRESSION */:
13212 genExpression(node, context);
13213 break;
13214 case 5 /* INTERPOLATION */:
13215 genInterpolation(node, context);
13216 break;
13217 case 12 /* TEXT_CALL */:
13218 genNode(node.codegenNode, context);
13219 break;
13220 case 8 /* COMPOUND_EXPRESSION */:
13221 genCompoundExpression(node, context);
13222 break;
13223 case 3 /* COMMENT */:
13224 genComment(node, context);
13225 break;
13226 case 13 /* VNODE_CALL */:
13227 genVNodeCall(node, context);
13228 break;
13229 case 14 /* JS_CALL_EXPRESSION */:
13230 genCallExpression(node, context);
13231 break;
13232 case 15 /* JS_OBJECT_EXPRESSION */:
13233 genObjectExpression(node, context);
13234 break;
13235 case 17 /* JS_ARRAY_EXPRESSION */:
13236 genArrayExpression(node, context);
13237 break;
13238 case 18 /* JS_FUNCTION_EXPRESSION */:
13239 genFunctionExpression(node, context);
13240 break;
13241 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13242 genConditionalExpression(node, context);
13243 break;
13244 case 20 /* JS_CACHE_EXPRESSION */:
13245 genCacheExpression(node, context);
13246 break;
13247 case 21 /* JS_BLOCK_STATEMENT */:
13248 genNodeList(node.body, context, true, false);
13249 break;
13250 // SSR only types
13251 case 22 /* JS_TEMPLATE_LITERAL */:
13252 break;
13253 case 23 /* JS_IF_STATEMENT */:
13254 break;
13255 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13256 break;
13257 case 25 /* JS_SEQUENCE_EXPRESSION */:
13258 break;
13259 case 26 /* JS_RETURN_STATEMENT */:
13260 break;
13261 /* istanbul ignore next */
13262 case 10 /* IF_BRANCH */:
13263 // noop
13264 break;
13265 default:
13266 {
13267 assert(false, `unhandled codegen node type: ${node.type}`);
13268 // make sure we exhaust all possible types
13269 const exhaustiveCheck = node;
13270 return exhaustiveCheck;
13271 }
13272 }
13273 }
13274 function genText(node, context) {
13275 context.push(JSON.stringify(node.content), node);
13276 }
13277 function genExpression(node, context) {
13278 const { content, isStatic } = node;
13279 context.push(isStatic ? JSON.stringify(content) : content, node);
13280 }
13281 function genInterpolation(node, context) {
13282 const { push, helper, pure } = context;
13283 if (pure)
13284 push(PURE_ANNOTATION);
13285 push(`${helper(TO_DISPLAY_STRING)}(`);
13286 genNode(node.content, context);
13287 push(`)`);
13288 }
13289 function genCompoundExpression(node, context) {
13290 for (let i = 0; i < node.children.length; i++) {
13291 const child = node.children[i];
13292 if (isString(child)) {
13293 context.push(child);
13294 }
13295 else {
13296 genNode(child, context);
13297 }
13298 }
13299 }
13300 function genExpressionAsPropertyKey(node, context) {
13301 const { push } = context;
13302 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13303 push(`[`);
13304 genCompoundExpression(node, context);
13305 push(`]`);
13306 }
13307 else if (node.isStatic) {
13308 // only quote keys if necessary
13309 const text = isSimpleIdentifier(node.content)
13310 ? node.content
13311 : JSON.stringify(node.content);
13312 push(text, node);
13313 }
13314 else {
13315 push(`[${node.content}]`, node);
13316 }
13317 }
13318 function genComment(node, context) {
13319 const { push, helper, pure } = context;
13320 if (pure) {
13321 push(PURE_ANNOTATION);
13322 }
13323 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13324 }
13325 function genVNodeCall(node, context) {
13326 const { push, helper, pure } = context;
13327 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13328 if (directives) {
13329 push(helper(WITH_DIRECTIVES) + `(`);
13330 }
13331 if (isBlock) {
13332 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13333 }
13334 if (pure) {
13335 push(PURE_ANNOTATION);
13336 }
13337 const callHelper = isBlock
13338 ? getVNodeBlockHelper(context.inSSR, isComponent)
13339 : getVNodeHelper(context.inSSR, isComponent);
13340 push(helper(callHelper) + `(`, node);
13341 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13342 push(`)`);
13343 if (isBlock) {
13344 push(`)`);
13345 }
13346 if (directives) {
13347 push(`, `);
13348 genNode(directives, context);
13349 push(`)`);
13350 }
13351 }
13352 function genNullableArgs(args) {
13353 let i = args.length;
13354 while (i--) {
13355 if (args[i] != null)
13356 break;
13357 }
13358 return args.slice(0, i + 1).map(arg => arg || `null`);
13359 }
13360 // JavaScript
13361 function genCallExpression(node, context) {
13362 const { push, helper, pure } = context;
13363 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13364 if (pure) {
13365 push(PURE_ANNOTATION);
13366 }
13367 push(callee + `(`, node);
13368 genNodeList(node.arguments, context);
13369 push(`)`);
13370 }
13371 function genObjectExpression(node, context) {
13372 const { push, indent, deindent, newline } = context;
13373 const { properties } = node;
13374 if (!properties.length) {
13375 push(`{}`, node);
13376 return;
13377 }
13378 const multilines = properties.length > 1 ||
13379 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13380 push(multilines ? `{` : `{ `);
13381 multilines && indent();
13382 for (let i = 0; i < properties.length; i++) {
13383 const { key, value } = properties[i];
13384 // key
13385 genExpressionAsPropertyKey(key, context);
13386 push(`: `);
13387 // value
13388 genNode(value, context);
13389 if (i < properties.length - 1) {
13390 // will only reach this if it's multilines
13391 push(`,`);
13392 newline();
13393 }
13394 }
13395 multilines && deindent();
13396 push(multilines ? `}` : ` }`);
13397 }
13398 function genArrayExpression(node, context) {
13399 genNodeListAsArray(node.elements, context);
13400 }
13401 function genFunctionExpression(node, context) {
13402 const { push, indent, deindent } = context;
13403 const { params, returns, body, newline, isSlot } = node;
13404 if (isSlot) {
13405 // wrap slot functions with owner context
13406 push(`_${helperNameMap[WITH_CTX]}(`);
13407 }
13408 push(`(`, node);
13409 if (isArray(params)) {
13410 genNodeList(params, context);
13411 }
13412 else if (params) {
13413 genNode(params, context);
13414 }
13415 push(`) => `);
13416 if (newline || body) {
13417 push(`{`);
13418 indent();
13419 }
13420 if (returns) {
13421 if (newline) {
13422 push(`return `);
13423 }
13424 if (isArray(returns)) {
13425 genNodeListAsArray(returns, context);
13426 }
13427 else {
13428 genNode(returns, context);
13429 }
13430 }
13431 else if (body) {
13432 genNode(body, context);
13433 }
13434 if (newline || body) {
13435 deindent();
13436 push(`}`);
13437 }
13438 if (isSlot) {
13439 push(`)`);
13440 }
13441 }
13442 function genConditionalExpression(node, context) {
13443 const { test, consequent, alternate, newline: needNewline } = node;
13444 const { push, indent, deindent, newline } = context;
13445 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13446 const needsParens = !isSimpleIdentifier(test.content);
13447 needsParens && push(`(`);
13448 genExpression(test, context);
13449 needsParens && push(`)`);
13450 }
13451 else {
13452 push(`(`);
13453 genNode(test, context);
13454 push(`)`);
13455 }
13456 needNewline && indent();
13457 context.indentLevel++;
13458 needNewline || push(` `);
13459 push(`? `);
13460 genNode(consequent, context);
13461 context.indentLevel--;
13462 needNewline && newline();
13463 needNewline || push(` `);
13464 push(`: `);
13465 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13466 if (!isNested) {
13467 context.indentLevel++;
13468 }
13469 genNode(alternate, context);
13470 if (!isNested) {
13471 context.indentLevel--;
13472 }
13473 needNewline && deindent(true /* without newline */);
13474 }
13475 function genCacheExpression(node, context) {
13476 const { push, helper, indent, deindent, newline } = context;
13477 push(`_cache[${node.index}] || (`);
13478 if (node.isVNode) {
13479 indent();
13480 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13481 newline();
13482 }
13483 push(`_cache[${node.index}] = `);
13484 genNode(node.value, context);
13485 if (node.isVNode) {
13486 push(`,`);
13487 newline();
13488 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13489 newline();
13490 push(`_cache[${node.index}]`);
13491 deindent();
13492 }
13493 push(`)`);
13494 }
13495
13496 // these keywords should not appear inside expressions, but operators like
13497 // typeof, instanceof and in are allowed
13498 const prohibitedKeywordRE = new RegExp('\\b' +
13499 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13500 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13501 'extends,finally,continue,debugger,function,arguments,typeof,void')
13502 .split(',')
13503 .join('\\b|\\b') +
13504 '\\b');
13505 // strip strings in expressions
13506 const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13507 /**
13508 * Validate a non-prefixed expression.
13509 * This is only called when using the in-browser runtime compiler since it
13510 * doesn't prefix expressions.
13511 */
13512 function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13513 const exp = node.content;
13514 // empty expressions are validated per-directive since some directives
13515 // do allow empty expressions.
13516 if (!exp.trim()) {
13517 return;
13518 }
13519 try {
13520 new Function(asRawStatements
13521 ? ` ${exp} `
13522 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13523 }
13524 catch (e) {
13525 let message = e.message;
13526 const keywordMatch = exp
13527 .replace(stripStringRE, '')
13528 .match(prohibitedKeywordRE);
13529 if (keywordMatch) {
13530 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13531 }
13532 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13533 }
13534 }
13535
13536 const transformExpression = (node, context) => {
13537 if (node.type === 5 /* INTERPOLATION */) {
13538 node.content = processExpression(node.content, context);
13539 }
13540 else if (node.type === 1 /* ELEMENT */) {
13541 // handle directives on element
13542 for (let i = 0; i < node.props.length; i++) {
13543 const dir = node.props[i];
13544 // do not process for v-on & v-for since they are special handled
13545 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13546 const exp = dir.exp;
13547 const arg = dir.arg;
13548 // do not process exp if this is v-on:arg - we need special handling
13549 // for wrapping inline statements.
13550 if (exp &&
13551 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13552 !(dir.name === 'on' && arg)) {
13553 dir.exp = processExpression(exp, context,
13554 // slot args must be processed as function params
13555 dir.name === 'slot');
13556 }
13557 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13558 dir.arg = processExpression(arg, context);
13559 }
13560 }
13561 }
13562 }
13563 };
13564 // Important: since this function uses Node.js only dependencies, it should
13565 // always be used with a leading !true check so that it can be
13566 // tree-shaken from the browser build.
13567 function processExpression(node, context,
13568 // some expressions like v-slot props & v-for aliases should be parsed as
13569 // function params
13570 asParams = false,
13571 // v-on handler values may contain multiple statements
13572 asRawStatements = false, localVars = Object.create(context.identifiers)) {
13573 {
13574 {
13575 // simple in-browser validation (same logic in 2.x)
13576 validateBrowserExpression(node, context, asParams, asRawStatements);
13577 }
13578 return node;
13579 }
13580 }
13581
13582 const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13583 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13584 // #1587: We need to dynamically increment the key based on the current
13585 // node's sibling nodes, since chained v-if/else branches are
13586 // rendered at the same depth
13587 const siblings = context.parent.children;
13588 let i = siblings.indexOf(ifNode);
13589 let key = 0;
13590 while (i-- >= 0) {
13591 const sibling = siblings[i];
13592 if (sibling && sibling.type === 9 /* IF */) {
13593 key += sibling.branches.length;
13594 }
13595 }
13596 // Exit callback. Complete the codegenNode when all children have been
13597 // transformed.
13598 return () => {
13599 if (isRoot) {
13600 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13601 }
13602 else {
13603 // attach this branch's codegen node to the v-if root.
13604 const parentCondition = getParentCondition(ifNode.codegenNode);
13605 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13606 }
13607 };
13608 });
13609 });
13610 // target-agnostic transform used for both Client and SSR
13611 function processIf(node, dir, context, processCodegen) {
13612 if (dir.name !== 'else' &&
13613 (!dir.exp || !dir.exp.content.trim())) {
13614 const loc = dir.exp ? dir.exp.loc : node.loc;
13615 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13616 dir.exp = createSimpleExpression(`true`, false, loc);
13617 }
13618 if (dir.exp) {
13619 validateBrowserExpression(dir.exp, context);
13620 }
13621 if (dir.name === 'if') {
13622 const branch = createIfBranch(node, dir);
13623 const ifNode = {
13624 type: 9 /* IF */,
13625 loc: node.loc,
13626 branches: [branch]
13627 };
13628 context.replaceNode(ifNode);
13629 if (processCodegen) {
13630 return processCodegen(ifNode, branch, true);
13631 }
13632 }
13633 else {
13634 // locate the adjacent v-if
13635 const siblings = context.parent.children;
13636 const comments = [];
13637 let i = siblings.indexOf(node);
13638 while (i-- >= -1) {
13639 const sibling = siblings[i];
13640 if (sibling && sibling.type === 3 /* COMMENT */) {
13641 context.removeNode(sibling);
13642 comments.unshift(sibling);
13643 continue;
13644 }
13645 if (sibling &&
13646 sibling.type === 2 /* TEXT */ &&
13647 !sibling.content.trim().length) {
13648 context.removeNode(sibling);
13649 continue;
13650 }
13651 if (sibling && sibling.type === 9 /* IF */) {
13652 // Check if v-else was followed by v-else-if
13653 if (dir.name === 'else-if' &&
13654 sibling.branches[sibling.branches.length - 1].condition === undefined) {
13655 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13656 }
13657 // move the node to the if node's branches
13658 context.removeNode();
13659 const branch = createIfBranch(node, dir);
13660 if (comments.length &&
13661 // #3619 ignore comments if the v-if is direct child of <transition>
13662 !(context.parent &&
13663 context.parent.type === 1 /* ELEMENT */ &&
13664 isBuiltInType(context.parent.tag, 'transition'))) {
13665 branch.children = [...comments, ...branch.children];
13666 }
13667 // check if user is forcing same key on different branches
13668 {
13669 const key = branch.userKey;
13670 if (key) {
13671 sibling.branches.forEach(({ userKey }) => {
13672 if (isSameKey(userKey, key)) {
13673 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13674 }
13675 });
13676 }
13677 }
13678 sibling.branches.push(branch);
13679 const onExit = processCodegen && processCodegen(sibling, branch, false);
13680 // since the branch was removed, it will not be traversed.
13681 // make sure to traverse here.
13682 traverseNode(branch, context);
13683 // call on exit
13684 if (onExit)
13685 onExit();
13686 // make sure to reset currentNode after traversal to indicate this
13687 // node has been removed.
13688 context.currentNode = null;
13689 }
13690 else {
13691 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13692 }
13693 break;
13694 }
13695 }
13696 }
13697 function createIfBranch(node, dir) {
13698 const isTemplateIf = node.tagType === 3 /* TEMPLATE */;
13699 return {
13700 type: 10 /* IF_BRANCH */,
13701 loc: node.loc,
13702 condition: dir.name === 'else' ? undefined : dir.exp,
13703 children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
13704 userKey: findProp(node, `key`),
13705 isTemplateIf
13706 };
13707 }
13708 function createCodegenNodeForBranch(branch, keyIndex, context) {
13709 if (branch.condition) {
13710 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13711 // make sure to pass in asBlock: true so that the comment node call
13712 // closes the current block.
13713 createCallExpression(context.helper(CREATE_COMMENT), [
13714 '"v-if"' ,
13715 'true'
13716 ]));
13717 }
13718 else {
13719 return createChildrenCodegenNode(branch, keyIndex, context);
13720 }
13721 }
13722 function createChildrenCodegenNode(branch, keyIndex, context) {
13723 const { helper } = context;
13724 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13725 const { children } = branch;
13726 const firstChild = children[0];
13727 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13728 if (needFragmentWrapper) {
13729 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13730 // optimize away nested fragments when child is a ForNode
13731 const vnodeCall = firstChild.codegenNode;
13732 injectProp(vnodeCall, keyProperty, context);
13733 return vnodeCall;
13734 }
13735 else {
13736 let patchFlag = 64 /* STABLE_FRAGMENT */;
13737 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13738 // check if the fragment actually contains a single valid child with
13739 // the rest being comments
13740 if (!branch.isTemplateIf &&
13741 children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13742 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13743 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13744 }
13745 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13746 }
13747 }
13748 else {
13749 const ret = firstChild.codegenNode;
13750 const vnodeCall = getMemoedVNodeCall(ret);
13751 // Change createVNode to createBlock.
13752 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13753 makeBlock(vnodeCall, context);
13754 }
13755 // inject branch key
13756 injectProp(vnodeCall, keyProperty, context);
13757 return ret;
13758 }
13759 }
13760 function isSameKey(a, b) {
13761 if (!a || a.type !== b.type) {
13762 return false;
13763 }
13764 if (a.type === 6 /* ATTRIBUTE */) {
13765 if (a.value.content !== b.value.content) {
13766 return false;
13767 }
13768 }
13769 else {
13770 // directive
13771 const exp = a.exp;
13772 const branchExp = b.exp;
13773 if (exp.type !== branchExp.type) {
13774 return false;
13775 }
13776 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13777 exp.isStatic !== branchExp.isStatic ||
13778 exp.content !== branchExp.content) {
13779 return false;
13780 }
13781 }
13782 return true;
13783 }
13784 function getParentCondition(node) {
13785 while (true) {
13786 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13787 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13788 node = node.alternate;
13789 }
13790 else {
13791 return node;
13792 }
13793 }
13794 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13795 node = node.value;
13796 }
13797 }
13798 }
13799
13800 const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13801 const { helper, removeHelper } = context;
13802 return processFor(node, dir, context, forNode => {
13803 // create the loop render function expression now, and add the
13804 // iterator on exit after all children have been traversed
13805 const renderExp = createCallExpression(helper(RENDER_LIST), [
13806 forNode.source
13807 ]);
13808 const isTemplate = isTemplateNode(node);
13809 const memo = findDir(node, 'memo');
13810 const keyProp = findProp(node, `key`);
13811 const keyExp = keyProp &&
13812 (keyProp.type === 6 /* ATTRIBUTE */
13813 ? createSimpleExpression(keyProp.value.content, true)
13814 : keyProp.exp);
13815 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13816 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13817 forNode.source.constType > 0 /* NOT_CONSTANT */;
13818 const fragmentFlag = isStableFragment
13819 ? 64 /* STABLE_FRAGMENT */
13820 : keyProp
13821 ? 128 /* KEYED_FRAGMENT */
13822 : 256 /* UNKEYED_FRAGMENT */;
13823 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13824 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13825 return () => {
13826 // finish the codegen now that all children have been traversed
13827 let childBlock;
13828 const { children } = forNode;
13829 // check <template v-for> key placement
13830 if (isTemplate) {
13831 node.children.some(c => {
13832 if (c.type === 1 /* ELEMENT */) {
13833 const key = findProp(c, 'key');
13834 if (key) {
13835 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13836 return true;
13837 }
13838 }
13839 });
13840 }
13841 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13842 const slotOutlet = isSlotOutlet(node)
13843 ? node
13844 : isTemplate &&
13845 node.children.length === 1 &&
13846 isSlotOutlet(node.children[0])
13847 ? node.children[0] // api-extractor somehow fails to infer this
13848 : null;
13849 if (slotOutlet) {
13850 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13851 childBlock = slotOutlet.codegenNode;
13852 if (isTemplate && keyProperty) {
13853 // <template v-for="..." :key="..."><slot/></template>
13854 // we need to inject the key to the renderSlot() call.
13855 // the props for renderSlot is passed as the 3rd argument.
13856 injectProp(childBlock, keyProperty, context);
13857 }
13858 }
13859 else if (needFragmentWrapper) {
13860 // <template v-for="..."> with text or multi-elements
13861 // should generate a fragment block for each loop
13862 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
13863 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
13864 ), undefined, undefined, true, undefined, false /* isComponent */);
13865 }
13866 else {
13867 // Normal element v-for. Directly use the child's codegenNode
13868 // but mark it as a block.
13869 childBlock = children[0]
13870 .codegenNode;
13871 if (isTemplate && keyProperty) {
13872 injectProp(childBlock, keyProperty, context);
13873 }
13874 if (childBlock.isBlock !== !isStableFragment) {
13875 if (childBlock.isBlock) {
13876 // switch from block to vnode
13877 removeHelper(OPEN_BLOCK);
13878 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13879 }
13880 else {
13881 // switch from vnode to block
13882 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13883 }
13884 }
13885 childBlock.isBlock = !isStableFragment;
13886 if (childBlock.isBlock) {
13887 helper(OPEN_BLOCK);
13888 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13889 }
13890 else {
13891 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13892 }
13893 }
13894 if (memo) {
13895 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
13896 createSimpleExpression(`_cached`)
13897 ]));
13898 loop.body = createBlockStatement([
13899 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
13900 createCompoundExpression([
13901 `if (_cached`,
13902 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
13903 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
13904 ]),
13905 createCompoundExpression([`const _item = `, childBlock]),
13906 createSimpleExpression(`_item.memo = _memo`),
13907 createSimpleExpression(`return _item`)
13908 ]);
13909 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
13910 }
13911 else {
13912 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
13913 }
13914 };
13915 });
13916 });
13917 // target-agnostic transform used for both Client and SSR
13918 function processFor(node, dir, context, processCodegen) {
13919 if (!dir.exp) {
13920 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
13921 return;
13922 }
13923 const parseResult = parseForExpression(
13924 // can only be simple expression because vFor transform is applied
13925 // before expression transform.
13926 dir.exp, context);
13927 if (!parseResult) {
13928 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
13929 return;
13930 }
13931 const { addIdentifiers, removeIdentifiers, scopes } = context;
13932 const { source, value, key, index } = parseResult;
13933 const forNode = {
13934 type: 11 /* FOR */,
13935 loc: dir.loc,
13936 source,
13937 valueAlias: value,
13938 keyAlias: key,
13939 objectIndexAlias: index,
13940 parseResult,
13941 children: isTemplateNode(node) ? node.children : [node]
13942 };
13943 context.replaceNode(forNode);
13944 // bookkeeping
13945 scopes.vFor++;
13946 const onExit = processCodegen && processCodegen(forNode);
13947 return () => {
13948 scopes.vFor--;
13949 if (onExit)
13950 onExit();
13951 };
13952 }
13953 const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
13954 // This regex doesn't cover the case if key or index aliases have destructuring,
13955 // but those do not make sense in the first place, so this works in practice.
13956 const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
13957 const stripParensRE = /^\(|\)$/g;
13958 function parseForExpression(input, context) {
13959 const loc = input.loc;
13960 const exp = input.content;
13961 const inMatch = exp.match(forAliasRE);
13962 if (!inMatch)
13963 return;
13964 const [, LHS, RHS] = inMatch;
13965 const result = {
13966 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
13967 value: undefined,
13968 key: undefined,
13969 index: undefined
13970 };
13971 {
13972 validateBrowserExpression(result.source, context);
13973 }
13974 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
13975 const trimmedOffset = LHS.indexOf(valueContent);
13976 const iteratorMatch = valueContent.match(forIteratorRE);
13977 if (iteratorMatch) {
13978 valueContent = valueContent.replace(forIteratorRE, '').trim();
13979 const keyContent = iteratorMatch[1].trim();
13980 let keyOffset;
13981 if (keyContent) {
13982 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
13983 result.key = createAliasExpression(loc, keyContent, keyOffset);
13984 {
13985 validateBrowserExpression(result.key, context, true);
13986 }
13987 }
13988 if (iteratorMatch[2]) {
13989 const indexContent = iteratorMatch[2].trim();
13990 if (indexContent) {
13991 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
13992 ? keyOffset + keyContent.length
13993 : trimmedOffset + valueContent.length));
13994 {
13995 validateBrowserExpression(result.index, context, true);
13996 }
13997 }
13998 }
13999 }
14000 if (valueContent) {
14001 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
14002 {
14003 validateBrowserExpression(result.value, context, true);
14004 }
14005 }
14006 return result;
14007 }
14008 function createAliasExpression(range, content, offset) {
14009 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14010 }
14011 function createForLoopParams({ value, key, index }, memoArgs = []) {
14012 return createParamsList([value, key, index, ...memoArgs]);
14013 }
14014 function createParamsList(args) {
14015 let i = args.length;
14016 while (i--) {
14017 if (args[i])
14018 break;
14019 }
14020 return args
14021 .slice(0, i + 1)
14022 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14023 }
14024
14025 const defaultFallback = createSimpleExpression(`undefined`, false);
14026 // A NodeTransform that:
14027 // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14028 // by transformExpression. This is only applied in non-browser builds with
14029 // { prefixIdentifiers: true }.
14030 // 2. Track v-slot depths so that we know a slot is inside another slot.
14031 // Note the exit callback is executed before buildSlots() on the same node,
14032 // so only nested slots see positive numbers.
14033 const trackSlotScopes = (node, context) => {
14034 if (node.type === 1 /* ELEMENT */ &&
14035 (node.tagType === 1 /* COMPONENT */ ||
14036 node.tagType === 3 /* TEMPLATE */)) {
14037 // We are only checking non-empty v-slot here
14038 // since we only care about slots that introduce scope variables.
14039 const vSlot = findDir(node, 'slot');
14040 if (vSlot) {
14041 vSlot.exp;
14042 context.scopes.vSlot++;
14043 return () => {
14044 context.scopes.vSlot--;
14045 };
14046 }
14047 }
14048 };
14049 const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14050 // Instead of being a DirectiveTransform, v-slot processing is called during
14051 // transformElement to build the slots object for a component.
14052 function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14053 context.helper(WITH_CTX);
14054 const { children, loc } = node;
14055 const slotsProperties = [];
14056 const dynamicSlots = [];
14057 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14058 // since it likely uses a scope variable.
14059 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14060 // 1. Check for slot with slotProps on component itself.
14061 // <Comp v-slot="{ prop }"/>
14062 const onComponentSlot = findDir(node, 'slot', true);
14063 if (onComponentSlot) {
14064 const { arg, exp } = onComponentSlot;
14065 if (arg && !isStaticExp(arg)) {
14066 hasDynamicSlots = true;
14067 }
14068 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14069 }
14070 // 2. Iterate through children and check for template slots
14071 // <template v-slot:foo="{ prop }">
14072 let hasTemplateSlots = false;
14073 let hasNamedDefaultSlot = false;
14074 const implicitDefaultChildren = [];
14075 const seenSlotNames = new Set();
14076 for (let i = 0; i < children.length; i++) {
14077 const slotElement = children[i];
14078 let slotDir;
14079 if (!isTemplateNode(slotElement) ||
14080 !(slotDir = findDir(slotElement, 'slot', true))) {
14081 // not a <template v-slot>, skip.
14082 if (slotElement.type !== 3 /* COMMENT */) {
14083 implicitDefaultChildren.push(slotElement);
14084 }
14085 continue;
14086 }
14087 if (onComponentSlot) {
14088 // already has on-component slot - this is incorrect usage.
14089 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14090 break;
14091 }
14092 hasTemplateSlots = true;
14093 const { children: slotChildren, loc: slotLoc } = slotElement;
14094 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14095 // check if name is dynamic.
14096 let staticSlotName;
14097 if (isStaticExp(slotName)) {
14098 staticSlotName = slotName ? slotName.content : `default`;
14099 }
14100 else {
14101 hasDynamicSlots = true;
14102 }
14103 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14104 // check if this slot is conditional (v-if/v-for)
14105 let vIf;
14106 let vElse;
14107 let vFor;
14108 if ((vIf = findDir(slotElement, 'if'))) {
14109 hasDynamicSlots = true;
14110 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14111 }
14112 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14113 // find adjacent v-if
14114 let j = i;
14115 let prev;
14116 while (j--) {
14117 prev = children[j];
14118 if (prev.type !== 3 /* COMMENT */) {
14119 break;
14120 }
14121 }
14122 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14123 // remove node
14124 children.splice(i, 1);
14125 i--;
14126 // attach this slot to previous conditional
14127 let conditional = dynamicSlots[dynamicSlots.length - 1];
14128 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14129 conditional = conditional.alternate;
14130 }
14131 conditional.alternate = vElse.exp
14132 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14133 : buildDynamicSlot(slotName, slotFunction);
14134 }
14135 else {
14136 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14137 }
14138 }
14139 else if ((vFor = findDir(slotElement, 'for'))) {
14140 hasDynamicSlots = true;
14141 const parseResult = vFor.parseResult ||
14142 parseForExpression(vFor.exp, context);
14143 if (parseResult) {
14144 // Render the dynamic slots as an array and add it to the createSlot()
14145 // args. The runtime knows how to handle it appropriately.
14146 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14147 parseResult.source,
14148 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14149 ]));
14150 }
14151 else {
14152 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14153 }
14154 }
14155 else {
14156 // check duplicate static names
14157 if (staticSlotName) {
14158 if (seenSlotNames.has(staticSlotName)) {
14159 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14160 continue;
14161 }
14162 seenSlotNames.add(staticSlotName);
14163 if (staticSlotName === 'default') {
14164 hasNamedDefaultSlot = true;
14165 }
14166 }
14167 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14168 }
14169 }
14170 if (!onComponentSlot) {
14171 const buildDefaultSlotProperty = (props, children) => {
14172 const fn = buildSlotFn(props, children, loc);
14173 return createObjectProperty(`default`, fn);
14174 };
14175 if (!hasTemplateSlots) {
14176 // implicit default slot (on component)
14177 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14178 }
14179 else if (implicitDefaultChildren.length &&
14180 // #3766
14181 // with whitespace: 'preserve', whitespaces between slots will end up in
14182 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14183 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14184 // implicit default slot (mixed with named slots)
14185 if (hasNamedDefaultSlot) {
14186 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14187 }
14188 else {
14189 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14190 }
14191 }
14192 }
14193 const slotFlag = hasDynamicSlots
14194 ? 2 /* DYNAMIC */
14195 : hasForwardedSlots(node.children)
14196 ? 3 /* FORWARDED */
14197 : 1 /* STABLE */;
14198 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14199 // 2 = compiled but dynamic = can skip normalization, but must run diff
14200 // 1 = compiled and static = can skip normalization AND diff as optimized
14201 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14202 if (dynamicSlots.length) {
14203 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14204 slots,
14205 createArrayExpression(dynamicSlots)
14206 ]);
14207 }
14208 return {
14209 slots,
14210 hasDynamicSlots
14211 };
14212 }
14213 function buildDynamicSlot(name, fn) {
14214 return createObjectExpression([
14215 createObjectProperty(`name`, name),
14216 createObjectProperty(`fn`, fn)
14217 ]);
14218 }
14219 function hasForwardedSlots(children) {
14220 for (let i = 0; i < children.length; i++) {
14221 const child = children[i];
14222 switch (child.type) {
14223 case 1 /* ELEMENT */:
14224 if (child.tagType === 2 /* SLOT */ ||
14225 hasForwardedSlots(child.children)) {
14226 return true;
14227 }
14228 break;
14229 case 9 /* IF */:
14230 if (hasForwardedSlots(child.branches))
14231 return true;
14232 break;
14233 case 10 /* IF_BRANCH */:
14234 case 11 /* FOR */:
14235 if (hasForwardedSlots(child.children))
14236 return true;
14237 break;
14238 }
14239 }
14240 return false;
14241 }
14242 function isNonWhitespaceContent(node) {
14243 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14244 return true;
14245 return node.type === 2 /* TEXT */
14246 ? !!node.content.trim()
14247 : isNonWhitespaceContent(node.content);
14248 }
14249
14250 // some directive transforms (e.g. v-model) may return a symbol for runtime
14251 // import, which should be used instead of a resolveDirective call.
14252 const directiveImportMap = new WeakMap();
14253 // generate a JavaScript AST for this element's codegen
14254 const transformElement = (node, context) => {
14255 // perform the work on exit, after all child expressions have been
14256 // processed and merged.
14257 return function postTransformElement() {
14258 node = context.currentNode;
14259 if (!(node.type === 1 /* ELEMENT */ &&
14260 (node.tagType === 0 /* ELEMENT */ ||
14261 node.tagType === 1 /* COMPONENT */))) {
14262 return;
14263 }
14264 const { tag, props } = node;
14265 const isComponent = node.tagType === 1 /* COMPONENT */;
14266 // The goal of the transform is to create a codegenNode implementing the
14267 // VNodeCall interface.
14268 let vnodeTag = isComponent
14269 ? resolveComponentType(node, context)
14270 : `"${tag}"`;
14271 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14272 let vnodeProps;
14273 let vnodeChildren;
14274 let vnodePatchFlag;
14275 let patchFlag = 0;
14276 let vnodeDynamicProps;
14277 let dynamicPropNames;
14278 let vnodeDirectives;
14279 let shouldUseBlock =
14280 // dynamic component may resolve to plain elements
14281 isDynamicComponent ||
14282 vnodeTag === TELEPORT ||
14283 vnodeTag === SUSPENSE ||
14284 (!isComponent &&
14285 // <svg> and <foreignObject> must be forced into blocks so that block
14286 // updates inside get proper isSVG flag at runtime. (#639, #643)
14287 // This is technically web-specific, but splitting the logic out of core
14288 // leads to too much unnecessary complexity.
14289 (tag === 'svg' || tag === 'foreignObject'));
14290 // props
14291 if (props.length > 0) {
14292 const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
14293 vnodeProps = propsBuildResult.props;
14294 patchFlag = propsBuildResult.patchFlag;
14295 dynamicPropNames = propsBuildResult.dynamicPropNames;
14296 const directives = propsBuildResult.directives;
14297 vnodeDirectives =
14298 directives && directives.length
14299 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14300 : undefined;
14301 if (propsBuildResult.shouldUseBlock) {
14302 shouldUseBlock = true;
14303 }
14304 }
14305 // children
14306 if (node.children.length > 0) {
14307 if (vnodeTag === KEEP_ALIVE) {
14308 // Although a built-in component, we compile KeepAlive with raw children
14309 // instead of slot functions so that it can be used inside Transition
14310 // or other Transition-wrapping HOCs.
14311 // To ensure correct updates with block optimizations, we need to:
14312 // 1. Force keep-alive into a block. This avoids its children being
14313 // collected by a parent block.
14314 shouldUseBlock = true;
14315 // 2. Force keep-alive to always be updated, since it uses raw children.
14316 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14317 if (node.children.length > 1) {
14318 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14319 start: node.children[0].loc.start,
14320 end: node.children[node.children.length - 1].loc.end,
14321 source: ''
14322 }));
14323 }
14324 }
14325 const shouldBuildAsSlots = isComponent &&
14326 // Teleport is not a real component and has dedicated runtime handling
14327 vnodeTag !== TELEPORT &&
14328 // explained above.
14329 vnodeTag !== KEEP_ALIVE;
14330 if (shouldBuildAsSlots) {
14331 const { slots, hasDynamicSlots } = buildSlots(node, context);
14332 vnodeChildren = slots;
14333 if (hasDynamicSlots) {
14334 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14335 }
14336 }
14337 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14338 const child = node.children[0];
14339 const type = child.type;
14340 // check for dynamic text children
14341 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14342 type === 8 /* COMPOUND_EXPRESSION */;
14343 if (hasDynamicTextChild &&
14344 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14345 patchFlag |= 1 /* TEXT */;
14346 }
14347 // pass directly if the only child is a text node
14348 // (plain / interpolation / expression)
14349 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14350 vnodeChildren = child;
14351 }
14352 else {
14353 vnodeChildren = node.children;
14354 }
14355 }
14356 else {
14357 vnodeChildren = node.children;
14358 }
14359 }
14360 // patchFlag & dynamicPropNames
14361 if (patchFlag !== 0) {
14362 {
14363 if (patchFlag < 0) {
14364 // special flags (negative and mutually exclusive)
14365 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14366 }
14367 else {
14368 // bitwise flags
14369 const flagNames = Object.keys(PatchFlagNames)
14370 .map(Number)
14371 .filter(n => n > 0 && patchFlag & n)
14372 .map(n => PatchFlagNames[n])
14373 .join(`, `);
14374 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14375 }
14376 }
14377 if (dynamicPropNames && dynamicPropNames.length) {
14378 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14379 }
14380 }
14381 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14382 };
14383 };
14384 function resolveComponentType(node, context, ssr = false) {
14385 let { tag } = node;
14386 // 1. dynamic component
14387 const isExplicitDynamic = isComponentTag(tag);
14388 const isProp = findProp(node, 'is');
14389 if (isProp) {
14390 if (isExplicitDynamic ||
14391 (false )) {
14392 const exp = isProp.type === 6 /* ATTRIBUTE */
14393 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14394 : isProp.exp;
14395 if (exp) {
14396 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14397 exp
14398 ]);
14399 }
14400 }
14401 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14402 isProp.value.content.startsWith('vue:')) {
14403 // <button is="vue:xxx">
14404 // if not <component>, only is value that starts with "vue:" will be
14405 // treated as component by the parse phase and reach here, unless it's
14406 // compat mode where all is values are considered components
14407 tag = isProp.value.content.slice(4);
14408 }
14409 }
14410 // 1.5 v-is (TODO: Deprecate)
14411 const isDir = !isExplicitDynamic && findDir(node, 'is');
14412 if (isDir && isDir.exp) {
14413 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14414 isDir.exp
14415 ]);
14416 }
14417 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14418 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14419 if (builtIn) {
14420 // built-ins are simply fallthroughs / have special handling during ssr
14421 // so we don't need to import their runtime equivalents
14422 if (!ssr)
14423 context.helper(builtIn);
14424 return builtIn;
14425 }
14426 // 5. user component (resolve)
14427 context.helper(RESOLVE_COMPONENT);
14428 context.components.add(tag);
14429 return toValidAssetId(tag, `component`);
14430 }
14431 function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
14432 const { tag, loc: elementLoc, children } = node;
14433 let properties = [];
14434 const mergeArgs = [];
14435 const runtimeDirectives = [];
14436 const hasChildren = children.length > 0;
14437 let shouldUseBlock = false;
14438 // patchFlag analysis
14439 let patchFlag = 0;
14440 let hasRef = false;
14441 let hasClassBinding = false;
14442 let hasStyleBinding = false;
14443 let hasHydrationEventBinding = false;
14444 let hasDynamicKeys = false;
14445 let hasVnodeHook = false;
14446 const dynamicPropNames = [];
14447 const analyzePatchFlag = ({ key, value }) => {
14448 if (isStaticExp(key)) {
14449 const name = key.content;
14450 const isEventHandler = isOn(name);
14451 if (isEventHandler &&
14452 (!isComponent || isDynamicComponent) &&
14453 // omit the flag for click handlers because hydration gives click
14454 // dedicated fast path.
14455 name.toLowerCase() !== 'onclick' &&
14456 // omit v-model handlers
14457 name !== 'onUpdate:modelValue' &&
14458 // omit onVnodeXXX hooks
14459 !isReservedProp(name)) {
14460 hasHydrationEventBinding = true;
14461 }
14462 if (isEventHandler && isReservedProp(name)) {
14463 hasVnodeHook = true;
14464 }
14465 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14466 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14467 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14468 getConstantType(value, context) > 0)) {
14469 // skip if the prop is a cached handler or has constant value
14470 return;
14471 }
14472 if (name === 'ref') {
14473 hasRef = true;
14474 }
14475 else if (name === 'class') {
14476 hasClassBinding = true;
14477 }
14478 else if (name === 'style') {
14479 hasStyleBinding = true;
14480 }
14481 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14482 dynamicPropNames.push(name);
14483 }
14484 // treat the dynamic class and style binding of the component as dynamic props
14485 if (isComponent &&
14486 (name === 'class' || name === 'style') &&
14487 !dynamicPropNames.includes(name)) {
14488 dynamicPropNames.push(name);
14489 }
14490 }
14491 else {
14492 hasDynamicKeys = true;
14493 }
14494 };
14495 for (let i = 0; i < props.length; i++) {
14496 // static attribute
14497 const prop = props[i];
14498 if (prop.type === 6 /* ATTRIBUTE */) {
14499 const { loc, name, value } = prop;
14500 let isStatic = true;
14501 if (name === 'ref') {
14502 hasRef = true;
14503 if (context.scopes.vFor > 0) {
14504 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14505 }
14506 }
14507 // skip is on <component>, or is="vue:xxx"
14508 if (name === 'is' &&
14509 (isComponentTag(tag) ||
14510 (value && value.content.startsWith('vue:')) ||
14511 (false ))) {
14512 continue;
14513 }
14514 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
14515 }
14516 else {
14517 // directives
14518 const { name, arg, exp, loc } = prop;
14519 const isVBind = name === 'bind';
14520 const isVOn = name === 'on';
14521 // skip v-slot - it is handled by its dedicated transform.
14522 if (name === 'slot') {
14523 if (!isComponent) {
14524 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14525 }
14526 continue;
14527 }
14528 // skip v-once/v-memo - they are handled by dedicated transforms.
14529 if (name === 'once' || name === 'memo') {
14530 continue;
14531 }
14532 // skip v-is and :is on <component>
14533 if (name === 'is' ||
14534 (isVBind &&
14535 isStaticArgOf(arg, 'is') &&
14536 (isComponentTag(tag) ||
14537 (false )))) {
14538 continue;
14539 }
14540 // skip v-on in SSR compilation
14541 if (isVOn && ssr) {
14542 continue;
14543 }
14544 if (
14545 // #938: elements with dynamic keys should be forced into blocks
14546 (isVBind && isStaticArgOf(arg, 'key')) ||
14547 // inline before-update hooks need to force block so that it is invoked
14548 // before children
14549 (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
14550 shouldUseBlock = true;
14551 }
14552 if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
14553 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14554 }
14555 // special case for v-bind and v-on with no argument
14556 if (!arg && (isVBind || isVOn)) {
14557 hasDynamicKeys = true;
14558 if (exp) {
14559 if (properties.length) {
14560 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14561 properties = [];
14562 }
14563 if (isVBind) {
14564 mergeArgs.push(exp);
14565 }
14566 else {
14567 // v-on="obj" -> toHandlers(obj)
14568 mergeArgs.push({
14569 type: 14 /* JS_CALL_EXPRESSION */,
14570 loc,
14571 callee: context.helper(TO_HANDLERS),
14572 arguments: [exp]
14573 });
14574 }
14575 }
14576 else {
14577 context.onError(createCompilerError(isVBind
14578 ? 34 /* X_V_BIND_NO_EXPRESSION */
14579 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14580 }
14581 continue;
14582 }
14583 const directiveTransform = context.directiveTransforms[name];
14584 if (directiveTransform) {
14585 // has built-in directive transform.
14586 const { props, needRuntime } = directiveTransform(prop, node, context);
14587 !ssr && props.forEach(analyzePatchFlag);
14588 properties.push(...props);
14589 if (needRuntime) {
14590 runtimeDirectives.push(prop);
14591 if (isSymbol(needRuntime)) {
14592 directiveImportMap.set(prop, needRuntime);
14593 }
14594 }
14595 }
14596 else if (!isBuiltInDirective(name)) {
14597 // no built-in transform, this is a user custom directive.
14598 runtimeDirectives.push(prop);
14599 // custom dirs may use beforeUpdate so they need to force blocks
14600 // to ensure before-update gets called before children update
14601 if (hasChildren) {
14602 shouldUseBlock = true;
14603 }
14604 }
14605 }
14606 }
14607 let propsExpression = undefined;
14608 // has v-bind="object" or v-on="object", wrap with mergeProps
14609 if (mergeArgs.length) {
14610 if (properties.length) {
14611 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14612 }
14613 if (mergeArgs.length > 1) {
14614 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14615 }
14616 else {
14617 // single v-bind with nothing else - no need for a mergeProps call
14618 propsExpression = mergeArgs[0];
14619 }
14620 }
14621 else if (properties.length) {
14622 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14623 }
14624 // patchFlag analysis
14625 if (hasDynamicKeys) {
14626 patchFlag |= 16 /* FULL_PROPS */;
14627 }
14628 else {
14629 if (hasClassBinding && !isComponent) {
14630 patchFlag |= 2 /* CLASS */;
14631 }
14632 if (hasStyleBinding && !isComponent) {
14633 patchFlag |= 4 /* STYLE */;
14634 }
14635 if (dynamicPropNames.length) {
14636 patchFlag |= 8 /* PROPS */;
14637 }
14638 if (hasHydrationEventBinding) {
14639 patchFlag |= 32 /* HYDRATE_EVENTS */;
14640 }
14641 }
14642 if (!shouldUseBlock &&
14643 (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14644 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14645 patchFlag |= 512 /* NEED_PATCH */;
14646 }
14647 // pre-normalize props, SSR is skipped for now
14648 if (!context.inSSR && propsExpression) {
14649 switch (propsExpression.type) {
14650 case 15 /* JS_OBJECT_EXPRESSION */:
14651 // means that there is no v-bind,
14652 // but still need to deal with dynamic key binding
14653 let classKeyIndex = -1;
14654 let styleKeyIndex = -1;
14655 let hasDynamicKey = false;
14656 for (let i = 0; i < propsExpression.properties.length; i++) {
14657 const key = propsExpression.properties[i].key;
14658 if (isStaticExp(key)) {
14659 if (key.content === 'class') {
14660 classKeyIndex = i;
14661 }
14662 else if (key.content === 'style') {
14663 styleKeyIndex = i;
14664 }
14665 }
14666 else if (!key.isHandlerKey) {
14667 hasDynamicKey = true;
14668 }
14669 }
14670 const classProp = propsExpression.properties[classKeyIndex];
14671 const styleProp = propsExpression.properties[styleKeyIndex];
14672 // no dynamic key
14673 if (!hasDynamicKey) {
14674 if (classProp && !isStaticExp(classProp.value)) {
14675 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14676 }
14677 if (styleProp &&
14678 // the static style is compiled into an object,
14679 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14680 (hasStyleBinding ||
14681 (styleProp.value.type === 4 /* SIMPLE_EXPRESSION */ &&
14682 styleProp.value.content.trim()[0] === `[`) ||
14683 // v-bind:style and style both exist,
14684 // v-bind:style with static literal object
14685 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14686 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14687 }
14688 }
14689 else {
14690 // dynamic key binding, wrap with `normalizeProps`
14691 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14692 }
14693 break;
14694 case 14 /* JS_CALL_EXPRESSION */:
14695 // mergeProps call, do nothing
14696 break;
14697 default:
14698 // single v-bind
14699 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14700 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14701 propsExpression
14702 ])
14703 ]);
14704 break;
14705 }
14706 }
14707 return {
14708 props: propsExpression,
14709 directives: runtimeDirectives,
14710 patchFlag,
14711 dynamicPropNames,
14712 shouldUseBlock
14713 };
14714 }
14715 // Dedupe props in an object literal.
14716 // Literal duplicated attributes would have been warned during the parse phase,
14717 // however, it's possible to encounter duplicated `onXXX` handlers with different
14718 // modifiers. We also need to merge static and dynamic class / style attributes.
14719 // - onXXX handlers / style: merge into array
14720 // - class: merge into single expression with concatenation
14721 function dedupeProperties(properties) {
14722 const knownProps = new Map();
14723 const deduped = [];
14724 for (let i = 0; i < properties.length; i++) {
14725 const prop = properties[i];
14726 // dynamic keys are always allowed
14727 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14728 deduped.push(prop);
14729 continue;
14730 }
14731 const name = prop.key.content;
14732 const existing = knownProps.get(name);
14733 if (existing) {
14734 if (name === 'style' || name === 'class' || isOn(name)) {
14735 mergeAsArray$1(existing, prop);
14736 }
14737 // unexpected duplicate, should have emitted error during parse
14738 }
14739 else {
14740 knownProps.set(name, prop);
14741 deduped.push(prop);
14742 }
14743 }
14744 return deduped;
14745 }
14746 function mergeAsArray$1(existing, incoming) {
14747 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14748 existing.value.elements.push(incoming.value);
14749 }
14750 else {
14751 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14752 }
14753 }
14754 function buildDirectiveArgs(dir, context) {
14755 const dirArgs = [];
14756 const runtime = directiveImportMap.get(dir);
14757 if (runtime) {
14758 // built-in directive with runtime
14759 dirArgs.push(context.helperString(runtime));
14760 }
14761 else {
14762 {
14763 // inject statement for resolving directive
14764 context.helper(RESOLVE_DIRECTIVE);
14765 context.directives.add(dir.name);
14766 dirArgs.push(toValidAssetId(dir.name, `directive`));
14767 }
14768 }
14769 const { loc } = dir;
14770 if (dir.exp)
14771 dirArgs.push(dir.exp);
14772 if (dir.arg) {
14773 if (!dir.exp) {
14774 dirArgs.push(`void 0`);
14775 }
14776 dirArgs.push(dir.arg);
14777 }
14778 if (Object.keys(dir.modifiers).length) {
14779 if (!dir.arg) {
14780 if (!dir.exp) {
14781 dirArgs.push(`void 0`);
14782 }
14783 dirArgs.push(`void 0`);
14784 }
14785 const trueExpression = createSimpleExpression(`true`, false, loc);
14786 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14787 }
14788 return createArrayExpression(dirArgs, dir.loc);
14789 }
14790 function stringifyDynamicPropNames(props) {
14791 let propsNamesString = `[`;
14792 for (let i = 0, l = props.length; i < l; i++) {
14793 propsNamesString += JSON.stringify(props[i]);
14794 if (i < l - 1)
14795 propsNamesString += ', ';
14796 }
14797 return propsNamesString + `]`;
14798 }
14799 function isComponentTag(tag) {
14800 return tag === 'component' || tag === 'Component';
14801 }
14802
14803 const transformSlotOutlet = (node, context) => {
14804 if (isSlotOutlet(node)) {
14805 const { children, loc } = node;
14806 const { slotName, slotProps } = processSlotOutlet(node, context);
14807 const slotArgs = [
14808 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14809 slotName,
14810 '{}',
14811 'undefined',
14812 'true'
14813 ];
14814 let expectedLen = 2;
14815 if (slotProps) {
14816 slotArgs[2] = slotProps;
14817 expectedLen = 3;
14818 }
14819 if (children.length) {
14820 slotArgs[3] = createFunctionExpression([], children, false, false, loc);
14821 expectedLen = 4;
14822 }
14823 if (context.scopeId && !context.slotted) {
14824 expectedLen = 5;
14825 }
14826 slotArgs.splice(expectedLen); // remove unused arguments
14827 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14828 }
14829 };
14830 function processSlotOutlet(node, context) {
14831 let slotName = `"default"`;
14832 let slotProps = undefined;
14833 const nonNameProps = [];
14834 for (let i = 0; i < node.props.length; i++) {
14835 const p = node.props[i];
14836 if (p.type === 6 /* ATTRIBUTE */) {
14837 if (p.value) {
14838 if (p.name === 'name') {
14839 slotName = JSON.stringify(p.value.content);
14840 }
14841 else {
14842 p.name = camelize(p.name);
14843 nonNameProps.push(p);
14844 }
14845 }
14846 }
14847 else {
14848 if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
14849 if (p.exp)
14850 slotName = p.exp;
14851 }
14852 else {
14853 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14854 p.arg.content = camelize(p.arg.content);
14855 }
14856 nonNameProps.push(p);
14857 }
14858 }
14859 }
14860 if (nonNameProps.length > 0) {
14861 const { props, directives } = buildProps(node, context, nonNameProps, false, false);
14862 slotProps = props;
14863 if (directives.length) {
14864 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14865 }
14866 }
14867 return {
14868 slotName,
14869 slotProps
14870 };
14871 }
14872
14873 const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
14874 const transformOn = (dir, node, context, augmentor) => {
14875 const { loc, modifiers, arg } = dir;
14876 if (!dir.exp && !modifiers.length) {
14877 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
14878 }
14879 let eventName;
14880 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14881 if (arg.isStatic) {
14882 let rawName = arg.content;
14883 // TODO deprecate @vnodeXXX usage
14884 if (rawName.startsWith('vue:')) {
14885 rawName = `vnode-${rawName.slice(4)}`;
14886 }
14887 // for all event listeners, auto convert it to camelCase. See issue #2249
14888 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
14889 }
14890 else {
14891 // #2388
14892 eventName = createCompoundExpression([
14893 `${context.helperString(TO_HANDLER_KEY)}(`,
14894 arg,
14895 `)`
14896 ]);
14897 }
14898 }
14899 else {
14900 // already a compound expression.
14901 eventName = arg;
14902 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
14903 eventName.children.push(`)`);
14904 }
14905 // handler processing
14906 let exp = dir.exp;
14907 if (exp && !exp.content.trim()) {
14908 exp = undefined;
14909 }
14910 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
14911 if (exp) {
14912 const isMemberExp = isMemberExpression(exp.content);
14913 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
14914 const hasMultipleStatements = exp.content.includes(`;`);
14915 {
14916 validateBrowserExpression(exp, context, false, hasMultipleStatements);
14917 }
14918 if (isInlineStatement || (shouldCache && isMemberExp)) {
14919 // wrap inline statement in a function expression
14920 exp = createCompoundExpression([
14921 `${isInlineStatement
14922 ? `$event`
14923 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
14924 exp,
14925 hasMultipleStatements ? `}` : `)`
14926 ]);
14927 }
14928 }
14929 let ret = {
14930 props: [
14931 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
14932 ]
14933 };
14934 // apply extended compiler augmentor
14935 if (augmentor) {
14936 ret = augmentor(ret);
14937 }
14938 if (shouldCache) {
14939 // cache handlers so that it's always the same handler being passed down.
14940 // this avoids unnecessary re-renders when users use inline handlers on
14941 // components.
14942 ret.props[0].value = context.cache(ret.props[0].value);
14943 }
14944 // mark the key as handler for props normalization check
14945 ret.props.forEach(p => (p.key.isHandlerKey = true));
14946 return ret;
14947 };
14948
14949 // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
14950 // codegen for the entire props object. This transform here is only for v-bind
14951 // *with* args.
14952 const transformBind = (dir, _node, context) => {
14953 const { exp, modifiers, loc } = dir;
14954 const arg = dir.arg;
14955 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
14956 arg.children.unshift(`(`);
14957 arg.children.push(`) || ""`);
14958 }
14959 else if (!arg.isStatic) {
14960 arg.content = `${arg.content} || ""`;
14961 }
14962 // .sync is replaced by v-model:arg
14963 if (modifiers.includes('camel')) {
14964 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14965 if (arg.isStatic) {
14966 arg.content = camelize(arg.content);
14967 }
14968 else {
14969 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
14970 }
14971 }
14972 else {
14973 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
14974 arg.children.push(`)`);
14975 }
14976 }
14977 if (!context.inSSR) {
14978 if (modifiers.includes('prop')) {
14979 injectPrefix(arg, '.');
14980 }
14981 if (modifiers.includes('attr')) {
14982 injectPrefix(arg, '^');
14983 }
14984 }
14985 if (!exp ||
14986 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
14987 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
14988 return {
14989 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
14990 };
14991 }
14992 return {
14993 props: [createObjectProperty(arg, exp)]
14994 };
14995 };
14996 const injectPrefix = (arg, prefix) => {
14997 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14998 if (arg.isStatic) {
14999 arg.content = prefix + arg.content;
15000 }
15001 else {
15002 arg.content = `\`${prefix}\${${arg.content}}\``;
15003 }
15004 }
15005 else {
15006 arg.children.unshift(`'${prefix}' + (`);
15007 arg.children.push(`)`);
15008 }
15009 };
15010
15011 // Merge adjacent text nodes and expressions into a single expression
15012 // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15013 const transformText = (node, context) => {
15014 if (node.type === 0 /* ROOT */ ||
15015 node.type === 1 /* ELEMENT */ ||
15016 node.type === 11 /* FOR */ ||
15017 node.type === 10 /* IF_BRANCH */) {
15018 // perform the transform on node exit so that all expressions have already
15019 // been processed.
15020 return () => {
15021 const children = node.children;
15022 let currentContainer = undefined;
15023 let hasText = false;
15024 for (let i = 0; i < children.length; i++) {
15025 const child = children[i];
15026 if (isText(child)) {
15027 hasText = true;
15028 for (let j = i + 1; j < children.length; j++) {
15029 const next = children[j];
15030 if (isText(next)) {
15031 if (!currentContainer) {
15032 currentContainer = children[i] = createCompoundExpression([child], child.loc);
15033 }
15034 // merge adjacent text node into current
15035 currentContainer.children.push(` + `, next);
15036 children.splice(j, 1);
15037 j--;
15038 }
15039 else {
15040 currentContainer = undefined;
15041 break;
15042 }
15043 }
15044 }
15045 }
15046 if (!hasText ||
15047 // if this is a plain element with a single text child, leave it
15048 // as-is since the runtime has dedicated fast path for this by directly
15049 // setting textContent of the element.
15050 // for component root it's always normalized anyway.
15051 (children.length === 1 &&
15052 (node.type === 0 /* ROOT */ ||
15053 (node.type === 1 /* ELEMENT */ &&
15054 node.tagType === 0 /* ELEMENT */ &&
15055 // #3756
15056 // custom directives can potentially add DOM elements arbitrarily,
15057 // we need to avoid setting textContent of the element at runtime
15058 // to avoid accidentally overwriting the DOM elements added
15059 // by the user through custom directives.
15060 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15061 !context.directiveTransforms[p.name]) &&
15062 // in compat mode, <template> tags with no special directives
15063 // will be rendered as a fragment so its children must be
15064 // converted into vnodes.
15065 !(false ))))) {
15066 return;
15067 }
15068 // pre-convert text nodes into createTextVNode(text) calls to avoid
15069 // runtime normalization.
15070 for (let i = 0; i < children.length; i++) {
15071 const child = children[i];
15072 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15073 const callArgs = [];
15074 // createTextVNode defaults to single whitespace, so if it is a
15075 // single space the code could be an empty call to save bytes.
15076 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15077 callArgs.push(child);
15078 }
15079 // mark dynamic text with flag so it gets patched inside a block
15080 if (!context.ssr &&
15081 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15082 callArgs.push(1 /* TEXT */ +
15083 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15084 }
15085 children[i] = {
15086 type: 12 /* TEXT_CALL */,
15087 content: child,
15088 loc: child.loc,
15089 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15090 };
15091 }
15092 }
15093 };
15094 }
15095 };
15096
15097 const seen = new WeakSet();
15098 const transformOnce = (node, context) => {
15099 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15100 if (seen.has(node) || context.inVOnce) {
15101 return;
15102 }
15103 seen.add(node);
15104 context.inVOnce = true;
15105 context.helper(SET_BLOCK_TRACKING);
15106 return () => {
15107 context.inVOnce = false;
15108 const cur = context.currentNode;
15109 if (cur.codegenNode) {
15110 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15111 }
15112 };
15113 }
15114 };
15115
15116 const transformModel = (dir, node, context) => {
15117 const { exp, arg } = dir;
15118 if (!exp) {
15119 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15120 return createTransformProps();
15121 }
15122 const rawExp = exp.loc.source;
15123 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15124 // im SFC <script setup> inline mode, the exp may have been transformed into
15125 // _unref(exp)
15126 context.bindingMetadata[rawExp];
15127 const maybeRef = !true /* SETUP_CONST */;
15128 if (!expString.trim() ||
15129 (!isMemberExpression(expString) && !maybeRef)) {
15130 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15131 return createTransformProps();
15132 }
15133 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15134 const eventName = arg
15135 ? isStaticExp(arg)
15136 ? `onUpdate:${arg.content}`
15137 : createCompoundExpression(['"onUpdate:" + ', arg])
15138 : `onUpdate:modelValue`;
15139 let assignmentExp;
15140 const eventArg = context.isTS ? `($event: any)` : `$event`;
15141 {
15142 assignmentExp = createCompoundExpression([
15143 `${eventArg} => ((`,
15144 exp,
15145 `) = $event)`
15146 ]);
15147 }
15148 const props = [
15149 // modelValue: foo
15150 createObjectProperty(propName, dir.exp),
15151 // "onUpdate:modelValue": $event => (foo = $event)
15152 createObjectProperty(eventName, assignmentExp)
15153 ];
15154 // modelModifiers: { foo: true, "bar-baz": true }
15155 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15156 const modifiers = dir.modifiers
15157 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15158 .join(`, `);
15159 const modifiersKey = arg
15160 ? isStaticExp(arg)
15161 ? `${arg.content}Modifiers`
15162 : createCompoundExpression([arg, ' + "Modifiers"'])
15163 : `modelModifiers`;
15164 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15165 }
15166 return createTransformProps(props);
15167 };
15168 function createTransformProps(props = []) {
15169 return { props };
15170 }
15171
15172 const seen$1 = new WeakSet();
15173 const transformMemo = (node, context) => {
15174 if (node.type === 1 /* ELEMENT */) {
15175 const dir = findDir(node, 'memo');
15176 if (!dir || seen$1.has(node)) {
15177 return;
15178 }
15179 seen$1.add(node);
15180 return () => {
15181 const codegenNode = node.codegenNode ||
15182 context.currentNode.codegenNode;
15183 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15184 // non-component sub tree should be turned into a block
15185 if (node.tagType !== 1 /* COMPONENT */) {
15186 makeBlock(codegenNode, context);
15187 }
15188 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15189 dir.exp,
15190 createFunctionExpression(undefined, codegenNode),
15191 `_cache`,
15192 String(context.cached++)
15193 ]);
15194 }
15195 };
15196 }
15197 };
15198
15199 function getBaseTransformPreset(prefixIdentifiers) {
15200 return [
15201 [
15202 transformOnce,
15203 transformIf,
15204 transformMemo,
15205 transformFor,
15206 ...([]),
15207 ...([transformExpression]
15208 ),
15209 transformSlotOutlet,
15210 transformElement,
15211 trackSlotScopes,
15212 transformText
15213 ],
15214 {
15215 on: transformOn,
15216 bind: transformBind,
15217 model: transformModel
15218 }
15219 ];
15220 }
15221 // we name it `baseCompile` so that higher order compilers like
15222 // @vue/compiler-dom can export `compile` while re-exporting everything else.
15223 function baseCompile(template, options = {}) {
15224 const onError = options.onError || defaultOnError;
15225 const isModuleMode = options.mode === 'module';
15226 /* istanbul ignore if */
15227 {
15228 if (options.prefixIdentifiers === true) {
15229 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15230 }
15231 else if (isModuleMode) {
15232 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15233 }
15234 }
15235 const prefixIdentifiers = !true ;
15236 if (options.cacheHandlers) {
15237 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15238 }
15239 if (options.scopeId && !isModuleMode) {
15240 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15241 }
15242 const ast = isString(template) ? baseParse(template, options) : template;
15243 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15244 transform(ast, extend({}, options, {
15245 prefixIdentifiers,
15246 nodeTransforms: [
15247 ...nodeTransforms,
15248 ...(options.nodeTransforms || []) // user transforms
15249 ],
15250 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15251 )
15252 }));
15253 return generate(ast, extend({}, options, {
15254 prefixIdentifiers
15255 }));
15256 }
15257
15258 const noopDirectiveTransform = () => ({ props: [] });
15259
15260 const V_MODEL_RADIO = Symbol(`vModelRadio` );
15261 const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15262 const V_MODEL_TEXT = Symbol(`vModelText` );
15263 const V_MODEL_SELECT = Symbol(`vModelSelect` );
15264 const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15265 const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15266 const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15267 const V_SHOW = Symbol(`vShow` );
15268 const TRANSITION$1 = Symbol(`Transition` );
15269 const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15270 registerRuntimeHelpers({
15271 [V_MODEL_RADIO]: `vModelRadio`,
15272 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15273 [V_MODEL_TEXT]: `vModelText`,
15274 [V_MODEL_SELECT]: `vModelSelect`,
15275 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15276 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15277 [V_ON_WITH_KEYS]: `withKeys`,
15278 [V_SHOW]: `vShow`,
15279 [TRANSITION$1]: `Transition`,
15280 [TRANSITION_GROUP]: `TransitionGroup`
15281 });
15282
15283 /* eslint-disable no-restricted-globals */
15284 let decoder;
15285 function decodeHtmlBrowser(raw, asAttr = false) {
15286 if (!decoder) {
15287 decoder = document.createElement('div');
15288 }
15289 if (asAttr) {
15290 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15291 return decoder.children[0].getAttribute('foo');
15292 }
15293 else {
15294 decoder.innerHTML = raw;
15295 return decoder.textContent;
15296 }
15297 }
15298
15299 const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15300 const parserOptions = {
15301 isVoidTag,
15302 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15303 isPreTag: tag => tag === 'pre',
15304 decodeEntities: decodeHtmlBrowser ,
15305 isBuiltInComponent: (tag) => {
15306 if (isBuiltInType(tag, `Transition`)) {
15307 return TRANSITION$1;
15308 }
15309 else if (isBuiltInType(tag, `TransitionGroup`)) {
15310 return TRANSITION_GROUP;
15311 }
15312 },
15313 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15314 getNamespace(tag, parent) {
15315 let ns = parent ? parent.ns : 0 /* HTML */;
15316 if (parent && ns === 2 /* MATH_ML */) {
15317 if (parent.tag === 'annotation-xml') {
15318 if (tag === 'svg') {
15319 return 1 /* SVG */;
15320 }
15321 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15322 a.name === 'encoding' &&
15323 a.value != null &&
15324 (a.value.content === 'text/html' ||
15325 a.value.content === 'application/xhtml+xml'))) {
15326 ns = 0 /* HTML */;
15327 }
15328 }
15329 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15330 tag !== 'mglyph' &&
15331 tag !== 'malignmark') {
15332 ns = 0 /* HTML */;
15333 }
15334 }
15335 else if (parent && ns === 1 /* SVG */) {
15336 if (parent.tag === 'foreignObject' ||
15337 parent.tag === 'desc' ||
15338 parent.tag === 'title') {
15339 ns = 0 /* HTML */;
15340 }
15341 }
15342 if (ns === 0 /* HTML */) {
15343 if (tag === 'svg') {
15344 return 1 /* SVG */;
15345 }
15346 if (tag === 'math') {
15347 return 2 /* MATH_ML */;
15348 }
15349 }
15350 return ns;
15351 },
15352 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15353 getTextMode({ tag, ns }) {
15354 if (ns === 0 /* HTML */) {
15355 if (tag === 'textarea' || tag === 'title') {
15356 return 1 /* RCDATA */;
15357 }
15358 if (isRawTextContainer(tag)) {
15359 return 2 /* RAWTEXT */;
15360 }
15361 }
15362 return 0 /* DATA */;
15363 }
15364 };
15365
15366 // Parse inline CSS strings for static style attributes into an object.
15367 // This is a NodeTransform since it works on the static `style` attribute and
15368 // converts it into a dynamic equivalent:
15369 // style="color: red" -> :style='{ "color": "red" }'
15370 // It is then processed by `transformElement` and included in the generated
15371 // props.
15372 const transformStyle = node => {
15373 if (node.type === 1 /* ELEMENT */) {
15374 node.props.forEach((p, i) => {
15375 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15376 // replace p with an expression node
15377 node.props[i] = {
15378 type: 7 /* DIRECTIVE */,
15379 name: `bind`,
15380 arg: createSimpleExpression(`style`, true, p.loc),
15381 exp: parseInlineCSS(p.value.content, p.loc),
15382 modifiers: [],
15383 loc: p.loc
15384 };
15385 }
15386 });
15387 }
15388 };
15389 const parseInlineCSS = (cssText, loc) => {
15390 const normalized = parseStringStyle(cssText);
15391 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15392 };
15393
15394 function createDOMCompilerError(code, loc) {
15395 return createCompilerError(code, loc, DOMErrorMessages );
15396 }
15397 const DOMErrorMessages = {
15398 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15399 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15400 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15401 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15402 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15403 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15404 [56 /* 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.`,
15405 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15406 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15407 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15408 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15409 };
15410
15411 const transformVHtml = (dir, node, context) => {
15412 const { exp, loc } = dir;
15413 if (!exp) {
15414 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15415 }
15416 if (node.children.length) {
15417 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15418 node.children.length = 0;
15419 }
15420 return {
15421 props: [
15422 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15423 ]
15424 };
15425 };
15426
15427 const transformVText = (dir, node, context) => {
15428 const { exp, loc } = dir;
15429 if (!exp) {
15430 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15431 }
15432 if (node.children.length) {
15433 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15434 node.children.length = 0;
15435 }
15436 return {
15437 props: [
15438 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15439 ? getConstantType(exp, context) > 0
15440 ? exp
15441 : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15442 : createSimpleExpression('', true))
15443 ]
15444 };
15445 };
15446
15447 const transformModel$1 = (dir, node, context) => {
15448 const baseResult = transformModel(dir, node, context);
15449 // base transform has errors OR component v-model (only need props)
15450 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15451 return baseResult;
15452 }
15453 if (dir.arg) {
15454 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15455 }
15456 function checkDuplicatedValue() {
15457 const value = findProp(node, 'value');
15458 if (value) {
15459 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15460 }
15461 }
15462 const { tag } = node;
15463 const isCustomElement = context.isCustomElement(tag);
15464 if (tag === 'input' ||
15465 tag === 'textarea' ||
15466 tag === 'select' ||
15467 isCustomElement) {
15468 let directiveToUse = V_MODEL_TEXT;
15469 let isInvalidType = false;
15470 if (tag === 'input' || isCustomElement) {
15471 const type = findProp(node, `type`);
15472 if (type) {
15473 if (type.type === 7 /* DIRECTIVE */) {
15474 // :type="foo"
15475 directiveToUse = V_MODEL_DYNAMIC;
15476 }
15477 else if (type.value) {
15478 switch (type.value.content) {
15479 case 'radio':
15480 directiveToUse = V_MODEL_RADIO;
15481 break;
15482 case 'checkbox':
15483 directiveToUse = V_MODEL_CHECKBOX;
15484 break;
15485 case 'file':
15486 isInvalidType = true;
15487 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15488 break;
15489 default:
15490 // text type
15491 checkDuplicatedValue();
15492 break;
15493 }
15494 }
15495 }
15496 else if (hasDynamicKeyVBind(node)) {
15497 // element has bindings with dynamic keys, which can possibly contain
15498 // "type".
15499 directiveToUse = V_MODEL_DYNAMIC;
15500 }
15501 else {
15502 // text type
15503 checkDuplicatedValue();
15504 }
15505 }
15506 else if (tag === 'select') {
15507 directiveToUse = V_MODEL_SELECT;
15508 }
15509 else {
15510 // textarea
15511 checkDuplicatedValue();
15512 }
15513 // inject runtime directive
15514 // by returning the helper symbol via needRuntime
15515 // the import will replaced a resolveDirective call.
15516 if (!isInvalidType) {
15517 baseResult.needRuntime = context.helper(directiveToUse);
15518 }
15519 }
15520 else {
15521 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15522 }
15523 // native vmodel doesn't need the `modelValue` props since they are also
15524 // passed to the runtime as `binding.value`. removing it reduces code size.
15525 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15526 p.key.content === 'modelValue'));
15527 return baseResult;
15528 };
15529
15530 const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15531 const isNonKeyModifier = /*#__PURE__*/ makeMap(
15532 // event propagation management
15533`stop,prevent,self,` +
15534 // system modifiers + exact
15535 `ctrl,shift,alt,meta,exact,` +
15536 // mouse
15537 `middle`);
15538 // left & right could be mouse or key modifiers based on event type
15539 const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15540 const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15541 const resolveModifiers = (key, modifiers, context, loc) => {
15542 const keyModifiers = [];
15543 const nonKeyModifiers = [];
15544 const eventOptionModifiers = [];
15545 for (let i = 0; i < modifiers.length; i++) {
15546 const modifier = modifiers[i];
15547 if (isEventOptionModifier(modifier)) {
15548 // eventOptionModifiers: modifiers for addEventListener() options,
15549 // e.g. .passive & .capture
15550 eventOptionModifiers.push(modifier);
15551 }
15552 else {
15553 // runtimeModifiers: modifiers that needs runtime guards
15554 if (maybeKeyModifier(modifier)) {
15555 if (isStaticExp(key)) {
15556 if (isKeyboardEvent(key.content)) {
15557 keyModifiers.push(modifier);
15558 }
15559 else {
15560 nonKeyModifiers.push(modifier);
15561 }
15562 }
15563 else {
15564 keyModifiers.push(modifier);
15565 nonKeyModifiers.push(modifier);
15566 }
15567 }
15568 else {
15569 if (isNonKeyModifier(modifier)) {
15570 nonKeyModifiers.push(modifier);
15571 }
15572 else {
15573 keyModifiers.push(modifier);
15574 }
15575 }
15576 }
15577 }
15578 return {
15579 keyModifiers,
15580 nonKeyModifiers,
15581 eventOptionModifiers
15582 };
15583 };
15584 const transformClick = (key, event) => {
15585 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15586 return isStaticClick
15587 ? createSimpleExpression(event, true)
15588 : key.type !== 4 /* SIMPLE_EXPRESSION */
15589 ? createCompoundExpression([
15590 `(`,
15591 key,
15592 `) === "onClick" ? "${event}" : (`,
15593 key,
15594 `)`
15595 ])
15596 : key;
15597 };
15598 const transformOn$1 = (dir, node, context) => {
15599 return transformOn(dir, node, context, baseResult => {
15600 const { modifiers } = dir;
15601 if (!modifiers.length)
15602 return baseResult;
15603 let { key, value: handlerExp } = baseResult.props[0];
15604 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15605 // normalize click.right and click.middle since they don't actually fire
15606 if (nonKeyModifiers.includes('right')) {
15607 key = transformClick(key, `onContextmenu`);
15608 }
15609 if (nonKeyModifiers.includes('middle')) {
15610 key = transformClick(key, `onMouseup`);
15611 }
15612 if (nonKeyModifiers.length) {
15613 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15614 handlerExp,
15615 JSON.stringify(nonKeyModifiers)
15616 ]);
15617 }
15618 if (keyModifiers.length &&
15619 // if event name is dynamic, always wrap with keys guard
15620 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15621 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15622 handlerExp,
15623 JSON.stringify(keyModifiers)
15624 ]);
15625 }
15626 if (eventOptionModifiers.length) {
15627 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15628 key = isStaticExp(key)
15629 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15630 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15631 }
15632 return {
15633 props: [createObjectProperty(key, handlerExp)]
15634 };
15635 });
15636 };
15637
15638 const transformShow = (dir, node, context) => {
15639 const { exp, loc } = dir;
15640 if (!exp) {
15641 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15642 }
15643 return {
15644 props: [],
15645 needRuntime: context.helper(V_SHOW)
15646 };
15647 };
15648
15649 const transformTransition = (node, context) => {
15650 if (node.type === 1 /* ELEMENT */ &&
15651 node.tagType === 1 /* COMPONENT */) {
15652 const component = context.isBuiltInComponent(node.tag);
15653 if (component === TRANSITION$1) {
15654 return () => {
15655 if (!node.children.length) {
15656 return;
15657 }
15658 // warn multiple transition children
15659 if (hasMultipleChildren(node)) {
15660 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15661 start: node.children[0].loc.start,
15662 end: node.children[node.children.length - 1].loc.end,
15663 source: ''
15664 }));
15665 }
15666 // check if it's s single child w/ v-show
15667 // if yes, inject "persisted: true" to the transition props
15668 const child = node.children[0];
15669 if (child.type === 1 /* ELEMENT */) {
15670 for (const p of child.props) {
15671 if (p.type === 7 /* DIRECTIVE */ && p.name === 'show') {
15672 node.props.push({
15673 type: 6 /* ATTRIBUTE */,
15674 name: 'persisted',
15675 value: undefined,
15676 loc: node.loc
15677 });
15678 }
15679 }
15680 }
15681 };
15682 }
15683 }
15684 };
15685 function hasMultipleChildren(node) {
15686 // #1352 filter out potential comment nodes.
15687 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
15688 !(c.type === 2 /* TEXT */ && !c.content.trim())));
15689 const child = children[0];
15690 return (children.length !== 1 ||
15691 child.type === 11 /* FOR */ ||
15692 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15693 }
15694
15695 const ignoreSideEffectTags = (node, context) => {
15696 if (node.type === 1 /* ELEMENT */ &&
15697 node.tagType === 0 /* ELEMENT */ &&
15698 (node.tag === 'script' || node.tag === 'style')) {
15699 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15700 context.removeNode();
15701 }
15702 };
15703
15704 const DOMNodeTransforms = [
15705 transformStyle,
15706 ...([transformTransition] )
15707 ];
15708 const DOMDirectiveTransforms = {
15709 cloak: noopDirectiveTransform,
15710 html: transformVHtml,
15711 text: transformVText,
15712 model: transformModel$1,
15713 on: transformOn$1,
15714 show: transformShow
15715 };
15716 function compile$1(template, options = {}) {
15717 return baseCompile(template, extend({}, parserOptions, options, {
15718 nodeTransforms: [
15719 // ignore <script> and <tag>
15720 // this is not put inside DOMNodeTransforms because that list is used
15721 // by compiler-ssr to generate vnode fallback branches
15722 ignoreSideEffectTags,
15723 ...DOMNodeTransforms,
15724 ...(options.nodeTransforms || [])
15725 ],
15726 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15727 transformHoist: null
15728 }));
15729 }
15730
15731 // This entry is the "full-build" that includes both the runtime
15732 {
15733 initDev();
15734 }
15735 const compileCache = Object.create(null);
15736 function compileToFunction(template, options) {
15737 if (!isString(template)) {
15738 if (template.nodeType) {
15739 template = template.innerHTML;
15740 }
15741 else {
15742 warn$1(`invalid template option: `, template);
15743 return NOOP;
15744 }
15745 }
15746 const key = template;
15747 const cached = compileCache[key];
15748 if (cached) {
15749 return cached;
15750 }
15751 if (template[0] === '#') {
15752 const el = document.querySelector(template);
15753 if (!el) {
15754 warn$1(`Template element not found or is empty: ${template}`);
15755 }
15756 // __UNSAFE__
15757 // Reason: potential execution of JS expressions in in-DOM template.
15758 // The user must make sure the in-DOM template is trusted. If it's rendered
15759 // by the server, the template should not contain any user data.
15760 template = el ? el.innerHTML : ``;
15761 }
15762 const { code } = compile$1(template, extend({
15763 hoistStatic: true,
15764 onError: onError ,
15765 onWarn: e => onError(e, true)
15766 }, options));
15767 function onError(err, asWarning = false) {
15768 const message = asWarning
15769 ? err.message
15770 : `Template compilation error: ${err.message}`;
15771 const codeFrame = err.loc &&
15772 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15773 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15774 }
15775 // The wildcard import results in a huge object with every export
15776 // with keys that cannot be mangled, and can be quite heavy size-wise.
15777 // In the global build we know `Vue` is available globally so we can avoid
15778 // the wildcard object.
15779 const render = (new Function(code)() );
15780 render._rc = true;
15781 return (compileCache[key] = render);
15782 }
15783 registerRuntimeCompiler(compileToFunction);
15784
15785 exports.BaseTransition = BaseTransition;
15786 exports.Comment = Comment;
15787 exports.EffectScope = EffectScope;
15788 exports.Fragment = Fragment;
15789 exports.KeepAlive = KeepAlive;
15790 exports.ReactiveEffect = ReactiveEffect;
15791 exports.Static = Static;
15792 exports.Suspense = Suspense;
15793 exports.Teleport = Teleport;
15794 exports.Text = Text;
15795 exports.Transition = Transition;
15796 exports.TransitionGroup = TransitionGroup;
15797 exports.VueElement = VueElement;
15798 exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
15799 exports.callWithErrorHandling = callWithErrorHandling;
15800 exports.camelize = camelize;
15801 exports.capitalize = capitalize;
15802 exports.cloneVNode = cloneVNode;
15803 exports.compatUtils = compatUtils;
15804 exports.compile = compileToFunction;
15805 exports.computed = computed$1;
15806 exports.createApp = createApp;
15807 exports.createBlock = createBlock;
15808 exports.createCommentVNode = createCommentVNode;
15809 exports.createElementBlock = createElementBlock;
15810 exports.createElementVNode = createBaseVNode;
15811 exports.createHydrationRenderer = createHydrationRenderer;
15812 exports.createPropsRestProxy = createPropsRestProxy;
15813 exports.createRenderer = createRenderer;
15814 exports.createSSRApp = createSSRApp;
15815 exports.createSlots = createSlots;
15816 exports.createStaticVNode = createStaticVNode;
15817 exports.createTextVNode = createTextVNode;
15818 exports.createVNode = createVNode;
15819 exports.customRef = customRef;
15820 exports.defineAsyncComponent = defineAsyncComponent;
15821 exports.defineComponent = defineComponent;
15822 exports.defineCustomElement = defineCustomElement;
15823 exports.defineEmits = defineEmits;
15824 exports.defineExpose = defineExpose;
15825 exports.defineProps = defineProps;
15826 exports.defineSSRCustomElement = defineSSRCustomElement;
15827 exports.effect = effect;
15828 exports.effectScope = effectScope;
15829 exports.getCurrentInstance = getCurrentInstance;
15830 exports.getCurrentScope = getCurrentScope;
15831 exports.getTransitionRawChildren = getTransitionRawChildren;
15832 exports.guardReactiveProps = guardReactiveProps;
15833 exports.h = h;
15834 exports.handleError = handleError;
15835 exports.hydrate = hydrate;
15836 exports.initCustomFormatter = initCustomFormatter;
15837 exports.initDirectivesForSSR = initDirectivesForSSR;
15838 exports.inject = inject;
15839 exports.isMemoSame = isMemoSame;
15840 exports.isProxy = isProxy;
15841 exports.isReactive = isReactive;
15842 exports.isReadonly = isReadonly;
15843 exports.isRef = isRef;
15844 exports.isRuntimeOnly = isRuntimeOnly;
15845 exports.isShallow = isShallow;
15846 exports.isVNode = isVNode;
15847 exports.markRaw = markRaw;
15848 exports.mergeDefaults = mergeDefaults;
15849 exports.mergeProps = mergeProps;
15850 exports.nextTick = nextTick;
15851 exports.normalizeClass = normalizeClass;
15852 exports.normalizeProps = normalizeProps;
15853 exports.normalizeStyle = normalizeStyle;
15854 exports.onActivated = onActivated;
15855 exports.onBeforeMount = onBeforeMount;
15856 exports.onBeforeUnmount = onBeforeUnmount;
15857 exports.onBeforeUpdate = onBeforeUpdate;
15858 exports.onDeactivated = onDeactivated;
15859 exports.onErrorCaptured = onErrorCaptured;
15860 exports.onMounted = onMounted;
15861 exports.onRenderTracked = onRenderTracked;
15862 exports.onRenderTriggered = onRenderTriggered;
15863 exports.onScopeDispose = onScopeDispose;
15864 exports.onServerPrefetch = onServerPrefetch;
15865 exports.onUnmounted = onUnmounted;
15866 exports.onUpdated = onUpdated;
15867 exports.openBlock = openBlock;
15868 exports.popScopeId = popScopeId;
15869 exports.provide = provide;
15870 exports.proxyRefs = proxyRefs;
15871 exports.pushScopeId = pushScopeId;
15872 exports.queuePostFlushCb = queuePostFlushCb;
15873 exports.reactive = reactive;
15874 exports.readonly = readonly;
15875 exports.ref = ref;
15876 exports.registerRuntimeCompiler = registerRuntimeCompiler;
15877 exports.render = render;
15878 exports.renderList = renderList;
15879 exports.renderSlot = renderSlot;
15880 exports.resolveComponent = resolveComponent;
15881 exports.resolveDirective = resolveDirective;
15882 exports.resolveDynamicComponent = resolveDynamicComponent;
15883 exports.resolveFilter = resolveFilter;
15884 exports.resolveTransitionHooks = resolveTransitionHooks;
15885 exports.setBlockTracking = setBlockTracking;
15886 exports.setDevtoolsHook = setDevtoolsHook;
15887 exports.setTransitionHooks = setTransitionHooks;
15888 exports.shallowReactive = shallowReactive;
15889 exports.shallowReadonly = shallowReadonly;
15890 exports.shallowRef = shallowRef;
15891 exports.ssrContextKey = ssrContextKey;
15892 exports.ssrUtils = ssrUtils;
15893 exports.stop = stop;
15894 exports.toDisplayString = toDisplayString;
15895 exports.toHandlerKey = toHandlerKey;
15896 exports.toHandlers = toHandlers;
15897 exports.toRaw = toRaw;
15898 exports.toRef = toRef;
15899 exports.toRefs = toRefs;
15900 exports.transformVNodeArgs = transformVNodeArgs;
15901 exports.triggerRef = triggerRef;
15902 exports.unref = unref;
15903 exports.useAttrs = useAttrs;
15904 exports.useCssModule = useCssModule;
15905 exports.useCssVars = useCssVars;
15906 exports.useSSRContext = useSSRContext;
15907 exports.useSlots = useSlots;
15908 exports.useTransitionState = useTransitionState;
15909 exports.vModelCheckbox = vModelCheckbox;
15910 exports.vModelDynamic = vModelDynamic;
15911 exports.vModelRadio = vModelRadio;
15912 exports.vModelSelect = vModelSelect;
15913 exports.vModelText = vModelText;
15914 exports.vShow = vShow;
15915 exports.version = version;
15916 exports.warn = warn$1;
15917 exports.watch = watch;
15918 exports.watchEffect = watchEffect;
15919 exports.watchPostEffect = watchPostEffect;
15920 exports.watchSyncEffect = watchSyncEffect;
15921 exports.withAsyncContext = withAsyncContext;
15922 exports.withCtx = withCtx;
15923 exports.withDefaults = withDefaults;
15924 exports.withDirectives = withDirectives;
15925 exports.withKeys = withKeys;
15926 exports.withMemo = withMemo;
15927 exports.withModifiers = withModifiers;
15928 exports.withScopeId = withScopeId;
15929
15930 Object.defineProperty(exports, '__esModule', { value: true });
15931
15932 return exports;
15933
15934}({}));