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);
1535 record = map.get(id);
1536 }
1537 record.add(instance);
1538}
1539function unregisterHMR(instance) {
1540 map.get(instance.type.__hmrId).delete(instance);
1541}
1542function createRecord(id) {
1543 if (map.has(id)) {
1544 return false;
1545 }
1546 map.set(id, new Set());
1547 return true;
1548}
1549function normalizeClassComponent(component) {
1550 return isClassComponent(component) ? component.__vccOpts : component;
1551}
1552function rerender(id, newRender) {
1553 const record = map.get(id);
1554 if (!record) {
1555 return;
1556 }
1557 [...record].forEach(instance => {
1558 if (newRender) {
1559 instance.render = newRender;
1560 normalizeClassComponent(instance.type).render = newRender;
1561 }
1562 instance.renderCache = [];
1563 // this flag forces child components with slot content to update
1564 isHmrUpdating = true;
1565 instance.update();
1566 isHmrUpdating = false;
1567 });
1568}
1569function reload(id, newComp) {
1570 const record = map.get(id);
1571 if (!record)
1572 return;
1573 newComp = normalizeClassComponent(newComp);
1574 // create a snapshot which avoids the set being mutated during updates
1575 const instances = [...record];
1576 for (const instance of instances) {
1577 const oldComp = normalizeClassComponent(instance.type);
1578 if (!hmrDirtyComponents.has(oldComp)) {
1579 // 1. Update existing comp definition to match new one
1580 extend(oldComp, newComp);
1581 for (const key in oldComp) {
1582 if (key !== '__file' && !(key in newComp)) {
1583 delete oldComp[key];
1584 }
1585 }
1586 // 2. mark definition dirty. This forces the renderer to replace the
1587 // component on patch.
1588 hmrDirtyComponents.add(oldComp);
1589 }
1590 // 3. invalidate options resolution cache
1591 instance.appContext.optionsCache.delete(instance.type);
1592 // 4. actually update
1593 if (instance.ceReload) {
1594 // custom element
1595 hmrDirtyComponents.add(oldComp);
1596 instance.ceReload(newComp.styles);
1597 hmrDirtyComponents.delete(oldComp);
1598 }
1599 else if (instance.parent) {
1600 // 4. Force the parent instance to re-render. This will cause all updated
1601 // components to be unmounted and re-mounted. Queue the update so that we
1602 // don't end up forcing the same parent to re-render multiple times.
1603 queueJob(instance.parent.update);
1604 // instance is the inner component of an async custom element
1605 // invoke to reset styles
1606 if (instance.parent.type.__asyncLoader &&
1607 instance.parent.ceReload) {
1608 instance.parent.ceReload(newComp.styles);
1609 }
1610 }
1611 else if (instance.appContext.reload) {
1612 // root instance mounted via createApp() has a reload method
1613 instance.appContext.reload();
1614 }
1615 else if (typeof window !== 'undefined') {
1616 // root instance inside tree created via raw render(). Force reload.
1617 window.location.reload();
1618 }
1619 else {
1620 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1621 }
1622 }
1623 // 5. make sure to cleanup dirty hmr components after update
1624 queuePostFlushCb(() => {
1625 for (const instance of instances) {
1626 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
1627 }
1628 });
1629}
1630function tryWrap(fn) {
1631 return (id, arg) => {
1632 try {
1633 return fn(id, arg);
1634 }
1635 catch (e) {
1636 console.error(e);
1637 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1638 `Full reload required.`);
1639 }
1640 };
1641}
1642
1643let devtools;
1644function setDevtoolsHook(hook) {
1645 devtools = hook;
1646}
1647function devtoolsInitApp(app, version) {
1648 // TODO queue if devtools is undefined
1649 if (!devtools)
1650 return;
1651 devtools.emit("app:init" /* APP_INIT */, app, version, {
1652 Fragment,
1653 Text,
1654 Comment,
1655 Static
1656 });
1657}
1658function devtoolsUnmountApp(app) {
1659 if (!devtools)
1660 return;
1661 devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1662}
1663const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1664const devtoolsComponentUpdated =
1665/*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1666const devtoolsComponentRemoved =
1667/*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1668function createDevtoolsComponentHook(hook) {
1669 return (component) => {
1670 if (!devtools)
1671 return;
1672 devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1673 };
1674}
1675const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
1676const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
1677function createDevtoolsPerformanceHook(hook) {
1678 return (component, type, time) => {
1679 if (!devtools)
1680 return;
1681 devtools.emit(hook, component.appContext.app, component.uid, component, type, time);
1682 };
1683}
1684function devtoolsComponentEmit(component, event, params) {
1685 if (!devtools)
1686 return;
1687 devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1688}
1689
1690const deprecationData = {
1691 ["GLOBAL_MOUNT" /* GLOBAL_MOUNT */]: {
1692 message: `The global app bootstrapping API has changed: vm.$mount() and the "el" ` +
1693 `option have been removed. Use createApp(RootComponent).mount() instead.`,
1694 link: `https://v3.vuejs.org/guide/migration/global-api.html#mounting-app-instance`
1695 },
1696 ["GLOBAL_MOUNT_CONTAINER" /* GLOBAL_MOUNT_CONTAINER */]: {
1697 message: `Vue detected directives on the mount container. ` +
1698 `In Vue 3, the container is no longer considered part of the template ` +
1699 `and will not be processed/replaced.`,
1700 link: `https://v3.vuejs.org/guide/migration/mount-changes.html`
1701 },
1702 ["GLOBAL_EXTEND" /* GLOBAL_EXTEND */]: {
1703 message: `Vue.extend() has been removed in Vue 3. ` +
1704 `Use defineComponent() instead.`,
1705 link: `https://v3.vuejs.org/api/global-api.html#definecomponent`
1706 },
1707 ["GLOBAL_PROTOTYPE" /* GLOBAL_PROTOTYPE */]: {
1708 message: `Vue.prototype is no longer available in Vue 3. ` +
1709 `Use app.config.globalProperties instead.`,
1710 link: `https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties`
1711 },
1712 ["GLOBAL_SET" /* GLOBAL_SET */]: {
1713 message: `Vue.set() has been removed as it is no longer needed in Vue 3. ` +
1714 `Simply use native JavaScript mutations.`
1715 },
1716 ["GLOBAL_DELETE" /* GLOBAL_DELETE */]: {
1717 message: `Vue.delete() has been removed as it is no longer needed in Vue 3. ` +
1718 `Simply use native JavaScript mutations.`
1719 },
1720 ["GLOBAL_OBSERVABLE" /* GLOBAL_OBSERVABLE */]: {
1721 message: `Vue.observable() has been removed. ` +
1722 `Use \`import { reactive } from "vue"\` from Composition API instead.`,
1723 link: `https://v3.vuejs.org/api/basic-reactivity.html`
1724 },
1725 ["GLOBAL_PRIVATE_UTIL" /* GLOBAL_PRIVATE_UTIL */]: {
1726 message: `Vue.util has been removed. Please refactor to avoid its usage ` +
1727 `since it was an internal API even in Vue 2.`
1728 },
1729 ["CONFIG_SILENT" /* CONFIG_SILENT */]: {
1730 message: `config.silent has been removed because it is not good practice to ` +
1731 `intentionally suppress warnings. You can use your browser console's ` +
1732 `filter features to focus on relevant messages.`
1733 },
1734 ["CONFIG_DEVTOOLS" /* CONFIG_DEVTOOLS */]: {
1735 message: `config.devtools has been removed. To enable devtools for ` +
1736 `production, configure the __VUE_PROD_DEVTOOLS__ compile-time flag.`,
1737 link: `https://github.com/vuejs/vue-next/tree/master/packages/vue#bundler-build-feature-flags`
1738 },
1739 ["CONFIG_KEY_CODES" /* CONFIG_KEY_CODES */]: {
1740 message: `config.keyCodes has been removed. ` +
1741 `In Vue 3, you can directly use the kebab-case key names as v-on modifiers.`,
1742 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1743 },
1744 ["CONFIG_PRODUCTION_TIP" /* CONFIG_PRODUCTION_TIP */]: {
1745 message: `config.productionTip has been removed.`,
1746 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-productiontip-removed`
1747 },
1748 ["CONFIG_IGNORED_ELEMENTS" /* CONFIG_IGNORED_ELEMENTS */]: {
1749 message: () => {
1750 let msg = `config.ignoredElements has been removed.`;
1751 if (isRuntimeOnly()) {
1752 msg += ` Pass the "isCustomElement" option to @vue/compiler-dom instead.`;
1753 }
1754 else {
1755 msg += ` Use config.isCustomElement instead.`;
1756 }
1757 return msg;
1758 },
1759 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-ignoredelements-is-now-config-iscustomelement`
1760 },
1761 ["CONFIG_WHITESPACE" /* CONFIG_WHITESPACE */]: {
1762 // this warning is only relevant in the full build when using runtime
1763 // compilation, so it's put in the runtime compatConfig list.
1764 message: `Vue 3 compiler's whitespace option will default to "condense" instead of ` +
1765 `"preserve". To suppress this warning, provide an explicit value for ` +
1766 `\`config.compilerOptions.whitespace\`.`
1767 },
1768 ["CONFIG_OPTION_MERGE_STRATS" /* CONFIG_OPTION_MERGE_STRATS */]: {
1769 message: `config.optionMergeStrategies no longer exposes internal strategies. ` +
1770 `Use custom merge functions instead.`
1771 },
1772 ["INSTANCE_SET" /* INSTANCE_SET */]: {
1773 message: `vm.$set() has been removed as it is no longer needed in Vue 3. ` +
1774 `Simply use native JavaScript mutations.`
1775 },
1776 ["INSTANCE_DELETE" /* INSTANCE_DELETE */]: {
1777 message: `vm.$delete() has been removed as it is no longer needed in Vue 3. ` +
1778 `Simply use native JavaScript mutations.`
1779 },
1780 ["INSTANCE_DESTROY" /* INSTANCE_DESTROY */]: {
1781 message: `vm.$destroy() has been removed. Use app.unmount() instead.`,
1782 link: `https://v3.vuejs.org/api/application-api.html#unmount`
1783 },
1784 ["INSTANCE_EVENT_EMITTER" /* INSTANCE_EVENT_EMITTER */]: {
1785 message: `vm.$on/$once/$off() have been removed. ` +
1786 `Use an external event emitter library instead.`,
1787 link: `https://v3.vuejs.org/guide/migration/events-api.html`
1788 },
1789 ["INSTANCE_EVENT_HOOKS" /* INSTANCE_EVENT_HOOKS */]: {
1790 message: event => `"${event}" lifecycle events are no longer supported. From templates, ` +
1791 `use the "vnode" prefix instead of "hook:". For example, @${event} ` +
1792 `should be changed to @vnode-${event.slice(5)}. ` +
1793 `From JavaScript, use Composition API to dynamically register lifecycle ` +
1794 `hooks.`,
1795 link: `https://v3.vuejs.org/guide/migration/vnode-lifecycle-events.html`
1796 },
1797 ["INSTANCE_CHILDREN" /* INSTANCE_CHILDREN */]: {
1798 message: `vm.$children has been removed. Consider refactoring your logic ` +
1799 `to avoid relying on direct access to child components.`,
1800 link: `https://v3.vuejs.org/guide/migration/children.html`
1801 },
1802 ["INSTANCE_LISTENERS" /* INSTANCE_LISTENERS */]: {
1803 message: `vm.$listeners has been removed. In Vue 3, parent v-on listeners are ` +
1804 `included in vm.$attrs and it is no longer necessary to separately use ` +
1805 `v-on="$listeners" if you are already using v-bind="$attrs". ` +
1806 `(Note: the Vue 3 behavior only applies if this compat config is disabled)`,
1807 link: `https://v3.vuejs.org/guide/migration/listeners-removed.html`
1808 },
1809 ["INSTANCE_SCOPED_SLOTS" /* INSTANCE_SCOPED_SLOTS */]: {
1810 message: `vm.$scopedSlots has been removed. Use vm.$slots instead.`,
1811 link: `https://v3.vuejs.org/guide/migration/slots-unification.html`
1812 },
1813 ["INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */]: {
1814 message: componentName => `Component <${componentName || 'Anonymous'}> has \`inheritAttrs: false\` but is ` +
1815 `relying on class/style fallthrough from parent. In Vue 3, class/style ` +
1816 `are now included in $attrs and will no longer fallthrough when ` +
1817 `inheritAttrs is false. If you are already using v-bind="$attrs" on ` +
1818 `component root it should render the same end result. ` +
1819 `If you are binding $attrs to a non-root element and expecting ` +
1820 `class/style to fallthrough on root, you will need to now manually bind ` +
1821 `them on root via :class="$attrs.class".`,
1822 link: `https://v3.vuejs.org/guide/migration/attrs-includes-class-style.html`
1823 },
1824 ["OPTIONS_DATA_FN" /* OPTIONS_DATA_FN */]: {
1825 message: `The "data" option can no longer be a plain object. ` +
1826 `Always use a function.`,
1827 link: `https://v3.vuejs.org/guide/migration/data-option.html`
1828 },
1829 ["OPTIONS_DATA_MERGE" /* OPTIONS_DATA_MERGE */]: {
1830 message: (key) => `Detected conflicting key "${key}" when merging data option values. ` +
1831 `In Vue 3, data keys are merged shallowly and will override one another.`,
1832 link: `https://v3.vuejs.org/guide/migration/data-option.html#mixin-merge-behavior-change`
1833 },
1834 ["OPTIONS_BEFORE_DESTROY" /* OPTIONS_BEFORE_DESTROY */]: {
1835 message: `\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`
1836 },
1837 ["OPTIONS_DESTROYED" /* OPTIONS_DESTROYED */]: {
1838 message: `\`destroyed\` has been renamed to \`unmounted\`.`
1839 },
1840 ["WATCH_ARRAY" /* WATCH_ARRAY */]: {
1841 message: `"watch" option or vm.$watch on an array value will no longer ` +
1842 `trigger on array mutation unless the "deep" option is specified. ` +
1843 `If current usage is intended, you can disable the compat behavior and ` +
1844 `suppress this warning with:` +
1845 `\n\n configureCompat({ ${"WATCH_ARRAY" /* WATCH_ARRAY */}: false })\n`,
1846 link: `https://v3.vuejs.org/guide/migration/watch.html`
1847 },
1848 ["PROPS_DEFAULT_THIS" /* PROPS_DEFAULT_THIS */]: {
1849 message: (key) => `props default value function no longer has access to "this". The compat ` +
1850 `build only offers access to this.$options.` +
1851 `(found in prop "${key}")`,
1852 link: `https://v3.vuejs.org/guide/migration/props-default-this.html`
1853 },
1854 ["CUSTOM_DIR" /* CUSTOM_DIR */]: {
1855 message: (legacyHook, newHook) => `Custom directive hook "${legacyHook}" has been removed. ` +
1856 `Use "${newHook}" instead.`,
1857 link: `https://v3.vuejs.org/guide/migration/custom-directives.html`
1858 },
1859 ["V_FOR_REF" /* V_FOR_REF */]: {
1860 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
1861 `Consider using function refs or refactor to avoid ref usage altogether.`,
1862 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
1863 },
1864 ["V_ON_KEYCODE_MODIFIER" /* V_ON_KEYCODE_MODIFIER */]: {
1865 message: `Using keyCode as v-on modifier is no longer supported. ` +
1866 `Use kebab-case key name modifiers instead.`,
1867 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1868 },
1869 ["ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */]: {
1870 message: (name) => `Attribute "${name}" with v-bind value \`false\` will render ` +
1871 `${name}="false" instead of removing it in Vue 3. To remove the attribute, ` +
1872 `use \`null\` or \`undefined\` instead. If the usage is intended, ` +
1873 `you can disable the compat behavior and suppress this warning with:` +
1874 `\n\n configureCompat({ ${"ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */}: false })\n`,
1875 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
1876 },
1877 ["ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */]: {
1878 message: (name, value, coerced) => `Enumerated attribute "${name}" with v-bind value \`${value}\` will ` +
1879 `${value === null ? `be removed` : `render the value as-is`} instead of coercing the value to "${coerced}" in Vue 3. ` +
1880 `Always use explicit "true" or "false" values for enumerated attributes. ` +
1881 `If the usage is intended, ` +
1882 `you can disable the compat behavior and suppress this warning with:` +
1883 `\n\n configureCompat({ ${"ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */}: false })\n`,
1884 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
1885 },
1886 ["TRANSITION_CLASSES" /* TRANSITION_CLASSES */]: {
1887 message: `` // this feature cannot be runtime-detected
1888 },
1889 ["TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */]: {
1890 message: `<TransitionGroup> no longer renders a root <span> element by ` +
1891 `default if no "tag" prop is specified. If you do not rely on the span ` +
1892 `for styling, you can disable the compat behavior and suppress this ` +
1893 `warning with:` +
1894 `\n\n configureCompat({ ${"TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */}: false })\n`,
1895 link: `https://v3.vuejs.org/guide/migration/transition-group.html`
1896 },
1897 ["COMPONENT_ASYNC" /* COMPONENT_ASYNC */]: {
1898 message: (comp) => {
1899 const name = getComponentName(comp);
1900 return (`Async component${name ? ` <${name}>` : `s`} should be explicitly created via \`defineAsyncComponent()\` ` +
1901 `in Vue 3. Plain functions will be treated as functional components in ` +
1902 `non-compat build. If you have already migrated all async component ` +
1903 `usage and intend to use plain functions for functional components, ` +
1904 `you can disable the compat behavior and suppress this ` +
1905 `warning with:` +
1906 `\n\n configureCompat({ ${"COMPONENT_ASYNC" /* COMPONENT_ASYNC */}: false })\n`);
1907 },
1908 link: `https://v3.vuejs.org/guide/migration/async-components.html`
1909 },
1910 ["COMPONENT_FUNCTIONAL" /* COMPONENT_FUNCTIONAL */]: {
1911 message: (comp) => {
1912 const name = getComponentName(comp);
1913 return (`Functional component${name ? ` <${name}>` : `s`} should be defined as a plain function in Vue 3. The "functional" ` +
1914 `option has been removed. NOTE: Before migrating to use plain ` +
1915 `functions for functional components, first make sure that all async ` +
1916 `components usage have been migrated and its compat behavior has ` +
1917 `been disabled.`);
1918 },
1919 link: `https://v3.vuejs.org/guide/migration/functional-components.html`
1920 },
1921 ["COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */]: {
1922 message: (comp) => {
1923 const configMsg = `opt-in to ` +
1924 `Vue 3 behavior on a per-component basis with \`compatConfig: { ${"COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */}: false }\`.`;
1925 if (comp.props &&
1926 (isArray(comp.props)
1927 ? comp.props.includes('modelValue')
1928 : hasOwn(comp.props, 'modelValue'))) {
1929 return (`Component delcares "modelValue" prop, which is Vue 3 usage, but ` +
1930 `is running under Vue 2 compat v-model behavior. You can ${configMsg}`);
1931 }
1932 return (`v-model usage on component has changed in Vue 3. Component that expects ` +
1933 `to work with v-model should now use the "modelValue" prop and emit the ` +
1934 `"update:modelValue" event. You can update the usage and then ${configMsg}`);
1935 },
1936 link: `https://v3.vuejs.org/guide/migration/v-model.html`
1937 },
1938 ["RENDER_FUNCTION" /* RENDER_FUNCTION */]: {
1939 message: `Vue 3's render function API has changed. ` +
1940 `You can opt-in to the new API with:` +
1941 `\n\n configureCompat({ ${"RENDER_FUNCTION" /* RENDER_FUNCTION */}: false })\n` +
1942 `\n (This can also be done per-component via the "compatConfig" option.)`,
1943 link: `https://v3.vuejs.org/guide/migration/render-function-api.html`
1944 },
1945 ["FILTERS" /* FILTERS */]: {
1946 message: `filters have been removed in Vue 3. ` +
1947 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
1948 `Use method calls or computed properties instead.`,
1949 link: `https://v3.vuejs.org/guide/migration/filters.html`
1950 },
1951 ["PRIVATE_APIS" /* PRIVATE_APIS */]: {
1952 message: name => `"${name}" is a Vue 2 private API that no longer exists in Vue 3. ` +
1953 `If you are seeing this warning only due to a dependency, you can ` +
1954 `suppress this warning via { PRIVATE_APIS: 'supress-warning' }.`
1955 }
1956};
1957const instanceWarned = Object.create(null);
1958const warnCount = Object.create(null);
1959function warnDeprecation(key, instance, ...args) {
1960 instance = instance || getCurrentInstance();
1961 // check user config
1962 const config = getCompatConfigForKey(key, instance);
1963 if (config === 'suppress-warning') {
1964 return;
1965 }
1966 const dupKey = key + args.join('');
1967 let compId = instance && formatComponentName(instance, instance.type);
1968 if (compId === 'Anonymous' && instance) {
1969 compId = instance.uid;
1970 }
1971 // skip if the same warning is emitted for the same component type
1972 const componentDupKey = dupKey + compId;
1973 if (componentDupKey in instanceWarned) {
1974 return;
1975 }
1976 instanceWarned[componentDupKey] = true;
1977 // same warning, but different component. skip the long message and just
1978 // log the key and count.
1979 if (dupKey in warnCount) {
1980 warn$1(`(deprecation ${key}) (${++warnCount[dupKey] + 1})`);
1981 return;
1982 }
1983 warnCount[dupKey] = 0;
1984 const { message, link } = deprecationData[key];
1985 warn$1(`(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`);
1986 if (!isCompatEnabled(key, instance, true)) {
1987 console.error(`^ The above deprecation's compat behavior is disabled and will likely ` +
1988 `lead to runtime errors.`);
1989 }
1990}
1991const globalCompatConfig = {
1992 MODE: 2
1993};
1994function getCompatConfigForKey(key, instance) {
1995 const instanceConfig = instance && instance.type.compatConfig;
1996 if (instanceConfig && key in instanceConfig) {
1997 return instanceConfig[key];
1998 }
1999 return globalCompatConfig[key];
2000}
2001function isCompatEnabled(key, instance, enableForBuiltIn = false) {
2002 // skip compat for built-in components
2003 if (!enableForBuiltIn && instance && instance.type.__isBuiltIn) {
2004 return false;
2005 }
2006 const rawMode = getCompatConfigForKey('MODE', instance) || 2;
2007 const val = getCompatConfigForKey(key, instance);
2008 const mode = isFunction(rawMode)
2009 ? rawMode(instance && instance.type)
2010 : rawMode;
2011 if (mode === 2) {
2012 return val !== false;
2013 }
2014 else {
2015 return val === true || val === 'suppress-warning';
2016 }
2017}
2018
2019function emit(instance, event, ...rawArgs) {
2020 const props = instance.vnode.props || EMPTY_OBJ;
2021 {
2022 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2023 if (emitsOptions) {
2024 if (!(event in emitsOptions) &&
2025 !(false )) {
2026 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2027 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2028 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2029 }
2030 }
2031 else {
2032 const validator = emitsOptions[event];
2033 if (isFunction(validator)) {
2034 const isValid = validator(...rawArgs);
2035 if (!isValid) {
2036 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2037 }
2038 }
2039 }
2040 }
2041 }
2042 let args = rawArgs;
2043 const isModelListener = event.startsWith('update:');
2044 // for v-model update:xxx events, apply modifiers on args
2045 const modelArg = isModelListener && event.slice(7);
2046 if (modelArg && modelArg in props) {
2047 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2048 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2049 if (trim) {
2050 args = rawArgs.map(a => a.trim());
2051 }
2052 else if (number) {
2053 args = rawArgs.map(toNumber);
2054 }
2055 }
2056 {
2057 devtoolsComponentEmit(instance, event, args);
2058 }
2059 {
2060 const lowerCaseEvent = event.toLowerCase();
2061 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2062 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2063 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2064 `Note that HTML attributes are case-insensitive and you cannot use ` +
2065 `v-on to listen to camelCase events when using in-DOM templates. ` +
2066 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2067 }
2068 }
2069 let handlerName;
2070 let handler = props[(handlerName = toHandlerKey(event))] ||
2071 // also try camelCase event handler (#2249)
2072 props[(handlerName = toHandlerKey(camelize(event)))];
2073 // for v-model update:xxx events, also trigger kebab-case equivalent
2074 // for props passed via kebab-case
2075 if (!handler && isModelListener) {
2076 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2077 }
2078 if (handler) {
2079 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2080 }
2081 const onceHandler = props[handlerName + `Once`];
2082 if (onceHandler) {
2083 if (!instance.emitted) {
2084 instance.emitted = {};
2085 }
2086 else if (instance.emitted[handlerName]) {
2087 return;
2088 }
2089 instance.emitted[handlerName] = true;
2090 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2091 }
2092}
2093function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2094 const cache = appContext.emitsCache;
2095 const cached = cache.get(comp);
2096 if (cached !== undefined) {
2097 return cached;
2098 }
2099 const raw = comp.emits;
2100 let normalized = {};
2101 // apply mixin/extends props
2102 let hasExtends = false;
2103 if (!isFunction(comp)) {
2104 const extendEmits = (raw) => {
2105 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2106 if (normalizedFromExtend) {
2107 hasExtends = true;
2108 extend(normalized, normalizedFromExtend);
2109 }
2110 };
2111 if (!asMixin && appContext.mixins.length) {
2112 appContext.mixins.forEach(extendEmits);
2113 }
2114 if (comp.extends) {
2115 extendEmits(comp.extends);
2116 }
2117 if (comp.mixins) {
2118 comp.mixins.forEach(extendEmits);
2119 }
2120 }
2121 if (!raw && !hasExtends) {
2122 cache.set(comp, null);
2123 return null;
2124 }
2125 if (isArray(raw)) {
2126 raw.forEach(key => (normalized[key] = null));
2127 }
2128 else {
2129 extend(normalized, raw);
2130 }
2131 cache.set(comp, normalized);
2132 return normalized;
2133}
2134// Check if an incoming prop key is a declared emit event listener.
2135// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2136// both considered matched listeners.
2137function isEmitListener(options, key) {
2138 if (!options || !isOn(key)) {
2139 return false;
2140 }
2141 key = key.slice(2).replace(/Once$/, '');
2142 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2143 hasOwn(options, hyphenate(key)) ||
2144 hasOwn(options, key));
2145}
2146
2147/**
2148 * mark the current rendering instance for asset resolution (e.g.
2149 * resolveComponent, resolveDirective) during render
2150 */
2151let currentRenderingInstance = null;
2152let currentScopeId = null;
2153/**
2154 * Note: rendering calls maybe nested. The function returns the parent rendering
2155 * instance if present, which should be restored after the render is done:
2156 *
2157 * ```js
2158 * const prev = setCurrentRenderingInstance(i)
2159 * // ...render
2160 * setCurrentRenderingInstance(prev)
2161 * ```
2162 */
2163function setCurrentRenderingInstance(instance) {
2164 const prev = currentRenderingInstance;
2165 currentRenderingInstance = instance;
2166 currentScopeId = (instance && instance.type.__scopeId) || null;
2167 return prev;
2168}
2169/**
2170 * Set scope id when creating hoisted vnodes.
2171 * @private compiler helper
2172 */
2173function pushScopeId(id) {
2174 currentScopeId = id;
2175}
2176/**
2177 * Technically we no longer need this after 3.0.8 but we need to keep the same
2178 * API for backwards compat w/ code generated by compilers.
2179 * @private
2180 */
2181function popScopeId() {
2182 currentScopeId = null;
2183}
2184/**
2185 * Only for backwards compat
2186 * @private
2187 */
2188const withScopeId = (_id) => withCtx;
2189/**
2190 * Wrap a slot function to memoize current rendering instance
2191 * @private compiler helper
2192 */
2193function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2194) {
2195 if (!ctx)
2196 return fn;
2197 // already normalized
2198 if (fn._n) {
2199 return fn;
2200 }
2201 const renderFnWithContext = (...args) => {
2202 // If a user calls a compiled slot inside a template expression (#1745), it
2203 // can mess up block tracking, so by default we disable block tracking and
2204 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2205 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2206 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2207 if (renderFnWithContext._d) {
2208 setBlockTracking(-1);
2209 }
2210 const prevInstance = setCurrentRenderingInstance(ctx);
2211 const res = fn(...args);
2212 setCurrentRenderingInstance(prevInstance);
2213 if (renderFnWithContext._d) {
2214 setBlockTracking(1);
2215 }
2216 {
2217 devtoolsComponentUpdated(ctx);
2218 }
2219 return res;
2220 };
2221 // mark normalized to avoid duplicated wrapping
2222 renderFnWithContext._n = true;
2223 // mark this as compiled by default
2224 // this is used in vnode.ts -> normalizeChildren() to set the slot
2225 // rendering flag.
2226 renderFnWithContext._c = true;
2227 // disable block tracking by default
2228 renderFnWithContext._d = true;
2229 return renderFnWithContext;
2230}
2231
2232/**
2233 * dev only flag to track whether $attrs was used during render.
2234 * If $attrs was used during render then the warning for failed attrs
2235 * fallthrough can be suppressed.
2236 */
2237let accessedAttrs = false;
2238function markAttrsAccessed() {
2239 accessedAttrs = true;
2240}
2241function renderComponentRoot(instance) {
2242 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2243 let result;
2244 const prev = setCurrentRenderingInstance(instance);
2245 {
2246 accessedAttrs = false;
2247 }
2248 try {
2249 let fallthroughAttrs;
2250 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2251 // withProxy is a proxy with a different `has` trap only for
2252 // runtime-compiled render functions using `with` block.
2253 const proxyToUse = withProxy || proxy;
2254 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2255 fallthroughAttrs = attrs;
2256 }
2257 else {
2258 // functional
2259 const render = Component;
2260 // in dev, mark attrs accessed if optional props (attrs === props)
2261 if (true && attrs === props) {
2262 markAttrsAccessed();
2263 }
2264 result = normalizeVNode(render.length > 1
2265 ? render(props, true
2266 ? {
2267 get attrs() {
2268 markAttrsAccessed();
2269 return attrs;
2270 },
2271 slots,
2272 emit
2273 }
2274 : { attrs, slots, emit })
2275 : render(props, null /* we know it doesn't need it */));
2276 fallthroughAttrs = Component.props
2277 ? attrs
2278 : getFunctionalFallthrough(attrs);
2279 }
2280 // attr merging
2281 // in dev mode, comments are preserved, and it's possible for a template
2282 // to have comments along side the root element which makes it a fragment
2283 let root = result;
2284 let setRoot = undefined;
2285 if (true &&
2286 result.patchFlag > 0 &&
2287 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2288 ;
2289 [root, setRoot] = getChildRoot(result);
2290 }
2291 if (fallthroughAttrs && inheritAttrs !== false) {
2292 const keys = Object.keys(fallthroughAttrs);
2293 const { shapeFlag } = root;
2294 if (keys.length) {
2295 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2296 if (propsOptions && keys.some(isModelListener)) {
2297 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2298 // prop, it indicates this component expects to handle v-model and
2299 // it should not fallthrough.
2300 // related: #1543, #1643, #1989
2301 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2302 }
2303 root = cloneVNode(root, fallthroughAttrs);
2304 }
2305 else if (true && !accessedAttrs && root.type !== Comment) {
2306 const allAttrs = Object.keys(attrs);
2307 const eventAttrs = [];
2308 const extraAttrs = [];
2309 for (let i = 0, l = allAttrs.length; i < l; i++) {
2310 const key = allAttrs[i];
2311 if (isOn(key)) {
2312 // ignore v-model handlers when they fail to fallthrough
2313 if (!isModelListener(key)) {
2314 // remove `on`, lowercase first letter to reflect event casing
2315 // accurately
2316 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2317 }
2318 }
2319 else {
2320 extraAttrs.push(key);
2321 }
2322 }
2323 if (extraAttrs.length) {
2324 warn$1(`Extraneous non-props attributes (` +
2325 `${extraAttrs.join(', ')}) ` +
2326 `were passed to component but could not be automatically inherited ` +
2327 `because component renders fragment or text root nodes.`);
2328 }
2329 if (eventAttrs.length) {
2330 warn$1(`Extraneous non-emits event listeners (` +
2331 `${eventAttrs.join(', ')}) ` +
2332 `were passed to component but could not be automatically inherited ` +
2333 `because component renders fragment or text root nodes. ` +
2334 `If the listener is intended to be a component custom event listener only, ` +
2335 `declare it using the "emits" option.`);
2336 }
2337 }
2338 }
2339 }
2340 if (false &&
2341 isCompatEnabled("INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */, instance) &&
2342 vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */ &&
2343 root.shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) ;
2344 // inherit directives
2345 if (vnode.dirs) {
2346 if (true && !isElementRoot(root)) {
2347 warn$1(`Runtime directive used on component with non-element root node. ` +
2348 `The directives will not function as intended.`);
2349 }
2350 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2351 }
2352 // inherit transition data
2353 if (vnode.transition) {
2354 if (true && !isElementRoot(root)) {
2355 warn$1(`Component inside <Transition> renders non-element root node ` +
2356 `that cannot be animated.`);
2357 }
2358 root.transition = vnode.transition;
2359 }
2360 if (true && setRoot) {
2361 setRoot(root);
2362 }
2363 else {
2364 result = root;
2365 }
2366 }
2367 catch (err) {
2368 blockStack.length = 0;
2369 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2370 result = createVNode(Comment);
2371 }
2372 setCurrentRenderingInstance(prev);
2373 return result;
2374}
2375/**
2376 * dev only
2377 * In dev mode, template root level comments are rendered, which turns the
2378 * template into a fragment root, but we need to locate the single element
2379 * root for attrs and scope id processing.
2380 */
2381const getChildRoot = (vnode) => {
2382 const rawChildren = vnode.children;
2383 const dynamicChildren = vnode.dynamicChildren;
2384 const childRoot = filterSingleRoot(rawChildren);
2385 if (!childRoot) {
2386 return [vnode, undefined];
2387 }
2388 const index = rawChildren.indexOf(childRoot);
2389 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2390 const setRoot = (updatedRoot) => {
2391 rawChildren[index] = updatedRoot;
2392 if (dynamicChildren) {
2393 if (dynamicIndex > -1) {
2394 dynamicChildren[dynamicIndex] = updatedRoot;
2395 }
2396 else if (updatedRoot.patchFlag > 0) {
2397 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2398 }
2399 }
2400 };
2401 return [normalizeVNode(childRoot), setRoot];
2402};
2403function filterSingleRoot(children) {
2404 let singleRoot;
2405 for (let i = 0; i < children.length; i++) {
2406 const child = children[i];
2407 if (isVNode(child)) {
2408 // ignore user comment
2409 if (child.type !== Comment || child.children === 'v-if') {
2410 if (singleRoot) {
2411 // has more than 1 non-comment child, return now
2412 return;
2413 }
2414 else {
2415 singleRoot = child;
2416 }
2417 }
2418 }
2419 else {
2420 return;
2421 }
2422 }
2423 return singleRoot;
2424}
2425const getFunctionalFallthrough = (attrs) => {
2426 let res;
2427 for (const key in attrs) {
2428 if (key === 'class' || key === 'style' || isOn(key)) {
2429 (res || (res = {}))[key] = attrs[key];
2430 }
2431 }
2432 return res;
2433};
2434const filterModelListeners = (attrs, props) => {
2435 const res = {};
2436 for (const key in attrs) {
2437 if (!isModelListener(key) || !(key.slice(9) in props)) {
2438 res[key] = attrs[key];
2439 }
2440 }
2441 return res;
2442};
2443const isElementRoot = (vnode) => {
2444 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2445 vnode.type === Comment // potential v-if branch switch
2446 );
2447};
2448function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2449 const { props: prevProps, children: prevChildren, component } = prevVNode;
2450 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2451 const emits = component.emitsOptions;
2452 // Parent component's render function was hot-updated. Since this may have
2453 // caused the child component's slots content to have changed, we need to
2454 // force the child to update as well.
2455 if ((prevChildren || nextChildren) && isHmrUpdating) {
2456 return true;
2457 }
2458 // force child update for runtime directive or transition on component vnode.
2459 if (nextVNode.dirs || nextVNode.transition) {
2460 return true;
2461 }
2462 if (optimized && patchFlag >= 0) {
2463 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2464 // slot content that references values that might have changed,
2465 // e.g. in a v-for
2466 return true;
2467 }
2468 if (patchFlag & 16 /* FULL_PROPS */) {
2469 if (!prevProps) {
2470 return !!nextProps;
2471 }
2472 // presence of this flag indicates props are always non-null
2473 return hasPropsChanged(prevProps, nextProps, emits);
2474 }
2475 else if (patchFlag & 8 /* PROPS */) {
2476 const dynamicProps = nextVNode.dynamicProps;
2477 for (let i = 0; i < dynamicProps.length; i++) {
2478 const key = dynamicProps[i];
2479 if (nextProps[key] !== prevProps[key] &&
2480 !isEmitListener(emits, key)) {
2481 return true;
2482 }
2483 }
2484 }
2485 }
2486 else {
2487 // this path is only taken by manually written render functions
2488 // so presence of any children leads to a forced update
2489 if (prevChildren || nextChildren) {
2490 if (!nextChildren || !nextChildren.$stable) {
2491 return true;
2492 }
2493 }
2494 if (prevProps === nextProps) {
2495 return false;
2496 }
2497 if (!prevProps) {
2498 return !!nextProps;
2499 }
2500 if (!nextProps) {
2501 return true;
2502 }
2503 return hasPropsChanged(prevProps, nextProps, emits);
2504 }
2505 return false;
2506}
2507function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2508 const nextKeys = Object.keys(nextProps);
2509 if (nextKeys.length !== Object.keys(prevProps).length) {
2510 return true;
2511 }
2512 for (let i = 0; i < nextKeys.length; i++) {
2513 const key = nextKeys[i];
2514 if (nextProps[key] !== prevProps[key] &&
2515 !isEmitListener(emitsOptions, key)) {
2516 return true;
2517 }
2518 }
2519 return false;
2520}
2521function updateHOCHostEl({ vnode, parent }, el // HostNode
2522) {
2523 while (parent && parent.subTree === vnode) {
2524 (vnode = parent.vnode).el = el;
2525 parent = parent.parent;
2526 }
2527}
2528
2529const isSuspense = (type) => type.__isSuspense;
2530// Suspense exposes a component-like API, and is treated like a component
2531// in the compiler, but internally it's a special built-in type that hooks
2532// directly into the renderer.
2533const SuspenseImpl = {
2534 name: 'Suspense',
2535 // In order to make Suspense tree-shakable, we need to avoid importing it
2536 // directly in the renderer. The renderer checks for the __isSuspense flag
2537 // on a vnode's type and calls the `process` method, passing in renderer
2538 // internals.
2539 __isSuspense: true,
2540 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2541 // platform-specific impl passed from renderer
2542 rendererInternals) {
2543 if (n1 == null) {
2544 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2545 }
2546 else {
2547 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2548 }
2549 },
2550 hydrate: hydrateSuspense,
2551 create: createSuspenseBoundary,
2552 normalize: normalizeSuspenseChildren
2553};
2554// Force-casted public typing for h and TSX props inference
2555const Suspense = (SuspenseImpl );
2556function triggerEvent(vnode, name) {
2557 const eventListener = vnode.props && vnode.props[name];
2558 if (isFunction(eventListener)) {
2559 eventListener();
2560 }
2561}
2562function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2563 const { p: patch, o: { createElement } } = rendererInternals;
2564 const hiddenContainer = createElement('div');
2565 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2566 // start mounting the content subtree in an off-dom container
2567 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2568 // now check if we have encountered any async deps
2569 if (suspense.deps > 0) {
2570 // has async
2571 // invoke @fallback event
2572 triggerEvent(vnode, 'onPending');
2573 triggerEvent(vnode, 'onFallback');
2574 // mount the fallback tree
2575 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2576 isSVG, slotScopeIds);
2577 setActiveBranch(suspense, vnode.ssFallback);
2578 }
2579 else {
2580 // Suspense has no async deps. Just resolve.
2581 suspense.resolve();
2582 }
2583}
2584function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2585 const suspense = (n2.suspense = n1.suspense);
2586 suspense.vnode = n2;
2587 n2.el = n1.el;
2588 const newBranch = n2.ssContent;
2589 const newFallback = n2.ssFallback;
2590 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2591 if (pendingBranch) {
2592 suspense.pendingBranch = newBranch;
2593 if (isSameVNodeType(newBranch, pendingBranch)) {
2594 // same root type but content may have changed.
2595 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2596 if (suspense.deps <= 0) {
2597 suspense.resolve();
2598 }
2599 else if (isInFallback) {
2600 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2601 isSVG, slotScopeIds, optimized);
2602 setActiveBranch(suspense, newFallback);
2603 }
2604 }
2605 else {
2606 // toggled before pending tree is resolved
2607 suspense.pendingId++;
2608 if (isHydrating) {
2609 // if toggled before hydration is finished, the current DOM tree is
2610 // no longer valid. set it as the active branch so it will be unmounted
2611 // when resolved
2612 suspense.isHydrating = false;
2613 suspense.activeBranch = pendingBranch;
2614 }
2615 else {
2616 unmount(pendingBranch, parentComponent, suspense);
2617 }
2618 // increment pending ID. this is used to invalidate async callbacks
2619 // reset suspense state
2620 suspense.deps = 0;
2621 // discard effects from pending branch
2622 suspense.effects.length = 0;
2623 // discard previous container
2624 suspense.hiddenContainer = createElement('div');
2625 if (isInFallback) {
2626 // already in fallback state
2627 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2628 if (suspense.deps <= 0) {
2629 suspense.resolve();
2630 }
2631 else {
2632 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2633 isSVG, slotScopeIds, optimized);
2634 setActiveBranch(suspense, newFallback);
2635 }
2636 }
2637 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2638 // toggled "back" to current active branch
2639 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2640 // force resolve
2641 suspense.resolve(true);
2642 }
2643 else {
2644 // switched to a 3rd branch
2645 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2646 if (suspense.deps <= 0) {
2647 suspense.resolve();
2648 }
2649 }
2650 }
2651 }
2652 else {
2653 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2654 // root did not change, just normal patch
2655 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2656 setActiveBranch(suspense, newBranch);
2657 }
2658 else {
2659 // root node toggled
2660 // invoke @pending event
2661 triggerEvent(n2, 'onPending');
2662 // mount pending branch in off-dom container
2663 suspense.pendingBranch = newBranch;
2664 suspense.pendingId++;
2665 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2666 if (suspense.deps <= 0) {
2667 // incoming branch has no async deps, resolve now.
2668 suspense.resolve();
2669 }
2670 else {
2671 const { timeout, pendingId } = suspense;
2672 if (timeout > 0) {
2673 setTimeout(() => {
2674 if (suspense.pendingId === pendingId) {
2675 suspense.fallback(newFallback);
2676 }
2677 }, timeout);
2678 }
2679 else if (timeout === 0) {
2680 suspense.fallback(newFallback);
2681 }
2682 }
2683 }
2684 }
2685}
2686let hasWarned = false;
2687function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2688 /* istanbul ignore if */
2689 if (!hasWarned) {
2690 hasWarned = true;
2691 // @ts-ignore `console.info` cannot be null error
2692 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2693 }
2694 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2695 const timeout = toNumber(vnode.props && vnode.props.timeout);
2696 const suspense = {
2697 vnode,
2698 parent,
2699 parentComponent,
2700 isSVG,
2701 container,
2702 hiddenContainer,
2703 anchor,
2704 deps: 0,
2705 pendingId: 0,
2706 timeout: typeof timeout === 'number' ? timeout : -1,
2707 activeBranch: null,
2708 pendingBranch: null,
2709 isInFallback: true,
2710 isHydrating,
2711 isUnmounted: false,
2712 effects: [],
2713 resolve(resume = false) {
2714 {
2715 if (!resume && !suspense.pendingBranch) {
2716 throw new Error(`suspense.resolve() is called without a pending branch.`);
2717 }
2718 if (suspense.isUnmounted) {
2719 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2720 }
2721 }
2722 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2723 if (suspense.isHydrating) {
2724 suspense.isHydrating = false;
2725 }
2726 else if (!resume) {
2727 const delayEnter = activeBranch &&
2728 pendingBranch.transition &&
2729 pendingBranch.transition.mode === 'out-in';
2730 if (delayEnter) {
2731 activeBranch.transition.afterLeave = () => {
2732 if (pendingId === suspense.pendingId) {
2733 move(pendingBranch, container, anchor, 0 /* ENTER */);
2734 }
2735 };
2736 }
2737 // this is initial anchor on mount
2738 let { anchor } = suspense;
2739 // unmount current active tree
2740 if (activeBranch) {
2741 // if the fallback tree was mounted, it may have been moved
2742 // as part of a parent suspense. get the latest anchor for insertion
2743 anchor = next(activeBranch);
2744 unmount(activeBranch, parentComponent, suspense, true);
2745 }
2746 if (!delayEnter) {
2747 // move content from off-dom container to actual container
2748 move(pendingBranch, container, anchor, 0 /* ENTER */);
2749 }
2750 }
2751 setActiveBranch(suspense, pendingBranch);
2752 suspense.pendingBranch = null;
2753 suspense.isInFallback = false;
2754 // flush buffered effects
2755 // check if there is a pending parent suspense
2756 let parent = suspense.parent;
2757 let hasUnresolvedAncestor = false;
2758 while (parent) {
2759 if (parent.pendingBranch) {
2760 // found a pending parent suspense, merge buffered post jobs
2761 // into that parent
2762 parent.effects.push(...effects);
2763 hasUnresolvedAncestor = true;
2764 break;
2765 }
2766 parent = parent.parent;
2767 }
2768 // no pending parent suspense, flush all jobs
2769 if (!hasUnresolvedAncestor) {
2770 queuePostFlushCb(effects);
2771 }
2772 suspense.effects = [];
2773 // invoke @resolve event
2774 triggerEvent(vnode, 'onResolve');
2775 },
2776 fallback(fallbackVNode) {
2777 if (!suspense.pendingBranch) {
2778 return;
2779 }
2780 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2781 // invoke @fallback event
2782 triggerEvent(vnode, 'onFallback');
2783 const anchor = next(activeBranch);
2784 const mountFallback = () => {
2785 if (!suspense.isInFallback) {
2786 return;
2787 }
2788 // mount the fallback tree
2789 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2790 isSVG, slotScopeIds, optimized);
2791 setActiveBranch(suspense, fallbackVNode);
2792 };
2793 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2794 if (delayEnter) {
2795 activeBranch.transition.afterLeave = mountFallback;
2796 }
2797 suspense.isInFallback = true;
2798 // unmount current active branch
2799 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2800 true // shouldRemove
2801 );
2802 if (!delayEnter) {
2803 mountFallback();
2804 }
2805 },
2806 move(container, anchor, type) {
2807 suspense.activeBranch &&
2808 move(suspense.activeBranch, container, anchor, type);
2809 suspense.container = container;
2810 },
2811 next() {
2812 return suspense.activeBranch && next(suspense.activeBranch);
2813 },
2814 registerDep(instance, setupRenderEffect) {
2815 const isInPendingSuspense = !!suspense.pendingBranch;
2816 if (isInPendingSuspense) {
2817 suspense.deps++;
2818 }
2819 const hydratedEl = instance.vnode.el;
2820 instance
2821 .asyncDep.catch(err => {
2822 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2823 })
2824 .then(asyncSetupResult => {
2825 // retry when the setup() promise resolves.
2826 // component may have been unmounted before resolve.
2827 if (instance.isUnmounted ||
2828 suspense.isUnmounted ||
2829 suspense.pendingId !== instance.suspenseId) {
2830 return;
2831 }
2832 // retry from this component
2833 instance.asyncResolved = true;
2834 const { vnode } = instance;
2835 {
2836 pushWarningContext(vnode);
2837 }
2838 handleSetupResult(instance, asyncSetupResult, false);
2839 if (hydratedEl) {
2840 // vnode may have been replaced if an update happened before the
2841 // async dep is resolved.
2842 vnode.el = hydratedEl;
2843 }
2844 const placeholder = !hydratedEl && instance.subTree.el;
2845 setupRenderEffect(instance, vnode,
2846 // component may have been moved before resolve.
2847 // if this is not a hydration, instance.subTree will be the comment
2848 // placeholder.
2849 parentNode(hydratedEl || instance.subTree.el),
2850 // anchor will not be used if this is hydration, so only need to
2851 // consider the comment placeholder case.
2852 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
2853 if (placeholder) {
2854 remove(placeholder);
2855 }
2856 updateHOCHostEl(instance, vnode.el);
2857 {
2858 popWarningContext();
2859 }
2860 // only decrease deps count if suspense is not already resolved
2861 if (isInPendingSuspense && --suspense.deps === 0) {
2862 suspense.resolve();
2863 }
2864 });
2865 },
2866 unmount(parentSuspense, doRemove) {
2867 suspense.isUnmounted = true;
2868 if (suspense.activeBranch) {
2869 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
2870 }
2871 if (suspense.pendingBranch) {
2872 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
2873 }
2874 }
2875 };
2876 return suspense;
2877}
2878function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
2879 /* eslint-disable no-restricted-globals */
2880 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
2881 // there are two possible scenarios for server-rendered suspense:
2882 // - success: ssr content should be fully resolved
2883 // - failure: ssr content should be the fallback branch.
2884 // however, on the client we don't really know if it has failed or not
2885 // attempt to hydrate the DOM assuming it has succeeded, but we still
2886 // need to construct a suspense boundary first
2887 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
2888 if (suspense.deps === 0) {
2889 suspense.resolve();
2890 }
2891 return result;
2892 /* eslint-enable no-restricted-globals */
2893}
2894function normalizeSuspenseChildren(vnode) {
2895 const { shapeFlag, children } = vnode;
2896 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
2897 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
2898 vnode.ssFallback = isSlotChildren
2899 ? normalizeSuspenseSlot(children.fallback)
2900 : createVNode(Comment);
2901}
2902function normalizeSuspenseSlot(s) {
2903 let block;
2904 if (isFunction(s)) {
2905 const isCompiledSlot = s._c;
2906 if (isCompiledSlot) {
2907 // disableTracking: false
2908 // allow block tracking for compiled slots
2909 // (see ./componentRenderContext.ts)
2910 s._d = false;
2911 openBlock();
2912 }
2913 s = s();
2914 if (isCompiledSlot) {
2915 s._d = true;
2916 block = currentBlock;
2917 closeBlock();
2918 }
2919 }
2920 if (isArray(s)) {
2921 const singleChild = filterSingleRoot(s);
2922 if (!singleChild) {
2923 warn$1(`<Suspense> slots expect a single root node.`);
2924 }
2925 s = singleChild;
2926 }
2927 s = normalizeVNode(s);
2928 if (block && !s.dynamicChildren) {
2929 s.dynamicChildren = block.filter(c => c !== s);
2930 }
2931 return s;
2932}
2933function queueEffectWithSuspense(fn, suspense) {
2934 if (suspense && suspense.pendingBranch) {
2935 if (isArray(fn)) {
2936 suspense.effects.push(...fn);
2937 }
2938 else {
2939 suspense.effects.push(fn);
2940 }
2941 }
2942 else {
2943 queuePostFlushCb(fn);
2944 }
2945}
2946function setActiveBranch(suspense, branch) {
2947 suspense.activeBranch = branch;
2948 const { vnode, parentComponent } = suspense;
2949 const el = (vnode.el = branch.el);
2950 // in case suspense is the root node of a component,
2951 // recursively update the HOC el
2952 if (parentComponent && parentComponent.subTree === vnode) {
2953 parentComponent.vnode.el = el;
2954 updateHOCHostEl(parentComponent, el);
2955 }
2956}
2957
2958function provide(key, value) {
2959 if (!currentInstance) {
2960 {
2961 warn$1(`provide() can only be used inside setup().`);
2962 }
2963 }
2964 else {
2965 let provides = currentInstance.provides;
2966 // by default an instance inherits its parent's provides object
2967 // but when it needs to provide values of its own, it creates its
2968 // own provides object using parent provides object as prototype.
2969 // this way in `inject` we can simply look up injections from direct
2970 // parent and let the prototype chain do the work.
2971 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
2972 if (parentProvides === provides) {
2973 provides = currentInstance.provides = Object.create(parentProvides);
2974 }
2975 // TS doesn't allow symbol as index type
2976 provides[key] = value;
2977 }
2978}
2979function inject(key, defaultValue, treatDefaultAsFactory = false) {
2980 // fallback to `currentRenderingInstance` so that this can be called in
2981 // a functional component
2982 const instance = currentInstance || currentRenderingInstance;
2983 if (instance) {
2984 // #2400
2985 // to support `app.use` plugins,
2986 // fallback to appContext's `provides` if the intance is at root
2987 const provides = instance.parent == null
2988 ? instance.vnode.appContext && instance.vnode.appContext.provides
2989 : instance.parent.provides;
2990 if (provides && key in provides) {
2991 // TS doesn't allow symbol as index type
2992 return provides[key];
2993 }
2994 else if (arguments.length > 1) {
2995 return treatDefaultAsFactory && isFunction(defaultValue)
2996 ? defaultValue.call(instance.proxy)
2997 : defaultValue;
2998 }
2999 else {
3000 warn$1(`injection "${String(key)}" not found.`);
3001 }
3002 }
3003 else {
3004 warn$1(`inject() can only be used inside setup() or functional components.`);
3005 }
3006}
3007
3008function useTransitionState() {
3009 const state = {
3010 isMounted: false,
3011 isLeaving: false,
3012 isUnmounting: false,
3013 leavingVNodes: new Map()
3014 };
3015 onMounted(() => {
3016 state.isMounted = true;
3017 });
3018 onBeforeUnmount(() => {
3019 state.isUnmounting = true;
3020 });
3021 return state;
3022}
3023const TransitionHookValidator = [Function, Array];
3024const BaseTransitionImpl = {
3025 name: `BaseTransition`,
3026 props: {
3027 mode: String,
3028 appear: Boolean,
3029 persisted: Boolean,
3030 // enter
3031 onBeforeEnter: TransitionHookValidator,
3032 onEnter: TransitionHookValidator,
3033 onAfterEnter: TransitionHookValidator,
3034 onEnterCancelled: TransitionHookValidator,
3035 // leave
3036 onBeforeLeave: TransitionHookValidator,
3037 onLeave: TransitionHookValidator,
3038 onAfterLeave: TransitionHookValidator,
3039 onLeaveCancelled: TransitionHookValidator,
3040 // appear
3041 onBeforeAppear: TransitionHookValidator,
3042 onAppear: TransitionHookValidator,
3043 onAfterAppear: TransitionHookValidator,
3044 onAppearCancelled: TransitionHookValidator
3045 },
3046 setup(props, { slots }) {
3047 const instance = getCurrentInstance();
3048 const state = useTransitionState();
3049 let prevTransitionKey;
3050 return () => {
3051 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3052 if (!children || !children.length) {
3053 return;
3054 }
3055 // warn multiple elements
3056 if (children.length > 1) {
3057 warn$1('<transition> can only be used on a single element or component. Use ' +
3058 '<transition-group> for lists.');
3059 }
3060 // there's no need to track reactivity for these props so use the raw
3061 // props for a bit better perf
3062 const rawProps = toRaw(props);
3063 const { mode } = rawProps;
3064 // check mode
3065 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3066 warn$1(`invalid <transition> mode: ${mode}`);
3067 }
3068 // at this point children has a guaranteed length of 1.
3069 const child = children[0];
3070 if (state.isLeaving) {
3071 return emptyPlaceholder(child);
3072 }
3073 // in the case of <transition><keep-alive/></transition>, we need to
3074 // compare the type of the kept-alive children.
3075 const innerChild = getKeepAliveChild(child);
3076 if (!innerChild) {
3077 return emptyPlaceholder(child);
3078 }
3079 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3080 setTransitionHooks(innerChild, enterHooks);
3081 const oldChild = instance.subTree;
3082 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3083 let transitionKeyChanged = false;
3084 const { getTransitionKey } = innerChild.type;
3085 if (getTransitionKey) {
3086 const key = getTransitionKey();
3087 if (prevTransitionKey === undefined) {
3088 prevTransitionKey = key;
3089 }
3090 else if (key !== prevTransitionKey) {
3091 prevTransitionKey = key;
3092 transitionKeyChanged = true;
3093 }
3094 }
3095 // handle mode
3096 if (oldInnerChild &&
3097 oldInnerChild.type !== Comment &&
3098 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3099 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3100 // update old tree's hooks in case of dynamic transition
3101 setTransitionHooks(oldInnerChild, leavingHooks);
3102 // switching between different views
3103 if (mode === 'out-in') {
3104 state.isLeaving = true;
3105 // return placeholder node and queue update when leave finishes
3106 leavingHooks.afterLeave = () => {
3107 state.isLeaving = false;
3108 instance.update();
3109 };
3110 return emptyPlaceholder(child);
3111 }
3112 else if (mode === 'in-out' && innerChild.type !== Comment) {
3113 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3114 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3115 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3116 // early removal callback
3117 el._leaveCb = () => {
3118 earlyRemove();
3119 el._leaveCb = undefined;
3120 delete enterHooks.delayedLeave;
3121 };
3122 enterHooks.delayedLeave = delayedLeave;
3123 };
3124 }
3125 }
3126 return child;
3127 };
3128 }
3129};
3130// export the public type for h/tsx inference
3131// also to avoid inline import() in generated d.ts files
3132const BaseTransition = BaseTransitionImpl;
3133function getLeavingNodesForType(state, vnode) {
3134 const { leavingVNodes } = state;
3135 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3136 if (!leavingVNodesCache) {
3137 leavingVNodesCache = Object.create(null);
3138 leavingVNodes.set(vnode.type, leavingVNodesCache);
3139 }
3140 return leavingVNodesCache;
3141}
3142// The transition hooks are attached to the vnode as vnode.transition
3143// and will be called at appropriate timing in the renderer.
3144function resolveTransitionHooks(vnode, props, state, instance) {
3145 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3146 const key = String(vnode.key);
3147 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3148 const callHook = (hook, args) => {
3149 hook &&
3150 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3151 };
3152 const hooks = {
3153 mode,
3154 persisted,
3155 beforeEnter(el) {
3156 let hook = onBeforeEnter;
3157 if (!state.isMounted) {
3158 if (appear) {
3159 hook = onBeforeAppear || onBeforeEnter;
3160 }
3161 else {
3162 return;
3163 }
3164 }
3165 // for same element (v-show)
3166 if (el._leaveCb) {
3167 el._leaveCb(true /* cancelled */);
3168 }
3169 // for toggled element with same key (v-if)
3170 const leavingVNode = leavingVNodesCache[key];
3171 if (leavingVNode &&
3172 isSameVNodeType(vnode, leavingVNode) &&
3173 leavingVNode.el._leaveCb) {
3174 // force early removal (not cancelled)
3175 leavingVNode.el._leaveCb();
3176 }
3177 callHook(hook, [el]);
3178 },
3179 enter(el) {
3180 let hook = onEnter;
3181 let afterHook = onAfterEnter;
3182 let cancelHook = onEnterCancelled;
3183 if (!state.isMounted) {
3184 if (appear) {
3185 hook = onAppear || onEnter;
3186 afterHook = onAfterAppear || onAfterEnter;
3187 cancelHook = onAppearCancelled || onEnterCancelled;
3188 }
3189 else {
3190 return;
3191 }
3192 }
3193 let called = false;
3194 const done = (el._enterCb = (cancelled) => {
3195 if (called)
3196 return;
3197 called = true;
3198 if (cancelled) {
3199 callHook(cancelHook, [el]);
3200 }
3201 else {
3202 callHook(afterHook, [el]);
3203 }
3204 if (hooks.delayedLeave) {
3205 hooks.delayedLeave();
3206 }
3207 el._enterCb = undefined;
3208 });
3209 if (hook) {
3210 hook(el, done);
3211 if (hook.length <= 1) {
3212 done();
3213 }
3214 }
3215 else {
3216 done();
3217 }
3218 },
3219 leave(el, remove) {
3220 const key = String(vnode.key);
3221 if (el._enterCb) {
3222 el._enterCb(true /* cancelled */);
3223 }
3224 if (state.isUnmounting) {
3225 return remove();
3226 }
3227 callHook(onBeforeLeave, [el]);
3228 let called = false;
3229 const done = (el._leaveCb = (cancelled) => {
3230 if (called)
3231 return;
3232 called = true;
3233 remove();
3234 if (cancelled) {
3235 callHook(onLeaveCancelled, [el]);
3236 }
3237 else {
3238 callHook(onAfterLeave, [el]);
3239 }
3240 el._leaveCb = undefined;
3241 if (leavingVNodesCache[key] === vnode) {
3242 delete leavingVNodesCache[key];
3243 }
3244 });
3245 leavingVNodesCache[key] = vnode;
3246 if (onLeave) {
3247 onLeave(el, done);
3248 if (onLeave.length <= 1) {
3249 done();
3250 }
3251 }
3252 else {
3253 done();
3254 }
3255 },
3256 clone(vnode) {
3257 return resolveTransitionHooks(vnode, props, state, instance);
3258 }
3259 };
3260 return hooks;
3261}
3262// the placeholder really only handles one special case: KeepAlive
3263// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3264// placeholder with empty content to avoid the KeepAlive instance from being
3265// unmounted.
3266function emptyPlaceholder(vnode) {
3267 if (isKeepAlive(vnode)) {
3268 vnode = cloneVNode(vnode);
3269 vnode.children = null;
3270 return vnode;
3271 }
3272}
3273function getKeepAliveChild(vnode) {
3274 return isKeepAlive(vnode)
3275 ? vnode.children
3276 ? vnode.children[0]
3277 : undefined
3278 : vnode;
3279}
3280function setTransitionHooks(vnode, hooks) {
3281 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3282 setTransitionHooks(vnode.component.subTree, hooks);
3283 }
3284 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3285 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3286 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3287 }
3288 else {
3289 vnode.transition = hooks;
3290 }
3291}
3292function getTransitionRawChildren(children, keepComment = false) {
3293 let ret = [];
3294 let keyedFragmentCount = 0;
3295 for (let i = 0; i < children.length; i++) {
3296 const child = children[i];
3297 // handle fragment children case, e.g. v-for
3298 if (child.type === Fragment) {
3299 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3300 keyedFragmentCount++;
3301 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3302 }
3303 // comment placeholders should be skipped, e.g. v-if
3304 else if (keepComment || child.type !== Comment) {
3305 ret.push(child);
3306 }
3307 }
3308 // #1126 if a transition children list contains multiple sub fragments, these
3309 // fragments will be merged into a flat children array. Since each v-for
3310 // fragment may contain different static bindings inside, we need to de-op
3311 // these children to force full diffs to ensure correct behavior.
3312 if (keyedFragmentCount > 1) {
3313 for (let i = 0; i < ret.length; i++) {
3314 ret[i].patchFlag = -2 /* BAIL */;
3315 }
3316 }
3317 return ret;
3318}
3319
3320// implementation, close to no-op
3321function defineComponent(options) {
3322 return isFunction(options) ? { setup: options, name: options.name } : options;
3323}
3324
3325const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3326function defineAsyncComponent(source) {
3327 if (isFunction(source)) {
3328 source = { loader: source };
3329 }
3330 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3331 suspensible = true, onError: userOnError } = source;
3332 let pendingRequest = null;
3333 let resolvedComp;
3334 let retries = 0;
3335 const retry = () => {
3336 retries++;
3337 pendingRequest = null;
3338 return load();
3339 };
3340 const load = () => {
3341 let thisRequest;
3342 return (pendingRequest ||
3343 (thisRequest = pendingRequest =
3344 loader()
3345 .catch(err => {
3346 err = err instanceof Error ? err : new Error(String(err));
3347 if (userOnError) {
3348 return new Promise((resolve, reject) => {
3349 const userRetry = () => resolve(retry());
3350 const userFail = () => reject(err);
3351 userOnError(err, userRetry, userFail, retries + 1);
3352 });
3353 }
3354 else {
3355 throw err;
3356 }
3357 })
3358 .then((comp) => {
3359 if (thisRequest !== pendingRequest && pendingRequest) {
3360 return pendingRequest;
3361 }
3362 if (!comp) {
3363 warn$1(`Async component loader resolved to undefined. ` +
3364 `If you are using retry(), make sure to return its return value.`);
3365 }
3366 // interop module default
3367 if (comp &&
3368 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3369 comp = comp.default;
3370 }
3371 if (comp && !isObject(comp) && !isFunction(comp)) {
3372 throw new Error(`Invalid async component load result: ${comp}`);
3373 }
3374 resolvedComp = comp;
3375 return comp;
3376 })));
3377 };
3378 return defineComponent({
3379 name: 'AsyncComponentWrapper',
3380 __asyncLoader: load,
3381 get __asyncResolved() {
3382 return resolvedComp;
3383 },
3384 setup() {
3385 const instance = currentInstance;
3386 // already resolved
3387 if (resolvedComp) {
3388 return () => createInnerComp(resolvedComp, instance);
3389 }
3390 const onError = (err) => {
3391 pendingRequest = null;
3392 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3393 };
3394 // suspense-controlled or SSR.
3395 if ((suspensible && instance.suspense) ||
3396 (false )) {
3397 return load()
3398 .then(comp => {
3399 return () => createInnerComp(comp, instance);
3400 })
3401 .catch(err => {
3402 onError(err);
3403 return () => errorComponent
3404 ? createVNode(errorComponent, {
3405 error: err
3406 })
3407 : null;
3408 });
3409 }
3410 const loaded = ref(false);
3411 const error = ref();
3412 const delayed = ref(!!delay);
3413 if (delay) {
3414 setTimeout(() => {
3415 delayed.value = false;
3416 }, delay);
3417 }
3418 if (timeout != null) {
3419 setTimeout(() => {
3420 if (!loaded.value && !error.value) {
3421 const err = new Error(`Async component timed out after ${timeout}ms.`);
3422 onError(err);
3423 error.value = err;
3424 }
3425 }, timeout);
3426 }
3427 load()
3428 .then(() => {
3429 loaded.value = true;
3430 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3431 // parent is keep-alive, force update so the loaded component's
3432 // name is taken into account
3433 queueJob(instance.parent.update);
3434 }
3435 })
3436 .catch(err => {
3437 onError(err);
3438 error.value = err;
3439 });
3440 return () => {
3441 if (loaded.value && resolvedComp) {
3442 return createInnerComp(resolvedComp, instance);
3443 }
3444 else if (error.value && errorComponent) {
3445 return createVNode(errorComponent, {
3446 error: error.value
3447 });
3448 }
3449 else if (loadingComponent && !delayed.value) {
3450 return createVNode(loadingComponent);
3451 }
3452 };
3453 }
3454 });
3455}
3456function createInnerComp(comp, { vnode: { ref, props, children } }) {
3457 const vnode = createVNode(comp, props, children);
3458 // ensure inner component inherits the async wrapper's ref owner
3459 vnode.ref = ref;
3460 return vnode;
3461}
3462
3463const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3464const KeepAliveImpl = {
3465 name: `KeepAlive`,
3466 // Marker for special handling inside the renderer. We are not using a ===
3467 // check directly on KeepAlive in the renderer, because importing it directly
3468 // would prevent it from being tree-shaken.
3469 __isKeepAlive: true,
3470 props: {
3471 include: [String, RegExp, Array],
3472 exclude: [String, RegExp, Array],
3473 max: [String, Number]
3474 },
3475 setup(props, { slots }) {
3476 const instance = getCurrentInstance();
3477 // KeepAlive communicates with the instantiated renderer via the
3478 // ctx where the renderer passes in its internals,
3479 // and the KeepAlive instance exposes activate/deactivate implementations.
3480 // The whole point of this is to avoid importing KeepAlive directly in the
3481 // renderer to facilitate tree-shaking.
3482 const sharedContext = instance.ctx;
3483 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3484 // for KeepAlive, we just need to render its children
3485 if (!sharedContext.renderer) {
3486 return slots.default;
3487 }
3488 const cache = new Map();
3489 const keys = new Set();
3490 let current = null;
3491 {
3492 instance.__v_cache = cache;
3493 }
3494 const parentSuspense = instance.suspense;
3495 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3496 const storageContainer = createElement('div');
3497 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3498 const instance = vnode.component;
3499 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3500 // in case props have changed
3501 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3502 queuePostRenderEffect(() => {
3503 instance.isDeactivated = false;
3504 if (instance.a) {
3505 invokeArrayFns(instance.a);
3506 }
3507 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3508 if (vnodeHook) {
3509 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3510 }
3511 }, parentSuspense);
3512 {
3513 // Update components tree
3514 devtoolsComponentAdded(instance);
3515 }
3516 };
3517 sharedContext.deactivate = (vnode) => {
3518 const instance = vnode.component;
3519 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3520 queuePostRenderEffect(() => {
3521 if (instance.da) {
3522 invokeArrayFns(instance.da);
3523 }
3524 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3525 if (vnodeHook) {
3526 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3527 }
3528 instance.isDeactivated = true;
3529 }, parentSuspense);
3530 {
3531 // Update components tree
3532 devtoolsComponentAdded(instance);
3533 }
3534 };
3535 function unmount(vnode) {
3536 // reset the shapeFlag so it can be properly unmounted
3537 resetShapeFlag(vnode);
3538 _unmount(vnode, instance, parentSuspense);
3539 }
3540 function pruneCache(filter) {
3541 cache.forEach((vnode, key) => {
3542 const name = getComponentName(vnode.type);
3543 if (name && (!filter || !filter(name))) {
3544 pruneCacheEntry(key);
3545 }
3546 });
3547 }
3548 function pruneCacheEntry(key) {
3549 const cached = cache.get(key);
3550 if (!current || cached.type !== current.type) {
3551 unmount(cached);
3552 }
3553 else if (current) {
3554 // current active instance should no longer be kept-alive.
3555 // we can't unmount it now but it might be later, so reset its flag now.
3556 resetShapeFlag(current);
3557 }
3558 cache.delete(key);
3559 keys.delete(key);
3560 }
3561 // prune cache on include/exclude prop change
3562 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3563 include && pruneCache(name => matches(include, name));
3564 exclude && pruneCache(name => !matches(exclude, name));
3565 },
3566 // prune post-render after `current` has been updated
3567 { flush: 'post', deep: true });
3568 // cache sub tree after render
3569 let pendingCacheKey = null;
3570 const cacheSubtree = () => {
3571 // fix #1621, the pendingCacheKey could be 0
3572 if (pendingCacheKey != null) {
3573 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3574 }
3575 };
3576 onMounted(cacheSubtree);
3577 onUpdated(cacheSubtree);
3578 onBeforeUnmount(() => {
3579 cache.forEach(cached => {
3580 const { subTree, suspense } = instance;
3581 const vnode = getInnerChild(subTree);
3582 if (cached.type === vnode.type) {
3583 // current instance will be unmounted as part of keep-alive's unmount
3584 resetShapeFlag(vnode);
3585 // but invoke its deactivated hook here
3586 const da = vnode.component.da;
3587 da && queuePostRenderEffect(da, suspense);
3588 return;
3589 }
3590 unmount(cached);
3591 });
3592 });
3593 return () => {
3594 pendingCacheKey = null;
3595 if (!slots.default) {
3596 return null;
3597 }
3598 const children = slots.default();
3599 const rawVNode = children[0];
3600 if (children.length > 1) {
3601 {
3602 warn$1(`KeepAlive should contain exactly one component child.`);
3603 }
3604 current = null;
3605 return children;
3606 }
3607 else if (!isVNode(rawVNode) ||
3608 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3609 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3610 current = null;
3611 return rawVNode;
3612 }
3613 let vnode = getInnerChild(rawVNode);
3614 const comp = vnode.type;
3615 // for async components, name check should be based in its loaded
3616 // inner component if available
3617 const name = getComponentName(isAsyncWrapper(vnode)
3618 ? vnode.type.__asyncResolved || {}
3619 : comp);
3620 const { include, exclude, max } = props;
3621 if ((include && (!name || !matches(include, name))) ||
3622 (exclude && name && matches(exclude, name))) {
3623 current = vnode;
3624 return rawVNode;
3625 }
3626 const key = vnode.key == null ? comp : vnode.key;
3627 const cachedVNode = cache.get(key);
3628 // clone vnode if it's reused because we are going to mutate it
3629 if (vnode.el) {
3630 vnode = cloneVNode(vnode);
3631 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
3632 rawVNode.ssContent = vnode;
3633 }
3634 }
3635 // #1513 it's possible for the returned vnode to be cloned due to attr
3636 // fallthrough or scopeId, so the vnode here may not be the final vnode
3637 // that is mounted. Instead of caching it directly, we store the pending
3638 // key and cache `instance.subTree` (the normalized vnode) in
3639 // beforeMount/beforeUpdate hooks.
3640 pendingCacheKey = key;
3641 if (cachedVNode) {
3642 // copy over mounted state
3643 vnode.el = cachedVNode.el;
3644 vnode.component = cachedVNode.component;
3645 if (vnode.transition) {
3646 // recursively update transition hooks on subTree
3647 setTransitionHooks(vnode, vnode.transition);
3648 }
3649 // avoid vnode being mounted as fresh
3650 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
3651 // make this key the freshest
3652 keys.delete(key);
3653 keys.add(key);
3654 }
3655 else {
3656 keys.add(key);
3657 // prune oldest entry
3658 if (max && keys.size > parseInt(max, 10)) {
3659 pruneCacheEntry(keys.values().next().value);
3660 }
3661 }
3662 // avoid vnode being unmounted
3663 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3664 current = vnode;
3665 return rawVNode;
3666 };
3667 }
3668};
3669// export the public type for h/tsx inference
3670// also to avoid inline import() in generated d.ts files
3671const KeepAlive = KeepAliveImpl;
3672function matches(pattern, name) {
3673 if (isArray(pattern)) {
3674 return pattern.some((p) => matches(p, name));
3675 }
3676 else if (isString(pattern)) {
3677 return pattern.split(',').indexOf(name) > -1;
3678 }
3679 else if (pattern.test) {
3680 return pattern.test(name);
3681 }
3682 /* istanbul ignore next */
3683 return false;
3684}
3685function onActivated(hook, target) {
3686 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
3687}
3688function onDeactivated(hook, target) {
3689 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
3690}
3691function registerKeepAliveHook(hook, type, target = currentInstance) {
3692 // cache the deactivate branch check wrapper for injected hooks so the same
3693 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
3694 // deactivation check".
3695 const wrappedHook = hook.__wdc ||
3696 (hook.__wdc = () => {
3697 // only fire the hook if the target instance is NOT in a deactivated branch.
3698 let current = target;
3699 while (current) {
3700 if (current.isDeactivated) {
3701 return;
3702 }
3703 current = current.parent;
3704 }
3705 hook();
3706 });
3707 injectHook(type, wrappedHook, target);
3708 // In addition to registering it on the target instance, we walk up the parent
3709 // chain and register it on all ancestor instances that are keep-alive roots.
3710 // This avoids the need to walk the entire component tree when invoking these
3711 // hooks, and more importantly, avoids the need to track child components in
3712 // arrays.
3713 if (target) {
3714 let current = target.parent;
3715 while (current && current.parent) {
3716 if (isKeepAlive(current.parent.vnode)) {
3717 injectToKeepAliveRoot(wrappedHook, type, target, current);
3718 }
3719 current = current.parent;
3720 }
3721 }
3722}
3723function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
3724 // injectHook wraps the original for error handling, so make sure to remove
3725 // the wrapped version.
3726 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
3727 onUnmounted(() => {
3728 remove(keepAliveRoot[type], injected);
3729 }, target);
3730}
3731function resetShapeFlag(vnode) {
3732 let shapeFlag = vnode.shapeFlag;
3733 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
3734 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3735 }
3736 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
3737 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
3738 }
3739 vnode.shapeFlag = shapeFlag;
3740}
3741function getInnerChild(vnode) {
3742 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
3743}
3744
3745function injectHook(type, hook, target = currentInstance, prepend = false) {
3746 if (target) {
3747 const hooks = target[type] || (target[type] = []);
3748 // cache the error handling wrapper for injected hooks so the same hook
3749 // can be properly deduped by the scheduler. "__weh" stands for "with error
3750 // handling".
3751 const wrappedHook = hook.__weh ||
3752 (hook.__weh = (...args) => {
3753 if (target.isUnmounted) {
3754 return;
3755 }
3756 // disable tracking inside all lifecycle hooks
3757 // since they can potentially be called inside effects.
3758 pauseTracking();
3759 // Set currentInstance during hook invocation.
3760 // This assumes the hook does not synchronously trigger other hooks, which
3761 // can only be false when the user does something really funky.
3762 setCurrentInstance(target);
3763 const res = callWithAsyncErrorHandling(hook, target, type, args);
3764 unsetCurrentInstance();
3765 resetTracking();
3766 return res;
3767 });
3768 if (prepend) {
3769 hooks.unshift(wrappedHook);
3770 }
3771 else {
3772 hooks.push(wrappedHook);
3773 }
3774 return wrappedHook;
3775 }
3776 else {
3777 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
3778 warn$1(`${apiName} is called when there is no active component instance to be ` +
3779 `associated with. ` +
3780 `Lifecycle injection APIs can only be used during execution of setup().` +
3781 (` If you are using async setup(), make sure to register lifecycle ` +
3782 `hooks before the first await statement.`
3783 ));
3784 }
3785}
3786const createHook = (lifecycle) => (hook, target = currentInstance) =>
3787// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
3788(!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
3789 injectHook(lifecycle, hook, target);
3790const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
3791const onMounted = createHook("m" /* MOUNTED */);
3792const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
3793const onUpdated = createHook("u" /* UPDATED */);
3794const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
3795const onUnmounted = createHook("um" /* UNMOUNTED */);
3796const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
3797const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
3798const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
3799function onErrorCaptured(hook, target = currentInstance) {
3800 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
3801}
3802
3803function createDuplicateChecker() {
3804 const cache = Object.create(null);
3805 return (type, key) => {
3806 if (cache[key]) {
3807 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
3808 }
3809 else {
3810 cache[key] = type;
3811 }
3812 };
3813}
3814let shouldCacheAccess = true;
3815function applyOptions(instance) {
3816 const options = resolveMergedOptions(instance);
3817 const publicThis = instance.proxy;
3818 const ctx = instance.ctx;
3819 // do not cache property access on public proxy during state initialization
3820 shouldCacheAccess = false;
3821 // call beforeCreate first before accessing other options since
3822 // the hook may mutate resolved options (#2791)
3823 if (options.beforeCreate) {
3824 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
3825 }
3826 const {
3827 // state
3828 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
3829 // lifecycle
3830 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
3831 // public API
3832 expose, inheritAttrs,
3833 // assets
3834 components, directives, filters } = options;
3835 const checkDuplicateProperties = createDuplicateChecker() ;
3836 {
3837 const [propsOptions] = instance.propsOptions;
3838 if (propsOptions) {
3839 for (const key in propsOptions) {
3840 checkDuplicateProperties("Props" /* PROPS */, key);
3841 }
3842 }
3843 }
3844 // options initialization order (to be consistent with Vue 2):
3845 // - props (already done outside of this function)
3846 // - inject
3847 // - methods
3848 // - data (deferred since it relies on `this` access)
3849 // - computed
3850 // - watch (deferred since it relies on `this` access)
3851 if (injectOptions) {
3852 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
3853 }
3854 if (methods) {
3855 for (const key in methods) {
3856 const methodHandler = methods[key];
3857 if (isFunction(methodHandler)) {
3858 // In dev mode, we use the `createRenderContext` function to define
3859 // methods to the proxy target, and those are read-only but
3860 // reconfigurable, so it needs to be redefined here
3861 {
3862 Object.defineProperty(ctx, key, {
3863 value: methodHandler.bind(publicThis),
3864 configurable: true,
3865 enumerable: true,
3866 writable: true
3867 });
3868 }
3869 {
3870 checkDuplicateProperties("Methods" /* METHODS */, key);
3871 }
3872 }
3873 else {
3874 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
3875 `Did you reference the function correctly?`);
3876 }
3877 }
3878 }
3879 if (dataOptions) {
3880 if (!isFunction(dataOptions)) {
3881 warn$1(`The data option must be a function. ` +
3882 `Plain object usage is no longer supported.`);
3883 }
3884 const data = dataOptions.call(publicThis, publicThis);
3885 if (isPromise(data)) {
3886 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
3887 `intend to perform data fetching before component renders, use ` +
3888 `async setup() + <Suspense>.`);
3889 }
3890 if (!isObject(data)) {
3891 warn$1(`data() should return an object.`);
3892 }
3893 else {
3894 instance.data = reactive(data);
3895 {
3896 for (const key in data) {
3897 checkDuplicateProperties("Data" /* DATA */, key);
3898 // expose data on ctx during dev
3899 if (key[0] !== '$' && key[0] !== '_') {
3900 Object.defineProperty(ctx, key, {
3901 configurable: true,
3902 enumerable: true,
3903 get: () => data[key],
3904 set: NOOP
3905 });
3906 }
3907 }
3908 }
3909 }
3910 }
3911 // state initialization complete at this point - start caching access
3912 shouldCacheAccess = true;
3913 if (computedOptions) {
3914 for (const key in computedOptions) {
3915 const opt = computedOptions[key];
3916 const get = isFunction(opt)
3917 ? opt.bind(publicThis, publicThis)
3918 : isFunction(opt.get)
3919 ? opt.get.bind(publicThis, publicThis)
3920 : NOOP;
3921 if (get === NOOP) {
3922 warn$1(`Computed property "${key}" has no getter.`);
3923 }
3924 const set = !isFunction(opt) && isFunction(opt.set)
3925 ? opt.set.bind(publicThis)
3926 : () => {
3927 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
3928 }
3929 ;
3930 const c = computed({
3931 get,
3932 set
3933 });
3934 Object.defineProperty(ctx, key, {
3935 enumerable: true,
3936 configurable: true,
3937 get: () => c.value,
3938 set: v => (c.value = v)
3939 });
3940 {
3941 checkDuplicateProperties("Computed" /* COMPUTED */, key);
3942 }
3943 }
3944 }
3945 if (watchOptions) {
3946 for (const key in watchOptions) {
3947 createWatcher(watchOptions[key], ctx, publicThis, key);
3948 }
3949 }
3950 if (provideOptions) {
3951 const provides = isFunction(provideOptions)
3952 ? provideOptions.call(publicThis)
3953 : provideOptions;
3954 Reflect.ownKeys(provides).forEach(key => {
3955 provide(key, provides[key]);
3956 });
3957 }
3958 if (created) {
3959 callHook(created, instance, "c" /* CREATED */);
3960 }
3961 function registerLifecycleHook(register, hook) {
3962 if (isArray(hook)) {
3963 hook.forEach(_hook => register(_hook.bind(publicThis)));
3964 }
3965 else if (hook) {
3966 register(hook.bind(publicThis));
3967 }
3968 }
3969 registerLifecycleHook(onBeforeMount, beforeMount);
3970 registerLifecycleHook(onMounted, mounted);
3971 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
3972 registerLifecycleHook(onUpdated, updated);
3973 registerLifecycleHook(onActivated, activated);
3974 registerLifecycleHook(onDeactivated, deactivated);
3975 registerLifecycleHook(onErrorCaptured, errorCaptured);
3976 registerLifecycleHook(onRenderTracked, renderTracked);
3977 registerLifecycleHook(onRenderTriggered, renderTriggered);
3978 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
3979 registerLifecycleHook(onUnmounted, unmounted);
3980 registerLifecycleHook(onServerPrefetch, serverPrefetch);
3981 if (isArray(expose)) {
3982 if (expose.length) {
3983 const exposed = instance.exposed || (instance.exposed = {});
3984 expose.forEach(key => {
3985 Object.defineProperty(exposed, key, {
3986 get: () => publicThis[key],
3987 set: val => (publicThis[key] = val)
3988 });
3989 });
3990 }
3991 else if (!instance.exposed) {
3992 instance.exposed = {};
3993 }
3994 }
3995 // options that are handled when creating the instance but also need to be
3996 // applied from mixins
3997 if (render && instance.render === NOOP) {
3998 instance.render = render;
3999 }
4000 if (inheritAttrs != null) {
4001 instance.inheritAttrs = inheritAttrs;
4002 }
4003 // asset options.
4004 if (components)
4005 instance.components = components;
4006 if (directives)
4007 instance.directives = directives;
4008}
4009function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4010 if (isArray(injectOptions)) {
4011 injectOptions = normalizeInject(injectOptions);
4012 }
4013 for (const key in injectOptions) {
4014 const opt = injectOptions[key];
4015 let injected;
4016 if (isObject(opt)) {
4017 if ('default' in opt) {
4018 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4019 }
4020 else {
4021 injected = inject(opt.from || key);
4022 }
4023 }
4024 else {
4025 injected = inject(opt);
4026 }
4027 if (isRef(injected)) {
4028 // TODO remove the check in 3.3
4029 if (unwrapRef) {
4030 Object.defineProperty(ctx, key, {
4031 enumerable: true,
4032 configurable: true,
4033 get: () => injected.value,
4034 set: v => (injected.value = v)
4035 });
4036 }
4037 else {
4038 {
4039 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4040 `and no longer needs \`.value\` in the next minor release. ` +
4041 `To opt-in to the new behavior now, ` +
4042 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4043 `temporary and will not be needed in the future.)`);
4044 }
4045 ctx[key] = injected;
4046 }
4047 }
4048 else {
4049 ctx[key] = injected;
4050 }
4051 {
4052 checkDuplicateProperties("Inject" /* INJECT */, key);
4053 }
4054 }
4055}
4056function callHook(hook, instance, type) {
4057 callWithAsyncErrorHandling(isArray(hook)
4058 ? hook.map(h => h.bind(instance.proxy))
4059 : hook.bind(instance.proxy), instance, type);
4060}
4061function createWatcher(raw, ctx, publicThis, key) {
4062 const getter = key.includes('.')
4063 ? createPathGetter(publicThis, key)
4064 : () => publicThis[key];
4065 if (isString(raw)) {
4066 const handler = ctx[raw];
4067 if (isFunction(handler)) {
4068 watch(getter, handler);
4069 }
4070 else {
4071 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4072 }
4073 }
4074 else if (isFunction(raw)) {
4075 watch(getter, raw.bind(publicThis));
4076 }
4077 else if (isObject(raw)) {
4078 if (isArray(raw)) {
4079 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4080 }
4081 else {
4082 const handler = isFunction(raw.handler)
4083 ? raw.handler.bind(publicThis)
4084 : ctx[raw.handler];
4085 if (isFunction(handler)) {
4086 watch(getter, handler, raw);
4087 }
4088 else {
4089 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4090 }
4091 }
4092 }
4093 else {
4094 warn$1(`Invalid watch option: "${key}"`, raw);
4095 }
4096}
4097/**
4098 * Resolve merged options and cache it on the component.
4099 * This is done only once per-component since the merging does not involve
4100 * instances.
4101 */
4102function resolveMergedOptions(instance) {
4103 const base = instance.type;
4104 const { mixins, extends: extendsOptions } = base;
4105 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4106 const cached = cache.get(base);
4107 let resolved;
4108 if (cached) {
4109 resolved = cached;
4110 }
4111 else if (!globalMixins.length && !mixins && !extendsOptions) {
4112 {
4113 resolved = base;
4114 }
4115 }
4116 else {
4117 resolved = {};
4118 if (globalMixins.length) {
4119 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4120 }
4121 mergeOptions(resolved, base, optionMergeStrategies);
4122 }
4123 cache.set(base, resolved);
4124 return resolved;
4125}
4126function mergeOptions(to, from, strats, asMixin = false) {
4127 const { mixins, extends: extendsOptions } = from;
4128 if (extendsOptions) {
4129 mergeOptions(to, extendsOptions, strats, true);
4130 }
4131 if (mixins) {
4132 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4133 }
4134 for (const key in from) {
4135 if (asMixin && key === 'expose') {
4136 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4137 `It should only be declared in the base component itself.`);
4138 }
4139 else {
4140 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4141 to[key] = strat ? strat(to[key], from[key]) : from[key];
4142 }
4143 }
4144 return to;
4145}
4146const internalOptionMergeStrats = {
4147 data: mergeDataFn,
4148 props: mergeObjectOptions,
4149 emits: mergeObjectOptions,
4150 // objects
4151 methods: mergeObjectOptions,
4152 computed: mergeObjectOptions,
4153 // lifecycle
4154 beforeCreate: mergeAsArray,
4155 created: mergeAsArray,
4156 beforeMount: mergeAsArray,
4157 mounted: mergeAsArray,
4158 beforeUpdate: mergeAsArray,
4159 updated: mergeAsArray,
4160 beforeDestroy: mergeAsArray,
4161 beforeUnmount: mergeAsArray,
4162 destroyed: mergeAsArray,
4163 unmounted: mergeAsArray,
4164 activated: mergeAsArray,
4165 deactivated: mergeAsArray,
4166 errorCaptured: mergeAsArray,
4167 serverPrefetch: mergeAsArray,
4168 // assets
4169 components: mergeObjectOptions,
4170 directives: mergeObjectOptions,
4171 // watch
4172 watch: mergeWatchOptions,
4173 // provide / inject
4174 provide: mergeDataFn,
4175 inject: mergeInject
4176};
4177function mergeDataFn(to, from) {
4178 if (!from) {
4179 return to;
4180 }
4181 if (!to) {
4182 return from;
4183 }
4184 return function mergedDataFn() {
4185 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4186 };
4187}
4188function mergeInject(to, from) {
4189 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4190}
4191function normalizeInject(raw) {
4192 if (isArray(raw)) {
4193 const res = {};
4194 for (let i = 0; i < raw.length; i++) {
4195 res[raw[i]] = raw[i];
4196 }
4197 return res;
4198 }
4199 return raw;
4200}
4201function mergeAsArray(to, from) {
4202 return to ? [...new Set([].concat(to, from))] : from;
4203}
4204function mergeObjectOptions(to, from) {
4205 return to ? extend(extend(Object.create(null), to), from) : from;
4206}
4207function mergeWatchOptions(to, from) {
4208 if (!to)
4209 return from;
4210 if (!from)
4211 return to;
4212 const merged = extend(Object.create(null), to);
4213 for (const key in from) {
4214 merged[key] = mergeAsArray(to[key], from[key]);
4215 }
4216 return merged;
4217}
4218
4219function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4220isSSR = false) {
4221 const props = {};
4222 const attrs = {};
4223 def(attrs, InternalObjectKey, 1);
4224 instance.propsDefaults = Object.create(null);
4225 setFullProps(instance, rawProps, props, attrs);
4226 // ensure all declared prop keys are present
4227 for (const key in instance.propsOptions[0]) {
4228 if (!(key in props)) {
4229 props[key] = undefined;
4230 }
4231 }
4232 // validation
4233 {
4234 validateProps(rawProps || {}, props, instance);
4235 }
4236 if (isStateful) {
4237 // stateful
4238 instance.props = isSSR ? props : shallowReactive(props);
4239 }
4240 else {
4241 if (!instance.type.props) {
4242 // functional w/ optional props, props === attrs
4243 instance.props = attrs;
4244 }
4245 else {
4246 // functional w/ declared props
4247 instance.props = props;
4248 }
4249 }
4250 instance.attrs = attrs;
4251}
4252function updateProps(instance, rawProps, rawPrevProps, optimized) {
4253 const { props, attrs, vnode: { patchFlag } } = instance;
4254 const rawCurrentProps = toRaw(props);
4255 const [options] = instance.propsOptions;
4256 let hasAttrsChanged = false;
4257 if (
4258 // always force full diff in dev
4259 // - #1942 if hmr is enabled with sfc component
4260 // - vite#872 non-sfc component used by sfc component
4261 !((instance.type.__hmrId ||
4262 (instance.parent && instance.parent.type.__hmrId))) &&
4263 (optimized || patchFlag > 0) &&
4264 !(patchFlag & 16 /* FULL_PROPS */)) {
4265 if (patchFlag & 8 /* PROPS */) {
4266 // Compiler-generated props & no keys change, just set the updated
4267 // the props.
4268 const propsToUpdate = instance.vnode.dynamicProps;
4269 for (let i = 0; i < propsToUpdate.length; i++) {
4270 let key = propsToUpdate[i];
4271 // PROPS flag guarantees rawProps to be non-null
4272 const value = rawProps[key];
4273 if (options) {
4274 // attr / props separation was done on init and will be consistent
4275 // in this code path, so just check if attrs have it.
4276 if (hasOwn(attrs, key)) {
4277 if (value !== attrs[key]) {
4278 attrs[key] = value;
4279 hasAttrsChanged = true;
4280 }
4281 }
4282 else {
4283 const camelizedKey = camelize(key);
4284 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4285 }
4286 }
4287 else {
4288 if (value !== attrs[key]) {
4289 attrs[key] = value;
4290 hasAttrsChanged = true;
4291 }
4292 }
4293 }
4294 }
4295 }
4296 else {
4297 // full props update.
4298 if (setFullProps(instance, rawProps, props, attrs)) {
4299 hasAttrsChanged = true;
4300 }
4301 // in case of dynamic props, check if we need to delete keys from
4302 // the props object
4303 let kebabKey;
4304 for (const key in rawCurrentProps) {
4305 if (!rawProps ||
4306 // for camelCase
4307 (!hasOwn(rawProps, key) &&
4308 // it's possible the original props was passed in as kebab-case
4309 // and converted to camelCase (#955)
4310 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4311 if (options) {
4312 if (rawPrevProps &&
4313 // for camelCase
4314 (rawPrevProps[key] !== undefined ||
4315 // for kebab-case
4316 rawPrevProps[kebabKey] !== undefined)) {
4317 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4318 }
4319 }
4320 else {
4321 delete props[key];
4322 }
4323 }
4324 }
4325 // in the case of functional component w/o props declaration, props and
4326 // attrs point to the same object so it should already have been updated.
4327 if (attrs !== rawCurrentProps) {
4328 for (const key in attrs) {
4329 if (!rawProps || !hasOwn(rawProps, key)) {
4330 delete attrs[key];
4331 hasAttrsChanged = true;
4332 }
4333 }
4334 }
4335 }
4336 // trigger updates for $attrs in case it's used in component slots
4337 if (hasAttrsChanged) {
4338 trigger(instance, "set" /* SET */, '$attrs');
4339 }
4340 {
4341 validateProps(rawProps || {}, props, instance);
4342 }
4343}
4344function setFullProps(instance, rawProps, props, attrs) {
4345 const [options, needCastKeys] = instance.propsOptions;
4346 let hasAttrsChanged = false;
4347 let rawCastValues;
4348 if (rawProps) {
4349 for (let key in rawProps) {
4350 // key, ref are reserved and never passed down
4351 if (isReservedProp(key)) {
4352 continue;
4353 }
4354 const value = rawProps[key];
4355 // prop option names are camelized during normalization, so to support
4356 // kebab -> camel conversion here we need to camelize the key.
4357 let camelKey;
4358 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4359 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4360 props[camelKey] = value;
4361 }
4362 else {
4363 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4364 }
4365 }
4366 else if (!isEmitListener(instance.emitsOptions, key)) {
4367 if (value !== attrs[key]) {
4368 attrs[key] = value;
4369 hasAttrsChanged = true;
4370 }
4371 }
4372 }
4373 }
4374 if (needCastKeys) {
4375 const rawCurrentProps = toRaw(props);
4376 const castValues = rawCastValues || EMPTY_OBJ;
4377 for (let i = 0; i < needCastKeys.length; i++) {
4378 const key = needCastKeys[i];
4379 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4380 }
4381 }
4382 return hasAttrsChanged;
4383}
4384function resolvePropValue(options, props, key, value, instance, isAbsent) {
4385 const opt = options[key];
4386 if (opt != null) {
4387 const hasDefault = hasOwn(opt, 'default');
4388 // default values
4389 if (hasDefault && value === undefined) {
4390 const defaultValue = opt.default;
4391 if (opt.type !== Function && isFunction(defaultValue)) {
4392 const { propsDefaults } = instance;
4393 if (key in propsDefaults) {
4394 value = propsDefaults[key];
4395 }
4396 else {
4397 setCurrentInstance(instance);
4398 value = propsDefaults[key] = defaultValue.call(null, props);
4399 unsetCurrentInstance();
4400 }
4401 }
4402 else {
4403 value = defaultValue;
4404 }
4405 }
4406 // boolean casting
4407 if (opt[0 /* shouldCast */]) {
4408 if (isAbsent && !hasDefault) {
4409 value = false;
4410 }
4411 else if (opt[1 /* shouldCastTrue */] &&
4412 (value === '' || value === hyphenate(key))) {
4413 value = true;
4414 }
4415 }
4416 }
4417 return value;
4418}
4419function normalizePropsOptions(comp, appContext, asMixin = false) {
4420 const cache = appContext.propsCache;
4421 const cached = cache.get(comp);
4422 if (cached) {
4423 return cached;
4424 }
4425 const raw = comp.props;
4426 const normalized = {};
4427 const needCastKeys = [];
4428 // apply mixin/extends props
4429 let hasExtends = false;
4430 if (!isFunction(comp)) {
4431 const extendProps = (raw) => {
4432 hasExtends = true;
4433 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4434 extend(normalized, props);
4435 if (keys)
4436 needCastKeys.push(...keys);
4437 };
4438 if (!asMixin && appContext.mixins.length) {
4439 appContext.mixins.forEach(extendProps);
4440 }
4441 if (comp.extends) {
4442 extendProps(comp.extends);
4443 }
4444 if (comp.mixins) {
4445 comp.mixins.forEach(extendProps);
4446 }
4447 }
4448 if (!raw && !hasExtends) {
4449 cache.set(comp, EMPTY_ARR);
4450 return EMPTY_ARR;
4451 }
4452 if (isArray(raw)) {
4453 for (let i = 0; i < raw.length; i++) {
4454 if (!isString(raw[i])) {
4455 warn$1(`props must be strings when using array syntax.`, raw[i]);
4456 }
4457 const normalizedKey = camelize(raw[i]);
4458 if (validatePropName(normalizedKey)) {
4459 normalized[normalizedKey] = EMPTY_OBJ;
4460 }
4461 }
4462 }
4463 else if (raw) {
4464 if (!isObject(raw)) {
4465 warn$1(`invalid props options`, raw);
4466 }
4467 for (const key in raw) {
4468 const normalizedKey = camelize(key);
4469 if (validatePropName(normalizedKey)) {
4470 const opt = raw[key];
4471 const prop = (normalized[normalizedKey] =
4472 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4473 if (prop) {
4474 const booleanIndex = getTypeIndex(Boolean, prop.type);
4475 const stringIndex = getTypeIndex(String, prop.type);
4476 prop[0 /* shouldCast */] = booleanIndex > -1;
4477 prop[1 /* shouldCastTrue */] =
4478 stringIndex < 0 || booleanIndex < stringIndex;
4479 // if the prop needs boolean casting or default value
4480 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4481 needCastKeys.push(normalizedKey);
4482 }
4483 }
4484 }
4485 }
4486 }
4487 const res = [normalized, needCastKeys];
4488 cache.set(comp, res);
4489 return res;
4490}
4491function validatePropName(key) {
4492 if (key[0] !== '$') {
4493 return true;
4494 }
4495 else {
4496 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4497 }
4498 return false;
4499}
4500// use function string name to check type constructors
4501// so that it works across vms / iframes.
4502function getType(ctor) {
4503 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4504 return match ? match[1] : ctor === null ? 'null' : '';
4505}
4506function isSameType(a, b) {
4507 return getType(a) === getType(b);
4508}
4509function getTypeIndex(type, expectedTypes) {
4510 if (isArray(expectedTypes)) {
4511 return expectedTypes.findIndex(t => isSameType(t, type));
4512 }
4513 else if (isFunction(expectedTypes)) {
4514 return isSameType(expectedTypes, type) ? 0 : -1;
4515 }
4516 return -1;
4517}
4518/**
4519 * dev only
4520 */
4521function validateProps(rawProps, props, instance) {
4522 const resolvedValues = toRaw(props);
4523 const options = instance.propsOptions[0];
4524 for (const key in options) {
4525 let opt = options[key];
4526 if (opt == null)
4527 continue;
4528 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4529 }
4530}
4531/**
4532 * dev only
4533 */
4534function validateProp(name, value, prop, isAbsent) {
4535 const { type, required, validator } = prop;
4536 // required!
4537 if (required && isAbsent) {
4538 warn$1('Missing required prop: "' + name + '"');
4539 return;
4540 }
4541 // missing but optional
4542 if (value == null && !prop.required) {
4543 return;
4544 }
4545 // type check
4546 if (type != null && type !== true) {
4547 let isValid = false;
4548 const types = isArray(type) ? type : [type];
4549 const expectedTypes = [];
4550 // value is valid as long as one of the specified types match
4551 for (let i = 0; i < types.length && !isValid; i++) {
4552 const { valid, expectedType } = assertType(value, types[i]);
4553 expectedTypes.push(expectedType || '');
4554 isValid = valid;
4555 }
4556 if (!isValid) {
4557 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
4558 return;
4559 }
4560 }
4561 // custom validator
4562 if (validator && !validator(value)) {
4563 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
4564 }
4565}
4566const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4567/**
4568 * dev only
4569 */
4570function assertType(value, type) {
4571 let valid;
4572 const expectedType = getType(type);
4573 if (isSimpleType(expectedType)) {
4574 const t = typeof value;
4575 valid = t === expectedType.toLowerCase();
4576 // for primitive wrapper objects
4577 if (!valid && t === 'object') {
4578 valid = value instanceof type;
4579 }
4580 }
4581 else if (expectedType === 'Object') {
4582 valid = isObject(value);
4583 }
4584 else if (expectedType === 'Array') {
4585 valid = isArray(value);
4586 }
4587 else if (expectedType === 'null') {
4588 valid = value === null;
4589 }
4590 else {
4591 valid = value instanceof type;
4592 }
4593 return {
4594 valid,
4595 expectedType
4596 };
4597}
4598/**
4599 * dev only
4600 */
4601function getInvalidTypeMessage(name, value, expectedTypes) {
4602 let message = `Invalid prop: type check failed for prop "${name}".` +
4603 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
4604 const expectedType = expectedTypes[0];
4605 const receivedType = toRawType(value);
4606 const expectedValue = styleValue(value, expectedType);
4607 const receivedValue = styleValue(value, receivedType);
4608 // check if we need to specify expected value
4609 if (expectedTypes.length === 1 &&
4610 isExplicable(expectedType) &&
4611 !isBoolean(expectedType, receivedType)) {
4612 message += ` with value ${expectedValue}`;
4613 }
4614 message += `, got ${receivedType} `;
4615 // check if we need to specify received value
4616 if (isExplicable(receivedType)) {
4617 message += `with value ${receivedValue}.`;
4618 }
4619 return message;
4620}
4621/**
4622 * dev only
4623 */
4624function styleValue(value, type) {
4625 if (type === 'String') {
4626 return `"${value}"`;
4627 }
4628 else if (type === 'Number') {
4629 return `${Number(value)}`;
4630 }
4631 else {
4632 return `${value}`;
4633 }
4634}
4635/**
4636 * dev only
4637 */
4638function isExplicable(type) {
4639 const explicitTypes = ['string', 'number', 'boolean'];
4640 return explicitTypes.some(elem => type.toLowerCase() === elem);
4641}
4642/**
4643 * dev only
4644 */
4645function isBoolean(...args) {
4646 return args.some(elem => elem.toLowerCase() === 'boolean');
4647}
4648
4649const isInternalKey = (key) => key[0] === '_' || key === '$stable';
4650const normalizeSlotValue = (value) => isArray(value)
4651 ? value.map(normalizeVNode)
4652 : [normalizeVNode(value)];
4653const normalizeSlot = (key, rawSlot, ctx) => {
4654 const normalized = withCtx((...args) => {
4655 if (currentInstance) {
4656 warn$1(`Slot "${key}" invoked outside of the render function: ` +
4657 `this will not track dependencies used in the slot. ` +
4658 `Invoke the slot function inside the render function instead.`);
4659 }
4660 return normalizeSlotValue(rawSlot(...args));
4661 }, ctx);
4662 normalized._c = false;
4663 return normalized;
4664};
4665const normalizeObjectSlots = (rawSlots, slots, instance) => {
4666 const ctx = rawSlots._ctx;
4667 for (const key in rawSlots) {
4668 if (isInternalKey(key))
4669 continue;
4670 const value = rawSlots[key];
4671 if (isFunction(value)) {
4672 slots[key] = normalizeSlot(key, value, ctx);
4673 }
4674 else if (value != null) {
4675 {
4676 warn$1(`Non-function value encountered for slot "${key}". ` +
4677 `Prefer function slots for better performance.`);
4678 }
4679 const normalized = normalizeSlotValue(value);
4680 slots[key] = () => normalized;
4681 }
4682 }
4683};
4684const normalizeVNodeSlots = (instance, children) => {
4685 if (!isKeepAlive(instance.vnode) &&
4686 !(false )) {
4687 warn$1(`Non-function value encountered for default slot. ` +
4688 `Prefer function slots for better performance.`);
4689 }
4690 const normalized = normalizeSlotValue(children);
4691 instance.slots.default = () => normalized;
4692};
4693const initSlots = (instance, children) => {
4694 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4695 const type = children._;
4696 if (type) {
4697 // users can get the shallow readonly version of the slots object through `this.$slots`,
4698 // we should avoid the proxy object polluting the slots of the internal instance
4699 instance.slots = toRaw(children);
4700 // make compiler marker non-enumerable
4701 def(children, '_', type);
4702 }
4703 else {
4704 normalizeObjectSlots(children, (instance.slots = {}));
4705 }
4706 }
4707 else {
4708 instance.slots = {};
4709 if (children) {
4710 normalizeVNodeSlots(instance, children);
4711 }
4712 }
4713 def(instance.slots, InternalObjectKey, 1);
4714};
4715const updateSlots = (instance, children, optimized) => {
4716 const { vnode, slots } = instance;
4717 let needDeletionCheck = true;
4718 let deletionComparisonTarget = EMPTY_OBJ;
4719 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4720 const type = children._;
4721 if (type) {
4722 // compiled slots.
4723 if (isHmrUpdating) {
4724 // Parent was HMR updated so slot content may have changed.
4725 // force update slots and mark instance for hmr as well
4726 extend(slots, children);
4727 }
4728 else if (optimized && type === 1 /* STABLE */) {
4729 // compiled AND stable.
4730 // no need to update, and skip stale slots removal.
4731 needDeletionCheck = false;
4732 }
4733 else {
4734 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
4735 // normalization.
4736 extend(slots, children);
4737 // #2893
4738 // when rendering the optimized slots by manually written render function,
4739 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
4740 // i.e. let the `renderSlot` create the bailed Fragment
4741 if (!optimized && type === 1 /* STABLE */) {
4742 delete slots._;
4743 }
4744 }
4745 }
4746 else {
4747 needDeletionCheck = !children.$stable;
4748 normalizeObjectSlots(children, slots);
4749 }
4750 deletionComparisonTarget = children;
4751 }
4752 else if (children) {
4753 // non slot object children (direct value) passed to a component
4754 normalizeVNodeSlots(instance, children);
4755 deletionComparisonTarget = { default: 1 };
4756 }
4757 // delete stale slots
4758 if (needDeletionCheck) {
4759 for (const key in slots) {
4760 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
4761 delete slots[key];
4762 }
4763 }
4764 }
4765};
4766
4767/**
4768Runtime helper for applying directives to a vnode. Example usage:
4769
4770const comp = resolveComponent('comp')
4771const foo = resolveDirective('foo')
4772const bar = resolveDirective('bar')
4773
4774return withDirectives(h(comp), [
4775 [foo, this.x],
4776 [bar, this.y]
4777])
4778*/
4779const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
4780function validateDirectiveName(name) {
4781 if (isBuiltInDirective(name)) {
4782 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
4783 }
4784}
4785/**
4786 * Adds directives to a VNode.
4787 */
4788function withDirectives(vnode, directives) {
4789 const internalInstance = currentRenderingInstance;
4790 if (internalInstance === null) {
4791 warn$1(`withDirectives can only be used inside render functions.`);
4792 return vnode;
4793 }
4794 const instance = internalInstance.proxy;
4795 const bindings = vnode.dirs || (vnode.dirs = []);
4796 for (let i = 0; i < directives.length; i++) {
4797 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4798 if (isFunction(dir)) {
4799 dir = {
4800 mounted: dir,
4801 updated: dir
4802 };
4803 }
4804 if (dir.deep) {
4805 traverse(value);
4806 }
4807 bindings.push({
4808 dir,
4809 instance,
4810 value,
4811 oldValue: void 0,
4812 arg,
4813 modifiers
4814 });
4815 }
4816 return vnode;
4817}
4818function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4819 const bindings = vnode.dirs;
4820 const oldBindings = prevVNode && prevVNode.dirs;
4821 for (let i = 0; i < bindings.length; i++) {
4822 const binding = bindings[i];
4823 if (oldBindings) {
4824 binding.oldValue = oldBindings[i].value;
4825 }
4826 let hook = binding.dir[name];
4827 if (hook) {
4828 // disable tracking inside all lifecycle hooks
4829 // since they can potentially be called inside effects.
4830 pauseTracking();
4831 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4832 vnode.el,
4833 binding,
4834 vnode,
4835 prevVNode
4836 ]);
4837 resetTracking();
4838 }
4839 }
4840}
4841
4842function createAppContext() {
4843 return {
4844 app: null,
4845 config: {
4846 isNativeTag: NO,
4847 performance: false,
4848 globalProperties: {},
4849 optionMergeStrategies: {},
4850 errorHandler: undefined,
4851 warnHandler: undefined,
4852 compilerOptions: {}
4853 },
4854 mixins: [],
4855 components: {},
4856 directives: {},
4857 provides: Object.create(null),
4858 optionsCache: new WeakMap(),
4859 propsCache: new WeakMap(),
4860 emitsCache: new WeakMap()
4861 };
4862}
4863let uid = 0;
4864function createAppAPI(render, hydrate) {
4865 return function createApp(rootComponent, rootProps = null) {
4866 if (rootProps != null && !isObject(rootProps)) {
4867 warn$1(`root props passed to app.mount() must be an object.`);
4868 rootProps = null;
4869 }
4870 const context = createAppContext();
4871 const installedPlugins = new Set();
4872 let isMounted = false;
4873 const app = (context.app = {
4874 _uid: uid++,
4875 _component: rootComponent,
4876 _props: rootProps,
4877 _container: null,
4878 _context: context,
4879 _instance: null,
4880 version,
4881 get config() {
4882 return context.config;
4883 },
4884 set config(v) {
4885 {
4886 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
4887 }
4888 },
4889 use(plugin, ...options) {
4890 if (installedPlugins.has(plugin)) {
4891 warn$1(`Plugin has already been applied to target app.`);
4892 }
4893 else if (plugin && isFunction(plugin.install)) {
4894 installedPlugins.add(plugin);
4895 plugin.install(app, ...options);
4896 }
4897 else if (isFunction(plugin)) {
4898 installedPlugins.add(plugin);
4899 plugin(app, ...options);
4900 }
4901 else {
4902 warn$1(`A plugin must either be a function or an object with an "install" ` +
4903 `function.`);
4904 }
4905 return app;
4906 },
4907 mixin(mixin) {
4908 {
4909 if (!context.mixins.includes(mixin)) {
4910 context.mixins.push(mixin);
4911 }
4912 else {
4913 warn$1('Mixin has already been applied to target app' +
4914 (mixin.name ? `: ${mixin.name}` : ''));
4915 }
4916 }
4917 return app;
4918 },
4919 component(name, component) {
4920 {
4921 validateComponentName(name, context.config);
4922 }
4923 if (!component) {
4924 return context.components[name];
4925 }
4926 if (context.components[name]) {
4927 warn$1(`Component "${name}" has already been registered in target app.`);
4928 }
4929 context.components[name] = component;
4930 return app;
4931 },
4932 directive(name, directive) {
4933 {
4934 validateDirectiveName(name);
4935 }
4936 if (!directive) {
4937 return context.directives[name];
4938 }
4939 if (context.directives[name]) {
4940 warn$1(`Directive "${name}" has already been registered in target app.`);
4941 }
4942 context.directives[name] = directive;
4943 return app;
4944 },
4945 mount(rootContainer, isHydrate, isSVG) {
4946 if (!isMounted) {
4947 const vnode = createVNode(rootComponent, rootProps);
4948 // store app context on the root VNode.
4949 // this will be set on the root instance on initial mount.
4950 vnode.appContext = context;
4951 // HMR root reload
4952 {
4953 context.reload = () => {
4954 render(cloneVNode(vnode), rootContainer, isSVG);
4955 };
4956 }
4957 if (isHydrate && hydrate) {
4958 hydrate(vnode, rootContainer);
4959 }
4960 else {
4961 render(vnode, rootContainer, isSVG);
4962 }
4963 isMounted = true;
4964 app._container = rootContainer;
4965 rootContainer.__vue_app__ = app;
4966 {
4967 app._instance = vnode.component;
4968 devtoolsInitApp(app, version);
4969 }
4970 return vnode.component.proxy;
4971 }
4972 else {
4973 warn$1(`App has already been mounted.\n` +
4974 `If you want to remount the same app, move your app creation logic ` +
4975 `into a factory function and create fresh app instances for each ` +
4976 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
4977 }
4978 },
4979 unmount() {
4980 if (isMounted) {
4981 render(null, app._container);
4982 {
4983 app._instance = null;
4984 devtoolsUnmountApp(app);
4985 }
4986 delete app._container.__vue_app__;
4987 }
4988 else {
4989 warn$1(`Cannot unmount an app that is not mounted.`);
4990 }
4991 },
4992 provide(key, value) {
4993 if (key in context.provides) {
4994 warn$1(`App already provides property with key "${String(key)}". ` +
4995 `It will be overwritten with the new value.`);
4996 }
4997 // TypeScript doesn't allow symbols as index type
4998 // https://github.com/Microsoft/TypeScript/issues/24587
4999 context.provides[key] = value;
5000 return app;
5001 }
5002 });
5003 return app;
5004 };
5005}
5006
5007let hasMismatch = false;
5008const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5009const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5010// Note: hydration is DOM-specific
5011// But we have to place it in core due to tight coupling with core - splitting
5012// it out creates a ton of unnecessary complexity.
5013// Hydration also depends on some renderer internal logic which needs to be
5014// passed in via arguments.
5015function createHydrationFunctions(rendererInternals) {
5016 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5017 const hydrate = (vnode, container) => {
5018 if (!container.hasChildNodes()) {
5019 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5020 `Performing full mount instead.`);
5021 patch(null, vnode, container);
5022 flushPostFlushCbs();
5023 return;
5024 }
5025 hasMismatch = false;
5026 hydrateNode(container.firstChild, vnode, null, null, null);
5027 flushPostFlushCbs();
5028 if (hasMismatch && !false) {
5029 // this error should show up in production
5030 console.error(`Hydration completed but contains mismatches.`);
5031 }
5032 };
5033 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5034 const isFragmentStart = isComment(node) && node.data === '[';
5035 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5036 const { type, ref, shapeFlag } = vnode;
5037 const domType = node.nodeType;
5038 vnode.el = node;
5039 let nextNode = null;
5040 switch (type) {
5041 case Text:
5042 if (domType !== 3 /* TEXT */) {
5043 nextNode = onMismatch();
5044 }
5045 else {
5046 if (node.data !== vnode.children) {
5047 hasMismatch = true;
5048 warn$1(`Hydration text mismatch:` +
5049 `\n- Client: ${JSON.stringify(node.data)}` +
5050 `\n- Server: ${JSON.stringify(vnode.children)}`);
5051 node.data = vnode.children;
5052 }
5053 nextNode = nextSibling(node);
5054 }
5055 break;
5056 case Comment:
5057 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5058 nextNode = onMismatch();
5059 }
5060 else {
5061 nextNode = nextSibling(node);
5062 }
5063 break;
5064 case Static:
5065 if (domType !== 1 /* ELEMENT */) {
5066 nextNode = onMismatch();
5067 }
5068 else {
5069 // determine anchor, adopt content
5070 nextNode = node;
5071 // if the static vnode has its content stripped during build,
5072 // adopt it from the server-rendered HTML.
5073 const needToAdoptContent = !vnode.children.length;
5074 for (let i = 0; i < vnode.staticCount; i++) {
5075 if (needToAdoptContent)
5076 vnode.children += nextNode.outerHTML;
5077 if (i === vnode.staticCount - 1) {
5078 vnode.anchor = nextNode;
5079 }
5080 nextNode = nextSibling(nextNode);
5081 }
5082 return nextNode;
5083 }
5084 break;
5085 case Fragment:
5086 if (!isFragmentStart) {
5087 nextNode = onMismatch();
5088 }
5089 else {
5090 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5091 }
5092 break;
5093 default:
5094 if (shapeFlag & 1 /* ELEMENT */) {
5095 if (domType !== 1 /* ELEMENT */ ||
5096 vnode.type.toLowerCase() !==
5097 node.tagName.toLowerCase()) {
5098 nextNode = onMismatch();
5099 }
5100 else {
5101 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5102 }
5103 }
5104 else if (shapeFlag & 6 /* COMPONENT */) {
5105 // when setting up the render effect, if the initial vnode already
5106 // has .el set, the component will perform hydration instead of mount
5107 // on its sub-tree.
5108 vnode.slotScopeIds = slotScopeIds;
5109 const container = parentNode(node);
5110 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5111 // component may be async, so in the case of fragments we cannot rely
5112 // on component's rendered output to determine the end of the fragment
5113 // instead, we do a lookahead to find the end anchor node.
5114 nextNode = isFragmentStart
5115 ? locateClosingAsyncAnchor(node)
5116 : nextSibling(node);
5117 // #3787
5118 // if component is async, it may get moved / unmounted before its
5119 // inner component is loaded, so we need to give it a placeholder
5120 // vnode that matches its adopted DOM.
5121 if (isAsyncWrapper(vnode)) {
5122 let subTree;
5123 if (isFragmentStart) {
5124 subTree = createVNode(Fragment);
5125 subTree.anchor = nextNode
5126 ? nextNode.previousSibling
5127 : container.lastChild;
5128 }
5129 else {
5130 subTree =
5131 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5132 }
5133 subTree.el = node;
5134 vnode.component.subTree = subTree;
5135 }
5136 }
5137 else if (shapeFlag & 64 /* TELEPORT */) {
5138 if (domType !== 8 /* COMMENT */) {
5139 nextNode = onMismatch();
5140 }
5141 else {
5142 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5143 }
5144 }
5145 else if (shapeFlag & 128 /* SUSPENSE */) {
5146 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5147 }
5148 else {
5149 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5150 }
5151 }
5152 if (ref != null) {
5153 setRef(ref, null, parentSuspense, vnode);
5154 }
5155 return nextNode;
5156 };
5157 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5158 optimized = optimized || !!vnode.dynamicChildren;
5159 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5160 // #4006 for form elements with non-string v-model value bindings
5161 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5162 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5163 // skip props & children if this is hoisted static nodes
5164 if (forcePatchValue || patchFlag !== -1 /* HOISTED */) {
5165 if (dirs) {
5166 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5167 }
5168 // props
5169 if (props) {
5170 if (forcePatchValue ||
5171 !optimized ||
5172 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5173 for (const key in props) {
5174 if ((forcePatchValue && key.endsWith('value')) ||
5175 (isOn(key) && !isReservedProp(key))) {
5176 patchProp(el, key, null, props[key]);
5177 }
5178 }
5179 }
5180 else if (props.onClick) {
5181 // Fast path for click listeners (which is most often) to avoid
5182 // iterating through props.
5183 patchProp(el, 'onClick', null, props.onClick);
5184 }
5185 }
5186 // vnode / directive hooks
5187 let vnodeHooks;
5188 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5189 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5190 }
5191 if (dirs) {
5192 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5193 }
5194 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5195 queueEffectWithSuspense(() => {
5196 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5197 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5198 }, parentSuspense);
5199 }
5200 // children
5201 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5202 // skip if element has innerHTML / textContent
5203 !(props && (props.innerHTML || props.textContent))) {
5204 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5205 let hasWarned = false;
5206 while (next) {
5207 hasMismatch = true;
5208 if (!hasWarned) {
5209 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5210 `server rendered element contains more child nodes than client vdom.`);
5211 hasWarned = true;
5212 }
5213 // The SSRed DOM contains more nodes than it should. Remove them.
5214 const cur = next;
5215 next = next.nextSibling;
5216 remove(cur);
5217 }
5218 }
5219 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5220 if (el.textContent !== vnode.children) {
5221 hasMismatch = true;
5222 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5223 `- Client: ${el.textContent}\n` +
5224 `- Server: ${vnode.children}`);
5225 el.textContent = vnode.children;
5226 }
5227 }
5228 }
5229 return el.nextSibling;
5230 };
5231 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5232 optimized = optimized || !!parentVNode.dynamicChildren;
5233 const children = parentVNode.children;
5234 const l = children.length;
5235 let hasWarned = false;
5236 for (let i = 0; i < l; i++) {
5237 const vnode = optimized
5238 ? children[i]
5239 : (children[i] = normalizeVNode(children[i]));
5240 if (node) {
5241 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5242 }
5243 else if (vnode.type === Text && !vnode.children) {
5244 continue;
5245 }
5246 else {
5247 hasMismatch = true;
5248 if (!hasWarned) {
5249 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5250 `server rendered element contains fewer child nodes than client vdom.`);
5251 hasWarned = true;
5252 }
5253 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5254 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5255 }
5256 }
5257 return node;
5258 };
5259 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5260 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5261 if (fragmentSlotScopeIds) {
5262 slotScopeIds = slotScopeIds
5263 ? slotScopeIds.concat(fragmentSlotScopeIds)
5264 : fragmentSlotScopeIds;
5265 }
5266 const container = parentNode(node);
5267 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5268 if (next && isComment(next) && next.data === ']') {
5269 return nextSibling((vnode.anchor = next));
5270 }
5271 else {
5272 // fragment didn't hydrate successfully, since we didn't get a end anchor
5273 // back. This should have led to node/children mismatch warnings.
5274 hasMismatch = true;
5275 // since the anchor is missing, we need to create one and insert it
5276 insert((vnode.anchor = createComment(`]`)), container, next);
5277 return next;
5278 }
5279 };
5280 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5281 hasMismatch = true;
5282 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5283 ? `(text)`
5284 : isComment(node) && node.data === '['
5285 ? `(start of fragment)`
5286 : ``);
5287 vnode.el = null;
5288 if (isFragment) {
5289 // remove excessive fragment nodes
5290 const end = locateClosingAsyncAnchor(node);
5291 while (true) {
5292 const next = nextSibling(node);
5293 if (next && next !== end) {
5294 remove(next);
5295 }
5296 else {
5297 break;
5298 }
5299 }
5300 }
5301 const next = nextSibling(node);
5302 const container = parentNode(node);
5303 remove(node);
5304 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5305 return next;
5306 };
5307 const locateClosingAsyncAnchor = (node) => {
5308 let match = 0;
5309 while (node) {
5310 node = nextSibling(node);
5311 if (node && isComment(node)) {
5312 if (node.data === '[')
5313 match++;
5314 if (node.data === ']') {
5315 if (match === 0) {
5316 return nextSibling(node);
5317 }
5318 else {
5319 match--;
5320 }
5321 }
5322 }
5323 }
5324 return node;
5325 };
5326 return [hydrate, hydrateNode];
5327}
5328
5329let supported;
5330let perf;
5331function startMeasure(instance, type) {
5332 if (instance.appContext.config.performance && isSupported()) {
5333 perf.mark(`vue-${type}-${instance.uid}`);
5334 }
5335 {
5336 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5337 }
5338}
5339function endMeasure(instance, type) {
5340 if (instance.appContext.config.performance && isSupported()) {
5341 const startTag = `vue-${type}-${instance.uid}`;
5342 const endTag = startTag + `:end`;
5343 perf.mark(endTag);
5344 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5345 perf.clearMarks(startTag);
5346 perf.clearMarks(endTag);
5347 }
5348 {
5349 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5350 }
5351}
5352function isSupported() {
5353 if (supported !== undefined) {
5354 return supported;
5355 }
5356 /* eslint-disable no-restricted-globals */
5357 if (typeof window !== 'undefined' && window.performance) {
5358 supported = true;
5359 perf = window.performance;
5360 }
5361 else {
5362 supported = false;
5363 }
5364 /* eslint-enable no-restricted-globals */
5365 return supported;
5366}
5367
5368const queuePostRenderEffect = queueEffectWithSuspense
5369 ;
5370/**
5371 * The createRenderer function accepts two generic arguments:
5372 * HostNode and HostElement, corresponding to Node and Element types in the
5373 * host environment. For example, for runtime-dom, HostNode would be the DOM
5374 * `Node` interface and HostElement would be the DOM `Element` interface.
5375 *
5376 * Custom renderers can pass in the platform specific types like this:
5377 *
5378 * ``` js
5379 * const { render, createApp } = createRenderer<Node, Element>({
5380 * patchProp,
5381 * ...nodeOps
5382 * })
5383 * ```
5384 */
5385function createRenderer(options) {
5386 return baseCreateRenderer(options);
5387}
5388// Separate API for creating hydration-enabled renderer.
5389// Hydration logic is only used when calling this function, making it
5390// tree-shakable.
5391function createHydrationRenderer(options) {
5392 return baseCreateRenderer(options, createHydrationFunctions);
5393}
5394// implementation
5395function baseCreateRenderer(options, createHydrationFns) {
5396 {
5397 const target = getGlobalThis();
5398 target.__VUE__ = true;
5399 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
5400 }
5401 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;
5402 // Note: functions inside this closure should use `const xxx = () => {}`
5403 // style in order to prevent being inlined by minifiers.
5404 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5405 if (n1 === n2) {
5406 return;
5407 }
5408 // patching & not same type, unmount old tree
5409 if (n1 && !isSameVNodeType(n1, n2)) {
5410 anchor = getNextHostNode(n1);
5411 unmount(n1, parentComponent, parentSuspense, true);
5412 n1 = null;
5413 }
5414 if (n2.patchFlag === -2 /* BAIL */) {
5415 optimized = false;
5416 n2.dynamicChildren = null;
5417 }
5418 const { type, ref, shapeFlag } = n2;
5419 switch (type) {
5420 case Text:
5421 processText(n1, n2, container, anchor);
5422 break;
5423 case Comment:
5424 processCommentNode(n1, n2, container, anchor);
5425 break;
5426 case Static:
5427 if (n1 == null) {
5428 mountStaticNode(n2, container, anchor, isSVG);
5429 }
5430 else {
5431 patchStaticNode(n1, n2, container, isSVG);
5432 }
5433 break;
5434 case Fragment:
5435 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5436 break;
5437 default:
5438 if (shapeFlag & 1 /* ELEMENT */) {
5439 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5440 }
5441 else if (shapeFlag & 6 /* COMPONENT */) {
5442 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5443 }
5444 else if (shapeFlag & 64 /* TELEPORT */) {
5445 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5446 }
5447 else if (shapeFlag & 128 /* SUSPENSE */) {
5448 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5449 }
5450 else {
5451 warn$1('Invalid VNode type:', type, `(${typeof type})`);
5452 }
5453 }
5454 // set ref
5455 if (ref != null && parentComponent) {
5456 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5457 }
5458 };
5459 const processText = (n1, n2, container, anchor) => {
5460 if (n1 == null) {
5461 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5462 }
5463 else {
5464 const el = (n2.el = n1.el);
5465 if (n2.children !== n1.children) {
5466 hostSetText(el, n2.children);
5467 }
5468 }
5469 };
5470 const processCommentNode = (n1, n2, container, anchor) => {
5471 if (n1 == null) {
5472 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5473 }
5474 else {
5475 // there's no support for dynamic comments
5476 n2.el = n1.el;
5477 }
5478 };
5479 const mountStaticNode = (n2, container, anchor, isSVG) => {
5480 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5481 };
5482 /**
5483 * Dev / HMR only
5484 */
5485 const patchStaticNode = (n1, n2, container, isSVG) => {
5486 // static nodes are only patched during dev for HMR
5487 if (n2.children !== n1.children) {
5488 const anchor = hostNextSibling(n1.anchor);
5489 // remove existing
5490 removeStaticNode(n1);
5491 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5492 }
5493 else {
5494 n2.el = n1.el;
5495 n2.anchor = n1.anchor;
5496 }
5497 };
5498 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5499 let next;
5500 while (el && el !== anchor) {
5501 next = hostNextSibling(el);
5502 hostInsert(el, container, nextSibling);
5503 el = next;
5504 }
5505 hostInsert(anchor, container, nextSibling);
5506 };
5507 const removeStaticNode = ({ el, anchor }) => {
5508 let next;
5509 while (el && el !== anchor) {
5510 next = hostNextSibling(el);
5511 hostRemove(el);
5512 el = next;
5513 }
5514 hostRemove(anchor);
5515 };
5516 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5517 isSVG = isSVG || n2.type === 'svg';
5518 if (n1 == null) {
5519 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5520 }
5521 else {
5522 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5523 }
5524 };
5525 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5526 let el;
5527 let vnodeHook;
5528 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
5529 {
5530 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
5531 // mount children first, since some props may rely on child content
5532 // being already rendered, e.g. `<select value>`
5533 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5534 hostSetElementText(el, vnode.children);
5535 }
5536 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5537 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
5538 }
5539 if (dirs) {
5540 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5541 }
5542 // props
5543 if (props) {
5544 for (const key in props) {
5545 if (key !== 'value' && !isReservedProp(key)) {
5546 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5547 }
5548 }
5549 /**
5550 * Special case for setting value on DOM elements:
5551 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
5552 * - it needs to be forced (#1471)
5553 * #2353 proposes adding another renderer option to configure this, but
5554 * the properties affects are so finite it is worth special casing it
5555 * here to reduce the complexity. (Special casing it also should not
5556 * affect non-DOM renderers)
5557 */
5558 if ('value' in props) {
5559 hostPatchProp(el, 'value', null, props.value);
5560 }
5561 if ((vnodeHook = props.onVnodeBeforeMount)) {
5562 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5563 }
5564 }
5565 // scopeId
5566 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
5567 }
5568 {
5569 Object.defineProperty(el, '__vnode', {
5570 value: vnode,
5571 enumerable: false
5572 });
5573 Object.defineProperty(el, '__vueParentComponent', {
5574 value: parentComponent,
5575 enumerable: false
5576 });
5577 }
5578 if (dirs) {
5579 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5580 }
5581 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5582 // #1689 For inside suspense + suspense resolved case, just call it
5583 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5584 transition &&
5585 !transition.persisted;
5586 if (needCallTransitionHooks) {
5587 transition.beforeEnter(el);
5588 }
5589 hostInsert(el, container, anchor);
5590 if ((vnodeHook = props && props.onVnodeMounted) ||
5591 needCallTransitionHooks ||
5592 dirs) {
5593 queuePostRenderEffect(() => {
5594 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5595 needCallTransitionHooks && transition.enter(el);
5596 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5597 }, parentSuspense);
5598 }
5599 };
5600 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
5601 if (scopeId) {
5602 hostSetScopeId(el, scopeId);
5603 }
5604 if (slotScopeIds) {
5605 for (let i = 0; i < slotScopeIds.length; i++) {
5606 hostSetScopeId(el, slotScopeIds[i]);
5607 }
5608 }
5609 if (parentComponent) {
5610 let subTree = parentComponent.subTree;
5611 if (subTree.patchFlag > 0 &&
5612 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
5613 subTree =
5614 filterSingleRoot(subTree.children) || subTree;
5615 }
5616 if (vnode === subTree) {
5617 const parentVNode = parentComponent.vnode;
5618 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
5619 }
5620 }
5621 };
5622 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
5623 for (let i = start; i < children.length; i++) {
5624 const child = (children[i] = optimized
5625 ? cloneIfMounted(children[i])
5626 : normalizeVNode(children[i]));
5627 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5628 }
5629 };
5630 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5631 const el = (n2.el = n1.el);
5632 let { patchFlag, dynamicChildren, dirs } = n2;
5633 // #1426 take the old vnode's patch flag into account since user may clone a
5634 // compiler-generated vnode, which de-opts to FULL_PROPS
5635 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
5636 const oldProps = n1.props || EMPTY_OBJ;
5637 const newProps = n2.props || EMPTY_OBJ;
5638 let vnodeHook;
5639 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
5640 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5641 }
5642 if (dirs) {
5643 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
5644 }
5645 if (isHmrUpdating) {
5646 // HMR updated, force full diff
5647 patchFlag = 0;
5648 optimized = false;
5649 dynamicChildren = null;
5650 }
5651 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
5652 if (dynamicChildren) {
5653 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
5654 if (parentComponent && parentComponent.type.__hmrId) {
5655 traverseStaticChildren(n1, n2);
5656 }
5657 }
5658 else if (!optimized) {
5659 // full diff
5660 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
5661 }
5662 if (patchFlag > 0) {
5663 // the presence of a patchFlag means this element's render code was
5664 // generated by the compiler and can take the fast path.
5665 // in this path old node and new node are guaranteed to have the same shape
5666 // (i.e. at the exact same position in the source template)
5667 if (patchFlag & 16 /* FULL_PROPS */) {
5668 // element props contain dynamic keys, full diff needed
5669 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5670 }
5671 else {
5672 // class
5673 // this flag is matched when the element has dynamic class bindings.
5674 if (patchFlag & 2 /* CLASS */) {
5675 if (oldProps.class !== newProps.class) {
5676 hostPatchProp(el, 'class', null, newProps.class, isSVG);
5677 }
5678 }
5679 // style
5680 // this flag is matched when the element has dynamic style bindings
5681 if (patchFlag & 4 /* STYLE */) {
5682 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
5683 }
5684 // props
5685 // This flag is matched when the element has dynamic prop/attr bindings
5686 // other than class and style. The keys of dynamic prop/attrs are saved for
5687 // faster iteration.
5688 // Note dynamic keys like :[foo]="bar" will cause this optimization to
5689 // bail out and go through a full diff because we need to unset the old key
5690 if (patchFlag & 8 /* PROPS */) {
5691 // if the flag is present then dynamicProps must be non-null
5692 const propsToUpdate = n2.dynamicProps;
5693 for (let i = 0; i < propsToUpdate.length; i++) {
5694 const key = propsToUpdate[i];
5695 const prev = oldProps[key];
5696 const next = newProps[key];
5697 // #1471 force patch value
5698 if (next !== prev || key === 'value') {
5699 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
5700 }
5701 }
5702 }
5703 }
5704 // text
5705 // This flag is matched when the element has only dynamic text children.
5706 if (patchFlag & 1 /* TEXT */) {
5707 if (n1.children !== n2.children) {
5708 hostSetElementText(el, n2.children);
5709 }
5710 }
5711 }
5712 else if (!optimized && dynamicChildren == null) {
5713 // unoptimized, full diff
5714 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5715 }
5716 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
5717 queuePostRenderEffect(() => {
5718 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5719 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
5720 }, parentSuspense);
5721 }
5722 };
5723 // The fast path for blocks.
5724 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
5725 for (let i = 0; i < newChildren.length; i++) {
5726 const oldVNode = oldChildren[i];
5727 const newVNode = newChildren[i];
5728 // Determine the container (parent element) for the patch.
5729 const container =
5730 // oldVNode may be an errored async setup() component inside Suspense
5731 // which will not have a mounted element
5732 oldVNode.el &&
5733 // - In the case of a Fragment, we need to provide the actual parent
5734 // of the Fragment itself so it can move its children.
5735 (oldVNode.type === Fragment ||
5736 // - In the case of different nodes, there is going to be a replacement
5737 // which also requires the correct parent container
5738 !isSameVNodeType(oldVNode, newVNode) ||
5739 // - In the case of a component, it could contain anything.
5740 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
5741 ? hostParentNode(oldVNode.el)
5742 : // In other cases, the parent container is not actually used so we
5743 // just pass the block element here to avoid a DOM parentNode call.
5744 fallbackContainer;
5745 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
5746 }
5747 };
5748 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
5749 if (oldProps !== newProps) {
5750 for (const key in newProps) {
5751 // empty string is not valid prop
5752 if (isReservedProp(key))
5753 continue;
5754 const next = newProps[key];
5755 const prev = oldProps[key];
5756 // defer patching value
5757 if (next !== prev && key !== 'value') {
5758 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5759 }
5760 }
5761 if (oldProps !== EMPTY_OBJ) {
5762 for (const key in oldProps) {
5763 if (!isReservedProp(key) && !(key in newProps)) {
5764 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5765 }
5766 }
5767 }
5768 if ('value' in newProps) {
5769 hostPatchProp(el, 'value', oldProps.value, newProps.value);
5770 }
5771 }
5772 };
5773 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5774 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
5775 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
5776 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
5777 if (isHmrUpdating) {
5778 // HMR updated, force full diff
5779 patchFlag = 0;
5780 optimized = false;
5781 dynamicChildren = null;
5782 }
5783 // check if this is a slot fragment with :slotted scope ids
5784 if (fragmentSlotScopeIds) {
5785 slotScopeIds = slotScopeIds
5786 ? slotScopeIds.concat(fragmentSlotScopeIds)
5787 : fragmentSlotScopeIds;
5788 }
5789 if (n1 == null) {
5790 hostInsert(fragmentStartAnchor, container, anchor);
5791 hostInsert(fragmentEndAnchor, container, anchor);
5792 // a fragment can only have array children
5793 // since they are either generated by the compiler, or implicitly created
5794 // from arrays.
5795 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5796 }
5797 else {
5798 if (patchFlag > 0 &&
5799 patchFlag & 64 /* STABLE_FRAGMENT */ &&
5800 dynamicChildren &&
5801 // #2715 the previous fragment could've been a BAILed one as a result
5802 // of renderSlot() with no valid children
5803 n1.dynamicChildren) {
5804 // a stable fragment (template root or <template v-for>) doesn't need to
5805 // patch children order, but it may contain dynamicChildren.
5806 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
5807 if (parentComponent && parentComponent.type.__hmrId) {
5808 traverseStaticChildren(n1, n2);
5809 }
5810 else if (
5811 // #2080 if the stable fragment has a key, it's a <template v-for> that may
5812 // get moved around. Make sure all root level vnodes inherit el.
5813 // #2134 or if it's a component root, it may also get moved around
5814 // as the component is being moved.
5815 n2.key != null ||
5816 (parentComponent && n2 === parentComponent.subTree)) {
5817 traverseStaticChildren(n1, n2, true /* shallow */);
5818 }
5819 }
5820 else {
5821 // keyed / unkeyed, or manual fragments.
5822 // for keyed & unkeyed, since they are compiler generated from v-for,
5823 // each child is guaranteed to be a block so the fragment will never
5824 // have dynamicChildren.
5825 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5826 }
5827 }
5828 };
5829 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5830 n2.slotScopeIds = slotScopeIds;
5831 if (n1 == null) {
5832 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
5833 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
5834 }
5835 else {
5836 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5837 }
5838 }
5839 else {
5840 updateComponent(n1, n2, optimized);
5841 }
5842 };
5843 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5844 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
5845 if (instance.type.__hmrId) {
5846 registerHMR(instance);
5847 }
5848 {
5849 pushWarningContext(initialVNode);
5850 startMeasure(instance, `mount`);
5851 }
5852 // inject renderer internals for keepAlive
5853 if (isKeepAlive(initialVNode)) {
5854 instance.ctx.renderer = internals;
5855 }
5856 // resolve props and slots for setup context
5857 {
5858 {
5859 startMeasure(instance, `init`);
5860 }
5861 setupComponent(instance);
5862 {
5863 endMeasure(instance, `init`);
5864 }
5865 }
5866 // setup() is async. This component relies on async logic to be resolved
5867 // before proceeding
5868 if (instance.asyncDep) {
5869 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
5870 // Give it a placeholder if this is not hydration
5871 // TODO handle self-defined fallback
5872 if (!initialVNode.el) {
5873 const placeholder = (instance.subTree = createVNode(Comment));
5874 processCommentNode(null, placeholder, container, anchor);
5875 }
5876 return;
5877 }
5878 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
5879 {
5880 popWarningContext();
5881 endMeasure(instance, `mount`);
5882 }
5883 };
5884 const updateComponent = (n1, n2, optimized) => {
5885 const instance = (n2.component = n1.component);
5886 if (shouldUpdateComponent(n1, n2, optimized)) {
5887 if (instance.asyncDep &&
5888 !instance.asyncResolved) {
5889 // async & still pending - just update props and slots
5890 // since the component's reactive effect for render isn't set-up yet
5891 {
5892 pushWarningContext(n2);
5893 }
5894 updateComponentPreRender(instance, n2, optimized);
5895 {
5896 popWarningContext();
5897 }
5898 return;
5899 }
5900 else {
5901 // normal update
5902 instance.next = n2;
5903 // in case the child component is also queued, remove it to avoid
5904 // double updating the same child component in the same flush.
5905 invalidateJob(instance.update);
5906 // instance.update is the reactive effect.
5907 instance.update();
5908 }
5909 }
5910 else {
5911 // no update needed. just copy over properties
5912 n2.component = n1.component;
5913 n2.el = n1.el;
5914 instance.vnode = n2;
5915 }
5916 };
5917 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
5918 const componentUpdateFn = () => {
5919 if (!instance.isMounted) {
5920 let vnodeHook;
5921 const { el, props } = initialVNode;
5922 const { bm, m, parent } = instance;
5923 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
5924 effect.allowRecurse = false;
5925 // beforeMount hook
5926 if (bm) {
5927 invokeArrayFns(bm);
5928 }
5929 // onVnodeBeforeMount
5930 if (!isAsyncWrapperVNode &&
5931 (vnodeHook = props && props.onVnodeBeforeMount)) {
5932 invokeVNodeHook(vnodeHook, parent, initialVNode);
5933 }
5934 effect.allowRecurse = true;
5935 if (el && hydrateNode) {
5936 // vnode has adopted host node - perform hydration instead of mount.
5937 const hydrateSubTree = () => {
5938 {
5939 startMeasure(instance, `render`);
5940 }
5941 instance.subTree = renderComponentRoot(instance);
5942 {
5943 endMeasure(instance, `render`);
5944 }
5945 {
5946 startMeasure(instance, `hydrate`);
5947 }
5948 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
5949 {
5950 endMeasure(instance, `hydrate`);
5951 }
5952 };
5953 if (isAsyncWrapperVNode) {
5954 initialVNode.type.__asyncLoader().then(
5955 // note: we are moving the render call into an async callback,
5956 // which means it won't track dependencies - but it's ok because
5957 // a server-rendered async wrapper is already in resolved state
5958 // and it will never need to change.
5959 () => !instance.isUnmounted && hydrateSubTree());
5960 }
5961 else {
5962 hydrateSubTree();
5963 }
5964 }
5965 else {
5966 {
5967 startMeasure(instance, `render`);
5968 }
5969 const subTree = (instance.subTree = renderComponentRoot(instance));
5970 {
5971 endMeasure(instance, `render`);
5972 }
5973 {
5974 startMeasure(instance, `patch`);
5975 }
5976 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
5977 {
5978 endMeasure(instance, `patch`);
5979 }
5980 initialVNode.el = subTree.el;
5981 }
5982 // mounted hook
5983 if (m) {
5984 queuePostRenderEffect(m, parentSuspense);
5985 }
5986 // onVnodeMounted
5987 if (!isAsyncWrapperVNode &&
5988 (vnodeHook = props && props.onVnodeMounted)) {
5989 const scopedInitialVNode = initialVNode;
5990 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
5991 }
5992 // activated hook for keep-alive roots.
5993 // #1742 activated hook must be accessed after first render
5994 // since the hook may be injected by a child keep-alive
5995 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5996 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
5997 }
5998 instance.isMounted = true;
5999 {
6000 devtoolsComponentAdded(instance);
6001 }
6002 // #2458: deference mount-only object parameters to prevent memleaks
6003 initialVNode = container = anchor = null;
6004 }
6005 else {
6006 // updateComponent
6007 // This is triggered by mutation of component's own state (next: null)
6008 // OR parent calling processComponent (next: VNode)
6009 let { next, bu, u, parent, vnode } = instance;
6010 let originNext = next;
6011 let vnodeHook;
6012 {
6013 pushWarningContext(next || instance.vnode);
6014 }
6015 // Disallow component effect recursion during pre-lifecycle hooks.
6016 effect.allowRecurse = false;
6017 if (next) {
6018 next.el = vnode.el;
6019 updateComponentPreRender(instance, next, optimized);
6020 }
6021 else {
6022 next = vnode;
6023 }
6024 // beforeUpdate hook
6025 if (bu) {
6026 invokeArrayFns(bu);
6027 }
6028 // onVnodeBeforeUpdate
6029 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6030 invokeVNodeHook(vnodeHook, parent, next, vnode);
6031 }
6032 effect.allowRecurse = true;
6033 // render
6034 {
6035 startMeasure(instance, `render`);
6036 }
6037 const nextTree = renderComponentRoot(instance);
6038 {
6039 endMeasure(instance, `render`);
6040 }
6041 const prevTree = instance.subTree;
6042 instance.subTree = nextTree;
6043 {
6044 startMeasure(instance, `patch`);
6045 }
6046 patch(prevTree, nextTree,
6047 // parent may have changed if it's in a teleport
6048 hostParentNode(prevTree.el),
6049 // anchor may have changed if it's in a fragment
6050 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6051 {
6052 endMeasure(instance, `patch`);
6053 }
6054 next.el = nextTree.el;
6055 if (originNext === null) {
6056 // self-triggered update. In case of HOC, update parent component
6057 // vnode el. HOC is indicated by parent instance's subTree pointing
6058 // to child component's vnode
6059 updateHOCHostEl(instance, nextTree.el);
6060 }
6061 // updated hook
6062 if (u) {
6063 queuePostRenderEffect(u, parentSuspense);
6064 }
6065 // onVnodeUpdated
6066 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6067 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6068 }
6069 {
6070 devtoolsComponentUpdated(instance);
6071 }
6072 {
6073 popWarningContext();
6074 }
6075 }
6076 };
6077 // create reactive effect for rendering
6078 const effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6079 );
6080 const update = (instance.update = effect.run.bind(effect));
6081 update.id = instance.uid;
6082 // allowRecurse
6083 // #1801, #2043 component render effects should allow recursive updates
6084 effect.allowRecurse = update.allowRecurse = true;
6085 {
6086 effect.onTrack = instance.rtc
6087 ? e => invokeArrayFns(instance.rtc, e)
6088 : void 0;
6089 effect.onTrigger = instance.rtg
6090 ? e => invokeArrayFns(instance.rtg, e)
6091 : void 0;
6092 // @ts-ignore (for scheduler)
6093 update.ownerInstance = instance;
6094 }
6095 update();
6096 };
6097 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6098 nextVNode.component = instance;
6099 const prevProps = instance.vnode.props;
6100 instance.vnode = nextVNode;
6101 instance.next = null;
6102 updateProps(instance, nextVNode.props, prevProps, optimized);
6103 updateSlots(instance, nextVNode.children, optimized);
6104 pauseTracking();
6105 // props update may have triggered pre-flush watchers.
6106 // flush them before the render update.
6107 flushPreFlushCbs(undefined, instance.update);
6108 resetTracking();
6109 };
6110 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6111 const c1 = n1 && n1.children;
6112 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6113 const c2 = n2.children;
6114 const { patchFlag, shapeFlag } = n2;
6115 // fast path
6116 if (patchFlag > 0) {
6117 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6118 // this could be either fully-keyed or mixed (some keyed some not)
6119 // presence of patchFlag means children are guaranteed to be arrays
6120 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6121 return;
6122 }
6123 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6124 // unkeyed
6125 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6126 return;
6127 }
6128 }
6129 // children has 3 possibilities: text, array or no children.
6130 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6131 // text children fast path
6132 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6133 unmountChildren(c1, parentComponent, parentSuspense);
6134 }
6135 if (c2 !== c1) {
6136 hostSetElementText(container, c2);
6137 }
6138 }
6139 else {
6140 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6141 // prev children was array
6142 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6143 // two arrays, cannot assume anything, do full diff
6144 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6145 }
6146 else {
6147 // no new children, just unmount old
6148 unmountChildren(c1, parentComponent, parentSuspense, true);
6149 }
6150 }
6151 else {
6152 // prev children was text OR null
6153 // new children is array OR null
6154 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6155 hostSetElementText(container, '');
6156 }
6157 // mount new if array
6158 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6159 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6160 }
6161 }
6162 }
6163 };
6164 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6165 c1 = c1 || EMPTY_ARR;
6166 c2 = c2 || EMPTY_ARR;
6167 const oldLength = c1.length;
6168 const newLength = c2.length;
6169 const commonLength = Math.min(oldLength, newLength);
6170 let i;
6171 for (i = 0; i < commonLength; i++) {
6172 const nextChild = (c2[i] = optimized
6173 ? cloneIfMounted(c2[i])
6174 : normalizeVNode(c2[i]));
6175 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6176 }
6177 if (oldLength > newLength) {
6178 // remove old
6179 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6180 }
6181 else {
6182 // mount new
6183 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6184 }
6185 };
6186 // can be all-keyed or mixed
6187 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6188 let i = 0;
6189 const l2 = c2.length;
6190 let e1 = c1.length - 1; // prev ending index
6191 let e2 = l2 - 1; // next ending index
6192 // 1. sync from start
6193 // (a b) c
6194 // (a b) d e
6195 while (i <= e1 && i <= e2) {
6196 const n1 = c1[i];
6197 const n2 = (c2[i] = optimized
6198 ? cloneIfMounted(c2[i])
6199 : normalizeVNode(c2[i]));
6200 if (isSameVNodeType(n1, n2)) {
6201 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6202 }
6203 else {
6204 break;
6205 }
6206 i++;
6207 }
6208 // 2. sync from end
6209 // a (b c)
6210 // d e (b c)
6211 while (i <= e1 && i <= e2) {
6212 const n1 = c1[e1];
6213 const n2 = (c2[e2] = optimized
6214 ? cloneIfMounted(c2[e2])
6215 : normalizeVNode(c2[e2]));
6216 if (isSameVNodeType(n1, n2)) {
6217 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6218 }
6219 else {
6220 break;
6221 }
6222 e1--;
6223 e2--;
6224 }
6225 // 3. common sequence + mount
6226 // (a b)
6227 // (a b) c
6228 // i = 2, e1 = 1, e2 = 2
6229 // (a b)
6230 // c (a b)
6231 // i = 0, e1 = -1, e2 = 0
6232 if (i > e1) {
6233 if (i <= e2) {
6234 const nextPos = e2 + 1;
6235 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6236 while (i <= e2) {
6237 patch(null, (c2[i] = optimized
6238 ? cloneIfMounted(c2[i])
6239 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6240 i++;
6241 }
6242 }
6243 }
6244 // 4. common sequence + unmount
6245 // (a b) c
6246 // (a b)
6247 // i = 2, e1 = 2, e2 = 1
6248 // a (b c)
6249 // (b c)
6250 // i = 0, e1 = 0, e2 = -1
6251 else if (i > e2) {
6252 while (i <= e1) {
6253 unmount(c1[i], parentComponent, parentSuspense, true);
6254 i++;
6255 }
6256 }
6257 // 5. unknown sequence
6258 // [i ... e1 + 1]: a b [c d e] f g
6259 // [i ... e2 + 1]: a b [e d c h] f g
6260 // i = 2, e1 = 4, e2 = 5
6261 else {
6262 const s1 = i; // prev starting index
6263 const s2 = i; // next starting index
6264 // 5.1 build key:index map for newChildren
6265 const keyToNewIndexMap = new Map();
6266 for (i = s2; i <= e2; i++) {
6267 const nextChild = (c2[i] = optimized
6268 ? cloneIfMounted(c2[i])
6269 : normalizeVNode(c2[i]));
6270 if (nextChild.key != null) {
6271 if (keyToNewIndexMap.has(nextChild.key)) {
6272 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6273 }
6274 keyToNewIndexMap.set(nextChild.key, i);
6275 }
6276 }
6277 // 5.2 loop through old children left to be patched and try to patch
6278 // matching nodes & remove nodes that are no longer present
6279 let j;
6280 let patched = 0;
6281 const toBePatched = e2 - s2 + 1;
6282 let moved = false;
6283 // used to track whether any node has moved
6284 let maxNewIndexSoFar = 0;
6285 // works as Map<newIndex, oldIndex>
6286 // Note that oldIndex is offset by +1
6287 // and oldIndex = 0 is a special value indicating the new node has
6288 // no corresponding old node.
6289 // used for determining longest stable subsequence
6290 const newIndexToOldIndexMap = new Array(toBePatched);
6291 for (i = 0; i < toBePatched; i++)
6292 newIndexToOldIndexMap[i] = 0;
6293 for (i = s1; i <= e1; i++) {
6294 const prevChild = c1[i];
6295 if (patched >= toBePatched) {
6296 // all new children have been patched so this can only be a removal
6297 unmount(prevChild, parentComponent, parentSuspense, true);
6298 continue;
6299 }
6300 let newIndex;
6301 if (prevChild.key != null) {
6302 newIndex = keyToNewIndexMap.get(prevChild.key);
6303 }
6304 else {
6305 // key-less node, try to locate a key-less node of the same type
6306 for (j = s2; j <= e2; j++) {
6307 if (newIndexToOldIndexMap[j - s2] === 0 &&
6308 isSameVNodeType(prevChild, c2[j])) {
6309 newIndex = j;
6310 break;
6311 }
6312 }
6313 }
6314 if (newIndex === undefined) {
6315 unmount(prevChild, parentComponent, parentSuspense, true);
6316 }
6317 else {
6318 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6319 if (newIndex >= maxNewIndexSoFar) {
6320 maxNewIndexSoFar = newIndex;
6321 }
6322 else {
6323 moved = true;
6324 }
6325 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6326 patched++;
6327 }
6328 }
6329 // 5.3 move and mount
6330 // generate longest stable subsequence only when nodes have moved
6331 const increasingNewIndexSequence = moved
6332 ? getSequence(newIndexToOldIndexMap)
6333 : EMPTY_ARR;
6334 j = increasingNewIndexSequence.length - 1;
6335 // looping backwards so that we can use last patched node as anchor
6336 for (i = toBePatched - 1; i >= 0; i--) {
6337 const nextIndex = s2 + i;
6338 const nextChild = c2[nextIndex];
6339 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6340 if (newIndexToOldIndexMap[i] === 0) {
6341 // mount new
6342 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6343 }
6344 else if (moved) {
6345 // move if:
6346 // There is no stable subsequence (e.g. a reverse)
6347 // OR current node is not among the stable sequence
6348 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6349 move(nextChild, container, anchor, 2 /* REORDER */);
6350 }
6351 else {
6352 j--;
6353 }
6354 }
6355 }
6356 }
6357 };
6358 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6359 const { el, type, transition, children, shapeFlag } = vnode;
6360 if (shapeFlag & 6 /* COMPONENT */) {
6361 move(vnode.component.subTree, container, anchor, moveType);
6362 return;
6363 }
6364 if (shapeFlag & 128 /* SUSPENSE */) {
6365 vnode.suspense.move(container, anchor, moveType);
6366 return;
6367 }
6368 if (shapeFlag & 64 /* TELEPORT */) {
6369 type.move(vnode, container, anchor, internals);
6370 return;
6371 }
6372 if (type === Fragment) {
6373 hostInsert(el, container, anchor);
6374 for (let i = 0; i < children.length; i++) {
6375 move(children[i], container, anchor, moveType);
6376 }
6377 hostInsert(vnode.anchor, container, anchor);
6378 return;
6379 }
6380 if (type === Static) {
6381 moveStaticNode(vnode, container, anchor);
6382 return;
6383 }
6384 // single nodes
6385 const needTransition = moveType !== 2 /* REORDER */ &&
6386 shapeFlag & 1 /* ELEMENT */ &&
6387 transition;
6388 if (needTransition) {
6389 if (moveType === 0 /* ENTER */) {
6390 transition.beforeEnter(el);
6391 hostInsert(el, container, anchor);
6392 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6393 }
6394 else {
6395 const { leave, delayLeave, afterLeave } = transition;
6396 const remove = () => hostInsert(el, container, anchor);
6397 const performLeave = () => {
6398 leave(el, () => {
6399 remove();
6400 afterLeave && afterLeave();
6401 });
6402 };
6403 if (delayLeave) {
6404 delayLeave(el, remove, performLeave);
6405 }
6406 else {
6407 performLeave();
6408 }
6409 }
6410 }
6411 else {
6412 hostInsert(el, container, anchor);
6413 }
6414 };
6415 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6416 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6417 // unset ref
6418 if (ref != null) {
6419 setRef(ref, null, parentSuspense, vnode, true);
6420 }
6421 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6422 parentComponent.ctx.deactivate(vnode);
6423 return;
6424 }
6425 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6426 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6427 let vnodeHook;
6428 if (shouldInvokeVnodeHook &&
6429 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6430 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6431 }
6432 if (shapeFlag & 6 /* COMPONENT */) {
6433 unmountComponent(vnode.component, parentSuspense, doRemove);
6434 }
6435 else {
6436 if (shapeFlag & 128 /* SUSPENSE */) {
6437 vnode.suspense.unmount(parentSuspense, doRemove);
6438 return;
6439 }
6440 if (shouldInvokeDirs) {
6441 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6442 }
6443 if (shapeFlag & 64 /* TELEPORT */) {
6444 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6445 }
6446 else if (dynamicChildren &&
6447 // #1153: fast path should not be taken for non-stable (v-for) fragments
6448 (type !== Fragment ||
6449 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6450 // fast path for block nodes: only need to unmount dynamic children.
6451 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6452 }
6453 else if ((type === Fragment &&
6454 patchFlag &
6455 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
6456 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6457 unmountChildren(children, parentComponent, parentSuspense);
6458 }
6459 if (doRemove) {
6460 remove(vnode);
6461 }
6462 }
6463 if ((shouldInvokeVnodeHook &&
6464 (vnodeHook = props && props.onVnodeUnmounted)) ||
6465 shouldInvokeDirs) {
6466 queuePostRenderEffect(() => {
6467 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6468 shouldInvokeDirs &&
6469 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6470 }, parentSuspense);
6471 }
6472 };
6473 const remove = vnode => {
6474 const { type, el, anchor, transition } = vnode;
6475 if (type === Fragment) {
6476 removeFragment(el, anchor);
6477 return;
6478 }
6479 if (type === Static) {
6480 removeStaticNode(vnode);
6481 return;
6482 }
6483 const performRemove = () => {
6484 hostRemove(el);
6485 if (transition && !transition.persisted && transition.afterLeave) {
6486 transition.afterLeave();
6487 }
6488 };
6489 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6490 transition &&
6491 !transition.persisted) {
6492 const { leave, delayLeave } = transition;
6493 const performLeave = () => leave(el, performRemove);
6494 if (delayLeave) {
6495 delayLeave(vnode.el, performRemove, performLeave);
6496 }
6497 else {
6498 performLeave();
6499 }
6500 }
6501 else {
6502 performRemove();
6503 }
6504 };
6505 const removeFragment = (cur, end) => {
6506 // For fragments, directly remove all contained DOM nodes.
6507 // (fragment child nodes cannot have transition)
6508 let next;
6509 while (cur !== end) {
6510 next = hostNextSibling(cur);
6511 hostRemove(cur);
6512 cur = next;
6513 }
6514 hostRemove(end);
6515 };
6516 const unmountComponent = (instance, parentSuspense, doRemove) => {
6517 if (instance.type.__hmrId) {
6518 unregisterHMR(instance);
6519 }
6520 const { bum, scope, update, subTree, um } = instance;
6521 // beforeUnmount hook
6522 if (bum) {
6523 invokeArrayFns(bum);
6524 }
6525 // stop effects in component scope
6526 scope.stop();
6527 // update may be null if a component is unmounted before its async
6528 // setup has resolved.
6529 if (update) {
6530 // so that scheduler will no longer invoke it
6531 update.active = false;
6532 unmount(subTree, instance, parentSuspense, doRemove);
6533 }
6534 // unmounted hook
6535 if (um) {
6536 queuePostRenderEffect(um, parentSuspense);
6537 }
6538 queuePostRenderEffect(() => {
6539 instance.isUnmounted = true;
6540 }, parentSuspense);
6541 // A component with async dep inside a pending suspense is unmounted before
6542 // its async dep resolves. This should remove the dep from the suspense, and
6543 // cause the suspense to resolve immediately if that was the last dep.
6544 if (parentSuspense &&
6545 parentSuspense.pendingBranch &&
6546 !parentSuspense.isUnmounted &&
6547 instance.asyncDep &&
6548 !instance.asyncResolved &&
6549 instance.suspenseId === parentSuspense.pendingId) {
6550 parentSuspense.deps--;
6551 if (parentSuspense.deps === 0) {
6552 parentSuspense.resolve();
6553 }
6554 }
6555 {
6556 devtoolsComponentRemoved(instance);
6557 }
6558 };
6559 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
6560 for (let i = start; i < children.length; i++) {
6561 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
6562 }
6563 };
6564 const getNextHostNode = vnode => {
6565 if (vnode.shapeFlag & 6 /* COMPONENT */) {
6566 return getNextHostNode(vnode.component.subTree);
6567 }
6568 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
6569 return vnode.suspense.next();
6570 }
6571 return hostNextSibling((vnode.anchor || vnode.el));
6572 };
6573 const render = (vnode, container, isSVG) => {
6574 if (vnode == null) {
6575 if (container._vnode) {
6576 unmount(container._vnode, null, null, true);
6577 }
6578 }
6579 else {
6580 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
6581 }
6582 flushPostFlushCbs();
6583 container._vnode = vnode;
6584 };
6585 const internals = {
6586 p: patch,
6587 um: unmount,
6588 m: move,
6589 r: remove,
6590 mt: mountComponent,
6591 mc: mountChildren,
6592 pc: patchChildren,
6593 pbc: patchBlockChildren,
6594 n: getNextHostNode,
6595 o: options
6596 };
6597 let hydrate;
6598 let hydrateNode;
6599 if (createHydrationFns) {
6600 [hydrate, hydrateNode] = createHydrationFns(internals);
6601 }
6602 return {
6603 render,
6604 hydrate,
6605 createApp: createAppAPI(render, hydrate)
6606 };
6607}
6608function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
6609 if (isArray(rawRef)) {
6610 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
6611 return;
6612 }
6613 if (isAsyncWrapper(vnode) && !isUnmount) {
6614 // when mounting async components, nothing needs to be done,
6615 // because the template ref is forwarded to inner component
6616 return;
6617 }
6618 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
6619 ? getExposeProxy(vnode.component) || vnode.component.proxy
6620 : vnode.el;
6621 const value = isUnmount ? null : refValue;
6622 const { i: owner, r: ref } = rawRef;
6623 if (!owner) {
6624 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
6625 `A vnode with ref must be created inside the render function.`);
6626 return;
6627 }
6628 const oldRef = oldRawRef && oldRawRef.r;
6629 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
6630 const setupState = owner.setupState;
6631 // dynamic ref changed. unset old ref
6632 if (oldRef != null && oldRef !== ref) {
6633 if (isString(oldRef)) {
6634 refs[oldRef] = null;
6635 if (hasOwn(setupState, oldRef)) {
6636 setupState[oldRef] = null;
6637 }
6638 }
6639 else if (isRef(oldRef)) {
6640 oldRef.value = null;
6641 }
6642 }
6643 if (isString(ref)) {
6644 const doSet = () => {
6645 {
6646 refs[ref] = value;
6647 }
6648 if (hasOwn(setupState, ref)) {
6649 setupState[ref] = value;
6650 }
6651 };
6652 // #1789: for non-null values, set them after render
6653 // null values means this is unmount and it should not overwrite another
6654 // ref with the same key
6655 if (value) {
6656 doSet.id = -1;
6657 queuePostRenderEffect(doSet, parentSuspense);
6658 }
6659 else {
6660 doSet();
6661 }
6662 }
6663 else if (isRef(ref)) {
6664 const doSet = () => {
6665 ref.value = value;
6666 };
6667 if (value) {
6668 doSet.id = -1;
6669 queuePostRenderEffect(doSet, parentSuspense);
6670 }
6671 else {
6672 doSet();
6673 }
6674 }
6675 else if (isFunction(ref)) {
6676 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
6677 }
6678 else {
6679 warn$1('Invalid template ref type:', value, `(${typeof value})`);
6680 }
6681}
6682function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6683 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6684 vnode,
6685 prevVNode
6686 ]);
6687}
6688/**
6689 * #1156
6690 * When a component is HMR-enabled, we need to make sure that all static nodes
6691 * inside a block also inherit the DOM element from the previous tree so that
6692 * HMR updates (which are full updates) can retrieve the element for patching.
6693 *
6694 * #2080
6695 * Inside keyed `template` fragment static children, if a fragment is moved,
6696 * the children will always moved so that need inherit el form previous nodes
6697 * to ensure correct moved position.
6698 */
6699function traverseStaticChildren(n1, n2, shallow = false) {
6700 const ch1 = n1.children;
6701 const ch2 = n2.children;
6702 if (isArray(ch1) && isArray(ch2)) {
6703 for (let i = 0; i < ch1.length; i++) {
6704 // this is only called in the optimized path so array children are
6705 // guaranteed to be vnodes
6706 const c1 = ch1[i];
6707 let c2 = ch2[i];
6708 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
6709 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
6710 c2 = ch2[i] = cloneIfMounted(ch2[i]);
6711 c2.el = c1.el;
6712 }
6713 if (!shallow)
6714 traverseStaticChildren(c1, c2);
6715 }
6716 // also inherit for comment nodes, but not placeholders (e.g. v-if which
6717 // would have received .el during block patch)
6718 if (c2.type === Comment && !c2.el) {
6719 c2.el = c1.el;
6720 }
6721 }
6722 }
6723}
6724// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
6725function getSequence(arr) {
6726 const p = arr.slice();
6727 const result = [0];
6728 let i, j, u, v, c;
6729 const len = arr.length;
6730 for (i = 0; i < len; i++) {
6731 const arrI = arr[i];
6732 if (arrI !== 0) {
6733 j = result[result.length - 1];
6734 if (arr[j] < arrI) {
6735 p[i] = j;
6736 result.push(i);
6737 continue;
6738 }
6739 u = 0;
6740 v = result.length - 1;
6741 while (u < v) {
6742 c = (u + v) >> 1;
6743 if (arr[result[c]] < arrI) {
6744 u = c + 1;
6745 }
6746 else {
6747 v = c;
6748 }
6749 }
6750 if (arrI < arr[result[u]]) {
6751 if (u > 0) {
6752 p[i] = result[u - 1];
6753 }
6754 result[u] = i;
6755 }
6756 }
6757 }
6758 u = result.length;
6759 v = result[u - 1];
6760 while (u-- > 0) {
6761 result[u] = v;
6762 v = p[v];
6763 }
6764 return result;
6765}
6766
6767const isTeleport = (type) => type.__isTeleport;
6768const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
6769const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
6770const resolveTarget = (props, select) => {
6771 const targetSelector = props && props.to;
6772 if (isString(targetSelector)) {
6773 if (!select) {
6774 warn$1(`Current renderer does not support string target for Teleports. ` +
6775 `(missing querySelector renderer option)`);
6776 return null;
6777 }
6778 else {
6779 const target = select(targetSelector);
6780 if (!target) {
6781 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
6782 `Note the target element must exist before the component is mounted - ` +
6783 `i.e. the target cannot be rendered by the component itself, and ` +
6784 `ideally should be outside of the entire Vue component tree.`);
6785 }
6786 return target;
6787 }
6788 }
6789 else {
6790 if (!targetSelector && !isTeleportDisabled(props)) {
6791 warn$1(`Invalid Teleport target: ${targetSelector}`);
6792 }
6793 return targetSelector;
6794 }
6795};
6796const TeleportImpl = {
6797 __isTeleport: true,
6798 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
6799 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
6800 const disabled = isTeleportDisabled(n2.props);
6801 let { shapeFlag, children, dynamicChildren } = n2;
6802 // #3302
6803 // HMR updated, force full diff
6804 if (isHmrUpdating) {
6805 optimized = false;
6806 dynamicChildren = null;
6807 }
6808 if (n1 == null) {
6809 // insert anchors in the main view
6810 const placeholder = (n2.el = createComment('teleport start')
6811 );
6812 const mainAnchor = (n2.anchor = createComment('teleport end')
6813 );
6814 insert(placeholder, container, anchor);
6815 insert(mainAnchor, container, anchor);
6816 const target = (n2.target = resolveTarget(n2.props, querySelector));
6817 const targetAnchor = (n2.targetAnchor = createText(''));
6818 if (target) {
6819 insert(targetAnchor, target);
6820 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
6821 isSVG = isSVG || isTargetSVG(target);
6822 }
6823 else if (!disabled) {
6824 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
6825 }
6826 const mount = (container, anchor) => {
6827 // Teleport *always* has Array children. This is enforced in both the
6828 // compiler and vnode children normalization.
6829 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6830 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6831 }
6832 };
6833 if (disabled) {
6834 mount(container, mainAnchor);
6835 }
6836 else if (target) {
6837 mount(target, targetAnchor);
6838 }
6839 }
6840 else {
6841 // update content
6842 n2.el = n1.el;
6843 const mainAnchor = (n2.anchor = n1.anchor);
6844 const target = (n2.target = n1.target);
6845 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
6846 const wasDisabled = isTeleportDisabled(n1.props);
6847 const currentContainer = wasDisabled ? container : target;
6848 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
6849 isSVG = isSVG || isTargetSVG(target);
6850 if (dynamicChildren) {
6851 // fast path when the teleport happens to be a block root
6852 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
6853 // even in block tree mode we need to make sure all root-level nodes
6854 // in the teleport inherit previous DOM references so that they can
6855 // be moved in future patches.
6856 traverseStaticChildren(n1, n2, true);
6857 }
6858 else if (!optimized) {
6859 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
6860 }
6861 if (disabled) {
6862 if (!wasDisabled) {
6863 // enabled -> disabled
6864 // move into main container
6865 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
6866 }
6867 }
6868 else {
6869 // target changed
6870 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
6871 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
6872 if (nextTarget) {
6873 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
6874 }
6875 else {
6876 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
6877 }
6878 }
6879 else if (wasDisabled) {
6880 // disabled -> enabled
6881 // move into teleport target
6882 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
6883 }
6884 }
6885 }
6886 },
6887 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
6888 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
6889 if (target) {
6890 hostRemove(targetAnchor);
6891 }
6892 // an unmounted teleport should always remove its children if not disabled
6893 if (doRemove || !isTeleportDisabled(props)) {
6894 hostRemove(anchor);
6895 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6896 for (let i = 0; i < children.length; i++) {
6897 const child = children[i];
6898 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
6899 }
6900 }
6901 }
6902 },
6903 move: moveTeleport,
6904 hydrate: hydrateTeleport
6905};
6906function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
6907 // move target anchor if this is a target change.
6908 if (moveType === 0 /* TARGET_CHANGE */) {
6909 insert(vnode.targetAnchor, container, parentAnchor);
6910 }
6911 const { el, anchor, shapeFlag, children, props } = vnode;
6912 const isReorder = moveType === 2 /* REORDER */;
6913 // move main view anchor if this is a re-order.
6914 if (isReorder) {
6915 insert(el, container, parentAnchor);
6916 }
6917 // if this is a re-order and teleport is enabled (content is in target)
6918 // do not move children. So the opposite is: only move children if this
6919 // is not a reorder, or the teleport is disabled
6920 if (!isReorder || isTeleportDisabled(props)) {
6921 // Teleport has either Array children or no children.
6922 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6923 for (let i = 0; i < children.length; i++) {
6924 move(children[i], container, parentAnchor, 2 /* REORDER */);
6925 }
6926 }
6927 }
6928 // move main view anchor if this is a re-order.
6929 if (isReorder) {
6930 insert(anchor, container, parentAnchor);
6931 }
6932}
6933function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
6934 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
6935 if (target) {
6936 // if multiple teleports rendered to the same target element, we need to
6937 // pick up from where the last teleport finished instead of the first node
6938 const targetNode = target._lpa || target.firstChild;
6939 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
6940 if (isTeleportDisabled(vnode.props)) {
6941 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
6942 vnode.targetAnchor = targetNode;
6943 }
6944 else {
6945 vnode.anchor = nextSibling(node);
6946 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
6947 }
6948 target._lpa =
6949 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
6950 }
6951 }
6952 return vnode.anchor && nextSibling(vnode.anchor);
6953}
6954// Force-casted public typing for h and TSX props inference
6955const Teleport = TeleportImpl;
6956
6957const COMPONENTS = 'components';
6958const DIRECTIVES = 'directives';
6959/**
6960 * @private
6961 */
6962function resolveComponent(name, maybeSelfReference) {
6963 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
6964}
6965const NULL_DYNAMIC_COMPONENT = Symbol();
6966/**
6967 * @private
6968 */
6969function resolveDynamicComponent(component) {
6970 if (isString(component)) {
6971 return resolveAsset(COMPONENTS, component, false) || component;
6972 }
6973 else {
6974 // invalid types will fallthrough to createVNode and raise warning
6975 return (component || NULL_DYNAMIC_COMPONENT);
6976 }
6977}
6978/**
6979 * @private
6980 */
6981function resolveDirective(name) {
6982 return resolveAsset(DIRECTIVES, name);
6983}
6984// implementation
6985function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
6986 const instance = currentRenderingInstance || currentInstance;
6987 if (instance) {
6988 const Component = instance.type;
6989 // explicit self name has highest priority
6990 if (type === COMPONENTS) {
6991 const selfName = getComponentName(Component);
6992 if (selfName &&
6993 (selfName === name ||
6994 selfName === camelize(name) ||
6995 selfName === capitalize(camelize(name)))) {
6996 return Component;
6997 }
6998 }
6999 const res =
7000 // local registration
7001 // check instance[type] first which is resolved for options API
7002 resolve(instance[type] || Component[type], name) ||
7003 // global registration
7004 resolve(instance.appContext[type], name);
7005 if (!res && maybeSelfReference) {
7006 // fallback to implicit self-reference
7007 return Component;
7008 }
7009 if (warnMissing && !res) {
7010 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
7011 }
7012 return res;
7013 }
7014 else {
7015 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7016 `can only be used in render() or setup().`);
7017 }
7018}
7019function resolve(registry, name) {
7020 return (registry &&
7021 (registry[name] ||
7022 registry[camelize(name)] ||
7023 registry[capitalize(camelize(name))]));
7024}
7025
7026const Fragment = Symbol('Fragment' );
7027const Text = Symbol('Text' );
7028const Comment = Symbol('Comment' );
7029const Static = Symbol('Static' );
7030// Since v-if and v-for are the two possible ways node structure can dynamically
7031// change, once we consider v-if branches and each v-for fragment a block, we
7032// can divide a template into nested blocks, and within each block the node
7033// structure would be stable. This allows us to skip most children diffing
7034// and only worry about the dynamic nodes (indicated by patch flags).
7035const blockStack = [];
7036let currentBlock = null;
7037/**
7038 * Open a block.
7039 * This must be called before `createBlock`. It cannot be part of `createBlock`
7040 * because the children of the block are evaluated before `createBlock` itself
7041 * is called. The generated code typically looks like this:
7042 *
7043 * ```js
7044 * function render() {
7045 * return (openBlock(),createBlock('div', null, [...]))
7046 * }
7047 * ```
7048 * disableTracking is true when creating a v-for fragment block, since a v-for
7049 * fragment always diffs its children.
7050 *
7051 * @private
7052 */
7053function openBlock(disableTracking = false) {
7054 blockStack.push((currentBlock = disableTracking ? null : []));
7055}
7056function closeBlock() {
7057 blockStack.pop();
7058 currentBlock = blockStack[blockStack.length - 1] || null;
7059}
7060// Whether we should be tracking dynamic child nodes inside a block.
7061// Only tracks when this value is > 0
7062// We are not using a simple boolean because this value may need to be
7063// incremented/decremented by nested usage of v-once (see below)
7064let isBlockTreeEnabled = 1;
7065/**
7066 * Block tracking sometimes needs to be disabled, for example during the
7067 * creation of a tree that needs to be cached by v-once. The compiler generates
7068 * code like this:
7069 *
7070 * ``` js
7071 * _cache[1] || (
7072 * setBlockTracking(-1),
7073 * _cache[1] = createVNode(...),
7074 * setBlockTracking(1),
7075 * _cache[1]
7076 * )
7077 * ```
7078 *
7079 * @private
7080 */
7081function setBlockTracking(value) {
7082 isBlockTreeEnabled += value;
7083}
7084function setupBlock(vnode) {
7085 // save current block children on the block vnode
7086 vnode.dynamicChildren =
7087 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7088 // close block
7089 closeBlock();
7090 // a block is always going to be patched, so track it as a child of its
7091 // parent block
7092 if (isBlockTreeEnabled > 0 && currentBlock) {
7093 currentBlock.push(vnode);
7094 }
7095 return vnode;
7096}
7097/**
7098 * @private
7099 */
7100function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7101 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7102}
7103/**
7104 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7105 * A block root keeps track of dynamic nodes within the block in the
7106 * `dynamicChildren` array.
7107 *
7108 * @private
7109 */
7110function createBlock(type, props, children, patchFlag, dynamicProps) {
7111 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7112}
7113function isVNode(value) {
7114 return value ? value.__v_isVNode === true : false;
7115}
7116function isSameVNodeType(n1, n2) {
7117 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7118 hmrDirtyComponents.has(n2.type)) {
7119 // HMR only: if the component has been hot-updated, force a reload.
7120 return false;
7121 }
7122 return n1.type === n2.type && n1.key === n2.key;
7123}
7124let vnodeArgsTransformer;
7125/**
7126 * Internal API for registering an arguments transform for createVNode
7127 * used for creating stubs in the test-utils
7128 * It is *internal* but needs to be exposed for test-utils to pick up proper
7129 * typings
7130 */
7131function transformVNodeArgs(transformer) {
7132 vnodeArgsTransformer = transformer;
7133}
7134const createVNodeWithArgsTransform = (...args) => {
7135 return _createVNode(...(vnodeArgsTransformer
7136 ? vnodeArgsTransformer(args, currentRenderingInstance)
7137 : args));
7138};
7139const InternalObjectKey = `__vInternal`;
7140const normalizeKey = ({ key }) => key != null ? key : null;
7141const normalizeRef = ({ ref }) => {
7142 return (ref != null
7143 ? isString(ref) || isRef(ref) || isFunction(ref)
7144 ? { i: currentRenderingInstance, r: ref }
7145 : ref
7146 : null);
7147};
7148function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7149 const vnode = {
7150 __v_isVNode: true,
7151 __v_skip: true,
7152 type,
7153 props,
7154 key: props && normalizeKey(props),
7155 ref: props && normalizeRef(props),
7156 scopeId: currentScopeId,
7157 slotScopeIds: null,
7158 children,
7159 component: null,
7160 suspense: null,
7161 ssContent: null,
7162 ssFallback: null,
7163 dirs: null,
7164 transition: null,
7165 el: null,
7166 anchor: null,
7167 target: null,
7168 targetAnchor: null,
7169 staticCount: 0,
7170 shapeFlag,
7171 patchFlag,
7172 dynamicProps,
7173 dynamicChildren: null,
7174 appContext: null
7175 };
7176 if (needFullChildrenNormalization) {
7177 normalizeChildren(vnode, children);
7178 // normalize suspense children
7179 if (shapeFlag & 128 /* SUSPENSE */) {
7180 type.normalize(vnode);
7181 }
7182 }
7183 else if (children) {
7184 // compiled element vnode - if children is passed, only possible types are
7185 // string or Array.
7186 vnode.shapeFlag |= isString(children)
7187 ? 8 /* TEXT_CHILDREN */
7188 : 16 /* ARRAY_CHILDREN */;
7189 }
7190 // validate key
7191 if (vnode.key !== vnode.key) {
7192 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7193 }
7194 // track vnode for block tree
7195 if (isBlockTreeEnabled > 0 &&
7196 // avoid a block node from tracking itself
7197 !isBlockNode &&
7198 // has current parent block
7199 currentBlock &&
7200 // presence of a patch flag indicates this node needs patching on updates.
7201 // component nodes also should always be patched, because even if the
7202 // component doesn't need to update, it needs to persist the instance on to
7203 // the next vnode so that it can be properly unmounted later.
7204 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7205 // the EVENTS flag is only for hydration and if it is the only flag, the
7206 // vnode should not be considered dynamic due to handler caching.
7207 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7208 currentBlock.push(vnode);
7209 }
7210 return vnode;
7211}
7212const createVNode = (createVNodeWithArgsTransform );
7213function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7214 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7215 if (!type) {
7216 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7217 }
7218 type = Comment;
7219 }
7220 if (isVNode(type)) {
7221 // createVNode receiving an existing vnode. This happens in cases like
7222 // <component :is="vnode"/>
7223 // #2078 make sure to merge refs during the clone instead of overwriting it
7224 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7225 if (children) {
7226 normalizeChildren(cloned, children);
7227 }
7228 return cloned;
7229 }
7230 // class component normalization.
7231 if (isClassComponent(type)) {
7232 type = type.__vccOpts;
7233 }
7234 // class & style normalization.
7235 if (props) {
7236 // for reactive or proxy objects, we need to clone it to enable mutation.
7237 props = guardReactiveProps(props);
7238 let { class: klass, style } = props;
7239 if (klass && !isString(klass)) {
7240 props.class = normalizeClass(klass);
7241 }
7242 if (isObject(style)) {
7243 // reactive state objects need to be cloned since they are likely to be
7244 // mutated
7245 if (isProxy(style) && !isArray(style)) {
7246 style = extend({}, style);
7247 }
7248 props.style = normalizeStyle(style);
7249 }
7250 }
7251 // encode the vnode type information into a bitmap
7252 const shapeFlag = isString(type)
7253 ? 1 /* ELEMENT */
7254 : isSuspense(type)
7255 ? 128 /* SUSPENSE */
7256 : isTeleport(type)
7257 ? 64 /* TELEPORT */
7258 : isObject(type)
7259 ? 4 /* STATEFUL_COMPONENT */
7260 : isFunction(type)
7261 ? 2 /* FUNCTIONAL_COMPONENT */
7262 : 0;
7263 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7264 type = toRaw(type);
7265 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7266 `lead to unnecessary performance overhead, and should be avoided by ` +
7267 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7268 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7269 }
7270 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7271}
7272function guardReactiveProps(props) {
7273 if (!props)
7274 return null;
7275 return isProxy(props) || InternalObjectKey in props
7276 ? extend({}, props)
7277 : props;
7278}
7279function cloneVNode(vnode, extraProps, mergeRef = false) {
7280 // This is intentionally NOT using spread or extend to avoid the runtime
7281 // key enumeration cost.
7282 const { props, ref, patchFlag, children } = vnode;
7283 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7284 const cloned = {
7285 __v_isVNode: true,
7286 __v_skip: true,
7287 type: vnode.type,
7288 props: mergedProps,
7289 key: mergedProps && normalizeKey(mergedProps),
7290 ref: extraProps && extraProps.ref
7291 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7292 // if the vnode itself already has a ref, cloneVNode will need to merge
7293 // the refs so the single vnode can be set on multiple refs
7294 mergeRef && ref
7295 ? isArray(ref)
7296 ? ref.concat(normalizeRef(extraProps))
7297 : [ref, normalizeRef(extraProps)]
7298 : normalizeRef(extraProps)
7299 : ref,
7300 scopeId: vnode.scopeId,
7301 slotScopeIds: vnode.slotScopeIds,
7302 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7303 ? children.map(deepCloneVNode)
7304 : children,
7305 target: vnode.target,
7306 targetAnchor: vnode.targetAnchor,
7307 staticCount: vnode.staticCount,
7308 shapeFlag: vnode.shapeFlag,
7309 // if the vnode is cloned with extra props, we can no longer assume its
7310 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7311 // note: perserve flag for fragments since they use the flag for children
7312 // fast paths only.
7313 patchFlag: extraProps && vnode.type !== Fragment
7314 ? patchFlag === -1 // hoisted node
7315 ? 16 /* FULL_PROPS */
7316 : patchFlag | 16 /* FULL_PROPS */
7317 : patchFlag,
7318 dynamicProps: vnode.dynamicProps,
7319 dynamicChildren: vnode.dynamicChildren,
7320 appContext: vnode.appContext,
7321 dirs: vnode.dirs,
7322 transition: vnode.transition,
7323 // These should technically only be non-null on mounted VNodes. However,
7324 // they *should* be copied for kept-alive vnodes. So we just always copy
7325 // them since them being non-null during a mount doesn't affect the logic as
7326 // they will simply be overwritten.
7327 component: vnode.component,
7328 suspense: vnode.suspense,
7329 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7330 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7331 el: vnode.el,
7332 anchor: vnode.anchor
7333 };
7334 return cloned;
7335}
7336/**
7337 * Dev only, for HMR of hoisted vnodes reused in v-for
7338 * https://github.com/vitejs/vite/issues/2022
7339 */
7340function deepCloneVNode(vnode) {
7341 const cloned = cloneVNode(vnode);
7342 if (isArray(vnode.children)) {
7343 cloned.children = vnode.children.map(deepCloneVNode);
7344 }
7345 return cloned;
7346}
7347/**
7348 * @private
7349 */
7350function createTextVNode(text = ' ', flag = 0) {
7351 return createVNode(Text, null, text, flag);
7352}
7353/**
7354 * @private
7355 */
7356function createStaticVNode(content, numberOfNodes) {
7357 // A static vnode can contain multiple stringified elements, and the number
7358 // of elements is necessary for hydration.
7359 const vnode = createVNode(Static, null, content);
7360 vnode.staticCount = numberOfNodes;
7361 return vnode;
7362}
7363/**
7364 * @private
7365 */
7366function createCommentVNode(text = '',
7367// when used as the v-else branch, the comment node must be created as a
7368// block to ensure correct updates.
7369asBlock = false) {
7370 return asBlock
7371 ? (openBlock(), createBlock(Comment, null, text))
7372 : createVNode(Comment, null, text);
7373}
7374function normalizeVNode(child) {
7375 if (child == null || typeof child === 'boolean') {
7376 // empty placeholder
7377 return createVNode(Comment);
7378 }
7379 else if (isArray(child)) {
7380 // fragment
7381 return createVNode(Fragment, null,
7382 // #3666, avoid reference pollution when reusing vnode
7383 child.slice());
7384 }
7385 else if (typeof child === 'object') {
7386 // already vnode, this should be the most common since compiled templates
7387 // always produce all-vnode children arrays
7388 return cloneIfMounted(child);
7389 }
7390 else {
7391 // strings and numbers
7392 return createVNode(Text, null, String(child));
7393 }
7394}
7395// optimized normalization for template-compiled render fns
7396function cloneIfMounted(child) {
7397 return child.el === null || child.memo ? child : cloneVNode(child);
7398}
7399function normalizeChildren(vnode, children) {
7400 let type = 0;
7401 const { shapeFlag } = vnode;
7402 if (children == null) {
7403 children = null;
7404 }
7405 else if (isArray(children)) {
7406 type = 16 /* ARRAY_CHILDREN */;
7407 }
7408 else if (typeof children === 'object') {
7409 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7410 // Normalize slot to plain children for plain element and Teleport
7411 const slot = children.default;
7412 if (slot) {
7413 // _c marker is added by withCtx() indicating this is a compiled slot
7414 slot._c && (slot._d = false);
7415 normalizeChildren(vnode, slot());
7416 slot._c && (slot._d = true);
7417 }
7418 return;
7419 }
7420 else {
7421 type = 32 /* SLOTS_CHILDREN */;
7422 const slotFlag = children._;
7423 if (!slotFlag && !(InternalObjectKey in children)) {
7424 children._ctx = currentRenderingInstance;
7425 }
7426 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7427 // a child component receives forwarded slots from the parent.
7428 // its slot type is determined by its parent's slot type.
7429 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7430 children._ = 1 /* STABLE */;
7431 }
7432 else {
7433 children._ = 2 /* DYNAMIC */;
7434 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7435 }
7436 }
7437 }
7438 }
7439 else if (isFunction(children)) {
7440 children = { default: children, _ctx: currentRenderingInstance };
7441 type = 32 /* SLOTS_CHILDREN */;
7442 }
7443 else {
7444 children = String(children);
7445 // force teleport children to array so it can be moved around
7446 if (shapeFlag & 64 /* TELEPORT */) {
7447 type = 16 /* ARRAY_CHILDREN */;
7448 children = [createTextVNode(children)];
7449 }
7450 else {
7451 type = 8 /* TEXT_CHILDREN */;
7452 }
7453 }
7454 vnode.children = children;
7455 vnode.shapeFlag |= type;
7456}
7457function mergeProps(...args) {
7458 const ret = {};
7459 for (let i = 0; i < args.length; i++) {
7460 const toMerge = args[i];
7461 for (const key in toMerge) {
7462 if (key === 'class') {
7463 if (ret.class !== toMerge.class) {
7464 ret.class = normalizeClass([ret.class, toMerge.class]);
7465 }
7466 }
7467 else if (key === 'style') {
7468 ret.style = normalizeStyle([ret.style, toMerge.style]);
7469 }
7470 else if (isOn(key)) {
7471 const existing = ret[key];
7472 const incoming = toMerge[key];
7473 if (existing !== incoming) {
7474 ret[key] = existing
7475 ? [].concat(existing, incoming)
7476 : incoming;
7477 }
7478 }
7479 else if (key !== '') {
7480 ret[key] = toMerge[key];
7481 }
7482 }
7483 }
7484 return ret;
7485}
7486
7487/**
7488 * Actual implementation
7489 */
7490function renderList(source, renderItem, cache, index) {
7491 let ret;
7492 const cached = (cache && cache[index]);
7493 if (isArray(source) || isString(source)) {
7494 ret = new Array(source.length);
7495 for (let i = 0, l = source.length; i < l; i++) {
7496 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
7497 }
7498 }
7499 else if (typeof source === 'number') {
7500 if (!Number.isInteger(source)) {
7501 warn$1(`The v-for range expect an integer value but got ${source}.`);
7502 return [];
7503 }
7504 ret = new Array(source);
7505 for (let i = 0; i < source; i++) {
7506 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
7507 }
7508 }
7509 else if (isObject(source)) {
7510 if (source[Symbol.iterator]) {
7511 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
7512 }
7513 else {
7514 const keys = Object.keys(source);
7515 ret = new Array(keys.length);
7516 for (let i = 0, l = keys.length; i < l; i++) {
7517 const key = keys[i];
7518 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
7519 }
7520 }
7521 }
7522 else {
7523 ret = [];
7524 }
7525 if (cache) {
7526 cache[index] = ret;
7527 }
7528 return ret;
7529}
7530
7531/**
7532 * Compiler runtime helper for creating dynamic slots object
7533 * @private
7534 */
7535function createSlots(slots, dynamicSlots) {
7536 for (let i = 0; i < dynamicSlots.length; i++) {
7537 const slot = dynamicSlots[i];
7538 // array of dynamic slot generated by <template v-for="..." #[...]>
7539 if (isArray(slot)) {
7540 for (let j = 0; j < slot.length; j++) {
7541 slots[slot[j].name] = slot[j].fn;
7542 }
7543 }
7544 else if (slot) {
7545 // conditional single slot generated by <template v-if="..." #foo>
7546 slots[slot.name] = slot.fn;
7547 }
7548 }
7549 return slots;
7550}
7551
7552/**
7553 * Compiler runtime helper for rendering `<slot/>`
7554 * @private
7555 */
7556function renderSlot(slots, name, props = {},
7557// this is not a user-facing function, so the fallback is always generated by
7558// the compiler and guaranteed to be a function returning an array
7559fallback, noSlotted) {
7560 if (currentRenderingInstance.isCE) {
7561 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
7562 }
7563 let slot = slots[name];
7564 if (slot && slot.length > 1) {
7565 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
7566 `function. You need to mark this component with $dynamic-slots in the ` +
7567 `parent template.`);
7568 slot = () => [];
7569 }
7570 // a compiled slot disables block tracking by default to avoid manual
7571 // invocation interfering with template-based block tracking, but in
7572 // `renderSlot` we can be sure that it's template-based so we can force
7573 // enable it.
7574 if (slot && slot._c) {
7575 slot._d = false;
7576 }
7577 openBlock();
7578 const validSlotContent = slot && ensureValidVNode(slot(props));
7579 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
7580 ? 64 /* STABLE_FRAGMENT */
7581 : -2 /* BAIL */);
7582 if (!noSlotted && rendered.scopeId) {
7583 rendered.slotScopeIds = [rendered.scopeId + '-s'];
7584 }
7585 if (slot && slot._c) {
7586 slot._d = true;
7587 }
7588 return rendered;
7589}
7590function ensureValidVNode(vnodes) {
7591 return vnodes.some(child => {
7592 if (!isVNode(child))
7593 return true;
7594 if (child.type === Comment)
7595 return false;
7596 if (child.type === Fragment &&
7597 !ensureValidVNode(child.children))
7598 return false;
7599 return true;
7600 })
7601 ? vnodes
7602 : null;
7603}
7604
7605/**
7606 * For prefixing keys in v-on="obj" with "on"
7607 * @private
7608 */
7609function toHandlers(obj) {
7610 const ret = {};
7611 if (!isObject(obj)) {
7612 warn$1(`v-on with no argument expects an object value.`);
7613 return ret;
7614 }
7615 for (const key in obj) {
7616 ret[toHandlerKey(key)] = obj[key];
7617 }
7618 return ret;
7619}
7620
7621/**
7622 * #2437 In Vue 3, functional components do not have a public instance proxy but
7623 * they exist in the internal parent chain. For code that relies on traversing
7624 * public $parent chains, skip functional ones and go to the parent instead.
7625 */
7626const getPublicInstance = (i) => {
7627 if (!i)
7628 return null;
7629 if (isStatefulComponent(i))
7630 return getExposeProxy(i) || i.proxy;
7631 return getPublicInstance(i.parent);
7632};
7633const publicPropertiesMap = extend(Object.create(null), {
7634 $: i => i,
7635 $el: i => i.vnode.el,
7636 $data: i => i.data,
7637 $props: i => (shallowReadonly(i.props) ),
7638 $attrs: i => (shallowReadonly(i.attrs) ),
7639 $slots: i => (shallowReadonly(i.slots) ),
7640 $refs: i => (shallowReadonly(i.refs) ),
7641 $parent: i => getPublicInstance(i.parent),
7642 $root: i => getPublicInstance(i.root),
7643 $emit: i => i.emit,
7644 $options: i => (resolveMergedOptions(i) ),
7645 $forceUpdate: i => () => queueJob(i.update),
7646 $nextTick: i => nextTick.bind(i.proxy),
7647 $watch: i => (instanceWatch.bind(i) )
7648});
7649const PublicInstanceProxyHandlers = {
7650 get({ _: instance }, key) {
7651 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7652 // for internal formatters to know that this is a Vue instance
7653 if (key === '__isVue') {
7654 return true;
7655 }
7656 // prioritize <script setup> bindings during dev.
7657 // this allows even properties that start with _ or $ to be used - so that
7658 // it aligns with the production behavior where the render fn is inlined and
7659 // indeed has access to all declared variables.
7660 if (setupState !== EMPTY_OBJ &&
7661 setupState.__isScriptSetup &&
7662 hasOwn(setupState, key)) {
7663 return setupState[key];
7664 }
7665 // data / props / ctx
7666 // This getter gets called for every property access on the render context
7667 // during render and is a major hotspot. The most expensive part of this
7668 // is the multiple hasOwn() calls. It's much faster to do a simple property
7669 // access on a plain object, so we use an accessCache object (with null
7670 // prototype) to memoize what access type a key corresponds to.
7671 let normalizedProps;
7672 if (key[0] !== '$') {
7673 const n = accessCache[key];
7674 if (n !== undefined) {
7675 switch (n) {
7676 case 0 /* SETUP */:
7677 return setupState[key];
7678 case 1 /* DATA */:
7679 return data[key];
7680 case 3 /* CONTEXT */:
7681 return ctx[key];
7682 case 2 /* PROPS */:
7683 return props[key];
7684 // default: just fallthrough
7685 }
7686 }
7687 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7688 accessCache[key] = 0 /* SETUP */;
7689 return setupState[key];
7690 }
7691 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7692 accessCache[key] = 1 /* DATA */;
7693 return data[key];
7694 }
7695 else if (
7696 // only cache other properties when instance has declared (thus stable)
7697 // props
7698 (normalizedProps = instance.propsOptions[0]) &&
7699 hasOwn(normalizedProps, key)) {
7700 accessCache[key] = 2 /* PROPS */;
7701 return props[key];
7702 }
7703 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7704 accessCache[key] = 3 /* CONTEXT */;
7705 return ctx[key];
7706 }
7707 else if (shouldCacheAccess) {
7708 accessCache[key] = 4 /* OTHER */;
7709 }
7710 }
7711 const publicGetter = publicPropertiesMap[key];
7712 let cssModule, globalProperties;
7713 // public $xxx properties
7714 if (publicGetter) {
7715 if (key === '$attrs') {
7716 track(instance, "get" /* GET */, key);
7717 markAttrsAccessed();
7718 }
7719 return publicGetter(instance);
7720 }
7721 else if (
7722 // css module (injected by vue-loader)
7723 (cssModule = type.__cssModules) &&
7724 (cssModule = cssModule[key])) {
7725 return cssModule;
7726 }
7727 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7728 // user may set custom properties to `this` that start with `$`
7729 accessCache[key] = 3 /* CONTEXT */;
7730 return ctx[key];
7731 }
7732 else if (
7733 // global properties
7734 ((globalProperties = appContext.config.globalProperties),
7735 hasOwn(globalProperties, key))) {
7736 {
7737 return globalProperties[key];
7738 }
7739 }
7740 else if (currentRenderingInstance &&
7741 (!isString(key) ||
7742 // #1091 avoid internal isRef/isVNode checks on component instance leading
7743 // to infinite warning loop
7744 key.indexOf('__v') !== 0)) {
7745 if (data !== EMPTY_OBJ &&
7746 (key[0] === '$' || key[0] === '_') &&
7747 hasOwn(data, key)) {
7748 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
7749 `character ("$" or "_") and is not proxied on the render context.`);
7750 }
7751 else if (instance === currentRenderingInstance) {
7752 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
7753 `but is not defined on instance.`);
7754 }
7755 }
7756 },
7757 set({ _: instance }, key, value) {
7758 const { data, setupState, ctx } = instance;
7759 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7760 setupState[key] = value;
7761 }
7762 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7763 data[key] = value;
7764 }
7765 else if (hasOwn(instance.props, key)) {
7766 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
7767 return false;
7768 }
7769 if (key[0] === '$' && key.slice(1) in instance) {
7770 warn$1(`Attempting to mutate public property "${key}". ` +
7771 `Properties starting with $ are reserved and readonly.`, instance);
7772 return false;
7773 }
7774 else {
7775 if (key in instance.appContext.config.globalProperties) {
7776 Object.defineProperty(ctx, key, {
7777 enumerable: true,
7778 configurable: true,
7779 value
7780 });
7781 }
7782 else {
7783 ctx[key] = value;
7784 }
7785 }
7786 return true;
7787 },
7788 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
7789 let normalizedProps;
7790 return (accessCache[key] !== undefined ||
7791 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
7792 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
7793 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
7794 hasOwn(ctx, key) ||
7795 hasOwn(publicPropertiesMap, key) ||
7796 hasOwn(appContext.config.globalProperties, key));
7797 }
7798};
7799{
7800 PublicInstanceProxyHandlers.ownKeys = (target) => {
7801 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
7802 `The keys will be empty in production mode to avoid performance overhead.`);
7803 return Reflect.ownKeys(target);
7804 };
7805}
7806const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
7807 get(target, key) {
7808 // fast path for unscopables when using `with` block
7809 if (key === Symbol.unscopables) {
7810 return;
7811 }
7812 return PublicInstanceProxyHandlers.get(target, key, target);
7813 },
7814 has(_, key) {
7815 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
7816 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
7817 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
7818 }
7819 return has;
7820 }
7821});
7822// dev only
7823// In dev mode, the proxy target exposes the same properties as seen on `this`
7824// for easier console inspection. In prod mode it will be an empty object so
7825// these properties definitions can be skipped.
7826function createDevRenderContext(instance) {
7827 const target = {};
7828 // expose internal instance for proxy handlers
7829 Object.defineProperty(target, `_`, {
7830 configurable: true,
7831 enumerable: false,
7832 get: () => instance
7833 });
7834 // expose public properties
7835 Object.keys(publicPropertiesMap).forEach(key => {
7836 Object.defineProperty(target, key, {
7837 configurable: true,
7838 enumerable: false,
7839 get: () => publicPropertiesMap[key](instance),
7840 // intercepted by the proxy so no need for implementation,
7841 // but needed to prevent set errors
7842 set: NOOP
7843 });
7844 });
7845 return target;
7846}
7847// dev only
7848function exposePropsOnRenderContext(instance) {
7849 const { ctx, propsOptions: [propsOptions] } = instance;
7850 if (propsOptions) {
7851 Object.keys(propsOptions).forEach(key => {
7852 Object.defineProperty(ctx, key, {
7853 enumerable: true,
7854 configurable: true,
7855 get: () => instance.props[key],
7856 set: NOOP
7857 });
7858 });
7859 }
7860}
7861// dev only
7862function exposeSetupStateOnRenderContext(instance) {
7863 const { ctx, setupState } = instance;
7864 Object.keys(toRaw(setupState)).forEach(key => {
7865 if (!setupState.__isScriptSetup && (key[0] === '$' || key[0] === '_')) {
7866 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
7867 `which are reserved prefixes for Vue internals.`);
7868 return;
7869 }
7870 Object.defineProperty(ctx, key, {
7871 enumerable: true,
7872 configurable: true,
7873 get: () => setupState[key],
7874 set: NOOP
7875 });
7876 });
7877}
7878
7879const emptyAppContext = createAppContext();
7880let uid$1 = 0;
7881function createComponentInstance(vnode, parent, suspense) {
7882 const type = vnode.type;
7883 // inherit parent app context - or - if root, adopt from root vnode
7884 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
7885 const instance = {
7886 uid: uid$1++,
7887 vnode,
7888 type,
7889 parent,
7890 appContext,
7891 root: null,
7892 next: null,
7893 subTree: null,
7894 update: null,
7895 scope: new EffectScope(true /* detached */),
7896 render: null,
7897 proxy: null,
7898 exposed: null,
7899 exposeProxy: null,
7900 withProxy: null,
7901 provides: parent ? parent.provides : Object.create(appContext.provides),
7902 accessCache: null,
7903 renderCache: [],
7904 // local resovled assets
7905 components: null,
7906 directives: null,
7907 // resolved props and emits options
7908 propsOptions: normalizePropsOptions(type, appContext),
7909 emitsOptions: normalizeEmitsOptions(type, appContext),
7910 // emit
7911 emit: null,
7912 emitted: null,
7913 // props default value
7914 propsDefaults: EMPTY_OBJ,
7915 // inheritAttrs
7916 inheritAttrs: type.inheritAttrs,
7917 // state
7918 ctx: EMPTY_OBJ,
7919 data: EMPTY_OBJ,
7920 props: EMPTY_OBJ,
7921 attrs: EMPTY_OBJ,
7922 slots: EMPTY_OBJ,
7923 refs: EMPTY_OBJ,
7924 setupState: EMPTY_OBJ,
7925 setupContext: null,
7926 // suspense related
7927 suspense,
7928 suspenseId: suspense ? suspense.pendingId : 0,
7929 asyncDep: null,
7930 asyncResolved: false,
7931 // lifecycle hooks
7932 // not using enums here because it results in computed properties
7933 isMounted: false,
7934 isUnmounted: false,
7935 isDeactivated: false,
7936 bc: null,
7937 c: null,
7938 bm: null,
7939 m: null,
7940 bu: null,
7941 u: null,
7942 um: null,
7943 bum: null,
7944 da: null,
7945 a: null,
7946 rtg: null,
7947 rtc: null,
7948 ec: null,
7949 sp: null
7950 };
7951 {
7952 instance.ctx = createDevRenderContext(instance);
7953 }
7954 instance.root = parent ? parent.root : instance;
7955 instance.emit = emit.bind(null, instance);
7956 // apply custom element special handling
7957 if (vnode.ce) {
7958 vnode.ce(instance);
7959 }
7960 return instance;
7961}
7962let currentInstance = null;
7963const getCurrentInstance = () => currentInstance || currentRenderingInstance;
7964const setCurrentInstance = (instance) => {
7965 currentInstance = instance;
7966 instance.scope.on();
7967};
7968const unsetCurrentInstance = () => {
7969 currentInstance && currentInstance.scope.off();
7970 currentInstance = null;
7971};
7972const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
7973function validateComponentName(name, config) {
7974 const appIsNativeTag = config.isNativeTag || NO;
7975 if (isBuiltInTag(name) || appIsNativeTag(name)) {
7976 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
7977 }
7978}
7979function isStatefulComponent(instance) {
7980 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
7981}
7982let isInSSRComponentSetup = false;
7983function setupComponent(instance, isSSR = false) {
7984 isInSSRComponentSetup = isSSR;
7985 const { props, children } = instance.vnode;
7986 const isStateful = isStatefulComponent(instance);
7987 initProps(instance, props, isStateful, isSSR);
7988 initSlots(instance, children);
7989 const setupResult = isStateful
7990 ? setupStatefulComponent(instance, isSSR)
7991 : undefined;
7992 isInSSRComponentSetup = false;
7993 return setupResult;
7994}
7995function setupStatefulComponent(instance, isSSR) {
7996 const Component = instance.type;
7997 {
7998 if (Component.name) {
7999 validateComponentName(Component.name, instance.appContext.config);
8000 }
8001 if (Component.components) {
8002 const names = Object.keys(Component.components);
8003 for (let i = 0; i < names.length; i++) {
8004 validateComponentName(names[i], instance.appContext.config);
8005 }
8006 }
8007 if (Component.directives) {
8008 const names = Object.keys(Component.directives);
8009 for (let i = 0; i < names.length; i++) {
8010 validateDirectiveName(names[i]);
8011 }
8012 }
8013 if (Component.compilerOptions && isRuntimeOnly()) {
8014 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8015 `includes the runtime compiler. Since you are using a runtime-only ` +
8016 `build, the options should be passed via your build tool config instead.`);
8017 }
8018 }
8019 // 0. create render proxy property access cache
8020 instance.accessCache = Object.create(null);
8021 // 1. create public instance / render proxy
8022 // also mark it raw so it's never observed
8023 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8024 {
8025 exposePropsOnRenderContext(instance);
8026 }
8027 // 2. call setup()
8028 const { setup } = Component;
8029 if (setup) {
8030 const setupContext = (instance.setupContext =
8031 setup.length > 1 ? createSetupContext(instance) : null);
8032 setCurrentInstance(instance);
8033 pauseTracking();
8034 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8035 resetTracking();
8036 unsetCurrentInstance();
8037 if (isPromise(setupResult)) {
8038 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8039 if (isSSR) {
8040 // return the promise so server-renderer can wait on it
8041 return setupResult
8042 .then((resolvedResult) => {
8043 handleSetupResult(instance, resolvedResult, isSSR);
8044 })
8045 .catch(e => {
8046 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8047 });
8048 }
8049 else {
8050 // async setup returned Promise.
8051 // bail here and wait for re-entry.
8052 instance.asyncDep = setupResult;
8053 }
8054 }
8055 else {
8056 handleSetupResult(instance, setupResult, isSSR);
8057 }
8058 }
8059 else {
8060 finishComponentSetup(instance, isSSR);
8061 }
8062}
8063function handleSetupResult(instance, setupResult, isSSR) {
8064 if (isFunction(setupResult)) {
8065 // setup returned an inline render function
8066 {
8067 instance.render = setupResult;
8068 }
8069 }
8070 else if (isObject(setupResult)) {
8071 if (isVNode(setupResult)) {
8072 warn$1(`setup() should not return VNodes directly - ` +
8073 `return a render function instead.`);
8074 }
8075 // setup returned bindings.
8076 // assuming a render function compiled from template is present.
8077 {
8078 instance.devtoolsRawSetupState = setupResult;
8079 }
8080 instance.setupState = proxyRefs(setupResult);
8081 {
8082 exposeSetupStateOnRenderContext(instance);
8083 }
8084 }
8085 else if (setupResult !== undefined) {
8086 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8087 }
8088 finishComponentSetup(instance, isSSR);
8089}
8090let compile;
8091let installWithProxy;
8092/**
8093 * For runtime-dom to register the compiler.
8094 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8095 */
8096function registerRuntimeCompiler(_compile) {
8097 compile = _compile;
8098 installWithProxy = i => {
8099 if (i.render._rc) {
8100 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8101 }
8102 };
8103}
8104// dev only
8105const isRuntimeOnly = () => !compile;
8106function finishComponentSetup(instance, isSSR, skipOptions) {
8107 const Component = instance.type;
8108 // template / render function normalization
8109 if (!instance.render) {
8110 // could be set from setup()
8111 if (compile && !Component.render) {
8112 const template = Component.template;
8113 if (template) {
8114 {
8115 startMeasure(instance, `compile`);
8116 }
8117 const { isCustomElement, compilerOptions } = instance.appContext.config;
8118 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8119 const finalCompilerOptions = extend(extend({
8120 isCustomElement,
8121 delimiters
8122 }, compilerOptions), componentCompilerOptions);
8123 Component.render = compile(template, finalCompilerOptions);
8124 {
8125 endMeasure(instance, `compile`);
8126 }
8127 }
8128 }
8129 instance.render = (Component.render || NOOP);
8130 // for runtime-compiled render functions using `with` blocks, the render
8131 // proxy used needs a different `has` handler which is more performant and
8132 // also only allows a whitelist of globals to fallthrough.
8133 if (installWithProxy) {
8134 installWithProxy(instance);
8135 }
8136 }
8137 // support for 2.x options
8138 {
8139 setCurrentInstance(instance);
8140 pauseTracking();
8141 applyOptions(instance);
8142 resetTracking();
8143 unsetCurrentInstance();
8144 }
8145 // warn missing template/render
8146 // the runtime compilation of template in SSR is done by server-render
8147 if (!Component.render && instance.render === NOOP && !isSSR) {
8148 /* istanbul ignore if */
8149 if (!compile && Component.template) {
8150 warn$1(`Component provided template option but ` +
8151 `runtime compilation is not supported in this build of Vue.` +
8152 (` Use "vue.esm-browser.js" instead.`
8153 ) /* should not happen */);
8154 }
8155 else {
8156 warn$1(`Component is missing template or render function.`);
8157 }
8158 }
8159}
8160function createAttrsProxy(instance) {
8161 return new Proxy(instance.attrs, {
8162 get(target, key) {
8163 markAttrsAccessed();
8164 track(instance, "get" /* GET */, '$attrs');
8165 return target[key];
8166 },
8167 set() {
8168 warn$1(`setupContext.attrs is readonly.`);
8169 return false;
8170 },
8171 deleteProperty() {
8172 warn$1(`setupContext.attrs is readonly.`);
8173 return false;
8174 }
8175 }
8176 );
8177}
8178function createSetupContext(instance) {
8179 const expose = exposed => {
8180 if (instance.exposed) {
8181 warn$1(`expose() should be called only once per setup().`);
8182 }
8183 instance.exposed = exposed || {};
8184 };
8185 let attrs;
8186 {
8187 // We use getters in dev in case libs like test-utils overwrite instance
8188 // properties (overwrites should not be done in prod)
8189 return Object.freeze({
8190 get attrs() {
8191 return attrs || (attrs = createAttrsProxy(instance));
8192 },
8193 get slots() {
8194 return shallowReadonly(instance.slots);
8195 },
8196 get emit() {
8197 return (event, ...args) => instance.emit(event, ...args);
8198 },
8199 expose
8200 });
8201 }
8202}
8203function getExposeProxy(instance) {
8204 if (instance.exposed) {
8205 return (instance.exposeProxy ||
8206 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8207 get(target, key) {
8208 if (key in target) {
8209 return target[key];
8210 }
8211 else if (key in publicPropertiesMap) {
8212 return publicPropertiesMap[key](instance);
8213 }
8214 }
8215 })));
8216 }
8217}
8218const classifyRE = /(?:^|[-_])(\w)/g;
8219const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8220function getComponentName(Component) {
8221 return isFunction(Component)
8222 ? Component.displayName || Component.name
8223 : Component.name;
8224}
8225/* istanbul ignore next */
8226function formatComponentName(instance, Component, isRoot = false) {
8227 let name = getComponentName(Component);
8228 if (!name && Component.__file) {
8229 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8230 if (match) {
8231 name = match[1];
8232 }
8233 }
8234 if (!name && instance && instance.parent) {
8235 // try to infer the name based on reverse resolution
8236 const inferFromRegistry = (registry) => {
8237 for (const key in registry) {
8238 if (registry[key] === Component) {
8239 return key;
8240 }
8241 }
8242 };
8243 name =
8244 inferFromRegistry(instance.components ||
8245 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8246 }
8247 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8248}
8249function isClassComponent(value) {
8250 return isFunction(value) && '__vccOpts' in value;
8251}
8252
8253const stack = [];
8254function pushWarningContext(vnode) {
8255 stack.push(vnode);
8256}
8257function popWarningContext() {
8258 stack.pop();
8259}
8260function warn$1(msg, ...args) {
8261 // avoid props formatting or warn handler tracking deps that might be mutated
8262 // during patch, leading to infinite recursion.
8263 pauseTracking();
8264 const instance = stack.length ? stack[stack.length - 1].component : null;
8265 const appWarnHandler = instance && instance.appContext.config.warnHandler;
8266 const trace = getComponentTrace();
8267 if (appWarnHandler) {
8268 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
8269 msg + args.join(''),
8270 instance && instance.proxy,
8271 trace
8272 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
8273 .join('\n'),
8274 trace
8275 ]);
8276 }
8277 else {
8278 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
8279 /* istanbul ignore if */
8280 if (trace.length &&
8281 // avoid spamming console during tests
8282 !false) {
8283 warnArgs.push(`\n`, ...formatTrace(trace));
8284 }
8285 console.warn(...warnArgs);
8286 }
8287 resetTracking();
8288}
8289function getComponentTrace() {
8290 let currentVNode = stack[stack.length - 1];
8291 if (!currentVNode) {
8292 return [];
8293 }
8294 // we can't just use the stack because it will be incomplete during updates
8295 // that did not start from the root. Re-construct the parent chain using
8296 // instance parent pointers.
8297 const normalizedStack = [];
8298 while (currentVNode) {
8299 const last = normalizedStack[0];
8300 if (last && last.vnode === currentVNode) {
8301 last.recurseCount++;
8302 }
8303 else {
8304 normalizedStack.push({
8305 vnode: currentVNode,
8306 recurseCount: 0
8307 });
8308 }
8309 const parentInstance = currentVNode.component && currentVNode.component.parent;
8310 currentVNode = parentInstance && parentInstance.vnode;
8311 }
8312 return normalizedStack;
8313}
8314/* istanbul ignore next */
8315function formatTrace(trace) {
8316 const logs = [];
8317 trace.forEach((entry, i) => {
8318 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
8319 });
8320 return logs;
8321}
8322function formatTraceEntry({ vnode, recurseCount }) {
8323 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
8324 const isRoot = vnode.component ? vnode.component.parent == null : false;
8325 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
8326 const close = `>` + postfix;
8327 return vnode.props
8328 ? [open, ...formatProps(vnode.props), close]
8329 : [open + close];
8330}
8331/* istanbul ignore next */
8332function formatProps(props) {
8333 const res = [];
8334 const keys = Object.keys(props);
8335 keys.slice(0, 3).forEach(key => {
8336 res.push(...formatProp(key, props[key]));
8337 });
8338 if (keys.length > 3) {
8339 res.push(` ...`);
8340 }
8341 return res;
8342}
8343/* istanbul ignore next */
8344function formatProp(key, value, raw) {
8345 if (isString(value)) {
8346 value = JSON.stringify(value);
8347 return raw ? value : [`${key}=${value}`];
8348 }
8349 else if (typeof value === 'number' ||
8350 typeof value === 'boolean' ||
8351 value == null) {
8352 return raw ? value : [`${key}=${value}`];
8353 }
8354 else if (isRef(value)) {
8355 value = formatProp(key, toRaw(value.value), true);
8356 return raw ? value : [`${key}=Ref<`, value, `>`];
8357 }
8358 else if (isFunction(value)) {
8359 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
8360 }
8361 else {
8362 value = toRaw(value);
8363 return raw ? value : [`${key}=`, value];
8364 }
8365}
8366
8367const ErrorTypeStrings = {
8368 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
8369 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
8370 ["c" /* CREATED */]: 'created hook',
8371 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
8372 ["m" /* MOUNTED */]: 'mounted hook',
8373 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
8374 ["u" /* UPDATED */]: 'updated',
8375 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
8376 ["um" /* UNMOUNTED */]: 'unmounted hook',
8377 ["a" /* ACTIVATED */]: 'activated hook',
8378 ["da" /* DEACTIVATED */]: 'deactivated hook',
8379 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
8380 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
8381 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
8382 [0 /* SETUP_FUNCTION */]: 'setup function',
8383 [1 /* RENDER_FUNCTION */]: 'render function',
8384 [2 /* WATCH_GETTER */]: 'watcher getter',
8385 [3 /* WATCH_CALLBACK */]: 'watcher callback',
8386 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
8387 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
8388 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
8389 [7 /* VNODE_HOOK */]: 'vnode hook',
8390 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
8391 [9 /* TRANSITION_HOOK */]: 'transition hook',
8392 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
8393 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
8394 [12 /* FUNCTION_REF */]: 'ref function',
8395 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
8396 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
8397 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
8398};
8399function callWithErrorHandling(fn, instance, type, args) {
8400 let res;
8401 try {
8402 res = args ? fn(...args) : fn();
8403 }
8404 catch (err) {
8405 handleError(err, instance, type);
8406 }
8407 return res;
8408}
8409function callWithAsyncErrorHandling(fn, instance, type, args) {
8410 if (isFunction(fn)) {
8411 const res = callWithErrorHandling(fn, instance, type, args);
8412 if (res && isPromise(res)) {
8413 res.catch(err => {
8414 handleError(err, instance, type);
8415 });
8416 }
8417 return res;
8418 }
8419 const values = [];
8420 for (let i = 0; i < fn.length; i++) {
8421 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
8422 }
8423 return values;
8424}
8425function handleError(err, instance, type, throwInDev = true) {
8426 const contextVNode = instance ? instance.vnode : null;
8427 if (instance) {
8428 let cur = instance.parent;
8429 // the exposed instance is the render proxy to keep it consistent with 2.x
8430 const exposedInstance = instance.proxy;
8431 // in production the hook receives only the error code
8432 const errorInfo = ErrorTypeStrings[type] ;
8433 while (cur) {
8434 const errorCapturedHooks = cur.ec;
8435 if (errorCapturedHooks) {
8436 for (let i = 0; i < errorCapturedHooks.length; i++) {
8437 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
8438 return;
8439 }
8440 }
8441 }
8442 cur = cur.parent;
8443 }
8444 // app-level handling
8445 const appErrorHandler = instance.appContext.config.errorHandler;
8446 if (appErrorHandler) {
8447 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
8448 return;
8449 }
8450 }
8451 logError(err, type, contextVNode, throwInDev);
8452}
8453function logError(err, type, contextVNode, throwInDev = true) {
8454 {
8455 const info = ErrorTypeStrings[type];
8456 if (contextVNode) {
8457 pushWarningContext(contextVNode);
8458 }
8459 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
8460 if (contextVNode) {
8461 popWarningContext();
8462 }
8463 // crash in dev by default so it's more noticeable
8464 if (throwInDev) {
8465 throw err;
8466 }
8467 else {
8468 console.error(err);
8469 }
8470 }
8471}
8472
8473let isFlushing = false;
8474let isFlushPending = false;
8475const queue = [];
8476let flushIndex = 0;
8477const pendingPreFlushCbs = [];
8478let activePreFlushCbs = null;
8479let preFlushIndex = 0;
8480const pendingPostFlushCbs = [];
8481let activePostFlushCbs = null;
8482let postFlushIndex = 0;
8483const resolvedPromise = Promise.resolve();
8484let currentFlushPromise = null;
8485let currentPreFlushParentJob = null;
8486const RECURSION_LIMIT = 100;
8487function nextTick(fn) {
8488 const p = currentFlushPromise || resolvedPromise;
8489 return fn ? p.then(this ? fn.bind(this) : fn) : p;
8490}
8491// #2768
8492// Use binary-search to find a suitable position in the queue,
8493// so that the queue maintains the increasing order of job's id,
8494// which can prevent the job from being skipped and also can avoid repeated patching.
8495function findInsertionIndex(id) {
8496 // the start index should be `flushIndex + 1`
8497 let start = flushIndex + 1;
8498 let end = queue.length;
8499 while (start < end) {
8500 const middle = (start + end) >>> 1;
8501 const middleJobId = getId(queue[middle]);
8502 middleJobId < id ? (start = middle + 1) : (end = middle);
8503 }
8504 return start;
8505}
8506function queueJob(job) {
8507 // the dedupe search uses the startIndex argument of Array.includes()
8508 // by default the search index includes the current job that is being run
8509 // so it cannot recursively trigger itself again.
8510 // if the job is a watch() callback, the search will start with a +1 index to
8511 // allow it recursively trigger itself - it is the user's responsibility to
8512 // ensure it doesn't end up in an infinite loop.
8513 if ((!queue.length ||
8514 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
8515 job !== currentPreFlushParentJob) {
8516 if (job.id == null) {
8517 queue.push(job);
8518 }
8519 else {
8520 queue.splice(findInsertionIndex(job.id), 0, job);
8521 }
8522 queueFlush();
8523 }
8524}
8525function queueFlush() {
8526 if (!isFlushing && !isFlushPending) {
8527 isFlushPending = true;
8528 currentFlushPromise = resolvedPromise.then(flushJobs);
8529 }
8530}
8531function invalidateJob(job) {
8532 const i = queue.indexOf(job);
8533 if (i > flushIndex) {
8534 queue.splice(i, 1);
8535 }
8536}
8537function queueCb(cb, activeQueue, pendingQueue, index) {
8538 if (!isArray(cb)) {
8539 if (!activeQueue ||
8540 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
8541 pendingQueue.push(cb);
8542 }
8543 }
8544 else {
8545 // if cb is an array, it is a component lifecycle hook which can only be
8546 // triggered by a job, which is already deduped in the main queue, so
8547 // we can skip duplicate check here to improve perf
8548 pendingQueue.push(...cb);
8549 }
8550 queueFlush();
8551}
8552function queuePreFlushCb(cb) {
8553 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
8554}
8555function queuePostFlushCb(cb) {
8556 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
8557}
8558function flushPreFlushCbs(seen, parentJob = null) {
8559 if (pendingPreFlushCbs.length) {
8560 currentPreFlushParentJob = parentJob;
8561 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
8562 pendingPreFlushCbs.length = 0;
8563 {
8564 seen = seen || new Map();
8565 }
8566 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
8567 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
8568 continue;
8569 }
8570 activePreFlushCbs[preFlushIndex]();
8571 }
8572 activePreFlushCbs = null;
8573 preFlushIndex = 0;
8574 currentPreFlushParentJob = null;
8575 // recursively flush until it drains
8576 flushPreFlushCbs(seen, parentJob);
8577 }
8578}
8579function flushPostFlushCbs(seen) {
8580 if (pendingPostFlushCbs.length) {
8581 const deduped = [...new Set(pendingPostFlushCbs)];
8582 pendingPostFlushCbs.length = 0;
8583 // #1947 already has active queue, nested flushPostFlushCbs call
8584 if (activePostFlushCbs) {
8585 activePostFlushCbs.push(...deduped);
8586 return;
8587 }
8588 activePostFlushCbs = deduped;
8589 {
8590 seen = seen || new Map();
8591 }
8592 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
8593 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
8594 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
8595 continue;
8596 }
8597 activePostFlushCbs[postFlushIndex]();
8598 }
8599 activePostFlushCbs = null;
8600 postFlushIndex = 0;
8601 }
8602}
8603const getId = (job) => job.id == null ? Infinity : job.id;
8604function flushJobs(seen) {
8605 isFlushPending = false;
8606 isFlushing = true;
8607 {
8608 seen = seen || new Map();
8609 }
8610 flushPreFlushCbs(seen);
8611 // Sort queue before flush.
8612 // This ensures that:
8613 // 1. Components are updated from parent to child. (because parent is always
8614 // created before the child so its render effect will have smaller
8615 // priority number)
8616 // 2. If a component is unmounted during a parent component's update,
8617 // its update can be skipped.
8618 queue.sort((a, b) => getId(a) - getId(b));
8619 try {
8620 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
8621 const job = queue[flushIndex];
8622 if (job && job.active !== false) {
8623 if (true && checkRecursiveUpdates(seen, job)) {
8624 continue;
8625 }
8626 // console.log(`running:`, job.id)
8627 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
8628 }
8629 }
8630 }
8631 finally {
8632 flushIndex = 0;
8633 queue.length = 0;
8634 flushPostFlushCbs(seen);
8635 isFlushing = false;
8636 currentFlushPromise = null;
8637 // some postFlushCb queued jobs!
8638 // keep flushing until it drains.
8639 if (queue.length ||
8640 pendingPreFlushCbs.length ||
8641 pendingPostFlushCbs.length) {
8642 flushJobs(seen);
8643 }
8644 }
8645}
8646function checkRecursiveUpdates(seen, fn) {
8647 if (!seen.has(fn)) {
8648 seen.set(fn, 1);
8649 }
8650 else {
8651 const count = seen.get(fn);
8652 if (count > RECURSION_LIMIT) {
8653 const instance = fn.ownerInstance;
8654 const componentName = instance && getComponentName(instance.type);
8655 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
8656 `This means you have a reactive effect that is mutating its own ` +
8657 `dependencies and thus recursively triggering itself. Possible sources ` +
8658 `include component template, render function, updated hook or ` +
8659 `watcher source function.`);
8660 return true;
8661 }
8662 else {
8663 seen.set(fn, count + 1);
8664 }
8665 }
8666}
8667
8668// Simple effect.
8669function watchEffect(effect, options) {
8670 return doWatch(effect, null, options);
8671}
8672function watchPostEffect(effect, options) {
8673 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
8674 ));
8675}
8676function watchSyncEffect(effect, options) {
8677 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
8678 ));
8679}
8680// initial value for watchers to trigger on undefined initial values
8681const INITIAL_WATCHER_VALUE = {};
8682// implementation
8683function watch(source, cb, options) {
8684 if (!isFunction(cb)) {
8685 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
8686 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
8687 `supports \`watch(source, cb, options?) signature.`);
8688 }
8689 return doWatch(source, cb, options);
8690}
8691function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
8692 if (!cb) {
8693 if (immediate !== undefined) {
8694 warn$1(`watch() "immediate" option is only respected when using the ` +
8695 `watch(source, callback, options?) signature.`);
8696 }
8697 if (deep !== undefined) {
8698 warn$1(`watch() "deep" option is only respected when using the ` +
8699 `watch(source, callback, options?) signature.`);
8700 }
8701 }
8702 const warnInvalidSource = (s) => {
8703 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
8704 `a reactive object, or an array of these types.`);
8705 };
8706 const instance = currentInstance;
8707 let getter;
8708 let forceTrigger = false;
8709 let isMultiSource = false;
8710 if (isRef(source)) {
8711 getter = () => source.value;
8712 forceTrigger = !!source._shallow;
8713 }
8714 else if (isReactive(source)) {
8715 getter = () => source;
8716 deep = true;
8717 }
8718 else if (isArray(source)) {
8719 isMultiSource = true;
8720 forceTrigger = source.some(isReactive);
8721 getter = () => source.map(s => {
8722 if (isRef(s)) {
8723 return s.value;
8724 }
8725 else if (isReactive(s)) {
8726 return traverse(s);
8727 }
8728 else if (isFunction(s)) {
8729 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
8730 }
8731 else {
8732 warnInvalidSource(s);
8733 }
8734 });
8735 }
8736 else if (isFunction(source)) {
8737 if (cb) {
8738 // getter with cb
8739 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
8740 }
8741 else {
8742 // no cb -> simple effect
8743 getter = () => {
8744 if (instance && instance.isUnmounted) {
8745 return;
8746 }
8747 if (cleanup) {
8748 cleanup();
8749 }
8750 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
8751 };
8752 }
8753 }
8754 else {
8755 getter = NOOP;
8756 warnInvalidSource(source);
8757 }
8758 if (cb && deep) {
8759 const baseGetter = getter;
8760 getter = () => traverse(baseGetter());
8761 }
8762 let cleanup;
8763 let onInvalidate = (fn) => {
8764 cleanup = effect.onStop = () => {
8765 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
8766 };
8767 };
8768 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
8769 const job = () => {
8770 if (!effect.active) {
8771 return;
8772 }
8773 if (cb) {
8774 // watch(source, cb)
8775 const newValue = effect.run();
8776 if (deep ||
8777 forceTrigger ||
8778 (isMultiSource
8779 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
8780 : hasChanged(newValue, oldValue)) ||
8781 (false )) {
8782 // cleanup before running cb again
8783 if (cleanup) {
8784 cleanup();
8785 }
8786 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
8787 newValue,
8788 // pass undefined as the old value when it's changed for the first time
8789 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
8790 onInvalidate
8791 ]);
8792 oldValue = newValue;
8793 }
8794 }
8795 else {
8796 // watchEffect
8797 effect.run();
8798 }
8799 };
8800 // important: mark the job as a watcher callback so that scheduler knows
8801 // it is allowed to self-trigger (#1727)
8802 job.allowRecurse = !!cb;
8803 let scheduler;
8804 if (flush === 'sync') {
8805 scheduler = job; // the scheduler function gets called directly
8806 }
8807 else if (flush === 'post') {
8808 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
8809 }
8810 else {
8811 // default: 'pre'
8812 scheduler = () => {
8813 if (!instance || instance.isMounted) {
8814 queuePreFlushCb(job);
8815 }
8816 else {
8817 // with 'pre' option, the first call must happen before
8818 // the component is mounted so it is called synchronously.
8819 job();
8820 }
8821 };
8822 }
8823 const effect = new ReactiveEffect(getter, scheduler);
8824 {
8825 effect.onTrack = onTrack;
8826 effect.onTrigger = onTrigger;
8827 }
8828 // initial run
8829 if (cb) {
8830 if (immediate) {
8831 job();
8832 }
8833 else {
8834 oldValue = effect.run();
8835 }
8836 }
8837 else if (flush === 'post') {
8838 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
8839 }
8840 else {
8841 effect.run();
8842 }
8843 return () => {
8844 effect.stop();
8845 if (instance && instance.scope) {
8846 remove(instance.scope.effects, effect);
8847 }
8848 };
8849}
8850// this.$watch
8851function instanceWatch(source, value, options) {
8852 const publicThis = this.proxy;
8853 const getter = isString(source)
8854 ? source.includes('.')
8855 ? createPathGetter(publicThis, source)
8856 : () => publicThis[source]
8857 : source.bind(publicThis, publicThis);
8858 let cb;
8859 if (isFunction(value)) {
8860 cb = value;
8861 }
8862 else {
8863 cb = value.handler;
8864 options = value;
8865 }
8866 const cur = currentInstance;
8867 setCurrentInstance(this);
8868 const res = doWatch(getter, cb.bind(publicThis), options);
8869 if (cur) {
8870 setCurrentInstance(cur);
8871 }
8872 else {
8873 unsetCurrentInstance();
8874 }
8875 return res;
8876}
8877function createPathGetter(ctx, path) {
8878 const segments = path.split('.');
8879 return () => {
8880 let cur = ctx;
8881 for (let i = 0; i < segments.length && cur; i++) {
8882 cur = cur[segments[i]];
8883 }
8884 return cur;
8885 };
8886}
8887function traverse(value, seen = new Set()) {
8888 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
8889 return value;
8890 }
8891 seen = seen || new Set();
8892 if (seen.has(value)) {
8893 return value;
8894 }
8895 seen.add(value);
8896 if (isRef(value)) {
8897 traverse(value.value, seen);
8898 }
8899 else if (isArray(value)) {
8900 for (let i = 0; i < value.length; i++) {
8901 traverse(value[i], seen);
8902 }
8903 }
8904 else if (isSet(value) || isMap(value)) {
8905 value.forEach((v) => {
8906 traverse(v, seen);
8907 });
8908 }
8909 else if (isPlainObject(value)) {
8910 for (const key in value) {
8911 traverse(value[key], seen);
8912 }
8913 }
8914 return value;
8915}
8916
8917// dev only
8918const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8919 `<script setup> of a single file component. Its arguments should be ` +
8920 `compiled away and passing it at runtime has no effect.`);
8921// implementation
8922function defineProps() {
8923 {
8924 warnRuntimeUsage(`defineProps`);
8925 }
8926 return null;
8927}
8928// implementation
8929function defineEmits() {
8930 {
8931 warnRuntimeUsage(`defineEmits`);
8932 }
8933 return null;
8934}
8935/**
8936 * Vue `<script setup>` compiler macro for declaring a component's exposed
8937 * instance properties when it is accessed by a parent component via template
8938 * refs.
8939 *
8940 * `<script setup>` components are closed by default - i.e. varaibles inside
8941 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8942 * via `defineExpose`.
8943 *
8944 * This is only usable inside `<script setup>`, is compiled away in the
8945 * output and should **not** be actually called at runtime.
8946 */
8947function defineExpose(exposed) {
8948 {
8949 warnRuntimeUsage(`defineExpose`);
8950 }
8951}
8952/**
8953 * Vue `<script setup>` compiler macro for providing props default values when
8954 * using type-based `defineProps` declaration.
8955 *
8956 * Example usage:
8957 * ```ts
8958 * withDefaults(defineProps<{
8959 * size?: number
8960 * labels?: string[]
8961 * }>(), {
8962 * size: 3,
8963 * labels: () => ['default label']
8964 * })
8965 * ```
8966 *
8967 * This is only usable inside `<script setup>`, is compiled away in the output
8968 * and should **not** be actually called at runtime.
8969 */
8970function withDefaults(props, defaults) {
8971 {
8972 warnRuntimeUsage(`withDefaults`);
8973 }
8974 return null;
8975}
8976function useSlots() {
8977 return getContext().slots;
8978}
8979function useAttrs() {
8980 return getContext().attrs;
8981}
8982function getContext() {
8983 const i = getCurrentInstance();
8984 if (!i) {
8985 warn$1(`useContext() called without active instance.`);
8986 }
8987 return i.setupContext || (i.setupContext = createSetupContext(i));
8988}
8989/**
8990 * Runtime helper for merging default declarations. Imported by compiled code
8991 * only.
8992 * @internal
8993 */
8994function mergeDefaults(
8995// the base props is compiler-generated and guaranteed to be in this shape.
8996props, defaults) {
8997 for (const key in defaults) {
8998 const val = props[key];
8999 if (val) {
9000 val.default = defaults[key];
9001 }
9002 else if (val === null) {
9003 props[key] = { default: defaults[key] };
9004 }
9005 else {
9006 warn$1(`props default key "${key}" has no corresponding declaration.`);
9007 }
9008 }
9009 return props;
9010}
9011/**
9012 * `<script setup>` helper for persisting the current instance context over
9013 * async/await flows.
9014 *
9015 * `@vue/compiler-sfc` converts the following:
9016 *
9017 * ```ts
9018 * const x = await foo()
9019 * ```
9020 *
9021 * into:
9022 *
9023 * ```ts
9024 * let __temp, __restore
9025 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
9026 * ```
9027 * @internal
9028 */
9029function withAsyncContext(getAwaitable) {
9030 const ctx = getCurrentInstance();
9031 if (!ctx) {
9032 warn$1(`withAsyncContext called without active current instance. ` +
9033 `This is likely a bug.`);
9034 }
9035 let awaitable = getAwaitable();
9036 unsetCurrentInstance();
9037 if (isPromise(awaitable)) {
9038 awaitable = awaitable.catch(e => {
9039 setCurrentInstance(ctx);
9040 throw e;
9041 });
9042 }
9043 return [awaitable, () => setCurrentInstance(ctx)];
9044}
9045
9046// Actual implementation
9047function h(type, propsOrChildren, children) {
9048 const l = arguments.length;
9049 if (l === 2) {
9050 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
9051 // single vnode without props
9052 if (isVNode(propsOrChildren)) {
9053 return createVNode(type, null, [propsOrChildren]);
9054 }
9055 // props without children
9056 return createVNode(type, propsOrChildren);
9057 }
9058 else {
9059 // omit props
9060 return createVNode(type, null, propsOrChildren);
9061 }
9062 }
9063 else {
9064 if (l > 3) {
9065 children = Array.prototype.slice.call(arguments, 2);
9066 }
9067 else if (l === 3 && isVNode(children)) {
9068 children = [children];
9069 }
9070 return createVNode(type, propsOrChildren, children);
9071 }
9072}
9073
9074const ssrContextKey = Symbol(`ssrContext` );
9075const useSSRContext = () => {
9076 {
9077 const ctx = inject(ssrContextKey);
9078 if (!ctx) {
9079 warn$1(`Server rendering context not provided. Make sure to only call ` +
9080 `useSSRContext() conditionally in the server build.`);
9081 }
9082 return ctx;
9083 }
9084};
9085
9086function initCustomFormatter() {
9087 /* eslint-disable no-restricted-globals */
9088 if (typeof window === 'undefined') {
9089 return;
9090 }
9091 const vueStyle = { style: 'color:#3ba776' };
9092 const numberStyle = { style: 'color:#0b1bc9' };
9093 const stringStyle = { style: 'color:#b62e24' };
9094 const keywordStyle = { style: 'color:#9d288c' };
9095 // custom formatter for Chrome
9096 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
9097 const formatter = {
9098 header(obj) {
9099 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
9100 if (!isObject(obj)) {
9101 return null;
9102 }
9103 if (obj.__isVue) {
9104 return ['div', vueStyle, `VueInstance`];
9105 }
9106 else if (isRef(obj)) {
9107 return [
9108 'div',
9109 {},
9110 ['span', vueStyle, genRefFlag(obj)],
9111 '<',
9112 formatValue(obj.value),
9113 `>`
9114 ];
9115 }
9116 else if (isReactive(obj)) {
9117 return [
9118 'div',
9119 {},
9120 ['span', vueStyle, 'Reactive'],
9121 '<',
9122 formatValue(obj),
9123 `>${isReadonly(obj) ? ` (readonly)` : ``}`
9124 ];
9125 }
9126 else if (isReadonly(obj)) {
9127 return [
9128 'div',
9129 {},
9130 ['span', vueStyle, 'Readonly'],
9131 '<',
9132 formatValue(obj),
9133 '>'
9134 ];
9135 }
9136 return null;
9137 },
9138 hasBody(obj) {
9139 return obj && obj.__isVue;
9140 },
9141 body(obj) {
9142 if (obj && obj.__isVue) {
9143 return [
9144 'div',
9145 {},
9146 ...formatInstance(obj.$)
9147 ];
9148 }
9149 }
9150 };
9151 function formatInstance(instance) {
9152 const blocks = [];
9153 if (instance.type.props && instance.props) {
9154 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
9155 }
9156 if (instance.setupState !== EMPTY_OBJ) {
9157 blocks.push(createInstanceBlock('setup', instance.setupState));
9158 }
9159 if (instance.data !== EMPTY_OBJ) {
9160 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
9161 }
9162 const computed = extractKeys(instance, 'computed');
9163 if (computed) {
9164 blocks.push(createInstanceBlock('computed', computed));
9165 }
9166 const injected = extractKeys(instance, 'inject');
9167 if (injected) {
9168 blocks.push(createInstanceBlock('injected', injected));
9169 }
9170 blocks.push([
9171 'div',
9172 {},
9173 [
9174 'span',
9175 {
9176 style: keywordStyle.style + ';opacity:0.66'
9177 },
9178 '$ (internal): '
9179 ],
9180 ['object', { object: instance }]
9181 ]);
9182 return blocks;
9183 }
9184 function createInstanceBlock(type, target) {
9185 target = extend({}, target);
9186 if (!Object.keys(target).length) {
9187 return ['span', {}];
9188 }
9189 return [
9190 'div',
9191 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9192 [
9193 'div',
9194 {
9195 style: 'color:#476582'
9196 },
9197 type
9198 ],
9199 [
9200 'div',
9201 {
9202 style: 'padding-left:1.25em'
9203 },
9204 ...Object.keys(target).map(key => {
9205 return [
9206 'div',
9207 {},
9208 ['span', keywordStyle, key + ': '],
9209 formatValue(target[key], false)
9210 ];
9211 })
9212 ]
9213 ];
9214 }
9215 function formatValue(v, asRaw = true) {
9216 if (typeof v === 'number') {
9217 return ['span', numberStyle, v];
9218 }
9219 else if (typeof v === 'string') {
9220 return ['span', stringStyle, JSON.stringify(v)];
9221 }
9222 else if (typeof v === 'boolean') {
9223 return ['span', keywordStyle, v];
9224 }
9225 else if (isObject(v)) {
9226 return ['object', { object: asRaw ? toRaw(v) : v }];
9227 }
9228 else {
9229 return ['span', stringStyle, String(v)];
9230 }
9231 }
9232 function extractKeys(instance, type) {
9233 const Comp = instance.type;
9234 if (isFunction(Comp)) {
9235 return;
9236 }
9237 const extracted = {};
9238 for (const key in instance.ctx) {
9239 if (isKeyOfType(Comp, key, type)) {
9240 extracted[key] = instance.ctx[key];
9241 }
9242 }
9243 return extracted;
9244 }
9245 function isKeyOfType(Comp, key, type) {
9246 const opts = Comp[type];
9247 if ((isArray(opts) && opts.includes(key)) ||
9248 (isObject(opts) && key in opts)) {
9249 return true;
9250 }
9251 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9252 return true;
9253 }
9254 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9255 return true;
9256 }
9257 }
9258 function genRefFlag(v) {
9259 if (v._shallow) {
9260 return `ShallowRef`;
9261 }
9262 if (v.effect) {
9263 return `ComputedRef`;
9264 }
9265 return `Ref`;
9266 }
9267 if (window.devtoolsFormatters) {
9268 window.devtoolsFormatters.push(formatter);
9269 }
9270 else {
9271 window.devtoolsFormatters = [formatter];
9272 }
9273}
9274
9275function withMemo(memo, render, cache, index) {
9276 const cached = cache[index];
9277 if (cached && isMemoSame(cached, memo)) {
9278 return cached;
9279 }
9280 const ret = render();
9281 // shallow clone
9282 ret.memo = memo.slice();
9283 return (cache[index] = ret);
9284}
9285function isMemoSame(cached, memo) {
9286 const prev = cached.memo;
9287 if (prev.length != memo.length) {
9288 return false;
9289 }
9290 for (let i = 0; i < prev.length; i++) {
9291 if (prev[i] !== memo[i]) {
9292 return false;
9293 }
9294 }
9295 // make sure to let parent block track it when returning cached
9296 if (isBlockTreeEnabled > 0 && currentBlock) {
9297 currentBlock.push(cached);
9298 }
9299 return true;
9300}
9301
9302// Core API ------------------------------------------------------------------
9303const version = "3.2.11";
9304/**
9305 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9306 * @internal
9307 */
9308const ssrUtils = (null);
9309/**
9310 * @internal only exposed in compat builds
9311 */
9312const resolveFilter = null;
9313/**
9314 * @internal only exposed in compat builds.
9315 */
9316const compatUtils = (null);
9317
9318const svgNS = 'http://www.w3.org/2000/svg';
9319const doc = (typeof document !== 'undefined' ? document : null);
9320const staticTemplateCache = new Map();
9321const nodeOps = {
9322 insert: (child, parent, anchor) => {
9323 parent.insertBefore(child, anchor || null);
9324 },
9325 remove: child => {
9326 const parent = child.parentNode;
9327 if (parent) {
9328 parent.removeChild(child);
9329 }
9330 },
9331 createElement: (tag, isSVG, is, props) => {
9332 const el = isSVG
9333 ? doc.createElementNS(svgNS, tag)
9334 : doc.createElement(tag, is ? { is } : undefined);
9335 if (tag === 'select' && props && props.multiple != null) {
9336 el.setAttribute('multiple', props.multiple);
9337 }
9338 return el;
9339 },
9340 createText: text => doc.createTextNode(text),
9341 createComment: text => doc.createComment(text),
9342 setText: (node, text) => {
9343 node.nodeValue = text;
9344 },
9345 setElementText: (el, text) => {
9346 el.textContent = text;
9347 },
9348 parentNode: node => node.parentNode,
9349 nextSibling: node => node.nextSibling,
9350 querySelector: selector => doc.querySelector(selector),
9351 setScopeId(el, id) {
9352 el.setAttribute(id, '');
9353 },
9354 cloneNode(el) {
9355 const cloned = el.cloneNode(true);
9356 // #3072
9357 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9358 // - normally, elements using `:value` bindings will not be hoisted, but if
9359 // the bound value is a constant, e.g. `:value="true"` - they do get
9360 // hoisted.
9361 // - in production, hoisted nodes are cloned when subsequent inserts, but
9362 // cloneNode() does not copy the custom property we attached.
9363 // - This may need to account for other custom DOM properties we attach to
9364 // elements in addition to `_value` in the future.
9365 if (`_value` in el) {
9366 cloned._value = el._value;
9367 }
9368 return cloned;
9369 },
9370 // __UNSAFE__
9371 // Reason: innerHTML.
9372 // Static content here can only come from compiled templates.
9373 // As long as the user only uses trusted templates, this is safe.
9374 insertStaticContent(content, parent, anchor, isSVG) {
9375 // <parent> before | first ... last | anchor </parent>
9376 const before = anchor ? anchor.previousSibling : parent.lastChild;
9377 let template = staticTemplateCache.get(content);
9378 if (!template) {
9379 const t = doc.createElement('template');
9380 t.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9381 template = t.content;
9382 if (isSVG) {
9383 // remove outer svg wrapper
9384 const wrapper = template.firstChild;
9385 while (wrapper.firstChild) {
9386 template.appendChild(wrapper.firstChild);
9387 }
9388 template.removeChild(wrapper);
9389 }
9390 staticTemplateCache.set(content, template);
9391 }
9392 parent.insertBefore(template.cloneNode(true), anchor);
9393 return [
9394 // first
9395 before ? before.nextSibling : parent.firstChild,
9396 // last
9397 anchor ? anchor.previousSibling : parent.lastChild
9398 ];
9399 }
9400};
9401
9402// compiler should normalize class + :class bindings on the same element
9403// into a single binding ['staticClass', dynamic]
9404function patchClass(el, value, isSVG) {
9405 // directly setting className should be faster than setAttribute in theory
9406 // if this is an element during a transition, take the temporary transition
9407 // classes into account.
9408 const transitionClasses = el._vtc;
9409 if (transitionClasses) {
9410 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9411 }
9412 if (value == null) {
9413 el.removeAttribute('class');
9414 }
9415 else if (isSVG) {
9416 el.setAttribute('class', value);
9417 }
9418 else {
9419 el.className = value;
9420 }
9421}
9422
9423function patchStyle(el, prev, next) {
9424 const style = el.style;
9425 const currentDisplay = style.display;
9426 if (!next) {
9427 el.removeAttribute('style');
9428 }
9429 else if (isString(next)) {
9430 if (prev !== next) {
9431 style.cssText = next;
9432 }
9433 }
9434 else {
9435 for (const key in next) {
9436 setStyle(style, key, next[key]);
9437 }
9438 if (prev && !isString(prev)) {
9439 for (const key in prev) {
9440 if (next[key] == null) {
9441 setStyle(style, key, '');
9442 }
9443 }
9444 }
9445 }
9446 // indicates that the `display` of the element is controlled by `v-show`,
9447 // so we always keep the current `display` value regardless of the `style` value,
9448 // thus handing over control to `v-show`.
9449 if ('_vod' in el) {
9450 style.display = currentDisplay;
9451 }
9452}
9453const importantRE = /\s*!important$/;
9454function setStyle(style, name, val) {
9455 if (isArray(val)) {
9456 val.forEach(v => setStyle(style, name, v));
9457 }
9458 else {
9459 if (name.startsWith('--')) {
9460 // custom property definition
9461 style.setProperty(name, val);
9462 }
9463 else {
9464 const prefixed = autoPrefix(style, name);
9465 if (importantRE.test(val)) {
9466 // !important
9467 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9468 }
9469 else {
9470 style[prefixed] = val;
9471 }
9472 }
9473 }
9474}
9475const prefixes = ['Webkit', 'Moz', 'ms'];
9476const prefixCache = {};
9477function autoPrefix(style, rawName) {
9478 const cached = prefixCache[rawName];
9479 if (cached) {
9480 return cached;
9481 }
9482 let name = camelize(rawName);
9483 if (name !== 'filter' && name in style) {
9484 return (prefixCache[rawName] = name);
9485 }
9486 name = capitalize(name);
9487 for (let i = 0; i < prefixes.length; i++) {
9488 const prefixed = prefixes[i] + name;
9489 if (prefixed in style) {
9490 return (prefixCache[rawName] = prefixed);
9491 }
9492 }
9493 return rawName;
9494}
9495
9496const xlinkNS = 'http://www.w3.org/1999/xlink';
9497function patchAttr(el, key, value, isSVG, instance) {
9498 if (isSVG && key.startsWith('xlink:')) {
9499 if (value == null) {
9500 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9501 }
9502 else {
9503 el.setAttributeNS(xlinkNS, key, value);
9504 }
9505 }
9506 else {
9507 // note we are only checking boolean attributes that don't have a
9508 // corresponding dom prop of the same name here.
9509 const isBoolean = isSpecialBooleanAttr(key);
9510 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9511 el.removeAttribute(key);
9512 }
9513 else {
9514 el.setAttribute(key, isBoolean ? '' : value);
9515 }
9516 }
9517}
9518
9519// __UNSAFE__
9520// functions. The user is responsible for using them with only trusted content.
9521function patchDOMProp(el, key, value,
9522// the following args are passed only due to potential innerHTML/textContent
9523// overriding existing VNodes, in which case the old tree must be properly
9524// unmounted.
9525prevChildren, parentComponent, parentSuspense, unmountChildren) {
9526 if (key === 'innerHTML' || key === 'textContent') {
9527 if (prevChildren) {
9528 unmountChildren(prevChildren, parentComponent, parentSuspense);
9529 }
9530 el[key] = value == null ? '' : value;
9531 return;
9532 }
9533 if (key === 'value' && el.tagName !== 'PROGRESS') {
9534 // store value as _value as well since
9535 // non-string values will be stringified.
9536 el._value = value;
9537 const newValue = value == null ? '' : value;
9538 if (el.value !== newValue) {
9539 el.value = newValue;
9540 }
9541 if (value == null) {
9542 el.removeAttribute(key);
9543 }
9544 return;
9545 }
9546 if (value === '' || value == null) {
9547 const type = typeof el[key];
9548 if (type === 'boolean') {
9549 // e.g. <select multiple> compiles to { multiple: '' }
9550 el[key] = includeBooleanAttr(value);
9551 return;
9552 }
9553 else if (value == null && type === 'string') {
9554 // e.g. <div :id="null">
9555 el[key] = '';
9556 el.removeAttribute(key);
9557 return;
9558 }
9559 else if (type === 'number') {
9560 // e.g. <img :width="null">
9561 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9562 try {
9563 el[key] = 0;
9564 }
9565 catch (_a) { }
9566 el.removeAttribute(key);
9567 return;
9568 }
9569 }
9570 // some properties perform value validation and throw
9571 try {
9572 el[key] = value;
9573 }
9574 catch (e) {
9575 {
9576 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9577 `value ${value} is invalid.`, e);
9578 }
9579 }
9580}
9581
9582// Async edge case fix requires storing an event listener's attach timestamp.
9583let _getNow = Date.now;
9584let skipTimestampCheck = false;
9585if (typeof window !== 'undefined') {
9586 // Determine what event timestamp the browser is using. Annoyingly, the
9587 // timestamp can either be hi-res (relative to page load) or low-res
9588 // (relative to UNIX epoch), so in order to compare time we have to use the
9589 // same timestamp type when saving the flush timestamp.
9590 if (_getNow() > document.createEvent('Event').timeStamp) {
9591 // if the low-res timestamp which is bigger than the event timestamp
9592 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9593 // and we need to use the hi-res version for event listeners as well.
9594 _getNow = () => performance.now();
9595 }
9596 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9597 // and does not fire microtasks in between event propagation, so safe to exclude.
9598 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9599 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9600}
9601// To avoid the overhead of repeatedly calling performance.now(), we cache
9602// and use the same timestamp for all event listeners attached in the same tick.
9603let cachedNow = 0;
9604const p = Promise.resolve();
9605const reset = () => {
9606 cachedNow = 0;
9607};
9608const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9609function addEventListener(el, event, handler, options) {
9610 el.addEventListener(event, handler, options);
9611}
9612function removeEventListener(el, event, handler, options) {
9613 el.removeEventListener(event, handler, options);
9614}
9615function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9616 // vei = vue event invokers
9617 const invokers = el._vei || (el._vei = {});
9618 const existingInvoker = invokers[rawName];
9619 if (nextValue && existingInvoker) {
9620 // patch
9621 existingInvoker.value = nextValue;
9622 }
9623 else {
9624 const [name, options] = parseName(rawName);
9625 if (nextValue) {
9626 // add
9627 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9628 addEventListener(el, name, invoker, options);
9629 }
9630 else if (existingInvoker) {
9631 // remove
9632 removeEventListener(el, name, existingInvoker, options);
9633 invokers[rawName] = undefined;
9634 }
9635 }
9636}
9637const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9638function parseName(name) {
9639 let options;
9640 if (optionsModifierRE.test(name)) {
9641 options = {};
9642 let m;
9643 while ((m = name.match(optionsModifierRE))) {
9644 name = name.slice(0, name.length - m[0].length);
9645 options[m[0].toLowerCase()] = true;
9646 }
9647 }
9648 return [hyphenate(name.slice(2)), options];
9649}
9650function createInvoker(initialValue, instance) {
9651 const invoker = (e) => {
9652 // async edge case #6566: inner click event triggers patch, event handler
9653 // attached to outer element during patch, and triggered again. This
9654 // happens because browsers fire microtask ticks between event propagation.
9655 // the solution is simple: we save the timestamp when a handler is attached,
9656 // and the handler would only fire if the event passed to it was fired
9657 // AFTER it was attached.
9658 const timeStamp = e.timeStamp || _getNow();
9659 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9660 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9661 }
9662 };
9663 invoker.value = initialValue;
9664 invoker.attached = getNow();
9665 return invoker;
9666}
9667function patchStopImmediatePropagation(e, value) {
9668 if (isArray(value)) {
9669 const originalStop = e.stopImmediatePropagation;
9670 e.stopImmediatePropagation = () => {
9671 originalStop.call(e);
9672 e._stopped = true;
9673 };
9674 return value.map(fn => (e) => !e._stopped && fn(e));
9675 }
9676 else {
9677 return value;
9678 }
9679}
9680
9681const nativeOnRE = /^on[a-z]/;
9682const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9683 if (key === 'class') {
9684 patchClass(el, nextValue, isSVG);
9685 }
9686 else if (key === 'style') {
9687 patchStyle(el, prevValue, nextValue);
9688 }
9689 else if (isOn(key)) {
9690 // ignore v-model listeners
9691 if (!isModelListener(key)) {
9692 patchEvent(el, key, prevValue, nextValue, parentComponent);
9693 }
9694 }
9695 else if (key[0] === '.'
9696 ? ((key = key.slice(1)), true)
9697 : key[0] === '^'
9698 ? ((key = key.slice(1)), false)
9699 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9700 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9701 }
9702 else {
9703 // special case for <input v-model type="checkbox"> with
9704 // :true-value & :false-value
9705 // store value as dom properties since non-string values will be
9706 // stringified.
9707 if (key === 'true-value') {
9708 el._trueValue = nextValue;
9709 }
9710 else if (key === 'false-value') {
9711 el._falseValue = nextValue;
9712 }
9713 patchAttr(el, key, nextValue, isSVG);
9714 }
9715};
9716function shouldSetAsProp(el, key, value, isSVG) {
9717 if (isSVG) {
9718 // most keys must be set as attribute on svg elements to work
9719 // ...except innerHTML & textContent
9720 if (key === 'innerHTML' || key === 'textContent') {
9721 return true;
9722 }
9723 // or native onclick with function values
9724 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9725 return true;
9726 }
9727 return false;
9728 }
9729 // spellcheck and draggable are numerated attrs, however their
9730 // corresponding DOM properties are actually booleans - this leads to
9731 // setting it with a string "false" value leading it to be coerced to
9732 // `true`, so we need to always treat them as attributes.
9733 // Note that `contentEditable` doesn't have this problem: its DOM
9734 // property is also enumerated string values.
9735 if (key === 'spellcheck' || key === 'draggable') {
9736 return false;
9737 }
9738 // #1787, #2840 form property on form elements is readonly and must be set as
9739 // attribute.
9740 if (key === 'form') {
9741 return false;
9742 }
9743 // #1526 <input list> must be set as attribute
9744 if (key === 'list' && el.tagName === 'INPUT') {
9745 return false;
9746 }
9747 // #2766 <textarea type> must be set as attribute
9748 if (key === 'type' && el.tagName === 'TEXTAREA') {
9749 return false;
9750 }
9751 // native onclick with string value, must be set as attribute
9752 if (nativeOnRE.test(key) && isString(value)) {
9753 return false;
9754 }
9755 return key in el;
9756}
9757
9758function defineCustomElement(options, hydate) {
9759 const Comp = defineComponent(options);
9760 class VueCustomElement extends VueElement {
9761 constructor(initialProps) {
9762 super(Comp, initialProps, hydate);
9763 }
9764 }
9765 VueCustomElement.def = Comp;
9766 return VueCustomElement;
9767}
9768const defineSSRCustomElement = ((options) => {
9769 // @ts-ignore
9770 return defineCustomElement(options, hydrate);
9771});
9772const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9773});
9774class VueElement extends BaseClass {
9775 constructor(_def, _props = {}, hydrate) {
9776 super();
9777 this._def = _def;
9778 this._props = _props;
9779 /**
9780 * @internal
9781 */
9782 this._instance = null;
9783 this._connected = false;
9784 this._resolved = false;
9785 if (this.shadowRoot && hydrate) {
9786 hydrate(this._createVNode(), this.shadowRoot);
9787 }
9788 else {
9789 if (this.shadowRoot) {
9790 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9791 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9792 }
9793 this.attachShadow({ mode: 'open' });
9794 }
9795 // set initial attrs
9796 for (let i = 0; i < this.attributes.length; i++) {
9797 this._setAttr(this.attributes[i].name);
9798 }
9799 // watch future attr changes
9800 const observer = new MutationObserver(mutations => {
9801 for (const m of mutations) {
9802 this._setAttr(m.attributeName);
9803 }
9804 });
9805 observer.observe(this, { attributes: true });
9806 }
9807 connectedCallback() {
9808 this._connected = true;
9809 if (!this._instance) {
9810 this._resolveDef();
9811 render(this._createVNode(), this.shadowRoot);
9812 }
9813 }
9814 disconnectedCallback() {
9815 this._connected = false;
9816 nextTick(() => {
9817 if (!this._connected) {
9818 render(null, this.shadowRoot);
9819 this._instance = null;
9820 }
9821 });
9822 }
9823 /**
9824 * resolve inner component definition (handle possible async component)
9825 */
9826 _resolveDef() {
9827 if (this._resolved) {
9828 return;
9829 }
9830 const resolve = (def) => {
9831 this._resolved = true;
9832 // check if there are props set pre-upgrade or connect
9833 for (const key of Object.keys(this)) {
9834 if (key[0] !== '_') {
9835 this._setProp(key, this[key]);
9836 }
9837 }
9838 const { props, styles } = def;
9839 // defining getter/setters on prototype
9840 const rawKeys = props ? (isArray(props) ? props : Object.keys(props)) : [];
9841 for (const key of rawKeys.map(camelize)) {
9842 Object.defineProperty(this, key, {
9843 get() {
9844 return this._getProp(key);
9845 },
9846 set(val) {
9847 this._setProp(key, val);
9848 }
9849 });
9850 }
9851 this._applyStyles(styles);
9852 };
9853 const asyncDef = this._def.__asyncLoader;
9854 if (asyncDef) {
9855 asyncDef().then(resolve);
9856 }
9857 else {
9858 resolve(this._def);
9859 }
9860 }
9861 _setAttr(key) {
9862 this._setProp(camelize(key), toNumber(this.getAttribute(key)), false);
9863 }
9864 /**
9865 * @internal
9866 */
9867 _getProp(key) {
9868 return this._props[key];
9869 }
9870 /**
9871 * @internal
9872 */
9873 _setProp(key, val, shouldReflect = true) {
9874 if (val !== this._props[key]) {
9875 this._props[key] = val;
9876 if (this._instance) {
9877 render(this._createVNode(), this.shadowRoot);
9878 }
9879 // reflect
9880 if (shouldReflect) {
9881 if (val === true) {
9882 this.setAttribute(hyphenate(key), '');
9883 }
9884 else if (typeof val === 'string' || typeof val === 'number') {
9885 this.setAttribute(hyphenate(key), val + '');
9886 }
9887 else if (!val) {
9888 this.removeAttribute(hyphenate(key));
9889 }
9890 }
9891 }
9892 }
9893 _createVNode() {
9894 const vnode = createVNode(this._def, extend({}, this._props));
9895 if (!this._instance) {
9896 vnode.ce = instance => {
9897 this._instance = instance;
9898 instance.isCE = true;
9899 // HMR
9900 {
9901 instance.ceReload = newStyles => {
9902 // alawys reset styles
9903 if (this._styles) {
9904 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9905 this._styles.length = 0;
9906 }
9907 this._applyStyles(newStyles);
9908 // if this is an async component, ceReload is called from the inner
9909 // component so no need to reload the async wrapper
9910 if (!this._def.__asyncLoader) {
9911 // reload
9912 this._instance = null;
9913 render(this._createVNode(), this.shadowRoot);
9914 }
9915 };
9916 }
9917 // intercept emit
9918 instance.emit = (event, ...args) => {
9919 this.dispatchEvent(new CustomEvent(event, {
9920 detail: args
9921 }));
9922 };
9923 // locate nearest Vue custom element parent for provide/inject
9924 let parent = this;
9925 while ((parent =
9926 parent && (parent.parentNode || parent.host))) {
9927 if (parent instanceof VueElement) {
9928 instance.parent = parent._instance;
9929 break;
9930 }
9931 }
9932 };
9933 }
9934 return vnode;
9935 }
9936 _applyStyles(styles) {
9937 if (styles) {
9938 styles.forEach(css => {
9939 const s = document.createElement('style');
9940 s.textContent = css;
9941 this.shadowRoot.appendChild(s);
9942 // record for HMR
9943 {
9944 (this._styles || (this._styles = [])).push(s);
9945 }
9946 });
9947 }
9948 }
9949}
9950
9951function useCssModule(name = '$style') {
9952 /* istanbul ignore else */
9953 {
9954 const instance = getCurrentInstance();
9955 if (!instance) {
9956 warn$1(`useCssModule must be called inside setup()`);
9957 return EMPTY_OBJ;
9958 }
9959 const modules = instance.type.__cssModules;
9960 if (!modules) {
9961 warn$1(`Current instance does not have CSS modules injected.`);
9962 return EMPTY_OBJ;
9963 }
9964 const mod = modules[name];
9965 if (!mod) {
9966 warn$1(`Current instance does not have CSS module named "${name}".`);
9967 return EMPTY_OBJ;
9968 }
9969 return mod;
9970 }
9971}
9972
9973/**
9974 * Runtime helper for SFC's CSS variable injection feature.
9975 * @private
9976 */
9977function useCssVars(getter) {
9978 const instance = getCurrentInstance();
9979 /* istanbul ignore next */
9980 if (!instance) {
9981 warn$1(`useCssVars is called without current active component instance.`);
9982 return;
9983 }
9984 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9985 watchPostEffect(setVars);
9986 onMounted(() => {
9987 const ob = new MutationObserver(setVars);
9988 ob.observe(instance.subTree.el.parentNode, { childList: true });
9989 onUnmounted(() => ob.disconnect());
9990 });
9991}
9992function setVarsOnVNode(vnode, vars) {
9993 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9994 const suspense = vnode.suspense;
9995 vnode = suspense.activeBranch;
9996 if (suspense.pendingBranch && !suspense.isHydrating) {
9997 suspense.effects.push(() => {
9998 setVarsOnVNode(suspense.activeBranch, vars);
9999 });
10000 }
10001 }
10002 // drill down HOCs until it's a non-component vnode
10003 while (vnode.component) {
10004 vnode = vnode.component.subTree;
10005 }
10006 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
10007 setVarsOnNode(vnode.el, vars);
10008 }
10009 else if (vnode.type === Fragment) {
10010 vnode.children.forEach(c => setVarsOnVNode(c, vars));
10011 }
10012 else if (vnode.type === Static) {
10013 let { el, anchor } = vnode;
10014 while (el) {
10015 setVarsOnNode(el, vars);
10016 if (el === anchor)
10017 break;
10018 el = el.nextSibling;
10019 }
10020 }
10021}
10022function setVarsOnNode(el, vars) {
10023 if (el.nodeType === 1) {
10024 const style = el.style;
10025 for (const key in vars) {
10026 style.setProperty(`--${key}`, vars[key]);
10027 }
10028 }
10029}
10030
10031const TRANSITION = 'transition';
10032const ANIMATION = 'animation';
10033// DOM Transition is a higher-order-component based on the platform-agnostic
10034// base Transition component, with DOM-specific logic.
10035const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
10036Transition.displayName = 'Transition';
10037const DOMTransitionPropsValidators = {
10038 name: String,
10039 type: String,
10040 css: {
10041 type: Boolean,
10042 default: true
10043 },
10044 duration: [String, Number, Object],
10045 enterFromClass: String,
10046 enterActiveClass: String,
10047 enterToClass: String,
10048 appearFromClass: String,
10049 appearActiveClass: String,
10050 appearToClass: String,
10051 leaveFromClass: String,
10052 leaveActiveClass: String,
10053 leaveToClass: String
10054};
10055const TransitionPropsValidators = (Transition.props =
10056 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
10057/**
10058 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
10059 * with custom HOCs.
10060 */
10061const callHook$1 = (hook, args = []) => {
10062 if (isArray(hook)) {
10063 hook.forEach(h => h(...args));
10064 }
10065 else if (hook) {
10066 hook(...args);
10067 }
10068};
10069/**
10070 * Check if a hook expects a callback (2nd arg), which means the user
10071 * intends to explicitly control the end of the transition.
10072 */
10073const hasExplicitCallback = (hook) => {
10074 return hook
10075 ? isArray(hook)
10076 ? hook.some(h => h.length > 1)
10077 : hook.length > 1
10078 : false;
10079};
10080function resolveTransitionProps(rawProps) {
10081 const baseProps = {};
10082 for (const key in rawProps) {
10083 if (!(key in DOMTransitionPropsValidators)) {
10084 baseProps[key] = rawProps[key];
10085 }
10086 }
10087 if (rawProps.css === false) {
10088 return baseProps;
10089 }
10090 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;
10091 const durations = normalizeDuration(duration);
10092 const enterDuration = durations && durations[0];
10093 const leaveDuration = durations && durations[1];
10094 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
10095 const finishEnter = (el, isAppear, done) => {
10096 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
10097 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
10098 done && done();
10099 };
10100 const finishLeave = (el, done) => {
10101 removeTransitionClass(el, leaveToClass);
10102 removeTransitionClass(el, leaveActiveClass);
10103 done && done();
10104 };
10105 const makeEnterHook = (isAppear) => {
10106 return (el, done) => {
10107 const hook = isAppear ? onAppear : onEnter;
10108 const resolve = () => finishEnter(el, isAppear, done);
10109 callHook$1(hook, [el, resolve]);
10110 nextFrame(() => {
10111 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
10112 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
10113 if (!hasExplicitCallback(hook)) {
10114 whenTransitionEnds(el, type, enterDuration, resolve);
10115 }
10116 });
10117 };
10118 };
10119 return extend(baseProps, {
10120 onBeforeEnter(el) {
10121 callHook$1(onBeforeEnter, [el]);
10122 addTransitionClass(el, enterFromClass);
10123 addTransitionClass(el, enterActiveClass);
10124 },
10125 onBeforeAppear(el) {
10126 callHook$1(onBeforeAppear, [el]);
10127 addTransitionClass(el, appearFromClass);
10128 addTransitionClass(el, appearActiveClass);
10129 },
10130 onEnter: makeEnterHook(false),
10131 onAppear: makeEnterHook(true),
10132 onLeave(el, done) {
10133 const resolve = () => finishLeave(el, done);
10134 addTransitionClass(el, leaveFromClass);
10135 // force reflow so *-leave-from classes immediately take effect (#2593)
10136 forceReflow();
10137 addTransitionClass(el, leaveActiveClass);
10138 nextFrame(() => {
10139 removeTransitionClass(el, leaveFromClass);
10140 addTransitionClass(el, leaveToClass);
10141 if (!hasExplicitCallback(onLeave)) {
10142 whenTransitionEnds(el, type, leaveDuration, resolve);
10143 }
10144 });
10145 callHook$1(onLeave, [el, resolve]);
10146 },
10147 onEnterCancelled(el) {
10148 finishEnter(el, false);
10149 callHook$1(onEnterCancelled, [el]);
10150 },
10151 onAppearCancelled(el) {
10152 finishEnter(el, true);
10153 callHook$1(onAppearCancelled, [el]);
10154 },
10155 onLeaveCancelled(el) {
10156 finishLeave(el);
10157 callHook$1(onLeaveCancelled, [el]);
10158 }
10159 });
10160}
10161function normalizeDuration(duration) {
10162 if (duration == null) {
10163 return null;
10164 }
10165 else if (isObject(duration)) {
10166 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10167 }
10168 else {
10169 const n = NumberOf(duration);
10170 return [n, n];
10171 }
10172}
10173function NumberOf(val) {
10174 const res = toNumber(val);
10175 validateDuration(res);
10176 return res;
10177}
10178function validateDuration(val) {
10179 if (typeof val !== 'number') {
10180 warn$1(`<transition> explicit duration is not a valid number - ` +
10181 `got ${JSON.stringify(val)}.`);
10182 }
10183 else if (isNaN(val)) {
10184 warn$1(`<transition> explicit duration is NaN - ` +
10185 'the duration expression might be incorrect.');
10186 }
10187}
10188function addTransitionClass(el, cls) {
10189 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10190 (el._vtc ||
10191 (el._vtc = new Set())).add(cls);
10192}
10193function removeTransitionClass(el, cls) {
10194 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10195 const { _vtc } = el;
10196 if (_vtc) {
10197 _vtc.delete(cls);
10198 if (!_vtc.size) {
10199 el._vtc = undefined;
10200 }
10201 }
10202}
10203function nextFrame(cb) {
10204 requestAnimationFrame(() => {
10205 requestAnimationFrame(cb);
10206 });
10207}
10208let endId = 0;
10209function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10210 const id = (el._endId = ++endId);
10211 const resolveIfNotStale = () => {
10212 if (id === el._endId) {
10213 resolve();
10214 }
10215 };
10216 if (explicitTimeout) {
10217 return setTimeout(resolveIfNotStale, explicitTimeout);
10218 }
10219 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10220 if (!type) {
10221 return resolve();
10222 }
10223 const endEvent = type + 'end';
10224 let ended = 0;
10225 const end = () => {
10226 el.removeEventListener(endEvent, onEnd);
10227 resolveIfNotStale();
10228 };
10229 const onEnd = (e) => {
10230 if (e.target === el && ++ended >= propCount) {
10231 end();
10232 }
10233 };
10234 setTimeout(() => {
10235 if (ended < propCount) {
10236 end();
10237 }
10238 }, timeout + 1);
10239 el.addEventListener(endEvent, onEnd);
10240}
10241function getTransitionInfo(el, expectedType) {
10242 const styles = window.getComputedStyle(el);
10243 // JSDOM may return undefined for transition properties
10244 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10245 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10246 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10247 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10248 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10249 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10250 const animationTimeout = getTimeout(animationDelays, animationDurations);
10251 let type = null;
10252 let timeout = 0;
10253 let propCount = 0;
10254 /* istanbul ignore if */
10255 if (expectedType === TRANSITION) {
10256 if (transitionTimeout > 0) {
10257 type = TRANSITION;
10258 timeout = transitionTimeout;
10259 propCount = transitionDurations.length;
10260 }
10261 }
10262 else if (expectedType === ANIMATION) {
10263 if (animationTimeout > 0) {
10264 type = ANIMATION;
10265 timeout = animationTimeout;
10266 propCount = animationDurations.length;
10267 }
10268 }
10269 else {
10270 timeout = Math.max(transitionTimeout, animationTimeout);
10271 type =
10272 timeout > 0
10273 ? transitionTimeout > animationTimeout
10274 ? TRANSITION
10275 : ANIMATION
10276 : null;
10277 propCount = type
10278 ? type === TRANSITION
10279 ? transitionDurations.length
10280 : animationDurations.length
10281 : 0;
10282 }
10283 const hasTransform = type === TRANSITION &&
10284 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10285 return {
10286 type,
10287 timeout,
10288 propCount,
10289 hasTransform
10290 };
10291}
10292function getTimeout(delays, durations) {
10293 while (delays.length < durations.length) {
10294 delays = delays.concat(delays);
10295 }
10296 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10297}
10298// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10299// numbers in a locale-dependent way, using a comma instead of a dot.
10300// If comma is not replaced with a dot, the input will be rounded down
10301// (i.e. acting as a floor function) causing unexpected behaviors
10302function toMs(s) {
10303 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10304}
10305// synchronously force layout to put elements into a certain state
10306function forceReflow() {
10307 return document.body.offsetHeight;
10308}
10309
10310const positionMap = new WeakMap();
10311const newPositionMap = new WeakMap();
10312const TransitionGroupImpl = {
10313 name: 'TransitionGroup',
10314 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10315 tag: String,
10316 moveClass: String
10317 }),
10318 setup(props, { slots }) {
10319 const instance = getCurrentInstance();
10320 const state = useTransitionState();
10321 let prevChildren;
10322 let children;
10323 onUpdated(() => {
10324 // children is guaranteed to exist after initial render
10325 if (!prevChildren.length) {
10326 return;
10327 }
10328 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10329 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10330 return;
10331 }
10332 // we divide the work into three loops to avoid mixing DOM reads and writes
10333 // in each iteration - which helps prevent layout thrashing.
10334 prevChildren.forEach(callPendingCbs);
10335 prevChildren.forEach(recordPosition);
10336 const movedChildren = prevChildren.filter(applyTranslation);
10337 // force reflow to put everything in position
10338 forceReflow();
10339 movedChildren.forEach(c => {
10340 const el = c.el;
10341 const style = el.style;
10342 addTransitionClass(el, moveClass);
10343 style.transform = style.webkitTransform = style.transitionDuration = '';
10344 const cb = (el._moveCb = (e) => {
10345 if (e && e.target !== el) {
10346 return;
10347 }
10348 if (!e || /transform$/.test(e.propertyName)) {
10349 el.removeEventListener('transitionend', cb);
10350 el._moveCb = null;
10351 removeTransitionClass(el, moveClass);
10352 }
10353 });
10354 el.addEventListener('transitionend', cb);
10355 });
10356 });
10357 return () => {
10358 const rawProps = toRaw(props);
10359 const cssTransitionProps = resolveTransitionProps(rawProps);
10360 let tag = rawProps.tag || Fragment;
10361 prevChildren = children;
10362 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10363 for (let i = 0; i < children.length; i++) {
10364 const child = children[i];
10365 if (child.key != null) {
10366 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10367 }
10368 else {
10369 warn$1(`<TransitionGroup> children must be keyed.`);
10370 }
10371 }
10372 if (prevChildren) {
10373 for (let i = 0; i < prevChildren.length; i++) {
10374 const child = prevChildren[i];
10375 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10376 positionMap.set(child, child.el.getBoundingClientRect());
10377 }
10378 }
10379 return createVNode(tag, null, children);
10380 };
10381 }
10382};
10383const TransitionGroup = TransitionGroupImpl;
10384function callPendingCbs(c) {
10385 const el = c.el;
10386 if (el._moveCb) {
10387 el._moveCb();
10388 }
10389 if (el._enterCb) {
10390 el._enterCb();
10391 }
10392}
10393function recordPosition(c) {
10394 newPositionMap.set(c, c.el.getBoundingClientRect());
10395}
10396function applyTranslation(c) {
10397 const oldPos = positionMap.get(c);
10398 const newPos = newPositionMap.get(c);
10399 const dx = oldPos.left - newPos.left;
10400 const dy = oldPos.top - newPos.top;
10401 if (dx || dy) {
10402 const s = c.el.style;
10403 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10404 s.transitionDuration = '0s';
10405 return c;
10406 }
10407}
10408function hasCSSTransform(el, root, moveClass) {
10409 // Detect whether an element with the move class applied has
10410 // CSS transitions. Since the element may be inside an entering
10411 // transition at this very moment, we make a clone of it and remove
10412 // all other transition classes applied to ensure only the move class
10413 // is applied.
10414 const clone = el.cloneNode();
10415 if (el._vtc) {
10416 el._vtc.forEach(cls => {
10417 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10418 });
10419 }
10420 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10421 clone.style.display = 'none';
10422 const container = (root.nodeType === 1 ? root : root.parentNode);
10423 container.appendChild(clone);
10424 const { hasTransform } = getTransitionInfo(clone);
10425 container.removeChild(clone);
10426 return hasTransform;
10427}
10428
10429const getModelAssigner = (vnode) => {
10430 const fn = vnode.props['onUpdate:modelValue'];
10431 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10432};
10433function onCompositionStart(e) {
10434 e.target.composing = true;
10435}
10436function onCompositionEnd(e) {
10437 const target = e.target;
10438 if (target.composing) {
10439 target.composing = false;
10440 trigger$1(target, 'input');
10441 }
10442}
10443function trigger$1(el, type) {
10444 const e = document.createEvent('HTMLEvents');
10445 e.initEvent(type, true, true);
10446 el.dispatchEvent(e);
10447}
10448// We are exporting the v-model runtime directly as vnode hooks so that it can
10449// be tree-shaken in case v-model is never used.
10450const vModelText = {
10451 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10452 el._assign = getModelAssigner(vnode);
10453 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10454 addEventListener(el, lazy ? 'change' : 'input', e => {
10455 if (e.target.composing)
10456 return;
10457 let domValue = el.value;
10458 if (trim) {
10459 domValue = domValue.trim();
10460 }
10461 else if (castToNumber) {
10462 domValue = toNumber(domValue);
10463 }
10464 el._assign(domValue);
10465 });
10466 if (trim) {
10467 addEventListener(el, 'change', () => {
10468 el.value = el.value.trim();
10469 });
10470 }
10471 if (!lazy) {
10472 addEventListener(el, 'compositionstart', onCompositionStart);
10473 addEventListener(el, 'compositionend', onCompositionEnd);
10474 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10475 // switching focus before confirming composition choice
10476 // this also fixes the issue where some browsers e.g. iOS Chrome
10477 // fires "change" instead of "input" on autocomplete.
10478 addEventListener(el, 'change', onCompositionEnd);
10479 }
10480 },
10481 // set value on mounted so it's after min/max for type="range"
10482 mounted(el, { value }) {
10483 el.value = value == null ? '' : value;
10484 },
10485 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10486 el._assign = getModelAssigner(vnode);
10487 // avoid clearing unresolved text. #2302
10488 if (el.composing)
10489 return;
10490 if (document.activeElement === el) {
10491 if (lazy) {
10492 return;
10493 }
10494 if (trim && el.value.trim() === value) {
10495 return;
10496 }
10497 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10498 return;
10499 }
10500 }
10501 const newValue = value == null ? '' : value;
10502 if (el.value !== newValue) {
10503 el.value = newValue;
10504 }
10505 }
10506};
10507const vModelCheckbox = {
10508 // #4096 array checkboxes need to be deep traversed
10509 deep: true,
10510 created(el, _, vnode) {
10511 el._assign = getModelAssigner(vnode);
10512 addEventListener(el, 'change', () => {
10513 const modelValue = el._modelValue;
10514 const elementValue = getValue(el);
10515 const checked = el.checked;
10516 const assign = el._assign;
10517 if (isArray(modelValue)) {
10518 const index = looseIndexOf(modelValue, elementValue);
10519 const found = index !== -1;
10520 if (checked && !found) {
10521 assign(modelValue.concat(elementValue));
10522 }
10523 else if (!checked && found) {
10524 const filtered = [...modelValue];
10525 filtered.splice(index, 1);
10526 assign(filtered);
10527 }
10528 }
10529 else if (isSet(modelValue)) {
10530 const cloned = new Set(modelValue);
10531 if (checked) {
10532 cloned.add(elementValue);
10533 }
10534 else {
10535 cloned.delete(elementValue);
10536 }
10537 assign(cloned);
10538 }
10539 else {
10540 assign(getCheckboxValue(el, checked));
10541 }
10542 });
10543 },
10544 // set initial checked on mount to wait for true-value/false-value
10545 mounted: setChecked,
10546 beforeUpdate(el, binding, vnode) {
10547 el._assign = getModelAssigner(vnode);
10548 setChecked(el, binding, vnode);
10549 }
10550};
10551function setChecked(el, { value, oldValue }, vnode) {
10552 el._modelValue = value;
10553 if (isArray(value)) {
10554 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10555 }
10556 else if (isSet(value)) {
10557 el.checked = value.has(vnode.props.value);
10558 }
10559 else if (value !== oldValue) {
10560 el.checked = looseEqual(value, getCheckboxValue(el, true));
10561 }
10562}
10563const vModelRadio = {
10564 created(el, { value }, vnode) {
10565 el.checked = looseEqual(value, vnode.props.value);
10566 el._assign = getModelAssigner(vnode);
10567 addEventListener(el, 'change', () => {
10568 el._assign(getValue(el));
10569 });
10570 },
10571 beforeUpdate(el, { value, oldValue }, vnode) {
10572 el._assign = getModelAssigner(vnode);
10573 if (value !== oldValue) {
10574 el.checked = looseEqual(value, vnode.props.value);
10575 }
10576 }
10577};
10578const vModelSelect = {
10579 // <select multiple> value need to be deep traversed
10580 deep: true,
10581 created(el, { value, modifiers: { number } }, vnode) {
10582 const isSetModel = isSet(value);
10583 addEventListener(el, 'change', () => {
10584 const selectedVal = Array.prototype.filter
10585 .call(el.options, (o) => o.selected)
10586 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10587 el._assign(el.multiple
10588 ? isSetModel
10589 ? new Set(selectedVal)
10590 : selectedVal
10591 : selectedVal[0]);
10592 });
10593 el._assign = getModelAssigner(vnode);
10594 },
10595 // set value in mounted & updated because <select> relies on its children
10596 // <option>s.
10597 mounted(el, { value }) {
10598 setSelected(el, value);
10599 },
10600 beforeUpdate(el, _binding, vnode) {
10601 el._assign = getModelAssigner(vnode);
10602 },
10603 updated(el, { value }) {
10604 setSelected(el, value);
10605 }
10606};
10607function setSelected(el, value) {
10608 const isMultiple = el.multiple;
10609 if (isMultiple && !isArray(value) && !isSet(value)) {
10610 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10611 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10612 return;
10613 }
10614 for (let i = 0, l = el.options.length; i < l; i++) {
10615 const option = el.options[i];
10616 const optionValue = getValue(option);
10617 if (isMultiple) {
10618 if (isArray(value)) {
10619 option.selected = looseIndexOf(value, optionValue) > -1;
10620 }
10621 else {
10622 option.selected = value.has(optionValue);
10623 }
10624 }
10625 else {
10626 if (looseEqual(getValue(option), value)) {
10627 if (el.selectedIndex !== i)
10628 el.selectedIndex = i;
10629 return;
10630 }
10631 }
10632 }
10633 if (!isMultiple && el.selectedIndex !== -1) {
10634 el.selectedIndex = -1;
10635 }
10636}
10637// retrieve raw value set via :value bindings
10638function getValue(el) {
10639 return '_value' in el ? el._value : el.value;
10640}
10641// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10642function getCheckboxValue(el, checked) {
10643 const key = checked ? '_trueValue' : '_falseValue';
10644 return key in el ? el[key] : checked;
10645}
10646const vModelDynamic = {
10647 created(el, binding, vnode) {
10648 callModelHook(el, binding, vnode, null, 'created');
10649 },
10650 mounted(el, binding, vnode) {
10651 callModelHook(el, binding, vnode, null, 'mounted');
10652 },
10653 beforeUpdate(el, binding, vnode, prevVNode) {
10654 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10655 },
10656 updated(el, binding, vnode, prevVNode) {
10657 callModelHook(el, binding, vnode, prevVNode, 'updated');
10658 }
10659};
10660function callModelHook(el, binding, vnode, prevVNode, hook) {
10661 let modelToUse;
10662 switch (el.tagName) {
10663 case 'SELECT':
10664 modelToUse = vModelSelect;
10665 break;
10666 case 'TEXTAREA':
10667 modelToUse = vModelText;
10668 break;
10669 default:
10670 switch (vnode.props && vnode.props.type) {
10671 case 'checkbox':
10672 modelToUse = vModelCheckbox;
10673 break;
10674 case 'radio':
10675 modelToUse = vModelRadio;
10676 break;
10677 default:
10678 modelToUse = vModelText;
10679 }
10680 }
10681 const fn = modelToUse[hook];
10682 fn && fn(el, binding, vnode, prevVNode);
10683}
10684
10685const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10686const modifierGuards = {
10687 stop: e => e.stopPropagation(),
10688 prevent: e => e.preventDefault(),
10689 self: e => e.target !== e.currentTarget,
10690 ctrl: e => !e.ctrlKey,
10691 shift: e => !e.shiftKey,
10692 alt: e => !e.altKey,
10693 meta: e => !e.metaKey,
10694 left: e => 'button' in e && e.button !== 0,
10695 middle: e => 'button' in e && e.button !== 1,
10696 right: e => 'button' in e && e.button !== 2,
10697 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10698};
10699/**
10700 * @private
10701 */
10702const withModifiers = (fn, modifiers) => {
10703 return (event, ...args) => {
10704 for (let i = 0; i < modifiers.length; i++) {
10705 const guard = modifierGuards[modifiers[i]];
10706 if (guard && guard(event, modifiers))
10707 return;
10708 }
10709 return fn(event, ...args);
10710 };
10711};
10712// Kept for 2.x compat.
10713// Note: IE11 compat for `spacebar` and `del` is removed for now.
10714const keyNames = {
10715 esc: 'escape',
10716 space: ' ',
10717 up: 'arrow-up',
10718 left: 'arrow-left',
10719 right: 'arrow-right',
10720 down: 'arrow-down',
10721 delete: 'backspace'
10722};
10723/**
10724 * @private
10725 */
10726const withKeys = (fn, modifiers) => {
10727 return (event) => {
10728 if (!('key' in event)) {
10729 return;
10730 }
10731 const eventKey = hyphenate(event.key);
10732 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10733 return fn(event);
10734 }
10735 };
10736};
10737
10738const vShow = {
10739 beforeMount(el, { value }, { transition }) {
10740 el._vod = el.style.display === 'none' ? '' : el.style.display;
10741 if (transition && value) {
10742 transition.beforeEnter(el);
10743 }
10744 else {
10745 setDisplay(el, value);
10746 }
10747 },
10748 mounted(el, { value }, { transition }) {
10749 if (transition && value) {
10750 transition.enter(el);
10751 }
10752 },
10753 updated(el, { value, oldValue }, { transition }) {
10754 if (!value === !oldValue)
10755 return;
10756 if (transition) {
10757 if (value) {
10758 transition.beforeEnter(el);
10759 setDisplay(el, true);
10760 transition.enter(el);
10761 }
10762 else {
10763 transition.leave(el, () => {
10764 setDisplay(el, false);
10765 });
10766 }
10767 }
10768 else {
10769 setDisplay(el, value);
10770 }
10771 },
10772 beforeUnmount(el, { value }) {
10773 setDisplay(el, value);
10774 }
10775};
10776function setDisplay(el, value) {
10777 el.style.display = value ? el._vod : 'none';
10778}
10779
10780const rendererOptions = extend({ patchProp }, nodeOps);
10781// lazy create the renderer - this makes core renderer logic tree-shakable
10782// in case the user only imports reactivity utilities from Vue.
10783let renderer;
10784let enabledHydration = false;
10785function ensureRenderer() {
10786 return (renderer ||
10787 (renderer = createRenderer(rendererOptions)));
10788}
10789function ensureHydrationRenderer() {
10790 renderer = enabledHydration
10791 ? renderer
10792 : createHydrationRenderer(rendererOptions);
10793 enabledHydration = true;
10794 return renderer;
10795}
10796// use explicit type casts here to avoid import() calls in rolled-up d.ts
10797const render = ((...args) => {
10798 ensureRenderer().render(...args);
10799});
10800const hydrate = ((...args) => {
10801 ensureHydrationRenderer().hydrate(...args);
10802});
10803const createApp = ((...args) => {
10804 const app = ensureRenderer().createApp(...args);
10805 {
10806 injectNativeTagCheck(app);
10807 injectCompilerOptionsCheck(app);
10808 }
10809 const { mount } = app;
10810 app.mount = (containerOrSelector) => {
10811 const container = normalizeContainer(containerOrSelector);
10812 if (!container)
10813 return;
10814 const component = app._component;
10815 if (!isFunction(component) && !component.render && !component.template) {
10816 // __UNSAFE__
10817 // Reason: potential execution of JS expressions in in-DOM template.
10818 // The user must make sure the in-DOM template is trusted. If it's
10819 // rendered by the server, the template should not contain any user data.
10820 component.template = container.innerHTML;
10821 }
10822 // clear content before mounting
10823 container.innerHTML = '';
10824 const proxy = mount(container, false, container instanceof SVGElement);
10825 if (container instanceof Element) {
10826 container.removeAttribute('v-cloak');
10827 container.setAttribute('data-v-app', '');
10828 }
10829 return proxy;
10830 };
10831 return app;
10832});
10833const createSSRApp = ((...args) => {
10834 const app = ensureHydrationRenderer().createApp(...args);
10835 {
10836 injectNativeTagCheck(app);
10837 injectCompilerOptionsCheck(app);
10838 }
10839 const { mount } = app;
10840 app.mount = (containerOrSelector) => {
10841 const container = normalizeContainer(containerOrSelector);
10842 if (container) {
10843 return mount(container, true, container instanceof SVGElement);
10844 }
10845 };
10846 return app;
10847});
10848function injectNativeTagCheck(app) {
10849 // Inject `isNativeTag`
10850 // this is used for component name validation (dev only)
10851 Object.defineProperty(app.config, 'isNativeTag', {
10852 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10853 writable: false
10854 });
10855}
10856// dev only
10857function injectCompilerOptionsCheck(app) {
10858 if (isRuntimeOnly()) {
10859 const isCustomElement = app.config.isCustomElement;
10860 Object.defineProperty(app.config, 'isCustomElement', {
10861 get() {
10862 return isCustomElement;
10863 },
10864 set() {
10865 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10866 `\`compilerOptions.isCustomElement\` instead.`);
10867 }
10868 });
10869 const compilerOptions = app.config.compilerOptions;
10870 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10871 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10872 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10873 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10874 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10875 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10876 `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
10877 Object.defineProperty(app.config, 'compilerOptions', {
10878 get() {
10879 warn$1(msg);
10880 return compilerOptions;
10881 },
10882 set() {
10883 warn$1(msg);
10884 }
10885 });
10886 }
10887}
10888function normalizeContainer(container) {
10889 if (isString(container)) {
10890 const res = document.querySelector(container);
10891 if (!res) {
10892 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10893 }
10894 return res;
10895 }
10896 if (window.ShadowRoot &&
10897 container instanceof window.ShadowRoot &&
10898 container.mode === 'closed') {
10899 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10900 }
10901 return container;
10902}
10903
10904var runtimeDom = /*#__PURE__*/Object.freeze({
10905 __proto__: null,
10906 render: render,
10907 hydrate: hydrate,
10908 createApp: createApp,
10909 createSSRApp: createSSRApp,
10910 defineCustomElement: defineCustomElement,
10911 defineSSRCustomElement: defineSSRCustomElement,
10912 VueElement: VueElement,
10913 useCssModule: useCssModule,
10914 useCssVars: useCssVars,
10915 Transition: Transition,
10916 TransitionGroup: TransitionGroup,
10917 vModelText: vModelText,
10918 vModelCheckbox: vModelCheckbox,
10919 vModelRadio: vModelRadio,
10920 vModelSelect: vModelSelect,
10921 vModelDynamic: vModelDynamic,
10922 withModifiers: withModifiers,
10923 withKeys: withKeys,
10924 vShow: vShow,
10925 computed: computed,
10926 reactive: reactive,
10927 ref: ref,
10928 readonly: readonly,
10929 unref: unref,
10930 proxyRefs: proxyRefs,
10931 isRef: isRef,
10932 toRef: toRef,
10933 toRefs: toRefs,
10934 isProxy: isProxy,
10935 isReactive: isReactive,
10936 isReadonly: isReadonly,
10937 customRef: customRef,
10938 triggerRef: triggerRef,
10939 shallowRef: shallowRef,
10940 shallowReactive: shallowReactive,
10941 shallowReadonly: shallowReadonly,
10942 markRaw: markRaw,
10943 toRaw: toRaw,
10944 effect: effect,
10945 stop: stop,
10946 ReactiveEffect: ReactiveEffect,
10947 effectScope: effectScope,
10948 EffectScope: EffectScope,
10949 getCurrentScope: getCurrentScope,
10950 onScopeDispose: onScopeDispose,
10951 watch: watch,
10952 watchEffect: watchEffect,
10953 watchPostEffect: watchPostEffect,
10954 watchSyncEffect: watchSyncEffect,
10955 onBeforeMount: onBeforeMount,
10956 onMounted: onMounted,
10957 onBeforeUpdate: onBeforeUpdate,
10958 onUpdated: onUpdated,
10959 onBeforeUnmount: onBeforeUnmount,
10960 onUnmounted: onUnmounted,
10961 onActivated: onActivated,
10962 onDeactivated: onDeactivated,
10963 onRenderTracked: onRenderTracked,
10964 onRenderTriggered: onRenderTriggered,
10965 onErrorCaptured: onErrorCaptured,
10966 onServerPrefetch: onServerPrefetch,
10967 provide: provide,
10968 inject: inject,
10969 nextTick: nextTick,
10970 defineComponent: defineComponent,
10971 defineAsyncComponent: defineAsyncComponent,
10972 useAttrs: useAttrs,
10973 useSlots: useSlots,
10974 defineProps: defineProps,
10975 defineEmits: defineEmits,
10976 defineExpose: defineExpose,
10977 withDefaults: withDefaults,
10978 mergeDefaults: mergeDefaults,
10979 withAsyncContext: withAsyncContext,
10980 getCurrentInstance: getCurrentInstance,
10981 h: h,
10982 createVNode: createVNode,
10983 cloneVNode: cloneVNode,
10984 mergeProps: mergeProps,
10985 isVNode: isVNode,
10986 Fragment: Fragment,
10987 Text: Text,
10988 Comment: Comment,
10989 Static: Static,
10990 Teleport: Teleport,
10991 Suspense: Suspense,
10992 KeepAlive: KeepAlive,
10993 BaseTransition: BaseTransition,
10994 withDirectives: withDirectives,
10995 useSSRContext: useSSRContext,
10996 ssrContextKey: ssrContextKey,
10997 createRenderer: createRenderer,
10998 createHydrationRenderer: createHydrationRenderer,
10999 queuePostFlushCb: queuePostFlushCb,
11000 warn: warn$1,
11001 handleError: handleError,
11002 callWithErrorHandling: callWithErrorHandling,
11003 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
11004 resolveComponent: resolveComponent,
11005 resolveDirective: resolveDirective,
11006 resolveDynamicComponent: resolveDynamicComponent,
11007 registerRuntimeCompiler: registerRuntimeCompiler,
11008 isRuntimeOnly: isRuntimeOnly,
11009 useTransitionState: useTransitionState,
11010 resolveTransitionHooks: resolveTransitionHooks,
11011 setTransitionHooks: setTransitionHooks,
11012 getTransitionRawChildren: getTransitionRawChildren,
11013 initCustomFormatter: initCustomFormatter,
11014 get devtools () { return devtools; },
11015 setDevtoolsHook: setDevtoolsHook,
11016 withCtx: withCtx,
11017 pushScopeId: pushScopeId,
11018 popScopeId: popScopeId,
11019 withScopeId: withScopeId,
11020 renderList: renderList,
11021 toHandlers: toHandlers,
11022 renderSlot: renderSlot,
11023 createSlots: createSlots,
11024 withMemo: withMemo,
11025 isMemoSame: isMemoSame,
11026 openBlock: openBlock,
11027 createBlock: createBlock,
11028 setBlockTracking: setBlockTracking,
11029 createTextVNode: createTextVNode,
11030 createCommentVNode: createCommentVNode,
11031 createStaticVNode: createStaticVNode,
11032 createElementVNode: createBaseVNode,
11033 createElementBlock: createElementBlock,
11034 guardReactiveProps: guardReactiveProps,
11035 toDisplayString: toDisplayString,
11036 camelize: camelize,
11037 capitalize: capitalize,
11038 toHandlerKey: toHandlerKey,
11039 normalizeProps: normalizeProps,
11040 normalizeClass: normalizeClass,
11041 normalizeStyle: normalizeStyle,
11042 transformVNodeArgs: transformVNodeArgs,
11043 version: version,
11044 ssrUtils: ssrUtils,
11045 resolveFilter: resolveFilter,
11046 compatUtils: compatUtils
11047});
11048
11049function initDev() {
11050 {
11051 {
11052 console.info(`You are running a development build of Vue.\n` +
11053 `Make sure to use the production build (*.prod.js) when deploying for production.`);
11054 }
11055 initCustomFormatter();
11056 }
11057}
11058
11059function defaultOnError(error) {
11060 throw error;
11061}
11062function defaultOnWarn(msg) {
11063 console.warn(`[Vue warn] ${msg.message}`);
11064}
11065function createCompilerError(code, loc, messages, additionalMessage) {
11066 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
11067 ;
11068 const error = new SyntaxError(String(msg));
11069 error.code = code;
11070 error.loc = loc;
11071 return error;
11072}
11073const errorMessages = {
11074 // parse errors
11075 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
11076 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
11077 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
11078 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
11079 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
11080 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
11081 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
11082 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
11083 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
11084 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
11085 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
11086 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
11087 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
11088 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
11089 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
11090 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
11091 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
11092 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
11093 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
11094 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
11095 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
11096 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
11097 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
11098 // Vue-specific parse errors
11099 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
11100 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
11101 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
11102 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
11103 'Note that dynamic directive argument cannot contain spaces.',
11104 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
11105 // transform errors
11106 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
11107 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
11108 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
11109 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
11110 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
11111 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
11112 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
11113 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
11114 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
11115 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
11116 `When there are multiple named slots, all slots should use <template> ` +
11117 `syntax to avoid scope ambiguity.`,
11118 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
11119 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
11120 `default slot. These children will be ignored.`,
11121 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
11122 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
11123 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
11124 [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.`,
11125 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
11126 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
11127 // generic errors
11128 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
11129 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
11130 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
11131 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
11132 // just to fullfill types
11133 [50 /* __EXTEND_POINT__ */]: ``
11134};
11135
11136const FRAGMENT = Symbol(`Fragment` );
11137const TELEPORT = Symbol(`Teleport` );
11138const SUSPENSE = Symbol(`Suspense` );
11139const KEEP_ALIVE = Symbol(`KeepAlive` );
11140const BASE_TRANSITION = Symbol(`BaseTransition` );
11141const OPEN_BLOCK = Symbol(`openBlock` );
11142const CREATE_BLOCK = Symbol(`createBlock` );
11143const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11144const CREATE_VNODE = Symbol(`createVNode` );
11145const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11146const CREATE_COMMENT = Symbol(`createCommentVNode` );
11147const CREATE_TEXT = Symbol(`createTextVNode` );
11148const CREATE_STATIC = Symbol(`createStaticVNode` );
11149const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11150const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11151const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11152const RESOLVE_FILTER = Symbol(`resolveFilter` );
11153const WITH_DIRECTIVES = Symbol(`withDirectives` );
11154const RENDER_LIST = Symbol(`renderList` );
11155const RENDER_SLOT = Symbol(`renderSlot` );
11156const CREATE_SLOTS = Symbol(`createSlots` );
11157const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11158const MERGE_PROPS = Symbol(`mergeProps` );
11159const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11160const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11161const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11162const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11163const TO_HANDLERS = Symbol(`toHandlers` );
11164const CAMELIZE = Symbol(`camelize` );
11165const CAPITALIZE = Symbol(`capitalize` );
11166const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11167const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11168const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11169const POP_SCOPE_ID = Symbol(`popScopeId` );
11170const WITH_CTX = Symbol(`withCtx` );
11171const UNREF = Symbol(`unref` );
11172const IS_REF = Symbol(`isRef` );
11173const WITH_MEMO = Symbol(`withMemo` );
11174const IS_MEMO_SAME = Symbol(`isMemoSame` );
11175// Name mapping for runtime helpers that need to be imported from 'vue' in
11176// generated code. Make sure these are correctly exported in the runtime!
11177// Using `any` here because TS doesn't allow symbols as index type.
11178const helperNameMap = {
11179 [FRAGMENT]: `Fragment`,
11180 [TELEPORT]: `Teleport`,
11181 [SUSPENSE]: `Suspense`,
11182 [KEEP_ALIVE]: `KeepAlive`,
11183 [BASE_TRANSITION]: `BaseTransition`,
11184 [OPEN_BLOCK]: `openBlock`,
11185 [CREATE_BLOCK]: `createBlock`,
11186 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11187 [CREATE_VNODE]: `createVNode`,
11188 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11189 [CREATE_COMMENT]: `createCommentVNode`,
11190 [CREATE_TEXT]: `createTextVNode`,
11191 [CREATE_STATIC]: `createStaticVNode`,
11192 [RESOLVE_COMPONENT]: `resolveComponent`,
11193 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11194 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11195 [RESOLVE_FILTER]: `resolveFilter`,
11196 [WITH_DIRECTIVES]: `withDirectives`,
11197 [RENDER_LIST]: `renderList`,
11198 [RENDER_SLOT]: `renderSlot`,
11199 [CREATE_SLOTS]: `createSlots`,
11200 [TO_DISPLAY_STRING]: `toDisplayString`,
11201 [MERGE_PROPS]: `mergeProps`,
11202 [NORMALIZE_CLASS]: `normalizeClass`,
11203 [NORMALIZE_STYLE]: `normalizeStyle`,
11204 [NORMALIZE_PROPS]: `normalizeProps`,
11205 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11206 [TO_HANDLERS]: `toHandlers`,
11207 [CAMELIZE]: `camelize`,
11208 [CAPITALIZE]: `capitalize`,
11209 [TO_HANDLER_KEY]: `toHandlerKey`,
11210 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11211 [PUSH_SCOPE_ID]: `pushScopeId`,
11212 [POP_SCOPE_ID]: `popScopeId`,
11213 [WITH_CTX]: `withCtx`,
11214 [UNREF]: `unref`,
11215 [IS_REF]: `isRef`,
11216 [WITH_MEMO]: `withMemo`,
11217 [IS_MEMO_SAME]: `isMemoSame`
11218};
11219function registerRuntimeHelpers(helpers) {
11220 Object.getOwnPropertySymbols(helpers).forEach(s => {
11221 helperNameMap[s] = helpers[s];
11222 });
11223}
11224
11225// AST Utilities ---------------------------------------------------------------
11226// Some expressions, e.g. sequence and conditional expressions, are never
11227// associated with template nodes, so their source locations are just a stub.
11228// Container types like CompoundExpression also don't need a real location.
11229const locStub = {
11230 source: '',
11231 start: { line: 1, column: 1, offset: 0 },
11232 end: { line: 1, column: 1, offset: 0 }
11233};
11234function createRoot(children, loc = locStub) {
11235 return {
11236 type: 0 /* ROOT */,
11237 children,
11238 helpers: [],
11239 components: [],
11240 directives: [],
11241 hoists: [],
11242 imports: [],
11243 cached: 0,
11244 temps: 0,
11245 codegenNode: undefined,
11246 loc
11247 };
11248}
11249function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11250 if (context) {
11251 if (isBlock) {
11252 context.helper(OPEN_BLOCK);
11253 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11254 }
11255 else {
11256 context.helper(getVNodeHelper(context.inSSR, isComponent));
11257 }
11258 if (directives) {
11259 context.helper(WITH_DIRECTIVES);
11260 }
11261 }
11262 return {
11263 type: 13 /* VNODE_CALL */,
11264 tag,
11265 props,
11266 children,
11267 patchFlag,
11268 dynamicProps,
11269 directives,
11270 isBlock,
11271 disableTracking,
11272 isComponent,
11273 loc
11274 };
11275}
11276function createArrayExpression(elements, loc = locStub) {
11277 return {
11278 type: 17 /* JS_ARRAY_EXPRESSION */,
11279 loc,
11280 elements
11281 };
11282}
11283function createObjectExpression(properties, loc = locStub) {
11284 return {
11285 type: 15 /* JS_OBJECT_EXPRESSION */,
11286 loc,
11287 properties
11288 };
11289}
11290function createObjectProperty(key, value) {
11291 return {
11292 type: 16 /* JS_PROPERTY */,
11293 loc: locStub,
11294 key: isString(key) ? createSimpleExpression(key, true) : key,
11295 value
11296 };
11297}
11298function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11299 return {
11300 type: 4 /* SIMPLE_EXPRESSION */,
11301 loc,
11302 content,
11303 isStatic,
11304 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11305 };
11306}
11307function createCompoundExpression(children, loc = locStub) {
11308 return {
11309 type: 8 /* COMPOUND_EXPRESSION */,
11310 loc,
11311 children
11312 };
11313}
11314function createCallExpression(callee, args = [], loc = locStub) {
11315 return {
11316 type: 14 /* JS_CALL_EXPRESSION */,
11317 loc,
11318 callee,
11319 arguments: args
11320 };
11321}
11322function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11323 return {
11324 type: 18 /* JS_FUNCTION_EXPRESSION */,
11325 params,
11326 returns,
11327 newline,
11328 isSlot,
11329 loc
11330 };
11331}
11332function createConditionalExpression(test, consequent, alternate, newline = true) {
11333 return {
11334 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11335 test,
11336 consequent,
11337 alternate,
11338 newline,
11339 loc: locStub
11340 };
11341}
11342function createCacheExpression(index, value, isVNode = false) {
11343 return {
11344 type: 20 /* JS_CACHE_EXPRESSION */,
11345 index,
11346 value,
11347 isVNode,
11348 loc: locStub
11349 };
11350}
11351function createBlockStatement(body) {
11352 return {
11353 type: 21 /* JS_BLOCK_STATEMENT */,
11354 body,
11355 loc: locStub
11356 };
11357}
11358
11359const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11360const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11361function isCoreComponent(tag) {
11362 if (isBuiltInType(tag, 'Teleport')) {
11363 return TELEPORT;
11364 }
11365 else if (isBuiltInType(tag, 'Suspense')) {
11366 return SUSPENSE;
11367 }
11368 else if (isBuiltInType(tag, 'KeepAlive')) {
11369 return KEEP_ALIVE;
11370 }
11371 else if (isBuiltInType(tag, 'BaseTransition')) {
11372 return BASE_TRANSITION;
11373 }
11374}
11375const nonIdentifierRE = /^\d|[^\$\w]/;
11376const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11377const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11378const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11379const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11380/**
11381 * Simple lexer to check if an expression is a member expression. This is
11382 * lax and only checks validity at the root level (i.e. does not validate exps
11383 * inside square brackets), but it's ok since these are only used on template
11384 * expressions and false positives are invalid expressions in the first place.
11385 */
11386const isMemberExpression = (path) => {
11387 // remove whitespaces around . or [ first
11388 path = path.trim().replace(whitespaceRE, s => s.trim());
11389 let state = 0 /* inMemberExp */;
11390 let stateStack = [];
11391 let currentOpenBracketCount = 0;
11392 let currentOpenParensCount = 0;
11393 let currentStringType = null;
11394 for (let i = 0; i < path.length; i++) {
11395 const char = path.charAt(i);
11396 switch (state) {
11397 case 0 /* inMemberExp */:
11398 if (char === '[') {
11399 stateStack.push(state);
11400 state = 1 /* inBrackets */;
11401 currentOpenBracketCount++;
11402 }
11403 else if (char === '(') {
11404 stateStack.push(state);
11405 state = 2 /* inParens */;
11406 currentOpenParensCount++;
11407 }
11408 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11409 return false;
11410 }
11411 break;
11412 case 1 /* inBrackets */:
11413 if (char === `'` || char === `"` || char === '`') {
11414 stateStack.push(state);
11415 state = 3 /* inString */;
11416 currentStringType = char;
11417 }
11418 else if (char === `[`) {
11419 currentOpenBracketCount++;
11420 }
11421 else if (char === `]`) {
11422 if (!--currentOpenBracketCount) {
11423 state = stateStack.pop();
11424 }
11425 }
11426 break;
11427 case 2 /* inParens */:
11428 if (char === `'` || char === `"` || char === '`') {
11429 stateStack.push(state);
11430 state = 3 /* inString */;
11431 currentStringType = char;
11432 }
11433 else if (char === `(`) {
11434 currentOpenParensCount++;
11435 }
11436 else if (char === `)`) {
11437 // if the exp ends as a call then it should not be considered valid
11438 if (i === path.length - 1) {
11439 return false;
11440 }
11441 if (!--currentOpenParensCount) {
11442 state = stateStack.pop();
11443 }
11444 }
11445 break;
11446 case 3 /* inString */:
11447 if (char === currentStringType) {
11448 state = stateStack.pop();
11449 currentStringType = null;
11450 }
11451 break;
11452 }
11453 }
11454 return !currentOpenBracketCount && !currentOpenParensCount;
11455};
11456function getInnerRange(loc, offset, length) {
11457 const source = loc.source.substr(offset, length);
11458 const newLoc = {
11459 source,
11460 start: advancePositionWithClone(loc.start, loc.source, offset),
11461 end: loc.end
11462 };
11463 if (length != null) {
11464 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11465 }
11466 return newLoc;
11467}
11468function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11469 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11470}
11471// advance by mutation without cloning (for performance reasons), since this
11472// gets called a lot in the parser
11473function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11474 let linesCount = 0;
11475 let lastNewLinePos = -1;
11476 for (let i = 0; i < numberOfCharacters; i++) {
11477 if (source.charCodeAt(i) === 10 /* newline char code */) {
11478 linesCount++;
11479 lastNewLinePos = i;
11480 }
11481 }
11482 pos.offset += numberOfCharacters;
11483 pos.line += linesCount;
11484 pos.column =
11485 lastNewLinePos === -1
11486 ? pos.column + numberOfCharacters
11487 : numberOfCharacters - lastNewLinePos;
11488 return pos;
11489}
11490function assert(condition, msg) {
11491 /* istanbul ignore if */
11492 if (!condition) {
11493 throw new Error(msg || `unexpected compiler condition`);
11494 }
11495}
11496function findDir(node, name, allowEmpty = false) {
11497 for (let i = 0; i < node.props.length; i++) {
11498 const p = node.props[i];
11499 if (p.type === 7 /* DIRECTIVE */ &&
11500 (allowEmpty || p.exp) &&
11501 (isString(name) ? p.name === name : name.test(p.name))) {
11502 return p;
11503 }
11504 }
11505}
11506function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11507 for (let i = 0; i < node.props.length; i++) {
11508 const p = node.props[i];
11509 if (p.type === 6 /* ATTRIBUTE */) {
11510 if (dynamicOnly)
11511 continue;
11512 if (p.name === name && (p.value || allowEmpty)) {
11513 return p;
11514 }
11515 }
11516 else if (p.name === 'bind' &&
11517 (p.exp || allowEmpty) &&
11518 isBindKey(p.arg, name)) {
11519 return p;
11520 }
11521 }
11522}
11523function isBindKey(arg, name) {
11524 return !!(arg && isStaticExp(arg) && arg.content === name);
11525}
11526function hasDynamicKeyVBind(node) {
11527 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11528 p.name === 'bind' &&
11529 (!p.arg || // v-bind="obj"
11530 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11531 !p.arg.isStatic) // v-bind:[foo]
11532 );
11533}
11534function isText(node) {
11535 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11536}
11537function isVSlot(p) {
11538 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11539}
11540function isTemplateNode(node) {
11541 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11542}
11543function isSlotOutlet(node) {
11544 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11545}
11546function getVNodeHelper(ssr, isComponent) {
11547 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11548}
11549function getVNodeBlockHelper(ssr, isComponent) {
11550 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11551}
11552const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11553function getUnnormalizedProps(props, callPath = []) {
11554 if (props &&
11555 !isString(props) &&
11556 props.type === 14 /* JS_CALL_EXPRESSION */) {
11557 const callee = props.callee;
11558 if (!isString(callee) && propsHelperSet.has(callee)) {
11559 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11560 }
11561 }
11562 return [props, callPath];
11563}
11564function injectProp(node, prop, context) {
11565 let propsWithInjection;
11566 const originalProps = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11567 /**
11568 * 1. mergeProps(...)
11569 * 2. toHandlers(...)
11570 * 3. normalizeProps(...)
11571 * 4. normalizeProps(guardReactiveProps(...))
11572 *
11573 * we need to get the real props before normalization
11574 */
11575 let props = originalProps;
11576 let callPath = [];
11577 let parentCall;
11578 if (props &&
11579 !isString(props) &&
11580 props.type === 14 /* JS_CALL_EXPRESSION */) {
11581 const ret = getUnnormalizedProps(props);
11582 props = ret[0];
11583 callPath = ret[1];
11584 parentCall = callPath[callPath.length - 1];
11585 }
11586 if (props == null || isString(props)) {
11587 propsWithInjection = createObjectExpression([prop]);
11588 }
11589 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11590 // merged props... add ours
11591 // only inject key to object literal if it's the first argument so that
11592 // if doesn't override user provided keys
11593 const first = props.arguments[0];
11594 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11595 first.properties.unshift(prop);
11596 }
11597 else {
11598 if (props.callee === TO_HANDLERS) {
11599 // #2366
11600 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11601 createObjectExpression([prop]),
11602 props
11603 ]);
11604 }
11605 else {
11606 props.arguments.unshift(createObjectExpression([prop]));
11607 }
11608 }
11609 !propsWithInjection && (propsWithInjection = props);
11610 }
11611 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11612 let alreadyExists = false;
11613 // check existing key to avoid overriding user provided keys
11614 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11615 const propKeyName = prop.key.content;
11616 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11617 p.key.content === propKeyName);
11618 }
11619 if (!alreadyExists) {
11620 props.properties.unshift(prop);
11621 }
11622 propsWithInjection = props;
11623 }
11624 else {
11625 // single v-bind with expression, return a merged replacement
11626 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11627 createObjectExpression([prop]),
11628 props
11629 ]);
11630 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11631 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11632 // the `guardReactiveProps` will no longer be needed
11633 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11634 parentCall = callPath[callPath.length - 2];
11635 }
11636 }
11637 if (node.type === 13 /* VNODE_CALL */) {
11638 if (parentCall) {
11639 parentCall.arguments[0] = propsWithInjection;
11640 }
11641 else {
11642 node.props = propsWithInjection;
11643 }
11644 }
11645 else {
11646 if (parentCall) {
11647 parentCall.arguments[0] = propsWithInjection;
11648 }
11649 else {
11650 node.arguments[2] = propsWithInjection;
11651 }
11652 }
11653}
11654function toValidAssetId(name, type) {
11655 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11656 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11657 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11658 })}`;
11659}
11660function getMemoedVNodeCall(node) {
11661 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11662 return node.arguments[1].returns;
11663 }
11664 else {
11665 return node;
11666 }
11667}
11668function makeBlock(node, { helper, removeHelper, inSSR }) {
11669 if (!node.isBlock) {
11670 node.isBlock = true;
11671 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11672 helper(OPEN_BLOCK);
11673 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11674 }
11675}
11676
11677const deprecationData$1 = {
11678 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11679 message: `Platform-native elements with "is" prop will no longer be ` +
11680 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11681 `prefixed with "vue:".`,
11682 link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
11683 },
11684 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11685 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11686 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11687 `\`v-model:${key}\`.`,
11688 link: `https://v3.vuejs.org/guide/migration/v-model.html`
11689 },
11690 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11691 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11692 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11693 },
11694 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11695 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11696 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11697 `that appears before v-bind in the case of conflict. ` +
11698 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11699 `You can also suppress this warning if the usage is intended.`,
11700 link: `https://v3.vuejs.org/guide/migration/v-bind.html`
11701 },
11702 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11703 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11704 link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
11705 },
11706 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11707 message: `v-if / v-for precedence when used on the same element has changed ` +
11708 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11709 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11710 `with <template> tags or use a computed property that filters v-for ` +
11711 `data source.`,
11712 link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
11713 },
11714 ["COMPILER_V_FOR_REF" /* COMPILER_V_FOR_REF */]: {
11715 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
11716 `Consider using function refs or refactor to avoid ref usage altogether.`,
11717 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
11718 },
11719 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11720 message: `<template> with no special directives will render as a native template ` +
11721 `element instead of its inner content in Vue 3.`
11722 },
11723 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11724 message: `"inline-template" has been removed in Vue 3.`,
11725 link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
11726 },
11727 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11728 message: `filters have been removed in Vue 3. ` +
11729 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11730 `Use method calls or computed properties instead.`,
11731 link: `https://v3.vuejs.org/guide/migration/filters.html`
11732 }
11733};
11734function getCompatValue(key, context) {
11735 const config = context.options
11736 ? context.options.compatConfig
11737 : context.compatConfig;
11738 const value = config && config[key];
11739 if (key === 'MODE') {
11740 return value || 3; // compiler defaults to v3 behavior
11741 }
11742 else {
11743 return value;
11744 }
11745}
11746function isCompatEnabled$1(key, context) {
11747 const mode = getCompatValue('MODE', context);
11748 const value = getCompatValue(key, context);
11749 // in v3 mode, only enable if explicitly set to true
11750 // otherwise enable for any non-false value
11751 return mode === 3 ? value === true : value !== false;
11752}
11753function checkCompatEnabled(key, context, loc, ...args) {
11754 const enabled = isCompatEnabled$1(key, context);
11755 if (enabled) {
11756 warnDeprecation$1(key, context, loc, ...args);
11757 }
11758 return enabled;
11759}
11760function warnDeprecation$1(key, context, loc, ...args) {
11761 const val = getCompatValue(key, context);
11762 if (val === 'suppress-warning') {
11763 return;
11764 }
11765 const { message, link } = deprecationData$1[key];
11766 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11767 const err = new SyntaxError(msg);
11768 err.code = key;
11769 if (loc)
11770 err.loc = loc;
11771 context.onWarn(err);
11772}
11773
11774// The default decoder only provides escapes for characters reserved as part of
11775// the template syntax, and is only used if the custom renderer did not provide
11776// a platform-specific decoder.
11777const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11778const decodeMap = {
11779 gt: '>',
11780 lt: '<',
11781 amp: '&',
11782 apos: "'",
11783 quot: '"'
11784};
11785const defaultParserOptions = {
11786 delimiters: [`{{`, `}}`],
11787 getNamespace: () => 0 /* HTML */,
11788 getTextMode: () => 0 /* DATA */,
11789 isVoidTag: NO,
11790 isPreTag: NO,
11791 isCustomElement: NO,
11792 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11793 onError: defaultOnError,
11794 onWarn: defaultOnWarn,
11795 comments: true
11796};
11797function baseParse(content, options = {}) {
11798 const context = createParserContext(content, options);
11799 const start = getCursor(context);
11800 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11801}
11802function createParserContext(content, rawOptions) {
11803 const options = extend({}, defaultParserOptions);
11804 let key;
11805 for (key in rawOptions) {
11806 // @ts-ignore
11807 options[key] =
11808 rawOptions[key] === undefined
11809 ? defaultParserOptions[key]
11810 : rawOptions[key];
11811 }
11812 return {
11813 options,
11814 column: 1,
11815 line: 1,
11816 offset: 0,
11817 originalSource: content,
11818 source: content,
11819 inPre: false,
11820 inVPre: false,
11821 onWarn: options.onWarn
11822 };
11823}
11824function parseChildren(context, mode, ancestors) {
11825 const parent = last(ancestors);
11826 const ns = parent ? parent.ns : 0 /* HTML */;
11827 const nodes = [];
11828 while (!isEnd(context, mode, ancestors)) {
11829 const s = context.source;
11830 let node = undefined;
11831 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11832 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11833 // '{{'
11834 node = parseInterpolation(context, mode);
11835 }
11836 else if (mode === 0 /* DATA */ && s[0] === '<') {
11837 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11838 if (s.length === 1) {
11839 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11840 }
11841 else if (s[1] === '!') {
11842 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11843 if (startsWith(s, '<!--')) {
11844 node = parseComment(context);
11845 }
11846 else if (startsWith(s, '<!DOCTYPE')) {
11847 // Ignore DOCTYPE by a limitation.
11848 node = parseBogusComment(context);
11849 }
11850 else if (startsWith(s, '<![CDATA[')) {
11851 if (ns !== 0 /* HTML */) {
11852 node = parseCDATA(context, ancestors);
11853 }
11854 else {
11855 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11856 node = parseBogusComment(context);
11857 }
11858 }
11859 else {
11860 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11861 node = parseBogusComment(context);
11862 }
11863 }
11864 else if (s[1] === '/') {
11865 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11866 if (s.length === 2) {
11867 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11868 }
11869 else if (s[2] === '>') {
11870 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11871 advanceBy(context, 3);
11872 continue;
11873 }
11874 else if (/[a-z]/i.test(s[2])) {
11875 emitError(context, 23 /* X_INVALID_END_TAG */);
11876 parseTag(context, 1 /* End */, parent);
11877 continue;
11878 }
11879 else {
11880 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11881 node = parseBogusComment(context);
11882 }
11883 }
11884 else if (/[a-z]/i.test(s[1])) {
11885 node = parseElement(context, ancestors);
11886 }
11887 else if (s[1] === '?') {
11888 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11889 node = parseBogusComment(context);
11890 }
11891 else {
11892 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11893 }
11894 }
11895 }
11896 if (!node) {
11897 node = parseText(context, mode);
11898 }
11899 if (isArray(node)) {
11900 for (let i = 0; i < node.length; i++) {
11901 pushNode(nodes, node[i]);
11902 }
11903 }
11904 else {
11905 pushNode(nodes, node);
11906 }
11907 }
11908 // Whitespace handling strategy like v2
11909 let removedWhitespace = false;
11910 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11911 const shouldCondense = context.options.whitespace !== 'preserve';
11912 for (let i = 0; i < nodes.length; i++) {
11913 const node = nodes[i];
11914 if (!context.inPre && node.type === 2 /* TEXT */) {
11915 if (!/[^\t\r\n\f ]/.test(node.content)) {
11916 const prev = nodes[i - 1];
11917 const next = nodes[i + 1];
11918 // Remove if:
11919 // - the whitespace is the first or last node, or:
11920 // - (condense mode) the whitespace is adjacent to a comment, or:
11921 // - (condense mode) the whitespace is between two elements AND contains newline
11922 if (!prev ||
11923 !next ||
11924 (shouldCondense &&
11925 (prev.type === 3 /* COMMENT */ ||
11926 next.type === 3 /* COMMENT */ ||
11927 (prev.type === 1 /* ELEMENT */ &&
11928 next.type === 1 /* ELEMENT */ &&
11929 /[\r\n]/.test(node.content))))) {
11930 removedWhitespace = true;
11931 nodes[i] = null;
11932 }
11933 else {
11934 // Otherwise, the whitespace is condensed into a single space
11935 node.content = ' ';
11936 }
11937 }
11938 else if (shouldCondense) {
11939 // in condense mode, consecutive whitespaces in text are condensed
11940 // down to a single space.
11941 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11942 }
11943 }
11944 // Remove comment nodes if desired by configuration.
11945 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11946 removedWhitespace = true;
11947 nodes[i] = null;
11948 }
11949 }
11950 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11951 // remove leading newline per html spec
11952 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11953 const first = nodes[0];
11954 if (first && first.type === 2 /* TEXT */) {
11955 first.content = first.content.replace(/^\r?\n/, '');
11956 }
11957 }
11958 }
11959 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11960}
11961function pushNode(nodes, node) {
11962 if (node.type === 2 /* TEXT */) {
11963 const prev = last(nodes);
11964 // Merge if both this and the previous node are text and those are
11965 // consecutive. This happens for cases like "a < b".
11966 if (prev &&
11967 prev.type === 2 /* TEXT */ &&
11968 prev.loc.end.offset === node.loc.start.offset) {
11969 prev.content += node.content;
11970 prev.loc.end = node.loc.end;
11971 prev.loc.source += node.loc.source;
11972 return;
11973 }
11974 }
11975 nodes.push(node);
11976}
11977function parseCDATA(context, ancestors) {
11978 advanceBy(context, 9);
11979 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11980 if (context.source.length === 0) {
11981 emitError(context, 6 /* EOF_IN_CDATA */);
11982 }
11983 else {
11984 advanceBy(context, 3);
11985 }
11986 return nodes;
11987}
11988function parseComment(context) {
11989 const start = getCursor(context);
11990 let content;
11991 // Regular comment.
11992 const match = /--(\!)?>/.exec(context.source);
11993 if (!match) {
11994 content = context.source.slice(4);
11995 advanceBy(context, context.source.length);
11996 emitError(context, 7 /* EOF_IN_COMMENT */);
11997 }
11998 else {
11999 if (match.index <= 3) {
12000 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
12001 }
12002 if (match[1]) {
12003 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
12004 }
12005 content = context.source.slice(4, match.index);
12006 // Advancing with reporting nested comments.
12007 const s = context.source.slice(0, match.index);
12008 let prevIndex = 1, nestedIndex = 0;
12009 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
12010 advanceBy(context, nestedIndex - prevIndex + 1);
12011 if (nestedIndex + 4 < s.length) {
12012 emitError(context, 16 /* NESTED_COMMENT */);
12013 }
12014 prevIndex = nestedIndex + 1;
12015 }
12016 advanceBy(context, match.index + match[0].length - prevIndex + 1);
12017 }
12018 return {
12019 type: 3 /* COMMENT */,
12020 content,
12021 loc: getSelection(context, start)
12022 };
12023}
12024function parseBogusComment(context) {
12025 const start = getCursor(context);
12026 const contentStart = context.source[1] === '?' ? 1 : 2;
12027 let content;
12028 const closeIndex = context.source.indexOf('>');
12029 if (closeIndex === -1) {
12030 content = context.source.slice(contentStart);
12031 advanceBy(context, context.source.length);
12032 }
12033 else {
12034 content = context.source.slice(contentStart, closeIndex);
12035 advanceBy(context, closeIndex + 1);
12036 }
12037 return {
12038 type: 3 /* COMMENT */,
12039 content,
12040 loc: getSelection(context, start)
12041 };
12042}
12043function parseElement(context, ancestors) {
12044 // Start tag.
12045 const wasInPre = context.inPre;
12046 const wasInVPre = context.inVPre;
12047 const parent = last(ancestors);
12048 const element = parseTag(context, 0 /* Start */, parent);
12049 const isPreBoundary = context.inPre && !wasInPre;
12050 const isVPreBoundary = context.inVPre && !wasInVPre;
12051 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
12052 // #4030 self-closing <pre> tag
12053 if (isPreBoundary) {
12054 context.inPre = false;
12055 }
12056 if (isVPreBoundary) {
12057 context.inVPre = false;
12058 }
12059 return element;
12060 }
12061 // Children.
12062 ancestors.push(element);
12063 const mode = context.options.getTextMode(element, parent);
12064 const children = parseChildren(context, mode, ancestors);
12065 ancestors.pop();
12066 element.children = children;
12067 // End tag.
12068 if (startsWithEndTagOpen(context.source, element.tag)) {
12069 parseTag(context, 1 /* End */, parent);
12070 }
12071 else {
12072 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
12073 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
12074 const first = children[0];
12075 if (first && startsWith(first.loc.source, '<!--')) {
12076 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
12077 }
12078 }
12079 }
12080 element.loc = getSelection(context, element.loc.start);
12081 if (isPreBoundary) {
12082 context.inPre = false;
12083 }
12084 if (isVPreBoundary) {
12085 context.inVPre = false;
12086 }
12087 return element;
12088}
12089const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
12090function parseTag(context, type, parent) {
12091 // Tag open.
12092 const start = getCursor(context);
12093 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
12094 const tag = match[1];
12095 const ns = context.options.getNamespace(tag, parent);
12096 advanceBy(context, match[0].length);
12097 advanceSpaces(context);
12098 // save current state in case we need to re-parse attributes with v-pre
12099 const cursor = getCursor(context);
12100 const currentSource = context.source;
12101 // check <pre> tag
12102 if (context.options.isPreTag(tag)) {
12103 context.inPre = true;
12104 }
12105 // Attributes.
12106 let props = parseAttributes(context, type);
12107 // check v-pre
12108 if (type === 0 /* Start */ &&
12109 !context.inVPre &&
12110 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
12111 context.inVPre = true;
12112 // reset context
12113 extend(context, cursor);
12114 context.source = currentSource;
12115 // re-parse attrs and filter out v-pre itself
12116 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
12117 }
12118 // Tag close.
12119 let isSelfClosing = false;
12120 if (context.source.length === 0) {
12121 emitError(context, 9 /* EOF_IN_TAG */);
12122 }
12123 else {
12124 isSelfClosing = startsWith(context.source, '/>');
12125 if (type === 1 /* End */ && isSelfClosing) {
12126 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
12127 }
12128 advanceBy(context, isSelfClosing ? 2 : 1);
12129 }
12130 if (type === 1 /* End */) {
12131 return;
12132 }
12133 let tagType = 0 /* ELEMENT */;
12134 if (!context.inVPre) {
12135 if (tag === 'slot') {
12136 tagType = 2 /* SLOT */;
12137 }
12138 else if (tag === 'template') {
12139 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
12140 tagType = 3 /* TEMPLATE */;
12141 }
12142 }
12143 else if (isComponent(tag, props, context)) {
12144 tagType = 1 /* COMPONENT */;
12145 }
12146 }
12147 return {
12148 type: 1 /* ELEMENT */,
12149 ns,
12150 tag,
12151 tagType,
12152 props,
12153 isSelfClosing,
12154 children: [],
12155 loc: getSelection(context, start),
12156 codegenNode: undefined // to be created during transform phase
12157 };
12158}
12159function isComponent(tag, props, context) {
12160 const options = context.options;
12161 if (options.isCustomElement(tag)) {
12162 return false;
12163 }
12164 if (tag === 'component' ||
12165 /^[A-Z]/.test(tag) ||
12166 isCoreComponent(tag) ||
12167 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12168 (options.isNativeTag && !options.isNativeTag(tag))) {
12169 return true;
12170 }
12171 // at this point the tag should be a native tag, but check for potential "is"
12172 // casting
12173 for (let i = 0; i < props.length; i++) {
12174 const p = props[i];
12175 if (p.type === 6 /* ATTRIBUTE */) {
12176 if (p.name === 'is' && p.value) {
12177 if (p.value.content.startsWith('vue:')) {
12178 return true;
12179 }
12180 }
12181 }
12182 else {
12183 // directive
12184 // v-is (TODO Deprecate)
12185 if (p.name === 'is') {
12186 return true;
12187 }
12188 else if (
12189 // :is on plain element - only treat as component in compat mode
12190 p.name === 'bind' &&
12191 isBindKey(p.arg, 'is') &&
12192 false &&
12193 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12194 return true;
12195 }
12196 }
12197 }
12198}
12199function parseAttributes(context, type) {
12200 const props = [];
12201 const attributeNames = new Set();
12202 while (context.source.length > 0 &&
12203 !startsWith(context.source, '>') &&
12204 !startsWith(context.source, '/>')) {
12205 if (startsWith(context.source, '/')) {
12206 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12207 advanceBy(context, 1);
12208 advanceSpaces(context);
12209 continue;
12210 }
12211 if (type === 1 /* End */) {
12212 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12213 }
12214 const attr = parseAttribute(context, attributeNames);
12215 // Trim whitespace between class
12216 // https://github.com/vuejs/vue-next/issues/4251
12217 if (attr.type === 6 /* ATTRIBUTE */ &&
12218 attr.value &&
12219 attr.name === 'class') {
12220 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12221 }
12222 if (type === 0 /* Start */) {
12223 props.push(attr);
12224 }
12225 if (/^[^\t\r\n\f />]/.test(context.source)) {
12226 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12227 }
12228 advanceSpaces(context);
12229 }
12230 return props;
12231}
12232function parseAttribute(context, nameSet) {
12233 // Name.
12234 const start = getCursor(context);
12235 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12236 const name = match[0];
12237 if (nameSet.has(name)) {
12238 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12239 }
12240 nameSet.add(name);
12241 if (name[0] === '=') {
12242 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12243 }
12244 {
12245 const pattern = /["'<]/g;
12246 let m;
12247 while ((m = pattern.exec(name))) {
12248 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12249 }
12250 }
12251 advanceBy(context, name.length);
12252 // Value
12253 let value = undefined;
12254 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12255 advanceSpaces(context);
12256 advanceBy(context, 1);
12257 advanceSpaces(context);
12258 value = parseAttributeValue(context);
12259 if (!value) {
12260 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12261 }
12262 }
12263 const loc = getSelection(context, start);
12264 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12265 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12266 let isPropShorthand = startsWith(name, '.');
12267 let dirName = match[1] ||
12268 (isPropShorthand || startsWith(name, ':')
12269 ? 'bind'
12270 : startsWith(name, '@')
12271 ? 'on'
12272 : 'slot');
12273 let arg;
12274 if (match[2]) {
12275 const isSlot = dirName === 'slot';
12276 const startOffset = name.lastIndexOf(match[2]);
12277 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12278 let content = match[2];
12279 let isStatic = true;
12280 if (content.startsWith('[')) {
12281 isStatic = false;
12282 if (!content.endsWith(']')) {
12283 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12284 content = content.substr(1);
12285 }
12286 else {
12287 content = content.substr(1, content.length - 2);
12288 }
12289 }
12290 else if (isSlot) {
12291 // #1241 special case for v-slot: vuetify relies extensively on slot
12292 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12293 // supports such usage so we are keeping it consistent with 2.x.
12294 content += match[3] || '';
12295 }
12296 arg = {
12297 type: 4 /* SIMPLE_EXPRESSION */,
12298 content,
12299 isStatic,
12300 constType: isStatic
12301 ? 3 /* CAN_STRINGIFY */
12302 : 0 /* NOT_CONSTANT */,
12303 loc
12304 };
12305 }
12306 if (value && value.isQuoted) {
12307 const valueLoc = value.loc;
12308 valueLoc.start.offset++;
12309 valueLoc.start.column++;
12310 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12311 valueLoc.source = valueLoc.source.slice(1, -1);
12312 }
12313 const modifiers = match[3] ? match[3].substr(1).split('.') : [];
12314 if (isPropShorthand)
12315 modifiers.push('prop');
12316 return {
12317 type: 7 /* DIRECTIVE */,
12318 name: dirName,
12319 exp: value && {
12320 type: 4 /* SIMPLE_EXPRESSION */,
12321 content: value.content,
12322 isStatic: false,
12323 // Treat as non-constant by default. This can be potentially set to
12324 // other values by `transformExpression` to make it eligible for hoisting.
12325 constType: 0 /* NOT_CONSTANT */,
12326 loc: value.loc
12327 },
12328 arg,
12329 modifiers,
12330 loc
12331 };
12332 }
12333 // missing directive name or illegal directive name
12334 if (!context.inVPre && startsWith(name, 'v-')) {
12335 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12336 }
12337 return {
12338 type: 6 /* ATTRIBUTE */,
12339 name,
12340 value: value && {
12341 type: 2 /* TEXT */,
12342 content: value.content,
12343 loc: value.loc
12344 },
12345 loc
12346 };
12347}
12348function parseAttributeValue(context) {
12349 const start = getCursor(context);
12350 let content;
12351 const quote = context.source[0];
12352 const isQuoted = quote === `"` || quote === `'`;
12353 if (isQuoted) {
12354 // Quoted value.
12355 advanceBy(context, 1);
12356 const endIndex = context.source.indexOf(quote);
12357 if (endIndex === -1) {
12358 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12359 }
12360 else {
12361 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12362 advanceBy(context, 1);
12363 }
12364 }
12365 else {
12366 // Unquoted
12367 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12368 if (!match) {
12369 return undefined;
12370 }
12371 const unexpectedChars = /["'<=`]/g;
12372 let m;
12373 while ((m = unexpectedChars.exec(match[0]))) {
12374 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12375 }
12376 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12377 }
12378 return { content, isQuoted, loc: getSelection(context, start) };
12379}
12380function parseInterpolation(context, mode) {
12381 const [open, close] = context.options.delimiters;
12382 const closeIndex = context.source.indexOf(close, open.length);
12383 if (closeIndex === -1) {
12384 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12385 return undefined;
12386 }
12387 const start = getCursor(context);
12388 advanceBy(context, open.length);
12389 const innerStart = getCursor(context);
12390 const innerEnd = getCursor(context);
12391 const rawContentLength = closeIndex - open.length;
12392 const rawContent = context.source.slice(0, rawContentLength);
12393 const preTrimContent = parseTextData(context, rawContentLength, mode);
12394 const content = preTrimContent.trim();
12395 const startOffset = preTrimContent.indexOf(content);
12396 if (startOffset > 0) {
12397 advancePositionWithMutation(innerStart, rawContent, startOffset);
12398 }
12399 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12400 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12401 advanceBy(context, close.length);
12402 return {
12403 type: 5 /* INTERPOLATION */,
12404 content: {
12405 type: 4 /* SIMPLE_EXPRESSION */,
12406 isStatic: false,
12407 // Set `isConstant` to false by default and will decide in transformExpression
12408 constType: 0 /* NOT_CONSTANT */,
12409 content,
12410 loc: getSelection(context, innerStart, innerEnd)
12411 },
12412 loc: getSelection(context, start)
12413 };
12414}
12415function parseText(context, mode) {
12416 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12417 let endIndex = context.source.length;
12418 for (let i = 0; i < endTokens.length; i++) {
12419 const index = context.source.indexOf(endTokens[i], 1);
12420 if (index !== -1 && endIndex > index) {
12421 endIndex = index;
12422 }
12423 }
12424 const start = getCursor(context);
12425 const content = parseTextData(context, endIndex, mode);
12426 return {
12427 type: 2 /* TEXT */,
12428 content,
12429 loc: getSelection(context, start)
12430 };
12431}
12432/**
12433 * Get text data with a given length from the current location.
12434 * This translates HTML entities in the text data.
12435 */
12436function parseTextData(context, length, mode) {
12437 const rawText = context.source.slice(0, length);
12438 advanceBy(context, length);
12439 if (mode === 2 /* RAWTEXT */ ||
12440 mode === 3 /* CDATA */ ||
12441 rawText.indexOf('&') === -1) {
12442 return rawText;
12443 }
12444 else {
12445 // DATA or RCDATA containing "&"". Entity decoding required.
12446 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12447 }
12448}
12449function getCursor(context) {
12450 const { column, line, offset } = context;
12451 return { column, line, offset };
12452}
12453function getSelection(context, start, end) {
12454 end = end || getCursor(context);
12455 return {
12456 start,
12457 end,
12458 source: context.originalSource.slice(start.offset, end.offset)
12459 };
12460}
12461function last(xs) {
12462 return xs[xs.length - 1];
12463}
12464function startsWith(source, searchString) {
12465 return source.startsWith(searchString);
12466}
12467function advanceBy(context, numberOfCharacters) {
12468 const { source } = context;
12469 advancePositionWithMutation(context, source, numberOfCharacters);
12470 context.source = source.slice(numberOfCharacters);
12471}
12472function advanceSpaces(context) {
12473 const match = /^[\t\r\n\f ]+/.exec(context.source);
12474 if (match) {
12475 advanceBy(context, match[0].length);
12476 }
12477}
12478function getNewPosition(context, start, numberOfCharacters) {
12479 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12480}
12481function emitError(context, code, offset, loc = getCursor(context)) {
12482 if (offset) {
12483 loc.offset += offset;
12484 loc.column += offset;
12485 }
12486 context.options.onError(createCompilerError(code, {
12487 start: loc,
12488 end: loc,
12489 source: ''
12490 }));
12491}
12492function isEnd(context, mode, ancestors) {
12493 const s = context.source;
12494 switch (mode) {
12495 case 0 /* DATA */:
12496 if (startsWith(s, '</')) {
12497 // TODO: probably bad performance
12498 for (let i = ancestors.length - 1; i >= 0; --i) {
12499 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12500 return true;
12501 }
12502 }
12503 }
12504 break;
12505 case 1 /* RCDATA */:
12506 case 2 /* RAWTEXT */: {
12507 const parent = last(ancestors);
12508 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12509 return true;
12510 }
12511 break;
12512 }
12513 case 3 /* CDATA */:
12514 if (startsWith(s, ']]>')) {
12515 return true;
12516 }
12517 break;
12518 }
12519 return !s;
12520}
12521function startsWithEndTagOpen(source, tag) {
12522 return (startsWith(source, '</') &&
12523 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
12524 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12525}
12526
12527function hoistStatic(root, context) {
12528 walk(root, context,
12529 // Root node is unfortunately non-hoistable due to potential parent
12530 // fallthrough attributes.
12531 isSingleElementRoot(root, root.children[0]));
12532}
12533function isSingleElementRoot(root, child) {
12534 const { children } = root;
12535 return (children.length === 1 &&
12536 child.type === 1 /* ELEMENT */ &&
12537 !isSlotOutlet(child));
12538}
12539function walk(node, context, doNotHoistNode = false) {
12540 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
12541 // static bindings with expressions. These expressions are guaranteed to be
12542 // constant so they are still eligible for hoisting, but they are only
12543 // available at runtime and therefore cannot be evaluated ahead of time.
12544 // This is only a concern for pre-stringification (via transformHoist by
12545 // @vue/compiler-dom), but doing it here allows us to perform only one full
12546 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
12547 // stringficiation threshold is met.
12548 let canStringify = true;
12549 const { children } = node;
12550 const originalCount = children.length;
12551 let hoistedCount = 0;
12552 for (let i = 0; i < children.length; i++) {
12553 const child = children[i];
12554 // only plain elements & text calls are eligible for hoisting.
12555 if (child.type === 1 /* ELEMENT */ &&
12556 child.tagType === 0 /* ELEMENT */) {
12557 const constantType = doNotHoistNode
12558 ? 0 /* NOT_CONSTANT */
12559 : getConstantType(child, context);
12560 if (constantType > 0 /* NOT_CONSTANT */) {
12561 if (constantType < 3 /* CAN_STRINGIFY */) {
12562 canStringify = false;
12563 }
12564 if (constantType >= 2 /* CAN_HOIST */) {
12565 child.codegenNode.patchFlag =
12566 -1 /* HOISTED */ + (` /* HOISTED */` );
12567 child.codegenNode = context.hoist(child.codegenNode);
12568 hoistedCount++;
12569 continue;
12570 }
12571 }
12572 else {
12573 // node may contain dynamic children, but its props may be eligible for
12574 // hoisting.
12575 const codegenNode = child.codegenNode;
12576 if (codegenNode.type === 13 /* VNODE_CALL */) {
12577 const flag = getPatchFlag(codegenNode);
12578 if ((!flag ||
12579 flag === 512 /* NEED_PATCH */ ||
12580 flag === 1 /* TEXT */) &&
12581 getGeneratedPropsConstantType(child, context) >=
12582 2 /* CAN_HOIST */) {
12583 const props = getNodeProps(child);
12584 if (props) {
12585 codegenNode.props = context.hoist(props);
12586 }
12587 }
12588 if (codegenNode.dynamicProps) {
12589 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12590 }
12591 }
12592 }
12593 }
12594 else if (child.type === 12 /* TEXT_CALL */) {
12595 const contentType = getConstantType(child.content, context);
12596 if (contentType > 0) {
12597 if (contentType < 3 /* CAN_STRINGIFY */) {
12598 canStringify = false;
12599 }
12600 if (contentType >= 2 /* CAN_HOIST */) {
12601 child.codegenNode = context.hoist(child.codegenNode);
12602 hoistedCount++;
12603 }
12604 }
12605 }
12606 // walk further
12607 if (child.type === 1 /* ELEMENT */) {
12608 const isComponent = child.tagType === 1 /* COMPONENT */;
12609 if (isComponent) {
12610 context.scopes.vSlot++;
12611 }
12612 walk(child, context);
12613 if (isComponent) {
12614 context.scopes.vSlot--;
12615 }
12616 }
12617 else if (child.type === 11 /* FOR */) {
12618 // Do not hoist v-for single child because it has to be a block
12619 walk(child, context, child.children.length === 1);
12620 }
12621 else if (child.type === 9 /* IF */) {
12622 for (let i = 0; i < child.branches.length; i++) {
12623 // Do not hoist v-if single child because it has to be a block
12624 walk(child.branches[i], context, child.branches[i].children.length === 1);
12625 }
12626 }
12627 }
12628 if (canStringify && hoistedCount && context.transformHoist) {
12629 context.transformHoist(children, context, node);
12630 }
12631 // all children were hoisted - the entire children array is hoistable.
12632 if (hoistedCount &&
12633 hoistedCount === originalCount &&
12634 node.type === 1 /* ELEMENT */ &&
12635 node.tagType === 0 /* ELEMENT */ &&
12636 node.codegenNode &&
12637 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12638 isArray(node.codegenNode.children)) {
12639 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12640 }
12641}
12642function getConstantType(node, context) {
12643 const { constantCache } = context;
12644 switch (node.type) {
12645 case 1 /* ELEMENT */:
12646 if (node.tagType !== 0 /* ELEMENT */) {
12647 return 0 /* NOT_CONSTANT */;
12648 }
12649 const cached = constantCache.get(node);
12650 if (cached !== undefined) {
12651 return cached;
12652 }
12653 const codegenNode = node.codegenNode;
12654 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12655 return 0 /* NOT_CONSTANT */;
12656 }
12657 const flag = getPatchFlag(codegenNode);
12658 if (!flag) {
12659 let returnType = 3 /* CAN_STRINGIFY */;
12660 // Element itself has no patch flag. However we still need to check:
12661 // 1. Even for a node with no patch flag, it is possible for it to contain
12662 // non-hoistable expressions that refers to scope variables, e.g. compiler
12663 // injected keys or cached event handlers. Therefore we need to always
12664 // check the codegenNode's props to be sure.
12665 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12666 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12667 constantCache.set(node, 0 /* NOT_CONSTANT */);
12668 return 0 /* NOT_CONSTANT */;
12669 }
12670 if (generatedPropsType < returnType) {
12671 returnType = generatedPropsType;
12672 }
12673 // 2. its children.
12674 for (let i = 0; i < node.children.length; i++) {
12675 const childType = getConstantType(node.children[i], context);
12676 if (childType === 0 /* NOT_CONSTANT */) {
12677 constantCache.set(node, 0 /* NOT_CONSTANT */);
12678 return 0 /* NOT_CONSTANT */;
12679 }
12680 if (childType < returnType) {
12681 returnType = childType;
12682 }
12683 }
12684 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12685 // type, check if any of the props can cause the type to be lowered
12686 // we can skip can_patch because it's guaranteed by the absence of a
12687 // patchFlag.
12688 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12689 for (let i = 0; i < node.props.length; i++) {
12690 const p = node.props[i];
12691 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12692 const expType = getConstantType(p.exp, context);
12693 if (expType === 0 /* NOT_CONSTANT */) {
12694 constantCache.set(node, 0 /* NOT_CONSTANT */);
12695 return 0 /* NOT_CONSTANT */;
12696 }
12697 if (expType < returnType) {
12698 returnType = expType;
12699 }
12700 }
12701 }
12702 }
12703 // only svg/foreignObject could be block here, however if they are
12704 // static then they don't need to be blocks since there will be no
12705 // nested updates.
12706 if (codegenNode.isBlock) {
12707 context.removeHelper(OPEN_BLOCK);
12708 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12709 codegenNode.isBlock = false;
12710 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12711 }
12712 constantCache.set(node, returnType);
12713 return returnType;
12714 }
12715 else {
12716 constantCache.set(node, 0 /* NOT_CONSTANT */);
12717 return 0 /* NOT_CONSTANT */;
12718 }
12719 case 2 /* TEXT */:
12720 case 3 /* COMMENT */:
12721 return 3 /* CAN_STRINGIFY */;
12722 case 9 /* IF */:
12723 case 11 /* FOR */:
12724 case 10 /* IF_BRANCH */:
12725 return 0 /* NOT_CONSTANT */;
12726 case 5 /* INTERPOLATION */:
12727 case 12 /* TEXT_CALL */:
12728 return getConstantType(node.content, context);
12729 case 4 /* SIMPLE_EXPRESSION */:
12730 return node.constType;
12731 case 8 /* COMPOUND_EXPRESSION */:
12732 let returnType = 3 /* CAN_STRINGIFY */;
12733 for (let i = 0; i < node.children.length; i++) {
12734 const child = node.children[i];
12735 if (isString(child) || isSymbol(child)) {
12736 continue;
12737 }
12738 const childType = getConstantType(child, context);
12739 if (childType === 0 /* NOT_CONSTANT */) {
12740 return 0 /* NOT_CONSTANT */;
12741 }
12742 else if (childType < returnType) {
12743 returnType = childType;
12744 }
12745 }
12746 return returnType;
12747 default:
12748 return 0 /* NOT_CONSTANT */;
12749 }
12750}
12751const allowHoistedHelperSet = new Set([
12752 NORMALIZE_CLASS,
12753 NORMALIZE_STYLE,
12754 NORMALIZE_PROPS,
12755 GUARD_REACTIVE_PROPS
12756]);
12757function getConstantTypeOfHelperCall(value, context) {
12758 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12759 !isString(value.callee) &&
12760 allowHoistedHelperSet.has(value.callee)) {
12761 const arg = value.arguments[0];
12762 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12763 return getConstantType(arg, context);
12764 }
12765 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12766 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12767 return getConstantTypeOfHelperCall(arg, context);
12768 }
12769 }
12770 return 0 /* NOT_CONSTANT */;
12771}
12772function getGeneratedPropsConstantType(node, context) {
12773 let returnType = 3 /* CAN_STRINGIFY */;
12774 const props = getNodeProps(node);
12775 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12776 const { properties } = props;
12777 for (let i = 0; i < properties.length; i++) {
12778 const { key, value } = properties[i];
12779 const keyType = getConstantType(key, context);
12780 if (keyType === 0 /* NOT_CONSTANT */) {
12781 return keyType;
12782 }
12783 if (keyType < returnType) {
12784 returnType = keyType;
12785 }
12786 let valueType;
12787 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12788 valueType = getConstantType(value, context);
12789 }
12790 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12791 // some helper calls can be hoisted,
12792 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12793 // in this case we need to respect the ConstanType of the helper's argments
12794 valueType = getConstantTypeOfHelperCall(value, context);
12795 }
12796 else {
12797 valueType = 0 /* NOT_CONSTANT */;
12798 }
12799 if (valueType === 0 /* NOT_CONSTANT */) {
12800 return valueType;
12801 }
12802 if (valueType < returnType) {
12803 returnType = valueType;
12804 }
12805 }
12806 }
12807 return returnType;
12808}
12809function getNodeProps(node) {
12810 const codegenNode = node.codegenNode;
12811 if (codegenNode.type === 13 /* VNODE_CALL */) {
12812 return codegenNode.props;
12813 }
12814}
12815function getPatchFlag(node) {
12816 const flag = node.patchFlag;
12817 return flag ? parseInt(flag, 10) : undefined;
12818}
12819
12820function 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 }) {
12821 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12822 const context = {
12823 // options
12824 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12825 prefixIdentifiers,
12826 hoistStatic,
12827 cacheHandlers,
12828 nodeTransforms,
12829 directiveTransforms,
12830 transformHoist,
12831 isBuiltInComponent,
12832 isCustomElement,
12833 expressionPlugins,
12834 scopeId,
12835 slotted,
12836 ssr,
12837 inSSR,
12838 ssrCssVars,
12839 bindingMetadata,
12840 inline,
12841 isTS,
12842 onError,
12843 onWarn,
12844 compatConfig,
12845 // state
12846 root,
12847 helpers: new Map(),
12848 components: new Set(),
12849 directives: new Set(),
12850 hoists: [],
12851 imports: [],
12852 constantCache: new Map(),
12853 temps: 0,
12854 cached: 0,
12855 identifiers: Object.create(null),
12856 scopes: {
12857 vFor: 0,
12858 vSlot: 0,
12859 vPre: 0,
12860 vOnce: 0
12861 },
12862 parent: null,
12863 currentNode: root,
12864 childIndex: 0,
12865 inVOnce: false,
12866 // methods
12867 helper(name) {
12868 const count = context.helpers.get(name) || 0;
12869 context.helpers.set(name, count + 1);
12870 return name;
12871 },
12872 removeHelper(name) {
12873 const count = context.helpers.get(name);
12874 if (count) {
12875 const currentCount = count - 1;
12876 if (!currentCount) {
12877 context.helpers.delete(name);
12878 }
12879 else {
12880 context.helpers.set(name, currentCount);
12881 }
12882 }
12883 },
12884 helperString(name) {
12885 return `_${helperNameMap[context.helper(name)]}`;
12886 },
12887 replaceNode(node) {
12888 /* istanbul ignore if */
12889 {
12890 if (!context.currentNode) {
12891 throw new Error(`Node being replaced is already removed.`);
12892 }
12893 if (!context.parent) {
12894 throw new Error(`Cannot replace root node.`);
12895 }
12896 }
12897 context.parent.children[context.childIndex] = context.currentNode = node;
12898 },
12899 removeNode(node) {
12900 if (!context.parent) {
12901 throw new Error(`Cannot remove root node.`);
12902 }
12903 const list = context.parent.children;
12904 const removalIndex = node
12905 ? list.indexOf(node)
12906 : context.currentNode
12907 ? context.childIndex
12908 : -1;
12909 /* istanbul ignore if */
12910 if (removalIndex < 0) {
12911 throw new Error(`node being removed is not a child of current parent`);
12912 }
12913 if (!node || node === context.currentNode) {
12914 // current node removed
12915 context.currentNode = null;
12916 context.onNodeRemoved();
12917 }
12918 else {
12919 // sibling node removed
12920 if (context.childIndex > removalIndex) {
12921 context.childIndex--;
12922 context.onNodeRemoved();
12923 }
12924 }
12925 context.parent.children.splice(removalIndex, 1);
12926 },
12927 onNodeRemoved: () => { },
12928 addIdentifiers(exp) {
12929 },
12930 removeIdentifiers(exp) {
12931 },
12932 hoist(exp) {
12933 if (isString(exp))
12934 exp = createSimpleExpression(exp);
12935 context.hoists.push(exp);
12936 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12937 identifier.hoisted = exp;
12938 return identifier;
12939 },
12940 cache(exp, isVNode = false) {
12941 return createCacheExpression(context.cached++, exp, isVNode);
12942 }
12943 };
12944 return context;
12945}
12946function transform(root, options) {
12947 const context = createTransformContext(root, options);
12948 traverseNode(root, context);
12949 if (options.hoistStatic) {
12950 hoistStatic(root, context);
12951 }
12952 if (!options.ssr) {
12953 createRootCodegen(root, context);
12954 }
12955 // finalize meta information
12956 root.helpers = [...context.helpers.keys()];
12957 root.components = [...context.components];
12958 root.directives = [...context.directives];
12959 root.imports = context.imports;
12960 root.hoists = context.hoists;
12961 root.temps = context.temps;
12962 root.cached = context.cached;
12963}
12964function createRootCodegen(root, context) {
12965 const { helper } = context;
12966 const { children } = root;
12967 if (children.length === 1) {
12968 const child = children[0];
12969 // if the single child is an element, turn it into a block.
12970 if (isSingleElementRoot(root, child) && child.codegenNode) {
12971 // single element root is never hoisted so codegenNode will never be
12972 // SimpleExpressionNode
12973 const codegenNode = child.codegenNode;
12974 if (codegenNode.type === 13 /* VNODE_CALL */) {
12975 makeBlock(codegenNode, context);
12976 }
12977 root.codegenNode = codegenNode;
12978 }
12979 else {
12980 // - single <slot/>, IfNode, ForNode: already blocks.
12981 // - single text node: always patched.
12982 // root codegen falls through via genNode()
12983 root.codegenNode = child;
12984 }
12985 }
12986 else if (children.length > 1) {
12987 // root has multiple nodes - return a fragment block.
12988 let patchFlag = 64 /* STABLE_FRAGMENT */;
12989 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12990 // check if the fragment actually contains a single valid child with
12991 // the rest being comments
12992 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12993 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12994 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12995 }
12996 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12997 }
12998 else ;
12999}
13000function traverseChildren(parent, context) {
13001 let i = 0;
13002 const nodeRemoved = () => {
13003 i--;
13004 };
13005 for (; i < parent.children.length; i++) {
13006 const child = parent.children[i];
13007 if (isString(child))
13008 continue;
13009 context.parent = parent;
13010 context.childIndex = i;
13011 context.onNodeRemoved = nodeRemoved;
13012 traverseNode(child, context);
13013 }
13014}
13015function traverseNode(node, context) {
13016 context.currentNode = node;
13017 // apply transform plugins
13018 const { nodeTransforms } = context;
13019 const exitFns = [];
13020 for (let i = 0; i < nodeTransforms.length; i++) {
13021 const onExit = nodeTransforms[i](node, context);
13022 if (onExit) {
13023 if (isArray(onExit)) {
13024 exitFns.push(...onExit);
13025 }
13026 else {
13027 exitFns.push(onExit);
13028 }
13029 }
13030 if (!context.currentNode) {
13031 // node was removed
13032 return;
13033 }
13034 else {
13035 // node may have been replaced
13036 node = context.currentNode;
13037 }
13038 }
13039 switch (node.type) {
13040 case 3 /* COMMENT */:
13041 if (!context.ssr) {
13042 // inject import for the Comment symbol, which is needed for creating
13043 // comment nodes with `createVNode`
13044 context.helper(CREATE_COMMENT);
13045 }
13046 break;
13047 case 5 /* INTERPOLATION */:
13048 // no need to traverse, but we need to inject toString helper
13049 if (!context.ssr) {
13050 context.helper(TO_DISPLAY_STRING);
13051 }
13052 break;
13053 // for container types, further traverse downwards
13054 case 9 /* IF */:
13055 for (let i = 0; i < node.branches.length; i++) {
13056 traverseNode(node.branches[i], context);
13057 }
13058 break;
13059 case 10 /* IF_BRANCH */:
13060 case 11 /* FOR */:
13061 case 1 /* ELEMENT */:
13062 case 0 /* ROOT */:
13063 traverseChildren(node, context);
13064 break;
13065 }
13066 // exit transforms
13067 context.currentNode = node;
13068 let i = exitFns.length;
13069 while (i--) {
13070 exitFns[i]();
13071 }
13072}
13073function createStructuralDirectiveTransform(name, fn) {
13074 const matches = isString(name)
13075 ? (n) => n === name
13076 : (n) => name.test(n);
13077 return (node, context) => {
13078 if (node.type === 1 /* ELEMENT */) {
13079 const { props } = node;
13080 // structural directive transforms are not concerned with slots
13081 // as they are handled separately in vSlot.ts
13082 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
13083 return;
13084 }
13085 const exitFns = [];
13086 for (let i = 0; i < props.length; i++) {
13087 const prop = props[i];
13088 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
13089 // structural directives are removed to avoid infinite recursion
13090 // also we remove them *before* applying so that it can further
13091 // traverse itself in case it moves the node around
13092 props.splice(i, 1);
13093 i--;
13094 const onExit = fn(node, prop, context);
13095 if (onExit)
13096 exitFns.push(onExit);
13097 }
13098 }
13099 return exitFns;
13100 }
13101 };
13102}
13103
13104const PURE_ANNOTATION = `/*#__PURE__*/`;
13105function 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 }) {
13106 const context = {
13107 mode,
13108 prefixIdentifiers,
13109 sourceMap,
13110 filename,
13111 scopeId,
13112 optimizeImports,
13113 runtimeGlobalName,
13114 runtimeModuleName,
13115 ssr,
13116 isTS,
13117 inSSR,
13118 source: ast.loc.source,
13119 code: ``,
13120 column: 1,
13121 line: 1,
13122 offset: 0,
13123 indentLevel: 0,
13124 pure: false,
13125 map: undefined,
13126 helper(key) {
13127 return `_${helperNameMap[key]}`;
13128 },
13129 push(code, node) {
13130 context.code += code;
13131 },
13132 indent() {
13133 newline(++context.indentLevel);
13134 },
13135 deindent(withoutNewLine = false) {
13136 if (withoutNewLine) {
13137 --context.indentLevel;
13138 }
13139 else {
13140 newline(--context.indentLevel);
13141 }
13142 },
13143 newline() {
13144 newline(context.indentLevel);
13145 }
13146 };
13147 function newline(n) {
13148 context.push('\n' + ` `.repeat(n));
13149 }
13150 return context;
13151}
13152function generate(ast, options = {}) {
13153 const context = createCodegenContext(ast, options);
13154 if (options.onContextCreated)
13155 options.onContextCreated(context);
13156 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
13157 const hasHelpers = ast.helpers.length > 0;
13158 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13159 // preambles
13160 // in setup() inline mode, the preamble is generated in a sub context
13161 // and returned separately.
13162 const preambleContext = context;
13163 {
13164 genFunctionPreamble(ast, preambleContext);
13165 }
13166 // enter render function
13167 const functionName = ssr ? `ssrRender` : `render`;
13168 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13169 const signature = args.join(', ');
13170 {
13171 push(`function ${functionName}(${signature}) {`);
13172 }
13173 indent();
13174 if (useWithBlock) {
13175 push(`with (_ctx) {`);
13176 indent();
13177 // function mode const declarations should be inside with block
13178 // also they should be renamed to avoid collision with user properties
13179 if (hasHelpers) {
13180 push(`const { ${ast.helpers
13181 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
13182 .join(', ')} } = _Vue`);
13183 push(`\n`);
13184 newline();
13185 }
13186 }
13187 // generate asset resolution statements
13188 if (ast.components.length) {
13189 genAssets(ast.components, 'component', context);
13190 if (ast.directives.length || ast.temps > 0) {
13191 newline();
13192 }
13193 }
13194 if (ast.directives.length) {
13195 genAssets(ast.directives, 'directive', context);
13196 if (ast.temps > 0) {
13197 newline();
13198 }
13199 }
13200 if (ast.temps > 0) {
13201 push(`let `);
13202 for (let i = 0; i < ast.temps; i++) {
13203 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13204 }
13205 }
13206 if (ast.components.length || ast.directives.length || ast.temps) {
13207 push(`\n`);
13208 newline();
13209 }
13210 // generate the VNode tree expression
13211 if (!ssr) {
13212 push(`return `);
13213 }
13214 if (ast.codegenNode) {
13215 genNode(ast.codegenNode, context);
13216 }
13217 else {
13218 push(`null`);
13219 }
13220 if (useWithBlock) {
13221 deindent();
13222 push(`}`);
13223 }
13224 deindent();
13225 push(`}`);
13226 return {
13227 ast,
13228 code: context.code,
13229 preamble: ``,
13230 // SourceMapGenerator does have toJSON() method but it's not in the types
13231 map: context.map ? context.map.toJSON() : undefined
13232 };
13233}
13234function genFunctionPreamble(ast, context) {
13235 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
13236 const VueBinding = runtimeGlobalName;
13237 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13238 // Generate const declaration for helpers
13239 // In prefix mode, we place the const declaration at top so it's done
13240 // only once; But if we not prefixing, we place the declaration inside the
13241 // with block so it doesn't incur the `in` check cost for every helper access.
13242 if (ast.helpers.length > 0) {
13243 {
13244 // "with" mode.
13245 // save Vue in a separate variable to avoid collision
13246 push(`const _Vue = ${VueBinding}\n`);
13247 // in "with" mode, helpers are declared inside the with block to avoid
13248 // has check cost, but hoists are lifted out of the function - we need
13249 // to provide the helper here.
13250 if (ast.hoists.length) {
13251 const staticHelpers = [
13252 CREATE_VNODE,
13253 CREATE_ELEMENT_VNODE,
13254 CREATE_COMMENT,
13255 CREATE_TEXT,
13256 CREATE_STATIC
13257 ]
13258 .filter(helper => ast.helpers.includes(helper))
13259 .map(aliasHelper)
13260 .join(', ');
13261 push(`const { ${staticHelpers} } = _Vue\n`);
13262 }
13263 }
13264 }
13265 genHoists(ast.hoists, context);
13266 newline();
13267 push(`return `);
13268}
13269function genAssets(assets, type, { helper, push, newline, isTS }) {
13270 const resolver = helper(type === 'component'
13271 ? RESOLVE_COMPONENT
13272 : RESOLVE_DIRECTIVE);
13273 for (let i = 0; i < assets.length; i++) {
13274 let id = assets[i];
13275 // potential component implicit self-reference inferred from SFC filename
13276 const maybeSelfReference = id.endsWith('__self');
13277 if (maybeSelfReference) {
13278 id = id.slice(0, -6);
13279 }
13280 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13281 if (i < assets.length - 1) {
13282 newline();
13283 }
13284 }
13285}
13286function genHoists(hoists, context) {
13287 if (!hoists.length) {
13288 return;
13289 }
13290 context.pure = true;
13291 const { push, newline, helper, scopeId, mode } = context;
13292 newline();
13293 hoists.forEach((exp, i) => {
13294 if (exp) {
13295 push(`const _hoisted_${i + 1} = `);
13296 genNode(exp, context);
13297 newline();
13298 }
13299 });
13300 context.pure = false;
13301}
13302function isText$1(n) {
13303 return (isString(n) ||
13304 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13305 n.type === 2 /* TEXT */ ||
13306 n.type === 5 /* INTERPOLATION */ ||
13307 n.type === 8 /* COMPOUND_EXPRESSION */);
13308}
13309function genNodeListAsArray(nodes, context) {
13310 const multilines = nodes.length > 3 ||
13311 (nodes.some(n => isArray(n) || !isText$1(n)));
13312 context.push(`[`);
13313 multilines && context.indent();
13314 genNodeList(nodes, context, multilines);
13315 multilines && context.deindent();
13316 context.push(`]`);
13317}
13318function genNodeList(nodes, context, multilines = false, comma = true) {
13319 const { push, newline } = context;
13320 for (let i = 0; i < nodes.length; i++) {
13321 const node = nodes[i];
13322 if (isString(node)) {
13323 push(node);
13324 }
13325 else if (isArray(node)) {
13326 genNodeListAsArray(node, context);
13327 }
13328 else {
13329 genNode(node, context);
13330 }
13331 if (i < nodes.length - 1) {
13332 if (multilines) {
13333 comma && push(',');
13334 newline();
13335 }
13336 else {
13337 comma && push(', ');
13338 }
13339 }
13340 }
13341}
13342function genNode(node, context) {
13343 if (isString(node)) {
13344 context.push(node);
13345 return;
13346 }
13347 if (isSymbol(node)) {
13348 context.push(context.helper(node));
13349 return;
13350 }
13351 switch (node.type) {
13352 case 1 /* ELEMENT */:
13353 case 9 /* IF */:
13354 case 11 /* FOR */:
13355 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13356 `Apply appropriate transforms first.`);
13357 genNode(node.codegenNode, context);
13358 break;
13359 case 2 /* TEXT */:
13360 genText(node, context);
13361 break;
13362 case 4 /* SIMPLE_EXPRESSION */:
13363 genExpression(node, context);
13364 break;
13365 case 5 /* INTERPOLATION */:
13366 genInterpolation(node, context);
13367 break;
13368 case 12 /* TEXT_CALL */:
13369 genNode(node.codegenNode, context);
13370 break;
13371 case 8 /* COMPOUND_EXPRESSION */:
13372 genCompoundExpression(node, context);
13373 break;
13374 case 3 /* COMMENT */:
13375 genComment(node, context);
13376 break;
13377 case 13 /* VNODE_CALL */:
13378 genVNodeCall(node, context);
13379 break;
13380 case 14 /* JS_CALL_EXPRESSION */:
13381 genCallExpression(node, context);
13382 break;
13383 case 15 /* JS_OBJECT_EXPRESSION */:
13384 genObjectExpression(node, context);
13385 break;
13386 case 17 /* JS_ARRAY_EXPRESSION */:
13387 genArrayExpression(node, context);
13388 break;
13389 case 18 /* JS_FUNCTION_EXPRESSION */:
13390 genFunctionExpression(node, context);
13391 break;
13392 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13393 genConditionalExpression(node, context);
13394 break;
13395 case 20 /* JS_CACHE_EXPRESSION */:
13396 genCacheExpression(node, context);
13397 break;
13398 case 21 /* JS_BLOCK_STATEMENT */:
13399 genNodeList(node.body, context, true, false);
13400 break;
13401 // SSR only types
13402 case 22 /* JS_TEMPLATE_LITERAL */:
13403 break;
13404 case 23 /* JS_IF_STATEMENT */:
13405 break;
13406 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13407 break;
13408 case 25 /* JS_SEQUENCE_EXPRESSION */:
13409 break;
13410 case 26 /* JS_RETURN_STATEMENT */:
13411 break;
13412 /* istanbul ignore next */
13413 case 10 /* IF_BRANCH */:
13414 // noop
13415 break;
13416 default:
13417 {
13418 assert(false, `unhandled codegen node type: ${node.type}`);
13419 // make sure we exhaust all possible types
13420 const exhaustiveCheck = node;
13421 return exhaustiveCheck;
13422 }
13423 }
13424}
13425function genText(node, context) {
13426 context.push(JSON.stringify(node.content), node);
13427}
13428function genExpression(node, context) {
13429 const { content, isStatic } = node;
13430 context.push(isStatic ? JSON.stringify(content) : content, node);
13431}
13432function genInterpolation(node, context) {
13433 const { push, helper, pure } = context;
13434 if (pure)
13435 push(PURE_ANNOTATION);
13436 push(`${helper(TO_DISPLAY_STRING)}(`);
13437 genNode(node.content, context);
13438 push(`)`);
13439}
13440function genCompoundExpression(node, context) {
13441 for (let i = 0; i < node.children.length; i++) {
13442 const child = node.children[i];
13443 if (isString(child)) {
13444 context.push(child);
13445 }
13446 else {
13447 genNode(child, context);
13448 }
13449 }
13450}
13451function genExpressionAsPropertyKey(node, context) {
13452 const { push } = context;
13453 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13454 push(`[`);
13455 genCompoundExpression(node, context);
13456 push(`]`);
13457 }
13458 else if (node.isStatic) {
13459 // only quote keys if necessary
13460 const text = isSimpleIdentifier(node.content)
13461 ? node.content
13462 : JSON.stringify(node.content);
13463 push(text, node);
13464 }
13465 else {
13466 push(`[${node.content}]`, node);
13467 }
13468}
13469function genComment(node, context) {
13470 const { push, helper, pure } = context;
13471 if (pure) {
13472 push(PURE_ANNOTATION);
13473 }
13474 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13475}
13476function genVNodeCall(node, context) {
13477 const { push, helper, pure } = context;
13478 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13479 if (directives) {
13480 push(helper(WITH_DIRECTIVES) + `(`);
13481 }
13482 if (isBlock) {
13483 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13484 }
13485 if (pure) {
13486 push(PURE_ANNOTATION);
13487 }
13488 const callHelper = isBlock
13489 ? getVNodeBlockHelper(context.inSSR, isComponent)
13490 : getVNodeHelper(context.inSSR, isComponent);
13491 push(helper(callHelper) + `(`, node);
13492 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13493 push(`)`);
13494 if (isBlock) {
13495 push(`)`);
13496 }
13497 if (directives) {
13498 push(`, `);
13499 genNode(directives, context);
13500 push(`)`);
13501 }
13502}
13503function genNullableArgs(args) {
13504 let i = args.length;
13505 while (i--) {
13506 if (args[i] != null)
13507 break;
13508 }
13509 return args.slice(0, i + 1).map(arg => arg || `null`);
13510}
13511// JavaScript
13512function genCallExpression(node, context) {
13513 const { push, helper, pure } = context;
13514 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13515 if (pure) {
13516 push(PURE_ANNOTATION);
13517 }
13518 push(callee + `(`, node);
13519 genNodeList(node.arguments, context);
13520 push(`)`);
13521}
13522function genObjectExpression(node, context) {
13523 const { push, indent, deindent, newline } = context;
13524 const { properties } = node;
13525 if (!properties.length) {
13526 push(`{}`, node);
13527 return;
13528 }
13529 const multilines = properties.length > 1 ||
13530 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13531 push(multilines ? `{` : `{ `);
13532 multilines && indent();
13533 for (let i = 0; i < properties.length; i++) {
13534 const { key, value } = properties[i];
13535 // key
13536 genExpressionAsPropertyKey(key, context);
13537 push(`: `);
13538 // value
13539 genNode(value, context);
13540 if (i < properties.length - 1) {
13541 // will only reach this if it's multilines
13542 push(`,`);
13543 newline();
13544 }
13545 }
13546 multilines && deindent();
13547 push(multilines ? `}` : ` }`);
13548}
13549function genArrayExpression(node, context) {
13550 genNodeListAsArray(node.elements, context);
13551}
13552function genFunctionExpression(node, context) {
13553 const { push, indent, deindent } = context;
13554 const { params, returns, body, newline, isSlot } = node;
13555 if (isSlot) {
13556 // wrap slot functions with owner context
13557 push(`_${helperNameMap[WITH_CTX]}(`);
13558 }
13559 push(`(`, node);
13560 if (isArray(params)) {
13561 genNodeList(params, context);
13562 }
13563 else if (params) {
13564 genNode(params, context);
13565 }
13566 push(`) => `);
13567 if (newline || body) {
13568 push(`{`);
13569 indent();
13570 }
13571 if (returns) {
13572 if (newline) {
13573 push(`return `);
13574 }
13575 if (isArray(returns)) {
13576 genNodeListAsArray(returns, context);
13577 }
13578 else {
13579 genNode(returns, context);
13580 }
13581 }
13582 else if (body) {
13583 genNode(body, context);
13584 }
13585 if (newline || body) {
13586 deindent();
13587 push(`}`);
13588 }
13589 if (isSlot) {
13590 push(`)`);
13591 }
13592}
13593function genConditionalExpression(node, context) {
13594 const { test, consequent, alternate, newline: needNewline } = node;
13595 const { push, indent, deindent, newline } = context;
13596 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13597 const needsParens = !isSimpleIdentifier(test.content);
13598 needsParens && push(`(`);
13599 genExpression(test, context);
13600 needsParens && push(`)`);
13601 }
13602 else {
13603 push(`(`);
13604 genNode(test, context);
13605 push(`)`);
13606 }
13607 needNewline && indent();
13608 context.indentLevel++;
13609 needNewline || push(` `);
13610 push(`? `);
13611 genNode(consequent, context);
13612 context.indentLevel--;
13613 needNewline && newline();
13614 needNewline || push(` `);
13615 push(`: `);
13616 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13617 if (!isNested) {
13618 context.indentLevel++;
13619 }
13620 genNode(alternate, context);
13621 if (!isNested) {
13622 context.indentLevel--;
13623 }
13624 needNewline && deindent(true /* without newline */);
13625}
13626function genCacheExpression(node, context) {
13627 const { push, helper, indent, deindent, newline } = context;
13628 push(`_cache[${node.index}] || (`);
13629 if (node.isVNode) {
13630 indent();
13631 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13632 newline();
13633 }
13634 push(`_cache[${node.index}] = `);
13635 genNode(node.value, context);
13636 if (node.isVNode) {
13637 push(`,`);
13638 newline();
13639 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13640 newline();
13641 push(`_cache[${node.index}]`);
13642 deindent();
13643 }
13644 push(`)`);
13645}
13646
13647// these keywords should not appear inside expressions, but operators like
13648// typeof, instanceof and in are allowed
13649const prohibitedKeywordRE = new RegExp('\\b' +
13650 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13651 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13652 'extends,finally,continue,debugger,function,arguments,typeof,void')
13653 .split(',')
13654 .join('\\b|\\b') +
13655 '\\b');
13656// strip strings in expressions
13657const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13658/**
13659 * Validate a non-prefixed expression.
13660 * This is only called when using the in-browser runtime compiler since it
13661 * doesn't prefix expressions.
13662 */
13663function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13664 const exp = node.content;
13665 // empty expressions are validated per-directive since some directives
13666 // do allow empty expressions.
13667 if (!exp.trim()) {
13668 return;
13669 }
13670 try {
13671 new Function(asRawStatements
13672 ? ` ${exp} `
13673 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13674 }
13675 catch (e) {
13676 let message = e.message;
13677 const keywordMatch = exp
13678 .replace(stripStringRE, '')
13679 .match(prohibitedKeywordRE);
13680 if (keywordMatch) {
13681 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13682 }
13683 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13684 }
13685}
13686
13687const transformExpression = (node, context) => {
13688 if (node.type === 5 /* INTERPOLATION */) {
13689 node.content = processExpression(node.content, context);
13690 }
13691 else if (node.type === 1 /* ELEMENT */) {
13692 // handle directives on element
13693 for (let i = 0; i < node.props.length; i++) {
13694 const dir = node.props[i];
13695 // do not process for v-on & v-for since they are special handled
13696 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13697 const exp = dir.exp;
13698 const arg = dir.arg;
13699 // do not process exp if this is v-on:arg - we need special handling
13700 // for wrapping inline statements.
13701 if (exp &&
13702 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13703 !(dir.name === 'on' && arg)) {
13704 dir.exp = processExpression(exp, context,
13705 // slot args must be processed as function params
13706 dir.name === 'slot');
13707 }
13708 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13709 dir.arg = processExpression(arg, context);
13710 }
13711 }
13712 }
13713 }
13714};
13715// Important: since this function uses Node.js only dependencies, it should
13716// always be used with a leading !true check so that it can be
13717// tree-shaken from the browser build.
13718function processExpression(node, context,
13719// some expressions like v-slot props & v-for aliases should be parsed as
13720// function params
13721asParams = false,
13722// v-on handler values may contain multiple statements
13723asRawStatements = false, localVars = Object.create(context.identifiers)) {
13724 {
13725 {
13726 // simple in-browser validation (same logic in 2.x)
13727 validateBrowserExpression(node, context, asParams, asRawStatements);
13728 }
13729 return node;
13730 }
13731}
13732
13733const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13734 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13735 // #1587: We need to dynamically increment the key based on the current
13736 // node's sibling nodes, since chained v-if/else branches are
13737 // rendered at the same depth
13738 const siblings = context.parent.children;
13739 let i = siblings.indexOf(ifNode);
13740 let key = 0;
13741 while (i-- >= 0) {
13742 const sibling = siblings[i];
13743 if (sibling && sibling.type === 9 /* IF */) {
13744 key += sibling.branches.length;
13745 }
13746 }
13747 // Exit callback. Complete the codegenNode when all children have been
13748 // transformed.
13749 return () => {
13750 if (isRoot) {
13751 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13752 }
13753 else {
13754 // attach this branch's codegen node to the v-if root.
13755 const parentCondition = getParentCondition(ifNode.codegenNode);
13756 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13757 }
13758 };
13759 });
13760});
13761// target-agnostic transform used for both Client and SSR
13762function processIf(node, dir, context, processCodegen) {
13763 if (dir.name !== 'else' &&
13764 (!dir.exp || !dir.exp.content.trim())) {
13765 const loc = dir.exp ? dir.exp.loc : node.loc;
13766 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13767 dir.exp = createSimpleExpression(`true`, false, loc);
13768 }
13769 if (dir.exp) {
13770 validateBrowserExpression(dir.exp, context);
13771 }
13772 if (dir.name === 'if') {
13773 const branch = createIfBranch(node, dir);
13774 const ifNode = {
13775 type: 9 /* IF */,
13776 loc: node.loc,
13777 branches: [branch]
13778 };
13779 context.replaceNode(ifNode);
13780 if (processCodegen) {
13781 return processCodegen(ifNode, branch, true);
13782 }
13783 }
13784 else {
13785 // locate the adjacent v-if
13786 const siblings = context.parent.children;
13787 const comments = [];
13788 let i = siblings.indexOf(node);
13789 while (i-- >= -1) {
13790 const sibling = siblings[i];
13791 if (sibling && sibling.type === 3 /* COMMENT */) {
13792 context.removeNode(sibling);
13793 comments.unshift(sibling);
13794 continue;
13795 }
13796 if (sibling &&
13797 sibling.type === 2 /* TEXT */ &&
13798 !sibling.content.trim().length) {
13799 context.removeNode(sibling);
13800 continue;
13801 }
13802 if (sibling && sibling.type === 9 /* IF */) {
13803 // move the node to the if node's branches
13804 context.removeNode();
13805 const branch = createIfBranch(node, dir);
13806 if (comments.length &&
13807 // #3619 ignore comments if the v-if is direct child of <transition>
13808 !(context.parent &&
13809 context.parent.type === 1 /* ELEMENT */ &&
13810 isBuiltInType(context.parent.tag, 'transition'))) {
13811 branch.children = [...comments, ...branch.children];
13812 }
13813 // check if user is forcing same key on different branches
13814 {
13815 const key = branch.userKey;
13816 if (key) {
13817 sibling.branches.forEach(({ userKey }) => {
13818 if (isSameKey(userKey, key)) {
13819 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13820 }
13821 });
13822 }
13823 }
13824 sibling.branches.push(branch);
13825 const onExit = processCodegen && processCodegen(sibling, branch, false);
13826 // since the branch was removed, it will not be traversed.
13827 // make sure to traverse here.
13828 traverseNode(branch, context);
13829 // call on exit
13830 if (onExit)
13831 onExit();
13832 // make sure to reset currentNode after traversal to indicate this
13833 // node has been removed.
13834 context.currentNode = null;
13835 }
13836 else {
13837 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13838 }
13839 break;
13840 }
13841 }
13842}
13843function createIfBranch(node, dir) {
13844 return {
13845 type: 10 /* IF_BRANCH */,
13846 loc: node.loc,
13847 condition: dir.name === 'else' ? undefined : dir.exp,
13848 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13849 ? node.children
13850 : [node],
13851 userKey: findProp(node, `key`)
13852 };
13853}
13854function createCodegenNodeForBranch(branch, keyIndex, context) {
13855 if (branch.condition) {
13856 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13857 // make sure to pass in asBlock: true so that the comment node call
13858 // closes the current block.
13859 createCallExpression(context.helper(CREATE_COMMENT), [
13860 '"v-if"' ,
13861 'true'
13862 ]));
13863 }
13864 else {
13865 return createChildrenCodegenNode(branch, keyIndex, context);
13866 }
13867}
13868function createChildrenCodegenNode(branch, keyIndex, context) {
13869 const { helper } = context;
13870 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13871 const { children } = branch;
13872 const firstChild = children[0];
13873 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13874 if (needFragmentWrapper) {
13875 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13876 // optimize away nested fragments when child is a ForNode
13877 const vnodeCall = firstChild.codegenNode;
13878 injectProp(vnodeCall, keyProperty, context);
13879 return vnodeCall;
13880 }
13881 else {
13882 let patchFlag = 64 /* STABLE_FRAGMENT */;
13883 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13884 // check if the fragment actually contains a single valid child with
13885 // the rest being comments
13886 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13887 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13888 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13889 }
13890 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13891 }
13892 }
13893 else {
13894 const ret = firstChild.codegenNode;
13895 const vnodeCall = getMemoedVNodeCall(ret);
13896 // Change createVNode to createBlock.
13897 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13898 makeBlock(vnodeCall, context);
13899 }
13900 // inject branch key
13901 injectProp(vnodeCall, keyProperty, context);
13902 return ret;
13903 }
13904}
13905function isSameKey(a, b) {
13906 if (!a || a.type !== b.type) {
13907 return false;
13908 }
13909 if (a.type === 6 /* ATTRIBUTE */) {
13910 if (a.value.content !== b.value.content) {
13911 return false;
13912 }
13913 }
13914 else {
13915 // directive
13916 const exp = a.exp;
13917 const branchExp = b.exp;
13918 if (exp.type !== branchExp.type) {
13919 return false;
13920 }
13921 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13922 exp.isStatic !== branchExp.isStatic ||
13923 exp.content !== branchExp.content) {
13924 return false;
13925 }
13926 }
13927 return true;
13928}
13929function getParentCondition(node) {
13930 while (true) {
13931 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13932 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13933 node = node.alternate;
13934 }
13935 else {
13936 return node;
13937 }
13938 }
13939 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13940 node = node.value;
13941 }
13942 }
13943}
13944
13945const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13946 const { helper, removeHelper } = context;
13947 return processFor(node, dir, context, forNode => {
13948 // create the loop render function expression now, and add the
13949 // iterator on exit after all children have been traversed
13950 const renderExp = createCallExpression(helper(RENDER_LIST), [
13951 forNode.source
13952 ]);
13953 const memo = findDir(node, 'memo');
13954 const keyProp = findProp(node, `key`);
13955 const keyExp = keyProp &&
13956 (keyProp.type === 6 /* ATTRIBUTE */
13957 ? createSimpleExpression(keyProp.value.content, true)
13958 : keyProp.exp);
13959 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13960 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13961 forNode.source.constType > 0 /* NOT_CONSTANT */;
13962 const fragmentFlag = isStableFragment
13963 ? 64 /* STABLE_FRAGMENT */
13964 : keyProp
13965 ? 128 /* KEYED_FRAGMENT */
13966 : 256 /* UNKEYED_FRAGMENT */;
13967 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13968 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13969 return () => {
13970 // finish the codegen now that all children have been traversed
13971 let childBlock;
13972 const isTemplate = isTemplateNode(node);
13973 const { children } = forNode;
13974 // check <template v-for> key placement
13975 if (isTemplate) {
13976 node.children.some(c => {
13977 if (c.type === 1 /* ELEMENT */) {
13978 const key = findProp(c, 'key');
13979 if (key) {
13980 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13981 return true;
13982 }
13983 }
13984 });
13985 }
13986 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13987 const slotOutlet = isSlotOutlet(node)
13988 ? node
13989 : isTemplate &&
13990 node.children.length === 1 &&
13991 isSlotOutlet(node.children[0])
13992 ? node.children[0] // api-extractor somehow fails to infer this
13993 : null;
13994 if (slotOutlet) {
13995 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13996 childBlock = slotOutlet.codegenNode;
13997 if (isTemplate && keyProperty) {
13998 // <template v-for="..." :key="..."><slot/></template>
13999 // we need to inject the key to the renderSlot() call.
14000 // the props for renderSlot is passed as the 3rd argument.
14001 injectProp(childBlock, keyProperty, context);
14002 }
14003 }
14004 else if (needFragmentWrapper) {
14005 // <template v-for="..."> with text or multi-elements
14006 // should generate a fragment block for each loop
14007 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
14008 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
14009 ), undefined, undefined, true, undefined, false /* isComponent */);
14010 }
14011 else {
14012 // Normal element v-for. Directly use the child's codegenNode
14013 // but mark it as a block.
14014 childBlock = children[0]
14015 .codegenNode;
14016 if (isTemplate && keyProperty) {
14017 injectProp(childBlock, keyProperty, context);
14018 }
14019 if (childBlock.isBlock !== !isStableFragment) {
14020 if (childBlock.isBlock) {
14021 // switch from block to vnode
14022 removeHelper(OPEN_BLOCK);
14023 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
14024 }
14025 else {
14026 // switch from vnode to block
14027 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
14028 }
14029 }
14030 childBlock.isBlock = !isStableFragment;
14031 if (childBlock.isBlock) {
14032 helper(OPEN_BLOCK);
14033 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
14034 }
14035 else {
14036 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
14037 }
14038 }
14039 if (memo) {
14040 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
14041 createSimpleExpression(`_cached`)
14042 ]));
14043 loop.body = createBlockStatement([
14044 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
14045 createCompoundExpression([
14046 `if (_cached`,
14047 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
14048 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
14049 ]),
14050 createCompoundExpression([`const _item = `, childBlock]),
14051 createSimpleExpression(`_item.memo = _memo`),
14052 createSimpleExpression(`return _item`)
14053 ]);
14054 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
14055 }
14056 else {
14057 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
14058 }
14059 };
14060 });
14061});
14062// target-agnostic transform used for both Client and SSR
14063function processFor(node, dir, context, processCodegen) {
14064 if (!dir.exp) {
14065 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
14066 return;
14067 }
14068 const parseResult = parseForExpression(
14069 // can only be simple expression because vFor transform is applied
14070 // before expression transform.
14071 dir.exp, context);
14072 if (!parseResult) {
14073 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
14074 return;
14075 }
14076 const { addIdentifiers, removeIdentifiers, scopes } = context;
14077 const { source, value, key, index } = parseResult;
14078 const forNode = {
14079 type: 11 /* FOR */,
14080 loc: dir.loc,
14081 source,
14082 valueAlias: value,
14083 keyAlias: key,
14084 objectIndexAlias: index,
14085 parseResult,
14086 children: isTemplateNode(node) ? node.children : [node]
14087 };
14088 context.replaceNode(forNode);
14089 // bookkeeping
14090 scopes.vFor++;
14091 const onExit = processCodegen && processCodegen(forNode);
14092 return () => {
14093 scopes.vFor--;
14094 if (onExit)
14095 onExit();
14096 };
14097}
14098const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
14099// This regex doesn't cover the case if key or index aliases have destructuring,
14100// but those do not make sense in the first place, so this works in practice.
14101const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
14102const stripParensRE = /^\(|\)$/g;
14103function parseForExpression(input, context) {
14104 const loc = input.loc;
14105 const exp = input.content;
14106 const inMatch = exp.match(forAliasRE);
14107 if (!inMatch)
14108 return;
14109 const [, LHS, RHS] = inMatch;
14110 const result = {
14111 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
14112 value: undefined,
14113 key: undefined,
14114 index: undefined
14115 };
14116 {
14117 validateBrowserExpression(result.source, context);
14118 }
14119 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
14120 const trimmedOffset = LHS.indexOf(valueContent);
14121 const iteratorMatch = valueContent.match(forIteratorRE);
14122 if (iteratorMatch) {
14123 valueContent = valueContent.replace(forIteratorRE, '').trim();
14124 const keyContent = iteratorMatch[1].trim();
14125 let keyOffset;
14126 if (keyContent) {
14127 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
14128 result.key = createAliasExpression(loc, keyContent, keyOffset);
14129 {
14130 validateBrowserExpression(result.key, context, true);
14131 }
14132 }
14133 if (iteratorMatch[2]) {
14134 const indexContent = iteratorMatch[2].trim();
14135 if (indexContent) {
14136 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
14137 ? keyOffset + keyContent.length
14138 : trimmedOffset + valueContent.length));
14139 {
14140 validateBrowserExpression(result.index, context, true);
14141 }
14142 }
14143 }
14144 }
14145 if (valueContent) {
14146 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
14147 {
14148 validateBrowserExpression(result.value, context, true);
14149 }
14150 }
14151 return result;
14152}
14153function createAliasExpression(range, content, offset) {
14154 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14155}
14156function createForLoopParams({ value, key, index }, memoArgs = []) {
14157 return createParamsList([value, key, index, ...memoArgs]);
14158}
14159function createParamsList(args) {
14160 let i = args.length;
14161 while (i--) {
14162 if (args[i])
14163 break;
14164 }
14165 return args
14166 .slice(0, i + 1)
14167 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14168}
14169
14170const defaultFallback = createSimpleExpression(`undefined`, false);
14171// A NodeTransform that:
14172// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14173// by transformExpression. This is only applied in non-browser builds with
14174// { prefixIdentifiers: true }.
14175// 2. Track v-slot depths so that we know a slot is inside another slot.
14176// Note the exit callback is executed before buildSlots() on the same node,
14177// so only nested slots see positive numbers.
14178const trackSlotScopes = (node, context) => {
14179 if (node.type === 1 /* ELEMENT */ &&
14180 (node.tagType === 1 /* COMPONENT */ ||
14181 node.tagType === 3 /* TEMPLATE */)) {
14182 // We are only checking non-empty v-slot here
14183 // since we only care about slots that introduce scope variables.
14184 const vSlot = findDir(node, 'slot');
14185 if (vSlot) {
14186 vSlot.exp;
14187 context.scopes.vSlot++;
14188 return () => {
14189 context.scopes.vSlot--;
14190 };
14191 }
14192 }
14193};
14194const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14195// Instead of being a DirectiveTransform, v-slot processing is called during
14196// transformElement to build the slots object for a component.
14197function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14198 context.helper(WITH_CTX);
14199 const { children, loc } = node;
14200 const slotsProperties = [];
14201 const dynamicSlots = [];
14202 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14203 // since it likely uses a scope variable.
14204 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14205 // 1. Check for slot with slotProps on component itself.
14206 // <Comp v-slot="{ prop }"/>
14207 const onComponentSlot = findDir(node, 'slot', true);
14208 if (onComponentSlot) {
14209 const { arg, exp } = onComponentSlot;
14210 if (arg && !isStaticExp(arg)) {
14211 hasDynamicSlots = true;
14212 }
14213 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14214 }
14215 // 2. Iterate through children and check for template slots
14216 // <template v-slot:foo="{ prop }">
14217 let hasTemplateSlots = false;
14218 let hasNamedDefaultSlot = false;
14219 const implicitDefaultChildren = [];
14220 const seenSlotNames = new Set();
14221 for (let i = 0; i < children.length; i++) {
14222 const slotElement = children[i];
14223 let slotDir;
14224 if (!isTemplateNode(slotElement) ||
14225 !(slotDir = findDir(slotElement, 'slot', true))) {
14226 // not a <template v-slot>, skip.
14227 if (slotElement.type !== 3 /* COMMENT */) {
14228 implicitDefaultChildren.push(slotElement);
14229 }
14230 continue;
14231 }
14232 if (onComponentSlot) {
14233 // already has on-component slot - this is incorrect usage.
14234 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14235 break;
14236 }
14237 hasTemplateSlots = true;
14238 const { children: slotChildren, loc: slotLoc } = slotElement;
14239 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14240 // check if name is dynamic.
14241 let staticSlotName;
14242 if (isStaticExp(slotName)) {
14243 staticSlotName = slotName ? slotName.content : `default`;
14244 }
14245 else {
14246 hasDynamicSlots = true;
14247 }
14248 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14249 // check if this slot is conditional (v-if/v-for)
14250 let vIf;
14251 let vElse;
14252 let vFor;
14253 if ((vIf = findDir(slotElement, 'if'))) {
14254 hasDynamicSlots = true;
14255 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14256 }
14257 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14258 // find adjacent v-if
14259 let j = i;
14260 let prev;
14261 while (j--) {
14262 prev = children[j];
14263 if (prev.type !== 3 /* COMMENT */) {
14264 break;
14265 }
14266 }
14267 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14268 // remove node
14269 children.splice(i, 1);
14270 i--;
14271 // attach this slot to previous conditional
14272 let conditional = dynamicSlots[dynamicSlots.length - 1];
14273 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14274 conditional = conditional.alternate;
14275 }
14276 conditional.alternate = vElse.exp
14277 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14278 : buildDynamicSlot(slotName, slotFunction);
14279 }
14280 else {
14281 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14282 }
14283 }
14284 else if ((vFor = findDir(slotElement, 'for'))) {
14285 hasDynamicSlots = true;
14286 const parseResult = vFor.parseResult ||
14287 parseForExpression(vFor.exp, context);
14288 if (parseResult) {
14289 // Render the dynamic slots as an array and add it to the createSlot()
14290 // args. The runtime knows how to handle it appropriately.
14291 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14292 parseResult.source,
14293 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14294 ]));
14295 }
14296 else {
14297 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14298 }
14299 }
14300 else {
14301 // check duplicate static names
14302 if (staticSlotName) {
14303 if (seenSlotNames.has(staticSlotName)) {
14304 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14305 continue;
14306 }
14307 seenSlotNames.add(staticSlotName);
14308 if (staticSlotName === 'default') {
14309 hasNamedDefaultSlot = true;
14310 }
14311 }
14312 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14313 }
14314 }
14315 if (!onComponentSlot) {
14316 const buildDefaultSlotProperty = (props, children) => {
14317 const fn = buildSlotFn(props, children, loc);
14318 return createObjectProperty(`default`, fn);
14319 };
14320 if (!hasTemplateSlots) {
14321 // implicit default slot (on component)
14322 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14323 }
14324 else if (implicitDefaultChildren.length &&
14325 // #3766
14326 // with whitespace: 'preserve', whitespaces between slots will end up in
14327 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14328 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14329 // implicit default slot (mixed with named slots)
14330 if (hasNamedDefaultSlot) {
14331 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14332 }
14333 else {
14334 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14335 }
14336 }
14337 }
14338 const slotFlag = hasDynamicSlots
14339 ? 2 /* DYNAMIC */
14340 : hasForwardedSlots(node.children)
14341 ? 3 /* FORWARDED */
14342 : 1 /* STABLE */;
14343 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14344 // 2 = compiled but dynamic = can skip normalization, but must run diff
14345 // 1 = compiled and static = can skip normalization AND diff as optimized
14346 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14347 if (dynamicSlots.length) {
14348 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14349 slots,
14350 createArrayExpression(dynamicSlots)
14351 ]);
14352 }
14353 return {
14354 slots,
14355 hasDynamicSlots
14356 };
14357}
14358function buildDynamicSlot(name, fn) {
14359 return createObjectExpression([
14360 createObjectProperty(`name`, name),
14361 createObjectProperty(`fn`, fn)
14362 ]);
14363}
14364function hasForwardedSlots(children) {
14365 for (let i = 0; i < children.length; i++) {
14366 const child = children[i];
14367 switch (child.type) {
14368 case 1 /* ELEMENT */:
14369 if (child.tagType === 2 /* SLOT */ ||
14370 hasForwardedSlots(child.children)) {
14371 return true;
14372 }
14373 break;
14374 case 9 /* IF */:
14375 if (hasForwardedSlots(child.branches))
14376 return true;
14377 break;
14378 case 10 /* IF_BRANCH */:
14379 case 11 /* FOR */:
14380 if (hasForwardedSlots(child.children))
14381 return true;
14382 break;
14383 }
14384 }
14385 return false;
14386}
14387function isNonWhitespaceContent(node) {
14388 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14389 return true;
14390 return node.type === 2 /* TEXT */
14391 ? !!node.content.trim()
14392 : isNonWhitespaceContent(node.content);
14393}
14394
14395// some directive transforms (e.g. v-model) may return a symbol for runtime
14396// import, which should be used instead of a resolveDirective call.
14397const directiveImportMap = new WeakMap();
14398// generate a JavaScript AST for this element's codegen
14399const transformElement = (node, context) => {
14400 // perform the work on exit, after all child expressions have been
14401 // processed and merged.
14402 return function postTransformElement() {
14403 node = context.currentNode;
14404 if (!(node.type === 1 /* ELEMENT */ &&
14405 (node.tagType === 0 /* ELEMENT */ ||
14406 node.tagType === 1 /* COMPONENT */))) {
14407 return;
14408 }
14409 const { tag, props } = node;
14410 const isComponent = node.tagType === 1 /* COMPONENT */;
14411 // The goal of the transform is to create a codegenNode implementing the
14412 // VNodeCall interface.
14413 let vnodeTag = isComponent
14414 ? resolveComponentType(node, context)
14415 : `"${tag}"`;
14416 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14417 let vnodeProps;
14418 let vnodeChildren;
14419 let vnodePatchFlag;
14420 let patchFlag = 0;
14421 let vnodeDynamicProps;
14422 let dynamicPropNames;
14423 let vnodeDirectives;
14424 let shouldUseBlock =
14425 // dynamic component may resolve to plain elements
14426 isDynamicComponent ||
14427 vnodeTag === TELEPORT ||
14428 vnodeTag === SUSPENSE ||
14429 (!isComponent &&
14430 // <svg> and <foreignObject> must be forced into blocks so that block
14431 // updates inside get proper isSVG flag at runtime. (#639, #643)
14432 // This is technically web-specific, but splitting the logic out of core
14433 // leads to too much unnecessary complexity.
14434 (tag === 'svg' ||
14435 tag === 'foreignObject' ||
14436 // #938: elements with dynamic keys should be forced into blocks
14437 findProp(node, 'key', true)));
14438 // props
14439 if (props.length > 0) {
14440 const propsBuildResult = buildProps(node, context);
14441 vnodeProps = propsBuildResult.props;
14442 patchFlag = propsBuildResult.patchFlag;
14443 dynamicPropNames = propsBuildResult.dynamicPropNames;
14444 const directives = propsBuildResult.directives;
14445 vnodeDirectives =
14446 directives && directives.length
14447 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14448 : undefined;
14449 }
14450 // children
14451 if (node.children.length > 0) {
14452 if (vnodeTag === KEEP_ALIVE) {
14453 // Although a built-in component, we compile KeepAlive with raw children
14454 // instead of slot functions so that it can be used inside Transition
14455 // or other Transition-wrapping HOCs.
14456 // To ensure correct updates with block optimizations, we need to:
14457 // 1. Force keep-alive into a block. This avoids its children being
14458 // collected by a parent block.
14459 shouldUseBlock = true;
14460 // 2. Force keep-alive to always be updated, since it uses raw children.
14461 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14462 if (node.children.length > 1) {
14463 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14464 start: node.children[0].loc.start,
14465 end: node.children[node.children.length - 1].loc.end,
14466 source: ''
14467 }));
14468 }
14469 }
14470 const shouldBuildAsSlots = isComponent &&
14471 // Teleport is not a real component and has dedicated runtime handling
14472 vnodeTag !== TELEPORT &&
14473 // explained above.
14474 vnodeTag !== KEEP_ALIVE;
14475 if (shouldBuildAsSlots) {
14476 const { slots, hasDynamicSlots } = buildSlots(node, context);
14477 vnodeChildren = slots;
14478 if (hasDynamicSlots) {
14479 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14480 }
14481 }
14482 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14483 const child = node.children[0];
14484 const type = child.type;
14485 // check for dynamic text children
14486 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14487 type === 8 /* COMPOUND_EXPRESSION */;
14488 if (hasDynamicTextChild &&
14489 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14490 patchFlag |= 1 /* TEXT */;
14491 }
14492 // pass directly if the only child is a text node
14493 // (plain / interpolation / expression)
14494 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14495 vnodeChildren = child;
14496 }
14497 else {
14498 vnodeChildren = node.children;
14499 }
14500 }
14501 else {
14502 vnodeChildren = node.children;
14503 }
14504 }
14505 // patchFlag & dynamicPropNames
14506 if (patchFlag !== 0) {
14507 {
14508 if (patchFlag < 0) {
14509 // special flags (negative and mutually exclusive)
14510 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14511 }
14512 else {
14513 // bitwise flags
14514 const flagNames = Object.keys(PatchFlagNames)
14515 .map(Number)
14516 .filter(n => n > 0 && patchFlag & n)
14517 .map(n => PatchFlagNames[n])
14518 .join(`, `);
14519 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14520 }
14521 }
14522 if (dynamicPropNames && dynamicPropNames.length) {
14523 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14524 }
14525 }
14526 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14527 };
14528};
14529function resolveComponentType(node, context, ssr = false) {
14530 let { tag } = node;
14531 // 1. dynamic component
14532 const isExplicitDynamic = isComponentTag(tag);
14533 const isProp = findProp(node, 'is');
14534 if (isProp) {
14535 if (isExplicitDynamic ||
14536 (false )) {
14537 const exp = isProp.type === 6 /* ATTRIBUTE */
14538 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14539 : isProp.exp;
14540 if (exp) {
14541 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14542 exp
14543 ]);
14544 }
14545 }
14546 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14547 isProp.value.content.startsWith('vue:')) {
14548 // <button is="vue:xxx">
14549 // if not <component>, only is value that starts with "vue:" will be
14550 // treated as component by the parse phase and reach here, unless it's
14551 // compat mode where all is values are considered components
14552 tag = isProp.value.content.slice(4);
14553 }
14554 }
14555 // 1.5 v-is (TODO: Deprecate)
14556 const isDir = !isExplicitDynamic && findDir(node, 'is');
14557 if (isDir && isDir.exp) {
14558 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14559 isDir.exp
14560 ]);
14561 }
14562 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14563 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14564 if (builtIn) {
14565 // built-ins are simply fallthroughs / have special handling during ssr
14566 // so we don't need to import their runtime equivalents
14567 if (!ssr)
14568 context.helper(builtIn);
14569 return builtIn;
14570 }
14571 // 5. user component (resolve)
14572 context.helper(RESOLVE_COMPONENT);
14573 context.components.add(tag);
14574 return toValidAssetId(tag, `component`);
14575}
14576function buildProps(node, context, props = node.props, ssr = false) {
14577 const { tag, loc: elementLoc } = node;
14578 const isComponent = node.tagType === 1 /* COMPONENT */;
14579 let properties = [];
14580 const mergeArgs = [];
14581 const runtimeDirectives = [];
14582 // patchFlag analysis
14583 let patchFlag = 0;
14584 let hasRef = false;
14585 let hasClassBinding = false;
14586 let hasStyleBinding = false;
14587 let hasHydrationEventBinding = false;
14588 let hasDynamicKeys = false;
14589 let hasVnodeHook = false;
14590 const dynamicPropNames = [];
14591 const analyzePatchFlag = ({ key, value }) => {
14592 if (isStaticExp(key)) {
14593 const name = key.content;
14594 const isEventHandler = isOn(name);
14595 if (!isComponent &&
14596 isEventHandler &&
14597 // omit the flag for click handlers because hydration gives click
14598 // dedicated fast path.
14599 name.toLowerCase() !== 'onclick' &&
14600 // omit v-model handlers
14601 name !== 'onUpdate:modelValue' &&
14602 // omit onVnodeXXX hooks
14603 !isReservedProp(name)) {
14604 hasHydrationEventBinding = true;
14605 }
14606 if (isEventHandler && isReservedProp(name)) {
14607 hasVnodeHook = true;
14608 }
14609 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14610 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14611 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14612 getConstantType(value, context) > 0)) {
14613 // skip if the prop is a cached handler or has constant value
14614 return;
14615 }
14616 if (name === 'ref') {
14617 hasRef = true;
14618 }
14619 else if (name === 'class') {
14620 hasClassBinding = true;
14621 }
14622 else if (name === 'style') {
14623 hasStyleBinding = true;
14624 }
14625 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14626 dynamicPropNames.push(name);
14627 }
14628 // treat the dynamic class and style binding of the component as dynamic props
14629 if (isComponent &&
14630 (name === 'class' || name === 'style') &&
14631 !dynamicPropNames.includes(name)) {
14632 dynamicPropNames.push(name);
14633 }
14634 }
14635 else {
14636 hasDynamicKeys = true;
14637 }
14638 };
14639 for (let i = 0; i < props.length; i++) {
14640 // static attribute
14641 const prop = props[i];
14642 if (prop.type === 6 /* ATTRIBUTE */) {
14643 const { loc, name, value } = prop;
14644 let valueNode = createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc);
14645 if (name === 'ref') {
14646 hasRef = true;
14647 }
14648 // skip is on <component>, or is="vue:xxx"
14649 if (name === 'is' &&
14650 (isComponentTag(tag) ||
14651 (value && value.content.startsWith('vue:')) ||
14652 (false ))) {
14653 continue;
14654 }
14655 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), valueNode));
14656 }
14657 else {
14658 // directives
14659 const { name, arg, exp, loc } = prop;
14660 const isVBind = name === 'bind';
14661 const isVOn = name === 'on';
14662 // skip v-slot - it is handled by its dedicated transform.
14663 if (name === 'slot') {
14664 if (!isComponent) {
14665 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14666 }
14667 continue;
14668 }
14669 // skip v-once/v-memo - they are handled by dedicated transforms.
14670 if (name === 'once' || name === 'memo') {
14671 continue;
14672 }
14673 // skip v-is and :is on <component>
14674 if (name === 'is' ||
14675 (isVBind &&
14676 isBindKey(arg, 'is') &&
14677 (isComponentTag(tag) ||
14678 (false )))) {
14679 continue;
14680 }
14681 // skip v-on in SSR compilation
14682 if (isVOn && ssr) {
14683 continue;
14684 }
14685 // special case for v-bind and v-on with no argument
14686 if (!arg && (isVBind || isVOn)) {
14687 hasDynamicKeys = true;
14688 if (exp) {
14689 if (properties.length) {
14690 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14691 properties = [];
14692 }
14693 if (isVBind) {
14694 mergeArgs.push(exp);
14695 }
14696 else {
14697 // v-on="obj" -> toHandlers(obj)
14698 mergeArgs.push({
14699 type: 14 /* JS_CALL_EXPRESSION */,
14700 loc,
14701 callee: context.helper(TO_HANDLERS),
14702 arguments: [exp]
14703 });
14704 }
14705 }
14706 else {
14707 context.onError(createCompilerError(isVBind
14708 ? 34 /* X_V_BIND_NO_EXPRESSION */
14709 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14710 }
14711 continue;
14712 }
14713 const directiveTransform = context.directiveTransforms[name];
14714 if (directiveTransform) {
14715 // has built-in directive transform.
14716 const { props, needRuntime } = directiveTransform(prop, node, context);
14717 !ssr && props.forEach(analyzePatchFlag);
14718 properties.push(...props);
14719 if (needRuntime) {
14720 runtimeDirectives.push(prop);
14721 if (isSymbol(needRuntime)) {
14722 directiveImportMap.set(prop, needRuntime);
14723 }
14724 }
14725 }
14726 else {
14727 // no built-in transform, this is a user custom directive.
14728 runtimeDirectives.push(prop);
14729 }
14730 }
14731 }
14732 let propsExpression = undefined;
14733 // has v-bind="object" or v-on="object", wrap with mergeProps
14734 if (mergeArgs.length) {
14735 if (properties.length) {
14736 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14737 }
14738 if (mergeArgs.length > 1) {
14739 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14740 }
14741 else {
14742 // single v-bind with nothing else - no need for a mergeProps call
14743 propsExpression = mergeArgs[0];
14744 }
14745 }
14746 else if (properties.length) {
14747 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14748 }
14749 // patchFlag analysis
14750 if (hasDynamicKeys) {
14751 patchFlag |= 16 /* FULL_PROPS */;
14752 }
14753 else {
14754 if (hasClassBinding && !isComponent) {
14755 patchFlag |= 2 /* CLASS */;
14756 }
14757 if (hasStyleBinding && !isComponent) {
14758 patchFlag |= 4 /* STYLE */;
14759 }
14760 if (dynamicPropNames.length) {
14761 patchFlag |= 8 /* PROPS */;
14762 }
14763 if (hasHydrationEventBinding) {
14764 patchFlag |= 32 /* HYDRATE_EVENTS */;
14765 }
14766 }
14767 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14768 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14769 patchFlag |= 512 /* NEED_PATCH */;
14770 }
14771 // pre-normalize props, SSR is skipped for now
14772 if (!context.inSSR && propsExpression) {
14773 switch (propsExpression.type) {
14774 case 15 /* JS_OBJECT_EXPRESSION */:
14775 // means that there is no v-bind,
14776 // but still need to deal with dynamic key binding
14777 let classKeyIndex = -1;
14778 let styleKeyIndex = -1;
14779 let hasDynamicKey = false;
14780 for (let i = 0; i < propsExpression.properties.length; i++) {
14781 const key = propsExpression.properties[i].key;
14782 if (isStaticExp(key)) {
14783 if (key.content === 'class') {
14784 classKeyIndex = i;
14785 }
14786 else if (key.content === 'style') {
14787 styleKeyIndex = i;
14788 }
14789 }
14790 else if (!key.isHandlerKey) {
14791 hasDynamicKey = true;
14792 }
14793 }
14794 const classProp = propsExpression.properties[classKeyIndex];
14795 const styleProp = propsExpression.properties[styleKeyIndex];
14796 // no dynamic key
14797 if (!hasDynamicKey) {
14798 if (classProp && !isStaticExp(classProp.value)) {
14799 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14800 }
14801 if (styleProp &&
14802 !isStaticExp(styleProp.value) &&
14803 // the static style is compiled into an object,
14804 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14805 (hasStyleBinding ||
14806 // v-bind:style and style both exist,
14807 // v-bind:style with static literal object
14808 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14809 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14810 }
14811 }
14812 else {
14813 // dynamic key binding, wrap with `normalizeProps`
14814 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14815 }
14816 break;
14817 case 14 /* JS_CALL_EXPRESSION */:
14818 // mergeProps call, do nothing
14819 break;
14820 default:
14821 // single v-bind
14822 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14823 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14824 propsExpression
14825 ])
14826 ]);
14827 break;
14828 }
14829 }
14830 return {
14831 props: propsExpression,
14832 directives: runtimeDirectives,
14833 patchFlag,
14834 dynamicPropNames
14835 };
14836}
14837// Dedupe props in an object literal.
14838// Literal duplicated attributes would have been warned during the parse phase,
14839// however, it's possible to encounter duplicated `onXXX` handlers with different
14840// modifiers. We also need to merge static and dynamic class / style attributes.
14841// - onXXX handlers / style: merge into array
14842// - class: merge into single expression with concatenation
14843function dedupeProperties(properties) {
14844 const knownProps = new Map();
14845 const deduped = [];
14846 for (let i = 0; i < properties.length; i++) {
14847 const prop = properties[i];
14848 // dynamic keys are always allowed
14849 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14850 deduped.push(prop);
14851 continue;
14852 }
14853 const name = prop.key.content;
14854 const existing = knownProps.get(name);
14855 if (existing) {
14856 if (name === 'style' || name === 'class' || name.startsWith('on')) {
14857 mergeAsArray$1(existing, prop);
14858 }
14859 // unexpected duplicate, should have emitted error during parse
14860 }
14861 else {
14862 knownProps.set(name, prop);
14863 deduped.push(prop);
14864 }
14865 }
14866 return deduped;
14867}
14868function mergeAsArray$1(existing, incoming) {
14869 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14870 existing.value.elements.push(incoming.value);
14871 }
14872 else {
14873 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14874 }
14875}
14876function buildDirectiveArgs(dir, context) {
14877 const dirArgs = [];
14878 const runtime = directiveImportMap.get(dir);
14879 if (runtime) {
14880 // built-in directive with runtime
14881 dirArgs.push(context.helperString(runtime));
14882 }
14883 else {
14884 {
14885 // inject statement for resolving directive
14886 context.helper(RESOLVE_DIRECTIVE);
14887 context.directives.add(dir.name);
14888 dirArgs.push(toValidAssetId(dir.name, `directive`));
14889 }
14890 }
14891 const { loc } = dir;
14892 if (dir.exp)
14893 dirArgs.push(dir.exp);
14894 if (dir.arg) {
14895 if (!dir.exp) {
14896 dirArgs.push(`void 0`);
14897 }
14898 dirArgs.push(dir.arg);
14899 }
14900 if (Object.keys(dir.modifiers).length) {
14901 if (!dir.arg) {
14902 if (!dir.exp) {
14903 dirArgs.push(`void 0`);
14904 }
14905 dirArgs.push(`void 0`);
14906 }
14907 const trueExpression = createSimpleExpression(`true`, false, loc);
14908 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14909 }
14910 return createArrayExpression(dirArgs, dir.loc);
14911}
14912function stringifyDynamicPropNames(props) {
14913 let propsNamesString = `[`;
14914 for (let i = 0, l = props.length; i < l; i++) {
14915 propsNamesString += JSON.stringify(props[i]);
14916 if (i < l - 1)
14917 propsNamesString += ', ';
14918 }
14919 return propsNamesString + `]`;
14920}
14921function isComponentTag(tag) {
14922 return tag[0].toLowerCase() + tag.slice(1) === 'component';
14923}
14924
14925const transformSlotOutlet = (node, context) => {
14926 if (isSlotOutlet(node)) {
14927 const { children, loc } = node;
14928 const { slotName, slotProps } = processSlotOutlet(node, context);
14929 const slotArgs = [
14930 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14931 slotName
14932 ];
14933 if (slotProps) {
14934 slotArgs.push(slotProps);
14935 }
14936 if (children.length) {
14937 if (!slotProps) {
14938 slotArgs.push(`{}`);
14939 }
14940 slotArgs.push(createFunctionExpression([], children, false, false, loc));
14941 }
14942 if (context.scopeId && !context.slotted) {
14943 if (!slotProps) {
14944 slotArgs.push(`{}`);
14945 }
14946 if (!children.length) {
14947 slotArgs.push(`undefined`);
14948 }
14949 slotArgs.push(`true`);
14950 }
14951 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14952 }
14953};
14954function processSlotOutlet(node, context) {
14955 let slotName = `"default"`;
14956 let slotProps = undefined;
14957 const nonNameProps = [];
14958 for (let i = 0; i < node.props.length; i++) {
14959 const p = node.props[i];
14960 if (p.type === 6 /* ATTRIBUTE */) {
14961 if (p.value) {
14962 if (p.name === 'name') {
14963 slotName = JSON.stringify(p.value.content);
14964 }
14965 else {
14966 p.name = camelize(p.name);
14967 nonNameProps.push(p);
14968 }
14969 }
14970 }
14971 else {
14972 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
14973 if (p.exp)
14974 slotName = p.exp;
14975 }
14976 else {
14977 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14978 p.arg.content = camelize(p.arg.content);
14979 }
14980 nonNameProps.push(p);
14981 }
14982 }
14983 }
14984 if (nonNameProps.length > 0) {
14985 const { props, directives } = buildProps(node, context, nonNameProps);
14986 slotProps = props;
14987 if (directives.length) {
14988 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14989 }
14990 }
14991 return {
14992 slotName,
14993 slotProps
14994 };
14995}
14996
14997const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
14998const transformOn = (dir, node, context, augmentor) => {
14999 const { loc, modifiers, arg } = dir;
15000 if (!dir.exp && !modifiers.length) {
15001 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
15002 }
15003 let eventName;
15004 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15005 if (arg.isStatic) {
15006 const rawName = arg.content;
15007 // for all event listeners, auto convert it to camelCase. See issue #2249
15008 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
15009 }
15010 else {
15011 // #2388
15012 eventName = createCompoundExpression([
15013 `${context.helperString(TO_HANDLER_KEY)}(`,
15014 arg,
15015 `)`
15016 ]);
15017 }
15018 }
15019 else {
15020 // already a compound expression.
15021 eventName = arg;
15022 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
15023 eventName.children.push(`)`);
15024 }
15025 // handler processing
15026 let exp = dir.exp;
15027 if (exp && !exp.content.trim()) {
15028 exp = undefined;
15029 }
15030 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
15031 if (exp) {
15032 const isMemberExp = isMemberExpression(exp.content);
15033 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
15034 const hasMultipleStatements = exp.content.includes(`;`);
15035 {
15036 validateBrowserExpression(exp, context, false, hasMultipleStatements);
15037 }
15038 if (isInlineStatement || (shouldCache && isMemberExp)) {
15039 // wrap inline statement in a function expression
15040 exp = createCompoundExpression([
15041 `${isInlineStatement
15042 ? `$event`
15043 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
15044 exp,
15045 hasMultipleStatements ? `}` : `)`
15046 ]);
15047 }
15048 }
15049 let ret = {
15050 props: [
15051 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
15052 ]
15053 };
15054 // apply extended compiler augmentor
15055 if (augmentor) {
15056 ret = augmentor(ret);
15057 }
15058 if (shouldCache) {
15059 // cache handlers so that it's always the same handler being passed down.
15060 // this avoids unnecessary re-renders when users use inline handlers on
15061 // components.
15062 ret.props[0].value = context.cache(ret.props[0].value);
15063 }
15064 // mark the key as handler for props normalization check
15065 ret.props.forEach(p => (p.key.isHandlerKey = true));
15066 return ret;
15067};
15068
15069// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
15070// codegen for the entire props object. This transform here is only for v-bind
15071// *with* args.
15072const transformBind = (dir, _node, context) => {
15073 const { exp, modifiers, loc } = dir;
15074 const arg = dir.arg;
15075 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
15076 arg.children.unshift(`(`);
15077 arg.children.push(`) || ""`);
15078 }
15079 else if (!arg.isStatic) {
15080 arg.content = `${arg.content} || ""`;
15081 }
15082 // .sync is replaced by v-model:arg
15083 if (modifiers.includes('camel')) {
15084 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15085 if (arg.isStatic) {
15086 arg.content = camelize(arg.content);
15087 }
15088 else {
15089 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
15090 }
15091 }
15092 else {
15093 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
15094 arg.children.push(`)`);
15095 }
15096 }
15097 if (!context.inSSR) {
15098 if (modifiers.includes('prop')) {
15099 injectPrefix(arg, '.');
15100 }
15101 if (modifiers.includes('attr')) {
15102 injectPrefix(arg, '^');
15103 }
15104 }
15105 if (!exp ||
15106 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
15107 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
15108 return {
15109 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
15110 };
15111 }
15112 return {
15113 props: [createObjectProperty(arg, exp)]
15114 };
15115};
15116const injectPrefix = (arg, prefix) => {
15117 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
15118 if (arg.isStatic) {
15119 arg.content = prefix + arg.content;
15120 }
15121 else {
15122 arg.content = `\`${prefix}\${${arg.content}}\``;
15123 }
15124 }
15125 else {
15126 arg.children.unshift(`'${prefix}' + (`);
15127 arg.children.push(`)`);
15128 }
15129};
15130
15131// Merge adjacent text nodes and expressions into a single expression
15132// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15133const transformText = (node, context) => {
15134 if (node.type === 0 /* ROOT */ ||
15135 node.type === 1 /* ELEMENT */ ||
15136 node.type === 11 /* FOR */ ||
15137 node.type === 10 /* IF_BRANCH */) {
15138 // perform the transform on node exit so that all expressions have already
15139 // been processed.
15140 return () => {
15141 const children = node.children;
15142 let currentContainer = undefined;
15143 let hasText = false;
15144 for (let i = 0; i < children.length; i++) {
15145 const child = children[i];
15146 if (isText(child)) {
15147 hasText = true;
15148 for (let j = i + 1; j < children.length; j++) {
15149 const next = children[j];
15150 if (isText(next)) {
15151 if (!currentContainer) {
15152 currentContainer = children[i] = {
15153 type: 8 /* COMPOUND_EXPRESSION */,
15154 loc: child.loc,
15155 children: [child]
15156 };
15157 }
15158 // merge adjacent text node into current
15159 currentContainer.children.push(` + `, next);
15160 children.splice(j, 1);
15161 j--;
15162 }
15163 else {
15164 currentContainer = undefined;
15165 break;
15166 }
15167 }
15168 }
15169 }
15170 if (!hasText ||
15171 // if this is a plain element with a single text child, leave it
15172 // as-is since the runtime has dedicated fast path for this by directly
15173 // setting textContent of the element.
15174 // for component root it's always normalized anyway.
15175 (children.length === 1 &&
15176 (node.type === 0 /* ROOT */ ||
15177 (node.type === 1 /* ELEMENT */ &&
15178 node.tagType === 0 /* ELEMENT */ &&
15179 // #3756
15180 // custom directives can potentially add DOM elements arbitrarily,
15181 // we need to avoid setting textContent of the element at runtime
15182 // to avoid accidentally overwriting the DOM elements added
15183 // by the user through custom directives.
15184 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15185 !context.directiveTransforms[p.name]) &&
15186 // in compat mode, <template> tags with no special directives
15187 // will be rendered as a fragment so its children must be
15188 // converted into vnodes.
15189 !(false ))))) {
15190 return;
15191 }
15192 // pre-convert text nodes into createTextVNode(text) calls to avoid
15193 // runtime normalization.
15194 for (let i = 0; i < children.length; i++) {
15195 const child = children[i];
15196 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15197 const callArgs = [];
15198 // createTextVNode defaults to single whitespace, so if it is a
15199 // single space the code could be an empty call to save bytes.
15200 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15201 callArgs.push(child);
15202 }
15203 // mark dynamic text with flag so it gets patched inside a block
15204 if (!context.ssr &&
15205 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15206 callArgs.push(1 /* TEXT */ +
15207 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15208 }
15209 children[i] = {
15210 type: 12 /* TEXT_CALL */,
15211 content: child,
15212 loc: child.loc,
15213 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15214 };
15215 }
15216 }
15217 };
15218 }
15219};
15220
15221const seen = new WeakSet();
15222const transformOnce = (node, context) => {
15223 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15224 if (seen.has(node) || context.inVOnce) {
15225 return;
15226 }
15227 seen.add(node);
15228 context.inVOnce = true;
15229 context.helper(SET_BLOCK_TRACKING);
15230 return () => {
15231 context.inVOnce = false;
15232 const cur = context.currentNode;
15233 if (cur.codegenNode) {
15234 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15235 }
15236 };
15237 }
15238};
15239
15240const transformModel = (dir, node, context) => {
15241 const { exp, arg } = dir;
15242 if (!exp) {
15243 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15244 return createTransformProps();
15245 }
15246 const rawExp = exp.loc.source;
15247 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15248 // im SFC <script setup> inline mode, the exp may have been transformed into
15249 // _unref(exp)
15250 context.bindingMetadata[rawExp];
15251 const maybeRef = !true /* SETUP_CONST */;
15252 if (!expString.trim() || (!isMemberExpression(expString) && !maybeRef)) {
15253 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15254 return createTransformProps();
15255 }
15256 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15257 const eventName = arg
15258 ? isStaticExp(arg)
15259 ? `onUpdate:${arg.content}`
15260 : createCompoundExpression(['"onUpdate:" + ', arg])
15261 : `onUpdate:modelValue`;
15262 let assignmentExp;
15263 const eventArg = context.isTS ? `($event: any)` : `$event`;
15264 {
15265 assignmentExp = createCompoundExpression([
15266 `${eventArg} => (`,
15267 exp,
15268 ` = $event)`
15269 ]);
15270 }
15271 const props = [
15272 // modelValue: foo
15273 createObjectProperty(propName, dir.exp),
15274 // "onUpdate:modelValue": $event => (foo = $event)
15275 createObjectProperty(eventName, assignmentExp)
15276 ];
15277 // modelModifiers: { foo: true, "bar-baz": true }
15278 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15279 const modifiers = dir.modifiers
15280 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15281 .join(`, `);
15282 const modifiersKey = arg
15283 ? isStaticExp(arg)
15284 ? `${arg.content}Modifiers`
15285 : createCompoundExpression([arg, ' + "Modifiers"'])
15286 : `modelModifiers`;
15287 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15288 }
15289 return createTransformProps(props);
15290};
15291function createTransformProps(props = []) {
15292 return { props };
15293}
15294
15295const seen$1 = new WeakSet();
15296const transformMemo = (node, context) => {
15297 if (node.type === 1 /* ELEMENT */) {
15298 const dir = findDir(node, 'memo');
15299 if (!dir || seen$1.has(node)) {
15300 return;
15301 }
15302 seen$1.add(node);
15303 return () => {
15304 const codegenNode = node.codegenNode ||
15305 context.currentNode.codegenNode;
15306 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15307 // non-component sub tree should be turned into a block
15308 if (node.tagType !== 1 /* COMPONENT */) {
15309 makeBlock(codegenNode, context);
15310 }
15311 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15312 dir.exp,
15313 createFunctionExpression(undefined, codegenNode),
15314 `_cache`,
15315 String(context.cached++)
15316 ]);
15317 }
15318 };
15319 }
15320};
15321
15322function getBaseTransformPreset(prefixIdentifiers) {
15323 return [
15324 [
15325 transformOnce,
15326 transformIf,
15327 transformMemo,
15328 transformFor,
15329 ...([]),
15330 ...([transformExpression]
15331 ),
15332 transformSlotOutlet,
15333 transformElement,
15334 trackSlotScopes,
15335 transformText
15336 ],
15337 {
15338 on: transformOn,
15339 bind: transformBind,
15340 model: transformModel
15341 }
15342 ];
15343}
15344// we name it `baseCompile` so that higher order compilers like
15345// @vue/compiler-dom can export `compile` while re-exporting everything else.
15346function baseCompile(template, options = {}) {
15347 const onError = options.onError || defaultOnError;
15348 const isModuleMode = options.mode === 'module';
15349 /* istanbul ignore if */
15350 {
15351 if (options.prefixIdentifiers === true) {
15352 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15353 }
15354 else if (isModuleMode) {
15355 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15356 }
15357 }
15358 const prefixIdentifiers = !true ;
15359 if (options.cacheHandlers) {
15360 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15361 }
15362 if (options.scopeId && !isModuleMode) {
15363 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15364 }
15365 const ast = isString(template) ? baseParse(template, options) : template;
15366 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15367 transform(ast, extend({}, options, {
15368 prefixIdentifiers,
15369 nodeTransforms: [
15370 ...nodeTransforms,
15371 ...(options.nodeTransforms || []) // user transforms
15372 ],
15373 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15374 )
15375 }));
15376 return generate(ast, extend({}, options, {
15377 prefixIdentifiers
15378 }));
15379}
15380
15381const noopDirectiveTransform = () => ({ props: [] });
15382
15383const V_MODEL_RADIO = Symbol(`vModelRadio` );
15384const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15385const V_MODEL_TEXT = Symbol(`vModelText` );
15386const V_MODEL_SELECT = Symbol(`vModelSelect` );
15387const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15388const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15389const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15390const V_SHOW = Symbol(`vShow` );
15391const TRANSITION$1 = Symbol(`Transition` );
15392const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15393registerRuntimeHelpers({
15394 [V_MODEL_RADIO]: `vModelRadio`,
15395 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15396 [V_MODEL_TEXT]: `vModelText`,
15397 [V_MODEL_SELECT]: `vModelSelect`,
15398 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15399 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15400 [V_ON_WITH_KEYS]: `withKeys`,
15401 [V_SHOW]: `vShow`,
15402 [TRANSITION$1]: `Transition`,
15403 [TRANSITION_GROUP]: `TransitionGroup`
15404});
15405
15406/* eslint-disable no-restricted-globals */
15407let decoder;
15408function decodeHtmlBrowser(raw, asAttr = false) {
15409 if (!decoder) {
15410 decoder = document.createElement('div');
15411 }
15412 if (asAttr) {
15413 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15414 return decoder.children[0].getAttribute('foo');
15415 }
15416 else {
15417 decoder.innerHTML = raw;
15418 return decoder.textContent;
15419 }
15420}
15421
15422const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15423const parserOptions = {
15424 isVoidTag,
15425 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15426 isPreTag: tag => tag === 'pre',
15427 decodeEntities: decodeHtmlBrowser ,
15428 isBuiltInComponent: (tag) => {
15429 if (isBuiltInType(tag, `Transition`)) {
15430 return TRANSITION$1;
15431 }
15432 else if (isBuiltInType(tag, `TransitionGroup`)) {
15433 return TRANSITION_GROUP;
15434 }
15435 },
15436 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15437 getNamespace(tag, parent) {
15438 let ns = parent ? parent.ns : 0 /* HTML */;
15439 if (parent && ns === 2 /* MATH_ML */) {
15440 if (parent.tag === 'annotation-xml') {
15441 if (tag === 'svg') {
15442 return 1 /* SVG */;
15443 }
15444 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15445 a.name === 'encoding' &&
15446 a.value != null &&
15447 (a.value.content === 'text/html' ||
15448 a.value.content === 'application/xhtml+xml'))) {
15449 ns = 0 /* HTML */;
15450 }
15451 }
15452 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15453 tag !== 'mglyph' &&
15454 tag !== 'malignmark') {
15455 ns = 0 /* HTML */;
15456 }
15457 }
15458 else if (parent && ns === 1 /* SVG */) {
15459 if (parent.tag === 'foreignObject' ||
15460 parent.tag === 'desc' ||
15461 parent.tag === 'title') {
15462 ns = 0 /* HTML */;
15463 }
15464 }
15465 if (ns === 0 /* HTML */) {
15466 if (tag === 'svg') {
15467 return 1 /* SVG */;
15468 }
15469 if (tag === 'math') {
15470 return 2 /* MATH_ML */;
15471 }
15472 }
15473 return ns;
15474 },
15475 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15476 getTextMode({ tag, ns }) {
15477 if (ns === 0 /* HTML */) {
15478 if (tag === 'textarea' || tag === 'title') {
15479 return 1 /* RCDATA */;
15480 }
15481 if (isRawTextContainer(tag)) {
15482 return 2 /* RAWTEXT */;
15483 }
15484 }
15485 return 0 /* DATA */;
15486 }
15487};
15488
15489// Parse inline CSS strings for static style attributes into an object.
15490// This is a NodeTransform since it works on the static `style` attribute and
15491// converts it into a dynamic equivalent:
15492// style="color: red" -> :style='{ "color": "red" }'
15493// It is then processed by `transformElement` and included in the generated
15494// props.
15495const transformStyle = node => {
15496 if (node.type === 1 /* ELEMENT */) {
15497 node.props.forEach((p, i) => {
15498 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15499 // replace p with an expression node
15500 node.props[i] = {
15501 type: 7 /* DIRECTIVE */,
15502 name: `bind`,
15503 arg: createSimpleExpression(`style`, true, p.loc),
15504 exp: parseInlineCSS(p.value.content, p.loc),
15505 modifiers: [],
15506 loc: p.loc
15507 };
15508 }
15509 });
15510 }
15511};
15512const parseInlineCSS = (cssText, loc) => {
15513 const normalized = parseStringStyle(cssText);
15514 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15515};
15516
15517function createDOMCompilerError(code, loc) {
15518 return createCompilerError(code, loc, DOMErrorMessages );
15519}
15520const DOMErrorMessages = {
15521 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15522 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15523 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15524 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15525 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15526 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15527 [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.`,
15528 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15529 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15530 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15531 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15532};
15533
15534const transformVHtml = (dir, node, context) => {
15535 const { exp, loc } = dir;
15536 if (!exp) {
15537 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15538 }
15539 if (node.children.length) {
15540 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15541 node.children.length = 0;
15542 }
15543 return {
15544 props: [
15545 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15546 ]
15547 };
15548};
15549
15550const transformVText = (dir, node, context) => {
15551 const { exp, loc } = dir;
15552 if (!exp) {
15553 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15554 }
15555 if (node.children.length) {
15556 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15557 node.children.length = 0;
15558 }
15559 return {
15560 props: [
15561 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15562 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15563 : createSimpleExpression('', true))
15564 ]
15565 };
15566};
15567
15568const transformModel$1 = (dir, node, context) => {
15569 const baseResult = transformModel(dir, node, context);
15570 // base transform has errors OR component v-model (only need props)
15571 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15572 return baseResult;
15573 }
15574 if (dir.arg) {
15575 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15576 }
15577 function checkDuplicatedValue() {
15578 const value = findProp(node, 'value');
15579 if (value) {
15580 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15581 }
15582 }
15583 const { tag } = node;
15584 const isCustomElement = context.isCustomElement(tag);
15585 if (tag === 'input' ||
15586 tag === 'textarea' ||
15587 tag === 'select' ||
15588 isCustomElement) {
15589 let directiveToUse = V_MODEL_TEXT;
15590 let isInvalidType = false;
15591 if (tag === 'input' || isCustomElement) {
15592 const type = findProp(node, `type`);
15593 if (type) {
15594 if (type.type === 7 /* DIRECTIVE */) {
15595 // :type="foo"
15596 directiveToUse = V_MODEL_DYNAMIC;
15597 }
15598 else if (type.value) {
15599 switch (type.value.content) {
15600 case 'radio':
15601 directiveToUse = V_MODEL_RADIO;
15602 break;
15603 case 'checkbox':
15604 directiveToUse = V_MODEL_CHECKBOX;
15605 break;
15606 case 'file':
15607 isInvalidType = true;
15608 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15609 break;
15610 default:
15611 // text type
15612 checkDuplicatedValue();
15613 break;
15614 }
15615 }
15616 }
15617 else if (hasDynamicKeyVBind(node)) {
15618 // element has bindings with dynamic keys, which can possibly contain
15619 // "type".
15620 directiveToUse = V_MODEL_DYNAMIC;
15621 }
15622 else {
15623 // text type
15624 checkDuplicatedValue();
15625 }
15626 }
15627 else if (tag === 'select') {
15628 directiveToUse = V_MODEL_SELECT;
15629 }
15630 else {
15631 // textarea
15632 checkDuplicatedValue();
15633 }
15634 // inject runtime directive
15635 // by returning the helper symbol via needRuntime
15636 // the import will replaced a resolveDirective call.
15637 if (!isInvalidType) {
15638 baseResult.needRuntime = context.helper(directiveToUse);
15639 }
15640 }
15641 else {
15642 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15643 }
15644 // native vmodel doesn't need the `modelValue` props since they are also
15645 // passed to the runtime as `binding.value`. removing it reduces code size.
15646 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15647 p.key.content === 'modelValue'));
15648 return baseResult;
15649};
15650
15651const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15652const isNonKeyModifier = /*#__PURE__*/ makeMap(
15653// event propagation management
15654`stop,prevent,self,` +
15655 // system modifiers + exact
15656 `ctrl,shift,alt,meta,exact,` +
15657 // mouse
15658 `middle`);
15659// left & right could be mouse or key modifiers based on event type
15660const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15661const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15662const resolveModifiers = (key, modifiers, context, loc) => {
15663 const keyModifiers = [];
15664 const nonKeyModifiers = [];
15665 const eventOptionModifiers = [];
15666 for (let i = 0; i < modifiers.length; i++) {
15667 const modifier = modifiers[i];
15668 if (isEventOptionModifier(modifier)) {
15669 // eventOptionModifiers: modifiers for addEventListener() options,
15670 // e.g. .passive & .capture
15671 eventOptionModifiers.push(modifier);
15672 }
15673 else {
15674 // runtimeModifiers: modifiers that needs runtime guards
15675 if (maybeKeyModifier(modifier)) {
15676 if (isStaticExp(key)) {
15677 if (isKeyboardEvent(key.content)) {
15678 keyModifiers.push(modifier);
15679 }
15680 else {
15681 nonKeyModifiers.push(modifier);
15682 }
15683 }
15684 else {
15685 keyModifiers.push(modifier);
15686 nonKeyModifiers.push(modifier);
15687 }
15688 }
15689 else {
15690 if (isNonKeyModifier(modifier)) {
15691 nonKeyModifiers.push(modifier);
15692 }
15693 else {
15694 keyModifiers.push(modifier);
15695 }
15696 }
15697 }
15698 }
15699 return {
15700 keyModifiers,
15701 nonKeyModifiers,
15702 eventOptionModifiers
15703 };
15704};
15705const transformClick = (key, event) => {
15706 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15707 return isStaticClick
15708 ? createSimpleExpression(event, true)
15709 : key.type !== 4 /* SIMPLE_EXPRESSION */
15710 ? createCompoundExpression([
15711 `(`,
15712 key,
15713 `) === "onClick" ? "${event}" : (`,
15714 key,
15715 `)`
15716 ])
15717 : key;
15718};
15719const transformOn$1 = (dir, node, context) => {
15720 return transformOn(dir, node, context, baseResult => {
15721 const { modifiers } = dir;
15722 if (!modifiers.length)
15723 return baseResult;
15724 let { key, value: handlerExp } = baseResult.props[0];
15725 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15726 // normalize click.right and click.middle since they don't actually fire
15727 if (nonKeyModifiers.includes('right')) {
15728 key = transformClick(key, `onContextmenu`);
15729 }
15730 if (nonKeyModifiers.includes('middle')) {
15731 key = transformClick(key, `onMouseup`);
15732 }
15733 if (nonKeyModifiers.length) {
15734 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15735 handlerExp,
15736 JSON.stringify(nonKeyModifiers)
15737 ]);
15738 }
15739 if (keyModifiers.length &&
15740 // if event name is dynamic, always wrap with keys guard
15741 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15742 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15743 handlerExp,
15744 JSON.stringify(keyModifiers)
15745 ]);
15746 }
15747 if (eventOptionModifiers.length) {
15748 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15749 key = isStaticExp(key)
15750 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15751 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15752 }
15753 return {
15754 props: [createObjectProperty(key, handlerExp)]
15755 };
15756 });
15757};
15758
15759const transformShow = (dir, node, context) => {
15760 const { exp, loc } = dir;
15761 if (!exp) {
15762 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15763 }
15764 return {
15765 props: [],
15766 needRuntime: context.helper(V_SHOW)
15767 };
15768};
15769
15770const warnTransitionChildren = (node, context) => {
15771 if (node.type === 1 /* ELEMENT */ &&
15772 node.tagType === 1 /* COMPONENT */) {
15773 const component = context.isBuiltInComponent(node.tag);
15774 if (component === TRANSITION$1) {
15775 return () => {
15776 if (node.children.length && hasMultipleChildren(node)) {
15777 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15778 start: node.children[0].loc.start,
15779 end: node.children[node.children.length - 1].loc.end,
15780 source: ''
15781 }));
15782 }
15783 };
15784 }
15785 }
15786};
15787function hasMultipleChildren(node) {
15788 // #1352 filter out potential comment nodes.
15789 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
15790 const child = children[0];
15791 return (children.length !== 1 ||
15792 child.type === 11 /* FOR */ ||
15793 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15794}
15795
15796const ignoreSideEffectTags = (node, context) => {
15797 if (node.type === 1 /* ELEMENT */ &&
15798 node.tagType === 0 /* ELEMENT */ &&
15799 (node.tag === 'script' || node.tag === 'style')) {
15800 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15801 context.removeNode();
15802 }
15803};
15804
15805const DOMNodeTransforms = [
15806 transformStyle,
15807 ...([warnTransitionChildren] )
15808];
15809const DOMDirectiveTransforms = {
15810 cloak: noopDirectiveTransform,
15811 html: transformVHtml,
15812 text: transformVText,
15813 model: transformModel$1,
15814 on: transformOn$1,
15815 show: transformShow
15816};
15817function compile$1(template, options = {}) {
15818 return baseCompile(template, extend({}, parserOptions, options, {
15819 nodeTransforms: [
15820 // ignore <script> and <tag>
15821 // this is not put inside DOMNodeTransforms because that list is used
15822 // by compiler-ssr to generate vnode fallback branches
15823 ignoreSideEffectTags,
15824 ...DOMNodeTransforms,
15825 ...(options.nodeTransforms || [])
15826 ],
15827 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15828 transformHoist: null
15829 }));
15830}
15831
15832// This entry is the "full-build" that includes both the runtime
15833{
15834 initDev();
15835}
15836const compileCache = Object.create(null);
15837function compileToFunction(template, options) {
15838 if (!isString(template)) {
15839 if (template.nodeType) {
15840 template = template.innerHTML;
15841 }
15842 else {
15843 warn$1(`invalid template option: `, template);
15844 return NOOP;
15845 }
15846 }
15847 const key = template;
15848 const cached = compileCache[key];
15849 if (cached) {
15850 return cached;
15851 }
15852 if (template[0] === '#') {
15853 const el = document.querySelector(template);
15854 if (!el) {
15855 warn$1(`Template element not found or is empty: ${template}`);
15856 }
15857 // __UNSAFE__
15858 // Reason: potential execution of JS expressions in in-DOM template.
15859 // The user must make sure the in-DOM template is trusted. If it's rendered
15860 // by the server, the template should not contain any user data.
15861 template = el ? el.innerHTML : ``;
15862 }
15863 const { code } = compile$1(template, extend({
15864 hoistStatic: true,
15865 onError: onError ,
15866 onWarn: e => onError(e, true)
15867 }, options));
15868 function onError(err, asWarning = false) {
15869 const message = asWarning
15870 ? err.message
15871 : `Template compilation error: ${err.message}`;
15872 const codeFrame = err.loc &&
15873 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15874 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15875 }
15876 // The wildcard import results in a huge object with every export
15877 // with keys that cannot be mangled, and can be quite heavy size-wise.
15878 // In the global build we know `Vue` is available globally so we can avoid
15879 // the wildcard object.
15880 const render = (new Function('Vue', code)(runtimeDom));
15881 render._rc = true;
15882 return (compileCache[key] = render);
15883}
15884registerRuntimeCompiler(compileToFunction);
15885
15886export { 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 };