UNPKG

612 kBJavaScriptView Raw
1/**
2 * Make a map and return a function for checking if a key
3 * is in that map.
4 * IMPORTANT: all calls of this function must be prefixed with
5 * \/\*#\_\_PURE\_\_\*\/
6 * So that rollup can tree-shake them if necessary.
7 */
8function makeMap(str, expectsLowerCase) {
9 const map = Object.create(null);
10 const list = str.split(',');
11 for (let i = 0; i < list.length; i++) {
12 map[list[i]] = true;
13 }
14 return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
15}
16
17/**
18 * dev only flag -> name mapping
19 */
20const PatchFlagNames = {
21 [1 /* TEXT */]: `TEXT`,
22 [2 /* CLASS */]: `CLASS`,
23 [4 /* STYLE */]: `STYLE`,
24 [8 /* PROPS */]: `PROPS`,
25 [16 /* FULL_PROPS */]: `FULL_PROPS`,
26 [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
27 [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
28 [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
29 [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
30 [512 /* NEED_PATCH */]: `NEED_PATCH`,
31 [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
32 [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
33 [-1 /* HOISTED */]: `HOISTED`,
34 [-2 /* BAIL */]: `BAIL`
35};
36
37/**
38 * Dev only
39 */
40const slotFlagsText = {
41 [1 /* STABLE */]: 'STABLE',
42 [2 /* DYNAMIC */]: 'DYNAMIC',
43 [3 /* FORWARDED */]: 'FORWARDED'
44};
45
46const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
47 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
48 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
49const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
50
51const range = 2;
52function generateCodeFrame(source, start = 0, end = source.length) {
53 // Split the content into individual lines but capture the newline sequence
54 // that separated each line. This is important because the actual sequence is
55 // needed to properly take into account the full line length for offset
56 // comparison
57 let lines = source.split(/(\r?\n)/);
58 // Separate the lines and newline sequences into separate arrays for easier referencing
59 const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
60 lines = lines.filter((_, idx) => idx % 2 === 0);
61 let count = 0;
62 const res = [];
63 for (let i = 0; i < lines.length; i++) {
64 count +=
65 lines[i].length +
66 ((newlineSequences[i] && newlineSequences[i].length) || 0);
67 if (count >= start) {
68 for (let j = i - range; j <= i + range || end > count; j++) {
69 if (j < 0 || j >= lines.length)
70 continue;
71 const line = j + 1;
72 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
73 const lineLength = lines[j].length;
74 const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
75 if (j === i) {
76 // push underline
77 const pad = start - (count - (lineLength + newLineSeqLength));
78 const length = Math.max(1, end > count ? lineLength - pad : end - start);
79 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
80 }
81 else if (j > i) {
82 if (end > count) {
83 const length = Math.max(Math.min(end - count, lineLength), 1);
84 res.push(` | ` + '^'.repeat(length));
85 }
86 count += lineLength + newLineSeqLength;
87 }
88 }
89 break;
90 }
91 }
92 return res.join('\n');
93}
94
95/**
96 * On the client we only need to offer special cases for boolean attributes that
97 * have different names from their corresponding dom properties:
98 * - itemscope -> N/A
99 * - allowfullscreen -> allowFullscreen
100 * - formnovalidate -> formNoValidate
101 * - ismap -> isMap
102 * - nomodule -> noModule
103 * - novalidate -> noValidate
104 * - readonly -> readOnly
105 */
106const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
107const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
108/**
109 * Boolean attributes should be included if the value is truthy or ''.
110 * e.g. <select multiple> compiles to { multiple: '' }
111 */
112function includeBooleanAttr(value) {
113 return !!value || value === '';
114}
115
116function normalizeStyle(value) {
117 if (isArray(value)) {
118 const res = {};
119 for (let i = 0; i < value.length; i++) {
120 const item = value[i];
121 const normalized = isString(item)
122 ? parseStringStyle(item)
123 : normalizeStyle(item);
124 if (normalized) {
125 for (const key in normalized) {
126 res[key] = normalized[key];
127 }
128 }
129 }
130 return res;
131 }
132 else if (isString(value)) {
133 return value;
134 }
135 else if (isObject(value)) {
136 return value;
137 }
138}
139const listDelimiterRE = /;(?![^(]*\))/g;
140const propertyDelimiterRE = /:(.+)/;
141function parseStringStyle(cssText) {
142 const ret = {};
143 cssText.split(listDelimiterRE).forEach(item => {
144 if (item) {
145 const tmp = item.split(propertyDelimiterRE);
146 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
147 }
148 });
149 return ret;
150}
151function normalizeClass(value) {
152 let res = '';
153 if (isString(value)) {
154 res = value;
155 }
156 else if (isArray(value)) {
157 for (let i = 0; i < value.length; i++) {
158 const normalized = normalizeClass(value[i]);
159 if (normalized) {
160 res += normalized + ' ';
161 }
162 }
163 }
164 else if (isObject(value)) {
165 for (const name in value) {
166 if (value[name]) {
167 res += name + ' ';
168 }
169 }
170 }
171 return res.trim();
172}
173function normalizeProps(props) {
174 if (!props)
175 return null;
176 let { class: klass, style } = props;
177 if (klass && !isString(klass)) {
178 props.class = normalizeClass(klass);
179 }
180 if (style) {
181 props.style = normalizeStyle(style);
182 }
183 return props;
184}
185
186// These tag configs are shared between compiler-dom and runtime-dom, so they
187// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
188const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
189 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
190 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
191 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
192 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
193 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
194 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
195 'option,output,progress,select,textarea,details,dialog,menu,' +
196 'summary,template,blockquote,iframe,tfoot';
197// https://developer.mozilla.org/en-US/docs/Web/SVG/Element
198const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
199 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
200 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
201 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
202 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
203 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
204 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
205 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
206 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
207 'text,textPath,title,tspan,unknown,use,view';
208const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
209const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
210const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
211const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
212
213function looseCompareArrays(a, b) {
214 if (a.length !== b.length)
215 return false;
216 let equal = true;
217 for (let i = 0; equal && i < a.length; i++) {
218 equal = looseEqual(a[i], b[i]);
219 }
220 return equal;
221}
222function looseEqual(a, b) {
223 if (a === b)
224 return true;
225 let aValidType = isDate(a);
226 let bValidType = isDate(b);
227 if (aValidType || bValidType) {
228 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
229 }
230 aValidType = isArray(a);
231 bValidType = isArray(b);
232 if (aValidType || bValidType) {
233 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
234 }
235 aValidType = isObject(a);
236 bValidType = isObject(b);
237 if (aValidType || bValidType) {
238 /* istanbul ignore if: this if will probably never be called */
239 if (!aValidType || !bValidType) {
240 return false;
241 }
242 const aKeysCount = Object.keys(a).length;
243 const bKeysCount = Object.keys(b).length;
244 if (aKeysCount !== bKeysCount) {
245 return false;
246 }
247 for (const key in a) {
248 const aHasKey = a.hasOwnProperty(key);
249 const bHasKey = b.hasOwnProperty(key);
250 if ((aHasKey && !bHasKey) ||
251 (!aHasKey && bHasKey) ||
252 !looseEqual(a[key], b[key])) {
253 return false;
254 }
255 }
256 }
257 return String(a) === String(b);
258}
259function looseIndexOf(arr, val) {
260 return arr.findIndex(item => looseEqual(item, val));
261}
262
263/**
264 * For converting {{ interpolation }} values to displayed strings.
265 * @private
266 */
267const toDisplayString = (val) => {
268 return val == null
269 ? ''
270 : isArray(val) ||
271 (isObject(val) &&
272 (val.toString === objectToString || !isFunction(val.toString)))
273 ? JSON.stringify(val, replacer, 2)
274 : String(val);
275};
276const replacer = (_key, val) => {
277 // can't use isRef here since @vue/shared has no deps
278 if (val && val.__v_isRef) {
279 return replacer(_key, val.value);
280 }
281 else if (isMap(val)) {
282 return {
283 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
284 entries[`${key} =>`] = val;
285 return entries;
286 }, {})
287 };
288 }
289 else if (isSet(val)) {
290 return {
291 [`Set(${val.size})`]: [...val.values()]
292 };
293 }
294 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
295 return String(val);
296 }
297 return val;
298};
299
300const EMPTY_OBJ = Object.freeze({})
301 ;
302const EMPTY_ARR = Object.freeze([]) ;
303const NOOP = () => { };
304/**
305 * Always return false.
306 */
307const NO = () => false;
308const onRE = /^on[^a-z]/;
309const isOn = (key) => onRE.test(key);
310const isModelListener = (key) => key.startsWith('onUpdate:');
311const extend = Object.assign;
312const remove = (arr, el) => {
313 const i = arr.indexOf(el);
314 if (i > -1) {
315 arr.splice(i, 1);
316 }
317};
318const hasOwnProperty = Object.prototype.hasOwnProperty;
319const hasOwn = (val, key) => hasOwnProperty.call(val, key);
320const isArray = Array.isArray;
321const isMap = (val) => toTypeString(val) === '[object Map]';
322const isSet = (val) => toTypeString(val) === '[object Set]';
323const isDate = (val) => val instanceof Date;
324const isFunction = (val) => typeof val === 'function';
325const isString = (val) => typeof val === 'string';
326const isSymbol = (val) => typeof val === 'symbol';
327const isObject = (val) => val !== null && typeof val === 'object';
328const isPromise = (val) => {
329 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
330};
331const objectToString = Object.prototype.toString;
332const toTypeString = (value) => objectToString.call(value);
333const toRawType = (value) => {
334 // extract "RawType" from strings like "[object RawType]"
335 return toTypeString(value).slice(8, -1);
336};
337const isPlainObject = (val) => toTypeString(val) === '[object Object]';
338const isIntegerKey = (key) => isString(key) &&
339 key !== 'NaN' &&
340 key[0] !== '-' &&
341 '' + parseInt(key, 10) === key;
342const isReservedProp = /*#__PURE__*/ makeMap(
343// the leading comma is intentional so empty string "" is also included
344',key,ref,' +
345 'onVnodeBeforeMount,onVnodeMounted,' +
346 'onVnodeBeforeUpdate,onVnodeUpdated,' +
347 'onVnodeBeforeUnmount,onVnodeUnmounted');
348const cacheStringFunction = (fn) => {
349 const cache = Object.create(null);
350 return ((str) => {
351 const hit = cache[str];
352 return hit || (cache[str] = fn(str));
353 });
354};
355const camelizeRE = /-(\w)/g;
356/**
357 * @private
358 */
359const camelize = cacheStringFunction((str) => {
360 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
361});
362const hyphenateRE = /\B([A-Z])/g;
363/**
364 * @private
365 */
366const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
367/**
368 * @private
369 */
370const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
371/**
372 * @private
373 */
374const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
375// compare whether a value has changed, accounting for NaN.
376const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
377const invokeArrayFns = (fns, arg) => {
378 for (let i = 0; i < fns.length; i++) {
379 fns[i](arg);
380 }
381};
382const def = (obj, key, value) => {
383 Object.defineProperty(obj, key, {
384 configurable: true,
385 enumerable: false,
386 value
387 });
388};
389const toNumber = (val) => {
390 const n = parseFloat(val);
391 return isNaN(n) ? val : n;
392};
393let _globalThis;
394const getGlobalThis = () => {
395 return (_globalThis ||
396 (_globalThis =
397 typeof globalThis !== 'undefined'
398 ? globalThis
399 : typeof self !== 'undefined'
400 ? self
401 : typeof window !== 'undefined'
402 ? window
403 : typeof global !== 'undefined'
404 ? global
405 : {}));
406};
407
408function warn(msg, ...args) {
409 console.warn(`[Vue warn] ${msg}`, ...args);
410}
411
412let activeEffectScope;
413const effectScopeStack = [];
414class EffectScope {
415 constructor(detached = false) {
416 this.active = true;
417 this.effects = [];
418 this.cleanups = [];
419 if (!detached && activeEffectScope) {
420 this.parent = activeEffectScope;
421 this.index =
422 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
423 }
424 }
425 run(fn) {
426 if (this.active) {
427 try {
428 this.on();
429 return fn();
430 }
431 finally {
432 this.off();
433 }
434 }
435 else {
436 warn(`cannot run an inactive effect scope.`);
437 }
438 }
439 on() {
440 if (this.active) {
441 effectScopeStack.push(this);
442 activeEffectScope = this;
443 }
444 }
445 off() {
446 if (this.active) {
447 effectScopeStack.pop();
448 activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
449 }
450 }
451 stop(fromParent) {
452 if (this.active) {
453 this.effects.forEach(e => e.stop());
454 this.cleanups.forEach(cleanup => cleanup());
455 if (this.scopes) {
456 this.scopes.forEach(e => e.stop(true));
457 }
458 // nested scope, dereference from parent to avoid memory leaks
459 if (this.parent && !fromParent) {
460 // optimized O(1) removal
461 const last = this.parent.scopes.pop();
462 if (last && last !== this) {
463 this.parent.scopes[this.index] = last;
464 last.index = this.index;
465 }
466 }
467 this.active = false;
468 }
469 }
470}
471function effectScope(detached) {
472 return new EffectScope(detached);
473}
474function recordEffectScope(effect, scope) {
475 scope = scope || activeEffectScope;
476 if (scope && scope.active) {
477 scope.effects.push(effect);
478 }
479}
480function getCurrentScope() {
481 return activeEffectScope;
482}
483function onScopeDispose(fn) {
484 if (activeEffectScope) {
485 activeEffectScope.cleanups.push(fn);
486 }
487 else {
488 warn(`onScopeDispose() is called when there is no active effect scope` +
489 ` to be associated with.`);
490 }
491}
492
493const createDep = (effects) => {
494 const dep = new Set(effects);
495 dep.w = 0;
496 dep.n = 0;
497 return dep;
498};
499const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
500const newTracked = (dep) => (dep.n & trackOpBit) > 0;
501const initDepMarkers = ({ deps }) => {
502 if (deps.length) {
503 for (let i = 0; i < deps.length; i++) {
504 deps[i].w |= trackOpBit; // set was tracked
505 }
506 }
507};
508const finalizeDepMarkers = (effect) => {
509 const { deps } = effect;
510 if (deps.length) {
511 let ptr = 0;
512 for (let i = 0; i < deps.length; i++) {
513 const dep = deps[i];
514 if (wasTracked(dep) && !newTracked(dep)) {
515 dep.delete(effect);
516 }
517 else {
518 deps[ptr++] = dep;
519 }
520 // clear bits
521 dep.w &= ~trackOpBit;
522 dep.n &= ~trackOpBit;
523 }
524 deps.length = ptr;
525 }
526};
527
528const targetMap = new WeakMap();
529// The number of effects currently being tracked recursively.
530let effectTrackDepth = 0;
531let trackOpBit = 1;
532/**
533 * The bitwise track markers support at most 30 levels op recursion.
534 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
535 * When recursion depth is greater, fall back to using a full cleanup.
536 */
537const maxMarkerBits = 30;
538const effectStack = [];
539let activeEffect;
540const ITERATE_KEY = Symbol('iterate' );
541const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
542class ReactiveEffect {
543 constructor(fn, scheduler = null, scope) {
544 this.fn = fn;
545 this.scheduler = scheduler;
546 this.active = true;
547 this.deps = [];
548 recordEffectScope(this, scope);
549 }
550 run() {
551 if (!this.active) {
552 return this.fn();
553 }
554 if (!effectStack.includes(this)) {
555 try {
556 effectStack.push((activeEffect = this));
557 enableTracking();
558 trackOpBit = 1 << ++effectTrackDepth;
559 if (effectTrackDepth <= maxMarkerBits) {
560 initDepMarkers(this);
561 }
562 else {
563 cleanupEffect(this);
564 }
565 return this.fn();
566 }
567 finally {
568 if (effectTrackDepth <= maxMarkerBits) {
569 finalizeDepMarkers(this);
570 }
571 trackOpBit = 1 << --effectTrackDepth;
572 resetTracking();
573 effectStack.pop();
574 const n = effectStack.length;
575 activeEffect = n > 0 ? effectStack[n - 1] : undefined;
576 }
577 }
578 }
579 stop() {
580 if (this.active) {
581 cleanupEffect(this);
582 if (this.onStop) {
583 this.onStop();
584 }
585 this.active = false;
586 }
587 }
588}
589function cleanupEffect(effect) {
590 const { deps } = effect;
591 if (deps.length) {
592 for (let i = 0; i < deps.length; i++) {
593 deps[i].delete(effect);
594 }
595 deps.length = 0;
596 }
597}
598function effect(fn, options) {
599 if (fn.effect) {
600 fn = fn.effect.fn;
601 }
602 const _effect = new ReactiveEffect(fn);
603 if (options) {
604 extend(_effect, options);
605 if (options.scope)
606 recordEffectScope(_effect, options.scope);
607 }
608 if (!options || !options.lazy) {
609 _effect.run();
610 }
611 const runner = _effect.run.bind(_effect);
612 runner.effect = _effect;
613 return runner;
614}
615function stop(runner) {
616 runner.effect.stop();
617}
618let shouldTrack = true;
619const trackStack = [];
620function pauseTracking() {
621 trackStack.push(shouldTrack);
622 shouldTrack = false;
623}
624function enableTracking() {
625 trackStack.push(shouldTrack);
626 shouldTrack = true;
627}
628function resetTracking() {
629 const last = trackStack.pop();
630 shouldTrack = last === undefined ? true : last;
631}
632function track(target, type, key) {
633 if (!isTracking()) {
634 return;
635 }
636 let depsMap = targetMap.get(target);
637 if (!depsMap) {
638 targetMap.set(target, (depsMap = new Map()));
639 }
640 let dep = depsMap.get(key);
641 if (!dep) {
642 depsMap.set(key, (dep = createDep()));
643 }
644 const eventInfo = { effect: activeEffect, target, type, key }
645 ;
646 trackEffects(dep, eventInfo);
647}
648function isTracking() {
649 return shouldTrack && activeEffect !== undefined;
650}
651function trackEffects(dep, debuggerEventExtraInfo) {
652 let shouldTrack = false;
653 if (effectTrackDepth <= maxMarkerBits) {
654 if (!newTracked(dep)) {
655 dep.n |= trackOpBit; // set newly tracked
656 shouldTrack = !wasTracked(dep);
657 }
658 }
659 else {
660 // Full cleanup mode.
661 shouldTrack = !dep.has(activeEffect);
662 }
663 if (shouldTrack) {
664 dep.add(activeEffect);
665 activeEffect.deps.push(dep);
666 if (activeEffect.onTrack) {
667 activeEffect.onTrack(Object.assign({
668 effect: activeEffect
669 }, debuggerEventExtraInfo));
670 }
671 }
672}
673function trigger(target, type, key, newValue, oldValue, oldTarget) {
674 const depsMap = targetMap.get(target);
675 if (!depsMap) {
676 // never been tracked
677 return;
678 }
679 let deps = [];
680 if (type === "clear" /* CLEAR */) {
681 // collection being cleared
682 // trigger all effects for target
683 deps = [...depsMap.values()];
684 }
685 else if (key === 'length' && isArray(target)) {
686 depsMap.forEach((dep, key) => {
687 if (key === 'length' || key >= newValue) {
688 deps.push(dep);
689 }
690 });
691 }
692 else {
693 // schedule runs for SET | ADD | DELETE
694 if (key !== void 0) {
695 deps.push(depsMap.get(key));
696 }
697 // also run for iteration key on ADD | DELETE | Map.SET
698 switch (type) {
699 case "add" /* ADD */:
700 if (!isArray(target)) {
701 deps.push(depsMap.get(ITERATE_KEY));
702 if (isMap(target)) {
703 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
704 }
705 }
706 else if (isIntegerKey(key)) {
707 // new index added to array -> length changes
708 deps.push(depsMap.get('length'));
709 }
710 break;
711 case "delete" /* DELETE */:
712 if (!isArray(target)) {
713 deps.push(depsMap.get(ITERATE_KEY));
714 if (isMap(target)) {
715 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
716 }
717 }
718 break;
719 case "set" /* SET */:
720 if (isMap(target)) {
721 deps.push(depsMap.get(ITERATE_KEY));
722 }
723 break;
724 }
725 }
726 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
727 ;
728 if (deps.length === 1) {
729 if (deps[0]) {
730 {
731 triggerEffects(deps[0], eventInfo);
732 }
733 }
734 }
735 else {
736 const effects = [];
737 for (const dep of deps) {
738 if (dep) {
739 effects.push(...dep);
740 }
741 }
742 {
743 triggerEffects(createDep(effects), eventInfo);
744 }
745 }
746}
747function triggerEffects(dep, debuggerEventExtraInfo) {
748 // spread into array for stabilization
749 for (const effect of isArray(dep) ? dep : [...dep]) {
750 if (effect !== activeEffect || effect.allowRecurse) {
751 if (effect.onTrigger) {
752 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
753 }
754 if (effect.scheduler) {
755 effect.scheduler();
756 }
757 else {
758 effect.run();
759 }
760 }
761 }
762}
763
764const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
765const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
766 .map(key => Symbol[key])
767 .filter(isSymbol));
768const get = /*#__PURE__*/ createGetter();
769const shallowGet = /*#__PURE__*/ createGetter(false, true);
770const readonlyGet = /*#__PURE__*/ createGetter(true);
771const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
772const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
773function createArrayInstrumentations() {
774 const instrumentations = {};
775 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
776 instrumentations[key] = function (...args) {
777 const arr = toRaw(this);
778 for (let i = 0, l = this.length; i < l; i++) {
779 track(arr, "get" /* GET */, i + '');
780 }
781 // we run the method using the original args first (which may be reactive)
782 const res = arr[key](...args);
783 if (res === -1 || res === false) {
784 // if that didn't work, run it again using raw values.
785 return arr[key](...args.map(toRaw));
786 }
787 else {
788 return res;
789 }
790 };
791 });
792 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
793 instrumentations[key] = function (...args) {
794 pauseTracking();
795 const res = toRaw(this)[key].apply(this, args);
796 resetTracking();
797 return res;
798 };
799 });
800 return instrumentations;
801}
802function createGetter(isReadonly = false, shallow = false) {
803 return function get(target, key, receiver) {
804 if (key === "__v_isReactive" /* IS_REACTIVE */) {
805 return !isReadonly;
806 }
807 else if (key === "__v_isReadonly" /* IS_READONLY */) {
808 return isReadonly;
809 }
810 else if (key === "__v_raw" /* RAW */ &&
811 receiver ===
812 (isReadonly
813 ? shallow
814 ? shallowReadonlyMap
815 : readonlyMap
816 : shallow
817 ? shallowReactiveMap
818 : reactiveMap).get(target)) {
819 return target;
820 }
821 const targetIsArray = isArray(target);
822 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
823 return Reflect.get(arrayInstrumentations, key, receiver);
824 }
825 const res = Reflect.get(target, key, receiver);
826 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
827 return res;
828 }
829 if (!isReadonly) {
830 track(target, "get" /* GET */, key);
831 }
832 if (shallow) {
833 return res;
834 }
835 if (isRef(res)) {
836 // ref unwrapping - does not apply for Array + integer key.
837 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
838 return shouldUnwrap ? res.value : res;
839 }
840 if (isObject(res)) {
841 // Convert returned value into a proxy as well. we do the isObject check
842 // here to avoid invalid value warning. Also need to lazy access readonly
843 // and reactive here to avoid circular dependency.
844 return isReadonly ? readonly(res) : reactive(res);
845 }
846 return res;
847 };
848}
849const set = /*#__PURE__*/ createSetter();
850const shallowSet = /*#__PURE__*/ createSetter(true);
851function createSetter(shallow = false) {
852 return function set(target, key, value, receiver) {
853 let oldValue = target[key];
854 if (!shallow) {
855 value = toRaw(value);
856 oldValue = toRaw(oldValue);
857 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
858 oldValue.value = value;
859 return true;
860 }
861 }
862 const hadKey = isArray(target) && isIntegerKey(key)
863 ? Number(key) < target.length
864 : hasOwn(target, key);
865 const result = Reflect.set(target, key, value, receiver);
866 // don't trigger if target is something up in the prototype chain of original
867 if (target === toRaw(receiver)) {
868 if (!hadKey) {
869 trigger(target, "add" /* ADD */, key, value);
870 }
871 else if (hasChanged(value, oldValue)) {
872 trigger(target, "set" /* SET */, key, value, oldValue);
873 }
874 }
875 return result;
876 };
877}
878function deleteProperty(target, key) {
879 const hadKey = hasOwn(target, key);
880 const oldValue = target[key];
881 const result = Reflect.deleteProperty(target, key);
882 if (result && hadKey) {
883 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
884 }
885 return result;
886}
887function has(target, key) {
888 const result = Reflect.has(target, key);
889 if (!isSymbol(key) || !builtInSymbols.has(key)) {
890 track(target, "has" /* HAS */, key);
891 }
892 return result;
893}
894function ownKeys(target) {
895 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
896 return Reflect.ownKeys(target);
897}
898const mutableHandlers = {
899 get,
900 set,
901 deleteProperty,
902 has,
903 ownKeys
904};
905const readonlyHandlers = {
906 get: readonlyGet,
907 set(target, key) {
908 {
909 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
910 }
911 return true;
912 },
913 deleteProperty(target, key) {
914 {
915 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
916 }
917 return true;
918 }
919};
920const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
921 get: shallowGet,
922 set: shallowSet
923});
924// Props handlers are special in the sense that it should not unwrap top-level
925// refs (in order to allow refs to be explicitly passed down), but should
926// retain the reactivity of the normal readonly object.
927const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
928 get: shallowReadonlyGet
929});
930
931const toReactive = (value) => isObject(value) ? reactive(value) : value;
932const toReadonly = (value) => isObject(value) ? readonly(value) : value;
933const toShallow = (value) => value;
934const getProto = (v) => Reflect.getPrototypeOf(v);
935function get$1(target, key, isReadonly = false, isShallow = false) {
936 // #1772: readonly(reactive(Map)) should return readonly + reactive version
937 // of the value
938 target = target["__v_raw" /* RAW */];
939 const rawTarget = toRaw(target);
940 const rawKey = toRaw(key);
941 if (key !== rawKey) {
942 !isReadonly && track(rawTarget, "get" /* GET */, key);
943 }
944 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
945 const { has } = getProto(rawTarget);
946 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
947 if (has.call(rawTarget, key)) {
948 return wrap(target.get(key));
949 }
950 else if (has.call(rawTarget, rawKey)) {
951 return wrap(target.get(rawKey));
952 }
953 else if (target !== rawTarget) {
954 // #3602 readonly(reactive(Map))
955 // ensure that the nested reactive `Map` can do tracking for itself
956 target.get(key);
957 }
958}
959function has$1(key, isReadonly = false) {
960 const target = this["__v_raw" /* RAW */];
961 const rawTarget = toRaw(target);
962 const rawKey = toRaw(key);
963 if (key !== rawKey) {
964 !isReadonly && track(rawTarget, "has" /* HAS */, key);
965 }
966 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
967 return key === rawKey
968 ? target.has(key)
969 : target.has(key) || target.has(rawKey);
970}
971function size(target, isReadonly = false) {
972 target = target["__v_raw" /* RAW */];
973 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
974 return Reflect.get(target, 'size', target);
975}
976function add(value) {
977 value = toRaw(value);
978 const target = toRaw(this);
979 const proto = getProto(target);
980 const hadKey = proto.has.call(target, value);
981 if (!hadKey) {
982 target.add(value);
983 trigger(target, "add" /* ADD */, value, value);
984 }
985 return this;
986}
987function set$1(key, value) {
988 value = toRaw(value);
989 const target = toRaw(this);
990 const { has, get } = getProto(target);
991 let hadKey = has.call(target, key);
992 if (!hadKey) {
993 key = toRaw(key);
994 hadKey = has.call(target, key);
995 }
996 else {
997 checkIdentityKeys(target, has, key);
998 }
999 const oldValue = get.call(target, key);
1000 target.set(key, value);
1001 if (!hadKey) {
1002 trigger(target, "add" /* ADD */, key, value);
1003 }
1004 else if (hasChanged(value, oldValue)) {
1005 trigger(target, "set" /* SET */, key, value, oldValue);
1006 }
1007 return this;
1008}
1009function deleteEntry(key) {
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 ? get.call(target, key) : undefined;
1021 // forward the operation before queueing reactions
1022 const result = target.delete(key);
1023 if (hadKey) {
1024 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1025 }
1026 return result;
1027}
1028function clear() {
1029 const target = toRaw(this);
1030 const hadItems = target.size !== 0;
1031 const oldTarget = isMap(target)
1032 ? new Map(target)
1033 : new Set(target)
1034 ;
1035 // forward the operation before queueing reactions
1036 const result = target.clear();
1037 if (hadItems) {
1038 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1039 }
1040 return result;
1041}
1042function createForEach(isReadonly, isShallow) {
1043 return function forEach(callback, thisArg) {
1044 const observed = this;
1045 const target = observed["__v_raw" /* RAW */];
1046 const rawTarget = toRaw(target);
1047 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1048 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1049 return target.forEach((value, key) => {
1050 // important: make sure the callback is
1051 // 1. invoked with the reactive map as `this` and 3rd arg
1052 // 2. the value received should be a corresponding reactive/readonly.
1053 return callback.call(thisArg, wrap(value), wrap(key), observed);
1054 });
1055 };
1056}
1057function createIterableMethod(method, isReadonly, isShallow) {
1058 return function (...args) {
1059 const target = this["__v_raw" /* RAW */];
1060 const rawTarget = toRaw(target);
1061 const targetIsMap = isMap(rawTarget);
1062 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1063 const isKeyOnly = method === 'keys' && targetIsMap;
1064 const innerIterator = target[method](...args);
1065 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1066 !isReadonly &&
1067 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1068 // return a wrapped iterator which returns observed versions of the
1069 // values emitted from the real iterator
1070 return {
1071 // iterator protocol
1072 next() {
1073 const { value, done } = innerIterator.next();
1074 return done
1075 ? { value, done }
1076 : {
1077 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1078 done
1079 };
1080 },
1081 // iterable protocol
1082 [Symbol.iterator]() {
1083 return this;
1084 }
1085 };
1086 };
1087}
1088function createReadonlyMethod(type) {
1089 return function (...args) {
1090 {
1091 const key = args[0] ? `on key "${args[0]}" ` : ``;
1092 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1093 }
1094 return type === "delete" /* DELETE */ ? false : this;
1095 };
1096}
1097function createInstrumentations() {
1098 const mutableInstrumentations = {
1099 get(key) {
1100 return get$1(this, key);
1101 },
1102 get size() {
1103 return size(this);
1104 },
1105 has: has$1,
1106 add,
1107 set: set$1,
1108 delete: deleteEntry,
1109 clear,
1110 forEach: createForEach(false, false)
1111 };
1112 const shallowInstrumentations = {
1113 get(key) {
1114 return get$1(this, key, false, true);
1115 },
1116 get size() {
1117 return size(this);
1118 },
1119 has: has$1,
1120 add,
1121 set: set$1,
1122 delete: deleteEntry,
1123 clear,
1124 forEach: createForEach(false, true)
1125 };
1126 const readonlyInstrumentations = {
1127 get(key) {
1128 return get$1(this, key, true);
1129 },
1130 get size() {
1131 return size(this, true);
1132 },
1133 has(key) {
1134 return has$1.call(this, key, true);
1135 },
1136 add: createReadonlyMethod("add" /* ADD */),
1137 set: createReadonlyMethod("set" /* SET */),
1138 delete: createReadonlyMethod("delete" /* DELETE */),
1139 clear: createReadonlyMethod("clear" /* CLEAR */),
1140 forEach: createForEach(true, false)
1141 };
1142 const shallowReadonlyInstrumentations = {
1143 get(key) {
1144 return get$1(this, key, true, true);
1145 },
1146 get size() {
1147 return size(this, true);
1148 },
1149 has(key) {
1150 return has$1.call(this, key, true);
1151 },
1152 add: createReadonlyMethod("add" /* ADD */),
1153 set: createReadonlyMethod("set" /* SET */),
1154 delete: createReadonlyMethod("delete" /* DELETE */),
1155 clear: createReadonlyMethod("clear" /* CLEAR */),
1156 forEach: createForEach(true, true)
1157 };
1158 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1159 iteratorMethods.forEach(method => {
1160 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1161 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1162 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1163 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1164 });
1165 return [
1166 mutableInstrumentations,
1167 readonlyInstrumentations,
1168 shallowInstrumentations,
1169 shallowReadonlyInstrumentations
1170 ];
1171}
1172const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1173function createInstrumentationGetter(isReadonly, shallow) {
1174 const instrumentations = shallow
1175 ? isReadonly
1176 ? shallowReadonlyInstrumentations
1177 : shallowInstrumentations
1178 : isReadonly
1179 ? readonlyInstrumentations
1180 : mutableInstrumentations;
1181 return (target, key, receiver) => {
1182 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1183 return !isReadonly;
1184 }
1185 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1186 return isReadonly;
1187 }
1188 else if (key === "__v_raw" /* RAW */) {
1189 return target;
1190 }
1191 return Reflect.get(hasOwn(instrumentations, key) && key in target
1192 ? instrumentations
1193 : target, key, receiver);
1194 };
1195}
1196const mutableCollectionHandlers = {
1197 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1198};
1199const shallowCollectionHandlers = {
1200 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1201};
1202const readonlyCollectionHandlers = {
1203 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1204};
1205const shallowReadonlyCollectionHandlers = {
1206 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1207};
1208function checkIdentityKeys(target, has, key) {
1209 const rawKey = toRaw(key);
1210 if (rawKey !== key && has.call(target, rawKey)) {
1211 const type = toRawType(target);
1212 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1213 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1214 `which can lead to inconsistencies. ` +
1215 `Avoid differentiating between the raw and reactive versions ` +
1216 `of an object and only use the reactive version if possible.`);
1217 }
1218}
1219
1220const reactiveMap = new WeakMap();
1221const shallowReactiveMap = new WeakMap();
1222const readonlyMap = new WeakMap();
1223const shallowReadonlyMap = new WeakMap();
1224function targetTypeMap(rawType) {
1225 switch (rawType) {
1226 case 'Object':
1227 case 'Array':
1228 return 1 /* COMMON */;
1229 case 'Map':
1230 case 'Set':
1231 case 'WeakMap':
1232 case 'WeakSet':
1233 return 2 /* COLLECTION */;
1234 default:
1235 return 0 /* INVALID */;
1236 }
1237}
1238function getTargetType(value) {
1239 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1240 ? 0 /* INVALID */
1241 : targetTypeMap(toRawType(value));
1242}
1243function reactive(target) {
1244 // if trying to observe a readonly proxy, return the readonly version.
1245 if (target && target["__v_isReadonly" /* IS_READONLY */]) {
1246 return target;
1247 }
1248 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1249}
1250/**
1251 * Return a shallowly-reactive copy of the original object, where only the root
1252 * level properties are reactive. It also does not auto-unwrap refs (even at the
1253 * root level).
1254 */
1255function shallowReactive(target) {
1256 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1257}
1258/**
1259 * Creates a readonly copy of the original object. Note the returned copy is not
1260 * made reactive, but `readonly` can be called on an already reactive object.
1261 */
1262function readonly(target) {
1263 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1264}
1265/**
1266 * Returns a reactive-copy of the original object, where only the root level
1267 * properties are readonly, and does NOT unwrap refs nor recursively convert
1268 * returned properties.
1269 * This is used for creating the props proxy object for stateful components.
1270 */
1271function shallowReadonly(target) {
1272 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1273}
1274function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1275 if (!isObject(target)) {
1276 {
1277 console.warn(`value cannot be made reactive: ${String(target)}`);
1278 }
1279 return target;
1280 }
1281 // target is already a Proxy, return it.
1282 // exception: calling readonly() on a reactive object
1283 if (target["__v_raw" /* RAW */] &&
1284 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1285 return target;
1286 }
1287 // target already has corresponding Proxy
1288 const existingProxy = proxyMap.get(target);
1289 if (existingProxy) {
1290 return existingProxy;
1291 }
1292 // only a whitelist of value types can be observed.
1293 const targetType = getTargetType(target);
1294 if (targetType === 0 /* INVALID */) {
1295 return target;
1296 }
1297 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1298 proxyMap.set(target, proxy);
1299 return proxy;
1300}
1301function isReactive(value) {
1302 if (isReadonly(value)) {
1303 return isReactive(value["__v_raw" /* RAW */]);
1304 }
1305 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1306}
1307function isReadonly(value) {
1308 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1309}
1310function isProxy(value) {
1311 return isReactive(value) || isReadonly(value);
1312}
1313function toRaw(observed) {
1314 const raw = observed && observed["__v_raw" /* RAW */];
1315 return raw ? toRaw(raw) : observed;
1316}
1317function markRaw(value) {
1318 def(value, "__v_skip" /* SKIP */, true);
1319 return value;
1320}
1321
1322function trackRefValue(ref) {
1323 if (isTracking()) {
1324 ref = toRaw(ref);
1325 if (!ref.dep) {
1326 ref.dep = createDep();
1327 }
1328 {
1329 trackEffects(ref.dep, {
1330 target: ref,
1331 type: "get" /* GET */,
1332 key: 'value'
1333 });
1334 }
1335 }
1336}
1337function triggerRefValue(ref, newVal) {
1338 ref = toRaw(ref);
1339 if (ref.dep) {
1340 {
1341 triggerEffects(ref.dep, {
1342 target: ref,
1343 type: "set" /* SET */,
1344 key: 'value',
1345 newValue: newVal
1346 });
1347 }
1348 }
1349}
1350const convert = (val) => isObject(val) ? reactive(val) : val;
1351function isRef(r) {
1352 return Boolean(r && r.__v_isRef === true);
1353}
1354function ref(value) {
1355 return createRef(value, false);
1356}
1357function shallowRef(value) {
1358 return createRef(value, true);
1359}
1360class RefImpl {
1361 constructor(value, _shallow) {
1362 this._shallow = _shallow;
1363 this.dep = undefined;
1364 this.__v_isRef = true;
1365 this._rawValue = _shallow ? value : toRaw(value);
1366 this._value = _shallow ? value : convert(value);
1367 }
1368 get value() {
1369 trackRefValue(this);
1370 return this._value;
1371 }
1372 set value(newVal) {
1373 newVal = this._shallow ? newVal : toRaw(newVal);
1374 if (hasChanged(newVal, this._rawValue)) {
1375 this._rawValue = newVal;
1376 this._value = this._shallow ? newVal : convert(newVal);
1377 triggerRefValue(this, newVal);
1378 }
1379 }
1380}
1381function createRef(rawValue, shallow) {
1382 if (isRef(rawValue)) {
1383 return rawValue;
1384 }
1385 return new RefImpl(rawValue, shallow);
1386}
1387function triggerRef(ref) {
1388 triggerRefValue(ref, ref.value );
1389}
1390function unref(ref) {
1391 return isRef(ref) ? ref.value : ref;
1392}
1393const shallowUnwrapHandlers = {
1394 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1395 set: (target, key, value, receiver) => {
1396 const oldValue = target[key];
1397 if (isRef(oldValue) && !isRef(value)) {
1398 oldValue.value = value;
1399 return true;
1400 }
1401 else {
1402 return Reflect.set(target, key, value, receiver);
1403 }
1404 }
1405};
1406function proxyRefs(objectWithRefs) {
1407 return isReactive(objectWithRefs)
1408 ? objectWithRefs
1409 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1410}
1411class CustomRefImpl {
1412 constructor(factory) {
1413 this.dep = undefined;
1414 this.__v_isRef = true;
1415 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1416 this._get = get;
1417 this._set = set;
1418 }
1419 get value() {
1420 return this._get();
1421 }
1422 set value(newVal) {
1423 this._set(newVal);
1424 }
1425}
1426function customRef(factory) {
1427 return new CustomRefImpl(factory);
1428}
1429function toRefs(object) {
1430 if (!isProxy(object)) {
1431 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1432 }
1433 const ret = isArray(object) ? new Array(object.length) : {};
1434 for (const key in object) {
1435 ret[key] = toRef(object, key);
1436 }
1437 return ret;
1438}
1439class ObjectRefImpl {
1440 constructor(_object, _key) {
1441 this._object = _object;
1442 this._key = _key;
1443 this.__v_isRef = true;
1444 }
1445 get value() {
1446 return this._object[this._key];
1447 }
1448 set value(newVal) {
1449 this._object[this._key] = newVal;
1450 }
1451}
1452function toRef(object, key) {
1453 const val = object[key];
1454 return isRef(val) ? val : new ObjectRefImpl(object, key);
1455}
1456
1457class ComputedRefImpl {
1458 constructor(getter, _setter, isReadonly) {
1459 this._setter = _setter;
1460 this.dep = undefined;
1461 this._dirty = true;
1462 this.__v_isRef = true;
1463 this.effect = new ReactiveEffect(getter, () => {
1464 if (!this._dirty) {
1465 this._dirty = true;
1466 triggerRefValue(this);
1467 }
1468 });
1469 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1470 }
1471 get value() {
1472 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1473 const self = toRaw(this);
1474 trackRefValue(self);
1475 if (self._dirty) {
1476 self._dirty = false;
1477 self._value = self.effect.run();
1478 }
1479 return self._value;
1480 }
1481 set value(newValue) {
1482 this._setter(newValue);
1483 }
1484}
1485function computed(getterOrOptions, debugOptions) {
1486 let getter;
1487 let setter;
1488 if (isFunction(getterOrOptions)) {
1489 getter = getterOrOptions;
1490 setter = () => {
1491 console.warn('Write operation failed: computed value is readonly');
1492 }
1493 ;
1494 }
1495 else {
1496 getter = getterOrOptions.get;
1497 setter = getterOrOptions.set;
1498 }
1499 const cRef = new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
1500 if (debugOptions) {
1501 cRef.effect.onTrack = debugOptions.onTrack;
1502 cRef.effect.onTrigger = debugOptions.onTrigger;
1503 }
1504 return cRef;
1505}
1506
1507/* eslint-disable no-restricted-globals */
1508let isHmrUpdating = false;
1509const hmrDirtyComponents = new Set();
1510// Expose the HMR runtime on the global object
1511// This makes it entirely tree-shakable without polluting the exports and makes
1512// it easier to be used in toolings like vue-loader
1513// Note: for a component to be eligible for HMR it also needs the __hmrId option
1514// to be set so that its instances can be registered / removed.
1515{
1516 const globalObject = typeof global !== 'undefined'
1517 ? global
1518 : typeof self !== 'undefined'
1519 ? self
1520 : typeof window !== 'undefined'
1521 ? window
1522 : {};
1523 globalObject.__VUE_HMR_RUNTIME__ = {
1524 createRecord: tryWrap(createRecord),
1525 rerender: tryWrap(rerender),
1526 reload: tryWrap(reload)
1527 };
1528}
1529const map = new Map();
1530function registerHMR(instance) {
1531 const id = instance.type.__hmrId;
1532 let record = map.get(id);
1533 if (!record) {
1534 createRecord(id, instance.type);
1535 record = map.get(id);
1536 }
1537 record.instances.add(instance);
1538}
1539function unregisterHMR(instance) {
1540 map.get(instance.type.__hmrId).instances.delete(instance);
1541}
1542function createRecord(id, component) {
1543 if (!component) {
1544 warn$1(`HMR API usage is out of date.\n` +
1545 `Please upgrade vue-loader/vite/rollup-plugin-vue or other relevant ` +
1546 `dependency that handles Vue SFC compilation.`);
1547 component = {};
1548 }
1549 if (map.has(id)) {
1550 return false;
1551 }
1552 map.set(id, {
1553 component: isClassComponent(component) ? component.__vccOpts : component,
1554 instances: new Set()
1555 });
1556 return true;
1557}
1558function rerender(id, newRender) {
1559 const record = map.get(id);
1560 if (!record)
1561 return;
1562 if (newRender)
1563 record.component.render = newRender;
1564 // Array.from creates a snapshot which avoids the set being mutated during
1565 // updates
1566 Array.from(record.instances).forEach(instance => {
1567 if (newRender) {
1568 instance.render = newRender;
1569 }
1570 instance.renderCache = [];
1571 // this flag forces child components with slot content to update
1572 isHmrUpdating = true;
1573 instance.update();
1574 isHmrUpdating = false;
1575 });
1576}
1577function reload(id, newComp) {
1578 const record = map.get(id);
1579 if (!record)
1580 return;
1581 // Array.from creates a snapshot which avoids the set being mutated during
1582 // updates
1583 const { component, instances } = record;
1584 if (!hmrDirtyComponents.has(component)) {
1585 // 1. Update existing comp definition to match new one
1586 newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
1587 extend(component, newComp);
1588 for (const key in component) {
1589 if (key !== '__file' && !(key in newComp)) {
1590 delete component[key];
1591 }
1592 }
1593 // 2. Mark component dirty. This forces the renderer to replace the component
1594 // on patch.
1595 hmrDirtyComponents.add(component);
1596 // 3. Make sure to unmark the component after the reload.
1597 queuePostFlushCb(() => {
1598 hmrDirtyComponents.delete(component);
1599 });
1600 }
1601 Array.from(instances).forEach(instance => {
1602 // invalidate options resolution cache
1603 instance.appContext.optionsCache.delete(instance.type);
1604 if (instance.ceReload) {
1605 // custom element
1606 hmrDirtyComponents.add(component);
1607 instance.ceReload(newComp.styles);
1608 hmrDirtyComponents.delete(component);
1609 }
1610 else if (instance.parent) {
1611 // 4. Force the parent instance to re-render. This will cause all updated
1612 // components to be unmounted and re-mounted. Queue the update so that we
1613 // don't end up forcing the same parent to re-render multiple times.
1614 queueJob(instance.parent.update);
1615 // instance is the inner component of an async custom element
1616 // invoke to reset styles
1617 if (instance.parent.type.__asyncLoader &&
1618 instance.parent.ceReload) {
1619 instance.parent.ceReload(newComp.styles);
1620 }
1621 }
1622 else if (instance.appContext.reload) {
1623 // root instance mounted via createApp() has a reload method
1624 instance.appContext.reload();
1625 }
1626 else if (typeof window !== 'undefined') {
1627 // root instance inside tree created via raw render(). Force reload.
1628 window.location.reload();
1629 }
1630 else {
1631 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1632 }
1633 });
1634}
1635function tryWrap(fn) {
1636 return (id, arg) => {
1637 try {
1638 return fn(id, arg);
1639 }
1640 catch (e) {
1641 console.error(e);
1642 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1643 `Full reload required.`);
1644 }
1645 };
1646}
1647
1648let devtools;
1649function setDevtoolsHook(hook) {
1650 devtools = hook;
1651}
1652function devtoolsInitApp(app, version) {
1653 // TODO queue if devtools is undefined
1654 if (!devtools)
1655 return;
1656 devtools.emit("app:init" /* APP_INIT */, app, version, {
1657 Fragment,
1658 Text,
1659 Comment,
1660 Static
1661 });
1662}
1663function devtoolsUnmountApp(app) {
1664 if (!devtools)
1665 return;
1666 devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1667}
1668const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1669const devtoolsComponentUpdated =
1670/*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1671const devtoolsComponentRemoved =
1672/*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1673function createDevtoolsComponentHook(hook) {
1674 return (component) => {
1675 if (!devtools)
1676 return;
1677 devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1678 };
1679}
1680const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
1681const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
1682function createDevtoolsPerformanceHook(hook) {
1683 return (component, type, time) => {
1684 if (!devtools)
1685 return;
1686 devtools.emit(hook, component.appContext.app, component.uid, component, type, time);
1687 };
1688}
1689function devtoolsComponentEmit(component, event, params) {
1690 if (!devtools)
1691 return;
1692 devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1693}
1694
1695const deprecationData = {
1696 ["GLOBAL_MOUNT" /* GLOBAL_MOUNT */]: {
1697 message: `The global app bootstrapping API has changed: vm.$mount() and the "el" ` +
1698 `option have been removed. Use createApp(RootComponent).mount() instead.`,
1699 link: `https://v3.vuejs.org/guide/migration/global-api.html#mounting-app-instance`
1700 },
1701 ["GLOBAL_MOUNT_CONTAINER" /* GLOBAL_MOUNT_CONTAINER */]: {
1702 message: `Vue detected directives on the mount container. ` +
1703 `In Vue 3, the container is no longer considered part of the template ` +
1704 `and will not be processed/replaced.`,
1705 link: `https://v3.vuejs.org/guide/migration/mount-changes.html`
1706 },
1707 ["GLOBAL_EXTEND" /* GLOBAL_EXTEND */]: {
1708 message: `Vue.extend() has been removed in Vue 3. ` +
1709 `Use defineComponent() instead.`,
1710 link: `https://v3.vuejs.org/api/global-api.html#definecomponent`
1711 },
1712 ["GLOBAL_PROTOTYPE" /* GLOBAL_PROTOTYPE */]: {
1713 message: `Vue.prototype is no longer available in Vue 3. ` +
1714 `Use app.config.globalProperties instead.`,
1715 link: `https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties`
1716 },
1717 ["GLOBAL_SET" /* GLOBAL_SET */]: {
1718 message: `Vue.set() has been removed as it is no longer needed in Vue 3. ` +
1719 `Simply use native JavaScript mutations.`
1720 },
1721 ["GLOBAL_DELETE" /* GLOBAL_DELETE */]: {
1722 message: `Vue.delete() has been removed as it is no longer needed in Vue 3. ` +
1723 `Simply use native JavaScript mutations.`
1724 },
1725 ["GLOBAL_OBSERVABLE" /* GLOBAL_OBSERVABLE */]: {
1726 message: `Vue.observable() has been removed. ` +
1727 `Use \`import { reactive } from "vue"\` from Composition API instead.`,
1728 link: `https://v3.vuejs.org/api/basic-reactivity.html`
1729 },
1730 ["GLOBAL_PRIVATE_UTIL" /* GLOBAL_PRIVATE_UTIL */]: {
1731 message: `Vue.util has been removed. Please refactor to avoid its usage ` +
1732 `since it was an internal API even in Vue 2.`
1733 },
1734 ["CONFIG_SILENT" /* CONFIG_SILENT */]: {
1735 message: `config.silent has been removed because it is not good practice to ` +
1736 `intentionally suppress warnings. You can use your browser console's ` +
1737 `filter features to focus on relevant messages.`
1738 },
1739 ["CONFIG_DEVTOOLS" /* CONFIG_DEVTOOLS */]: {
1740 message: `config.devtools has been removed. To enable devtools for ` +
1741 `production, configure the __VUE_PROD_DEVTOOLS__ compile-time flag.`,
1742 link: `https://github.com/vuejs/vue-next/tree/master/packages/vue#bundler-build-feature-flags`
1743 },
1744 ["CONFIG_KEY_CODES" /* CONFIG_KEY_CODES */]: {
1745 message: `config.keyCodes has been removed. ` +
1746 `In Vue 3, you can directly use the kebab-case key names as v-on modifiers.`,
1747 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1748 },
1749 ["CONFIG_PRODUCTION_TIP" /* CONFIG_PRODUCTION_TIP */]: {
1750 message: `config.productionTip has been removed.`,
1751 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-productiontip-removed`
1752 },
1753 ["CONFIG_IGNORED_ELEMENTS" /* CONFIG_IGNORED_ELEMENTS */]: {
1754 message: () => {
1755 let msg = `config.ignoredElements has been removed.`;
1756 if (isRuntimeOnly()) {
1757 msg += ` Pass the "isCustomElement" option to @vue/compiler-dom instead.`;
1758 }
1759 else {
1760 msg += ` Use config.isCustomElement instead.`;
1761 }
1762 return msg;
1763 },
1764 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-ignoredelements-is-now-config-iscustomelement`
1765 },
1766 ["CONFIG_WHITESPACE" /* CONFIG_WHITESPACE */]: {
1767 // this warning is only relevant in the full build when using runtime
1768 // compilation, so it's put in the runtime compatConfig list.
1769 message: `Vue 3 compiler's whitespace option will default to "condense" instead of ` +
1770 `"preserve". To suppress this warning, provide an explicit value for ` +
1771 `\`config.compilerOptions.whitespace\`.`
1772 },
1773 ["CONFIG_OPTION_MERGE_STRATS" /* CONFIG_OPTION_MERGE_STRATS */]: {
1774 message: `config.optionMergeStrategies no longer exposes internal strategies. ` +
1775 `Use custom merge functions instead.`
1776 },
1777 ["INSTANCE_SET" /* INSTANCE_SET */]: {
1778 message: `vm.$set() has been removed as it is no longer needed in Vue 3. ` +
1779 `Simply use native JavaScript mutations.`
1780 },
1781 ["INSTANCE_DELETE" /* INSTANCE_DELETE */]: {
1782 message: `vm.$delete() has been removed as it is no longer needed in Vue 3. ` +
1783 `Simply use native JavaScript mutations.`
1784 },
1785 ["INSTANCE_DESTROY" /* INSTANCE_DESTROY */]: {
1786 message: `vm.$destroy() has been removed. Use app.unmount() instead.`,
1787 link: `https://v3.vuejs.org/api/application-api.html#unmount`
1788 },
1789 ["INSTANCE_EVENT_EMITTER" /* INSTANCE_EVENT_EMITTER */]: {
1790 message: `vm.$on/$once/$off() have been removed. ` +
1791 `Use an external event emitter library instead.`,
1792 link: `https://v3.vuejs.org/guide/migration/events-api.html`
1793 },
1794 ["INSTANCE_EVENT_HOOKS" /* INSTANCE_EVENT_HOOKS */]: {
1795 message: event => `"${event}" lifecycle events are no longer supported. From templates, ` +
1796 `use the "vnode" prefix instead of "hook:". For example, @${event} ` +
1797 `should be changed to @vnode-${event.slice(5)}. ` +
1798 `From JavaScript, use Composition API to dynamically register lifecycle ` +
1799 `hooks.`,
1800 link: `https://v3.vuejs.org/guide/migration/vnode-lifecycle-events.html`
1801 },
1802 ["INSTANCE_CHILDREN" /* INSTANCE_CHILDREN */]: {
1803 message: `vm.$children has been removed. Consider refactoring your logic ` +
1804 `to avoid relying on direct access to child components.`,
1805 link: `https://v3.vuejs.org/guide/migration/children.html`
1806 },
1807 ["INSTANCE_LISTENERS" /* INSTANCE_LISTENERS */]: {
1808 message: `vm.$listeners has been removed. In Vue 3, parent v-on listeners are ` +
1809 `included in vm.$attrs and it is no longer necessary to separately use ` +
1810 `v-on="$listeners" if you are already using v-bind="$attrs". ` +
1811 `(Note: the Vue 3 behavior only applies if this compat config is disabled)`,
1812 link: `https://v3.vuejs.org/guide/migration/listeners-removed.html`
1813 },
1814 ["INSTANCE_SCOPED_SLOTS" /* INSTANCE_SCOPED_SLOTS */]: {
1815 message: `vm.$scopedSlots has been removed. Use vm.$slots instead.`,
1816 link: `https://v3.vuejs.org/guide/migration/slots-unification.html`
1817 },
1818 ["INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */]: {
1819 message: componentName => `Component <${componentName || 'Anonymous'}> has \`inheritAttrs: false\` but is ` +
1820 `relying on class/style fallthrough from parent. In Vue 3, class/style ` +
1821 `are now included in $attrs and will no longer fallthrough when ` +
1822 `inheritAttrs is false. If you are already using v-bind="$attrs" on ` +
1823 `component root it should render the same end result. ` +
1824 `If you are binding $attrs to a non-root element and expecting ` +
1825 `class/style to fallthrough on root, you will need to now manually bind ` +
1826 `them on root via :class="$attrs.class".`,
1827 link: `https://v3.vuejs.org/guide/migration/attrs-includes-class-style.html`
1828 },
1829 ["OPTIONS_DATA_FN" /* OPTIONS_DATA_FN */]: {
1830 message: `The "data" option can no longer be a plain object. ` +
1831 `Always use a function.`,
1832 link: `https://v3.vuejs.org/guide/migration/data-option.html`
1833 },
1834 ["OPTIONS_DATA_MERGE" /* OPTIONS_DATA_MERGE */]: {
1835 message: (key) => `Detected conflicting key "${key}" when merging data option values. ` +
1836 `In Vue 3, data keys are merged shallowly and will override one another.`,
1837 link: `https://v3.vuejs.org/guide/migration/data-option.html#mixin-merge-behavior-change`
1838 },
1839 ["OPTIONS_BEFORE_DESTROY" /* OPTIONS_BEFORE_DESTROY */]: {
1840 message: `\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`
1841 },
1842 ["OPTIONS_DESTROYED" /* OPTIONS_DESTROYED */]: {
1843 message: `\`destroyed\` has been renamed to \`unmounted\`.`
1844 },
1845 ["WATCH_ARRAY" /* WATCH_ARRAY */]: {
1846 message: `"watch" option or vm.$watch on an array value will no longer ` +
1847 `trigger on array mutation unless the "deep" option is specified. ` +
1848 `If current usage is intended, you can disable the compat behavior and ` +
1849 `suppress this warning with:` +
1850 `\n\n configureCompat({ ${"WATCH_ARRAY" /* WATCH_ARRAY */}: false })\n`,
1851 link: `https://v3.vuejs.org/guide/migration/watch.html`
1852 },
1853 ["PROPS_DEFAULT_THIS" /* PROPS_DEFAULT_THIS */]: {
1854 message: (key) => `props default value function no longer has access to "this". The compat ` +
1855 `build only offers access to this.$options.` +
1856 `(found in prop "${key}")`,
1857 link: `https://v3.vuejs.org/guide/migration/props-default-this.html`
1858 },
1859 ["CUSTOM_DIR" /* CUSTOM_DIR */]: {
1860 message: (legacyHook, newHook) => `Custom directive hook "${legacyHook}" has been removed. ` +
1861 `Use "${newHook}" instead.`,
1862 link: `https://v3.vuejs.org/guide/migration/custom-directives.html`
1863 },
1864 ["V_FOR_REF" /* V_FOR_REF */]: {
1865 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
1866 `Consider using function refs or refactor to avoid ref usage altogether.`,
1867 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
1868 },
1869 ["V_ON_KEYCODE_MODIFIER" /* V_ON_KEYCODE_MODIFIER */]: {
1870 message: `Using keyCode as v-on modifier is no longer supported. ` +
1871 `Use kebab-case key name modifiers instead.`,
1872 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1873 },
1874 ["ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */]: {
1875 message: (name) => `Attribute "${name}" with v-bind value \`false\` will render ` +
1876 `${name}="false" instead of removing it in Vue 3. To remove the attribute, ` +
1877 `use \`null\` or \`undefined\` instead. If the usage is intended, ` +
1878 `you can disable the compat behavior and suppress this warning with:` +
1879 `\n\n configureCompat({ ${"ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */}: false })\n`,
1880 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
1881 },
1882 ["ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */]: {
1883 message: (name, value, coerced) => `Enumerated attribute "${name}" with v-bind value \`${value}\` will ` +
1884 `${value === null ? `be removed` : `render the value as-is`} instead of coercing the value to "${coerced}" in Vue 3. ` +
1885 `Always use explicit "true" or "false" values for enumerated attributes. ` +
1886 `If the usage is intended, ` +
1887 `you can disable the compat behavior and suppress this warning with:` +
1888 `\n\n configureCompat({ ${"ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */}: false })\n`,
1889 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
1890 },
1891 ["TRANSITION_CLASSES" /* TRANSITION_CLASSES */]: {
1892 message: `` // this feature cannot be runtime-detected
1893 },
1894 ["TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */]: {
1895 message: `<TransitionGroup> no longer renders a root <span> element by ` +
1896 `default if no "tag" prop is specified. If you do not rely on the span ` +
1897 `for styling, you can disable the compat behavior and suppress this ` +
1898 `warning with:` +
1899 `\n\n configureCompat({ ${"TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */}: false })\n`,
1900 link: `https://v3.vuejs.org/guide/migration/transition-group.html`
1901 },
1902 ["COMPONENT_ASYNC" /* COMPONENT_ASYNC */]: {
1903 message: (comp) => {
1904 const name = getComponentName(comp);
1905 return (`Async component${name ? ` <${name}>` : `s`} should be explicitly created via \`defineAsyncComponent()\` ` +
1906 `in Vue 3. Plain functions will be treated as functional components in ` +
1907 `non-compat build. If you have already migrated all async component ` +
1908 `usage and intend to use plain functions for functional components, ` +
1909 `you can disable the compat behavior and suppress this ` +
1910 `warning with:` +
1911 `\n\n configureCompat({ ${"COMPONENT_ASYNC" /* COMPONENT_ASYNC */}: false })\n`);
1912 },
1913 link: `https://v3.vuejs.org/guide/migration/async-components.html`
1914 },
1915 ["COMPONENT_FUNCTIONAL" /* COMPONENT_FUNCTIONAL */]: {
1916 message: (comp) => {
1917 const name = getComponentName(comp);
1918 return (`Functional component${name ? ` <${name}>` : `s`} should be defined as a plain function in Vue 3. The "functional" ` +
1919 `option has been removed. NOTE: Before migrating to use plain ` +
1920 `functions for functional components, first make sure that all async ` +
1921 `components usage have been migrated and its compat behavior has ` +
1922 `been disabled.`);
1923 },
1924 link: `https://v3.vuejs.org/guide/migration/functional-components.html`
1925 },
1926 ["COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */]: {
1927 message: (comp) => {
1928 const configMsg = `opt-in to ` +
1929 `Vue 3 behavior on a per-component basis with \`compatConfig: { ${"COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */}: false }\`.`;
1930 if (comp.props &&
1931 (isArray(comp.props)
1932 ? comp.props.includes('modelValue')
1933 : hasOwn(comp.props, 'modelValue'))) {
1934 return (`Component delcares "modelValue" prop, which is Vue 3 usage, but ` +
1935 `is running under Vue 2 compat v-model behavior. You can ${configMsg}`);
1936 }
1937 return (`v-model usage on component has changed in Vue 3. Component that expects ` +
1938 `to work with v-model should now use the "modelValue" prop and emit the ` +
1939 `"update:modelValue" event. You can update the usage and then ${configMsg}`);
1940 },
1941 link: `https://v3.vuejs.org/guide/migration/v-model.html`
1942 },
1943 ["RENDER_FUNCTION" /* RENDER_FUNCTION */]: {
1944 message: `Vue 3's render function API has changed. ` +
1945 `You can opt-in to the new API with:` +
1946 `\n\n configureCompat({ ${"RENDER_FUNCTION" /* RENDER_FUNCTION */}: false })\n` +
1947 `\n (This can also be done per-component via the "compatConfig" option.)`,
1948 link: `https://v3.vuejs.org/guide/migration/render-function-api.html`
1949 },
1950 ["FILTERS" /* FILTERS */]: {
1951 message: `filters have been removed in Vue 3. ` +
1952 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
1953 `Use method calls or computed properties instead.`,
1954 link: `https://v3.vuejs.org/guide/migration/filters.html`
1955 },
1956 ["PRIVATE_APIS" /* PRIVATE_APIS */]: {
1957 message: name => `"${name}" is a Vue 2 private API that no longer exists in Vue 3. ` +
1958 `If you are seeing this warning only due to a dependency, you can ` +
1959 `suppress this warning via { PRIVATE_APIS: 'supress-warning' }.`
1960 }
1961};
1962const instanceWarned = Object.create(null);
1963const warnCount = Object.create(null);
1964function warnDeprecation(key, instance, ...args) {
1965 instance = instance || getCurrentInstance();
1966 // check user config
1967 const config = getCompatConfigForKey(key, instance);
1968 if (config === 'suppress-warning') {
1969 return;
1970 }
1971 const dupKey = key + args.join('');
1972 let compId = instance && formatComponentName(instance, instance.type);
1973 if (compId === 'Anonymous' && instance) {
1974 compId = instance.uid;
1975 }
1976 // skip if the same warning is emitted for the same component type
1977 const componentDupKey = dupKey + compId;
1978 if (componentDupKey in instanceWarned) {
1979 return;
1980 }
1981 instanceWarned[componentDupKey] = true;
1982 // same warning, but different component. skip the long message and just
1983 // log the key and count.
1984 if (dupKey in warnCount) {
1985 warn$1(`(deprecation ${key}) (${++warnCount[dupKey] + 1})`);
1986 return;
1987 }
1988 warnCount[dupKey] = 0;
1989 const { message, link } = deprecationData[key];
1990 warn$1(`(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`);
1991 if (!isCompatEnabled(key, instance, true)) {
1992 console.error(`^ The above deprecation's compat behavior is disabled and will likely ` +
1993 `lead to runtime errors.`);
1994 }
1995}
1996const globalCompatConfig = {
1997 MODE: 2
1998};
1999function getCompatConfigForKey(key, instance) {
2000 const instanceConfig = instance && instance.type.compatConfig;
2001 if (instanceConfig && key in instanceConfig) {
2002 return instanceConfig[key];
2003 }
2004 return globalCompatConfig[key];
2005}
2006function isCompatEnabled(key, instance, enableForBuiltIn = false) {
2007 // skip compat for built-in components
2008 if (!enableForBuiltIn && instance && instance.type.__isBuiltIn) {
2009 return false;
2010 }
2011 const rawMode = getCompatConfigForKey('MODE', instance) || 2;
2012 const val = getCompatConfigForKey(key, instance);
2013 const mode = isFunction(rawMode)
2014 ? rawMode(instance && instance.type)
2015 : rawMode;
2016 if (mode === 2) {
2017 return val !== false;
2018 }
2019 else {
2020 return val === true || val === 'suppress-warning';
2021 }
2022}
2023
2024function emit(instance, event, ...rawArgs) {
2025 const props = instance.vnode.props || EMPTY_OBJ;
2026 {
2027 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2028 if (emitsOptions) {
2029 if (!(event in emitsOptions) &&
2030 !(false )) {
2031 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2032 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2033 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2034 }
2035 }
2036 else {
2037 const validator = emitsOptions[event];
2038 if (isFunction(validator)) {
2039 const isValid = validator(...rawArgs);
2040 if (!isValid) {
2041 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2042 }
2043 }
2044 }
2045 }
2046 }
2047 let args = rawArgs;
2048 const isModelListener = event.startsWith('update:');
2049 // for v-model update:xxx events, apply modifiers on args
2050 const modelArg = isModelListener && event.slice(7);
2051 if (modelArg && modelArg in props) {
2052 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2053 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2054 if (trim) {
2055 args = rawArgs.map(a => a.trim());
2056 }
2057 else if (number) {
2058 args = rawArgs.map(toNumber);
2059 }
2060 }
2061 {
2062 devtoolsComponentEmit(instance, event, args);
2063 }
2064 {
2065 const lowerCaseEvent = event.toLowerCase();
2066 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2067 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2068 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2069 `Note that HTML attributes are case-insensitive and you cannot use ` +
2070 `v-on to listen to camelCase events when using in-DOM templates. ` +
2071 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2072 }
2073 }
2074 let handlerName;
2075 let handler = props[(handlerName = toHandlerKey(event))] ||
2076 // also try camelCase event handler (#2249)
2077 props[(handlerName = toHandlerKey(camelize(event)))];
2078 // for v-model update:xxx events, also trigger kebab-case equivalent
2079 // for props passed via kebab-case
2080 if (!handler && isModelListener) {
2081 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2082 }
2083 if (handler) {
2084 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2085 }
2086 const onceHandler = props[handlerName + `Once`];
2087 if (onceHandler) {
2088 if (!instance.emitted) {
2089 instance.emitted = {};
2090 }
2091 else if (instance.emitted[handlerName]) {
2092 return;
2093 }
2094 instance.emitted[handlerName] = true;
2095 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2096 }
2097}
2098function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2099 const cache = appContext.emitsCache;
2100 const cached = cache.get(comp);
2101 if (cached !== undefined) {
2102 return cached;
2103 }
2104 const raw = comp.emits;
2105 let normalized = {};
2106 // apply mixin/extends props
2107 let hasExtends = false;
2108 if (!isFunction(comp)) {
2109 const extendEmits = (raw) => {
2110 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2111 if (normalizedFromExtend) {
2112 hasExtends = true;
2113 extend(normalized, normalizedFromExtend);
2114 }
2115 };
2116 if (!asMixin && appContext.mixins.length) {
2117 appContext.mixins.forEach(extendEmits);
2118 }
2119 if (comp.extends) {
2120 extendEmits(comp.extends);
2121 }
2122 if (comp.mixins) {
2123 comp.mixins.forEach(extendEmits);
2124 }
2125 }
2126 if (!raw && !hasExtends) {
2127 cache.set(comp, null);
2128 return null;
2129 }
2130 if (isArray(raw)) {
2131 raw.forEach(key => (normalized[key] = null));
2132 }
2133 else {
2134 extend(normalized, raw);
2135 }
2136 cache.set(comp, normalized);
2137 return normalized;
2138}
2139// Check if an incoming prop key is a declared emit event listener.
2140// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2141// both considered matched listeners.
2142function isEmitListener(options, key) {
2143 if (!options || !isOn(key)) {
2144 return false;
2145 }
2146 key = key.slice(2).replace(/Once$/, '');
2147 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2148 hasOwn(options, hyphenate(key)) ||
2149 hasOwn(options, key));
2150}
2151
2152/**
2153 * mark the current rendering instance for asset resolution (e.g.
2154 * resolveComponent, resolveDirective) during render
2155 */
2156let currentRenderingInstance = null;
2157let currentScopeId = null;
2158/**
2159 * Note: rendering calls maybe nested. The function returns the parent rendering
2160 * instance if present, which should be restored after the render is done:
2161 *
2162 * ```js
2163 * const prev = setCurrentRenderingInstance(i)
2164 * // ...render
2165 * setCurrentRenderingInstance(prev)
2166 * ```
2167 */
2168function setCurrentRenderingInstance(instance) {
2169 const prev = currentRenderingInstance;
2170 currentRenderingInstance = instance;
2171 currentScopeId = (instance && instance.type.__scopeId) || null;
2172 return prev;
2173}
2174/**
2175 * Set scope id when creating hoisted vnodes.
2176 * @private compiler helper
2177 */
2178function pushScopeId(id) {
2179 currentScopeId = id;
2180}
2181/**
2182 * Technically we no longer need this after 3.0.8 but we need to keep the same
2183 * API for backwards compat w/ code generated by compilers.
2184 * @private
2185 */
2186function popScopeId() {
2187 currentScopeId = null;
2188}
2189/**
2190 * Only for backwards compat
2191 * @private
2192 */
2193const withScopeId = (_id) => withCtx;
2194/**
2195 * Wrap a slot function to memoize current rendering instance
2196 * @private compiler helper
2197 */
2198function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2199) {
2200 if (!ctx)
2201 return fn;
2202 // already normalized
2203 if (fn._n) {
2204 return fn;
2205 }
2206 const renderFnWithContext = (...args) => {
2207 // If a user calls a compiled slot inside a template expression (#1745), it
2208 // can mess up block tracking, so by default we disable block tracking and
2209 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2210 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2211 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2212 if (renderFnWithContext._d) {
2213 setBlockTracking(-1);
2214 }
2215 const prevInstance = setCurrentRenderingInstance(ctx);
2216 const res = fn(...args);
2217 setCurrentRenderingInstance(prevInstance);
2218 if (renderFnWithContext._d) {
2219 setBlockTracking(1);
2220 }
2221 {
2222 devtoolsComponentUpdated(ctx);
2223 }
2224 return res;
2225 };
2226 // mark normalized to avoid duplicated wrapping
2227 renderFnWithContext._n = true;
2228 // mark this as compiled by default
2229 // this is used in vnode.ts -> normalizeChildren() to set the slot
2230 // rendering flag.
2231 renderFnWithContext._c = true;
2232 // disable block tracking by default
2233 renderFnWithContext._d = true;
2234 return renderFnWithContext;
2235}
2236
2237/**
2238 * dev only flag to track whether $attrs was used during render.
2239 * If $attrs was used during render then the warning for failed attrs
2240 * fallthrough can be suppressed.
2241 */
2242let accessedAttrs = false;
2243function markAttrsAccessed() {
2244 accessedAttrs = true;
2245}
2246function renderComponentRoot(instance) {
2247 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2248 let result;
2249 const prev = setCurrentRenderingInstance(instance);
2250 {
2251 accessedAttrs = false;
2252 }
2253 try {
2254 let fallthroughAttrs;
2255 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2256 // withProxy is a proxy with a different `has` trap only for
2257 // runtime-compiled render functions using `with` block.
2258 const proxyToUse = withProxy || proxy;
2259 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2260 fallthroughAttrs = attrs;
2261 }
2262 else {
2263 // functional
2264 const render = Component;
2265 // in dev, mark attrs accessed if optional props (attrs === props)
2266 if (true && attrs === props) {
2267 markAttrsAccessed();
2268 }
2269 result = normalizeVNode(render.length > 1
2270 ? render(props, true
2271 ? {
2272 get attrs() {
2273 markAttrsAccessed();
2274 return attrs;
2275 },
2276 slots,
2277 emit
2278 }
2279 : { attrs, slots, emit })
2280 : render(props, null /* we know it doesn't need it */));
2281 fallthroughAttrs = Component.props
2282 ? attrs
2283 : getFunctionalFallthrough(attrs);
2284 }
2285 // attr merging
2286 // in dev mode, comments are preserved, and it's possible for a template
2287 // to have comments along side the root element which makes it a fragment
2288 let root = result;
2289 let setRoot = undefined;
2290 if (true &&
2291 result.patchFlag > 0 &&
2292 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2293 ;
2294 [root, setRoot] = getChildRoot(result);
2295 }
2296 if (fallthroughAttrs && inheritAttrs !== false) {
2297 const keys = Object.keys(fallthroughAttrs);
2298 const { shapeFlag } = root;
2299 if (keys.length) {
2300 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2301 if (propsOptions && keys.some(isModelListener)) {
2302 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2303 // prop, it indicates this component expects to handle v-model and
2304 // it should not fallthrough.
2305 // related: #1543, #1643, #1989
2306 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2307 }
2308 root = cloneVNode(root, fallthroughAttrs);
2309 }
2310 else if (true && !accessedAttrs && root.type !== Comment) {
2311 const allAttrs = Object.keys(attrs);
2312 const eventAttrs = [];
2313 const extraAttrs = [];
2314 for (let i = 0, l = allAttrs.length; i < l; i++) {
2315 const key = allAttrs[i];
2316 if (isOn(key)) {
2317 // ignore v-model handlers when they fail to fallthrough
2318 if (!isModelListener(key)) {
2319 // remove `on`, lowercase first letter to reflect event casing
2320 // accurately
2321 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2322 }
2323 }
2324 else {
2325 extraAttrs.push(key);
2326 }
2327 }
2328 if (extraAttrs.length) {
2329 warn$1(`Extraneous non-props attributes (` +
2330 `${extraAttrs.join(', ')}) ` +
2331 `were passed to component but could not be automatically inherited ` +
2332 `because component renders fragment or text root nodes.`);
2333 }
2334 if (eventAttrs.length) {
2335 warn$1(`Extraneous non-emits event listeners (` +
2336 `${eventAttrs.join(', ')}) ` +
2337 `were passed to component but could not be automatically inherited ` +
2338 `because component renders fragment or text root nodes. ` +
2339 `If the listener is intended to be a component custom event listener only, ` +
2340 `declare it using the "emits" option.`);
2341 }
2342 }
2343 }
2344 }
2345 if (false &&
2346 isCompatEnabled("INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */, instance) &&
2347 vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */ &&
2348 root.shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) ;
2349 // inherit directives
2350 if (vnode.dirs) {
2351 if (true && !isElementRoot(root)) {
2352 warn$1(`Runtime directive used on component with non-element root node. ` +
2353 `The directives will not function as intended.`);
2354 }
2355 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2356 }
2357 // inherit transition data
2358 if (vnode.transition) {
2359 if (true && !isElementRoot(root)) {
2360 warn$1(`Component inside <Transition> renders non-element root node ` +
2361 `that cannot be animated.`);
2362 }
2363 root.transition = vnode.transition;
2364 }
2365 if (true && setRoot) {
2366 setRoot(root);
2367 }
2368 else {
2369 result = root;
2370 }
2371 }
2372 catch (err) {
2373 blockStack.length = 0;
2374 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2375 result = createVNode(Comment);
2376 }
2377 setCurrentRenderingInstance(prev);
2378 return result;
2379}
2380/**
2381 * dev only
2382 * In dev mode, template root level comments are rendered, which turns the
2383 * template into a fragment root, but we need to locate the single element
2384 * root for attrs and scope id processing.
2385 */
2386const getChildRoot = (vnode) => {
2387 const rawChildren = vnode.children;
2388 const dynamicChildren = vnode.dynamicChildren;
2389 const childRoot = filterSingleRoot(rawChildren);
2390 if (!childRoot) {
2391 return [vnode, undefined];
2392 }
2393 const index = rawChildren.indexOf(childRoot);
2394 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2395 const setRoot = (updatedRoot) => {
2396 rawChildren[index] = updatedRoot;
2397 if (dynamicChildren) {
2398 if (dynamicIndex > -1) {
2399 dynamicChildren[dynamicIndex] = updatedRoot;
2400 }
2401 else if (updatedRoot.patchFlag > 0) {
2402 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2403 }
2404 }
2405 };
2406 return [normalizeVNode(childRoot), setRoot];
2407};
2408function filterSingleRoot(children) {
2409 let singleRoot;
2410 for (let i = 0; i < children.length; i++) {
2411 const child = children[i];
2412 if (isVNode(child)) {
2413 // ignore user comment
2414 if (child.type !== Comment || child.children === 'v-if') {
2415 if (singleRoot) {
2416 // has more than 1 non-comment child, return now
2417 return;
2418 }
2419 else {
2420 singleRoot = child;
2421 }
2422 }
2423 }
2424 else {
2425 return;
2426 }
2427 }
2428 return singleRoot;
2429}
2430const getFunctionalFallthrough = (attrs) => {
2431 let res;
2432 for (const key in attrs) {
2433 if (key === 'class' || key === 'style' || isOn(key)) {
2434 (res || (res = {}))[key] = attrs[key];
2435 }
2436 }
2437 return res;
2438};
2439const filterModelListeners = (attrs, props) => {
2440 const res = {};
2441 for (const key in attrs) {
2442 if (!isModelListener(key) || !(key.slice(9) in props)) {
2443 res[key] = attrs[key];
2444 }
2445 }
2446 return res;
2447};
2448const isElementRoot = (vnode) => {
2449 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2450 vnode.type === Comment // potential v-if branch switch
2451 );
2452};
2453function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2454 const { props: prevProps, children: prevChildren, component } = prevVNode;
2455 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2456 const emits = component.emitsOptions;
2457 // Parent component's render function was hot-updated. Since this may have
2458 // caused the child component's slots content to have changed, we need to
2459 // force the child to update as well.
2460 if ((prevChildren || nextChildren) && isHmrUpdating) {
2461 return true;
2462 }
2463 // force child update for runtime directive or transition on component vnode.
2464 if (nextVNode.dirs || nextVNode.transition) {
2465 return true;
2466 }
2467 if (optimized && patchFlag >= 0) {
2468 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2469 // slot content that references values that might have changed,
2470 // e.g. in a v-for
2471 return true;
2472 }
2473 if (patchFlag & 16 /* FULL_PROPS */) {
2474 if (!prevProps) {
2475 return !!nextProps;
2476 }
2477 // presence of this flag indicates props are always non-null
2478 return hasPropsChanged(prevProps, nextProps, emits);
2479 }
2480 else if (patchFlag & 8 /* PROPS */) {
2481 const dynamicProps = nextVNode.dynamicProps;
2482 for (let i = 0; i < dynamicProps.length; i++) {
2483 const key = dynamicProps[i];
2484 if (nextProps[key] !== prevProps[key] &&
2485 !isEmitListener(emits, key)) {
2486 return true;
2487 }
2488 }
2489 }
2490 }
2491 else {
2492 // this path is only taken by manually written render functions
2493 // so presence of any children leads to a forced update
2494 if (prevChildren || nextChildren) {
2495 if (!nextChildren || !nextChildren.$stable) {
2496 return true;
2497 }
2498 }
2499 if (prevProps === nextProps) {
2500 return false;
2501 }
2502 if (!prevProps) {
2503 return !!nextProps;
2504 }
2505 if (!nextProps) {
2506 return true;
2507 }
2508 return hasPropsChanged(prevProps, nextProps, emits);
2509 }
2510 return false;
2511}
2512function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2513 const nextKeys = Object.keys(nextProps);
2514 if (nextKeys.length !== Object.keys(prevProps).length) {
2515 return true;
2516 }
2517 for (let i = 0; i < nextKeys.length; i++) {
2518 const key = nextKeys[i];
2519 if (nextProps[key] !== prevProps[key] &&
2520 !isEmitListener(emitsOptions, key)) {
2521 return true;
2522 }
2523 }
2524 return false;
2525}
2526function updateHOCHostEl({ vnode, parent }, el // HostNode
2527) {
2528 while (parent && parent.subTree === vnode) {
2529 (vnode = parent.vnode).el = el;
2530 parent = parent.parent;
2531 }
2532}
2533
2534const isSuspense = (type) => type.__isSuspense;
2535// Suspense exposes a component-like API, and is treated like a component
2536// in the compiler, but internally it's a special built-in type that hooks
2537// directly into the renderer.
2538const SuspenseImpl = {
2539 name: 'Suspense',
2540 // In order to make Suspense tree-shakable, we need to avoid importing it
2541 // directly in the renderer. The renderer checks for the __isSuspense flag
2542 // on a vnode's type and calls the `process` method, passing in renderer
2543 // internals.
2544 __isSuspense: true,
2545 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2546 // platform-specific impl passed from renderer
2547 rendererInternals) {
2548 if (n1 == null) {
2549 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2550 }
2551 else {
2552 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2553 }
2554 },
2555 hydrate: hydrateSuspense,
2556 create: createSuspenseBoundary,
2557 normalize: normalizeSuspenseChildren
2558};
2559// Force-casted public typing for h and TSX props inference
2560const Suspense = (SuspenseImpl );
2561function triggerEvent(vnode, name) {
2562 const eventListener = vnode.props && vnode.props[name];
2563 if (isFunction(eventListener)) {
2564 eventListener();
2565 }
2566}
2567function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2568 const { p: patch, o: { createElement } } = rendererInternals;
2569 const hiddenContainer = createElement('div');
2570 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2571 // start mounting the content subtree in an off-dom container
2572 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2573 // now check if we have encountered any async deps
2574 if (suspense.deps > 0) {
2575 // has async
2576 // invoke @fallback event
2577 triggerEvent(vnode, 'onPending');
2578 triggerEvent(vnode, 'onFallback');
2579 // mount the fallback tree
2580 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2581 isSVG, slotScopeIds);
2582 setActiveBranch(suspense, vnode.ssFallback);
2583 }
2584 else {
2585 // Suspense has no async deps. Just resolve.
2586 suspense.resolve();
2587 }
2588}
2589function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2590 const suspense = (n2.suspense = n1.suspense);
2591 suspense.vnode = n2;
2592 n2.el = n1.el;
2593 const newBranch = n2.ssContent;
2594 const newFallback = n2.ssFallback;
2595 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2596 if (pendingBranch) {
2597 suspense.pendingBranch = newBranch;
2598 if (isSameVNodeType(newBranch, pendingBranch)) {
2599 // same root type but content may have changed.
2600 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2601 if (suspense.deps <= 0) {
2602 suspense.resolve();
2603 }
2604 else if (isInFallback) {
2605 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2606 isSVG, slotScopeIds, optimized);
2607 setActiveBranch(suspense, newFallback);
2608 }
2609 }
2610 else {
2611 // toggled before pending tree is resolved
2612 suspense.pendingId++;
2613 if (isHydrating) {
2614 // if toggled before hydration is finished, the current DOM tree is
2615 // no longer valid. set it as the active branch so it will be unmounted
2616 // when resolved
2617 suspense.isHydrating = false;
2618 suspense.activeBranch = pendingBranch;
2619 }
2620 else {
2621 unmount(pendingBranch, parentComponent, suspense);
2622 }
2623 // increment pending ID. this is used to invalidate async callbacks
2624 // reset suspense state
2625 suspense.deps = 0;
2626 // discard effects from pending branch
2627 suspense.effects.length = 0;
2628 // discard previous container
2629 suspense.hiddenContainer = createElement('div');
2630 if (isInFallback) {
2631 // already in fallback state
2632 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2633 if (suspense.deps <= 0) {
2634 suspense.resolve();
2635 }
2636 else {
2637 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2638 isSVG, slotScopeIds, optimized);
2639 setActiveBranch(suspense, newFallback);
2640 }
2641 }
2642 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2643 // toggled "back" to current active branch
2644 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2645 // force resolve
2646 suspense.resolve(true);
2647 }
2648 else {
2649 // switched to a 3rd branch
2650 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2651 if (suspense.deps <= 0) {
2652 suspense.resolve();
2653 }
2654 }
2655 }
2656 }
2657 else {
2658 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2659 // root did not change, just normal patch
2660 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2661 setActiveBranch(suspense, newBranch);
2662 }
2663 else {
2664 // root node toggled
2665 // invoke @pending event
2666 triggerEvent(n2, 'onPending');
2667 // mount pending branch in off-dom container
2668 suspense.pendingBranch = newBranch;
2669 suspense.pendingId++;
2670 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2671 if (suspense.deps <= 0) {
2672 // incoming branch has no async deps, resolve now.
2673 suspense.resolve();
2674 }
2675 else {
2676 const { timeout, pendingId } = suspense;
2677 if (timeout > 0) {
2678 setTimeout(() => {
2679 if (suspense.pendingId === pendingId) {
2680 suspense.fallback(newFallback);
2681 }
2682 }, timeout);
2683 }
2684 else if (timeout === 0) {
2685 suspense.fallback(newFallback);
2686 }
2687 }
2688 }
2689 }
2690}
2691let hasWarned = false;
2692function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2693 /* istanbul ignore if */
2694 if (!hasWarned) {
2695 hasWarned = true;
2696 // @ts-ignore `console.info` cannot be null error
2697 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2698 }
2699 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2700 const timeout = toNumber(vnode.props && vnode.props.timeout);
2701 const suspense = {
2702 vnode,
2703 parent,
2704 parentComponent,
2705 isSVG,
2706 container,
2707 hiddenContainer,
2708 anchor,
2709 deps: 0,
2710 pendingId: 0,
2711 timeout: typeof timeout === 'number' ? timeout : -1,
2712 activeBranch: null,
2713 pendingBranch: null,
2714 isInFallback: true,
2715 isHydrating,
2716 isUnmounted: false,
2717 effects: [],
2718 resolve(resume = false) {
2719 {
2720 if (!resume && !suspense.pendingBranch) {
2721 throw new Error(`suspense.resolve() is called without a pending branch.`);
2722 }
2723 if (suspense.isUnmounted) {
2724 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2725 }
2726 }
2727 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2728 if (suspense.isHydrating) {
2729 suspense.isHydrating = false;
2730 }
2731 else if (!resume) {
2732 const delayEnter = activeBranch &&
2733 pendingBranch.transition &&
2734 pendingBranch.transition.mode === 'out-in';
2735 if (delayEnter) {
2736 activeBranch.transition.afterLeave = () => {
2737 if (pendingId === suspense.pendingId) {
2738 move(pendingBranch, container, anchor, 0 /* ENTER */);
2739 }
2740 };
2741 }
2742 // this is initial anchor on mount
2743 let { anchor } = suspense;
2744 // unmount current active tree
2745 if (activeBranch) {
2746 // if the fallback tree was mounted, it may have been moved
2747 // as part of a parent suspense. get the latest anchor for insertion
2748 anchor = next(activeBranch);
2749 unmount(activeBranch, parentComponent, suspense, true);
2750 }
2751 if (!delayEnter) {
2752 // move content from off-dom container to actual container
2753 move(pendingBranch, container, anchor, 0 /* ENTER */);
2754 }
2755 }
2756 setActiveBranch(suspense, pendingBranch);
2757 suspense.pendingBranch = null;
2758 suspense.isInFallback = false;
2759 // flush buffered effects
2760 // check if there is a pending parent suspense
2761 let parent = suspense.parent;
2762 let hasUnresolvedAncestor = false;
2763 while (parent) {
2764 if (parent.pendingBranch) {
2765 // found a pending parent suspense, merge buffered post jobs
2766 // into that parent
2767 parent.effects.push(...effects);
2768 hasUnresolvedAncestor = true;
2769 break;
2770 }
2771 parent = parent.parent;
2772 }
2773 // no pending parent suspense, flush all jobs
2774 if (!hasUnresolvedAncestor) {
2775 queuePostFlushCb(effects);
2776 }
2777 suspense.effects = [];
2778 // invoke @resolve event
2779 triggerEvent(vnode, 'onResolve');
2780 },
2781 fallback(fallbackVNode) {
2782 if (!suspense.pendingBranch) {
2783 return;
2784 }
2785 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2786 // invoke @fallback event
2787 triggerEvent(vnode, 'onFallback');
2788 const anchor = next(activeBranch);
2789 const mountFallback = () => {
2790 if (!suspense.isInFallback) {
2791 return;
2792 }
2793 // mount the fallback tree
2794 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2795 isSVG, slotScopeIds, optimized);
2796 setActiveBranch(suspense, fallbackVNode);
2797 };
2798 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2799 if (delayEnter) {
2800 activeBranch.transition.afterLeave = mountFallback;
2801 }
2802 suspense.isInFallback = true;
2803 // unmount current active branch
2804 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2805 true // shouldRemove
2806 );
2807 if (!delayEnter) {
2808 mountFallback();
2809 }
2810 },
2811 move(container, anchor, type) {
2812 suspense.activeBranch &&
2813 move(suspense.activeBranch, container, anchor, type);
2814 suspense.container = container;
2815 },
2816 next() {
2817 return suspense.activeBranch && next(suspense.activeBranch);
2818 },
2819 registerDep(instance, setupRenderEffect) {
2820 const isInPendingSuspense = !!suspense.pendingBranch;
2821 if (isInPendingSuspense) {
2822 suspense.deps++;
2823 }
2824 const hydratedEl = instance.vnode.el;
2825 instance
2826 .asyncDep.catch(err => {
2827 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2828 })
2829 .then(asyncSetupResult => {
2830 // retry when the setup() promise resolves.
2831 // component may have been unmounted before resolve.
2832 if (instance.isUnmounted ||
2833 suspense.isUnmounted ||
2834 suspense.pendingId !== instance.suspenseId) {
2835 return;
2836 }
2837 // retry from this component
2838 instance.asyncResolved = true;
2839 const { vnode } = instance;
2840 {
2841 pushWarningContext(vnode);
2842 }
2843 handleSetupResult(instance, asyncSetupResult, false);
2844 if (hydratedEl) {
2845 // vnode may have been replaced if an update happened before the
2846 // async dep is resolved.
2847 vnode.el = hydratedEl;
2848 }
2849 const placeholder = !hydratedEl && instance.subTree.el;
2850 setupRenderEffect(instance, vnode,
2851 // component may have been moved before resolve.
2852 // if this is not a hydration, instance.subTree will be the comment
2853 // placeholder.
2854 parentNode(hydratedEl || instance.subTree.el),
2855 // anchor will not be used if this is hydration, so only need to
2856 // consider the comment placeholder case.
2857 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
2858 if (placeholder) {
2859 remove(placeholder);
2860 }
2861 updateHOCHostEl(instance, vnode.el);
2862 {
2863 popWarningContext();
2864 }
2865 // only decrease deps count if suspense is not already resolved
2866 if (isInPendingSuspense && --suspense.deps === 0) {
2867 suspense.resolve();
2868 }
2869 });
2870 },
2871 unmount(parentSuspense, doRemove) {
2872 suspense.isUnmounted = true;
2873 if (suspense.activeBranch) {
2874 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
2875 }
2876 if (suspense.pendingBranch) {
2877 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
2878 }
2879 }
2880 };
2881 return suspense;
2882}
2883function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
2884 /* eslint-disable no-restricted-globals */
2885 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
2886 // there are two possible scenarios for server-rendered suspense:
2887 // - success: ssr content should be fully resolved
2888 // - failure: ssr content should be the fallback branch.
2889 // however, on the client we don't really know if it has failed or not
2890 // attempt to hydrate the DOM assuming it has succeeded, but we still
2891 // need to construct a suspense boundary first
2892 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
2893 if (suspense.deps === 0) {
2894 suspense.resolve();
2895 }
2896 return result;
2897 /* eslint-enable no-restricted-globals */
2898}
2899function normalizeSuspenseChildren(vnode) {
2900 const { shapeFlag, children } = vnode;
2901 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
2902 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
2903 vnode.ssFallback = isSlotChildren
2904 ? normalizeSuspenseSlot(children.fallback)
2905 : createVNode(Comment);
2906}
2907function normalizeSuspenseSlot(s) {
2908 let block;
2909 if (isFunction(s)) {
2910 const isCompiledSlot = s._c;
2911 if (isCompiledSlot) {
2912 // disableTracking: false
2913 // allow block tracking for compiled slots
2914 // (see ./componentRenderContext.ts)
2915 s._d = false;
2916 openBlock();
2917 }
2918 s = s();
2919 if (isCompiledSlot) {
2920 s._d = true;
2921 block = currentBlock;
2922 closeBlock();
2923 }
2924 }
2925 if (isArray(s)) {
2926 const singleChild = filterSingleRoot(s);
2927 if (!singleChild) {
2928 warn$1(`<Suspense> slots expect a single root node.`);
2929 }
2930 s = singleChild;
2931 }
2932 s = normalizeVNode(s);
2933 if (block && !s.dynamicChildren) {
2934 s.dynamicChildren = block.filter(c => c !== s);
2935 }
2936 return s;
2937}
2938function queueEffectWithSuspense(fn, suspense) {
2939 if (suspense && suspense.pendingBranch) {
2940 if (isArray(fn)) {
2941 suspense.effects.push(...fn);
2942 }
2943 else {
2944 suspense.effects.push(fn);
2945 }
2946 }
2947 else {
2948 queuePostFlushCb(fn);
2949 }
2950}
2951function setActiveBranch(suspense, branch) {
2952 suspense.activeBranch = branch;
2953 const { vnode, parentComponent } = suspense;
2954 const el = (vnode.el = branch.el);
2955 // in case suspense is the root node of a component,
2956 // recursively update the HOC el
2957 if (parentComponent && parentComponent.subTree === vnode) {
2958 parentComponent.vnode.el = el;
2959 updateHOCHostEl(parentComponent, el);
2960 }
2961}
2962
2963function provide(key, value) {
2964 if (!currentInstance) {
2965 {
2966 warn$1(`provide() can only be used inside setup().`);
2967 }
2968 }
2969 else {
2970 let provides = currentInstance.provides;
2971 // by default an instance inherits its parent's provides object
2972 // but when it needs to provide values of its own, it creates its
2973 // own provides object using parent provides object as prototype.
2974 // this way in `inject` we can simply look up injections from direct
2975 // parent and let the prototype chain do the work.
2976 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
2977 if (parentProvides === provides) {
2978 provides = currentInstance.provides = Object.create(parentProvides);
2979 }
2980 // TS doesn't allow symbol as index type
2981 provides[key] = value;
2982 }
2983}
2984function inject(key, defaultValue, treatDefaultAsFactory = false) {
2985 // fallback to `currentRenderingInstance` so that this can be called in
2986 // a functional component
2987 const instance = currentInstance || currentRenderingInstance;
2988 if (instance) {
2989 // #2400
2990 // to support `app.use` plugins,
2991 // fallback to appContext's `provides` if the intance is at root
2992 const provides = instance.parent == null
2993 ? instance.vnode.appContext && instance.vnode.appContext.provides
2994 : instance.parent.provides;
2995 if (provides && key in provides) {
2996 // TS doesn't allow symbol as index type
2997 return provides[key];
2998 }
2999 else if (arguments.length > 1) {
3000 return treatDefaultAsFactory && isFunction(defaultValue)
3001 ? defaultValue.call(instance.proxy)
3002 : defaultValue;
3003 }
3004 else {
3005 warn$1(`injection "${String(key)}" not found.`);
3006 }
3007 }
3008 else {
3009 warn$1(`inject() can only be used inside setup() or functional components.`);
3010 }
3011}
3012
3013function useTransitionState() {
3014 const state = {
3015 isMounted: false,
3016 isLeaving: false,
3017 isUnmounting: false,
3018 leavingVNodes: new Map()
3019 };
3020 onMounted(() => {
3021 state.isMounted = true;
3022 });
3023 onBeforeUnmount(() => {
3024 state.isUnmounting = true;
3025 });
3026 return state;
3027}
3028const TransitionHookValidator = [Function, Array];
3029const BaseTransitionImpl = {
3030 name: `BaseTransition`,
3031 props: {
3032 mode: String,
3033 appear: Boolean,
3034 persisted: Boolean,
3035 // enter
3036 onBeforeEnter: TransitionHookValidator,
3037 onEnter: TransitionHookValidator,
3038 onAfterEnter: TransitionHookValidator,
3039 onEnterCancelled: TransitionHookValidator,
3040 // leave
3041 onBeforeLeave: TransitionHookValidator,
3042 onLeave: TransitionHookValidator,
3043 onAfterLeave: TransitionHookValidator,
3044 onLeaveCancelled: TransitionHookValidator,
3045 // appear
3046 onBeforeAppear: TransitionHookValidator,
3047 onAppear: TransitionHookValidator,
3048 onAfterAppear: TransitionHookValidator,
3049 onAppearCancelled: TransitionHookValidator
3050 },
3051 setup(props, { slots }) {
3052 const instance = getCurrentInstance();
3053 const state = useTransitionState();
3054 let prevTransitionKey;
3055 return () => {
3056 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3057 if (!children || !children.length) {
3058 return;
3059 }
3060 // warn multiple elements
3061 if (children.length > 1) {
3062 warn$1('<transition> can only be used on a single element or component. Use ' +
3063 '<transition-group> for lists.');
3064 }
3065 // there's no need to track reactivity for these props so use the raw
3066 // props for a bit better perf
3067 const rawProps = toRaw(props);
3068 const { mode } = rawProps;
3069 // check mode
3070 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3071 warn$1(`invalid <transition> mode: ${mode}`);
3072 }
3073 // at this point children has a guaranteed length of 1.
3074 const child = children[0];
3075 if (state.isLeaving) {
3076 return emptyPlaceholder(child);
3077 }
3078 // in the case of <transition><keep-alive/></transition>, we need to
3079 // compare the type of the kept-alive children.
3080 const innerChild = getKeepAliveChild(child);
3081 if (!innerChild) {
3082 return emptyPlaceholder(child);
3083 }
3084 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3085 setTransitionHooks(innerChild, enterHooks);
3086 const oldChild = instance.subTree;
3087 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3088 let transitionKeyChanged = false;
3089 const { getTransitionKey } = innerChild.type;
3090 if (getTransitionKey) {
3091 const key = getTransitionKey();
3092 if (prevTransitionKey === undefined) {
3093 prevTransitionKey = key;
3094 }
3095 else if (key !== prevTransitionKey) {
3096 prevTransitionKey = key;
3097 transitionKeyChanged = true;
3098 }
3099 }
3100 // handle mode
3101 if (oldInnerChild &&
3102 oldInnerChild.type !== Comment &&
3103 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3104 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3105 // update old tree's hooks in case of dynamic transition
3106 setTransitionHooks(oldInnerChild, leavingHooks);
3107 // switching between different views
3108 if (mode === 'out-in') {
3109 state.isLeaving = true;
3110 // return placeholder node and queue update when leave finishes
3111 leavingHooks.afterLeave = () => {
3112 state.isLeaving = false;
3113 instance.update();
3114 };
3115 return emptyPlaceholder(child);
3116 }
3117 else if (mode === 'in-out' && innerChild.type !== Comment) {
3118 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3119 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3120 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3121 // early removal callback
3122 el._leaveCb = () => {
3123 earlyRemove();
3124 el._leaveCb = undefined;
3125 delete enterHooks.delayedLeave;
3126 };
3127 enterHooks.delayedLeave = delayedLeave;
3128 };
3129 }
3130 }
3131 return child;
3132 };
3133 }
3134};
3135// export the public type for h/tsx inference
3136// also to avoid inline import() in generated d.ts files
3137const BaseTransition = BaseTransitionImpl;
3138function getLeavingNodesForType(state, vnode) {
3139 const { leavingVNodes } = state;
3140 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3141 if (!leavingVNodesCache) {
3142 leavingVNodesCache = Object.create(null);
3143 leavingVNodes.set(vnode.type, leavingVNodesCache);
3144 }
3145 return leavingVNodesCache;
3146}
3147// The transition hooks are attached to the vnode as vnode.transition
3148// and will be called at appropriate timing in the renderer.
3149function resolveTransitionHooks(vnode, props, state, instance) {
3150 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3151 const key = String(vnode.key);
3152 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3153 const callHook = (hook, args) => {
3154 hook &&
3155 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3156 };
3157 const hooks = {
3158 mode,
3159 persisted,
3160 beforeEnter(el) {
3161 let hook = onBeforeEnter;
3162 if (!state.isMounted) {
3163 if (appear) {
3164 hook = onBeforeAppear || onBeforeEnter;
3165 }
3166 else {
3167 return;
3168 }
3169 }
3170 // for same element (v-show)
3171 if (el._leaveCb) {
3172 el._leaveCb(true /* cancelled */);
3173 }
3174 // for toggled element with same key (v-if)
3175 const leavingVNode = leavingVNodesCache[key];
3176 if (leavingVNode &&
3177 isSameVNodeType(vnode, leavingVNode) &&
3178 leavingVNode.el._leaveCb) {
3179 // force early removal (not cancelled)
3180 leavingVNode.el._leaveCb();
3181 }
3182 callHook(hook, [el]);
3183 },
3184 enter(el) {
3185 let hook = onEnter;
3186 let afterHook = onAfterEnter;
3187 let cancelHook = onEnterCancelled;
3188 if (!state.isMounted) {
3189 if (appear) {
3190 hook = onAppear || onEnter;
3191 afterHook = onAfterAppear || onAfterEnter;
3192 cancelHook = onAppearCancelled || onEnterCancelled;
3193 }
3194 else {
3195 return;
3196 }
3197 }
3198 let called = false;
3199 const done = (el._enterCb = (cancelled) => {
3200 if (called)
3201 return;
3202 called = true;
3203 if (cancelled) {
3204 callHook(cancelHook, [el]);
3205 }
3206 else {
3207 callHook(afterHook, [el]);
3208 }
3209 if (hooks.delayedLeave) {
3210 hooks.delayedLeave();
3211 }
3212 el._enterCb = undefined;
3213 });
3214 if (hook) {
3215 hook(el, done);
3216 if (hook.length <= 1) {
3217 done();
3218 }
3219 }
3220 else {
3221 done();
3222 }
3223 },
3224 leave(el, remove) {
3225 const key = String(vnode.key);
3226 if (el._enterCb) {
3227 el._enterCb(true /* cancelled */);
3228 }
3229 if (state.isUnmounting) {
3230 return remove();
3231 }
3232 callHook(onBeforeLeave, [el]);
3233 let called = false;
3234 const done = (el._leaveCb = (cancelled) => {
3235 if (called)
3236 return;
3237 called = true;
3238 remove();
3239 if (cancelled) {
3240 callHook(onLeaveCancelled, [el]);
3241 }
3242 else {
3243 callHook(onAfterLeave, [el]);
3244 }
3245 el._leaveCb = undefined;
3246 if (leavingVNodesCache[key] === vnode) {
3247 delete leavingVNodesCache[key];
3248 }
3249 });
3250 leavingVNodesCache[key] = vnode;
3251 if (onLeave) {
3252 onLeave(el, done);
3253 if (onLeave.length <= 1) {
3254 done();
3255 }
3256 }
3257 else {
3258 done();
3259 }
3260 },
3261 clone(vnode) {
3262 return resolveTransitionHooks(vnode, props, state, instance);
3263 }
3264 };
3265 return hooks;
3266}
3267// the placeholder really only handles one special case: KeepAlive
3268// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3269// placeholder with empty content to avoid the KeepAlive instance from being
3270// unmounted.
3271function emptyPlaceholder(vnode) {
3272 if (isKeepAlive(vnode)) {
3273 vnode = cloneVNode(vnode);
3274 vnode.children = null;
3275 return vnode;
3276 }
3277}
3278function getKeepAliveChild(vnode) {
3279 return isKeepAlive(vnode)
3280 ? vnode.children
3281 ? vnode.children[0]
3282 : undefined
3283 : vnode;
3284}
3285function setTransitionHooks(vnode, hooks) {
3286 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3287 setTransitionHooks(vnode.component.subTree, hooks);
3288 }
3289 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3290 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3291 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3292 }
3293 else {
3294 vnode.transition = hooks;
3295 }
3296}
3297function getTransitionRawChildren(children, keepComment = false) {
3298 let ret = [];
3299 let keyedFragmentCount = 0;
3300 for (let i = 0; i < children.length; i++) {
3301 const child = children[i];
3302 // handle fragment children case, e.g. v-for
3303 if (child.type === Fragment) {
3304 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3305 keyedFragmentCount++;
3306 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3307 }
3308 // comment placeholders should be skipped, e.g. v-if
3309 else if (keepComment || child.type !== Comment) {
3310 ret.push(child);
3311 }
3312 }
3313 // #1126 if a transition children list contains multiple sub fragments, these
3314 // fragments will be merged into a flat children array. Since each v-for
3315 // fragment may contain different static bindings inside, we need to de-op
3316 // these children to force full diffs to ensure correct behavior.
3317 if (keyedFragmentCount > 1) {
3318 for (let i = 0; i < ret.length; i++) {
3319 ret[i].patchFlag = -2 /* BAIL */;
3320 }
3321 }
3322 return ret;
3323}
3324
3325// implementation, close to no-op
3326function defineComponent(options) {
3327 return isFunction(options) ? { setup: options, name: options.name } : options;
3328}
3329
3330const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3331function defineAsyncComponent(source) {
3332 if (isFunction(source)) {
3333 source = { loader: source };
3334 }
3335 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3336 suspensible = true, onError: userOnError } = source;
3337 let pendingRequest = null;
3338 let resolvedComp;
3339 let retries = 0;
3340 const retry = () => {
3341 retries++;
3342 pendingRequest = null;
3343 return load();
3344 };
3345 const load = () => {
3346 let thisRequest;
3347 return (pendingRequest ||
3348 (thisRequest = pendingRequest =
3349 loader()
3350 .catch(err => {
3351 err = err instanceof Error ? err : new Error(String(err));
3352 if (userOnError) {
3353 return new Promise((resolve, reject) => {
3354 const userRetry = () => resolve(retry());
3355 const userFail = () => reject(err);
3356 userOnError(err, userRetry, userFail, retries + 1);
3357 });
3358 }
3359 else {
3360 throw err;
3361 }
3362 })
3363 .then((comp) => {
3364 if (thisRequest !== pendingRequest && pendingRequest) {
3365 return pendingRequest;
3366 }
3367 if (!comp) {
3368 warn$1(`Async component loader resolved to undefined. ` +
3369 `If you are using retry(), make sure to return its return value.`);
3370 }
3371 // interop module default
3372 if (comp &&
3373 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3374 comp = comp.default;
3375 }
3376 if (comp && !isObject(comp) && !isFunction(comp)) {
3377 throw new Error(`Invalid async component load result: ${comp}`);
3378 }
3379 resolvedComp = comp;
3380 return comp;
3381 })));
3382 };
3383 return defineComponent({
3384 name: 'AsyncComponentWrapper',
3385 __asyncLoader: load,
3386 get __asyncResolved() {
3387 return resolvedComp;
3388 },
3389 setup() {
3390 const instance = currentInstance;
3391 // already resolved
3392 if (resolvedComp) {
3393 return () => createInnerComp(resolvedComp, instance);
3394 }
3395 const onError = (err) => {
3396 pendingRequest = null;
3397 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3398 };
3399 // suspense-controlled or SSR.
3400 if ((suspensible && instance.suspense) ||
3401 (false )) {
3402 return load()
3403 .then(comp => {
3404 return () => createInnerComp(comp, instance);
3405 })
3406 .catch(err => {
3407 onError(err);
3408 return () => errorComponent
3409 ? createVNode(errorComponent, {
3410 error: err
3411 })
3412 : null;
3413 });
3414 }
3415 const loaded = ref(false);
3416 const error = ref();
3417 const delayed = ref(!!delay);
3418 if (delay) {
3419 setTimeout(() => {
3420 delayed.value = false;
3421 }, delay);
3422 }
3423 if (timeout != null) {
3424 setTimeout(() => {
3425 if (!loaded.value && !error.value) {
3426 const err = new Error(`Async component timed out after ${timeout}ms.`);
3427 onError(err);
3428 error.value = err;
3429 }
3430 }, timeout);
3431 }
3432 load()
3433 .then(() => {
3434 loaded.value = true;
3435 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3436 // parent is keep-alive, force update so the loaded component's
3437 // name is taken into account
3438 queueJob(instance.parent.update);
3439 }
3440 })
3441 .catch(err => {
3442 onError(err);
3443 error.value = err;
3444 });
3445 return () => {
3446 if (loaded.value && resolvedComp) {
3447 return createInnerComp(resolvedComp, instance);
3448 }
3449 else if (error.value && errorComponent) {
3450 return createVNode(errorComponent, {
3451 error: error.value
3452 });
3453 }
3454 else if (loadingComponent && !delayed.value) {
3455 return createVNode(loadingComponent);
3456 }
3457 };
3458 }
3459 });
3460}
3461function createInnerComp(comp, { vnode: { ref, props, children } }) {
3462 const vnode = createVNode(comp, props, children);
3463 // ensure inner component inherits the async wrapper's ref owner
3464 vnode.ref = ref;
3465 return vnode;
3466}
3467
3468const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3469const KeepAliveImpl = {
3470 name: `KeepAlive`,
3471 // Marker for special handling inside the renderer. We are not using a ===
3472 // check directly on KeepAlive in the renderer, because importing it directly
3473 // would prevent it from being tree-shaken.
3474 __isKeepAlive: true,
3475 props: {
3476 include: [String, RegExp, Array],
3477 exclude: [String, RegExp, Array],
3478 max: [String, Number]
3479 },
3480 setup(props, { slots }) {
3481 const instance = getCurrentInstance();
3482 // KeepAlive communicates with the instantiated renderer via the
3483 // ctx where the renderer passes in its internals,
3484 // and the KeepAlive instance exposes activate/deactivate implementations.
3485 // The whole point of this is to avoid importing KeepAlive directly in the
3486 // renderer to facilitate tree-shaking.
3487 const sharedContext = instance.ctx;
3488 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3489 // for KeepAlive, we just need to render its children
3490 if (!sharedContext.renderer) {
3491 return slots.default;
3492 }
3493 const cache = new Map();
3494 const keys = new Set();
3495 let current = null;
3496 {
3497 instance.__v_cache = cache;
3498 }
3499 const parentSuspense = instance.suspense;
3500 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3501 const storageContainer = createElement('div');
3502 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3503 const instance = vnode.component;
3504 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3505 // in case props have changed
3506 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3507 queuePostRenderEffect(() => {
3508 instance.isDeactivated = false;
3509 if (instance.a) {
3510 invokeArrayFns(instance.a);
3511 }
3512 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3513 if (vnodeHook) {
3514 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3515 }
3516 }, parentSuspense);
3517 {
3518 // Update components tree
3519 devtoolsComponentAdded(instance);
3520 }
3521 };
3522 sharedContext.deactivate = (vnode) => {
3523 const instance = vnode.component;
3524 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3525 queuePostRenderEffect(() => {
3526 if (instance.da) {
3527 invokeArrayFns(instance.da);
3528 }
3529 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3530 if (vnodeHook) {
3531 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3532 }
3533 instance.isDeactivated = true;
3534 }, parentSuspense);
3535 {
3536 // Update components tree
3537 devtoolsComponentAdded(instance);
3538 }
3539 };
3540 function unmount(vnode) {
3541 // reset the shapeFlag so it can be properly unmounted
3542 resetShapeFlag(vnode);
3543 _unmount(vnode, instance, parentSuspense);
3544 }
3545 function pruneCache(filter) {
3546 cache.forEach((vnode, key) => {
3547 const name = getComponentName(vnode.type);
3548 if (name && (!filter || !filter(name))) {
3549 pruneCacheEntry(key);
3550 }
3551 });
3552 }
3553 function pruneCacheEntry(key) {
3554 const cached = cache.get(key);
3555 if (!current || cached.type !== current.type) {
3556 unmount(cached);
3557 }
3558 else if (current) {
3559 // current active instance should no longer be kept-alive.
3560 // we can't unmount it now but it might be later, so reset its flag now.
3561 resetShapeFlag(current);
3562 }
3563 cache.delete(key);
3564 keys.delete(key);
3565 }
3566 // prune cache on include/exclude prop change
3567 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3568 include && pruneCache(name => matches(include, name));
3569 exclude && pruneCache(name => !matches(exclude, name));
3570 },
3571 // prune post-render after `current` has been updated
3572 { flush: 'post', deep: true });
3573 // cache sub tree after render
3574 let pendingCacheKey = null;
3575 const cacheSubtree = () => {
3576 // fix #1621, the pendingCacheKey could be 0
3577 if (pendingCacheKey != null) {
3578 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3579 }
3580 };
3581 onMounted(cacheSubtree);
3582 onUpdated(cacheSubtree);
3583 onBeforeUnmount(() => {
3584 cache.forEach(cached => {
3585 const { subTree, suspense } = instance;
3586 const vnode = getInnerChild(subTree);
3587 if (cached.type === vnode.type) {
3588 // current instance will be unmounted as part of keep-alive's unmount
3589 resetShapeFlag(vnode);
3590 // but invoke its deactivated hook here
3591 const da = vnode.component.da;
3592 da && queuePostRenderEffect(da, suspense);
3593 return;
3594 }
3595 unmount(cached);
3596 });
3597 });
3598 return () => {
3599 pendingCacheKey = null;
3600 if (!slots.default) {
3601 return null;
3602 }
3603 const children = slots.default();
3604 const rawVNode = children[0];
3605 if (children.length > 1) {
3606 {
3607 warn$1(`KeepAlive should contain exactly one component child.`);
3608 }
3609 current = null;
3610 return children;
3611 }
3612 else if (!isVNode(rawVNode) ||
3613 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3614 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3615 current = null;
3616 return rawVNode;
3617 }
3618 let vnode = getInnerChild(rawVNode);
3619 const comp = vnode.type;
3620 // for async components, name check should be based in its loaded
3621 // inner component if available
3622 const name = getComponentName(isAsyncWrapper(vnode)
3623 ? vnode.type.__asyncResolved || {}
3624 : comp);
3625 const { include, exclude, max } = props;
3626 if ((include && (!name || !matches(include, name))) ||
3627 (exclude && name && matches(exclude, name))) {
3628 current = vnode;
3629 return rawVNode;
3630 }
3631 const key = vnode.key == null ? comp : vnode.key;
3632 const cachedVNode = cache.get(key);
3633 // clone vnode if it's reused because we are going to mutate it
3634 if (vnode.el) {
3635 vnode = cloneVNode(vnode);
3636 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
3637 rawVNode.ssContent = vnode;
3638 }
3639 }
3640 // #1513 it's possible for the returned vnode to be cloned due to attr
3641 // fallthrough or scopeId, so the vnode here may not be the final vnode
3642 // that is mounted. Instead of caching it directly, we store the pending
3643 // key and cache `instance.subTree` (the normalized vnode) in
3644 // beforeMount/beforeUpdate hooks.
3645 pendingCacheKey = key;
3646 if (cachedVNode) {
3647 // copy over mounted state
3648 vnode.el = cachedVNode.el;
3649 vnode.component = cachedVNode.component;
3650 if (vnode.transition) {
3651 // recursively update transition hooks on subTree
3652 setTransitionHooks(vnode, vnode.transition);
3653 }
3654 // avoid vnode being mounted as fresh
3655 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
3656 // make this key the freshest
3657 keys.delete(key);
3658 keys.add(key);
3659 }
3660 else {
3661 keys.add(key);
3662 // prune oldest entry
3663 if (max && keys.size > parseInt(max, 10)) {
3664 pruneCacheEntry(keys.values().next().value);
3665 }
3666 }
3667 // avoid vnode being unmounted
3668 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3669 current = vnode;
3670 return rawVNode;
3671 };
3672 }
3673};
3674// export the public type for h/tsx inference
3675// also to avoid inline import() in generated d.ts files
3676const KeepAlive = KeepAliveImpl;
3677function matches(pattern, name) {
3678 if (isArray(pattern)) {
3679 return pattern.some((p) => matches(p, name));
3680 }
3681 else if (isString(pattern)) {
3682 return pattern.split(',').indexOf(name) > -1;
3683 }
3684 else if (pattern.test) {
3685 return pattern.test(name);
3686 }
3687 /* istanbul ignore next */
3688 return false;
3689}
3690function onActivated(hook, target) {
3691 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
3692}
3693function onDeactivated(hook, target) {
3694 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
3695}
3696function registerKeepAliveHook(hook, type, target = currentInstance) {
3697 // cache the deactivate branch check wrapper for injected hooks so the same
3698 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
3699 // deactivation check".
3700 const wrappedHook = hook.__wdc ||
3701 (hook.__wdc = () => {
3702 // only fire the hook if the target instance is NOT in a deactivated branch.
3703 let current = target;
3704 while (current) {
3705 if (current.isDeactivated) {
3706 return;
3707 }
3708 current = current.parent;
3709 }
3710 hook();
3711 });
3712 injectHook(type, wrappedHook, target);
3713 // In addition to registering it on the target instance, we walk up the parent
3714 // chain and register it on all ancestor instances that are keep-alive roots.
3715 // This avoids the need to walk the entire component tree when invoking these
3716 // hooks, and more importantly, avoids the need to track child components in
3717 // arrays.
3718 if (target) {
3719 let current = target.parent;
3720 while (current && current.parent) {
3721 if (isKeepAlive(current.parent.vnode)) {
3722 injectToKeepAliveRoot(wrappedHook, type, target, current);
3723 }
3724 current = current.parent;
3725 }
3726 }
3727}
3728function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
3729 // injectHook wraps the original for error handling, so make sure to remove
3730 // the wrapped version.
3731 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
3732 onUnmounted(() => {
3733 remove(keepAliveRoot[type], injected);
3734 }, target);
3735}
3736function resetShapeFlag(vnode) {
3737 let shapeFlag = vnode.shapeFlag;
3738 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
3739 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3740 }
3741 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
3742 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
3743 }
3744 vnode.shapeFlag = shapeFlag;
3745}
3746function getInnerChild(vnode) {
3747 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
3748}
3749
3750function injectHook(type, hook, target = currentInstance, prepend = false) {
3751 if (target) {
3752 const hooks = target[type] || (target[type] = []);
3753 // cache the error handling wrapper for injected hooks so the same hook
3754 // can be properly deduped by the scheduler. "__weh" stands for "with error
3755 // handling".
3756 const wrappedHook = hook.__weh ||
3757 (hook.__weh = (...args) => {
3758 if (target.isUnmounted) {
3759 return;
3760 }
3761 // disable tracking inside all lifecycle hooks
3762 // since they can potentially be called inside effects.
3763 pauseTracking();
3764 // Set currentInstance during hook invocation.
3765 // This assumes the hook does not synchronously trigger other hooks, which
3766 // can only be false when the user does something really funky.
3767 setCurrentInstance(target);
3768 const res = callWithAsyncErrorHandling(hook, target, type, args);
3769 unsetCurrentInstance();
3770 resetTracking();
3771 return res;
3772 });
3773 if (prepend) {
3774 hooks.unshift(wrappedHook);
3775 }
3776 else {
3777 hooks.push(wrappedHook);
3778 }
3779 return wrappedHook;
3780 }
3781 else {
3782 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
3783 warn$1(`${apiName} is called when there is no active component instance to be ` +
3784 `associated with. ` +
3785 `Lifecycle injection APIs can only be used during execution of setup().` +
3786 (` If you are using async setup(), make sure to register lifecycle ` +
3787 `hooks before the first await statement.`
3788 ));
3789 }
3790}
3791const createHook = (lifecycle) => (hook, target = currentInstance) =>
3792// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
3793(!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
3794 injectHook(lifecycle, hook, target);
3795const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
3796const onMounted = createHook("m" /* MOUNTED */);
3797const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
3798const onUpdated = createHook("u" /* UPDATED */);
3799const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
3800const onUnmounted = createHook("um" /* UNMOUNTED */);
3801const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
3802const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
3803const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
3804function onErrorCaptured(hook, target = currentInstance) {
3805 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
3806}
3807
3808function createDuplicateChecker() {
3809 const cache = Object.create(null);
3810 return (type, key) => {
3811 if (cache[key]) {
3812 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
3813 }
3814 else {
3815 cache[key] = type;
3816 }
3817 };
3818}
3819let shouldCacheAccess = true;
3820function applyOptions(instance) {
3821 const options = resolveMergedOptions(instance);
3822 const publicThis = instance.proxy;
3823 const ctx = instance.ctx;
3824 // do not cache property access on public proxy during state initialization
3825 shouldCacheAccess = false;
3826 // call beforeCreate first before accessing other options since
3827 // the hook may mutate resolved options (#2791)
3828 if (options.beforeCreate) {
3829 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
3830 }
3831 const {
3832 // state
3833 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
3834 // lifecycle
3835 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
3836 // public API
3837 expose, inheritAttrs,
3838 // assets
3839 components, directives, filters } = options;
3840 const checkDuplicateProperties = createDuplicateChecker() ;
3841 {
3842 const [propsOptions] = instance.propsOptions;
3843 if (propsOptions) {
3844 for (const key in propsOptions) {
3845 checkDuplicateProperties("Props" /* PROPS */, key);
3846 }
3847 }
3848 }
3849 // options initialization order (to be consistent with Vue 2):
3850 // - props (already done outside of this function)
3851 // - inject
3852 // - methods
3853 // - data (deferred since it relies on `this` access)
3854 // - computed
3855 // - watch (deferred since it relies on `this` access)
3856 if (injectOptions) {
3857 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
3858 }
3859 if (methods) {
3860 for (const key in methods) {
3861 const methodHandler = methods[key];
3862 if (isFunction(methodHandler)) {
3863 // In dev mode, we use the `createRenderContext` function to define
3864 // methods to the proxy target, and those are read-only but
3865 // reconfigurable, so it needs to be redefined here
3866 {
3867 Object.defineProperty(ctx, key, {
3868 value: methodHandler.bind(publicThis),
3869 configurable: true,
3870 enumerable: true,
3871 writable: true
3872 });
3873 }
3874 {
3875 checkDuplicateProperties("Methods" /* METHODS */, key);
3876 }
3877 }
3878 else {
3879 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
3880 `Did you reference the function correctly?`);
3881 }
3882 }
3883 }
3884 if (dataOptions) {
3885 if (!isFunction(dataOptions)) {
3886 warn$1(`The data option must be a function. ` +
3887 `Plain object usage is no longer supported.`);
3888 }
3889 const data = dataOptions.call(publicThis, publicThis);
3890 if (isPromise(data)) {
3891 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
3892 `intend to perform data fetching before component renders, use ` +
3893 `async setup() + <Suspense>.`);
3894 }
3895 if (!isObject(data)) {
3896 warn$1(`data() should return an object.`);
3897 }
3898 else {
3899 instance.data = reactive(data);
3900 {
3901 for (const key in data) {
3902 checkDuplicateProperties("Data" /* DATA */, key);
3903 // expose data on ctx during dev
3904 if (key[0] !== '$' && key[0] !== '_') {
3905 Object.defineProperty(ctx, key, {
3906 configurable: true,
3907 enumerable: true,
3908 get: () => data[key],
3909 set: NOOP
3910 });
3911 }
3912 }
3913 }
3914 }
3915 }
3916 // state initialization complete at this point - start caching access
3917 shouldCacheAccess = true;
3918 if (computedOptions) {
3919 for (const key in computedOptions) {
3920 const opt = computedOptions[key];
3921 const get = isFunction(opt)
3922 ? opt.bind(publicThis, publicThis)
3923 : isFunction(opt.get)
3924 ? opt.get.bind(publicThis, publicThis)
3925 : NOOP;
3926 if (get === NOOP) {
3927 warn$1(`Computed property "${key}" has no getter.`);
3928 }
3929 const set = !isFunction(opt) && isFunction(opt.set)
3930 ? opt.set.bind(publicThis)
3931 : () => {
3932 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
3933 }
3934 ;
3935 const c = computed({
3936 get,
3937 set
3938 });
3939 Object.defineProperty(ctx, key, {
3940 enumerable: true,
3941 configurable: true,
3942 get: () => c.value,
3943 set: v => (c.value = v)
3944 });
3945 {
3946 checkDuplicateProperties("Computed" /* COMPUTED */, key);
3947 }
3948 }
3949 }
3950 if (watchOptions) {
3951 for (const key in watchOptions) {
3952 createWatcher(watchOptions[key], ctx, publicThis, key);
3953 }
3954 }
3955 if (provideOptions) {
3956 const provides = isFunction(provideOptions)
3957 ? provideOptions.call(publicThis)
3958 : provideOptions;
3959 Reflect.ownKeys(provides).forEach(key => {
3960 provide(key, provides[key]);
3961 });
3962 }
3963 if (created) {
3964 callHook(created, instance, "c" /* CREATED */);
3965 }
3966 function registerLifecycleHook(register, hook) {
3967 if (isArray(hook)) {
3968 hook.forEach(_hook => register(_hook.bind(publicThis)));
3969 }
3970 else if (hook) {
3971 register(hook.bind(publicThis));
3972 }
3973 }
3974 registerLifecycleHook(onBeforeMount, beforeMount);
3975 registerLifecycleHook(onMounted, mounted);
3976 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
3977 registerLifecycleHook(onUpdated, updated);
3978 registerLifecycleHook(onActivated, activated);
3979 registerLifecycleHook(onDeactivated, deactivated);
3980 registerLifecycleHook(onErrorCaptured, errorCaptured);
3981 registerLifecycleHook(onRenderTracked, renderTracked);
3982 registerLifecycleHook(onRenderTriggered, renderTriggered);
3983 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
3984 registerLifecycleHook(onUnmounted, unmounted);
3985 registerLifecycleHook(onServerPrefetch, serverPrefetch);
3986 if (isArray(expose)) {
3987 if (expose.length) {
3988 const exposed = instance.exposed || (instance.exposed = {});
3989 expose.forEach(key => {
3990 Object.defineProperty(exposed, key, {
3991 get: () => publicThis[key],
3992 set: val => (publicThis[key] = val)
3993 });
3994 });
3995 }
3996 else if (!instance.exposed) {
3997 instance.exposed = {};
3998 }
3999 }
4000 // options that are handled when creating the instance but also need to be
4001 // applied from mixins
4002 if (render && instance.render === NOOP) {
4003 instance.render = render;
4004 }
4005 if (inheritAttrs != null) {
4006 instance.inheritAttrs = inheritAttrs;
4007 }
4008 // asset options.
4009 if (components)
4010 instance.components = components;
4011 if (directives)
4012 instance.directives = directives;
4013}
4014function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4015 if (isArray(injectOptions)) {
4016 injectOptions = normalizeInject(injectOptions);
4017 }
4018 for (const key in injectOptions) {
4019 const opt = injectOptions[key];
4020 let injected;
4021 if (isObject(opt)) {
4022 if ('default' in opt) {
4023 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4024 }
4025 else {
4026 injected = inject(opt.from || key);
4027 }
4028 }
4029 else {
4030 injected = inject(opt);
4031 }
4032 if (isRef(injected)) {
4033 // TODO remove the check in 3.3
4034 if (unwrapRef) {
4035 Object.defineProperty(ctx, key, {
4036 enumerable: true,
4037 configurable: true,
4038 get: () => injected.value,
4039 set: v => (injected.value = v)
4040 });
4041 }
4042 else {
4043 {
4044 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4045 `and no longer needs \`.value\` in the next minor release. ` +
4046 `To opt-in to the new behavior now, ` +
4047 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4048 `temporary and will not be needed in the future.)`);
4049 }
4050 ctx[key] = injected;
4051 }
4052 }
4053 else {
4054 ctx[key] = injected;
4055 }
4056 {
4057 checkDuplicateProperties("Inject" /* INJECT */, key);
4058 }
4059 }
4060}
4061function callHook(hook, instance, type) {
4062 callWithAsyncErrorHandling(isArray(hook)
4063 ? hook.map(h => h.bind(instance.proxy))
4064 : hook.bind(instance.proxy), instance, type);
4065}
4066function createWatcher(raw, ctx, publicThis, key) {
4067 const getter = key.includes('.')
4068 ? createPathGetter(publicThis, key)
4069 : () => publicThis[key];
4070 if (isString(raw)) {
4071 const handler = ctx[raw];
4072 if (isFunction(handler)) {
4073 watch(getter, handler);
4074 }
4075 else {
4076 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4077 }
4078 }
4079 else if (isFunction(raw)) {
4080 watch(getter, raw.bind(publicThis));
4081 }
4082 else if (isObject(raw)) {
4083 if (isArray(raw)) {
4084 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4085 }
4086 else {
4087 const handler = isFunction(raw.handler)
4088 ? raw.handler.bind(publicThis)
4089 : ctx[raw.handler];
4090 if (isFunction(handler)) {
4091 watch(getter, handler, raw);
4092 }
4093 else {
4094 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4095 }
4096 }
4097 }
4098 else {
4099 warn$1(`Invalid watch option: "${key}"`, raw);
4100 }
4101}
4102/**
4103 * Resolve merged options and cache it on the component.
4104 * This is done only once per-component since the merging does not involve
4105 * instances.
4106 */
4107function resolveMergedOptions(instance) {
4108 const base = instance.type;
4109 const { mixins, extends: extendsOptions } = base;
4110 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4111 const cached = cache.get(base);
4112 let resolved;
4113 if (cached) {
4114 resolved = cached;
4115 }
4116 else if (!globalMixins.length && !mixins && !extendsOptions) {
4117 {
4118 resolved = base;
4119 }
4120 }
4121 else {
4122 resolved = {};
4123 if (globalMixins.length) {
4124 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4125 }
4126 mergeOptions(resolved, base, optionMergeStrategies);
4127 }
4128 cache.set(base, resolved);
4129 return resolved;
4130}
4131function mergeOptions(to, from, strats, asMixin = false) {
4132 const { mixins, extends: extendsOptions } = from;
4133 if (extendsOptions) {
4134 mergeOptions(to, extendsOptions, strats, true);
4135 }
4136 if (mixins) {
4137 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4138 }
4139 for (const key in from) {
4140 if (asMixin && key === 'expose') {
4141 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4142 `It should only be declared in the base component itself.`);
4143 }
4144 else {
4145 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4146 to[key] = strat ? strat(to[key], from[key]) : from[key];
4147 }
4148 }
4149 return to;
4150}
4151const internalOptionMergeStrats = {
4152 data: mergeDataFn,
4153 props: mergeObjectOptions,
4154 emits: mergeObjectOptions,
4155 // objects
4156 methods: mergeObjectOptions,
4157 computed: mergeObjectOptions,
4158 // lifecycle
4159 beforeCreate: mergeAsArray,
4160 created: mergeAsArray,
4161 beforeMount: mergeAsArray,
4162 mounted: mergeAsArray,
4163 beforeUpdate: mergeAsArray,
4164 updated: mergeAsArray,
4165 beforeDestroy: mergeAsArray,
4166 beforeUnmount: mergeAsArray,
4167 destroyed: mergeAsArray,
4168 unmounted: mergeAsArray,
4169 activated: mergeAsArray,
4170 deactivated: mergeAsArray,
4171 errorCaptured: mergeAsArray,
4172 serverPrefetch: mergeAsArray,
4173 // assets
4174 components: mergeObjectOptions,
4175 directives: mergeObjectOptions,
4176 // watch
4177 watch: mergeWatchOptions,
4178 // provide / inject
4179 provide: mergeDataFn,
4180 inject: mergeInject
4181};
4182function mergeDataFn(to, from) {
4183 if (!from) {
4184 return to;
4185 }
4186 if (!to) {
4187 return from;
4188 }
4189 return function mergedDataFn() {
4190 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4191 };
4192}
4193function mergeInject(to, from) {
4194 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4195}
4196function normalizeInject(raw) {
4197 if (isArray(raw)) {
4198 const res = {};
4199 for (let i = 0; i < raw.length; i++) {
4200 res[raw[i]] = raw[i];
4201 }
4202 return res;
4203 }
4204 return raw;
4205}
4206function mergeAsArray(to, from) {
4207 return to ? [...new Set([].concat(to, from))] : from;
4208}
4209function mergeObjectOptions(to, from) {
4210 return to ? extend(extend(Object.create(null), to), from) : from;
4211}
4212function mergeWatchOptions(to, from) {
4213 if (!to)
4214 return from;
4215 if (!from)
4216 return to;
4217 const merged = extend(Object.create(null), to);
4218 for (const key in from) {
4219 merged[key] = mergeAsArray(to[key], from[key]);
4220 }
4221 return merged;
4222}
4223
4224function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4225isSSR = false) {
4226 const props = {};
4227 const attrs = {};
4228 def(attrs, InternalObjectKey, 1);
4229 instance.propsDefaults = Object.create(null);
4230 setFullProps(instance, rawProps, props, attrs);
4231 // ensure all declared prop keys are present
4232 for (const key in instance.propsOptions[0]) {
4233 if (!(key in props)) {
4234 props[key] = undefined;
4235 }
4236 }
4237 // validation
4238 {
4239 validateProps(rawProps || {}, props, instance);
4240 }
4241 if (isStateful) {
4242 // stateful
4243 instance.props = isSSR ? props : shallowReactive(props);
4244 }
4245 else {
4246 if (!instance.type.props) {
4247 // functional w/ optional props, props === attrs
4248 instance.props = attrs;
4249 }
4250 else {
4251 // functional w/ declared props
4252 instance.props = props;
4253 }
4254 }
4255 instance.attrs = attrs;
4256}
4257function updateProps(instance, rawProps, rawPrevProps, optimized) {
4258 const { props, attrs, vnode: { patchFlag } } = instance;
4259 const rawCurrentProps = toRaw(props);
4260 const [options] = instance.propsOptions;
4261 let hasAttrsChanged = false;
4262 if (
4263 // always force full diff in dev
4264 // - #1942 if hmr is enabled with sfc component
4265 // - vite#872 non-sfc component used by sfc component
4266 !((instance.type.__hmrId ||
4267 (instance.parent && instance.parent.type.__hmrId))) &&
4268 (optimized || patchFlag > 0) &&
4269 !(patchFlag & 16 /* FULL_PROPS */)) {
4270 if (patchFlag & 8 /* PROPS */) {
4271 // Compiler-generated props & no keys change, just set the updated
4272 // the props.
4273 const propsToUpdate = instance.vnode.dynamicProps;
4274 for (let i = 0; i < propsToUpdate.length; i++) {
4275 let key = propsToUpdate[i];
4276 // PROPS flag guarantees rawProps to be non-null
4277 const value = rawProps[key];
4278 if (options) {
4279 // attr / props separation was done on init and will be consistent
4280 // in this code path, so just check if attrs have it.
4281 if (hasOwn(attrs, key)) {
4282 if (value !== attrs[key]) {
4283 attrs[key] = value;
4284 hasAttrsChanged = true;
4285 }
4286 }
4287 else {
4288 const camelizedKey = camelize(key);
4289 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4290 }
4291 }
4292 else {
4293 if (value !== attrs[key]) {
4294 attrs[key] = value;
4295 hasAttrsChanged = true;
4296 }
4297 }
4298 }
4299 }
4300 }
4301 else {
4302 // full props update.
4303 if (setFullProps(instance, rawProps, props, attrs)) {
4304 hasAttrsChanged = true;
4305 }
4306 // in case of dynamic props, check if we need to delete keys from
4307 // the props object
4308 let kebabKey;
4309 for (const key in rawCurrentProps) {
4310 if (!rawProps ||
4311 // for camelCase
4312 (!hasOwn(rawProps, key) &&
4313 // it's possible the original props was passed in as kebab-case
4314 // and converted to camelCase (#955)
4315 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4316 if (options) {
4317 if (rawPrevProps &&
4318 // for camelCase
4319 (rawPrevProps[key] !== undefined ||
4320 // for kebab-case
4321 rawPrevProps[kebabKey] !== undefined)) {
4322 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4323 }
4324 }
4325 else {
4326 delete props[key];
4327 }
4328 }
4329 }
4330 // in the case of functional component w/o props declaration, props and
4331 // attrs point to the same object so it should already have been updated.
4332 if (attrs !== rawCurrentProps) {
4333 for (const key in attrs) {
4334 if (!rawProps || !hasOwn(rawProps, key)) {
4335 delete attrs[key];
4336 hasAttrsChanged = true;
4337 }
4338 }
4339 }
4340 }
4341 // trigger updates for $attrs in case it's used in component slots
4342 if (hasAttrsChanged) {
4343 trigger(instance, "set" /* SET */, '$attrs');
4344 }
4345 {
4346 validateProps(rawProps || {}, props, instance);
4347 }
4348}
4349function setFullProps(instance, rawProps, props, attrs) {
4350 const [options, needCastKeys] = instance.propsOptions;
4351 let hasAttrsChanged = false;
4352 let rawCastValues;
4353 if (rawProps) {
4354 for (let key in rawProps) {
4355 // key, ref are reserved and never passed down
4356 if (isReservedProp(key)) {
4357 continue;
4358 }
4359 const value = rawProps[key];
4360 // prop option names are camelized during normalization, so to support
4361 // kebab -> camel conversion here we need to camelize the key.
4362 let camelKey;
4363 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4364 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4365 props[camelKey] = value;
4366 }
4367 else {
4368 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4369 }
4370 }
4371 else if (!isEmitListener(instance.emitsOptions, key)) {
4372 if (value !== attrs[key]) {
4373 attrs[key] = value;
4374 hasAttrsChanged = true;
4375 }
4376 }
4377 }
4378 }
4379 if (needCastKeys) {
4380 const rawCurrentProps = toRaw(props);
4381 const castValues = rawCastValues || EMPTY_OBJ;
4382 for (let i = 0; i < needCastKeys.length; i++) {
4383 const key = needCastKeys[i];
4384 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4385 }
4386 }
4387 return hasAttrsChanged;
4388}
4389function resolvePropValue(options, props, key, value, instance, isAbsent) {
4390 const opt = options[key];
4391 if (opt != null) {
4392 const hasDefault = hasOwn(opt, 'default');
4393 // default values
4394 if (hasDefault && value === undefined) {
4395 const defaultValue = opt.default;
4396 if (opt.type !== Function && isFunction(defaultValue)) {
4397 const { propsDefaults } = instance;
4398 if (key in propsDefaults) {
4399 value = propsDefaults[key];
4400 }
4401 else {
4402 setCurrentInstance(instance);
4403 value = propsDefaults[key] = defaultValue.call(null, props);
4404 unsetCurrentInstance();
4405 }
4406 }
4407 else {
4408 value = defaultValue;
4409 }
4410 }
4411 // boolean casting
4412 if (opt[0 /* shouldCast */]) {
4413 if (isAbsent && !hasDefault) {
4414 value = false;
4415 }
4416 else if (opt[1 /* shouldCastTrue */] &&
4417 (value === '' || value === hyphenate(key))) {
4418 value = true;
4419 }
4420 }
4421 }
4422 return value;
4423}
4424function normalizePropsOptions(comp, appContext, asMixin = false) {
4425 const cache = appContext.propsCache;
4426 const cached = cache.get(comp);
4427 if (cached) {
4428 return cached;
4429 }
4430 const raw = comp.props;
4431 const normalized = {};
4432 const needCastKeys = [];
4433 // apply mixin/extends props
4434 let hasExtends = false;
4435 if (!isFunction(comp)) {
4436 const extendProps = (raw) => {
4437 hasExtends = true;
4438 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4439 extend(normalized, props);
4440 if (keys)
4441 needCastKeys.push(...keys);
4442 };
4443 if (!asMixin && appContext.mixins.length) {
4444 appContext.mixins.forEach(extendProps);
4445 }
4446 if (comp.extends) {
4447 extendProps(comp.extends);
4448 }
4449 if (comp.mixins) {
4450 comp.mixins.forEach(extendProps);
4451 }
4452 }
4453 if (!raw && !hasExtends) {
4454 cache.set(comp, EMPTY_ARR);
4455 return EMPTY_ARR;
4456 }
4457 if (isArray(raw)) {
4458 for (let i = 0; i < raw.length; i++) {
4459 if (!isString(raw[i])) {
4460 warn$1(`props must be strings when using array syntax.`, raw[i]);
4461 }
4462 const normalizedKey = camelize(raw[i]);
4463 if (validatePropName(normalizedKey)) {
4464 normalized[normalizedKey] = EMPTY_OBJ;
4465 }
4466 }
4467 }
4468 else if (raw) {
4469 if (!isObject(raw)) {
4470 warn$1(`invalid props options`, raw);
4471 }
4472 for (const key in raw) {
4473 const normalizedKey = camelize(key);
4474 if (validatePropName(normalizedKey)) {
4475 const opt = raw[key];
4476 const prop = (normalized[normalizedKey] =
4477 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4478 if (prop) {
4479 const booleanIndex = getTypeIndex(Boolean, prop.type);
4480 const stringIndex = getTypeIndex(String, prop.type);
4481 prop[0 /* shouldCast */] = booleanIndex > -1;
4482 prop[1 /* shouldCastTrue */] =
4483 stringIndex < 0 || booleanIndex < stringIndex;
4484 // if the prop needs boolean casting or default value
4485 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4486 needCastKeys.push(normalizedKey);
4487 }
4488 }
4489 }
4490 }
4491 }
4492 const res = [normalized, needCastKeys];
4493 cache.set(comp, res);
4494 return res;
4495}
4496function validatePropName(key) {
4497 if (key[0] !== '$') {
4498 return true;
4499 }
4500 else {
4501 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4502 }
4503 return false;
4504}
4505// use function string name to check type constructors
4506// so that it works across vms / iframes.
4507function getType(ctor) {
4508 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4509 return match ? match[1] : ctor === null ? 'null' : '';
4510}
4511function isSameType(a, b) {
4512 return getType(a) === getType(b);
4513}
4514function getTypeIndex(type, expectedTypes) {
4515 if (isArray(expectedTypes)) {
4516 return expectedTypes.findIndex(t => isSameType(t, type));
4517 }
4518 else if (isFunction(expectedTypes)) {
4519 return isSameType(expectedTypes, type) ? 0 : -1;
4520 }
4521 return -1;
4522}
4523/**
4524 * dev only
4525 */
4526function validateProps(rawProps, props, instance) {
4527 const resolvedValues = toRaw(props);
4528 const options = instance.propsOptions[0];
4529 for (const key in options) {
4530 let opt = options[key];
4531 if (opt == null)
4532 continue;
4533 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4534 }
4535}
4536/**
4537 * dev only
4538 */
4539function validateProp(name, value, prop, isAbsent) {
4540 const { type, required, validator } = prop;
4541 // required!
4542 if (required && isAbsent) {
4543 warn$1('Missing required prop: "' + name + '"');
4544 return;
4545 }
4546 // missing but optional
4547 if (value == null && !prop.required) {
4548 return;
4549 }
4550 // type check
4551 if (type != null && type !== true) {
4552 let isValid = false;
4553 const types = isArray(type) ? type : [type];
4554 const expectedTypes = [];
4555 // value is valid as long as one of the specified types match
4556 for (let i = 0; i < types.length && !isValid; i++) {
4557 const { valid, expectedType } = assertType(value, types[i]);
4558 expectedTypes.push(expectedType || '');
4559 isValid = valid;
4560 }
4561 if (!isValid) {
4562 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
4563 return;
4564 }
4565 }
4566 // custom validator
4567 if (validator && !validator(value)) {
4568 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
4569 }
4570}
4571const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4572/**
4573 * dev only
4574 */
4575function assertType(value, type) {
4576 let valid;
4577 const expectedType = getType(type);
4578 if (isSimpleType(expectedType)) {
4579 const t = typeof value;
4580 valid = t === expectedType.toLowerCase();
4581 // for primitive wrapper objects
4582 if (!valid && t === 'object') {
4583 valid = value instanceof type;
4584 }
4585 }
4586 else if (expectedType === 'Object') {
4587 valid = isObject(value);
4588 }
4589 else if (expectedType === 'Array') {
4590 valid = isArray(value);
4591 }
4592 else if (expectedType === 'null') {
4593 valid = value === null;
4594 }
4595 else {
4596 valid = value instanceof type;
4597 }
4598 return {
4599 valid,
4600 expectedType
4601 };
4602}
4603/**
4604 * dev only
4605 */
4606function getInvalidTypeMessage(name, value, expectedTypes) {
4607 let message = `Invalid prop: type check failed for prop "${name}".` +
4608 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
4609 const expectedType = expectedTypes[0];
4610 const receivedType = toRawType(value);
4611 const expectedValue = styleValue(value, expectedType);
4612 const receivedValue = styleValue(value, receivedType);
4613 // check if we need to specify expected value
4614 if (expectedTypes.length === 1 &&
4615 isExplicable(expectedType) &&
4616 !isBoolean(expectedType, receivedType)) {
4617 message += ` with value ${expectedValue}`;
4618 }
4619 message += `, got ${receivedType} `;
4620 // check if we need to specify received value
4621 if (isExplicable(receivedType)) {
4622 message += `with value ${receivedValue}.`;
4623 }
4624 return message;
4625}
4626/**
4627 * dev only
4628 */
4629function styleValue(value, type) {
4630 if (type === 'String') {
4631 return `"${value}"`;
4632 }
4633 else if (type === 'Number') {
4634 return `${Number(value)}`;
4635 }
4636 else {
4637 return `${value}`;
4638 }
4639}
4640/**
4641 * dev only
4642 */
4643function isExplicable(type) {
4644 const explicitTypes = ['string', 'number', 'boolean'];
4645 return explicitTypes.some(elem => type.toLowerCase() === elem);
4646}
4647/**
4648 * dev only
4649 */
4650function isBoolean(...args) {
4651 return args.some(elem => elem.toLowerCase() === 'boolean');
4652}
4653
4654const isInternalKey = (key) => key[0] === '_' || key === '$stable';
4655const normalizeSlotValue = (value) => isArray(value)
4656 ? value.map(normalizeVNode)
4657 : [normalizeVNode(value)];
4658const normalizeSlot = (key, rawSlot, ctx) => {
4659 const normalized = withCtx((...args) => {
4660 if (currentInstance) {
4661 warn$1(`Slot "${key}" invoked outside of the render function: ` +
4662 `this will not track dependencies used in the slot. ` +
4663 `Invoke the slot function inside the render function instead.`);
4664 }
4665 return normalizeSlotValue(rawSlot(...args));
4666 }, ctx);
4667 normalized._c = false;
4668 return normalized;
4669};
4670const normalizeObjectSlots = (rawSlots, slots, instance) => {
4671 const ctx = rawSlots._ctx;
4672 for (const key in rawSlots) {
4673 if (isInternalKey(key))
4674 continue;
4675 const value = rawSlots[key];
4676 if (isFunction(value)) {
4677 slots[key] = normalizeSlot(key, value, ctx);
4678 }
4679 else if (value != null) {
4680 {
4681 warn$1(`Non-function value encountered for slot "${key}". ` +
4682 `Prefer function slots for better performance.`);
4683 }
4684 const normalized = normalizeSlotValue(value);
4685 slots[key] = () => normalized;
4686 }
4687 }
4688};
4689const normalizeVNodeSlots = (instance, children) => {
4690 if (!isKeepAlive(instance.vnode) &&
4691 !(false )) {
4692 warn$1(`Non-function value encountered for default slot. ` +
4693 `Prefer function slots for better performance.`);
4694 }
4695 const normalized = normalizeSlotValue(children);
4696 instance.slots.default = () => normalized;
4697};
4698const initSlots = (instance, children) => {
4699 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4700 const type = children._;
4701 if (type) {
4702 // users can get the shallow readonly version of the slots object through `this.$slots`,
4703 // we should avoid the proxy object polluting the slots of the internal instance
4704 instance.slots = toRaw(children);
4705 // make compiler marker non-enumerable
4706 def(children, '_', type);
4707 }
4708 else {
4709 normalizeObjectSlots(children, (instance.slots = {}));
4710 }
4711 }
4712 else {
4713 instance.slots = {};
4714 if (children) {
4715 normalizeVNodeSlots(instance, children);
4716 }
4717 }
4718 def(instance.slots, InternalObjectKey, 1);
4719};
4720const updateSlots = (instance, children, optimized) => {
4721 const { vnode, slots } = instance;
4722 let needDeletionCheck = true;
4723 let deletionComparisonTarget = EMPTY_OBJ;
4724 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4725 const type = children._;
4726 if (type) {
4727 // compiled slots.
4728 if (isHmrUpdating) {
4729 // Parent was HMR updated so slot content may have changed.
4730 // force update slots and mark instance for hmr as well
4731 extend(slots, children);
4732 }
4733 else if (optimized && type === 1 /* STABLE */) {
4734 // compiled AND stable.
4735 // no need to update, and skip stale slots removal.
4736 needDeletionCheck = false;
4737 }
4738 else {
4739 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
4740 // normalization.
4741 extend(slots, children);
4742 // #2893
4743 // when rendering the optimized slots by manually written render function,
4744 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
4745 // i.e. let the `renderSlot` create the bailed Fragment
4746 if (!optimized && type === 1 /* STABLE */) {
4747 delete slots._;
4748 }
4749 }
4750 }
4751 else {
4752 needDeletionCheck = !children.$stable;
4753 normalizeObjectSlots(children, slots);
4754 }
4755 deletionComparisonTarget = children;
4756 }
4757 else if (children) {
4758 // non slot object children (direct value) passed to a component
4759 normalizeVNodeSlots(instance, children);
4760 deletionComparisonTarget = { default: 1 };
4761 }
4762 // delete stale slots
4763 if (needDeletionCheck) {
4764 for (const key in slots) {
4765 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
4766 delete slots[key];
4767 }
4768 }
4769 }
4770};
4771
4772/**
4773Runtime helper for applying directives to a vnode. Example usage:
4774
4775const comp = resolveComponent('comp')
4776const foo = resolveDirective('foo')
4777const bar = resolveDirective('bar')
4778
4779return withDirectives(h(comp), [
4780 [foo, this.x],
4781 [bar, this.y]
4782])
4783*/
4784const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
4785function validateDirectiveName(name) {
4786 if (isBuiltInDirective(name)) {
4787 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
4788 }
4789}
4790/**
4791 * Adds directives to a VNode.
4792 */
4793function withDirectives(vnode, directives) {
4794 const internalInstance = currentRenderingInstance;
4795 if (internalInstance === null) {
4796 warn$1(`withDirectives can only be used inside render functions.`);
4797 return vnode;
4798 }
4799 const instance = internalInstance.proxy;
4800 const bindings = vnode.dirs || (vnode.dirs = []);
4801 for (let i = 0; i < directives.length; i++) {
4802 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4803 if (isFunction(dir)) {
4804 dir = {
4805 mounted: dir,
4806 updated: dir
4807 };
4808 }
4809 if (dir.deep) {
4810 traverse(value);
4811 }
4812 bindings.push({
4813 dir,
4814 instance,
4815 value,
4816 oldValue: void 0,
4817 arg,
4818 modifiers
4819 });
4820 }
4821 return vnode;
4822}
4823function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4824 const bindings = vnode.dirs;
4825 const oldBindings = prevVNode && prevVNode.dirs;
4826 for (let i = 0; i < bindings.length; i++) {
4827 const binding = bindings[i];
4828 if (oldBindings) {
4829 binding.oldValue = oldBindings[i].value;
4830 }
4831 let hook = binding.dir[name];
4832 if (hook) {
4833 // disable tracking inside all lifecycle hooks
4834 // since they can potentially be called inside effects.
4835 pauseTracking();
4836 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4837 vnode.el,
4838 binding,
4839 vnode,
4840 prevVNode
4841 ]);
4842 resetTracking();
4843 }
4844 }
4845}
4846
4847function createAppContext() {
4848 return {
4849 app: null,
4850 config: {
4851 isNativeTag: NO,
4852 performance: false,
4853 globalProperties: {},
4854 optionMergeStrategies: {},
4855 errorHandler: undefined,
4856 warnHandler: undefined,
4857 compilerOptions: {}
4858 },
4859 mixins: [],
4860 components: {},
4861 directives: {},
4862 provides: Object.create(null),
4863 optionsCache: new WeakMap(),
4864 propsCache: new WeakMap(),
4865 emitsCache: new WeakMap()
4866 };
4867}
4868let uid = 0;
4869function createAppAPI(render, hydrate) {
4870 return function createApp(rootComponent, rootProps = null) {
4871 if (rootProps != null && !isObject(rootProps)) {
4872 warn$1(`root props passed to app.mount() must be an object.`);
4873 rootProps = null;
4874 }
4875 const context = createAppContext();
4876 const installedPlugins = new Set();
4877 let isMounted = false;
4878 const app = (context.app = {
4879 _uid: uid++,
4880 _component: rootComponent,
4881 _props: rootProps,
4882 _container: null,
4883 _context: context,
4884 _instance: null,
4885 version,
4886 get config() {
4887 return context.config;
4888 },
4889 set config(v) {
4890 {
4891 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
4892 }
4893 },
4894 use(plugin, ...options) {
4895 if (installedPlugins.has(plugin)) {
4896 warn$1(`Plugin has already been applied to target app.`);
4897 }
4898 else if (plugin && isFunction(plugin.install)) {
4899 installedPlugins.add(plugin);
4900 plugin.install(app, ...options);
4901 }
4902 else if (isFunction(plugin)) {
4903 installedPlugins.add(plugin);
4904 plugin(app, ...options);
4905 }
4906 else {
4907 warn$1(`A plugin must either be a function or an object with an "install" ` +
4908 `function.`);
4909 }
4910 return app;
4911 },
4912 mixin(mixin) {
4913 {
4914 if (!context.mixins.includes(mixin)) {
4915 context.mixins.push(mixin);
4916 }
4917 else {
4918 warn$1('Mixin has already been applied to target app' +
4919 (mixin.name ? `: ${mixin.name}` : ''));
4920 }
4921 }
4922 return app;
4923 },
4924 component(name, component) {
4925 {
4926 validateComponentName(name, context.config);
4927 }
4928 if (!component) {
4929 return context.components[name];
4930 }
4931 if (context.components[name]) {
4932 warn$1(`Component "${name}" has already been registered in target app.`);
4933 }
4934 context.components[name] = component;
4935 return app;
4936 },
4937 directive(name, directive) {
4938 {
4939 validateDirectiveName(name);
4940 }
4941 if (!directive) {
4942 return context.directives[name];
4943 }
4944 if (context.directives[name]) {
4945 warn$1(`Directive "${name}" has already been registered in target app.`);
4946 }
4947 context.directives[name] = directive;
4948 return app;
4949 },
4950 mount(rootContainer, isHydrate, isSVG) {
4951 if (!isMounted) {
4952 const vnode = createVNode(rootComponent, rootProps);
4953 // store app context on the root VNode.
4954 // this will be set on the root instance on initial mount.
4955 vnode.appContext = context;
4956 // HMR root reload
4957 {
4958 context.reload = () => {
4959 render(cloneVNode(vnode), rootContainer, isSVG);
4960 };
4961 }
4962 if (isHydrate && hydrate) {
4963 hydrate(vnode, rootContainer);
4964 }
4965 else {
4966 render(vnode, rootContainer, isSVG);
4967 }
4968 isMounted = true;
4969 app._container = rootContainer;
4970 rootContainer.__vue_app__ = app;
4971 {
4972 app._instance = vnode.component;
4973 devtoolsInitApp(app, version);
4974 }
4975 return vnode.component.proxy;
4976 }
4977 else {
4978 warn$1(`App has already been mounted.\n` +
4979 `If you want to remount the same app, move your app creation logic ` +
4980 `into a factory function and create fresh app instances for each ` +
4981 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
4982 }
4983 },
4984 unmount() {
4985 if (isMounted) {
4986 render(null, app._container);
4987 {
4988 app._instance = null;
4989 devtoolsUnmountApp(app);
4990 }
4991 delete app._container.__vue_app__;
4992 }
4993 else {
4994 warn$1(`Cannot unmount an app that is not mounted.`);
4995 }
4996 },
4997 provide(key, value) {
4998 if (key in context.provides) {
4999 warn$1(`App already provides property with key "${String(key)}". ` +
5000 `It will be overwritten with the new value.`);
5001 }
5002 // TypeScript doesn't allow symbols as index type
5003 // https://github.com/Microsoft/TypeScript/issues/24587
5004 context.provides[key] = value;
5005 return app;
5006 }
5007 });
5008 return app;
5009 };
5010}
5011
5012let hasMismatch = false;
5013const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5014const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5015// Note: hydration is DOM-specific
5016// But we have to place it in core due to tight coupling with core - splitting
5017// it out creates a ton of unnecessary complexity.
5018// Hydration also depends on some renderer internal logic which needs to be
5019// passed in via arguments.
5020function createHydrationFunctions(rendererInternals) {
5021 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5022 const hydrate = (vnode, container) => {
5023 if (!container.hasChildNodes()) {
5024 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5025 `Performing full mount instead.`);
5026 patch(null, vnode, container);
5027 flushPostFlushCbs();
5028 return;
5029 }
5030 hasMismatch = false;
5031 hydrateNode(container.firstChild, vnode, null, null, null);
5032 flushPostFlushCbs();
5033 if (hasMismatch && !false) {
5034 // this error should show up in production
5035 console.error(`Hydration completed but contains mismatches.`);
5036 }
5037 };
5038 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5039 const isFragmentStart = isComment(node) && node.data === '[';
5040 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5041 const { type, ref, shapeFlag } = vnode;
5042 const domType = node.nodeType;
5043 vnode.el = node;
5044 let nextNode = null;
5045 switch (type) {
5046 case Text:
5047 if (domType !== 3 /* TEXT */) {
5048 nextNode = onMismatch();
5049 }
5050 else {
5051 if (node.data !== vnode.children) {
5052 hasMismatch = true;
5053 warn$1(`Hydration text mismatch:` +
5054 `\n- Client: ${JSON.stringify(node.data)}` +
5055 `\n- Server: ${JSON.stringify(vnode.children)}`);
5056 node.data = vnode.children;
5057 }
5058 nextNode = nextSibling(node);
5059 }
5060 break;
5061 case Comment:
5062 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5063 nextNode = onMismatch();
5064 }
5065 else {
5066 nextNode = nextSibling(node);
5067 }
5068 break;
5069 case Static:
5070 if (domType !== 1 /* ELEMENT */) {
5071 nextNode = onMismatch();
5072 }
5073 else {
5074 // determine anchor, adopt content
5075 nextNode = node;
5076 // if the static vnode has its content stripped during build,
5077 // adopt it from the server-rendered HTML.
5078 const needToAdoptContent = !vnode.children.length;
5079 for (let i = 0; i < vnode.staticCount; i++) {
5080 if (needToAdoptContent)
5081 vnode.children += nextNode.outerHTML;
5082 if (i === vnode.staticCount - 1) {
5083 vnode.anchor = nextNode;
5084 }
5085 nextNode = nextSibling(nextNode);
5086 }
5087 return nextNode;
5088 }
5089 break;
5090 case Fragment:
5091 if (!isFragmentStart) {
5092 nextNode = onMismatch();
5093 }
5094 else {
5095 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5096 }
5097 break;
5098 default:
5099 if (shapeFlag & 1 /* ELEMENT */) {
5100 if (domType !== 1 /* ELEMENT */ ||
5101 vnode.type.toLowerCase() !==
5102 node.tagName.toLowerCase()) {
5103 nextNode = onMismatch();
5104 }
5105 else {
5106 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5107 }
5108 }
5109 else if (shapeFlag & 6 /* COMPONENT */) {
5110 // when setting up the render effect, if the initial vnode already
5111 // has .el set, the component will perform hydration instead of mount
5112 // on its sub-tree.
5113 vnode.slotScopeIds = slotScopeIds;
5114 const container = parentNode(node);
5115 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5116 // component may be async, so in the case of fragments we cannot rely
5117 // on component's rendered output to determine the end of the fragment
5118 // instead, we do a lookahead to find the end anchor node.
5119 nextNode = isFragmentStart
5120 ? locateClosingAsyncAnchor(node)
5121 : nextSibling(node);
5122 // #3787
5123 // if component is async, it may get moved / unmounted before its
5124 // inner component is loaded, so we need to give it a placeholder
5125 // vnode that matches its adopted DOM.
5126 if (isAsyncWrapper(vnode)) {
5127 let subTree;
5128 if (isFragmentStart) {
5129 subTree = createVNode(Fragment);
5130 subTree.anchor = nextNode
5131 ? nextNode.previousSibling
5132 : container.lastChild;
5133 }
5134 else {
5135 subTree =
5136 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5137 }
5138 subTree.el = node;
5139 vnode.component.subTree = subTree;
5140 }
5141 }
5142 else if (shapeFlag & 64 /* TELEPORT */) {
5143 if (domType !== 8 /* COMMENT */) {
5144 nextNode = onMismatch();
5145 }
5146 else {
5147 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5148 }
5149 }
5150 else if (shapeFlag & 128 /* SUSPENSE */) {
5151 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5152 }
5153 else {
5154 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5155 }
5156 }
5157 if (ref != null) {
5158 setRef(ref, null, parentSuspense, vnode);
5159 }
5160 return nextNode;
5161 };
5162 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5163 optimized = optimized || !!vnode.dynamicChildren;
5164 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5165 // #4006 for form elements with non-string v-model value bindings
5166 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5167 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5168 // skip props & children if this is hoisted static nodes
5169 if (forcePatchValue || patchFlag !== -1 /* HOISTED */) {
5170 if (dirs) {
5171 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5172 }
5173 // props
5174 if (props) {
5175 if (forcePatchValue ||
5176 !optimized ||
5177 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5178 for (const key in props) {
5179 if ((forcePatchValue && key.endsWith('value')) ||
5180 (isOn(key) && !isReservedProp(key))) {
5181 patchProp(el, key, null, props[key]);
5182 }
5183 }
5184 }
5185 else if (props.onClick) {
5186 // Fast path for click listeners (which is most often) to avoid
5187 // iterating through props.
5188 patchProp(el, 'onClick', null, props.onClick);
5189 }
5190 }
5191 // vnode / directive hooks
5192 let vnodeHooks;
5193 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5194 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5195 }
5196 if (dirs) {
5197 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5198 }
5199 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5200 queueEffectWithSuspense(() => {
5201 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5202 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5203 }, parentSuspense);
5204 }
5205 // children
5206 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5207 // skip if element has innerHTML / textContent
5208 !(props && (props.innerHTML || props.textContent))) {
5209 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5210 let hasWarned = false;
5211 while (next) {
5212 hasMismatch = true;
5213 if (!hasWarned) {
5214 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5215 `server rendered element contains more child nodes than client vdom.`);
5216 hasWarned = true;
5217 }
5218 // The SSRed DOM contains more nodes than it should. Remove them.
5219 const cur = next;
5220 next = next.nextSibling;
5221 remove(cur);
5222 }
5223 }
5224 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5225 if (el.textContent !== vnode.children) {
5226 hasMismatch = true;
5227 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5228 `- Client: ${el.textContent}\n` +
5229 `- Server: ${vnode.children}`);
5230 el.textContent = vnode.children;
5231 }
5232 }
5233 }
5234 return el.nextSibling;
5235 };
5236 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5237 optimized = optimized || !!parentVNode.dynamicChildren;
5238 const children = parentVNode.children;
5239 const l = children.length;
5240 let hasWarned = false;
5241 for (let i = 0; i < l; i++) {
5242 const vnode = optimized
5243 ? children[i]
5244 : (children[i] = normalizeVNode(children[i]));
5245 if (node) {
5246 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5247 }
5248 else if (vnode.type === Text && !vnode.children) {
5249 continue;
5250 }
5251 else {
5252 hasMismatch = true;
5253 if (!hasWarned) {
5254 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5255 `server rendered element contains fewer child nodes than client vdom.`);
5256 hasWarned = true;
5257 }
5258 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5259 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5260 }
5261 }
5262 return node;
5263 };
5264 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5265 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5266 if (fragmentSlotScopeIds) {
5267 slotScopeIds = slotScopeIds
5268 ? slotScopeIds.concat(fragmentSlotScopeIds)
5269 : fragmentSlotScopeIds;
5270 }
5271 const container = parentNode(node);
5272 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5273 if (next && isComment(next) && next.data === ']') {
5274 return nextSibling((vnode.anchor = next));
5275 }
5276 else {
5277 // fragment didn't hydrate successfully, since we didn't get a end anchor
5278 // back. This should have led to node/children mismatch warnings.
5279 hasMismatch = true;
5280 // since the anchor is missing, we need to create one and insert it
5281 insert((vnode.anchor = createComment(`]`)), container, next);
5282 return next;
5283 }
5284 };
5285 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5286 hasMismatch = true;
5287 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5288 ? `(text)`
5289 : isComment(node) && node.data === '['
5290 ? `(start of fragment)`
5291 : ``);
5292 vnode.el = null;
5293 if (isFragment) {
5294 // remove excessive fragment nodes
5295 const end = locateClosingAsyncAnchor(node);
5296 while (true) {
5297 const next = nextSibling(node);
5298 if (next && next !== end) {
5299 remove(next);
5300 }
5301 else {
5302 break;
5303 }
5304 }
5305 }
5306 const next = nextSibling(node);
5307 const container = parentNode(node);
5308 remove(node);
5309 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5310 return next;
5311 };
5312 const locateClosingAsyncAnchor = (node) => {
5313 let match = 0;
5314 while (node) {
5315 node = nextSibling(node);
5316 if (node && isComment(node)) {
5317 if (node.data === '[')
5318 match++;
5319 if (node.data === ']') {
5320 if (match === 0) {
5321 return nextSibling(node);
5322 }
5323 else {
5324 match--;
5325 }
5326 }
5327 }
5328 }
5329 return node;
5330 };
5331 return [hydrate, hydrateNode];
5332}
5333
5334let supported;
5335let perf;
5336function startMeasure(instance, type) {
5337 if (instance.appContext.config.performance && isSupported()) {
5338 perf.mark(`vue-${type}-${instance.uid}`);
5339 }
5340 {
5341 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5342 }
5343}
5344function endMeasure(instance, type) {
5345 if (instance.appContext.config.performance && isSupported()) {
5346 const startTag = `vue-${type}-${instance.uid}`;
5347 const endTag = startTag + `:end`;
5348 perf.mark(endTag);
5349 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5350 perf.clearMarks(startTag);
5351 perf.clearMarks(endTag);
5352 }
5353 {
5354 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5355 }
5356}
5357function isSupported() {
5358 if (supported !== undefined) {
5359 return supported;
5360 }
5361 /* eslint-disable no-restricted-globals */
5362 if (typeof window !== 'undefined' && window.performance) {
5363 supported = true;
5364 perf = window.performance;
5365 }
5366 else {
5367 supported = false;
5368 }
5369 /* eslint-enable no-restricted-globals */
5370 return supported;
5371}
5372
5373const queuePostRenderEffect = queueEffectWithSuspense
5374 ;
5375/**
5376 * The createRenderer function accepts two generic arguments:
5377 * HostNode and HostElement, corresponding to Node and Element types in the
5378 * host environment. For example, for runtime-dom, HostNode would be the DOM
5379 * `Node` interface and HostElement would be the DOM `Element` interface.
5380 *
5381 * Custom renderers can pass in the platform specific types like this:
5382 *
5383 * ``` js
5384 * const { render, createApp } = createRenderer<Node, Element>({
5385 * patchProp,
5386 * ...nodeOps
5387 * })
5388 * ```
5389 */
5390function createRenderer(options) {
5391 return baseCreateRenderer(options);
5392}
5393// Separate API for creating hydration-enabled renderer.
5394// Hydration logic is only used when calling this function, making it
5395// tree-shakable.
5396function createHydrationRenderer(options) {
5397 return baseCreateRenderer(options, createHydrationFunctions);
5398}
5399// implementation
5400function baseCreateRenderer(options, createHydrationFns) {
5401 {
5402 const target = getGlobalThis();
5403 target.__VUE__ = true;
5404 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
5405 }
5406 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;
5407 // Note: functions inside this closure should use `const xxx = () => {}`
5408 // style in order to prevent being inlined by minifiers.
5409 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5410 if (n1 === n2) {
5411 return;
5412 }
5413 // patching & not same type, unmount old tree
5414 if (n1 && !isSameVNodeType(n1, n2)) {
5415 anchor = getNextHostNode(n1);
5416 unmount(n1, parentComponent, parentSuspense, true);
5417 n1 = null;
5418 }
5419 if (n2.patchFlag === -2 /* BAIL */) {
5420 optimized = false;
5421 n2.dynamicChildren = null;
5422 }
5423 const { type, ref, shapeFlag } = n2;
5424 switch (type) {
5425 case Text:
5426 processText(n1, n2, container, anchor);
5427 break;
5428 case Comment:
5429 processCommentNode(n1, n2, container, anchor);
5430 break;
5431 case Static:
5432 if (n1 == null) {
5433 mountStaticNode(n2, container, anchor, isSVG);
5434 }
5435 else {
5436 patchStaticNode(n1, n2, container, isSVG);
5437 }
5438 break;
5439 case Fragment:
5440 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5441 break;
5442 default:
5443 if (shapeFlag & 1 /* ELEMENT */) {
5444 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5445 }
5446 else if (shapeFlag & 6 /* COMPONENT */) {
5447 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5448 }
5449 else if (shapeFlag & 64 /* TELEPORT */) {
5450 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5451 }
5452 else if (shapeFlag & 128 /* SUSPENSE */) {
5453 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5454 }
5455 else {
5456 warn$1('Invalid VNode type:', type, `(${typeof type})`);
5457 }
5458 }
5459 // set ref
5460 if (ref != null && parentComponent) {
5461 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5462 }
5463 };
5464 const processText = (n1, n2, container, anchor) => {
5465 if (n1 == null) {
5466 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5467 }
5468 else {
5469 const el = (n2.el = n1.el);
5470 if (n2.children !== n1.children) {
5471 hostSetText(el, n2.children);
5472 }
5473 }
5474 };
5475 const processCommentNode = (n1, n2, container, anchor) => {
5476 if (n1 == null) {
5477 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5478 }
5479 else {
5480 // there's no support for dynamic comments
5481 n2.el = n1.el;
5482 }
5483 };
5484 const mountStaticNode = (n2, container, anchor, isSVG) => {
5485 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5486 };
5487 /**
5488 * Dev / HMR only
5489 */
5490 const patchStaticNode = (n1, n2, container, isSVG) => {
5491 // static nodes are only patched during dev for HMR
5492 if (n2.children !== n1.children) {
5493 const anchor = hostNextSibling(n1.anchor);
5494 // remove existing
5495 removeStaticNode(n1);
5496 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5497 }
5498 else {
5499 n2.el = n1.el;
5500 n2.anchor = n1.anchor;
5501 }
5502 };
5503 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5504 let next;
5505 while (el && el !== anchor) {
5506 next = hostNextSibling(el);
5507 hostInsert(el, container, nextSibling);
5508 el = next;
5509 }
5510 hostInsert(anchor, container, nextSibling);
5511 };
5512 const removeStaticNode = ({ el, anchor }) => {
5513 let next;
5514 while (el && el !== anchor) {
5515 next = hostNextSibling(el);
5516 hostRemove(el);
5517 el = next;
5518 }
5519 hostRemove(anchor);
5520 };
5521 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5522 isSVG = isSVG || n2.type === 'svg';
5523 if (n1 == null) {
5524 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5525 }
5526 else {
5527 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5528 }
5529 };
5530 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5531 let el;
5532 let vnodeHook;
5533 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
5534 {
5535 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
5536 // mount children first, since some props may rely on child content
5537 // being already rendered, e.g. `<select value>`
5538 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5539 hostSetElementText(el, vnode.children);
5540 }
5541 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5542 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
5543 }
5544 if (dirs) {
5545 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5546 }
5547 // props
5548 if (props) {
5549 for (const key in props) {
5550 if (key !== 'value' && !isReservedProp(key)) {
5551 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5552 }
5553 }
5554 /**
5555 * Special case for setting value on DOM elements:
5556 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
5557 * - it needs to be forced (#1471)
5558 * #2353 proposes adding another renderer option to configure this, but
5559 * the properties affects are so finite it is worth special casing it
5560 * here to reduce the complexity. (Special casing it also should not
5561 * affect non-DOM renderers)
5562 */
5563 if ('value' in props) {
5564 hostPatchProp(el, 'value', null, props.value);
5565 }
5566 if ((vnodeHook = props.onVnodeBeforeMount)) {
5567 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5568 }
5569 }
5570 // scopeId
5571 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
5572 }
5573 {
5574 Object.defineProperty(el, '__vnode', {
5575 value: vnode,
5576 enumerable: false
5577 });
5578 Object.defineProperty(el, '__vueParentComponent', {
5579 value: parentComponent,
5580 enumerable: false
5581 });
5582 }
5583 if (dirs) {
5584 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5585 }
5586 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5587 // #1689 For inside suspense + suspense resolved case, just call it
5588 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5589 transition &&
5590 !transition.persisted;
5591 if (needCallTransitionHooks) {
5592 transition.beforeEnter(el);
5593 }
5594 hostInsert(el, container, anchor);
5595 if ((vnodeHook = props && props.onVnodeMounted) ||
5596 needCallTransitionHooks ||
5597 dirs) {
5598 queuePostRenderEffect(() => {
5599 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5600 needCallTransitionHooks && transition.enter(el);
5601 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5602 }, parentSuspense);
5603 }
5604 };
5605 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
5606 if (scopeId) {
5607 hostSetScopeId(el, scopeId);
5608 }
5609 if (slotScopeIds) {
5610 for (let i = 0; i < slotScopeIds.length; i++) {
5611 hostSetScopeId(el, slotScopeIds[i]);
5612 }
5613 }
5614 if (parentComponent) {
5615 let subTree = parentComponent.subTree;
5616 if (subTree.patchFlag > 0 &&
5617 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
5618 subTree =
5619 filterSingleRoot(subTree.children) || subTree;
5620 }
5621 if (vnode === subTree) {
5622 const parentVNode = parentComponent.vnode;
5623 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
5624 }
5625 }
5626 };
5627 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
5628 for (let i = start; i < children.length; i++) {
5629 const child = (children[i] = optimized
5630 ? cloneIfMounted(children[i])
5631 : normalizeVNode(children[i]));
5632 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5633 }
5634 };
5635 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5636 const el = (n2.el = n1.el);
5637 let { patchFlag, dynamicChildren, dirs } = n2;
5638 // #1426 take the old vnode's patch flag into account since user may clone a
5639 // compiler-generated vnode, which de-opts to FULL_PROPS
5640 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
5641 const oldProps = n1.props || EMPTY_OBJ;
5642 const newProps = n2.props || EMPTY_OBJ;
5643 let vnodeHook;
5644 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
5645 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5646 }
5647 if (dirs) {
5648 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
5649 }
5650 if (isHmrUpdating) {
5651 // HMR updated, force full diff
5652 patchFlag = 0;
5653 optimized = false;
5654 dynamicChildren = null;
5655 }
5656 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
5657 if (dynamicChildren) {
5658 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
5659 if (parentComponent && parentComponent.type.__hmrId) {
5660 traverseStaticChildren(n1, n2);
5661 }
5662 }
5663 else if (!optimized) {
5664 // full diff
5665 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
5666 }
5667 if (patchFlag > 0) {
5668 // the presence of a patchFlag means this element's render code was
5669 // generated by the compiler and can take the fast path.
5670 // in this path old node and new node are guaranteed to have the same shape
5671 // (i.e. at the exact same position in the source template)
5672 if (patchFlag & 16 /* FULL_PROPS */) {
5673 // element props contain dynamic keys, full diff needed
5674 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5675 }
5676 else {
5677 // class
5678 // this flag is matched when the element has dynamic class bindings.
5679 if (patchFlag & 2 /* CLASS */) {
5680 if (oldProps.class !== newProps.class) {
5681 hostPatchProp(el, 'class', null, newProps.class, isSVG);
5682 }
5683 }
5684 // style
5685 // this flag is matched when the element has dynamic style bindings
5686 if (patchFlag & 4 /* STYLE */) {
5687 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
5688 }
5689 // props
5690 // This flag is matched when the element has dynamic prop/attr bindings
5691 // other than class and style. The keys of dynamic prop/attrs are saved for
5692 // faster iteration.
5693 // Note dynamic keys like :[foo]="bar" will cause this optimization to
5694 // bail out and go through a full diff because we need to unset the old key
5695 if (patchFlag & 8 /* PROPS */) {
5696 // if the flag is present then dynamicProps must be non-null
5697 const propsToUpdate = n2.dynamicProps;
5698 for (let i = 0; i < propsToUpdate.length; i++) {
5699 const key = propsToUpdate[i];
5700 const prev = oldProps[key];
5701 const next = newProps[key];
5702 // #1471 force patch value
5703 if (next !== prev || key === 'value') {
5704 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
5705 }
5706 }
5707 }
5708 }
5709 // text
5710 // This flag is matched when the element has only dynamic text children.
5711 if (patchFlag & 1 /* TEXT */) {
5712 if (n1.children !== n2.children) {
5713 hostSetElementText(el, n2.children);
5714 }
5715 }
5716 }
5717 else if (!optimized && dynamicChildren == null) {
5718 // unoptimized, full diff
5719 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5720 }
5721 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
5722 queuePostRenderEffect(() => {
5723 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5724 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
5725 }, parentSuspense);
5726 }
5727 };
5728 // The fast path for blocks.
5729 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
5730 for (let i = 0; i < newChildren.length; i++) {
5731 const oldVNode = oldChildren[i];
5732 const newVNode = newChildren[i];
5733 // Determine the container (parent element) for the patch.
5734 const container =
5735 // oldVNode may be an errored async setup() component inside Suspense
5736 // which will not have a mounted element
5737 oldVNode.el &&
5738 // - In the case of a Fragment, we need to provide the actual parent
5739 // of the Fragment itself so it can move its children.
5740 (oldVNode.type === Fragment ||
5741 // - In the case of different nodes, there is going to be a replacement
5742 // which also requires the correct parent container
5743 !isSameVNodeType(oldVNode, newVNode) ||
5744 // - In the case of a component, it could contain anything.
5745 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
5746 ? hostParentNode(oldVNode.el)
5747 : // In other cases, the parent container is not actually used so we
5748 // just pass the block element here to avoid a DOM parentNode call.
5749 fallbackContainer;
5750 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
5751 }
5752 };
5753 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
5754 if (oldProps !== newProps) {
5755 for (const key in newProps) {
5756 // empty string is not valid prop
5757 if (isReservedProp(key))
5758 continue;
5759 const next = newProps[key];
5760 const prev = oldProps[key];
5761 // defer patching value
5762 if (next !== prev && key !== 'value') {
5763 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5764 }
5765 }
5766 if (oldProps !== EMPTY_OBJ) {
5767 for (const key in oldProps) {
5768 if (!isReservedProp(key) && !(key in newProps)) {
5769 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5770 }
5771 }
5772 }
5773 if ('value' in newProps) {
5774 hostPatchProp(el, 'value', oldProps.value, newProps.value);
5775 }
5776 }
5777 };
5778 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5779 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
5780 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
5781 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
5782 if (isHmrUpdating) {
5783 // HMR updated, force full diff
5784 patchFlag = 0;
5785 optimized = false;
5786 dynamicChildren = null;
5787 }
5788 // check if this is a slot fragment with :slotted scope ids
5789 if (fragmentSlotScopeIds) {
5790 slotScopeIds = slotScopeIds
5791 ? slotScopeIds.concat(fragmentSlotScopeIds)
5792 : fragmentSlotScopeIds;
5793 }
5794 if (n1 == null) {
5795 hostInsert(fragmentStartAnchor, container, anchor);
5796 hostInsert(fragmentEndAnchor, container, anchor);
5797 // a fragment can only have array children
5798 // since they are either generated by the compiler, or implicitly created
5799 // from arrays.
5800 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5801 }
5802 else {
5803 if (patchFlag > 0 &&
5804 patchFlag & 64 /* STABLE_FRAGMENT */ &&
5805 dynamicChildren &&
5806 // #2715 the previous fragment could've been a BAILed one as a result
5807 // of renderSlot() with no valid children
5808 n1.dynamicChildren) {
5809 // a stable fragment (template root or <template v-for>) doesn't need to
5810 // patch children order, but it may contain dynamicChildren.
5811 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
5812 if (parentComponent && parentComponent.type.__hmrId) {
5813 traverseStaticChildren(n1, n2);
5814 }
5815 else if (
5816 // #2080 if the stable fragment has a key, it's a <template v-for> that may
5817 // get moved around. Make sure all root level vnodes inherit el.
5818 // #2134 or if it's a component root, it may also get moved around
5819 // as the component is being moved.
5820 n2.key != null ||
5821 (parentComponent && n2 === parentComponent.subTree)) {
5822 traverseStaticChildren(n1, n2, true /* shallow */);
5823 }
5824 }
5825 else {
5826 // keyed / unkeyed, or manual fragments.
5827 // for keyed & unkeyed, since they are compiler generated from v-for,
5828 // each child is guaranteed to be a block so the fragment will never
5829 // have dynamicChildren.
5830 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5831 }
5832 }
5833 };
5834 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5835 n2.slotScopeIds = slotScopeIds;
5836 if (n1 == null) {
5837 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
5838 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
5839 }
5840 else {
5841 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5842 }
5843 }
5844 else {
5845 updateComponent(n1, n2, optimized);
5846 }
5847 };
5848 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5849 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
5850 if (instance.type.__hmrId) {
5851 registerHMR(instance);
5852 }
5853 {
5854 pushWarningContext(initialVNode);
5855 startMeasure(instance, `mount`);
5856 }
5857 // inject renderer internals for keepAlive
5858 if (isKeepAlive(initialVNode)) {
5859 instance.ctx.renderer = internals;
5860 }
5861 // resolve props and slots for setup context
5862 {
5863 {
5864 startMeasure(instance, `init`);
5865 }
5866 setupComponent(instance);
5867 {
5868 endMeasure(instance, `init`);
5869 }
5870 }
5871 // setup() is async. This component relies on async logic to be resolved
5872 // before proceeding
5873 if (instance.asyncDep) {
5874 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
5875 // Give it a placeholder if this is not hydration
5876 // TODO handle self-defined fallback
5877 if (!initialVNode.el) {
5878 const placeholder = (instance.subTree = createVNode(Comment));
5879 processCommentNode(null, placeholder, container, anchor);
5880 }
5881 return;
5882 }
5883 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
5884 {
5885 popWarningContext();
5886 endMeasure(instance, `mount`);
5887 }
5888 };
5889 const updateComponent = (n1, n2, optimized) => {
5890 const instance = (n2.component = n1.component);
5891 if (shouldUpdateComponent(n1, n2, optimized)) {
5892 if (instance.asyncDep &&
5893 !instance.asyncResolved) {
5894 // async & still pending - just update props and slots
5895 // since the component's reactive effect for render isn't set-up yet
5896 {
5897 pushWarningContext(n2);
5898 }
5899 updateComponentPreRender(instance, n2, optimized);
5900 {
5901 popWarningContext();
5902 }
5903 return;
5904 }
5905 else {
5906 // normal update
5907 instance.next = n2;
5908 // in case the child component is also queued, remove it to avoid
5909 // double updating the same child component in the same flush.
5910 invalidateJob(instance.update);
5911 // instance.update is the reactive effect.
5912 instance.update();
5913 }
5914 }
5915 else {
5916 // no update needed. just copy over properties
5917 n2.component = n1.component;
5918 n2.el = n1.el;
5919 instance.vnode = n2;
5920 }
5921 };
5922 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
5923 const componentUpdateFn = () => {
5924 if (!instance.isMounted) {
5925 let vnodeHook;
5926 const { el, props } = initialVNode;
5927 const { bm, m, parent } = instance;
5928 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
5929 effect.allowRecurse = false;
5930 // beforeMount hook
5931 if (bm) {
5932 invokeArrayFns(bm);
5933 }
5934 // onVnodeBeforeMount
5935 if (!isAsyncWrapperVNode &&
5936 (vnodeHook = props && props.onVnodeBeforeMount)) {
5937 invokeVNodeHook(vnodeHook, parent, initialVNode);
5938 }
5939 effect.allowRecurse = true;
5940 if (el && hydrateNode) {
5941 // vnode has adopted host node - perform hydration instead of mount.
5942 const hydrateSubTree = () => {
5943 {
5944 startMeasure(instance, `render`);
5945 }
5946 instance.subTree = renderComponentRoot(instance);
5947 {
5948 endMeasure(instance, `render`);
5949 }
5950 {
5951 startMeasure(instance, `hydrate`);
5952 }
5953 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
5954 {
5955 endMeasure(instance, `hydrate`);
5956 }
5957 };
5958 if (isAsyncWrapperVNode) {
5959 initialVNode.type.__asyncLoader().then(
5960 // note: we are moving the render call into an async callback,
5961 // which means it won't track dependencies - but it's ok because
5962 // a server-rendered async wrapper is already in resolved state
5963 // and it will never need to change.
5964 () => !instance.isUnmounted && hydrateSubTree());
5965 }
5966 else {
5967 hydrateSubTree();
5968 }
5969 }
5970 else {
5971 {
5972 startMeasure(instance, `render`);
5973 }
5974 const subTree = (instance.subTree = renderComponentRoot(instance));
5975 {
5976 endMeasure(instance, `render`);
5977 }
5978 {
5979 startMeasure(instance, `patch`);
5980 }
5981 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
5982 {
5983 endMeasure(instance, `patch`);
5984 }
5985 initialVNode.el = subTree.el;
5986 }
5987 // mounted hook
5988 if (m) {
5989 queuePostRenderEffect(m, parentSuspense);
5990 }
5991 // onVnodeMounted
5992 if (!isAsyncWrapperVNode &&
5993 (vnodeHook = props && props.onVnodeMounted)) {
5994 const scopedInitialVNode = initialVNode;
5995 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
5996 }
5997 // activated hook for keep-alive roots.
5998 // #1742 activated hook must be accessed after first render
5999 // since the hook may be injected by a child keep-alive
6000 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6001 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
6002 }
6003 instance.isMounted = true;
6004 {
6005 devtoolsComponentAdded(instance);
6006 }
6007 // #2458: deference mount-only object parameters to prevent memleaks
6008 initialVNode = container = anchor = null;
6009 }
6010 else {
6011 // updateComponent
6012 // This is triggered by mutation of component's own state (next: null)
6013 // OR parent calling processComponent (next: VNode)
6014 let { next, bu, u, parent, vnode } = instance;
6015 let originNext = next;
6016 let vnodeHook;
6017 {
6018 pushWarningContext(next || instance.vnode);
6019 }
6020 // Disallow component effect recursion during pre-lifecycle hooks.
6021 effect.allowRecurse = false;
6022 if (next) {
6023 next.el = vnode.el;
6024 updateComponentPreRender(instance, next, optimized);
6025 }
6026 else {
6027 next = vnode;
6028 }
6029 // beforeUpdate hook
6030 if (bu) {
6031 invokeArrayFns(bu);
6032 }
6033 // onVnodeBeforeUpdate
6034 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6035 invokeVNodeHook(vnodeHook, parent, next, vnode);
6036 }
6037 effect.allowRecurse = true;
6038 // render
6039 {
6040 startMeasure(instance, `render`);
6041 }
6042 const nextTree = renderComponentRoot(instance);
6043 {
6044 endMeasure(instance, `render`);
6045 }
6046 const prevTree = instance.subTree;
6047 instance.subTree = nextTree;
6048 {
6049 startMeasure(instance, `patch`);
6050 }
6051 patch(prevTree, nextTree,
6052 // parent may have changed if it's in a teleport
6053 hostParentNode(prevTree.el),
6054 // anchor may have changed if it's in a fragment
6055 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6056 {
6057 endMeasure(instance, `patch`);
6058 }
6059 next.el = nextTree.el;
6060 if (originNext === null) {
6061 // self-triggered update. In case of HOC, update parent component
6062 // vnode el. HOC is indicated by parent instance's subTree pointing
6063 // to child component's vnode
6064 updateHOCHostEl(instance, nextTree.el);
6065 }
6066 // updated hook
6067 if (u) {
6068 queuePostRenderEffect(u, parentSuspense);
6069 }
6070 // onVnodeUpdated
6071 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6072 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6073 }
6074 {
6075 devtoolsComponentUpdated(instance);
6076 }
6077 {
6078 popWarningContext();
6079 }
6080 }
6081 };
6082 // create reactive effect for rendering
6083 const effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6084 );
6085 const update = (instance.update = effect.run.bind(effect));
6086 update.id = instance.uid;
6087 // allowRecurse
6088 // #1801, #2043 component render effects should allow recursive updates
6089 effect.allowRecurse = update.allowRecurse = true;
6090 {
6091 effect.onTrack = instance.rtc
6092 ? e => invokeArrayFns(instance.rtc, e)
6093 : void 0;
6094 effect.onTrigger = instance.rtg
6095 ? e => invokeArrayFns(instance.rtg, e)
6096 : void 0;
6097 // @ts-ignore (for scheduler)
6098 update.ownerInstance = instance;
6099 }
6100 update();
6101 };
6102 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6103 nextVNode.component = instance;
6104 const prevProps = instance.vnode.props;
6105 instance.vnode = nextVNode;
6106 instance.next = null;
6107 updateProps(instance, nextVNode.props, prevProps, optimized);
6108 updateSlots(instance, nextVNode.children, optimized);
6109 pauseTracking();
6110 // props update may have triggered pre-flush watchers.
6111 // flush them before the render update.
6112 flushPreFlushCbs(undefined, instance.update);
6113 resetTracking();
6114 };
6115 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6116 const c1 = n1 && n1.children;
6117 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6118 const c2 = n2.children;
6119 const { patchFlag, shapeFlag } = n2;
6120 // fast path
6121 if (patchFlag > 0) {
6122 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6123 // this could be either fully-keyed or mixed (some keyed some not)
6124 // presence of patchFlag means children are guaranteed to be arrays
6125 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6126 return;
6127 }
6128 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6129 // unkeyed
6130 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6131 return;
6132 }
6133 }
6134 // children has 3 possibilities: text, array or no children.
6135 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6136 // text children fast path
6137 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6138 unmountChildren(c1, parentComponent, parentSuspense);
6139 }
6140 if (c2 !== c1) {
6141 hostSetElementText(container, c2);
6142 }
6143 }
6144 else {
6145 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6146 // prev children was array
6147 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6148 // two arrays, cannot assume anything, do full diff
6149 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6150 }
6151 else {
6152 // no new children, just unmount old
6153 unmountChildren(c1, parentComponent, parentSuspense, true);
6154 }
6155 }
6156 else {
6157 // prev children was text OR null
6158 // new children is array OR null
6159 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6160 hostSetElementText(container, '');
6161 }
6162 // mount new if array
6163 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6164 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6165 }
6166 }
6167 }
6168 };
6169 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6170 c1 = c1 || EMPTY_ARR;
6171 c2 = c2 || EMPTY_ARR;
6172 const oldLength = c1.length;
6173 const newLength = c2.length;
6174 const commonLength = Math.min(oldLength, newLength);
6175 let i;
6176 for (i = 0; i < commonLength; i++) {
6177 const nextChild = (c2[i] = optimized
6178 ? cloneIfMounted(c2[i])
6179 : normalizeVNode(c2[i]));
6180 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6181 }
6182 if (oldLength > newLength) {
6183 // remove old
6184 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6185 }
6186 else {
6187 // mount new
6188 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6189 }
6190 };
6191 // can be all-keyed or mixed
6192 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6193 let i = 0;
6194 const l2 = c2.length;
6195 let e1 = c1.length - 1; // prev ending index
6196 let e2 = l2 - 1; // next ending index
6197 // 1. sync from start
6198 // (a b) c
6199 // (a b) d e
6200 while (i <= e1 && i <= e2) {
6201 const n1 = c1[i];
6202 const n2 = (c2[i] = optimized
6203 ? cloneIfMounted(c2[i])
6204 : normalizeVNode(c2[i]));
6205 if (isSameVNodeType(n1, n2)) {
6206 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6207 }
6208 else {
6209 break;
6210 }
6211 i++;
6212 }
6213 // 2. sync from end
6214 // a (b c)
6215 // d e (b c)
6216 while (i <= e1 && i <= e2) {
6217 const n1 = c1[e1];
6218 const n2 = (c2[e2] = optimized
6219 ? cloneIfMounted(c2[e2])
6220 : normalizeVNode(c2[e2]));
6221 if (isSameVNodeType(n1, n2)) {
6222 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6223 }
6224 else {
6225 break;
6226 }
6227 e1--;
6228 e2--;
6229 }
6230 // 3. common sequence + mount
6231 // (a b)
6232 // (a b) c
6233 // i = 2, e1 = 1, e2 = 2
6234 // (a b)
6235 // c (a b)
6236 // i = 0, e1 = -1, e2 = 0
6237 if (i > e1) {
6238 if (i <= e2) {
6239 const nextPos = e2 + 1;
6240 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6241 while (i <= e2) {
6242 patch(null, (c2[i] = optimized
6243 ? cloneIfMounted(c2[i])
6244 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6245 i++;
6246 }
6247 }
6248 }
6249 // 4. common sequence + unmount
6250 // (a b) c
6251 // (a b)
6252 // i = 2, e1 = 2, e2 = 1
6253 // a (b c)
6254 // (b c)
6255 // i = 0, e1 = 0, e2 = -1
6256 else if (i > e2) {
6257 while (i <= e1) {
6258 unmount(c1[i], parentComponent, parentSuspense, true);
6259 i++;
6260 }
6261 }
6262 // 5. unknown sequence
6263 // [i ... e1 + 1]: a b [c d e] f g
6264 // [i ... e2 + 1]: a b [e d c h] f g
6265 // i = 2, e1 = 4, e2 = 5
6266 else {
6267 const s1 = i; // prev starting index
6268 const s2 = i; // next starting index
6269 // 5.1 build key:index map for newChildren
6270 const keyToNewIndexMap = new Map();
6271 for (i = s2; i <= e2; i++) {
6272 const nextChild = (c2[i] = optimized
6273 ? cloneIfMounted(c2[i])
6274 : normalizeVNode(c2[i]));
6275 if (nextChild.key != null) {
6276 if (keyToNewIndexMap.has(nextChild.key)) {
6277 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6278 }
6279 keyToNewIndexMap.set(nextChild.key, i);
6280 }
6281 }
6282 // 5.2 loop through old children left to be patched and try to patch
6283 // matching nodes & remove nodes that are no longer present
6284 let j;
6285 let patched = 0;
6286 const toBePatched = e2 - s2 + 1;
6287 let moved = false;
6288 // used to track whether any node has moved
6289 let maxNewIndexSoFar = 0;
6290 // works as Map<newIndex, oldIndex>
6291 // Note that oldIndex is offset by +1
6292 // and oldIndex = 0 is a special value indicating the new node has
6293 // no corresponding old node.
6294 // used for determining longest stable subsequence
6295 const newIndexToOldIndexMap = new Array(toBePatched);
6296 for (i = 0; i < toBePatched; i++)
6297 newIndexToOldIndexMap[i] = 0;
6298 for (i = s1; i <= e1; i++) {
6299 const prevChild = c1[i];
6300 if (patched >= toBePatched) {
6301 // all new children have been patched so this can only be a removal
6302 unmount(prevChild, parentComponent, parentSuspense, true);
6303 continue;
6304 }
6305 let newIndex;
6306 if (prevChild.key != null) {
6307 newIndex = keyToNewIndexMap.get(prevChild.key);
6308 }
6309 else {
6310 // key-less node, try to locate a key-less node of the same type
6311 for (j = s2; j <= e2; j++) {
6312 if (newIndexToOldIndexMap[j - s2] === 0 &&
6313 isSameVNodeType(prevChild, c2[j])) {
6314 newIndex = j;
6315 break;
6316 }
6317 }
6318 }
6319 if (newIndex === undefined) {
6320 unmount(prevChild, parentComponent, parentSuspense, true);
6321 }
6322 else {
6323 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6324 if (newIndex >= maxNewIndexSoFar) {
6325 maxNewIndexSoFar = newIndex;
6326 }
6327 else {
6328 moved = true;
6329 }
6330 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6331 patched++;
6332 }
6333 }
6334 // 5.3 move and mount
6335 // generate longest stable subsequence only when nodes have moved
6336 const increasingNewIndexSequence = moved
6337 ? getSequence(newIndexToOldIndexMap)
6338 : EMPTY_ARR;
6339 j = increasingNewIndexSequence.length - 1;
6340 // looping backwards so that we can use last patched node as anchor
6341 for (i = toBePatched - 1; i >= 0; i--) {
6342 const nextIndex = s2 + i;
6343 const nextChild = c2[nextIndex];
6344 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6345 if (newIndexToOldIndexMap[i] === 0) {
6346 // mount new
6347 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6348 }
6349 else if (moved) {
6350 // move if:
6351 // There is no stable subsequence (e.g. a reverse)
6352 // OR current node is not among the stable sequence
6353 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6354 move(nextChild, container, anchor, 2 /* REORDER */);
6355 }
6356 else {
6357 j--;
6358 }
6359 }
6360 }
6361 }
6362 };
6363 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6364 const { el, type, transition, children, shapeFlag } = vnode;
6365 if (shapeFlag & 6 /* COMPONENT */) {
6366 move(vnode.component.subTree, container, anchor, moveType);
6367 return;
6368 }
6369 if (shapeFlag & 128 /* SUSPENSE */) {
6370 vnode.suspense.move(container, anchor, moveType);
6371 return;
6372 }
6373 if (shapeFlag & 64 /* TELEPORT */) {
6374 type.move(vnode, container, anchor, internals);
6375 return;
6376 }
6377 if (type === Fragment) {
6378 hostInsert(el, container, anchor);
6379 for (let i = 0; i < children.length; i++) {
6380 move(children[i], container, anchor, moveType);
6381 }
6382 hostInsert(vnode.anchor, container, anchor);
6383 return;
6384 }
6385 if (type === Static) {
6386 moveStaticNode(vnode, container, anchor);
6387 return;
6388 }
6389 // single nodes
6390 const needTransition = moveType !== 2 /* REORDER */ &&
6391 shapeFlag & 1 /* ELEMENT */ &&
6392 transition;
6393 if (needTransition) {
6394 if (moveType === 0 /* ENTER */) {
6395 transition.beforeEnter(el);
6396 hostInsert(el, container, anchor);
6397 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6398 }
6399 else {
6400 const { leave, delayLeave, afterLeave } = transition;
6401 const remove = () => hostInsert(el, container, anchor);
6402 const performLeave = () => {
6403 leave(el, () => {
6404 remove();
6405 afterLeave && afterLeave();
6406 });
6407 };
6408 if (delayLeave) {
6409 delayLeave(el, remove, performLeave);
6410 }
6411 else {
6412 performLeave();
6413 }
6414 }
6415 }
6416 else {
6417 hostInsert(el, container, anchor);
6418 }
6419 };
6420 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6421 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6422 // unset ref
6423 if (ref != null) {
6424 setRef(ref, null, parentSuspense, vnode, true);
6425 }
6426 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6427 parentComponent.ctx.deactivate(vnode);
6428 return;
6429 }
6430 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6431 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6432 let vnodeHook;
6433 if (shouldInvokeVnodeHook &&
6434 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6435 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6436 }
6437 if (shapeFlag & 6 /* COMPONENT */) {
6438 unmountComponent(vnode.component, parentSuspense, doRemove);
6439 }
6440 else {
6441 if (shapeFlag & 128 /* SUSPENSE */) {
6442 vnode.suspense.unmount(parentSuspense, doRemove);
6443 return;
6444 }
6445 if (shouldInvokeDirs) {
6446 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6447 }
6448 if (shapeFlag & 64 /* TELEPORT */) {
6449 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6450 }
6451 else if (dynamicChildren &&
6452 // #1153: fast path should not be taken for non-stable (v-for) fragments
6453 (type !== Fragment ||
6454 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6455 // fast path for block nodes: only need to unmount dynamic children.
6456 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6457 }
6458 else if ((type === Fragment &&
6459 patchFlag &
6460 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
6461 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6462 unmountChildren(children, parentComponent, parentSuspense);
6463 }
6464 if (doRemove) {
6465 remove(vnode);
6466 }
6467 }
6468 if ((shouldInvokeVnodeHook &&
6469 (vnodeHook = props && props.onVnodeUnmounted)) ||
6470 shouldInvokeDirs) {
6471 queuePostRenderEffect(() => {
6472 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6473 shouldInvokeDirs &&
6474 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6475 }, parentSuspense);
6476 }
6477 };
6478 const remove = vnode => {
6479 const { type, el, anchor, transition } = vnode;
6480 if (type === Fragment) {
6481 removeFragment(el, anchor);
6482 return;
6483 }
6484 if (type === Static) {
6485 removeStaticNode(vnode);
6486 return;
6487 }
6488 const performRemove = () => {
6489 hostRemove(el);
6490 if (transition && !transition.persisted && transition.afterLeave) {
6491 transition.afterLeave();
6492 }
6493 };
6494 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6495 transition &&
6496 !transition.persisted) {
6497 const { leave, delayLeave } = transition;
6498 const performLeave = () => leave(el, performRemove);
6499 if (delayLeave) {
6500 delayLeave(vnode.el, performRemove, performLeave);
6501 }
6502 else {
6503 performLeave();
6504 }
6505 }
6506 else {
6507 performRemove();
6508 }
6509 };
6510 const removeFragment = (cur, end) => {
6511 // For fragments, directly remove all contained DOM nodes.
6512 // (fragment child nodes cannot have transition)
6513 let next;
6514 while (cur !== end) {
6515 next = hostNextSibling(cur);
6516 hostRemove(cur);
6517 cur = next;
6518 }
6519 hostRemove(end);
6520 };
6521 const unmountComponent = (instance, parentSuspense, doRemove) => {
6522 if (instance.type.__hmrId) {
6523 unregisterHMR(instance);
6524 }
6525 const { bum, scope, update, subTree, um } = instance;
6526 // beforeUnmount hook
6527 if (bum) {
6528 invokeArrayFns(bum);
6529 }
6530 // stop effects in component scope
6531 scope.stop();
6532 // update may be null if a component is unmounted before its async
6533 // setup has resolved.
6534 if (update) {
6535 // so that scheduler will no longer invoke it
6536 update.active = false;
6537 unmount(subTree, instance, parentSuspense, doRemove);
6538 }
6539 // unmounted hook
6540 if (um) {
6541 queuePostRenderEffect(um, parentSuspense);
6542 }
6543 queuePostRenderEffect(() => {
6544 instance.isUnmounted = true;
6545 }, parentSuspense);
6546 // A component with async dep inside a pending suspense is unmounted before
6547 // its async dep resolves. This should remove the dep from the suspense, and
6548 // cause the suspense to resolve immediately if that was the last dep.
6549 if (parentSuspense &&
6550 parentSuspense.pendingBranch &&
6551 !parentSuspense.isUnmounted &&
6552 instance.asyncDep &&
6553 !instance.asyncResolved &&
6554 instance.suspenseId === parentSuspense.pendingId) {
6555 parentSuspense.deps--;
6556 if (parentSuspense.deps === 0) {
6557 parentSuspense.resolve();
6558 }
6559 }
6560 {
6561 devtoolsComponentRemoved(instance);
6562 }
6563 };
6564 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
6565 for (let i = start; i < children.length; i++) {
6566 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
6567 }
6568 };
6569 const getNextHostNode = vnode => {
6570 if (vnode.shapeFlag & 6 /* COMPONENT */) {
6571 return getNextHostNode(vnode.component.subTree);
6572 }
6573 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
6574 return vnode.suspense.next();
6575 }
6576 return hostNextSibling((vnode.anchor || vnode.el));
6577 };
6578 const render = (vnode, container, isSVG) => {
6579 if (vnode == null) {
6580 if (container._vnode) {
6581 unmount(container._vnode, null, null, true);
6582 }
6583 }
6584 else {
6585 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
6586 }
6587 flushPostFlushCbs();
6588 container._vnode = vnode;
6589 };
6590 const internals = {
6591 p: patch,
6592 um: unmount,
6593 m: move,
6594 r: remove,
6595 mt: mountComponent,
6596 mc: mountChildren,
6597 pc: patchChildren,
6598 pbc: patchBlockChildren,
6599 n: getNextHostNode,
6600 o: options
6601 };
6602 let hydrate;
6603 let hydrateNode;
6604 if (createHydrationFns) {
6605 [hydrate, hydrateNode] = createHydrationFns(internals);
6606 }
6607 return {
6608 render,
6609 hydrate,
6610 createApp: createAppAPI(render, hydrate)
6611 };
6612}
6613function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
6614 if (isArray(rawRef)) {
6615 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
6616 return;
6617 }
6618 if (isAsyncWrapper(vnode) && !isUnmount) {
6619 // when mounting async components, nothing needs to be done,
6620 // because the template ref is forwarded to inner component
6621 return;
6622 }
6623 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
6624 ? getExposeProxy(vnode.component) || vnode.component.proxy
6625 : vnode.el;
6626 const value = isUnmount ? null : refValue;
6627 const { i: owner, r: ref } = rawRef;
6628 if (!owner) {
6629 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
6630 `A vnode with ref must be created inside the render function.`);
6631 return;
6632 }
6633 const oldRef = oldRawRef && oldRawRef.r;
6634 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
6635 const setupState = owner.setupState;
6636 // dynamic ref changed. unset old ref
6637 if (oldRef != null && oldRef !== ref) {
6638 if (isString(oldRef)) {
6639 refs[oldRef] = null;
6640 if (hasOwn(setupState, oldRef)) {
6641 setupState[oldRef] = null;
6642 }
6643 }
6644 else if (isRef(oldRef)) {
6645 oldRef.value = null;
6646 }
6647 }
6648 if (isString(ref)) {
6649 const doSet = () => {
6650 {
6651 refs[ref] = value;
6652 }
6653 if (hasOwn(setupState, ref)) {
6654 setupState[ref] = value;
6655 }
6656 };
6657 // #1789: for non-null values, set them after render
6658 // null values means this is unmount and it should not overwrite another
6659 // ref with the same key
6660 if (value) {
6661 doSet.id = -1;
6662 queuePostRenderEffect(doSet, parentSuspense);
6663 }
6664 else {
6665 doSet();
6666 }
6667 }
6668 else if (isRef(ref)) {
6669 const doSet = () => {
6670 ref.value = value;
6671 };
6672 if (value) {
6673 doSet.id = -1;
6674 queuePostRenderEffect(doSet, parentSuspense);
6675 }
6676 else {
6677 doSet();
6678 }
6679 }
6680 else if (isFunction(ref)) {
6681 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
6682 }
6683 else {
6684 warn$1('Invalid template ref type:', value, `(${typeof value})`);
6685 }
6686}
6687function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6688 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6689 vnode,
6690 prevVNode
6691 ]);
6692}
6693/**
6694 * #1156
6695 * When a component is HMR-enabled, we need to make sure that all static nodes
6696 * inside a block also inherit the DOM element from the previous tree so that
6697 * HMR updates (which are full updates) can retrieve the element for patching.
6698 *
6699 * #2080
6700 * Inside keyed `template` fragment static children, if a fragment is moved,
6701 * the children will always moved so that need inherit el form previous nodes
6702 * to ensure correct moved position.
6703 */
6704function traverseStaticChildren(n1, n2, shallow = false) {
6705 const ch1 = n1.children;
6706 const ch2 = n2.children;
6707 if (isArray(ch1) && isArray(ch2)) {
6708 for (let i = 0; i < ch1.length; i++) {
6709 // this is only called in the optimized path so array children are
6710 // guaranteed to be vnodes
6711 const c1 = ch1[i];
6712 let c2 = ch2[i];
6713 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
6714 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
6715 c2 = ch2[i] = cloneIfMounted(ch2[i]);
6716 c2.el = c1.el;
6717 }
6718 if (!shallow)
6719 traverseStaticChildren(c1, c2);
6720 }
6721 // also inherit for comment nodes, but not placeholders (e.g. v-if which
6722 // would have received .el during block patch)
6723 if (c2.type === Comment && !c2.el) {
6724 c2.el = c1.el;
6725 }
6726 }
6727 }
6728}
6729// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
6730function getSequence(arr) {
6731 const p = arr.slice();
6732 const result = [0];
6733 let i, j, u, v, c;
6734 const len = arr.length;
6735 for (i = 0; i < len; i++) {
6736 const arrI = arr[i];
6737 if (arrI !== 0) {
6738 j = result[result.length - 1];
6739 if (arr[j] < arrI) {
6740 p[i] = j;
6741 result.push(i);
6742 continue;
6743 }
6744 u = 0;
6745 v = result.length - 1;
6746 while (u < v) {
6747 c = (u + v) >> 1;
6748 if (arr[result[c]] < arrI) {
6749 u = c + 1;
6750 }
6751 else {
6752 v = c;
6753 }
6754 }
6755 if (arrI < arr[result[u]]) {
6756 if (u > 0) {
6757 p[i] = result[u - 1];
6758 }
6759 result[u] = i;
6760 }
6761 }
6762 }
6763 u = result.length;
6764 v = result[u - 1];
6765 while (u-- > 0) {
6766 result[u] = v;
6767 v = p[v];
6768 }
6769 return result;
6770}
6771
6772const isTeleport = (type) => type.__isTeleport;
6773const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
6774const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
6775const resolveTarget = (props, select) => {
6776 const targetSelector = props && props.to;
6777 if (isString(targetSelector)) {
6778 if (!select) {
6779 warn$1(`Current renderer does not support string target for Teleports. ` +
6780 `(missing querySelector renderer option)`);
6781 return null;
6782 }
6783 else {
6784 const target = select(targetSelector);
6785 if (!target) {
6786 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
6787 `Note the target element must exist before the component is mounted - ` +
6788 `i.e. the target cannot be rendered by the component itself, and ` +
6789 `ideally should be outside of the entire Vue component tree.`);
6790 }
6791 return target;
6792 }
6793 }
6794 else {
6795 if (!targetSelector && !isTeleportDisabled(props)) {
6796 warn$1(`Invalid Teleport target: ${targetSelector}`);
6797 }
6798 return targetSelector;
6799 }
6800};
6801const TeleportImpl = {
6802 __isTeleport: true,
6803 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
6804 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
6805 const disabled = isTeleportDisabled(n2.props);
6806 let { shapeFlag, children, dynamicChildren } = n2;
6807 // #3302
6808 // HMR updated, force full diff
6809 if (isHmrUpdating) {
6810 optimized = false;
6811 dynamicChildren = null;
6812 }
6813 if (n1 == null) {
6814 // insert anchors in the main view
6815 const placeholder = (n2.el = createComment('teleport start')
6816 );
6817 const mainAnchor = (n2.anchor = createComment('teleport end')
6818 );
6819 insert(placeholder, container, anchor);
6820 insert(mainAnchor, container, anchor);
6821 const target = (n2.target = resolveTarget(n2.props, querySelector));
6822 const targetAnchor = (n2.targetAnchor = createText(''));
6823 if (target) {
6824 insert(targetAnchor, target);
6825 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
6826 isSVG = isSVG || isTargetSVG(target);
6827 }
6828 else if (!disabled) {
6829 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
6830 }
6831 const mount = (container, anchor) => {
6832 // Teleport *always* has Array children. This is enforced in both the
6833 // compiler and vnode children normalization.
6834 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6835 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6836 }
6837 };
6838 if (disabled) {
6839 mount(container, mainAnchor);
6840 }
6841 else if (target) {
6842 mount(target, targetAnchor);
6843 }
6844 }
6845 else {
6846 // update content
6847 n2.el = n1.el;
6848 const mainAnchor = (n2.anchor = n1.anchor);
6849 const target = (n2.target = n1.target);
6850 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
6851 const wasDisabled = isTeleportDisabled(n1.props);
6852 const currentContainer = wasDisabled ? container : target;
6853 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
6854 isSVG = isSVG || isTargetSVG(target);
6855 if (dynamicChildren) {
6856 // fast path when the teleport happens to be a block root
6857 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
6858 // even in block tree mode we need to make sure all root-level nodes
6859 // in the teleport inherit previous DOM references so that they can
6860 // be moved in future patches.
6861 traverseStaticChildren(n1, n2, true);
6862 }
6863 else if (!optimized) {
6864 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
6865 }
6866 if (disabled) {
6867 if (!wasDisabled) {
6868 // enabled -> disabled
6869 // move into main container
6870 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
6871 }
6872 }
6873 else {
6874 // target changed
6875 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
6876 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
6877 if (nextTarget) {
6878 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
6879 }
6880 else {
6881 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
6882 }
6883 }
6884 else if (wasDisabled) {
6885 // disabled -> enabled
6886 // move into teleport target
6887 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
6888 }
6889 }
6890 }
6891 },
6892 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
6893 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
6894 if (target) {
6895 hostRemove(targetAnchor);
6896 }
6897 // an unmounted teleport should always remove its children if not disabled
6898 if (doRemove || !isTeleportDisabled(props)) {
6899 hostRemove(anchor);
6900 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6901 for (let i = 0; i < children.length; i++) {
6902 const child = children[i];
6903 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
6904 }
6905 }
6906 }
6907 },
6908 move: moveTeleport,
6909 hydrate: hydrateTeleport
6910};
6911function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
6912 // move target anchor if this is a target change.
6913 if (moveType === 0 /* TARGET_CHANGE */) {
6914 insert(vnode.targetAnchor, container, parentAnchor);
6915 }
6916 const { el, anchor, shapeFlag, children, props } = vnode;
6917 const isReorder = moveType === 2 /* REORDER */;
6918 // move main view anchor if this is a re-order.
6919 if (isReorder) {
6920 insert(el, container, parentAnchor);
6921 }
6922 // if this is a re-order and teleport is enabled (content is in target)
6923 // do not move children. So the opposite is: only move children if this
6924 // is not a reorder, or the teleport is disabled
6925 if (!isReorder || isTeleportDisabled(props)) {
6926 // Teleport has either Array children or no children.
6927 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6928 for (let i = 0; i < children.length; i++) {
6929 move(children[i], container, parentAnchor, 2 /* REORDER */);
6930 }
6931 }
6932 }
6933 // move main view anchor if this is a re-order.
6934 if (isReorder) {
6935 insert(anchor, container, parentAnchor);
6936 }
6937}
6938function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
6939 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
6940 if (target) {
6941 // if multiple teleports rendered to the same target element, we need to
6942 // pick up from where the last teleport finished instead of the first node
6943 const targetNode = target._lpa || target.firstChild;
6944 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
6945 if (isTeleportDisabled(vnode.props)) {
6946 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
6947 vnode.targetAnchor = targetNode;
6948 }
6949 else {
6950 vnode.anchor = nextSibling(node);
6951 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
6952 }
6953 target._lpa =
6954 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
6955 }
6956 }
6957 return vnode.anchor && nextSibling(vnode.anchor);
6958}
6959// Force-casted public typing for h and TSX props inference
6960const Teleport = TeleportImpl;
6961
6962const COMPONENTS = 'components';
6963const DIRECTIVES = 'directives';
6964/**
6965 * @private
6966 */
6967function resolveComponent(name, maybeSelfReference) {
6968 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
6969}
6970const NULL_DYNAMIC_COMPONENT = Symbol();
6971/**
6972 * @private
6973 */
6974function resolveDynamicComponent(component) {
6975 if (isString(component)) {
6976 return resolveAsset(COMPONENTS, component, false) || component;
6977 }
6978 else {
6979 // invalid types will fallthrough to createVNode and raise warning
6980 return (component || NULL_DYNAMIC_COMPONENT);
6981 }
6982}
6983/**
6984 * @private
6985 */
6986function resolveDirective(name) {
6987 return resolveAsset(DIRECTIVES, name);
6988}
6989// implementation
6990function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
6991 const instance = currentRenderingInstance || currentInstance;
6992 if (instance) {
6993 const Component = instance.type;
6994 // explicit self name has highest priority
6995 if (type === COMPONENTS) {
6996 const selfName = getComponentName(Component);
6997 if (selfName &&
6998 (selfName === name ||
6999 selfName === camelize(name) ||
7000 selfName === capitalize(camelize(name)))) {
7001 return Component;
7002 }
7003 }
7004 const res =
7005 // local registration
7006 // check instance[type] first which is resolved for options API
7007 resolve(instance[type] || Component[type], name) ||
7008 // global registration
7009 resolve(instance.appContext[type], name);
7010 if (!res && maybeSelfReference) {
7011 // fallback to implicit self-reference
7012 return Component;
7013 }
7014 if (warnMissing && !res) {
7015 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
7016 }
7017 return res;
7018 }
7019 else {
7020 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7021 `can only be used in render() or setup().`);
7022 }
7023}
7024function resolve(registry, name) {
7025 return (registry &&
7026 (registry[name] ||
7027 registry[camelize(name)] ||
7028 registry[capitalize(camelize(name))]));
7029}
7030
7031const Fragment = Symbol('Fragment' );
7032const Text = Symbol('Text' );
7033const Comment = Symbol('Comment' );
7034const Static = Symbol('Static' );
7035// Since v-if and v-for are the two possible ways node structure can dynamically
7036// change, once we consider v-if branches and each v-for fragment a block, we
7037// can divide a template into nested blocks, and within each block the node
7038// structure would be stable. This allows us to skip most children diffing
7039// and only worry about the dynamic nodes (indicated by patch flags).
7040const blockStack = [];
7041let currentBlock = null;
7042/**
7043 * Open a block.
7044 * This must be called before `createBlock`. It cannot be part of `createBlock`
7045 * because the children of the block are evaluated before `createBlock` itself
7046 * is called. The generated code typically looks like this:
7047 *
7048 * ```js
7049 * function render() {
7050 * return (openBlock(),createBlock('div', null, [...]))
7051 * }
7052 * ```
7053 * disableTracking is true when creating a v-for fragment block, since a v-for
7054 * fragment always diffs its children.
7055 *
7056 * @private
7057 */
7058function openBlock(disableTracking = false) {
7059 blockStack.push((currentBlock = disableTracking ? null : []));
7060}
7061function closeBlock() {
7062 blockStack.pop();
7063 currentBlock = blockStack[blockStack.length - 1] || null;
7064}
7065// Whether we should be tracking dynamic child nodes inside a block.
7066// Only tracks when this value is > 0
7067// We are not using a simple boolean because this value may need to be
7068// incremented/decremented by nested usage of v-once (see below)
7069let isBlockTreeEnabled = 1;
7070/**
7071 * Block tracking sometimes needs to be disabled, for example during the
7072 * creation of a tree that needs to be cached by v-once. The compiler generates
7073 * code like this:
7074 *
7075 * ``` js
7076 * _cache[1] || (
7077 * setBlockTracking(-1),
7078 * _cache[1] = createVNode(...),
7079 * setBlockTracking(1),
7080 * _cache[1]
7081 * )
7082 * ```
7083 *
7084 * @private
7085 */
7086function setBlockTracking(value) {
7087 isBlockTreeEnabled += value;
7088}
7089function setupBlock(vnode) {
7090 // save current block children on the block vnode
7091 vnode.dynamicChildren =
7092 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7093 // close block
7094 closeBlock();
7095 // a block is always going to be patched, so track it as a child of its
7096 // parent block
7097 if (isBlockTreeEnabled > 0 && currentBlock) {
7098 currentBlock.push(vnode);
7099 }
7100 return vnode;
7101}
7102/**
7103 * @private
7104 */
7105function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7106 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7107}
7108/**
7109 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7110 * A block root keeps track of dynamic nodes within the block in the
7111 * `dynamicChildren` array.
7112 *
7113 * @private
7114 */
7115function createBlock(type, props, children, patchFlag, dynamicProps) {
7116 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7117}
7118function isVNode(value) {
7119 return value ? value.__v_isVNode === true : false;
7120}
7121function isSameVNodeType(n1, n2) {
7122 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7123 hmrDirtyComponents.has(n2.type)) {
7124 // HMR only: if the component has been hot-updated, force a reload.
7125 return false;
7126 }
7127 return n1.type === n2.type && n1.key === n2.key;
7128}
7129let vnodeArgsTransformer;
7130/**
7131 * Internal API for registering an arguments transform for createVNode
7132 * used for creating stubs in the test-utils
7133 * It is *internal* but needs to be exposed for test-utils to pick up proper
7134 * typings
7135 */
7136function transformVNodeArgs(transformer) {
7137 vnodeArgsTransformer = transformer;
7138}
7139const createVNodeWithArgsTransform = (...args) => {
7140 return _createVNode(...(vnodeArgsTransformer
7141 ? vnodeArgsTransformer(args, currentRenderingInstance)
7142 : args));
7143};
7144const InternalObjectKey = `__vInternal`;
7145const normalizeKey = ({ key }) => key != null ? key : null;
7146const normalizeRef = ({ ref }) => {
7147 return (ref != null
7148 ? isString(ref) || isRef(ref) || isFunction(ref)
7149 ? { i: currentRenderingInstance, r: ref }
7150 : ref
7151 : null);
7152};
7153function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7154 const vnode = {
7155 __v_isVNode: true,
7156 __v_skip: true,
7157 type,
7158 props,
7159 key: props && normalizeKey(props),
7160 ref: props && normalizeRef(props),
7161 scopeId: currentScopeId,
7162 slotScopeIds: null,
7163 children,
7164 component: null,
7165 suspense: null,
7166 ssContent: null,
7167 ssFallback: null,
7168 dirs: null,
7169 transition: null,
7170 el: null,
7171 anchor: null,
7172 target: null,
7173 targetAnchor: null,
7174 staticCount: 0,
7175 shapeFlag,
7176 patchFlag,
7177 dynamicProps,
7178 dynamicChildren: null,
7179 appContext: null
7180 };
7181 if (needFullChildrenNormalization) {
7182 normalizeChildren(vnode, children);
7183 // normalize suspense children
7184 if (shapeFlag & 128 /* SUSPENSE */) {
7185 type.normalize(vnode);
7186 }
7187 }
7188 else if (children) {
7189 // compiled element vnode - if children is passed, only possible types are
7190 // string or Array.
7191 vnode.shapeFlag |= isString(children)
7192 ? 8 /* TEXT_CHILDREN */
7193 : 16 /* ARRAY_CHILDREN */;
7194 }
7195 // validate key
7196 if (vnode.key !== vnode.key) {
7197 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7198 }
7199 // track vnode for block tree
7200 if (isBlockTreeEnabled > 0 &&
7201 // avoid a block node from tracking itself
7202 !isBlockNode &&
7203 // has current parent block
7204 currentBlock &&
7205 // presence of a patch flag indicates this node needs patching on updates.
7206 // component nodes also should always be patched, because even if the
7207 // component doesn't need to update, it needs to persist the instance on to
7208 // the next vnode so that it can be properly unmounted later.
7209 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7210 // the EVENTS flag is only for hydration and if it is the only flag, the
7211 // vnode should not be considered dynamic due to handler caching.
7212 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7213 currentBlock.push(vnode);
7214 }
7215 return vnode;
7216}
7217const createVNode = (createVNodeWithArgsTransform );
7218function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7219 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7220 if (!type) {
7221 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7222 }
7223 type = Comment;
7224 }
7225 if (isVNode(type)) {
7226 // createVNode receiving an existing vnode. This happens in cases like
7227 // <component :is="vnode"/>
7228 // #2078 make sure to merge refs during the clone instead of overwriting it
7229 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7230 if (children) {
7231 normalizeChildren(cloned, children);
7232 }
7233 return cloned;
7234 }
7235 // class component normalization.
7236 if (isClassComponent(type)) {
7237 type = type.__vccOpts;
7238 }
7239 // class & style normalization.
7240 if (props) {
7241 // for reactive or proxy objects, we need to clone it to enable mutation.
7242 props = guardReactiveProps(props);
7243 let { class: klass, style } = props;
7244 if (klass && !isString(klass)) {
7245 props.class = normalizeClass(klass);
7246 }
7247 if (isObject(style)) {
7248 // reactive state objects need to be cloned since they are likely to be
7249 // mutated
7250 if (isProxy(style) && !isArray(style)) {
7251 style = extend({}, style);
7252 }
7253 props.style = normalizeStyle(style);
7254 }
7255 }
7256 // encode the vnode type information into a bitmap
7257 const shapeFlag = isString(type)
7258 ? 1 /* ELEMENT */
7259 : isSuspense(type)
7260 ? 128 /* SUSPENSE */
7261 : isTeleport(type)
7262 ? 64 /* TELEPORT */
7263 : isObject(type)
7264 ? 4 /* STATEFUL_COMPONENT */
7265 : isFunction(type)
7266 ? 2 /* FUNCTIONAL_COMPONENT */
7267 : 0;
7268 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7269 type = toRaw(type);
7270 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7271 `lead to unnecessary performance overhead, and should be avoided by ` +
7272 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7273 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7274 }
7275 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7276}
7277function guardReactiveProps(props) {
7278 if (!props)
7279 return null;
7280 return isProxy(props) || InternalObjectKey in props
7281 ? extend({}, props)
7282 : props;
7283}
7284function cloneVNode(vnode, extraProps, mergeRef = false) {
7285 // This is intentionally NOT using spread or extend to avoid the runtime
7286 // key enumeration cost.
7287 const { props, ref, patchFlag, children } = vnode;
7288 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7289 const cloned = {
7290 __v_isVNode: true,
7291 __v_skip: true,
7292 type: vnode.type,
7293 props: mergedProps,
7294 key: mergedProps && normalizeKey(mergedProps),
7295 ref: extraProps && extraProps.ref
7296 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7297 // if the vnode itself already has a ref, cloneVNode will need to merge
7298 // the refs so the single vnode can be set on multiple refs
7299 mergeRef && ref
7300 ? isArray(ref)
7301 ? ref.concat(normalizeRef(extraProps))
7302 : [ref, normalizeRef(extraProps)]
7303 : normalizeRef(extraProps)
7304 : ref,
7305 scopeId: vnode.scopeId,
7306 slotScopeIds: vnode.slotScopeIds,
7307 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7308 ? children.map(deepCloneVNode)
7309 : children,
7310 target: vnode.target,
7311 targetAnchor: vnode.targetAnchor,
7312 staticCount: vnode.staticCount,
7313 shapeFlag: vnode.shapeFlag,
7314 // if the vnode is cloned with extra props, we can no longer assume its
7315 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7316 // note: perserve flag for fragments since they use the flag for children
7317 // fast paths only.
7318 patchFlag: extraProps && vnode.type !== Fragment
7319 ? patchFlag === -1 // hoisted node
7320 ? 16 /* FULL_PROPS */
7321 : patchFlag | 16 /* FULL_PROPS */
7322 : patchFlag,
7323 dynamicProps: vnode.dynamicProps,
7324 dynamicChildren: vnode.dynamicChildren,
7325 appContext: vnode.appContext,
7326 dirs: vnode.dirs,
7327 transition: vnode.transition,
7328 // These should technically only be non-null on mounted VNodes. However,
7329 // they *should* be copied for kept-alive vnodes. So we just always copy
7330 // them since them being non-null during a mount doesn't affect the logic as
7331 // they will simply be overwritten.
7332 component: vnode.component,
7333 suspense: vnode.suspense,
7334 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7335 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7336 el: vnode.el,
7337 anchor: vnode.anchor
7338 };
7339 return cloned;
7340}
7341/**
7342 * Dev only, for HMR of hoisted vnodes reused in v-for
7343 * https://github.com/vitejs/vite/issues/2022
7344 */
7345function deepCloneVNode(vnode) {
7346 const cloned = cloneVNode(vnode);
7347 if (isArray(vnode.children)) {
7348 cloned.children = vnode.children.map(deepCloneVNode);
7349 }
7350 return cloned;
7351}
7352/**
7353 * @private
7354 */
7355function createTextVNode(text = ' ', flag = 0) {
7356 return createVNode(Text, null, text, flag);
7357}
7358/**
7359 * @private
7360 */
7361function createStaticVNode(content, numberOfNodes) {
7362 // A static vnode can contain multiple stringified elements, and the number
7363 // of elements is necessary for hydration.
7364 const vnode = createVNode(Static, null, content);
7365 vnode.staticCount = numberOfNodes;
7366 return vnode;
7367}
7368/**
7369 * @private
7370 */
7371function createCommentVNode(text = '',
7372// when used as the v-else branch, the comment node must be created as a
7373// block to ensure correct updates.
7374asBlock = false) {
7375 return asBlock
7376 ? (openBlock(), createBlock(Comment, null, text))
7377 : createVNode(Comment, null, text);
7378}
7379function normalizeVNode(child) {
7380 if (child == null || typeof child === 'boolean') {
7381 // empty placeholder
7382 return createVNode(Comment);
7383 }
7384 else if (isArray(child)) {
7385 // fragment
7386 return createVNode(Fragment, null,
7387 // #3666, avoid reference pollution when reusing vnode
7388 child.slice());
7389 }
7390 else if (typeof child === 'object') {
7391 // already vnode, this should be the most common since compiled templates
7392 // always produce all-vnode children arrays
7393 return cloneIfMounted(child);
7394 }
7395 else {
7396 // strings and numbers
7397 return createVNode(Text, null, String(child));
7398 }
7399}
7400// optimized normalization for template-compiled render fns
7401function cloneIfMounted(child) {
7402 return child.el === null || child.memo ? child : cloneVNode(child);
7403}
7404function normalizeChildren(vnode, children) {
7405 let type = 0;
7406 const { shapeFlag } = vnode;
7407 if (children == null) {
7408 children = null;
7409 }
7410 else if (isArray(children)) {
7411 type = 16 /* ARRAY_CHILDREN */;
7412 }
7413 else if (typeof children === 'object') {
7414 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7415 // Normalize slot to plain children for plain element and Teleport
7416 const slot = children.default;
7417 if (slot) {
7418 // _c marker is added by withCtx() indicating this is a compiled slot
7419 slot._c && (slot._d = false);
7420 normalizeChildren(vnode, slot());
7421 slot._c && (slot._d = true);
7422 }
7423 return;
7424 }
7425 else {
7426 type = 32 /* SLOTS_CHILDREN */;
7427 const slotFlag = children._;
7428 if (!slotFlag && !(InternalObjectKey in children)) {
7429 children._ctx = currentRenderingInstance;
7430 }
7431 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7432 // a child component receives forwarded slots from the parent.
7433 // its slot type is determined by its parent's slot type.
7434 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7435 children._ = 1 /* STABLE */;
7436 }
7437 else {
7438 children._ = 2 /* DYNAMIC */;
7439 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7440 }
7441 }
7442 }
7443 }
7444 else if (isFunction(children)) {
7445 children = { default: children, _ctx: currentRenderingInstance };
7446 type = 32 /* SLOTS_CHILDREN */;
7447 }
7448 else {
7449 children = String(children);
7450 // force teleport children to array so it can be moved around
7451 if (shapeFlag & 64 /* TELEPORT */) {
7452 type = 16 /* ARRAY_CHILDREN */;
7453 children = [createTextVNode(children)];
7454 }
7455 else {
7456 type = 8 /* TEXT_CHILDREN */;
7457 }
7458 }
7459 vnode.children = children;
7460 vnode.shapeFlag |= type;
7461}
7462function mergeProps(...args) {
7463 const ret = {};
7464 for (let i = 0; i < args.length; i++) {
7465 const toMerge = args[i];
7466 for (const key in toMerge) {
7467 if (key === 'class') {
7468 if (ret.class !== toMerge.class) {
7469 ret.class = normalizeClass([ret.class, toMerge.class]);
7470 }
7471 }
7472 else if (key === 'style') {
7473 ret.style = normalizeStyle([ret.style, toMerge.style]);
7474 }
7475 else if (isOn(key)) {
7476 const existing = ret[key];
7477 const incoming = toMerge[key];
7478 if (existing !== incoming) {
7479 ret[key] = existing
7480 ? [].concat(existing, incoming)
7481 : incoming;
7482 }
7483 }
7484 else if (key !== '') {
7485 ret[key] = toMerge[key];
7486 }
7487 }
7488 }
7489 return ret;
7490}
7491
7492/**
7493 * Actual implementation
7494 */
7495function renderList(source, renderItem, cache, index) {
7496 let ret;
7497 const cached = (cache && cache[index]);
7498 if (isArray(source) || isString(source)) {
7499 ret = new Array(source.length);
7500 for (let i = 0, l = source.length; i < l; i++) {
7501 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
7502 }
7503 }
7504 else if (typeof source === 'number') {
7505 if (!Number.isInteger(source)) {
7506 warn$1(`The v-for range expect an integer value but got ${source}.`);
7507 return [];
7508 }
7509 ret = new Array(source);
7510 for (let i = 0; i < source; i++) {
7511 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
7512 }
7513 }
7514 else if (isObject(source)) {
7515 if (source[Symbol.iterator]) {
7516 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
7517 }
7518 else {
7519 const keys = Object.keys(source);
7520 ret = new Array(keys.length);
7521 for (let i = 0, l = keys.length; i < l; i++) {
7522 const key = keys[i];
7523 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
7524 }
7525 }
7526 }
7527 else {
7528 ret = [];
7529 }
7530 if (cache) {
7531 cache[index] = ret;
7532 }
7533 return ret;
7534}
7535
7536/**
7537 * Compiler runtime helper for creating dynamic slots object
7538 * @private
7539 */
7540function createSlots(slots, dynamicSlots) {
7541 for (let i = 0; i < dynamicSlots.length; i++) {
7542 const slot = dynamicSlots[i];
7543 // array of dynamic slot generated by <template v-for="..." #[...]>
7544 if (isArray(slot)) {
7545 for (let j = 0; j < slot.length; j++) {
7546 slots[slot[j].name] = slot[j].fn;
7547 }
7548 }
7549 else if (slot) {
7550 // conditional single slot generated by <template v-if="..." #foo>
7551 slots[slot.name] = slot.fn;
7552 }
7553 }
7554 return slots;
7555}
7556
7557/**
7558 * Compiler runtime helper for rendering `<slot/>`
7559 * @private
7560 */
7561function renderSlot(slots, name, props = {},
7562// this is not a user-facing function, so the fallback is always generated by
7563// the compiler and guaranteed to be a function returning an array
7564fallback, noSlotted) {
7565 if (currentRenderingInstance.isCE) {
7566 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
7567 }
7568 let slot = slots[name];
7569 if (slot && slot.length > 1) {
7570 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
7571 `function. You need to mark this component with $dynamic-slots in the ` +
7572 `parent template.`);
7573 slot = () => [];
7574 }
7575 // a compiled slot disables block tracking by default to avoid manual
7576 // invocation interfering with template-based block tracking, but in
7577 // `renderSlot` we can be sure that it's template-based so we can force
7578 // enable it.
7579 if (slot && slot._c) {
7580 slot._d = false;
7581 }
7582 openBlock();
7583 const validSlotContent = slot && ensureValidVNode(slot(props));
7584 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
7585 ? 64 /* STABLE_FRAGMENT */
7586 : -2 /* BAIL */);
7587 if (!noSlotted && rendered.scopeId) {
7588 rendered.slotScopeIds = [rendered.scopeId + '-s'];
7589 }
7590 if (slot && slot._c) {
7591 slot._d = true;
7592 }
7593 return rendered;
7594}
7595function ensureValidVNode(vnodes) {
7596 return vnodes.some(child => {
7597 if (!isVNode(child))
7598 return true;
7599 if (child.type === Comment)
7600 return false;
7601 if (child.type === Fragment &&
7602 !ensureValidVNode(child.children))
7603 return false;
7604 return true;
7605 })
7606 ? vnodes
7607 : null;
7608}
7609
7610/**
7611 * For prefixing keys in v-on="obj" with "on"
7612 * @private
7613 */
7614function toHandlers(obj) {
7615 const ret = {};
7616 if (!isObject(obj)) {
7617 warn$1(`v-on with no argument expects an object value.`);
7618 return ret;
7619 }
7620 for (const key in obj) {
7621 ret[toHandlerKey(key)] = obj[key];
7622 }
7623 return ret;
7624}
7625
7626/**
7627 * #2437 In Vue 3, functional components do not have a public instance proxy but
7628 * they exist in the internal parent chain. For code that relies on traversing
7629 * public $parent chains, skip functional ones and go to the parent instead.
7630 */
7631const getPublicInstance = (i) => {
7632 if (!i)
7633 return null;
7634 if (isStatefulComponent(i))
7635 return getExposeProxy(i) || i.proxy;
7636 return getPublicInstance(i.parent);
7637};
7638const publicPropertiesMap = extend(Object.create(null), {
7639 $: i => i,
7640 $el: i => i.vnode.el,
7641 $data: i => i.data,
7642 $props: i => (shallowReadonly(i.props) ),
7643 $attrs: i => (shallowReadonly(i.attrs) ),
7644 $slots: i => (shallowReadonly(i.slots) ),
7645 $refs: i => (shallowReadonly(i.refs) ),
7646 $parent: i => getPublicInstance(i.parent),
7647 $root: i => getPublicInstance(i.root),
7648 $emit: i => i.emit,
7649 $options: i => (resolveMergedOptions(i) ),
7650 $forceUpdate: i => () => queueJob(i.update),
7651 $nextTick: i => nextTick.bind(i.proxy),
7652 $watch: i => (instanceWatch.bind(i) )
7653});
7654const PublicInstanceProxyHandlers = {
7655 get({ _: instance }, key) {
7656 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7657 // for internal formatters to know that this is a Vue instance
7658 if (key === '__isVue') {
7659 return true;
7660 }
7661 // prioritize <script setup> bindings during dev.
7662 // this allows even properties that start with _ or $ to be used - so that
7663 // it aligns with the production behavior where the render fn is inlined and
7664 // indeed has access to all declared variables.
7665 if (setupState !== EMPTY_OBJ &&
7666 setupState.__isScriptSetup &&
7667 hasOwn(setupState, key)) {
7668 return setupState[key];
7669 }
7670 // data / props / ctx
7671 // This getter gets called for every property access on the render context
7672 // during render and is a major hotspot. The most expensive part of this
7673 // is the multiple hasOwn() calls. It's much faster to do a simple property
7674 // access on a plain object, so we use an accessCache object (with null
7675 // prototype) to memoize what access type a key corresponds to.
7676 let normalizedProps;
7677 if (key[0] !== '$') {
7678 const n = accessCache[key];
7679 if (n !== undefined) {
7680 switch (n) {
7681 case 0 /* SETUP */:
7682 return setupState[key];
7683 case 1 /* DATA */:
7684 return data[key];
7685 case 3 /* CONTEXT */:
7686 return ctx[key];
7687 case 2 /* PROPS */:
7688 return props[key];
7689 // default: just fallthrough
7690 }
7691 }
7692 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7693 accessCache[key] = 0 /* SETUP */;
7694 return setupState[key];
7695 }
7696 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7697 accessCache[key] = 1 /* DATA */;
7698 return data[key];
7699 }
7700 else if (
7701 // only cache other properties when instance has declared (thus stable)
7702 // props
7703 (normalizedProps = instance.propsOptions[0]) &&
7704 hasOwn(normalizedProps, key)) {
7705 accessCache[key] = 2 /* PROPS */;
7706 return props[key];
7707 }
7708 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7709 accessCache[key] = 3 /* CONTEXT */;
7710 return ctx[key];
7711 }
7712 else if (shouldCacheAccess) {
7713 accessCache[key] = 4 /* OTHER */;
7714 }
7715 }
7716 const publicGetter = publicPropertiesMap[key];
7717 let cssModule, globalProperties;
7718 // public $xxx properties
7719 if (publicGetter) {
7720 if (key === '$attrs') {
7721 track(instance, "get" /* GET */, key);
7722 markAttrsAccessed();
7723 }
7724 return publicGetter(instance);
7725 }
7726 else if (
7727 // css module (injected by vue-loader)
7728 (cssModule = type.__cssModules) &&
7729 (cssModule = cssModule[key])) {
7730 return cssModule;
7731 }
7732 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7733 // user may set custom properties to `this` that start with `$`
7734 accessCache[key] = 3 /* CONTEXT */;
7735 return ctx[key];
7736 }
7737 else if (
7738 // global properties
7739 ((globalProperties = appContext.config.globalProperties),
7740 hasOwn(globalProperties, key))) {
7741 {
7742 return globalProperties[key];
7743 }
7744 }
7745 else if (currentRenderingInstance &&
7746 (!isString(key) ||
7747 // #1091 avoid internal isRef/isVNode checks on component instance leading
7748 // to infinite warning loop
7749 key.indexOf('__v') !== 0)) {
7750 if (data !== EMPTY_OBJ &&
7751 (key[0] === '$' || key[0] === '_') &&
7752 hasOwn(data, key)) {
7753 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
7754 `character ("$" or "_") and is not proxied on the render context.`);
7755 }
7756 else if (instance === currentRenderingInstance) {
7757 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
7758 `but is not defined on instance.`);
7759 }
7760 }
7761 },
7762 set({ _: instance }, key, value) {
7763 const { data, setupState, ctx } = instance;
7764 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7765 setupState[key] = value;
7766 }
7767 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7768 data[key] = value;
7769 }
7770 else if (hasOwn(instance.props, key)) {
7771 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
7772 return false;
7773 }
7774 if (key[0] === '$' && key.slice(1) in instance) {
7775 warn$1(`Attempting to mutate public property "${key}". ` +
7776 `Properties starting with $ are reserved and readonly.`, instance);
7777 return false;
7778 }
7779 else {
7780 if (key in instance.appContext.config.globalProperties) {
7781 Object.defineProperty(ctx, key, {
7782 enumerable: true,
7783 configurable: true,
7784 value
7785 });
7786 }
7787 else {
7788 ctx[key] = value;
7789 }
7790 }
7791 return true;
7792 },
7793 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
7794 let normalizedProps;
7795 return (accessCache[key] !== undefined ||
7796 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
7797 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
7798 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
7799 hasOwn(ctx, key) ||
7800 hasOwn(publicPropertiesMap, key) ||
7801 hasOwn(appContext.config.globalProperties, key));
7802 }
7803};
7804{
7805 PublicInstanceProxyHandlers.ownKeys = (target) => {
7806 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
7807 `The keys will be empty in production mode to avoid performance overhead.`);
7808 return Reflect.ownKeys(target);
7809 };
7810}
7811const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
7812 get(target, key) {
7813 // fast path for unscopables when using `with` block
7814 if (key === Symbol.unscopables) {
7815 return;
7816 }
7817 return PublicInstanceProxyHandlers.get(target, key, target);
7818 },
7819 has(_, key) {
7820 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
7821 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
7822 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
7823 }
7824 return has;
7825 }
7826});
7827// dev only
7828// In dev mode, the proxy target exposes the same properties as seen on `this`
7829// for easier console inspection. In prod mode it will be an empty object so
7830// these properties definitions can be skipped.
7831function createDevRenderContext(instance) {
7832 const target = {};
7833 // expose internal instance for proxy handlers
7834 Object.defineProperty(target, `_`, {
7835 configurable: true,
7836 enumerable: false,
7837 get: () => instance
7838 });
7839 // expose public properties
7840 Object.keys(publicPropertiesMap).forEach(key => {
7841 Object.defineProperty(target, key, {
7842 configurable: true,
7843 enumerable: false,
7844 get: () => publicPropertiesMap[key](instance),
7845 // intercepted by the proxy so no need for implementation,
7846 // but needed to prevent set errors
7847 set: NOOP
7848 });
7849 });
7850 return target;
7851}
7852// dev only
7853function exposePropsOnRenderContext(instance) {
7854 const { ctx, propsOptions: [propsOptions] } = instance;
7855 if (propsOptions) {
7856 Object.keys(propsOptions).forEach(key => {
7857 Object.defineProperty(ctx, key, {
7858 enumerable: true,
7859 configurable: true,
7860 get: () => instance.props[key],
7861 set: NOOP
7862 });
7863 });
7864 }
7865}
7866// dev only
7867function exposeSetupStateOnRenderContext(instance) {
7868 const { ctx, setupState } = instance;
7869 Object.keys(toRaw(setupState)).forEach(key => {
7870 if (!setupState.__isScriptSetup && (key[0] === '$' || key[0] === '_')) {
7871 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
7872 `which are reserved prefixes for Vue internals.`);
7873 return;
7874 }
7875 Object.defineProperty(ctx, key, {
7876 enumerable: true,
7877 configurable: true,
7878 get: () => setupState[key],
7879 set: NOOP
7880 });
7881 });
7882}
7883
7884const emptyAppContext = createAppContext();
7885let uid$1 = 0;
7886function createComponentInstance(vnode, parent, suspense) {
7887 const type = vnode.type;
7888 // inherit parent app context - or - if root, adopt from root vnode
7889 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
7890 const instance = {
7891 uid: uid$1++,
7892 vnode,
7893 type,
7894 parent,
7895 appContext,
7896 root: null,
7897 next: null,
7898 subTree: null,
7899 update: null,
7900 scope: new EffectScope(true /* detached */),
7901 render: null,
7902 proxy: null,
7903 exposed: null,
7904 exposeProxy: null,
7905 withProxy: null,
7906 provides: parent ? parent.provides : Object.create(appContext.provides),
7907 accessCache: null,
7908 renderCache: [],
7909 // local resovled assets
7910 components: null,
7911 directives: null,
7912 // resolved props and emits options
7913 propsOptions: normalizePropsOptions(type, appContext),
7914 emitsOptions: normalizeEmitsOptions(type, appContext),
7915 // emit
7916 emit: null,
7917 emitted: null,
7918 // props default value
7919 propsDefaults: EMPTY_OBJ,
7920 // inheritAttrs
7921 inheritAttrs: type.inheritAttrs,
7922 // state
7923 ctx: EMPTY_OBJ,
7924 data: EMPTY_OBJ,
7925 props: EMPTY_OBJ,
7926 attrs: EMPTY_OBJ,
7927 slots: EMPTY_OBJ,
7928 refs: EMPTY_OBJ,
7929 setupState: EMPTY_OBJ,
7930 setupContext: null,
7931 // suspense related
7932 suspense,
7933 suspenseId: suspense ? suspense.pendingId : 0,
7934 asyncDep: null,
7935 asyncResolved: false,
7936 // lifecycle hooks
7937 // not using enums here because it results in computed properties
7938 isMounted: false,
7939 isUnmounted: false,
7940 isDeactivated: false,
7941 bc: null,
7942 c: null,
7943 bm: null,
7944 m: null,
7945 bu: null,
7946 u: null,
7947 um: null,
7948 bum: null,
7949 da: null,
7950 a: null,
7951 rtg: null,
7952 rtc: null,
7953 ec: null,
7954 sp: null
7955 };
7956 {
7957 instance.ctx = createDevRenderContext(instance);
7958 }
7959 instance.root = parent ? parent.root : instance;
7960 instance.emit = emit.bind(null, instance);
7961 // apply custom element special handling
7962 if (vnode.ce) {
7963 vnode.ce(instance);
7964 }
7965 return instance;
7966}
7967let currentInstance = null;
7968const getCurrentInstance = () => currentInstance || currentRenderingInstance;
7969const setCurrentInstance = (instance) => {
7970 currentInstance = instance;
7971 instance.scope.on();
7972};
7973const unsetCurrentInstance = () => {
7974 currentInstance && currentInstance.scope.off();
7975 currentInstance = null;
7976};
7977const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
7978function validateComponentName(name, config) {
7979 const appIsNativeTag = config.isNativeTag || NO;
7980 if (isBuiltInTag(name) || appIsNativeTag(name)) {
7981 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
7982 }
7983}
7984function isStatefulComponent(instance) {
7985 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
7986}
7987let isInSSRComponentSetup = false;
7988function setupComponent(instance, isSSR = false) {
7989 isInSSRComponentSetup = isSSR;
7990 const { props, children } = instance.vnode;
7991 const isStateful = isStatefulComponent(instance);
7992 initProps(instance, props, isStateful, isSSR);
7993 initSlots(instance, children);
7994 const setupResult = isStateful
7995 ? setupStatefulComponent(instance, isSSR)
7996 : undefined;
7997 isInSSRComponentSetup = false;
7998 return setupResult;
7999}
8000function setupStatefulComponent(instance, isSSR) {
8001 const Component = instance.type;
8002 {
8003 if (Component.name) {
8004 validateComponentName(Component.name, instance.appContext.config);
8005 }
8006 if (Component.components) {
8007 const names = Object.keys(Component.components);
8008 for (let i = 0; i < names.length; i++) {
8009 validateComponentName(names[i], instance.appContext.config);
8010 }
8011 }
8012 if (Component.directives) {
8013 const names = Object.keys(Component.directives);
8014 for (let i = 0; i < names.length; i++) {
8015 validateDirectiveName(names[i]);
8016 }
8017 }
8018 if (Component.compilerOptions && isRuntimeOnly()) {
8019 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8020 `includes the runtime compiler. Since you are using a runtime-only ` +
8021 `build, the options should be passed via your build tool config instead.`);
8022 }
8023 }
8024 // 0. create render proxy property access cache
8025 instance.accessCache = Object.create(null);
8026 // 1. create public instance / render proxy
8027 // also mark it raw so it's never observed
8028 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8029 {
8030 exposePropsOnRenderContext(instance);
8031 }
8032 // 2. call setup()
8033 const { setup } = Component;
8034 if (setup) {
8035 const setupContext = (instance.setupContext =
8036 setup.length > 1 ? createSetupContext(instance) : null);
8037 setCurrentInstance(instance);
8038 pauseTracking();
8039 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8040 resetTracking();
8041 unsetCurrentInstance();
8042 if (isPromise(setupResult)) {
8043 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8044 if (isSSR) {
8045 // return the promise so server-renderer can wait on it
8046 return setupResult
8047 .then((resolvedResult) => {
8048 handleSetupResult(instance, resolvedResult, isSSR);
8049 })
8050 .catch(e => {
8051 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8052 });
8053 }
8054 else {
8055 // async setup returned Promise.
8056 // bail here and wait for re-entry.
8057 instance.asyncDep = setupResult;
8058 }
8059 }
8060 else {
8061 handleSetupResult(instance, setupResult, isSSR);
8062 }
8063 }
8064 else {
8065 finishComponentSetup(instance, isSSR);
8066 }
8067}
8068function handleSetupResult(instance, setupResult, isSSR) {
8069 if (isFunction(setupResult)) {
8070 // setup returned an inline render function
8071 {
8072 instance.render = setupResult;
8073 }
8074 }
8075 else if (isObject(setupResult)) {
8076 if (isVNode(setupResult)) {
8077 warn$1(`setup() should not return VNodes directly - ` +
8078 `return a render function instead.`);
8079 }
8080 // setup returned bindings.
8081 // assuming a render function compiled from template is present.
8082 {
8083 instance.devtoolsRawSetupState = setupResult;
8084 }
8085 instance.setupState = proxyRefs(setupResult);
8086 {
8087 exposeSetupStateOnRenderContext(instance);
8088 }
8089 }
8090 else if (setupResult !== undefined) {
8091 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8092 }
8093 finishComponentSetup(instance, isSSR);
8094}
8095let compile;
8096let installWithProxy;
8097/**
8098 * For runtime-dom to register the compiler.
8099 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8100 */
8101function registerRuntimeCompiler(_compile) {
8102 compile = _compile;
8103 installWithProxy = i => {
8104 if (i.render._rc) {
8105 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8106 }
8107 };
8108}
8109// dev only
8110const isRuntimeOnly = () => !compile;
8111function finishComponentSetup(instance, isSSR, skipOptions) {
8112 const Component = instance.type;
8113 // template / render function normalization
8114 if (!instance.render) {
8115 // could be set from setup()
8116 if (compile && !Component.render) {
8117 const template = Component.template;
8118 if (template) {
8119 {
8120 startMeasure(instance, `compile`);
8121 }
8122 const { isCustomElement, compilerOptions } = instance.appContext.config;
8123 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8124 const finalCompilerOptions = extend(extend({
8125 isCustomElement,
8126 delimiters
8127 }, compilerOptions), componentCompilerOptions);
8128 Component.render = compile(template, finalCompilerOptions);
8129 {
8130 endMeasure(instance, `compile`);
8131 }
8132 }
8133 }
8134 instance.render = (Component.render || NOOP);
8135 // for runtime-compiled render functions using `with` blocks, the render
8136 // proxy used needs a different `has` handler which is more performant and
8137 // also only allows a whitelist of globals to fallthrough.
8138 if (installWithProxy) {
8139 installWithProxy(instance);
8140 }
8141 }
8142 // support for 2.x options
8143 {
8144 setCurrentInstance(instance);
8145 pauseTracking();
8146 applyOptions(instance);
8147 resetTracking();
8148 unsetCurrentInstance();
8149 }
8150 // warn missing template/render
8151 // the runtime compilation of template in SSR is done by server-render
8152 if (!Component.render && instance.render === NOOP && !isSSR) {
8153 /* istanbul ignore if */
8154 if (!compile && Component.template) {
8155 warn$1(`Component provided template option but ` +
8156 `runtime compilation is not supported in this build of Vue.` +
8157 (` Use "vue.esm-browser.js" instead.`
8158 ) /* should not happen */);
8159 }
8160 else {
8161 warn$1(`Component is missing template or render function.`);
8162 }
8163 }
8164}
8165function createAttrsProxy(instance) {
8166 return new Proxy(instance.attrs, {
8167 get(target, key) {
8168 markAttrsAccessed();
8169 track(instance, "get" /* GET */, '$attrs');
8170 return target[key];
8171 },
8172 set() {
8173 warn$1(`setupContext.attrs is readonly.`);
8174 return false;
8175 },
8176 deleteProperty() {
8177 warn$1(`setupContext.attrs is readonly.`);
8178 return false;
8179 }
8180 }
8181 );
8182}
8183function createSetupContext(instance) {
8184 const expose = exposed => {
8185 if (instance.exposed) {
8186 warn$1(`expose() should be called only once per setup().`);
8187 }
8188 instance.exposed = exposed || {};
8189 };
8190 let attrs;
8191 {
8192 // We use getters in dev in case libs like test-utils overwrite instance
8193 // properties (overwrites should not be done in prod)
8194 return Object.freeze({
8195 get attrs() {
8196 return attrs || (attrs = createAttrsProxy(instance));
8197 },
8198 get slots() {
8199 return shallowReadonly(instance.slots);
8200 },
8201 get emit() {
8202 return (event, ...args) => instance.emit(event, ...args);
8203 },
8204 expose
8205 });
8206 }
8207}
8208function getExposeProxy(instance) {
8209 if (instance.exposed) {
8210 return (instance.exposeProxy ||
8211 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8212 get(target, key) {
8213 if (key in target) {
8214 return target[key];
8215 }
8216 else if (key in publicPropertiesMap) {
8217 return publicPropertiesMap[key](instance);
8218 }
8219 }
8220 })));
8221 }
8222}
8223const classifyRE = /(?:^|[-_])(\w)/g;
8224const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8225function getComponentName(Component) {
8226 return isFunction(Component)
8227 ? Component.displayName || Component.name
8228 : Component.name;
8229}
8230/* istanbul ignore next */
8231function formatComponentName(instance, Component, isRoot = false) {
8232 let name = getComponentName(Component);
8233 if (!name && Component.__file) {
8234 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8235 if (match) {
8236 name = match[1];
8237 }
8238 }
8239 if (!name && instance && instance.parent) {
8240 // try to infer the name based on reverse resolution
8241 const inferFromRegistry = (registry) => {
8242 for (const key in registry) {
8243 if (registry[key] === Component) {
8244 return key;
8245 }
8246 }
8247 };
8248 name =
8249 inferFromRegistry(instance.components ||
8250 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8251 }
8252 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8253}
8254function isClassComponent(value) {
8255 return isFunction(value) && '__vccOpts' in value;
8256}
8257
8258const stack = [];
8259function pushWarningContext(vnode) {
8260 stack.push(vnode);
8261}
8262function popWarningContext() {
8263 stack.pop();
8264}
8265function warn$1(msg, ...args) {
8266 // avoid props formatting or warn handler tracking deps that might be mutated
8267 // during patch, leading to infinite recursion.
8268 pauseTracking();
8269 const instance = stack.length ? stack[stack.length - 1].component : null;
8270 const appWarnHandler = instance && instance.appContext.config.warnHandler;
8271 const trace = getComponentTrace();
8272 if (appWarnHandler) {
8273 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
8274 msg + args.join(''),
8275 instance && instance.proxy,
8276 trace
8277 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
8278 .join('\n'),
8279 trace
8280 ]);
8281 }
8282 else {
8283 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
8284 /* istanbul ignore if */
8285 if (trace.length &&
8286 // avoid spamming console during tests
8287 !false) {
8288 warnArgs.push(`\n`, ...formatTrace(trace));
8289 }
8290 console.warn(...warnArgs);
8291 }
8292 resetTracking();
8293}
8294function getComponentTrace() {
8295 let currentVNode = stack[stack.length - 1];
8296 if (!currentVNode) {
8297 return [];
8298 }
8299 // we can't just use the stack because it will be incomplete during updates
8300 // that did not start from the root. Re-construct the parent chain using
8301 // instance parent pointers.
8302 const normalizedStack = [];
8303 while (currentVNode) {
8304 const last = normalizedStack[0];
8305 if (last && last.vnode === currentVNode) {
8306 last.recurseCount++;
8307 }
8308 else {
8309 normalizedStack.push({
8310 vnode: currentVNode,
8311 recurseCount: 0
8312 });
8313 }
8314 const parentInstance = currentVNode.component && currentVNode.component.parent;
8315 currentVNode = parentInstance && parentInstance.vnode;
8316 }
8317 return normalizedStack;
8318}
8319/* istanbul ignore next */
8320function formatTrace(trace) {
8321 const logs = [];
8322 trace.forEach((entry, i) => {
8323 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
8324 });
8325 return logs;
8326}
8327function formatTraceEntry({ vnode, recurseCount }) {
8328 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
8329 const isRoot = vnode.component ? vnode.component.parent == null : false;
8330 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
8331 const close = `>` + postfix;
8332 return vnode.props
8333 ? [open, ...formatProps(vnode.props), close]
8334 : [open + close];
8335}
8336/* istanbul ignore next */
8337function formatProps(props) {
8338 const res = [];
8339 const keys = Object.keys(props);
8340 keys.slice(0, 3).forEach(key => {
8341 res.push(...formatProp(key, props[key]));
8342 });
8343 if (keys.length > 3) {
8344 res.push(` ...`);
8345 }
8346 return res;
8347}
8348/* istanbul ignore next */
8349function formatProp(key, value, raw) {
8350 if (isString(value)) {
8351 value = JSON.stringify(value);
8352 return raw ? value : [`${key}=${value}`];
8353 }
8354 else if (typeof value === 'number' ||
8355 typeof value === 'boolean' ||
8356 value == null) {
8357 return raw ? value : [`${key}=${value}`];
8358 }
8359 else if (isRef(value)) {
8360 value = formatProp(key, toRaw(value.value), true);
8361 return raw ? value : [`${key}=Ref<`, value, `>`];
8362 }
8363 else if (isFunction(value)) {
8364 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
8365 }
8366 else {
8367 value = toRaw(value);
8368 return raw ? value : [`${key}=`, value];
8369 }
8370}
8371
8372const ErrorTypeStrings = {
8373 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
8374 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
8375 ["c" /* CREATED */]: 'created hook',
8376 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
8377 ["m" /* MOUNTED */]: 'mounted hook',
8378 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
8379 ["u" /* UPDATED */]: 'updated',
8380 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
8381 ["um" /* UNMOUNTED */]: 'unmounted hook',
8382 ["a" /* ACTIVATED */]: 'activated hook',
8383 ["da" /* DEACTIVATED */]: 'deactivated hook',
8384 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
8385 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
8386 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
8387 [0 /* SETUP_FUNCTION */]: 'setup function',
8388 [1 /* RENDER_FUNCTION */]: 'render function',
8389 [2 /* WATCH_GETTER */]: 'watcher getter',
8390 [3 /* WATCH_CALLBACK */]: 'watcher callback',
8391 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
8392 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
8393 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
8394 [7 /* VNODE_HOOK */]: 'vnode hook',
8395 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
8396 [9 /* TRANSITION_HOOK */]: 'transition hook',
8397 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
8398 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
8399 [12 /* FUNCTION_REF */]: 'ref function',
8400 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
8401 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
8402 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
8403};
8404function callWithErrorHandling(fn, instance, type, args) {
8405 let res;
8406 try {
8407 res = args ? fn(...args) : fn();
8408 }
8409 catch (err) {
8410 handleError(err, instance, type);
8411 }
8412 return res;
8413}
8414function callWithAsyncErrorHandling(fn, instance, type, args) {
8415 if (isFunction(fn)) {
8416 const res = callWithErrorHandling(fn, instance, type, args);
8417 if (res && isPromise(res)) {
8418 res.catch(err => {
8419 handleError(err, instance, type);
8420 });
8421 }
8422 return res;
8423 }
8424 const values = [];
8425 for (let i = 0; i < fn.length; i++) {
8426 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
8427 }
8428 return values;
8429}
8430function handleError(err, instance, type, throwInDev = true) {
8431 const contextVNode = instance ? instance.vnode : null;
8432 if (instance) {
8433 let cur = instance.parent;
8434 // the exposed instance is the render proxy to keep it consistent with 2.x
8435 const exposedInstance = instance.proxy;
8436 // in production the hook receives only the error code
8437 const errorInfo = ErrorTypeStrings[type] ;
8438 while (cur) {
8439 const errorCapturedHooks = cur.ec;
8440 if (errorCapturedHooks) {
8441 for (let i = 0; i < errorCapturedHooks.length; i++) {
8442 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
8443 return;
8444 }
8445 }
8446 }
8447 cur = cur.parent;
8448 }
8449 // app-level handling
8450 const appErrorHandler = instance.appContext.config.errorHandler;
8451 if (appErrorHandler) {
8452 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
8453 return;
8454 }
8455 }
8456 logError(err, type, contextVNode, throwInDev);
8457}
8458function logError(err, type, contextVNode, throwInDev = true) {
8459 {
8460 const info = ErrorTypeStrings[type];
8461 if (contextVNode) {
8462 pushWarningContext(contextVNode);
8463 }
8464 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
8465 if (contextVNode) {
8466 popWarningContext();
8467 }
8468 // crash in dev by default so it's more noticeable
8469 if (throwInDev) {
8470 throw err;
8471 }
8472 else {
8473 console.error(err);
8474 }
8475 }
8476}
8477
8478let isFlushing = false;
8479let isFlushPending = false;
8480const queue = [];
8481let flushIndex = 0;
8482const pendingPreFlushCbs = [];
8483let activePreFlushCbs = null;
8484let preFlushIndex = 0;
8485const pendingPostFlushCbs = [];
8486let activePostFlushCbs = null;
8487let postFlushIndex = 0;
8488const resolvedPromise = Promise.resolve();
8489let currentFlushPromise = null;
8490let currentPreFlushParentJob = null;
8491const RECURSION_LIMIT = 100;
8492function nextTick(fn) {
8493 const p = currentFlushPromise || resolvedPromise;
8494 return fn ? p.then(this ? fn.bind(this) : fn) : p;
8495}
8496// #2768
8497// Use binary-search to find a suitable position in the queue,
8498// so that the queue maintains the increasing order of job's id,
8499// which can prevent the job from being skipped and also can avoid repeated patching.
8500function findInsertionIndex(id) {
8501 // the start index should be `flushIndex + 1`
8502 let start = flushIndex + 1;
8503 let end = queue.length;
8504 while (start < end) {
8505 const middle = (start + end) >>> 1;
8506 const middleJobId = getId(queue[middle]);
8507 middleJobId < id ? (start = middle + 1) : (end = middle);
8508 }
8509 return start;
8510}
8511function queueJob(job) {
8512 // the dedupe search uses the startIndex argument of Array.includes()
8513 // by default the search index includes the current job that is being run
8514 // so it cannot recursively trigger itself again.
8515 // if the job is a watch() callback, the search will start with a +1 index to
8516 // allow it recursively trigger itself - it is the user's responsibility to
8517 // ensure it doesn't end up in an infinite loop.
8518 if ((!queue.length ||
8519 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
8520 job !== currentPreFlushParentJob) {
8521 if (job.id == null) {
8522 queue.push(job);
8523 }
8524 else {
8525 queue.splice(findInsertionIndex(job.id), 0, job);
8526 }
8527 queueFlush();
8528 }
8529}
8530function queueFlush() {
8531 if (!isFlushing && !isFlushPending) {
8532 isFlushPending = true;
8533 currentFlushPromise = resolvedPromise.then(flushJobs);
8534 }
8535}
8536function invalidateJob(job) {
8537 const i = queue.indexOf(job);
8538 if (i > flushIndex) {
8539 queue.splice(i, 1);
8540 }
8541}
8542function queueCb(cb, activeQueue, pendingQueue, index) {
8543 if (!isArray(cb)) {
8544 if (!activeQueue ||
8545 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
8546 pendingQueue.push(cb);
8547 }
8548 }
8549 else {
8550 // if cb is an array, it is a component lifecycle hook which can only be
8551 // triggered by a job, which is already deduped in the main queue, so
8552 // we can skip duplicate check here to improve perf
8553 pendingQueue.push(...cb);
8554 }
8555 queueFlush();
8556}
8557function queuePreFlushCb(cb) {
8558 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
8559}
8560function queuePostFlushCb(cb) {
8561 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
8562}
8563function flushPreFlushCbs(seen, parentJob = null) {
8564 if (pendingPreFlushCbs.length) {
8565 currentPreFlushParentJob = parentJob;
8566 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
8567 pendingPreFlushCbs.length = 0;
8568 {
8569 seen = seen || new Map();
8570 }
8571 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
8572 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
8573 continue;
8574 }
8575 activePreFlushCbs[preFlushIndex]();
8576 }
8577 activePreFlushCbs = null;
8578 preFlushIndex = 0;
8579 currentPreFlushParentJob = null;
8580 // recursively flush until it drains
8581 flushPreFlushCbs(seen, parentJob);
8582 }
8583}
8584function flushPostFlushCbs(seen) {
8585 if (pendingPostFlushCbs.length) {
8586 const deduped = [...new Set(pendingPostFlushCbs)];
8587 pendingPostFlushCbs.length = 0;
8588 // #1947 already has active queue, nested flushPostFlushCbs call
8589 if (activePostFlushCbs) {
8590 activePostFlushCbs.push(...deduped);
8591 return;
8592 }
8593 activePostFlushCbs = deduped;
8594 {
8595 seen = seen || new Map();
8596 }
8597 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
8598 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
8599 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
8600 continue;
8601 }
8602 activePostFlushCbs[postFlushIndex]();
8603 }
8604 activePostFlushCbs = null;
8605 postFlushIndex = 0;
8606 }
8607}
8608const getId = (job) => job.id == null ? Infinity : job.id;
8609function flushJobs(seen) {
8610 isFlushPending = false;
8611 isFlushing = true;
8612 {
8613 seen = seen || new Map();
8614 }
8615 flushPreFlushCbs(seen);
8616 // Sort queue before flush.
8617 // This ensures that:
8618 // 1. Components are updated from parent to child. (because parent is always
8619 // created before the child so its render effect will have smaller
8620 // priority number)
8621 // 2. If a component is unmounted during a parent component's update,
8622 // its update can be skipped.
8623 queue.sort((a, b) => getId(a) - getId(b));
8624 try {
8625 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
8626 const job = queue[flushIndex];
8627 if (job && job.active !== false) {
8628 if (true && checkRecursiveUpdates(seen, job)) {
8629 continue;
8630 }
8631 // console.log(`running:`, job.id)
8632 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
8633 }
8634 }
8635 }
8636 finally {
8637 flushIndex = 0;
8638 queue.length = 0;
8639 flushPostFlushCbs(seen);
8640 isFlushing = false;
8641 currentFlushPromise = null;
8642 // some postFlushCb queued jobs!
8643 // keep flushing until it drains.
8644 if (queue.length ||
8645 pendingPreFlushCbs.length ||
8646 pendingPostFlushCbs.length) {
8647 flushJobs(seen);
8648 }
8649 }
8650}
8651function checkRecursiveUpdates(seen, fn) {
8652 if (!seen.has(fn)) {
8653 seen.set(fn, 1);
8654 }
8655 else {
8656 const count = seen.get(fn);
8657 if (count > RECURSION_LIMIT) {
8658 const instance = fn.ownerInstance;
8659 const componentName = instance && getComponentName(instance.type);
8660 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
8661 `This means you have a reactive effect that is mutating its own ` +
8662 `dependencies and thus recursively triggering itself. Possible sources ` +
8663 `include component template, render function, updated hook or ` +
8664 `watcher source function.`);
8665 return true;
8666 }
8667 else {
8668 seen.set(fn, count + 1);
8669 }
8670 }
8671}
8672
8673// Simple effect.
8674function watchEffect(effect, options) {
8675 return doWatch(effect, null, options);
8676}
8677function watchPostEffect(effect, options) {
8678 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
8679 ));
8680}
8681function watchSyncEffect(effect, options) {
8682 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
8683 ));
8684}
8685// initial value for watchers to trigger on undefined initial values
8686const INITIAL_WATCHER_VALUE = {};
8687// implementation
8688function watch(source, cb, options) {
8689 if (!isFunction(cb)) {
8690 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
8691 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
8692 `supports \`watch(source, cb, options?) signature.`);
8693 }
8694 return doWatch(source, cb, options);
8695}
8696function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
8697 if (!cb) {
8698 if (immediate !== undefined) {
8699 warn$1(`watch() "immediate" option is only respected when using the ` +
8700 `watch(source, callback, options?) signature.`);
8701 }
8702 if (deep !== undefined) {
8703 warn$1(`watch() "deep" option is only respected when using the ` +
8704 `watch(source, callback, options?) signature.`);
8705 }
8706 }
8707 const warnInvalidSource = (s) => {
8708 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
8709 `a reactive object, or an array of these types.`);
8710 };
8711 const instance = currentInstance;
8712 let getter;
8713 let forceTrigger = false;
8714 let isMultiSource = false;
8715 if (isRef(source)) {
8716 getter = () => source.value;
8717 forceTrigger = !!source._shallow;
8718 }
8719 else if (isReactive(source)) {
8720 getter = () => source;
8721 deep = true;
8722 }
8723 else if (isArray(source)) {
8724 isMultiSource = true;
8725 forceTrigger = source.some(isReactive);
8726 getter = () => source.map(s => {
8727 if (isRef(s)) {
8728 return s.value;
8729 }
8730 else if (isReactive(s)) {
8731 return traverse(s);
8732 }
8733 else if (isFunction(s)) {
8734 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
8735 }
8736 else {
8737 warnInvalidSource(s);
8738 }
8739 });
8740 }
8741 else if (isFunction(source)) {
8742 if (cb) {
8743 // getter with cb
8744 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
8745 }
8746 else {
8747 // no cb -> simple effect
8748 getter = () => {
8749 if (instance && instance.isUnmounted) {
8750 return;
8751 }
8752 if (cleanup) {
8753 cleanup();
8754 }
8755 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
8756 };
8757 }
8758 }
8759 else {
8760 getter = NOOP;
8761 warnInvalidSource(source);
8762 }
8763 if (cb && deep) {
8764 const baseGetter = getter;
8765 getter = () => traverse(baseGetter());
8766 }
8767 let cleanup;
8768 let onInvalidate = (fn) => {
8769 cleanup = effect.onStop = () => {
8770 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
8771 };
8772 };
8773 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
8774 const job = () => {
8775 if (!effect.active) {
8776 return;
8777 }
8778 if (cb) {
8779 // watch(source, cb)
8780 const newValue = effect.run();
8781 if (deep ||
8782 forceTrigger ||
8783 (isMultiSource
8784 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
8785 : hasChanged(newValue, oldValue)) ||
8786 (false )) {
8787 // cleanup before running cb again
8788 if (cleanup) {
8789 cleanup();
8790 }
8791 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
8792 newValue,
8793 // pass undefined as the old value when it's changed for the first time
8794 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
8795 onInvalidate
8796 ]);
8797 oldValue = newValue;
8798 }
8799 }
8800 else {
8801 // watchEffect
8802 effect.run();
8803 }
8804 };
8805 // important: mark the job as a watcher callback so that scheduler knows
8806 // it is allowed to self-trigger (#1727)
8807 job.allowRecurse = !!cb;
8808 let scheduler;
8809 if (flush === 'sync') {
8810 scheduler = job; // the scheduler function gets called directly
8811 }
8812 else if (flush === 'post') {
8813 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
8814 }
8815 else {
8816 // default: 'pre'
8817 scheduler = () => {
8818 if (!instance || instance.isMounted) {
8819 queuePreFlushCb(job);
8820 }
8821 else {
8822 // with 'pre' option, the first call must happen before
8823 // the component is mounted so it is called synchronously.
8824 job();
8825 }
8826 };
8827 }
8828 const effect = new ReactiveEffect(getter, scheduler);
8829 {
8830 effect.onTrack = onTrack;
8831 effect.onTrigger = onTrigger;
8832 }
8833 // initial run
8834 if (cb) {
8835 if (immediate) {
8836 job();
8837 }
8838 else {
8839 oldValue = effect.run();
8840 }
8841 }
8842 else if (flush === 'post') {
8843 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
8844 }
8845 else {
8846 effect.run();
8847 }
8848 return () => {
8849 effect.stop();
8850 if (instance && instance.scope) {
8851 remove(instance.scope.effects, effect);
8852 }
8853 };
8854}
8855// this.$watch
8856function instanceWatch(source, value, options) {
8857 const publicThis = this.proxy;
8858 const getter = isString(source)
8859 ? source.includes('.')
8860 ? createPathGetter(publicThis, source)
8861 : () => publicThis[source]
8862 : source.bind(publicThis, publicThis);
8863 let cb;
8864 if (isFunction(value)) {
8865 cb = value;
8866 }
8867 else {
8868 cb = value.handler;
8869 options = value;
8870 }
8871 const cur = currentInstance;
8872 setCurrentInstance(this);
8873 const res = doWatch(getter, cb.bind(publicThis), options);
8874 if (cur) {
8875 setCurrentInstance(cur);
8876 }
8877 else {
8878 unsetCurrentInstance();
8879 }
8880 return res;
8881}
8882function createPathGetter(ctx, path) {
8883 const segments = path.split('.');
8884 return () => {
8885 let cur = ctx;
8886 for (let i = 0; i < segments.length && cur; i++) {
8887 cur = cur[segments[i]];
8888 }
8889 return cur;
8890 };
8891}
8892function traverse(value, seen = new Set()) {
8893 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
8894 return value;
8895 }
8896 seen = seen || new Set();
8897 if (seen.has(value)) {
8898 return value;
8899 }
8900 seen.add(value);
8901 if (isRef(value)) {
8902 traverse(value.value, seen);
8903 }
8904 else if (isArray(value)) {
8905 for (let i = 0; i < value.length; i++) {
8906 traverse(value[i], seen);
8907 }
8908 }
8909 else if (isSet(value) || isMap(value)) {
8910 value.forEach((v) => {
8911 traverse(v, seen);
8912 });
8913 }
8914 else if (isPlainObject(value)) {
8915 for (const key in value) {
8916 traverse(value[key], seen);
8917 }
8918 }
8919 return value;
8920}
8921
8922// dev only
8923const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8924 `<script setup> of a single file component. Its arguments should be ` +
8925 `compiled away and passing it at runtime has no effect.`);
8926// implementation
8927function defineProps() {
8928 {
8929 warnRuntimeUsage(`defineProps`);
8930 }
8931 return null;
8932}
8933// implementation
8934function defineEmits() {
8935 {
8936 warnRuntimeUsage(`defineEmits`);
8937 }
8938 return null;
8939}
8940/**
8941 * Vue `<script setup>` compiler macro for declaring a component's exposed
8942 * instance properties when it is accessed by a parent component via template
8943 * refs.
8944 *
8945 * `<script setup>` components are closed by default - i.e. varaibles inside
8946 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8947 * via `defineExpose`.
8948 *
8949 * This is only usable inside `<script setup>`, is compiled away in the
8950 * output and should **not** be actually called at runtime.
8951 */
8952function defineExpose(exposed) {
8953 {
8954 warnRuntimeUsage(`defineExpose`);
8955 }
8956}
8957/**
8958 * Vue `<script setup>` compiler macro for providing props default values when
8959 * using type-based `defineProps` declaration.
8960 *
8961 * Example usage:
8962 * ```ts
8963 * withDefaults(defineProps<{
8964 * size?: number
8965 * labels?: string[]
8966 * }>(), {
8967 * size: 3,
8968 * labels: () => ['default label']
8969 * })
8970 * ```
8971 *
8972 * This is only usable inside `<script setup>`, is compiled away in the output
8973 * and should **not** be actually called at runtime.
8974 */
8975function withDefaults(props, defaults) {
8976 {
8977 warnRuntimeUsage(`withDefaults`);
8978 }
8979 return null;
8980}
8981function useSlots() {
8982 return getContext().slots;
8983}
8984function useAttrs() {
8985 return getContext().attrs;
8986}
8987function getContext() {
8988 const i = getCurrentInstance();
8989 if (!i) {
8990 warn$1(`useContext() called without active instance.`);
8991 }
8992 return i.setupContext || (i.setupContext = createSetupContext(i));
8993}
8994/**
8995 * Runtime helper for merging default declarations. Imported by compiled code
8996 * only.
8997 * @internal
8998 */
8999function mergeDefaults(
9000// the base props is compiler-generated and guaranteed to be in this shape.
9001props, defaults) {
9002 for (const key in defaults) {
9003 const val = props[key];
9004 if (val) {
9005 val.default = defaults[key];
9006 }
9007 else if (val === null) {
9008 props[key] = { default: defaults[key] };
9009 }
9010 else {
9011 warn$1(`props default key "${key}" has no corresponding declaration.`);
9012 }
9013 }
9014 return props;
9015}
9016/**
9017 * `<script setup>` helper for persisting the current instance context over
9018 * async/await flows.
9019 *
9020 * `@vue/compiler-sfc` converts the following:
9021 *
9022 * ```ts
9023 * const x = await foo()
9024 * ```
9025 *
9026 * into:
9027 *
9028 * ```ts
9029 * let __temp, __restore
9030 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
9031 * ```
9032 * @internal
9033 */
9034function withAsyncContext(getAwaitable) {
9035 const ctx = getCurrentInstance();
9036 if (!ctx) {
9037 warn$1(`withAsyncContext called without active current instance. ` +
9038 `This is likely a bug.`);
9039 }
9040 let awaitable = getAwaitable();
9041 unsetCurrentInstance();
9042 if (isPromise(awaitable)) {
9043 awaitable = awaitable.catch(e => {
9044 setCurrentInstance(ctx);
9045 throw e;
9046 });
9047 }
9048 return [awaitable, () => setCurrentInstance(ctx)];
9049}
9050
9051// Actual implementation
9052function h(type, propsOrChildren, children) {
9053 const l = arguments.length;
9054 if (l === 2) {
9055 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
9056 // single vnode without props
9057 if (isVNode(propsOrChildren)) {
9058 return createVNode(type, null, [propsOrChildren]);
9059 }
9060 // props without children
9061 return createVNode(type, propsOrChildren);
9062 }
9063 else {
9064 // omit props
9065 return createVNode(type, null, propsOrChildren);
9066 }
9067 }
9068 else {
9069 if (l > 3) {
9070 children = Array.prototype.slice.call(arguments, 2);
9071 }
9072 else if (l === 3 && isVNode(children)) {
9073 children = [children];
9074 }
9075 return createVNode(type, propsOrChildren, children);
9076 }
9077}
9078
9079const ssrContextKey = Symbol(`ssrContext` );
9080const useSSRContext = () => {
9081 {
9082 const ctx = inject(ssrContextKey);
9083 if (!ctx) {
9084 warn$1(`Server rendering context not provided. Make sure to only call ` +
9085 `useSSRContext() conditionally in the server build.`);
9086 }
9087 return ctx;
9088 }
9089};
9090
9091function initCustomFormatter() {
9092 /* eslint-disable no-restricted-globals */
9093 if (typeof window === 'undefined') {
9094 return;
9095 }
9096 const vueStyle = { style: 'color:#3ba776' };
9097 const numberStyle = { style: 'color:#0b1bc9' };
9098 const stringStyle = { style: 'color:#b62e24' };
9099 const keywordStyle = { style: 'color:#9d288c' };
9100 // custom formatter for Chrome
9101 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
9102 const formatter = {
9103 header(obj) {
9104 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
9105 if (!isObject(obj)) {
9106 return null;
9107 }
9108 if (obj.__isVue) {
9109 return ['div', vueStyle, `VueInstance`];
9110 }
9111 else if (isRef(obj)) {
9112 return [
9113 'div',
9114 {},
9115 ['span', vueStyle, genRefFlag(obj)],
9116 '<',
9117 formatValue(obj.value),
9118 `>`
9119 ];
9120 }
9121 else if (isReactive(obj)) {
9122 return [
9123 'div',
9124 {},
9125 ['span', vueStyle, 'Reactive'],
9126 '<',
9127 formatValue(obj),
9128 `>${isReadonly(obj) ? ` (readonly)` : ``}`
9129 ];
9130 }
9131 else if (isReadonly(obj)) {
9132 return [
9133 'div',
9134 {},
9135 ['span', vueStyle, 'Readonly'],
9136 '<',
9137 formatValue(obj),
9138 '>'
9139 ];
9140 }
9141 return null;
9142 },
9143 hasBody(obj) {
9144 return obj && obj.__isVue;
9145 },
9146 body(obj) {
9147 if (obj && obj.__isVue) {
9148 return [
9149 'div',
9150 {},
9151 ...formatInstance(obj.$)
9152 ];
9153 }
9154 }
9155 };
9156 function formatInstance(instance) {
9157 const blocks = [];
9158 if (instance.type.props && instance.props) {
9159 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
9160 }
9161 if (instance.setupState !== EMPTY_OBJ) {
9162 blocks.push(createInstanceBlock('setup', instance.setupState));
9163 }
9164 if (instance.data !== EMPTY_OBJ) {
9165 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
9166 }
9167 const computed = extractKeys(instance, 'computed');
9168 if (computed) {
9169 blocks.push(createInstanceBlock('computed', computed));
9170 }
9171 const injected = extractKeys(instance, 'inject');
9172 if (injected) {
9173 blocks.push(createInstanceBlock('injected', injected));
9174 }
9175 blocks.push([
9176 'div',
9177 {},
9178 [
9179 'span',
9180 {
9181 style: keywordStyle.style + ';opacity:0.66'
9182 },
9183 '$ (internal): '
9184 ],
9185 ['object', { object: instance }]
9186 ]);
9187 return blocks;
9188 }
9189 function createInstanceBlock(type, target) {
9190 target = extend({}, target);
9191 if (!Object.keys(target).length) {
9192 return ['span', {}];
9193 }
9194 return [
9195 'div',
9196 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9197 [
9198 'div',
9199 {
9200 style: 'color:#476582'
9201 },
9202 type
9203 ],
9204 [
9205 'div',
9206 {
9207 style: 'padding-left:1.25em'
9208 },
9209 ...Object.keys(target).map(key => {
9210 return [
9211 'div',
9212 {},
9213 ['span', keywordStyle, key + ': '],
9214 formatValue(target[key], false)
9215 ];
9216 })
9217 ]
9218 ];
9219 }
9220 function formatValue(v, asRaw = true) {
9221 if (typeof v === 'number') {
9222 return ['span', numberStyle, v];
9223 }
9224 else if (typeof v === 'string') {
9225 return ['span', stringStyle, JSON.stringify(v)];
9226 }
9227 else if (typeof v === 'boolean') {
9228 return ['span', keywordStyle, v];
9229 }
9230 else if (isObject(v)) {
9231 return ['object', { object: asRaw ? toRaw(v) : v }];
9232 }
9233 else {
9234 return ['span', stringStyle, String(v)];
9235 }
9236 }
9237 function extractKeys(instance, type) {
9238 const Comp = instance.type;
9239 if (isFunction(Comp)) {
9240 return;
9241 }
9242 const extracted = {};
9243 for (const key in instance.ctx) {
9244 if (isKeyOfType(Comp, key, type)) {
9245 extracted[key] = instance.ctx[key];
9246 }
9247 }
9248 return extracted;
9249 }
9250 function isKeyOfType(Comp, key, type) {
9251 const opts = Comp[type];
9252 if ((isArray(opts) && opts.includes(key)) ||
9253 (isObject(opts) && key in opts)) {
9254 return true;
9255 }
9256 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9257 return true;
9258 }
9259 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9260 return true;
9261 }
9262 }
9263 function genRefFlag(v) {
9264 if (v._shallow) {
9265 return `ShallowRef`;
9266 }
9267 if (v.effect) {
9268 return `ComputedRef`;
9269 }
9270 return `Ref`;
9271 }
9272 if (window.devtoolsFormatters) {
9273 window.devtoolsFormatters.push(formatter);
9274 }
9275 else {
9276 window.devtoolsFormatters = [formatter];
9277 }
9278}
9279
9280function withMemo(memo, render, cache, index) {
9281 const cached = cache[index];
9282 if (cached && isMemoSame(cached, memo)) {
9283 return cached;
9284 }
9285 const ret = render();
9286 // shallow clone
9287 ret.memo = memo.slice();
9288 return (cache[index] = ret);
9289}
9290function isMemoSame(cached, memo) {
9291 const prev = cached.memo;
9292 if (prev.length != memo.length) {
9293 return false;
9294 }
9295 for (let i = 0; i < prev.length; i++) {
9296 if (prev[i] !== memo[i]) {
9297 return false;
9298 }
9299 }
9300 // make sure to let parent block track it when returning cached
9301 if (isBlockTreeEnabled > 0 && currentBlock) {
9302 currentBlock.push(cached);
9303 }
9304 return true;
9305}
9306
9307// Core API ------------------------------------------------------------------
9308const version = "3.2.10";
9309/**
9310 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9311 * @internal
9312 */
9313const ssrUtils = (null);
9314/**
9315 * @internal only exposed in compat builds
9316 */
9317const resolveFilter = null;
9318/**
9319 * @internal only exposed in compat builds.
9320 */
9321const compatUtils = (null);
9322
9323const svgNS = 'http://www.w3.org/2000/svg';
9324const doc = (typeof document !== 'undefined' ? document : null);
9325const staticTemplateCache = new Map();
9326const nodeOps = {
9327 insert: (child, parent, anchor) => {
9328 parent.insertBefore(child, anchor || null);
9329 },
9330 remove: child => {
9331 const parent = child.parentNode;
9332 if (parent) {
9333 parent.removeChild(child);
9334 }
9335 },
9336 createElement: (tag, isSVG, is, props) => {
9337 const el = isSVG
9338 ? doc.createElementNS(svgNS, tag)
9339 : doc.createElement(tag, is ? { is } : undefined);
9340 if (tag === 'select' && props && props.multiple != null) {
9341 el.setAttribute('multiple', props.multiple);
9342 }
9343 return el;
9344 },
9345 createText: text => doc.createTextNode(text),
9346 createComment: text => doc.createComment(text),
9347 setText: (node, text) => {
9348 node.nodeValue = text;
9349 },
9350 setElementText: (el, text) => {
9351 el.textContent = text;
9352 },
9353 parentNode: node => node.parentNode,
9354 nextSibling: node => node.nextSibling,
9355 querySelector: selector => doc.querySelector(selector),
9356 setScopeId(el, id) {
9357 el.setAttribute(id, '');
9358 },
9359 cloneNode(el) {
9360 const cloned = el.cloneNode(true);
9361 // #3072
9362 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9363 // - normally, elements using `:value` bindings will not be hoisted, but if
9364 // the bound value is a constant, e.g. `:value="true"` - they do get
9365 // hoisted.
9366 // - in production, hoisted nodes are cloned when subsequent inserts, but
9367 // cloneNode() does not copy the custom property we attached.
9368 // - This may need to account for other custom DOM properties we attach to
9369 // elements in addition to `_value` in the future.
9370 if (`_value` in el) {
9371 cloned._value = el._value;
9372 }
9373 return cloned;
9374 },
9375 // __UNSAFE__
9376 // Reason: innerHTML.
9377 // Static content here can only come from compiled templates.
9378 // As long as the user only uses trusted templates, this is safe.
9379 insertStaticContent(content, parent, anchor, isSVG) {
9380 // <parent> before | first ... last | anchor </parent>
9381 const before = anchor ? anchor.previousSibling : parent.lastChild;
9382 let template = staticTemplateCache.get(content);
9383 if (!template) {
9384 const t = doc.createElement('template');
9385 t.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9386 template = t.content;
9387 if (isSVG) {
9388 // remove outer svg wrapper
9389 const wrapper = template.firstChild;
9390 while (wrapper.firstChild) {
9391 template.appendChild(wrapper.firstChild);
9392 }
9393 template.removeChild(wrapper);
9394 }
9395 staticTemplateCache.set(content, template);
9396 }
9397 parent.insertBefore(template.cloneNode(true), anchor);
9398 return [
9399 // first
9400 before ? before.nextSibling : parent.firstChild,
9401 // last
9402 anchor ? anchor.previousSibling : parent.lastChild
9403 ];
9404 }
9405};
9406
9407// compiler should normalize class + :class bindings on the same element
9408// into a single binding ['staticClass', dynamic]
9409function patchClass(el, value, isSVG) {
9410 // directly setting className should be faster than setAttribute in theory
9411 // if this is an element during a transition, take the temporary transition
9412 // classes into account.
9413 const transitionClasses = el._vtc;
9414 if (transitionClasses) {
9415 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9416 }
9417 if (value == null) {
9418 el.removeAttribute('class');
9419 }
9420 else if (isSVG) {
9421 el.setAttribute('class', value);
9422 }
9423 else {
9424 el.className = value;
9425 }
9426}
9427
9428function patchStyle(el, prev, next) {
9429 const style = el.style;
9430 const currentDisplay = style.display;
9431 if (!next) {
9432 el.removeAttribute('style');
9433 }
9434 else if (isString(next)) {
9435 if (prev !== next) {
9436 style.cssText = next;
9437 }
9438 }
9439 else {
9440 for (const key in next) {
9441 setStyle(style, key, next[key]);
9442 }
9443 if (prev && !isString(prev)) {
9444 for (const key in prev) {
9445 if (next[key] == null) {
9446 setStyle(style, key, '');
9447 }
9448 }
9449 }
9450 }
9451 // indicates that the `display` of the element is controlled by `v-show`,
9452 // so we always keep the current `display` value regardless of the `style` value,
9453 // thus handing over control to `v-show`.
9454 if ('_vod' in el) {
9455 style.display = currentDisplay;
9456 }
9457}
9458const importantRE = /\s*!important$/;
9459function setStyle(style, name, val) {
9460 if (isArray(val)) {
9461 val.forEach(v => setStyle(style, name, v));
9462 }
9463 else {
9464 if (name.startsWith('--')) {
9465 // custom property definition
9466 style.setProperty(name, val);
9467 }
9468 else {
9469 const prefixed = autoPrefix(style, name);
9470 if (importantRE.test(val)) {
9471 // !important
9472 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9473 }
9474 else {
9475 style[prefixed] = val;
9476 }
9477 }
9478 }
9479}
9480const prefixes = ['Webkit', 'Moz', 'ms'];
9481const prefixCache = {};
9482function autoPrefix(style, rawName) {
9483 const cached = prefixCache[rawName];
9484 if (cached) {
9485 return cached;
9486 }
9487 let name = camelize(rawName);
9488 if (name !== 'filter' && name in style) {
9489 return (prefixCache[rawName] = name);
9490 }
9491 name = capitalize(name);
9492 for (let i = 0; i < prefixes.length; i++) {
9493 const prefixed = prefixes[i] + name;
9494 if (prefixed in style) {
9495 return (prefixCache[rawName] = prefixed);
9496 }
9497 }
9498 return rawName;
9499}
9500
9501const xlinkNS = 'http://www.w3.org/1999/xlink';
9502function patchAttr(el, key, value, isSVG, instance) {
9503 if (isSVG && key.startsWith('xlink:')) {
9504 if (value == null) {
9505 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9506 }
9507 else {
9508 el.setAttributeNS(xlinkNS, key, value);
9509 }
9510 }
9511 else {
9512 // note we are only checking boolean attributes that don't have a
9513 // corresponding dom prop of the same name here.
9514 const isBoolean = isSpecialBooleanAttr(key);
9515 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9516 el.removeAttribute(key);
9517 }
9518 else {
9519 el.setAttribute(key, isBoolean ? '' : value);
9520 }
9521 }
9522}
9523
9524// __UNSAFE__
9525// functions. The user is responsible for using them with only trusted content.
9526function patchDOMProp(el, key, value,
9527// the following args are passed only due to potential innerHTML/textContent
9528// overriding existing VNodes, in which case the old tree must be properly
9529// unmounted.
9530prevChildren, parentComponent, parentSuspense, unmountChildren) {
9531 if (key === 'innerHTML' || key === 'textContent') {
9532 if (prevChildren) {
9533 unmountChildren(prevChildren, parentComponent, parentSuspense);
9534 }
9535 el[key] = value == null ? '' : value;
9536 return;
9537 }
9538 if (key === 'value' && el.tagName !== 'PROGRESS') {
9539 // store value as _value as well since
9540 // non-string values will be stringified.
9541 el._value = value;
9542 const newValue = value == null ? '' : value;
9543 if (el.value !== newValue) {
9544 el.value = newValue;
9545 }
9546 if (value == null) {
9547 el.removeAttribute(key);
9548 }
9549 return;
9550 }
9551 if (value === '' || value == null) {
9552 const type = typeof el[key];
9553 if (type === 'boolean') {
9554 // e.g. <select multiple> compiles to { multiple: '' }
9555 el[key] = includeBooleanAttr(value);
9556 return;
9557 }
9558 else if (value == null && type === 'string') {
9559 // e.g. <div :id="null">
9560 el[key] = '';
9561 el.removeAttribute(key);
9562 return;
9563 }
9564 else if (type === 'number') {
9565 // e.g. <img :width="null">
9566 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9567 try {
9568 el[key] = 0;
9569 }
9570 catch (_a) { }
9571 el.removeAttribute(key);
9572 return;
9573 }
9574 }
9575 // some properties perform value validation and throw
9576 try {
9577 el[key] = value;
9578 }
9579 catch (e) {
9580 {
9581 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9582 `value ${value} is invalid.`, e);
9583 }
9584 }
9585}
9586
9587// Async edge case fix requires storing an event listener's attach timestamp.
9588let _getNow = Date.now;
9589let skipTimestampCheck = false;
9590if (typeof window !== 'undefined') {
9591 // Determine what event timestamp the browser is using. Annoyingly, the
9592 // timestamp can either be hi-res (relative to page load) or low-res
9593 // (relative to UNIX epoch), so in order to compare time we have to use the
9594 // same timestamp type when saving the flush timestamp.
9595 if (_getNow() > document.createEvent('Event').timeStamp) {
9596 // if the low-res timestamp which is bigger than the event timestamp
9597 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9598 // and we need to use the hi-res version for event listeners as well.
9599 _getNow = () => performance.now();
9600 }
9601 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9602 // and does not fire microtasks in between event propagation, so safe to exclude.
9603 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9604 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9605}
9606// To avoid the overhead of repeatedly calling performance.now(), we cache
9607// and use the same timestamp for all event listeners attached in the same tick.
9608let cachedNow = 0;
9609const p = Promise.resolve();
9610const reset = () => {
9611 cachedNow = 0;
9612};
9613const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9614function addEventListener(el, event, handler, options) {
9615 el.addEventListener(event, handler, options);
9616}
9617function removeEventListener(el, event, handler, options) {
9618 el.removeEventListener(event, handler, options);
9619}
9620function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9621 // vei = vue event invokers
9622 const invokers = el._vei || (el._vei = {});
9623 const existingInvoker = invokers[rawName];
9624 if (nextValue && existingInvoker) {
9625 // patch
9626 existingInvoker.value = nextValue;
9627 }
9628 else {
9629 const [name, options] = parseName(rawName);
9630 if (nextValue) {
9631 // add
9632 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9633 addEventListener(el, name, invoker, options);
9634 }
9635 else if (existingInvoker) {
9636 // remove
9637 removeEventListener(el, name, existingInvoker, options);
9638 invokers[rawName] = undefined;
9639 }
9640 }
9641}
9642const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9643function parseName(name) {
9644 let options;
9645 if (optionsModifierRE.test(name)) {
9646 options = {};
9647 let m;
9648 while ((m = name.match(optionsModifierRE))) {
9649 name = name.slice(0, name.length - m[0].length);
9650 options[m[0].toLowerCase()] = true;
9651 }
9652 }
9653 return [hyphenate(name.slice(2)), options];
9654}
9655function createInvoker(initialValue, instance) {
9656 const invoker = (e) => {
9657 // async edge case #6566: inner click event triggers patch, event handler
9658 // attached to outer element during patch, and triggered again. This
9659 // happens because browsers fire microtask ticks between event propagation.
9660 // the solution is simple: we save the timestamp when a handler is attached,
9661 // and the handler would only fire if the event passed to it was fired
9662 // AFTER it was attached.
9663 const timeStamp = e.timeStamp || _getNow();
9664 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9665 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9666 }
9667 };
9668 invoker.value = initialValue;
9669 invoker.attached = getNow();
9670 return invoker;
9671}
9672function patchStopImmediatePropagation(e, value) {
9673 if (isArray(value)) {
9674 const originalStop = e.stopImmediatePropagation;
9675 e.stopImmediatePropagation = () => {
9676 originalStop.call(e);
9677 e._stopped = true;
9678 };
9679 return value.map(fn => (e) => !e._stopped && fn(e));
9680 }
9681 else {
9682 return value;
9683 }
9684}
9685
9686const nativeOnRE = /^on[a-z]/;
9687const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9688 if (key === 'class') {
9689 patchClass(el, nextValue, isSVG);
9690 }
9691 else if (key === 'style') {
9692 patchStyle(el, prevValue, nextValue);
9693 }
9694 else if (isOn(key)) {
9695 // ignore v-model listeners
9696 if (!isModelListener(key)) {
9697 patchEvent(el, key, prevValue, nextValue, parentComponent);
9698 }
9699 }
9700 else if (key[0] === '.'
9701 ? ((key = key.slice(1)), true)
9702 : key[0] === '^'
9703 ? ((key = key.slice(1)), false)
9704 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9705 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9706 }
9707 else {
9708 // special case for <input v-model type="checkbox"> with
9709 // :true-value & :false-value
9710 // store value as dom properties since non-string values will be
9711 // stringified.
9712 if (key === 'true-value') {
9713 el._trueValue = nextValue;
9714 }
9715 else if (key === 'false-value') {
9716 el._falseValue = nextValue;
9717 }
9718 patchAttr(el, key, nextValue, isSVG);
9719 }
9720};
9721function shouldSetAsProp(el, key, value, isSVG) {
9722 if (isSVG) {
9723 // most keys must be set as attribute on svg elements to work
9724 // ...except innerHTML & textContent
9725 if (key === 'innerHTML' || key === 'textContent') {
9726 return true;
9727 }
9728 // or native onclick with function values
9729 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9730 return true;
9731 }
9732 return false;
9733 }
9734 // spellcheck and draggable are numerated attrs, however their
9735 // corresponding DOM properties are actually booleans - this leads to
9736 // setting it with a string "false" value leading it to be coerced to
9737 // `true`, so we need to always treat them as attributes.
9738 // Note that `contentEditable` doesn't have this problem: its DOM
9739 // property is also enumerated string values.
9740 if (key === 'spellcheck' || key === 'draggable') {
9741 return false;
9742 }
9743 // #1787, #2840 form property on form elements is readonly and must be set as
9744 // attribute.
9745 if (key === 'form') {
9746 return false;
9747 }
9748 // #1526 <input list> must be set as attribute
9749 if (key === 'list' && el.tagName === 'INPUT') {
9750 return false;
9751 }
9752 // #2766 <textarea type> must be set as attribute
9753 if (key === 'type' && el.tagName === 'TEXTAREA') {
9754 return false;
9755 }
9756 // native onclick with string value, must be set as attribute
9757 if (nativeOnRE.test(key) && isString(value)) {
9758 return false;
9759 }
9760 return key in el;
9761}
9762
9763function defineCustomElement(options, hydate) {
9764 const Comp = defineComponent(options);
9765 class VueCustomElement extends VueElement {
9766 constructor(initialProps) {
9767 super(Comp, initialProps, hydate);
9768 }
9769 }
9770 VueCustomElement.def = Comp;
9771 return VueCustomElement;
9772}
9773const defineSSRCustomElement = ((options) => {
9774 // @ts-ignore
9775 return defineCustomElement(options, hydrate);
9776});
9777const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9778});
9779class VueElement extends BaseClass {
9780 constructor(_def, _props = {}, hydrate) {
9781 super();
9782 this._def = _def;
9783 this._props = _props;
9784 /**
9785 * @internal
9786 */
9787 this._instance = null;
9788 this._connected = false;
9789 this._resolved = false;
9790 if (this.shadowRoot && hydrate) {
9791 hydrate(this._createVNode(), this.shadowRoot);
9792 }
9793 else {
9794 if (this.shadowRoot) {
9795 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9796 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9797 }
9798 this.attachShadow({ mode: 'open' });
9799 }
9800 // set initial attrs
9801 for (let i = 0; i < this.attributes.length; i++) {
9802 this._setAttr(this.attributes[i].name);
9803 }
9804 // watch future attr changes
9805 const observer = new MutationObserver(mutations => {
9806 for (const m of mutations) {
9807 this._setAttr(m.attributeName);
9808 }
9809 });
9810 observer.observe(this, { attributes: true });
9811 }
9812 connectedCallback() {
9813 this._connected = true;
9814 if (!this._instance) {
9815 this._resolveDef();
9816 render(this._createVNode(), this.shadowRoot);
9817 }
9818 }
9819 disconnectedCallback() {
9820 this._connected = false;
9821 nextTick(() => {
9822 if (!this._connected) {
9823 render(null, this.shadowRoot);
9824 this._instance = null;
9825 }
9826 });
9827 }
9828 /**
9829 * resolve inner component definition (handle possible async component)
9830 */
9831 _resolveDef() {
9832 if (this._resolved) {
9833 return;
9834 }
9835 const resolve = (def) => {
9836 this._resolved = true;
9837 // check if there are props set pre-upgrade or connect
9838 for (const key of Object.keys(this)) {
9839 if (key[0] !== '_') {
9840 this._setProp(key, this[key]);
9841 }
9842 }
9843 const { props, styles } = def;
9844 // defining getter/setters on prototype
9845 const rawKeys = props ? (isArray(props) ? props : Object.keys(props)) : [];
9846 for (const key of rawKeys.map(camelize)) {
9847 Object.defineProperty(this, key, {
9848 get() {
9849 return this._getProp(key);
9850 },
9851 set(val) {
9852 this._setProp(key, val);
9853 }
9854 });
9855 }
9856 this._applyStyles(styles);
9857 };
9858 const asyncDef = this._def.__asyncLoader;
9859 if (asyncDef) {
9860 asyncDef().then(resolve);
9861 }
9862 else {
9863 resolve(this._def);
9864 }
9865 }
9866 _setAttr(key) {
9867 this._setProp(camelize(key), toNumber(this.getAttribute(key)), false);
9868 }
9869 /**
9870 * @internal
9871 */
9872 _getProp(key) {
9873 return this._props[key];
9874 }
9875 /**
9876 * @internal
9877 */
9878 _setProp(key, val, shouldReflect = true) {
9879 if (val !== this._props[key]) {
9880 this._props[key] = val;
9881 if (this._instance) {
9882 render(this._createVNode(), this.shadowRoot);
9883 }
9884 // reflect
9885 if (shouldReflect) {
9886 if (val === true) {
9887 this.setAttribute(hyphenate(key), '');
9888 }
9889 else if (typeof val === 'string' || typeof val === 'number') {
9890 this.setAttribute(hyphenate(key), val + '');
9891 }
9892 else if (!val) {
9893 this.removeAttribute(hyphenate(key));
9894 }
9895 }
9896 }
9897 }
9898 _createVNode() {
9899 const vnode = createVNode(this._def, extend({}, this._props));
9900 if (!this._instance) {
9901 vnode.ce = instance => {
9902 this._instance = instance;
9903 instance.isCE = true;
9904 // HMR
9905 {
9906 instance.ceReload = newStyles => {
9907 // alawys reset styles
9908 if (this._styles) {
9909 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9910 this._styles.length = 0;
9911 }
9912 this._applyStyles(newStyles);
9913 // if this is an async component, ceReload is called from the inner
9914 // component so no need to reload the async wrapper
9915 if (!this._def.__asyncLoader) {
9916 // reload
9917 this._instance = null;
9918 render(this._createVNode(), this.shadowRoot);
9919 }
9920 };
9921 }
9922 // intercept emit
9923 instance.emit = (event, ...args) => {
9924 this.dispatchEvent(new CustomEvent(event, {
9925 detail: args
9926 }));
9927 };
9928 // locate nearest Vue custom element parent for provide/inject
9929 let parent = this;
9930 while ((parent =
9931 parent && (parent.parentNode || parent.host))) {
9932 if (parent instanceof VueElement) {
9933 instance.parent = parent._instance;
9934 break;
9935 }
9936 }
9937 };
9938 }
9939 return vnode;
9940 }
9941 _applyStyles(styles) {
9942 if (styles) {
9943 styles.forEach(css => {
9944 const s = document.createElement('style');
9945 s.textContent = css;
9946 this.shadowRoot.appendChild(s);
9947 // record for HMR
9948 {
9949 (this._styles || (this._styles = [])).push(s);
9950 }
9951 });
9952 }
9953 }
9954}
9955
9956function useCssModule(name = '$style') {
9957 /* istanbul ignore else */
9958 {
9959 const instance = getCurrentInstance();
9960 if (!instance) {
9961 warn$1(`useCssModule must be called inside setup()`);
9962 return EMPTY_OBJ;
9963 }
9964 const modules = instance.type.__cssModules;
9965 if (!modules) {
9966 warn$1(`Current instance does not have CSS modules injected.`);
9967 return EMPTY_OBJ;
9968 }
9969 const mod = modules[name];
9970 if (!mod) {
9971 warn$1(`Current instance does not have CSS module named "${name}".`);
9972 return EMPTY_OBJ;
9973 }
9974 return mod;
9975 }
9976}
9977
9978/**
9979 * Runtime helper for SFC's CSS variable injection feature.
9980 * @private
9981 */
9982function useCssVars(getter) {
9983 const instance = getCurrentInstance();
9984 /* istanbul ignore next */
9985 if (!instance) {
9986 warn$1(`useCssVars is called without current active component instance.`);
9987 return;
9988 }
9989 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9990 watchPostEffect(setVars);
9991 onMounted(() => {
9992 const ob = new MutationObserver(setVars);
9993 ob.observe(instance.subTree.el.parentNode, { childList: true });
9994 onUnmounted(() => ob.disconnect());
9995 });
9996}
9997function setVarsOnVNode(vnode, vars) {
9998 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9999 const suspense = vnode.suspense;
10000 vnode = suspense.activeBranch;
10001 if (suspense.pendingBranch && !suspense.isHydrating) {
10002 suspense.effects.push(() => {
10003 setVarsOnVNode(suspense.activeBranch, vars);
10004 });
10005 }
10006 }
10007 // drill down HOCs until it's a non-component vnode
10008 while (vnode.component) {
10009 vnode = vnode.component.subTree;
10010 }
10011 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
10012 setVarsOnNode(vnode.el, vars);
10013 }
10014 else if (vnode.type === Fragment) {
10015 vnode.children.forEach(c => setVarsOnVNode(c, vars));
10016 }
10017 else if (vnode.type === Static) {
10018 let { el, anchor } = vnode;
10019 while (el) {
10020 setVarsOnNode(el, vars);
10021 if (el === anchor)
10022 break;
10023 el = el.nextSibling;
10024 }
10025 }
10026}
10027function setVarsOnNode(el, vars) {
10028 if (el.nodeType === 1) {
10029 const style = el.style;
10030 for (const key in vars) {
10031 style.setProperty(`--${key}`, vars[key]);
10032 }
10033 }
10034}
10035
10036const TRANSITION = 'transition';
10037const ANIMATION = 'animation';
10038// DOM Transition is a higher-order-component based on the platform-agnostic
10039// base Transition component, with DOM-specific logic.
10040const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
10041Transition.displayName = 'Transition';
10042const DOMTransitionPropsValidators = {
10043 name: String,
10044 type: String,
10045 css: {
10046 type: Boolean,
10047 default: true
10048 },
10049 duration: [String, Number, Object],
10050 enterFromClass: String,
10051 enterActiveClass: String,
10052 enterToClass: String,
10053 appearFromClass: String,
10054 appearActiveClass: String,
10055 appearToClass: String,
10056 leaveFromClass: String,
10057 leaveActiveClass: String,
10058 leaveToClass: String
10059};
10060const TransitionPropsValidators = (Transition.props =
10061 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
10062/**
10063 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
10064 * with custom HOCs.
10065 */
10066const callHook$1 = (hook, args = []) => {
10067 if (isArray(hook)) {
10068 hook.forEach(h => h(...args));
10069 }
10070 else if (hook) {
10071 hook(...args);
10072 }
10073};
10074/**
10075 * Check if a hook expects a callback (2nd arg), which means the user
10076 * intends to explicitly control the end of the transition.
10077 */
10078const hasExplicitCallback = (hook) => {
10079 return hook
10080 ? isArray(hook)
10081 ? hook.some(h => h.length > 1)
10082 : hook.length > 1
10083 : false;
10084};
10085function resolveTransitionProps(rawProps) {
10086 const baseProps = {};
10087 for (const key in rawProps) {
10088 if (!(key in DOMTransitionPropsValidators)) {
10089 baseProps[key] = rawProps[key];
10090 }
10091 }
10092 if (rawProps.css === false) {
10093 return baseProps;
10094 }
10095 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;
10096 const durations = normalizeDuration(duration);
10097 const enterDuration = durations && durations[0];
10098 const leaveDuration = durations && durations[1];
10099 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
10100 const finishEnter = (el, isAppear, done) => {
10101 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
10102 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
10103 done && done();
10104 };
10105 const finishLeave = (el, done) => {
10106 removeTransitionClass(el, leaveToClass);
10107 removeTransitionClass(el, leaveActiveClass);
10108 done && done();
10109 };
10110 const makeEnterHook = (isAppear) => {
10111 return (el, done) => {
10112 const hook = isAppear ? onAppear : onEnter;
10113 const resolve = () => finishEnter(el, isAppear, done);
10114 callHook$1(hook, [el, resolve]);
10115 nextFrame(() => {
10116 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
10117 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
10118 if (!hasExplicitCallback(hook)) {
10119 whenTransitionEnds(el, type, enterDuration, resolve);
10120 }
10121 });
10122 };
10123 };
10124 return extend(baseProps, {
10125 onBeforeEnter(el) {
10126 callHook$1(onBeforeEnter, [el]);
10127 addTransitionClass(el, enterFromClass);
10128 addTransitionClass(el, enterActiveClass);
10129 },
10130 onBeforeAppear(el) {
10131 callHook$1(onBeforeAppear, [el]);
10132 addTransitionClass(el, appearFromClass);
10133 addTransitionClass(el, appearActiveClass);
10134 },
10135 onEnter: makeEnterHook(false),
10136 onAppear: makeEnterHook(true),
10137 onLeave(el, done) {
10138 const resolve = () => finishLeave(el, done);
10139 addTransitionClass(el, leaveFromClass);
10140 // force reflow so *-leave-from classes immediately take effect (#2593)
10141 forceReflow();
10142 addTransitionClass(el, leaveActiveClass);
10143 nextFrame(() => {
10144 removeTransitionClass(el, leaveFromClass);
10145 addTransitionClass(el, leaveToClass);
10146 if (!hasExplicitCallback(onLeave)) {
10147 whenTransitionEnds(el, type, leaveDuration, resolve);
10148 }
10149 });
10150 callHook$1(onLeave, [el, resolve]);
10151 },
10152 onEnterCancelled(el) {
10153 finishEnter(el, false);
10154 callHook$1(onEnterCancelled, [el]);
10155 },
10156 onAppearCancelled(el) {
10157 finishEnter(el, true);
10158 callHook$1(onAppearCancelled, [el]);
10159 },
10160 onLeaveCancelled(el) {
10161 finishLeave(el);
10162 callHook$1(onLeaveCancelled, [el]);
10163 }
10164 });
10165}
10166function normalizeDuration(duration) {
10167 if (duration == null) {
10168 return null;
10169 }
10170 else if (isObject(duration)) {
10171 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10172 }
10173 else {
10174 const n = NumberOf(duration);
10175 return [n, n];
10176 }
10177}
10178function NumberOf(val) {
10179 const res = toNumber(val);
10180 validateDuration(res);
10181 return res;
10182}
10183function validateDuration(val) {
10184 if (typeof val !== 'number') {
10185 warn$1(`<transition> explicit duration is not a valid number - ` +
10186 `got ${JSON.stringify(val)}.`);
10187 }
10188 else if (isNaN(val)) {
10189 warn$1(`<transition> explicit duration is NaN - ` +
10190 'the duration expression might be incorrect.');
10191 }
10192}
10193function addTransitionClass(el, cls) {
10194 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10195 (el._vtc ||
10196 (el._vtc = new Set())).add(cls);
10197}
10198function removeTransitionClass(el, cls) {
10199 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10200 const { _vtc } = el;
10201 if (_vtc) {
10202 _vtc.delete(cls);
10203 if (!_vtc.size) {
10204 el._vtc = undefined;
10205 }
10206 }
10207}
10208function nextFrame(cb) {
10209 requestAnimationFrame(() => {
10210 requestAnimationFrame(cb);
10211 });
10212}
10213let endId = 0;
10214function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10215 const id = (el._endId = ++endId);
10216 const resolveIfNotStale = () => {
10217 if (id === el._endId) {
10218 resolve();
10219 }
10220 };
10221 if (explicitTimeout) {
10222 return setTimeout(resolveIfNotStale, explicitTimeout);
10223 }
10224 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10225 if (!type) {
10226 return resolve();
10227 }
10228 const endEvent = type + 'end';
10229 let ended = 0;
10230 const end = () => {
10231 el.removeEventListener(endEvent, onEnd);
10232 resolveIfNotStale();
10233 };
10234 const onEnd = (e) => {
10235 if (e.target === el && ++ended >= propCount) {
10236 end();
10237 }
10238 };
10239 setTimeout(() => {
10240 if (ended < propCount) {
10241 end();
10242 }
10243 }, timeout + 1);
10244 el.addEventListener(endEvent, onEnd);
10245}
10246function getTransitionInfo(el, expectedType) {
10247 const styles = window.getComputedStyle(el);
10248 // JSDOM may return undefined for transition properties
10249 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10250 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10251 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10252 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10253 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10254 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10255 const animationTimeout = getTimeout(animationDelays, animationDurations);
10256 let type = null;
10257 let timeout = 0;
10258 let propCount = 0;
10259 /* istanbul ignore if */
10260 if (expectedType === TRANSITION) {
10261 if (transitionTimeout > 0) {
10262 type = TRANSITION;
10263 timeout = transitionTimeout;
10264 propCount = transitionDurations.length;
10265 }
10266 }
10267 else if (expectedType === ANIMATION) {
10268 if (animationTimeout > 0) {
10269 type = ANIMATION;
10270 timeout = animationTimeout;
10271 propCount = animationDurations.length;
10272 }
10273 }
10274 else {
10275 timeout = Math.max(transitionTimeout, animationTimeout);
10276 type =
10277 timeout > 0
10278 ? transitionTimeout > animationTimeout
10279 ? TRANSITION
10280 : ANIMATION
10281 : null;
10282 propCount = type
10283 ? type === TRANSITION
10284 ? transitionDurations.length
10285 : animationDurations.length
10286 : 0;
10287 }
10288 const hasTransform = type === TRANSITION &&
10289 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10290 return {
10291 type,
10292 timeout,
10293 propCount,
10294 hasTransform
10295 };
10296}
10297function getTimeout(delays, durations) {
10298 while (delays.length < durations.length) {
10299 delays = delays.concat(delays);
10300 }
10301 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10302}
10303// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10304// numbers in a locale-dependent way, using a comma instead of a dot.
10305// If comma is not replaced with a dot, the input will be rounded down
10306// (i.e. acting as a floor function) causing unexpected behaviors
10307function toMs(s) {
10308 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10309}
10310// synchronously force layout to put elements into a certain state
10311function forceReflow() {
10312 return document.body.offsetHeight;
10313}
10314
10315const positionMap = new WeakMap();
10316const newPositionMap = new WeakMap();
10317const TransitionGroupImpl = {
10318 name: 'TransitionGroup',
10319 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10320 tag: String,
10321 moveClass: String
10322 }),
10323 setup(props, { slots }) {
10324 const instance = getCurrentInstance();
10325 const state = useTransitionState();
10326 let prevChildren;
10327 let children;
10328 onUpdated(() => {
10329 // children is guaranteed to exist after initial render
10330 if (!prevChildren.length) {
10331 return;
10332 }
10333 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10334 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10335 return;
10336 }
10337 // we divide the work into three loops to avoid mixing DOM reads and writes
10338 // in each iteration - which helps prevent layout thrashing.
10339 prevChildren.forEach(callPendingCbs);
10340 prevChildren.forEach(recordPosition);
10341 const movedChildren = prevChildren.filter(applyTranslation);
10342 // force reflow to put everything in position
10343 forceReflow();
10344 movedChildren.forEach(c => {
10345 const el = c.el;
10346 const style = el.style;
10347 addTransitionClass(el, moveClass);
10348 style.transform = style.webkitTransform = style.transitionDuration = '';
10349 const cb = (el._moveCb = (e) => {
10350 if (e && e.target !== el) {
10351 return;
10352 }
10353 if (!e || /transform$/.test(e.propertyName)) {
10354 el.removeEventListener('transitionend', cb);
10355 el._moveCb = null;
10356 removeTransitionClass(el, moveClass);
10357 }
10358 });
10359 el.addEventListener('transitionend', cb);
10360 });
10361 });
10362 return () => {
10363 const rawProps = toRaw(props);
10364 const cssTransitionProps = resolveTransitionProps(rawProps);
10365 let tag = rawProps.tag || Fragment;
10366 prevChildren = children;
10367 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10368 for (let i = 0; i < children.length; i++) {
10369 const child = children[i];
10370 if (child.key != null) {
10371 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10372 }
10373 else {
10374 warn$1(`<TransitionGroup> children must be keyed.`);
10375 }
10376 }
10377 if (prevChildren) {
10378 for (let i = 0; i < prevChildren.length; i++) {
10379 const child = prevChildren[i];
10380 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10381 positionMap.set(child, child.el.getBoundingClientRect());
10382 }
10383 }
10384 return createVNode(tag, null, children);
10385 };
10386 }
10387};
10388const TransitionGroup = TransitionGroupImpl;
10389function callPendingCbs(c) {
10390 const el = c.el;
10391 if (el._moveCb) {
10392 el._moveCb();
10393 }
10394 if (el._enterCb) {
10395 el._enterCb();
10396 }
10397}
10398function recordPosition(c) {
10399 newPositionMap.set(c, c.el.getBoundingClientRect());
10400}
10401function applyTranslation(c) {
10402 const oldPos = positionMap.get(c);
10403 const newPos = newPositionMap.get(c);
10404 const dx = oldPos.left - newPos.left;
10405 const dy = oldPos.top - newPos.top;
10406 if (dx || dy) {
10407 const s = c.el.style;
10408 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10409 s.transitionDuration = '0s';
10410 return c;
10411 }
10412}
10413function hasCSSTransform(el, root, moveClass) {
10414 // Detect whether an element with the move class applied has
10415 // CSS transitions. Since the element may be inside an entering
10416 // transition at this very moment, we make a clone of it and remove
10417 // all other transition classes applied to ensure only the move class
10418 // is applied.
10419 const clone = el.cloneNode();
10420 if (el._vtc) {
10421 el._vtc.forEach(cls => {
10422 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10423 });
10424 }
10425 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10426 clone.style.display = 'none';
10427 const container = (root.nodeType === 1 ? root : root.parentNode);
10428 container.appendChild(clone);
10429 const { hasTransform } = getTransitionInfo(clone);
10430 container.removeChild(clone);
10431 return hasTransform;
10432}
10433
10434const getModelAssigner = (vnode) => {
10435 const fn = vnode.props['onUpdate:modelValue'];
10436 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10437};
10438function onCompositionStart(e) {
10439 e.target.composing = true;
10440}
10441function onCompositionEnd(e) {
10442 const target = e.target;
10443 if (target.composing) {
10444 target.composing = false;
10445 trigger$1(target, 'input');
10446 }
10447}
10448function trigger$1(el, type) {
10449 const e = document.createEvent('HTMLEvents');
10450 e.initEvent(type, true, true);
10451 el.dispatchEvent(e);
10452}
10453// We are exporting the v-model runtime directly as vnode hooks so that it can
10454// be tree-shaken in case v-model is never used.
10455const vModelText = {
10456 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10457 el._assign = getModelAssigner(vnode);
10458 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10459 addEventListener(el, lazy ? 'change' : 'input', e => {
10460 if (e.target.composing)
10461 return;
10462 let domValue = el.value;
10463 if (trim) {
10464 domValue = domValue.trim();
10465 }
10466 else if (castToNumber) {
10467 domValue = toNumber(domValue);
10468 }
10469 el._assign(domValue);
10470 });
10471 if (trim) {
10472 addEventListener(el, 'change', () => {
10473 el.value = el.value.trim();
10474 });
10475 }
10476 if (!lazy) {
10477 addEventListener(el, 'compositionstart', onCompositionStart);
10478 addEventListener(el, 'compositionend', onCompositionEnd);
10479 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10480 // switching focus before confirming composition choice
10481 // this also fixes the issue where some browsers e.g. iOS Chrome
10482 // fires "change" instead of "input" on autocomplete.
10483 addEventListener(el, 'change', onCompositionEnd);
10484 }
10485 },
10486 // set value on mounted so it's after min/max for type="range"
10487 mounted(el, { value }) {
10488 el.value = value == null ? '' : value;
10489 },
10490 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10491 el._assign = getModelAssigner(vnode);
10492 // avoid clearing unresolved text. #2302
10493 if (el.composing)
10494 return;
10495 if (document.activeElement === el) {
10496 if (lazy) {
10497 return;
10498 }
10499 if (trim && el.value.trim() === value) {
10500 return;
10501 }
10502 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10503 return;
10504 }
10505 }
10506 const newValue = value == null ? '' : value;
10507 if (el.value !== newValue) {
10508 el.value = newValue;
10509 }
10510 }
10511};
10512const vModelCheckbox = {
10513 // #4096 array checkboxes need to be deep traversed
10514 deep: true,
10515 created(el, _, vnode) {
10516 el._assign = getModelAssigner(vnode);
10517 addEventListener(el, 'change', () => {
10518 const modelValue = el._modelValue;
10519 const elementValue = getValue(el);
10520 const checked = el.checked;
10521 const assign = el._assign;
10522 if (isArray(modelValue)) {
10523 const index = looseIndexOf(modelValue, elementValue);
10524 const found = index !== -1;
10525 if (checked && !found) {
10526 assign(modelValue.concat(elementValue));
10527 }
10528 else if (!checked && found) {
10529 const filtered = [...modelValue];
10530 filtered.splice(index, 1);
10531 assign(filtered);
10532 }
10533 }
10534 else if (isSet(modelValue)) {
10535 const cloned = new Set(modelValue);
10536 if (checked) {
10537 cloned.add(elementValue);
10538 }
10539 else {
10540 cloned.delete(elementValue);
10541 }
10542 assign(cloned);
10543 }
10544 else {
10545 assign(getCheckboxValue(el, checked));
10546 }
10547 });
10548 },
10549 // set initial checked on mount to wait for true-value/false-value
10550 mounted: setChecked,
10551 beforeUpdate(el, binding, vnode) {
10552 el._assign = getModelAssigner(vnode);
10553 setChecked(el, binding, vnode);
10554 }
10555};
10556function setChecked(el, { value, oldValue }, vnode) {
10557 el._modelValue = value;
10558 if (isArray(value)) {
10559 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10560 }
10561 else if (isSet(value)) {
10562 el.checked = value.has(vnode.props.value);
10563 }
10564 else if (value !== oldValue) {
10565 el.checked = looseEqual(value, getCheckboxValue(el, true));
10566 }
10567}
10568const vModelRadio = {
10569 created(el, { value }, vnode) {
10570 el.checked = looseEqual(value, vnode.props.value);
10571 el._assign = getModelAssigner(vnode);
10572 addEventListener(el, 'change', () => {
10573 el._assign(getValue(el));
10574 });
10575 },
10576 beforeUpdate(el, { value, oldValue }, vnode) {
10577 el._assign = getModelAssigner(vnode);
10578 if (value !== oldValue) {
10579 el.checked = looseEqual(value, vnode.props.value);
10580 }
10581 }
10582};
10583const vModelSelect = {
10584 // <select multiple> value need to be deep traversed
10585 deep: true,
10586 created(el, { value, modifiers: { number } }, vnode) {
10587 const isSetModel = isSet(value);
10588 addEventListener(el, 'change', () => {
10589 const selectedVal = Array.prototype.filter
10590 .call(el.options, (o) => o.selected)
10591 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10592 el._assign(el.multiple
10593 ? isSetModel
10594 ? new Set(selectedVal)
10595 : selectedVal
10596 : selectedVal[0]);
10597 });
10598 el._assign = getModelAssigner(vnode);
10599 },
10600 // set value in mounted & updated because <select> relies on its children
10601 // <option>s.
10602 mounted(el, { value }) {
10603 setSelected(el, value);
10604 },
10605 beforeUpdate(el, _binding, vnode) {
10606 el._assign = getModelAssigner(vnode);
10607 },
10608 updated(el, { value }) {
10609 setSelected(el, value);
10610 }
10611};
10612function setSelected(el, value) {
10613 const isMultiple = el.multiple;
10614 if (isMultiple && !isArray(value) && !isSet(value)) {
10615 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10616 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10617 return;
10618 }
10619 for (let i = 0, l = el.options.length; i < l; i++) {
10620 const option = el.options[i];
10621 const optionValue = getValue(option);
10622 if (isMultiple) {
10623 if (isArray(value)) {
10624 option.selected = looseIndexOf(value, optionValue) > -1;
10625 }
10626 else {
10627 option.selected = value.has(optionValue);
10628 }
10629 }
10630 else {
10631 if (looseEqual(getValue(option), value)) {
10632 if (el.selectedIndex !== i)
10633 el.selectedIndex = i;
10634 return;
10635 }
10636 }
10637 }
10638 if (!isMultiple && el.selectedIndex !== -1) {
10639 el.selectedIndex = -1;
10640 }
10641}
10642// retrieve raw value set via :value bindings
10643function getValue(el) {
10644 return '_value' in el ? el._value : el.value;
10645}
10646// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10647function getCheckboxValue(el, checked) {
10648 const key = checked ? '_trueValue' : '_falseValue';
10649 return key in el ? el[key] : checked;
10650}
10651const vModelDynamic = {
10652 created(el, binding, vnode) {
10653 callModelHook(el, binding, vnode, null, 'created');
10654 },
10655 mounted(el, binding, vnode) {
10656 callModelHook(el, binding, vnode, null, 'mounted');
10657 },
10658 beforeUpdate(el, binding, vnode, prevVNode) {
10659 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10660 },
10661 updated(el, binding, vnode, prevVNode) {
10662 callModelHook(el, binding, vnode, prevVNode, 'updated');
10663 }
10664};
10665function callModelHook(el, binding, vnode, prevVNode, hook) {
10666 let modelToUse;
10667 switch (el.tagName) {
10668 case 'SELECT':
10669 modelToUse = vModelSelect;
10670 break;
10671 case 'TEXTAREA':
10672 modelToUse = vModelText;
10673 break;
10674 default:
10675 switch (vnode.props && vnode.props.type) {
10676 case 'checkbox':
10677 modelToUse = vModelCheckbox;
10678 break;
10679 case 'radio':
10680 modelToUse = vModelRadio;
10681 break;
10682 default:
10683 modelToUse = vModelText;
10684 }
10685 }
10686 const fn = modelToUse[hook];
10687 fn && fn(el, binding, vnode, prevVNode);
10688}
10689
10690const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10691const modifierGuards = {
10692 stop: e => e.stopPropagation(),
10693 prevent: e => e.preventDefault(),
10694 self: e => e.target !== e.currentTarget,
10695 ctrl: e => !e.ctrlKey,
10696 shift: e => !e.shiftKey,
10697 alt: e => !e.altKey,
10698 meta: e => !e.metaKey,
10699 left: e => 'button' in e && e.button !== 0,
10700 middle: e => 'button' in e && e.button !== 1,
10701 right: e => 'button' in e && e.button !== 2,
10702 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10703};
10704/**
10705 * @private
10706 */
10707const withModifiers = (fn, modifiers) => {
10708 return (event, ...args) => {
10709 for (let i = 0; i < modifiers.length; i++) {
10710 const guard = modifierGuards[modifiers[i]];
10711 if (guard && guard(event, modifiers))
10712 return;
10713 }
10714 return fn(event, ...args);
10715 };
10716};
10717// Kept for 2.x compat.
10718// Note: IE11 compat for `spacebar` and `del` is removed for now.
10719const keyNames = {
10720 esc: 'escape',
10721 space: ' ',
10722 up: 'arrow-up',
10723 left: 'arrow-left',
10724 right: 'arrow-right',
10725 down: 'arrow-down',
10726 delete: 'backspace'
10727};
10728/**
10729 * @private
10730 */
10731const withKeys = (fn, modifiers) => {
10732 return (event) => {
10733 if (!('key' in event)) {
10734 return;
10735 }
10736 const eventKey = hyphenate(event.key);
10737 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10738 return fn(event);
10739 }
10740 };
10741};
10742
10743const vShow = {
10744 beforeMount(el, { value }, { transition }) {
10745 el._vod = el.style.display === 'none' ? '' : el.style.display;
10746 if (transition && value) {
10747 transition.beforeEnter(el);
10748 }
10749 else {
10750 setDisplay(el, value);
10751 }
10752 },
10753 mounted(el, { value }, { transition }) {
10754 if (transition && value) {
10755 transition.enter(el);
10756 }
10757 },
10758 updated(el, { value, oldValue }, { transition }) {
10759 if (!value === !oldValue)
10760 return;
10761 if (transition) {
10762 if (value) {
10763 transition.beforeEnter(el);
10764 setDisplay(el, true);
10765 transition.enter(el);
10766 }
10767 else {
10768 transition.leave(el, () => {
10769 setDisplay(el, false);
10770 });
10771 }
10772 }
10773 else {
10774 setDisplay(el, value);
10775 }
10776 },
10777 beforeUnmount(el, { value }) {
10778 setDisplay(el, value);
10779 }
10780};
10781function setDisplay(el, value) {
10782 el.style.display = value ? el._vod : 'none';
10783}
10784
10785const rendererOptions = extend({ patchProp }, nodeOps);
10786// lazy create the renderer - this makes core renderer logic tree-shakable
10787// in case the user only imports reactivity utilities from Vue.
10788let renderer;
10789let enabledHydration = false;
10790function ensureRenderer() {
10791 return (renderer ||
10792 (renderer = createRenderer(rendererOptions)));
10793}
10794function ensureHydrationRenderer() {
10795 renderer = enabledHydration
10796 ? renderer
10797 : createHydrationRenderer(rendererOptions);
10798 enabledHydration = true;
10799 return renderer;
10800}
10801// use explicit type casts here to avoid import() calls in rolled-up d.ts
10802const render = ((...args) => {
10803 ensureRenderer().render(...args);
10804});
10805const hydrate = ((...args) => {
10806 ensureHydrationRenderer().hydrate(...args);
10807});
10808const createApp = ((...args) => {
10809 const app = ensureRenderer().createApp(...args);
10810 {
10811 injectNativeTagCheck(app);
10812 injectCompilerOptionsCheck(app);
10813 }
10814 const { mount } = app;
10815 app.mount = (containerOrSelector) => {
10816 const container = normalizeContainer(containerOrSelector);
10817 if (!container)
10818 return;
10819 const component = app._component;
10820 if (!isFunction(component) && !component.render && !component.template) {
10821 // __UNSAFE__
10822 // Reason: potential execution of JS expressions in in-DOM template.
10823 // The user must make sure the in-DOM template is trusted. If it's
10824 // rendered by the server, the template should not contain any user data.
10825 component.template = container.innerHTML;
10826 }
10827 // clear content before mounting
10828 container.innerHTML = '';
10829 const proxy = mount(container, false, container instanceof SVGElement);
10830 if (container instanceof Element) {
10831 container.removeAttribute('v-cloak');
10832 container.setAttribute('data-v-app', '');
10833 }
10834 return proxy;
10835 };
10836 return app;
10837});
10838const createSSRApp = ((...args) => {
10839 const app = ensureHydrationRenderer().createApp(...args);
10840 {
10841 injectNativeTagCheck(app);
10842 injectCompilerOptionsCheck(app);
10843 }
10844 const { mount } = app;
10845 app.mount = (containerOrSelector) => {
10846 const container = normalizeContainer(containerOrSelector);
10847 if (container) {
10848 return mount(container, true, container instanceof SVGElement);
10849 }
10850 };
10851 return app;
10852});
10853function injectNativeTagCheck(app) {
10854 // Inject `isNativeTag`
10855 // this is used for component name validation (dev only)
10856 Object.defineProperty(app.config, 'isNativeTag', {
10857 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10858 writable: false
10859 });
10860}
10861// dev only
10862function injectCompilerOptionsCheck(app) {
10863 if (isRuntimeOnly()) {
10864 const isCustomElement = app.config.isCustomElement;
10865 Object.defineProperty(app.config, 'isCustomElement', {
10866 get() {
10867 return isCustomElement;
10868 },
10869 set() {
10870 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10871 `\`compilerOptions.isCustomElement\` instead.`);
10872 }
10873 });
10874 const compilerOptions = app.config.compilerOptions;
10875 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10876 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10877 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10878 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10879 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10880 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10881 `- 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`;
10882 Object.defineProperty(app.config, 'compilerOptions', {
10883 get() {
10884 warn$1(msg);
10885 return compilerOptions;
10886 },
10887 set() {
10888 warn$1(msg);
10889 }
10890 });
10891 }
10892}
10893function normalizeContainer(container) {
10894 if (isString(container)) {
10895 const res = document.querySelector(container);
10896 if (!res) {
10897 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10898 }
10899 return res;
10900 }
10901 if (window.ShadowRoot &&
10902 container instanceof window.ShadowRoot &&
10903 container.mode === 'closed') {
10904 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10905 }
10906 return container;
10907}
10908
10909var runtimeDom = /*#__PURE__*/Object.freeze({
10910 __proto__: null,
10911 render: render,
10912 hydrate: hydrate,
10913 createApp: createApp,
10914 createSSRApp: createSSRApp,
10915 defineCustomElement: defineCustomElement,
10916 defineSSRCustomElement: defineSSRCustomElement,
10917 VueElement: VueElement,
10918 useCssModule: useCssModule,
10919 useCssVars: useCssVars,
10920 Transition: Transition,
10921 TransitionGroup: TransitionGroup,
10922 vModelText: vModelText,
10923 vModelCheckbox: vModelCheckbox,
10924 vModelRadio: vModelRadio,
10925 vModelSelect: vModelSelect,
10926 vModelDynamic: vModelDynamic,
10927 withModifiers: withModifiers,
10928 withKeys: withKeys,
10929 vShow: vShow,
10930 computed: computed,
10931 reactive: reactive,
10932 ref: ref,
10933 readonly: readonly,
10934 unref: unref,
10935 proxyRefs: proxyRefs,
10936 isRef: isRef,
10937 toRef: toRef,
10938 toRefs: toRefs,
10939 isProxy: isProxy,
10940 isReactive: isReactive,
10941 isReadonly: isReadonly,
10942 customRef: customRef,
10943 triggerRef: triggerRef,
10944 shallowRef: shallowRef,
10945 shallowReactive: shallowReactive,
10946 shallowReadonly: shallowReadonly,
10947 markRaw: markRaw,
10948 toRaw: toRaw,
10949 effect: effect,
10950 stop: stop,
10951 ReactiveEffect: ReactiveEffect,
10952 effectScope: effectScope,
10953 EffectScope: EffectScope,
10954 getCurrentScope: getCurrentScope,
10955 onScopeDispose: onScopeDispose,
10956 watch: watch,
10957 watchEffect: watchEffect,
10958 watchPostEffect: watchPostEffect,
10959 watchSyncEffect: watchSyncEffect,
10960 onBeforeMount: onBeforeMount,
10961 onMounted: onMounted,
10962 onBeforeUpdate: onBeforeUpdate,
10963 onUpdated: onUpdated,
10964 onBeforeUnmount: onBeforeUnmount,
10965 onUnmounted: onUnmounted,
10966 onActivated: onActivated,
10967 onDeactivated: onDeactivated,
10968 onRenderTracked: onRenderTracked,
10969 onRenderTriggered: onRenderTriggered,
10970 onErrorCaptured: onErrorCaptured,
10971 onServerPrefetch: onServerPrefetch,
10972 provide: provide,
10973 inject: inject,
10974 nextTick: nextTick,
10975 defineComponent: defineComponent,
10976 defineAsyncComponent: defineAsyncComponent,
10977 useAttrs: useAttrs,
10978 useSlots: useSlots,
10979 defineProps: defineProps,
10980 defineEmits: defineEmits,
10981 defineExpose: defineExpose,
10982 withDefaults: withDefaults,
10983 mergeDefaults: mergeDefaults,
10984 withAsyncContext: withAsyncContext,
10985 getCurrentInstance: getCurrentInstance,
10986 h: h,
10987 createVNode: createVNode,
10988 cloneVNode: cloneVNode,
10989 mergeProps: mergeProps,
10990 isVNode: isVNode,
10991 Fragment: Fragment,
10992 Text: Text,
10993 Comment: Comment,
10994 Static: Static,
10995 Teleport: Teleport,
10996 Suspense: Suspense,
10997 KeepAlive: KeepAlive,
10998 BaseTransition: BaseTransition,
10999 withDirectives: withDirectives,
11000 useSSRContext: useSSRContext,
11001 ssrContextKey: ssrContextKey,
11002 createRenderer: createRenderer,
11003 createHydrationRenderer: createHydrationRenderer,
11004 queuePostFlushCb: queuePostFlushCb,
11005 warn: warn$1,
11006 handleError: handleError,
11007 callWithErrorHandling: callWithErrorHandling,
11008 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
11009 resolveComponent: resolveComponent,
11010 resolveDirective: resolveDirective,
11011 resolveDynamicComponent: resolveDynamicComponent,
11012 registerRuntimeCompiler: registerRuntimeCompiler,
11013 isRuntimeOnly: isRuntimeOnly,
11014 useTransitionState: useTransitionState,
11015 resolveTransitionHooks: resolveTransitionHooks,
11016 setTransitionHooks: setTransitionHooks,
11017 getTransitionRawChildren: getTransitionRawChildren,
11018 initCustomFormatter: initCustomFormatter,
11019 get devtools () { return devtools; },
11020 setDevtoolsHook: setDevtoolsHook,
11021 withCtx: withCtx,
11022 pushScopeId: pushScopeId,
11023 popScopeId: popScopeId,
11024 withScopeId: withScopeId,
11025 renderList: renderList,
11026 toHandlers: toHandlers,
11027 renderSlot: renderSlot,
11028 createSlots: createSlots,
11029 withMemo: withMemo,
11030 isMemoSame: isMemoSame,
11031 openBlock: openBlock,
11032 createBlock: createBlock,
11033 setBlockTracking: setBlockTracking,
11034 createTextVNode: createTextVNode,
11035 createCommentVNode: createCommentVNode,
11036 createStaticVNode: createStaticVNode,
11037 createElementVNode: createBaseVNode,
11038 createElementBlock: createElementBlock,
11039 guardReactiveProps: guardReactiveProps,
11040 toDisplayString: toDisplayString,
11041 camelize: camelize,
11042 capitalize: capitalize,
11043 toHandlerKey: toHandlerKey,
11044 normalizeProps: normalizeProps,
11045 normalizeClass: normalizeClass,
11046 normalizeStyle: normalizeStyle,
11047 transformVNodeArgs: transformVNodeArgs,
11048 version: version,
11049 ssrUtils: ssrUtils,
11050 resolveFilter: resolveFilter,
11051 compatUtils: compatUtils
11052});
11053
11054function initDev() {
11055 {
11056 {
11057 console.info(`You are running a development build of Vue.\n` +
11058 `Make sure to use the production build (*.prod.js) when deploying for production.`);
11059 }
11060 initCustomFormatter();
11061 }
11062}
11063
11064function defaultOnError(error) {
11065 throw error;
11066}
11067function defaultOnWarn(msg) {
11068 console.warn(`[Vue warn] ${msg.message}`);
11069}
11070function createCompilerError(code, loc, messages, additionalMessage) {
11071 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
11072 ;
11073 const error = new SyntaxError(String(msg));
11074 error.code = code;
11075 error.loc = loc;
11076 return error;
11077}
11078const errorMessages = {
11079 // parse errors
11080 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
11081 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
11082 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
11083 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
11084 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
11085 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
11086 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
11087 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
11088 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
11089 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
11090 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
11091 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
11092 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
11093 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
11094 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
11095 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
11096 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
11097 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
11098 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
11099 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
11100 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
11101 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
11102 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
11103 // Vue-specific parse errors
11104 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
11105 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
11106 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
11107 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
11108 'Note that dynamic directive argument cannot contain spaces.',
11109 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
11110 // transform errors
11111 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
11112 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
11113 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
11114 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
11115 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
11116 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
11117 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
11118 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
11119 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
11120 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
11121 `When there are multiple named slots, all slots should use <template> ` +
11122 `syntax to avoid scope ambiguity.`,
11123 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
11124 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
11125 `default slot. These children will be ignored.`,
11126 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
11127 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
11128 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
11129 [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.`,
11130 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
11131 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
11132 // generic errors
11133 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
11134 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
11135 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
11136 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
11137 // just to fullfill types
11138 [50 /* __EXTEND_POINT__ */]: ``
11139};
11140
11141const FRAGMENT = Symbol(`Fragment` );
11142const TELEPORT = Symbol(`Teleport` );
11143const SUSPENSE = Symbol(`Suspense` );
11144const KEEP_ALIVE = Symbol(`KeepAlive` );
11145const BASE_TRANSITION = Symbol(`BaseTransition` );
11146const OPEN_BLOCK = Symbol(`openBlock` );
11147const CREATE_BLOCK = Symbol(`createBlock` );
11148const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11149const CREATE_VNODE = Symbol(`createVNode` );
11150const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11151const CREATE_COMMENT = Symbol(`createCommentVNode` );
11152const CREATE_TEXT = Symbol(`createTextVNode` );
11153const CREATE_STATIC = Symbol(`createStaticVNode` );
11154const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11155const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11156const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11157const RESOLVE_FILTER = Symbol(`resolveFilter` );
11158const WITH_DIRECTIVES = Symbol(`withDirectives` );
11159const RENDER_LIST = Symbol(`renderList` );
11160const RENDER_SLOT = Symbol(`renderSlot` );
11161const CREATE_SLOTS = Symbol(`createSlots` );
11162const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11163const MERGE_PROPS = Symbol(`mergeProps` );
11164const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11165const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11166const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11167const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11168const TO_HANDLERS = Symbol(`toHandlers` );
11169const CAMELIZE = Symbol(`camelize` );
11170const CAPITALIZE = Symbol(`capitalize` );
11171const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11172const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11173const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11174const POP_SCOPE_ID = Symbol(`popScopeId` );
11175const WITH_CTX = Symbol(`withCtx` );
11176const UNREF = Symbol(`unref` );
11177const IS_REF = Symbol(`isRef` );
11178const WITH_MEMO = Symbol(`withMemo` );
11179const IS_MEMO_SAME = Symbol(`isMemoSame` );
11180// Name mapping for runtime helpers that need to be imported from 'vue' in
11181// generated code. Make sure these are correctly exported in the runtime!
11182// Using `any` here because TS doesn't allow symbols as index type.
11183const helperNameMap = {
11184 [FRAGMENT]: `Fragment`,
11185 [TELEPORT]: `Teleport`,
11186 [SUSPENSE]: `Suspense`,
11187 [KEEP_ALIVE]: `KeepAlive`,
11188 [BASE_TRANSITION]: `BaseTransition`,
11189 [OPEN_BLOCK]: `openBlock`,
11190 [CREATE_BLOCK]: `createBlock`,
11191 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11192 [CREATE_VNODE]: `createVNode`,
11193 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11194 [CREATE_COMMENT]: `createCommentVNode`,
11195 [CREATE_TEXT]: `createTextVNode`,
11196 [CREATE_STATIC]: `createStaticVNode`,
11197 [RESOLVE_COMPONENT]: `resolveComponent`,
11198 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11199 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11200 [RESOLVE_FILTER]: `resolveFilter`,
11201 [WITH_DIRECTIVES]: `withDirectives`,
11202 [RENDER_LIST]: `renderList`,
11203 [RENDER_SLOT]: `renderSlot`,
11204 [CREATE_SLOTS]: `createSlots`,
11205 [TO_DISPLAY_STRING]: `toDisplayString`,
11206 [MERGE_PROPS]: `mergeProps`,
11207 [NORMALIZE_CLASS]: `normalizeClass`,
11208 [NORMALIZE_STYLE]: `normalizeStyle`,
11209 [NORMALIZE_PROPS]: `normalizeProps`,
11210 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11211 [TO_HANDLERS]: `toHandlers`,
11212 [CAMELIZE]: `camelize`,
11213 [CAPITALIZE]: `capitalize`,
11214 [TO_HANDLER_KEY]: `toHandlerKey`,
11215 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11216 [PUSH_SCOPE_ID]: `pushScopeId`,
11217 [POP_SCOPE_ID]: `popScopeId`,
11218 [WITH_CTX]: `withCtx`,
11219 [UNREF]: `unref`,
11220 [IS_REF]: `isRef`,
11221 [WITH_MEMO]: `withMemo`,
11222 [IS_MEMO_SAME]: `isMemoSame`
11223};
11224function registerRuntimeHelpers(helpers) {
11225 Object.getOwnPropertySymbols(helpers).forEach(s => {
11226 helperNameMap[s] = helpers[s];
11227 });
11228}
11229
11230// AST Utilities ---------------------------------------------------------------
11231// Some expressions, e.g. sequence and conditional expressions, are never
11232// associated with template nodes, so their source locations are just a stub.
11233// Container types like CompoundExpression also don't need a real location.
11234const locStub = {
11235 source: '',
11236 start: { line: 1, column: 1, offset: 0 },
11237 end: { line: 1, column: 1, offset: 0 }
11238};
11239function createRoot(children, loc = locStub) {
11240 return {
11241 type: 0 /* ROOT */,
11242 children,
11243 helpers: [],
11244 components: [],
11245 directives: [],
11246 hoists: [],
11247 imports: [],
11248 cached: 0,
11249 temps: 0,
11250 codegenNode: undefined,
11251 loc
11252 };
11253}
11254function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11255 if (context) {
11256 if (isBlock) {
11257 context.helper(OPEN_BLOCK);
11258 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11259 }
11260 else {
11261 context.helper(getVNodeHelper(context.inSSR, isComponent));
11262 }
11263 if (directives) {
11264 context.helper(WITH_DIRECTIVES);
11265 }
11266 }
11267 return {
11268 type: 13 /* VNODE_CALL */,
11269 tag,
11270 props,
11271 children,
11272 patchFlag,
11273 dynamicProps,
11274 directives,
11275 isBlock,
11276 disableTracking,
11277 isComponent,
11278 loc
11279 };
11280}
11281function createArrayExpression(elements, loc = locStub) {
11282 return {
11283 type: 17 /* JS_ARRAY_EXPRESSION */,
11284 loc,
11285 elements
11286 };
11287}
11288function createObjectExpression(properties, loc = locStub) {
11289 return {
11290 type: 15 /* JS_OBJECT_EXPRESSION */,
11291 loc,
11292 properties
11293 };
11294}
11295function createObjectProperty(key, value) {
11296 return {
11297 type: 16 /* JS_PROPERTY */,
11298 loc: locStub,
11299 key: isString(key) ? createSimpleExpression(key, true) : key,
11300 value
11301 };
11302}
11303function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11304 return {
11305 type: 4 /* SIMPLE_EXPRESSION */,
11306 loc,
11307 content,
11308 isStatic,
11309 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11310 };
11311}
11312function createCompoundExpression(children, loc = locStub) {
11313 return {
11314 type: 8 /* COMPOUND_EXPRESSION */,
11315 loc,
11316 children
11317 };
11318}
11319function createCallExpression(callee, args = [], loc = locStub) {
11320 return {
11321 type: 14 /* JS_CALL_EXPRESSION */,
11322 loc,
11323 callee,
11324 arguments: args
11325 };
11326}
11327function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11328 return {
11329 type: 18 /* JS_FUNCTION_EXPRESSION */,
11330 params,
11331 returns,
11332 newline,
11333 isSlot,
11334 loc
11335 };
11336}
11337function createConditionalExpression(test, consequent, alternate, newline = true) {
11338 return {
11339 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11340 test,
11341 consequent,
11342 alternate,
11343 newline,
11344 loc: locStub
11345 };
11346}
11347function createCacheExpression(index, value, isVNode = false) {
11348 return {
11349 type: 20 /* JS_CACHE_EXPRESSION */,
11350 index,
11351 value,
11352 isVNode,
11353 loc: locStub
11354 };
11355}
11356function createBlockStatement(body) {
11357 return {
11358 type: 21 /* JS_BLOCK_STATEMENT */,
11359 body,
11360 loc: locStub
11361 };
11362}
11363
11364const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11365const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11366function isCoreComponent(tag) {
11367 if (isBuiltInType(tag, 'Teleport')) {
11368 return TELEPORT;
11369 }
11370 else if (isBuiltInType(tag, 'Suspense')) {
11371 return SUSPENSE;
11372 }
11373 else if (isBuiltInType(tag, 'KeepAlive')) {
11374 return KEEP_ALIVE;
11375 }
11376 else if (isBuiltInType(tag, 'BaseTransition')) {
11377 return BASE_TRANSITION;
11378 }
11379}
11380const nonIdentifierRE = /^\d|[^\$\w]/;
11381const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11382const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11383const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11384const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11385/**
11386 * Simple lexer to check if an expression is a member expression. This is
11387 * lax and only checks validity at the root level (i.e. does not validate exps
11388 * inside square brackets), but it's ok since these are only used on template
11389 * expressions and false positives are invalid expressions in the first place.
11390 */
11391const isMemberExpression = (path) => {
11392 // remove whitespaces around . or [ first
11393 path = path.trim().replace(whitespaceRE, s => s.trim());
11394 let state = 0 /* inMemberExp */;
11395 let stateStack = [];
11396 let currentOpenBracketCount = 0;
11397 let currentOpenParensCount = 0;
11398 let currentStringType = null;
11399 for (let i = 0; i < path.length; i++) {
11400 const char = path.charAt(i);
11401 switch (state) {
11402 case 0 /* inMemberExp */:
11403 if (char === '[') {
11404 stateStack.push(state);
11405 state = 1 /* inBrackets */;
11406 currentOpenBracketCount++;
11407 }
11408 else if (char === '(') {
11409 stateStack.push(state);
11410 state = 2 /* inParens */;
11411 currentOpenParensCount++;
11412 }
11413 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11414 return false;
11415 }
11416 break;
11417 case 1 /* inBrackets */:
11418 if (char === `'` || char === `"` || char === '`') {
11419 stateStack.push(state);
11420 state = 3 /* inString */;
11421 currentStringType = char;
11422 }
11423 else if (char === `[`) {
11424 currentOpenBracketCount++;
11425 }
11426 else if (char === `]`) {
11427 if (!--currentOpenBracketCount) {
11428 state = stateStack.pop();
11429 }
11430 }
11431 break;
11432 case 2 /* inParens */:
11433 if (char === `'` || char === `"` || char === '`') {
11434 stateStack.push(state);
11435 state = 3 /* inString */;
11436 currentStringType = char;
11437 }
11438 else if (char === `(`) {
11439 currentOpenParensCount++;
11440 }
11441 else if (char === `)`) {
11442 // if the exp ends as a call then it should not be considered valid
11443 if (i === path.length - 1) {
11444 return false;
11445 }
11446 if (!--currentOpenParensCount) {
11447 state = stateStack.pop();
11448 }
11449 }
11450 break;
11451 case 3 /* inString */:
11452 if (char === currentStringType) {
11453 state = stateStack.pop();
11454 currentStringType = null;
11455 }
11456 break;
11457 }
11458 }
11459 return !currentOpenBracketCount && !currentOpenParensCount;
11460};
11461function getInnerRange(loc, offset, length) {
11462 const source = loc.source.substr(offset, length);
11463 const newLoc = {
11464 source,
11465 start: advancePositionWithClone(loc.start, loc.source, offset),
11466 end: loc.end
11467 };
11468 if (length != null) {
11469 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11470 }
11471 return newLoc;
11472}
11473function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11474 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11475}
11476// advance by mutation without cloning (for performance reasons), since this
11477// gets called a lot in the parser
11478function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11479 let linesCount = 0;
11480 let lastNewLinePos = -1;
11481 for (let i = 0; i < numberOfCharacters; i++) {
11482 if (source.charCodeAt(i) === 10 /* newline char code */) {
11483 linesCount++;
11484 lastNewLinePos = i;
11485 }
11486 }
11487 pos.offset += numberOfCharacters;
11488 pos.line += linesCount;
11489 pos.column =
11490 lastNewLinePos === -1
11491 ? pos.column + numberOfCharacters
11492 : numberOfCharacters - lastNewLinePos;
11493 return pos;
11494}
11495function assert(condition, msg) {
11496 /* istanbul ignore if */
11497 if (!condition) {
11498 throw new Error(msg || `unexpected compiler condition`);
11499 }
11500}
11501function findDir(node, name, allowEmpty = false) {
11502 for (let i = 0; i < node.props.length; i++) {
11503 const p = node.props[i];
11504 if (p.type === 7 /* DIRECTIVE */ &&
11505 (allowEmpty || p.exp) &&
11506 (isString(name) ? p.name === name : name.test(p.name))) {
11507 return p;
11508 }
11509 }
11510}
11511function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11512 for (let i = 0; i < node.props.length; i++) {
11513 const p = node.props[i];
11514 if (p.type === 6 /* ATTRIBUTE */) {
11515 if (dynamicOnly)
11516 continue;
11517 if (p.name === name && (p.value || allowEmpty)) {
11518 return p;
11519 }
11520 }
11521 else if (p.name === 'bind' &&
11522 (p.exp || allowEmpty) &&
11523 isBindKey(p.arg, name)) {
11524 return p;
11525 }
11526 }
11527}
11528function isBindKey(arg, name) {
11529 return !!(arg && isStaticExp(arg) && arg.content === name);
11530}
11531function hasDynamicKeyVBind(node) {
11532 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11533 p.name === 'bind' &&
11534 (!p.arg || // v-bind="obj"
11535 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11536 !p.arg.isStatic) // v-bind:[foo]
11537 );
11538}
11539function isText(node) {
11540 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11541}
11542function isVSlot(p) {
11543 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11544}
11545function isTemplateNode(node) {
11546 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11547}
11548function isSlotOutlet(node) {
11549 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11550}
11551function getVNodeHelper(ssr, isComponent) {
11552 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11553}
11554function getVNodeBlockHelper(ssr, isComponent) {
11555 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11556}
11557const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11558function getUnnormalizedProps(props, callPath = []) {
11559 if (props &&
11560 !isString(props) &&
11561 props.type === 14 /* JS_CALL_EXPRESSION */) {
11562 const callee = props.callee;
11563 if (!isString(callee) && propsHelperSet.has(callee)) {
11564 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11565 }
11566 }
11567 return [props, callPath];
11568}
11569function injectProp(node, prop, context) {
11570 let propsWithInjection;
11571 const originalProps = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11572 /**
11573 * 1. mergeProps(...)
11574 * 2. toHandlers(...)
11575 * 3. normalizeProps(...)
11576 * 4. normalizeProps(guardReactiveProps(...))
11577 *
11578 * we need to get the real props before normalization
11579 */
11580 let props = originalProps;
11581 let callPath = [];
11582 let parentCall;
11583 if (props &&
11584 !isString(props) &&
11585 props.type === 14 /* JS_CALL_EXPRESSION */) {
11586 const ret = getUnnormalizedProps(props);
11587 props = ret[0];
11588 callPath = ret[1];
11589 parentCall = callPath[callPath.length - 1];
11590 }
11591 if (props == null || isString(props)) {
11592 propsWithInjection = createObjectExpression([prop]);
11593 }
11594 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11595 // merged props... add ours
11596 // only inject key to object literal if it's the first argument so that
11597 // if doesn't override user provided keys
11598 const first = props.arguments[0];
11599 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11600 first.properties.unshift(prop);
11601 }
11602 else {
11603 if (props.callee === TO_HANDLERS) {
11604 // #2366
11605 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11606 createObjectExpression([prop]),
11607 props
11608 ]);
11609 }
11610 else {
11611 props.arguments.unshift(createObjectExpression([prop]));
11612 }
11613 }
11614 !propsWithInjection && (propsWithInjection = props);
11615 }
11616 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11617 let alreadyExists = false;
11618 // check existing key to avoid overriding user provided keys
11619 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11620 const propKeyName = prop.key.content;
11621 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11622 p.key.content === propKeyName);
11623 }
11624 if (!alreadyExists) {
11625 props.properties.unshift(prop);
11626 }
11627 propsWithInjection = props;
11628 }
11629 else {
11630 // single v-bind with expression, return a merged replacement
11631 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11632 createObjectExpression([prop]),
11633 props
11634 ]);
11635 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11636 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11637 // the `guardReactiveProps` will no longer be needed
11638 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11639 parentCall = callPath[callPath.length - 2];
11640 }
11641 }
11642 if (node.type === 13 /* VNODE_CALL */) {
11643 if (parentCall) {
11644 parentCall.arguments[0] = propsWithInjection;
11645 }
11646 else {
11647 node.props = propsWithInjection;
11648 }
11649 }
11650 else {
11651 if (parentCall) {
11652 parentCall.arguments[0] = propsWithInjection;
11653 }
11654 else {
11655 node.arguments[2] = propsWithInjection;
11656 }
11657 }
11658}
11659function toValidAssetId(name, type) {
11660 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11661 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11662 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11663 })}`;
11664}
11665function getMemoedVNodeCall(node) {
11666 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11667 return node.arguments[1].returns;
11668 }
11669 else {
11670 return node;
11671 }
11672}
11673function makeBlock(node, { helper, removeHelper, inSSR }) {
11674 if (!node.isBlock) {
11675 node.isBlock = true;
11676 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11677 helper(OPEN_BLOCK);
11678 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11679 }
11680}
11681
11682const deprecationData$1 = {
11683 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11684 message: `Platform-native elements with "is" prop will no longer be ` +
11685 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11686 `prefixed with "vue:".`,
11687 link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
11688 },
11689 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11690 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11691 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11692 `\`v-model:${key}\`.`,
11693 link: `https://v3.vuejs.org/guide/migration/v-model.html`
11694 },
11695 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11696 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11697 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11698 },
11699 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11700 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11701 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11702 `that appears before v-bind in the case of conflict. ` +
11703 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11704 `You can also suppress this warning if the usage is intended.`,
11705 link: `https://v3.vuejs.org/guide/migration/v-bind.html`
11706 },
11707 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11708 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11709 link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
11710 },
11711 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11712 message: `v-if / v-for precedence when used on the same element has changed ` +
11713 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11714 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11715 `with <template> tags or use a computed property that filters v-for ` +
11716 `data source.`,
11717 link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
11718 },
11719 ["COMPILER_V_FOR_REF" /* COMPILER_V_FOR_REF */]: {
11720 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
11721 `Consider using function refs or refactor to avoid ref usage altogether.`,
11722 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
11723 },
11724 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11725 message: `<template> with no special directives will render as a native template ` +
11726 `element instead of its inner content in Vue 3.`
11727 },
11728 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11729 message: `"inline-template" has been removed in Vue 3.`,
11730 link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
11731 },
11732 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11733 message: `filters have been removed in Vue 3. ` +
11734 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11735 `Use method calls or computed properties instead.`,
11736 link: `https://v3.vuejs.org/guide/migration/filters.html`
11737 }
11738};
11739function getCompatValue(key, context) {
11740 const config = context.options
11741 ? context.options.compatConfig
11742 : context.compatConfig;
11743 const value = config && config[key];
11744 if (key === 'MODE') {
11745 return value || 3; // compiler defaults to v3 behavior
11746 }
11747 else {
11748 return value;
11749 }
11750}
11751function isCompatEnabled$1(key, context) {
11752 const mode = getCompatValue('MODE', context);
11753 const value = getCompatValue(key, context);
11754 // in v3 mode, only enable if explicitly set to true
11755 // otherwise enable for any non-false value
11756 return mode === 3 ? value === true : value !== false;
11757}
11758function checkCompatEnabled(key, context, loc, ...args) {
11759 const enabled = isCompatEnabled$1(key, context);
11760 if (enabled) {
11761 warnDeprecation$1(key, context, loc, ...args);
11762 }
11763 return enabled;
11764}
11765function warnDeprecation$1(key, context, loc, ...args) {
11766 const val = getCompatValue(key, context);
11767 if (val === 'suppress-warning') {
11768 return;
11769 }
11770 const { message, link } = deprecationData$1[key];
11771 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11772 const err = new SyntaxError(msg);
11773 err.code = key;
11774 if (loc)
11775 err.loc = loc;
11776 context.onWarn(err);
11777}
11778
11779// The default decoder only provides escapes for characters reserved as part of
11780// the template syntax, and is only used if the custom renderer did not provide
11781// a platform-specific decoder.
11782const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11783const decodeMap = {
11784 gt: '>',
11785 lt: '<',
11786 amp: '&',
11787 apos: "'",
11788 quot: '"'
11789};
11790const defaultParserOptions = {
11791 delimiters: [`{{`, `}}`],
11792 getNamespace: () => 0 /* HTML */,
11793 getTextMode: () => 0 /* DATA */,
11794 isVoidTag: NO,
11795 isPreTag: NO,
11796 isCustomElement: NO,
11797 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11798 onError: defaultOnError,
11799 onWarn: defaultOnWarn,
11800 comments: true
11801};
11802function baseParse(content, options = {}) {
11803 const context = createParserContext(content, options);
11804 const start = getCursor(context);
11805 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11806}
11807function createParserContext(content, rawOptions) {
11808 const options = extend({}, defaultParserOptions);
11809 let key;
11810 for (key in rawOptions) {
11811 // @ts-ignore
11812 options[key] =
11813 rawOptions[key] === undefined
11814 ? defaultParserOptions[key]
11815 : rawOptions[key];
11816 }
11817 return {
11818 options,
11819 column: 1,
11820 line: 1,
11821 offset: 0,
11822 originalSource: content,
11823 source: content,
11824 inPre: false,
11825 inVPre: false,
11826 onWarn: options.onWarn
11827 };
11828}
11829function parseChildren(context, mode, ancestors) {
11830 const parent = last(ancestors);
11831 const ns = parent ? parent.ns : 0 /* HTML */;
11832 const nodes = [];
11833 while (!isEnd(context, mode, ancestors)) {
11834 const s = context.source;
11835 let node = undefined;
11836 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11837 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11838 // '{{'
11839 node = parseInterpolation(context, mode);
11840 }
11841 else if (mode === 0 /* DATA */ && s[0] === '<') {
11842 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11843 if (s.length === 1) {
11844 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11845 }
11846 else if (s[1] === '!') {
11847 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11848 if (startsWith(s, '<!--')) {
11849 node = parseComment(context);
11850 }
11851 else if (startsWith(s, '<!DOCTYPE')) {
11852 // Ignore DOCTYPE by a limitation.
11853 node = parseBogusComment(context);
11854 }
11855 else if (startsWith(s, '<![CDATA[')) {
11856 if (ns !== 0 /* HTML */) {
11857 node = parseCDATA(context, ancestors);
11858 }
11859 else {
11860 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11861 node = parseBogusComment(context);
11862 }
11863 }
11864 else {
11865 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11866 node = parseBogusComment(context);
11867 }
11868 }
11869 else if (s[1] === '/') {
11870 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11871 if (s.length === 2) {
11872 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11873 }
11874 else if (s[2] === '>') {
11875 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11876 advanceBy(context, 3);
11877 continue;
11878 }
11879 else if (/[a-z]/i.test(s[2])) {
11880 emitError(context, 23 /* X_INVALID_END_TAG */);
11881 parseTag(context, 1 /* End */, parent);
11882 continue;
11883 }
11884 else {
11885 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11886 node = parseBogusComment(context);
11887 }
11888 }
11889 else if (/[a-z]/i.test(s[1])) {
11890 node = parseElement(context, ancestors);
11891 }
11892 else if (s[1] === '?') {
11893 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11894 node = parseBogusComment(context);
11895 }
11896 else {
11897 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11898 }
11899 }
11900 }
11901 if (!node) {
11902 node = parseText(context, mode);
11903 }
11904 if (isArray(node)) {
11905 for (let i = 0; i < node.length; i++) {
11906 pushNode(nodes, node[i]);
11907 }
11908 }
11909 else {
11910 pushNode(nodes, node);
11911 }
11912 }
11913 // Whitespace handling strategy like v2
11914 let removedWhitespace = false;
11915 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11916 const shouldCondense = context.options.whitespace !== 'preserve';
11917 for (let i = 0; i < nodes.length; i++) {
11918 const node = nodes[i];
11919 if (!context.inPre && node.type === 2 /* TEXT */) {
11920 if (!/[^\t\r\n\f ]/.test(node.content)) {
11921 const prev = nodes[i - 1];
11922 const next = nodes[i + 1];
11923 // Remove if:
11924 // - the whitespace is the first or last node, or:
11925 // - (condense mode) the whitespace is adjacent to a comment, or:
11926 // - (condense mode) the whitespace is between two elements AND contains newline
11927 if (!prev ||
11928 !next ||
11929 (shouldCondense &&
11930 (prev.type === 3 /* COMMENT */ ||
11931 next.type === 3 /* COMMENT */ ||
11932 (prev.type === 1 /* ELEMENT */ &&
11933 next.type === 1 /* ELEMENT */ &&
11934 /[\r\n]/.test(node.content))))) {
11935 removedWhitespace = true;
11936 nodes[i] = null;
11937 }
11938 else {
11939 // Otherwise, the whitespace is condensed into a single space
11940 node.content = ' ';
11941 }
11942 }
11943 else if (shouldCondense) {
11944 // in condense mode, consecutive whitespaces in text are condensed
11945 // down to a single space.
11946 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11947 }
11948 }
11949 // Remove comment nodes if desired by configuration.
11950 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11951 removedWhitespace = true;
11952 nodes[i] = null;
11953 }
11954 }
11955 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11956 // remove leading newline per html spec
11957 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11958 const first = nodes[0];
11959 if (first && first.type === 2 /* TEXT */) {
11960 first.content = first.content.replace(/^\r?\n/, '');
11961 }
11962 }
11963 }
11964 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11965}
11966function pushNode(nodes, node) {
11967 if (node.type === 2 /* TEXT */) {
11968 const prev = last(nodes);
11969 // Merge if both this and the previous node are text and those are
11970 // consecutive. This happens for cases like "a < b".
11971 if (prev &&
11972 prev.type === 2 /* TEXT */ &&
11973 prev.loc.end.offset === node.loc.start.offset) {
11974 prev.content += node.content;
11975 prev.loc.end = node.loc.end;
11976 prev.loc.source += node.loc.source;
11977 return;
11978 }
11979 }
11980 nodes.push(node);
11981}
11982function parseCDATA(context, ancestors) {
11983 advanceBy(context, 9);
11984 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11985 if (context.source.length === 0) {
11986 emitError(context, 6 /* EOF_IN_CDATA */);
11987 }
11988 else {
11989 advanceBy(context, 3);
11990 }
11991 return nodes;
11992}
11993function parseComment(context) {
11994 const start = getCursor(context);
11995 let content;
11996 // Regular comment.
11997 const match = /--(\!)?>/.exec(context.source);
11998 if (!match) {
11999 content = context.source.slice(4);
12000 advanceBy(context, context.source.length);
12001 emitError(context, 7 /* EOF_IN_COMMENT */);
12002 }
12003 else {
12004 if (match.index <= 3) {
12005 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
12006 }
12007 if (match[1]) {
12008 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
12009 }
12010 content = context.source.slice(4, match.index);
12011 // Advancing with reporting nested comments.
12012 const s = context.source.slice(0, match.index);
12013 let prevIndex = 1, nestedIndex = 0;
12014 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
12015 advanceBy(context, nestedIndex - prevIndex + 1);
12016 if (nestedIndex + 4 < s.length) {
12017 emitError(context, 16 /* NESTED_COMMENT */);
12018 }
12019 prevIndex = nestedIndex + 1;
12020 }
12021 advanceBy(context, match.index + match[0].length - prevIndex + 1);
12022 }
12023 return {
12024 type: 3 /* COMMENT */,
12025 content,
12026 loc: getSelection(context, start)
12027 };
12028}
12029function parseBogusComment(context) {
12030 const start = getCursor(context);
12031 const contentStart = context.source[1] === '?' ? 1 : 2;
12032 let content;
12033 const closeIndex = context.source.indexOf('>');
12034 if (closeIndex === -1) {
12035 content = context.source.slice(contentStart);
12036 advanceBy(context, context.source.length);
12037 }
12038 else {
12039 content = context.source.slice(contentStart, closeIndex);
12040 advanceBy(context, closeIndex + 1);
12041 }
12042 return {
12043 type: 3 /* COMMENT */,
12044 content,
12045 loc: getSelection(context, start)
12046 };
12047}
12048function parseElement(context, ancestors) {
12049 // Start tag.
12050 const wasInPre = context.inPre;
12051 const wasInVPre = context.inVPre;
12052 const parent = last(ancestors);
12053 const element = parseTag(context, 0 /* Start */, parent);
12054 const isPreBoundary = context.inPre && !wasInPre;
12055 const isVPreBoundary = context.inVPre && !wasInVPre;
12056 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
12057 // #4030 self-closing <pre> tag
12058 if (isPreBoundary) {
12059 context.inPre = false;
12060 }
12061 if (isVPreBoundary) {
12062 context.inVPre = false;
12063 }
12064 return element;
12065 }
12066 // Children.
12067 ancestors.push(element);
12068 const mode = context.options.getTextMode(element, parent);
12069 const children = parseChildren(context, mode, ancestors);
12070 ancestors.pop();
12071 element.children = children;
12072 // End tag.
12073 if (startsWithEndTagOpen(context.source, element.tag)) {
12074 parseTag(context, 1 /* End */, parent);
12075 }
12076 else {
12077 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
12078 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
12079 const first = children[0];
12080 if (first && startsWith(first.loc.source, '<!--')) {
12081 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
12082 }
12083 }
12084 }
12085 element.loc = getSelection(context, element.loc.start);
12086 if (isPreBoundary) {
12087 context.inPre = false;
12088 }
12089 if (isVPreBoundary) {
12090 context.inVPre = false;
12091 }
12092 return element;
12093}
12094const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
12095function parseTag(context, type, parent) {
12096 // Tag open.
12097 const start = getCursor(context);
12098 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
12099 const tag = match[1];
12100 const ns = context.options.getNamespace(tag, parent);
12101 advanceBy(context, match[0].length);
12102 advanceSpaces(context);
12103 // save current state in case we need to re-parse attributes with v-pre
12104 const cursor = getCursor(context);
12105 const currentSource = context.source;
12106 // check <pre> tag
12107 if (context.options.isPreTag(tag)) {
12108 context.inPre = true;
12109 }
12110 // Attributes.
12111 let props = parseAttributes(context, type);
12112 // check v-pre
12113 if (type === 0 /* Start */ &&
12114 !context.inVPre &&
12115 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
12116 context.inVPre = true;
12117 // reset context
12118 extend(context, cursor);
12119 context.source = currentSource;
12120 // re-parse attrs and filter out v-pre itself
12121 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
12122 }
12123 // Tag close.
12124 let isSelfClosing = false;
12125 if (context.source.length === 0) {
12126 emitError(context, 9 /* EOF_IN_TAG */);
12127 }
12128 else {
12129 isSelfClosing = startsWith(context.source, '/>');
12130 if (type === 1 /* End */ && isSelfClosing) {
12131 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
12132 }
12133 advanceBy(context, isSelfClosing ? 2 : 1);
12134 }
12135 if (type === 1 /* End */) {
12136 return;
12137 }
12138 let tagType = 0 /* ELEMENT */;
12139 if (!context.inVPre) {
12140 if (tag === 'slot') {
12141 tagType = 2 /* SLOT */;
12142 }
12143 else if (tag === 'template') {
12144 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
12145 tagType = 3 /* TEMPLATE */;
12146 }
12147 }
12148 else if (isComponent(tag, props, context)) {
12149 tagType = 1 /* COMPONENT */;
12150 }
12151 }
12152 return {
12153 type: 1 /* ELEMENT */,
12154 ns,
12155 tag,
12156 tagType,
12157 props,
12158 isSelfClosing,
12159 children: [],
12160 loc: getSelection(context, start),
12161 codegenNode: undefined // to be created during transform phase
12162 };
12163}
12164function isComponent(tag, props, context) {
12165 const options = context.options;
12166 if (options.isCustomElement(tag)) {
12167 return false;
12168 }
12169 if (tag === 'component' ||
12170 /^[A-Z]/.test(tag) ||
12171 isCoreComponent(tag) ||
12172 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12173 (options.isNativeTag && !options.isNativeTag(tag))) {
12174 return true;
12175 }
12176 // at this point the tag should be a native tag, but check for potential "is"
12177 // casting
12178 for (let i = 0; i < props.length; i++) {
12179 const p = props[i];
12180 if (p.type === 6 /* ATTRIBUTE */) {
12181 if (p.name === 'is' && p.value) {
12182 if (p.value.content.startsWith('vue:')) {
12183 return true;
12184 }
12185 }
12186 }
12187 else {
12188 // directive
12189 // v-is (TODO Deprecate)
12190 if (p.name === 'is') {
12191 return true;
12192 }
12193 else if (
12194 // :is on plain element - only treat as component in compat mode
12195 p.name === 'bind' &&
12196 isBindKey(p.arg, 'is') &&
12197 false &&
12198 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12199 return true;
12200 }
12201 }
12202 }
12203}
12204function parseAttributes(context, type) {
12205 const props = [];
12206 const attributeNames = new Set();
12207 while (context.source.length > 0 &&
12208 !startsWith(context.source, '>') &&
12209 !startsWith(context.source, '/>')) {
12210 if (startsWith(context.source, '/')) {
12211 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12212 advanceBy(context, 1);
12213 advanceSpaces(context);
12214 continue;
12215 }
12216 if (type === 1 /* End */) {
12217 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12218 }
12219 const attr = parseAttribute(context, attributeNames);
12220 // Trim whitespace between class
12221 // https://github.com/vuejs/vue-next/issues/4251
12222 if (attr.type === 6 /* ATTRIBUTE */ &&
12223 attr.value &&
12224 attr.name === 'class') {
12225 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12226 }
12227 if (type === 0 /* Start */) {
12228 props.push(attr);
12229 }
12230 if (/^[^\t\r\n\f />]/.test(context.source)) {
12231 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12232 }
12233 advanceSpaces(context);
12234 }
12235 return props;
12236}
12237function parseAttribute(context, nameSet) {
12238 // Name.
12239 const start = getCursor(context);
12240 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12241 const name = match[0];
12242 if (nameSet.has(name)) {
12243 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12244 }
12245 nameSet.add(name);
12246 if (name[0] === '=') {
12247 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12248 }
12249 {
12250 const pattern = /["'<]/g;
12251 let m;
12252 while ((m = pattern.exec(name))) {
12253 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12254 }
12255 }
12256 advanceBy(context, name.length);
12257 // Value
12258 let value = undefined;
12259 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12260 advanceSpaces(context);
12261 advanceBy(context, 1);
12262 advanceSpaces(context);
12263 value = parseAttributeValue(context);
12264 if (!value) {
12265 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12266 }
12267 }
12268 const loc = getSelection(context, start);
12269 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12270 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12271 let isPropShorthand = startsWith(name, '.');
12272 let dirName = match[1] ||
12273 (isPropShorthand || startsWith(name, ':')
12274 ? 'bind'
12275 : startsWith(name, '@')
12276 ? 'on'
12277 : 'slot');
12278 let arg;
12279 if (match[2]) {
12280 const isSlot = dirName === 'slot';
12281 const startOffset = name.lastIndexOf(match[2]);
12282 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12283 let content = match[2];
12284 let isStatic = true;
12285 if (content.startsWith('[')) {
12286 isStatic = false;
12287 if (!content.endsWith(']')) {
12288 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12289 content = content.substr(1);
12290 }
12291 else {
12292 content = content.substr(1, content.length - 2);
12293 }
12294 }
12295 else if (isSlot) {
12296 // #1241 special case for v-slot: vuetify relies extensively on slot
12297 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12298 // supports such usage so we are keeping it consistent with 2.x.
12299 content += match[3] || '';
12300 }
12301 arg = {
12302 type: 4 /* SIMPLE_EXPRESSION */,
12303 content,
12304 isStatic,
12305 constType: isStatic
12306 ? 3 /* CAN_STRINGIFY */
12307 : 0 /* NOT_CONSTANT */,
12308 loc
12309 };
12310 }
12311 if (value && value.isQuoted) {
12312 const valueLoc = value.loc;
12313 valueLoc.start.offset++;
12314 valueLoc.start.column++;
12315 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12316 valueLoc.source = valueLoc.source.slice(1, -1);
12317 }
12318 const modifiers = match[3] ? match[3].substr(1).split('.') : [];
12319 if (isPropShorthand)
12320 modifiers.push('prop');
12321 return {
12322 type: 7 /* DIRECTIVE */,
12323 name: dirName,
12324 exp: value && {
12325 type: 4 /* SIMPLE_EXPRESSION */,
12326 content: value.content,
12327 isStatic: false,
12328 // Treat as non-constant by default. This can be potentially set to
12329 // other values by `transformExpression` to make it eligible for hoisting.
12330 constType: 0 /* NOT_CONSTANT */,
12331 loc: value.loc
12332 },
12333 arg,
12334 modifiers,
12335 loc
12336 };
12337 }
12338 // missing directive name or illegal directive name
12339 if (!context.inVPre && startsWith(name, 'v-')) {
12340 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12341 }
12342 return {
12343 type: 6 /* ATTRIBUTE */,
12344 name,
12345 value: value && {
12346 type: 2 /* TEXT */,
12347 content: value.content,
12348 loc: value.loc
12349 },
12350 loc
12351 };
12352}
12353function parseAttributeValue(context) {
12354 const start = getCursor(context);
12355 let content;
12356 const quote = context.source[0];
12357 const isQuoted = quote === `"` || quote === `'`;
12358 if (isQuoted) {
12359 // Quoted value.
12360 advanceBy(context, 1);
12361 const endIndex = context.source.indexOf(quote);
12362 if (endIndex === -1) {
12363 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12364 }
12365 else {
12366 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12367 advanceBy(context, 1);
12368 }
12369 }
12370 else {
12371 // Unquoted
12372 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12373 if (!match) {
12374 return undefined;
12375 }
12376 const unexpectedChars = /["'<=`]/g;
12377 let m;
12378 while ((m = unexpectedChars.exec(match[0]))) {
12379 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12380 }
12381 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12382 }
12383 return { content, isQuoted, loc: getSelection(context, start) };
12384}
12385function parseInterpolation(context, mode) {
12386 const [open, close] = context.options.delimiters;
12387 const closeIndex = context.source.indexOf(close, open.length);
12388 if (closeIndex === -1) {
12389 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12390 return undefined;
12391 }
12392 const start = getCursor(context);
12393 advanceBy(context, open.length);
12394 const innerStart = getCursor(context);
12395 const innerEnd = getCursor(context);
12396 const rawContentLength = closeIndex - open.length;
12397 const rawContent = context.source.slice(0, rawContentLength);
12398 const preTrimContent = parseTextData(context, rawContentLength, mode);
12399 const content = preTrimContent.trim();
12400 const startOffset = preTrimContent.indexOf(content);
12401 if (startOffset > 0) {
12402 advancePositionWithMutation(innerStart, rawContent, startOffset);
12403 }
12404 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12405 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12406 advanceBy(context, close.length);
12407 return {
12408 type: 5 /* INTERPOLATION */,
12409 content: {
12410 type: 4 /* SIMPLE_EXPRESSION */,
12411 isStatic: false,
12412 // Set `isConstant` to false by default and will decide in transformExpression
12413 constType: 0 /* NOT_CONSTANT */,
12414 content,
12415 loc: getSelection(context, innerStart, innerEnd)
12416 },
12417 loc: getSelection(context, start)
12418 };
12419}
12420function parseText(context, mode) {
12421 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12422 let endIndex = context.source.length;
12423 for (let i = 0; i < endTokens.length; i++) {
12424 const index = context.source.indexOf(endTokens[i], 1);
12425 if (index !== -1 && endIndex > index) {
12426 endIndex = index;
12427 }
12428 }
12429 const start = getCursor(context);
12430 const content = parseTextData(context, endIndex, mode);
12431 return {
12432 type: 2 /* TEXT */,
12433 content,
12434 loc: getSelection(context, start)
12435 };
12436}
12437/**
12438 * Get text data with a given length from the current location.
12439 * This translates HTML entities in the text data.
12440 */
12441function parseTextData(context, length, mode) {
12442 const rawText = context.source.slice(0, length);
12443 advanceBy(context, length);
12444 if (mode === 2 /* RAWTEXT */ ||
12445 mode === 3 /* CDATA */ ||
12446 rawText.indexOf('&') === -1) {
12447 return rawText;
12448 }
12449 else {
12450 // DATA or RCDATA containing "&"". Entity decoding required.
12451 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12452 }
12453}
12454function getCursor(context) {
12455 const { column, line, offset } = context;
12456 return { column, line, offset };
12457}
12458function getSelection(context, start, end) {
12459 end = end || getCursor(context);
12460 return {
12461 start,
12462 end,
12463 source: context.originalSource.slice(start.offset, end.offset)
12464 };
12465}
12466function last(xs) {
12467 return xs[xs.length - 1];
12468}
12469function startsWith(source, searchString) {
12470 return source.startsWith(searchString);
12471}
12472function advanceBy(context, numberOfCharacters) {
12473 const { source } = context;
12474 advancePositionWithMutation(context, source, numberOfCharacters);
12475 context.source = source.slice(numberOfCharacters);
12476}
12477function advanceSpaces(context) {
12478 const match = /^[\t\r\n\f ]+/.exec(context.source);
12479 if (match) {
12480 advanceBy(context, match[0].length);
12481 }
12482}
12483function getNewPosition(context, start, numberOfCharacters) {
12484 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12485}
12486function emitError(context, code, offset, loc = getCursor(context)) {
12487 if (offset) {
12488 loc.offset += offset;
12489 loc.column += offset;
12490 }
12491 context.options.onError(createCompilerError(code, {
12492 start: loc,
12493 end: loc,
12494 source: ''
12495 }));
12496}
12497function isEnd(context, mode, ancestors) {
12498 const s = context.source;
12499 switch (mode) {
12500 case 0 /* DATA */:
12501 if (startsWith(s, '</')) {
12502 // TODO: probably bad performance
12503 for (let i = ancestors.length - 1; i >= 0; --i) {
12504 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12505 return true;
12506 }
12507 }
12508 }
12509 break;
12510 case 1 /* RCDATA */:
12511 case 2 /* RAWTEXT */: {
12512 const parent = last(ancestors);
12513 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12514 return true;
12515 }
12516 break;
12517 }
12518 case 3 /* CDATA */:
12519 if (startsWith(s, ']]>')) {
12520 return true;
12521 }
12522 break;
12523 }
12524 return !s;
12525}
12526function startsWithEndTagOpen(source, tag) {
12527 return (startsWith(source, '</') &&
12528 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
12529 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12530}
12531
12532function hoistStatic(root, context) {
12533 walk(root, context,
12534 // Root node is unfortunately non-hoistable due to potential parent
12535 // fallthrough attributes.
12536 isSingleElementRoot(root, root.children[0]));
12537}
12538function isSingleElementRoot(root, child) {
12539 const { children } = root;
12540 return (children.length === 1 &&
12541 child.type === 1 /* ELEMENT */ &&
12542 !isSlotOutlet(child));
12543}
12544function walk(node, context, doNotHoistNode = false) {
12545 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
12546 // static bindings with expressions. These expressions are guaranteed to be
12547 // constant so they are still eligible for hoisting, but they are only
12548 // available at runtime and therefore cannot be evaluated ahead of time.
12549 // This is only a concern for pre-stringification (via transformHoist by
12550 // @vue/compiler-dom), but doing it here allows us to perform only one full
12551 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
12552 // stringficiation threshold is met.
12553 let canStringify = true;
12554 const { children } = node;
12555 const originalCount = children.length;
12556 let hoistedCount = 0;
12557 for (let i = 0; i < children.length; i++) {
12558 const child = children[i];
12559 // only plain elements & text calls are eligible for hoisting.
12560 if (child.type === 1 /* ELEMENT */ &&
12561 child.tagType === 0 /* ELEMENT */) {
12562 const constantType = doNotHoistNode
12563 ? 0 /* NOT_CONSTANT */
12564 : getConstantType(child, context);
12565 if (constantType > 0 /* NOT_CONSTANT */) {
12566 if (constantType < 3 /* CAN_STRINGIFY */) {
12567 canStringify = false;
12568 }
12569 if (constantType >= 2 /* CAN_HOIST */) {
12570 child.codegenNode.patchFlag =
12571 -1 /* HOISTED */ + (` /* HOISTED */` );
12572 child.codegenNode = context.hoist(child.codegenNode);
12573 hoistedCount++;
12574 continue;
12575 }
12576 }
12577 else {
12578 // node may contain dynamic children, but its props may be eligible for
12579 // hoisting.
12580 const codegenNode = child.codegenNode;
12581 if (codegenNode.type === 13 /* VNODE_CALL */) {
12582 const flag = getPatchFlag(codegenNode);
12583 if ((!flag ||
12584 flag === 512 /* NEED_PATCH */ ||
12585 flag === 1 /* TEXT */) &&
12586 getGeneratedPropsConstantType(child, context) >=
12587 2 /* CAN_HOIST */) {
12588 const props = getNodeProps(child);
12589 if (props) {
12590 codegenNode.props = context.hoist(props);
12591 }
12592 }
12593 if (codegenNode.dynamicProps) {
12594 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12595 }
12596 }
12597 }
12598 }
12599 else if (child.type === 12 /* TEXT_CALL */) {
12600 const contentType = getConstantType(child.content, context);
12601 if (contentType > 0) {
12602 if (contentType < 3 /* CAN_STRINGIFY */) {
12603 canStringify = false;
12604 }
12605 if (contentType >= 2 /* CAN_HOIST */) {
12606 child.codegenNode = context.hoist(child.codegenNode);
12607 hoistedCount++;
12608 }
12609 }
12610 }
12611 // walk further
12612 if (child.type === 1 /* ELEMENT */) {
12613 const isComponent = child.tagType === 1 /* COMPONENT */;
12614 if (isComponent) {
12615 context.scopes.vSlot++;
12616 }
12617 walk(child, context);
12618 if (isComponent) {
12619 context.scopes.vSlot--;
12620 }
12621 }
12622 else if (child.type === 11 /* FOR */) {
12623 // Do not hoist v-for single child because it has to be a block
12624 walk(child, context, child.children.length === 1);
12625 }
12626 else if (child.type === 9 /* IF */) {
12627 for (let i = 0; i < child.branches.length; i++) {
12628 // Do not hoist v-if single child because it has to be a block
12629 walk(child.branches[i], context, child.branches[i].children.length === 1);
12630 }
12631 }
12632 }
12633 if (canStringify && hoistedCount && context.transformHoist) {
12634 context.transformHoist(children, context, node);
12635 }
12636 // all children were hoisted - the entire children array is hoistable.
12637 if (hoistedCount &&
12638 hoistedCount === originalCount &&
12639 node.type === 1 /* ELEMENT */ &&
12640 node.tagType === 0 /* ELEMENT */ &&
12641 node.codegenNode &&
12642 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12643 isArray(node.codegenNode.children)) {
12644 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12645 }
12646}
12647function getConstantType(node, context) {
12648 const { constantCache } = context;
12649 switch (node.type) {
12650 case 1 /* ELEMENT */:
12651 if (node.tagType !== 0 /* ELEMENT */) {
12652 return 0 /* NOT_CONSTANT */;
12653 }
12654 const cached = constantCache.get(node);
12655 if (cached !== undefined) {
12656 return cached;
12657 }
12658 const codegenNode = node.codegenNode;
12659 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12660 return 0 /* NOT_CONSTANT */;
12661 }
12662 const flag = getPatchFlag(codegenNode);
12663 if (!flag) {
12664 let returnType = 3 /* CAN_STRINGIFY */;
12665 // Element itself has no patch flag. However we still need to check:
12666 // 1. Even for a node with no patch flag, it is possible for it to contain
12667 // non-hoistable expressions that refers to scope variables, e.g. compiler
12668 // injected keys or cached event handlers. Therefore we need to always
12669 // check the codegenNode's props to be sure.
12670 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12671 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12672 constantCache.set(node, 0 /* NOT_CONSTANT */);
12673 return 0 /* NOT_CONSTANT */;
12674 }
12675 if (generatedPropsType < returnType) {
12676 returnType = generatedPropsType;
12677 }
12678 // 2. its children.
12679 for (let i = 0; i < node.children.length; i++) {
12680 const childType = getConstantType(node.children[i], context);
12681 if (childType === 0 /* NOT_CONSTANT */) {
12682 constantCache.set(node, 0 /* NOT_CONSTANT */);
12683 return 0 /* NOT_CONSTANT */;
12684 }
12685 if (childType < returnType) {
12686 returnType = childType;
12687 }
12688 }
12689 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12690 // type, check if any of the props can cause the type to be lowered
12691 // we can skip can_patch because it's guaranteed by the absence of a
12692 // patchFlag.
12693 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12694 for (let i = 0; i < node.props.length; i++) {
12695 const p = node.props[i];
12696 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12697 const expType = getConstantType(p.exp, context);
12698 if (expType === 0 /* NOT_CONSTANT */) {
12699 constantCache.set(node, 0 /* NOT_CONSTANT */);
12700 return 0 /* NOT_CONSTANT */;
12701 }
12702 if (expType < returnType) {
12703 returnType = expType;
12704 }
12705 }
12706 }
12707 }
12708 // only svg/foreignObject could be block here, however if they are
12709 // static then they don't need to be blocks since there will be no
12710 // nested updates.
12711 if (codegenNode.isBlock) {
12712 context.removeHelper(OPEN_BLOCK);
12713 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12714 codegenNode.isBlock = false;
12715 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12716 }
12717 constantCache.set(node, returnType);
12718 return returnType;
12719 }
12720 else {
12721 constantCache.set(node, 0 /* NOT_CONSTANT */);
12722 return 0 /* NOT_CONSTANT */;
12723 }
12724 case 2 /* TEXT */:
12725 case 3 /* COMMENT */:
12726 return 3 /* CAN_STRINGIFY */;
12727 case 9 /* IF */:
12728 case 11 /* FOR */:
12729 case 10 /* IF_BRANCH */:
12730 return 0 /* NOT_CONSTANT */;
12731 case 5 /* INTERPOLATION */:
12732 case 12 /* TEXT_CALL */:
12733 return getConstantType(node.content, context);
12734 case 4 /* SIMPLE_EXPRESSION */:
12735 return node.constType;
12736 case 8 /* COMPOUND_EXPRESSION */:
12737 let returnType = 3 /* CAN_STRINGIFY */;
12738 for (let i = 0; i < node.children.length; i++) {
12739 const child = node.children[i];
12740 if (isString(child) || isSymbol(child)) {
12741 continue;
12742 }
12743 const childType = getConstantType(child, context);
12744 if (childType === 0 /* NOT_CONSTANT */) {
12745 return 0 /* NOT_CONSTANT */;
12746 }
12747 else if (childType < returnType) {
12748 returnType = childType;
12749 }
12750 }
12751 return returnType;
12752 default:
12753 return 0 /* NOT_CONSTANT */;
12754 }
12755}
12756const allowHoistedHelperSet = new Set([
12757 NORMALIZE_CLASS,
12758 NORMALIZE_STYLE,
12759 NORMALIZE_PROPS,
12760 GUARD_REACTIVE_PROPS
12761]);
12762function getConstantTypeOfHelperCall(value, context) {
12763 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12764 !isString(value.callee) &&
12765 allowHoistedHelperSet.has(value.callee)) {
12766 const arg = value.arguments[0];
12767 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12768 return getConstantType(arg, context);
12769 }
12770 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12771 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12772 return getConstantTypeOfHelperCall(arg, context);
12773 }
12774 }
12775 return 0 /* NOT_CONSTANT */;
12776}
12777function getGeneratedPropsConstantType(node, context) {
12778 let returnType = 3 /* CAN_STRINGIFY */;
12779 const props = getNodeProps(node);
12780 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12781 const { properties } = props;
12782 for (let i = 0; i < properties.length; i++) {
12783 const { key, value } = properties[i];
12784 const keyType = getConstantType(key, context);
12785 if (keyType === 0 /* NOT_CONSTANT */) {
12786 return keyType;
12787 }
12788 if (keyType < returnType) {
12789 returnType = keyType;
12790 }
12791 let valueType;
12792 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12793 valueType = getConstantType(value, context);
12794 }
12795 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12796 // some helper calls can be hoisted,
12797 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12798 // in this case we need to respect the ConstanType of the helper's argments
12799 valueType = getConstantTypeOfHelperCall(value, context);
12800 }
12801 else {
12802 valueType = 0 /* NOT_CONSTANT */;
12803 }
12804 if (valueType === 0 /* NOT_CONSTANT */) {
12805 return valueType;
12806 }
12807 if (valueType < returnType) {
12808 returnType = valueType;
12809 }
12810 }
12811 }
12812 return returnType;
12813}
12814function getNodeProps(node) {
12815 const codegenNode = node.codegenNode;
12816 if (codegenNode.type === 13 /* VNODE_CALL */) {
12817 return codegenNode.props;
12818 }
12819}
12820function getPatchFlag(node) {
12821 const flag = node.patchFlag;
12822 return flag ? parseInt(flag, 10) : undefined;
12823}
12824
12825function 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 }) {
12826 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12827 const context = {
12828 // options
12829 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12830 prefixIdentifiers,
12831 hoistStatic,
12832 cacheHandlers,
12833 nodeTransforms,
12834 directiveTransforms,
12835 transformHoist,
12836 isBuiltInComponent,
12837 isCustomElement,
12838 expressionPlugins,
12839 scopeId,
12840 slotted,
12841 ssr,
12842 inSSR,
12843 ssrCssVars,
12844 bindingMetadata,
12845 inline,
12846 isTS,
12847 onError,
12848 onWarn,
12849 compatConfig,
12850 // state
12851 root,
12852 helpers: new Map(),
12853 components: new Set(),
12854 directives: new Set(),
12855 hoists: [],
12856 imports: [],
12857 constantCache: new Map(),
12858 temps: 0,
12859 cached: 0,
12860 identifiers: Object.create(null),
12861 scopes: {
12862 vFor: 0,
12863 vSlot: 0,
12864 vPre: 0,
12865 vOnce: 0
12866 },
12867 parent: null,
12868 currentNode: root,
12869 childIndex: 0,
12870 inVOnce: false,
12871 // methods
12872 helper(name) {
12873 const count = context.helpers.get(name) || 0;
12874 context.helpers.set(name, count + 1);
12875 return name;
12876 },
12877 removeHelper(name) {
12878 const count = context.helpers.get(name);
12879 if (count) {
12880 const currentCount = count - 1;
12881 if (!currentCount) {
12882 context.helpers.delete(name);
12883 }
12884 else {
12885 context.helpers.set(name, currentCount);
12886 }
12887 }
12888 },
12889 helperString(name) {
12890 return `_${helperNameMap[context.helper(name)]}`;
12891 },
12892 replaceNode(node) {
12893 /* istanbul ignore if */
12894 {
12895 if (!context.currentNode) {
12896 throw new Error(`Node being replaced is already removed.`);
12897 }
12898 if (!context.parent) {
12899 throw new Error(`Cannot replace root node.`);
12900 }
12901 }
12902 context.parent.children[context.childIndex] = context.currentNode = node;
12903 },
12904 removeNode(node) {
12905 if (!context.parent) {
12906 throw new Error(`Cannot remove root node.`);
12907 }
12908 const list = context.parent.children;
12909 const removalIndex = node
12910 ? list.indexOf(node)
12911 : context.currentNode
12912 ? context.childIndex
12913 : -1;
12914 /* istanbul ignore if */
12915 if (removalIndex < 0) {
12916 throw new Error(`node being removed is not a child of current parent`);
12917 }
12918 if (!node || node === context.currentNode) {
12919 // current node removed
12920 context.currentNode = null;
12921 context.onNodeRemoved();
12922 }
12923 else {
12924 // sibling node removed
12925 if (context.childIndex > removalIndex) {
12926 context.childIndex--;
12927 context.onNodeRemoved();
12928 }
12929 }
12930 context.parent.children.splice(removalIndex, 1);
12931 },
12932 onNodeRemoved: () => { },
12933 addIdentifiers(exp) {
12934 },
12935 removeIdentifiers(exp) {
12936 },
12937 hoist(exp) {
12938 if (isString(exp))
12939 exp = createSimpleExpression(exp);
12940 context.hoists.push(exp);
12941 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12942 identifier.hoisted = exp;
12943 return identifier;
12944 },
12945 cache(exp, isVNode = false) {
12946 return createCacheExpression(context.cached++, exp, isVNode);
12947 }
12948 };
12949 return context;
12950}
12951function transform(root, options) {
12952 const context = createTransformContext(root, options);
12953 traverseNode(root, context);
12954 if (options.hoistStatic) {
12955 hoistStatic(root, context);
12956 }
12957 if (!options.ssr) {
12958 createRootCodegen(root, context);
12959 }
12960 // finalize meta information
12961 root.helpers = [...context.helpers.keys()];
12962 root.components = [...context.components];
12963 root.directives = [...context.directives];
12964 root.imports = context.imports;
12965 root.hoists = context.hoists;
12966 root.temps = context.temps;
12967 root.cached = context.cached;
12968}
12969function createRootCodegen(root, context) {
12970 const { helper } = context;
12971 const { children } = root;
12972 if (children.length === 1) {
12973 const child = children[0];
12974 // if the single child is an element, turn it into a block.
12975 if (isSingleElementRoot(root, child) && child.codegenNode) {
12976 // single element root is never hoisted so codegenNode will never be
12977 // SimpleExpressionNode
12978 const codegenNode = child.codegenNode;
12979 if (codegenNode.type === 13 /* VNODE_CALL */) {
12980 makeBlock(codegenNode, context);
12981 }
12982 root.codegenNode = codegenNode;
12983 }
12984 else {
12985 // - single <slot/>, IfNode, ForNode: already blocks.
12986 // - single text node: always patched.
12987 // root codegen falls through via genNode()
12988 root.codegenNode = child;
12989 }
12990 }
12991 else if (children.length > 1) {
12992 // root has multiple nodes - return a fragment block.
12993 let patchFlag = 64 /* STABLE_FRAGMENT */;
12994 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12995 // check if the fragment actually contains a single valid child with
12996 // the rest being comments
12997 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12998 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12999 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13000 }
13001 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
13002 }
13003 else ;
13004}
13005function traverseChildren(parent, context) {
13006 let i = 0;
13007 const nodeRemoved = () => {
13008 i--;
13009 };
13010 for (; i < parent.children.length; i++) {
13011 const child = parent.children[i];
13012 if (isString(child))
13013 continue;
13014 context.parent = parent;
13015 context.childIndex = i;
13016 context.onNodeRemoved = nodeRemoved;
13017 traverseNode(child, context);
13018 }
13019}
13020function traverseNode(node, context) {
13021 context.currentNode = node;
13022 // apply transform plugins
13023 const { nodeTransforms } = context;
13024 const exitFns = [];
13025 for (let i = 0; i < nodeTransforms.length; i++) {
13026 const onExit = nodeTransforms[i](node, context);
13027 if (onExit) {
13028 if (isArray(onExit)) {
13029 exitFns.push(...onExit);
13030 }
13031 else {
13032 exitFns.push(onExit);
13033 }
13034 }
13035 if (!context.currentNode) {
13036 // node was removed
13037 return;
13038 }
13039 else {
13040 // node may have been replaced
13041 node = context.currentNode;
13042 }
13043 }
13044 switch (node.type) {
13045 case 3 /* COMMENT */:
13046 if (!context.ssr) {
13047 // inject import for the Comment symbol, which is needed for creating
13048 // comment nodes with `createVNode`
13049 context.helper(CREATE_COMMENT);
13050 }
13051 break;
13052 case 5 /* INTERPOLATION */:
13053 // no need to traverse, but we need to inject toString helper
13054 if (!context.ssr) {
13055 context.helper(TO_DISPLAY_STRING);
13056 }
13057 break;
13058 // for container types, further traverse downwards
13059 case 9 /* IF */:
13060 for (let i = 0; i < node.branches.length; i++) {
13061 traverseNode(node.branches[i], context);
13062 }
13063 break;
13064 case 10 /* IF_BRANCH */:
13065 case 11 /* FOR */:
13066 case 1 /* ELEMENT */:
13067 case 0 /* ROOT */:
13068 traverseChildren(node, context);
13069 break;
13070 }
13071 // exit transforms
13072 context.currentNode = node;
13073 let i = exitFns.length;
13074 while (i--) {
13075 exitFns[i]();
13076 }
13077}
13078function createStructuralDirectiveTransform(name, fn) {
13079 const matches = isString(name)
13080 ? (n) => n === name
13081 : (n) => name.test(n);
13082 return (node, context) => {
13083 if (node.type === 1 /* ELEMENT */) {
13084 const { props } = node;
13085 // structural directive transforms are not concerned with slots
13086 // as they are handled separately in vSlot.ts
13087 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
13088 return;
13089 }
13090 const exitFns = [];
13091 for (let i = 0; i < props.length; i++) {
13092 const prop = props[i];
13093 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
13094 // structural directives are removed to avoid infinite recursion
13095 // also we remove them *before* applying so that it can further
13096 // traverse itself in case it moves the node around
13097 props.splice(i, 1);
13098 i--;
13099 const onExit = fn(node, prop, context);
13100 if (onExit)
13101 exitFns.push(onExit);
13102 }
13103 }
13104 return exitFns;
13105 }
13106 };
13107}
13108
13109const PURE_ANNOTATION = `/*#__PURE__*/`;
13110function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false, isTS = false, inSSR = false }) {
13111 const context = {
13112 mode,
13113 prefixIdentifiers,
13114 sourceMap,
13115 filename,
13116 scopeId,
13117 optimizeImports,
13118 runtimeGlobalName,
13119 runtimeModuleName,
13120 ssr,
13121 isTS,
13122 inSSR,
13123 source: ast.loc.source,
13124 code: ``,
13125 column: 1,
13126 line: 1,
13127 offset: 0,
13128 indentLevel: 0,
13129 pure: false,
13130 map: undefined,
13131 helper(key) {
13132 return `_${helperNameMap[key]}`;
13133 },
13134 push(code, node) {
13135 context.code += code;
13136 },
13137 indent() {
13138 newline(++context.indentLevel);
13139 },
13140 deindent(withoutNewLine = false) {
13141 if (withoutNewLine) {
13142 --context.indentLevel;
13143 }
13144 else {
13145 newline(--context.indentLevel);
13146 }
13147 },
13148 newline() {
13149 newline(context.indentLevel);
13150 }
13151 };
13152 function newline(n) {
13153 context.push('\n' + ` `.repeat(n));
13154 }
13155 return context;
13156}
13157function generate(ast, options = {}) {
13158 const context = createCodegenContext(ast, options);
13159 if (options.onContextCreated)
13160 options.onContextCreated(context);
13161 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
13162 const hasHelpers = ast.helpers.length > 0;
13163 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13164 // preambles
13165 // in setup() inline mode, the preamble is generated in a sub context
13166 // and returned separately.
13167 const preambleContext = context;
13168 {
13169 genFunctionPreamble(ast, preambleContext);
13170 }
13171 // enter render function
13172 const functionName = ssr ? `ssrRender` : `render`;
13173 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13174 const signature = args.join(', ');
13175 {
13176 push(`function ${functionName}(${signature}) {`);
13177 }
13178 indent();
13179 if (useWithBlock) {
13180 push(`with (_ctx) {`);
13181 indent();
13182 // function mode const declarations should be inside with block
13183 // also they should be renamed to avoid collision with user properties
13184 if (hasHelpers) {
13185 push(`const { ${ast.helpers
13186 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
13187 .join(', ')} } = _Vue`);
13188 push(`\n`);
13189 newline();
13190 }
13191 }
13192 // generate asset resolution statements
13193 if (ast.components.length) {
13194 genAssets(ast.components, 'component', context);
13195 if (ast.directives.length || ast.temps > 0) {
13196 newline();
13197 }
13198 }
13199 if (ast.directives.length) {
13200 genAssets(ast.directives, 'directive', context);
13201 if (ast.temps > 0) {
13202 newline();
13203 }
13204 }
13205 if (ast.temps > 0) {
13206 push(`let `);
13207 for (let i = 0; i < ast.temps; i++) {
13208 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13209 }
13210 }
13211 if (ast.components.length || ast.directives.length || ast.temps) {
13212 push(`\n`);
13213 newline();
13214 }
13215 // generate the VNode tree expression
13216 if (!ssr) {
13217 push(`return `);
13218 }
13219 if (ast.codegenNode) {
13220 genNode(ast.codegenNode, context);
13221 }
13222 else {
13223 push(`null`);
13224 }
13225 if (useWithBlock) {
13226 deindent();
13227 push(`}`);
13228 }
13229 deindent();
13230 push(`}`);
13231 return {
13232 ast,
13233 code: context.code,
13234 preamble: ``,
13235 // SourceMapGenerator does have toJSON() method but it's not in the types
13236 map: context.map ? context.map.toJSON() : undefined
13237 };
13238}
13239function genFunctionPreamble(ast, context) {
13240 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
13241 const VueBinding = runtimeGlobalName;
13242 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13243 // Generate const declaration for helpers
13244 // In prefix mode, we place the const declaration at top so it's done
13245 // only once; But if we not prefixing, we place the declaration inside the
13246 // with block so it doesn't incur the `in` check cost for every helper access.
13247 if (ast.helpers.length > 0) {
13248 {
13249 // "with" mode.
13250 // save Vue in a separate variable to avoid collision
13251 push(`const _Vue = ${VueBinding}\n`);
13252 // in "with" mode, helpers are declared inside the with block to avoid
13253 // has check cost, but hoists are lifted out of the function - we need
13254 // to provide the helper here.
13255 if (ast.hoists.length) {
13256 const staticHelpers = [
13257 CREATE_VNODE,
13258 CREATE_ELEMENT_VNODE,
13259 CREATE_COMMENT,
13260 CREATE_TEXT,
13261 CREATE_STATIC
13262 ]
13263 .filter(helper => ast.helpers.includes(helper))
13264 .map(aliasHelper)
13265 .join(', ');
13266 push(`const { ${staticHelpers} } = _Vue\n`);
13267 }
13268 }
13269 }
13270 genHoists(ast.hoists, context);
13271 newline();
13272 push(`return `);
13273}
13274function genAssets(assets, type, { helper, push, newline, isTS }) {
13275 const resolver = helper(type === 'component'
13276 ? RESOLVE_COMPONENT
13277 : RESOLVE_DIRECTIVE);
13278 for (let i = 0; i < assets.length; i++) {
13279 let id = assets[i];
13280 // potential component implicit self-reference inferred from SFC filename
13281 const maybeSelfReference = id.endsWith('__self');
13282 if (maybeSelfReference) {
13283 id = id.slice(0, -6);
13284 }
13285 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13286 if (i < assets.length - 1) {
13287 newline();
13288 }
13289 }
13290}
13291function genHoists(hoists, context) {
13292 if (!hoists.length) {
13293 return;
13294 }
13295 context.pure = true;
13296 const { push, newline, helper, scopeId, mode } = context;
13297 newline();
13298 hoists.forEach((exp, i) => {
13299 if (exp) {
13300 push(`const _hoisted_${i + 1} = `);
13301 genNode(exp, context);
13302 newline();
13303 }
13304 });
13305 context.pure = false;
13306}
13307function isText$1(n) {
13308 return (isString(n) ||
13309 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13310 n.type === 2 /* TEXT */ ||
13311 n.type === 5 /* INTERPOLATION */ ||
13312 n.type === 8 /* COMPOUND_EXPRESSION */);
13313}
13314function genNodeListAsArray(nodes, context) {
13315 const multilines = nodes.length > 3 ||
13316 (nodes.some(n => isArray(n) || !isText$1(n)));
13317 context.push(`[`);
13318 multilines && context.indent();
13319 genNodeList(nodes, context, multilines);
13320 multilines && context.deindent();
13321 context.push(`]`);
13322}
13323function genNodeList(nodes, context, multilines = false, comma = true) {
13324 const { push, newline } = context;
13325 for (let i = 0; i < nodes.length; i++) {
13326 const node = nodes[i];
13327 if (isString(node)) {
13328 push(node);
13329 }
13330 else if (isArray(node)) {
13331 genNodeListAsArray(node, context);
13332 }
13333 else {
13334 genNode(node, context);
13335 }
13336 if (i < nodes.length - 1) {
13337 if (multilines) {
13338 comma && push(',');
13339 newline();
13340 }
13341 else {
13342 comma && push(', ');
13343 }
13344 }
13345 }
13346}
13347function genNode(node, context) {
13348 if (isString(node)) {
13349 context.push(node);
13350 return;
13351 }
13352 if (isSymbol(node)) {
13353 context.push(context.helper(node));
13354 return;
13355 }
13356 switch (node.type) {
13357 case 1 /* ELEMENT */:
13358 case 9 /* IF */:
13359 case 11 /* FOR */:
13360 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13361 `Apply appropriate transforms first.`);
13362 genNode(node.codegenNode, context);
13363 break;
13364 case 2 /* TEXT */:
13365 genText(node, context);
13366 break;
13367 case 4 /* SIMPLE_EXPRESSION */:
13368 genExpression(node, context);
13369 break;
13370 case 5 /* INTERPOLATION */:
13371 genInterpolation(node, context);
13372 break;
13373 case 12 /* TEXT_CALL */:
13374 genNode(node.codegenNode, context);
13375 break;
13376 case 8 /* COMPOUND_EXPRESSION */:
13377 genCompoundExpression(node, context);
13378 break;
13379 case 3 /* COMMENT */:
13380 genComment(node, context);
13381 break;
13382 case 13 /* VNODE_CALL */:
13383 genVNodeCall(node, context);
13384 break;
13385 case 14 /* JS_CALL_EXPRESSION */:
13386 genCallExpression(node, context);
13387 break;
13388 case 15 /* JS_OBJECT_EXPRESSION */:
13389 genObjectExpression(node, context);
13390 break;
13391 case 17 /* JS_ARRAY_EXPRESSION */:
13392 genArrayExpression(node, context);
13393 break;
13394 case 18 /* JS_FUNCTION_EXPRESSION */:
13395 genFunctionExpression(node, context);
13396 break;
13397 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13398 genConditionalExpression(node, context);
13399 break;
13400 case 20 /* JS_CACHE_EXPRESSION */:
13401 genCacheExpression(node, context);
13402 break;
13403 case 21 /* JS_BLOCK_STATEMENT */:
13404 genNodeList(node.body, context, true, false);
13405 break;
13406 // SSR only types
13407 case 22 /* JS_TEMPLATE_LITERAL */:
13408 break;
13409 case 23 /* JS_IF_STATEMENT */:
13410 break;
13411 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13412 break;
13413 case 25 /* JS_SEQUENCE_EXPRESSION */:
13414 break;
13415 case 26 /* JS_RETURN_STATEMENT */:
13416 break;
13417 /* istanbul ignore next */
13418 case 10 /* IF_BRANCH */:
13419 // noop
13420 break;
13421 default:
13422 {
13423 assert(false, `unhandled codegen node type: ${node.type}`);
13424 // make sure we exhaust all possible types
13425 const exhaustiveCheck = node;
13426 return exhaustiveCheck;
13427 }
13428 }
13429}
13430function genText(node, context) {
13431 context.push(JSON.stringify(node.content), node);
13432}
13433function genExpression(node, context) {
13434 const { content, isStatic } = node;
13435 context.push(isStatic ? JSON.stringify(content) : content, node);
13436}
13437function genInterpolation(node, context) {
13438 const { push, helper, pure } = context;
13439 if (pure)
13440 push(PURE_ANNOTATION);
13441 push(`${helper(TO_DISPLAY_STRING)}(`);
13442 genNode(node.content, context);
13443 push(`)`);
13444}
13445function genCompoundExpression(node, context) {
13446 for (let i = 0; i < node.children.length; i++) {
13447 const child = node.children[i];
13448 if (isString(child)) {
13449 context.push(child);
13450 }
13451 else {
13452 genNode(child, context);
13453 }
13454 }
13455}
13456function genExpressionAsPropertyKey(node, context) {
13457 const { push } = context;
13458 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13459 push(`[`);
13460 genCompoundExpression(node, context);
13461 push(`]`);
13462 }
13463 else if (node.isStatic) {
13464 // only quote keys if necessary
13465 const text = isSimpleIdentifier(node.content)
13466 ? node.content
13467 : JSON.stringify(node.content);
13468 push(text, node);
13469 }
13470 else {
13471 push(`[${node.content}]`, node);
13472 }
13473}
13474function genComment(node, context) {
13475 const { push, helper, pure } = context;
13476 if (pure) {
13477 push(PURE_ANNOTATION);
13478 }
13479 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13480}
13481function genVNodeCall(node, context) {
13482 const { push, helper, pure } = context;
13483 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13484 if (directives) {
13485 push(helper(WITH_DIRECTIVES) + `(`);
13486 }
13487 if (isBlock) {
13488 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13489 }
13490 if (pure) {
13491 push(PURE_ANNOTATION);
13492 }
13493 const callHelper = isBlock
13494 ? getVNodeBlockHelper(context.inSSR, isComponent)
13495 : getVNodeHelper(context.inSSR, isComponent);
13496 push(helper(callHelper) + `(`, node);
13497 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13498 push(`)`);
13499 if (isBlock) {
13500 push(`)`);
13501 }
13502 if (directives) {
13503 push(`, `);
13504 genNode(directives, context);
13505 push(`)`);
13506 }
13507}
13508function genNullableArgs(args) {
13509 let i = args.length;
13510 while (i--) {
13511 if (args[i] != null)
13512 break;
13513 }
13514 return args.slice(0, i + 1).map(arg => arg || `null`);
13515}
13516// JavaScript
13517function genCallExpression(node, context) {
13518 const { push, helper, pure } = context;
13519 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13520 if (pure) {
13521 push(PURE_ANNOTATION);
13522 }
13523 push(callee + `(`, node);
13524 genNodeList(node.arguments, context);
13525 push(`)`);
13526}
13527function genObjectExpression(node, context) {
13528 const { push, indent, deindent, newline } = context;
13529 const { properties } = node;
13530 if (!properties.length) {
13531 push(`{}`, node);
13532 return;
13533 }
13534 const multilines = properties.length > 1 ||
13535 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13536 push(multilines ? `{` : `{ `);
13537 multilines && indent();
13538 for (let i = 0; i < properties.length; i++) {
13539 const { key, value } = properties[i];
13540 // key
13541 genExpressionAsPropertyKey(key, context);
13542 push(`: `);
13543 // value
13544 genNode(value, context);
13545 if (i < properties.length - 1) {
13546 // will only reach this if it's multilines
13547 push(`,`);
13548 newline();
13549 }
13550 }
13551 multilines && deindent();
13552 push(multilines ? `}` : ` }`);
13553}
13554function genArrayExpression(node, context) {
13555 genNodeListAsArray(node.elements, context);
13556}
13557function genFunctionExpression(node, context) {
13558 const { push, indent, deindent } = context;
13559 const { params, returns, body, newline, isSlot } = node;
13560 if (isSlot) {
13561 // wrap slot functions with owner context
13562 push(`_${helperNameMap[WITH_CTX]}(`);
13563 }
13564 push(`(`, node);
13565 if (isArray(params)) {
13566 genNodeList(params, context);
13567 }
13568 else if (params) {
13569 genNode(params, context);
13570 }
13571 push(`) => `);
13572 if (newline || body) {
13573 push(`{`);
13574 indent();
13575 }
13576 if (returns) {
13577 if (newline) {
13578 push(`return `);
13579 }
13580 if (isArray(returns)) {
13581 genNodeListAsArray(returns, context);
13582 }
13583 else {
13584 genNode(returns, context);
13585 }
13586 }
13587 else if (body) {
13588 genNode(body, context);
13589 }
13590 if (newline || body) {
13591 deindent();
13592 push(`}`);
13593 }
13594 if (isSlot) {
13595 push(`)`);
13596 }
13597}
13598function genConditionalExpression(node, context) {
13599 const { test, consequent, alternate, newline: needNewline } = node;
13600 const { push, indent, deindent, newline } = context;
13601 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13602 const needsParens = !isSimpleIdentifier(test.content);
13603 needsParens && push(`(`);
13604 genExpression(test, context);
13605 needsParens && push(`)`);
13606 }
13607 else {
13608 push(`(`);
13609 genNode(test, context);
13610 push(`)`);
13611 }
13612 needNewline && indent();
13613 context.indentLevel++;
13614 needNewline || push(` `);
13615 push(`? `);
13616 genNode(consequent, context);
13617 context.indentLevel--;
13618 needNewline && newline();
13619 needNewline || push(` `);
13620 push(`: `);
13621 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13622 if (!isNested) {
13623 context.indentLevel++;
13624 }
13625 genNode(alternate, context);
13626 if (!isNested) {
13627 context.indentLevel--;
13628 }
13629 needNewline && deindent(true /* without newline */);
13630}
13631function genCacheExpression(node, context) {
13632 const { push, helper, indent, deindent, newline } = context;
13633 push(`_cache[${node.index}] || (`);
13634 if (node.isVNode) {
13635 indent();
13636 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13637 newline();
13638 }
13639 push(`_cache[${node.index}] = `);
13640 genNode(node.value, context);
13641 if (node.isVNode) {
13642 push(`,`);
13643 newline();
13644 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13645 newline();
13646 push(`_cache[${node.index}]`);
13647 deindent();
13648 }
13649 push(`)`);
13650}
13651
13652// these keywords should not appear inside expressions, but operators like
13653// typeof, instanceof and in are allowed
13654const prohibitedKeywordRE = new RegExp('\\b' +
13655 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13656 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13657 'extends,finally,continue,debugger,function,arguments,typeof,void')
13658 .split(',')
13659 .join('\\b|\\b') +
13660 '\\b');
13661// strip strings in expressions
13662const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13663/**
13664 * Validate a non-prefixed expression.
13665 * This is only called when using the in-browser runtime compiler since it
13666 * doesn't prefix expressions.
13667 */
13668function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13669 const exp = node.content;
13670 // empty expressions are validated per-directive since some directives
13671 // do allow empty expressions.
13672 if (!exp.trim()) {
13673 return;
13674 }
13675 try {
13676 new Function(asRawStatements
13677 ? ` ${exp} `
13678 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13679 }
13680 catch (e) {
13681 let message = e.message;
13682 const keywordMatch = exp
13683 .replace(stripStringRE, '')
13684 .match(prohibitedKeywordRE);
13685 if (keywordMatch) {
13686 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13687 }
13688 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13689 }
13690}
13691
13692const transformExpression = (node, context) => {
13693 if (node.type === 5 /* INTERPOLATION */) {
13694 node.content = processExpression(node.content, context);
13695 }
13696 else if (node.type === 1 /* ELEMENT */) {
13697 // handle directives on element
13698 for (let i = 0; i < node.props.length; i++) {
13699 const dir = node.props[i];
13700 // do not process for v-on & v-for since they are special handled
13701 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13702 const exp = dir.exp;
13703 const arg = dir.arg;
13704 // do not process exp if this is v-on:arg - we need special handling
13705 // for wrapping inline statements.
13706 if (exp &&
13707 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13708 !(dir.name === 'on' && arg)) {
13709 dir.exp = processExpression(exp, context,
13710 // slot args must be processed as function params
13711 dir.name === 'slot');
13712 }
13713 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13714 dir.arg = processExpression(arg, context);
13715 }
13716 }
13717 }
13718 }
13719};
13720// Important: since this function uses Node.js only dependencies, it should
13721// always be used with a leading !true check so that it can be
13722// tree-shaken from the browser build.
13723function processExpression(node, context,
13724// some expressions like v-slot props & v-for aliases should be parsed as
13725// function params
13726asParams = false,
13727// v-on handler values may contain multiple statements
13728asRawStatements = false, localVars = Object.create(context.identifiers)) {
13729 {
13730 {
13731 // simple in-browser validation (same logic in 2.x)
13732 validateBrowserExpression(node, context, asParams, asRawStatements);
13733 }
13734 return node;
13735 }
13736}
13737
13738const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13739 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13740 // #1587: We need to dynamically increment the key based on the current
13741 // node's sibling nodes, since chained v-if/else branches are
13742 // rendered at the same depth
13743 const siblings = context.parent.children;
13744 let i = siblings.indexOf(ifNode);
13745 let key = 0;
13746 while (i-- >= 0) {
13747 const sibling = siblings[i];
13748 if (sibling && sibling.type === 9 /* IF */) {
13749 key += sibling.branches.length;
13750 }
13751 }
13752 // Exit callback. Complete the codegenNode when all children have been
13753 // transformed.
13754 return () => {
13755 if (isRoot) {
13756 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13757 }
13758 else {
13759 // attach this branch's codegen node to the v-if root.
13760 const parentCondition = getParentCondition(ifNode.codegenNode);
13761 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13762 }
13763 };
13764 });
13765});
13766// target-agnostic transform used for both Client and SSR
13767function processIf(node, dir, context, processCodegen) {
13768 if (dir.name !== 'else' &&
13769 (!dir.exp || !dir.exp.content.trim())) {
13770 const loc = dir.exp ? dir.exp.loc : node.loc;
13771 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13772 dir.exp = createSimpleExpression(`true`, false, loc);
13773 }
13774 if (dir.exp) {
13775 validateBrowserExpression(dir.exp, context);
13776 }
13777 if (dir.name === 'if') {
13778 const branch = createIfBranch(node, dir);
13779 const ifNode = {
13780 type: 9 /* IF */,
13781 loc: node.loc,
13782 branches: [branch]
13783 };
13784 context.replaceNode(ifNode);
13785 if (processCodegen) {
13786 return processCodegen(ifNode, branch, true);
13787 }
13788 }
13789 else {
13790 // locate the adjacent v-if
13791 const siblings = context.parent.children;
13792 const comments = [];
13793 let i = siblings.indexOf(node);
13794 while (i-- >= -1) {
13795 const sibling = siblings[i];
13796 if (sibling && sibling.type === 3 /* COMMENT */) {
13797 context.removeNode(sibling);
13798 comments.unshift(sibling);
13799 continue;
13800 }
13801 if (sibling &&
13802 sibling.type === 2 /* TEXT */ &&
13803 !sibling.content.trim().length) {
13804 context.removeNode(sibling);
13805 continue;
13806 }
13807 if (sibling && sibling.type === 9 /* IF */) {
13808 // move the node to the if node's branches
13809 context.removeNode();
13810 const branch = createIfBranch(node, dir);
13811 if (comments.length &&
13812 // #3619 ignore comments if the v-if is direct child of <transition>
13813 !(context.parent &&
13814 context.parent.type === 1 /* ELEMENT */ &&
13815 isBuiltInType(context.parent.tag, 'transition'))) {
13816 branch.children = [...comments, ...branch.children];
13817 }
13818 // check if user is forcing same key on different branches
13819 {
13820 const key = branch.userKey;
13821 if (key) {
13822 sibling.branches.forEach(({ userKey }) => {
13823 if (isSameKey(userKey, key)) {
13824 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13825 }
13826 });
13827 }
13828 }
13829 sibling.branches.push(branch);
13830 const onExit = processCodegen && processCodegen(sibling, branch, false);
13831 // since the branch was removed, it will not be traversed.
13832 // make sure to traverse here.
13833 traverseNode(branch, context);
13834 // call on exit
13835 if (onExit)
13836 onExit();
13837 // make sure to reset currentNode after traversal to indicate this
13838 // node has been removed.
13839 context.currentNode = null;
13840 }
13841 else {
13842 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13843 }
13844 break;
13845 }
13846 }
13847}
13848function createIfBranch(node, dir) {
13849 return {
13850 type: 10 /* IF_BRANCH */,
13851 loc: node.loc,
13852 condition: dir.name === 'else' ? undefined : dir.exp,
13853 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13854 ? node.children
13855 : [node],
13856 userKey: findProp(node, `key`)
13857 };
13858}
13859function createCodegenNodeForBranch(branch, keyIndex, context) {
13860 if (branch.condition) {
13861 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13862 // make sure to pass in asBlock: true so that the comment node call
13863 // closes the current block.
13864 createCallExpression(context.helper(CREATE_COMMENT), [
13865 '"v-if"' ,
13866 'true'
13867 ]));
13868 }
13869 else {
13870 return createChildrenCodegenNode(branch, keyIndex, context);
13871 }
13872}
13873function createChildrenCodegenNode(branch, keyIndex, context) {
13874 const { helper } = context;
13875 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13876 const { children } = branch;
13877 const firstChild = children[0];
13878 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13879 if (needFragmentWrapper) {
13880 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13881 // optimize away nested fragments when child is a ForNode
13882 const vnodeCall = firstChild.codegenNode;
13883 injectProp(vnodeCall, keyProperty, context);
13884 return vnodeCall;
13885 }
13886 else {
13887 let patchFlag = 64 /* STABLE_FRAGMENT */;
13888 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13889 // check if the fragment actually contains a single valid child with
13890 // the rest being comments
13891 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13892 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13893 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13894 }
13895 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13896 }
13897 }
13898 else {
13899 const ret = firstChild.codegenNode;
13900 const vnodeCall = getMemoedVNodeCall(ret);
13901 // Change createVNode to createBlock.
13902 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13903 makeBlock(vnodeCall, context);
13904 }
13905 // inject branch key
13906 injectProp(vnodeCall, keyProperty, context);
13907 return ret;
13908 }
13909}
13910function isSameKey(a, b) {
13911 if (!a || a.type !== b.type) {
13912 return false;
13913 }
13914 if (a.type === 6 /* ATTRIBUTE */) {
13915 if (a.value.content !== b.value.content) {
13916 return false;
13917 }
13918 }
13919 else {
13920 // directive
13921 const exp = a.exp;
13922 const branchExp = b.exp;
13923 if (exp.type !== branchExp.type) {
13924 return false;
13925 }
13926 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13927 exp.isStatic !== branchExp.isStatic ||
13928 exp.content !== branchExp.content) {
13929 return false;
13930 }
13931 }
13932 return true;
13933}
13934function getParentCondition(node) {
13935 while (true) {
13936 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13937 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13938 node = node.alternate;
13939 }
13940 else {
13941 return node;
13942 }
13943 }
13944 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13945 node = node.value;
13946 }
13947 }
13948}
13949
13950const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13951 const { helper, removeHelper } = context;
13952 return processFor(node, dir, context, forNode => {
13953 // create the loop render function expression now, and add the
13954 // iterator on exit after all children have been traversed
13955 const renderExp = createCallExpression(helper(RENDER_LIST), [
13956 forNode.source
13957 ]);
13958 const memo = findDir(node, 'memo');
13959 const keyProp = findProp(node, `key`);
13960 const keyExp = keyProp &&
13961 (keyProp.type === 6 /* ATTRIBUTE */
13962 ? createSimpleExpression(keyProp.value.content, true)
13963 : keyProp.exp);
13964 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13965 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13966 forNode.source.constType > 0 /* NOT_CONSTANT */;
13967 const fragmentFlag = isStableFragment
13968 ? 64 /* STABLE_FRAGMENT */
13969 : keyProp
13970 ? 128 /* KEYED_FRAGMENT */
13971 : 256 /* UNKEYED_FRAGMENT */;
13972 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13973 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13974 return () => {
13975 // finish the codegen now that all children have been traversed
13976 let childBlock;
13977 const isTemplate = isTemplateNode(node);
13978 const { children } = forNode;
13979 // check <template v-for> key placement
13980 if (isTemplate) {
13981 node.children.some(c => {
13982 if (c.type === 1 /* ELEMENT */) {
13983 const key = findProp(c, 'key');
13984 if (key) {
13985 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13986 return true;
13987 }
13988 }
13989 });
13990 }
13991 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13992 const slotOutlet = isSlotOutlet(node)
13993 ? node
13994 : isTemplate &&
13995 node.children.length === 1 &&
13996 isSlotOutlet(node.children[0])
13997 ? node.children[0] // api-extractor somehow fails to infer this
13998 : null;
13999 if (slotOutlet) {
14000 // <slot v-for="..."> or <template v-for="..."><slot/></template>
14001 childBlock = slotOutlet.codegenNode;
14002 if (isTemplate && keyProperty) {
14003 // <template v-for="..." :key="..."><slot/></template>
14004 // we need to inject the key to the renderSlot() call.
14005 // the props for renderSlot is passed as the 3rd argument.
14006 injectProp(childBlock, keyProperty, context);
14007 }
14008 }
14009 else if (needFragmentWrapper) {
14010 // <template v-for="..."> with text or multi-elements
14011 // should generate a fragment block for each loop
14012 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
14013 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
14014 ), undefined, undefined, true, undefined, false /* isComponent */);
14015 }
14016 else {
14017 // Normal element v-for. Directly use the child's codegenNode
14018 // but mark it as a block.
14019 childBlock = children[0]
14020 .codegenNode;
14021 if (isTemplate && keyProperty) {
14022 injectProp(childBlock, keyProperty, context);
14023 }
14024 if (childBlock.isBlock !== !isStableFragment) {
14025 if (childBlock.isBlock) {
14026 // switch from block to vnode
14027 removeHelper(OPEN_BLOCK);
14028 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
14029 }
14030 else {
14031 // switch from vnode to block
14032 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
14033 }
14034 }
14035 childBlock.isBlock = !isStableFragment;
14036 if (childBlock.isBlock) {
14037 helper(OPEN_BLOCK);
14038 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
14039 }
14040 else {
14041 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
14042 }
14043 }
14044 if (memo) {
14045 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
14046 createSimpleExpression(`_cached`)
14047 ]));
14048 loop.body = createBlockStatement([
14049 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
14050 createCompoundExpression([
14051 `if (_cached`,
14052 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
14053 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
14054 ]),
14055 createCompoundExpression([`const _item = `, childBlock]),
14056 createSimpleExpression(`_item.memo = _memo`),
14057 createSimpleExpression(`return _item`)
14058 ]);
14059 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
14060 }
14061 else {
14062 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
14063 }
14064 };
14065 });
14066});
14067// target-agnostic transform used for both Client and SSR
14068function processFor(node, dir, context, processCodegen) {
14069 if (!dir.exp) {
14070 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
14071 return;
14072 }
14073 const parseResult = parseForExpression(
14074 // can only be simple expression because vFor transform is applied
14075 // before expression transform.
14076 dir.exp, context);
14077 if (!parseResult) {
14078 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
14079 return;
14080 }
14081 const { addIdentifiers, removeIdentifiers, scopes } = context;
14082 const { source, value, key, index } = parseResult;
14083 const forNode = {
14084 type: 11 /* FOR */,
14085 loc: dir.loc,
14086 source,
14087 valueAlias: value,
14088 keyAlias: key,
14089 objectIndexAlias: index,
14090 parseResult,
14091 children: isTemplateNode(node) ? node.children : [node]
14092 };
14093 context.replaceNode(forNode);
14094 // bookkeeping
14095 scopes.vFor++;
14096 const onExit = processCodegen && processCodegen(forNode);
14097 return () => {
14098 scopes.vFor--;
14099 if (onExit)
14100 onExit();
14101 };
14102}
14103const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
14104// This regex doesn't cover the case if key or index aliases have destructuring,
14105// but those do not make sense in the first place, so this works in practice.
14106const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
14107const stripParensRE = /^\(|\)$/g;
14108function parseForExpression(input, context) {
14109 const loc = input.loc;
14110 const exp = input.content;
14111 const inMatch = exp.match(forAliasRE);
14112 if (!inMatch)
14113 return;
14114 const [, LHS, RHS] = inMatch;
14115 const result = {
14116 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
14117 value: undefined,
14118 key: undefined,
14119 index: undefined
14120 };
14121 {
14122 validateBrowserExpression(result.source, context);
14123 }
14124 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
14125 const trimmedOffset = LHS.indexOf(valueContent);
14126 const iteratorMatch = valueContent.match(forIteratorRE);
14127 if (iteratorMatch) {
14128 valueContent = valueContent.replace(forIteratorRE, '').trim();
14129 const keyContent = iteratorMatch[1].trim();
14130 let keyOffset;
14131 if (keyContent) {
14132 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
14133 result.key = createAliasExpression(loc, keyContent, keyOffset);
14134 {
14135 validateBrowserExpression(result.key, context, true);
14136 }
14137 }
14138 if (iteratorMatch[2]) {
14139 const indexContent = iteratorMatch[2].trim();
14140 if (indexContent) {
14141 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
14142 ? keyOffset + keyContent.length
14143 : trimmedOffset + valueContent.length));
14144 {
14145 validateBrowserExpression(result.index, context, true);
14146 }
14147 }
14148 }
14149 }
14150 if (valueContent) {
14151 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
14152 {
14153 validateBrowserExpression(result.value, context, true);
14154 }
14155 }
14156 return result;
14157}
14158function createAliasExpression(range, content, offset) {
14159 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14160}
14161function createForLoopParams({ value, key, index }, memoArgs = []) {
14162 return createParamsList([value, key, index, ...memoArgs]);
14163}
14164function createParamsList(args) {
14165 let i = args.length;
14166 while (i--) {
14167 if (args[i])
14168 break;
14169 }
14170 return args
14171 .slice(0, i + 1)
14172 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14173}
14174
14175const defaultFallback = createSimpleExpression(`undefined`, false);
14176// A NodeTransform that:
14177// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14178// by transformExpression. This is only applied in non-browser builds with
14179// { prefixIdentifiers: true }.
14180// 2. Track v-slot depths so that we know a slot is inside another slot.
14181// Note the exit callback is executed before buildSlots() on the same node,
14182// so only nested slots see positive numbers.
14183const trackSlotScopes = (node, context) => {
14184 if (node.type === 1 /* ELEMENT */ &&
14185 (node.tagType === 1 /* COMPONENT */ ||
14186 node.tagType === 3 /* TEMPLATE */)) {
14187 // We are only checking non-empty v-slot here
14188 // since we only care about slots that introduce scope variables.
14189 const vSlot = findDir(node, 'slot');
14190 if (vSlot) {
14191 vSlot.exp;
14192 context.scopes.vSlot++;
14193 return () => {
14194 context.scopes.vSlot--;
14195 };
14196 }
14197 }
14198};
14199const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14200// Instead of being a DirectiveTransform, v-slot processing is called during
14201// transformElement to build the slots object for a component.
14202function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14203 context.helper(WITH_CTX);
14204 const { children, loc } = node;
14205 const slotsProperties = [];
14206 const dynamicSlots = [];
14207 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14208 // since it likely uses a scope variable.
14209 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14210 // 1. Check for slot with slotProps on component itself.
14211 // <Comp v-slot="{ prop }"/>
14212 const onComponentSlot = findDir(node, 'slot', true);
14213 if (onComponentSlot) {
14214 const { arg, exp } = onComponentSlot;
14215 if (arg && !isStaticExp(arg)) {
14216 hasDynamicSlots = true;
14217 }
14218 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14219 }
14220 // 2. Iterate through children and check for template slots
14221 // <template v-slot:foo="{ prop }">
14222 let hasTemplateSlots = false;
14223 let hasNamedDefaultSlot = false;
14224 const implicitDefaultChildren = [];
14225 const seenSlotNames = new Set();
14226 for (let i = 0; i < children.length; i++) {
14227 const slotElement = children[i];
14228 let slotDir;
14229 if (!isTemplateNode(slotElement) ||
14230 !(slotDir = findDir(slotElement, 'slot', true))) {
14231 // not a <template v-slot>, skip.
14232 if (slotElement.type !== 3 /* COMMENT */) {
14233 implicitDefaultChildren.push(slotElement);
14234 }
14235 continue;
14236 }
14237 if (onComponentSlot) {
14238 // already has on-component slot - this is incorrect usage.
14239 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14240 break;
14241 }
14242 hasTemplateSlots = true;
14243 const { children: slotChildren, loc: slotLoc } = slotElement;
14244 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14245 // check if name is dynamic.
14246 let staticSlotName;
14247 if (isStaticExp(slotName)) {
14248 staticSlotName = slotName ? slotName.content : `default`;
14249 }
14250 else {
14251 hasDynamicSlots = true;
14252 }
14253 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14254 // check if this slot is conditional (v-if/v-for)
14255 let vIf;
14256 let vElse;
14257 let vFor;
14258 if ((vIf = findDir(slotElement, 'if'))) {
14259 hasDynamicSlots = true;
14260 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14261 }
14262 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14263 // find adjacent v-if
14264 let j = i;
14265 let prev;
14266 while (j--) {
14267 prev = children[j];
14268 if (prev.type !== 3 /* COMMENT */) {
14269 break;
14270 }
14271 }
14272 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14273 // remove node
14274 children.splice(i, 1);
14275 i--;
14276 // attach this slot to previous conditional
14277 let conditional = dynamicSlots[dynamicSlots.length - 1];
14278 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14279 conditional = conditional.alternate;
14280 }
14281 conditional.alternate = vElse.exp
14282 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14283 : buildDynamicSlot(slotName, slotFunction);
14284 }
14285 else {
14286 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14287 }
14288 }
14289 else if ((vFor = findDir(slotElement, 'for'))) {
14290 hasDynamicSlots = true;
14291 const parseResult = vFor.parseResult ||
14292 parseForExpression(vFor.exp, context);
14293 if (parseResult) {
14294 // Render the dynamic slots as an array and add it to the createSlot()
14295 // args. The runtime knows how to handle it appropriately.
14296 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14297 parseResult.source,
14298 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14299 ]));
14300 }
14301 else {
14302 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14303 }
14304 }
14305 else {
14306 // check duplicate static names
14307 if (staticSlotName) {
14308 if (seenSlotNames.has(staticSlotName)) {
14309 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14310 continue;
14311 }
14312 seenSlotNames.add(staticSlotName);
14313 if (staticSlotName === 'default') {
14314 hasNamedDefaultSlot = true;
14315 }
14316 }
14317 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14318 }
14319 }
14320 if (!onComponentSlot) {
14321 const buildDefaultSlotProperty = (props, children) => {
14322 const fn = buildSlotFn(props, children, loc);
14323 return createObjectProperty(`default`, fn);
14324 };
14325 if (!hasTemplateSlots) {
14326 // implicit default slot (on component)
14327 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14328 }
14329 else if (implicitDefaultChildren.length &&
14330 // #3766
14331 // with whitespace: 'preserve', whitespaces between slots will end up in
14332 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14333 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14334 // implicit default slot (mixed with named slots)
14335 if (hasNamedDefaultSlot) {
14336 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14337 }
14338 else {
14339 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14340 }
14341 }
14342 }
14343 const slotFlag = hasDynamicSlots
14344 ? 2 /* DYNAMIC */
14345 : hasForwardedSlots(node.children)
14346 ? 3 /* FORWARDED */
14347 : 1 /* STABLE */;
14348 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14349 // 2 = compiled but dynamic = can skip normalization, but must run diff
14350 // 1 = compiled and static = can skip normalization AND diff as optimized
14351 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14352 if (dynamicSlots.length) {
14353 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14354 slots,
14355 createArrayExpression(dynamicSlots)
14356 ]);
14357 }
14358 return {
14359 slots,
14360 hasDynamicSlots
14361 };
14362}
14363function buildDynamicSlot(name, fn) {
14364 return createObjectExpression([
14365 createObjectProperty(`name`, name),
14366 createObjectProperty(`fn`, fn)
14367 ]);
14368}
14369function hasForwardedSlots(children) {
14370 for (let i = 0; i < children.length; i++) {
14371 const child = children[i];
14372 switch (child.type) {
14373 case 1 /* ELEMENT */:
14374 if (child.tagType === 2 /* SLOT */ ||
14375 hasForwardedSlots(child.children)) {
14376 return true;
14377 }
14378 break;
14379 case 9 /* IF */:
14380 if (hasForwardedSlots(child.branches))
14381 return true;
14382 break;
14383 case 10 /* IF_BRANCH */:
14384 case 11 /* FOR */:
14385 if (hasForwardedSlots(child.children))
14386 return true;
14387 break;
14388 }
14389 }
14390 return false;
14391}
14392function isNonWhitespaceContent(node) {
14393 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14394 return true;
14395 return node.type === 2 /* TEXT */
14396 ? !!node.content.trim()
14397 : isNonWhitespaceContent(node.content);
14398}
14399
14400// some directive transforms (e.g. v-model) may return a symbol for runtime
14401// import, which should be used instead of a resolveDirective call.
14402const directiveImportMap = new WeakMap();
14403// generate a JavaScript AST for this element's codegen
14404const transformElement = (node, context) => {
14405 // perform the work on exit, after all child expressions have been
14406 // processed and merged.
14407 return function postTransformElement() {
14408 node = context.currentNode;
14409 if (!(node.type === 1 /* ELEMENT */ &&
14410 (node.tagType === 0 /* ELEMENT */ ||
14411 node.tagType === 1 /* COMPONENT */))) {
14412 return;
14413 }
14414 const { tag, props } = node;
14415 const isComponent = node.tagType === 1 /* COMPONENT */;
14416 // The goal of the transform is to create a codegenNode implementing the
14417 // VNodeCall interface.
14418 let vnodeTag = isComponent
14419 ? resolveComponentType(node, context)
14420 : `"${tag}"`;
14421 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14422 let vnodeProps;
14423 let vnodeChildren;
14424 let vnodePatchFlag;
14425 let patchFlag = 0;
14426 let vnodeDynamicProps;
14427 let dynamicPropNames;
14428 let vnodeDirectives;
14429 let shouldUseBlock =
14430 // dynamic component may resolve to plain elements
14431 isDynamicComponent ||
14432 vnodeTag === TELEPORT ||
14433 vnodeTag === SUSPENSE ||
14434 (!isComponent &&
14435 // <svg> and <foreignObject> must be forced into blocks so that block
14436 // updates inside get proper isSVG flag at runtime. (#639, #643)
14437 // This is technically web-specific, but splitting the logic out of core
14438 // leads to too much unnecessary complexity.
14439 (tag === 'svg' ||
14440 tag === 'foreignObject' ||
14441 // #938: elements with dynamic keys should be forced into blocks
14442 findProp(node, 'key', true)));
14443 // props
14444 if (props.length > 0) {
14445 const propsBuildResult = buildProps(node, context);
14446 vnodeProps = propsBuildResult.props;
14447 patchFlag = propsBuildResult.patchFlag;
14448 dynamicPropNames = propsBuildResult.dynamicPropNames;
14449 const directives = propsBuildResult.directives;
14450 vnodeDirectives =
14451 directives && directives.length
14452 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14453 : undefined;
14454 }
14455 // children
14456 if (node.children.length > 0) {
14457 if (vnodeTag === KEEP_ALIVE) {
14458 // Although a built-in component, we compile KeepAlive with raw children
14459 // instead of slot functions so that it can be used inside Transition
14460 // or other Transition-wrapping HOCs.
14461 // To ensure correct updates with block optimizations, we need to:
14462 // 1. Force keep-alive into a block. This avoids its children being
14463 // collected by a parent block.
14464 shouldUseBlock = true;
14465 // 2. Force keep-alive to always be updated, since it uses raw children.
14466 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14467 if (node.children.length > 1) {
14468 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14469 start: node.children[0].loc.start,
14470 end: node.children[node.children.length - 1].loc.end,
14471 source: ''
14472 }));
14473 }
14474 }
14475 const shouldBuildAsSlots = isComponent &&
14476 // Teleport is not a real component and has dedicated runtime handling
14477 vnodeTag !== TELEPORT &&
14478 // explained above.
14479 vnodeTag !== KEEP_ALIVE;
14480 if (shouldBuildAsSlots) {
14481 const { slots, hasDynamicSlots } = buildSlots(node, context);
14482 vnodeChildren = slots;
14483 if (hasDynamicSlots) {
14484 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14485 }
14486 }
14487 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14488 const child = node.children[0];
14489 const type = child.type;
14490 // check for dynamic text children
14491 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14492 type === 8 /* COMPOUND_EXPRESSION */;
14493 if (hasDynamicTextChild &&
14494 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14495 patchFlag |= 1 /* TEXT */;
14496 }
14497 // pass directly if the only child is a text node
14498 // (plain / interpolation / expression)
14499 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14500 vnodeChildren = child;
14501 }
14502 else {
14503 vnodeChildren = node.children;
14504 }
14505 }
14506 else {
14507 vnodeChildren = node.children;
14508 }
14509 }
14510 // patchFlag & dynamicPropNames
14511 if (patchFlag !== 0) {
14512 {
14513 if (patchFlag < 0) {
14514 // special flags (negative and mutually exclusive)
14515 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14516 }
14517 else {
14518 // bitwise flags
14519 const flagNames = Object.keys(PatchFlagNames)
14520 .map(Number)
14521 .filter(n => n > 0 && patchFlag & n)
14522 .map(n => PatchFlagNames[n])
14523 .join(`, `);
14524 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14525 }
14526 }
14527 if (dynamicPropNames && dynamicPropNames.length) {
14528 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14529 }
14530 }
14531 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14532 };
14533};
14534function resolveComponentType(node, context, ssr = false) {
14535 let { tag } = node;
14536 // 1. dynamic component
14537 const isExplicitDynamic = isComponentTag(tag);
14538 const isProp = findProp(node, 'is');
14539 if (isProp) {
14540 if (isExplicitDynamic ||
14541 (false )) {
14542 const exp = isProp.type === 6 /* ATTRIBUTE */
14543 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14544 : isProp.exp;
14545 if (exp) {
14546 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14547 exp
14548 ]);
14549 }
14550 }
14551 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14552 isProp.value.content.startsWith('vue:')) {
14553 // <button is="vue:xxx">
14554 // if not <component>, only is value that starts with "vue:" will be
14555 // treated as component by the parse phase and reach here, unless it's
14556 // compat mode where all is values are considered components
14557 tag = isProp.value.content.slice(4);
14558 }
14559 }
14560 // 1.5 v-is (TODO: Deprecate)
14561 const isDir = !isExplicitDynamic && findDir(node, 'is');
14562 if (isDir && isDir.exp) {
14563 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14564 isDir.exp
14565 ]);
14566 }
14567 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14568 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14569 if (builtIn) {
14570 // built-ins are simply fallthroughs / have special handling during ssr
14571 // so we don't need to import their runtime equivalents
14572 if (!ssr)
14573 context.helper(builtIn);
14574 return builtIn;
14575 }
14576 // 5. user component (resolve)
14577 context.helper(RESOLVE_COMPONENT);
14578 context.components.add(tag);
14579 return toValidAssetId(tag, `component`);
14580}
14581function buildProps(node, context, props = node.props, ssr = false) {
14582 const { tag, loc: elementLoc } = node;
14583 const isComponent = node.tagType === 1 /* COMPONENT */;
14584 let properties = [];
14585 const mergeArgs = [];
14586 const runtimeDirectives = [];
14587 // patchFlag analysis
14588 let patchFlag = 0;
14589 let hasRef = false;
14590 let hasClassBinding = false;
14591 let hasStyleBinding = false;
14592 let hasHydrationEventBinding = false;
14593 let hasDynamicKeys = false;
14594 let hasVnodeHook = false;
14595 const dynamicPropNames = [];
14596 const analyzePatchFlag = ({ key, value }) => {
14597 if (isStaticExp(key)) {
14598 const name = key.content;
14599 const isEventHandler = isOn(name);
14600 if (!isComponent &&
14601 isEventHandler &&
14602 // omit the flag for click handlers because hydration gives click
14603 // dedicated fast path.
14604 name.toLowerCase() !== 'onclick' &&
14605 // omit v-model handlers
14606 name !== 'onUpdate:modelValue' &&
14607 // omit onVnodeXXX hooks
14608 !isReservedProp(name)) {
14609 hasHydrationEventBinding = true;
14610 }
14611 if (isEventHandler && isReservedProp(name)) {
14612 hasVnodeHook = true;
14613 }
14614 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14615 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14616 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14617 getConstantType(value, context) > 0)) {
14618 // skip if the prop is a cached handler or has constant value
14619 return;
14620 }
14621 if (name === 'ref') {
14622 hasRef = true;
14623 }
14624 else if (name === 'class') {
14625 hasClassBinding = true;
14626 }
14627 else if (name === 'style') {
14628 hasStyleBinding = true;
14629 }
14630 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14631 dynamicPropNames.push(name);
14632 }
14633 // treat the dynamic class and style binding of the component as dynamic props
14634 if (isComponent &&
14635 (name === 'class' || name === 'style') &&
14636 !dynamicPropNames.includes(name)) {
14637 dynamicPropNames.push(name);
14638 }
14639 }
14640 else {
14641 hasDynamicKeys = true;
14642 }
14643 };
14644 for (let i = 0; i < props.length; i++) {
14645 // static attribute
14646 const prop = props[i];
14647 if (prop.type === 6 /* ATTRIBUTE */) {
14648 const { loc, name, value } = prop;
14649 let valueNode = createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc);
14650 if (name === 'ref') {
14651 hasRef = true;
14652 }
14653 // skip is on <component>, or is="vue:xxx"
14654 if (name === 'is' &&
14655 (isComponentTag(tag) ||
14656 (value && value.content.startsWith('vue:')) ||
14657 (false ))) {
14658 continue;
14659 }
14660 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), valueNode));
14661 }
14662 else {
14663 // directives
14664 const { name, arg, exp, loc } = prop;
14665 const isVBind = name === 'bind';
14666 const isVOn = name === 'on';
14667 // skip v-slot - it is handled by its dedicated transform.
14668 if (name === 'slot') {
14669 if (!isComponent) {
14670 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14671 }
14672 continue;
14673 }
14674 // skip v-once/v-memo - they are handled by dedicated transforms.
14675 if (name === 'once' || name === 'memo') {
14676 continue;
14677 }
14678 // skip v-is and :is on <component>
14679 if (name === 'is' ||
14680 (isVBind &&
14681 isBindKey(arg, 'is') &&
14682 (isComponentTag(tag) ||
14683 (false )))) {
14684 continue;
14685 }
14686 // skip v-on in SSR compilation
14687 if (isVOn && ssr) {
14688 continue;
14689 }
14690 // special case for v-bind and v-on with no argument
14691 if (!arg && (isVBind || isVOn)) {
14692 hasDynamicKeys = true;
14693 if (exp) {
14694 if (properties.length) {
14695 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14696 properties = [];
14697 }
14698 if (isVBind) {
14699 mergeArgs.push(exp);
14700 }
14701 else {
14702 // v-on="obj" -> toHandlers(obj)
14703 mergeArgs.push({
14704 type: 14 /* JS_CALL_EXPRESSION */,
14705 loc,
14706 callee: context.helper(TO_HANDLERS),
14707 arguments: [exp]
14708 });
14709 }
14710 }
14711 else {
14712 context.onError(createCompilerError(isVBind
14713 ? 34 /* X_V_BIND_NO_EXPRESSION */
14714 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14715 }
14716 continue;
14717 }
14718 const directiveTransform = context.directiveTransforms[name];
14719 if (directiveTransform) {
14720 // has built-in directive transform.
14721 const { props, needRuntime } = directiveTransform(prop, node, context);
14722 !ssr && props.forEach(analyzePatchFlag);
14723 properties.push(...props);
14724 if (needRuntime) {
14725 runtimeDirectives.push(prop);
14726 if (isSymbol(needRuntime)) {
14727 directiveImportMap.set(prop, needRuntime);
14728 }
14729 }
14730 }
14731 else {
14732 // no built-in transform, this is a user custom directive.
14733 runtimeDirectives.push(prop);
14734 }
14735 }
14736 }
14737 let propsExpression = undefined;
14738 // has v-bind="object" or v-on="object", wrap with mergeProps
14739 if (mergeArgs.length) {
14740 if (properties.length) {
14741 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14742 }
14743 if (mergeArgs.length > 1) {
14744 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14745 }
14746 else {
14747 // single v-bind with nothing else - no need for a mergeProps call
14748 propsExpression = mergeArgs[0];
14749 }
14750 }
14751 else if (properties.length) {
14752 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14753 }
14754 // patchFlag analysis
14755 if (hasDynamicKeys) {
14756 patchFlag |= 16 /* FULL_PROPS */;
14757 }
14758 else {
14759 if (hasClassBinding && !isComponent) {
14760 patchFlag |= 2 /* CLASS */;
14761 }
14762 if (hasStyleBinding && !isComponent) {
14763 patchFlag |= 4 /* STYLE */;
14764 }
14765 if (dynamicPropNames.length) {
14766 patchFlag |= 8 /* PROPS */;
14767 }
14768 if (hasHydrationEventBinding) {
14769 patchFlag |= 32 /* HYDRATE_EVENTS */;
14770 }
14771 }
14772 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14773 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14774 patchFlag |= 512 /* NEED_PATCH */;
14775 }
14776 // pre-normalize props, SSR is skipped for now
14777 if (!context.inSSR && propsExpression) {
14778 switch (propsExpression.type) {
14779 case 15 /* JS_OBJECT_EXPRESSION */:
14780 // means that there is no v-bind,
14781 // but still need to deal with dynamic key binding
14782 let classKeyIndex = -1;
14783 let styleKeyIndex = -1;
14784 let hasDynamicKey = false;
14785 for (let i = 0; i < propsExpression.properties.length; i++) {
14786 const key = propsExpression.properties[i].key;
14787 if (isStaticExp(key)) {
14788 if (key.content === 'class') {
14789 classKeyIndex = i;
14790 }
14791 else if (key.content === 'style') {
14792 styleKeyIndex = i;
14793 }
14794 }
14795 else if (!key.isHandlerKey) {
14796 hasDynamicKey = true;
14797 }
14798 }
14799 const classProp = propsExpression.properties[classKeyIndex];
14800 const styleProp = propsExpression.properties[styleKeyIndex];
14801 // no dynamic key
14802 if (!hasDynamicKey) {
14803 if (classProp && !isStaticExp(classProp.value)) {
14804 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14805 }
14806 if (styleProp &&
14807 !isStaticExp(styleProp.value) &&
14808 // the static style is compiled into an object,
14809 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14810 (hasStyleBinding ||
14811 // v-bind:style and style both exist,
14812 // v-bind:style with static literal object
14813 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14814 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14815 }
14816 }
14817 else {
14818 // dynamic key binding, wrap with `normalizeProps`
14819 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14820 }
14821 break;
14822 case 14 /* JS_CALL_EXPRESSION */:
14823 // mergeProps call, do nothing
14824 break;
14825 default:
14826 // single v-bind
14827 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14828 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14829 propsExpression
14830 ])
14831 ]);
14832 break;
14833 }
14834 }
14835 return {
14836 props: propsExpression,
14837 directives: runtimeDirectives,
14838 patchFlag,
14839 dynamicPropNames
14840 };
14841}
14842// Dedupe props in an object literal.
14843// Literal duplicated attributes would have been warned during the parse phase,
14844// however, it's possible to encounter duplicated `onXXX` handlers with different
14845// modifiers. We also need to merge static and dynamic class / style attributes.
14846// - onXXX handlers / style: merge into array
14847// - class: merge into single expression with concatenation
14848function dedupeProperties(properties) {
14849 const knownProps = new Map();
14850 const deduped = [];
14851 for (let i = 0; i < properties.length; i++) {
14852 const prop = properties[i];
14853 // dynamic keys are always allowed
14854 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14855 deduped.push(prop);
14856 continue;
14857 }
14858 const name = prop.key.content;
14859 const existing = knownProps.get(name);
14860 if (existing) {
14861 if (name === 'style' || name === 'class' || name.startsWith('on')) {
14862 mergeAsArray$1(existing, prop);
14863 }
14864 // unexpected duplicate, should have emitted error during parse
14865 }
14866 else {
14867 knownProps.set(name, prop);
14868 deduped.push(prop);
14869 }
14870 }
14871 return deduped;
14872}
14873function mergeAsArray$1(existing, incoming) {
14874 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14875 existing.value.elements.push(incoming.value);
14876 }
14877 else {
14878 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14879 }
14880}
14881function buildDirectiveArgs(dir, context) {
14882 const dirArgs = [];
14883 const runtime = directiveImportMap.get(dir);
14884 if (runtime) {
14885 // built-in directive with runtime
14886 dirArgs.push(context.helperString(runtime));
14887 }
14888 else {
14889 {
14890 // inject statement for resolving directive
14891 context.helper(RESOLVE_DIRECTIVE);
14892 context.directives.add(dir.name);
14893 dirArgs.push(toValidAssetId(dir.name, `directive`));
14894 }
14895 }
14896 const { loc } = dir;
14897 if (dir.exp)
14898 dirArgs.push(dir.exp);
14899 if (dir.arg) {
14900 if (!dir.exp) {
14901 dirArgs.push(`void 0`);
14902 }
14903 dirArgs.push(dir.arg);
14904 }
14905 if (Object.keys(dir.modifiers).length) {
14906 if (!dir.arg) {
14907 if (!dir.exp) {
14908 dirArgs.push(`void 0`);
14909 }
14910 dirArgs.push(`void 0`);
14911 }
14912 const trueExpression = createSimpleExpression(`true`, false, loc);
14913 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14914 }
14915 return createArrayExpression(dirArgs, dir.loc);
14916}
14917function stringifyDynamicPropNames(props) {
14918 let propsNamesString = `[`;
14919 for (let i = 0, l = props.length; i < l; i++) {
14920 propsNamesString += JSON.stringify(props[i]);
14921 if (i < l - 1)
14922 propsNamesString += ', ';
14923 }
14924 return propsNamesString + `]`;
14925}
14926function isComponentTag(tag) {
14927 return tag[0].toLowerCase() + tag.slice(1) === 'component';
14928}
14929
14930const transformSlotOutlet = (node, context) => {
14931 if (isSlotOutlet(node)) {
14932 const { children, loc } = node;
14933 const { slotName, slotProps } = processSlotOutlet(node, context);
14934 const slotArgs = [
14935 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14936 slotName
14937 ];
14938 if (slotProps) {
14939 slotArgs.push(slotProps);
14940 }
14941 if (children.length) {
14942 if (!slotProps) {
14943 slotArgs.push(`{}`);
14944 }
14945 slotArgs.push(createFunctionExpression([], children, false, false, loc));
14946 }
14947 if (context.scopeId && !context.slotted) {
14948 if (!slotProps) {
14949 slotArgs.push(`{}`);
14950 }
14951 if (!children.length) {
14952 slotArgs.push(`undefined`);
14953 }
14954 slotArgs.push(`true`);
14955 }
14956 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14957 }
14958};
14959function processSlotOutlet(node, context) {
14960 let slotName = `"default"`;
14961 let slotProps = undefined;
14962 const nonNameProps = [];
14963 for (let i = 0; i < node.props.length; i++) {
14964 const p = node.props[i];
14965 if (p.type === 6 /* ATTRIBUTE */) {
14966 if (p.value) {
14967 if (p.name === 'name') {
14968 slotName = JSON.stringify(p.value.content);
14969 }
14970 else {
14971 p.name = camelize(p.name);
14972 nonNameProps.push(p);
14973 }
14974 }
14975 }
14976 else {
14977 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
14978 if (p.exp)
14979 slotName = p.exp;
14980 }
14981 else {
14982 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14983 p.arg.content = camelize(p.arg.content);
14984 }
14985 nonNameProps.push(p);
14986 }
14987 }
14988 }
14989 if (nonNameProps.length > 0) {
14990 const { props, directives } = buildProps(node, context, nonNameProps);
14991 slotProps = props;
14992 if (directives.length) {
14993 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14994 }
14995 }
14996 return {
14997 slotName,
14998 slotProps
14999 };
15000}
15001
15002const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
15003const transformOn = (dir, node, context, augmentor) => {
15004 const { loc, modifiers, arg } = dir;
15005 if (!dir.exp && !modifiers.length) {
15006 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
15007 }
15008 let eventName;
15009 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15010 if (arg.isStatic) {
15011 const rawName = arg.content;
15012 // for all event listeners, auto convert it to camelCase. See issue #2249
15013 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
15014 }
15015 else {
15016 // #2388
15017 eventName = createCompoundExpression([
15018 `${context.helperString(TO_HANDLER_KEY)}(`,
15019 arg,
15020 `)`
15021 ]);
15022 }
15023 }
15024 else {
15025 // already a compound expression.
15026 eventName = arg;
15027 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
15028 eventName.children.push(`)`);
15029 }
15030 // handler processing
15031 let exp = dir.exp;
15032 if (exp && !exp.content.trim()) {
15033 exp = undefined;
15034 }
15035 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
15036 if (exp) {
15037 const isMemberExp = isMemberExpression(exp.content);
15038 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
15039 const hasMultipleStatements = exp.content.includes(`;`);
15040 {
15041 validateBrowserExpression(exp, context, false, hasMultipleStatements);
15042 }
15043 if (isInlineStatement || (shouldCache && isMemberExp)) {
15044 // wrap inline statement in a function expression
15045 exp = createCompoundExpression([
15046 `${isInlineStatement
15047 ? `$event`
15048 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
15049 exp,
15050 hasMultipleStatements ? `}` : `)`
15051 ]);
15052 }
15053 }
15054 let ret = {
15055 props: [
15056 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
15057 ]
15058 };
15059 // apply extended compiler augmentor
15060 if (augmentor) {
15061 ret = augmentor(ret);
15062 }
15063 if (shouldCache) {
15064 // cache handlers so that it's always the same handler being passed down.
15065 // this avoids unnecessary re-renders when users use inline handlers on
15066 // components.
15067 ret.props[0].value = context.cache(ret.props[0].value);
15068 }
15069 // mark the key as handler for props normalization check
15070 ret.props.forEach(p => (p.key.isHandlerKey = true));
15071 return ret;
15072};
15073
15074// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
15075// codegen for the entire props object. This transform here is only for v-bind
15076// *with* args.
15077const transformBind = (dir, _node, context) => {
15078 const { exp, modifiers, loc } = dir;
15079 const arg = dir.arg;
15080 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
15081 arg.children.unshift(`(`);
15082 arg.children.push(`) || ""`);
15083 }
15084 else if (!arg.isStatic) {
15085 arg.content = `${arg.content} || ""`;
15086 }
15087 // .sync is replaced by v-model:arg
15088 if (modifiers.includes('camel')) {
15089 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15090 if (arg.isStatic) {
15091 arg.content = camelize(arg.content);
15092 }
15093 else {
15094 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
15095 }
15096 }
15097 else {
15098 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
15099 arg.children.push(`)`);
15100 }
15101 }
15102 if (!context.inSSR) {
15103 if (modifiers.includes('prop')) {
15104 injectPrefix(arg, '.');
15105 }
15106 if (modifiers.includes('attr')) {
15107 injectPrefix(arg, '^');
15108 }
15109 }
15110 if (!exp ||
15111 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
15112 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
15113 return {
15114 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
15115 };
15116 }
15117 return {
15118 props: [createObjectProperty(arg, exp)]
15119 };
15120};
15121const injectPrefix = (arg, prefix) => {
15122 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15123 if (arg.isStatic) {
15124 arg.content = prefix + arg.content;
15125 }
15126 else {
15127 arg.content = `\`${prefix}\${${arg.content}}\``;
15128 }
15129 }
15130 else {
15131 arg.children.unshift(`'${prefix}' + (`);
15132 arg.children.push(`)`);
15133 }
15134};
15135
15136// Merge adjacent text nodes and expressions into a single expression
15137// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15138const transformText = (node, context) => {
15139 if (node.type === 0 /* ROOT */ ||
15140 node.type === 1 /* ELEMENT */ ||
15141 node.type === 11 /* FOR */ ||
15142 node.type === 10 /* IF_BRANCH */) {
15143 // perform the transform on node exit so that all expressions have already
15144 // been processed.
15145 return () => {
15146 const children = node.children;
15147 let currentContainer = undefined;
15148 let hasText = false;
15149 for (let i = 0; i < children.length; i++) {
15150 const child = children[i];
15151 if (isText(child)) {
15152 hasText = true;
15153 for (let j = i + 1; j < children.length; j++) {
15154 const next = children[j];
15155 if (isText(next)) {
15156 if (!currentContainer) {
15157 currentContainer = children[i] = {
15158 type: 8 /* COMPOUND_EXPRESSION */,
15159 loc: child.loc,
15160 children: [child]
15161 };
15162 }
15163 // merge adjacent text node into current
15164 currentContainer.children.push(` + `, next);
15165 children.splice(j, 1);
15166 j--;
15167 }
15168 else {
15169 currentContainer = undefined;
15170 break;
15171 }
15172 }
15173 }
15174 }
15175 if (!hasText ||
15176 // if this is a plain element with a single text child, leave it
15177 // as-is since the runtime has dedicated fast path for this by directly
15178 // setting textContent of the element.
15179 // for component root it's always normalized anyway.
15180 (children.length === 1 &&
15181 (node.type === 0 /* ROOT */ ||
15182 (node.type === 1 /* ELEMENT */ &&
15183 node.tagType === 0 /* ELEMENT */ &&
15184 // #3756
15185 // custom directives can potentially add DOM elements arbitrarily,
15186 // we need to avoid setting textContent of the element at runtime
15187 // to avoid accidentally overwriting the DOM elements added
15188 // by the user through custom directives.
15189 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15190 !context.directiveTransforms[p.name]) &&
15191 // in compat mode, <template> tags with no special directives
15192 // will be rendered as a fragment so its children must be
15193 // converted into vnodes.
15194 !(false ))))) {
15195 return;
15196 }
15197 // pre-convert text nodes into createTextVNode(text) calls to avoid
15198 // runtime normalization.
15199 for (let i = 0; i < children.length; i++) {
15200 const child = children[i];
15201 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15202 const callArgs = [];
15203 // createTextVNode defaults to single whitespace, so if it is a
15204 // single space the code could be an empty call to save bytes.
15205 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15206 callArgs.push(child);
15207 }
15208 // mark dynamic text with flag so it gets patched inside a block
15209 if (!context.ssr &&
15210 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15211 callArgs.push(1 /* TEXT */ +
15212 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15213 }
15214 children[i] = {
15215 type: 12 /* TEXT_CALL */,
15216 content: child,
15217 loc: child.loc,
15218 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15219 };
15220 }
15221 }
15222 };
15223 }
15224};
15225
15226const seen = new WeakSet();
15227const transformOnce = (node, context) => {
15228 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15229 if (seen.has(node) || context.inVOnce) {
15230 return;
15231 }
15232 seen.add(node);
15233 context.inVOnce = true;
15234 context.helper(SET_BLOCK_TRACKING);
15235 return () => {
15236 context.inVOnce = false;
15237 const cur = context.currentNode;
15238 if (cur.codegenNode) {
15239 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15240 }
15241 };
15242 }
15243};
15244
15245const transformModel = (dir, node, context) => {
15246 const { exp, arg } = dir;
15247 if (!exp) {
15248 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15249 return createTransformProps();
15250 }
15251 const rawExp = exp.loc.source;
15252 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15253 // im SFC <script setup> inline mode, the exp may have been transformed into
15254 // _unref(exp)
15255 context.bindingMetadata[rawExp];
15256 const maybeRef = !true /* SETUP_CONST */;
15257 if (!expString.trim() || (!isMemberExpression(expString) && !maybeRef)) {
15258 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15259 return createTransformProps();
15260 }
15261 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15262 const eventName = arg
15263 ? isStaticExp(arg)
15264 ? `onUpdate:${arg.content}`
15265 : createCompoundExpression(['"onUpdate:" + ', arg])
15266 : `onUpdate:modelValue`;
15267 let assignmentExp;
15268 const eventArg = context.isTS ? `($event: any)` : `$event`;
15269 {
15270 assignmentExp = createCompoundExpression([
15271 `${eventArg} => (`,
15272 exp,
15273 ` = $event)`
15274 ]);
15275 }
15276 const props = [
15277 // modelValue: foo
15278 createObjectProperty(propName, dir.exp),
15279 // "onUpdate:modelValue": $event => (foo = $event)
15280 createObjectProperty(eventName, assignmentExp)
15281 ];
15282 // modelModifiers: { foo: true, "bar-baz": true }
15283 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15284 const modifiers = dir.modifiers
15285 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15286 .join(`, `);
15287 const modifiersKey = arg
15288 ? isStaticExp(arg)
15289 ? `${arg.content}Modifiers`
15290 : createCompoundExpression([arg, ' + "Modifiers"'])
15291 : `modelModifiers`;
15292 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15293 }
15294 return createTransformProps(props);
15295};
15296function createTransformProps(props = []) {
15297 return { props };
15298}
15299
15300const seen$1 = new WeakSet();
15301const transformMemo = (node, context) => {
15302 if (node.type === 1 /* ELEMENT */) {
15303 const dir = findDir(node, 'memo');
15304 if (!dir || seen$1.has(node)) {
15305 return;
15306 }
15307 seen$1.add(node);
15308 return () => {
15309 const codegenNode = node.codegenNode ||
15310 context.currentNode.codegenNode;
15311 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15312 // non-component sub tree should be turned into a block
15313 if (node.tagType !== 1 /* COMPONENT */) {
15314 makeBlock(codegenNode, context);
15315 }
15316 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15317 dir.exp,
15318 createFunctionExpression(undefined, codegenNode),
15319 `_cache`,
15320 String(context.cached++)
15321 ]);
15322 }
15323 };
15324 }
15325};
15326
15327function getBaseTransformPreset(prefixIdentifiers) {
15328 return [
15329 [
15330 transformOnce,
15331 transformIf,
15332 transformMemo,
15333 transformFor,
15334 ...([]),
15335 ...([transformExpression]
15336 ),
15337 transformSlotOutlet,
15338 transformElement,
15339 trackSlotScopes,
15340 transformText
15341 ],
15342 {
15343 on: transformOn,
15344 bind: transformBind,
15345 model: transformModel
15346 }
15347 ];
15348}
15349// we name it `baseCompile` so that higher order compilers like
15350// @vue/compiler-dom can export `compile` while re-exporting everything else.
15351function baseCompile(template, options = {}) {
15352 const onError = options.onError || defaultOnError;
15353 const isModuleMode = options.mode === 'module';
15354 /* istanbul ignore if */
15355 {
15356 if (options.prefixIdentifiers === true) {
15357 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15358 }
15359 else if (isModuleMode) {
15360 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15361 }
15362 }
15363 const prefixIdentifiers = !true ;
15364 if (options.cacheHandlers) {
15365 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15366 }
15367 if (options.scopeId && !isModuleMode) {
15368 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15369 }
15370 const ast = isString(template) ? baseParse(template, options) : template;
15371 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15372 transform(ast, extend({}, options, {
15373 prefixIdentifiers,
15374 nodeTransforms: [
15375 ...nodeTransforms,
15376 ...(options.nodeTransforms || []) // user transforms
15377 ],
15378 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15379 )
15380 }));
15381 return generate(ast, extend({}, options, {
15382 prefixIdentifiers
15383 }));
15384}
15385
15386const noopDirectiveTransform = () => ({ props: [] });
15387
15388const V_MODEL_RADIO = Symbol(`vModelRadio` );
15389const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15390const V_MODEL_TEXT = Symbol(`vModelText` );
15391const V_MODEL_SELECT = Symbol(`vModelSelect` );
15392const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15393const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15394const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15395const V_SHOW = Symbol(`vShow` );
15396const TRANSITION$1 = Symbol(`Transition` );
15397const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15398registerRuntimeHelpers({
15399 [V_MODEL_RADIO]: `vModelRadio`,
15400 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15401 [V_MODEL_TEXT]: `vModelText`,
15402 [V_MODEL_SELECT]: `vModelSelect`,
15403 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15404 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15405 [V_ON_WITH_KEYS]: `withKeys`,
15406 [V_SHOW]: `vShow`,
15407 [TRANSITION$1]: `Transition`,
15408 [TRANSITION_GROUP]: `TransitionGroup`
15409});
15410
15411/* eslint-disable no-restricted-globals */
15412let decoder;
15413function decodeHtmlBrowser(raw, asAttr = false) {
15414 if (!decoder) {
15415 decoder = document.createElement('div');
15416 }
15417 if (asAttr) {
15418 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15419 return decoder.children[0].getAttribute('foo');
15420 }
15421 else {
15422 decoder.innerHTML = raw;
15423 return decoder.textContent;
15424 }
15425}
15426
15427const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15428const parserOptions = {
15429 isVoidTag,
15430 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15431 isPreTag: tag => tag === 'pre',
15432 decodeEntities: decodeHtmlBrowser ,
15433 isBuiltInComponent: (tag) => {
15434 if (isBuiltInType(tag, `Transition`)) {
15435 return TRANSITION$1;
15436 }
15437 else if (isBuiltInType(tag, `TransitionGroup`)) {
15438 return TRANSITION_GROUP;
15439 }
15440 },
15441 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15442 getNamespace(tag, parent) {
15443 let ns = parent ? parent.ns : 0 /* HTML */;
15444 if (parent && ns === 2 /* MATH_ML */) {
15445 if (parent.tag === 'annotation-xml') {
15446 if (tag === 'svg') {
15447 return 1 /* SVG */;
15448 }
15449 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15450 a.name === 'encoding' &&
15451 a.value != null &&
15452 (a.value.content === 'text/html' ||
15453 a.value.content === 'application/xhtml+xml'))) {
15454 ns = 0 /* HTML */;
15455 }
15456 }
15457 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15458 tag !== 'mglyph' &&
15459 tag !== 'malignmark') {
15460 ns = 0 /* HTML */;
15461 }
15462 }
15463 else if (parent && ns === 1 /* SVG */) {
15464 if (parent.tag === 'foreignObject' ||
15465 parent.tag === 'desc' ||
15466 parent.tag === 'title') {
15467 ns = 0 /* HTML */;
15468 }
15469 }
15470 if (ns === 0 /* HTML */) {
15471 if (tag === 'svg') {
15472 return 1 /* SVG */;
15473 }
15474 if (tag === 'math') {
15475 return 2 /* MATH_ML */;
15476 }
15477 }
15478 return ns;
15479 },
15480 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15481 getTextMode({ tag, ns }) {
15482 if (ns === 0 /* HTML */) {
15483 if (tag === 'textarea' || tag === 'title') {
15484 return 1 /* RCDATA */;
15485 }
15486 if (isRawTextContainer(tag)) {
15487 return 2 /* RAWTEXT */;
15488 }
15489 }
15490 return 0 /* DATA */;
15491 }
15492};
15493
15494// Parse inline CSS strings for static style attributes into an object.
15495// This is a NodeTransform since it works on the static `style` attribute and
15496// converts it into a dynamic equivalent:
15497// style="color: red" -> :style='{ "color": "red" }'
15498// It is then processed by `transformElement` and included in the generated
15499// props.
15500const transformStyle = node => {
15501 if (node.type === 1 /* ELEMENT */) {
15502 node.props.forEach((p, i) => {
15503 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15504 // replace p with an expression node
15505 node.props[i] = {
15506 type: 7 /* DIRECTIVE */,
15507 name: `bind`,
15508 arg: createSimpleExpression(`style`, true, p.loc),
15509 exp: parseInlineCSS(p.value.content, p.loc),
15510 modifiers: [],
15511 loc: p.loc
15512 };
15513 }
15514 });
15515 }
15516};
15517const parseInlineCSS = (cssText, loc) => {
15518 const normalized = parseStringStyle(cssText);
15519 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15520};
15521
15522function createDOMCompilerError(code, loc) {
15523 return createCompilerError(code, loc, DOMErrorMessages );
15524}
15525const DOMErrorMessages = {
15526 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15527 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15528 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15529 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15530 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15531 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15532 [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.`,
15533 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15534 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15535 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15536 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15537};
15538
15539const transformVHtml = (dir, node, context) => {
15540 const { exp, loc } = dir;
15541 if (!exp) {
15542 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15543 }
15544 if (node.children.length) {
15545 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15546 node.children.length = 0;
15547 }
15548 return {
15549 props: [
15550 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15551 ]
15552 };
15553};
15554
15555const transformVText = (dir, node, context) => {
15556 const { exp, loc } = dir;
15557 if (!exp) {
15558 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15559 }
15560 if (node.children.length) {
15561 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15562 node.children.length = 0;
15563 }
15564 return {
15565 props: [
15566 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15567 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15568 : createSimpleExpression('', true))
15569 ]
15570 };
15571};
15572
15573const transformModel$1 = (dir, node, context) => {
15574 const baseResult = transformModel(dir, node, context);
15575 // base transform has errors OR component v-model (only need props)
15576 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15577 return baseResult;
15578 }
15579 if (dir.arg) {
15580 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15581 }
15582 function checkDuplicatedValue() {
15583 const value = findProp(node, 'value');
15584 if (value) {
15585 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15586 }
15587 }
15588 const { tag } = node;
15589 const isCustomElement = context.isCustomElement(tag);
15590 if (tag === 'input' ||
15591 tag === 'textarea' ||
15592 tag === 'select' ||
15593 isCustomElement) {
15594 let directiveToUse = V_MODEL_TEXT;
15595 let isInvalidType = false;
15596 if (tag === 'input' || isCustomElement) {
15597 const type = findProp(node, `type`);
15598 if (type) {
15599 if (type.type === 7 /* DIRECTIVE */) {
15600 // :type="foo"
15601 directiveToUse = V_MODEL_DYNAMIC;
15602 }
15603 else if (type.value) {
15604 switch (type.value.content) {
15605 case 'radio':
15606 directiveToUse = V_MODEL_RADIO;
15607 break;
15608 case 'checkbox':
15609 directiveToUse = V_MODEL_CHECKBOX;
15610 break;
15611 case 'file':
15612 isInvalidType = true;
15613 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15614 break;
15615 default:
15616 // text type
15617 checkDuplicatedValue();
15618 break;
15619 }
15620 }
15621 }
15622 else if (hasDynamicKeyVBind(node)) {
15623 // element has bindings with dynamic keys, which can possibly contain
15624 // "type".
15625 directiveToUse = V_MODEL_DYNAMIC;
15626 }
15627 else {
15628 // text type
15629 checkDuplicatedValue();
15630 }
15631 }
15632 else if (tag === 'select') {
15633 directiveToUse = V_MODEL_SELECT;
15634 }
15635 else {
15636 // textarea
15637 checkDuplicatedValue();
15638 }
15639 // inject runtime directive
15640 // by returning the helper symbol via needRuntime
15641 // the import will replaced a resolveDirective call.
15642 if (!isInvalidType) {
15643 baseResult.needRuntime = context.helper(directiveToUse);
15644 }
15645 }
15646 else {
15647 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15648 }
15649 // native vmodel doesn't need the `modelValue` props since they are also
15650 // passed to the runtime as `binding.value`. removing it reduces code size.
15651 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15652 p.key.content === 'modelValue'));
15653 return baseResult;
15654};
15655
15656const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15657const isNonKeyModifier = /*#__PURE__*/ makeMap(
15658// event propagation management
15659`stop,prevent,self,` +
15660 // system modifiers + exact
15661 `ctrl,shift,alt,meta,exact,` +
15662 // mouse
15663 `middle`);
15664// left & right could be mouse or key modifiers based on event type
15665const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15666const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15667const resolveModifiers = (key, modifiers, context, loc) => {
15668 const keyModifiers = [];
15669 const nonKeyModifiers = [];
15670 const eventOptionModifiers = [];
15671 for (let i = 0; i < modifiers.length; i++) {
15672 const modifier = modifiers[i];
15673 if (isEventOptionModifier(modifier)) {
15674 // eventOptionModifiers: modifiers for addEventListener() options,
15675 // e.g. .passive & .capture
15676 eventOptionModifiers.push(modifier);
15677 }
15678 else {
15679 // runtimeModifiers: modifiers that needs runtime guards
15680 if (maybeKeyModifier(modifier)) {
15681 if (isStaticExp(key)) {
15682 if (isKeyboardEvent(key.content)) {
15683 keyModifiers.push(modifier);
15684 }
15685 else {
15686 nonKeyModifiers.push(modifier);
15687 }
15688 }
15689 else {
15690 keyModifiers.push(modifier);
15691 nonKeyModifiers.push(modifier);
15692 }
15693 }
15694 else {
15695 if (isNonKeyModifier(modifier)) {
15696 nonKeyModifiers.push(modifier);
15697 }
15698 else {
15699 keyModifiers.push(modifier);
15700 }
15701 }
15702 }
15703 }
15704 return {
15705 keyModifiers,
15706 nonKeyModifiers,
15707 eventOptionModifiers
15708 };
15709};
15710const transformClick = (key, event) => {
15711 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15712 return isStaticClick
15713 ? createSimpleExpression(event, true)
15714 : key.type !== 4 /* SIMPLE_EXPRESSION */
15715 ? createCompoundExpression([
15716 `(`,
15717 key,
15718 `) === "onClick" ? "${event}" : (`,
15719 key,
15720 `)`
15721 ])
15722 : key;
15723};
15724const transformOn$1 = (dir, node, context) => {
15725 return transformOn(dir, node, context, baseResult => {
15726 const { modifiers } = dir;
15727 if (!modifiers.length)
15728 return baseResult;
15729 let { key, value: handlerExp } = baseResult.props[0];
15730 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15731 // normalize click.right and click.middle since they don't actually fire
15732 if (nonKeyModifiers.includes('right')) {
15733 key = transformClick(key, `onContextmenu`);
15734 }
15735 if (nonKeyModifiers.includes('middle')) {
15736 key = transformClick(key, `onMouseup`);
15737 }
15738 if (nonKeyModifiers.length) {
15739 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15740 handlerExp,
15741 JSON.stringify(nonKeyModifiers)
15742 ]);
15743 }
15744 if (keyModifiers.length &&
15745 // if event name is dynamic, always wrap with keys guard
15746 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15747 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15748 handlerExp,
15749 JSON.stringify(keyModifiers)
15750 ]);
15751 }
15752 if (eventOptionModifiers.length) {
15753 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15754 key = isStaticExp(key)
15755 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15756 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15757 }
15758 return {
15759 props: [createObjectProperty(key, handlerExp)]
15760 };
15761 });
15762};
15763
15764const transformShow = (dir, node, context) => {
15765 const { exp, loc } = dir;
15766 if (!exp) {
15767 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15768 }
15769 return {
15770 props: [],
15771 needRuntime: context.helper(V_SHOW)
15772 };
15773};
15774
15775const warnTransitionChildren = (node, context) => {
15776 if (node.type === 1 /* ELEMENT */ &&
15777 node.tagType === 1 /* COMPONENT */) {
15778 const component = context.isBuiltInComponent(node.tag);
15779 if (component === TRANSITION$1) {
15780 return () => {
15781 if (node.children.length && hasMultipleChildren(node)) {
15782 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15783 start: node.children[0].loc.start,
15784 end: node.children[node.children.length - 1].loc.end,
15785 source: ''
15786 }));
15787 }
15788 };
15789 }
15790 }
15791};
15792function hasMultipleChildren(node) {
15793 // #1352 filter out potential comment nodes.
15794 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
15795 const child = children[0];
15796 return (children.length !== 1 ||
15797 child.type === 11 /* FOR */ ||
15798 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15799}
15800
15801const ignoreSideEffectTags = (node, context) => {
15802 if (node.type === 1 /* ELEMENT */ &&
15803 node.tagType === 0 /* ELEMENT */ &&
15804 (node.tag === 'script' || node.tag === 'style')) {
15805 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15806 context.removeNode();
15807 }
15808};
15809
15810const DOMNodeTransforms = [
15811 transformStyle,
15812 ...([warnTransitionChildren] )
15813];
15814const DOMDirectiveTransforms = {
15815 cloak: noopDirectiveTransform,
15816 html: transformVHtml,
15817 text: transformVText,
15818 model: transformModel$1,
15819 on: transformOn$1,
15820 show: transformShow
15821};
15822function compile$1(template, options = {}) {
15823 return baseCompile(template, extend({}, parserOptions, options, {
15824 nodeTransforms: [
15825 // ignore <script> and <tag>
15826 // this is not put inside DOMNodeTransforms because that list is used
15827 // by compiler-ssr to generate vnode fallback branches
15828 ignoreSideEffectTags,
15829 ...DOMNodeTransforms,
15830 ...(options.nodeTransforms || [])
15831 ],
15832 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15833 transformHoist: null
15834 }));
15835}
15836
15837// This entry is the "full-build" that includes both the runtime
15838{
15839 initDev();
15840}
15841const compileCache = Object.create(null);
15842function compileToFunction(template, options) {
15843 if (!isString(template)) {
15844 if (template.nodeType) {
15845 template = template.innerHTML;
15846 }
15847 else {
15848 warn$1(`invalid template option: `, template);
15849 return NOOP;
15850 }
15851 }
15852 const key = template;
15853 const cached = compileCache[key];
15854 if (cached) {
15855 return cached;
15856 }
15857 if (template[0] === '#') {
15858 const el = document.querySelector(template);
15859 if (!el) {
15860 warn$1(`Template element not found or is empty: ${template}`);
15861 }
15862 // __UNSAFE__
15863 // Reason: potential execution of JS expressions in in-DOM template.
15864 // The user must make sure the in-DOM template is trusted. If it's rendered
15865 // by the server, the template should not contain any user data.
15866 template = el ? el.innerHTML : ``;
15867 }
15868 const { code } = compile$1(template, extend({
15869 hoistStatic: true,
15870 onError: onError ,
15871 onWarn: e => onError(e, true)
15872 }, options));
15873 function onError(err, asWarning = false) {
15874 const message = asWarning
15875 ? err.message
15876 : `Template compilation error: ${err.message}`;
15877 const codeFrame = err.loc &&
15878 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15879 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15880 }
15881 // The wildcard import results in a huge object with every export
15882 // with keys that cannot be mangled, and can be quite heavy size-wise.
15883 // In the global build we know `Vue` is available globally so we can avoid
15884 // the wildcard object.
15885 const render = (new Function('Vue', code)(runtimeDom));
15886 render._rc = true;
15887 return (compileCache[key] = render);
15888}
15889registerRuntimeCompiler(compileToFunction);
15890
15891export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId };