UNPKG

632 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 = isArray(a);
246 bValidType = isArray(b);
247 if (aValidType || bValidType) {
248 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
249 }
250 aValidType = isObject(a);
251 bValidType = isObject(b);
252 if (aValidType || bValidType) {
253 /* istanbul ignore if: this if will probably never be called */
254 if (!aValidType || !bValidType) {
255 return false;
256 }
257 const aKeysCount = Object.keys(a).length;
258 const bKeysCount = Object.keys(b).length;
259 if (aKeysCount !== bKeysCount) {
260 return false;
261 }
262 for (const key in a) {
263 const aHasKey = a.hasOwnProperty(key);
264 const bHasKey = b.hasOwnProperty(key);
265 if ((aHasKey && !bHasKey) ||
266 (!aHasKey && bHasKey) ||
267 !looseEqual(a[key], b[key])) {
268 return false;
269 }
270 }
271 }
272 return String(a) === String(b);
273 }
274 function looseIndexOf(arr, val) {
275 return arr.findIndex(item => looseEqual(item, val));
276 }
277
278 /**
279 * For converting {{ interpolation }} values to displayed strings.
280 * @private
281 */
282 const toDisplayString = (val) => {
283 return val == null
284 ? ''
285 : isArray(val) ||
286 (isObject(val) &&
287 (val.toString === objectToString || !isFunction(val.toString)))
288 ? JSON.stringify(val, replacer, 2)
289 : String(val);
290 };
291 const replacer = (_key, val) => {
292 // can't use isRef here since @vue/shared has no deps
293 if (val && val.__v_isRef) {
294 return replacer(_key, val.value);
295 }
296 else if (isMap(val)) {
297 return {
298 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
299 entries[`${key} =>`] = val;
300 return entries;
301 }, {})
302 };
303 }
304 else if (isSet(val)) {
305 return {
306 [`Set(${val.size})`]: [...val.values()]
307 };
308 }
309 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
310 return String(val);
311 }
312 return val;
313 };
314
315 const EMPTY_OBJ = Object.freeze({})
316 ;
317 const EMPTY_ARR = Object.freeze([]) ;
318 const NOOP = () => { };
319 /**
320 * Always return false.
321 */
322 const NO = () => false;
323 const onRE = /^on[^a-z]/;
324 const isOn = (key) => onRE.test(key);
325 const isModelListener = (key) => key.startsWith('onUpdate:');
326 const extend = Object.assign;
327 const remove = (arr, el) => {
328 const i = arr.indexOf(el);
329 if (i > -1) {
330 arr.splice(i, 1);
331 }
332 };
333 const hasOwnProperty = Object.prototype.hasOwnProperty;
334 const hasOwn = (val, key) => hasOwnProperty.call(val, key);
335 const isArray = Array.isArray;
336 const isMap = (val) => toTypeString(val) === '[object Map]';
337 const isSet = (val) => toTypeString(val) === '[object Set]';
338 const isDate = (val) => val instanceof Date;
339 const isFunction = (val) => typeof val === 'function';
340 const isString = (val) => typeof val === 'string';
341 const isSymbol = (val) => typeof val === 'symbol';
342 const isObject = (val) => val !== null && typeof val === 'object';
343 const isPromise = (val) => {
344 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
345 };
346 const objectToString = Object.prototype.toString;
347 const toTypeString = (value) => objectToString.call(value);
348 const toRawType = (value) => {
349 // extract "RawType" from strings like "[object RawType]"
350 return toTypeString(value).slice(8, -1);
351 };
352 const isPlainObject = (val) => toTypeString(val) === '[object Object]';
353 const isIntegerKey = (key) => isString(key) &&
354 key !== 'NaN' &&
355 key[0] !== '-' &&
356 '' + parseInt(key, 10) === key;
357 const isReservedProp = /*#__PURE__*/ makeMap(
358 // the leading comma is intentional so empty string "" is also included
359 ',key,ref,ref_for,ref_key,' +
360 'onVnodeBeforeMount,onVnodeMounted,' +
361 'onVnodeBeforeUpdate,onVnodeUpdated,' +
362 'onVnodeBeforeUnmount,onVnodeUnmounted');
363 const cacheStringFunction = (fn) => {
364 const cache = Object.create(null);
365 return ((str) => {
366 const hit = cache[str];
367 return hit || (cache[str] = fn(str));
368 });
369 };
370 const camelizeRE = /-(\w)/g;
371 /**
372 * @private
373 */
374 const camelize = cacheStringFunction((str) => {
375 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
376 });
377 const hyphenateRE = /\B([A-Z])/g;
378 /**
379 * @private
380 */
381 const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
382 /**
383 * @private
384 */
385 const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
386 /**
387 * @private
388 */
389 const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
390 // compare whether a value has changed, accounting for NaN.
391 const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
392 const invokeArrayFns = (fns, arg) => {
393 for (let i = 0; i < fns.length; i++) {
394 fns[i](arg);
395 }
396 };
397 const def = (obj, key, value) => {
398 Object.defineProperty(obj, key, {
399 configurable: true,
400 enumerable: false,
401 value
402 });
403 };
404 const toNumber = (val) => {
405 const n = parseFloat(val);
406 return isNaN(n) ? val : n;
407 };
408 let _globalThis;
409 const getGlobalThis = () => {
410 return (_globalThis ||
411 (_globalThis =
412 typeof globalThis !== 'undefined'
413 ? globalThis
414 : typeof self !== 'undefined'
415 ? self
416 : typeof window !== 'undefined'
417 ? window
418 : typeof global !== 'undefined'
419 ? global
420 : {}));
421 };
422
423 function warn(msg, ...args) {
424 console.warn(`[Vue warn] ${msg}`, ...args);
425 }
426
427 let activeEffectScope;
428 const effectScopeStack = [];
429 class EffectScope {
430 constructor(detached = false) {
431 this.active = true;
432 this.effects = [];
433 this.cleanups = [];
434 if (!detached && activeEffectScope) {
435 this.parent = activeEffectScope;
436 this.index =
437 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
438 }
439 }
440 run(fn) {
441 if (this.active) {
442 try {
443 this.on();
444 return fn();
445 }
446 finally {
447 this.off();
448 }
449 }
450 else {
451 warn(`cannot run an inactive effect scope.`);
452 }
453 }
454 on() {
455 if (this.active) {
456 effectScopeStack.push(this);
457 activeEffectScope = this;
458 }
459 }
460 off() {
461 if (this.active) {
462 effectScopeStack.pop();
463 activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
464 }
465 }
466 stop(fromParent) {
467 if (this.active) {
468 this.effects.forEach(e => e.stop());
469 this.cleanups.forEach(cleanup => cleanup());
470 if (this.scopes) {
471 this.scopes.forEach(e => e.stop(true));
472 }
473 // nested scope, dereference from parent to avoid memory leaks
474 if (this.parent && !fromParent) {
475 // optimized O(1) removal
476 const last = this.parent.scopes.pop();
477 if (last && last !== this) {
478 this.parent.scopes[this.index] = last;
479 last.index = this.index;
480 }
481 }
482 this.active = false;
483 }
484 }
485 }
486 function effectScope(detached) {
487 return new EffectScope(detached);
488 }
489 function recordEffectScope(effect, scope) {
490 scope = scope || activeEffectScope;
491 if (scope && scope.active) {
492 scope.effects.push(effect);
493 }
494 }
495 function getCurrentScope() {
496 return activeEffectScope;
497 }
498 function onScopeDispose(fn) {
499 if (activeEffectScope) {
500 activeEffectScope.cleanups.push(fn);
501 }
502 else {
503 warn(`onScopeDispose() is called when there is no active effect scope` +
504 ` to be associated with.`);
505 }
506 }
507
508 const createDep = (effects) => {
509 const dep = new Set(effects);
510 dep.w = 0;
511 dep.n = 0;
512 return dep;
513 };
514 const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
515 const newTracked = (dep) => (dep.n & trackOpBit) > 0;
516 const initDepMarkers = ({ deps }) => {
517 if (deps.length) {
518 for (let i = 0; i < deps.length; i++) {
519 deps[i].w |= trackOpBit; // set was tracked
520 }
521 }
522 };
523 const finalizeDepMarkers = (effect) => {
524 const { deps } = effect;
525 if (deps.length) {
526 let ptr = 0;
527 for (let i = 0; i < deps.length; i++) {
528 const dep = deps[i];
529 if (wasTracked(dep) && !newTracked(dep)) {
530 dep.delete(effect);
531 }
532 else {
533 deps[ptr++] = dep;
534 }
535 // clear bits
536 dep.w &= ~trackOpBit;
537 dep.n &= ~trackOpBit;
538 }
539 deps.length = ptr;
540 }
541 };
542
543 const targetMap = new WeakMap();
544 // The number of effects currently being tracked recursively.
545 let effectTrackDepth = 0;
546 let trackOpBit = 1;
547 /**
548 * The bitwise track markers support at most 30 levels of recursion.
549 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
550 * When recursion depth is greater, fall back to using a full cleanup.
551 */
552 const maxMarkerBits = 30;
553 const effectStack = [];
554 let activeEffect;
555 const ITERATE_KEY = Symbol('iterate' );
556 const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
557 class ReactiveEffect {
558 constructor(fn, scheduler = null, scope) {
559 this.fn = fn;
560 this.scheduler = scheduler;
561 this.active = true;
562 this.deps = [];
563 recordEffectScope(this, scope);
564 }
565 run() {
566 if (!this.active) {
567 return this.fn();
568 }
569 if (!effectStack.length || !effectStack.includes(this)) {
570 try {
571 effectStack.push((activeEffect = this));
572 enableTracking();
573 trackOpBit = 1 << ++effectTrackDepth;
574 if (effectTrackDepth <= maxMarkerBits) {
575 initDepMarkers(this);
576 }
577 else {
578 cleanupEffect(this);
579 }
580 return this.fn();
581 }
582 finally {
583 if (effectTrackDepth <= maxMarkerBits) {
584 finalizeDepMarkers(this);
585 }
586 trackOpBit = 1 << --effectTrackDepth;
587 resetTracking();
588 effectStack.pop();
589 const n = effectStack.length;
590 activeEffect = n > 0 ? effectStack[n - 1] : undefined;
591 }
592 }
593 }
594 stop() {
595 if (this.active) {
596 cleanupEffect(this);
597 if (this.onStop) {
598 this.onStop();
599 }
600 this.active = false;
601 }
602 }
603 }
604 function cleanupEffect(effect) {
605 const { deps } = effect;
606 if (deps.length) {
607 for (let i = 0; i < deps.length; i++) {
608 deps[i].delete(effect);
609 }
610 deps.length = 0;
611 }
612 }
613 function effect(fn, options) {
614 if (fn.effect) {
615 fn = fn.effect.fn;
616 }
617 const _effect = new ReactiveEffect(fn);
618 if (options) {
619 extend(_effect, options);
620 if (options.scope)
621 recordEffectScope(_effect, options.scope);
622 }
623 if (!options || !options.lazy) {
624 _effect.run();
625 }
626 const runner = _effect.run.bind(_effect);
627 runner.effect = _effect;
628 return runner;
629 }
630 function stop(runner) {
631 runner.effect.stop();
632 }
633 let shouldTrack = true;
634 const trackStack = [];
635 function pauseTracking() {
636 trackStack.push(shouldTrack);
637 shouldTrack = false;
638 }
639 function enableTracking() {
640 trackStack.push(shouldTrack);
641 shouldTrack = true;
642 }
643 function resetTracking() {
644 const last = trackStack.pop();
645 shouldTrack = last === undefined ? true : last;
646 }
647 function track(target, type, key) {
648 if (!isTracking()) {
649 return;
650 }
651 let depsMap = targetMap.get(target);
652 if (!depsMap) {
653 targetMap.set(target, (depsMap = new Map()));
654 }
655 let dep = depsMap.get(key);
656 if (!dep) {
657 depsMap.set(key, (dep = createDep()));
658 }
659 const eventInfo = { effect: activeEffect, target, type, key }
660 ;
661 trackEffects(dep, eventInfo);
662 }
663 function isTracking() {
664 return shouldTrack && activeEffect !== undefined;
665 }
666 function trackEffects(dep, debuggerEventExtraInfo) {
667 let shouldTrack = false;
668 if (effectTrackDepth <= maxMarkerBits) {
669 if (!newTracked(dep)) {
670 dep.n |= trackOpBit; // set newly tracked
671 shouldTrack = !wasTracked(dep);
672 }
673 }
674 else {
675 // Full cleanup mode.
676 shouldTrack = !dep.has(activeEffect);
677 }
678 if (shouldTrack) {
679 dep.add(activeEffect);
680 activeEffect.deps.push(dep);
681 if (activeEffect.onTrack) {
682 activeEffect.onTrack(Object.assign({
683 effect: activeEffect
684 }, debuggerEventExtraInfo));
685 }
686 }
687 }
688 function trigger(target, type, key, newValue, oldValue, oldTarget) {
689 const depsMap = targetMap.get(target);
690 if (!depsMap) {
691 // never been tracked
692 return;
693 }
694 let deps = [];
695 if (type === "clear" /* CLEAR */) {
696 // collection being cleared
697 // trigger all effects for target
698 deps = [...depsMap.values()];
699 }
700 else if (key === 'length' && isArray(target)) {
701 depsMap.forEach((dep, key) => {
702 if (key === 'length' || key >= newValue) {
703 deps.push(dep);
704 }
705 });
706 }
707 else {
708 // schedule runs for SET | ADD | DELETE
709 if (key !== void 0) {
710 deps.push(depsMap.get(key));
711 }
712 // also run for iteration key on ADD | DELETE | Map.SET
713 switch (type) {
714 case "add" /* ADD */:
715 if (!isArray(target)) {
716 deps.push(depsMap.get(ITERATE_KEY));
717 if (isMap(target)) {
718 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
719 }
720 }
721 else if (isIntegerKey(key)) {
722 // new index added to array -> length changes
723 deps.push(depsMap.get('length'));
724 }
725 break;
726 case "delete" /* DELETE */:
727 if (!isArray(target)) {
728 deps.push(depsMap.get(ITERATE_KEY));
729 if (isMap(target)) {
730 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
731 }
732 }
733 break;
734 case "set" /* SET */:
735 if (isMap(target)) {
736 deps.push(depsMap.get(ITERATE_KEY));
737 }
738 break;
739 }
740 }
741 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
742 ;
743 if (deps.length === 1) {
744 if (deps[0]) {
745 {
746 triggerEffects(deps[0], eventInfo);
747 }
748 }
749 }
750 else {
751 const effects = [];
752 for (const dep of deps) {
753 if (dep) {
754 effects.push(...dep);
755 }
756 }
757 {
758 triggerEffects(createDep(effects), eventInfo);
759 }
760 }
761 }
762 function triggerEffects(dep, debuggerEventExtraInfo) {
763 // spread into array for stabilization
764 for (const effect of isArray(dep) ? dep : [...dep]) {
765 if (effect !== activeEffect || effect.allowRecurse) {
766 if (effect.onTrigger) {
767 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
768 }
769 if (effect.scheduler) {
770 effect.scheduler();
771 }
772 else {
773 effect.run();
774 }
775 }
776 }
777 }
778
779 const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
780 const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
781 .map(key => Symbol[key])
782 .filter(isSymbol));
783 const get = /*#__PURE__*/ createGetter();
784 const shallowGet = /*#__PURE__*/ createGetter(false, true);
785 const readonlyGet = /*#__PURE__*/ createGetter(true);
786 const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
787 const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
788 function createArrayInstrumentations() {
789 const instrumentations = {};
790 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
791 instrumentations[key] = function (...args) {
792 const arr = toRaw(this);
793 for (let i = 0, l = this.length; i < l; i++) {
794 track(arr, "get" /* GET */, i + '');
795 }
796 // we run the method using the original args first (which may be reactive)
797 const res = arr[key](...args);
798 if (res === -1 || res === false) {
799 // if that didn't work, run it again using raw values.
800 return arr[key](...args.map(toRaw));
801 }
802 else {
803 return res;
804 }
805 };
806 });
807 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
808 instrumentations[key] = function (...args) {
809 pauseTracking();
810 const res = toRaw(this)[key].apply(this, args);
811 resetTracking();
812 return res;
813 };
814 });
815 return instrumentations;
816 }
817 function createGetter(isReadonly = false, shallow = false) {
818 return function get(target, key, receiver) {
819 if (key === "__v_isReactive" /* IS_REACTIVE */) {
820 return !isReadonly;
821 }
822 else if (key === "__v_isReadonly" /* IS_READONLY */) {
823 return isReadonly;
824 }
825 else if (key === "__v_isShallow" /* IS_SHALLOW */) {
826 return shallow;
827 }
828 else if (key === "__v_raw" /* RAW */ &&
829 receiver ===
830 (isReadonly
831 ? shallow
832 ? shallowReadonlyMap
833 : readonlyMap
834 : shallow
835 ? shallowReactiveMap
836 : reactiveMap).get(target)) {
837 return target;
838 }
839 const targetIsArray = isArray(target);
840 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
841 return Reflect.get(arrayInstrumentations, key, receiver);
842 }
843 const res = Reflect.get(target, key, receiver);
844 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
845 return res;
846 }
847 if (!isReadonly) {
848 track(target, "get" /* GET */, key);
849 }
850 if (shallow) {
851 return res;
852 }
853 if (isRef(res)) {
854 // ref unwrapping - does not apply for Array + integer key.
855 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
856 return shouldUnwrap ? res.value : res;
857 }
858 if (isObject(res)) {
859 // Convert returned value into a proxy as well. we do the isObject check
860 // here to avoid invalid value warning. Also need to lazy access readonly
861 // and reactive here to avoid circular dependency.
862 return isReadonly ? readonly(res) : reactive(res);
863 }
864 return res;
865 };
866 }
867 const set = /*#__PURE__*/ createSetter();
868 const shallowSet = /*#__PURE__*/ createSetter(true);
869 function createSetter(shallow = false) {
870 return function set(target, key, value, receiver) {
871 let oldValue = target[key];
872 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
873 return false;
874 }
875 if (!shallow && !isReadonly(value)) {
876 if (!isShallow(value)) {
877 value = toRaw(value);
878 oldValue = toRaw(oldValue);
879 }
880 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
881 oldValue.value = value;
882 return true;
883 }
884 }
885 const hadKey = isArray(target) && isIntegerKey(key)
886 ? Number(key) < target.length
887 : hasOwn(target, key);
888 const result = Reflect.set(target, key, value, receiver);
889 // don't trigger if target is something up in the prototype chain of original
890 if (target === toRaw(receiver)) {
891 if (!hadKey) {
892 trigger(target, "add" /* ADD */, key, value);
893 }
894 else if (hasChanged(value, oldValue)) {
895 trigger(target, "set" /* SET */, key, value, oldValue);
896 }
897 }
898 return result;
899 };
900 }
901 function deleteProperty(target, key) {
902 const hadKey = hasOwn(target, key);
903 const oldValue = target[key];
904 const result = Reflect.deleteProperty(target, key);
905 if (result && hadKey) {
906 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
907 }
908 return result;
909 }
910 function has(target, key) {
911 const result = Reflect.has(target, key);
912 if (!isSymbol(key) || !builtInSymbols.has(key)) {
913 track(target, "has" /* HAS */, key);
914 }
915 return result;
916 }
917 function ownKeys(target) {
918 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
919 return Reflect.ownKeys(target);
920 }
921 const mutableHandlers = {
922 get,
923 set,
924 deleteProperty,
925 has,
926 ownKeys
927 };
928 const readonlyHandlers = {
929 get: readonlyGet,
930 set(target, key) {
931 {
932 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
933 }
934 return true;
935 },
936 deleteProperty(target, key) {
937 {
938 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
939 }
940 return true;
941 }
942 };
943 const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
944 get: shallowGet,
945 set: shallowSet
946 });
947 // Props handlers are special in the sense that it should not unwrap top-level
948 // refs (in order to allow refs to be explicitly passed down), but should
949 // retain the reactivity of the normal readonly object.
950 const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
951 get: shallowReadonlyGet
952 });
953
954 const toShallow = (value) => value;
955 const getProto = (v) => Reflect.getPrototypeOf(v);
956 function get$1(target, key, isReadonly = false, isShallow = false) {
957 // #1772: readonly(reactive(Map)) should return readonly + reactive version
958 // of the value
959 target = target["__v_raw" /* RAW */];
960 const rawTarget = toRaw(target);
961 const rawKey = toRaw(key);
962 if (key !== rawKey) {
963 !isReadonly && track(rawTarget, "get" /* GET */, key);
964 }
965 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
966 const { has } = getProto(rawTarget);
967 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
968 if (has.call(rawTarget, key)) {
969 return wrap(target.get(key));
970 }
971 else if (has.call(rawTarget, rawKey)) {
972 return wrap(target.get(rawKey));
973 }
974 else if (target !== rawTarget) {
975 // #3602 readonly(reactive(Map))
976 // ensure that the nested reactive `Map` can do tracking for itself
977 target.get(key);
978 }
979 }
980 function has$1(key, isReadonly = false) {
981 const target = this["__v_raw" /* RAW */];
982 const rawTarget = toRaw(target);
983 const rawKey = toRaw(key);
984 if (key !== rawKey) {
985 !isReadonly && track(rawTarget, "has" /* HAS */, key);
986 }
987 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
988 return key === rawKey
989 ? target.has(key)
990 : target.has(key) || target.has(rawKey);
991 }
992 function size(target, isReadonly = false) {
993 target = target["__v_raw" /* RAW */];
994 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
995 return Reflect.get(target, 'size', target);
996 }
997 function add(value) {
998 value = toRaw(value);
999 const target = toRaw(this);
1000 const proto = getProto(target);
1001 const hadKey = proto.has.call(target, value);
1002 if (!hadKey) {
1003 target.add(value);
1004 trigger(target, "add" /* ADD */, value, value);
1005 }
1006 return this;
1007 }
1008 function set$1(key, value) {
1009 value = toRaw(value);
1010 const target = toRaw(this);
1011 const { has, get } = getProto(target);
1012 let hadKey = has.call(target, key);
1013 if (!hadKey) {
1014 key = toRaw(key);
1015 hadKey = has.call(target, key);
1016 }
1017 else {
1018 checkIdentityKeys(target, has, key);
1019 }
1020 const oldValue = get.call(target, key);
1021 target.set(key, value);
1022 if (!hadKey) {
1023 trigger(target, "add" /* ADD */, key, value);
1024 }
1025 else if (hasChanged(value, oldValue)) {
1026 trigger(target, "set" /* SET */, key, value, oldValue);
1027 }
1028 return this;
1029 }
1030 function deleteEntry(key) {
1031 const target = toRaw(this);
1032 const { has, get } = getProto(target);
1033 let hadKey = has.call(target, key);
1034 if (!hadKey) {
1035 key = toRaw(key);
1036 hadKey = has.call(target, key);
1037 }
1038 else {
1039 checkIdentityKeys(target, has, key);
1040 }
1041 const oldValue = get ? get.call(target, key) : undefined;
1042 // forward the operation before queueing reactions
1043 const result = target.delete(key);
1044 if (hadKey) {
1045 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1046 }
1047 return result;
1048 }
1049 function clear() {
1050 const target = toRaw(this);
1051 const hadItems = target.size !== 0;
1052 const oldTarget = isMap(target)
1053 ? new Map(target)
1054 : new Set(target)
1055 ;
1056 // forward the operation before queueing reactions
1057 const result = target.clear();
1058 if (hadItems) {
1059 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1060 }
1061 return result;
1062 }
1063 function createForEach(isReadonly, isShallow) {
1064 return function forEach(callback, thisArg) {
1065 const observed = this;
1066 const target = observed["__v_raw" /* RAW */];
1067 const rawTarget = toRaw(target);
1068 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1069 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1070 return target.forEach((value, key) => {
1071 // important: make sure the callback is
1072 // 1. invoked with the reactive map as `this` and 3rd arg
1073 // 2. the value received should be a corresponding reactive/readonly.
1074 return callback.call(thisArg, wrap(value), wrap(key), observed);
1075 });
1076 };
1077 }
1078 function createIterableMethod(method, isReadonly, isShallow) {
1079 return function (...args) {
1080 const target = this["__v_raw" /* RAW */];
1081 const rawTarget = toRaw(target);
1082 const targetIsMap = isMap(rawTarget);
1083 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1084 const isKeyOnly = method === 'keys' && targetIsMap;
1085 const innerIterator = target[method](...args);
1086 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1087 !isReadonly &&
1088 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1089 // return a wrapped iterator which returns observed versions of the
1090 // values emitted from the real iterator
1091 return {
1092 // iterator protocol
1093 next() {
1094 const { value, done } = innerIterator.next();
1095 return done
1096 ? { value, done }
1097 : {
1098 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1099 done
1100 };
1101 },
1102 // iterable protocol
1103 [Symbol.iterator]() {
1104 return this;
1105 }
1106 };
1107 };
1108 }
1109 function createReadonlyMethod(type) {
1110 return function (...args) {
1111 {
1112 const key = args[0] ? `on key "${args[0]}" ` : ``;
1113 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1114 }
1115 return type === "delete" /* DELETE */ ? false : this;
1116 };
1117 }
1118 function createInstrumentations() {
1119 const mutableInstrumentations = {
1120 get(key) {
1121 return get$1(this, key);
1122 },
1123 get size() {
1124 return size(this);
1125 },
1126 has: has$1,
1127 add,
1128 set: set$1,
1129 delete: deleteEntry,
1130 clear,
1131 forEach: createForEach(false, false)
1132 };
1133 const shallowInstrumentations = {
1134 get(key) {
1135 return get$1(this, key, false, true);
1136 },
1137 get size() {
1138 return size(this);
1139 },
1140 has: has$1,
1141 add,
1142 set: set$1,
1143 delete: deleteEntry,
1144 clear,
1145 forEach: createForEach(false, true)
1146 };
1147 const readonlyInstrumentations = {
1148 get(key) {
1149 return get$1(this, key, true);
1150 },
1151 get size() {
1152 return size(this, true);
1153 },
1154 has(key) {
1155 return has$1.call(this, key, true);
1156 },
1157 add: createReadonlyMethod("add" /* ADD */),
1158 set: createReadonlyMethod("set" /* SET */),
1159 delete: createReadonlyMethod("delete" /* DELETE */),
1160 clear: createReadonlyMethod("clear" /* CLEAR */),
1161 forEach: createForEach(true, false)
1162 };
1163 const shallowReadonlyInstrumentations = {
1164 get(key) {
1165 return get$1(this, key, true, true);
1166 },
1167 get size() {
1168 return size(this, true);
1169 },
1170 has(key) {
1171 return has$1.call(this, key, true);
1172 },
1173 add: createReadonlyMethod("add" /* ADD */),
1174 set: createReadonlyMethod("set" /* SET */),
1175 delete: createReadonlyMethod("delete" /* DELETE */),
1176 clear: createReadonlyMethod("clear" /* CLEAR */),
1177 forEach: createForEach(true, true)
1178 };
1179 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1180 iteratorMethods.forEach(method => {
1181 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1182 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1183 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1184 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1185 });
1186 return [
1187 mutableInstrumentations,
1188 readonlyInstrumentations,
1189 shallowInstrumentations,
1190 shallowReadonlyInstrumentations
1191 ];
1192 }
1193 const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1194 function createInstrumentationGetter(isReadonly, shallow) {
1195 const instrumentations = shallow
1196 ? isReadonly
1197 ? shallowReadonlyInstrumentations
1198 : shallowInstrumentations
1199 : isReadonly
1200 ? readonlyInstrumentations
1201 : mutableInstrumentations;
1202 return (target, key, receiver) => {
1203 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1204 return !isReadonly;
1205 }
1206 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1207 return isReadonly;
1208 }
1209 else if (key === "__v_raw" /* RAW */) {
1210 return target;
1211 }
1212 return Reflect.get(hasOwn(instrumentations, key) && key in target
1213 ? instrumentations
1214 : target, key, receiver);
1215 };
1216 }
1217 const mutableCollectionHandlers = {
1218 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1219 };
1220 const shallowCollectionHandlers = {
1221 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1222 };
1223 const readonlyCollectionHandlers = {
1224 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1225 };
1226 const shallowReadonlyCollectionHandlers = {
1227 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1228 };
1229 function checkIdentityKeys(target, has, key) {
1230 const rawKey = toRaw(key);
1231 if (rawKey !== key && has.call(target, rawKey)) {
1232 const type = toRawType(target);
1233 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1234 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1235 `which can lead to inconsistencies. ` +
1236 `Avoid differentiating between the raw and reactive versions ` +
1237 `of an object and only use the reactive version if possible.`);
1238 }
1239 }
1240
1241 const reactiveMap = new WeakMap();
1242 const shallowReactiveMap = new WeakMap();
1243 const readonlyMap = new WeakMap();
1244 const shallowReadonlyMap = new WeakMap();
1245 function targetTypeMap(rawType) {
1246 switch (rawType) {
1247 case 'Object':
1248 case 'Array':
1249 return 1 /* COMMON */;
1250 case 'Map':
1251 case 'Set':
1252 case 'WeakMap':
1253 case 'WeakSet':
1254 return 2 /* COLLECTION */;
1255 default:
1256 return 0 /* INVALID */;
1257 }
1258 }
1259 function getTargetType(value) {
1260 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1261 ? 0 /* INVALID */
1262 : targetTypeMap(toRawType(value));
1263 }
1264 function reactive(target) {
1265 // if trying to observe a readonly proxy, return the readonly version.
1266 if (isReadonly(target)) {
1267 return target;
1268 }
1269 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1270 }
1271 /**
1272 * Return a shallowly-reactive copy of the original object, where only the root
1273 * level properties are reactive. It also does not auto-unwrap refs (even at the
1274 * root level).
1275 */
1276 function shallowReactive(target) {
1277 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1278 }
1279 /**
1280 * Creates a readonly copy of the original object. Note the returned copy is not
1281 * made reactive, but `readonly` can be called on an already reactive object.
1282 */
1283 function readonly(target) {
1284 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1285 }
1286 /**
1287 * Returns a reactive-copy of the original object, where only the root level
1288 * properties are readonly, and does NOT unwrap refs nor recursively convert
1289 * returned properties.
1290 * This is used for creating the props proxy object for stateful components.
1291 */
1292 function shallowReadonly(target) {
1293 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1294 }
1295 function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1296 if (!isObject(target)) {
1297 {
1298 console.warn(`value cannot be made reactive: ${String(target)}`);
1299 }
1300 return target;
1301 }
1302 // target is already a Proxy, return it.
1303 // exception: calling readonly() on a reactive object
1304 if (target["__v_raw" /* RAW */] &&
1305 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1306 return target;
1307 }
1308 // target already has corresponding Proxy
1309 const existingProxy = proxyMap.get(target);
1310 if (existingProxy) {
1311 return existingProxy;
1312 }
1313 // only a whitelist of value types can be observed.
1314 const targetType = getTargetType(target);
1315 if (targetType === 0 /* INVALID */) {
1316 return target;
1317 }
1318 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1319 proxyMap.set(target, proxy);
1320 return proxy;
1321 }
1322 function isReactive(value) {
1323 if (isReadonly(value)) {
1324 return isReactive(value["__v_raw" /* RAW */]);
1325 }
1326 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1327 }
1328 function isReadonly(value) {
1329 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1330 }
1331 function isShallow(value) {
1332 return !!(value && value["__v_isShallow" /* IS_SHALLOW */]);
1333 }
1334 function isProxy(value) {
1335 return isReactive(value) || isReadonly(value);
1336 }
1337 function toRaw(observed) {
1338 const raw = observed && observed["__v_raw" /* RAW */];
1339 return raw ? toRaw(raw) : observed;
1340 }
1341 function markRaw(value) {
1342 def(value, "__v_skip" /* SKIP */, true);
1343 return value;
1344 }
1345 const toReactive = (value) => isObject(value) ? reactive(value) : value;
1346 const toReadonly = (value) => isObject(value) ? readonly(value) : value;
1347
1348 function trackRefValue(ref) {
1349 if (isTracking()) {
1350 ref = toRaw(ref);
1351 if (!ref.dep) {
1352 ref.dep = createDep();
1353 }
1354 {
1355 trackEffects(ref.dep, {
1356 target: ref,
1357 type: "get" /* GET */,
1358 key: 'value'
1359 });
1360 }
1361 }
1362 }
1363 function triggerRefValue(ref, newVal) {
1364 ref = toRaw(ref);
1365 if (ref.dep) {
1366 {
1367 triggerEffects(ref.dep, {
1368 target: ref,
1369 type: "set" /* SET */,
1370 key: 'value',
1371 newValue: newVal
1372 });
1373 }
1374 }
1375 }
1376 function isRef(r) {
1377 return Boolean(r && r.__v_isRef === true);
1378 }
1379 function ref(value) {
1380 return createRef(value, false);
1381 }
1382 function shallowRef(value) {
1383 return createRef(value, true);
1384 }
1385 function createRef(rawValue, shallow) {
1386 if (isRef(rawValue)) {
1387 return rawValue;
1388 }
1389 return new RefImpl(rawValue, shallow);
1390 }
1391 class RefImpl {
1392 constructor(value, __v_isShallow) {
1393 this.__v_isShallow = __v_isShallow;
1394 this.dep = undefined;
1395 this.__v_isRef = true;
1396 this._rawValue = __v_isShallow ? value : toRaw(value);
1397 this._value = __v_isShallow ? value : toReactive(value);
1398 }
1399 get value() {
1400 trackRefValue(this);
1401 return this._value;
1402 }
1403 set value(newVal) {
1404 newVal = this.__v_isShallow ? newVal : toRaw(newVal);
1405 if (hasChanged(newVal, this._rawValue)) {
1406 this._rawValue = newVal;
1407 this._value = this.__v_isShallow ? newVal : toReactive(newVal);
1408 triggerRefValue(this, newVal);
1409 }
1410 }
1411 }
1412 function triggerRef(ref) {
1413 triggerRefValue(ref, ref.value );
1414 }
1415 function unref(ref) {
1416 return isRef(ref) ? ref.value : ref;
1417 }
1418 const shallowUnwrapHandlers = {
1419 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1420 set: (target, key, value, receiver) => {
1421 const oldValue = target[key];
1422 if (isRef(oldValue) && !isRef(value)) {
1423 oldValue.value = value;
1424 return true;
1425 }
1426 else {
1427 return Reflect.set(target, key, value, receiver);
1428 }
1429 }
1430 };
1431 function proxyRefs(objectWithRefs) {
1432 return isReactive(objectWithRefs)
1433 ? objectWithRefs
1434 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1435 }
1436 class CustomRefImpl {
1437 constructor(factory) {
1438 this.dep = undefined;
1439 this.__v_isRef = true;
1440 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1441 this._get = get;
1442 this._set = set;
1443 }
1444 get value() {
1445 return this._get();
1446 }
1447 set value(newVal) {
1448 this._set(newVal);
1449 }
1450 }
1451 function customRef(factory) {
1452 return new CustomRefImpl(factory);
1453 }
1454 function toRefs(object) {
1455 if (!isProxy(object)) {
1456 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1457 }
1458 const ret = isArray(object) ? new Array(object.length) : {};
1459 for (const key in object) {
1460 ret[key] = toRef(object, key);
1461 }
1462 return ret;
1463 }
1464 class ObjectRefImpl {
1465 constructor(_object, _key, _defaultValue) {
1466 this._object = _object;
1467 this._key = _key;
1468 this._defaultValue = _defaultValue;
1469 this.__v_isRef = true;
1470 }
1471 get value() {
1472 const val = this._object[this._key];
1473 return val === undefined ? this._defaultValue : val;
1474 }
1475 set value(newVal) {
1476 this._object[this._key] = newVal;
1477 }
1478 }
1479 function toRef(object, key, defaultValue) {
1480 const val = object[key];
1481 return isRef(val)
1482 ? val
1483 : new ObjectRefImpl(object, key, defaultValue);
1484 }
1485
1486 class ComputedRefImpl {
1487 constructor(getter, _setter, isReadonly, isSSR) {
1488 this._setter = _setter;
1489 this.dep = undefined;
1490 this.__v_isRef = true;
1491 this._dirty = true;
1492 this.effect = new ReactiveEffect(getter, () => {
1493 if (!this._dirty) {
1494 this._dirty = true;
1495 triggerRefValue(this);
1496 }
1497 });
1498 this.effect.computed = this;
1499 this.effect.active = this._cacheable = !isSSR;
1500 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1501 }
1502 get value() {
1503 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1504 const self = toRaw(this);
1505 trackRefValue(self);
1506 if (self._dirty || !self._cacheable) {
1507 self._dirty = false;
1508 self._value = self.effect.run();
1509 }
1510 return self._value;
1511 }
1512 set value(newValue) {
1513 this._setter(newValue);
1514 }
1515 }
1516 function computed(getterOrOptions, debugOptions, isSSR = false) {
1517 let getter;
1518 let setter;
1519 const onlyGetter = isFunction(getterOrOptions);
1520 if (onlyGetter) {
1521 getter = getterOrOptions;
1522 setter = () => {
1523 console.warn('Write operation failed: computed value is readonly');
1524 }
1525 ;
1526 }
1527 else {
1528 getter = getterOrOptions.get;
1529 setter = getterOrOptions.set;
1530 }
1531 const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
1532 if (debugOptions && !isSSR) {
1533 cRef.effect.onTrack = debugOptions.onTrack;
1534 cRef.effect.onTrigger = debugOptions.onTrigger;
1535 }
1536 return cRef;
1537 }
1538
1539 const stack = [];
1540 function pushWarningContext(vnode) {
1541 stack.push(vnode);
1542 }
1543 function popWarningContext() {
1544 stack.pop();
1545 }
1546 function warn$1(msg, ...args) {
1547 // avoid props formatting or warn handler tracking deps that might be mutated
1548 // during patch, leading to infinite recursion.
1549 pauseTracking();
1550 const instance = stack.length ? stack[stack.length - 1].component : null;
1551 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1552 const trace = getComponentTrace();
1553 if (appWarnHandler) {
1554 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1555 msg + args.join(''),
1556 instance && instance.proxy,
1557 trace
1558 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1559 .join('\n'),
1560 trace
1561 ]);
1562 }
1563 else {
1564 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1565 /* istanbul ignore if */
1566 if (trace.length &&
1567 // avoid spamming console during tests
1568 !false) {
1569 warnArgs.push(`\n`, ...formatTrace(trace));
1570 }
1571 console.warn(...warnArgs);
1572 }
1573 resetTracking();
1574 }
1575 function getComponentTrace() {
1576 let currentVNode = stack[stack.length - 1];
1577 if (!currentVNode) {
1578 return [];
1579 }
1580 // we can't just use the stack because it will be incomplete during updates
1581 // that did not start from the root. Re-construct the parent chain using
1582 // instance parent pointers.
1583 const normalizedStack = [];
1584 while (currentVNode) {
1585 const last = normalizedStack[0];
1586 if (last && last.vnode === currentVNode) {
1587 last.recurseCount++;
1588 }
1589 else {
1590 normalizedStack.push({
1591 vnode: currentVNode,
1592 recurseCount: 0
1593 });
1594 }
1595 const parentInstance = currentVNode.component && currentVNode.component.parent;
1596 currentVNode = parentInstance && parentInstance.vnode;
1597 }
1598 return normalizedStack;
1599 }
1600 /* istanbul ignore next */
1601 function formatTrace(trace) {
1602 const logs = [];
1603 trace.forEach((entry, i) => {
1604 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1605 });
1606 return logs;
1607 }
1608 function formatTraceEntry({ vnode, recurseCount }) {
1609 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1610 const isRoot = vnode.component ? vnode.component.parent == null : false;
1611 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1612 const close = `>` + postfix;
1613 return vnode.props
1614 ? [open, ...formatProps(vnode.props), close]
1615 : [open + close];
1616 }
1617 /* istanbul ignore next */
1618 function formatProps(props) {
1619 const res = [];
1620 const keys = Object.keys(props);
1621 keys.slice(0, 3).forEach(key => {
1622 res.push(...formatProp(key, props[key]));
1623 });
1624 if (keys.length > 3) {
1625 res.push(` ...`);
1626 }
1627 return res;
1628 }
1629 /* istanbul ignore next */
1630 function formatProp(key, value, raw) {
1631 if (isString(value)) {
1632 value = JSON.stringify(value);
1633 return raw ? value : [`${key}=${value}`];
1634 }
1635 else if (typeof value === 'number' ||
1636 typeof value === 'boolean' ||
1637 value == null) {
1638 return raw ? value : [`${key}=${value}`];
1639 }
1640 else if (isRef(value)) {
1641 value = formatProp(key, toRaw(value.value), true);
1642 return raw ? value : [`${key}=Ref<`, value, `>`];
1643 }
1644 else if (isFunction(value)) {
1645 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1646 }
1647 else {
1648 value = toRaw(value);
1649 return raw ? value : [`${key}=`, value];
1650 }
1651 }
1652
1653 const ErrorTypeStrings = {
1654 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
1655 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1656 ["c" /* CREATED */]: 'created hook',
1657 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1658 ["m" /* MOUNTED */]: 'mounted hook',
1659 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1660 ["u" /* UPDATED */]: 'updated',
1661 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1662 ["um" /* UNMOUNTED */]: 'unmounted hook',
1663 ["a" /* ACTIVATED */]: 'activated hook',
1664 ["da" /* DEACTIVATED */]: 'deactivated hook',
1665 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1666 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1667 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1668 [0 /* SETUP_FUNCTION */]: 'setup function',
1669 [1 /* RENDER_FUNCTION */]: 'render function',
1670 [2 /* WATCH_GETTER */]: 'watcher getter',
1671 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1672 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1673 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1674 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1675 [7 /* VNODE_HOOK */]: 'vnode hook',
1676 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1677 [9 /* TRANSITION_HOOK */]: 'transition hook',
1678 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1679 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1680 [12 /* FUNCTION_REF */]: 'ref function',
1681 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1682 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1683 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
1684 };
1685 function callWithErrorHandling(fn, instance, type, args) {
1686 let res;
1687 try {
1688 res = args ? fn(...args) : fn();
1689 }
1690 catch (err) {
1691 handleError(err, instance, type);
1692 }
1693 return res;
1694 }
1695 function callWithAsyncErrorHandling(fn, instance, type, args) {
1696 if (isFunction(fn)) {
1697 const res = callWithErrorHandling(fn, instance, type, args);
1698 if (res && isPromise(res)) {
1699 res.catch(err => {
1700 handleError(err, instance, type);
1701 });
1702 }
1703 return res;
1704 }
1705 const values = [];
1706 for (let i = 0; i < fn.length; i++) {
1707 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1708 }
1709 return values;
1710 }
1711 function handleError(err, instance, type, throwInDev = true) {
1712 const contextVNode = instance ? instance.vnode : null;
1713 if (instance) {
1714 let cur = instance.parent;
1715 // the exposed instance is the render proxy to keep it consistent with 2.x
1716 const exposedInstance = instance.proxy;
1717 // in production the hook receives only the error code
1718 const errorInfo = ErrorTypeStrings[type] ;
1719 while (cur) {
1720 const errorCapturedHooks = cur.ec;
1721 if (errorCapturedHooks) {
1722 for (let i = 0; i < errorCapturedHooks.length; i++) {
1723 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1724 return;
1725 }
1726 }
1727 }
1728 cur = cur.parent;
1729 }
1730 // app-level handling
1731 const appErrorHandler = instance.appContext.config.errorHandler;
1732 if (appErrorHandler) {
1733 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1734 return;
1735 }
1736 }
1737 logError(err, type, contextVNode, throwInDev);
1738 }
1739 function logError(err, type, contextVNode, throwInDev = true) {
1740 {
1741 const info = ErrorTypeStrings[type];
1742 if (contextVNode) {
1743 pushWarningContext(contextVNode);
1744 }
1745 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1746 if (contextVNode) {
1747 popWarningContext();
1748 }
1749 // crash in dev by default so it's more noticeable
1750 if (throwInDev) {
1751 throw err;
1752 }
1753 else {
1754 console.error(err);
1755 }
1756 }
1757 }
1758
1759 let isFlushing = false;
1760 let isFlushPending = false;
1761 const queue = [];
1762 let flushIndex = 0;
1763 const pendingPreFlushCbs = [];
1764 let activePreFlushCbs = null;
1765 let preFlushIndex = 0;
1766 const pendingPostFlushCbs = [];
1767 let activePostFlushCbs = null;
1768 let postFlushIndex = 0;
1769 const resolvedPromise = Promise.resolve();
1770 let currentFlushPromise = null;
1771 let currentPreFlushParentJob = null;
1772 const RECURSION_LIMIT = 100;
1773 function nextTick(fn) {
1774 const p = currentFlushPromise || resolvedPromise;
1775 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1776 }
1777 // #2768
1778 // Use binary-search to find a suitable position in the queue,
1779 // so that the queue maintains the increasing order of job's id,
1780 // which can prevent the job from being skipped and also can avoid repeated patching.
1781 function findInsertionIndex(id) {
1782 // the start index should be `flushIndex + 1`
1783 let start = flushIndex + 1;
1784 let end = queue.length;
1785 while (start < end) {
1786 const middle = (start + end) >>> 1;
1787 const middleJobId = getId(queue[middle]);
1788 middleJobId < id ? (start = middle + 1) : (end = middle);
1789 }
1790 return start;
1791 }
1792 function queueJob(job) {
1793 // the dedupe search uses the startIndex argument of Array.includes()
1794 // by default the search index includes the current job that is being run
1795 // so it cannot recursively trigger itself again.
1796 // if the job is a watch() callback, the search will start with a +1 index to
1797 // allow it recursively trigger itself - it is the user's responsibility to
1798 // ensure it doesn't end up in an infinite loop.
1799 if ((!queue.length ||
1800 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1801 job !== currentPreFlushParentJob) {
1802 if (job.id == null) {
1803 queue.push(job);
1804 }
1805 else {
1806 queue.splice(findInsertionIndex(job.id), 0, job);
1807 }
1808 queueFlush();
1809 }
1810 }
1811 function queueFlush() {
1812 if (!isFlushing && !isFlushPending) {
1813 isFlushPending = true;
1814 currentFlushPromise = resolvedPromise.then(flushJobs);
1815 }
1816 }
1817 function invalidateJob(job) {
1818 const i = queue.indexOf(job);
1819 if (i > flushIndex) {
1820 queue.splice(i, 1);
1821 }
1822 }
1823 function queueCb(cb, activeQueue, pendingQueue, index) {
1824 if (!isArray(cb)) {
1825 if (!activeQueue ||
1826 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1827 pendingQueue.push(cb);
1828 }
1829 }
1830 else {
1831 // if cb is an array, it is a component lifecycle hook which can only be
1832 // triggered by a job, which is already deduped in the main queue, so
1833 // we can skip duplicate check here to improve perf
1834 pendingQueue.push(...cb);
1835 }
1836 queueFlush();
1837 }
1838 function queuePreFlushCb(cb) {
1839 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1840 }
1841 function queuePostFlushCb(cb) {
1842 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1843 }
1844 function flushPreFlushCbs(seen, parentJob = null) {
1845 if (pendingPreFlushCbs.length) {
1846 currentPreFlushParentJob = parentJob;
1847 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1848 pendingPreFlushCbs.length = 0;
1849 {
1850 seen = seen || new Map();
1851 }
1852 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1853 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
1854 continue;
1855 }
1856 activePreFlushCbs[preFlushIndex]();
1857 }
1858 activePreFlushCbs = null;
1859 preFlushIndex = 0;
1860 currentPreFlushParentJob = null;
1861 // recursively flush until it drains
1862 flushPreFlushCbs(seen, parentJob);
1863 }
1864 }
1865 function flushPostFlushCbs(seen) {
1866 if (pendingPostFlushCbs.length) {
1867 const deduped = [...new Set(pendingPostFlushCbs)];
1868 pendingPostFlushCbs.length = 0;
1869 // #1947 already has active queue, nested flushPostFlushCbs call
1870 if (activePostFlushCbs) {
1871 activePostFlushCbs.push(...deduped);
1872 return;
1873 }
1874 activePostFlushCbs = deduped;
1875 {
1876 seen = seen || new Map();
1877 }
1878 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1879 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1880 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1881 continue;
1882 }
1883 activePostFlushCbs[postFlushIndex]();
1884 }
1885 activePostFlushCbs = null;
1886 postFlushIndex = 0;
1887 }
1888 }
1889 const getId = (job) => job.id == null ? Infinity : job.id;
1890 function flushJobs(seen) {
1891 isFlushPending = false;
1892 isFlushing = true;
1893 {
1894 seen = seen || new Map();
1895 }
1896 flushPreFlushCbs(seen);
1897 // Sort queue before flush.
1898 // This ensures that:
1899 // 1. Components are updated from parent to child. (because parent is always
1900 // created before the child so its render effect will have smaller
1901 // priority number)
1902 // 2. If a component is unmounted during a parent component's update,
1903 // its update can be skipped.
1904 queue.sort((a, b) => getId(a) - getId(b));
1905 // conditional usage of checkRecursiveUpdate must be determined out of
1906 // try ... catch block since Rollup by default de-optimizes treeshaking
1907 // inside try-catch. This can leave all warning code unshaked. Although
1908 // they would get eventually shaken by a minifier like terser, some minifiers
1909 // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
1910 const check = (job) => checkRecursiveUpdates(seen, job)
1911 ;
1912 try {
1913 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1914 const job = queue[flushIndex];
1915 if (job && job.active !== false) {
1916 if (true && check(job)) {
1917 continue;
1918 }
1919 // console.log(`running:`, job.id)
1920 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1921 }
1922 }
1923 }
1924 finally {
1925 flushIndex = 0;
1926 queue.length = 0;
1927 flushPostFlushCbs(seen);
1928 isFlushing = false;
1929 currentFlushPromise = null;
1930 // some postFlushCb queued jobs!
1931 // keep flushing until it drains.
1932 if (queue.length ||
1933 pendingPreFlushCbs.length ||
1934 pendingPostFlushCbs.length) {
1935 flushJobs(seen);
1936 }
1937 }
1938 }
1939 function checkRecursiveUpdates(seen, fn) {
1940 if (!seen.has(fn)) {
1941 seen.set(fn, 1);
1942 }
1943 else {
1944 const count = seen.get(fn);
1945 if (count > RECURSION_LIMIT) {
1946 const instance = fn.ownerInstance;
1947 const componentName = instance && getComponentName(instance.type);
1948 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1949 `This means you have a reactive effect that is mutating its own ` +
1950 `dependencies and thus recursively triggering itself. Possible sources ` +
1951 `include component template, render function, updated hook or ` +
1952 `watcher source function.`);
1953 return true;
1954 }
1955 else {
1956 seen.set(fn, count + 1);
1957 }
1958 }
1959 }
1960
1961 /* eslint-disable no-restricted-globals */
1962 let isHmrUpdating = false;
1963 const hmrDirtyComponents = new Set();
1964 // Expose the HMR runtime on the global object
1965 // This makes it entirely tree-shakable without polluting the exports and makes
1966 // it easier to be used in toolings like vue-loader
1967 // Note: for a component to be eligible for HMR it also needs the __hmrId option
1968 // to be set so that its instances can be registered / removed.
1969 {
1970 getGlobalThis().__VUE_HMR_RUNTIME__ = {
1971 createRecord: tryWrap(createRecord),
1972 rerender: tryWrap(rerender),
1973 reload: tryWrap(reload)
1974 };
1975 }
1976 const map = new Map();
1977 function registerHMR(instance) {
1978 const id = instance.type.__hmrId;
1979 let record = map.get(id);
1980 if (!record) {
1981 createRecord(id, instance.type);
1982 record = map.get(id);
1983 }
1984 record.instances.add(instance);
1985 }
1986 function unregisterHMR(instance) {
1987 map.get(instance.type.__hmrId).instances.delete(instance);
1988 }
1989 function createRecord(id, initialDef) {
1990 if (map.has(id)) {
1991 return false;
1992 }
1993 map.set(id, {
1994 initialDef: normalizeClassComponent(initialDef),
1995 instances: new Set()
1996 });
1997 return true;
1998 }
1999 function normalizeClassComponent(component) {
2000 return isClassComponent(component) ? component.__vccOpts : component;
2001 }
2002 function rerender(id, newRender) {
2003 const record = map.get(id);
2004 if (!record) {
2005 return;
2006 }
2007 // update initial record (for not-yet-rendered component)
2008 record.initialDef.render = newRender;
2009 [...record.instances].forEach(instance => {
2010 if (newRender) {
2011 instance.render = newRender;
2012 normalizeClassComponent(instance.type).render = newRender;
2013 }
2014 instance.renderCache = [];
2015 // this flag forces child components with slot content to update
2016 isHmrUpdating = true;
2017 instance.update();
2018 isHmrUpdating = false;
2019 });
2020 }
2021 function reload(id, newComp) {
2022 const record = map.get(id);
2023 if (!record)
2024 return;
2025 newComp = normalizeClassComponent(newComp);
2026 // update initial def (for not-yet-rendered components)
2027 updateComponentDef(record.initialDef, newComp);
2028 // create a snapshot which avoids the set being mutated during updates
2029 const instances = [...record.instances];
2030 for (const instance of instances) {
2031 const oldComp = normalizeClassComponent(instance.type);
2032 if (!hmrDirtyComponents.has(oldComp)) {
2033 // 1. Update existing comp definition to match new one
2034 if (oldComp !== record.initialDef) {
2035 updateComponentDef(oldComp, newComp);
2036 }
2037 // 2. mark definition dirty. This forces the renderer to replace the
2038 // component on patch.
2039 hmrDirtyComponents.add(oldComp);
2040 }
2041 // 3. invalidate options resolution cache
2042 instance.appContext.optionsCache.delete(instance.type);
2043 // 4. actually update
2044 if (instance.ceReload) {
2045 // custom element
2046 hmrDirtyComponents.add(oldComp);
2047 instance.ceReload(newComp.styles);
2048 hmrDirtyComponents.delete(oldComp);
2049 }
2050 else if (instance.parent) {
2051 // 4. Force the parent instance to re-render. This will cause all updated
2052 // components to be unmounted and re-mounted. Queue the update so that we
2053 // don't end up forcing the same parent to re-render multiple times.
2054 queueJob(instance.parent.update);
2055 // instance is the inner component of an async custom element
2056 // invoke to reset styles
2057 if (instance.parent.type.__asyncLoader &&
2058 instance.parent.ceReload) {
2059 instance.parent.ceReload(newComp.styles);
2060 }
2061 }
2062 else if (instance.appContext.reload) {
2063 // root instance mounted via createApp() has a reload method
2064 instance.appContext.reload();
2065 }
2066 else if (typeof window !== 'undefined') {
2067 // root instance inside tree created via raw render(). Force reload.
2068 window.location.reload();
2069 }
2070 else {
2071 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
2072 }
2073 }
2074 // 5. make sure to cleanup dirty hmr components after update
2075 queuePostFlushCb(() => {
2076 for (const instance of instances) {
2077 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
2078 }
2079 });
2080 }
2081 function updateComponentDef(oldComp, newComp) {
2082 extend(oldComp, newComp);
2083 for (const key in oldComp) {
2084 if (key !== '__file' && !(key in newComp)) {
2085 delete oldComp[key];
2086 }
2087 }
2088 }
2089 function tryWrap(fn) {
2090 return (id, arg) => {
2091 try {
2092 return fn(id, arg);
2093 }
2094 catch (e) {
2095 console.error(e);
2096 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
2097 `Full reload required.`);
2098 }
2099 };
2100 }
2101
2102 let buffer = [];
2103 let devtoolsNotInstalled = false;
2104 function emit(event, ...args) {
2105 if (exports.devtools) {
2106 exports.devtools.emit(event, ...args);
2107 }
2108 else if (!devtoolsNotInstalled) {
2109 buffer.push({ event, args });
2110 }
2111 }
2112 function setDevtoolsHook(hook, target) {
2113 var _a, _b;
2114 exports.devtools = hook;
2115 if (exports.devtools) {
2116 exports.devtools.enabled = true;
2117 buffer.forEach(({ event, args }) => exports.devtools.emit(event, ...args));
2118 buffer = [];
2119 }
2120 else if (
2121 // handle late devtools injection - only do this if we are in an actual
2122 // browser environment to avoid the timer handle stalling test runner exit
2123 // (#4815)
2124 // eslint-disable-next-line no-restricted-globals
2125 typeof window !== 'undefined' &&
2126 // some envs mock window but not fully
2127 window.HTMLElement &&
2128 // also exclude jsdom
2129 !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
2130 const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
2131 target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
2132 replay.push((newHook) => {
2133 setDevtoolsHook(newHook, target);
2134 });
2135 // clear buffer after 3s - the user probably doesn't have devtools installed
2136 // at all, and keeping the buffer will cause memory leaks (#4738)
2137 setTimeout(() => {
2138 if (!exports.devtools) {
2139 target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
2140 devtoolsNotInstalled = true;
2141 buffer = [];
2142 }
2143 }, 3000);
2144 }
2145 else {
2146 // non-browser env, assume not installed
2147 devtoolsNotInstalled = true;
2148 buffer = [];
2149 }
2150 }
2151 function devtoolsInitApp(app, version) {
2152 emit("app:init" /* APP_INIT */, app, version, {
2153 Fragment,
2154 Text,
2155 Comment,
2156 Static
2157 });
2158 }
2159 function devtoolsUnmountApp(app) {
2160 emit("app:unmount" /* APP_UNMOUNT */, app);
2161 }
2162 const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
2163 const devtoolsComponentUpdated =
2164 /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
2165 const devtoolsComponentRemoved =
2166 /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
2167 function createDevtoolsComponentHook(hook) {
2168 return (component) => {
2169 emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
2170 };
2171 }
2172 const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
2173 const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
2174 function createDevtoolsPerformanceHook(hook) {
2175 return (component, type, time) => {
2176 emit(hook, component.appContext.app, component.uid, component, type, time);
2177 };
2178 }
2179 function devtoolsComponentEmit(component, event, params) {
2180 emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
2181 }
2182
2183 function emit$1(instance, event, ...rawArgs) {
2184 const props = instance.vnode.props || EMPTY_OBJ;
2185 {
2186 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2187 if (emitsOptions) {
2188 if (!(event in emitsOptions) &&
2189 !(false )) {
2190 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2191 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2192 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2193 }
2194 }
2195 else {
2196 const validator = emitsOptions[event];
2197 if (isFunction(validator)) {
2198 const isValid = validator(...rawArgs);
2199 if (!isValid) {
2200 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2201 }
2202 }
2203 }
2204 }
2205 }
2206 let args = rawArgs;
2207 const isModelListener = event.startsWith('update:');
2208 // for v-model update:xxx events, apply modifiers on args
2209 const modelArg = isModelListener && event.slice(7);
2210 if (modelArg && modelArg in props) {
2211 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2212 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2213 if (trim) {
2214 args = rawArgs.map(a => a.trim());
2215 }
2216 else if (number) {
2217 args = rawArgs.map(toNumber);
2218 }
2219 }
2220 {
2221 devtoolsComponentEmit(instance, event, args);
2222 }
2223 {
2224 const lowerCaseEvent = event.toLowerCase();
2225 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2226 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2227 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2228 `Note that HTML attributes are case-insensitive and you cannot use ` +
2229 `v-on to listen to camelCase events when using in-DOM templates. ` +
2230 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2231 }
2232 }
2233 let handlerName;
2234 let handler = props[(handlerName = toHandlerKey(event))] ||
2235 // also try camelCase event handler (#2249)
2236 props[(handlerName = toHandlerKey(camelize(event)))];
2237 // for v-model update:xxx events, also trigger kebab-case equivalent
2238 // for props passed via kebab-case
2239 if (!handler && isModelListener) {
2240 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2241 }
2242 if (handler) {
2243 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2244 }
2245 const onceHandler = props[handlerName + `Once`];
2246 if (onceHandler) {
2247 if (!instance.emitted) {
2248 instance.emitted = {};
2249 }
2250 else if (instance.emitted[handlerName]) {
2251 return;
2252 }
2253 instance.emitted[handlerName] = true;
2254 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2255 }
2256 }
2257 function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2258 const cache = appContext.emitsCache;
2259 const cached = cache.get(comp);
2260 if (cached !== undefined) {
2261 return cached;
2262 }
2263 const raw = comp.emits;
2264 let normalized = {};
2265 // apply mixin/extends props
2266 let hasExtends = false;
2267 if (!isFunction(comp)) {
2268 const extendEmits = (raw) => {
2269 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2270 if (normalizedFromExtend) {
2271 hasExtends = true;
2272 extend(normalized, normalizedFromExtend);
2273 }
2274 };
2275 if (!asMixin && appContext.mixins.length) {
2276 appContext.mixins.forEach(extendEmits);
2277 }
2278 if (comp.extends) {
2279 extendEmits(comp.extends);
2280 }
2281 if (comp.mixins) {
2282 comp.mixins.forEach(extendEmits);
2283 }
2284 }
2285 if (!raw && !hasExtends) {
2286 cache.set(comp, null);
2287 return null;
2288 }
2289 if (isArray(raw)) {
2290 raw.forEach(key => (normalized[key] = null));
2291 }
2292 else {
2293 extend(normalized, raw);
2294 }
2295 cache.set(comp, normalized);
2296 return normalized;
2297 }
2298 // Check if an incoming prop key is a declared emit event listener.
2299 // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2300 // both considered matched listeners.
2301 function isEmitListener(options, key) {
2302 if (!options || !isOn(key)) {
2303 return false;
2304 }
2305 key = key.slice(2).replace(/Once$/, '');
2306 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2307 hasOwn(options, hyphenate(key)) ||
2308 hasOwn(options, key));
2309 }
2310
2311 /**
2312 * mark the current rendering instance for asset resolution (e.g.
2313 * resolveComponent, resolveDirective) during render
2314 */
2315 let currentRenderingInstance = null;
2316 let currentScopeId = null;
2317 /**
2318 * Note: rendering calls maybe nested. The function returns the parent rendering
2319 * instance if present, which should be restored after the render is done:
2320 *
2321 * ```js
2322 * const prev = setCurrentRenderingInstance(i)
2323 * // ...render
2324 * setCurrentRenderingInstance(prev)
2325 * ```
2326 */
2327 function setCurrentRenderingInstance(instance) {
2328 const prev = currentRenderingInstance;
2329 currentRenderingInstance = instance;
2330 currentScopeId = (instance && instance.type.__scopeId) || null;
2331 return prev;
2332 }
2333 /**
2334 * Set scope id when creating hoisted vnodes.
2335 * @private compiler helper
2336 */
2337 function pushScopeId(id) {
2338 currentScopeId = id;
2339 }
2340 /**
2341 * Technically we no longer need this after 3.0.8 but we need to keep the same
2342 * API for backwards compat w/ code generated by compilers.
2343 * @private
2344 */
2345 function popScopeId() {
2346 currentScopeId = null;
2347 }
2348 /**
2349 * Only for backwards compat
2350 * @private
2351 */
2352 const withScopeId = (_id) => withCtx;
2353 /**
2354 * Wrap a slot function to memoize current rendering instance
2355 * @private compiler helper
2356 */
2357 function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2358 ) {
2359 if (!ctx)
2360 return fn;
2361 // already normalized
2362 if (fn._n) {
2363 return fn;
2364 }
2365 const renderFnWithContext = (...args) => {
2366 // If a user calls a compiled slot inside a template expression (#1745), it
2367 // can mess up block tracking, so by default we disable block tracking and
2368 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2369 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2370 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2371 if (renderFnWithContext._d) {
2372 setBlockTracking(-1);
2373 }
2374 const prevInstance = setCurrentRenderingInstance(ctx);
2375 const res = fn(...args);
2376 setCurrentRenderingInstance(prevInstance);
2377 if (renderFnWithContext._d) {
2378 setBlockTracking(1);
2379 }
2380 {
2381 devtoolsComponentUpdated(ctx);
2382 }
2383 return res;
2384 };
2385 // mark normalized to avoid duplicated wrapping
2386 renderFnWithContext._n = true;
2387 // mark this as compiled by default
2388 // this is used in vnode.ts -> normalizeChildren() to set the slot
2389 // rendering flag.
2390 renderFnWithContext._c = true;
2391 // disable block tracking by default
2392 renderFnWithContext._d = true;
2393 return renderFnWithContext;
2394 }
2395
2396 /**
2397 * dev only flag to track whether $attrs was used during render.
2398 * If $attrs was used during render then the warning for failed attrs
2399 * fallthrough can be suppressed.
2400 */
2401 let accessedAttrs = false;
2402 function markAttrsAccessed() {
2403 accessedAttrs = true;
2404 }
2405 function renderComponentRoot(instance) {
2406 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2407 let result;
2408 let fallthroughAttrs;
2409 const prev = setCurrentRenderingInstance(instance);
2410 {
2411 accessedAttrs = false;
2412 }
2413 try {
2414 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2415 // withProxy is a proxy with a different `has` trap only for
2416 // runtime-compiled render functions using `with` block.
2417 const proxyToUse = withProxy || proxy;
2418 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2419 fallthroughAttrs = attrs;
2420 }
2421 else {
2422 // functional
2423 const render = Component;
2424 // in dev, mark attrs accessed if optional props (attrs === props)
2425 if (true && attrs === props) {
2426 markAttrsAccessed();
2427 }
2428 result = normalizeVNode(render.length > 1
2429 ? render(props, true
2430 ? {
2431 get attrs() {
2432 markAttrsAccessed();
2433 return attrs;
2434 },
2435 slots,
2436 emit
2437 }
2438 : { attrs, slots, emit })
2439 : render(props, null /* we know it doesn't need it */));
2440 fallthroughAttrs = Component.props
2441 ? attrs
2442 : getFunctionalFallthrough(attrs);
2443 }
2444 }
2445 catch (err) {
2446 blockStack.length = 0;
2447 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2448 result = createVNode(Comment);
2449 }
2450 // attr merging
2451 // in dev mode, comments are preserved, and it's possible for a template
2452 // to have comments along side the root element which makes it a fragment
2453 let root = result;
2454 let setRoot = undefined;
2455 if (result.patchFlag > 0 &&
2456 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2457 [root, setRoot] = getChildRoot(result);
2458 }
2459 if (fallthroughAttrs && inheritAttrs !== false) {
2460 const keys = Object.keys(fallthroughAttrs);
2461 const { shapeFlag } = root;
2462 if (keys.length) {
2463 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2464 if (propsOptions && keys.some(isModelListener)) {
2465 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2466 // prop, it indicates this component expects to handle v-model and
2467 // it should not fallthrough.
2468 // related: #1543, #1643, #1989
2469 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2470 }
2471 root = cloneVNode(root, fallthroughAttrs);
2472 }
2473 else if (!accessedAttrs && root.type !== Comment) {
2474 const allAttrs = Object.keys(attrs);
2475 const eventAttrs = [];
2476 const extraAttrs = [];
2477 for (let i = 0, l = allAttrs.length; i < l; i++) {
2478 const key = allAttrs[i];
2479 if (isOn(key)) {
2480 // ignore v-model handlers when they fail to fallthrough
2481 if (!isModelListener(key)) {
2482 // remove `on`, lowercase first letter to reflect event casing
2483 // accurately
2484 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2485 }
2486 }
2487 else {
2488 extraAttrs.push(key);
2489 }
2490 }
2491 if (extraAttrs.length) {
2492 warn$1(`Extraneous non-props attributes (` +
2493 `${extraAttrs.join(', ')}) ` +
2494 `were passed to component but could not be automatically inherited ` +
2495 `because component renders fragment or text root nodes.`);
2496 }
2497 if (eventAttrs.length) {
2498 warn$1(`Extraneous non-emits event listeners (` +
2499 `${eventAttrs.join(', ')}) ` +
2500 `were passed to component but could not be automatically inherited ` +
2501 `because component renders fragment or text root nodes. ` +
2502 `If the listener is intended to be a component custom event listener only, ` +
2503 `declare it using the "emits" option.`);
2504 }
2505 }
2506 }
2507 }
2508 // inherit directives
2509 if (vnode.dirs) {
2510 if (!isElementRoot(root)) {
2511 warn$1(`Runtime directive used on component with non-element root node. ` +
2512 `The directives will not function as intended.`);
2513 }
2514 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2515 }
2516 // inherit transition data
2517 if (vnode.transition) {
2518 if (!isElementRoot(root)) {
2519 warn$1(`Component inside <Transition> renders non-element root node ` +
2520 `that cannot be animated.`);
2521 }
2522 root.transition = vnode.transition;
2523 }
2524 if (setRoot) {
2525 setRoot(root);
2526 }
2527 else {
2528 result = root;
2529 }
2530 setCurrentRenderingInstance(prev);
2531 return result;
2532 }
2533 /**
2534 * dev only
2535 * In dev mode, template root level comments are rendered, which turns the
2536 * template into a fragment root, but we need to locate the single element
2537 * root for attrs and scope id processing.
2538 */
2539 const getChildRoot = (vnode) => {
2540 const rawChildren = vnode.children;
2541 const dynamicChildren = vnode.dynamicChildren;
2542 const childRoot = filterSingleRoot(rawChildren);
2543 if (!childRoot) {
2544 return [vnode, undefined];
2545 }
2546 const index = rawChildren.indexOf(childRoot);
2547 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2548 const setRoot = (updatedRoot) => {
2549 rawChildren[index] = updatedRoot;
2550 if (dynamicChildren) {
2551 if (dynamicIndex > -1) {
2552 dynamicChildren[dynamicIndex] = updatedRoot;
2553 }
2554 else if (updatedRoot.patchFlag > 0) {
2555 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2556 }
2557 }
2558 };
2559 return [normalizeVNode(childRoot), setRoot];
2560 };
2561 function filterSingleRoot(children) {
2562 let singleRoot;
2563 for (let i = 0; i < children.length; i++) {
2564 const child = children[i];
2565 if (isVNode(child)) {
2566 // ignore user comment
2567 if (child.type !== Comment || child.children === 'v-if') {
2568 if (singleRoot) {
2569 // has more than 1 non-comment child, return now
2570 return;
2571 }
2572 else {
2573 singleRoot = child;
2574 }
2575 }
2576 }
2577 else {
2578 return;
2579 }
2580 }
2581 return singleRoot;
2582 }
2583 const getFunctionalFallthrough = (attrs) => {
2584 let res;
2585 for (const key in attrs) {
2586 if (key === 'class' || key === 'style' || isOn(key)) {
2587 (res || (res = {}))[key] = attrs[key];
2588 }
2589 }
2590 return res;
2591 };
2592 const filterModelListeners = (attrs, props) => {
2593 const res = {};
2594 for (const key in attrs) {
2595 if (!isModelListener(key) || !(key.slice(9) in props)) {
2596 res[key] = attrs[key];
2597 }
2598 }
2599 return res;
2600 };
2601 const isElementRoot = (vnode) => {
2602 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2603 vnode.type === Comment // potential v-if branch switch
2604 );
2605 };
2606 function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2607 const { props: prevProps, children: prevChildren, component } = prevVNode;
2608 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2609 const emits = component.emitsOptions;
2610 // Parent component's render function was hot-updated. Since this may have
2611 // caused the child component's slots content to have changed, we need to
2612 // force the child to update as well.
2613 if ((prevChildren || nextChildren) && isHmrUpdating) {
2614 return true;
2615 }
2616 // force child update for runtime directive or transition on component vnode.
2617 if (nextVNode.dirs || nextVNode.transition) {
2618 return true;
2619 }
2620 if (optimized && patchFlag >= 0) {
2621 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2622 // slot content that references values that might have changed,
2623 // e.g. in a v-for
2624 return true;
2625 }
2626 if (patchFlag & 16 /* FULL_PROPS */) {
2627 if (!prevProps) {
2628 return !!nextProps;
2629 }
2630 // presence of this flag indicates props are always non-null
2631 return hasPropsChanged(prevProps, nextProps, emits);
2632 }
2633 else if (patchFlag & 8 /* PROPS */) {
2634 const dynamicProps = nextVNode.dynamicProps;
2635 for (let i = 0; i < dynamicProps.length; i++) {
2636 const key = dynamicProps[i];
2637 if (nextProps[key] !== prevProps[key] &&
2638 !isEmitListener(emits, key)) {
2639 return true;
2640 }
2641 }
2642 }
2643 }
2644 else {
2645 // this path is only taken by manually written render functions
2646 // so presence of any children leads to a forced update
2647 if (prevChildren || nextChildren) {
2648 if (!nextChildren || !nextChildren.$stable) {
2649 return true;
2650 }
2651 }
2652 if (prevProps === nextProps) {
2653 return false;
2654 }
2655 if (!prevProps) {
2656 return !!nextProps;
2657 }
2658 if (!nextProps) {
2659 return true;
2660 }
2661 return hasPropsChanged(prevProps, nextProps, emits);
2662 }
2663 return false;
2664 }
2665 function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2666 const nextKeys = Object.keys(nextProps);
2667 if (nextKeys.length !== Object.keys(prevProps).length) {
2668 return true;
2669 }
2670 for (let i = 0; i < nextKeys.length; i++) {
2671 const key = nextKeys[i];
2672 if (nextProps[key] !== prevProps[key] &&
2673 !isEmitListener(emitsOptions, key)) {
2674 return true;
2675 }
2676 }
2677 return false;
2678 }
2679 function updateHOCHostEl({ vnode, parent }, el // HostNode
2680 ) {
2681 while (parent && parent.subTree === vnode) {
2682 (vnode = parent.vnode).el = el;
2683 parent = parent.parent;
2684 }
2685 }
2686
2687 const isSuspense = (type) => type.__isSuspense;
2688 // Suspense exposes a component-like API, and is treated like a component
2689 // in the compiler, but internally it's a special built-in type that hooks
2690 // directly into the renderer.
2691 const SuspenseImpl = {
2692 name: 'Suspense',
2693 // In order to make Suspense tree-shakable, we need to avoid importing it
2694 // directly in the renderer. The renderer checks for the __isSuspense flag
2695 // on a vnode's type and calls the `process` method, passing in renderer
2696 // internals.
2697 __isSuspense: true,
2698 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2699 // platform-specific impl passed from renderer
2700 rendererInternals) {
2701 if (n1 == null) {
2702 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2703 }
2704 else {
2705 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2706 }
2707 },
2708 hydrate: hydrateSuspense,
2709 create: createSuspenseBoundary,
2710 normalize: normalizeSuspenseChildren
2711 };
2712 // Force-casted public typing for h and TSX props inference
2713 const Suspense = (SuspenseImpl );
2714 function triggerEvent(vnode, name) {
2715 const eventListener = vnode.props && vnode.props[name];
2716 if (isFunction(eventListener)) {
2717 eventListener();
2718 }
2719 }
2720 function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2721 const { p: patch, o: { createElement } } = rendererInternals;
2722 const hiddenContainer = createElement('div');
2723 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2724 // start mounting the content subtree in an off-dom container
2725 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2726 // now check if we have encountered any async deps
2727 if (suspense.deps > 0) {
2728 // has async
2729 // invoke @fallback event
2730 triggerEvent(vnode, 'onPending');
2731 triggerEvent(vnode, 'onFallback');
2732 // mount the fallback tree
2733 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2734 isSVG, slotScopeIds);
2735 setActiveBranch(suspense, vnode.ssFallback);
2736 }
2737 else {
2738 // Suspense has no async deps. Just resolve.
2739 suspense.resolve();
2740 }
2741 }
2742 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2743 const suspense = (n2.suspense = n1.suspense);
2744 suspense.vnode = n2;
2745 n2.el = n1.el;
2746 const newBranch = n2.ssContent;
2747 const newFallback = n2.ssFallback;
2748 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2749 if (pendingBranch) {
2750 suspense.pendingBranch = newBranch;
2751 if (isSameVNodeType(newBranch, pendingBranch)) {
2752 // same root type but content may have changed.
2753 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2754 if (suspense.deps <= 0) {
2755 suspense.resolve();
2756 }
2757 else if (isInFallback) {
2758 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2759 isSVG, slotScopeIds, optimized);
2760 setActiveBranch(suspense, newFallback);
2761 }
2762 }
2763 else {
2764 // toggled before pending tree is resolved
2765 suspense.pendingId++;
2766 if (isHydrating) {
2767 // if toggled before hydration is finished, the current DOM tree is
2768 // no longer valid. set it as the active branch so it will be unmounted
2769 // when resolved
2770 suspense.isHydrating = false;
2771 suspense.activeBranch = pendingBranch;
2772 }
2773 else {
2774 unmount(pendingBranch, parentComponent, suspense);
2775 }
2776 // increment pending ID. this is used to invalidate async callbacks
2777 // reset suspense state
2778 suspense.deps = 0;
2779 // discard effects from pending branch
2780 suspense.effects.length = 0;
2781 // discard previous container
2782 suspense.hiddenContainer = createElement('div');
2783 if (isInFallback) {
2784 // already in fallback state
2785 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2786 if (suspense.deps <= 0) {
2787 suspense.resolve();
2788 }
2789 else {
2790 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2791 isSVG, slotScopeIds, optimized);
2792 setActiveBranch(suspense, newFallback);
2793 }
2794 }
2795 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2796 // toggled "back" to current active branch
2797 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2798 // force resolve
2799 suspense.resolve(true);
2800 }
2801 else {
2802 // switched to a 3rd branch
2803 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2804 if (suspense.deps <= 0) {
2805 suspense.resolve();
2806 }
2807 }
2808 }
2809 }
2810 else {
2811 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2812 // root did not change, just normal patch
2813 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2814 setActiveBranch(suspense, newBranch);
2815 }
2816 else {
2817 // root node toggled
2818 // invoke @pending event
2819 triggerEvent(n2, 'onPending');
2820 // mount pending branch in off-dom container
2821 suspense.pendingBranch = newBranch;
2822 suspense.pendingId++;
2823 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2824 if (suspense.deps <= 0) {
2825 // incoming branch has no async deps, resolve now.
2826 suspense.resolve();
2827 }
2828 else {
2829 const { timeout, pendingId } = suspense;
2830 if (timeout > 0) {
2831 setTimeout(() => {
2832 if (suspense.pendingId === pendingId) {
2833 suspense.fallback(newFallback);
2834 }
2835 }, timeout);
2836 }
2837 else if (timeout === 0) {
2838 suspense.fallback(newFallback);
2839 }
2840 }
2841 }
2842 }
2843 }
2844 let hasWarned = false;
2845 function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2846 /* istanbul ignore if */
2847 if (!hasWarned) {
2848 hasWarned = true;
2849 // @ts-ignore `console.info` cannot be null error
2850 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2851 }
2852 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2853 const timeout = toNumber(vnode.props && vnode.props.timeout);
2854 const suspense = {
2855 vnode,
2856 parent,
2857 parentComponent,
2858 isSVG,
2859 container,
2860 hiddenContainer,
2861 anchor,
2862 deps: 0,
2863 pendingId: 0,
2864 timeout: typeof timeout === 'number' ? timeout : -1,
2865 activeBranch: null,
2866 pendingBranch: null,
2867 isInFallback: true,
2868 isHydrating,
2869 isUnmounted: false,
2870 effects: [],
2871 resolve(resume = false) {
2872 {
2873 if (!resume && !suspense.pendingBranch) {
2874 throw new Error(`suspense.resolve() is called without a pending branch.`);
2875 }
2876 if (suspense.isUnmounted) {
2877 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2878 }
2879 }
2880 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2881 if (suspense.isHydrating) {
2882 suspense.isHydrating = false;
2883 }
2884 else if (!resume) {
2885 const delayEnter = activeBranch &&
2886 pendingBranch.transition &&
2887 pendingBranch.transition.mode === 'out-in';
2888 if (delayEnter) {
2889 activeBranch.transition.afterLeave = () => {
2890 if (pendingId === suspense.pendingId) {
2891 move(pendingBranch, container, anchor, 0 /* ENTER */);
2892 }
2893 };
2894 }
2895 // this is initial anchor on mount
2896 let { anchor } = suspense;
2897 // unmount current active tree
2898 if (activeBranch) {
2899 // if the fallback tree was mounted, it may have been moved
2900 // as part of a parent suspense. get the latest anchor for insertion
2901 anchor = next(activeBranch);
2902 unmount(activeBranch, parentComponent, suspense, true);
2903 }
2904 if (!delayEnter) {
2905 // move content from off-dom container to actual container
2906 move(pendingBranch, container, anchor, 0 /* ENTER */);
2907 }
2908 }
2909 setActiveBranch(suspense, pendingBranch);
2910 suspense.pendingBranch = null;
2911 suspense.isInFallback = false;
2912 // flush buffered effects
2913 // check if there is a pending parent suspense
2914 let parent = suspense.parent;
2915 let hasUnresolvedAncestor = false;
2916 while (parent) {
2917 if (parent.pendingBranch) {
2918 // found a pending parent suspense, merge buffered post jobs
2919 // into that parent
2920 parent.effects.push(...effects);
2921 hasUnresolvedAncestor = true;
2922 break;
2923 }
2924 parent = parent.parent;
2925 }
2926 // no pending parent suspense, flush all jobs
2927 if (!hasUnresolvedAncestor) {
2928 queuePostFlushCb(effects);
2929 }
2930 suspense.effects = [];
2931 // invoke @resolve event
2932 triggerEvent(vnode, 'onResolve');
2933 },
2934 fallback(fallbackVNode) {
2935 if (!suspense.pendingBranch) {
2936 return;
2937 }
2938 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2939 // invoke @fallback event
2940 triggerEvent(vnode, 'onFallback');
2941 const anchor = next(activeBranch);
2942 const mountFallback = () => {
2943 if (!suspense.isInFallback) {
2944 return;
2945 }
2946 // mount the fallback tree
2947 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2948 isSVG, slotScopeIds, optimized);
2949 setActiveBranch(suspense, fallbackVNode);
2950 };
2951 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2952 if (delayEnter) {
2953 activeBranch.transition.afterLeave = mountFallback;
2954 }
2955 suspense.isInFallback = true;
2956 // unmount current active branch
2957 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2958 true // shouldRemove
2959 );
2960 if (!delayEnter) {
2961 mountFallback();
2962 }
2963 },
2964 move(container, anchor, type) {
2965 suspense.activeBranch &&
2966 move(suspense.activeBranch, container, anchor, type);
2967 suspense.container = container;
2968 },
2969 next() {
2970 return suspense.activeBranch && next(suspense.activeBranch);
2971 },
2972 registerDep(instance, setupRenderEffect) {
2973 const isInPendingSuspense = !!suspense.pendingBranch;
2974 if (isInPendingSuspense) {
2975 suspense.deps++;
2976 }
2977 const hydratedEl = instance.vnode.el;
2978 instance
2979 .asyncDep.catch(err => {
2980 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2981 })
2982 .then(asyncSetupResult => {
2983 // retry when the setup() promise resolves.
2984 // component may have been unmounted before resolve.
2985 if (instance.isUnmounted ||
2986 suspense.isUnmounted ||
2987 suspense.pendingId !== instance.suspenseId) {
2988 return;
2989 }
2990 // retry from this component
2991 instance.asyncResolved = true;
2992 const { vnode } = instance;
2993 {
2994 pushWarningContext(vnode);
2995 }
2996 handleSetupResult(instance, asyncSetupResult, false);
2997 if (hydratedEl) {
2998 // vnode may have been replaced if an update happened before the
2999 // async dep is resolved.
3000 vnode.el = hydratedEl;
3001 }
3002 const placeholder = !hydratedEl && instance.subTree.el;
3003 setupRenderEffect(instance, vnode,
3004 // component may have been moved before resolve.
3005 // if this is not a hydration, instance.subTree will be the comment
3006 // placeholder.
3007 parentNode(hydratedEl || instance.subTree.el),
3008 // anchor will not be used if this is hydration, so only need to
3009 // consider the comment placeholder case.
3010 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3011 if (placeholder) {
3012 remove(placeholder);
3013 }
3014 updateHOCHostEl(instance, vnode.el);
3015 {
3016 popWarningContext();
3017 }
3018 // only decrease deps count if suspense is not already resolved
3019 if (isInPendingSuspense && --suspense.deps === 0) {
3020 suspense.resolve();
3021 }
3022 });
3023 },
3024 unmount(parentSuspense, doRemove) {
3025 suspense.isUnmounted = true;
3026 if (suspense.activeBranch) {
3027 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3028 }
3029 if (suspense.pendingBranch) {
3030 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3031 }
3032 }
3033 };
3034 return suspense;
3035 }
3036 function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3037 /* eslint-disable no-restricted-globals */
3038 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3039 // there are two possible scenarios for server-rendered suspense:
3040 // - success: ssr content should be fully resolved
3041 // - failure: ssr content should be the fallback branch.
3042 // however, on the client we don't really know if it has failed or not
3043 // attempt to hydrate the DOM assuming it has succeeded, but we still
3044 // need to construct a suspense boundary first
3045 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3046 if (suspense.deps === 0) {
3047 suspense.resolve();
3048 }
3049 return result;
3050 /* eslint-enable no-restricted-globals */
3051 }
3052 function normalizeSuspenseChildren(vnode) {
3053 const { shapeFlag, children } = vnode;
3054 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
3055 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3056 vnode.ssFallback = isSlotChildren
3057 ? normalizeSuspenseSlot(children.fallback)
3058 : createVNode(Comment);
3059 }
3060 function normalizeSuspenseSlot(s) {
3061 let block;
3062 if (isFunction(s)) {
3063 const trackBlock = isBlockTreeEnabled && s._c;
3064 if (trackBlock) {
3065 // disableTracking: false
3066 // allow block tracking for compiled slots
3067 // (see ./componentRenderContext.ts)
3068 s._d = false;
3069 openBlock();
3070 }
3071 s = s();
3072 if (trackBlock) {
3073 s._d = true;
3074 block = currentBlock;
3075 closeBlock();
3076 }
3077 }
3078 if (isArray(s)) {
3079 const singleChild = filterSingleRoot(s);
3080 if (!singleChild) {
3081 warn$1(`<Suspense> slots expect a single root node.`);
3082 }
3083 s = singleChild;
3084 }
3085 s = normalizeVNode(s);
3086 if (block && !s.dynamicChildren) {
3087 s.dynamicChildren = block.filter(c => c !== s);
3088 }
3089 return s;
3090 }
3091 function queueEffectWithSuspense(fn, suspense) {
3092 if (suspense && suspense.pendingBranch) {
3093 if (isArray(fn)) {
3094 suspense.effects.push(...fn);
3095 }
3096 else {
3097 suspense.effects.push(fn);
3098 }
3099 }
3100 else {
3101 queuePostFlushCb(fn);
3102 }
3103 }
3104 function setActiveBranch(suspense, branch) {
3105 suspense.activeBranch = branch;
3106 const { vnode, parentComponent } = suspense;
3107 const el = (vnode.el = branch.el);
3108 // in case suspense is the root node of a component,
3109 // recursively update the HOC el
3110 if (parentComponent && parentComponent.subTree === vnode) {
3111 parentComponent.vnode.el = el;
3112 updateHOCHostEl(parentComponent, el);
3113 }
3114 }
3115
3116 function provide(key, value) {
3117 if (!currentInstance) {
3118 {
3119 warn$1(`provide() can only be used inside setup().`);
3120 }
3121 }
3122 else {
3123 let provides = currentInstance.provides;
3124 // by default an instance inherits its parent's provides object
3125 // but when it needs to provide values of its own, it creates its
3126 // own provides object using parent provides object as prototype.
3127 // this way in `inject` we can simply look up injections from direct
3128 // parent and let the prototype chain do the work.
3129 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3130 if (parentProvides === provides) {
3131 provides = currentInstance.provides = Object.create(parentProvides);
3132 }
3133 // TS doesn't allow symbol as index type
3134 provides[key] = value;
3135 }
3136 }
3137 function inject(key, defaultValue, treatDefaultAsFactory = false) {
3138 // fallback to `currentRenderingInstance` so that this can be called in
3139 // a functional component
3140 const instance = currentInstance || currentRenderingInstance;
3141 if (instance) {
3142 // #2400
3143 // to support `app.use` plugins,
3144 // fallback to appContext's `provides` if the instance is at root
3145 const provides = instance.parent == null
3146 ? instance.vnode.appContext && instance.vnode.appContext.provides
3147 : instance.parent.provides;
3148 if (provides && key in provides) {
3149 // TS doesn't allow symbol as index type
3150 return provides[key];
3151 }
3152 else if (arguments.length > 1) {
3153 return treatDefaultAsFactory && isFunction(defaultValue)
3154 ? defaultValue.call(instance.proxy)
3155 : defaultValue;
3156 }
3157 else {
3158 warn$1(`injection "${String(key)}" not found.`);
3159 }
3160 }
3161 else {
3162 warn$1(`inject() can only be used inside setup() or functional components.`);
3163 }
3164 }
3165
3166 // Simple effect.
3167 function watchEffect(effect, options) {
3168 return doWatch(effect, null, options);
3169 }
3170 function watchPostEffect(effect, options) {
3171 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
3172 ));
3173 }
3174 function watchSyncEffect(effect, options) {
3175 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
3176 ));
3177 }
3178 // initial value for watchers to trigger on undefined initial values
3179 const INITIAL_WATCHER_VALUE = {};
3180 // implementation
3181 function watch(source, cb, options) {
3182 if (!isFunction(cb)) {
3183 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3184 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3185 `supports \`watch(source, cb, options?) signature.`);
3186 }
3187 return doWatch(source, cb, options);
3188 }
3189 function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
3190 if (!cb) {
3191 if (immediate !== undefined) {
3192 warn$1(`watch() "immediate" option is only respected when using the ` +
3193 `watch(source, callback, options?) signature.`);
3194 }
3195 if (deep !== undefined) {
3196 warn$1(`watch() "deep" option is only respected when using the ` +
3197 `watch(source, callback, options?) signature.`);
3198 }
3199 }
3200 const warnInvalidSource = (s) => {
3201 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3202 `a reactive object, or an array of these types.`);
3203 };
3204 const instance = currentInstance;
3205 let getter;
3206 let forceTrigger = false;
3207 let isMultiSource = false;
3208 if (isRef(source)) {
3209 getter = () => source.value;
3210 forceTrigger = isShallow(source);
3211 }
3212 else if (isReactive(source)) {
3213 getter = () => source;
3214 deep = true;
3215 }
3216 else if (isArray(source)) {
3217 isMultiSource = true;
3218 forceTrigger = source.some(isReactive);
3219 getter = () => source.map(s => {
3220 if (isRef(s)) {
3221 return s.value;
3222 }
3223 else if (isReactive(s)) {
3224 return traverse(s);
3225 }
3226 else if (isFunction(s)) {
3227 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
3228 }
3229 else {
3230 warnInvalidSource(s);
3231 }
3232 });
3233 }
3234 else if (isFunction(source)) {
3235 if (cb) {
3236 // getter with cb
3237 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
3238 }
3239 else {
3240 // no cb -> simple effect
3241 getter = () => {
3242 if (instance && instance.isUnmounted) {
3243 return;
3244 }
3245 if (cleanup) {
3246 cleanup();
3247 }
3248 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]);
3249 };
3250 }
3251 }
3252 else {
3253 getter = NOOP;
3254 warnInvalidSource(source);
3255 }
3256 if (cb && deep) {
3257 const baseGetter = getter;
3258 getter = () => traverse(baseGetter());
3259 }
3260 let cleanup;
3261 let onCleanup = (fn) => {
3262 cleanup = effect.onStop = () => {
3263 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3264 };
3265 };
3266 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
3267 const job = () => {
3268 if (!effect.active) {
3269 return;
3270 }
3271 if (cb) {
3272 // watch(source, cb)
3273 const newValue = effect.run();
3274 if (deep ||
3275 forceTrigger ||
3276 (isMultiSource
3277 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3278 : hasChanged(newValue, oldValue)) ||
3279 (false )) {
3280 // cleanup before running cb again
3281 if (cleanup) {
3282 cleanup();
3283 }
3284 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3285 newValue,
3286 // pass undefined as the old value when it's changed for the first time
3287 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3288 onCleanup
3289 ]);
3290 oldValue = newValue;
3291 }
3292 }
3293 else {
3294 // watchEffect
3295 effect.run();
3296 }
3297 };
3298 // important: mark the job as a watcher callback so that scheduler knows
3299 // it is allowed to self-trigger (#1727)
3300 job.allowRecurse = !!cb;
3301 let scheduler;
3302 if (flush === 'sync') {
3303 scheduler = job; // the scheduler function gets called directly
3304 }
3305 else if (flush === 'post') {
3306 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3307 }
3308 else {
3309 // default: 'pre'
3310 scheduler = () => {
3311 if (!instance || instance.isMounted) {
3312 queuePreFlushCb(job);
3313 }
3314 else {
3315 // with 'pre' option, the first call must happen before
3316 // the component is mounted so it is called synchronously.
3317 job();
3318 }
3319 };
3320 }
3321 const effect = new ReactiveEffect(getter, scheduler);
3322 {
3323 effect.onTrack = onTrack;
3324 effect.onTrigger = onTrigger;
3325 }
3326 // initial run
3327 if (cb) {
3328 if (immediate) {
3329 job();
3330 }
3331 else {
3332 oldValue = effect.run();
3333 }
3334 }
3335 else if (flush === 'post') {
3336 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
3337 }
3338 else {
3339 effect.run();
3340 }
3341 return () => {
3342 effect.stop();
3343 if (instance && instance.scope) {
3344 remove(instance.scope.effects, effect);
3345 }
3346 };
3347 }
3348 // this.$watch
3349 function instanceWatch(source, value, options) {
3350 const publicThis = this.proxy;
3351 const getter = isString(source)
3352 ? source.includes('.')
3353 ? createPathGetter(publicThis, source)
3354 : () => publicThis[source]
3355 : source.bind(publicThis, publicThis);
3356 let cb;
3357 if (isFunction(value)) {
3358 cb = value;
3359 }
3360 else {
3361 cb = value.handler;
3362 options = value;
3363 }
3364 const cur = currentInstance;
3365 setCurrentInstance(this);
3366 const res = doWatch(getter, cb.bind(publicThis), options);
3367 if (cur) {
3368 setCurrentInstance(cur);
3369 }
3370 else {
3371 unsetCurrentInstance();
3372 }
3373 return res;
3374 }
3375 function createPathGetter(ctx, path) {
3376 const segments = path.split('.');
3377 return () => {
3378 let cur = ctx;
3379 for (let i = 0; i < segments.length && cur; i++) {
3380 cur = cur[segments[i]];
3381 }
3382 return cur;
3383 };
3384 }
3385 function traverse(value, seen) {
3386 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
3387 return value;
3388 }
3389 seen = seen || new Set();
3390 if (seen.has(value)) {
3391 return value;
3392 }
3393 seen.add(value);
3394 if (isRef(value)) {
3395 traverse(value.value, seen);
3396 }
3397 else if (isArray(value)) {
3398 for (let i = 0; i < value.length; i++) {
3399 traverse(value[i], seen);
3400 }
3401 }
3402 else if (isSet(value) || isMap(value)) {
3403 value.forEach((v) => {
3404 traverse(v, seen);
3405 });
3406 }
3407 else if (isPlainObject(value)) {
3408 for (const key in value) {
3409 traverse(value[key], seen);
3410 }
3411 }
3412 return value;
3413 }
3414
3415 function useTransitionState() {
3416 const state = {
3417 isMounted: false,
3418 isLeaving: false,
3419 isUnmounting: false,
3420 leavingVNodes: new Map()
3421 };
3422 onMounted(() => {
3423 state.isMounted = true;
3424 });
3425 onBeforeUnmount(() => {
3426 state.isUnmounting = true;
3427 });
3428 return state;
3429 }
3430 const TransitionHookValidator = [Function, Array];
3431 const BaseTransitionImpl = {
3432 name: `BaseTransition`,
3433 props: {
3434 mode: String,
3435 appear: Boolean,
3436 persisted: Boolean,
3437 // enter
3438 onBeforeEnter: TransitionHookValidator,
3439 onEnter: TransitionHookValidator,
3440 onAfterEnter: TransitionHookValidator,
3441 onEnterCancelled: TransitionHookValidator,
3442 // leave
3443 onBeforeLeave: TransitionHookValidator,
3444 onLeave: TransitionHookValidator,
3445 onAfterLeave: TransitionHookValidator,
3446 onLeaveCancelled: TransitionHookValidator,
3447 // appear
3448 onBeforeAppear: TransitionHookValidator,
3449 onAppear: TransitionHookValidator,
3450 onAfterAppear: TransitionHookValidator,
3451 onAppearCancelled: TransitionHookValidator
3452 },
3453 setup(props, { slots }) {
3454 const instance = getCurrentInstance();
3455 const state = useTransitionState();
3456 let prevTransitionKey;
3457 return () => {
3458 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3459 if (!children || !children.length) {
3460 return;
3461 }
3462 // warn multiple elements
3463 if (children.length > 1) {
3464 warn$1('<transition> can only be used on a single element or component. Use ' +
3465 '<transition-group> for lists.');
3466 }
3467 // there's no need to track reactivity for these props so use the raw
3468 // props for a bit better perf
3469 const rawProps = toRaw(props);
3470 const { mode } = rawProps;
3471 // check mode
3472 if (mode &&
3473 mode !== 'in-out' && mode !== 'out-in' && mode !== 'default') {
3474 warn$1(`invalid <transition> mode: ${mode}`);
3475 }
3476 // at this point children has a guaranteed length of 1.
3477 const child = children[0];
3478 if (state.isLeaving) {
3479 return emptyPlaceholder(child);
3480 }
3481 // in the case of <transition><keep-alive/></transition>, we need to
3482 // compare the type of the kept-alive children.
3483 const innerChild = getKeepAliveChild(child);
3484 if (!innerChild) {
3485 return emptyPlaceholder(child);
3486 }
3487 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3488 setTransitionHooks(innerChild, enterHooks);
3489 const oldChild = instance.subTree;
3490 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3491 let transitionKeyChanged = false;
3492 const { getTransitionKey } = innerChild.type;
3493 if (getTransitionKey) {
3494 const key = getTransitionKey();
3495 if (prevTransitionKey === undefined) {
3496 prevTransitionKey = key;
3497 }
3498 else if (key !== prevTransitionKey) {
3499 prevTransitionKey = key;
3500 transitionKeyChanged = true;
3501 }
3502 }
3503 // handle mode
3504 if (oldInnerChild &&
3505 oldInnerChild.type !== Comment &&
3506 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3507 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3508 // update old tree's hooks in case of dynamic transition
3509 setTransitionHooks(oldInnerChild, leavingHooks);
3510 // switching between different views
3511 if (mode === 'out-in') {
3512 state.isLeaving = true;
3513 // return placeholder node and queue update when leave finishes
3514 leavingHooks.afterLeave = () => {
3515 state.isLeaving = false;
3516 instance.update();
3517 };
3518 return emptyPlaceholder(child);
3519 }
3520 else if (mode === 'in-out' && innerChild.type !== Comment) {
3521 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3522 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3523 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3524 // early removal callback
3525 el._leaveCb = () => {
3526 earlyRemove();
3527 el._leaveCb = undefined;
3528 delete enterHooks.delayedLeave;
3529 };
3530 enterHooks.delayedLeave = delayedLeave;
3531 };
3532 }
3533 }
3534 return child;
3535 };
3536 }
3537 };
3538 // export the public type for h/tsx inference
3539 // also to avoid inline import() in generated d.ts files
3540 const BaseTransition = BaseTransitionImpl;
3541 function getLeavingNodesForType(state, vnode) {
3542 const { leavingVNodes } = state;
3543 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3544 if (!leavingVNodesCache) {
3545 leavingVNodesCache = Object.create(null);
3546 leavingVNodes.set(vnode.type, leavingVNodesCache);
3547 }
3548 return leavingVNodesCache;
3549 }
3550 // The transition hooks are attached to the vnode as vnode.transition
3551 // and will be called at appropriate timing in the renderer.
3552 function resolveTransitionHooks(vnode, props, state, instance) {
3553 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3554 const key = String(vnode.key);
3555 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3556 const callHook = (hook, args) => {
3557 hook &&
3558 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3559 };
3560 const hooks = {
3561 mode,
3562 persisted,
3563 beforeEnter(el) {
3564 let hook = onBeforeEnter;
3565 if (!state.isMounted) {
3566 if (appear) {
3567 hook = onBeforeAppear || onBeforeEnter;
3568 }
3569 else {
3570 return;
3571 }
3572 }
3573 // for same element (v-show)
3574 if (el._leaveCb) {
3575 el._leaveCb(true /* cancelled */);
3576 }
3577 // for toggled element with same key (v-if)
3578 const leavingVNode = leavingVNodesCache[key];
3579 if (leavingVNode &&
3580 isSameVNodeType(vnode, leavingVNode) &&
3581 leavingVNode.el._leaveCb) {
3582 // force early removal (not cancelled)
3583 leavingVNode.el._leaveCb();
3584 }
3585 callHook(hook, [el]);
3586 },
3587 enter(el) {
3588 let hook = onEnter;
3589 let afterHook = onAfterEnter;
3590 let cancelHook = onEnterCancelled;
3591 if (!state.isMounted) {
3592 if (appear) {
3593 hook = onAppear || onEnter;
3594 afterHook = onAfterAppear || onAfterEnter;
3595 cancelHook = onAppearCancelled || onEnterCancelled;
3596 }
3597 else {
3598 return;
3599 }
3600 }
3601 let called = false;
3602 const done = (el._enterCb = (cancelled) => {
3603 if (called)
3604 return;
3605 called = true;
3606 if (cancelled) {
3607 callHook(cancelHook, [el]);
3608 }
3609 else {
3610 callHook(afterHook, [el]);
3611 }
3612 if (hooks.delayedLeave) {
3613 hooks.delayedLeave();
3614 }
3615 el._enterCb = undefined;
3616 });
3617 if (hook) {
3618 hook(el, done);
3619 if (hook.length <= 1) {
3620 done();
3621 }
3622 }
3623 else {
3624 done();
3625 }
3626 },
3627 leave(el, remove) {
3628 const key = String(vnode.key);
3629 if (el._enterCb) {
3630 el._enterCb(true /* cancelled */);
3631 }
3632 if (state.isUnmounting) {
3633 return remove();
3634 }
3635 callHook(onBeforeLeave, [el]);
3636 let called = false;
3637 const done = (el._leaveCb = (cancelled) => {
3638 if (called)
3639 return;
3640 called = true;
3641 remove();
3642 if (cancelled) {
3643 callHook(onLeaveCancelled, [el]);
3644 }
3645 else {
3646 callHook(onAfterLeave, [el]);
3647 }
3648 el._leaveCb = undefined;
3649 if (leavingVNodesCache[key] === vnode) {
3650 delete leavingVNodesCache[key];
3651 }
3652 });
3653 leavingVNodesCache[key] = vnode;
3654 if (onLeave) {
3655 onLeave(el, done);
3656 if (onLeave.length <= 1) {
3657 done();
3658 }
3659 }
3660 else {
3661 done();
3662 }
3663 },
3664 clone(vnode) {
3665 return resolveTransitionHooks(vnode, props, state, instance);
3666 }
3667 };
3668 return hooks;
3669 }
3670 // the placeholder really only handles one special case: KeepAlive
3671 // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3672 // placeholder with empty content to avoid the KeepAlive instance from being
3673 // unmounted.
3674 function emptyPlaceholder(vnode) {
3675 if (isKeepAlive(vnode)) {
3676 vnode = cloneVNode(vnode);
3677 vnode.children = null;
3678 return vnode;
3679 }
3680 }
3681 function getKeepAliveChild(vnode) {
3682 return isKeepAlive(vnode)
3683 ? vnode.children
3684 ? vnode.children[0]
3685 : undefined
3686 : vnode;
3687 }
3688 function setTransitionHooks(vnode, hooks) {
3689 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3690 setTransitionHooks(vnode.component.subTree, hooks);
3691 }
3692 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3693 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3694 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3695 }
3696 else {
3697 vnode.transition = hooks;
3698 }
3699 }
3700 function getTransitionRawChildren(children, keepComment = false) {
3701 let ret = [];
3702 let keyedFragmentCount = 0;
3703 for (let i = 0; i < children.length; i++) {
3704 const child = children[i];
3705 // handle fragment children case, e.g. v-for
3706 if (child.type === Fragment) {
3707 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3708 keyedFragmentCount++;
3709 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3710 }
3711 // comment placeholders should be skipped, e.g. v-if
3712 else if (keepComment || child.type !== Comment) {
3713 ret.push(child);
3714 }
3715 }
3716 // #1126 if a transition children list contains multiple sub fragments, these
3717 // fragments will be merged into a flat children array. Since each v-for
3718 // fragment may contain different static bindings inside, we need to de-op
3719 // these children to force full diffs to ensure correct behavior.
3720 if (keyedFragmentCount > 1) {
3721 for (let i = 0; i < ret.length; i++) {
3722 ret[i].patchFlag = -2 /* BAIL */;
3723 }
3724 }
3725 return ret;
3726 }
3727
3728 // implementation, close to no-op
3729 function defineComponent(options) {
3730 return isFunction(options) ? { setup: options, name: options.name } : options;
3731 }
3732
3733 const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3734 function defineAsyncComponent(source) {
3735 if (isFunction(source)) {
3736 source = { loader: source };
3737 }
3738 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3739 suspensible = true, onError: userOnError } = source;
3740 let pendingRequest = null;
3741 let resolvedComp;
3742 let retries = 0;
3743 const retry = () => {
3744 retries++;
3745 pendingRequest = null;
3746 return load();
3747 };
3748 const load = () => {
3749 let thisRequest;
3750 return (pendingRequest ||
3751 (thisRequest = pendingRequest =
3752 loader()
3753 .catch(err => {
3754 err = err instanceof Error ? err : new Error(String(err));
3755 if (userOnError) {
3756 return new Promise((resolve, reject) => {
3757 const userRetry = () => resolve(retry());
3758 const userFail = () => reject(err);
3759 userOnError(err, userRetry, userFail, retries + 1);
3760 });
3761 }
3762 else {
3763 throw err;
3764 }
3765 })
3766 .then((comp) => {
3767 if (thisRequest !== pendingRequest && pendingRequest) {
3768 return pendingRequest;
3769 }
3770 if (!comp) {
3771 warn$1(`Async component loader resolved to undefined. ` +
3772 `If you are using retry(), make sure to return its return value.`);
3773 }
3774 // interop module default
3775 if (comp &&
3776 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3777 comp = comp.default;
3778 }
3779 if (comp && !isObject(comp) && !isFunction(comp)) {
3780 throw new Error(`Invalid async component load result: ${comp}`);
3781 }
3782 resolvedComp = comp;
3783 return comp;
3784 })));
3785 };
3786 return defineComponent({
3787 name: 'AsyncComponentWrapper',
3788 __asyncLoader: load,
3789 get __asyncResolved() {
3790 return resolvedComp;
3791 },
3792 setup() {
3793 const instance = currentInstance;
3794 // already resolved
3795 if (resolvedComp) {
3796 return () => createInnerComp(resolvedComp, instance);
3797 }
3798 const onError = (err) => {
3799 pendingRequest = null;
3800 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3801 };
3802 // suspense-controlled or SSR.
3803 if ((suspensible && instance.suspense) ||
3804 (false )) {
3805 return load()
3806 .then(comp => {
3807 return () => createInnerComp(comp, instance);
3808 })
3809 .catch(err => {
3810 onError(err);
3811 return () => errorComponent
3812 ? createVNode(errorComponent, {
3813 error: err
3814 })
3815 : null;
3816 });
3817 }
3818 const loaded = ref(false);
3819 const error = ref();
3820 const delayed = ref(!!delay);
3821 if (delay) {
3822 setTimeout(() => {
3823 delayed.value = false;
3824 }, delay);
3825 }
3826 if (timeout != null) {
3827 setTimeout(() => {
3828 if (!loaded.value && !error.value) {
3829 const err = new Error(`Async component timed out after ${timeout}ms.`);
3830 onError(err);
3831 error.value = err;
3832 }
3833 }, timeout);
3834 }
3835 load()
3836 .then(() => {
3837 loaded.value = true;
3838 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3839 // parent is keep-alive, force update so the loaded component's
3840 // name is taken into account
3841 queueJob(instance.parent.update);
3842 }
3843 })
3844 .catch(err => {
3845 onError(err);
3846 error.value = err;
3847 });
3848 return () => {
3849 if (loaded.value && resolvedComp) {
3850 return createInnerComp(resolvedComp, instance);
3851 }
3852 else if (error.value && errorComponent) {
3853 return createVNode(errorComponent, {
3854 error: error.value
3855 });
3856 }
3857 else if (loadingComponent && !delayed.value) {
3858 return createVNode(loadingComponent);
3859 }
3860 };
3861 }
3862 });
3863 }
3864 function createInnerComp(comp, { vnode: { ref, props, children } }) {
3865 const vnode = createVNode(comp, props, children);
3866 // ensure inner component inherits the async wrapper's ref owner
3867 vnode.ref = ref;
3868 return vnode;
3869 }
3870
3871 const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3872 const KeepAliveImpl = {
3873 name: `KeepAlive`,
3874 // Marker for special handling inside the renderer. We are not using a ===
3875 // check directly on KeepAlive in the renderer, because importing it directly
3876 // would prevent it from being tree-shaken.
3877 __isKeepAlive: true,
3878 props: {
3879 include: [String, RegExp, Array],
3880 exclude: [String, RegExp, Array],
3881 max: [String, Number]
3882 },
3883 setup(props, { slots }) {
3884 const instance = getCurrentInstance();
3885 // KeepAlive communicates with the instantiated renderer via the
3886 // ctx where the renderer passes in its internals,
3887 // and the KeepAlive instance exposes activate/deactivate implementations.
3888 // The whole point of this is to avoid importing KeepAlive directly in the
3889 // renderer to facilitate tree-shaking.
3890 const sharedContext = instance.ctx;
3891 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3892 // for KeepAlive, we just need to render its children
3893 if (!sharedContext.renderer) {
3894 return slots.default;
3895 }
3896 const cache = new Map();
3897 const keys = new Set();
3898 let current = null;
3899 {
3900 instance.__v_cache = cache;
3901 }
3902 const parentSuspense = instance.suspense;
3903 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3904 const storageContainer = createElement('div');
3905 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3906 const instance = vnode.component;
3907 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3908 // in case props have changed
3909 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3910 queuePostRenderEffect(() => {
3911 instance.isDeactivated = false;
3912 if (instance.a) {
3913 invokeArrayFns(instance.a);
3914 }
3915 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3916 if (vnodeHook) {
3917 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3918 }
3919 }, parentSuspense);
3920 {
3921 // Update components tree
3922 devtoolsComponentAdded(instance);
3923 }
3924 };
3925 sharedContext.deactivate = (vnode) => {
3926 const instance = vnode.component;
3927 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3928 queuePostRenderEffect(() => {
3929 if (instance.da) {
3930 invokeArrayFns(instance.da);
3931 }
3932 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3933 if (vnodeHook) {
3934 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3935 }
3936 instance.isDeactivated = true;
3937 }, parentSuspense);
3938 {
3939 // Update components tree
3940 devtoolsComponentAdded(instance);
3941 }
3942 };
3943 function unmount(vnode) {
3944 // reset the shapeFlag so it can be properly unmounted
3945 resetShapeFlag(vnode);
3946 _unmount(vnode, instance, parentSuspense, true);
3947 }
3948 function pruneCache(filter) {
3949 cache.forEach((vnode, key) => {
3950 const name = getComponentName(vnode.type);
3951 if (name && (!filter || !filter(name))) {
3952 pruneCacheEntry(key);
3953 }
3954 });
3955 }
3956 function pruneCacheEntry(key) {
3957 const cached = cache.get(key);
3958 if (!current || cached.type !== current.type) {
3959 unmount(cached);
3960 }
3961 else if (current) {
3962 // current active instance should no longer be kept-alive.
3963 // we can't unmount it now but it might be later, so reset its flag now.
3964 resetShapeFlag(current);
3965 }
3966 cache.delete(key);
3967 keys.delete(key);
3968 }
3969 // prune cache on include/exclude prop change
3970 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3971 include && pruneCache(name => matches(include, name));
3972 exclude && pruneCache(name => !matches(exclude, name));
3973 },
3974 // prune post-render after `current` has been updated
3975 { flush: 'post', deep: true });
3976 // cache sub tree after render
3977 let pendingCacheKey = null;
3978 const cacheSubtree = () => {
3979 // fix #1621, the pendingCacheKey could be 0
3980 if (pendingCacheKey != null) {
3981 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3982 }
3983 };
3984 onMounted(cacheSubtree);
3985 onUpdated(cacheSubtree);
3986 onBeforeUnmount(() => {
3987 cache.forEach(cached => {
3988 const { subTree, suspense } = instance;
3989 const vnode = getInnerChild(subTree);
3990 if (cached.type === vnode.type) {
3991 // current instance will be unmounted as part of keep-alive's unmount
3992 resetShapeFlag(vnode);
3993 // but invoke its deactivated hook here
3994 const da = vnode.component.da;
3995 da && queuePostRenderEffect(da, suspense);
3996 return;
3997 }
3998 unmount(cached);
3999 });
4000 });
4001 return () => {
4002 pendingCacheKey = null;
4003 if (!slots.default) {
4004 return null;
4005 }
4006 const children = slots.default();
4007 const rawVNode = children[0];
4008 if (children.length > 1) {
4009 {
4010 warn$1(`KeepAlive should contain exactly one component child.`);
4011 }
4012 current = null;
4013 return children;
4014 }
4015 else if (!isVNode(rawVNode) ||
4016 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
4017 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
4018 current = null;
4019 return rawVNode;
4020 }
4021 let vnode = getInnerChild(rawVNode);
4022 const comp = vnode.type;
4023 // for async components, name check should be based in its loaded
4024 // inner component if available
4025 const name = getComponentName(isAsyncWrapper(vnode)
4026 ? vnode.type.__asyncResolved || {}
4027 : comp);
4028 const { include, exclude, max } = props;
4029 if ((include && (!name || !matches(include, name))) ||
4030 (exclude && name && matches(exclude, name))) {
4031 current = vnode;
4032 return rawVNode;
4033 }
4034 const key = vnode.key == null ? comp : vnode.key;
4035 const cachedVNode = cache.get(key);
4036 // clone vnode if it's reused because we are going to mutate it
4037 if (vnode.el) {
4038 vnode = cloneVNode(vnode);
4039 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
4040 rawVNode.ssContent = vnode;
4041 }
4042 }
4043 // #1513 it's possible for the returned vnode to be cloned due to attr
4044 // fallthrough or scopeId, so the vnode here may not be the final vnode
4045 // that is mounted. Instead of caching it directly, we store the pending
4046 // key and cache `instance.subTree` (the normalized vnode) in
4047 // beforeMount/beforeUpdate hooks.
4048 pendingCacheKey = key;
4049 if (cachedVNode) {
4050 // copy over mounted state
4051 vnode.el = cachedVNode.el;
4052 vnode.component = cachedVNode.component;
4053 if (vnode.transition) {
4054 // recursively update transition hooks on subTree
4055 setTransitionHooks(vnode, vnode.transition);
4056 }
4057 // avoid vnode being mounted as fresh
4058 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
4059 // make this key the freshest
4060 keys.delete(key);
4061 keys.add(key);
4062 }
4063 else {
4064 keys.add(key);
4065 // prune oldest entry
4066 if (max && keys.size > parseInt(max, 10)) {
4067 pruneCacheEntry(keys.values().next().value);
4068 }
4069 }
4070 // avoid vnode being unmounted
4071 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4072 current = vnode;
4073 return rawVNode;
4074 };
4075 }
4076 };
4077 // export the public type for h/tsx inference
4078 // also to avoid inline import() in generated d.ts files
4079 const KeepAlive = KeepAliveImpl;
4080 function matches(pattern, name) {
4081 if (isArray(pattern)) {
4082 return pattern.some((p) => matches(p, name));
4083 }
4084 else if (isString(pattern)) {
4085 return pattern.split(',').includes(name);
4086 }
4087 else if (pattern.test) {
4088 return pattern.test(name);
4089 }
4090 /* istanbul ignore next */
4091 return false;
4092 }
4093 function onActivated(hook, target) {
4094 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
4095 }
4096 function onDeactivated(hook, target) {
4097 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
4098 }
4099 function registerKeepAliveHook(hook, type, target = currentInstance) {
4100 // cache the deactivate branch check wrapper for injected hooks so the same
4101 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4102 // deactivation check".
4103 const wrappedHook = hook.__wdc ||
4104 (hook.__wdc = () => {
4105 // only fire the hook if the target instance is NOT in a deactivated branch.
4106 let current = target;
4107 while (current) {
4108 if (current.isDeactivated) {
4109 return;
4110 }
4111 current = current.parent;
4112 }
4113 return hook();
4114 });
4115 injectHook(type, wrappedHook, target);
4116 // In addition to registering it on the target instance, we walk up the parent
4117 // chain and register it on all ancestor instances that are keep-alive roots.
4118 // This avoids the need to walk the entire component tree when invoking these
4119 // hooks, and more importantly, avoids the need to track child components in
4120 // arrays.
4121 if (target) {
4122 let current = target.parent;
4123 while (current && current.parent) {
4124 if (isKeepAlive(current.parent.vnode)) {
4125 injectToKeepAliveRoot(wrappedHook, type, target, current);
4126 }
4127 current = current.parent;
4128 }
4129 }
4130 }
4131 function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4132 // injectHook wraps the original for error handling, so make sure to remove
4133 // the wrapped version.
4134 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4135 onUnmounted(() => {
4136 remove(keepAliveRoot[type], injected);
4137 }, target);
4138 }
4139 function resetShapeFlag(vnode) {
4140 let shapeFlag = vnode.shapeFlag;
4141 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4142 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4143 }
4144 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4145 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4146 }
4147 vnode.shapeFlag = shapeFlag;
4148 }
4149 function getInnerChild(vnode) {
4150 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4151 }
4152
4153 function injectHook(type, hook, target = currentInstance, prepend = false) {
4154 if (target) {
4155 const hooks = target[type] || (target[type] = []);
4156 // cache the error handling wrapper for injected hooks so the same hook
4157 // can be properly deduped by the scheduler. "__weh" stands for "with error
4158 // handling".
4159 const wrappedHook = hook.__weh ||
4160 (hook.__weh = (...args) => {
4161 if (target.isUnmounted) {
4162 return;
4163 }
4164 // disable tracking inside all lifecycle hooks
4165 // since they can potentially be called inside effects.
4166 pauseTracking();
4167 // Set currentInstance during hook invocation.
4168 // This assumes the hook does not synchronously trigger other hooks, which
4169 // can only be false when the user does something really funky.
4170 setCurrentInstance(target);
4171 const res = callWithAsyncErrorHandling(hook, target, type, args);
4172 unsetCurrentInstance();
4173 resetTracking();
4174 return res;
4175 });
4176 if (prepend) {
4177 hooks.unshift(wrappedHook);
4178 }
4179 else {
4180 hooks.push(wrappedHook);
4181 }
4182 return wrappedHook;
4183 }
4184 else {
4185 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4186 warn$1(`${apiName} is called when there is no active component instance to be ` +
4187 `associated with. ` +
4188 `Lifecycle injection APIs can only be used during execution of setup().` +
4189 (` If you are using async setup(), make sure to register lifecycle ` +
4190 `hooks before the first await statement.`
4191 ));
4192 }
4193 }
4194 const createHook = (lifecycle) => (hook, target = currentInstance) =>
4195 // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4196 (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
4197 injectHook(lifecycle, hook, target);
4198 const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
4199 const onMounted = createHook("m" /* MOUNTED */);
4200 const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
4201 const onUpdated = createHook("u" /* UPDATED */);
4202 const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
4203 const onUnmounted = createHook("um" /* UNMOUNTED */);
4204 const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
4205 const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
4206 const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
4207 function onErrorCaptured(hook, target = currentInstance) {
4208 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
4209 }
4210
4211 function createDuplicateChecker() {
4212 const cache = Object.create(null);
4213 return (type, key) => {
4214 if (cache[key]) {
4215 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
4216 }
4217 else {
4218 cache[key] = type;
4219 }
4220 };
4221 }
4222 let shouldCacheAccess = true;
4223 function applyOptions(instance) {
4224 const options = resolveMergedOptions(instance);
4225 const publicThis = instance.proxy;
4226 const ctx = instance.ctx;
4227 // do not cache property access on public proxy during state initialization
4228 shouldCacheAccess = false;
4229 // call beforeCreate first before accessing other options since
4230 // the hook may mutate resolved options (#2791)
4231 if (options.beforeCreate) {
4232 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
4233 }
4234 const {
4235 // state
4236 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4237 // lifecycle
4238 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4239 // public API
4240 expose, inheritAttrs,
4241 // assets
4242 components, directives, filters } = options;
4243 const checkDuplicateProperties = createDuplicateChecker() ;
4244 {
4245 const [propsOptions] = instance.propsOptions;
4246 if (propsOptions) {
4247 for (const key in propsOptions) {
4248 checkDuplicateProperties("Props" /* PROPS */, key);
4249 }
4250 }
4251 }
4252 // options initialization order (to be consistent with Vue 2):
4253 // - props (already done outside of this function)
4254 // - inject
4255 // - methods
4256 // - data (deferred since it relies on `this` access)
4257 // - computed
4258 // - watch (deferred since it relies on `this` access)
4259 if (injectOptions) {
4260 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
4261 }
4262 if (methods) {
4263 for (const key in methods) {
4264 const methodHandler = methods[key];
4265 if (isFunction(methodHandler)) {
4266 // In dev mode, we use the `createRenderContext` function to define
4267 // methods to the proxy target, and those are read-only but
4268 // reconfigurable, so it needs to be redefined here
4269 {
4270 Object.defineProperty(ctx, key, {
4271 value: methodHandler.bind(publicThis),
4272 configurable: true,
4273 enumerable: true,
4274 writable: true
4275 });
4276 }
4277 {
4278 checkDuplicateProperties("Methods" /* METHODS */, key);
4279 }
4280 }
4281 else {
4282 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4283 `Did you reference the function correctly?`);
4284 }
4285 }
4286 }
4287 if (dataOptions) {
4288 if (!isFunction(dataOptions)) {
4289 warn$1(`The data option must be a function. ` +
4290 `Plain object usage is no longer supported.`);
4291 }
4292 const data = dataOptions.call(publicThis, publicThis);
4293 if (isPromise(data)) {
4294 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
4295 `intend to perform data fetching before component renders, use ` +
4296 `async setup() + <Suspense>.`);
4297 }
4298 if (!isObject(data)) {
4299 warn$1(`data() should return an object.`);
4300 }
4301 else {
4302 instance.data = reactive(data);
4303 {
4304 for (const key in data) {
4305 checkDuplicateProperties("Data" /* DATA */, key);
4306 // expose data on ctx during dev
4307 if (key[0] !== '$' && key[0] !== '_') {
4308 Object.defineProperty(ctx, key, {
4309 configurable: true,
4310 enumerable: true,
4311 get: () => data[key],
4312 set: NOOP
4313 });
4314 }
4315 }
4316 }
4317 }
4318 }
4319 // state initialization complete at this point - start caching access
4320 shouldCacheAccess = true;
4321 if (computedOptions) {
4322 for (const key in computedOptions) {
4323 const opt = computedOptions[key];
4324 const get = isFunction(opt)
4325 ? opt.bind(publicThis, publicThis)
4326 : isFunction(opt.get)
4327 ? opt.get.bind(publicThis, publicThis)
4328 : NOOP;
4329 if (get === NOOP) {
4330 warn$1(`Computed property "${key}" has no getter.`);
4331 }
4332 const set = !isFunction(opt) && isFunction(opt.set)
4333 ? opt.set.bind(publicThis)
4334 : () => {
4335 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
4336 }
4337 ;
4338 const c = computed$1({
4339 get,
4340 set
4341 });
4342 Object.defineProperty(ctx, key, {
4343 enumerable: true,
4344 configurable: true,
4345 get: () => c.value,
4346 set: v => (c.value = v)
4347 });
4348 {
4349 checkDuplicateProperties("Computed" /* COMPUTED */, key);
4350 }
4351 }
4352 }
4353 if (watchOptions) {
4354 for (const key in watchOptions) {
4355 createWatcher(watchOptions[key], ctx, publicThis, key);
4356 }
4357 }
4358 if (provideOptions) {
4359 const provides = isFunction(provideOptions)
4360 ? provideOptions.call(publicThis)
4361 : provideOptions;
4362 Reflect.ownKeys(provides).forEach(key => {
4363 provide(key, provides[key]);
4364 });
4365 }
4366 if (created) {
4367 callHook(created, instance, "c" /* CREATED */);
4368 }
4369 function registerLifecycleHook(register, hook) {
4370 if (isArray(hook)) {
4371 hook.forEach(_hook => register(_hook.bind(publicThis)));
4372 }
4373 else if (hook) {
4374 register(hook.bind(publicThis));
4375 }
4376 }
4377 registerLifecycleHook(onBeforeMount, beforeMount);
4378 registerLifecycleHook(onMounted, mounted);
4379 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
4380 registerLifecycleHook(onUpdated, updated);
4381 registerLifecycleHook(onActivated, activated);
4382 registerLifecycleHook(onDeactivated, deactivated);
4383 registerLifecycleHook(onErrorCaptured, errorCaptured);
4384 registerLifecycleHook(onRenderTracked, renderTracked);
4385 registerLifecycleHook(onRenderTriggered, renderTriggered);
4386 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
4387 registerLifecycleHook(onUnmounted, unmounted);
4388 registerLifecycleHook(onServerPrefetch, serverPrefetch);
4389 if (isArray(expose)) {
4390 if (expose.length) {
4391 const exposed = instance.exposed || (instance.exposed = {});
4392 expose.forEach(key => {
4393 Object.defineProperty(exposed, key, {
4394 get: () => publicThis[key],
4395 set: val => (publicThis[key] = val)
4396 });
4397 });
4398 }
4399 else if (!instance.exposed) {
4400 instance.exposed = {};
4401 }
4402 }
4403 // options that are handled when creating the instance but also need to be
4404 // applied from mixins
4405 if (render && instance.render === NOOP) {
4406 instance.render = render;
4407 }
4408 if (inheritAttrs != null) {
4409 instance.inheritAttrs = inheritAttrs;
4410 }
4411 // asset options.
4412 if (components)
4413 instance.components = components;
4414 if (directives)
4415 instance.directives = directives;
4416 }
4417 function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4418 if (isArray(injectOptions)) {
4419 injectOptions = normalizeInject(injectOptions);
4420 }
4421 for (const key in injectOptions) {
4422 const opt = injectOptions[key];
4423 let injected;
4424 if (isObject(opt)) {
4425 if ('default' in opt) {
4426 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4427 }
4428 else {
4429 injected = inject(opt.from || key);
4430 }
4431 }
4432 else {
4433 injected = inject(opt);
4434 }
4435 if (isRef(injected)) {
4436 // TODO remove the check in 3.3
4437 if (unwrapRef) {
4438 Object.defineProperty(ctx, key, {
4439 enumerable: true,
4440 configurable: true,
4441 get: () => injected.value,
4442 set: v => (injected.value = v)
4443 });
4444 }
4445 else {
4446 {
4447 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4448 `and no longer needs \`.value\` in the next minor release. ` +
4449 `To opt-in to the new behavior now, ` +
4450 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4451 `temporary and will not be needed in the future.)`);
4452 }
4453 ctx[key] = injected;
4454 }
4455 }
4456 else {
4457 ctx[key] = injected;
4458 }
4459 {
4460 checkDuplicateProperties("Inject" /* INJECT */, key);
4461 }
4462 }
4463 }
4464 function callHook(hook, instance, type) {
4465 callWithAsyncErrorHandling(isArray(hook)
4466 ? hook.map(h => h.bind(instance.proxy))
4467 : hook.bind(instance.proxy), instance, type);
4468 }
4469 function createWatcher(raw, ctx, publicThis, key) {
4470 const getter = key.includes('.')
4471 ? createPathGetter(publicThis, key)
4472 : () => publicThis[key];
4473 if (isString(raw)) {
4474 const handler = ctx[raw];
4475 if (isFunction(handler)) {
4476 watch(getter, handler);
4477 }
4478 else {
4479 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4480 }
4481 }
4482 else if (isFunction(raw)) {
4483 watch(getter, raw.bind(publicThis));
4484 }
4485 else if (isObject(raw)) {
4486 if (isArray(raw)) {
4487 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4488 }
4489 else {
4490 const handler = isFunction(raw.handler)
4491 ? raw.handler.bind(publicThis)
4492 : ctx[raw.handler];
4493 if (isFunction(handler)) {
4494 watch(getter, handler, raw);
4495 }
4496 else {
4497 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4498 }
4499 }
4500 }
4501 else {
4502 warn$1(`Invalid watch option: "${key}"`, raw);
4503 }
4504 }
4505 /**
4506 * Resolve merged options and cache it on the component.
4507 * This is done only once per-component since the merging does not involve
4508 * instances.
4509 */
4510 function resolveMergedOptions(instance) {
4511 const base = instance.type;
4512 const { mixins, extends: extendsOptions } = base;
4513 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4514 const cached = cache.get(base);
4515 let resolved;
4516 if (cached) {
4517 resolved = cached;
4518 }
4519 else if (!globalMixins.length && !mixins && !extendsOptions) {
4520 {
4521 resolved = base;
4522 }
4523 }
4524 else {
4525 resolved = {};
4526 if (globalMixins.length) {
4527 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4528 }
4529 mergeOptions(resolved, base, optionMergeStrategies);
4530 }
4531 cache.set(base, resolved);
4532 return resolved;
4533 }
4534 function mergeOptions(to, from, strats, asMixin = false) {
4535 const { mixins, extends: extendsOptions } = from;
4536 if (extendsOptions) {
4537 mergeOptions(to, extendsOptions, strats, true);
4538 }
4539 if (mixins) {
4540 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4541 }
4542 for (const key in from) {
4543 if (asMixin && key === 'expose') {
4544 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4545 `It should only be declared in the base component itself.`);
4546 }
4547 else {
4548 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4549 to[key] = strat ? strat(to[key], from[key]) : from[key];
4550 }
4551 }
4552 return to;
4553 }
4554 const internalOptionMergeStrats = {
4555 data: mergeDataFn,
4556 props: mergeObjectOptions,
4557 emits: mergeObjectOptions,
4558 // objects
4559 methods: mergeObjectOptions,
4560 computed: mergeObjectOptions,
4561 // lifecycle
4562 beforeCreate: mergeAsArray,
4563 created: mergeAsArray,
4564 beforeMount: mergeAsArray,
4565 mounted: mergeAsArray,
4566 beforeUpdate: mergeAsArray,
4567 updated: mergeAsArray,
4568 beforeDestroy: mergeAsArray,
4569 beforeUnmount: mergeAsArray,
4570 destroyed: mergeAsArray,
4571 unmounted: mergeAsArray,
4572 activated: mergeAsArray,
4573 deactivated: mergeAsArray,
4574 errorCaptured: mergeAsArray,
4575 serverPrefetch: mergeAsArray,
4576 // assets
4577 components: mergeObjectOptions,
4578 directives: mergeObjectOptions,
4579 // watch
4580 watch: mergeWatchOptions,
4581 // provide / inject
4582 provide: mergeDataFn,
4583 inject: mergeInject
4584 };
4585 function mergeDataFn(to, from) {
4586 if (!from) {
4587 return to;
4588 }
4589 if (!to) {
4590 return from;
4591 }
4592 return function mergedDataFn() {
4593 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4594 };
4595 }
4596 function mergeInject(to, from) {
4597 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4598 }
4599 function normalizeInject(raw) {
4600 if (isArray(raw)) {
4601 const res = {};
4602 for (let i = 0; i < raw.length; i++) {
4603 res[raw[i]] = raw[i];
4604 }
4605 return res;
4606 }
4607 return raw;
4608 }
4609 function mergeAsArray(to, from) {
4610 return to ? [...new Set([].concat(to, from))] : from;
4611 }
4612 function mergeObjectOptions(to, from) {
4613 return to ? extend(extend(Object.create(null), to), from) : from;
4614 }
4615 function mergeWatchOptions(to, from) {
4616 if (!to)
4617 return from;
4618 if (!from)
4619 return to;
4620 const merged = extend(Object.create(null), to);
4621 for (const key in from) {
4622 merged[key] = mergeAsArray(to[key], from[key]);
4623 }
4624 return merged;
4625 }
4626
4627 function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4628 isSSR = false) {
4629 const props = {};
4630 const attrs = {};
4631 def(attrs, InternalObjectKey, 1);
4632 instance.propsDefaults = Object.create(null);
4633 setFullProps(instance, rawProps, props, attrs);
4634 // ensure all declared prop keys are present
4635 for (const key in instance.propsOptions[0]) {
4636 if (!(key in props)) {
4637 props[key] = undefined;
4638 }
4639 }
4640 // validation
4641 {
4642 validateProps(rawProps || {}, props, instance);
4643 }
4644 if (isStateful) {
4645 // stateful
4646 instance.props = isSSR ? props : shallowReactive(props);
4647 }
4648 else {
4649 if (!instance.type.props) {
4650 // functional w/ optional props, props === attrs
4651 instance.props = attrs;
4652 }
4653 else {
4654 // functional w/ declared props
4655 instance.props = props;
4656 }
4657 }
4658 instance.attrs = attrs;
4659 }
4660 function updateProps(instance, rawProps, rawPrevProps, optimized) {
4661 const { props, attrs, vnode: { patchFlag } } = instance;
4662 const rawCurrentProps = toRaw(props);
4663 const [options] = instance.propsOptions;
4664 let hasAttrsChanged = false;
4665 if (
4666 // always force full diff in dev
4667 // - #1942 if hmr is enabled with sfc component
4668 // - vite#872 non-sfc component used by sfc component
4669 !((instance.type.__hmrId ||
4670 (instance.parent && instance.parent.type.__hmrId))) &&
4671 (optimized || patchFlag > 0) &&
4672 !(patchFlag & 16 /* FULL_PROPS */)) {
4673 if (patchFlag & 8 /* PROPS */) {
4674 // Compiler-generated props & no keys change, just set the updated
4675 // the props.
4676 const propsToUpdate = instance.vnode.dynamicProps;
4677 for (let i = 0; i < propsToUpdate.length; i++) {
4678 let key = propsToUpdate[i];
4679 // PROPS flag guarantees rawProps to be non-null
4680 const value = rawProps[key];
4681 if (options) {
4682 // attr / props separation was done on init and will be consistent
4683 // in this code path, so just check if attrs have it.
4684 if (hasOwn(attrs, key)) {
4685 if (value !== attrs[key]) {
4686 attrs[key] = value;
4687 hasAttrsChanged = true;
4688 }
4689 }
4690 else {
4691 const camelizedKey = camelize(key);
4692 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4693 }
4694 }
4695 else {
4696 if (value !== attrs[key]) {
4697 attrs[key] = value;
4698 hasAttrsChanged = true;
4699 }
4700 }
4701 }
4702 }
4703 }
4704 else {
4705 // full props update.
4706 if (setFullProps(instance, rawProps, props, attrs)) {
4707 hasAttrsChanged = true;
4708 }
4709 // in case of dynamic props, check if we need to delete keys from
4710 // the props object
4711 let kebabKey;
4712 for (const key in rawCurrentProps) {
4713 if (!rawProps ||
4714 // for camelCase
4715 (!hasOwn(rawProps, key) &&
4716 // it's possible the original props was passed in as kebab-case
4717 // and converted to camelCase (#955)
4718 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4719 if (options) {
4720 if (rawPrevProps &&
4721 // for camelCase
4722 (rawPrevProps[key] !== undefined ||
4723 // for kebab-case
4724 rawPrevProps[kebabKey] !== undefined)) {
4725 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4726 }
4727 }
4728 else {
4729 delete props[key];
4730 }
4731 }
4732 }
4733 // in the case of functional component w/o props declaration, props and
4734 // attrs point to the same object so it should already have been updated.
4735 if (attrs !== rawCurrentProps) {
4736 for (const key in attrs) {
4737 if (!rawProps ||
4738 (!hasOwn(rawProps, key) &&
4739 (!false ))) {
4740 delete attrs[key];
4741 hasAttrsChanged = true;
4742 }
4743 }
4744 }
4745 }
4746 // trigger updates for $attrs in case it's used in component slots
4747 if (hasAttrsChanged) {
4748 trigger(instance, "set" /* SET */, '$attrs');
4749 }
4750 {
4751 validateProps(rawProps || {}, props, instance);
4752 }
4753 }
4754 function setFullProps(instance, rawProps, props, attrs) {
4755 const [options, needCastKeys] = instance.propsOptions;
4756 let hasAttrsChanged = false;
4757 let rawCastValues;
4758 if (rawProps) {
4759 for (let key in rawProps) {
4760 // key, ref are reserved and never passed down
4761 if (isReservedProp(key)) {
4762 continue;
4763 }
4764 const value = rawProps[key];
4765 // prop option names are camelized during normalization, so to support
4766 // kebab -> camel conversion here we need to camelize the key.
4767 let camelKey;
4768 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4769 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4770 props[camelKey] = value;
4771 }
4772 else {
4773 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4774 }
4775 }
4776 else if (!isEmitListener(instance.emitsOptions, key)) {
4777 if (!(key in attrs) || value !== attrs[key]) {
4778 attrs[key] = value;
4779 hasAttrsChanged = true;
4780 }
4781 }
4782 }
4783 }
4784 if (needCastKeys) {
4785 const rawCurrentProps = toRaw(props);
4786 const castValues = rawCastValues || EMPTY_OBJ;
4787 for (let i = 0; i < needCastKeys.length; i++) {
4788 const key = needCastKeys[i];
4789 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4790 }
4791 }
4792 return hasAttrsChanged;
4793 }
4794 function resolvePropValue(options, props, key, value, instance, isAbsent) {
4795 const opt = options[key];
4796 if (opt != null) {
4797 const hasDefault = hasOwn(opt, 'default');
4798 // default values
4799 if (hasDefault && value === undefined) {
4800 const defaultValue = opt.default;
4801 if (opt.type !== Function && isFunction(defaultValue)) {
4802 const { propsDefaults } = instance;
4803 if (key in propsDefaults) {
4804 value = propsDefaults[key];
4805 }
4806 else {
4807 setCurrentInstance(instance);
4808 value = propsDefaults[key] = defaultValue.call(null, props);
4809 unsetCurrentInstance();
4810 }
4811 }
4812 else {
4813 value = defaultValue;
4814 }
4815 }
4816 // boolean casting
4817 if (opt[0 /* shouldCast */]) {
4818 if (isAbsent && !hasDefault) {
4819 value = false;
4820 }
4821 else if (opt[1 /* shouldCastTrue */] &&
4822 (value === '' || value === hyphenate(key))) {
4823 value = true;
4824 }
4825 }
4826 }
4827 return value;
4828 }
4829 function normalizePropsOptions(comp, appContext, asMixin = false) {
4830 const cache = appContext.propsCache;
4831 const cached = cache.get(comp);
4832 if (cached) {
4833 return cached;
4834 }
4835 const raw = comp.props;
4836 const normalized = {};
4837 const needCastKeys = [];
4838 // apply mixin/extends props
4839 let hasExtends = false;
4840 if (!isFunction(comp)) {
4841 const extendProps = (raw) => {
4842 hasExtends = true;
4843 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4844 extend(normalized, props);
4845 if (keys)
4846 needCastKeys.push(...keys);
4847 };
4848 if (!asMixin && appContext.mixins.length) {
4849 appContext.mixins.forEach(extendProps);
4850 }
4851 if (comp.extends) {
4852 extendProps(comp.extends);
4853 }
4854 if (comp.mixins) {
4855 comp.mixins.forEach(extendProps);
4856 }
4857 }
4858 if (!raw && !hasExtends) {
4859 cache.set(comp, EMPTY_ARR);
4860 return EMPTY_ARR;
4861 }
4862 if (isArray(raw)) {
4863 for (let i = 0; i < raw.length; i++) {
4864 if (!isString(raw[i])) {
4865 warn$1(`props must be strings when using array syntax.`, raw[i]);
4866 }
4867 const normalizedKey = camelize(raw[i]);
4868 if (validatePropName(normalizedKey)) {
4869 normalized[normalizedKey] = EMPTY_OBJ;
4870 }
4871 }
4872 }
4873 else if (raw) {
4874 if (!isObject(raw)) {
4875 warn$1(`invalid props options`, raw);
4876 }
4877 for (const key in raw) {
4878 const normalizedKey = camelize(key);
4879 if (validatePropName(normalizedKey)) {
4880 const opt = raw[key];
4881 const prop = (normalized[normalizedKey] =
4882 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4883 if (prop) {
4884 const booleanIndex = getTypeIndex(Boolean, prop.type);
4885 const stringIndex = getTypeIndex(String, prop.type);
4886 prop[0 /* shouldCast */] = booleanIndex > -1;
4887 prop[1 /* shouldCastTrue */] =
4888 stringIndex < 0 || booleanIndex < stringIndex;
4889 // if the prop needs boolean casting or default value
4890 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4891 needCastKeys.push(normalizedKey);
4892 }
4893 }
4894 }
4895 }
4896 }
4897 const res = [normalized, needCastKeys];
4898 cache.set(comp, res);
4899 return res;
4900 }
4901 function validatePropName(key) {
4902 if (key[0] !== '$') {
4903 return true;
4904 }
4905 else {
4906 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4907 }
4908 return false;
4909 }
4910 // use function string name to check type constructors
4911 // so that it works across vms / iframes.
4912 function getType(ctor) {
4913 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4914 return match ? match[1] : ctor === null ? 'null' : '';
4915 }
4916 function isSameType(a, b) {
4917 return getType(a) === getType(b);
4918 }
4919 function getTypeIndex(type, expectedTypes) {
4920 if (isArray(expectedTypes)) {
4921 return expectedTypes.findIndex(t => isSameType(t, type));
4922 }
4923 else if (isFunction(expectedTypes)) {
4924 return isSameType(expectedTypes, type) ? 0 : -1;
4925 }
4926 return -1;
4927 }
4928 /**
4929 * dev only
4930 */
4931 function validateProps(rawProps, props, instance) {
4932 const resolvedValues = toRaw(props);
4933 const options = instance.propsOptions[0];
4934 for (const key in options) {
4935 let opt = options[key];
4936 if (opt == null)
4937 continue;
4938 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4939 }
4940 }
4941 /**
4942 * dev only
4943 */
4944 function validateProp(name, value, prop, isAbsent) {
4945 const { type, required, validator } = prop;
4946 // required!
4947 if (required && isAbsent) {
4948 warn$1('Missing required prop: "' + name + '"');
4949 return;
4950 }
4951 // missing but optional
4952 if (value == null && !prop.required) {
4953 return;
4954 }
4955 // type check
4956 if (type != null && type !== true) {
4957 let isValid = false;
4958 const types = isArray(type) ? type : [type];
4959 const expectedTypes = [];
4960 // value is valid as long as one of the specified types match
4961 for (let i = 0; i < types.length && !isValid; i++) {
4962 const { valid, expectedType } = assertType(value, types[i]);
4963 expectedTypes.push(expectedType || '');
4964 isValid = valid;
4965 }
4966 if (!isValid) {
4967 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
4968 return;
4969 }
4970 }
4971 // custom validator
4972 if (validator && !validator(value)) {
4973 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
4974 }
4975 }
4976 const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4977 /**
4978 * dev only
4979 */
4980 function assertType(value, type) {
4981 let valid;
4982 const expectedType = getType(type);
4983 if (isSimpleType(expectedType)) {
4984 const t = typeof value;
4985 valid = t === expectedType.toLowerCase();
4986 // for primitive wrapper objects
4987 if (!valid && t === 'object') {
4988 valid = value instanceof type;
4989 }
4990 }
4991 else if (expectedType === 'Object') {
4992 valid = isObject(value);
4993 }
4994 else if (expectedType === 'Array') {
4995 valid = isArray(value);
4996 }
4997 else if (expectedType === 'null') {
4998 valid = value === null;
4999 }
5000 else {
5001 valid = value instanceof type;
5002 }
5003 return {
5004 valid,
5005 expectedType
5006 };
5007 }
5008 /**
5009 * dev only
5010 */
5011 function getInvalidTypeMessage(name, value, expectedTypes) {
5012 let message = `Invalid prop: type check failed for prop "${name}".` +
5013 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
5014 const expectedType = expectedTypes[0];
5015 const receivedType = toRawType(value);
5016 const expectedValue = styleValue(value, expectedType);
5017 const receivedValue = styleValue(value, receivedType);
5018 // check if we need to specify expected value
5019 if (expectedTypes.length === 1 &&
5020 isExplicable(expectedType) &&
5021 !isBoolean(expectedType, receivedType)) {
5022 message += ` with value ${expectedValue}`;
5023 }
5024 message += `, got ${receivedType} `;
5025 // check if we need to specify received value
5026 if (isExplicable(receivedType)) {
5027 message += `with value ${receivedValue}.`;
5028 }
5029 return message;
5030 }
5031 /**
5032 * dev only
5033 */
5034 function styleValue(value, type) {
5035 if (type === 'String') {
5036 return `"${value}"`;
5037 }
5038 else if (type === 'Number') {
5039 return `${Number(value)}`;
5040 }
5041 else {
5042 return `${value}`;
5043 }
5044 }
5045 /**
5046 * dev only
5047 */
5048 function isExplicable(type) {
5049 const explicitTypes = ['string', 'number', 'boolean'];
5050 return explicitTypes.some(elem => type.toLowerCase() === elem);
5051 }
5052 /**
5053 * dev only
5054 */
5055 function isBoolean(...args) {
5056 return args.some(elem => elem.toLowerCase() === 'boolean');
5057 }
5058
5059 const isInternalKey = (key) => key[0] === '_' || key === '$stable';
5060 const normalizeSlotValue = (value) => isArray(value)
5061 ? value.map(normalizeVNode)
5062 : [normalizeVNode(value)];
5063 const normalizeSlot = (key, rawSlot, ctx) => {
5064 const normalized = withCtx((...args) => {
5065 if (currentInstance) {
5066 warn$1(`Slot "${key}" invoked outside of the render function: ` +
5067 `this will not track dependencies used in the slot. ` +
5068 `Invoke the slot function inside the render function instead.`);
5069 }
5070 return normalizeSlotValue(rawSlot(...args));
5071 }, ctx);
5072 normalized._c = false;
5073 return normalized;
5074 };
5075 const normalizeObjectSlots = (rawSlots, slots, instance) => {
5076 const ctx = rawSlots._ctx;
5077 for (const key in rawSlots) {
5078 if (isInternalKey(key))
5079 continue;
5080 const value = rawSlots[key];
5081 if (isFunction(value)) {
5082 slots[key] = normalizeSlot(key, value, ctx);
5083 }
5084 else if (value != null) {
5085 {
5086 warn$1(`Non-function value encountered for slot "${key}". ` +
5087 `Prefer function slots for better performance.`);
5088 }
5089 const normalized = normalizeSlotValue(value);
5090 slots[key] = () => normalized;
5091 }
5092 }
5093 };
5094 const normalizeVNodeSlots = (instance, children) => {
5095 if (!isKeepAlive(instance.vnode) &&
5096 !(false )) {
5097 warn$1(`Non-function value encountered for default slot. ` +
5098 `Prefer function slots for better performance.`);
5099 }
5100 const normalized = normalizeSlotValue(children);
5101 instance.slots.default = () => normalized;
5102 };
5103 const initSlots = (instance, children) => {
5104 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5105 const type = children._;
5106 if (type) {
5107 // users can get the shallow readonly version of the slots object through `this.$slots`,
5108 // we should avoid the proxy object polluting the slots of the internal instance
5109 instance.slots = toRaw(children);
5110 // make compiler marker non-enumerable
5111 def(children, '_', type);
5112 }
5113 else {
5114 normalizeObjectSlots(children, (instance.slots = {}));
5115 }
5116 }
5117 else {
5118 instance.slots = {};
5119 if (children) {
5120 normalizeVNodeSlots(instance, children);
5121 }
5122 }
5123 def(instance.slots, InternalObjectKey, 1);
5124 };
5125 const updateSlots = (instance, children, optimized) => {
5126 const { vnode, slots } = instance;
5127 let needDeletionCheck = true;
5128 let deletionComparisonTarget = EMPTY_OBJ;
5129 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5130 const type = children._;
5131 if (type) {
5132 // compiled slots.
5133 if (isHmrUpdating) {
5134 // Parent was HMR updated so slot content may have changed.
5135 // force update slots and mark instance for hmr as well
5136 extend(slots, children);
5137 }
5138 else if (optimized && type === 1 /* STABLE */) {
5139 // compiled AND stable.
5140 // no need to update, and skip stale slots removal.
5141 needDeletionCheck = false;
5142 }
5143 else {
5144 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5145 // normalization.
5146 extend(slots, children);
5147 // #2893
5148 // when rendering the optimized slots by manually written render function,
5149 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5150 // i.e. let the `renderSlot` create the bailed Fragment
5151 if (!optimized && type === 1 /* STABLE */) {
5152 delete slots._;
5153 }
5154 }
5155 }
5156 else {
5157 needDeletionCheck = !children.$stable;
5158 normalizeObjectSlots(children, slots);
5159 }
5160 deletionComparisonTarget = children;
5161 }
5162 else if (children) {
5163 // non slot object children (direct value) passed to a component
5164 normalizeVNodeSlots(instance, children);
5165 deletionComparisonTarget = { default: 1 };
5166 }
5167 // delete stale slots
5168 if (needDeletionCheck) {
5169 for (const key in slots) {
5170 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5171 delete slots[key];
5172 }
5173 }
5174 }
5175 };
5176
5177 /**
5178 Runtime helper for applying directives to a vnode. Example usage:
5179
5180 const comp = resolveComponent('comp')
5181 const foo = resolveDirective('foo')
5182 const bar = resolveDirective('bar')
5183
5184 return withDirectives(h(comp), [
5185 [foo, this.x],
5186 [bar, this.y]
5187 ])
5188 */
5189 const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
5190 function validateDirectiveName(name) {
5191 if (isBuiltInDirective(name)) {
5192 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
5193 }
5194 }
5195 /**
5196 * Adds directives to a VNode.
5197 */
5198 function withDirectives(vnode, directives) {
5199 const internalInstance = currentRenderingInstance;
5200 if (internalInstance === null) {
5201 warn$1(`withDirectives can only be used inside render functions.`);
5202 return vnode;
5203 }
5204 const instance = internalInstance.proxy;
5205 const bindings = vnode.dirs || (vnode.dirs = []);
5206 for (let i = 0; i < directives.length; i++) {
5207 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
5208 if (isFunction(dir)) {
5209 dir = {
5210 mounted: dir,
5211 updated: dir
5212 };
5213 }
5214 if (dir.deep) {
5215 traverse(value);
5216 }
5217 bindings.push({
5218 dir,
5219 instance,
5220 value,
5221 oldValue: void 0,
5222 arg,
5223 modifiers
5224 });
5225 }
5226 return vnode;
5227 }
5228 function invokeDirectiveHook(vnode, prevVNode, instance, name) {
5229 const bindings = vnode.dirs;
5230 const oldBindings = prevVNode && prevVNode.dirs;
5231 for (let i = 0; i < bindings.length; i++) {
5232 const binding = bindings[i];
5233 if (oldBindings) {
5234 binding.oldValue = oldBindings[i].value;
5235 }
5236 let hook = binding.dir[name];
5237 if (hook) {
5238 // disable tracking inside all lifecycle hooks
5239 // since they can potentially be called inside effects.
5240 pauseTracking();
5241 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
5242 vnode.el,
5243 binding,
5244 vnode,
5245 prevVNode
5246 ]);
5247 resetTracking();
5248 }
5249 }
5250 }
5251
5252 function createAppContext() {
5253 return {
5254 app: null,
5255 config: {
5256 isNativeTag: NO,
5257 performance: false,
5258 globalProperties: {},
5259 optionMergeStrategies: {},
5260 errorHandler: undefined,
5261 warnHandler: undefined,
5262 compilerOptions: {}
5263 },
5264 mixins: [],
5265 components: {},
5266 directives: {},
5267 provides: Object.create(null),
5268 optionsCache: new WeakMap(),
5269 propsCache: new WeakMap(),
5270 emitsCache: new WeakMap()
5271 };
5272 }
5273 let uid = 0;
5274 function createAppAPI(render, hydrate) {
5275 return function createApp(rootComponent, rootProps = null) {
5276 if (rootProps != null && !isObject(rootProps)) {
5277 warn$1(`root props passed to app.mount() must be an object.`);
5278 rootProps = null;
5279 }
5280 const context = createAppContext();
5281 const installedPlugins = new Set();
5282 let isMounted = false;
5283 const app = (context.app = {
5284 _uid: uid++,
5285 _component: rootComponent,
5286 _props: rootProps,
5287 _container: null,
5288 _context: context,
5289 _instance: null,
5290 version,
5291 get config() {
5292 return context.config;
5293 },
5294 set config(v) {
5295 {
5296 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
5297 }
5298 },
5299 use(plugin, ...options) {
5300 if (installedPlugins.has(plugin)) {
5301 warn$1(`Plugin has already been applied to target app.`);
5302 }
5303 else if (plugin && isFunction(plugin.install)) {
5304 installedPlugins.add(plugin);
5305 plugin.install(app, ...options);
5306 }
5307 else if (isFunction(plugin)) {
5308 installedPlugins.add(plugin);
5309 plugin(app, ...options);
5310 }
5311 else {
5312 warn$1(`A plugin must either be a function or an object with an "install" ` +
5313 `function.`);
5314 }
5315 return app;
5316 },
5317 mixin(mixin) {
5318 {
5319 if (!context.mixins.includes(mixin)) {
5320 context.mixins.push(mixin);
5321 }
5322 else {
5323 warn$1('Mixin has already been applied to target app' +
5324 (mixin.name ? `: ${mixin.name}` : ''));
5325 }
5326 }
5327 return app;
5328 },
5329 component(name, component) {
5330 {
5331 validateComponentName(name, context.config);
5332 }
5333 if (!component) {
5334 return context.components[name];
5335 }
5336 if (context.components[name]) {
5337 warn$1(`Component "${name}" has already been registered in target app.`);
5338 }
5339 context.components[name] = component;
5340 return app;
5341 },
5342 directive(name, directive) {
5343 {
5344 validateDirectiveName(name);
5345 }
5346 if (!directive) {
5347 return context.directives[name];
5348 }
5349 if (context.directives[name]) {
5350 warn$1(`Directive "${name}" has already been registered in target app.`);
5351 }
5352 context.directives[name] = directive;
5353 return app;
5354 },
5355 mount(rootContainer, isHydrate, isSVG) {
5356 if (!isMounted) {
5357 const vnode = createVNode(rootComponent, rootProps);
5358 // store app context on the root VNode.
5359 // this will be set on the root instance on initial mount.
5360 vnode.appContext = context;
5361 // HMR root reload
5362 {
5363 context.reload = () => {
5364 render(cloneVNode(vnode), rootContainer, isSVG);
5365 };
5366 }
5367 if (isHydrate && hydrate) {
5368 hydrate(vnode, rootContainer);
5369 }
5370 else {
5371 render(vnode, rootContainer, isSVG);
5372 }
5373 isMounted = true;
5374 app._container = rootContainer;
5375 rootContainer.__vue_app__ = app;
5376 {
5377 app._instance = vnode.component;
5378 devtoolsInitApp(app, version);
5379 }
5380 return getExposeProxy(vnode.component) || vnode.component.proxy;
5381 }
5382 else {
5383 warn$1(`App has already been mounted.\n` +
5384 `If you want to remount the same app, move your app creation logic ` +
5385 `into a factory function and create fresh app instances for each ` +
5386 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5387 }
5388 },
5389 unmount() {
5390 if (isMounted) {
5391 render(null, app._container);
5392 {
5393 app._instance = null;
5394 devtoolsUnmountApp(app);
5395 }
5396 delete app._container.__vue_app__;
5397 }
5398 else {
5399 warn$1(`Cannot unmount an app that is not mounted.`);
5400 }
5401 },
5402 provide(key, value) {
5403 if (key in context.provides) {
5404 warn$1(`App already provides property with key "${String(key)}". ` +
5405 `It will be overwritten with the new value.`);
5406 }
5407 // TypeScript doesn't allow symbols as index type
5408 // https://github.com/Microsoft/TypeScript/issues/24587
5409 context.provides[key] = value;
5410 return app;
5411 }
5412 });
5413 return app;
5414 };
5415 }
5416
5417 /**
5418 * Function for handling a template ref
5419 */
5420 function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
5421 if (isArray(rawRef)) {
5422 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
5423 return;
5424 }
5425 if (isAsyncWrapper(vnode) && !isUnmount) {
5426 // when mounting async components, nothing needs to be done,
5427 // because the template ref is forwarded to inner component
5428 return;
5429 }
5430 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
5431 ? getExposeProxy(vnode.component) || vnode.component.proxy
5432 : vnode.el;
5433 const value = isUnmount ? null : refValue;
5434 const { i: owner, r: ref } = rawRef;
5435 if (!owner) {
5436 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
5437 `A vnode with ref must be created inside the render function.`);
5438 return;
5439 }
5440 const oldRef = oldRawRef && oldRawRef.r;
5441 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
5442 const setupState = owner.setupState;
5443 // dynamic ref changed. unset old ref
5444 if (oldRef != null && oldRef !== ref) {
5445 if (isString(oldRef)) {
5446 refs[oldRef] = null;
5447 if (hasOwn(setupState, oldRef)) {
5448 setupState[oldRef] = null;
5449 }
5450 }
5451 else if (isRef(oldRef)) {
5452 oldRef.value = null;
5453 }
5454 }
5455 if (isFunction(ref)) {
5456 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
5457 }
5458 else {
5459 const _isString = isString(ref);
5460 const _isRef = isRef(ref);
5461 if (_isString || _isRef) {
5462 const doSet = () => {
5463 if (rawRef.f) {
5464 const existing = _isString ? refs[ref] : ref.value;
5465 if (isUnmount) {
5466 isArray(existing) && remove(existing, refValue);
5467 }
5468 else {
5469 if (!isArray(existing)) {
5470 if (_isString) {
5471 refs[ref] = [refValue];
5472 }
5473 else {
5474 ref.value = [refValue];
5475 if (rawRef.k)
5476 refs[rawRef.k] = ref.value;
5477 }
5478 }
5479 else if (!existing.includes(refValue)) {
5480 existing.push(refValue);
5481 }
5482 }
5483 }
5484 else if (_isString) {
5485 refs[ref] = value;
5486 if (hasOwn(setupState, ref)) {
5487 setupState[ref] = value;
5488 }
5489 }
5490 else if (isRef(ref)) {
5491 ref.value = value;
5492 if (rawRef.k)
5493 refs[rawRef.k] = value;
5494 }
5495 else {
5496 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5497 }
5498 };
5499 if (value) {
5500 doSet.id = -1;
5501 queuePostRenderEffect(doSet, parentSuspense);
5502 }
5503 else {
5504 doSet();
5505 }
5506 }
5507 else {
5508 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5509 }
5510 }
5511 }
5512
5513 let hasMismatch = false;
5514 const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5515 const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5516 // Note: hydration is DOM-specific
5517 // But we have to place it in core due to tight coupling with core - splitting
5518 // it out creates a ton of unnecessary complexity.
5519 // Hydration also depends on some renderer internal logic which needs to be
5520 // passed in via arguments.
5521 function createHydrationFunctions(rendererInternals) {
5522 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5523 const hydrate = (vnode, container) => {
5524 if (!container.hasChildNodes()) {
5525 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5526 `Performing full mount instead.`);
5527 patch(null, vnode, container);
5528 flushPostFlushCbs();
5529 return;
5530 }
5531 hasMismatch = false;
5532 hydrateNode(container.firstChild, vnode, null, null, null);
5533 flushPostFlushCbs();
5534 if (hasMismatch && !false) {
5535 // this error should show up in production
5536 console.error(`Hydration completed but contains mismatches.`);
5537 }
5538 };
5539 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5540 const isFragmentStart = isComment(node) && node.data === '[';
5541 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5542 const { type, ref, shapeFlag } = vnode;
5543 const domType = node.nodeType;
5544 vnode.el = node;
5545 let nextNode = null;
5546 switch (type) {
5547 case Text:
5548 if (domType !== 3 /* TEXT */) {
5549 nextNode = onMismatch();
5550 }
5551 else {
5552 if (node.data !== vnode.children) {
5553 hasMismatch = true;
5554 warn$1(`Hydration text mismatch:` +
5555 `\n- Client: ${JSON.stringify(node.data)}` +
5556 `\n- Server: ${JSON.stringify(vnode.children)}`);
5557 node.data = vnode.children;
5558 }
5559 nextNode = nextSibling(node);
5560 }
5561 break;
5562 case Comment:
5563 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5564 nextNode = onMismatch();
5565 }
5566 else {
5567 nextNode = nextSibling(node);
5568 }
5569 break;
5570 case Static:
5571 if (domType !== 1 /* ELEMENT */) {
5572 nextNode = onMismatch();
5573 }
5574 else {
5575 // determine anchor, adopt content
5576 nextNode = node;
5577 // if the static vnode has its content stripped during build,
5578 // adopt it from the server-rendered HTML.
5579 const needToAdoptContent = !vnode.children.length;
5580 for (let i = 0; i < vnode.staticCount; i++) {
5581 if (needToAdoptContent)
5582 vnode.children += nextNode.outerHTML;
5583 if (i === vnode.staticCount - 1) {
5584 vnode.anchor = nextNode;
5585 }
5586 nextNode = nextSibling(nextNode);
5587 }
5588 return nextNode;
5589 }
5590 break;
5591 case Fragment:
5592 if (!isFragmentStart) {
5593 nextNode = onMismatch();
5594 }
5595 else {
5596 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5597 }
5598 break;
5599 default:
5600 if (shapeFlag & 1 /* ELEMENT */) {
5601 if (domType !== 1 /* ELEMENT */ ||
5602 vnode.type.toLowerCase() !==
5603 node.tagName.toLowerCase()) {
5604 nextNode = onMismatch();
5605 }
5606 else {
5607 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5608 }
5609 }
5610 else if (shapeFlag & 6 /* COMPONENT */) {
5611 // when setting up the render effect, if the initial vnode already
5612 // has .el set, the component will perform hydration instead of mount
5613 // on its sub-tree.
5614 vnode.slotScopeIds = slotScopeIds;
5615 const container = parentNode(node);
5616 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5617 // component may be async, so in the case of fragments we cannot rely
5618 // on component's rendered output to determine the end of the fragment
5619 // instead, we do a lookahead to find the end anchor node.
5620 nextNode = isFragmentStart
5621 ? locateClosingAsyncAnchor(node)
5622 : nextSibling(node);
5623 // #3787
5624 // if component is async, it may get moved / unmounted before its
5625 // inner component is loaded, so we need to give it a placeholder
5626 // vnode that matches its adopted DOM.
5627 if (isAsyncWrapper(vnode)) {
5628 let subTree;
5629 if (isFragmentStart) {
5630 subTree = createVNode(Fragment);
5631 subTree.anchor = nextNode
5632 ? nextNode.previousSibling
5633 : container.lastChild;
5634 }
5635 else {
5636 subTree =
5637 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5638 }
5639 subTree.el = node;
5640 vnode.component.subTree = subTree;
5641 }
5642 }
5643 else if (shapeFlag & 64 /* TELEPORT */) {
5644 if (domType !== 8 /* COMMENT */) {
5645 nextNode = onMismatch();
5646 }
5647 else {
5648 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5649 }
5650 }
5651 else if (shapeFlag & 128 /* SUSPENSE */) {
5652 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5653 }
5654 else {
5655 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5656 }
5657 }
5658 if (ref != null) {
5659 setRef(ref, null, parentSuspense, vnode);
5660 }
5661 return nextNode;
5662 };
5663 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5664 optimized = optimized || !!vnode.dynamicChildren;
5665 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5666 // #4006 for form elements with non-string v-model value bindings
5667 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5668 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5669 // skip props & children if this is hoisted static nodes
5670 if (forcePatchValue || patchFlag !== -1 /* HOISTED */) {
5671 if (dirs) {
5672 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5673 }
5674 // props
5675 if (props) {
5676 if (forcePatchValue ||
5677 !optimized ||
5678 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5679 for (const key in props) {
5680 if ((forcePatchValue && key.endsWith('value')) ||
5681 (isOn(key) && !isReservedProp(key))) {
5682 patchProp(el, key, null, props[key], false, undefined, parentComponent);
5683 }
5684 }
5685 }
5686 else if (props.onClick) {
5687 // Fast path for click listeners (which is most often) to avoid
5688 // iterating through props.
5689 patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
5690 }
5691 }
5692 // vnode / directive hooks
5693 let vnodeHooks;
5694 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5695 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5696 }
5697 if (dirs) {
5698 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5699 }
5700 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5701 queueEffectWithSuspense(() => {
5702 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5703 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5704 }, parentSuspense);
5705 }
5706 // children
5707 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5708 // skip if element has innerHTML / textContent
5709 !(props && (props.innerHTML || props.textContent))) {
5710 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5711 let hasWarned = false;
5712 while (next) {
5713 hasMismatch = true;
5714 if (!hasWarned) {
5715 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5716 `server rendered element contains more child nodes than client vdom.`);
5717 hasWarned = true;
5718 }
5719 // The SSRed DOM contains more nodes than it should. Remove them.
5720 const cur = next;
5721 next = next.nextSibling;
5722 remove(cur);
5723 }
5724 }
5725 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5726 if (el.textContent !== vnode.children) {
5727 hasMismatch = true;
5728 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5729 `- Client: ${el.textContent}\n` +
5730 `- Server: ${vnode.children}`);
5731 el.textContent = vnode.children;
5732 }
5733 }
5734 }
5735 return el.nextSibling;
5736 };
5737 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5738 optimized = optimized || !!parentVNode.dynamicChildren;
5739 const children = parentVNode.children;
5740 const l = children.length;
5741 let hasWarned = false;
5742 for (let i = 0; i < l; i++) {
5743 const vnode = optimized
5744 ? children[i]
5745 : (children[i] = normalizeVNode(children[i]));
5746 if (node) {
5747 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5748 }
5749 else if (vnode.type === Text && !vnode.children) {
5750 continue;
5751 }
5752 else {
5753 hasMismatch = true;
5754 if (!hasWarned) {
5755 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5756 `server rendered element contains fewer child nodes than client vdom.`);
5757 hasWarned = true;
5758 }
5759 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5760 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5761 }
5762 }
5763 return node;
5764 };
5765 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5766 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5767 if (fragmentSlotScopeIds) {
5768 slotScopeIds = slotScopeIds
5769 ? slotScopeIds.concat(fragmentSlotScopeIds)
5770 : fragmentSlotScopeIds;
5771 }
5772 const container = parentNode(node);
5773 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5774 if (next && isComment(next) && next.data === ']') {
5775 return nextSibling((vnode.anchor = next));
5776 }
5777 else {
5778 // fragment didn't hydrate successfully, since we didn't get a end anchor
5779 // back. This should have led to node/children mismatch warnings.
5780 hasMismatch = true;
5781 // since the anchor is missing, we need to create one and insert it
5782 insert((vnode.anchor = createComment(`]`)), container, next);
5783 return next;
5784 }
5785 };
5786 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5787 hasMismatch = true;
5788 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5789 ? `(text)`
5790 : isComment(node) && node.data === '['
5791 ? `(start of fragment)`
5792 : ``);
5793 vnode.el = null;
5794 if (isFragment) {
5795 // remove excessive fragment nodes
5796 const end = locateClosingAsyncAnchor(node);
5797 while (true) {
5798 const next = nextSibling(node);
5799 if (next && next !== end) {
5800 remove(next);
5801 }
5802 else {
5803 break;
5804 }
5805 }
5806 }
5807 const next = nextSibling(node);
5808 const container = parentNode(node);
5809 remove(node);
5810 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5811 return next;
5812 };
5813 const locateClosingAsyncAnchor = (node) => {
5814 let match = 0;
5815 while (node) {
5816 node = nextSibling(node);
5817 if (node && isComment(node)) {
5818 if (node.data === '[')
5819 match++;
5820 if (node.data === ']') {
5821 if (match === 0) {
5822 return nextSibling(node);
5823 }
5824 else {
5825 match--;
5826 }
5827 }
5828 }
5829 }
5830 return node;
5831 };
5832 return [hydrate, hydrateNode];
5833 }
5834
5835 /* eslint-disable no-restricted-globals */
5836 let supported;
5837 let perf;
5838 function startMeasure(instance, type) {
5839 if (instance.appContext.config.performance && isSupported()) {
5840 perf.mark(`vue-${type}-${instance.uid}`);
5841 }
5842 {
5843 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5844 }
5845 }
5846 function endMeasure(instance, type) {
5847 if (instance.appContext.config.performance && isSupported()) {
5848 const startTag = `vue-${type}-${instance.uid}`;
5849 const endTag = startTag + `:end`;
5850 perf.mark(endTag);
5851 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5852 perf.clearMarks(startTag);
5853 perf.clearMarks(endTag);
5854 }
5855 {
5856 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5857 }
5858 }
5859 function isSupported() {
5860 if (supported !== undefined) {
5861 return supported;
5862 }
5863 if (typeof window !== 'undefined' && window.performance) {
5864 supported = true;
5865 perf = window.performance;
5866 }
5867 else {
5868 supported = false;
5869 }
5870 return supported;
5871 }
5872
5873 const queuePostRenderEffect = queueEffectWithSuspense
5874 ;
5875 /**
5876 * The createRenderer function accepts two generic arguments:
5877 * HostNode and HostElement, corresponding to Node and Element types in the
5878 * host environment. For example, for runtime-dom, HostNode would be the DOM
5879 * `Node` interface and HostElement would be the DOM `Element` interface.
5880 *
5881 * Custom renderers can pass in the platform specific types like this:
5882 *
5883 * ``` js
5884 * const { render, createApp } = createRenderer<Node, Element>({
5885 * patchProp,
5886 * ...nodeOps
5887 * })
5888 * ```
5889 */
5890 function createRenderer(options) {
5891 return baseCreateRenderer(options);
5892 }
5893 // Separate API for creating hydration-enabled renderer.
5894 // Hydration logic is only used when calling this function, making it
5895 // tree-shakable.
5896 function createHydrationRenderer(options) {
5897 return baseCreateRenderer(options, createHydrationFunctions);
5898 }
5899 // implementation
5900 function baseCreateRenderer(options, createHydrationFns) {
5901 const target = getGlobalThis();
5902 target.__VUE__ = true;
5903 {
5904 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
5905 }
5906 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;
5907 // Note: functions inside this closure should use `const xxx = () => {}`
5908 // style in order to prevent being inlined by minifiers.
5909 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5910 if (n1 === n2) {
5911 return;
5912 }
5913 // patching & not same type, unmount old tree
5914 if (n1 && !isSameVNodeType(n1, n2)) {
5915 anchor = getNextHostNode(n1);
5916 unmount(n1, parentComponent, parentSuspense, true);
5917 n1 = null;
5918 }
5919 if (n2.patchFlag === -2 /* BAIL */) {
5920 optimized = false;
5921 n2.dynamicChildren = null;
5922 }
5923 const { type, ref, shapeFlag } = n2;
5924 switch (type) {
5925 case Text:
5926 processText(n1, n2, container, anchor);
5927 break;
5928 case Comment:
5929 processCommentNode(n1, n2, container, anchor);
5930 break;
5931 case Static:
5932 if (n1 == null) {
5933 mountStaticNode(n2, container, anchor, isSVG);
5934 }
5935 else {
5936 patchStaticNode(n1, n2, container, isSVG);
5937 }
5938 break;
5939 case Fragment:
5940 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5941 break;
5942 default:
5943 if (shapeFlag & 1 /* ELEMENT */) {
5944 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5945 }
5946 else if (shapeFlag & 6 /* COMPONENT */) {
5947 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5948 }
5949 else if (shapeFlag & 64 /* TELEPORT */) {
5950 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5951 }
5952 else if (shapeFlag & 128 /* SUSPENSE */) {
5953 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5954 }
5955 else {
5956 warn$1('Invalid VNode type:', type, `(${typeof type})`);
5957 }
5958 }
5959 // set ref
5960 if (ref != null && parentComponent) {
5961 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5962 }
5963 };
5964 const processText = (n1, n2, container, anchor) => {
5965 if (n1 == null) {
5966 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5967 }
5968 else {
5969 const el = (n2.el = n1.el);
5970 if (n2.children !== n1.children) {
5971 hostSetText(el, n2.children);
5972 }
5973 }
5974 };
5975 const processCommentNode = (n1, n2, container, anchor) => {
5976 if (n1 == null) {
5977 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5978 }
5979 else {
5980 // there's no support for dynamic comments
5981 n2.el = n1.el;
5982 }
5983 };
5984 const mountStaticNode = (n2, container, anchor, isSVG) => {
5985 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
5986 };
5987 /**
5988 * Dev / HMR only
5989 */
5990 const patchStaticNode = (n1, n2, container, isSVG) => {
5991 // static nodes are only patched during dev for HMR
5992 if (n2.children !== n1.children) {
5993 const anchor = hostNextSibling(n1.anchor);
5994 // remove existing
5995 removeStaticNode(n1);
5996 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5997 }
5998 else {
5999 n2.el = n1.el;
6000 n2.anchor = n1.anchor;
6001 }
6002 };
6003 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
6004 let next;
6005 while (el && el !== anchor) {
6006 next = hostNextSibling(el);
6007 hostInsert(el, container, nextSibling);
6008 el = next;
6009 }
6010 hostInsert(anchor, container, nextSibling);
6011 };
6012 const removeStaticNode = ({ el, anchor }) => {
6013 let next;
6014 while (el && el !== anchor) {
6015 next = hostNextSibling(el);
6016 hostRemove(el);
6017 el = next;
6018 }
6019 hostRemove(anchor);
6020 };
6021 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6022 isSVG = isSVG || n2.type === 'svg';
6023 if (n1 == null) {
6024 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6025 }
6026 else {
6027 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6028 }
6029 };
6030 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6031 let el;
6032 let vnodeHook;
6033 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
6034 {
6035 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
6036 // mount children first, since some props may rely on child content
6037 // being already rendered, e.g. `<select value>`
6038 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6039 hostSetElementText(el, vnode.children);
6040 }
6041 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6042 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
6043 }
6044 if (dirs) {
6045 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6046 }
6047 // props
6048 if (props) {
6049 for (const key in props) {
6050 if (key !== 'value' && !isReservedProp(key)) {
6051 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6052 }
6053 }
6054 /**
6055 * Special case for setting value on DOM elements:
6056 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
6057 * - it needs to be forced (#1471)
6058 * #2353 proposes adding another renderer option to configure this, but
6059 * the properties affects are so finite it is worth special casing it
6060 * here to reduce the complexity. (Special casing it also should not
6061 * affect non-DOM renderers)
6062 */
6063 if ('value' in props) {
6064 hostPatchProp(el, 'value', null, props.value);
6065 }
6066 if ((vnodeHook = props.onVnodeBeforeMount)) {
6067 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6068 }
6069 }
6070 // scopeId
6071 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
6072 }
6073 {
6074 Object.defineProperty(el, '__vnode', {
6075 value: vnode,
6076 enumerable: false
6077 });
6078 Object.defineProperty(el, '__vueParentComponent', {
6079 value: parentComponent,
6080 enumerable: false
6081 });
6082 }
6083 if (dirs) {
6084 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6085 }
6086 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
6087 // #1689 For inside suspense + suspense resolved case, just call it
6088 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
6089 transition &&
6090 !transition.persisted;
6091 if (needCallTransitionHooks) {
6092 transition.beforeEnter(el);
6093 }
6094 hostInsert(el, container, anchor);
6095 if ((vnodeHook = props && props.onVnodeMounted) ||
6096 needCallTransitionHooks ||
6097 dirs) {
6098 queuePostRenderEffect(() => {
6099 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6100 needCallTransitionHooks && transition.enter(el);
6101 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6102 }, parentSuspense);
6103 }
6104 };
6105 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6106 if (scopeId) {
6107 hostSetScopeId(el, scopeId);
6108 }
6109 if (slotScopeIds) {
6110 for (let i = 0; i < slotScopeIds.length; i++) {
6111 hostSetScopeId(el, slotScopeIds[i]);
6112 }
6113 }
6114 if (parentComponent) {
6115 let subTree = parentComponent.subTree;
6116 if (subTree.patchFlag > 0 &&
6117 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
6118 subTree =
6119 filterSingleRoot(subTree.children) || subTree;
6120 }
6121 if (vnode === subTree) {
6122 const parentVNode = parentComponent.vnode;
6123 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6124 }
6125 }
6126 };
6127 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6128 for (let i = start; i < children.length; i++) {
6129 const child = (children[i] = optimized
6130 ? cloneIfMounted(children[i])
6131 : normalizeVNode(children[i]));
6132 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6133 }
6134 };
6135 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6136 const el = (n2.el = n1.el);
6137 let { patchFlag, dynamicChildren, dirs } = n2;
6138 // #1426 take the old vnode's patch flag into account since user may clone a
6139 // compiler-generated vnode, which de-opts to FULL_PROPS
6140 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
6141 const oldProps = n1.props || EMPTY_OBJ;
6142 const newProps = n2.props || EMPTY_OBJ;
6143 let vnodeHook;
6144 // disable recurse in beforeUpdate hooks
6145 parentComponent && toggleRecurse(parentComponent, false);
6146 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6147 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6148 }
6149 if (dirs) {
6150 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6151 }
6152 parentComponent && toggleRecurse(parentComponent, true);
6153 if (isHmrUpdating) {
6154 // HMR updated, force full diff
6155 patchFlag = 0;
6156 optimized = false;
6157 dynamicChildren = null;
6158 }
6159 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6160 if (dynamicChildren) {
6161 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6162 if (parentComponent && parentComponent.type.__hmrId) {
6163 traverseStaticChildren(n1, n2);
6164 }
6165 }
6166 else if (!optimized) {
6167 // full diff
6168 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6169 }
6170 if (patchFlag > 0) {
6171 // the presence of a patchFlag means this element's render code was
6172 // generated by the compiler and can take the fast path.
6173 // in this path old node and new node are guaranteed to have the same shape
6174 // (i.e. at the exact same position in the source template)
6175 if (patchFlag & 16 /* FULL_PROPS */) {
6176 // element props contain dynamic keys, full diff needed
6177 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6178 }
6179 else {
6180 // class
6181 // this flag is matched when the element has dynamic class bindings.
6182 if (patchFlag & 2 /* CLASS */) {
6183 if (oldProps.class !== newProps.class) {
6184 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6185 }
6186 }
6187 // style
6188 // this flag is matched when the element has dynamic style bindings
6189 if (patchFlag & 4 /* STYLE */) {
6190 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6191 }
6192 // props
6193 // This flag is matched when the element has dynamic prop/attr bindings
6194 // other than class and style. The keys of dynamic prop/attrs are saved for
6195 // faster iteration.
6196 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6197 // bail out and go through a full diff because we need to unset the old key
6198 if (patchFlag & 8 /* PROPS */) {
6199 // if the flag is present then dynamicProps must be non-null
6200 const propsToUpdate = n2.dynamicProps;
6201 for (let i = 0; i < propsToUpdate.length; i++) {
6202 const key = propsToUpdate[i];
6203 const prev = oldProps[key];
6204 const next = newProps[key];
6205 // #1471 force patch value
6206 if (next !== prev || key === 'value') {
6207 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6208 }
6209 }
6210 }
6211 }
6212 // text
6213 // This flag is matched when the element has only dynamic text children.
6214 if (patchFlag & 1 /* TEXT */) {
6215 if (n1.children !== n2.children) {
6216 hostSetElementText(el, n2.children);
6217 }
6218 }
6219 }
6220 else if (!optimized && dynamicChildren == null) {
6221 // unoptimized, full diff
6222 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6223 }
6224 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6225 queuePostRenderEffect(() => {
6226 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6227 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6228 }, parentSuspense);
6229 }
6230 };
6231 // The fast path for blocks.
6232 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6233 for (let i = 0; i < newChildren.length; i++) {
6234 const oldVNode = oldChildren[i];
6235 const newVNode = newChildren[i];
6236 // Determine the container (parent element) for the patch.
6237 const container =
6238 // oldVNode may be an errored async setup() component inside Suspense
6239 // which will not have a mounted element
6240 oldVNode.el &&
6241 // - In the case of a Fragment, we need to provide the actual parent
6242 // of the Fragment itself so it can move its children.
6243 (oldVNode.type === Fragment ||
6244 // - In the case of different nodes, there is going to be a replacement
6245 // which also requires the correct parent container
6246 !isSameVNodeType(oldVNode, newVNode) ||
6247 // - In the case of a component, it could contain anything.
6248 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
6249 ? hostParentNode(oldVNode.el)
6250 : // In other cases, the parent container is not actually used so we
6251 // just pass the block element here to avoid a DOM parentNode call.
6252 fallbackContainer;
6253 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6254 }
6255 };
6256 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6257 if (oldProps !== newProps) {
6258 for (const key in newProps) {
6259 // empty string is not valid prop
6260 if (isReservedProp(key))
6261 continue;
6262 const next = newProps[key];
6263 const prev = oldProps[key];
6264 // defer patching value
6265 if (next !== prev && key !== 'value') {
6266 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6267 }
6268 }
6269 if (oldProps !== EMPTY_OBJ) {
6270 for (const key in oldProps) {
6271 if (!isReservedProp(key) && !(key in newProps)) {
6272 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6273 }
6274 }
6275 }
6276 if ('value' in newProps) {
6277 hostPatchProp(el, 'value', oldProps.value, newProps.value);
6278 }
6279 }
6280 };
6281 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6282 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6283 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6284 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6285 if (isHmrUpdating) {
6286 // HMR updated, force full diff
6287 patchFlag = 0;
6288 optimized = false;
6289 dynamicChildren = null;
6290 }
6291 // check if this is a slot fragment with :slotted scope ids
6292 if (fragmentSlotScopeIds) {
6293 slotScopeIds = slotScopeIds
6294 ? slotScopeIds.concat(fragmentSlotScopeIds)
6295 : fragmentSlotScopeIds;
6296 }
6297 if (n1 == null) {
6298 hostInsert(fragmentStartAnchor, container, anchor);
6299 hostInsert(fragmentEndAnchor, container, anchor);
6300 // a fragment can only have array children
6301 // since they are either generated by the compiler, or implicitly created
6302 // from arrays.
6303 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6304 }
6305 else {
6306 if (patchFlag > 0 &&
6307 patchFlag & 64 /* STABLE_FRAGMENT */ &&
6308 dynamicChildren &&
6309 // #2715 the previous fragment could've been a BAILed one as a result
6310 // of renderSlot() with no valid children
6311 n1.dynamicChildren) {
6312 // a stable fragment (template root or <template v-for>) doesn't need to
6313 // patch children order, but it may contain dynamicChildren.
6314 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6315 if (parentComponent && parentComponent.type.__hmrId) {
6316 traverseStaticChildren(n1, n2);
6317 }
6318 else if (
6319 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6320 // get moved around. Make sure all root level vnodes inherit el.
6321 // #2134 or if it's a component root, it may also get moved around
6322 // as the component is being moved.
6323 n2.key != null ||
6324 (parentComponent && n2 === parentComponent.subTree)) {
6325 traverseStaticChildren(n1, n2, true /* shallow */);
6326 }
6327 }
6328 else {
6329 // keyed / unkeyed, or manual fragments.
6330 // for keyed & unkeyed, since they are compiler generated from v-for,
6331 // each child is guaranteed to be a block so the fragment will never
6332 // have dynamicChildren.
6333 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6334 }
6335 }
6336 };
6337 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6338 n2.slotScopeIds = slotScopeIds;
6339 if (n1 == null) {
6340 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
6341 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6342 }
6343 else {
6344 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6345 }
6346 }
6347 else {
6348 updateComponent(n1, n2, optimized);
6349 }
6350 };
6351 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6352 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6353 if (instance.type.__hmrId) {
6354 registerHMR(instance);
6355 }
6356 {
6357 pushWarningContext(initialVNode);
6358 startMeasure(instance, `mount`);
6359 }
6360 // inject renderer internals for keepAlive
6361 if (isKeepAlive(initialVNode)) {
6362 instance.ctx.renderer = internals;
6363 }
6364 // resolve props and slots for setup context
6365 {
6366 {
6367 startMeasure(instance, `init`);
6368 }
6369 setupComponent(instance);
6370 {
6371 endMeasure(instance, `init`);
6372 }
6373 }
6374 // setup() is async. This component relies on async logic to be resolved
6375 // before proceeding
6376 if (instance.asyncDep) {
6377 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
6378 // Give it a placeholder if this is not hydration
6379 // TODO handle self-defined fallback
6380 if (!initialVNode.el) {
6381 const placeholder = (instance.subTree = createVNode(Comment));
6382 processCommentNode(null, placeholder, container, anchor);
6383 }
6384 return;
6385 }
6386 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
6387 {
6388 popWarningContext();
6389 endMeasure(instance, `mount`);
6390 }
6391 };
6392 const updateComponent = (n1, n2, optimized) => {
6393 const instance = (n2.component = n1.component);
6394 if (shouldUpdateComponent(n1, n2, optimized)) {
6395 if (instance.asyncDep &&
6396 !instance.asyncResolved) {
6397 // async & still pending - just update props and slots
6398 // since the component's reactive effect for render isn't set-up yet
6399 {
6400 pushWarningContext(n2);
6401 }
6402 updateComponentPreRender(instance, n2, optimized);
6403 {
6404 popWarningContext();
6405 }
6406 return;
6407 }
6408 else {
6409 // normal update
6410 instance.next = n2;
6411 // in case the child component is also queued, remove it to avoid
6412 // double updating the same child component in the same flush.
6413 invalidateJob(instance.update);
6414 // instance.update is the reactive effect.
6415 instance.update();
6416 }
6417 }
6418 else {
6419 // no update needed. just copy over properties
6420 n2.component = n1.component;
6421 n2.el = n1.el;
6422 instance.vnode = n2;
6423 }
6424 };
6425 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
6426 const componentUpdateFn = () => {
6427 if (!instance.isMounted) {
6428 let vnodeHook;
6429 const { el, props } = initialVNode;
6430 const { bm, m, parent } = instance;
6431 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
6432 toggleRecurse(instance, false);
6433 // beforeMount hook
6434 if (bm) {
6435 invokeArrayFns(bm);
6436 }
6437 // onVnodeBeforeMount
6438 if (!isAsyncWrapperVNode &&
6439 (vnodeHook = props && props.onVnodeBeforeMount)) {
6440 invokeVNodeHook(vnodeHook, parent, initialVNode);
6441 }
6442 toggleRecurse(instance, true);
6443 if (el && hydrateNode) {
6444 // vnode has adopted host node - perform hydration instead of mount.
6445 const hydrateSubTree = () => {
6446 {
6447 startMeasure(instance, `render`);
6448 }
6449 instance.subTree = renderComponentRoot(instance);
6450 {
6451 endMeasure(instance, `render`);
6452 }
6453 {
6454 startMeasure(instance, `hydrate`);
6455 }
6456 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
6457 {
6458 endMeasure(instance, `hydrate`);
6459 }
6460 };
6461 if (isAsyncWrapperVNode) {
6462 initialVNode.type.__asyncLoader().then(
6463 // note: we are moving the render call into an async callback,
6464 // which means it won't track dependencies - but it's ok because
6465 // a server-rendered async wrapper is already in resolved state
6466 // and it will never need to change.
6467 () => !instance.isUnmounted && hydrateSubTree());
6468 }
6469 else {
6470 hydrateSubTree();
6471 }
6472 }
6473 else {
6474 {
6475 startMeasure(instance, `render`);
6476 }
6477 const subTree = (instance.subTree = renderComponentRoot(instance));
6478 {
6479 endMeasure(instance, `render`);
6480 }
6481 {
6482 startMeasure(instance, `patch`);
6483 }
6484 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
6485 {
6486 endMeasure(instance, `patch`);
6487 }
6488 initialVNode.el = subTree.el;
6489 }
6490 // mounted hook
6491 if (m) {
6492 queuePostRenderEffect(m, parentSuspense);
6493 }
6494 // onVnodeMounted
6495 if (!isAsyncWrapperVNode &&
6496 (vnodeHook = props && props.onVnodeMounted)) {
6497 const scopedInitialVNode = initialVNode;
6498 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
6499 }
6500 // activated hook for keep-alive roots.
6501 // #1742 activated hook must be accessed after first render
6502 // since the hook may be injected by a child keep-alive
6503 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6504 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
6505 }
6506 instance.isMounted = true;
6507 {
6508 devtoolsComponentAdded(instance);
6509 }
6510 // #2458: deference mount-only object parameters to prevent memleaks
6511 initialVNode = container = anchor = null;
6512 }
6513 else {
6514 // updateComponent
6515 // This is triggered by mutation of component's own state (next: null)
6516 // OR parent calling processComponent (next: VNode)
6517 let { next, bu, u, parent, vnode } = instance;
6518 let originNext = next;
6519 let vnodeHook;
6520 {
6521 pushWarningContext(next || instance.vnode);
6522 }
6523 // Disallow component effect recursion during pre-lifecycle hooks.
6524 toggleRecurse(instance, false);
6525 if (next) {
6526 next.el = vnode.el;
6527 updateComponentPreRender(instance, next, optimized);
6528 }
6529 else {
6530 next = vnode;
6531 }
6532 // beforeUpdate hook
6533 if (bu) {
6534 invokeArrayFns(bu);
6535 }
6536 // onVnodeBeforeUpdate
6537 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6538 invokeVNodeHook(vnodeHook, parent, next, vnode);
6539 }
6540 toggleRecurse(instance, true);
6541 // render
6542 {
6543 startMeasure(instance, `render`);
6544 }
6545 const nextTree = renderComponentRoot(instance);
6546 {
6547 endMeasure(instance, `render`);
6548 }
6549 const prevTree = instance.subTree;
6550 instance.subTree = nextTree;
6551 {
6552 startMeasure(instance, `patch`);
6553 }
6554 patch(prevTree, nextTree,
6555 // parent may have changed if it's in a teleport
6556 hostParentNode(prevTree.el),
6557 // anchor may have changed if it's in a fragment
6558 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6559 {
6560 endMeasure(instance, `patch`);
6561 }
6562 next.el = nextTree.el;
6563 if (originNext === null) {
6564 // self-triggered update. In case of HOC, update parent component
6565 // vnode el. HOC is indicated by parent instance's subTree pointing
6566 // to child component's vnode
6567 updateHOCHostEl(instance, nextTree.el);
6568 }
6569 // updated hook
6570 if (u) {
6571 queuePostRenderEffect(u, parentSuspense);
6572 }
6573 // onVnodeUpdated
6574 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6575 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6576 }
6577 {
6578 devtoolsComponentUpdated(instance);
6579 }
6580 {
6581 popWarningContext();
6582 }
6583 }
6584 };
6585 // create reactive effect for rendering
6586 const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6587 ));
6588 const update = (instance.update = effect.run.bind(effect));
6589 update.id = instance.uid;
6590 // allowRecurse
6591 // #1801, #2043 component render effects should allow recursive updates
6592 toggleRecurse(instance, true);
6593 {
6594 effect.onTrack = instance.rtc
6595 ? e => invokeArrayFns(instance.rtc, e)
6596 : void 0;
6597 effect.onTrigger = instance.rtg
6598 ? e => invokeArrayFns(instance.rtg, e)
6599 : void 0;
6600 // @ts-ignore (for scheduler)
6601 update.ownerInstance = instance;
6602 }
6603 update();
6604 };
6605 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6606 nextVNode.component = instance;
6607 const prevProps = instance.vnode.props;
6608 instance.vnode = nextVNode;
6609 instance.next = null;
6610 updateProps(instance, nextVNode.props, prevProps, optimized);
6611 updateSlots(instance, nextVNode.children, optimized);
6612 pauseTracking();
6613 // props update may have triggered pre-flush watchers.
6614 // flush them before the render update.
6615 flushPreFlushCbs(undefined, instance.update);
6616 resetTracking();
6617 };
6618 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6619 const c1 = n1 && n1.children;
6620 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6621 const c2 = n2.children;
6622 const { patchFlag, shapeFlag } = n2;
6623 // fast path
6624 if (patchFlag > 0) {
6625 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6626 // this could be either fully-keyed or mixed (some keyed some not)
6627 // presence of patchFlag means children are guaranteed to be arrays
6628 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6629 return;
6630 }
6631 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6632 // unkeyed
6633 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6634 return;
6635 }
6636 }
6637 // children has 3 possibilities: text, array or no children.
6638 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6639 // text children fast path
6640 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6641 unmountChildren(c1, parentComponent, parentSuspense);
6642 }
6643 if (c2 !== c1) {
6644 hostSetElementText(container, c2);
6645 }
6646 }
6647 else {
6648 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6649 // prev children was array
6650 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6651 // two arrays, cannot assume anything, do full diff
6652 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6653 }
6654 else {
6655 // no new children, just unmount old
6656 unmountChildren(c1, parentComponent, parentSuspense, true);
6657 }
6658 }
6659 else {
6660 // prev children was text OR null
6661 // new children is array OR null
6662 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6663 hostSetElementText(container, '');
6664 }
6665 // mount new if array
6666 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6667 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6668 }
6669 }
6670 }
6671 };
6672 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6673 c1 = c1 || EMPTY_ARR;
6674 c2 = c2 || EMPTY_ARR;
6675 const oldLength = c1.length;
6676 const newLength = c2.length;
6677 const commonLength = Math.min(oldLength, newLength);
6678 let i;
6679 for (i = 0; i < commonLength; i++) {
6680 const nextChild = (c2[i] = optimized
6681 ? cloneIfMounted(c2[i])
6682 : normalizeVNode(c2[i]));
6683 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6684 }
6685 if (oldLength > newLength) {
6686 // remove old
6687 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6688 }
6689 else {
6690 // mount new
6691 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6692 }
6693 };
6694 // can be all-keyed or mixed
6695 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6696 let i = 0;
6697 const l2 = c2.length;
6698 let e1 = c1.length - 1; // prev ending index
6699 let e2 = l2 - 1; // next ending index
6700 // 1. sync from start
6701 // (a b) c
6702 // (a b) d e
6703 while (i <= e1 && i <= e2) {
6704 const n1 = c1[i];
6705 const n2 = (c2[i] = optimized
6706 ? cloneIfMounted(c2[i])
6707 : normalizeVNode(c2[i]));
6708 if (isSameVNodeType(n1, n2)) {
6709 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6710 }
6711 else {
6712 break;
6713 }
6714 i++;
6715 }
6716 // 2. sync from end
6717 // a (b c)
6718 // d e (b c)
6719 while (i <= e1 && i <= e2) {
6720 const n1 = c1[e1];
6721 const n2 = (c2[e2] = optimized
6722 ? cloneIfMounted(c2[e2])
6723 : normalizeVNode(c2[e2]));
6724 if (isSameVNodeType(n1, n2)) {
6725 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6726 }
6727 else {
6728 break;
6729 }
6730 e1--;
6731 e2--;
6732 }
6733 // 3. common sequence + mount
6734 // (a b)
6735 // (a b) c
6736 // i = 2, e1 = 1, e2 = 2
6737 // (a b)
6738 // c (a b)
6739 // i = 0, e1 = -1, e2 = 0
6740 if (i > e1) {
6741 if (i <= e2) {
6742 const nextPos = e2 + 1;
6743 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6744 while (i <= e2) {
6745 patch(null, (c2[i] = optimized
6746 ? cloneIfMounted(c2[i])
6747 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6748 i++;
6749 }
6750 }
6751 }
6752 // 4. common sequence + unmount
6753 // (a b) c
6754 // (a b)
6755 // i = 2, e1 = 2, e2 = 1
6756 // a (b c)
6757 // (b c)
6758 // i = 0, e1 = 0, e2 = -1
6759 else if (i > e2) {
6760 while (i <= e1) {
6761 unmount(c1[i], parentComponent, parentSuspense, true);
6762 i++;
6763 }
6764 }
6765 // 5. unknown sequence
6766 // [i ... e1 + 1]: a b [c d e] f g
6767 // [i ... e2 + 1]: a b [e d c h] f g
6768 // i = 2, e1 = 4, e2 = 5
6769 else {
6770 const s1 = i; // prev starting index
6771 const s2 = i; // next starting index
6772 // 5.1 build key:index map for newChildren
6773 const keyToNewIndexMap = new Map();
6774 for (i = s2; i <= e2; i++) {
6775 const nextChild = (c2[i] = optimized
6776 ? cloneIfMounted(c2[i])
6777 : normalizeVNode(c2[i]));
6778 if (nextChild.key != null) {
6779 if (keyToNewIndexMap.has(nextChild.key)) {
6780 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6781 }
6782 keyToNewIndexMap.set(nextChild.key, i);
6783 }
6784 }
6785 // 5.2 loop through old children left to be patched and try to patch
6786 // matching nodes & remove nodes that are no longer present
6787 let j;
6788 let patched = 0;
6789 const toBePatched = e2 - s2 + 1;
6790 let moved = false;
6791 // used to track whether any node has moved
6792 let maxNewIndexSoFar = 0;
6793 // works as Map<newIndex, oldIndex>
6794 // Note that oldIndex is offset by +1
6795 // and oldIndex = 0 is a special value indicating the new node has
6796 // no corresponding old node.
6797 // used for determining longest stable subsequence
6798 const newIndexToOldIndexMap = new Array(toBePatched);
6799 for (i = 0; i < toBePatched; i++)
6800 newIndexToOldIndexMap[i] = 0;
6801 for (i = s1; i <= e1; i++) {
6802 const prevChild = c1[i];
6803 if (patched >= toBePatched) {
6804 // all new children have been patched so this can only be a removal
6805 unmount(prevChild, parentComponent, parentSuspense, true);
6806 continue;
6807 }
6808 let newIndex;
6809 if (prevChild.key != null) {
6810 newIndex = keyToNewIndexMap.get(prevChild.key);
6811 }
6812 else {
6813 // key-less node, try to locate a key-less node of the same type
6814 for (j = s2; j <= e2; j++) {
6815 if (newIndexToOldIndexMap[j - s2] === 0 &&
6816 isSameVNodeType(prevChild, c2[j])) {
6817 newIndex = j;
6818 break;
6819 }
6820 }
6821 }
6822 if (newIndex === undefined) {
6823 unmount(prevChild, parentComponent, parentSuspense, true);
6824 }
6825 else {
6826 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6827 if (newIndex >= maxNewIndexSoFar) {
6828 maxNewIndexSoFar = newIndex;
6829 }
6830 else {
6831 moved = true;
6832 }
6833 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6834 patched++;
6835 }
6836 }
6837 // 5.3 move and mount
6838 // generate longest stable subsequence only when nodes have moved
6839 const increasingNewIndexSequence = moved
6840 ? getSequence(newIndexToOldIndexMap)
6841 : EMPTY_ARR;
6842 j = increasingNewIndexSequence.length - 1;
6843 // looping backwards so that we can use last patched node as anchor
6844 for (i = toBePatched - 1; i >= 0; i--) {
6845 const nextIndex = s2 + i;
6846 const nextChild = c2[nextIndex];
6847 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6848 if (newIndexToOldIndexMap[i] === 0) {
6849 // mount new
6850 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6851 }
6852 else if (moved) {
6853 // move if:
6854 // There is no stable subsequence (e.g. a reverse)
6855 // OR current node is not among the stable sequence
6856 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6857 move(nextChild, container, anchor, 2 /* REORDER */);
6858 }
6859 else {
6860 j--;
6861 }
6862 }
6863 }
6864 }
6865 };
6866 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6867 const { el, type, transition, children, shapeFlag } = vnode;
6868 if (shapeFlag & 6 /* COMPONENT */) {
6869 move(vnode.component.subTree, container, anchor, moveType);
6870 return;
6871 }
6872 if (shapeFlag & 128 /* SUSPENSE */) {
6873 vnode.suspense.move(container, anchor, moveType);
6874 return;
6875 }
6876 if (shapeFlag & 64 /* TELEPORT */) {
6877 type.move(vnode, container, anchor, internals);
6878 return;
6879 }
6880 if (type === Fragment) {
6881 hostInsert(el, container, anchor);
6882 for (let i = 0; i < children.length; i++) {
6883 move(children[i], container, anchor, moveType);
6884 }
6885 hostInsert(vnode.anchor, container, anchor);
6886 return;
6887 }
6888 if (type === Static) {
6889 moveStaticNode(vnode, container, anchor);
6890 return;
6891 }
6892 // single nodes
6893 const needTransition = moveType !== 2 /* REORDER */ &&
6894 shapeFlag & 1 /* ELEMENT */ &&
6895 transition;
6896 if (needTransition) {
6897 if (moveType === 0 /* ENTER */) {
6898 transition.beforeEnter(el);
6899 hostInsert(el, container, anchor);
6900 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6901 }
6902 else {
6903 const { leave, delayLeave, afterLeave } = transition;
6904 const remove = () => hostInsert(el, container, anchor);
6905 const performLeave = () => {
6906 leave(el, () => {
6907 remove();
6908 afterLeave && afterLeave();
6909 });
6910 };
6911 if (delayLeave) {
6912 delayLeave(el, remove, performLeave);
6913 }
6914 else {
6915 performLeave();
6916 }
6917 }
6918 }
6919 else {
6920 hostInsert(el, container, anchor);
6921 }
6922 };
6923 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6924 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6925 // unset ref
6926 if (ref != null) {
6927 setRef(ref, null, parentSuspense, vnode, true);
6928 }
6929 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6930 parentComponent.ctx.deactivate(vnode);
6931 return;
6932 }
6933 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6934 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6935 let vnodeHook;
6936 if (shouldInvokeVnodeHook &&
6937 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6938 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6939 }
6940 if (shapeFlag & 6 /* COMPONENT */) {
6941 unmountComponent(vnode.component, parentSuspense, doRemove);
6942 }
6943 else {
6944 if (shapeFlag & 128 /* SUSPENSE */) {
6945 vnode.suspense.unmount(parentSuspense, doRemove);
6946 return;
6947 }
6948 if (shouldInvokeDirs) {
6949 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6950 }
6951 if (shapeFlag & 64 /* TELEPORT */) {
6952 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6953 }
6954 else if (dynamicChildren &&
6955 // #1153: fast path should not be taken for non-stable (v-for) fragments
6956 (type !== Fragment ||
6957 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6958 // fast path for block nodes: only need to unmount dynamic children.
6959 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6960 }
6961 else if ((type === Fragment &&
6962 patchFlag &
6963 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
6964 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6965 unmountChildren(children, parentComponent, parentSuspense);
6966 }
6967 if (doRemove) {
6968 remove(vnode);
6969 }
6970 }
6971 if ((shouldInvokeVnodeHook &&
6972 (vnodeHook = props && props.onVnodeUnmounted)) ||
6973 shouldInvokeDirs) {
6974 queuePostRenderEffect(() => {
6975 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6976 shouldInvokeDirs &&
6977 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6978 }, parentSuspense);
6979 }
6980 };
6981 const remove = vnode => {
6982 const { type, el, anchor, transition } = vnode;
6983 if (type === Fragment) {
6984 removeFragment(el, anchor);
6985 return;
6986 }
6987 if (type === Static) {
6988 removeStaticNode(vnode);
6989 return;
6990 }
6991 const performRemove = () => {
6992 hostRemove(el);
6993 if (transition && !transition.persisted && transition.afterLeave) {
6994 transition.afterLeave();
6995 }
6996 };
6997 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6998 transition &&
6999 !transition.persisted) {
7000 const { leave, delayLeave } = transition;
7001 const performLeave = () => leave(el, performRemove);
7002 if (delayLeave) {
7003 delayLeave(vnode.el, performRemove, performLeave);
7004 }
7005 else {
7006 performLeave();
7007 }
7008 }
7009 else {
7010 performRemove();
7011 }
7012 };
7013 const removeFragment = (cur, end) => {
7014 // For fragments, directly remove all contained DOM nodes.
7015 // (fragment child nodes cannot have transition)
7016 let next;
7017 while (cur !== end) {
7018 next = hostNextSibling(cur);
7019 hostRemove(cur);
7020 cur = next;
7021 }
7022 hostRemove(end);
7023 };
7024 const unmountComponent = (instance, parentSuspense, doRemove) => {
7025 if (instance.type.__hmrId) {
7026 unregisterHMR(instance);
7027 }
7028 const { bum, scope, update, subTree, um } = instance;
7029 // beforeUnmount hook
7030 if (bum) {
7031 invokeArrayFns(bum);
7032 }
7033 // stop effects in component scope
7034 scope.stop();
7035 // update may be null if a component is unmounted before its async
7036 // setup has resolved.
7037 if (update) {
7038 // so that scheduler will no longer invoke it
7039 update.active = false;
7040 unmount(subTree, instance, parentSuspense, doRemove);
7041 }
7042 // unmounted hook
7043 if (um) {
7044 queuePostRenderEffect(um, parentSuspense);
7045 }
7046 queuePostRenderEffect(() => {
7047 instance.isUnmounted = true;
7048 }, parentSuspense);
7049 // A component with async dep inside a pending suspense is unmounted before
7050 // its async dep resolves. This should remove the dep from the suspense, and
7051 // cause the suspense to resolve immediately if that was the last dep.
7052 if (parentSuspense &&
7053 parentSuspense.pendingBranch &&
7054 !parentSuspense.isUnmounted &&
7055 instance.asyncDep &&
7056 !instance.asyncResolved &&
7057 instance.suspenseId === parentSuspense.pendingId) {
7058 parentSuspense.deps--;
7059 if (parentSuspense.deps === 0) {
7060 parentSuspense.resolve();
7061 }
7062 }
7063 {
7064 devtoolsComponentRemoved(instance);
7065 }
7066 };
7067 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
7068 for (let i = start; i < children.length; i++) {
7069 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
7070 }
7071 };
7072 const getNextHostNode = vnode => {
7073 if (vnode.shapeFlag & 6 /* COMPONENT */) {
7074 return getNextHostNode(vnode.component.subTree);
7075 }
7076 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
7077 return vnode.suspense.next();
7078 }
7079 return hostNextSibling((vnode.anchor || vnode.el));
7080 };
7081 const render = (vnode, container, isSVG) => {
7082 if (vnode == null) {
7083 if (container._vnode) {
7084 unmount(container._vnode, null, null, true);
7085 }
7086 }
7087 else {
7088 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
7089 }
7090 flushPostFlushCbs();
7091 container._vnode = vnode;
7092 };
7093 const internals = {
7094 p: patch,
7095 um: unmount,
7096 m: move,
7097 r: remove,
7098 mt: mountComponent,
7099 mc: mountChildren,
7100 pc: patchChildren,
7101 pbc: patchBlockChildren,
7102 n: getNextHostNode,
7103 o: options
7104 };
7105 let hydrate;
7106 let hydrateNode;
7107 if (createHydrationFns) {
7108 [hydrate, hydrateNode] = createHydrationFns(internals);
7109 }
7110 return {
7111 render,
7112 hydrate,
7113 createApp: createAppAPI(render, hydrate)
7114 };
7115 }
7116 function toggleRecurse({ effect, update }, allowed) {
7117 effect.allowRecurse = update.allowRecurse = allowed;
7118 }
7119 /**
7120 * #1156
7121 * When a component is HMR-enabled, we need to make sure that all static nodes
7122 * inside a block also inherit the DOM element from the previous tree so that
7123 * HMR updates (which are full updates) can retrieve the element for patching.
7124 *
7125 * #2080
7126 * Inside keyed `template` fragment static children, if a fragment is moved,
7127 * the children will always be moved. Therefore, in order to ensure correct move
7128 * position, el should be inherited from previous nodes.
7129 */
7130 function traverseStaticChildren(n1, n2, shallow = false) {
7131 const ch1 = n1.children;
7132 const ch2 = n2.children;
7133 if (isArray(ch1) && isArray(ch2)) {
7134 for (let i = 0; i < ch1.length; i++) {
7135 // this is only called in the optimized path so array children are
7136 // guaranteed to be vnodes
7137 const c1 = ch1[i];
7138 let c2 = ch2[i];
7139 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
7140 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
7141 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7142 c2.el = c1.el;
7143 }
7144 if (!shallow)
7145 traverseStaticChildren(c1, c2);
7146 }
7147 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7148 // would have received .el during block patch)
7149 if (c2.type === Comment && !c2.el) {
7150 c2.el = c1.el;
7151 }
7152 }
7153 }
7154 }
7155 // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7156 function getSequence(arr) {
7157 const p = arr.slice();
7158 const result = [0];
7159 let i, j, u, v, c;
7160 const len = arr.length;
7161 for (i = 0; i < len; i++) {
7162 const arrI = arr[i];
7163 if (arrI !== 0) {
7164 j = result[result.length - 1];
7165 if (arr[j] < arrI) {
7166 p[i] = j;
7167 result.push(i);
7168 continue;
7169 }
7170 u = 0;
7171 v = result.length - 1;
7172 while (u < v) {
7173 c = (u + v) >> 1;
7174 if (arr[result[c]] < arrI) {
7175 u = c + 1;
7176 }
7177 else {
7178 v = c;
7179 }
7180 }
7181 if (arrI < arr[result[u]]) {
7182 if (u > 0) {
7183 p[i] = result[u - 1];
7184 }
7185 result[u] = i;
7186 }
7187 }
7188 }
7189 u = result.length;
7190 v = result[u - 1];
7191 while (u-- > 0) {
7192 result[u] = v;
7193 v = p[v];
7194 }
7195 return result;
7196 }
7197
7198 const isTeleport = (type) => type.__isTeleport;
7199 const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7200 const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7201 const resolveTarget = (props, select) => {
7202 const targetSelector = props && props.to;
7203 if (isString(targetSelector)) {
7204 if (!select) {
7205 warn$1(`Current renderer does not support string target for Teleports. ` +
7206 `(missing querySelector renderer option)`);
7207 return null;
7208 }
7209 else {
7210 const target = select(targetSelector);
7211 if (!target) {
7212 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7213 `Note the target element must exist before the component is mounted - ` +
7214 `i.e. the target cannot be rendered by the component itself, and ` +
7215 `ideally should be outside of the entire Vue component tree.`);
7216 }
7217 return target;
7218 }
7219 }
7220 else {
7221 if (!targetSelector && !isTeleportDisabled(props)) {
7222 warn$1(`Invalid Teleport target: ${targetSelector}`);
7223 }
7224 return targetSelector;
7225 }
7226 };
7227 const TeleportImpl = {
7228 __isTeleport: true,
7229 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7230 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7231 const disabled = isTeleportDisabled(n2.props);
7232 let { shapeFlag, children, dynamicChildren } = n2;
7233 // #3302
7234 // HMR updated, force full diff
7235 if (isHmrUpdating) {
7236 optimized = false;
7237 dynamicChildren = null;
7238 }
7239 if (n1 == null) {
7240 // insert anchors in the main view
7241 const placeholder = (n2.el = createComment('teleport start')
7242 );
7243 const mainAnchor = (n2.anchor = createComment('teleport end')
7244 );
7245 insert(placeholder, container, anchor);
7246 insert(mainAnchor, container, anchor);
7247 const target = (n2.target = resolveTarget(n2.props, querySelector));
7248 const targetAnchor = (n2.targetAnchor = createText(''));
7249 if (target) {
7250 insert(targetAnchor, target);
7251 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7252 isSVG = isSVG || isTargetSVG(target);
7253 }
7254 else if (!disabled) {
7255 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
7256 }
7257 const mount = (container, anchor) => {
7258 // Teleport *always* has Array children. This is enforced in both the
7259 // compiler and vnode children normalization.
7260 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7261 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7262 }
7263 };
7264 if (disabled) {
7265 mount(container, mainAnchor);
7266 }
7267 else if (target) {
7268 mount(target, targetAnchor);
7269 }
7270 }
7271 else {
7272 // update content
7273 n2.el = n1.el;
7274 const mainAnchor = (n2.anchor = n1.anchor);
7275 const target = (n2.target = n1.target);
7276 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7277 const wasDisabled = isTeleportDisabled(n1.props);
7278 const currentContainer = wasDisabled ? container : target;
7279 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7280 isSVG = isSVG || isTargetSVG(target);
7281 if (dynamicChildren) {
7282 // fast path when the teleport happens to be a block root
7283 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7284 // even in block tree mode we need to make sure all root-level nodes
7285 // in the teleport inherit previous DOM references so that they can
7286 // be moved in future patches.
7287 traverseStaticChildren(n1, n2, true);
7288 }
7289 else if (!optimized) {
7290 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7291 }
7292 if (disabled) {
7293 if (!wasDisabled) {
7294 // enabled -> disabled
7295 // move into main container
7296 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
7297 }
7298 }
7299 else {
7300 // target changed
7301 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7302 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7303 if (nextTarget) {
7304 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
7305 }
7306 else {
7307 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
7308 }
7309 }
7310 else if (wasDisabled) {
7311 // disabled -> enabled
7312 // move into teleport target
7313 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
7314 }
7315 }
7316 }
7317 },
7318 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7319 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7320 if (target) {
7321 hostRemove(targetAnchor);
7322 }
7323 // an unmounted teleport should always remove its children if not disabled
7324 if (doRemove || !isTeleportDisabled(props)) {
7325 hostRemove(anchor);
7326 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7327 for (let i = 0; i < children.length; i++) {
7328 const child = children[i];
7329 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7330 }
7331 }
7332 }
7333 },
7334 move: moveTeleport,
7335 hydrate: hydrateTeleport
7336 };
7337 function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
7338 // move target anchor if this is a target change.
7339 if (moveType === 0 /* TARGET_CHANGE */) {
7340 insert(vnode.targetAnchor, container, parentAnchor);
7341 }
7342 const { el, anchor, shapeFlag, children, props } = vnode;
7343 const isReorder = moveType === 2 /* REORDER */;
7344 // move main view anchor if this is a re-order.
7345 if (isReorder) {
7346 insert(el, container, parentAnchor);
7347 }
7348 // if this is a re-order and teleport is enabled (content is in target)
7349 // do not move children. So the opposite is: only move children if this
7350 // is not a reorder, or the teleport is disabled
7351 if (!isReorder || isTeleportDisabled(props)) {
7352 // Teleport has either Array children or no children.
7353 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7354 for (let i = 0; i < children.length; i++) {
7355 move(children[i], container, parentAnchor, 2 /* REORDER */);
7356 }
7357 }
7358 }
7359 // move main view anchor if this is a re-order.
7360 if (isReorder) {
7361 insert(anchor, container, parentAnchor);
7362 }
7363 }
7364 function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
7365 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
7366 if (target) {
7367 // if multiple teleports rendered to the same target element, we need to
7368 // pick up from where the last teleport finished instead of the first node
7369 const targetNode = target._lpa || target.firstChild;
7370 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
7371 if (isTeleportDisabled(vnode.props)) {
7372 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
7373 vnode.targetAnchor = targetNode;
7374 }
7375 else {
7376 vnode.anchor = nextSibling(node);
7377 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
7378 }
7379 target._lpa =
7380 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
7381 }
7382 }
7383 return vnode.anchor && nextSibling(vnode.anchor);
7384 }
7385 // Force-casted public typing for h and TSX props inference
7386 const Teleport = TeleportImpl;
7387
7388 const COMPONENTS = 'components';
7389 const DIRECTIVES = 'directives';
7390 /**
7391 * @private
7392 */
7393 function resolveComponent(name, maybeSelfReference) {
7394 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
7395 }
7396 const NULL_DYNAMIC_COMPONENT = Symbol();
7397 /**
7398 * @private
7399 */
7400 function resolveDynamicComponent(component) {
7401 if (isString(component)) {
7402 return resolveAsset(COMPONENTS, component, false) || component;
7403 }
7404 else {
7405 // invalid types will fallthrough to createVNode and raise warning
7406 return (component || NULL_DYNAMIC_COMPONENT);
7407 }
7408 }
7409 /**
7410 * @private
7411 */
7412 function resolveDirective(name) {
7413 return resolveAsset(DIRECTIVES, name);
7414 }
7415 // implementation
7416 function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
7417 const instance = currentRenderingInstance || currentInstance;
7418 if (instance) {
7419 const Component = instance.type;
7420 // explicit self name has highest priority
7421 if (type === COMPONENTS) {
7422 const selfName = getComponentName(Component);
7423 if (selfName &&
7424 (selfName === name ||
7425 selfName === camelize(name) ||
7426 selfName === capitalize(camelize(name)))) {
7427 return Component;
7428 }
7429 }
7430 const res =
7431 // local registration
7432 // check instance[type] first which is resolved for options API
7433 resolve(instance[type] || Component[type], name) ||
7434 // global registration
7435 resolve(instance.appContext[type], name);
7436 if (!res && maybeSelfReference) {
7437 // fallback to implicit self-reference
7438 return Component;
7439 }
7440 if (warnMissing && !res) {
7441 const extra = type === COMPONENTS
7442 ? `\nIf this is a native custom element, make sure to exclude it from ` +
7443 `component resolution via compilerOptions.isCustomElement.`
7444 : ``;
7445 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
7446 }
7447 return res;
7448 }
7449 else {
7450 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7451 `can only be used in render() or setup().`);
7452 }
7453 }
7454 function resolve(registry, name) {
7455 return (registry &&
7456 (registry[name] ||
7457 registry[camelize(name)] ||
7458 registry[capitalize(camelize(name))]));
7459 }
7460
7461 const Fragment = Symbol('Fragment' );
7462 const Text = Symbol('Text' );
7463 const Comment = Symbol('Comment' );
7464 const Static = Symbol('Static' );
7465 // Since v-if and v-for are the two possible ways node structure can dynamically
7466 // change, once we consider v-if branches and each v-for fragment a block, we
7467 // can divide a template into nested blocks, and within each block the node
7468 // structure would be stable. This allows us to skip most children diffing
7469 // and only worry about the dynamic nodes (indicated by patch flags).
7470 const blockStack = [];
7471 let currentBlock = null;
7472 /**
7473 * Open a block.
7474 * This must be called before `createBlock`. It cannot be part of `createBlock`
7475 * because the children of the block are evaluated before `createBlock` itself
7476 * is called. The generated code typically looks like this:
7477 *
7478 * ```js
7479 * function render() {
7480 * return (openBlock(),createBlock('div', null, [...]))
7481 * }
7482 * ```
7483 * disableTracking is true when creating a v-for fragment block, since a v-for
7484 * fragment always diffs its children.
7485 *
7486 * @private
7487 */
7488 function openBlock(disableTracking = false) {
7489 blockStack.push((currentBlock = disableTracking ? null : []));
7490 }
7491 function closeBlock() {
7492 blockStack.pop();
7493 currentBlock = blockStack[blockStack.length - 1] || null;
7494 }
7495 // Whether we should be tracking dynamic child nodes inside a block.
7496 // Only tracks when this value is > 0
7497 // We are not using a simple boolean because this value may need to be
7498 // incremented/decremented by nested usage of v-once (see below)
7499 let isBlockTreeEnabled = 1;
7500 /**
7501 * Block tracking sometimes needs to be disabled, for example during the
7502 * creation of a tree that needs to be cached by v-once. The compiler generates
7503 * code like this:
7504 *
7505 * ``` js
7506 * _cache[1] || (
7507 * setBlockTracking(-1),
7508 * _cache[1] = createVNode(...),
7509 * setBlockTracking(1),
7510 * _cache[1]
7511 * )
7512 * ```
7513 *
7514 * @private
7515 */
7516 function setBlockTracking(value) {
7517 isBlockTreeEnabled += value;
7518 }
7519 function setupBlock(vnode) {
7520 // save current block children on the block vnode
7521 vnode.dynamicChildren =
7522 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7523 // close block
7524 closeBlock();
7525 // a block is always going to be patched, so track it as a child of its
7526 // parent block
7527 if (isBlockTreeEnabled > 0 && currentBlock) {
7528 currentBlock.push(vnode);
7529 }
7530 return vnode;
7531 }
7532 /**
7533 * @private
7534 */
7535 function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7536 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7537 }
7538 /**
7539 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7540 * A block root keeps track of dynamic nodes within the block in the
7541 * `dynamicChildren` array.
7542 *
7543 * @private
7544 */
7545 function createBlock(type, props, children, patchFlag, dynamicProps) {
7546 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7547 }
7548 function isVNode(value) {
7549 return value ? value.__v_isVNode === true : false;
7550 }
7551 function isSameVNodeType(n1, n2) {
7552 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7553 hmrDirtyComponents.has(n2.type)) {
7554 // HMR only: if the component has been hot-updated, force a reload.
7555 return false;
7556 }
7557 return n1.type === n2.type && n1.key === n2.key;
7558 }
7559 let vnodeArgsTransformer;
7560 /**
7561 * Internal API for registering an arguments transform for createVNode
7562 * used for creating stubs in the test-utils
7563 * It is *internal* but needs to be exposed for test-utils to pick up proper
7564 * typings
7565 */
7566 function transformVNodeArgs(transformer) {
7567 vnodeArgsTransformer = transformer;
7568 }
7569 const createVNodeWithArgsTransform = (...args) => {
7570 return _createVNode(...(vnodeArgsTransformer
7571 ? vnodeArgsTransformer(args, currentRenderingInstance)
7572 : args));
7573 };
7574 const InternalObjectKey = `__vInternal`;
7575 const normalizeKey = ({ key }) => key != null ? key : null;
7576 const normalizeRef = ({ ref, ref_key, ref_for }) => {
7577 return (ref != null
7578 ? isString(ref) || isRef(ref) || isFunction(ref)
7579 ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
7580 : ref
7581 : null);
7582 };
7583 function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7584 const vnode = {
7585 __v_isVNode: true,
7586 __v_skip: true,
7587 type,
7588 props,
7589 key: props && normalizeKey(props),
7590 ref: props && normalizeRef(props),
7591 scopeId: currentScopeId,
7592 slotScopeIds: null,
7593 children,
7594 component: null,
7595 suspense: null,
7596 ssContent: null,
7597 ssFallback: null,
7598 dirs: null,
7599 transition: null,
7600 el: null,
7601 anchor: null,
7602 target: null,
7603 targetAnchor: null,
7604 staticCount: 0,
7605 shapeFlag,
7606 patchFlag,
7607 dynamicProps,
7608 dynamicChildren: null,
7609 appContext: null
7610 };
7611 if (needFullChildrenNormalization) {
7612 normalizeChildren(vnode, children);
7613 // normalize suspense children
7614 if (shapeFlag & 128 /* SUSPENSE */) {
7615 type.normalize(vnode);
7616 }
7617 }
7618 else if (children) {
7619 // compiled element vnode - if children is passed, only possible types are
7620 // string or Array.
7621 vnode.shapeFlag |= isString(children)
7622 ? 8 /* TEXT_CHILDREN */
7623 : 16 /* ARRAY_CHILDREN */;
7624 }
7625 // validate key
7626 if (vnode.key !== vnode.key) {
7627 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7628 }
7629 // track vnode for block tree
7630 if (isBlockTreeEnabled > 0 &&
7631 // avoid a block node from tracking itself
7632 !isBlockNode &&
7633 // has current parent block
7634 currentBlock &&
7635 // presence of a patch flag indicates this node needs patching on updates.
7636 // component nodes also should always be patched, because even if the
7637 // component doesn't need to update, it needs to persist the instance on to
7638 // the next vnode so that it can be properly unmounted later.
7639 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7640 // the EVENTS flag is only for hydration and if it is the only flag, the
7641 // vnode should not be considered dynamic due to handler caching.
7642 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7643 currentBlock.push(vnode);
7644 }
7645 return vnode;
7646 }
7647 const createVNode = (createVNodeWithArgsTransform );
7648 function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7649 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7650 if (!type) {
7651 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7652 }
7653 type = Comment;
7654 }
7655 if (isVNode(type)) {
7656 // createVNode receiving an existing vnode. This happens in cases like
7657 // <component :is="vnode"/>
7658 // #2078 make sure to merge refs during the clone instead of overwriting it
7659 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7660 if (children) {
7661 normalizeChildren(cloned, children);
7662 }
7663 return cloned;
7664 }
7665 // class component normalization.
7666 if (isClassComponent(type)) {
7667 type = type.__vccOpts;
7668 }
7669 // class & style normalization.
7670 if (props) {
7671 // for reactive or proxy objects, we need to clone it to enable mutation.
7672 props = guardReactiveProps(props);
7673 let { class: klass, style } = props;
7674 if (klass && !isString(klass)) {
7675 props.class = normalizeClass(klass);
7676 }
7677 if (isObject(style)) {
7678 // reactive state objects need to be cloned since they are likely to be
7679 // mutated
7680 if (isProxy(style) && !isArray(style)) {
7681 style = extend({}, style);
7682 }
7683 props.style = normalizeStyle(style);
7684 }
7685 }
7686 // encode the vnode type information into a bitmap
7687 const shapeFlag = isString(type)
7688 ? 1 /* ELEMENT */
7689 : isSuspense(type)
7690 ? 128 /* SUSPENSE */
7691 : isTeleport(type)
7692 ? 64 /* TELEPORT */
7693 : isObject(type)
7694 ? 4 /* STATEFUL_COMPONENT */
7695 : isFunction(type)
7696 ? 2 /* FUNCTIONAL_COMPONENT */
7697 : 0;
7698 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7699 type = toRaw(type);
7700 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7701 `lead to unnecessary performance overhead, and should be avoided by ` +
7702 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7703 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7704 }
7705 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7706 }
7707 function guardReactiveProps(props) {
7708 if (!props)
7709 return null;
7710 return isProxy(props) || InternalObjectKey in props
7711 ? extend({}, props)
7712 : props;
7713 }
7714 function cloneVNode(vnode, extraProps, mergeRef = false) {
7715 // This is intentionally NOT using spread or extend to avoid the runtime
7716 // key enumeration cost.
7717 const { props, ref, patchFlag, children } = vnode;
7718 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7719 const cloned = {
7720 __v_isVNode: true,
7721 __v_skip: true,
7722 type: vnode.type,
7723 props: mergedProps,
7724 key: mergedProps && normalizeKey(mergedProps),
7725 ref: extraProps && extraProps.ref
7726 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7727 // if the vnode itself already has a ref, cloneVNode will need to merge
7728 // the refs so the single vnode can be set on multiple refs
7729 mergeRef && ref
7730 ? isArray(ref)
7731 ? ref.concat(normalizeRef(extraProps))
7732 : [ref, normalizeRef(extraProps)]
7733 : normalizeRef(extraProps)
7734 : ref,
7735 scopeId: vnode.scopeId,
7736 slotScopeIds: vnode.slotScopeIds,
7737 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7738 ? children.map(deepCloneVNode)
7739 : children,
7740 target: vnode.target,
7741 targetAnchor: vnode.targetAnchor,
7742 staticCount: vnode.staticCount,
7743 shapeFlag: vnode.shapeFlag,
7744 // if the vnode is cloned with extra props, we can no longer assume its
7745 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7746 // note: preserve flag for fragments since they use the flag for children
7747 // fast paths only.
7748 patchFlag: extraProps && vnode.type !== Fragment
7749 ? patchFlag === -1 // hoisted node
7750 ? 16 /* FULL_PROPS */
7751 : patchFlag | 16 /* FULL_PROPS */
7752 : patchFlag,
7753 dynamicProps: vnode.dynamicProps,
7754 dynamicChildren: vnode.dynamicChildren,
7755 appContext: vnode.appContext,
7756 dirs: vnode.dirs,
7757 transition: vnode.transition,
7758 // These should technically only be non-null on mounted VNodes. However,
7759 // they *should* be copied for kept-alive vnodes. So we just always copy
7760 // them since them being non-null during a mount doesn't affect the logic as
7761 // they will simply be overwritten.
7762 component: vnode.component,
7763 suspense: vnode.suspense,
7764 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7765 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7766 el: vnode.el,
7767 anchor: vnode.anchor
7768 };
7769 return cloned;
7770 }
7771 /**
7772 * Dev only, for HMR of hoisted vnodes reused in v-for
7773 * https://github.com/vitejs/vite/issues/2022
7774 */
7775 function deepCloneVNode(vnode) {
7776 const cloned = cloneVNode(vnode);
7777 if (isArray(vnode.children)) {
7778 cloned.children = vnode.children.map(deepCloneVNode);
7779 }
7780 return cloned;
7781 }
7782 /**
7783 * @private
7784 */
7785 function createTextVNode(text = ' ', flag = 0) {
7786 return createVNode(Text, null, text, flag);
7787 }
7788 /**
7789 * @private
7790 */
7791 function createStaticVNode(content, numberOfNodes) {
7792 // A static vnode can contain multiple stringified elements, and the number
7793 // of elements is necessary for hydration.
7794 const vnode = createVNode(Static, null, content);
7795 vnode.staticCount = numberOfNodes;
7796 return vnode;
7797 }
7798 /**
7799 * @private
7800 */
7801 function createCommentVNode(text = '',
7802 // when used as the v-else branch, the comment node must be created as a
7803 // block to ensure correct updates.
7804 asBlock = false) {
7805 return asBlock
7806 ? (openBlock(), createBlock(Comment, null, text))
7807 : createVNode(Comment, null, text);
7808 }
7809 function normalizeVNode(child) {
7810 if (child == null || typeof child === 'boolean') {
7811 // empty placeholder
7812 return createVNode(Comment);
7813 }
7814 else if (isArray(child)) {
7815 // fragment
7816 return createVNode(Fragment, null,
7817 // #3666, avoid reference pollution when reusing vnode
7818 child.slice());
7819 }
7820 else if (typeof child === 'object') {
7821 // already vnode, this should be the most common since compiled templates
7822 // always produce all-vnode children arrays
7823 return cloneIfMounted(child);
7824 }
7825 else {
7826 // strings and numbers
7827 return createVNode(Text, null, String(child));
7828 }
7829 }
7830 // optimized normalization for template-compiled render fns
7831 function cloneIfMounted(child) {
7832 return child.el === null || child.memo ? child : cloneVNode(child);
7833 }
7834 function normalizeChildren(vnode, children) {
7835 let type = 0;
7836 const { shapeFlag } = vnode;
7837 if (children == null) {
7838 children = null;
7839 }
7840 else if (isArray(children)) {
7841 type = 16 /* ARRAY_CHILDREN */;
7842 }
7843 else if (typeof children === 'object') {
7844 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7845 // Normalize slot to plain children for plain element and Teleport
7846 const slot = children.default;
7847 if (slot) {
7848 // _c marker is added by withCtx() indicating this is a compiled slot
7849 slot._c && (slot._d = false);
7850 normalizeChildren(vnode, slot());
7851 slot._c && (slot._d = true);
7852 }
7853 return;
7854 }
7855 else {
7856 type = 32 /* SLOTS_CHILDREN */;
7857 const slotFlag = children._;
7858 if (!slotFlag && !(InternalObjectKey in children)) {
7859 children._ctx = currentRenderingInstance;
7860 }
7861 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7862 // a child component receives forwarded slots from the parent.
7863 // its slot type is determined by its parent's slot type.
7864 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7865 children._ = 1 /* STABLE */;
7866 }
7867 else {
7868 children._ = 2 /* DYNAMIC */;
7869 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7870 }
7871 }
7872 }
7873 }
7874 else if (isFunction(children)) {
7875 children = { default: children, _ctx: currentRenderingInstance };
7876 type = 32 /* SLOTS_CHILDREN */;
7877 }
7878 else {
7879 children = String(children);
7880 // force teleport children to array so it can be moved around
7881 if (shapeFlag & 64 /* TELEPORT */) {
7882 type = 16 /* ARRAY_CHILDREN */;
7883 children = [createTextVNode(children)];
7884 }
7885 else {
7886 type = 8 /* TEXT_CHILDREN */;
7887 }
7888 }
7889 vnode.children = children;
7890 vnode.shapeFlag |= type;
7891 }
7892 function mergeProps(...args) {
7893 const ret = {};
7894 for (let i = 0; i < args.length; i++) {
7895 const toMerge = args[i];
7896 for (const key in toMerge) {
7897 if (key === 'class') {
7898 if (ret.class !== toMerge.class) {
7899 ret.class = normalizeClass([ret.class, toMerge.class]);
7900 }
7901 }
7902 else if (key === 'style') {
7903 ret.style = normalizeStyle([ret.style, toMerge.style]);
7904 }
7905 else if (isOn(key)) {
7906 const existing = ret[key];
7907 const incoming = toMerge[key];
7908 if (incoming &&
7909 existing !== incoming &&
7910 !(isArray(existing) && existing.includes(incoming))) {
7911 ret[key] = existing
7912 ? [].concat(existing, incoming)
7913 : incoming;
7914 }
7915 }
7916 else if (key !== '') {
7917 ret[key] = toMerge[key];
7918 }
7919 }
7920 }
7921 return ret;
7922 }
7923 function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
7924 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
7925 vnode,
7926 prevVNode
7927 ]);
7928 }
7929
7930 /**
7931 * Actual implementation
7932 */
7933 function renderList(source, renderItem, cache, index) {
7934 let ret;
7935 const cached = (cache && cache[index]);
7936 if (isArray(source) || isString(source)) {
7937 ret = new Array(source.length);
7938 for (let i = 0, l = source.length; i < l; i++) {
7939 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
7940 }
7941 }
7942 else if (typeof source === 'number') {
7943 if (!Number.isInteger(source)) {
7944 warn$1(`The v-for range expect an integer value but got ${source}.`);
7945 return [];
7946 }
7947 ret = new Array(source);
7948 for (let i = 0; i < source; i++) {
7949 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
7950 }
7951 }
7952 else if (isObject(source)) {
7953 if (source[Symbol.iterator]) {
7954 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
7955 }
7956 else {
7957 const keys = Object.keys(source);
7958 ret = new Array(keys.length);
7959 for (let i = 0, l = keys.length; i < l; i++) {
7960 const key = keys[i];
7961 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
7962 }
7963 }
7964 }
7965 else {
7966 ret = [];
7967 }
7968 if (cache) {
7969 cache[index] = ret;
7970 }
7971 return ret;
7972 }
7973
7974 /**
7975 * Compiler runtime helper for creating dynamic slots object
7976 * @private
7977 */
7978 function createSlots(slots, dynamicSlots) {
7979 for (let i = 0; i < dynamicSlots.length; i++) {
7980 const slot = dynamicSlots[i];
7981 // array of dynamic slot generated by <template v-for="..." #[...]>
7982 if (isArray(slot)) {
7983 for (let j = 0; j < slot.length; j++) {
7984 slots[slot[j].name] = slot[j].fn;
7985 }
7986 }
7987 else if (slot) {
7988 // conditional single slot generated by <template v-if="..." #foo>
7989 slots[slot.name] = slot.fn;
7990 }
7991 }
7992 return slots;
7993 }
7994
7995 /**
7996 * Compiler runtime helper for rendering `<slot/>`
7997 * @private
7998 */
7999 function renderSlot(slots, name, props = {},
8000 // this is not a user-facing function, so the fallback is always generated by
8001 // the compiler and guaranteed to be a function returning an array
8002 fallback, noSlotted) {
8003 if (currentRenderingInstance.isCE) {
8004 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
8005 }
8006 let slot = slots[name];
8007 if (slot && slot.length > 1) {
8008 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
8009 `function. You need to mark this component with $dynamic-slots in the ` +
8010 `parent template.`);
8011 slot = () => [];
8012 }
8013 // a compiled slot disables block tracking by default to avoid manual
8014 // invocation interfering with template-based block tracking, but in
8015 // `renderSlot` we can be sure that it's template-based so we can force
8016 // enable it.
8017 if (slot && slot._c) {
8018 slot._d = false;
8019 }
8020 openBlock();
8021 const validSlotContent = slot && ensureValidVNode(slot(props));
8022 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
8023 ? 64 /* STABLE_FRAGMENT */
8024 : -2 /* BAIL */);
8025 if (!noSlotted && rendered.scopeId) {
8026 rendered.slotScopeIds = [rendered.scopeId + '-s'];
8027 }
8028 if (slot && slot._c) {
8029 slot._d = true;
8030 }
8031 return rendered;
8032 }
8033 function ensureValidVNode(vnodes) {
8034 return vnodes.some(child => {
8035 if (!isVNode(child))
8036 return true;
8037 if (child.type === Comment)
8038 return false;
8039 if (child.type === Fragment &&
8040 !ensureValidVNode(child.children))
8041 return false;
8042 return true;
8043 })
8044 ? vnodes
8045 : null;
8046 }
8047
8048 /**
8049 * For prefixing keys in v-on="obj" with "on"
8050 * @private
8051 */
8052 function toHandlers(obj) {
8053 const ret = {};
8054 if (!isObject(obj)) {
8055 warn$1(`v-on with no argument expects an object value.`);
8056 return ret;
8057 }
8058 for (const key in obj) {
8059 ret[toHandlerKey(key)] = obj[key];
8060 }
8061 return ret;
8062 }
8063
8064 /**
8065 * #2437 In Vue 3, functional components do not have a public instance proxy but
8066 * they exist in the internal parent chain. For code that relies on traversing
8067 * public $parent chains, skip functional ones and go to the parent instead.
8068 */
8069 const getPublicInstance = (i) => {
8070 if (!i)
8071 return null;
8072 if (isStatefulComponent(i))
8073 return getExposeProxy(i) || i.proxy;
8074 return getPublicInstance(i.parent);
8075 };
8076 const publicPropertiesMap = extend(Object.create(null), {
8077 $: i => i,
8078 $el: i => i.vnode.el,
8079 $data: i => i.data,
8080 $props: i => (shallowReadonly(i.props) ),
8081 $attrs: i => (shallowReadonly(i.attrs) ),
8082 $slots: i => (shallowReadonly(i.slots) ),
8083 $refs: i => (shallowReadonly(i.refs) ),
8084 $parent: i => getPublicInstance(i.parent),
8085 $root: i => getPublicInstance(i.root),
8086 $emit: i => i.emit,
8087 $options: i => (resolveMergedOptions(i) ),
8088 $forceUpdate: i => () => queueJob(i.update),
8089 $nextTick: i => nextTick.bind(i.proxy),
8090 $watch: i => (instanceWatch.bind(i) )
8091 });
8092 const PublicInstanceProxyHandlers = {
8093 get({ _: instance }, key) {
8094 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
8095 // for internal formatters to know that this is a Vue instance
8096 if (key === '__isVue') {
8097 return true;
8098 }
8099 // prioritize <script setup> bindings during dev.
8100 // this allows even properties that start with _ or $ to be used - so that
8101 // it aligns with the production behavior where the render fn is inlined and
8102 // indeed has access to all declared variables.
8103 if (setupState !== EMPTY_OBJ &&
8104 setupState.__isScriptSetup &&
8105 hasOwn(setupState, key)) {
8106 return setupState[key];
8107 }
8108 // data / props / ctx
8109 // This getter gets called for every property access on the render context
8110 // during render and is a major hotspot. The most expensive part of this
8111 // is the multiple hasOwn() calls. It's much faster to do a simple property
8112 // access on a plain object, so we use an accessCache object (with null
8113 // prototype) to memoize what access type a key corresponds to.
8114 let normalizedProps;
8115 if (key[0] !== '$') {
8116 const n = accessCache[key];
8117 if (n !== undefined) {
8118 switch (n) {
8119 case 1 /* SETUP */:
8120 return setupState[key];
8121 case 2 /* DATA */:
8122 return data[key];
8123 case 4 /* CONTEXT */:
8124 return ctx[key];
8125 case 3 /* PROPS */:
8126 return props[key];
8127 // default: just fallthrough
8128 }
8129 }
8130 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8131 accessCache[key] = 1 /* SETUP */;
8132 return setupState[key];
8133 }
8134 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8135 accessCache[key] = 2 /* DATA */;
8136 return data[key];
8137 }
8138 else if (
8139 // only cache other properties when instance has declared (thus stable)
8140 // props
8141 (normalizedProps = instance.propsOptions[0]) &&
8142 hasOwn(normalizedProps, key)) {
8143 accessCache[key] = 3 /* PROPS */;
8144 return props[key];
8145 }
8146 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8147 accessCache[key] = 4 /* CONTEXT */;
8148 return ctx[key];
8149 }
8150 else if (shouldCacheAccess) {
8151 accessCache[key] = 0 /* OTHER */;
8152 }
8153 }
8154 const publicGetter = publicPropertiesMap[key];
8155 let cssModule, globalProperties;
8156 // public $xxx properties
8157 if (publicGetter) {
8158 if (key === '$attrs') {
8159 track(instance, "get" /* GET */, key);
8160 markAttrsAccessed();
8161 }
8162 return publicGetter(instance);
8163 }
8164 else if (
8165 // css module (injected by vue-loader)
8166 (cssModule = type.__cssModules) &&
8167 (cssModule = cssModule[key])) {
8168 return cssModule;
8169 }
8170 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8171 // user may set custom properties to `this` that start with `$`
8172 accessCache[key] = 4 /* CONTEXT */;
8173 return ctx[key];
8174 }
8175 else if (
8176 // global properties
8177 ((globalProperties = appContext.config.globalProperties),
8178 hasOwn(globalProperties, key))) {
8179 {
8180 return globalProperties[key];
8181 }
8182 }
8183 else if (currentRenderingInstance &&
8184 (!isString(key) ||
8185 // #1091 avoid internal isRef/isVNode checks on component instance leading
8186 // to infinite warning loop
8187 key.indexOf('__v') !== 0)) {
8188 if (data !== EMPTY_OBJ &&
8189 (key[0] === '$' || key[0] === '_') &&
8190 hasOwn(data, key)) {
8191 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
8192 `character ("$" or "_") and is not proxied on the render context.`);
8193 }
8194 else if (instance === currentRenderingInstance) {
8195 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
8196 `but is not defined on instance.`);
8197 }
8198 }
8199 },
8200 set({ _: instance }, key, value) {
8201 const { data, setupState, ctx } = instance;
8202 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8203 setupState[key] = value;
8204 }
8205 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8206 data[key] = value;
8207 }
8208 else if (hasOwn(instance.props, key)) {
8209 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
8210 return false;
8211 }
8212 if (key[0] === '$' && key.slice(1) in instance) {
8213 warn$1(`Attempting to mutate public property "${key}". ` +
8214 `Properties starting with $ are reserved and readonly.`, instance);
8215 return false;
8216 }
8217 else {
8218 if (key in instance.appContext.config.globalProperties) {
8219 Object.defineProperty(ctx, key, {
8220 enumerable: true,
8221 configurable: true,
8222 value
8223 });
8224 }
8225 else {
8226 ctx[key] = value;
8227 }
8228 }
8229 return true;
8230 },
8231 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
8232 let normalizedProps;
8233 return (!!accessCache[key] ||
8234 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
8235 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
8236 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
8237 hasOwn(ctx, key) ||
8238 hasOwn(publicPropertiesMap, key) ||
8239 hasOwn(appContext.config.globalProperties, key));
8240 }
8241 };
8242 {
8243 PublicInstanceProxyHandlers.ownKeys = (target) => {
8244 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
8245 `The keys will be empty in production mode to avoid performance overhead.`);
8246 return Reflect.ownKeys(target);
8247 };
8248 }
8249 const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
8250 get(target, key) {
8251 // fast path for unscopables when using `with` block
8252 if (key === Symbol.unscopables) {
8253 return;
8254 }
8255 return PublicInstanceProxyHandlers.get(target, key, target);
8256 },
8257 has(_, key) {
8258 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
8259 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
8260 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
8261 }
8262 return has;
8263 }
8264 });
8265 // dev only
8266 // In dev mode, the proxy target exposes the same properties as seen on `this`
8267 // for easier console inspection. In prod mode it will be an empty object so
8268 // these properties definitions can be skipped.
8269 function createDevRenderContext(instance) {
8270 const target = {};
8271 // expose internal instance for proxy handlers
8272 Object.defineProperty(target, `_`, {
8273 configurable: true,
8274 enumerable: false,
8275 get: () => instance
8276 });
8277 // expose public properties
8278 Object.keys(publicPropertiesMap).forEach(key => {
8279 Object.defineProperty(target, key, {
8280 configurable: true,
8281 enumerable: false,
8282 get: () => publicPropertiesMap[key](instance),
8283 // intercepted by the proxy so no need for implementation,
8284 // but needed to prevent set errors
8285 set: NOOP
8286 });
8287 });
8288 return target;
8289 }
8290 // dev only
8291 function exposePropsOnRenderContext(instance) {
8292 const { ctx, propsOptions: [propsOptions] } = instance;
8293 if (propsOptions) {
8294 Object.keys(propsOptions).forEach(key => {
8295 Object.defineProperty(ctx, key, {
8296 enumerable: true,
8297 configurable: true,
8298 get: () => instance.props[key],
8299 set: NOOP
8300 });
8301 });
8302 }
8303 }
8304 // dev only
8305 function exposeSetupStateOnRenderContext(instance) {
8306 const { ctx, setupState } = instance;
8307 Object.keys(toRaw(setupState)).forEach(key => {
8308 if (!setupState.__isScriptSetup) {
8309 if (key[0] === '$' || key[0] === '_') {
8310 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
8311 `which are reserved prefixes for Vue internals.`);
8312 return;
8313 }
8314 Object.defineProperty(ctx, key, {
8315 enumerable: true,
8316 configurable: true,
8317 get: () => setupState[key],
8318 set: NOOP
8319 });
8320 }
8321 });
8322 }
8323
8324 const emptyAppContext = createAppContext();
8325 let uid$1 = 0;
8326 function createComponentInstance(vnode, parent, suspense) {
8327 const type = vnode.type;
8328 // inherit parent app context - or - if root, adopt from root vnode
8329 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8330 const instance = {
8331 uid: uid$1++,
8332 vnode,
8333 type,
8334 parent,
8335 appContext,
8336 root: null,
8337 next: null,
8338 subTree: null,
8339 effect: null,
8340 update: null,
8341 scope: new EffectScope(true /* detached */),
8342 render: null,
8343 proxy: null,
8344 exposed: null,
8345 exposeProxy: null,
8346 withProxy: null,
8347 provides: parent ? parent.provides : Object.create(appContext.provides),
8348 accessCache: null,
8349 renderCache: [],
8350 // local resovled assets
8351 components: null,
8352 directives: null,
8353 // resolved props and emits options
8354 propsOptions: normalizePropsOptions(type, appContext),
8355 emitsOptions: normalizeEmitsOptions(type, appContext),
8356 // emit
8357 emit: null,
8358 emitted: null,
8359 // props default value
8360 propsDefaults: EMPTY_OBJ,
8361 // inheritAttrs
8362 inheritAttrs: type.inheritAttrs,
8363 // state
8364 ctx: EMPTY_OBJ,
8365 data: EMPTY_OBJ,
8366 props: EMPTY_OBJ,
8367 attrs: EMPTY_OBJ,
8368 slots: EMPTY_OBJ,
8369 refs: EMPTY_OBJ,
8370 setupState: EMPTY_OBJ,
8371 setupContext: null,
8372 // suspense related
8373 suspense,
8374 suspenseId: suspense ? suspense.pendingId : 0,
8375 asyncDep: null,
8376 asyncResolved: false,
8377 // lifecycle hooks
8378 // not using enums here because it results in computed properties
8379 isMounted: false,
8380 isUnmounted: false,
8381 isDeactivated: false,
8382 bc: null,
8383 c: null,
8384 bm: null,
8385 m: null,
8386 bu: null,
8387 u: null,
8388 um: null,
8389 bum: null,
8390 da: null,
8391 a: null,
8392 rtg: null,
8393 rtc: null,
8394 ec: null,
8395 sp: null
8396 };
8397 {
8398 instance.ctx = createDevRenderContext(instance);
8399 }
8400 instance.root = parent ? parent.root : instance;
8401 instance.emit = emit$1.bind(null, instance);
8402 // apply custom element special handling
8403 if (vnode.ce) {
8404 vnode.ce(instance);
8405 }
8406 return instance;
8407 }
8408 let currentInstance = null;
8409 const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8410 const setCurrentInstance = (instance) => {
8411 currentInstance = instance;
8412 instance.scope.on();
8413 };
8414 const unsetCurrentInstance = () => {
8415 currentInstance && currentInstance.scope.off();
8416 currentInstance = null;
8417 };
8418 const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8419 function validateComponentName(name, config) {
8420 const appIsNativeTag = config.isNativeTag || NO;
8421 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8422 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
8423 }
8424 }
8425 function isStatefulComponent(instance) {
8426 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
8427 }
8428 let isInSSRComponentSetup = false;
8429 function setupComponent(instance, isSSR = false) {
8430 isInSSRComponentSetup = isSSR;
8431 const { props, children } = instance.vnode;
8432 const isStateful = isStatefulComponent(instance);
8433 initProps(instance, props, isStateful, isSSR);
8434 initSlots(instance, children);
8435 const setupResult = isStateful
8436 ? setupStatefulComponent(instance, isSSR)
8437 : undefined;
8438 isInSSRComponentSetup = false;
8439 return setupResult;
8440 }
8441 function setupStatefulComponent(instance, isSSR) {
8442 const Component = instance.type;
8443 {
8444 if (Component.name) {
8445 validateComponentName(Component.name, instance.appContext.config);
8446 }
8447 if (Component.components) {
8448 const names = Object.keys(Component.components);
8449 for (let i = 0; i < names.length; i++) {
8450 validateComponentName(names[i], instance.appContext.config);
8451 }
8452 }
8453 if (Component.directives) {
8454 const names = Object.keys(Component.directives);
8455 for (let i = 0; i < names.length; i++) {
8456 validateDirectiveName(names[i]);
8457 }
8458 }
8459 if (Component.compilerOptions && isRuntimeOnly()) {
8460 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8461 `includes the runtime compiler. Since you are using a runtime-only ` +
8462 `build, the options should be passed via your build tool config instead.`);
8463 }
8464 }
8465 // 0. create render proxy property access cache
8466 instance.accessCache = Object.create(null);
8467 // 1. create public instance / render proxy
8468 // also mark it raw so it's never observed
8469 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8470 {
8471 exposePropsOnRenderContext(instance);
8472 }
8473 // 2. call setup()
8474 const { setup } = Component;
8475 if (setup) {
8476 const setupContext = (instance.setupContext =
8477 setup.length > 1 ? createSetupContext(instance) : null);
8478 setCurrentInstance(instance);
8479 pauseTracking();
8480 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8481 resetTracking();
8482 unsetCurrentInstance();
8483 if (isPromise(setupResult)) {
8484 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8485 if (isSSR) {
8486 // return the promise so server-renderer can wait on it
8487 return setupResult
8488 .then((resolvedResult) => {
8489 handleSetupResult(instance, resolvedResult, isSSR);
8490 })
8491 .catch(e => {
8492 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8493 });
8494 }
8495 else {
8496 // async setup returned Promise.
8497 // bail here and wait for re-entry.
8498 instance.asyncDep = setupResult;
8499 }
8500 }
8501 else {
8502 handleSetupResult(instance, setupResult, isSSR);
8503 }
8504 }
8505 else {
8506 finishComponentSetup(instance, isSSR);
8507 }
8508 }
8509 function handleSetupResult(instance, setupResult, isSSR) {
8510 if (isFunction(setupResult)) {
8511 // setup returned an inline render function
8512 {
8513 instance.render = setupResult;
8514 }
8515 }
8516 else if (isObject(setupResult)) {
8517 if (isVNode(setupResult)) {
8518 warn$1(`setup() should not return VNodes directly - ` +
8519 `return a render function instead.`);
8520 }
8521 // setup returned bindings.
8522 // assuming a render function compiled from template is present.
8523 {
8524 instance.devtoolsRawSetupState = setupResult;
8525 }
8526 instance.setupState = proxyRefs(setupResult);
8527 {
8528 exposeSetupStateOnRenderContext(instance);
8529 }
8530 }
8531 else if (setupResult !== undefined) {
8532 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8533 }
8534 finishComponentSetup(instance, isSSR);
8535 }
8536 let compile;
8537 let installWithProxy;
8538 /**
8539 * For runtime-dom to register the compiler.
8540 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8541 */
8542 function registerRuntimeCompiler(_compile) {
8543 compile = _compile;
8544 installWithProxy = i => {
8545 if (i.render._rc) {
8546 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8547 }
8548 };
8549 }
8550 // dev only
8551 const isRuntimeOnly = () => !compile;
8552 function finishComponentSetup(instance, isSSR, skipOptions) {
8553 const Component = instance.type;
8554 // template / render function normalization
8555 // could be already set when returned from setup()
8556 if (!instance.render) {
8557 // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
8558 // is done by server-renderer
8559 if (!isSSR && compile && !Component.render) {
8560 const template = Component.template;
8561 if (template) {
8562 {
8563 startMeasure(instance, `compile`);
8564 }
8565 const { isCustomElement, compilerOptions } = instance.appContext.config;
8566 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8567 const finalCompilerOptions = extend(extend({
8568 isCustomElement,
8569 delimiters
8570 }, compilerOptions), componentCompilerOptions);
8571 Component.render = compile(template, finalCompilerOptions);
8572 {
8573 endMeasure(instance, `compile`);
8574 }
8575 }
8576 }
8577 instance.render = (Component.render || NOOP);
8578 // for runtime-compiled render functions using `with` blocks, the render
8579 // proxy used needs a different `has` handler which is more performant and
8580 // also only allows a whitelist of globals to fallthrough.
8581 if (installWithProxy) {
8582 installWithProxy(instance);
8583 }
8584 }
8585 // support for 2.x options
8586 {
8587 setCurrentInstance(instance);
8588 pauseTracking();
8589 applyOptions(instance);
8590 resetTracking();
8591 unsetCurrentInstance();
8592 }
8593 // warn missing template/render
8594 // the runtime compilation of template in SSR is done by server-render
8595 if (!Component.render && instance.render === NOOP && !isSSR) {
8596 /* istanbul ignore if */
8597 if (!compile && Component.template) {
8598 warn$1(`Component provided template option but ` +
8599 `runtime compilation is not supported in this build of Vue.` +
8600 (` Use "vue.global.js" instead.`
8601 ) /* should not happen */);
8602 }
8603 else {
8604 warn$1(`Component is missing template or render function.`);
8605 }
8606 }
8607 }
8608 function createAttrsProxy(instance) {
8609 return new Proxy(instance.attrs, {
8610 get(target, key) {
8611 markAttrsAccessed();
8612 track(instance, "get" /* GET */, '$attrs');
8613 return target[key];
8614 },
8615 set() {
8616 warn$1(`setupContext.attrs is readonly.`);
8617 return false;
8618 },
8619 deleteProperty() {
8620 warn$1(`setupContext.attrs is readonly.`);
8621 return false;
8622 }
8623 }
8624 );
8625 }
8626 function createSetupContext(instance) {
8627 const expose = exposed => {
8628 if (instance.exposed) {
8629 warn$1(`expose() should be called only once per setup().`);
8630 }
8631 instance.exposed = exposed || {};
8632 };
8633 let attrs;
8634 {
8635 // We use getters in dev in case libs like test-utils overwrite instance
8636 // properties (overwrites should not be done in prod)
8637 return Object.freeze({
8638 get attrs() {
8639 return attrs || (attrs = createAttrsProxy(instance));
8640 },
8641 get slots() {
8642 return shallowReadonly(instance.slots);
8643 },
8644 get emit() {
8645 return (event, ...args) => instance.emit(event, ...args);
8646 },
8647 expose
8648 });
8649 }
8650 }
8651 function getExposeProxy(instance) {
8652 if (instance.exposed) {
8653 return (instance.exposeProxy ||
8654 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8655 get(target, key) {
8656 if (key in target) {
8657 return target[key];
8658 }
8659 else if (key in publicPropertiesMap) {
8660 return publicPropertiesMap[key](instance);
8661 }
8662 }
8663 })));
8664 }
8665 }
8666 const classifyRE = /(?:^|[-_])(\w)/g;
8667 const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8668 function getComponentName(Component) {
8669 return isFunction(Component)
8670 ? Component.displayName || Component.name
8671 : Component.name;
8672 }
8673 /* istanbul ignore next */
8674 function formatComponentName(instance, Component, isRoot = false) {
8675 let name = getComponentName(Component);
8676 if (!name && Component.__file) {
8677 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8678 if (match) {
8679 name = match[1];
8680 }
8681 }
8682 if (!name && instance && instance.parent) {
8683 // try to infer the name based on reverse resolution
8684 const inferFromRegistry = (registry) => {
8685 for (const key in registry) {
8686 if (registry[key] === Component) {
8687 return key;
8688 }
8689 }
8690 };
8691 name =
8692 inferFromRegistry(instance.components ||
8693 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8694 }
8695 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8696 }
8697 function isClassComponent(value) {
8698 return isFunction(value) && '__vccOpts' in value;
8699 }
8700
8701 const computed$1 = ((getterOrOptions, debugOptions) => {
8702 // @ts-ignore
8703 return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
8704 });
8705
8706 // dev only
8707 const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8708 `<script setup> of a single file component. Its arguments should be ` +
8709 `compiled away and passing it at runtime has no effect.`);
8710 // implementation
8711 function defineProps() {
8712 {
8713 warnRuntimeUsage(`defineProps`);
8714 }
8715 return null;
8716 }
8717 // implementation
8718 function defineEmits() {
8719 {
8720 warnRuntimeUsage(`defineEmits`);
8721 }
8722 return null;
8723 }
8724 /**
8725 * Vue `<script setup>` compiler macro for declaring a component's exposed
8726 * instance properties when it is accessed by a parent component via template
8727 * refs.
8728 *
8729 * `<script setup>` components are closed by default - i.e. variables inside
8730 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8731 * via `defineExpose`.
8732 *
8733 * This is only usable inside `<script setup>`, is compiled away in the
8734 * output and should **not** be actually called at runtime.
8735 */
8736 function defineExpose(exposed) {
8737 {
8738 warnRuntimeUsage(`defineExpose`);
8739 }
8740 }
8741 /**
8742 * Vue `<script setup>` compiler macro for providing props default values when
8743 * using type-based `defineProps` declaration.
8744 *
8745 * Example usage:
8746 * ```ts
8747 * withDefaults(defineProps<{
8748 * size?: number
8749 * labels?: string[]
8750 * }>(), {
8751 * size: 3,
8752 * labels: () => ['default label']
8753 * })
8754 * ```
8755 *
8756 * This is only usable inside `<script setup>`, is compiled away in the output
8757 * and should **not** be actually called at runtime.
8758 */
8759 function withDefaults(props, defaults) {
8760 {
8761 warnRuntimeUsage(`withDefaults`);
8762 }
8763 return null;
8764 }
8765 function useSlots() {
8766 return getContext().slots;
8767 }
8768 function useAttrs() {
8769 return getContext().attrs;
8770 }
8771 function getContext() {
8772 const i = getCurrentInstance();
8773 if (!i) {
8774 warn$1(`useContext() called without active instance.`);
8775 }
8776 return i.setupContext || (i.setupContext = createSetupContext(i));
8777 }
8778 /**
8779 * Runtime helper for merging default declarations. Imported by compiled code
8780 * only.
8781 * @internal
8782 */
8783 function mergeDefaults(raw, defaults) {
8784 const props = isArray(raw)
8785 ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
8786 : raw;
8787 for (const key in defaults) {
8788 const opt = props[key];
8789 if (opt) {
8790 if (isArray(opt) || isFunction(opt)) {
8791 props[key] = { type: opt, default: defaults[key] };
8792 }
8793 else {
8794 opt.default = defaults[key];
8795 }
8796 }
8797 else if (opt === null) {
8798 props[key] = { default: defaults[key] };
8799 }
8800 else {
8801 warn$1(`props default key "${key}" has no corresponding declaration.`);
8802 }
8803 }
8804 return props;
8805 }
8806 /**
8807 * Used to create a proxy for the rest element when destructuring props with
8808 * defineProps().
8809 * @internal
8810 */
8811 function createPropsRestProxy(props, excludedKeys) {
8812 const ret = {};
8813 for (const key in props) {
8814 if (!excludedKeys.includes(key)) {
8815 Object.defineProperty(ret, key, {
8816 enumerable: true,
8817 get: () => props[key]
8818 });
8819 }
8820 }
8821 return ret;
8822 }
8823 /**
8824 * `<script setup>` helper for persisting the current instance context over
8825 * async/await flows.
8826 *
8827 * `@vue/compiler-sfc` converts the following:
8828 *
8829 * ```ts
8830 * const x = await foo()
8831 * ```
8832 *
8833 * into:
8834 *
8835 * ```ts
8836 * let __temp, __restore
8837 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
8838 * ```
8839 * @internal
8840 */
8841 function withAsyncContext(getAwaitable) {
8842 const ctx = getCurrentInstance();
8843 if (!ctx) {
8844 warn$1(`withAsyncContext called without active current instance. ` +
8845 `This is likely a bug.`);
8846 }
8847 let awaitable = getAwaitable();
8848 unsetCurrentInstance();
8849 if (isPromise(awaitable)) {
8850 awaitable = awaitable.catch(e => {
8851 setCurrentInstance(ctx);
8852 throw e;
8853 });
8854 }
8855 return [awaitable, () => setCurrentInstance(ctx)];
8856 }
8857
8858 // Actual implementation
8859 function h(type, propsOrChildren, children) {
8860 const l = arguments.length;
8861 if (l === 2) {
8862 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
8863 // single vnode without props
8864 if (isVNode(propsOrChildren)) {
8865 return createVNode(type, null, [propsOrChildren]);
8866 }
8867 // props without children
8868 return createVNode(type, propsOrChildren);
8869 }
8870 else {
8871 // omit props
8872 return createVNode(type, null, propsOrChildren);
8873 }
8874 }
8875 else {
8876 if (l > 3) {
8877 children = Array.prototype.slice.call(arguments, 2);
8878 }
8879 else if (l === 3 && isVNode(children)) {
8880 children = [children];
8881 }
8882 return createVNode(type, propsOrChildren, children);
8883 }
8884 }
8885
8886 const ssrContextKey = Symbol(`ssrContext` );
8887 const useSSRContext = () => {
8888 {
8889 warn$1(`useSSRContext() is not supported in the global build.`);
8890 }
8891 };
8892
8893 function initCustomFormatter() {
8894 /* eslint-disable no-restricted-globals */
8895 if (typeof window === 'undefined') {
8896 return;
8897 }
8898 const vueStyle = { style: 'color:#3ba776' };
8899 const numberStyle = { style: 'color:#0b1bc9' };
8900 const stringStyle = { style: 'color:#b62e24' };
8901 const keywordStyle = { style: 'color:#9d288c' };
8902 // custom formatter for Chrome
8903 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
8904 const formatter = {
8905 header(obj) {
8906 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
8907 if (!isObject(obj)) {
8908 return null;
8909 }
8910 if (obj.__isVue) {
8911 return ['div', vueStyle, `VueInstance`];
8912 }
8913 else if (isRef(obj)) {
8914 return [
8915 'div',
8916 {},
8917 ['span', vueStyle, genRefFlag(obj)],
8918 '<',
8919 formatValue(obj.value),
8920 `>`
8921 ];
8922 }
8923 else if (isReactive(obj)) {
8924 return [
8925 'div',
8926 {},
8927 ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
8928 '<',
8929 formatValue(obj),
8930 `>${isReadonly(obj) ? ` (readonly)` : ``}`
8931 ];
8932 }
8933 else if (isReadonly(obj)) {
8934 return [
8935 'div',
8936 {},
8937 ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
8938 '<',
8939 formatValue(obj),
8940 '>'
8941 ];
8942 }
8943 return null;
8944 },
8945 hasBody(obj) {
8946 return obj && obj.__isVue;
8947 },
8948 body(obj) {
8949 if (obj && obj.__isVue) {
8950 return [
8951 'div',
8952 {},
8953 ...formatInstance(obj.$)
8954 ];
8955 }
8956 }
8957 };
8958 function formatInstance(instance) {
8959 const blocks = [];
8960 if (instance.type.props && instance.props) {
8961 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
8962 }
8963 if (instance.setupState !== EMPTY_OBJ) {
8964 blocks.push(createInstanceBlock('setup', instance.setupState));
8965 }
8966 if (instance.data !== EMPTY_OBJ) {
8967 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
8968 }
8969 const computed = extractKeys(instance, 'computed');
8970 if (computed) {
8971 blocks.push(createInstanceBlock('computed', computed));
8972 }
8973 const injected = extractKeys(instance, 'inject');
8974 if (injected) {
8975 blocks.push(createInstanceBlock('injected', injected));
8976 }
8977 blocks.push([
8978 'div',
8979 {},
8980 [
8981 'span',
8982 {
8983 style: keywordStyle.style + ';opacity:0.66'
8984 },
8985 '$ (internal): '
8986 ],
8987 ['object', { object: instance }]
8988 ]);
8989 return blocks;
8990 }
8991 function createInstanceBlock(type, target) {
8992 target = extend({}, target);
8993 if (!Object.keys(target).length) {
8994 return ['span', {}];
8995 }
8996 return [
8997 'div',
8998 { style: 'line-height:1.25em;margin-bottom:0.6em' },
8999 [
9000 'div',
9001 {
9002 style: 'color:#476582'
9003 },
9004 type
9005 ],
9006 [
9007 'div',
9008 {
9009 style: 'padding-left:1.25em'
9010 },
9011 ...Object.keys(target).map(key => {
9012 return [
9013 'div',
9014 {},
9015 ['span', keywordStyle, key + ': '],
9016 formatValue(target[key], false)
9017 ];
9018 })
9019 ]
9020 ];
9021 }
9022 function formatValue(v, asRaw = true) {
9023 if (typeof v === 'number') {
9024 return ['span', numberStyle, v];
9025 }
9026 else if (typeof v === 'string') {
9027 return ['span', stringStyle, JSON.stringify(v)];
9028 }
9029 else if (typeof v === 'boolean') {
9030 return ['span', keywordStyle, v];
9031 }
9032 else if (isObject(v)) {
9033 return ['object', { object: asRaw ? toRaw(v) : v }];
9034 }
9035 else {
9036 return ['span', stringStyle, String(v)];
9037 }
9038 }
9039 function extractKeys(instance, type) {
9040 const Comp = instance.type;
9041 if (isFunction(Comp)) {
9042 return;
9043 }
9044 const extracted = {};
9045 for (const key in instance.ctx) {
9046 if (isKeyOfType(Comp, key, type)) {
9047 extracted[key] = instance.ctx[key];
9048 }
9049 }
9050 return extracted;
9051 }
9052 function isKeyOfType(Comp, key, type) {
9053 const opts = Comp[type];
9054 if ((isArray(opts) && opts.includes(key)) ||
9055 (isObject(opts) && key in opts)) {
9056 return true;
9057 }
9058 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9059 return true;
9060 }
9061 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9062 return true;
9063 }
9064 }
9065 function genRefFlag(v) {
9066 if (isShallow(v)) {
9067 return `ShallowRef`;
9068 }
9069 if (v.effect) {
9070 return `ComputedRef`;
9071 }
9072 return `Ref`;
9073 }
9074 if (window.devtoolsFormatters) {
9075 window.devtoolsFormatters.push(formatter);
9076 }
9077 else {
9078 window.devtoolsFormatters = [formatter];
9079 }
9080 }
9081
9082 function withMemo(memo, render, cache, index) {
9083 const cached = cache[index];
9084 if (cached && isMemoSame(cached, memo)) {
9085 return cached;
9086 }
9087 const ret = render();
9088 // shallow clone
9089 ret.memo = memo.slice();
9090 return (cache[index] = ret);
9091 }
9092 function isMemoSame(cached, memo) {
9093 const prev = cached.memo;
9094 if (prev.length != memo.length) {
9095 return false;
9096 }
9097 for (let i = 0; i < prev.length; i++) {
9098 if (prev[i] !== memo[i]) {
9099 return false;
9100 }
9101 }
9102 // make sure to let parent block track it when returning cached
9103 if (isBlockTreeEnabled > 0 && currentBlock) {
9104 currentBlock.push(cached);
9105 }
9106 return true;
9107 }
9108
9109 // Core API ------------------------------------------------------------------
9110 const version = "3.2.29";
9111 /**
9112 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9113 * @internal
9114 */
9115 const ssrUtils = (null);
9116 /**
9117 * @internal only exposed in compat builds
9118 */
9119 const resolveFilter = null;
9120 /**
9121 * @internal only exposed in compat builds.
9122 */
9123 const compatUtils = (null);
9124
9125 const svgNS = 'http://www.w3.org/2000/svg';
9126 const doc = (typeof document !== 'undefined' ? document : null);
9127 const templateContainer = doc && doc.createElement('template');
9128 const nodeOps = {
9129 insert: (child, parent, anchor) => {
9130 parent.insertBefore(child, anchor || null);
9131 },
9132 remove: child => {
9133 const parent = child.parentNode;
9134 if (parent) {
9135 parent.removeChild(child);
9136 }
9137 },
9138 createElement: (tag, isSVG, is, props) => {
9139 const el = isSVG
9140 ? doc.createElementNS(svgNS, tag)
9141 : doc.createElement(tag, is ? { is } : undefined);
9142 if (tag === 'select' && props && props.multiple != null) {
9143 el.setAttribute('multiple', props.multiple);
9144 }
9145 return el;
9146 },
9147 createText: text => doc.createTextNode(text),
9148 createComment: text => doc.createComment(text),
9149 setText: (node, text) => {
9150 node.nodeValue = text;
9151 },
9152 setElementText: (el, text) => {
9153 el.textContent = text;
9154 },
9155 parentNode: node => node.parentNode,
9156 nextSibling: node => node.nextSibling,
9157 querySelector: selector => doc.querySelector(selector),
9158 setScopeId(el, id) {
9159 el.setAttribute(id, '');
9160 },
9161 cloneNode(el) {
9162 const cloned = el.cloneNode(true);
9163 // #3072
9164 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9165 // - normally, elements using `:value` bindings will not be hoisted, but if
9166 // the bound value is a constant, e.g. `:value="true"` - they do get
9167 // hoisted.
9168 // - in production, hoisted nodes are cloned when subsequent inserts, but
9169 // cloneNode() does not copy the custom property we attached.
9170 // - This may need to account for other custom DOM properties we attach to
9171 // elements in addition to `_value` in the future.
9172 if (`_value` in el) {
9173 cloned._value = el._value;
9174 }
9175 return cloned;
9176 },
9177 // __UNSAFE__
9178 // Reason: innerHTML.
9179 // Static content here can only come from compiled templates.
9180 // As long as the user only uses trusted templates, this is safe.
9181 insertStaticContent(content, parent, anchor, isSVG, start, end) {
9182 // <parent> before | first ... last | anchor </parent>
9183 const before = anchor ? anchor.previousSibling : parent.lastChild;
9184 // #5308 can only take cached path if:
9185 // - has a single root node
9186 // - nextSibling info is still available
9187 if (start && (start === end || start.nextSibling)) {
9188 // cached
9189 while (true) {
9190 parent.insertBefore(start.cloneNode(true), anchor);
9191 if (start === end || !(start = start.nextSibling))
9192 break;
9193 }
9194 }
9195 else {
9196 // fresh insert
9197 templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9198 const template = templateContainer.content;
9199 if (isSVG) {
9200 // remove outer svg wrapper
9201 const wrapper = template.firstChild;
9202 while (wrapper.firstChild) {
9203 template.appendChild(wrapper.firstChild);
9204 }
9205 template.removeChild(wrapper);
9206 }
9207 parent.insertBefore(template, anchor);
9208 }
9209 return [
9210 // first
9211 before ? before.nextSibling : parent.firstChild,
9212 // last
9213 anchor ? anchor.previousSibling : parent.lastChild
9214 ];
9215 }
9216 };
9217
9218 // compiler should normalize class + :class bindings on the same element
9219 // into a single binding ['staticClass', dynamic]
9220 function patchClass(el, value, isSVG) {
9221 // directly setting className should be faster than setAttribute in theory
9222 // if this is an element during a transition, take the temporary transition
9223 // classes into account.
9224 const transitionClasses = el._vtc;
9225 if (transitionClasses) {
9226 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9227 }
9228 if (value == null) {
9229 el.removeAttribute('class');
9230 }
9231 else if (isSVG) {
9232 el.setAttribute('class', value);
9233 }
9234 else {
9235 el.className = value;
9236 }
9237 }
9238
9239 function patchStyle(el, prev, next) {
9240 const style = el.style;
9241 const isCssString = isString(next);
9242 if (next && !isCssString) {
9243 for (const key in next) {
9244 setStyle(style, key, next[key]);
9245 }
9246 if (prev && !isString(prev)) {
9247 for (const key in prev) {
9248 if (next[key] == null) {
9249 setStyle(style, key, '');
9250 }
9251 }
9252 }
9253 }
9254 else {
9255 const currentDisplay = style.display;
9256 if (isCssString) {
9257 if (prev !== next) {
9258 style.cssText = next;
9259 }
9260 }
9261 else if (prev) {
9262 el.removeAttribute('style');
9263 }
9264 // indicates that the `display` of the element is controlled by `v-show`,
9265 // so we always keep the current `display` value regardless of the `style`
9266 // value, thus handing over control to `v-show`.
9267 if ('_vod' in el) {
9268 style.display = currentDisplay;
9269 }
9270 }
9271 }
9272 const importantRE = /\s*!important$/;
9273 function setStyle(style, name, val) {
9274 if (isArray(val)) {
9275 val.forEach(v => setStyle(style, name, v));
9276 }
9277 else {
9278 if (name.startsWith('--')) {
9279 // custom property definition
9280 style.setProperty(name, val);
9281 }
9282 else {
9283 const prefixed = autoPrefix(style, name);
9284 if (importantRE.test(val)) {
9285 // !important
9286 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9287 }
9288 else {
9289 style[prefixed] = val;
9290 }
9291 }
9292 }
9293 }
9294 const prefixes = ['Webkit', 'Moz', 'ms'];
9295 const prefixCache = {};
9296 function autoPrefix(style, rawName) {
9297 const cached = prefixCache[rawName];
9298 if (cached) {
9299 return cached;
9300 }
9301 let name = camelize(rawName);
9302 if (name !== 'filter' && name in style) {
9303 return (prefixCache[rawName] = name);
9304 }
9305 name = capitalize(name);
9306 for (let i = 0; i < prefixes.length; i++) {
9307 const prefixed = prefixes[i] + name;
9308 if (prefixed in style) {
9309 return (prefixCache[rawName] = prefixed);
9310 }
9311 }
9312 return rawName;
9313 }
9314
9315 const xlinkNS = 'http://www.w3.org/1999/xlink';
9316 function patchAttr(el, key, value, isSVG, instance) {
9317 if (isSVG && key.startsWith('xlink:')) {
9318 if (value == null) {
9319 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9320 }
9321 else {
9322 el.setAttributeNS(xlinkNS, key, value);
9323 }
9324 }
9325 else {
9326 // note we are only checking boolean attributes that don't have a
9327 // corresponding dom prop of the same name here.
9328 const isBoolean = isSpecialBooleanAttr(key);
9329 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9330 el.removeAttribute(key);
9331 }
9332 else {
9333 el.setAttribute(key, isBoolean ? '' : value);
9334 }
9335 }
9336 }
9337
9338 // __UNSAFE__
9339 // functions. The user is responsible for using them with only trusted content.
9340 function patchDOMProp(el, key, value,
9341 // the following args are passed only due to potential innerHTML/textContent
9342 // overriding existing VNodes, in which case the old tree must be properly
9343 // unmounted.
9344 prevChildren, parentComponent, parentSuspense, unmountChildren) {
9345 if (key === 'innerHTML' || key === 'textContent') {
9346 if (prevChildren) {
9347 unmountChildren(prevChildren, parentComponent, parentSuspense);
9348 }
9349 el[key] = value == null ? '' : value;
9350 return;
9351 }
9352 if (key === 'value' &&
9353 el.tagName !== 'PROGRESS' &&
9354 // custom elements may use _value internally
9355 !el.tagName.includes('-')) {
9356 // store value as _value as well since
9357 // non-string values will be stringified.
9358 el._value = value;
9359 const newValue = value == null ? '' : value;
9360 if (el.value !== newValue ||
9361 // #4956: always set for OPTION elements because its value falls back to
9362 // textContent if no value attribute is present. And setting .value for
9363 // OPTION has no side effect
9364 el.tagName === 'OPTION') {
9365 el.value = newValue;
9366 }
9367 if (value == null) {
9368 el.removeAttribute(key);
9369 }
9370 return;
9371 }
9372 if (value === '' || value == null) {
9373 const type = typeof el[key];
9374 if (type === 'boolean') {
9375 // e.g. <select multiple> compiles to { multiple: '' }
9376 el[key] = includeBooleanAttr(value);
9377 return;
9378 }
9379 else if (value == null && type === 'string') {
9380 // e.g. <div :id="null">
9381 el[key] = '';
9382 el.removeAttribute(key);
9383 return;
9384 }
9385 else if (type === 'number') {
9386 // e.g. <img :width="null">
9387 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9388 try {
9389 el[key] = 0;
9390 }
9391 catch (_a) { }
9392 el.removeAttribute(key);
9393 return;
9394 }
9395 }
9396 // some properties perform value validation and throw
9397 try {
9398 el[key] = value;
9399 }
9400 catch (e) {
9401 {
9402 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9403 `value ${value} is invalid.`, e);
9404 }
9405 }
9406 }
9407
9408 // Async edge case fix requires storing an event listener's attach timestamp.
9409 let _getNow = Date.now;
9410 let skipTimestampCheck = false;
9411 if (typeof window !== 'undefined') {
9412 // Determine what event timestamp the browser is using. Annoyingly, the
9413 // timestamp can either be hi-res (relative to page load) or low-res
9414 // (relative to UNIX epoch), so in order to compare time we have to use the
9415 // same timestamp type when saving the flush timestamp.
9416 if (_getNow() > document.createEvent('Event').timeStamp) {
9417 // if the low-res timestamp which is bigger than the event timestamp
9418 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9419 // and we need to use the hi-res version for event listeners as well.
9420 _getNow = () => performance.now();
9421 }
9422 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9423 // and does not fire microtasks in between event propagation, so safe to exclude.
9424 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9425 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9426 }
9427 // To avoid the overhead of repeatedly calling performance.now(), we cache
9428 // and use the same timestamp for all event listeners attached in the same tick.
9429 let cachedNow = 0;
9430 const p = Promise.resolve();
9431 const reset = () => {
9432 cachedNow = 0;
9433 };
9434 const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9435 function addEventListener(el, event, handler, options) {
9436 el.addEventListener(event, handler, options);
9437 }
9438 function removeEventListener(el, event, handler, options) {
9439 el.removeEventListener(event, handler, options);
9440 }
9441 function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9442 // vei = vue event invokers
9443 const invokers = el._vei || (el._vei = {});
9444 const existingInvoker = invokers[rawName];
9445 if (nextValue && existingInvoker) {
9446 // patch
9447 existingInvoker.value = nextValue;
9448 }
9449 else {
9450 const [name, options] = parseName(rawName);
9451 if (nextValue) {
9452 // add
9453 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9454 addEventListener(el, name, invoker, options);
9455 }
9456 else if (existingInvoker) {
9457 // remove
9458 removeEventListener(el, name, existingInvoker, options);
9459 invokers[rawName] = undefined;
9460 }
9461 }
9462 }
9463 const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9464 function parseName(name) {
9465 let options;
9466 if (optionsModifierRE.test(name)) {
9467 options = {};
9468 let m;
9469 while ((m = name.match(optionsModifierRE))) {
9470 name = name.slice(0, name.length - m[0].length);
9471 options[m[0].toLowerCase()] = true;
9472 }
9473 }
9474 return [hyphenate(name.slice(2)), options];
9475 }
9476 function createInvoker(initialValue, instance) {
9477 const invoker = (e) => {
9478 // async edge case #6566: inner click event triggers patch, event handler
9479 // attached to outer element during patch, and triggered again. This
9480 // happens because browsers fire microtask ticks between event propagation.
9481 // the solution is simple: we save the timestamp when a handler is attached,
9482 // and the handler would only fire if the event passed to it was fired
9483 // AFTER it was attached.
9484 const timeStamp = e.timeStamp || _getNow();
9485 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9486 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9487 }
9488 };
9489 invoker.value = initialValue;
9490 invoker.attached = getNow();
9491 return invoker;
9492 }
9493 function patchStopImmediatePropagation(e, value) {
9494 if (isArray(value)) {
9495 const originalStop = e.stopImmediatePropagation;
9496 e.stopImmediatePropagation = () => {
9497 originalStop.call(e);
9498 e._stopped = true;
9499 };
9500 return value.map(fn => (e) => !e._stopped && fn && fn(e));
9501 }
9502 else {
9503 return value;
9504 }
9505 }
9506
9507 const nativeOnRE = /^on[a-z]/;
9508 const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9509 if (key === 'class') {
9510 patchClass(el, nextValue, isSVG);
9511 }
9512 else if (key === 'style') {
9513 patchStyle(el, prevValue, nextValue);
9514 }
9515 else if (isOn(key)) {
9516 // ignore v-model listeners
9517 if (!isModelListener(key)) {
9518 patchEvent(el, key, prevValue, nextValue, parentComponent);
9519 }
9520 }
9521 else if (key[0] === '.'
9522 ? ((key = key.slice(1)), true)
9523 : key[0] === '^'
9524 ? ((key = key.slice(1)), false)
9525 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9526 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9527 }
9528 else {
9529 // special case for <input v-model type="checkbox"> with
9530 // :true-value & :false-value
9531 // store value as dom properties since non-string values will be
9532 // stringified.
9533 if (key === 'true-value') {
9534 el._trueValue = nextValue;
9535 }
9536 else if (key === 'false-value') {
9537 el._falseValue = nextValue;
9538 }
9539 patchAttr(el, key, nextValue, isSVG);
9540 }
9541 };
9542 function shouldSetAsProp(el, key, value, isSVG) {
9543 if (isSVG) {
9544 // most keys must be set as attribute on svg elements to work
9545 // ...except innerHTML & textContent
9546 if (key === 'innerHTML' || key === 'textContent') {
9547 return true;
9548 }
9549 // or native onclick with function values
9550 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9551 return true;
9552 }
9553 return false;
9554 }
9555 // spellcheck and draggable are numerated attrs, however their
9556 // corresponding DOM properties are actually booleans - this leads to
9557 // setting it with a string "false" value leading it to be coerced to
9558 // `true`, so we need to always treat them as attributes.
9559 // Note that `contentEditable` doesn't have this problem: its DOM
9560 // property is also enumerated string values.
9561 if (key === 'spellcheck' || key === 'draggable') {
9562 return false;
9563 }
9564 // #1787, #2840 form property on form elements is readonly and must be set as
9565 // attribute.
9566 if (key === 'form') {
9567 return false;
9568 }
9569 // #1526 <input list> must be set as attribute
9570 if (key === 'list' && el.tagName === 'INPUT') {
9571 return false;
9572 }
9573 // #2766 <textarea type> must be set as attribute
9574 if (key === 'type' && el.tagName === 'TEXTAREA') {
9575 return false;
9576 }
9577 // native onclick with string value, must be set as attribute
9578 if (nativeOnRE.test(key) && isString(value)) {
9579 return false;
9580 }
9581 return key in el;
9582 }
9583
9584 function defineCustomElement(options, hydate) {
9585 const Comp = defineComponent(options);
9586 class VueCustomElement extends VueElement {
9587 constructor(initialProps) {
9588 super(Comp, initialProps, hydate);
9589 }
9590 }
9591 VueCustomElement.def = Comp;
9592 return VueCustomElement;
9593 }
9594 const defineSSRCustomElement = ((options) => {
9595 // @ts-ignore
9596 return defineCustomElement(options, hydrate);
9597 });
9598 const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9599 });
9600 class VueElement extends BaseClass {
9601 constructor(_def, _props = {}, hydrate) {
9602 super();
9603 this._def = _def;
9604 this._props = _props;
9605 /**
9606 * @internal
9607 */
9608 this._instance = null;
9609 this._connected = false;
9610 this._resolved = false;
9611 this._numberProps = null;
9612 if (this.shadowRoot && hydrate) {
9613 hydrate(this._createVNode(), this.shadowRoot);
9614 }
9615 else {
9616 if (this.shadowRoot) {
9617 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9618 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9619 }
9620 this.attachShadow({ mode: 'open' });
9621 }
9622 }
9623 connectedCallback() {
9624 this._connected = true;
9625 if (!this._instance) {
9626 this._resolveDef();
9627 }
9628 }
9629 disconnectedCallback() {
9630 this._connected = false;
9631 nextTick(() => {
9632 if (!this._connected) {
9633 render(null, this.shadowRoot);
9634 this._instance = null;
9635 }
9636 });
9637 }
9638 /**
9639 * resolve inner component definition (handle possible async component)
9640 */
9641 _resolveDef() {
9642 if (this._resolved) {
9643 return;
9644 }
9645 this._resolved = true;
9646 // set initial attrs
9647 for (let i = 0; i < this.attributes.length; i++) {
9648 this._setAttr(this.attributes[i].name);
9649 }
9650 // watch future attr changes
9651 new MutationObserver(mutations => {
9652 for (const m of mutations) {
9653 this._setAttr(m.attributeName);
9654 }
9655 }).observe(this, { attributes: true });
9656 const resolve = (def) => {
9657 const { props, styles } = def;
9658 const hasOptions = !isArray(props);
9659 const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
9660 // cast Number-type props set before resolve
9661 let numberProps;
9662 if (hasOptions) {
9663 for (const key in this._props) {
9664 const opt = props[key];
9665 if (opt === Number || (opt && opt.type === Number)) {
9666 this._props[key] = toNumber(this._props[key]);
9667 (numberProps || (numberProps = Object.create(null)))[key] = true;
9668 }
9669 }
9670 }
9671 this._numberProps = numberProps;
9672 // check if there are props set pre-upgrade or connect
9673 for (const key of Object.keys(this)) {
9674 if (key[0] !== '_') {
9675 this._setProp(key, this[key], true, false);
9676 }
9677 }
9678 // defining getter/setters on prototype
9679 for (const key of rawKeys.map(camelize)) {
9680 Object.defineProperty(this, key, {
9681 get() {
9682 return this._getProp(key);
9683 },
9684 set(val) {
9685 this._setProp(key, val);
9686 }
9687 });
9688 }
9689 // apply CSS
9690 this._applyStyles(styles);
9691 // initial render
9692 this._update();
9693 };
9694 const asyncDef = this._def.__asyncLoader;
9695 if (asyncDef) {
9696 asyncDef().then(resolve);
9697 }
9698 else {
9699 resolve(this._def);
9700 }
9701 }
9702 _setAttr(key) {
9703 let value = this.getAttribute(key);
9704 if (this._numberProps && this._numberProps[key]) {
9705 value = toNumber(value);
9706 }
9707 this._setProp(camelize(key), value, false);
9708 }
9709 /**
9710 * @internal
9711 */
9712 _getProp(key) {
9713 return this._props[key];
9714 }
9715 /**
9716 * @internal
9717 */
9718 _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
9719 if (val !== this._props[key]) {
9720 this._props[key] = val;
9721 if (shouldUpdate && this._instance) {
9722 this._update();
9723 }
9724 // reflect
9725 if (shouldReflect) {
9726 if (val === true) {
9727 this.setAttribute(hyphenate(key), '');
9728 }
9729 else if (typeof val === 'string' || typeof val === 'number') {
9730 this.setAttribute(hyphenate(key), val + '');
9731 }
9732 else if (!val) {
9733 this.removeAttribute(hyphenate(key));
9734 }
9735 }
9736 }
9737 }
9738 _update() {
9739 render(this._createVNode(), this.shadowRoot);
9740 }
9741 _createVNode() {
9742 const vnode = createVNode(this._def, extend({}, this._props));
9743 if (!this._instance) {
9744 vnode.ce = instance => {
9745 this._instance = instance;
9746 instance.isCE = true;
9747 // HMR
9748 {
9749 instance.ceReload = newStyles => {
9750 // always reset styles
9751 if (this._styles) {
9752 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9753 this._styles.length = 0;
9754 }
9755 this._applyStyles(newStyles);
9756 // if this is an async component, ceReload is called from the inner
9757 // component so no need to reload the async wrapper
9758 if (!this._def.__asyncLoader) {
9759 // reload
9760 this._instance = null;
9761 this._update();
9762 }
9763 };
9764 }
9765 // intercept emit
9766 instance.emit = (event, ...args) => {
9767 this.dispatchEvent(new CustomEvent(event, {
9768 detail: args
9769 }));
9770 };
9771 // locate nearest Vue custom element parent for provide/inject
9772 let parent = this;
9773 while ((parent =
9774 parent && (parent.parentNode || parent.host))) {
9775 if (parent instanceof VueElement) {
9776 instance.parent = parent._instance;
9777 break;
9778 }
9779 }
9780 };
9781 }
9782 return vnode;
9783 }
9784 _applyStyles(styles) {
9785 if (styles) {
9786 styles.forEach(css => {
9787 const s = document.createElement('style');
9788 s.textContent = css;
9789 this.shadowRoot.appendChild(s);
9790 // record for HMR
9791 {
9792 (this._styles || (this._styles = [])).push(s);
9793 }
9794 });
9795 }
9796 }
9797 }
9798
9799 function useCssModule(name = '$style') {
9800 /* istanbul ignore else */
9801 {
9802 {
9803 warn$1(`useCssModule() is not supported in the global build.`);
9804 }
9805 return EMPTY_OBJ;
9806 }
9807 }
9808
9809 /**
9810 * Runtime helper for SFC's CSS variable injection feature.
9811 * @private
9812 */
9813 function useCssVars(getter) {
9814 const instance = getCurrentInstance();
9815 /* istanbul ignore next */
9816 if (!instance) {
9817 warn$1(`useCssVars is called without current active component instance.`);
9818 return;
9819 }
9820 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9821 watchPostEffect(setVars);
9822 onMounted(() => {
9823 const ob = new MutationObserver(setVars);
9824 ob.observe(instance.subTree.el.parentNode, { childList: true });
9825 onUnmounted(() => ob.disconnect());
9826 });
9827 }
9828 function setVarsOnVNode(vnode, vars) {
9829 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9830 const suspense = vnode.suspense;
9831 vnode = suspense.activeBranch;
9832 if (suspense.pendingBranch && !suspense.isHydrating) {
9833 suspense.effects.push(() => {
9834 setVarsOnVNode(suspense.activeBranch, vars);
9835 });
9836 }
9837 }
9838 // drill down HOCs until it's a non-component vnode
9839 while (vnode.component) {
9840 vnode = vnode.component.subTree;
9841 }
9842 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
9843 setVarsOnNode(vnode.el, vars);
9844 }
9845 else if (vnode.type === Fragment) {
9846 vnode.children.forEach(c => setVarsOnVNode(c, vars));
9847 }
9848 else if (vnode.type === Static) {
9849 let { el, anchor } = vnode;
9850 while (el) {
9851 setVarsOnNode(el, vars);
9852 if (el === anchor)
9853 break;
9854 el = el.nextSibling;
9855 }
9856 }
9857 }
9858 function setVarsOnNode(el, vars) {
9859 if (el.nodeType === 1) {
9860 const style = el.style;
9861 for (const key in vars) {
9862 style.setProperty(`--${key}`, vars[key]);
9863 }
9864 }
9865 }
9866
9867 const TRANSITION = 'transition';
9868 const ANIMATION = 'animation';
9869 // DOM Transition is a higher-order-component based on the platform-agnostic
9870 // base Transition component, with DOM-specific logic.
9871 const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
9872 Transition.displayName = 'Transition';
9873 const DOMTransitionPropsValidators = {
9874 name: String,
9875 type: String,
9876 css: {
9877 type: Boolean,
9878 default: true
9879 },
9880 duration: [String, Number, Object],
9881 enterFromClass: String,
9882 enterActiveClass: String,
9883 enterToClass: String,
9884 appearFromClass: String,
9885 appearActiveClass: String,
9886 appearToClass: String,
9887 leaveFromClass: String,
9888 leaveActiveClass: String,
9889 leaveToClass: String
9890 };
9891 const TransitionPropsValidators = (Transition.props =
9892 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
9893 /**
9894 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
9895 * with custom HOCs.
9896 */
9897 const callHook$1 = (hook, args = []) => {
9898 if (isArray(hook)) {
9899 hook.forEach(h => h(...args));
9900 }
9901 else if (hook) {
9902 hook(...args);
9903 }
9904 };
9905 /**
9906 * Check if a hook expects a callback (2nd arg), which means the user
9907 * intends to explicitly control the end of the transition.
9908 */
9909 const hasExplicitCallback = (hook) => {
9910 return hook
9911 ? isArray(hook)
9912 ? hook.some(h => h.length > 1)
9913 : hook.length > 1
9914 : false;
9915 };
9916 function resolveTransitionProps(rawProps) {
9917 const baseProps = {};
9918 for (const key in rawProps) {
9919 if (!(key in DOMTransitionPropsValidators)) {
9920 baseProps[key] = rawProps[key];
9921 }
9922 }
9923 if (rawProps.css === false) {
9924 return baseProps;
9925 }
9926 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;
9927 const durations = normalizeDuration(duration);
9928 const enterDuration = durations && durations[0];
9929 const leaveDuration = durations && durations[1];
9930 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
9931 const finishEnter = (el, isAppear, done) => {
9932 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
9933 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
9934 done && done();
9935 };
9936 const finishLeave = (el, done) => {
9937 removeTransitionClass(el, leaveToClass);
9938 removeTransitionClass(el, leaveActiveClass);
9939 done && done();
9940 };
9941 const makeEnterHook = (isAppear) => {
9942 return (el, done) => {
9943 const hook = isAppear ? onAppear : onEnter;
9944 const resolve = () => finishEnter(el, isAppear, done);
9945 callHook$1(hook, [el, resolve]);
9946 nextFrame(() => {
9947 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
9948 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
9949 if (!hasExplicitCallback(hook)) {
9950 whenTransitionEnds(el, type, enterDuration, resolve);
9951 }
9952 });
9953 };
9954 };
9955 return extend(baseProps, {
9956 onBeforeEnter(el) {
9957 callHook$1(onBeforeEnter, [el]);
9958 addTransitionClass(el, enterFromClass);
9959 addTransitionClass(el, enterActiveClass);
9960 },
9961 onBeforeAppear(el) {
9962 callHook$1(onBeforeAppear, [el]);
9963 addTransitionClass(el, appearFromClass);
9964 addTransitionClass(el, appearActiveClass);
9965 },
9966 onEnter: makeEnterHook(false),
9967 onAppear: makeEnterHook(true),
9968 onLeave(el, done) {
9969 const resolve = () => finishLeave(el, done);
9970 addTransitionClass(el, leaveFromClass);
9971 // force reflow so *-leave-from classes immediately take effect (#2593)
9972 forceReflow();
9973 addTransitionClass(el, leaveActiveClass);
9974 nextFrame(() => {
9975 removeTransitionClass(el, leaveFromClass);
9976 addTransitionClass(el, leaveToClass);
9977 if (!hasExplicitCallback(onLeave)) {
9978 whenTransitionEnds(el, type, leaveDuration, resolve);
9979 }
9980 });
9981 callHook$1(onLeave, [el, resolve]);
9982 },
9983 onEnterCancelled(el) {
9984 finishEnter(el, false);
9985 callHook$1(onEnterCancelled, [el]);
9986 },
9987 onAppearCancelled(el) {
9988 finishEnter(el, true);
9989 callHook$1(onAppearCancelled, [el]);
9990 },
9991 onLeaveCancelled(el) {
9992 finishLeave(el);
9993 callHook$1(onLeaveCancelled, [el]);
9994 }
9995 });
9996 }
9997 function normalizeDuration(duration) {
9998 if (duration == null) {
9999 return null;
10000 }
10001 else if (isObject(duration)) {
10002 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10003 }
10004 else {
10005 const n = NumberOf(duration);
10006 return [n, n];
10007 }
10008 }
10009 function NumberOf(val) {
10010 const res = toNumber(val);
10011 validateDuration(res);
10012 return res;
10013 }
10014 function validateDuration(val) {
10015 if (typeof val !== 'number') {
10016 warn$1(`<transition> explicit duration is not a valid number - ` +
10017 `got ${JSON.stringify(val)}.`);
10018 }
10019 else if (isNaN(val)) {
10020 warn$1(`<transition> explicit duration is NaN - ` +
10021 'the duration expression might be incorrect.');
10022 }
10023 }
10024 function addTransitionClass(el, cls) {
10025 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10026 (el._vtc ||
10027 (el._vtc = new Set())).add(cls);
10028 }
10029 function removeTransitionClass(el, cls) {
10030 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10031 const { _vtc } = el;
10032 if (_vtc) {
10033 _vtc.delete(cls);
10034 if (!_vtc.size) {
10035 el._vtc = undefined;
10036 }
10037 }
10038 }
10039 function nextFrame(cb) {
10040 requestAnimationFrame(() => {
10041 requestAnimationFrame(cb);
10042 });
10043 }
10044 let endId = 0;
10045 function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10046 const id = (el._endId = ++endId);
10047 const resolveIfNotStale = () => {
10048 if (id === el._endId) {
10049 resolve();
10050 }
10051 };
10052 if (explicitTimeout) {
10053 return setTimeout(resolveIfNotStale, explicitTimeout);
10054 }
10055 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10056 if (!type) {
10057 return resolve();
10058 }
10059 const endEvent = type + 'end';
10060 let ended = 0;
10061 const end = () => {
10062 el.removeEventListener(endEvent, onEnd);
10063 resolveIfNotStale();
10064 };
10065 const onEnd = (e) => {
10066 if (e.target === el && ++ended >= propCount) {
10067 end();
10068 }
10069 };
10070 setTimeout(() => {
10071 if (ended < propCount) {
10072 end();
10073 }
10074 }, timeout + 1);
10075 el.addEventListener(endEvent, onEnd);
10076 }
10077 function getTransitionInfo(el, expectedType) {
10078 const styles = window.getComputedStyle(el);
10079 // JSDOM may return undefined for transition properties
10080 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10081 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10082 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10083 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10084 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10085 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10086 const animationTimeout = getTimeout(animationDelays, animationDurations);
10087 let type = null;
10088 let timeout = 0;
10089 let propCount = 0;
10090 /* istanbul ignore if */
10091 if (expectedType === TRANSITION) {
10092 if (transitionTimeout > 0) {
10093 type = TRANSITION;
10094 timeout = transitionTimeout;
10095 propCount = transitionDurations.length;
10096 }
10097 }
10098 else if (expectedType === ANIMATION) {
10099 if (animationTimeout > 0) {
10100 type = ANIMATION;
10101 timeout = animationTimeout;
10102 propCount = animationDurations.length;
10103 }
10104 }
10105 else {
10106 timeout = Math.max(transitionTimeout, animationTimeout);
10107 type =
10108 timeout > 0
10109 ? transitionTimeout > animationTimeout
10110 ? TRANSITION
10111 : ANIMATION
10112 : null;
10113 propCount = type
10114 ? type === TRANSITION
10115 ? transitionDurations.length
10116 : animationDurations.length
10117 : 0;
10118 }
10119 const hasTransform = type === TRANSITION &&
10120 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10121 return {
10122 type,
10123 timeout,
10124 propCount,
10125 hasTransform
10126 };
10127 }
10128 function getTimeout(delays, durations) {
10129 while (delays.length < durations.length) {
10130 delays = delays.concat(delays);
10131 }
10132 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10133 }
10134 // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10135 // numbers in a locale-dependent way, using a comma instead of a dot.
10136 // If comma is not replaced with a dot, the input will be rounded down
10137 // (i.e. acting as a floor function) causing unexpected behaviors
10138 function toMs(s) {
10139 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10140 }
10141 // synchronously force layout to put elements into a certain state
10142 function forceReflow() {
10143 return document.body.offsetHeight;
10144 }
10145
10146 const positionMap = new WeakMap();
10147 const newPositionMap = new WeakMap();
10148 const TransitionGroupImpl = {
10149 name: 'TransitionGroup',
10150 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10151 tag: String,
10152 moveClass: String
10153 }),
10154 setup(props, { slots }) {
10155 const instance = getCurrentInstance();
10156 const state = useTransitionState();
10157 let prevChildren;
10158 let children;
10159 onUpdated(() => {
10160 // children is guaranteed to exist after initial render
10161 if (!prevChildren.length) {
10162 return;
10163 }
10164 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10165 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10166 return;
10167 }
10168 // we divide the work into three loops to avoid mixing DOM reads and writes
10169 // in each iteration - which helps prevent layout thrashing.
10170 prevChildren.forEach(callPendingCbs);
10171 prevChildren.forEach(recordPosition);
10172 const movedChildren = prevChildren.filter(applyTranslation);
10173 // force reflow to put everything in position
10174 forceReflow();
10175 movedChildren.forEach(c => {
10176 const el = c.el;
10177 const style = el.style;
10178 addTransitionClass(el, moveClass);
10179 style.transform = style.webkitTransform = style.transitionDuration = '';
10180 const cb = (el._moveCb = (e) => {
10181 if (e && e.target !== el) {
10182 return;
10183 }
10184 if (!e || /transform$/.test(e.propertyName)) {
10185 el.removeEventListener('transitionend', cb);
10186 el._moveCb = null;
10187 removeTransitionClass(el, moveClass);
10188 }
10189 });
10190 el.addEventListener('transitionend', cb);
10191 });
10192 });
10193 return () => {
10194 const rawProps = toRaw(props);
10195 const cssTransitionProps = resolveTransitionProps(rawProps);
10196 let tag = rawProps.tag || Fragment;
10197 prevChildren = children;
10198 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10199 for (let i = 0; i < children.length; i++) {
10200 const child = children[i];
10201 if (child.key != null) {
10202 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10203 }
10204 else {
10205 warn$1(`<TransitionGroup> children must be keyed.`);
10206 }
10207 }
10208 if (prevChildren) {
10209 for (let i = 0; i < prevChildren.length; i++) {
10210 const child = prevChildren[i];
10211 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10212 positionMap.set(child, child.el.getBoundingClientRect());
10213 }
10214 }
10215 return createVNode(tag, null, children);
10216 };
10217 }
10218 };
10219 const TransitionGroup = TransitionGroupImpl;
10220 function callPendingCbs(c) {
10221 const el = c.el;
10222 if (el._moveCb) {
10223 el._moveCb();
10224 }
10225 if (el._enterCb) {
10226 el._enterCb();
10227 }
10228 }
10229 function recordPosition(c) {
10230 newPositionMap.set(c, c.el.getBoundingClientRect());
10231 }
10232 function applyTranslation(c) {
10233 const oldPos = positionMap.get(c);
10234 const newPos = newPositionMap.get(c);
10235 const dx = oldPos.left - newPos.left;
10236 const dy = oldPos.top - newPos.top;
10237 if (dx || dy) {
10238 const s = c.el.style;
10239 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10240 s.transitionDuration = '0s';
10241 return c;
10242 }
10243 }
10244 function hasCSSTransform(el, root, moveClass) {
10245 // Detect whether an element with the move class applied has
10246 // CSS transitions. Since the element may be inside an entering
10247 // transition at this very moment, we make a clone of it and remove
10248 // all other transition classes applied to ensure only the move class
10249 // is applied.
10250 const clone = el.cloneNode();
10251 if (el._vtc) {
10252 el._vtc.forEach(cls => {
10253 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10254 });
10255 }
10256 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10257 clone.style.display = 'none';
10258 const container = (root.nodeType === 1 ? root : root.parentNode);
10259 container.appendChild(clone);
10260 const { hasTransform } = getTransitionInfo(clone);
10261 container.removeChild(clone);
10262 return hasTransform;
10263 }
10264
10265 const getModelAssigner = (vnode) => {
10266 const fn = vnode.props['onUpdate:modelValue'];
10267 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10268 };
10269 function onCompositionStart(e) {
10270 e.target.composing = true;
10271 }
10272 function onCompositionEnd(e) {
10273 const target = e.target;
10274 if (target.composing) {
10275 target.composing = false;
10276 trigger$1(target, 'input');
10277 }
10278 }
10279 function trigger$1(el, type) {
10280 const e = document.createEvent('HTMLEvents');
10281 e.initEvent(type, true, true);
10282 el.dispatchEvent(e);
10283 }
10284 // We are exporting the v-model runtime directly as vnode hooks so that it can
10285 // be tree-shaken in case v-model is never used.
10286 const vModelText = {
10287 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10288 el._assign = getModelAssigner(vnode);
10289 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10290 addEventListener(el, lazy ? 'change' : 'input', e => {
10291 if (e.target.composing)
10292 return;
10293 let domValue = el.value;
10294 if (trim) {
10295 domValue = domValue.trim();
10296 }
10297 else if (castToNumber) {
10298 domValue = toNumber(domValue);
10299 }
10300 el._assign(domValue);
10301 });
10302 if (trim) {
10303 addEventListener(el, 'change', () => {
10304 el.value = el.value.trim();
10305 });
10306 }
10307 if (!lazy) {
10308 addEventListener(el, 'compositionstart', onCompositionStart);
10309 addEventListener(el, 'compositionend', onCompositionEnd);
10310 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10311 // switching focus before confirming composition choice
10312 // this also fixes the issue where some browsers e.g. iOS Chrome
10313 // fires "change" instead of "input" on autocomplete.
10314 addEventListener(el, 'change', onCompositionEnd);
10315 }
10316 },
10317 // set value on mounted so it's after min/max for type="range"
10318 mounted(el, { value }) {
10319 el.value = value == null ? '' : value;
10320 },
10321 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10322 el._assign = getModelAssigner(vnode);
10323 // avoid clearing unresolved text. #2302
10324 if (el.composing)
10325 return;
10326 if (document.activeElement === el) {
10327 if (lazy) {
10328 return;
10329 }
10330 if (trim && el.value.trim() === value) {
10331 return;
10332 }
10333 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10334 return;
10335 }
10336 }
10337 const newValue = value == null ? '' : value;
10338 if (el.value !== newValue) {
10339 el.value = newValue;
10340 }
10341 }
10342 };
10343 const vModelCheckbox = {
10344 // #4096 array checkboxes need to be deep traversed
10345 deep: true,
10346 created(el, _, vnode) {
10347 el._assign = getModelAssigner(vnode);
10348 addEventListener(el, 'change', () => {
10349 const modelValue = el._modelValue;
10350 const elementValue = getValue(el);
10351 const checked = el.checked;
10352 const assign = el._assign;
10353 if (isArray(modelValue)) {
10354 const index = looseIndexOf(modelValue, elementValue);
10355 const found = index !== -1;
10356 if (checked && !found) {
10357 assign(modelValue.concat(elementValue));
10358 }
10359 else if (!checked && found) {
10360 const filtered = [...modelValue];
10361 filtered.splice(index, 1);
10362 assign(filtered);
10363 }
10364 }
10365 else if (isSet(modelValue)) {
10366 const cloned = new Set(modelValue);
10367 if (checked) {
10368 cloned.add(elementValue);
10369 }
10370 else {
10371 cloned.delete(elementValue);
10372 }
10373 assign(cloned);
10374 }
10375 else {
10376 assign(getCheckboxValue(el, checked));
10377 }
10378 });
10379 },
10380 // set initial checked on mount to wait for true-value/false-value
10381 mounted: setChecked,
10382 beforeUpdate(el, binding, vnode) {
10383 el._assign = getModelAssigner(vnode);
10384 setChecked(el, binding, vnode);
10385 }
10386 };
10387 function setChecked(el, { value, oldValue }, vnode) {
10388 el._modelValue = value;
10389 if (isArray(value)) {
10390 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10391 }
10392 else if (isSet(value)) {
10393 el.checked = value.has(vnode.props.value);
10394 }
10395 else if (value !== oldValue) {
10396 el.checked = looseEqual(value, getCheckboxValue(el, true));
10397 }
10398 }
10399 const vModelRadio = {
10400 created(el, { value }, vnode) {
10401 el.checked = looseEqual(value, vnode.props.value);
10402 el._assign = getModelAssigner(vnode);
10403 addEventListener(el, 'change', () => {
10404 el._assign(getValue(el));
10405 });
10406 },
10407 beforeUpdate(el, { value, oldValue }, vnode) {
10408 el._assign = getModelAssigner(vnode);
10409 if (value !== oldValue) {
10410 el.checked = looseEqual(value, vnode.props.value);
10411 }
10412 }
10413 };
10414 const vModelSelect = {
10415 // <select multiple> value need to be deep traversed
10416 deep: true,
10417 created(el, { value, modifiers: { number } }, vnode) {
10418 const isSetModel = isSet(value);
10419 addEventListener(el, 'change', () => {
10420 const selectedVal = Array.prototype.filter
10421 .call(el.options, (o) => o.selected)
10422 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10423 el._assign(el.multiple
10424 ? isSetModel
10425 ? new Set(selectedVal)
10426 : selectedVal
10427 : selectedVal[0]);
10428 });
10429 el._assign = getModelAssigner(vnode);
10430 },
10431 // set value in mounted & updated because <select> relies on its children
10432 // <option>s.
10433 mounted(el, { value }) {
10434 setSelected(el, value);
10435 },
10436 beforeUpdate(el, _binding, vnode) {
10437 el._assign = getModelAssigner(vnode);
10438 },
10439 updated(el, { value }) {
10440 setSelected(el, value);
10441 }
10442 };
10443 function setSelected(el, value) {
10444 const isMultiple = el.multiple;
10445 if (isMultiple && !isArray(value) && !isSet(value)) {
10446 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10447 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10448 return;
10449 }
10450 for (let i = 0, l = el.options.length; i < l; i++) {
10451 const option = el.options[i];
10452 const optionValue = getValue(option);
10453 if (isMultiple) {
10454 if (isArray(value)) {
10455 option.selected = looseIndexOf(value, optionValue) > -1;
10456 }
10457 else {
10458 option.selected = value.has(optionValue);
10459 }
10460 }
10461 else {
10462 if (looseEqual(getValue(option), value)) {
10463 if (el.selectedIndex !== i)
10464 el.selectedIndex = i;
10465 return;
10466 }
10467 }
10468 }
10469 if (!isMultiple && el.selectedIndex !== -1) {
10470 el.selectedIndex = -1;
10471 }
10472 }
10473 // retrieve raw value set via :value bindings
10474 function getValue(el) {
10475 return '_value' in el ? el._value : el.value;
10476 }
10477 // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10478 function getCheckboxValue(el, checked) {
10479 const key = checked ? '_trueValue' : '_falseValue';
10480 return key in el ? el[key] : checked;
10481 }
10482 const vModelDynamic = {
10483 created(el, binding, vnode) {
10484 callModelHook(el, binding, vnode, null, 'created');
10485 },
10486 mounted(el, binding, vnode) {
10487 callModelHook(el, binding, vnode, null, 'mounted');
10488 },
10489 beforeUpdate(el, binding, vnode, prevVNode) {
10490 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10491 },
10492 updated(el, binding, vnode, prevVNode) {
10493 callModelHook(el, binding, vnode, prevVNode, 'updated');
10494 }
10495 };
10496 function callModelHook(el, binding, vnode, prevVNode, hook) {
10497 let modelToUse;
10498 switch (el.tagName) {
10499 case 'SELECT':
10500 modelToUse = vModelSelect;
10501 break;
10502 case 'TEXTAREA':
10503 modelToUse = vModelText;
10504 break;
10505 default:
10506 switch (vnode.props && vnode.props.type) {
10507 case 'checkbox':
10508 modelToUse = vModelCheckbox;
10509 break;
10510 case 'radio':
10511 modelToUse = vModelRadio;
10512 break;
10513 default:
10514 modelToUse = vModelText;
10515 }
10516 }
10517 const fn = modelToUse[hook];
10518 fn && fn(el, binding, vnode, prevVNode);
10519 }
10520
10521 const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10522 const modifierGuards = {
10523 stop: e => e.stopPropagation(),
10524 prevent: e => e.preventDefault(),
10525 self: e => e.target !== e.currentTarget,
10526 ctrl: e => !e.ctrlKey,
10527 shift: e => !e.shiftKey,
10528 alt: e => !e.altKey,
10529 meta: e => !e.metaKey,
10530 left: e => 'button' in e && e.button !== 0,
10531 middle: e => 'button' in e && e.button !== 1,
10532 right: e => 'button' in e && e.button !== 2,
10533 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10534 };
10535 /**
10536 * @private
10537 */
10538 const withModifiers = (fn, modifiers) => {
10539 return (event, ...args) => {
10540 for (let i = 0; i < modifiers.length; i++) {
10541 const guard = modifierGuards[modifiers[i]];
10542 if (guard && guard(event, modifiers))
10543 return;
10544 }
10545 return fn(event, ...args);
10546 };
10547 };
10548 // Kept for 2.x compat.
10549 // Note: IE11 compat for `spacebar` and `del` is removed for now.
10550 const keyNames = {
10551 esc: 'escape',
10552 space: ' ',
10553 up: 'arrow-up',
10554 left: 'arrow-left',
10555 right: 'arrow-right',
10556 down: 'arrow-down',
10557 delete: 'backspace'
10558 };
10559 /**
10560 * @private
10561 */
10562 const withKeys = (fn, modifiers) => {
10563 return (event) => {
10564 if (!('key' in event)) {
10565 return;
10566 }
10567 const eventKey = hyphenate(event.key);
10568 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10569 return fn(event);
10570 }
10571 };
10572 };
10573
10574 const vShow = {
10575 beforeMount(el, { value }, { transition }) {
10576 el._vod = el.style.display === 'none' ? '' : el.style.display;
10577 if (transition && value) {
10578 transition.beforeEnter(el);
10579 }
10580 else {
10581 setDisplay(el, value);
10582 }
10583 },
10584 mounted(el, { value }, { transition }) {
10585 if (transition && value) {
10586 transition.enter(el);
10587 }
10588 },
10589 updated(el, { value, oldValue }, { transition }) {
10590 if (!value === !oldValue)
10591 return;
10592 if (transition) {
10593 if (value) {
10594 transition.beforeEnter(el);
10595 setDisplay(el, true);
10596 transition.enter(el);
10597 }
10598 else {
10599 transition.leave(el, () => {
10600 setDisplay(el, false);
10601 });
10602 }
10603 }
10604 else {
10605 setDisplay(el, value);
10606 }
10607 },
10608 beforeUnmount(el, { value }) {
10609 setDisplay(el, value);
10610 }
10611 };
10612 function setDisplay(el, value) {
10613 el.style.display = value ? el._vod : 'none';
10614 }
10615
10616 const rendererOptions = extend({ patchProp }, nodeOps);
10617 // lazy create the renderer - this makes core renderer logic tree-shakable
10618 // in case the user only imports reactivity utilities from Vue.
10619 let renderer;
10620 let enabledHydration = false;
10621 function ensureRenderer() {
10622 return (renderer ||
10623 (renderer = createRenderer(rendererOptions)));
10624 }
10625 function ensureHydrationRenderer() {
10626 renderer = enabledHydration
10627 ? renderer
10628 : createHydrationRenderer(rendererOptions);
10629 enabledHydration = true;
10630 return renderer;
10631 }
10632 // use explicit type casts here to avoid import() calls in rolled-up d.ts
10633 const render = ((...args) => {
10634 ensureRenderer().render(...args);
10635 });
10636 const hydrate = ((...args) => {
10637 ensureHydrationRenderer().hydrate(...args);
10638 });
10639 const createApp = ((...args) => {
10640 const app = ensureRenderer().createApp(...args);
10641 {
10642 injectNativeTagCheck(app);
10643 injectCompilerOptionsCheck(app);
10644 }
10645 const { mount } = app;
10646 app.mount = (containerOrSelector) => {
10647 const container = normalizeContainer(containerOrSelector);
10648 if (!container)
10649 return;
10650 const component = app._component;
10651 if (!isFunction(component) && !component.render && !component.template) {
10652 // __UNSAFE__
10653 // Reason: potential execution of JS expressions in in-DOM template.
10654 // The user must make sure the in-DOM template is trusted. If it's
10655 // rendered by the server, the template should not contain any user data.
10656 component.template = container.innerHTML;
10657 }
10658 // clear content before mounting
10659 container.innerHTML = '';
10660 const proxy = mount(container, false, container instanceof SVGElement);
10661 if (container instanceof Element) {
10662 container.removeAttribute('v-cloak');
10663 container.setAttribute('data-v-app', '');
10664 }
10665 return proxy;
10666 };
10667 return app;
10668 });
10669 const createSSRApp = ((...args) => {
10670 const app = ensureHydrationRenderer().createApp(...args);
10671 {
10672 injectNativeTagCheck(app);
10673 injectCompilerOptionsCheck(app);
10674 }
10675 const { mount } = app;
10676 app.mount = (containerOrSelector) => {
10677 const container = normalizeContainer(containerOrSelector);
10678 if (container) {
10679 return mount(container, true, container instanceof SVGElement);
10680 }
10681 };
10682 return app;
10683 });
10684 function injectNativeTagCheck(app) {
10685 // Inject `isNativeTag`
10686 // this is used for component name validation (dev only)
10687 Object.defineProperty(app.config, 'isNativeTag', {
10688 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10689 writable: false
10690 });
10691 }
10692 // dev only
10693 function injectCompilerOptionsCheck(app) {
10694 if (isRuntimeOnly()) {
10695 const isCustomElement = app.config.isCustomElement;
10696 Object.defineProperty(app.config, 'isCustomElement', {
10697 get() {
10698 return isCustomElement;
10699 },
10700 set() {
10701 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10702 `\`compilerOptions.isCustomElement\` instead.`);
10703 }
10704 });
10705 const compilerOptions = app.config.compilerOptions;
10706 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10707 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10708 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10709 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10710 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10711 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10712 `- 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`;
10713 Object.defineProperty(app.config, 'compilerOptions', {
10714 get() {
10715 warn$1(msg);
10716 return compilerOptions;
10717 },
10718 set() {
10719 warn$1(msg);
10720 }
10721 });
10722 }
10723 }
10724 function normalizeContainer(container) {
10725 if (isString(container)) {
10726 const res = document.querySelector(container);
10727 if (!res) {
10728 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10729 }
10730 return res;
10731 }
10732 if (window.ShadowRoot &&
10733 container instanceof window.ShadowRoot &&
10734 container.mode === 'closed') {
10735 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10736 }
10737 return container;
10738 }
10739 /**
10740 * @internal
10741 */
10742 const initDirectivesForSSR = NOOP;
10743
10744 function initDev() {
10745 {
10746 {
10747 console.info(`You are running a development build of Vue.\n` +
10748 `Make sure to use the production build (*.prod.js) when deploying for production.`);
10749 }
10750 initCustomFormatter();
10751 }
10752 }
10753
10754 function defaultOnError(error) {
10755 throw error;
10756 }
10757 function defaultOnWarn(msg) {
10758 console.warn(`[Vue warn] ${msg.message}`);
10759 }
10760 function createCompilerError(code, loc, messages, additionalMessage) {
10761 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
10762 ;
10763 const error = new SyntaxError(String(msg));
10764 error.code = code;
10765 error.loc = loc;
10766 return error;
10767 }
10768 const errorMessages = {
10769 // parse errors
10770 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
10771 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
10772 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
10773 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
10774 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
10775 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
10776 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
10777 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
10778 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
10779 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
10780 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
10781 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
10782 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
10783 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
10784 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
10785 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
10786 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
10787 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
10788 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
10789 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
10790 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
10791 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
10792 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
10793 // Vue-specific parse errors
10794 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
10795 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
10796 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
10797 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
10798 'Note that dynamic directive argument cannot contain spaces.',
10799 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
10800 // transform errors
10801 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
10802 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
10803 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
10804 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
10805 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
10806 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
10807 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
10808 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
10809 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
10810 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
10811 `When there are multiple named slots, all slots should use <template> ` +
10812 `syntax to avoid scope ambiguity.`,
10813 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
10814 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
10815 `default slot. These children will be ignored.`,
10816 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
10817 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
10818 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
10819 [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.`,
10820 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
10821 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
10822 // generic errors
10823 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
10824 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
10825 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
10826 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
10827 // just to fulfill types
10828 [50 /* __EXTEND_POINT__ */]: ``
10829 };
10830
10831 const FRAGMENT = Symbol(`Fragment` );
10832 const TELEPORT = Symbol(`Teleport` );
10833 const SUSPENSE = Symbol(`Suspense` );
10834 const KEEP_ALIVE = Symbol(`KeepAlive` );
10835 const BASE_TRANSITION = Symbol(`BaseTransition` );
10836 const OPEN_BLOCK = Symbol(`openBlock` );
10837 const CREATE_BLOCK = Symbol(`createBlock` );
10838 const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
10839 const CREATE_VNODE = Symbol(`createVNode` );
10840 const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
10841 const CREATE_COMMENT = Symbol(`createCommentVNode` );
10842 const CREATE_TEXT = Symbol(`createTextVNode` );
10843 const CREATE_STATIC = Symbol(`createStaticVNode` );
10844 const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
10845 const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
10846 const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
10847 const RESOLVE_FILTER = Symbol(`resolveFilter` );
10848 const WITH_DIRECTIVES = Symbol(`withDirectives` );
10849 const RENDER_LIST = Symbol(`renderList` );
10850 const RENDER_SLOT = Symbol(`renderSlot` );
10851 const CREATE_SLOTS = Symbol(`createSlots` );
10852 const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
10853 const MERGE_PROPS = Symbol(`mergeProps` );
10854 const NORMALIZE_CLASS = Symbol(`normalizeClass` );
10855 const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
10856 const NORMALIZE_PROPS = Symbol(`normalizeProps` );
10857 const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
10858 const TO_HANDLERS = Symbol(`toHandlers` );
10859 const CAMELIZE = Symbol(`camelize` );
10860 const CAPITALIZE = Symbol(`capitalize` );
10861 const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
10862 const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
10863 const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
10864 const POP_SCOPE_ID = Symbol(`popScopeId` );
10865 const WITH_CTX = Symbol(`withCtx` );
10866 const UNREF = Symbol(`unref` );
10867 const IS_REF = Symbol(`isRef` );
10868 const WITH_MEMO = Symbol(`withMemo` );
10869 const IS_MEMO_SAME = Symbol(`isMemoSame` );
10870 // Name mapping for runtime helpers that need to be imported from 'vue' in
10871 // generated code. Make sure these are correctly exported in the runtime!
10872 // Using `any` here because TS doesn't allow symbols as index type.
10873 const helperNameMap = {
10874 [FRAGMENT]: `Fragment`,
10875 [TELEPORT]: `Teleport`,
10876 [SUSPENSE]: `Suspense`,
10877 [KEEP_ALIVE]: `KeepAlive`,
10878 [BASE_TRANSITION]: `BaseTransition`,
10879 [OPEN_BLOCK]: `openBlock`,
10880 [CREATE_BLOCK]: `createBlock`,
10881 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
10882 [CREATE_VNODE]: `createVNode`,
10883 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
10884 [CREATE_COMMENT]: `createCommentVNode`,
10885 [CREATE_TEXT]: `createTextVNode`,
10886 [CREATE_STATIC]: `createStaticVNode`,
10887 [RESOLVE_COMPONENT]: `resolveComponent`,
10888 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
10889 [RESOLVE_DIRECTIVE]: `resolveDirective`,
10890 [RESOLVE_FILTER]: `resolveFilter`,
10891 [WITH_DIRECTIVES]: `withDirectives`,
10892 [RENDER_LIST]: `renderList`,
10893 [RENDER_SLOT]: `renderSlot`,
10894 [CREATE_SLOTS]: `createSlots`,
10895 [TO_DISPLAY_STRING]: `toDisplayString`,
10896 [MERGE_PROPS]: `mergeProps`,
10897 [NORMALIZE_CLASS]: `normalizeClass`,
10898 [NORMALIZE_STYLE]: `normalizeStyle`,
10899 [NORMALIZE_PROPS]: `normalizeProps`,
10900 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
10901 [TO_HANDLERS]: `toHandlers`,
10902 [CAMELIZE]: `camelize`,
10903 [CAPITALIZE]: `capitalize`,
10904 [TO_HANDLER_KEY]: `toHandlerKey`,
10905 [SET_BLOCK_TRACKING]: `setBlockTracking`,
10906 [PUSH_SCOPE_ID]: `pushScopeId`,
10907 [POP_SCOPE_ID]: `popScopeId`,
10908 [WITH_CTX]: `withCtx`,
10909 [UNREF]: `unref`,
10910 [IS_REF]: `isRef`,
10911 [WITH_MEMO]: `withMemo`,
10912 [IS_MEMO_SAME]: `isMemoSame`
10913 };
10914 function registerRuntimeHelpers(helpers) {
10915 Object.getOwnPropertySymbols(helpers).forEach(s => {
10916 helperNameMap[s] = helpers[s];
10917 });
10918 }
10919
10920 // AST Utilities ---------------------------------------------------------------
10921 // Some expressions, e.g. sequence and conditional expressions, are never
10922 // associated with template nodes, so their source locations are just a stub.
10923 // Container types like CompoundExpression also don't need a real location.
10924 const locStub = {
10925 source: '',
10926 start: { line: 1, column: 1, offset: 0 },
10927 end: { line: 1, column: 1, offset: 0 }
10928 };
10929 function createRoot(children, loc = locStub) {
10930 return {
10931 type: 0 /* ROOT */,
10932 children,
10933 helpers: [],
10934 components: [],
10935 directives: [],
10936 hoists: [],
10937 imports: [],
10938 cached: 0,
10939 temps: 0,
10940 codegenNode: undefined,
10941 loc
10942 };
10943 }
10944 function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
10945 if (context) {
10946 if (isBlock) {
10947 context.helper(OPEN_BLOCK);
10948 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
10949 }
10950 else {
10951 context.helper(getVNodeHelper(context.inSSR, isComponent));
10952 }
10953 if (directives) {
10954 context.helper(WITH_DIRECTIVES);
10955 }
10956 }
10957 return {
10958 type: 13 /* VNODE_CALL */,
10959 tag,
10960 props,
10961 children,
10962 patchFlag,
10963 dynamicProps,
10964 directives,
10965 isBlock,
10966 disableTracking,
10967 isComponent,
10968 loc
10969 };
10970 }
10971 function createArrayExpression(elements, loc = locStub) {
10972 return {
10973 type: 17 /* JS_ARRAY_EXPRESSION */,
10974 loc,
10975 elements
10976 };
10977 }
10978 function createObjectExpression(properties, loc = locStub) {
10979 return {
10980 type: 15 /* JS_OBJECT_EXPRESSION */,
10981 loc,
10982 properties
10983 };
10984 }
10985 function createObjectProperty(key, value) {
10986 return {
10987 type: 16 /* JS_PROPERTY */,
10988 loc: locStub,
10989 key: isString(key) ? createSimpleExpression(key, true) : key,
10990 value
10991 };
10992 }
10993 function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
10994 return {
10995 type: 4 /* SIMPLE_EXPRESSION */,
10996 loc,
10997 content,
10998 isStatic,
10999 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11000 };
11001 }
11002 function createCompoundExpression(children, loc = locStub) {
11003 return {
11004 type: 8 /* COMPOUND_EXPRESSION */,
11005 loc,
11006 children
11007 };
11008 }
11009 function createCallExpression(callee, args = [], loc = locStub) {
11010 return {
11011 type: 14 /* JS_CALL_EXPRESSION */,
11012 loc,
11013 callee,
11014 arguments: args
11015 };
11016 }
11017 function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11018 return {
11019 type: 18 /* JS_FUNCTION_EXPRESSION */,
11020 params,
11021 returns,
11022 newline,
11023 isSlot,
11024 loc
11025 };
11026 }
11027 function createConditionalExpression(test, consequent, alternate, newline = true) {
11028 return {
11029 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11030 test,
11031 consequent,
11032 alternate,
11033 newline,
11034 loc: locStub
11035 };
11036 }
11037 function createCacheExpression(index, value, isVNode = false) {
11038 return {
11039 type: 20 /* JS_CACHE_EXPRESSION */,
11040 index,
11041 value,
11042 isVNode,
11043 loc: locStub
11044 };
11045 }
11046 function createBlockStatement(body) {
11047 return {
11048 type: 21 /* JS_BLOCK_STATEMENT */,
11049 body,
11050 loc: locStub
11051 };
11052 }
11053
11054 const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11055 const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11056 function isCoreComponent(tag) {
11057 if (isBuiltInType(tag, 'Teleport')) {
11058 return TELEPORT;
11059 }
11060 else if (isBuiltInType(tag, 'Suspense')) {
11061 return SUSPENSE;
11062 }
11063 else if (isBuiltInType(tag, 'KeepAlive')) {
11064 return KEEP_ALIVE;
11065 }
11066 else if (isBuiltInType(tag, 'BaseTransition')) {
11067 return BASE_TRANSITION;
11068 }
11069 }
11070 const nonIdentifierRE = /^\d|[^\$\w]/;
11071 const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11072 const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11073 const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11074 const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11075 /**
11076 * Simple lexer to check if an expression is a member expression. This is
11077 * lax and only checks validity at the root level (i.e. does not validate exps
11078 * inside square brackets), but it's ok since these are only used on template
11079 * expressions and false positives are invalid expressions in the first place.
11080 */
11081 const isMemberExpressionBrowser = (path) => {
11082 // remove whitespaces around . or [ first
11083 path = path.trim().replace(whitespaceRE, s => s.trim());
11084 let state = 0 /* inMemberExp */;
11085 let stateStack = [];
11086 let currentOpenBracketCount = 0;
11087 let currentOpenParensCount = 0;
11088 let currentStringType = null;
11089 for (let i = 0; i < path.length; i++) {
11090 const char = path.charAt(i);
11091 switch (state) {
11092 case 0 /* inMemberExp */:
11093 if (char === '[') {
11094 stateStack.push(state);
11095 state = 1 /* inBrackets */;
11096 currentOpenBracketCount++;
11097 }
11098 else if (char === '(') {
11099 stateStack.push(state);
11100 state = 2 /* inParens */;
11101 currentOpenParensCount++;
11102 }
11103 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11104 return false;
11105 }
11106 break;
11107 case 1 /* inBrackets */:
11108 if (char === `'` || char === `"` || char === '`') {
11109 stateStack.push(state);
11110 state = 3 /* inString */;
11111 currentStringType = char;
11112 }
11113 else if (char === `[`) {
11114 currentOpenBracketCount++;
11115 }
11116 else if (char === `]`) {
11117 if (!--currentOpenBracketCount) {
11118 state = stateStack.pop();
11119 }
11120 }
11121 break;
11122 case 2 /* inParens */:
11123 if (char === `'` || char === `"` || char === '`') {
11124 stateStack.push(state);
11125 state = 3 /* inString */;
11126 currentStringType = char;
11127 }
11128 else if (char === `(`) {
11129 currentOpenParensCount++;
11130 }
11131 else if (char === `)`) {
11132 // if the exp ends as a call then it should not be considered valid
11133 if (i === path.length - 1) {
11134 return false;
11135 }
11136 if (!--currentOpenParensCount) {
11137 state = stateStack.pop();
11138 }
11139 }
11140 break;
11141 case 3 /* inString */:
11142 if (char === currentStringType) {
11143 state = stateStack.pop();
11144 currentStringType = null;
11145 }
11146 break;
11147 }
11148 }
11149 return !currentOpenBracketCount && !currentOpenParensCount;
11150 };
11151 const isMemberExpression = isMemberExpressionBrowser
11152 ;
11153 function getInnerRange(loc, offset, length) {
11154 const source = loc.source.slice(offset, offset + length);
11155 const newLoc = {
11156 source,
11157 start: advancePositionWithClone(loc.start, loc.source, offset),
11158 end: loc.end
11159 };
11160 if (length != null) {
11161 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11162 }
11163 return newLoc;
11164 }
11165 function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11166 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11167 }
11168 // advance by mutation without cloning (for performance reasons), since this
11169 // gets called a lot in the parser
11170 function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11171 let linesCount = 0;
11172 let lastNewLinePos = -1;
11173 for (let i = 0; i < numberOfCharacters; i++) {
11174 if (source.charCodeAt(i) === 10 /* newline char code */) {
11175 linesCount++;
11176 lastNewLinePos = i;
11177 }
11178 }
11179 pos.offset += numberOfCharacters;
11180 pos.line += linesCount;
11181 pos.column =
11182 lastNewLinePos === -1
11183 ? pos.column + numberOfCharacters
11184 : numberOfCharacters - lastNewLinePos;
11185 return pos;
11186 }
11187 function assert(condition, msg) {
11188 /* istanbul ignore if */
11189 if (!condition) {
11190 throw new Error(msg || `unexpected compiler condition`);
11191 }
11192 }
11193 function findDir(node, name, allowEmpty = false) {
11194 for (let i = 0; i < node.props.length; i++) {
11195 const p = node.props[i];
11196 if (p.type === 7 /* DIRECTIVE */ &&
11197 (allowEmpty || p.exp) &&
11198 (isString(name) ? p.name === name : name.test(p.name))) {
11199 return p;
11200 }
11201 }
11202 }
11203 function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11204 for (let i = 0; i < node.props.length; i++) {
11205 const p = node.props[i];
11206 if (p.type === 6 /* ATTRIBUTE */) {
11207 if (dynamicOnly)
11208 continue;
11209 if (p.name === name && (p.value || allowEmpty)) {
11210 return p;
11211 }
11212 }
11213 else if (p.name === 'bind' &&
11214 (p.exp || allowEmpty) &&
11215 isStaticArgOf(p.arg, name)) {
11216 return p;
11217 }
11218 }
11219 }
11220 function isStaticArgOf(arg, name) {
11221 return !!(arg && isStaticExp(arg) && arg.content === name);
11222 }
11223 function hasDynamicKeyVBind(node) {
11224 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11225 p.name === 'bind' &&
11226 (!p.arg || // v-bind="obj"
11227 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11228 !p.arg.isStatic) // v-bind:[foo]
11229 );
11230 }
11231 function isText(node) {
11232 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11233 }
11234 function isVSlot(p) {
11235 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11236 }
11237 function isTemplateNode(node) {
11238 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11239 }
11240 function isSlotOutlet(node) {
11241 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11242 }
11243 function getVNodeHelper(ssr, isComponent) {
11244 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11245 }
11246 function getVNodeBlockHelper(ssr, isComponent) {
11247 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11248 }
11249 const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11250 function getUnnormalizedProps(props, callPath = []) {
11251 if (props &&
11252 !isString(props) &&
11253 props.type === 14 /* JS_CALL_EXPRESSION */) {
11254 const callee = props.callee;
11255 if (!isString(callee) && propsHelperSet.has(callee)) {
11256 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11257 }
11258 }
11259 return [props, callPath];
11260 }
11261 function injectProp(node, prop, context) {
11262 let propsWithInjection;
11263 /**
11264 * 1. mergeProps(...)
11265 * 2. toHandlers(...)
11266 * 3. normalizeProps(...)
11267 * 4. normalizeProps(guardReactiveProps(...))
11268 *
11269 * we need to get the real props before normalization
11270 */
11271 let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11272 let callPath = [];
11273 let parentCall;
11274 if (props &&
11275 !isString(props) &&
11276 props.type === 14 /* JS_CALL_EXPRESSION */) {
11277 const ret = getUnnormalizedProps(props);
11278 props = ret[0];
11279 callPath = ret[1];
11280 parentCall = callPath[callPath.length - 1];
11281 }
11282 if (props == null || isString(props)) {
11283 propsWithInjection = createObjectExpression([prop]);
11284 }
11285 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11286 // merged props... add ours
11287 // only inject key to object literal if it's the first argument so that
11288 // if doesn't override user provided keys
11289 const first = props.arguments[0];
11290 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11291 first.properties.unshift(prop);
11292 }
11293 else {
11294 if (props.callee === TO_HANDLERS) {
11295 // #2366
11296 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11297 createObjectExpression([prop]),
11298 props
11299 ]);
11300 }
11301 else {
11302 props.arguments.unshift(createObjectExpression([prop]));
11303 }
11304 }
11305 !propsWithInjection && (propsWithInjection = props);
11306 }
11307 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11308 let alreadyExists = false;
11309 // check existing key to avoid overriding user provided keys
11310 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11311 const propKeyName = prop.key.content;
11312 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11313 p.key.content === propKeyName);
11314 }
11315 if (!alreadyExists) {
11316 props.properties.unshift(prop);
11317 }
11318 propsWithInjection = props;
11319 }
11320 else {
11321 // single v-bind with expression, return a merged replacement
11322 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11323 createObjectExpression([prop]),
11324 props
11325 ]);
11326 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11327 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11328 // the `guardReactiveProps` will no longer be needed
11329 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11330 parentCall = callPath[callPath.length - 2];
11331 }
11332 }
11333 if (node.type === 13 /* VNODE_CALL */) {
11334 if (parentCall) {
11335 parentCall.arguments[0] = propsWithInjection;
11336 }
11337 else {
11338 node.props = propsWithInjection;
11339 }
11340 }
11341 else {
11342 if (parentCall) {
11343 parentCall.arguments[0] = propsWithInjection;
11344 }
11345 else {
11346 node.arguments[2] = propsWithInjection;
11347 }
11348 }
11349 }
11350 function toValidAssetId(name, type) {
11351 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11352 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11353 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11354 })}`;
11355 }
11356 function getMemoedVNodeCall(node) {
11357 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11358 return node.arguments[1].returns;
11359 }
11360 else {
11361 return node;
11362 }
11363 }
11364 function makeBlock(node, { helper, removeHelper, inSSR }) {
11365 if (!node.isBlock) {
11366 node.isBlock = true;
11367 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11368 helper(OPEN_BLOCK);
11369 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11370 }
11371 }
11372
11373 const deprecationData = {
11374 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11375 message: `Platform-native elements with "is" prop will no longer be ` +
11376 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11377 `prefixed with "vue:".`,
11378 link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
11379 },
11380 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11381 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11382 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11383 `\`v-model:${key}\`.`,
11384 link: `https://v3.vuejs.org/guide/migration/v-model.html`
11385 },
11386 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11387 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11388 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11389 },
11390 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11391 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11392 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11393 `that appears before v-bind in the case of conflict. ` +
11394 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11395 `You can also suppress this warning if the usage is intended.`,
11396 link: `https://v3.vuejs.org/guide/migration/v-bind.html`
11397 },
11398 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11399 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11400 link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
11401 },
11402 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11403 message: `v-if / v-for precedence when used on the same element has changed ` +
11404 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11405 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11406 `with <template> tags or use a computed property that filters v-for ` +
11407 `data source.`,
11408 link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
11409 },
11410 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11411 message: `<template> with no special directives will render as a native template ` +
11412 `element instead of its inner content in Vue 3.`
11413 },
11414 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11415 message: `"inline-template" has been removed in Vue 3.`,
11416 link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
11417 },
11418 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11419 message: `filters have been removed in Vue 3. ` +
11420 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11421 `Use method calls or computed properties instead.`,
11422 link: `https://v3.vuejs.org/guide/migration/filters.html`
11423 }
11424 };
11425 function getCompatValue(key, context) {
11426 const config = context.options
11427 ? context.options.compatConfig
11428 : context.compatConfig;
11429 const value = config && config[key];
11430 if (key === 'MODE') {
11431 return value || 3; // compiler defaults to v3 behavior
11432 }
11433 else {
11434 return value;
11435 }
11436 }
11437 function isCompatEnabled(key, context) {
11438 const mode = getCompatValue('MODE', context);
11439 const value = getCompatValue(key, context);
11440 // in v3 mode, only enable if explicitly set to true
11441 // otherwise enable for any non-false value
11442 return mode === 3 ? value === true : value !== false;
11443 }
11444 function checkCompatEnabled(key, context, loc, ...args) {
11445 const enabled = isCompatEnabled(key, context);
11446 if (enabled) {
11447 warnDeprecation(key, context, loc, ...args);
11448 }
11449 return enabled;
11450 }
11451 function warnDeprecation(key, context, loc, ...args) {
11452 const val = getCompatValue(key, context);
11453 if (val === 'suppress-warning') {
11454 return;
11455 }
11456 const { message, link } = deprecationData[key];
11457 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11458 const err = new SyntaxError(msg);
11459 err.code = key;
11460 if (loc)
11461 err.loc = loc;
11462 context.onWarn(err);
11463 }
11464
11465 // The default decoder only provides escapes for characters reserved as part of
11466 // the template syntax, and is only used if the custom renderer did not provide
11467 // a platform-specific decoder.
11468 const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11469 const decodeMap = {
11470 gt: '>',
11471 lt: '<',
11472 amp: '&',
11473 apos: "'",
11474 quot: '"'
11475 };
11476 const defaultParserOptions = {
11477 delimiters: [`{{`, `}}`],
11478 getNamespace: () => 0 /* HTML */,
11479 getTextMode: () => 0 /* DATA */,
11480 isVoidTag: NO,
11481 isPreTag: NO,
11482 isCustomElement: NO,
11483 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11484 onError: defaultOnError,
11485 onWarn: defaultOnWarn,
11486 comments: true
11487 };
11488 function baseParse(content, options = {}) {
11489 const context = createParserContext(content, options);
11490 const start = getCursor(context);
11491 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11492 }
11493 function createParserContext(content, rawOptions) {
11494 const options = extend({}, defaultParserOptions);
11495 let key;
11496 for (key in rawOptions) {
11497 // @ts-ignore
11498 options[key] =
11499 rawOptions[key] === undefined
11500 ? defaultParserOptions[key]
11501 : rawOptions[key];
11502 }
11503 return {
11504 options,
11505 column: 1,
11506 line: 1,
11507 offset: 0,
11508 originalSource: content,
11509 source: content,
11510 inPre: false,
11511 inVPre: false,
11512 onWarn: options.onWarn
11513 };
11514 }
11515 function parseChildren(context, mode, ancestors) {
11516 const parent = last(ancestors);
11517 const ns = parent ? parent.ns : 0 /* HTML */;
11518 const nodes = [];
11519 while (!isEnd(context, mode, ancestors)) {
11520 const s = context.source;
11521 let node = undefined;
11522 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11523 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11524 // '{{'
11525 node = parseInterpolation(context, mode);
11526 }
11527 else if (mode === 0 /* DATA */ && s[0] === '<') {
11528 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11529 if (s.length === 1) {
11530 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11531 }
11532 else if (s[1] === '!') {
11533 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11534 if (startsWith(s, '<!--')) {
11535 node = parseComment(context);
11536 }
11537 else if (startsWith(s, '<!DOCTYPE')) {
11538 // Ignore DOCTYPE by a limitation.
11539 node = parseBogusComment(context);
11540 }
11541 else if (startsWith(s, '<![CDATA[')) {
11542 if (ns !== 0 /* HTML */) {
11543 node = parseCDATA(context, ancestors);
11544 }
11545 else {
11546 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11547 node = parseBogusComment(context);
11548 }
11549 }
11550 else {
11551 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11552 node = parseBogusComment(context);
11553 }
11554 }
11555 else if (s[1] === '/') {
11556 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11557 if (s.length === 2) {
11558 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11559 }
11560 else if (s[2] === '>') {
11561 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11562 advanceBy(context, 3);
11563 continue;
11564 }
11565 else if (/[a-z]/i.test(s[2])) {
11566 emitError(context, 23 /* X_INVALID_END_TAG */);
11567 parseTag(context, 1 /* End */, parent);
11568 continue;
11569 }
11570 else {
11571 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11572 node = parseBogusComment(context);
11573 }
11574 }
11575 else if (/[a-z]/i.test(s[1])) {
11576 node = parseElement(context, ancestors);
11577 }
11578 else if (s[1] === '?') {
11579 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11580 node = parseBogusComment(context);
11581 }
11582 else {
11583 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11584 }
11585 }
11586 }
11587 if (!node) {
11588 node = parseText(context, mode);
11589 }
11590 if (isArray(node)) {
11591 for (let i = 0; i < node.length; i++) {
11592 pushNode(nodes, node[i]);
11593 }
11594 }
11595 else {
11596 pushNode(nodes, node);
11597 }
11598 }
11599 // Whitespace handling strategy like v2
11600 let removedWhitespace = false;
11601 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11602 const shouldCondense = context.options.whitespace !== 'preserve';
11603 for (let i = 0; i < nodes.length; i++) {
11604 const node = nodes[i];
11605 if (!context.inPre && node.type === 2 /* TEXT */) {
11606 if (!/[^\t\r\n\f ]/.test(node.content)) {
11607 const prev = nodes[i - 1];
11608 const next = nodes[i + 1];
11609 // Remove if:
11610 // - the whitespace is the first or last node, or:
11611 // - (condense mode) the whitespace is adjacent to a comment, or:
11612 // - (condense mode) the whitespace is between two elements AND contains newline
11613 if (!prev ||
11614 !next ||
11615 (shouldCondense &&
11616 (prev.type === 3 /* COMMENT */ ||
11617 next.type === 3 /* COMMENT */ ||
11618 (prev.type === 1 /* ELEMENT */ &&
11619 next.type === 1 /* ELEMENT */ &&
11620 /[\r\n]/.test(node.content))))) {
11621 removedWhitespace = true;
11622 nodes[i] = null;
11623 }
11624 else {
11625 // Otherwise, the whitespace is condensed into a single space
11626 node.content = ' ';
11627 }
11628 }
11629 else if (shouldCondense) {
11630 // in condense mode, consecutive whitespaces in text are condensed
11631 // down to a single space.
11632 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11633 }
11634 }
11635 // Remove comment nodes if desired by configuration.
11636 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11637 removedWhitespace = true;
11638 nodes[i] = null;
11639 }
11640 }
11641 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11642 // remove leading newline per html spec
11643 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11644 const first = nodes[0];
11645 if (first && first.type === 2 /* TEXT */) {
11646 first.content = first.content.replace(/^\r?\n/, '');
11647 }
11648 }
11649 }
11650 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11651 }
11652 function pushNode(nodes, node) {
11653 if (node.type === 2 /* TEXT */) {
11654 const prev = last(nodes);
11655 // Merge if both this and the previous node are text and those are
11656 // consecutive. This happens for cases like "a < b".
11657 if (prev &&
11658 prev.type === 2 /* TEXT */ &&
11659 prev.loc.end.offset === node.loc.start.offset) {
11660 prev.content += node.content;
11661 prev.loc.end = node.loc.end;
11662 prev.loc.source += node.loc.source;
11663 return;
11664 }
11665 }
11666 nodes.push(node);
11667 }
11668 function parseCDATA(context, ancestors) {
11669 advanceBy(context, 9);
11670 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11671 if (context.source.length === 0) {
11672 emitError(context, 6 /* EOF_IN_CDATA */);
11673 }
11674 else {
11675 advanceBy(context, 3);
11676 }
11677 return nodes;
11678 }
11679 function parseComment(context) {
11680 const start = getCursor(context);
11681 let content;
11682 // Regular comment.
11683 const match = /--(\!)?>/.exec(context.source);
11684 if (!match) {
11685 content = context.source.slice(4);
11686 advanceBy(context, context.source.length);
11687 emitError(context, 7 /* EOF_IN_COMMENT */);
11688 }
11689 else {
11690 if (match.index <= 3) {
11691 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
11692 }
11693 if (match[1]) {
11694 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
11695 }
11696 content = context.source.slice(4, match.index);
11697 // Advancing with reporting nested comments.
11698 const s = context.source.slice(0, match.index);
11699 let prevIndex = 1, nestedIndex = 0;
11700 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
11701 advanceBy(context, nestedIndex - prevIndex + 1);
11702 if (nestedIndex + 4 < s.length) {
11703 emitError(context, 16 /* NESTED_COMMENT */);
11704 }
11705 prevIndex = nestedIndex + 1;
11706 }
11707 advanceBy(context, match.index + match[0].length - prevIndex + 1);
11708 }
11709 return {
11710 type: 3 /* COMMENT */,
11711 content,
11712 loc: getSelection(context, start)
11713 };
11714 }
11715 function parseBogusComment(context) {
11716 const start = getCursor(context);
11717 const contentStart = context.source[1] === '?' ? 1 : 2;
11718 let content;
11719 const closeIndex = context.source.indexOf('>');
11720 if (closeIndex === -1) {
11721 content = context.source.slice(contentStart);
11722 advanceBy(context, context.source.length);
11723 }
11724 else {
11725 content = context.source.slice(contentStart, closeIndex);
11726 advanceBy(context, closeIndex + 1);
11727 }
11728 return {
11729 type: 3 /* COMMENT */,
11730 content,
11731 loc: getSelection(context, start)
11732 };
11733 }
11734 function parseElement(context, ancestors) {
11735 // Start tag.
11736 const wasInPre = context.inPre;
11737 const wasInVPre = context.inVPre;
11738 const parent = last(ancestors);
11739 const element = parseTag(context, 0 /* Start */, parent);
11740 const isPreBoundary = context.inPre && !wasInPre;
11741 const isVPreBoundary = context.inVPre && !wasInVPre;
11742 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
11743 // #4030 self-closing <pre> tag
11744 if (isPreBoundary) {
11745 context.inPre = false;
11746 }
11747 if (isVPreBoundary) {
11748 context.inVPre = false;
11749 }
11750 return element;
11751 }
11752 // Children.
11753 ancestors.push(element);
11754 const mode = context.options.getTextMode(element, parent);
11755 const children = parseChildren(context, mode, ancestors);
11756 ancestors.pop();
11757 element.children = children;
11758 // End tag.
11759 if (startsWithEndTagOpen(context.source, element.tag)) {
11760 parseTag(context, 1 /* End */, parent);
11761 }
11762 else {
11763 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
11764 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
11765 const first = children[0];
11766 if (first && startsWith(first.loc.source, '<!--')) {
11767 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
11768 }
11769 }
11770 }
11771 element.loc = getSelection(context, element.loc.start);
11772 if (isPreBoundary) {
11773 context.inPre = false;
11774 }
11775 if (isVPreBoundary) {
11776 context.inVPre = false;
11777 }
11778 return element;
11779 }
11780 const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
11781 function parseTag(context, type, parent) {
11782 // Tag open.
11783 const start = getCursor(context);
11784 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
11785 const tag = match[1];
11786 const ns = context.options.getNamespace(tag, parent);
11787 advanceBy(context, match[0].length);
11788 advanceSpaces(context);
11789 // save current state in case we need to re-parse attributes with v-pre
11790 const cursor = getCursor(context);
11791 const currentSource = context.source;
11792 // check <pre> tag
11793 if (context.options.isPreTag(tag)) {
11794 context.inPre = true;
11795 }
11796 // Attributes.
11797 let props = parseAttributes(context, type);
11798 // check v-pre
11799 if (type === 0 /* Start */ &&
11800 !context.inVPre &&
11801 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
11802 context.inVPre = true;
11803 // reset context
11804 extend(context, cursor);
11805 context.source = currentSource;
11806 // re-parse attrs and filter out v-pre itself
11807 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
11808 }
11809 // Tag close.
11810 let isSelfClosing = false;
11811 if (context.source.length === 0) {
11812 emitError(context, 9 /* EOF_IN_TAG */);
11813 }
11814 else {
11815 isSelfClosing = startsWith(context.source, '/>');
11816 if (type === 1 /* End */ && isSelfClosing) {
11817 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
11818 }
11819 advanceBy(context, isSelfClosing ? 2 : 1);
11820 }
11821 if (type === 1 /* End */) {
11822 return;
11823 }
11824 let tagType = 0 /* ELEMENT */;
11825 if (!context.inVPre) {
11826 if (tag === 'slot') {
11827 tagType = 2 /* SLOT */;
11828 }
11829 else if (tag === 'template') {
11830 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
11831 tagType = 3 /* TEMPLATE */;
11832 }
11833 }
11834 else if (isComponent(tag, props, context)) {
11835 tagType = 1 /* COMPONENT */;
11836 }
11837 }
11838 return {
11839 type: 1 /* ELEMENT */,
11840 ns,
11841 tag,
11842 tagType,
11843 props,
11844 isSelfClosing,
11845 children: [],
11846 loc: getSelection(context, start),
11847 codegenNode: undefined // to be created during transform phase
11848 };
11849 }
11850 function isComponent(tag, props, context) {
11851 const options = context.options;
11852 if (options.isCustomElement(tag)) {
11853 return false;
11854 }
11855 if (tag === 'component' ||
11856 /^[A-Z]/.test(tag) ||
11857 isCoreComponent(tag) ||
11858 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
11859 (options.isNativeTag && !options.isNativeTag(tag))) {
11860 return true;
11861 }
11862 // at this point the tag should be a native tag, but check for potential "is"
11863 // casting
11864 for (let i = 0; i < props.length; i++) {
11865 const p = props[i];
11866 if (p.type === 6 /* ATTRIBUTE */) {
11867 if (p.name === 'is' && p.value) {
11868 if (p.value.content.startsWith('vue:')) {
11869 return true;
11870 }
11871 }
11872 }
11873 else {
11874 // directive
11875 // v-is (TODO Deprecate)
11876 if (p.name === 'is') {
11877 return true;
11878 }
11879 else if (
11880 // :is on plain element - only treat as component in compat mode
11881 p.name === 'bind' &&
11882 isStaticArgOf(p.arg, 'is') &&
11883 false &&
11884 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
11885 return true;
11886 }
11887 }
11888 }
11889 }
11890 function parseAttributes(context, type) {
11891 const props = [];
11892 const attributeNames = new Set();
11893 while (context.source.length > 0 &&
11894 !startsWith(context.source, '>') &&
11895 !startsWith(context.source, '/>')) {
11896 if (startsWith(context.source, '/')) {
11897 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
11898 advanceBy(context, 1);
11899 advanceSpaces(context);
11900 continue;
11901 }
11902 if (type === 1 /* End */) {
11903 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
11904 }
11905 const attr = parseAttribute(context, attributeNames);
11906 // Trim whitespace between class
11907 // https://github.com/vuejs/core/issues/4251
11908 if (attr.type === 6 /* ATTRIBUTE */ &&
11909 attr.value &&
11910 attr.name === 'class') {
11911 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
11912 }
11913 if (type === 0 /* Start */) {
11914 props.push(attr);
11915 }
11916 if (/^[^\t\r\n\f />]/.test(context.source)) {
11917 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
11918 }
11919 advanceSpaces(context);
11920 }
11921 return props;
11922 }
11923 function parseAttribute(context, nameSet) {
11924 // Name.
11925 const start = getCursor(context);
11926 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
11927 const name = match[0];
11928 if (nameSet.has(name)) {
11929 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
11930 }
11931 nameSet.add(name);
11932 if (name[0] === '=') {
11933 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
11934 }
11935 {
11936 const pattern = /["'<]/g;
11937 let m;
11938 while ((m = pattern.exec(name))) {
11939 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
11940 }
11941 }
11942 advanceBy(context, name.length);
11943 // Value
11944 let value = undefined;
11945 if (/^[\t\r\n\f ]*=/.test(context.source)) {
11946 advanceSpaces(context);
11947 advanceBy(context, 1);
11948 advanceSpaces(context);
11949 value = parseAttributeValue(context);
11950 if (!value) {
11951 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
11952 }
11953 }
11954 const loc = getSelection(context, start);
11955 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
11956 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
11957 let isPropShorthand = startsWith(name, '.');
11958 let dirName = match[1] ||
11959 (isPropShorthand || startsWith(name, ':')
11960 ? 'bind'
11961 : startsWith(name, '@')
11962 ? 'on'
11963 : 'slot');
11964 let arg;
11965 if (match[2]) {
11966 const isSlot = dirName === 'slot';
11967 const startOffset = name.lastIndexOf(match[2]);
11968 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
11969 let content = match[2];
11970 let isStatic = true;
11971 if (content.startsWith('[')) {
11972 isStatic = false;
11973 if (!content.endsWith(']')) {
11974 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
11975 content = content.slice(1);
11976 }
11977 else {
11978 content = content.slice(1, content.length - 1);
11979 }
11980 }
11981 else if (isSlot) {
11982 // #1241 special case for v-slot: vuetify relies extensively on slot
11983 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
11984 // supports such usage so we are keeping it consistent with 2.x.
11985 content += match[3] || '';
11986 }
11987 arg = {
11988 type: 4 /* SIMPLE_EXPRESSION */,
11989 content,
11990 isStatic,
11991 constType: isStatic
11992 ? 3 /* CAN_STRINGIFY */
11993 : 0 /* NOT_CONSTANT */,
11994 loc
11995 };
11996 }
11997 if (value && value.isQuoted) {
11998 const valueLoc = value.loc;
11999 valueLoc.start.offset++;
12000 valueLoc.start.column++;
12001 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12002 valueLoc.source = valueLoc.source.slice(1, -1);
12003 }
12004 const modifiers = match[3] ? match[3].slice(1).split('.') : [];
12005 if (isPropShorthand)
12006 modifiers.push('prop');
12007 return {
12008 type: 7 /* DIRECTIVE */,
12009 name: dirName,
12010 exp: value && {
12011 type: 4 /* SIMPLE_EXPRESSION */,
12012 content: value.content,
12013 isStatic: false,
12014 // Treat as non-constant by default. This can be potentially set to
12015 // other values by `transformExpression` to make it eligible for hoisting.
12016 constType: 0 /* NOT_CONSTANT */,
12017 loc: value.loc
12018 },
12019 arg,
12020 modifiers,
12021 loc
12022 };
12023 }
12024 // missing directive name or illegal directive name
12025 if (!context.inVPre && startsWith(name, 'v-')) {
12026 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12027 }
12028 return {
12029 type: 6 /* ATTRIBUTE */,
12030 name,
12031 value: value && {
12032 type: 2 /* TEXT */,
12033 content: value.content,
12034 loc: value.loc
12035 },
12036 loc
12037 };
12038 }
12039 function parseAttributeValue(context) {
12040 const start = getCursor(context);
12041 let content;
12042 const quote = context.source[0];
12043 const isQuoted = quote === `"` || quote === `'`;
12044 if (isQuoted) {
12045 // Quoted value.
12046 advanceBy(context, 1);
12047 const endIndex = context.source.indexOf(quote);
12048 if (endIndex === -1) {
12049 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12050 }
12051 else {
12052 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12053 advanceBy(context, 1);
12054 }
12055 }
12056 else {
12057 // Unquoted
12058 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12059 if (!match) {
12060 return undefined;
12061 }
12062 const unexpectedChars = /["'<=`]/g;
12063 let m;
12064 while ((m = unexpectedChars.exec(match[0]))) {
12065 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12066 }
12067 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12068 }
12069 return { content, isQuoted, loc: getSelection(context, start) };
12070 }
12071 function parseInterpolation(context, mode) {
12072 const [open, close] = context.options.delimiters;
12073 const closeIndex = context.source.indexOf(close, open.length);
12074 if (closeIndex === -1) {
12075 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12076 return undefined;
12077 }
12078 const start = getCursor(context);
12079 advanceBy(context, open.length);
12080 const innerStart = getCursor(context);
12081 const innerEnd = getCursor(context);
12082 const rawContentLength = closeIndex - open.length;
12083 const rawContent = context.source.slice(0, rawContentLength);
12084 const preTrimContent = parseTextData(context, rawContentLength, mode);
12085 const content = preTrimContent.trim();
12086 const startOffset = preTrimContent.indexOf(content);
12087 if (startOffset > 0) {
12088 advancePositionWithMutation(innerStart, rawContent, startOffset);
12089 }
12090 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12091 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12092 advanceBy(context, close.length);
12093 return {
12094 type: 5 /* INTERPOLATION */,
12095 content: {
12096 type: 4 /* SIMPLE_EXPRESSION */,
12097 isStatic: false,
12098 // Set `isConstant` to false by default and will decide in transformExpression
12099 constType: 0 /* NOT_CONSTANT */,
12100 content,
12101 loc: getSelection(context, innerStart, innerEnd)
12102 },
12103 loc: getSelection(context, start)
12104 };
12105 }
12106 function parseText(context, mode) {
12107 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12108 let endIndex = context.source.length;
12109 for (let i = 0; i < endTokens.length; i++) {
12110 const index = context.source.indexOf(endTokens[i], 1);
12111 if (index !== -1 && endIndex > index) {
12112 endIndex = index;
12113 }
12114 }
12115 const start = getCursor(context);
12116 const content = parseTextData(context, endIndex, mode);
12117 return {
12118 type: 2 /* TEXT */,
12119 content,
12120 loc: getSelection(context, start)
12121 };
12122 }
12123 /**
12124 * Get text data with a given length from the current location.
12125 * This translates HTML entities in the text data.
12126 */
12127 function parseTextData(context, length, mode) {
12128 const rawText = context.source.slice(0, length);
12129 advanceBy(context, length);
12130 if (mode === 2 /* RAWTEXT */ ||
12131 mode === 3 /* CDATA */ ||
12132 !rawText.includes('&')) {
12133 return rawText;
12134 }
12135 else {
12136 // DATA or RCDATA containing "&"". Entity decoding required.
12137 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12138 }
12139 }
12140 function getCursor(context) {
12141 const { column, line, offset } = context;
12142 return { column, line, offset };
12143 }
12144 function getSelection(context, start, end) {
12145 end = end || getCursor(context);
12146 return {
12147 start,
12148 end,
12149 source: context.originalSource.slice(start.offset, end.offset)
12150 };
12151 }
12152 function last(xs) {
12153 return xs[xs.length - 1];
12154 }
12155 function startsWith(source, searchString) {
12156 return source.startsWith(searchString);
12157 }
12158 function advanceBy(context, numberOfCharacters) {
12159 const { source } = context;
12160 advancePositionWithMutation(context, source, numberOfCharacters);
12161 context.source = source.slice(numberOfCharacters);
12162 }
12163 function advanceSpaces(context) {
12164 const match = /^[\t\r\n\f ]+/.exec(context.source);
12165 if (match) {
12166 advanceBy(context, match[0].length);
12167 }
12168 }
12169 function getNewPosition(context, start, numberOfCharacters) {
12170 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12171 }
12172 function emitError(context, code, offset, loc = getCursor(context)) {
12173 if (offset) {
12174 loc.offset += offset;
12175 loc.column += offset;
12176 }
12177 context.options.onError(createCompilerError(code, {
12178 start: loc,
12179 end: loc,
12180 source: ''
12181 }));
12182 }
12183 function isEnd(context, mode, ancestors) {
12184 const s = context.source;
12185 switch (mode) {
12186 case 0 /* DATA */:
12187 if (startsWith(s, '</')) {
12188 // TODO: probably bad performance
12189 for (let i = ancestors.length - 1; i >= 0; --i) {
12190 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12191 return true;
12192 }
12193 }
12194 }
12195 break;
12196 case 1 /* RCDATA */:
12197 case 2 /* RAWTEXT */: {
12198 const parent = last(ancestors);
12199 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12200 return true;
12201 }
12202 break;
12203 }
12204 case 3 /* CDATA */:
12205 if (startsWith(s, ']]>')) {
12206 return true;
12207 }
12208 break;
12209 }
12210 return !s;
12211 }
12212 function startsWithEndTagOpen(source, tag) {
12213 return (startsWith(source, '</') &&
12214 source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
12215 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12216 }
12217
12218 function hoistStatic(root, context) {
12219 walk(root, context,
12220 // Root node is unfortunately non-hoistable due to potential parent
12221 // fallthrough attributes.
12222 isSingleElementRoot(root, root.children[0]));
12223 }
12224 function isSingleElementRoot(root, child) {
12225 const { children } = root;
12226 return (children.length === 1 &&
12227 child.type === 1 /* ELEMENT */ &&
12228 !isSlotOutlet(child));
12229 }
12230 function walk(node, context, doNotHoistNode = false) {
12231 const { children } = node;
12232 const originalCount = children.length;
12233 let hoistedCount = 0;
12234 for (let i = 0; i < children.length; i++) {
12235 const child = children[i];
12236 // only plain elements & text calls are eligible for hoisting.
12237 if (child.type === 1 /* ELEMENT */ &&
12238 child.tagType === 0 /* ELEMENT */) {
12239 const constantType = doNotHoistNode
12240 ? 0 /* NOT_CONSTANT */
12241 : getConstantType(child, context);
12242 if (constantType > 0 /* NOT_CONSTANT */) {
12243 if (constantType >= 2 /* CAN_HOIST */) {
12244 child.codegenNode.patchFlag =
12245 -1 /* HOISTED */ + (` /* HOISTED */` );
12246 child.codegenNode = context.hoist(child.codegenNode);
12247 hoistedCount++;
12248 continue;
12249 }
12250 }
12251 else {
12252 // node may contain dynamic children, but its props may be eligible for
12253 // hoisting.
12254 const codegenNode = child.codegenNode;
12255 if (codegenNode.type === 13 /* VNODE_CALL */) {
12256 const flag = getPatchFlag(codegenNode);
12257 if ((!flag ||
12258 flag === 512 /* NEED_PATCH */ ||
12259 flag === 1 /* TEXT */) &&
12260 getGeneratedPropsConstantType(child, context) >=
12261 2 /* CAN_HOIST */) {
12262 const props = getNodeProps(child);
12263 if (props) {
12264 codegenNode.props = context.hoist(props);
12265 }
12266 }
12267 if (codegenNode.dynamicProps) {
12268 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12269 }
12270 }
12271 }
12272 }
12273 else if (child.type === 12 /* TEXT_CALL */ &&
12274 getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
12275 child.codegenNode = context.hoist(child.codegenNode);
12276 hoistedCount++;
12277 }
12278 // walk further
12279 if (child.type === 1 /* ELEMENT */) {
12280 const isComponent = child.tagType === 1 /* COMPONENT */;
12281 if (isComponent) {
12282 context.scopes.vSlot++;
12283 }
12284 walk(child, context);
12285 if (isComponent) {
12286 context.scopes.vSlot--;
12287 }
12288 }
12289 else if (child.type === 11 /* FOR */) {
12290 // Do not hoist v-for single child because it has to be a block
12291 walk(child, context, child.children.length === 1);
12292 }
12293 else if (child.type === 9 /* IF */) {
12294 for (let i = 0; i < child.branches.length; i++) {
12295 // Do not hoist v-if single child because it has to be a block
12296 walk(child.branches[i], context, child.branches[i].children.length === 1);
12297 }
12298 }
12299 }
12300 if (hoistedCount && context.transformHoist) {
12301 context.transformHoist(children, context, node);
12302 }
12303 // all children were hoisted - the entire children array is hoistable.
12304 if (hoistedCount &&
12305 hoistedCount === originalCount &&
12306 node.type === 1 /* ELEMENT */ &&
12307 node.tagType === 0 /* ELEMENT */ &&
12308 node.codegenNode &&
12309 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12310 isArray(node.codegenNode.children)) {
12311 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12312 }
12313 }
12314 function getConstantType(node, context) {
12315 const { constantCache } = context;
12316 switch (node.type) {
12317 case 1 /* ELEMENT */:
12318 if (node.tagType !== 0 /* ELEMENT */) {
12319 return 0 /* NOT_CONSTANT */;
12320 }
12321 const cached = constantCache.get(node);
12322 if (cached !== undefined) {
12323 return cached;
12324 }
12325 const codegenNode = node.codegenNode;
12326 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12327 return 0 /* NOT_CONSTANT */;
12328 }
12329 if (codegenNode.isBlock &&
12330 node.tag !== 'svg' &&
12331 node.tag !== 'foreignObject') {
12332 return 0 /* NOT_CONSTANT */;
12333 }
12334 const flag = getPatchFlag(codegenNode);
12335 if (!flag) {
12336 let returnType = 3 /* CAN_STRINGIFY */;
12337 // Element itself has no patch flag. However we still need to check:
12338 // 1. Even for a node with no patch flag, it is possible for it to contain
12339 // non-hoistable expressions that refers to scope variables, e.g. compiler
12340 // injected keys or cached event handlers. Therefore we need to always
12341 // check the codegenNode's props to be sure.
12342 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12343 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12344 constantCache.set(node, 0 /* NOT_CONSTANT */);
12345 return 0 /* NOT_CONSTANT */;
12346 }
12347 if (generatedPropsType < returnType) {
12348 returnType = generatedPropsType;
12349 }
12350 // 2. its children.
12351 for (let i = 0; i < node.children.length; i++) {
12352 const childType = getConstantType(node.children[i], context);
12353 if (childType === 0 /* NOT_CONSTANT */) {
12354 constantCache.set(node, 0 /* NOT_CONSTANT */);
12355 return 0 /* NOT_CONSTANT */;
12356 }
12357 if (childType < returnType) {
12358 returnType = childType;
12359 }
12360 }
12361 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12362 // type, check if any of the props can cause the type to be lowered
12363 // we can skip can_patch because it's guaranteed by the absence of a
12364 // patchFlag.
12365 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12366 for (let i = 0; i < node.props.length; i++) {
12367 const p = node.props[i];
12368 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12369 const expType = getConstantType(p.exp, context);
12370 if (expType === 0 /* NOT_CONSTANT */) {
12371 constantCache.set(node, 0 /* NOT_CONSTANT */);
12372 return 0 /* NOT_CONSTANT */;
12373 }
12374 if (expType < returnType) {
12375 returnType = expType;
12376 }
12377 }
12378 }
12379 }
12380 // only svg/foreignObject could be block here, however if they are
12381 // static then they don't need to be blocks since there will be no
12382 // nested updates.
12383 if (codegenNode.isBlock) {
12384 context.removeHelper(OPEN_BLOCK);
12385 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12386 codegenNode.isBlock = false;
12387 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12388 }
12389 constantCache.set(node, returnType);
12390 return returnType;
12391 }
12392 else {
12393 constantCache.set(node, 0 /* NOT_CONSTANT */);
12394 return 0 /* NOT_CONSTANT */;
12395 }
12396 case 2 /* TEXT */:
12397 case 3 /* COMMENT */:
12398 return 3 /* CAN_STRINGIFY */;
12399 case 9 /* IF */:
12400 case 11 /* FOR */:
12401 case 10 /* IF_BRANCH */:
12402 return 0 /* NOT_CONSTANT */;
12403 case 5 /* INTERPOLATION */:
12404 case 12 /* TEXT_CALL */:
12405 return getConstantType(node.content, context);
12406 case 4 /* SIMPLE_EXPRESSION */:
12407 return node.constType;
12408 case 8 /* COMPOUND_EXPRESSION */:
12409 let returnType = 3 /* CAN_STRINGIFY */;
12410 for (let i = 0; i < node.children.length; i++) {
12411 const child = node.children[i];
12412 if (isString(child) || isSymbol(child)) {
12413 continue;
12414 }
12415 const childType = getConstantType(child, context);
12416 if (childType === 0 /* NOT_CONSTANT */) {
12417 return 0 /* NOT_CONSTANT */;
12418 }
12419 else if (childType < returnType) {
12420 returnType = childType;
12421 }
12422 }
12423 return returnType;
12424 default:
12425 return 0 /* NOT_CONSTANT */;
12426 }
12427 }
12428 const allowHoistedHelperSet = new Set([
12429 NORMALIZE_CLASS,
12430 NORMALIZE_STYLE,
12431 NORMALIZE_PROPS,
12432 GUARD_REACTIVE_PROPS
12433 ]);
12434 function getConstantTypeOfHelperCall(value, context) {
12435 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12436 !isString(value.callee) &&
12437 allowHoistedHelperSet.has(value.callee)) {
12438 const arg = value.arguments[0];
12439 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12440 return getConstantType(arg, context);
12441 }
12442 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12443 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12444 return getConstantTypeOfHelperCall(arg, context);
12445 }
12446 }
12447 return 0 /* NOT_CONSTANT */;
12448 }
12449 function getGeneratedPropsConstantType(node, context) {
12450 let returnType = 3 /* CAN_STRINGIFY */;
12451 const props = getNodeProps(node);
12452 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12453 const { properties } = props;
12454 for (let i = 0; i < properties.length; i++) {
12455 const { key, value } = properties[i];
12456 const keyType = getConstantType(key, context);
12457 if (keyType === 0 /* NOT_CONSTANT */) {
12458 return keyType;
12459 }
12460 if (keyType < returnType) {
12461 returnType = keyType;
12462 }
12463 let valueType;
12464 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12465 valueType = getConstantType(value, context);
12466 }
12467 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12468 // some helper calls can be hoisted,
12469 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12470 // in this case we need to respect the ConstantType of the helper's arguments
12471 valueType = getConstantTypeOfHelperCall(value, context);
12472 }
12473 else {
12474 valueType = 0 /* NOT_CONSTANT */;
12475 }
12476 if (valueType === 0 /* NOT_CONSTANT */) {
12477 return valueType;
12478 }
12479 if (valueType < returnType) {
12480 returnType = valueType;
12481 }
12482 }
12483 }
12484 return returnType;
12485 }
12486 function getNodeProps(node) {
12487 const codegenNode = node.codegenNode;
12488 if (codegenNode.type === 13 /* VNODE_CALL */) {
12489 return codegenNode.props;
12490 }
12491 }
12492 function getPatchFlag(node) {
12493 const flag = node.patchFlag;
12494 return flag ? parseInt(flag, 10) : undefined;
12495 }
12496
12497 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 }) {
12498 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12499 const context = {
12500 // options
12501 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12502 prefixIdentifiers,
12503 hoistStatic,
12504 cacheHandlers,
12505 nodeTransforms,
12506 directiveTransforms,
12507 transformHoist,
12508 isBuiltInComponent,
12509 isCustomElement,
12510 expressionPlugins,
12511 scopeId,
12512 slotted,
12513 ssr,
12514 inSSR,
12515 ssrCssVars,
12516 bindingMetadata,
12517 inline,
12518 isTS,
12519 onError,
12520 onWarn,
12521 compatConfig,
12522 // state
12523 root,
12524 helpers: new Map(),
12525 components: new Set(),
12526 directives: new Set(),
12527 hoists: [],
12528 imports: [],
12529 constantCache: new Map(),
12530 temps: 0,
12531 cached: 0,
12532 identifiers: Object.create(null),
12533 scopes: {
12534 vFor: 0,
12535 vSlot: 0,
12536 vPre: 0,
12537 vOnce: 0
12538 },
12539 parent: null,
12540 currentNode: root,
12541 childIndex: 0,
12542 inVOnce: false,
12543 // methods
12544 helper(name) {
12545 const count = context.helpers.get(name) || 0;
12546 context.helpers.set(name, count + 1);
12547 return name;
12548 },
12549 removeHelper(name) {
12550 const count = context.helpers.get(name);
12551 if (count) {
12552 const currentCount = count - 1;
12553 if (!currentCount) {
12554 context.helpers.delete(name);
12555 }
12556 else {
12557 context.helpers.set(name, currentCount);
12558 }
12559 }
12560 },
12561 helperString(name) {
12562 return `_${helperNameMap[context.helper(name)]}`;
12563 },
12564 replaceNode(node) {
12565 /* istanbul ignore if */
12566 {
12567 if (!context.currentNode) {
12568 throw new Error(`Node being replaced is already removed.`);
12569 }
12570 if (!context.parent) {
12571 throw new Error(`Cannot replace root node.`);
12572 }
12573 }
12574 context.parent.children[context.childIndex] = context.currentNode = node;
12575 },
12576 removeNode(node) {
12577 if (!context.parent) {
12578 throw new Error(`Cannot remove root node.`);
12579 }
12580 const list = context.parent.children;
12581 const removalIndex = node
12582 ? list.indexOf(node)
12583 : context.currentNode
12584 ? context.childIndex
12585 : -1;
12586 /* istanbul ignore if */
12587 if (removalIndex < 0) {
12588 throw new Error(`node being removed is not a child of current parent`);
12589 }
12590 if (!node || node === context.currentNode) {
12591 // current node removed
12592 context.currentNode = null;
12593 context.onNodeRemoved();
12594 }
12595 else {
12596 // sibling node removed
12597 if (context.childIndex > removalIndex) {
12598 context.childIndex--;
12599 context.onNodeRemoved();
12600 }
12601 }
12602 context.parent.children.splice(removalIndex, 1);
12603 },
12604 onNodeRemoved: () => { },
12605 addIdentifiers(exp) {
12606 },
12607 removeIdentifiers(exp) {
12608 },
12609 hoist(exp) {
12610 if (isString(exp))
12611 exp = createSimpleExpression(exp);
12612 context.hoists.push(exp);
12613 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12614 identifier.hoisted = exp;
12615 return identifier;
12616 },
12617 cache(exp, isVNode = false) {
12618 return createCacheExpression(context.cached++, exp, isVNode);
12619 }
12620 };
12621 return context;
12622 }
12623 function transform(root, options) {
12624 const context = createTransformContext(root, options);
12625 traverseNode(root, context);
12626 if (options.hoistStatic) {
12627 hoistStatic(root, context);
12628 }
12629 if (!options.ssr) {
12630 createRootCodegen(root, context);
12631 }
12632 // finalize meta information
12633 root.helpers = [...context.helpers.keys()];
12634 root.components = [...context.components];
12635 root.directives = [...context.directives];
12636 root.imports = context.imports;
12637 root.hoists = context.hoists;
12638 root.temps = context.temps;
12639 root.cached = context.cached;
12640 }
12641 function createRootCodegen(root, context) {
12642 const { helper } = context;
12643 const { children } = root;
12644 if (children.length === 1) {
12645 const child = children[0];
12646 // if the single child is an element, turn it into a block.
12647 if (isSingleElementRoot(root, child) && child.codegenNode) {
12648 // single element root is never hoisted so codegenNode will never be
12649 // SimpleExpressionNode
12650 const codegenNode = child.codegenNode;
12651 if (codegenNode.type === 13 /* VNODE_CALL */) {
12652 makeBlock(codegenNode, context);
12653 }
12654 root.codegenNode = codegenNode;
12655 }
12656 else {
12657 // - single <slot/>, IfNode, ForNode: already blocks.
12658 // - single text node: always patched.
12659 // root codegen falls through via genNode()
12660 root.codegenNode = child;
12661 }
12662 }
12663 else if (children.length > 1) {
12664 // root has multiple nodes - return a fragment block.
12665 let patchFlag = 64 /* STABLE_FRAGMENT */;
12666 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12667 // check if the fragment actually contains a single valid child with
12668 // the rest being comments
12669 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12670 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12671 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12672 }
12673 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12674 }
12675 else ;
12676 }
12677 function traverseChildren(parent, context) {
12678 let i = 0;
12679 const nodeRemoved = () => {
12680 i--;
12681 };
12682 for (; i < parent.children.length; i++) {
12683 const child = parent.children[i];
12684 if (isString(child))
12685 continue;
12686 context.parent = parent;
12687 context.childIndex = i;
12688 context.onNodeRemoved = nodeRemoved;
12689 traverseNode(child, context);
12690 }
12691 }
12692 function traverseNode(node, context) {
12693 context.currentNode = node;
12694 // apply transform plugins
12695 const { nodeTransforms } = context;
12696 const exitFns = [];
12697 for (let i = 0; i < nodeTransforms.length; i++) {
12698 const onExit = nodeTransforms[i](node, context);
12699 if (onExit) {
12700 if (isArray(onExit)) {
12701 exitFns.push(...onExit);
12702 }
12703 else {
12704 exitFns.push(onExit);
12705 }
12706 }
12707 if (!context.currentNode) {
12708 // node was removed
12709 return;
12710 }
12711 else {
12712 // node may have been replaced
12713 node = context.currentNode;
12714 }
12715 }
12716 switch (node.type) {
12717 case 3 /* COMMENT */:
12718 if (!context.ssr) {
12719 // inject import for the Comment symbol, which is needed for creating
12720 // comment nodes with `createVNode`
12721 context.helper(CREATE_COMMENT);
12722 }
12723 break;
12724 case 5 /* INTERPOLATION */:
12725 // no need to traverse, but we need to inject toString helper
12726 if (!context.ssr) {
12727 context.helper(TO_DISPLAY_STRING);
12728 }
12729 break;
12730 // for container types, further traverse downwards
12731 case 9 /* IF */:
12732 for (let i = 0; i < node.branches.length; i++) {
12733 traverseNode(node.branches[i], context);
12734 }
12735 break;
12736 case 10 /* IF_BRANCH */:
12737 case 11 /* FOR */:
12738 case 1 /* ELEMENT */:
12739 case 0 /* ROOT */:
12740 traverseChildren(node, context);
12741 break;
12742 }
12743 // exit transforms
12744 context.currentNode = node;
12745 let i = exitFns.length;
12746 while (i--) {
12747 exitFns[i]();
12748 }
12749 }
12750 function createStructuralDirectiveTransform(name, fn) {
12751 const matches = isString(name)
12752 ? (n) => n === name
12753 : (n) => name.test(n);
12754 return (node, context) => {
12755 if (node.type === 1 /* ELEMENT */) {
12756 const { props } = node;
12757 // structural directive transforms are not concerned with slots
12758 // as they are handled separately in vSlot.ts
12759 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
12760 return;
12761 }
12762 const exitFns = [];
12763 for (let i = 0; i < props.length; i++) {
12764 const prop = props[i];
12765 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
12766 // structural directives are removed to avoid infinite recursion
12767 // also we remove them *before* applying so that it can further
12768 // traverse itself in case it moves the node around
12769 props.splice(i, 1);
12770 i--;
12771 const onExit = fn(node, prop, context);
12772 if (onExit)
12773 exitFns.push(onExit);
12774 }
12775 }
12776 return exitFns;
12777 }
12778 };
12779 }
12780
12781 const PURE_ANNOTATION = `/*#__PURE__*/`;
12782 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 }) {
12783 const context = {
12784 mode,
12785 prefixIdentifiers,
12786 sourceMap,
12787 filename,
12788 scopeId,
12789 optimizeImports,
12790 runtimeGlobalName,
12791 runtimeModuleName,
12792 ssrRuntimeModuleName,
12793 ssr,
12794 isTS,
12795 inSSR,
12796 source: ast.loc.source,
12797 code: ``,
12798 column: 1,
12799 line: 1,
12800 offset: 0,
12801 indentLevel: 0,
12802 pure: false,
12803 map: undefined,
12804 helper(key) {
12805 return `_${helperNameMap[key]}`;
12806 },
12807 push(code, node) {
12808 context.code += code;
12809 },
12810 indent() {
12811 newline(++context.indentLevel);
12812 },
12813 deindent(withoutNewLine = false) {
12814 if (withoutNewLine) {
12815 --context.indentLevel;
12816 }
12817 else {
12818 newline(--context.indentLevel);
12819 }
12820 },
12821 newline() {
12822 newline(context.indentLevel);
12823 }
12824 };
12825 function newline(n) {
12826 context.push('\n' + ` `.repeat(n));
12827 }
12828 return context;
12829 }
12830 function generate(ast, options = {}) {
12831 const context = createCodegenContext(ast, options);
12832 if (options.onContextCreated)
12833 options.onContextCreated(context);
12834 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
12835 const hasHelpers = ast.helpers.length > 0;
12836 const useWithBlock = !prefixIdentifiers && mode !== 'module';
12837 // preambles
12838 // in setup() inline mode, the preamble is generated in a sub context
12839 // and returned separately.
12840 const preambleContext = context;
12841 {
12842 genFunctionPreamble(ast, preambleContext);
12843 }
12844 // enter render function
12845 const functionName = ssr ? `ssrRender` : `render`;
12846 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
12847 const signature = args.join(', ');
12848 {
12849 push(`function ${functionName}(${signature}) {`);
12850 }
12851 indent();
12852 if (useWithBlock) {
12853 push(`with (_ctx) {`);
12854 indent();
12855 // function mode const declarations should be inside with block
12856 // also they should be renamed to avoid collision with user properties
12857 if (hasHelpers) {
12858 push(`const { ${ast.helpers
12859 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
12860 .join(', ')} } = _Vue`);
12861 push(`\n`);
12862 newline();
12863 }
12864 }
12865 // generate asset resolution statements
12866 if (ast.components.length) {
12867 genAssets(ast.components, 'component', context);
12868 if (ast.directives.length || ast.temps > 0) {
12869 newline();
12870 }
12871 }
12872 if (ast.directives.length) {
12873 genAssets(ast.directives, 'directive', context);
12874 if (ast.temps > 0) {
12875 newline();
12876 }
12877 }
12878 if (ast.temps > 0) {
12879 push(`let `);
12880 for (let i = 0; i < ast.temps; i++) {
12881 push(`${i > 0 ? `, ` : ``}_temp${i}`);
12882 }
12883 }
12884 if (ast.components.length || ast.directives.length || ast.temps) {
12885 push(`\n`);
12886 newline();
12887 }
12888 // generate the VNode tree expression
12889 if (!ssr) {
12890 push(`return `);
12891 }
12892 if (ast.codegenNode) {
12893 genNode(ast.codegenNode, context);
12894 }
12895 else {
12896 push(`null`);
12897 }
12898 if (useWithBlock) {
12899 deindent();
12900 push(`}`);
12901 }
12902 deindent();
12903 push(`}`);
12904 return {
12905 ast,
12906 code: context.code,
12907 preamble: ``,
12908 // SourceMapGenerator does have toJSON() method but it's not in the types
12909 map: context.map ? context.map.toJSON() : undefined
12910 };
12911 }
12912 function genFunctionPreamble(ast, context) {
12913 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
12914 const VueBinding = runtimeGlobalName;
12915 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
12916 // Generate const declaration for helpers
12917 // In prefix mode, we place the const declaration at top so it's done
12918 // only once; But if we not prefixing, we place the declaration inside the
12919 // with block so it doesn't incur the `in` check cost for every helper access.
12920 if (ast.helpers.length > 0) {
12921 {
12922 // "with" mode.
12923 // save Vue in a separate variable to avoid collision
12924 push(`const _Vue = ${VueBinding}\n`);
12925 // in "with" mode, helpers are declared inside the with block to avoid
12926 // has check cost, but hoists are lifted out of the function - we need
12927 // to provide the helper here.
12928 if (ast.hoists.length) {
12929 const staticHelpers = [
12930 CREATE_VNODE,
12931 CREATE_ELEMENT_VNODE,
12932 CREATE_COMMENT,
12933 CREATE_TEXT,
12934 CREATE_STATIC
12935 ]
12936 .filter(helper => ast.helpers.includes(helper))
12937 .map(aliasHelper)
12938 .join(', ');
12939 push(`const { ${staticHelpers} } = _Vue\n`);
12940 }
12941 }
12942 }
12943 genHoists(ast.hoists, context);
12944 newline();
12945 push(`return `);
12946 }
12947 function genAssets(assets, type, { helper, push, newline, isTS }) {
12948 const resolver = helper(type === 'component'
12949 ? RESOLVE_COMPONENT
12950 : RESOLVE_DIRECTIVE);
12951 for (let i = 0; i < assets.length; i++) {
12952 let id = assets[i];
12953 // potential component implicit self-reference inferred from SFC filename
12954 const maybeSelfReference = id.endsWith('__self');
12955 if (maybeSelfReference) {
12956 id = id.slice(0, -6);
12957 }
12958 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
12959 if (i < assets.length - 1) {
12960 newline();
12961 }
12962 }
12963 }
12964 function genHoists(hoists, context) {
12965 if (!hoists.length) {
12966 return;
12967 }
12968 context.pure = true;
12969 const { push, newline, helper, scopeId, mode } = context;
12970 newline();
12971 for (let i = 0; i < hoists.length; i++) {
12972 const exp = hoists[i];
12973 if (exp) {
12974 push(`const _hoisted_${i + 1} = ${``}`);
12975 genNode(exp, context);
12976 newline();
12977 }
12978 }
12979 context.pure = false;
12980 }
12981 function isText$1(n) {
12982 return (isString(n) ||
12983 n.type === 4 /* SIMPLE_EXPRESSION */ ||
12984 n.type === 2 /* TEXT */ ||
12985 n.type === 5 /* INTERPOLATION */ ||
12986 n.type === 8 /* COMPOUND_EXPRESSION */);
12987 }
12988 function genNodeListAsArray(nodes, context) {
12989 const multilines = nodes.length > 3 ||
12990 (nodes.some(n => isArray(n) || !isText$1(n)));
12991 context.push(`[`);
12992 multilines && context.indent();
12993 genNodeList(nodes, context, multilines);
12994 multilines && context.deindent();
12995 context.push(`]`);
12996 }
12997 function genNodeList(nodes, context, multilines = false, comma = true) {
12998 const { push, newline } = context;
12999 for (let i = 0; i < nodes.length; i++) {
13000 const node = nodes[i];
13001 if (isString(node)) {
13002 push(node);
13003 }
13004 else if (isArray(node)) {
13005 genNodeListAsArray(node, context);
13006 }
13007 else {
13008 genNode(node, context);
13009 }
13010 if (i < nodes.length - 1) {
13011 if (multilines) {
13012 comma && push(',');
13013 newline();
13014 }
13015 else {
13016 comma && push(', ');
13017 }
13018 }
13019 }
13020 }
13021 function genNode(node, context) {
13022 if (isString(node)) {
13023 context.push(node);
13024 return;
13025 }
13026 if (isSymbol(node)) {
13027 context.push(context.helper(node));
13028 return;
13029 }
13030 switch (node.type) {
13031 case 1 /* ELEMENT */:
13032 case 9 /* IF */:
13033 case 11 /* FOR */:
13034 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13035 `Apply appropriate transforms first.`);
13036 genNode(node.codegenNode, context);
13037 break;
13038 case 2 /* TEXT */:
13039 genText(node, context);
13040 break;
13041 case 4 /* SIMPLE_EXPRESSION */:
13042 genExpression(node, context);
13043 break;
13044 case 5 /* INTERPOLATION */:
13045 genInterpolation(node, context);
13046 break;
13047 case 12 /* TEXT_CALL */:
13048 genNode(node.codegenNode, context);
13049 break;
13050 case 8 /* COMPOUND_EXPRESSION */:
13051 genCompoundExpression(node, context);
13052 break;
13053 case 3 /* COMMENT */:
13054 genComment(node, context);
13055 break;
13056 case 13 /* VNODE_CALL */:
13057 genVNodeCall(node, context);
13058 break;
13059 case 14 /* JS_CALL_EXPRESSION */:
13060 genCallExpression(node, context);
13061 break;
13062 case 15 /* JS_OBJECT_EXPRESSION */:
13063 genObjectExpression(node, context);
13064 break;
13065 case 17 /* JS_ARRAY_EXPRESSION */:
13066 genArrayExpression(node, context);
13067 break;
13068 case 18 /* JS_FUNCTION_EXPRESSION */:
13069 genFunctionExpression(node, context);
13070 break;
13071 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13072 genConditionalExpression(node, context);
13073 break;
13074 case 20 /* JS_CACHE_EXPRESSION */:
13075 genCacheExpression(node, context);
13076 break;
13077 case 21 /* JS_BLOCK_STATEMENT */:
13078 genNodeList(node.body, context, true, false);
13079 break;
13080 // SSR only types
13081 case 22 /* JS_TEMPLATE_LITERAL */:
13082 break;
13083 case 23 /* JS_IF_STATEMENT */:
13084 break;
13085 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13086 break;
13087 case 25 /* JS_SEQUENCE_EXPRESSION */:
13088 break;
13089 case 26 /* JS_RETURN_STATEMENT */:
13090 break;
13091 /* istanbul ignore next */
13092 case 10 /* IF_BRANCH */:
13093 // noop
13094 break;
13095 default:
13096 {
13097 assert(false, `unhandled codegen node type: ${node.type}`);
13098 // make sure we exhaust all possible types
13099 const exhaustiveCheck = node;
13100 return exhaustiveCheck;
13101 }
13102 }
13103 }
13104 function genText(node, context) {
13105 context.push(JSON.stringify(node.content), node);
13106 }
13107 function genExpression(node, context) {
13108 const { content, isStatic } = node;
13109 context.push(isStatic ? JSON.stringify(content) : content, node);
13110 }
13111 function genInterpolation(node, context) {
13112 const { push, helper, pure } = context;
13113 if (pure)
13114 push(PURE_ANNOTATION);
13115 push(`${helper(TO_DISPLAY_STRING)}(`);
13116 genNode(node.content, context);
13117 push(`)`);
13118 }
13119 function genCompoundExpression(node, context) {
13120 for (let i = 0; i < node.children.length; i++) {
13121 const child = node.children[i];
13122 if (isString(child)) {
13123 context.push(child);
13124 }
13125 else {
13126 genNode(child, context);
13127 }
13128 }
13129 }
13130 function genExpressionAsPropertyKey(node, context) {
13131 const { push } = context;
13132 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13133 push(`[`);
13134 genCompoundExpression(node, context);
13135 push(`]`);
13136 }
13137 else if (node.isStatic) {
13138 // only quote keys if necessary
13139 const text = isSimpleIdentifier(node.content)
13140 ? node.content
13141 : JSON.stringify(node.content);
13142 push(text, node);
13143 }
13144 else {
13145 push(`[${node.content}]`, node);
13146 }
13147 }
13148 function genComment(node, context) {
13149 const { push, helper, pure } = context;
13150 if (pure) {
13151 push(PURE_ANNOTATION);
13152 }
13153 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13154 }
13155 function genVNodeCall(node, context) {
13156 const { push, helper, pure } = context;
13157 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13158 if (directives) {
13159 push(helper(WITH_DIRECTIVES) + `(`);
13160 }
13161 if (isBlock) {
13162 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13163 }
13164 if (pure) {
13165 push(PURE_ANNOTATION);
13166 }
13167 const callHelper = isBlock
13168 ? getVNodeBlockHelper(context.inSSR, isComponent)
13169 : getVNodeHelper(context.inSSR, isComponent);
13170 push(helper(callHelper) + `(`, node);
13171 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13172 push(`)`);
13173 if (isBlock) {
13174 push(`)`);
13175 }
13176 if (directives) {
13177 push(`, `);
13178 genNode(directives, context);
13179 push(`)`);
13180 }
13181 }
13182 function genNullableArgs(args) {
13183 let i = args.length;
13184 while (i--) {
13185 if (args[i] != null)
13186 break;
13187 }
13188 return args.slice(0, i + 1).map(arg => arg || `null`);
13189 }
13190 // JavaScript
13191 function genCallExpression(node, context) {
13192 const { push, helper, pure } = context;
13193 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13194 if (pure) {
13195 push(PURE_ANNOTATION);
13196 }
13197 push(callee + `(`, node);
13198 genNodeList(node.arguments, context);
13199 push(`)`);
13200 }
13201 function genObjectExpression(node, context) {
13202 const { push, indent, deindent, newline } = context;
13203 const { properties } = node;
13204 if (!properties.length) {
13205 push(`{}`, node);
13206 return;
13207 }
13208 const multilines = properties.length > 1 ||
13209 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13210 push(multilines ? `{` : `{ `);
13211 multilines && indent();
13212 for (let i = 0; i < properties.length; i++) {
13213 const { key, value } = properties[i];
13214 // key
13215 genExpressionAsPropertyKey(key, context);
13216 push(`: `);
13217 // value
13218 genNode(value, context);
13219 if (i < properties.length - 1) {
13220 // will only reach this if it's multilines
13221 push(`,`);
13222 newline();
13223 }
13224 }
13225 multilines && deindent();
13226 push(multilines ? `}` : ` }`);
13227 }
13228 function genArrayExpression(node, context) {
13229 genNodeListAsArray(node.elements, context);
13230 }
13231 function genFunctionExpression(node, context) {
13232 const { push, indent, deindent } = context;
13233 const { params, returns, body, newline, isSlot } = node;
13234 if (isSlot) {
13235 // wrap slot functions with owner context
13236 push(`_${helperNameMap[WITH_CTX]}(`);
13237 }
13238 push(`(`, node);
13239 if (isArray(params)) {
13240 genNodeList(params, context);
13241 }
13242 else if (params) {
13243 genNode(params, context);
13244 }
13245 push(`) => `);
13246 if (newline || body) {
13247 push(`{`);
13248 indent();
13249 }
13250 if (returns) {
13251 if (newline) {
13252 push(`return `);
13253 }
13254 if (isArray(returns)) {
13255 genNodeListAsArray(returns, context);
13256 }
13257 else {
13258 genNode(returns, context);
13259 }
13260 }
13261 else if (body) {
13262 genNode(body, context);
13263 }
13264 if (newline || body) {
13265 deindent();
13266 push(`}`);
13267 }
13268 if (isSlot) {
13269 push(`)`);
13270 }
13271 }
13272 function genConditionalExpression(node, context) {
13273 const { test, consequent, alternate, newline: needNewline } = node;
13274 const { push, indent, deindent, newline } = context;
13275 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13276 const needsParens = !isSimpleIdentifier(test.content);
13277 needsParens && push(`(`);
13278 genExpression(test, context);
13279 needsParens && push(`)`);
13280 }
13281 else {
13282 push(`(`);
13283 genNode(test, context);
13284 push(`)`);
13285 }
13286 needNewline && indent();
13287 context.indentLevel++;
13288 needNewline || push(` `);
13289 push(`? `);
13290 genNode(consequent, context);
13291 context.indentLevel--;
13292 needNewline && newline();
13293 needNewline || push(` `);
13294 push(`: `);
13295 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13296 if (!isNested) {
13297 context.indentLevel++;
13298 }
13299 genNode(alternate, context);
13300 if (!isNested) {
13301 context.indentLevel--;
13302 }
13303 needNewline && deindent(true /* without newline */);
13304 }
13305 function genCacheExpression(node, context) {
13306 const { push, helper, indent, deindent, newline } = context;
13307 push(`_cache[${node.index}] || (`);
13308 if (node.isVNode) {
13309 indent();
13310 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13311 newline();
13312 }
13313 push(`_cache[${node.index}] = `);
13314 genNode(node.value, context);
13315 if (node.isVNode) {
13316 push(`,`);
13317 newline();
13318 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13319 newline();
13320 push(`_cache[${node.index}]`);
13321 deindent();
13322 }
13323 push(`)`);
13324 }
13325
13326 // these keywords should not appear inside expressions, but operators like
13327 // typeof, instanceof and in are allowed
13328 const prohibitedKeywordRE = new RegExp('\\b' +
13329 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13330 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13331 'extends,finally,continue,debugger,function,arguments,typeof,void')
13332 .split(',')
13333 .join('\\b|\\b') +
13334 '\\b');
13335 // strip strings in expressions
13336 const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13337 /**
13338 * Validate a non-prefixed expression.
13339 * This is only called when using the in-browser runtime compiler since it
13340 * doesn't prefix expressions.
13341 */
13342 function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13343 const exp = node.content;
13344 // empty expressions are validated per-directive since some directives
13345 // do allow empty expressions.
13346 if (!exp.trim()) {
13347 return;
13348 }
13349 try {
13350 new Function(asRawStatements
13351 ? ` ${exp} `
13352 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13353 }
13354 catch (e) {
13355 let message = e.message;
13356 const keywordMatch = exp
13357 .replace(stripStringRE, '')
13358 .match(prohibitedKeywordRE);
13359 if (keywordMatch) {
13360 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13361 }
13362 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13363 }
13364 }
13365
13366 const transformExpression = (node, context) => {
13367 if (node.type === 5 /* INTERPOLATION */) {
13368 node.content = processExpression(node.content, context);
13369 }
13370 else if (node.type === 1 /* ELEMENT */) {
13371 // handle directives on element
13372 for (let i = 0; i < node.props.length; i++) {
13373 const dir = node.props[i];
13374 // do not process for v-on & v-for since they are special handled
13375 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13376 const exp = dir.exp;
13377 const arg = dir.arg;
13378 // do not process exp if this is v-on:arg - we need special handling
13379 // for wrapping inline statements.
13380 if (exp &&
13381 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13382 !(dir.name === 'on' && arg)) {
13383 dir.exp = processExpression(exp, context,
13384 // slot args must be processed as function params
13385 dir.name === 'slot');
13386 }
13387 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13388 dir.arg = processExpression(arg, context);
13389 }
13390 }
13391 }
13392 }
13393 };
13394 // Important: since this function uses Node.js only dependencies, it should
13395 // always be used with a leading !true check so that it can be
13396 // tree-shaken from the browser build.
13397 function processExpression(node, context,
13398 // some expressions like v-slot props & v-for aliases should be parsed as
13399 // function params
13400 asParams = false,
13401 // v-on handler values may contain multiple statements
13402 asRawStatements = false, localVars = Object.create(context.identifiers)) {
13403 {
13404 {
13405 // simple in-browser validation (same logic in 2.x)
13406 validateBrowserExpression(node, context, asParams, asRawStatements);
13407 }
13408 return node;
13409 }
13410 }
13411
13412 const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13413 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13414 // #1587: We need to dynamically increment the key based on the current
13415 // node's sibling nodes, since chained v-if/else branches are
13416 // rendered at the same depth
13417 const siblings = context.parent.children;
13418 let i = siblings.indexOf(ifNode);
13419 let key = 0;
13420 while (i-- >= 0) {
13421 const sibling = siblings[i];
13422 if (sibling && sibling.type === 9 /* IF */) {
13423 key += sibling.branches.length;
13424 }
13425 }
13426 // Exit callback. Complete the codegenNode when all children have been
13427 // transformed.
13428 return () => {
13429 if (isRoot) {
13430 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13431 }
13432 else {
13433 // attach this branch's codegen node to the v-if root.
13434 const parentCondition = getParentCondition(ifNode.codegenNode);
13435 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13436 }
13437 };
13438 });
13439 });
13440 // target-agnostic transform used for both Client and SSR
13441 function processIf(node, dir, context, processCodegen) {
13442 if (dir.name !== 'else' &&
13443 (!dir.exp || !dir.exp.content.trim())) {
13444 const loc = dir.exp ? dir.exp.loc : node.loc;
13445 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13446 dir.exp = createSimpleExpression(`true`, false, loc);
13447 }
13448 if (dir.exp) {
13449 validateBrowserExpression(dir.exp, context);
13450 }
13451 if (dir.name === 'if') {
13452 const branch = createIfBranch(node, dir);
13453 const ifNode = {
13454 type: 9 /* IF */,
13455 loc: node.loc,
13456 branches: [branch]
13457 };
13458 context.replaceNode(ifNode);
13459 if (processCodegen) {
13460 return processCodegen(ifNode, branch, true);
13461 }
13462 }
13463 else {
13464 // locate the adjacent v-if
13465 const siblings = context.parent.children;
13466 const comments = [];
13467 let i = siblings.indexOf(node);
13468 while (i-- >= -1) {
13469 const sibling = siblings[i];
13470 if (sibling && sibling.type === 3 /* COMMENT */) {
13471 context.removeNode(sibling);
13472 comments.unshift(sibling);
13473 continue;
13474 }
13475 if (sibling &&
13476 sibling.type === 2 /* TEXT */ &&
13477 !sibling.content.trim().length) {
13478 context.removeNode(sibling);
13479 continue;
13480 }
13481 if (sibling && sibling.type === 9 /* IF */) {
13482 // Check if v-else was followed by v-else-if
13483 if (dir.name === 'else-if' &&
13484 sibling.branches[sibling.branches.length - 1].condition === undefined) {
13485 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13486 }
13487 // move the node to the if node's branches
13488 context.removeNode();
13489 const branch = createIfBranch(node, dir);
13490 if (comments.length &&
13491 // #3619 ignore comments if the v-if is direct child of <transition>
13492 !(context.parent &&
13493 context.parent.type === 1 /* ELEMENT */ &&
13494 isBuiltInType(context.parent.tag, 'transition'))) {
13495 branch.children = [...comments, ...branch.children];
13496 }
13497 // check if user is forcing same key on different branches
13498 {
13499 const key = branch.userKey;
13500 if (key) {
13501 sibling.branches.forEach(({ userKey }) => {
13502 if (isSameKey(userKey, key)) {
13503 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13504 }
13505 });
13506 }
13507 }
13508 sibling.branches.push(branch);
13509 const onExit = processCodegen && processCodegen(sibling, branch, false);
13510 // since the branch was removed, it will not be traversed.
13511 // make sure to traverse here.
13512 traverseNode(branch, context);
13513 // call on exit
13514 if (onExit)
13515 onExit();
13516 // make sure to reset currentNode after traversal to indicate this
13517 // node has been removed.
13518 context.currentNode = null;
13519 }
13520 else {
13521 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13522 }
13523 break;
13524 }
13525 }
13526 }
13527 function createIfBranch(node, dir) {
13528 return {
13529 type: 10 /* IF_BRANCH */,
13530 loc: node.loc,
13531 condition: dir.name === 'else' ? undefined : dir.exp,
13532 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13533 ? node.children
13534 : [node],
13535 userKey: findProp(node, `key`)
13536 };
13537 }
13538 function createCodegenNodeForBranch(branch, keyIndex, context) {
13539 if (branch.condition) {
13540 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13541 // make sure to pass in asBlock: true so that the comment node call
13542 // closes the current block.
13543 createCallExpression(context.helper(CREATE_COMMENT), [
13544 '"v-if"' ,
13545 'true'
13546 ]));
13547 }
13548 else {
13549 return createChildrenCodegenNode(branch, keyIndex, context);
13550 }
13551 }
13552 function createChildrenCodegenNode(branch, keyIndex, context) {
13553 const { helper } = context;
13554 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13555 const { children } = branch;
13556 const firstChild = children[0];
13557 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13558 if (needFragmentWrapper) {
13559 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13560 // optimize away nested fragments when child is a ForNode
13561 const vnodeCall = firstChild.codegenNode;
13562 injectProp(vnodeCall, keyProperty, context);
13563 return vnodeCall;
13564 }
13565 else {
13566 let patchFlag = 64 /* STABLE_FRAGMENT */;
13567 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13568 // check if the fragment actually contains a single valid child with
13569 // the rest being comments
13570 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13571 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13572 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13573 }
13574 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13575 }
13576 }
13577 else {
13578 const ret = firstChild.codegenNode;
13579 const vnodeCall = getMemoedVNodeCall(ret);
13580 // Change createVNode to createBlock.
13581 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13582 makeBlock(vnodeCall, context);
13583 }
13584 // inject branch key
13585 injectProp(vnodeCall, keyProperty, context);
13586 return ret;
13587 }
13588 }
13589 function isSameKey(a, b) {
13590 if (!a || a.type !== b.type) {
13591 return false;
13592 }
13593 if (a.type === 6 /* ATTRIBUTE */) {
13594 if (a.value.content !== b.value.content) {
13595 return false;
13596 }
13597 }
13598 else {
13599 // directive
13600 const exp = a.exp;
13601 const branchExp = b.exp;
13602 if (exp.type !== branchExp.type) {
13603 return false;
13604 }
13605 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13606 exp.isStatic !== branchExp.isStatic ||
13607 exp.content !== branchExp.content) {
13608 return false;
13609 }
13610 }
13611 return true;
13612 }
13613 function getParentCondition(node) {
13614 while (true) {
13615 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13616 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13617 node = node.alternate;
13618 }
13619 else {
13620 return node;
13621 }
13622 }
13623 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13624 node = node.value;
13625 }
13626 }
13627 }
13628
13629 const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13630 const { helper, removeHelper } = context;
13631 return processFor(node, dir, context, forNode => {
13632 // create the loop render function expression now, and add the
13633 // iterator on exit after all children have been traversed
13634 const renderExp = createCallExpression(helper(RENDER_LIST), [
13635 forNode.source
13636 ]);
13637 const isTemplate = isTemplateNode(node);
13638 const memo = findDir(node, 'memo');
13639 const keyProp = findProp(node, `key`);
13640 const keyExp = keyProp &&
13641 (keyProp.type === 6 /* ATTRIBUTE */
13642 ? createSimpleExpression(keyProp.value.content, true)
13643 : keyProp.exp);
13644 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13645 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13646 forNode.source.constType > 0 /* NOT_CONSTANT */;
13647 const fragmentFlag = isStableFragment
13648 ? 64 /* STABLE_FRAGMENT */
13649 : keyProp
13650 ? 128 /* KEYED_FRAGMENT */
13651 : 256 /* UNKEYED_FRAGMENT */;
13652 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13653 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13654 return () => {
13655 // finish the codegen now that all children have been traversed
13656 let childBlock;
13657 const { children } = forNode;
13658 // check <template v-for> key placement
13659 if (isTemplate) {
13660 node.children.some(c => {
13661 if (c.type === 1 /* ELEMENT */) {
13662 const key = findProp(c, 'key');
13663 if (key) {
13664 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13665 return true;
13666 }
13667 }
13668 });
13669 }
13670 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13671 const slotOutlet = isSlotOutlet(node)
13672 ? node
13673 : isTemplate &&
13674 node.children.length === 1 &&
13675 isSlotOutlet(node.children[0])
13676 ? node.children[0] // api-extractor somehow fails to infer this
13677 : null;
13678 if (slotOutlet) {
13679 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13680 childBlock = slotOutlet.codegenNode;
13681 if (isTemplate && keyProperty) {
13682 // <template v-for="..." :key="..."><slot/></template>
13683 // we need to inject the key to the renderSlot() call.
13684 // the props for renderSlot is passed as the 3rd argument.
13685 injectProp(childBlock, keyProperty, context);
13686 }
13687 }
13688 else if (needFragmentWrapper) {
13689 // <template v-for="..."> with text or multi-elements
13690 // should generate a fragment block for each loop
13691 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
13692 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
13693 ), undefined, undefined, true, undefined, false /* isComponent */);
13694 }
13695 else {
13696 // Normal element v-for. Directly use the child's codegenNode
13697 // but mark it as a block.
13698 childBlock = children[0]
13699 .codegenNode;
13700 if (isTemplate && keyProperty) {
13701 injectProp(childBlock, keyProperty, context);
13702 }
13703 if (childBlock.isBlock !== !isStableFragment) {
13704 if (childBlock.isBlock) {
13705 // switch from block to vnode
13706 removeHelper(OPEN_BLOCK);
13707 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13708 }
13709 else {
13710 // switch from vnode to block
13711 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13712 }
13713 }
13714 childBlock.isBlock = !isStableFragment;
13715 if (childBlock.isBlock) {
13716 helper(OPEN_BLOCK);
13717 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13718 }
13719 else {
13720 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13721 }
13722 }
13723 if (memo) {
13724 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
13725 createSimpleExpression(`_cached`)
13726 ]));
13727 loop.body = createBlockStatement([
13728 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
13729 createCompoundExpression([
13730 `if (_cached`,
13731 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
13732 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
13733 ]),
13734 createCompoundExpression([`const _item = `, childBlock]),
13735 createSimpleExpression(`_item.memo = _memo`),
13736 createSimpleExpression(`return _item`)
13737 ]);
13738 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
13739 }
13740 else {
13741 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
13742 }
13743 };
13744 });
13745 });
13746 // target-agnostic transform used for both Client and SSR
13747 function processFor(node, dir, context, processCodegen) {
13748 if (!dir.exp) {
13749 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
13750 return;
13751 }
13752 const parseResult = parseForExpression(
13753 // can only be simple expression because vFor transform is applied
13754 // before expression transform.
13755 dir.exp, context);
13756 if (!parseResult) {
13757 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
13758 return;
13759 }
13760 const { addIdentifiers, removeIdentifiers, scopes } = context;
13761 const { source, value, key, index } = parseResult;
13762 const forNode = {
13763 type: 11 /* FOR */,
13764 loc: dir.loc,
13765 source,
13766 valueAlias: value,
13767 keyAlias: key,
13768 objectIndexAlias: index,
13769 parseResult,
13770 children: isTemplateNode(node) ? node.children : [node]
13771 };
13772 context.replaceNode(forNode);
13773 // bookkeeping
13774 scopes.vFor++;
13775 const onExit = processCodegen && processCodegen(forNode);
13776 return () => {
13777 scopes.vFor--;
13778 if (onExit)
13779 onExit();
13780 };
13781 }
13782 const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
13783 // This regex doesn't cover the case if key or index aliases have destructuring,
13784 // but those do not make sense in the first place, so this works in practice.
13785 const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
13786 const stripParensRE = /^\(|\)$/g;
13787 function parseForExpression(input, context) {
13788 const loc = input.loc;
13789 const exp = input.content;
13790 const inMatch = exp.match(forAliasRE);
13791 if (!inMatch)
13792 return;
13793 const [, LHS, RHS] = inMatch;
13794 const result = {
13795 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
13796 value: undefined,
13797 key: undefined,
13798 index: undefined
13799 };
13800 {
13801 validateBrowserExpression(result.source, context);
13802 }
13803 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
13804 const trimmedOffset = LHS.indexOf(valueContent);
13805 const iteratorMatch = valueContent.match(forIteratorRE);
13806 if (iteratorMatch) {
13807 valueContent = valueContent.replace(forIteratorRE, '').trim();
13808 const keyContent = iteratorMatch[1].trim();
13809 let keyOffset;
13810 if (keyContent) {
13811 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
13812 result.key = createAliasExpression(loc, keyContent, keyOffset);
13813 {
13814 validateBrowserExpression(result.key, context, true);
13815 }
13816 }
13817 if (iteratorMatch[2]) {
13818 const indexContent = iteratorMatch[2].trim();
13819 if (indexContent) {
13820 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
13821 ? keyOffset + keyContent.length
13822 : trimmedOffset + valueContent.length));
13823 {
13824 validateBrowserExpression(result.index, context, true);
13825 }
13826 }
13827 }
13828 }
13829 if (valueContent) {
13830 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
13831 {
13832 validateBrowserExpression(result.value, context, true);
13833 }
13834 }
13835 return result;
13836 }
13837 function createAliasExpression(range, content, offset) {
13838 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
13839 }
13840 function createForLoopParams({ value, key, index }, memoArgs = []) {
13841 return createParamsList([value, key, index, ...memoArgs]);
13842 }
13843 function createParamsList(args) {
13844 let i = args.length;
13845 while (i--) {
13846 if (args[i])
13847 break;
13848 }
13849 return args
13850 .slice(0, i + 1)
13851 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
13852 }
13853
13854 const defaultFallback = createSimpleExpression(`undefined`, false);
13855 // A NodeTransform that:
13856 // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
13857 // by transformExpression. This is only applied in non-browser builds with
13858 // { prefixIdentifiers: true }.
13859 // 2. Track v-slot depths so that we know a slot is inside another slot.
13860 // Note the exit callback is executed before buildSlots() on the same node,
13861 // so only nested slots see positive numbers.
13862 const trackSlotScopes = (node, context) => {
13863 if (node.type === 1 /* ELEMENT */ &&
13864 (node.tagType === 1 /* COMPONENT */ ||
13865 node.tagType === 3 /* TEMPLATE */)) {
13866 // We are only checking non-empty v-slot here
13867 // since we only care about slots that introduce scope variables.
13868 const vSlot = findDir(node, 'slot');
13869 if (vSlot) {
13870 vSlot.exp;
13871 context.scopes.vSlot++;
13872 return () => {
13873 context.scopes.vSlot--;
13874 };
13875 }
13876 }
13877 };
13878 const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
13879 // Instead of being a DirectiveTransform, v-slot processing is called during
13880 // transformElement to build the slots object for a component.
13881 function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
13882 context.helper(WITH_CTX);
13883 const { children, loc } = node;
13884 const slotsProperties = [];
13885 const dynamicSlots = [];
13886 // If the slot is inside a v-for or another v-slot, force it to be dynamic
13887 // since it likely uses a scope variable.
13888 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
13889 // 1. Check for slot with slotProps on component itself.
13890 // <Comp v-slot="{ prop }"/>
13891 const onComponentSlot = findDir(node, 'slot', true);
13892 if (onComponentSlot) {
13893 const { arg, exp } = onComponentSlot;
13894 if (arg && !isStaticExp(arg)) {
13895 hasDynamicSlots = true;
13896 }
13897 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
13898 }
13899 // 2. Iterate through children and check for template slots
13900 // <template v-slot:foo="{ prop }">
13901 let hasTemplateSlots = false;
13902 let hasNamedDefaultSlot = false;
13903 const implicitDefaultChildren = [];
13904 const seenSlotNames = new Set();
13905 for (let i = 0; i < children.length; i++) {
13906 const slotElement = children[i];
13907 let slotDir;
13908 if (!isTemplateNode(slotElement) ||
13909 !(slotDir = findDir(slotElement, 'slot', true))) {
13910 // not a <template v-slot>, skip.
13911 if (slotElement.type !== 3 /* COMMENT */) {
13912 implicitDefaultChildren.push(slotElement);
13913 }
13914 continue;
13915 }
13916 if (onComponentSlot) {
13917 // already has on-component slot - this is incorrect usage.
13918 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
13919 break;
13920 }
13921 hasTemplateSlots = true;
13922 const { children: slotChildren, loc: slotLoc } = slotElement;
13923 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
13924 // check if name is dynamic.
13925 let staticSlotName;
13926 if (isStaticExp(slotName)) {
13927 staticSlotName = slotName ? slotName.content : `default`;
13928 }
13929 else {
13930 hasDynamicSlots = true;
13931 }
13932 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
13933 // check if this slot is conditional (v-if/v-for)
13934 let vIf;
13935 let vElse;
13936 let vFor;
13937 if ((vIf = findDir(slotElement, 'if'))) {
13938 hasDynamicSlots = true;
13939 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
13940 }
13941 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
13942 // find adjacent v-if
13943 let j = i;
13944 let prev;
13945 while (j--) {
13946 prev = children[j];
13947 if (prev.type !== 3 /* COMMENT */) {
13948 break;
13949 }
13950 }
13951 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
13952 // remove node
13953 children.splice(i, 1);
13954 i--;
13955 // attach this slot to previous conditional
13956 let conditional = dynamicSlots[dynamicSlots.length - 1];
13957 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13958 conditional = conditional.alternate;
13959 }
13960 conditional.alternate = vElse.exp
13961 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
13962 : buildDynamicSlot(slotName, slotFunction);
13963 }
13964 else {
13965 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
13966 }
13967 }
13968 else if ((vFor = findDir(slotElement, 'for'))) {
13969 hasDynamicSlots = true;
13970 const parseResult = vFor.parseResult ||
13971 parseForExpression(vFor.exp, context);
13972 if (parseResult) {
13973 // Render the dynamic slots as an array and add it to the createSlot()
13974 // args. The runtime knows how to handle it appropriately.
13975 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
13976 parseResult.source,
13977 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
13978 ]));
13979 }
13980 else {
13981 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
13982 }
13983 }
13984 else {
13985 // check duplicate static names
13986 if (staticSlotName) {
13987 if (seenSlotNames.has(staticSlotName)) {
13988 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
13989 continue;
13990 }
13991 seenSlotNames.add(staticSlotName);
13992 if (staticSlotName === 'default') {
13993 hasNamedDefaultSlot = true;
13994 }
13995 }
13996 slotsProperties.push(createObjectProperty(slotName, slotFunction));
13997 }
13998 }
13999 if (!onComponentSlot) {
14000 const buildDefaultSlotProperty = (props, children) => {
14001 const fn = buildSlotFn(props, children, loc);
14002 return createObjectProperty(`default`, fn);
14003 };
14004 if (!hasTemplateSlots) {
14005 // implicit default slot (on component)
14006 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14007 }
14008 else if (implicitDefaultChildren.length &&
14009 // #3766
14010 // with whitespace: 'preserve', whitespaces between slots will end up in
14011 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14012 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14013 // implicit default slot (mixed with named slots)
14014 if (hasNamedDefaultSlot) {
14015 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14016 }
14017 else {
14018 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14019 }
14020 }
14021 }
14022 const slotFlag = hasDynamicSlots
14023 ? 2 /* DYNAMIC */
14024 : hasForwardedSlots(node.children)
14025 ? 3 /* FORWARDED */
14026 : 1 /* STABLE */;
14027 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14028 // 2 = compiled but dynamic = can skip normalization, but must run diff
14029 // 1 = compiled and static = can skip normalization AND diff as optimized
14030 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14031 if (dynamicSlots.length) {
14032 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14033 slots,
14034 createArrayExpression(dynamicSlots)
14035 ]);
14036 }
14037 return {
14038 slots,
14039 hasDynamicSlots
14040 };
14041 }
14042 function buildDynamicSlot(name, fn) {
14043 return createObjectExpression([
14044 createObjectProperty(`name`, name),
14045 createObjectProperty(`fn`, fn)
14046 ]);
14047 }
14048 function hasForwardedSlots(children) {
14049 for (let i = 0; i < children.length; i++) {
14050 const child = children[i];
14051 switch (child.type) {
14052 case 1 /* ELEMENT */:
14053 if (child.tagType === 2 /* SLOT */ ||
14054 hasForwardedSlots(child.children)) {
14055 return true;
14056 }
14057 break;
14058 case 9 /* IF */:
14059 if (hasForwardedSlots(child.branches))
14060 return true;
14061 break;
14062 case 10 /* IF_BRANCH */:
14063 case 11 /* FOR */:
14064 if (hasForwardedSlots(child.children))
14065 return true;
14066 break;
14067 }
14068 }
14069 return false;
14070 }
14071 function isNonWhitespaceContent(node) {
14072 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14073 return true;
14074 return node.type === 2 /* TEXT */
14075 ? !!node.content.trim()
14076 : isNonWhitespaceContent(node.content);
14077 }
14078
14079 // some directive transforms (e.g. v-model) may return a symbol for runtime
14080 // import, which should be used instead of a resolveDirective call.
14081 const directiveImportMap = new WeakMap();
14082 // generate a JavaScript AST for this element's codegen
14083 const transformElement = (node, context) => {
14084 // perform the work on exit, after all child expressions have been
14085 // processed and merged.
14086 return function postTransformElement() {
14087 node = context.currentNode;
14088 if (!(node.type === 1 /* ELEMENT */ &&
14089 (node.tagType === 0 /* ELEMENT */ ||
14090 node.tagType === 1 /* COMPONENT */))) {
14091 return;
14092 }
14093 const { tag, props } = node;
14094 const isComponent = node.tagType === 1 /* COMPONENT */;
14095 // The goal of the transform is to create a codegenNode implementing the
14096 // VNodeCall interface.
14097 let vnodeTag = isComponent
14098 ? resolveComponentType(node, context)
14099 : `"${tag}"`;
14100 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14101 let vnodeProps;
14102 let vnodeChildren;
14103 let vnodePatchFlag;
14104 let patchFlag = 0;
14105 let vnodeDynamicProps;
14106 let dynamicPropNames;
14107 let vnodeDirectives;
14108 let shouldUseBlock =
14109 // dynamic component may resolve to plain elements
14110 isDynamicComponent ||
14111 vnodeTag === TELEPORT ||
14112 vnodeTag === SUSPENSE ||
14113 (!isComponent &&
14114 // <svg> and <foreignObject> must be forced into blocks so that block
14115 // updates inside get proper isSVG flag at runtime. (#639, #643)
14116 // This is technically web-specific, but splitting the logic out of core
14117 // leads to too much unnecessary complexity.
14118 (tag === 'svg' || tag === 'foreignObject'));
14119 // props
14120 if (props.length > 0) {
14121 const propsBuildResult = buildProps(node, context);
14122 vnodeProps = propsBuildResult.props;
14123 patchFlag = propsBuildResult.patchFlag;
14124 dynamicPropNames = propsBuildResult.dynamicPropNames;
14125 const directives = propsBuildResult.directives;
14126 vnodeDirectives =
14127 directives && directives.length
14128 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14129 : undefined;
14130 if (propsBuildResult.shouldUseBlock) {
14131 shouldUseBlock = true;
14132 }
14133 }
14134 // children
14135 if (node.children.length > 0) {
14136 if (vnodeTag === KEEP_ALIVE) {
14137 // Although a built-in component, we compile KeepAlive with raw children
14138 // instead of slot functions so that it can be used inside Transition
14139 // or other Transition-wrapping HOCs.
14140 // To ensure correct updates with block optimizations, we need to:
14141 // 1. Force keep-alive into a block. This avoids its children being
14142 // collected by a parent block.
14143 shouldUseBlock = true;
14144 // 2. Force keep-alive to always be updated, since it uses raw children.
14145 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14146 if (node.children.length > 1) {
14147 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14148 start: node.children[0].loc.start,
14149 end: node.children[node.children.length - 1].loc.end,
14150 source: ''
14151 }));
14152 }
14153 }
14154 const shouldBuildAsSlots = isComponent &&
14155 // Teleport is not a real component and has dedicated runtime handling
14156 vnodeTag !== TELEPORT &&
14157 // explained above.
14158 vnodeTag !== KEEP_ALIVE;
14159 if (shouldBuildAsSlots) {
14160 const { slots, hasDynamicSlots } = buildSlots(node, context);
14161 vnodeChildren = slots;
14162 if (hasDynamicSlots) {
14163 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14164 }
14165 }
14166 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14167 const child = node.children[0];
14168 const type = child.type;
14169 // check for dynamic text children
14170 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14171 type === 8 /* COMPOUND_EXPRESSION */;
14172 if (hasDynamicTextChild &&
14173 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14174 patchFlag |= 1 /* TEXT */;
14175 }
14176 // pass directly if the only child is a text node
14177 // (plain / interpolation / expression)
14178 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14179 vnodeChildren = child;
14180 }
14181 else {
14182 vnodeChildren = node.children;
14183 }
14184 }
14185 else {
14186 vnodeChildren = node.children;
14187 }
14188 }
14189 // patchFlag & dynamicPropNames
14190 if (patchFlag !== 0) {
14191 {
14192 if (patchFlag < 0) {
14193 // special flags (negative and mutually exclusive)
14194 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14195 }
14196 else {
14197 // bitwise flags
14198 const flagNames = Object.keys(PatchFlagNames)
14199 .map(Number)
14200 .filter(n => n > 0 && patchFlag & n)
14201 .map(n => PatchFlagNames[n])
14202 .join(`, `);
14203 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14204 }
14205 }
14206 if (dynamicPropNames && dynamicPropNames.length) {
14207 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14208 }
14209 }
14210 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14211 };
14212 };
14213 function resolveComponentType(node, context, ssr = false) {
14214 let { tag } = node;
14215 // 1. dynamic component
14216 const isExplicitDynamic = isComponentTag(tag);
14217 const isProp = findProp(node, 'is');
14218 if (isProp) {
14219 if (isExplicitDynamic ||
14220 (false )) {
14221 const exp = isProp.type === 6 /* ATTRIBUTE */
14222 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14223 : isProp.exp;
14224 if (exp) {
14225 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14226 exp
14227 ]);
14228 }
14229 }
14230 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14231 isProp.value.content.startsWith('vue:')) {
14232 // <button is="vue:xxx">
14233 // if not <component>, only is value that starts with "vue:" will be
14234 // treated as component by the parse phase and reach here, unless it's
14235 // compat mode where all is values are considered components
14236 tag = isProp.value.content.slice(4);
14237 }
14238 }
14239 // 1.5 v-is (TODO: Deprecate)
14240 const isDir = !isExplicitDynamic && findDir(node, 'is');
14241 if (isDir && isDir.exp) {
14242 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14243 isDir.exp
14244 ]);
14245 }
14246 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14247 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14248 if (builtIn) {
14249 // built-ins are simply fallthroughs / have special handling during ssr
14250 // so we don't need to import their runtime equivalents
14251 if (!ssr)
14252 context.helper(builtIn);
14253 return builtIn;
14254 }
14255 // 5. user component (resolve)
14256 context.helper(RESOLVE_COMPONENT);
14257 context.components.add(tag);
14258 return toValidAssetId(tag, `component`);
14259 }
14260 function buildProps(node, context, props = node.props, ssr = false) {
14261 const { tag, loc: elementLoc, children } = node;
14262 const isComponent = node.tagType === 1 /* COMPONENT */;
14263 let properties = [];
14264 const mergeArgs = [];
14265 const runtimeDirectives = [];
14266 const hasChildren = children.length > 0;
14267 let shouldUseBlock = false;
14268 // patchFlag analysis
14269 let patchFlag = 0;
14270 let hasRef = false;
14271 let hasClassBinding = false;
14272 let hasStyleBinding = false;
14273 let hasHydrationEventBinding = false;
14274 let hasDynamicKeys = false;
14275 let hasVnodeHook = false;
14276 const dynamicPropNames = [];
14277 const analyzePatchFlag = ({ key, value }) => {
14278 if (isStaticExp(key)) {
14279 const name = key.content;
14280 const isEventHandler = isOn(name);
14281 if (!isComponent &&
14282 isEventHandler &&
14283 // omit the flag for click handlers because hydration gives click
14284 // dedicated fast path.
14285 name.toLowerCase() !== 'onclick' &&
14286 // omit v-model handlers
14287 name !== 'onUpdate:modelValue' &&
14288 // omit onVnodeXXX hooks
14289 !isReservedProp(name)) {
14290 hasHydrationEventBinding = true;
14291 }
14292 if (isEventHandler && isReservedProp(name)) {
14293 hasVnodeHook = true;
14294 }
14295 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14296 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14297 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14298 getConstantType(value, context) > 0)) {
14299 // skip if the prop is a cached handler or has constant value
14300 return;
14301 }
14302 if (name === 'ref') {
14303 hasRef = true;
14304 }
14305 else if (name === 'class') {
14306 hasClassBinding = true;
14307 }
14308 else if (name === 'style') {
14309 hasStyleBinding = true;
14310 }
14311 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14312 dynamicPropNames.push(name);
14313 }
14314 // treat the dynamic class and style binding of the component as dynamic props
14315 if (isComponent &&
14316 (name === 'class' || name === 'style') &&
14317 !dynamicPropNames.includes(name)) {
14318 dynamicPropNames.push(name);
14319 }
14320 }
14321 else {
14322 hasDynamicKeys = true;
14323 }
14324 };
14325 for (let i = 0; i < props.length; i++) {
14326 // static attribute
14327 const prop = props[i];
14328 if (prop.type === 6 /* ATTRIBUTE */) {
14329 const { loc, name, value } = prop;
14330 let isStatic = true;
14331 if (name === 'ref') {
14332 hasRef = true;
14333 if (context.scopes.vFor > 0) {
14334 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14335 }
14336 }
14337 // skip is on <component>, or is="vue:xxx"
14338 if (name === 'is' &&
14339 (isComponentTag(tag) ||
14340 (value && value.content.startsWith('vue:')) ||
14341 (false ))) {
14342 continue;
14343 }
14344 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
14345 }
14346 else {
14347 // directives
14348 const { name, arg, exp, loc } = prop;
14349 const isVBind = name === 'bind';
14350 const isVOn = name === 'on';
14351 // skip v-slot - it is handled by its dedicated transform.
14352 if (name === 'slot') {
14353 if (!isComponent) {
14354 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14355 }
14356 continue;
14357 }
14358 // skip v-once/v-memo - they are handled by dedicated transforms.
14359 if (name === 'once' || name === 'memo') {
14360 continue;
14361 }
14362 // skip v-is and :is on <component>
14363 if (name === 'is' ||
14364 (isVBind &&
14365 isStaticArgOf(arg, 'is') &&
14366 (isComponentTag(tag) ||
14367 (false )))) {
14368 continue;
14369 }
14370 // skip v-on in SSR compilation
14371 if (isVOn && ssr) {
14372 continue;
14373 }
14374 if (
14375 // #938: elements with dynamic keys should be forced into blocks
14376 (isVBind && isStaticArgOf(arg, 'key')) ||
14377 // inline before-update hooks need to force block so that it is invoked
14378 // before children
14379 (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
14380 shouldUseBlock = true;
14381 }
14382 if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
14383 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14384 }
14385 // special case for v-bind and v-on with no argument
14386 if (!arg && (isVBind || isVOn)) {
14387 hasDynamicKeys = true;
14388 if (exp) {
14389 if (properties.length) {
14390 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14391 properties = [];
14392 }
14393 if (isVBind) {
14394 mergeArgs.push(exp);
14395 }
14396 else {
14397 // v-on="obj" -> toHandlers(obj)
14398 mergeArgs.push({
14399 type: 14 /* JS_CALL_EXPRESSION */,
14400 loc,
14401 callee: context.helper(TO_HANDLERS),
14402 arguments: [exp]
14403 });
14404 }
14405 }
14406 else {
14407 context.onError(createCompilerError(isVBind
14408 ? 34 /* X_V_BIND_NO_EXPRESSION */
14409 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14410 }
14411 continue;
14412 }
14413 const directiveTransform = context.directiveTransforms[name];
14414 if (directiveTransform) {
14415 // has built-in directive transform.
14416 const { props, needRuntime } = directiveTransform(prop, node, context);
14417 !ssr && props.forEach(analyzePatchFlag);
14418 properties.push(...props);
14419 if (needRuntime) {
14420 runtimeDirectives.push(prop);
14421 if (isSymbol(needRuntime)) {
14422 directiveImportMap.set(prop, needRuntime);
14423 }
14424 }
14425 }
14426 else {
14427 // no built-in transform, this is a user custom directive.
14428 runtimeDirectives.push(prop);
14429 // custom dirs may use beforeUpdate so they need to force blocks
14430 // to ensure before-update gets called before children update
14431 if (hasChildren) {
14432 shouldUseBlock = true;
14433 }
14434 }
14435 }
14436 }
14437 let propsExpression = undefined;
14438 // has v-bind="object" or v-on="object", wrap with mergeProps
14439 if (mergeArgs.length) {
14440 if (properties.length) {
14441 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14442 }
14443 if (mergeArgs.length > 1) {
14444 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14445 }
14446 else {
14447 // single v-bind with nothing else - no need for a mergeProps call
14448 propsExpression = mergeArgs[0];
14449 }
14450 }
14451 else if (properties.length) {
14452 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14453 }
14454 // patchFlag analysis
14455 if (hasDynamicKeys) {
14456 patchFlag |= 16 /* FULL_PROPS */;
14457 }
14458 else {
14459 if (hasClassBinding && !isComponent) {
14460 patchFlag |= 2 /* CLASS */;
14461 }
14462 if (hasStyleBinding && !isComponent) {
14463 patchFlag |= 4 /* STYLE */;
14464 }
14465 if (dynamicPropNames.length) {
14466 patchFlag |= 8 /* PROPS */;
14467 }
14468 if (hasHydrationEventBinding) {
14469 patchFlag |= 32 /* HYDRATE_EVENTS */;
14470 }
14471 }
14472 if (!shouldUseBlock &&
14473 (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14474 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14475 patchFlag |= 512 /* NEED_PATCH */;
14476 }
14477 // pre-normalize props, SSR is skipped for now
14478 if (!context.inSSR && propsExpression) {
14479 switch (propsExpression.type) {
14480 case 15 /* JS_OBJECT_EXPRESSION */:
14481 // means that there is no v-bind,
14482 // but still need to deal with dynamic key binding
14483 let classKeyIndex = -1;
14484 let styleKeyIndex = -1;
14485 let hasDynamicKey = false;
14486 for (let i = 0; i < propsExpression.properties.length; i++) {
14487 const key = propsExpression.properties[i].key;
14488 if (isStaticExp(key)) {
14489 if (key.content === 'class') {
14490 classKeyIndex = i;
14491 }
14492 else if (key.content === 'style') {
14493 styleKeyIndex = i;
14494 }
14495 }
14496 else if (!key.isHandlerKey) {
14497 hasDynamicKey = true;
14498 }
14499 }
14500 const classProp = propsExpression.properties[classKeyIndex];
14501 const styleProp = propsExpression.properties[styleKeyIndex];
14502 // no dynamic key
14503 if (!hasDynamicKey) {
14504 if (classProp && !isStaticExp(classProp.value)) {
14505 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14506 }
14507 if (styleProp &&
14508 !isStaticExp(styleProp.value) &&
14509 // the static style is compiled into an object,
14510 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14511 (hasStyleBinding ||
14512 // v-bind:style and style both exist,
14513 // v-bind:style with static literal object
14514 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14515 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14516 }
14517 }
14518 else {
14519 // dynamic key binding, wrap with `normalizeProps`
14520 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14521 }
14522 break;
14523 case 14 /* JS_CALL_EXPRESSION */:
14524 // mergeProps call, do nothing
14525 break;
14526 default:
14527 // single v-bind
14528 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14529 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14530 propsExpression
14531 ])
14532 ]);
14533 break;
14534 }
14535 }
14536 return {
14537 props: propsExpression,
14538 directives: runtimeDirectives,
14539 patchFlag,
14540 dynamicPropNames,
14541 shouldUseBlock
14542 };
14543 }
14544 // Dedupe props in an object literal.
14545 // Literal duplicated attributes would have been warned during the parse phase,
14546 // however, it's possible to encounter duplicated `onXXX` handlers with different
14547 // modifiers. We also need to merge static and dynamic class / style attributes.
14548 // - onXXX handlers / style: merge into array
14549 // - class: merge into single expression with concatenation
14550 function dedupeProperties(properties) {
14551 const knownProps = new Map();
14552 const deduped = [];
14553 for (let i = 0; i < properties.length; i++) {
14554 const prop = properties[i];
14555 // dynamic keys are always allowed
14556 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14557 deduped.push(prop);
14558 continue;
14559 }
14560 const name = prop.key.content;
14561 const existing = knownProps.get(name);
14562 if (existing) {
14563 if (name === 'style' || name === 'class' || isOn(name)) {
14564 mergeAsArray$1(existing, prop);
14565 }
14566 // unexpected duplicate, should have emitted error during parse
14567 }
14568 else {
14569 knownProps.set(name, prop);
14570 deduped.push(prop);
14571 }
14572 }
14573 return deduped;
14574 }
14575 function mergeAsArray$1(existing, incoming) {
14576 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14577 existing.value.elements.push(incoming.value);
14578 }
14579 else {
14580 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14581 }
14582 }
14583 function buildDirectiveArgs(dir, context) {
14584 const dirArgs = [];
14585 const runtime = directiveImportMap.get(dir);
14586 if (runtime) {
14587 // built-in directive with runtime
14588 dirArgs.push(context.helperString(runtime));
14589 }
14590 else {
14591 {
14592 // inject statement for resolving directive
14593 context.helper(RESOLVE_DIRECTIVE);
14594 context.directives.add(dir.name);
14595 dirArgs.push(toValidAssetId(dir.name, `directive`));
14596 }
14597 }
14598 const { loc } = dir;
14599 if (dir.exp)
14600 dirArgs.push(dir.exp);
14601 if (dir.arg) {
14602 if (!dir.exp) {
14603 dirArgs.push(`void 0`);
14604 }
14605 dirArgs.push(dir.arg);
14606 }
14607 if (Object.keys(dir.modifiers).length) {
14608 if (!dir.arg) {
14609 if (!dir.exp) {
14610 dirArgs.push(`void 0`);
14611 }
14612 dirArgs.push(`void 0`);
14613 }
14614 const trueExpression = createSimpleExpression(`true`, false, loc);
14615 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14616 }
14617 return createArrayExpression(dirArgs, dir.loc);
14618 }
14619 function stringifyDynamicPropNames(props) {
14620 let propsNamesString = `[`;
14621 for (let i = 0, l = props.length; i < l; i++) {
14622 propsNamesString += JSON.stringify(props[i]);
14623 if (i < l - 1)
14624 propsNamesString += ', ';
14625 }
14626 return propsNamesString + `]`;
14627 }
14628 function isComponentTag(tag) {
14629 return tag === 'component' || tag === 'Component';
14630 }
14631
14632 const transformSlotOutlet = (node, context) => {
14633 if (isSlotOutlet(node)) {
14634 const { children, loc } = node;
14635 const { slotName, slotProps } = processSlotOutlet(node, context);
14636 const slotArgs = [
14637 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14638 slotName,
14639 '{}',
14640 'undefined',
14641 'true'
14642 ];
14643 let expectedLen = 2;
14644 if (slotProps) {
14645 slotArgs[2] = slotProps;
14646 expectedLen = 3;
14647 }
14648 if (children.length) {
14649 slotArgs[3] = createFunctionExpression([], children, false, false, loc);
14650 expectedLen = 4;
14651 }
14652 if (context.scopeId && !context.slotted) {
14653 expectedLen = 5;
14654 }
14655 slotArgs.splice(expectedLen); // remove unused arguments
14656 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14657 }
14658 };
14659 function processSlotOutlet(node, context) {
14660 let slotName = `"default"`;
14661 let slotProps = undefined;
14662 const nonNameProps = [];
14663 for (let i = 0; i < node.props.length; i++) {
14664 const p = node.props[i];
14665 if (p.type === 6 /* ATTRIBUTE */) {
14666 if (p.value) {
14667 if (p.name === 'name') {
14668 slotName = JSON.stringify(p.value.content);
14669 }
14670 else {
14671 p.name = camelize(p.name);
14672 nonNameProps.push(p);
14673 }
14674 }
14675 }
14676 else {
14677 if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
14678 if (p.exp)
14679 slotName = p.exp;
14680 }
14681 else {
14682 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14683 p.arg.content = camelize(p.arg.content);
14684 }
14685 nonNameProps.push(p);
14686 }
14687 }
14688 }
14689 if (nonNameProps.length > 0) {
14690 const { props, directives } = buildProps(node, context, nonNameProps);
14691 slotProps = props;
14692 if (directives.length) {
14693 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14694 }
14695 }
14696 return {
14697 slotName,
14698 slotProps
14699 };
14700 }
14701
14702 const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
14703 const transformOn = (dir, node, context, augmentor) => {
14704 const { loc, modifiers, arg } = dir;
14705 if (!dir.exp && !modifiers.length) {
14706 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
14707 }
14708 let eventName;
14709 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14710 if (arg.isStatic) {
14711 let rawName = arg.content;
14712 // TODO deprecate @vnodeXXX usage
14713 if (rawName.startsWith('vue:')) {
14714 rawName = `vnode-${rawName.slice(4)}`;
14715 }
14716 // for all event listeners, auto convert it to camelCase. See issue #2249
14717 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
14718 }
14719 else {
14720 // #2388
14721 eventName = createCompoundExpression([
14722 `${context.helperString(TO_HANDLER_KEY)}(`,
14723 arg,
14724 `)`
14725 ]);
14726 }
14727 }
14728 else {
14729 // already a compound expression.
14730 eventName = arg;
14731 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
14732 eventName.children.push(`)`);
14733 }
14734 // handler processing
14735 let exp = dir.exp;
14736 if (exp && !exp.content.trim()) {
14737 exp = undefined;
14738 }
14739 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
14740 if (exp) {
14741 const isMemberExp = isMemberExpression(exp.content);
14742 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
14743 const hasMultipleStatements = exp.content.includes(`;`);
14744 {
14745 validateBrowserExpression(exp, context, false, hasMultipleStatements);
14746 }
14747 if (isInlineStatement || (shouldCache && isMemberExp)) {
14748 // wrap inline statement in a function expression
14749 exp = createCompoundExpression([
14750 `${isInlineStatement
14751 ? `$event`
14752 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
14753 exp,
14754 hasMultipleStatements ? `}` : `)`
14755 ]);
14756 }
14757 }
14758 let ret = {
14759 props: [
14760 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
14761 ]
14762 };
14763 // apply extended compiler augmentor
14764 if (augmentor) {
14765 ret = augmentor(ret);
14766 }
14767 if (shouldCache) {
14768 // cache handlers so that it's always the same handler being passed down.
14769 // this avoids unnecessary re-renders when users use inline handlers on
14770 // components.
14771 ret.props[0].value = context.cache(ret.props[0].value);
14772 }
14773 // mark the key as handler for props normalization check
14774 ret.props.forEach(p => (p.key.isHandlerKey = true));
14775 return ret;
14776 };
14777
14778 // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
14779 // codegen for the entire props object. This transform here is only for v-bind
14780 // *with* args.
14781 const transformBind = (dir, _node, context) => {
14782 const { exp, modifiers, loc } = dir;
14783 const arg = dir.arg;
14784 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
14785 arg.children.unshift(`(`);
14786 arg.children.push(`) || ""`);
14787 }
14788 else if (!arg.isStatic) {
14789 arg.content = `${arg.content} || ""`;
14790 }
14791 // .sync is replaced by v-model:arg
14792 if (modifiers.includes('camel')) {
14793 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14794 if (arg.isStatic) {
14795 arg.content = camelize(arg.content);
14796 }
14797 else {
14798 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
14799 }
14800 }
14801 else {
14802 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
14803 arg.children.push(`)`);
14804 }
14805 }
14806 if (!context.inSSR) {
14807 if (modifiers.includes('prop')) {
14808 injectPrefix(arg, '.');
14809 }
14810 if (modifiers.includes('attr')) {
14811 injectPrefix(arg, '^');
14812 }
14813 }
14814 if (!exp ||
14815 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
14816 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
14817 return {
14818 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
14819 };
14820 }
14821 return {
14822 props: [createObjectProperty(arg, exp)]
14823 };
14824 };
14825 const injectPrefix = (arg, prefix) => {
14826 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14827 if (arg.isStatic) {
14828 arg.content = prefix + arg.content;
14829 }
14830 else {
14831 arg.content = `\`${prefix}\${${arg.content}}\``;
14832 }
14833 }
14834 else {
14835 arg.children.unshift(`'${prefix}' + (`);
14836 arg.children.push(`)`);
14837 }
14838 };
14839
14840 // Merge adjacent text nodes and expressions into a single expression
14841 // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
14842 const transformText = (node, context) => {
14843 if (node.type === 0 /* ROOT */ ||
14844 node.type === 1 /* ELEMENT */ ||
14845 node.type === 11 /* FOR */ ||
14846 node.type === 10 /* IF_BRANCH */) {
14847 // perform the transform on node exit so that all expressions have already
14848 // been processed.
14849 return () => {
14850 const children = node.children;
14851 let currentContainer = undefined;
14852 let hasText = false;
14853 for (let i = 0; i < children.length; i++) {
14854 const child = children[i];
14855 if (isText(child)) {
14856 hasText = true;
14857 for (let j = i + 1; j < children.length; j++) {
14858 const next = children[j];
14859 if (isText(next)) {
14860 if (!currentContainer) {
14861 currentContainer = children[i] = {
14862 type: 8 /* COMPOUND_EXPRESSION */,
14863 loc: child.loc,
14864 children: [child]
14865 };
14866 }
14867 // merge adjacent text node into current
14868 currentContainer.children.push(` + `, next);
14869 children.splice(j, 1);
14870 j--;
14871 }
14872 else {
14873 currentContainer = undefined;
14874 break;
14875 }
14876 }
14877 }
14878 }
14879 if (!hasText ||
14880 // if this is a plain element with a single text child, leave it
14881 // as-is since the runtime has dedicated fast path for this by directly
14882 // setting textContent of the element.
14883 // for component root it's always normalized anyway.
14884 (children.length === 1 &&
14885 (node.type === 0 /* ROOT */ ||
14886 (node.type === 1 /* ELEMENT */ &&
14887 node.tagType === 0 /* ELEMENT */ &&
14888 // #3756
14889 // custom directives can potentially add DOM elements arbitrarily,
14890 // we need to avoid setting textContent of the element at runtime
14891 // to avoid accidentally overwriting the DOM elements added
14892 // by the user through custom directives.
14893 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
14894 !context.directiveTransforms[p.name]) &&
14895 // in compat mode, <template> tags with no special directives
14896 // will be rendered as a fragment so its children must be
14897 // converted into vnodes.
14898 !(false ))))) {
14899 return;
14900 }
14901 // pre-convert text nodes into createTextVNode(text) calls to avoid
14902 // runtime normalization.
14903 for (let i = 0; i < children.length; i++) {
14904 const child = children[i];
14905 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
14906 const callArgs = [];
14907 // createTextVNode defaults to single whitespace, so if it is a
14908 // single space the code could be an empty call to save bytes.
14909 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
14910 callArgs.push(child);
14911 }
14912 // mark dynamic text with flag so it gets patched inside a block
14913 if (!context.ssr &&
14914 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14915 callArgs.push(1 /* TEXT */ +
14916 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
14917 }
14918 children[i] = {
14919 type: 12 /* TEXT_CALL */,
14920 content: child,
14921 loc: child.loc,
14922 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
14923 };
14924 }
14925 }
14926 };
14927 }
14928 };
14929
14930 const seen = new WeakSet();
14931 const transformOnce = (node, context) => {
14932 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
14933 if (seen.has(node) || context.inVOnce) {
14934 return;
14935 }
14936 seen.add(node);
14937 context.inVOnce = true;
14938 context.helper(SET_BLOCK_TRACKING);
14939 return () => {
14940 context.inVOnce = false;
14941 const cur = context.currentNode;
14942 if (cur.codegenNode) {
14943 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
14944 }
14945 };
14946 }
14947 };
14948
14949 const transformModel = (dir, node, context) => {
14950 const { exp, arg } = dir;
14951 if (!exp) {
14952 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
14953 return createTransformProps();
14954 }
14955 const rawExp = exp.loc.source;
14956 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
14957 // im SFC <script setup> inline mode, the exp may have been transformed into
14958 // _unref(exp)
14959 context.bindingMetadata[rawExp];
14960 const maybeRef = !true /* SETUP_CONST */;
14961 if (!expString.trim() ||
14962 (!isMemberExpression(expString) && !maybeRef)) {
14963 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
14964 return createTransformProps();
14965 }
14966 const propName = arg ? arg : createSimpleExpression('modelValue', true);
14967 const eventName = arg
14968 ? isStaticExp(arg)
14969 ? `onUpdate:${arg.content}`
14970 : createCompoundExpression(['"onUpdate:" + ', arg])
14971 : `onUpdate:modelValue`;
14972 let assignmentExp;
14973 const eventArg = context.isTS ? `($event: any)` : `$event`;
14974 {
14975 assignmentExp = createCompoundExpression([
14976 `${eventArg} => ((`,
14977 exp,
14978 `) = $event)`
14979 ]);
14980 }
14981 const props = [
14982 // modelValue: foo
14983 createObjectProperty(propName, dir.exp),
14984 // "onUpdate:modelValue": $event => (foo = $event)
14985 createObjectProperty(eventName, assignmentExp)
14986 ];
14987 // modelModifiers: { foo: true, "bar-baz": true }
14988 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
14989 const modifiers = dir.modifiers
14990 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
14991 .join(`, `);
14992 const modifiersKey = arg
14993 ? isStaticExp(arg)
14994 ? `${arg.content}Modifiers`
14995 : createCompoundExpression([arg, ' + "Modifiers"'])
14996 : `modelModifiers`;
14997 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
14998 }
14999 return createTransformProps(props);
15000 };
15001 function createTransformProps(props = []) {
15002 return { props };
15003 }
15004
15005 const seen$1 = new WeakSet();
15006 const transformMemo = (node, context) => {
15007 if (node.type === 1 /* ELEMENT */) {
15008 const dir = findDir(node, 'memo');
15009 if (!dir || seen$1.has(node)) {
15010 return;
15011 }
15012 seen$1.add(node);
15013 return () => {
15014 const codegenNode = node.codegenNode ||
15015 context.currentNode.codegenNode;
15016 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15017 // non-component sub tree should be turned into a block
15018 if (node.tagType !== 1 /* COMPONENT */) {
15019 makeBlock(codegenNode, context);
15020 }
15021 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15022 dir.exp,
15023 createFunctionExpression(undefined, codegenNode),
15024 `_cache`,
15025 String(context.cached++)
15026 ]);
15027 }
15028 };
15029 }
15030 };
15031
15032 function getBaseTransformPreset(prefixIdentifiers) {
15033 return [
15034 [
15035 transformOnce,
15036 transformIf,
15037 transformMemo,
15038 transformFor,
15039 ...([]),
15040 ...([transformExpression]
15041 ),
15042 transformSlotOutlet,
15043 transformElement,
15044 trackSlotScopes,
15045 transformText
15046 ],
15047 {
15048 on: transformOn,
15049 bind: transformBind,
15050 model: transformModel
15051 }
15052 ];
15053 }
15054 // we name it `baseCompile` so that higher order compilers like
15055 // @vue/compiler-dom can export `compile` while re-exporting everything else.
15056 function baseCompile(template, options = {}) {
15057 const onError = options.onError || defaultOnError;
15058 const isModuleMode = options.mode === 'module';
15059 /* istanbul ignore if */
15060 {
15061 if (options.prefixIdentifiers === true) {
15062 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15063 }
15064 else if (isModuleMode) {
15065 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15066 }
15067 }
15068 const prefixIdentifiers = !true ;
15069 if (options.cacheHandlers) {
15070 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15071 }
15072 if (options.scopeId && !isModuleMode) {
15073 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15074 }
15075 const ast = isString(template) ? baseParse(template, options) : template;
15076 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15077 transform(ast, extend({}, options, {
15078 prefixIdentifiers,
15079 nodeTransforms: [
15080 ...nodeTransforms,
15081 ...(options.nodeTransforms || []) // user transforms
15082 ],
15083 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15084 )
15085 }));
15086 return generate(ast, extend({}, options, {
15087 prefixIdentifiers
15088 }));
15089 }
15090
15091 const noopDirectiveTransform = () => ({ props: [] });
15092
15093 const V_MODEL_RADIO = Symbol(`vModelRadio` );
15094 const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15095 const V_MODEL_TEXT = Symbol(`vModelText` );
15096 const V_MODEL_SELECT = Symbol(`vModelSelect` );
15097 const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15098 const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15099 const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15100 const V_SHOW = Symbol(`vShow` );
15101 const TRANSITION$1 = Symbol(`Transition` );
15102 const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15103 registerRuntimeHelpers({
15104 [V_MODEL_RADIO]: `vModelRadio`,
15105 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15106 [V_MODEL_TEXT]: `vModelText`,
15107 [V_MODEL_SELECT]: `vModelSelect`,
15108 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15109 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15110 [V_ON_WITH_KEYS]: `withKeys`,
15111 [V_SHOW]: `vShow`,
15112 [TRANSITION$1]: `Transition`,
15113 [TRANSITION_GROUP]: `TransitionGroup`
15114 });
15115
15116 /* eslint-disable no-restricted-globals */
15117 let decoder;
15118 function decodeHtmlBrowser(raw, asAttr = false) {
15119 if (!decoder) {
15120 decoder = document.createElement('div');
15121 }
15122 if (asAttr) {
15123 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15124 return decoder.children[0].getAttribute('foo');
15125 }
15126 else {
15127 decoder.innerHTML = raw;
15128 return decoder.textContent;
15129 }
15130 }
15131
15132 const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15133 const parserOptions = {
15134 isVoidTag,
15135 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15136 isPreTag: tag => tag === 'pre',
15137 decodeEntities: decodeHtmlBrowser ,
15138 isBuiltInComponent: (tag) => {
15139 if (isBuiltInType(tag, `Transition`)) {
15140 return TRANSITION$1;
15141 }
15142 else if (isBuiltInType(tag, `TransitionGroup`)) {
15143 return TRANSITION_GROUP;
15144 }
15145 },
15146 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15147 getNamespace(tag, parent) {
15148 let ns = parent ? parent.ns : 0 /* HTML */;
15149 if (parent && ns === 2 /* MATH_ML */) {
15150 if (parent.tag === 'annotation-xml') {
15151 if (tag === 'svg') {
15152 return 1 /* SVG */;
15153 }
15154 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15155 a.name === 'encoding' &&
15156 a.value != null &&
15157 (a.value.content === 'text/html' ||
15158 a.value.content === 'application/xhtml+xml'))) {
15159 ns = 0 /* HTML */;
15160 }
15161 }
15162 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15163 tag !== 'mglyph' &&
15164 tag !== 'malignmark') {
15165 ns = 0 /* HTML */;
15166 }
15167 }
15168 else if (parent && ns === 1 /* SVG */) {
15169 if (parent.tag === 'foreignObject' ||
15170 parent.tag === 'desc' ||
15171 parent.tag === 'title') {
15172 ns = 0 /* HTML */;
15173 }
15174 }
15175 if (ns === 0 /* HTML */) {
15176 if (tag === 'svg') {
15177 return 1 /* SVG */;
15178 }
15179 if (tag === 'math') {
15180 return 2 /* MATH_ML */;
15181 }
15182 }
15183 return ns;
15184 },
15185 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15186 getTextMode({ tag, ns }) {
15187 if (ns === 0 /* HTML */) {
15188 if (tag === 'textarea' || tag === 'title') {
15189 return 1 /* RCDATA */;
15190 }
15191 if (isRawTextContainer(tag)) {
15192 return 2 /* RAWTEXT */;
15193 }
15194 }
15195 return 0 /* DATA */;
15196 }
15197 };
15198
15199 // Parse inline CSS strings for static style attributes into an object.
15200 // This is a NodeTransform since it works on the static `style` attribute and
15201 // converts it into a dynamic equivalent:
15202 // style="color: red" -> :style='{ "color": "red" }'
15203 // It is then processed by `transformElement` and included in the generated
15204 // props.
15205 const transformStyle = node => {
15206 if (node.type === 1 /* ELEMENT */) {
15207 node.props.forEach((p, i) => {
15208 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15209 // replace p with an expression node
15210 node.props[i] = {
15211 type: 7 /* DIRECTIVE */,
15212 name: `bind`,
15213 arg: createSimpleExpression(`style`, true, p.loc),
15214 exp: parseInlineCSS(p.value.content, p.loc),
15215 modifiers: [],
15216 loc: p.loc
15217 };
15218 }
15219 });
15220 }
15221 };
15222 const parseInlineCSS = (cssText, loc) => {
15223 const normalized = parseStringStyle(cssText);
15224 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15225 };
15226
15227 function createDOMCompilerError(code, loc) {
15228 return createCompilerError(code, loc, DOMErrorMessages );
15229 }
15230 const DOMErrorMessages = {
15231 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15232 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15233 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15234 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15235 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15236 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15237 [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.`,
15238 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15239 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15240 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15241 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15242 };
15243
15244 const transformVHtml = (dir, node, context) => {
15245 const { exp, loc } = dir;
15246 if (!exp) {
15247 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15248 }
15249 if (node.children.length) {
15250 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15251 node.children.length = 0;
15252 }
15253 return {
15254 props: [
15255 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15256 ]
15257 };
15258 };
15259
15260 const transformVText = (dir, node, context) => {
15261 const { exp, loc } = dir;
15262 if (!exp) {
15263 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15264 }
15265 if (node.children.length) {
15266 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15267 node.children.length = 0;
15268 }
15269 return {
15270 props: [
15271 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15272 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15273 : createSimpleExpression('', true))
15274 ]
15275 };
15276 };
15277
15278 const transformModel$1 = (dir, node, context) => {
15279 const baseResult = transformModel(dir, node, context);
15280 // base transform has errors OR component v-model (only need props)
15281 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15282 return baseResult;
15283 }
15284 if (dir.arg) {
15285 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15286 }
15287 function checkDuplicatedValue() {
15288 const value = findProp(node, 'value');
15289 if (value) {
15290 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15291 }
15292 }
15293 const { tag } = node;
15294 const isCustomElement = context.isCustomElement(tag);
15295 if (tag === 'input' ||
15296 tag === 'textarea' ||
15297 tag === 'select' ||
15298 isCustomElement) {
15299 let directiveToUse = V_MODEL_TEXT;
15300 let isInvalidType = false;
15301 if (tag === 'input' || isCustomElement) {
15302 const type = findProp(node, `type`);
15303 if (type) {
15304 if (type.type === 7 /* DIRECTIVE */) {
15305 // :type="foo"
15306 directiveToUse = V_MODEL_DYNAMIC;
15307 }
15308 else if (type.value) {
15309 switch (type.value.content) {
15310 case 'radio':
15311 directiveToUse = V_MODEL_RADIO;
15312 break;
15313 case 'checkbox':
15314 directiveToUse = V_MODEL_CHECKBOX;
15315 break;
15316 case 'file':
15317 isInvalidType = true;
15318 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15319 break;
15320 default:
15321 // text type
15322 checkDuplicatedValue();
15323 break;
15324 }
15325 }
15326 }
15327 else if (hasDynamicKeyVBind(node)) {
15328 // element has bindings with dynamic keys, which can possibly contain
15329 // "type".
15330 directiveToUse = V_MODEL_DYNAMIC;
15331 }
15332 else {
15333 // text type
15334 checkDuplicatedValue();
15335 }
15336 }
15337 else if (tag === 'select') {
15338 directiveToUse = V_MODEL_SELECT;
15339 }
15340 else {
15341 // textarea
15342 checkDuplicatedValue();
15343 }
15344 // inject runtime directive
15345 // by returning the helper symbol via needRuntime
15346 // the import will replaced a resolveDirective call.
15347 if (!isInvalidType) {
15348 baseResult.needRuntime = context.helper(directiveToUse);
15349 }
15350 }
15351 else {
15352 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15353 }
15354 // native vmodel doesn't need the `modelValue` props since they are also
15355 // passed to the runtime as `binding.value`. removing it reduces code size.
15356 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15357 p.key.content === 'modelValue'));
15358 return baseResult;
15359 };
15360
15361 const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15362 const isNonKeyModifier = /*#__PURE__*/ makeMap(
15363 // event propagation management
15364`stop,prevent,self,` +
15365 // system modifiers + exact
15366 `ctrl,shift,alt,meta,exact,` +
15367 // mouse
15368 `middle`);
15369 // left & right could be mouse or key modifiers based on event type
15370 const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15371 const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15372 const resolveModifiers = (key, modifiers, context, loc) => {
15373 const keyModifiers = [];
15374 const nonKeyModifiers = [];
15375 const eventOptionModifiers = [];
15376 for (let i = 0; i < modifiers.length; i++) {
15377 const modifier = modifiers[i];
15378 if (isEventOptionModifier(modifier)) {
15379 // eventOptionModifiers: modifiers for addEventListener() options,
15380 // e.g. .passive & .capture
15381 eventOptionModifiers.push(modifier);
15382 }
15383 else {
15384 // runtimeModifiers: modifiers that needs runtime guards
15385 if (maybeKeyModifier(modifier)) {
15386 if (isStaticExp(key)) {
15387 if (isKeyboardEvent(key.content)) {
15388 keyModifiers.push(modifier);
15389 }
15390 else {
15391 nonKeyModifiers.push(modifier);
15392 }
15393 }
15394 else {
15395 keyModifiers.push(modifier);
15396 nonKeyModifiers.push(modifier);
15397 }
15398 }
15399 else {
15400 if (isNonKeyModifier(modifier)) {
15401 nonKeyModifiers.push(modifier);
15402 }
15403 else {
15404 keyModifiers.push(modifier);
15405 }
15406 }
15407 }
15408 }
15409 return {
15410 keyModifiers,
15411 nonKeyModifiers,
15412 eventOptionModifiers
15413 };
15414 };
15415 const transformClick = (key, event) => {
15416 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15417 return isStaticClick
15418 ? createSimpleExpression(event, true)
15419 : key.type !== 4 /* SIMPLE_EXPRESSION */
15420 ? createCompoundExpression([
15421 `(`,
15422 key,
15423 `) === "onClick" ? "${event}" : (`,
15424 key,
15425 `)`
15426 ])
15427 : key;
15428 };
15429 const transformOn$1 = (dir, node, context) => {
15430 return transformOn(dir, node, context, baseResult => {
15431 const { modifiers } = dir;
15432 if (!modifiers.length)
15433 return baseResult;
15434 let { key, value: handlerExp } = baseResult.props[0];
15435 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15436 // normalize click.right and click.middle since they don't actually fire
15437 if (nonKeyModifiers.includes('right')) {
15438 key = transformClick(key, `onContextmenu`);
15439 }
15440 if (nonKeyModifiers.includes('middle')) {
15441 key = transformClick(key, `onMouseup`);
15442 }
15443 if (nonKeyModifiers.length) {
15444 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15445 handlerExp,
15446 JSON.stringify(nonKeyModifiers)
15447 ]);
15448 }
15449 if (keyModifiers.length &&
15450 // if event name is dynamic, always wrap with keys guard
15451 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15452 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15453 handlerExp,
15454 JSON.stringify(keyModifiers)
15455 ]);
15456 }
15457 if (eventOptionModifiers.length) {
15458 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15459 key = isStaticExp(key)
15460 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15461 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15462 }
15463 return {
15464 props: [createObjectProperty(key, handlerExp)]
15465 };
15466 });
15467 };
15468
15469 const transformShow = (dir, node, context) => {
15470 const { exp, loc } = dir;
15471 if (!exp) {
15472 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15473 }
15474 return {
15475 props: [],
15476 needRuntime: context.helper(V_SHOW)
15477 };
15478 };
15479
15480 const warnTransitionChildren = (node, context) => {
15481 if (node.type === 1 /* ELEMENT */ &&
15482 node.tagType === 1 /* COMPONENT */) {
15483 const component = context.isBuiltInComponent(node.tag);
15484 if (component === TRANSITION$1) {
15485 return () => {
15486 if (node.children.length && hasMultipleChildren(node)) {
15487 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15488 start: node.children[0].loc.start,
15489 end: node.children[node.children.length - 1].loc.end,
15490 source: ''
15491 }));
15492 }
15493 };
15494 }
15495 }
15496 };
15497 function hasMultipleChildren(node) {
15498 // #1352 filter out potential comment nodes.
15499 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
15500 !(c.type === 2 /* TEXT */ && !c.content.trim())));
15501 const child = children[0];
15502 return (children.length !== 1 ||
15503 child.type === 11 /* FOR */ ||
15504 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15505 }
15506
15507 const ignoreSideEffectTags = (node, context) => {
15508 if (node.type === 1 /* ELEMENT */ &&
15509 node.tagType === 0 /* ELEMENT */ &&
15510 (node.tag === 'script' || node.tag === 'style')) {
15511 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15512 context.removeNode();
15513 }
15514 };
15515
15516 const DOMNodeTransforms = [
15517 transformStyle,
15518 ...([warnTransitionChildren] )
15519 ];
15520 const DOMDirectiveTransforms = {
15521 cloak: noopDirectiveTransform,
15522 html: transformVHtml,
15523 text: transformVText,
15524 model: transformModel$1,
15525 on: transformOn$1,
15526 show: transformShow
15527 };
15528 function compile$1(template, options = {}) {
15529 return baseCompile(template, extend({}, parserOptions, options, {
15530 nodeTransforms: [
15531 // ignore <script> and <tag>
15532 // this is not put inside DOMNodeTransforms because that list is used
15533 // by compiler-ssr to generate vnode fallback branches
15534 ignoreSideEffectTags,
15535 ...DOMNodeTransforms,
15536 ...(options.nodeTransforms || [])
15537 ],
15538 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15539 transformHoist: null
15540 }));
15541 }
15542
15543 // This entry is the "full-build" that includes both the runtime
15544 {
15545 initDev();
15546 }
15547 const compileCache = Object.create(null);
15548 function compileToFunction(template, options) {
15549 if (!isString(template)) {
15550 if (template.nodeType) {
15551 template = template.innerHTML;
15552 }
15553 else {
15554 warn$1(`invalid template option: `, template);
15555 return NOOP;
15556 }
15557 }
15558 const key = template;
15559 const cached = compileCache[key];
15560 if (cached) {
15561 return cached;
15562 }
15563 if (template[0] === '#') {
15564 const el = document.querySelector(template);
15565 if (!el) {
15566 warn$1(`Template element not found or is empty: ${template}`);
15567 }
15568 // __UNSAFE__
15569 // Reason: potential execution of JS expressions in in-DOM template.
15570 // The user must make sure the in-DOM template is trusted. If it's rendered
15571 // by the server, the template should not contain any user data.
15572 template = el ? el.innerHTML : ``;
15573 }
15574 const { code } = compile$1(template, extend({
15575 hoistStatic: true,
15576 onError: onError ,
15577 onWarn: e => onError(e, true)
15578 }, options));
15579 function onError(err, asWarning = false) {
15580 const message = asWarning
15581 ? err.message
15582 : `Template compilation error: ${err.message}`;
15583 const codeFrame = err.loc &&
15584 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15585 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15586 }
15587 // The wildcard import results in a huge object with every export
15588 // with keys that cannot be mangled, and can be quite heavy size-wise.
15589 // In the global build we know `Vue` is available globally so we can avoid
15590 // the wildcard object.
15591 const render = (new Function(code)() );
15592 render._rc = true;
15593 return (compileCache[key] = render);
15594 }
15595 registerRuntimeCompiler(compileToFunction);
15596
15597 exports.BaseTransition = BaseTransition;
15598 exports.Comment = Comment;
15599 exports.EffectScope = EffectScope;
15600 exports.Fragment = Fragment;
15601 exports.KeepAlive = KeepAlive;
15602 exports.ReactiveEffect = ReactiveEffect;
15603 exports.Static = Static;
15604 exports.Suspense = Suspense;
15605 exports.Teleport = Teleport;
15606 exports.Text = Text;
15607 exports.Transition = Transition;
15608 exports.TransitionGroup = TransitionGroup;
15609 exports.VueElement = VueElement;
15610 exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
15611 exports.callWithErrorHandling = callWithErrorHandling;
15612 exports.camelize = camelize;
15613 exports.capitalize = capitalize;
15614 exports.cloneVNode = cloneVNode;
15615 exports.compatUtils = compatUtils;
15616 exports.compile = compileToFunction;
15617 exports.computed = computed$1;
15618 exports.createApp = createApp;
15619 exports.createBlock = createBlock;
15620 exports.createCommentVNode = createCommentVNode;
15621 exports.createElementBlock = createElementBlock;
15622 exports.createElementVNode = createBaseVNode;
15623 exports.createHydrationRenderer = createHydrationRenderer;
15624 exports.createPropsRestProxy = createPropsRestProxy;
15625 exports.createRenderer = createRenderer;
15626 exports.createSSRApp = createSSRApp;
15627 exports.createSlots = createSlots;
15628 exports.createStaticVNode = createStaticVNode;
15629 exports.createTextVNode = createTextVNode;
15630 exports.createVNode = createVNode;
15631 exports.customRef = customRef;
15632 exports.defineAsyncComponent = defineAsyncComponent;
15633 exports.defineComponent = defineComponent;
15634 exports.defineCustomElement = defineCustomElement;
15635 exports.defineEmits = defineEmits;
15636 exports.defineExpose = defineExpose;
15637 exports.defineProps = defineProps;
15638 exports.defineSSRCustomElement = defineSSRCustomElement;
15639 exports.effect = effect;
15640 exports.effectScope = effectScope;
15641 exports.getCurrentInstance = getCurrentInstance;
15642 exports.getCurrentScope = getCurrentScope;
15643 exports.getTransitionRawChildren = getTransitionRawChildren;
15644 exports.guardReactiveProps = guardReactiveProps;
15645 exports.h = h;
15646 exports.handleError = handleError;
15647 exports.hydrate = hydrate;
15648 exports.initCustomFormatter = initCustomFormatter;
15649 exports.initDirectivesForSSR = initDirectivesForSSR;
15650 exports.inject = inject;
15651 exports.isMemoSame = isMemoSame;
15652 exports.isProxy = isProxy;
15653 exports.isReactive = isReactive;
15654 exports.isReadonly = isReadonly;
15655 exports.isRef = isRef;
15656 exports.isRuntimeOnly = isRuntimeOnly;
15657 exports.isShallow = isShallow;
15658 exports.isVNode = isVNode;
15659 exports.markRaw = markRaw;
15660 exports.mergeDefaults = mergeDefaults;
15661 exports.mergeProps = mergeProps;
15662 exports.nextTick = nextTick;
15663 exports.normalizeClass = normalizeClass;
15664 exports.normalizeProps = normalizeProps;
15665 exports.normalizeStyle = normalizeStyle;
15666 exports.onActivated = onActivated;
15667 exports.onBeforeMount = onBeforeMount;
15668 exports.onBeforeUnmount = onBeforeUnmount;
15669 exports.onBeforeUpdate = onBeforeUpdate;
15670 exports.onDeactivated = onDeactivated;
15671 exports.onErrorCaptured = onErrorCaptured;
15672 exports.onMounted = onMounted;
15673 exports.onRenderTracked = onRenderTracked;
15674 exports.onRenderTriggered = onRenderTriggered;
15675 exports.onScopeDispose = onScopeDispose;
15676 exports.onServerPrefetch = onServerPrefetch;
15677 exports.onUnmounted = onUnmounted;
15678 exports.onUpdated = onUpdated;
15679 exports.openBlock = openBlock;
15680 exports.popScopeId = popScopeId;
15681 exports.provide = provide;
15682 exports.proxyRefs = proxyRefs;
15683 exports.pushScopeId = pushScopeId;
15684 exports.queuePostFlushCb = queuePostFlushCb;
15685 exports.reactive = reactive;
15686 exports.readonly = readonly;
15687 exports.ref = ref;
15688 exports.registerRuntimeCompiler = registerRuntimeCompiler;
15689 exports.render = render;
15690 exports.renderList = renderList;
15691 exports.renderSlot = renderSlot;
15692 exports.resolveComponent = resolveComponent;
15693 exports.resolveDirective = resolveDirective;
15694 exports.resolveDynamicComponent = resolveDynamicComponent;
15695 exports.resolveFilter = resolveFilter;
15696 exports.resolveTransitionHooks = resolveTransitionHooks;
15697 exports.setBlockTracking = setBlockTracking;
15698 exports.setDevtoolsHook = setDevtoolsHook;
15699 exports.setTransitionHooks = setTransitionHooks;
15700 exports.shallowReactive = shallowReactive;
15701 exports.shallowReadonly = shallowReadonly;
15702 exports.shallowRef = shallowRef;
15703 exports.ssrContextKey = ssrContextKey;
15704 exports.ssrUtils = ssrUtils;
15705 exports.stop = stop;
15706 exports.toDisplayString = toDisplayString;
15707 exports.toHandlerKey = toHandlerKey;
15708 exports.toHandlers = toHandlers;
15709 exports.toRaw = toRaw;
15710 exports.toRef = toRef;
15711 exports.toRefs = toRefs;
15712 exports.transformVNodeArgs = transformVNodeArgs;
15713 exports.triggerRef = triggerRef;
15714 exports.unref = unref;
15715 exports.useAttrs = useAttrs;
15716 exports.useCssModule = useCssModule;
15717 exports.useCssVars = useCssVars;
15718 exports.useSSRContext = useSSRContext;
15719 exports.useSlots = useSlots;
15720 exports.useTransitionState = useTransitionState;
15721 exports.vModelCheckbox = vModelCheckbox;
15722 exports.vModelDynamic = vModelDynamic;
15723 exports.vModelRadio = vModelRadio;
15724 exports.vModelSelect = vModelSelect;
15725 exports.vModelText = vModelText;
15726 exports.vShow = vShow;
15727 exports.version = version;
15728 exports.warn = warn$1;
15729 exports.watch = watch;
15730 exports.watchEffect = watchEffect;
15731 exports.watchPostEffect = watchPostEffect;
15732 exports.watchSyncEffect = watchSyncEffect;
15733 exports.withAsyncContext = withAsyncContext;
15734 exports.withCtx = withCtx;
15735 exports.withDefaults = withDefaults;
15736 exports.withDirectives = withDirectives;
15737 exports.withKeys = withKeys;
15738 exports.withMemo = withMemo;
15739 exports.withModifiers = withModifiers;
15740 exports.withScopeId = withScopeId;
15741
15742 Object.defineProperty(exports, '__esModule', { value: true });
15743
15744 return exports;
15745
15746}({}));