UNPKG

602 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';
209/**
210 * Compiler only.
211 * Do NOT use in runtime code paths unless behind `true` flag.
212 */
213const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
214/**
215 * Compiler only.
216 * Do NOT use in runtime code paths unless behind `true` flag.
217 */
218const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
219/**
220 * Compiler only.
221 * Do NOT use in runtime code paths unless behind `true` flag.
222 */
223const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
224
225function looseCompareArrays(a, b) {
226 if (a.length !== b.length)
227 return false;
228 let equal = true;
229 for (let i = 0; equal && i < a.length; i++) {
230 equal = looseEqual(a[i], b[i]);
231 }
232 return equal;
233}
234function looseEqual(a, b) {
235 if (a === b)
236 return true;
237 let aValidType = isDate(a);
238 let bValidType = isDate(b);
239 if (aValidType || bValidType) {
240 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
241 }
242 aValidType = isArray(a);
243 bValidType = isArray(b);
244 if (aValidType || bValidType) {
245 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
246 }
247 aValidType = isObject(a);
248 bValidType = isObject(b);
249 if (aValidType || bValidType) {
250 /* istanbul ignore if: this if will probably never be called */
251 if (!aValidType || !bValidType) {
252 return false;
253 }
254 const aKeysCount = Object.keys(a).length;
255 const bKeysCount = Object.keys(b).length;
256 if (aKeysCount !== bKeysCount) {
257 return false;
258 }
259 for (const key in a) {
260 const aHasKey = a.hasOwnProperty(key);
261 const bHasKey = b.hasOwnProperty(key);
262 if ((aHasKey && !bHasKey) ||
263 (!aHasKey && bHasKey) ||
264 !looseEqual(a[key], b[key])) {
265 return false;
266 }
267 }
268 }
269 return String(a) === String(b);
270}
271function looseIndexOf(arr, val) {
272 return arr.findIndex(item => looseEqual(item, val));
273}
274
275/**
276 * For converting {{ interpolation }} values to displayed strings.
277 * @private
278 */
279const toDisplayString = (val) => {
280 return val == null
281 ? ''
282 : isArray(val) ||
283 (isObject(val) &&
284 (val.toString === objectToString || !isFunction(val.toString)))
285 ? JSON.stringify(val, replacer, 2)
286 : String(val);
287};
288const replacer = (_key, val) => {
289 // can't use isRef here since @vue/shared has no deps
290 if (val && val.__v_isRef) {
291 return replacer(_key, val.value);
292 }
293 else if (isMap(val)) {
294 return {
295 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
296 entries[`${key} =>`] = val;
297 return entries;
298 }, {})
299 };
300 }
301 else if (isSet(val)) {
302 return {
303 [`Set(${val.size})`]: [...val.values()]
304 };
305 }
306 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
307 return String(val);
308 }
309 return val;
310};
311
312const EMPTY_OBJ = Object.freeze({})
313 ;
314const EMPTY_ARR = Object.freeze([]) ;
315const NOOP = () => { };
316/**
317 * Always return false.
318 */
319const NO = () => false;
320const onRE = /^on[^a-z]/;
321const isOn = (key) => onRE.test(key);
322const isModelListener = (key) => key.startsWith('onUpdate:');
323const extend = Object.assign;
324const remove = (arr, el) => {
325 const i = arr.indexOf(el);
326 if (i > -1) {
327 arr.splice(i, 1);
328 }
329};
330const hasOwnProperty = Object.prototype.hasOwnProperty;
331const hasOwn = (val, key) => hasOwnProperty.call(val, key);
332const isArray = Array.isArray;
333const isMap = (val) => toTypeString(val) === '[object Map]';
334const isSet = (val) => toTypeString(val) === '[object Set]';
335const isDate = (val) => val instanceof Date;
336const isFunction = (val) => typeof val === 'function';
337const isString = (val) => typeof val === 'string';
338const isSymbol = (val) => typeof val === 'symbol';
339const isObject = (val) => val !== null && typeof val === 'object';
340const isPromise = (val) => {
341 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
342};
343const objectToString = Object.prototype.toString;
344const toTypeString = (value) => objectToString.call(value);
345const toRawType = (value) => {
346 // extract "RawType" from strings like "[object RawType]"
347 return toTypeString(value).slice(8, -1);
348};
349const isPlainObject = (val) => toTypeString(val) === '[object Object]';
350const isIntegerKey = (key) => isString(key) &&
351 key !== 'NaN' &&
352 key[0] !== '-' &&
353 '' + parseInt(key, 10) === key;
354const isReservedProp = /*#__PURE__*/ makeMap(
355// the leading comma is intentional so empty string "" is also included
356',key,ref,ref_for,ref_key,' +
357 'onVnodeBeforeMount,onVnodeMounted,' +
358 'onVnodeBeforeUpdate,onVnodeUpdated,' +
359 'onVnodeBeforeUnmount,onVnodeUnmounted');
360const cacheStringFunction = (fn) => {
361 const cache = Object.create(null);
362 return ((str) => {
363 const hit = cache[str];
364 return hit || (cache[str] = fn(str));
365 });
366};
367const camelizeRE = /-(\w)/g;
368/**
369 * @private
370 */
371const camelize = cacheStringFunction((str) => {
372 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
373});
374const hyphenateRE = /\B([A-Z])/g;
375/**
376 * @private
377 */
378const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
379/**
380 * @private
381 */
382const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
383/**
384 * @private
385 */
386const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
387// compare whether a value has changed, accounting for NaN.
388const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
389const invokeArrayFns = (fns, arg) => {
390 for (let i = 0; i < fns.length; i++) {
391 fns[i](arg);
392 }
393};
394const def = (obj, key, value) => {
395 Object.defineProperty(obj, key, {
396 configurable: true,
397 enumerable: false,
398 value
399 });
400};
401const toNumber = (val) => {
402 const n = parseFloat(val);
403 return isNaN(n) ? val : n;
404};
405let _globalThis;
406const getGlobalThis = () => {
407 return (_globalThis ||
408 (_globalThis =
409 typeof globalThis !== 'undefined'
410 ? globalThis
411 : typeof self !== 'undefined'
412 ? self
413 : typeof window !== 'undefined'
414 ? window
415 : typeof global !== 'undefined'
416 ? global
417 : {}));
418};
419
420function warn(msg, ...args) {
421 console.warn(`[Vue warn] ${msg}`, ...args);
422}
423
424let activeEffectScope;
425const effectScopeStack = [];
426class EffectScope {
427 constructor(detached = false) {
428 this.active = true;
429 this.effects = [];
430 this.cleanups = [];
431 if (!detached && activeEffectScope) {
432 this.parent = activeEffectScope;
433 this.index =
434 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
435 }
436 }
437 run(fn) {
438 if (this.active) {
439 try {
440 this.on();
441 return fn();
442 }
443 finally {
444 this.off();
445 }
446 }
447 else {
448 warn(`cannot run an inactive effect scope.`);
449 }
450 }
451 on() {
452 if (this.active) {
453 effectScopeStack.push(this);
454 activeEffectScope = this;
455 }
456 }
457 off() {
458 if (this.active) {
459 effectScopeStack.pop();
460 activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
461 }
462 }
463 stop(fromParent) {
464 if (this.active) {
465 this.effects.forEach(e => e.stop());
466 this.cleanups.forEach(cleanup => cleanup());
467 if (this.scopes) {
468 this.scopes.forEach(e => e.stop(true));
469 }
470 // nested scope, dereference from parent to avoid memory leaks
471 if (this.parent && !fromParent) {
472 // optimized O(1) removal
473 const last = this.parent.scopes.pop();
474 if (last && last !== this) {
475 this.parent.scopes[this.index] = last;
476 last.index = this.index;
477 }
478 }
479 this.active = false;
480 }
481 }
482}
483function effectScope(detached) {
484 return new EffectScope(detached);
485}
486function recordEffectScope(effect, scope) {
487 scope = scope || activeEffectScope;
488 if (scope && scope.active) {
489 scope.effects.push(effect);
490 }
491}
492function getCurrentScope() {
493 return activeEffectScope;
494}
495function onScopeDispose(fn) {
496 if (activeEffectScope) {
497 activeEffectScope.cleanups.push(fn);
498 }
499 else {
500 warn(`onScopeDispose() is called when there is no active effect scope` +
501 ` to be associated with.`);
502 }
503}
504
505const createDep = (effects) => {
506 const dep = new Set(effects);
507 dep.w = 0;
508 dep.n = 0;
509 return dep;
510};
511const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
512const newTracked = (dep) => (dep.n & trackOpBit) > 0;
513const initDepMarkers = ({ deps }) => {
514 if (deps.length) {
515 for (let i = 0; i < deps.length; i++) {
516 deps[i].w |= trackOpBit; // set was tracked
517 }
518 }
519};
520const finalizeDepMarkers = (effect) => {
521 const { deps } = effect;
522 if (deps.length) {
523 let ptr = 0;
524 for (let i = 0; i < deps.length; i++) {
525 const dep = deps[i];
526 if (wasTracked(dep) && !newTracked(dep)) {
527 dep.delete(effect);
528 }
529 else {
530 deps[ptr++] = dep;
531 }
532 // clear bits
533 dep.w &= ~trackOpBit;
534 dep.n &= ~trackOpBit;
535 }
536 deps.length = ptr;
537 }
538};
539
540const targetMap = new WeakMap();
541// The number of effects currently being tracked recursively.
542let effectTrackDepth = 0;
543let trackOpBit = 1;
544/**
545 * The bitwise track markers support at most 30 levels of recursion.
546 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
547 * When recursion depth is greater, fall back to using a full cleanup.
548 */
549const maxMarkerBits = 30;
550const effectStack = [];
551let activeEffect;
552const ITERATE_KEY = Symbol('iterate' );
553const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
554class ReactiveEffect {
555 constructor(fn, scheduler = null, scope) {
556 this.fn = fn;
557 this.scheduler = scheduler;
558 this.active = true;
559 this.deps = [];
560 recordEffectScope(this, scope);
561 }
562 run() {
563 if (!this.active) {
564 return this.fn();
565 }
566 if (!effectStack.length || !effectStack.includes(this)) {
567 try {
568 effectStack.push((activeEffect = this));
569 enableTracking();
570 trackOpBit = 1 << ++effectTrackDepth;
571 if (effectTrackDepth <= maxMarkerBits) {
572 initDepMarkers(this);
573 }
574 else {
575 cleanupEffect(this);
576 }
577 return this.fn();
578 }
579 finally {
580 if (effectTrackDepth <= maxMarkerBits) {
581 finalizeDepMarkers(this);
582 }
583 trackOpBit = 1 << --effectTrackDepth;
584 resetTracking();
585 effectStack.pop();
586 const n = effectStack.length;
587 activeEffect = n > 0 ? effectStack[n - 1] : undefined;
588 }
589 }
590 }
591 stop() {
592 if (this.active) {
593 cleanupEffect(this);
594 if (this.onStop) {
595 this.onStop();
596 }
597 this.active = false;
598 }
599 }
600}
601function cleanupEffect(effect) {
602 const { deps } = effect;
603 if (deps.length) {
604 for (let i = 0; i < deps.length; i++) {
605 deps[i].delete(effect);
606 }
607 deps.length = 0;
608 }
609}
610function effect(fn, options) {
611 if (fn.effect) {
612 fn = fn.effect.fn;
613 }
614 const _effect = new ReactiveEffect(fn);
615 if (options) {
616 extend(_effect, options);
617 if (options.scope)
618 recordEffectScope(_effect, options.scope);
619 }
620 if (!options || !options.lazy) {
621 _effect.run();
622 }
623 const runner = _effect.run.bind(_effect);
624 runner.effect = _effect;
625 return runner;
626}
627function stop(runner) {
628 runner.effect.stop();
629}
630let shouldTrack = true;
631const trackStack = [];
632function pauseTracking() {
633 trackStack.push(shouldTrack);
634 shouldTrack = false;
635}
636function enableTracking() {
637 trackStack.push(shouldTrack);
638 shouldTrack = true;
639}
640function resetTracking() {
641 const last = trackStack.pop();
642 shouldTrack = last === undefined ? true : last;
643}
644function track(target, type, key) {
645 if (!isTracking()) {
646 return;
647 }
648 let depsMap = targetMap.get(target);
649 if (!depsMap) {
650 targetMap.set(target, (depsMap = new Map()));
651 }
652 let dep = depsMap.get(key);
653 if (!dep) {
654 depsMap.set(key, (dep = createDep()));
655 }
656 const eventInfo = { effect: activeEffect, target, type, key }
657 ;
658 trackEffects(dep, eventInfo);
659}
660function isTracking() {
661 return shouldTrack && activeEffect !== undefined;
662}
663function trackEffects(dep, debuggerEventExtraInfo) {
664 let shouldTrack = false;
665 if (effectTrackDepth <= maxMarkerBits) {
666 if (!newTracked(dep)) {
667 dep.n |= trackOpBit; // set newly tracked
668 shouldTrack = !wasTracked(dep);
669 }
670 }
671 else {
672 // Full cleanup mode.
673 shouldTrack = !dep.has(activeEffect);
674 }
675 if (shouldTrack) {
676 dep.add(activeEffect);
677 activeEffect.deps.push(dep);
678 if (activeEffect.onTrack) {
679 activeEffect.onTrack(Object.assign({
680 effect: activeEffect
681 }, debuggerEventExtraInfo));
682 }
683 }
684}
685function trigger(target, type, key, newValue, oldValue, oldTarget) {
686 const depsMap = targetMap.get(target);
687 if (!depsMap) {
688 // never been tracked
689 return;
690 }
691 let deps = [];
692 if (type === "clear" /* CLEAR */) {
693 // collection being cleared
694 // trigger all effects for target
695 deps = [...depsMap.values()];
696 }
697 else if (key === 'length' && isArray(target)) {
698 depsMap.forEach((dep, key) => {
699 if (key === 'length' || key >= newValue) {
700 deps.push(dep);
701 }
702 });
703 }
704 else {
705 // schedule runs for SET | ADD | DELETE
706 if (key !== void 0) {
707 deps.push(depsMap.get(key));
708 }
709 // also run for iteration key on ADD | DELETE | Map.SET
710 switch (type) {
711 case "add" /* ADD */:
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 else if (isIntegerKey(key)) {
719 // new index added to array -> length changes
720 deps.push(depsMap.get('length'));
721 }
722 break;
723 case "delete" /* DELETE */:
724 if (!isArray(target)) {
725 deps.push(depsMap.get(ITERATE_KEY));
726 if (isMap(target)) {
727 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
728 }
729 }
730 break;
731 case "set" /* SET */:
732 if (isMap(target)) {
733 deps.push(depsMap.get(ITERATE_KEY));
734 }
735 break;
736 }
737 }
738 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
739 ;
740 if (deps.length === 1) {
741 if (deps[0]) {
742 {
743 triggerEffects(deps[0], eventInfo);
744 }
745 }
746 }
747 else {
748 const effects = [];
749 for (const dep of deps) {
750 if (dep) {
751 effects.push(...dep);
752 }
753 }
754 {
755 triggerEffects(createDep(effects), eventInfo);
756 }
757 }
758}
759function triggerEffects(dep, debuggerEventExtraInfo) {
760 // spread into array for stabilization
761 for (const effect of isArray(dep) ? dep : [...dep]) {
762 if (effect !== activeEffect || effect.allowRecurse) {
763 if (effect.onTrigger) {
764 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
765 }
766 if (effect.scheduler) {
767 effect.scheduler();
768 }
769 else {
770 effect.run();
771 }
772 }
773 }
774}
775
776const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
777const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
778 .map(key => Symbol[key])
779 .filter(isSymbol));
780const get = /*#__PURE__*/ createGetter();
781const shallowGet = /*#__PURE__*/ createGetter(false, true);
782const readonlyGet = /*#__PURE__*/ createGetter(true);
783const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
784const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
785function createArrayInstrumentations() {
786 const instrumentations = {};
787 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
788 instrumentations[key] = function (...args) {
789 const arr = toRaw(this);
790 for (let i = 0, l = this.length; i < l; i++) {
791 track(arr, "get" /* GET */, i + '');
792 }
793 // we run the method using the original args first (which may be reactive)
794 const res = arr[key](...args);
795 if (res === -1 || res === false) {
796 // if that didn't work, run it again using raw values.
797 return arr[key](...args.map(toRaw));
798 }
799 else {
800 return res;
801 }
802 };
803 });
804 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
805 instrumentations[key] = function (...args) {
806 pauseTracking();
807 const res = toRaw(this)[key].apply(this, args);
808 resetTracking();
809 return res;
810 };
811 });
812 return instrumentations;
813}
814function createGetter(isReadonly = false, shallow = false) {
815 return function get(target, key, receiver) {
816 if (key === "__v_isReactive" /* IS_REACTIVE */) {
817 return !isReadonly;
818 }
819 else if (key === "__v_isReadonly" /* IS_READONLY */) {
820 return isReadonly;
821 }
822 else if (key === "__v_isShallow" /* IS_SHALLOW */) {
823 return shallow;
824 }
825 else if (key === "__v_raw" /* RAW */ &&
826 receiver ===
827 (isReadonly
828 ? shallow
829 ? shallowReadonlyMap
830 : readonlyMap
831 : shallow
832 ? shallowReactiveMap
833 : reactiveMap).get(target)) {
834 return target;
835 }
836 const targetIsArray = isArray(target);
837 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
838 return Reflect.get(arrayInstrumentations, key, receiver);
839 }
840 const res = Reflect.get(target, key, receiver);
841 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
842 return res;
843 }
844 if (!isReadonly) {
845 track(target, "get" /* GET */, key);
846 }
847 if (shallow) {
848 return res;
849 }
850 if (isRef(res)) {
851 // ref unwrapping - does not apply for Array + integer key.
852 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
853 return shouldUnwrap ? res.value : res;
854 }
855 if (isObject(res)) {
856 // Convert returned value into a proxy as well. we do the isObject check
857 // here to avoid invalid value warning. Also need to lazy access readonly
858 // and reactive here to avoid circular dependency.
859 return isReadonly ? readonly(res) : reactive(res);
860 }
861 return res;
862 };
863}
864const set = /*#__PURE__*/ createSetter();
865const shallowSet = /*#__PURE__*/ createSetter(true);
866function createSetter(shallow = false) {
867 return function set(target, key, value, receiver) {
868 let oldValue = target[key];
869 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
870 return false;
871 }
872 if (!shallow && !isReadonly(value)) {
873 if (!isShallow(value)) {
874 value = toRaw(value);
875 oldValue = toRaw(oldValue);
876 }
877 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
878 oldValue.value = value;
879 return true;
880 }
881 }
882 const hadKey = isArray(target) && isIntegerKey(key)
883 ? Number(key) < target.length
884 : hasOwn(target, key);
885 const result = Reflect.set(target, key, value, receiver);
886 // don't trigger if target is something up in the prototype chain of original
887 if (target === toRaw(receiver)) {
888 if (!hadKey) {
889 trigger(target, "add" /* ADD */, key, value);
890 }
891 else if (hasChanged(value, oldValue)) {
892 trigger(target, "set" /* SET */, key, value, oldValue);
893 }
894 }
895 return result;
896 };
897}
898function deleteProperty(target, key) {
899 const hadKey = hasOwn(target, key);
900 const oldValue = target[key];
901 const result = Reflect.deleteProperty(target, key);
902 if (result && hadKey) {
903 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
904 }
905 return result;
906}
907function has(target, key) {
908 const result = Reflect.has(target, key);
909 if (!isSymbol(key) || !builtInSymbols.has(key)) {
910 track(target, "has" /* HAS */, key);
911 }
912 return result;
913}
914function ownKeys(target) {
915 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
916 return Reflect.ownKeys(target);
917}
918const mutableHandlers = {
919 get,
920 set,
921 deleteProperty,
922 has,
923 ownKeys
924};
925const readonlyHandlers = {
926 get: readonlyGet,
927 set(target, key) {
928 {
929 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
930 }
931 return true;
932 },
933 deleteProperty(target, key) {
934 {
935 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
936 }
937 return true;
938 }
939};
940const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
941 get: shallowGet,
942 set: shallowSet
943});
944// Props handlers are special in the sense that it should not unwrap top-level
945// refs (in order to allow refs to be explicitly passed down), but should
946// retain the reactivity of the normal readonly object.
947const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
948 get: shallowReadonlyGet
949});
950
951const toShallow = (value) => value;
952const getProto = (v) => Reflect.getPrototypeOf(v);
953function get$1(target, key, isReadonly = false, isShallow = false) {
954 // #1772: readonly(reactive(Map)) should return readonly + reactive version
955 // of the value
956 target = target["__v_raw" /* RAW */];
957 const rawTarget = toRaw(target);
958 const rawKey = toRaw(key);
959 if (key !== rawKey) {
960 !isReadonly && track(rawTarget, "get" /* GET */, key);
961 }
962 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
963 const { has } = getProto(rawTarget);
964 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
965 if (has.call(rawTarget, key)) {
966 return wrap(target.get(key));
967 }
968 else if (has.call(rawTarget, rawKey)) {
969 return wrap(target.get(rawKey));
970 }
971 else if (target !== rawTarget) {
972 // #3602 readonly(reactive(Map))
973 // ensure that the nested reactive `Map` can do tracking for itself
974 target.get(key);
975 }
976}
977function has$1(key, isReadonly = false) {
978 const target = this["__v_raw" /* RAW */];
979 const rawTarget = toRaw(target);
980 const rawKey = toRaw(key);
981 if (key !== rawKey) {
982 !isReadonly && track(rawTarget, "has" /* HAS */, key);
983 }
984 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
985 return key === rawKey
986 ? target.has(key)
987 : target.has(key) || target.has(rawKey);
988}
989function size(target, isReadonly = false) {
990 target = target["__v_raw" /* RAW */];
991 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
992 return Reflect.get(target, 'size', target);
993}
994function add(value) {
995 value = toRaw(value);
996 const target = toRaw(this);
997 const proto = getProto(target);
998 const hadKey = proto.has.call(target, value);
999 if (!hadKey) {
1000 target.add(value);
1001 trigger(target, "add" /* ADD */, value, value);
1002 }
1003 return this;
1004}
1005function set$1(key, value) {
1006 value = toRaw(value);
1007 const target = toRaw(this);
1008 const { has, get } = getProto(target);
1009 let hadKey = has.call(target, key);
1010 if (!hadKey) {
1011 key = toRaw(key);
1012 hadKey = has.call(target, key);
1013 }
1014 else {
1015 checkIdentityKeys(target, has, key);
1016 }
1017 const oldValue = get.call(target, key);
1018 target.set(key, value);
1019 if (!hadKey) {
1020 trigger(target, "add" /* ADD */, key, value);
1021 }
1022 else if (hasChanged(value, oldValue)) {
1023 trigger(target, "set" /* SET */, key, value, oldValue);
1024 }
1025 return this;
1026}
1027function deleteEntry(key) {
1028 const target = toRaw(this);
1029 const { has, get } = getProto(target);
1030 let hadKey = has.call(target, key);
1031 if (!hadKey) {
1032 key = toRaw(key);
1033 hadKey = has.call(target, key);
1034 }
1035 else {
1036 checkIdentityKeys(target, has, key);
1037 }
1038 const oldValue = get ? get.call(target, key) : undefined;
1039 // forward the operation before queueing reactions
1040 const result = target.delete(key);
1041 if (hadKey) {
1042 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1043 }
1044 return result;
1045}
1046function clear() {
1047 const target = toRaw(this);
1048 const hadItems = target.size !== 0;
1049 const oldTarget = isMap(target)
1050 ? new Map(target)
1051 : new Set(target)
1052 ;
1053 // forward the operation before queueing reactions
1054 const result = target.clear();
1055 if (hadItems) {
1056 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1057 }
1058 return result;
1059}
1060function createForEach(isReadonly, isShallow) {
1061 return function forEach(callback, thisArg) {
1062 const observed = this;
1063 const target = observed["__v_raw" /* RAW */];
1064 const rawTarget = toRaw(target);
1065 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1066 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1067 return target.forEach((value, key) => {
1068 // important: make sure the callback is
1069 // 1. invoked with the reactive map as `this` and 3rd arg
1070 // 2. the value received should be a corresponding reactive/readonly.
1071 return callback.call(thisArg, wrap(value), wrap(key), observed);
1072 });
1073 };
1074}
1075function createIterableMethod(method, isReadonly, isShallow) {
1076 return function (...args) {
1077 const target = this["__v_raw" /* RAW */];
1078 const rawTarget = toRaw(target);
1079 const targetIsMap = isMap(rawTarget);
1080 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1081 const isKeyOnly = method === 'keys' && targetIsMap;
1082 const innerIterator = target[method](...args);
1083 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1084 !isReadonly &&
1085 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1086 // return a wrapped iterator which returns observed versions of the
1087 // values emitted from the real iterator
1088 return {
1089 // iterator protocol
1090 next() {
1091 const { value, done } = innerIterator.next();
1092 return done
1093 ? { value, done }
1094 : {
1095 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1096 done
1097 };
1098 },
1099 // iterable protocol
1100 [Symbol.iterator]() {
1101 return this;
1102 }
1103 };
1104 };
1105}
1106function createReadonlyMethod(type) {
1107 return function (...args) {
1108 {
1109 const key = args[0] ? `on key "${args[0]}" ` : ``;
1110 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1111 }
1112 return type === "delete" /* DELETE */ ? false : this;
1113 };
1114}
1115function createInstrumentations() {
1116 const mutableInstrumentations = {
1117 get(key) {
1118 return get$1(this, key);
1119 },
1120 get size() {
1121 return size(this);
1122 },
1123 has: has$1,
1124 add,
1125 set: set$1,
1126 delete: deleteEntry,
1127 clear,
1128 forEach: createForEach(false, false)
1129 };
1130 const shallowInstrumentations = {
1131 get(key) {
1132 return get$1(this, key, false, true);
1133 },
1134 get size() {
1135 return size(this);
1136 },
1137 has: has$1,
1138 add,
1139 set: set$1,
1140 delete: deleteEntry,
1141 clear,
1142 forEach: createForEach(false, true)
1143 };
1144 const readonlyInstrumentations = {
1145 get(key) {
1146 return get$1(this, key, true);
1147 },
1148 get size() {
1149 return size(this, true);
1150 },
1151 has(key) {
1152 return has$1.call(this, key, true);
1153 },
1154 add: createReadonlyMethod("add" /* ADD */),
1155 set: createReadonlyMethod("set" /* SET */),
1156 delete: createReadonlyMethod("delete" /* DELETE */),
1157 clear: createReadonlyMethod("clear" /* CLEAR */),
1158 forEach: createForEach(true, false)
1159 };
1160 const shallowReadonlyInstrumentations = {
1161 get(key) {
1162 return get$1(this, key, true, true);
1163 },
1164 get size() {
1165 return size(this, true);
1166 },
1167 has(key) {
1168 return has$1.call(this, key, true);
1169 },
1170 add: createReadonlyMethod("add" /* ADD */),
1171 set: createReadonlyMethod("set" /* SET */),
1172 delete: createReadonlyMethod("delete" /* DELETE */),
1173 clear: createReadonlyMethod("clear" /* CLEAR */),
1174 forEach: createForEach(true, true)
1175 };
1176 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1177 iteratorMethods.forEach(method => {
1178 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1179 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1180 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1181 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1182 });
1183 return [
1184 mutableInstrumentations,
1185 readonlyInstrumentations,
1186 shallowInstrumentations,
1187 shallowReadonlyInstrumentations
1188 ];
1189}
1190const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1191function createInstrumentationGetter(isReadonly, shallow) {
1192 const instrumentations = shallow
1193 ? isReadonly
1194 ? shallowReadonlyInstrumentations
1195 : shallowInstrumentations
1196 : isReadonly
1197 ? readonlyInstrumentations
1198 : mutableInstrumentations;
1199 return (target, key, receiver) => {
1200 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1201 return !isReadonly;
1202 }
1203 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1204 return isReadonly;
1205 }
1206 else if (key === "__v_raw" /* RAW */) {
1207 return target;
1208 }
1209 return Reflect.get(hasOwn(instrumentations, key) && key in target
1210 ? instrumentations
1211 : target, key, receiver);
1212 };
1213}
1214const mutableCollectionHandlers = {
1215 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1216};
1217const shallowCollectionHandlers = {
1218 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1219};
1220const readonlyCollectionHandlers = {
1221 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1222};
1223const shallowReadonlyCollectionHandlers = {
1224 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1225};
1226function checkIdentityKeys(target, has, key) {
1227 const rawKey = toRaw(key);
1228 if (rawKey !== key && has.call(target, rawKey)) {
1229 const type = toRawType(target);
1230 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1231 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1232 `which can lead to inconsistencies. ` +
1233 `Avoid differentiating between the raw and reactive versions ` +
1234 `of an object and only use the reactive version if possible.`);
1235 }
1236}
1237
1238const reactiveMap = new WeakMap();
1239const shallowReactiveMap = new WeakMap();
1240const readonlyMap = new WeakMap();
1241const shallowReadonlyMap = new WeakMap();
1242function targetTypeMap(rawType) {
1243 switch (rawType) {
1244 case 'Object':
1245 case 'Array':
1246 return 1 /* COMMON */;
1247 case 'Map':
1248 case 'Set':
1249 case 'WeakMap':
1250 case 'WeakSet':
1251 return 2 /* COLLECTION */;
1252 default:
1253 return 0 /* INVALID */;
1254 }
1255}
1256function getTargetType(value) {
1257 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1258 ? 0 /* INVALID */
1259 : targetTypeMap(toRawType(value));
1260}
1261function reactive(target) {
1262 // if trying to observe a readonly proxy, return the readonly version.
1263 if (isReadonly(target)) {
1264 return target;
1265 }
1266 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1267}
1268/**
1269 * Return a shallowly-reactive copy of the original object, where only the root
1270 * level properties are reactive. It also does not auto-unwrap refs (even at the
1271 * root level).
1272 */
1273function shallowReactive(target) {
1274 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1275}
1276/**
1277 * Creates a readonly copy of the original object. Note the returned copy is not
1278 * made reactive, but `readonly` can be called on an already reactive object.
1279 */
1280function readonly(target) {
1281 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1282}
1283/**
1284 * Returns a reactive-copy of the original object, where only the root level
1285 * properties are readonly, and does NOT unwrap refs nor recursively convert
1286 * returned properties.
1287 * This is used for creating the props proxy object for stateful components.
1288 */
1289function shallowReadonly(target) {
1290 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1291}
1292function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1293 if (!isObject(target)) {
1294 {
1295 console.warn(`value cannot be made reactive: ${String(target)}`);
1296 }
1297 return target;
1298 }
1299 // target is already a Proxy, return it.
1300 // exception: calling readonly() on a reactive object
1301 if (target["__v_raw" /* RAW */] &&
1302 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1303 return target;
1304 }
1305 // target already has corresponding Proxy
1306 const existingProxy = proxyMap.get(target);
1307 if (existingProxy) {
1308 return existingProxy;
1309 }
1310 // only a whitelist of value types can be observed.
1311 const targetType = getTargetType(target);
1312 if (targetType === 0 /* INVALID */) {
1313 return target;
1314 }
1315 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1316 proxyMap.set(target, proxy);
1317 return proxy;
1318}
1319function isReactive(value) {
1320 if (isReadonly(value)) {
1321 return isReactive(value["__v_raw" /* RAW */]);
1322 }
1323 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1324}
1325function isReadonly(value) {
1326 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1327}
1328function isShallow(value) {
1329 return !!(value && value["__v_isShallow" /* IS_SHALLOW */]);
1330}
1331function isProxy(value) {
1332 return isReactive(value) || isReadonly(value);
1333}
1334function toRaw(observed) {
1335 const raw = observed && observed["__v_raw" /* RAW */];
1336 return raw ? toRaw(raw) : observed;
1337}
1338function markRaw(value) {
1339 def(value, "__v_skip" /* SKIP */, true);
1340 return value;
1341}
1342const toReactive = (value) => isObject(value) ? reactive(value) : value;
1343const toReadonly = (value) => isObject(value) ? readonly(value) : value;
1344
1345function trackRefValue(ref) {
1346 if (isTracking()) {
1347 ref = toRaw(ref);
1348 if (!ref.dep) {
1349 ref.dep = createDep();
1350 }
1351 {
1352 trackEffects(ref.dep, {
1353 target: ref,
1354 type: "get" /* GET */,
1355 key: 'value'
1356 });
1357 }
1358 }
1359}
1360function triggerRefValue(ref, newVal) {
1361 ref = toRaw(ref);
1362 if (ref.dep) {
1363 {
1364 triggerEffects(ref.dep, {
1365 target: ref,
1366 type: "set" /* SET */,
1367 key: 'value',
1368 newValue: newVal
1369 });
1370 }
1371 }
1372}
1373function isRef(r) {
1374 return Boolean(r && r.__v_isRef === true);
1375}
1376function ref(value) {
1377 return createRef(value, false);
1378}
1379function shallowRef(value) {
1380 return createRef(value, true);
1381}
1382function createRef(rawValue, shallow) {
1383 if (isRef(rawValue)) {
1384 return rawValue;
1385 }
1386 return new RefImpl(rawValue, shallow);
1387}
1388class RefImpl {
1389 constructor(value, __v_isShallow) {
1390 this.__v_isShallow = __v_isShallow;
1391 this.dep = undefined;
1392 this.__v_isRef = true;
1393 this._rawValue = __v_isShallow ? value : toRaw(value);
1394 this._value = __v_isShallow ? value : toReactive(value);
1395 }
1396 get value() {
1397 trackRefValue(this);
1398 return this._value;
1399 }
1400 set value(newVal) {
1401 newVal = this.__v_isShallow ? newVal : toRaw(newVal);
1402 if (hasChanged(newVal, this._rawValue)) {
1403 this._rawValue = newVal;
1404 this._value = this.__v_isShallow ? newVal : toReactive(newVal);
1405 triggerRefValue(this, newVal);
1406 }
1407 }
1408}
1409function triggerRef(ref) {
1410 triggerRefValue(ref, ref.value );
1411}
1412function unref(ref) {
1413 return isRef(ref) ? ref.value : ref;
1414}
1415const shallowUnwrapHandlers = {
1416 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1417 set: (target, key, value, receiver) => {
1418 const oldValue = target[key];
1419 if (isRef(oldValue) && !isRef(value)) {
1420 oldValue.value = value;
1421 return true;
1422 }
1423 else {
1424 return Reflect.set(target, key, value, receiver);
1425 }
1426 }
1427};
1428function proxyRefs(objectWithRefs) {
1429 return isReactive(objectWithRefs)
1430 ? objectWithRefs
1431 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1432}
1433class CustomRefImpl {
1434 constructor(factory) {
1435 this.dep = undefined;
1436 this.__v_isRef = true;
1437 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1438 this._get = get;
1439 this._set = set;
1440 }
1441 get value() {
1442 return this._get();
1443 }
1444 set value(newVal) {
1445 this._set(newVal);
1446 }
1447}
1448function customRef(factory) {
1449 return new CustomRefImpl(factory);
1450}
1451function toRefs(object) {
1452 if (!isProxy(object)) {
1453 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1454 }
1455 const ret = isArray(object) ? new Array(object.length) : {};
1456 for (const key in object) {
1457 ret[key] = toRef(object, key);
1458 }
1459 return ret;
1460}
1461class ObjectRefImpl {
1462 constructor(_object, _key, _defaultValue) {
1463 this._object = _object;
1464 this._key = _key;
1465 this._defaultValue = _defaultValue;
1466 this.__v_isRef = true;
1467 }
1468 get value() {
1469 const val = this._object[this._key];
1470 return val === undefined ? this._defaultValue : val;
1471 }
1472 set value(newVal) {
1473 this._object[this._key] = newVal;
1474 }
1475}
1476function toRef(object, key, defaultValue) {
1477 const val = object[key];
1478 return isRef(val)
1479 ? val
1480 : new ObjectRefImpl(object, key, defaultValue);
1481}
1482
1483class ComputedRefImpl {
1484 constructor(getter, _setter, isReadonly, isSSR) {
1485 this._setter = _setter;
1486 this.dep = undefined;
1487 this.__v_isRef = true;
1488 this._dirty = true;
1489 this.effect = new ReactiveEffect(getter, () => {
1490 if (!this._dirty) {
1491 this._dirty = true;
1492 triggerRefValue(this);
1493 }
1494 });
1495 this.effect.computed = this;
1496 this.effect.active = this._cacheable = !isSSR;
1497 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1498 }
1499 get value() {
1500 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1501 const self = toRaw(this);
1502 trackRefValue(self);
1503 if (self._dirty || !self._cacheable) {
1504 self._dirty = false;
1505 self._value = self.effect.run();
1506 }
1507 return self._value;
1508 }
1509 set value(newValue) {
1510 this._setter(newValue);
1511 }
1512}
1513function computed(getterOrOptions, debugOptions, isSSR = false) {
1514 let getter;
1515 let setter;
1516 const onlyGetter = isFunction(getterOrOptions);
1517 if (onlyGetter) {
1518 getter = getterOrOptions;
1519 setter = () => {
1520 console.warn('Write operation failed: computed value is readonly');
1521 }
1522 ;
1523 }
1524 else {
1525 getter = getterOrOptions.get;
1526 setter = getterOrOptions.set;
1527 }
1528 const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
1529 if (debugOptions && !isSSR) {
1530 cRef.effect.onTrack = debugOptions.onTrack;
1531 cRef.effect.onTrigger = debugOptions.onTrigger;
1532 }
1533 return cRef;
1534}
1535
1536const stack = [];
1537function pushWarningContext(vnode) {
1538 stack.push(vnode);
1539}
1540function popWarningContext() {
1541 stack.pop();
1542}
1543function warn$1(msg, ...args) {
1544 // avoid props formatting or warn handler tracking deps that might be mutated
1545 // during patch, leading to infinite recursion.
1546 pauseTracking();
1547 const instance = stack.length ? stack[stack.length - 1].component : null;
1548 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1549 const trace = getComponentTrace();
1550 if (appWarnHandler) {
1551 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1552 msg + args.join(''),
1553 instance && instance.proxy,
1554 trace
1555 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1556 .join('\n'),
1557 trace
1558 ]);
1559 }
1560 else {
1561 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1562 /* istanbul ignore if */
1563 if (trace.length &&
1564 // avoid spamming console during tests
1565 !false) {
1566 warnArgs.push(`\n`, ...formatTrace(trace));
1567 }
1568 console.warn(...warnArgs);
1569 }
1570 resetTracking();
1571}
1572function getComponentTrace() {
1573 let currentVNode = stack[stack.length - 1];
1574 if (!currentVNode) {
1575 return [];
1576 }
1577 // we can't just use the stack because it will be incomplete during updates
1578 // that did not start from the root. Re-construct the parent chain using
1579 // instance parent pointers.
1580 const normalizedStack = [];
1581 while (currentVNode) {
1582 const last = normalizedStack[0];
1583 if (last && last.vnode === currentVNode) {
1584 last.recurseCount++;
1585 }
1586 else {
1587 normalizedStack.push({
1588 vnode: currentVNode,
1589 recurseCount: 0
1590 });
1591 }
1592 const parentInstance = currentVNode.component && currentVNode.component.parent;
1593 currentVNode = parentInstance && parentInstance.vnode;
1594 }
1595 return normalizedStack;
1596}
1597/* istanbul ignore next */
1598function formatTrace(trace) {
1599 const logs = [];
1600 trace.forEach((entry, i) => {
1601 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1602 });
1603 return logs;
1604}
1605function formatTraceEntry({ vnode, recurseCount }) {
1606 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1607 const isRoot = vnode.component ? vnode.component.parent == null : false;
1608 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1609 const close = `>` + postfix;
1610 return vnode.props
1611 ? [open, ...formatProps(vnode.props), close]
1612 : [open + close];
1613}
1614/* istanbul ignore next */
1615function formatProps(props) {
1616 const res = [];
1617 const keys = Object.keys(props);
1618 keys.slice(0, 3).forEach(key => {
1619 res.push(...formatProp(key, props[key]));
1620 });
1621 if (keys.length > 3) {
1622 res.push(` ...`);
1623 }
1624 return res;
1625}
1626/* istanbul ignore next */
1627function formatProp(key, value, raw) {
1628 if (isString(value)) {
1629 value = JSON.stringify(value);
1630 return raw ? value : [`${key}=${value}`];
1631 }
1632 else if (typeof value === 'number' ||
1633 typeof value === 'boolean' ||
1634 value == null) {
1635 return raw ? value : [`${key}=${value}`];
1636 }
1637 else if (isRef(value)) {
1638 value = formatProp(key, toRaw(value.value), true);
1639 return raw ? value : [`${key}=Ref<`, value, `>`];
1640 }
1641 else if (isFunction(value)) {
1642 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1643 }
1644 else {
1645 value = toRaw(value);
1646 return raw ? value : [`${key}=`, value];
1647 }
1648}
1649
1650const ErrorTypeStrings = {
1651 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
1652 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1653 ["c" /* CREATED */]: 'created hook',
1654 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1655 ["m" /* MOUNTED */]: 'mounted hook',
1656 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1657 ["u" /* UPDATED */]: 'updated',
1658 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1659 ["um" /* UNMOUNTED */]: 'unmounted hook',
1660 ["a" /* ACTIVATED */]: 'activated hook',
1661 ["da" /* DEACTIVATED */]: 'deactivated hook',
1662 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1663 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1664 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1665 [0 /* SETUP_FUNCTION */]: 'setup function',
1666 [1 /* RENDER_FUNCTION */]: 'render function',
1667 [2 /* WATCH_GETTER */]: 'watcher getter',
1668 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1669 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1670 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1671 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1672 [7 /* VNODE_HOOK */]: 'vnode hook',
1673 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1674 [9 /* TRANSITION_HOOK */]: 'transition hook',
1675 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1676 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1677 [12 /* FUNCTION_REF */]: 'ref function',
1678 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1679 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1680 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
1681};
1682function callWithErrorHandling(fn, instance, type, args) {
1683 let res;
1684 try {
1685 res = args ? fn(...args) : fn();
1686 }
1687 catch (err) {
1688 handleError(err, instance, type);
1689 }
1690 return res;
1691}
1692function callWithAsyncErrorHandling(fn, instance, type, args) {
1693 if (isFunction(fn)) {
1694 const res = callWithErrorHandling(fn, instance, type, args);
1695 if (res && isPromise(res)) {
1696 res.catch(err => {
1697 handleError(err, instance, type);
1698 });
1699 }
1700 return res;
1701 }
1702 const values = [];
1703 for (let i = 0; i < fn.length; i++) {
1704 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1705 }
1706 return values;
1707}
1708function handleError(err, instance, type, throwInDev = true) {
1709 const contextVNode = instance ? instance.vnode : null;
1710 if (instance) {
1711 let cur = instance.parent;
1712 // the exposed instance is the render proxy to keep it consistent with 2.x
1713 const exposedInstance = instance.proxy;
1714 // in production the hook receives only the error code
1715 const errorInfo = ErrorTypeStrings[type] ;
1716 while (cur) {
1717 const errorCapturedHooks = cur.ec;
1718 if (errorCapturedHooks) {
1719 for (let i = 0; i < errorCapturedHooks.length; i++) {
1720 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1721 return;
1722 }
1723 }
1724 }
1725 cur = cur.parent;
1726 }
1727 // app-level handling
1728 const appErrorHandler = instance.appContext.config.errorHandler;
1729 if (appErrorHandler) {
1730 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1731 return;
1732 }
1733 }
1734 logError(err, type, contextVNode, throwInDev);
1735}
1736function logError(err, type, contextVNode, throwInDev = true) {
1737 {
1738 const info = ErrorTypeStrings[type];
1739 if (contextVNode) {
1740 pushWarningContext(contextVNode);
1741 }
1742 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1743 if (contextVNode) {
1744 popWarningContext();
1745 }
1746 // crash in dev by default so it's more noticeable
1747 if (throwInDev) {
1748 throw err;
1749 }
1750 else {
1751 console.error(err);
1752 }
1753 }
1754}
1755
1756let isFlushing = false;
1757let isFlushPending = false;
1758const queue = [];
1759let flushIndex = 0;
1760const pendingPreFlushCbs = [];
1761let activePreFlushCbs = null;
1762let preFlushIndex = 0;
1763const pendingPostFlushCbs = [];
1764let activePostFlushCbs = null;
1765let postFlushIndex = 0;
1766const resolvedPromise = Promise.resolve();
1767let currentFlushPromise = null;
1768let currentPreFlushParentJob = null;
1769const RECURSION_LIMIT = 100;
1770function nextTick(fn) {
1771 const p = currentFlushPromise || resolvedPromise;
1772 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1773}
1774// #2768
1775// Use binary-search to find a suitable position in the queue,
1776// so that the queue maintains the increasing order of job's id,
1777// which can prevent the job from being skipped and also can avoid repeated patching.
1778function findInsertionIndex(id) {
1779 // the start index should be `flushIndex + 1`
1780 let start = flushIndex + 1;
1781 let end = queue.length;
1782 while (start < end) {
1783 const middle = (start + end) >>> 1;
1784 const middleJobId = getId(queue[middle]);
1785 middleJobId < id ? (start = middle + 1) : (end = middle);
1786 }
1787 return start;
1788}
1789function queueJob(job) {
1790 // the dedupe search uses the startIndex argument of Array.includes()
1791 // by default the search index includes the current job that is being run
1792 // so it cannot recursively trigger itself again.
1793 // if the job is a watch() callback, the search will start with a +1 index to
1794 // allow it recursively trigger itself - it is the user's responsibility to
1795 // ensure it doesn't end up in an infinite loop.
1796 if ((!queue.length ||
1797 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1798 job !== currentPreFlushParentJob) {
1799 if (job.id == null) {
1800 queue.push(job);
1801 }
1802 else {
1803 queue.splice(findInsertionIndex(job.id), 0, job);
1804 }
1805 queueFlush();
1806 }
1807}
1808function queueFlush() {
1809 if (!isFlushing && !isFlushPending) {
1810 isFlushPending = true;
1811 currentFlushPromise = resolvedPromise.then(flushJobs);
1812 }
1813}
1814function invalidateJob(job) {
1815 const i = queue.indexOf(job);
1816 if (i > flushIndex) {
1817 queue.splice(i, 1);
1818 }
1819}
1820function queueCb(cb, activeQueue, pendingQueue, index) {
1821 if (!isArray(cb)) {
1822 if (!activeQueue ||
1823 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1824 pendingQueue.push(cb);
1825 }
1826 }
1827 else {
1828 // if cb is an array, it is a component lifecycle hook which can only be
1829 // triggered by a job, which is already deduped in the main queue, so
1830 // we can skip duplicate check here to improve perf
1831 pendingQueue.push(...cb);
1832 }
1833 queueFlush();
1834}
1835function queuePreFlushCb(cb) {
1836 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1837}
1838function queuePostFlushCb(cb) {
1839 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1840}
1841function flushPreFlushCbs(seen, parentJob = null) {
1842 if (pendingPreFlushCbs.length) {
1843 currentPreFlushParentJob = parentJob;
1844 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1845 pendingPreFlushCbs.length = 0;
1846 {
1847 seen = seen || new Map();
1848 }
1849 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1850 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
1851 continue;
1852 }
1853 activePreFlushCbs[preFlushIndex]();
1854 }
1855 activePreFlushCbs = null;
1856 preFlushIndex = 0;
1857 currentPreFlushParentJob = null;
1858 // recursively flush until it drains
1859 flushPreFlushCbs(seen, parentJob);
1860 }
1861}
1862function flushPostFlushCbs(seen) {
1863 if (pendingPostFlushCbs.length) {
1864 const deduped = [...new Set(pendingPostFlushCbs)];
1865 pendingPostFlushCbs.length = 0;
1866 // #1947 already has active queue, nested flushPostFlushCbs call
1867 if (activePostFlushCbs) {
1868 activePostFlushCbs.push(...deduped);
1869 return;
1870 }
1871 activePostFlushCbs = deduped;
1872 {
1873 seen = seen || new Map();
1874 }
1875 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1876 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1877 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1878 continue;
1879 }
1880 activePostFlushCbs[postFlushIndex]();
1881 }
1882 activePostFlushCbs = null;
1883 postFlushIndex = 0;
1884 }
1885}
1886const getId = (job) => job.id == null ? Infinity : job.id;
1887function flushJobs(seen) {
1888 isFlushPending = false;
1889 isFlushing = true;
1890 {
1891 seen = seen || new Map();
1892 }
1893 flushPreFlushCbs(seen);
1894 // Sort queue before flush.
1895 // This ensures that:
1896 // 1. Components are updated from parent to child. (because parent is always
1897 // created before the child so its render effect will have smaller
1898 // priority number)
1899 // 2. If a component is unmounted during a parent component's update,
1900 // its update can be skipped.
1901 queue.sort((a, b) => getId(a) - getId(b));
1902 // conditional usage of checkRecursiveUpdate must be determined out of
1903 // try ... catch block since Rollup by default de-optimizes treeshaking
1904 // inside try-catch. This can leave all warning code unshaked. Although
1905 // they would get eventually shaken by a minifier like terser, some minifiers
1906 // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
1907 const check = (job) => checkRecursiveUpdates(seen, job)
1908 ;
1909 try {
1910 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1911 const job = queue[flushIndex];
1912 if (job && job.active !== false) {
1913 if (true && check(job)) {
1914 continue;
1915 }
1916 // console.log(`running:`, job.id)
1917 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1918 }
1919 }
1920 }
1921 finally {
1922 flushIndex = 0;
1923 queue.length = 0;
1924 flushPostFlushCbs(seen);
1925 isFlushing = false;
1926 currentFlushPromise = null;
1927 // some postFlushCb queued jobs!
1928 // keep flushing until it drains.
1929 if (queue.length ||
1930 pendingPreFlushCbs.length ||
1931 pendingPostFlushCbs.length) {
1932 flushJobs(seen);
1933 }
1934 }
1935}
1936function checkRecursiveUpdates(seen, fn) {
1937 if (!seen.has(fn)) {
1938 seen.set(fn, 1);
1939 }
1940 else {
1941 const count = seen.get(fn);
1942 if (count > RECURSION_LIMIT) {
1943 const instance = fn.ownerInstance;
1944 const componentName = instance && getComponentName(instance.type);
1945 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1946 `This means you have a reactive effect that is mutating its own ` +
1947 `dependencies and thus recursively triggering itself. Possible sources ` +
1948 `include component template, render function, updated hook or ` +
1949 `watcher source function.`);
1950 return true;
1951 }
1952 else {
1953 seen.set(fn, count + 1);
1954 }
1955 }
1956}
1957
1958/* eslint-disable no-restricted-globals */
1959let isHmrUpdating = false;
1960const hmrDirtyComponents = new Set();
1961// Expose the HMR runtime on the global object
1962// This makes it entirely tree-shakable without polluting the exports and makes
1963// it easier to be used in toolings like vue-loader
1964// Note: for a component to be eligible for HMR it also needs the __hmrId option
1965// to be set so that its instances can be registered / removed.
1966{
1967 getGlobalThis().__VUE_HMR_RUNTIME__ = {
1968 createRecord: tryWrap(createRecord),
1969 rerender: tryWrap(rerender),
1970 reload: tryWrap(reload)
1971 };
1972}
1973const map = new Map();
1974function registerHMR(instance) {
1975 const id = instance.type.__hmrId;
1976 let record = map.get(id);
1977 if (!record) {
1978 createRecord(id, instance.type);
1979 record = map.get(id);
1980 }
1981 record.instances.add(instance);
1982}
1983function unregisterHMR(instance) {
1984 map.get(instance.type.__hmrId).instances.delete(instance);
1985}
1986function createRecord(id, initialDef) {
1987 if (map.has(id)) {
1988 return false;
1989 }
1990 map.set(id, {
1991 initialDef: normalizeClassComponent(initialDef),
1992 instances: new Set()
1993 });
1994 return true;
1995}
1996function normalizeClassComponent(component) {
1997 return isClassComponent(component) ? component.__vccOpts : component;
1998}
1999function rerender(id, newRender) {
2000 const record = map.get(id);
2001 if (!record) {
2002 return;
2003 }
2004 // update initial record (for not-yet-rendered component)
2005 record.initialDef.render = newRender;
2006 [...record.instances].forEach(instance => {
2007 if (newRender) {
2008 instance.render = newRender;
2009 normalizeClassComponent(instance.type).render = newRender;
2010 }
2011 instance.renderCache = [];
2012 // this flag forces child components with slot content to update
2013 isHmrUpdating = true;
2014 instance.update();
2015 isHmrUpdating = false;
2016 });
2017}
2018function reload(id, newComp) {
2019 const record = map.get(id);
2020 if (!record)
2021 return;
2022 newComp = normalizeClassComponent(newComp);
2023 // update initial def (for not-yet-rendered components)
2024 updateComponentDef(record.initialDef, newComp);
2025 // create a snapshot which avoids the set being mutated during updates
2026 const instances = [...record.instances];
2027 for (const instance of instances) {
2028 const oldComp = normalizeClassComponent(instance.type);
2029 if (!hmrDirtyComponents.has(oldComp)) {
2030 // 1. Update existing comp definition to match new one
2031 if (oldComp !== record.initialDef) {
2032 updateComponentDef(oldComp, newComp);
2033 }
2034 // 2. mark definition dirty. This forces the renderer to replace the
2035 // component on patch.
2036 hmrDirtyComponents.add(oldComp);
2037 }
2038 // 3. invalidate options resolution cache
2039 instance.appContext.optionsCache.delete(instance.type);
2040 // 4. actually update
2041 if (instance.ceReload) {
2042 // custom element
2043 hmrDirtyComponents.add(oldComp);
2044 instance.ceReload(newComp.styles);
2045 hmrDirtyComponents.delete(oldComp);
2046 }
2047 else if (instance.parent) {
2048 // 4. Force the parent instance to re-render. This will cause all updated
2049 // components to be unmounted and re-mounted. Queue the update so that we
2050 // don't end up forcing the same parent to re-render multiple times.
2051 queueJob(instance.parent.update);
2052 // instance is the inner component of an async custom element
2053 // invoke to reset styles
2054 if (instance.parent.type.__asyncLoader &&
2055 instance.parent.ceReload) {
2056 instance.parent.ceReload(newComp.styles);
2057 }
2058 }
2059 else if (instance.appContext.reload) {
2060 // root instance mounted via createApp() has a reload method
2061 instance.appContext.reload();
2062 }
2063 else if (typeof window !== 'undefined') {
2064 // root instance inside tree created via raw render(). Force reload.
2065 window.location.reload();
2066 }
2067 else {
2068 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
2069 }
2070 }
2071 // 5. make sure to cleanup dirty hmr components after update
2072 queuePostFlushCb(() => {
2073 for (const instance of instances) {
2074 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
2075 }
2076 });
2077}
2078function updateComponentDef(oldComp, newComp) {
2079 extend(oldComp, newComp);
2080 for (const key in oldComp) {
2081 if (key !== '__file' && !(key in newComp)) {
2082 delete oldComp[key];
2083 }
2084 }
2085}
2086function tryWrap(fn) {
2087 return (id, arg) => {
2088 try {
2089 return fn(id, arg);
2090 }
2091 catch (e) {
2092 console.error(e);
2093 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
2094 `Full reload required.`);
2095 }
2096 };
2097}
2098
2099let devtools;
2100let buffer = [];
2101let devtoolsNotInstalled = false;
2102function emit(event, ...args) {
2103 if (devtools) {
2104 devtools.emit(event, ...args);
2105 }
2106 else if (!devtoolsNotInstalled) {
2107 buffer.push({ event, args });
2108 }
2109}
2110function setDevtoolsHook(hook, target) {
2111 var _a, _b;
2112 devtools = hook;
2113 if (devtools) {
2114 devtools.enabled = true;
2115 buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
2116 buffer = [];
2117 }
2118 else if (
2119 // handle late devtools injection - only do this if we are in an actual
2120 // browser environment to avoid the timer handle stalling test runner exit
2121 // (#4815)
2122 // eslint-disable-next-line no-restricted-globals
2123 typeof window !== 'undefined' &&
2124 // some envs mock window but not fully
2125 window.HTMLElement &&
2126 // also exclude jsdom
2127 !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
2128 const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
2129 target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
2130 replay.push((newHook) => {
2131 setDevtoolsHook(newHook, target);
2132 });
2133 // clear buffer after 3s - the user probably doesn't have devtools installed
2134 // at all, and keeping the buffer will cause memory leaks (#4738)
2135 setTimeout(() => {
2136 if (!devtools) {
2137 target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
2138 devtoolsNotInstalled = true;
2139 buffer = [];
2140 }
2141 }, 3000);
2142 }
2143 else {
2144 // non-browser env, assume not installed
2145 devtoolsNotInstalled = true;
2146 buffer = [];
2147 }
2148}
2149function devtoolsInitApp(app, version) {
2150 emit("app:init" /* APP_INIT */, app, version, {
2151 Fragment,
2152 Text,
2153 Comment,
2154 Static
2155 });
2156}
2157function devtoolsUnmountApp(app) {
2158 emit("app:unmount" /* APP_UNMOUNT */, app);
2159}
2160const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
2161const devtoolsComponentUpdated =
2162/*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
2163const devtoolsComponentRemoved =
2164/*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
2165function createDevtoolsComponentHook(hook) {
2166 return (component) => {
2167 emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
2168 };
2169}
2170const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
2171const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
2172function createDevtoolsPerformanceHook(hook) {
2173 return (component, type, time) => {
2174 emit(hook, component.appContext.app, component.uid, component, type, time);
2175 };
2176}
2177function devtoolsComponentEmit(component, event, params) {
2178 emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
2179}
2180
2181function emit$1(instance, event, ...rawArgs) {
2182 const props = instance.vnode.props || EMPTY_OBJ;
2183 {
2184 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2185 if (emitsOptions) {
2186 if (!(event in emitsOptions) &&
2187 !(false )) {
2188 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2189 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2190 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2191 }
2192 }
2193 else {
2194 const validator = emitsOptions[event];
2195 if (isFunction(validator)) {
2196 const isValid = validator(...rawArgs);
2197 if (!isValid) {
2198 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2199 }
2200 }
2201 }
2202 }
2203 }
2204 let args = rawArgs;
2205 const isModelListener = event.startsWith('update:');
2206 // for v-model update:xxx events, apply modifiers on args
2207 const modelArg = isModelListener && event.slice(7);
2208 if (modelArg && modelArg in props) {
2209 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2210 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2211 if (trim) {
2212 args = rawArgs.map(a => a.trim());
2213 }
2214 else if (number) {
2215 args = rawArgs.map(toNumber);
2216 }
2217 }
2218 {
2219 devtoolsComponentEmit(instance, event, args);
2220 }
2221 {
2222 const lowerCaseEvent = event.toLowerCase();
2223 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2224 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2225 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2226 `Note that HTML attributes are case-insensitive and you cannot use ` +
2227 `v-on to listen to camelCase events when using in-DOM templates. ` +
2228 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2229 }
2230 }
2231 let handlerName;
2232 let handler = props[(handlerName = toHandlerKey(event))] ||
2233 // also try camelCase event handler (#2249)
2234 props[(handlerName = toHandlerKey(camelize(event)))];
2235 // for v-model update:xxx events, also trigger kebab-case equivalent
2236 // for props passed via kebab-case
2237 if (!handler && isModelListener) {
2238 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2239 }
2240 if (handler) {
2241 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2242 }
2243 const onceHandler = props[handlerName + `Once`];
2244 if (onceHandler) {
2245 if (!instance.emitted) {
2246 instance.emitted = {};
2247 }
2248 else if (instance.emitted[handlerName]) {
2249 return;
2250 }
2251 instance.emitted[handlerName] = true;
2252 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2253 }
2254}
2255function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2256 const cache = appContext.emitsCache;
2257 const cached = cache.get(comp);
2258 if (cached !== undefined) {
2259 return cached;
2260 }
2261 const raw = comp.emits;
2262 let normalized = {};
2263 // apply mixin/extends props
2264 let hasExtends = false;
2265 if (!isFunction(comp)) {
2266 const extendEmits = (raw) => {
2267 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2268 if (normalizedFromExtend) {
2269 hasExtends = true;
2270 extend(normalized, normalizedFromExtend);
2271 }
2272 };
2273 if (!asMixin && appContext.mixins.length) {
2274 appContext.mixins.forEach(extendEmits);
2275 }
2276 if (comp.extends) {
2277 extendEmits(comp.extends);
2278 }
2279 if (comp.mixins) {
2280 comp.mixins.forEach(extendEmits);
2281 }
2282 }
2283 if (!raw && !hasExtends) {
2284 cache.set(comp, null);
2285 return null;
2286 }
2287 if (isArray(raw)) {
2288 raw.forEach(key => (normalized[key] = null));
2289 }
2290 else {
2291 extend(normalized, raw);
2292 }
2293 cache.set(comp, normalized);
2294 return normalized;
2295}
2296// Check if an incoming prop key is a declared emit event listener.
2297// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2298// both considered matched listeners.
2299function isEmitListener(options, key) {
2300 if (!options || !isOn(key)) {
2301 return false;
2302 }
2303 key = key.slice(2).replace(/Once$/, '');
2304 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2305 hasOwn(options, hyphenate(key)) ||
2306 hasOwn(options, key));
2307}
2308
2309/**
2310 * mark the current rendering instance for asset resolution (e.g.
2311 * resolveComponent, resolveDirective) during render
2312 */
2313let currentRenderingInstance = null;
2314let currentScopeId = null;
2315/**
2316 * Note: rendering calls maybe nested. The function returns the parent rendering
2317 * instance if present, which should be restored after the render is done:
2318 *
2319 * ```js
2320 * const prev = setCurrentRenderingInstance(i)
2321 * // ...render
2322 * setCurrentRenderingInstance(prev)
2323 * ```
2324 */
2325function setCurrentRenderingInstance(instance) {
2326 const prev = currentRenderingInstance;
2327 currentRenderingInstance = instance;
2328 currentScopeId = (instance && instance.type.__scopeId) || null;
2329 return prev;
2330}
2331/**
2332 * Set scope id when creating hoisted vnodes.
2333 * @private compiler helper
2334 */
2335function pushScopeId(id) {
2336 currentScopeId = id;
2337}
2338/**
2339 * Technically we no longer need this after 3.0.8 but we need to keep the same
2340 * API for backwards compat w/ code generated by compilers.
2341 * @private
2342 */
2343function popScopeId() {
2344 currentScopeId = null;
2345}
2346/**
2347 * Only for backwards compat
2348 * @private
2349 */
2350const withScopeId = (_id) => withCtx;
2351/**
2352 * Wrap a slot function to memoize current rendering instance
2353 * @private compiler helper
2354 */
2355function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2356) {
2357 if (!ctx)
2358 return fn;
2359 // already normalized
2360 if (fn._n) {
2361 return fn;
2362 }
2363 const renderFnWithContext = (...args) => {
2364 // If a user calls a compiled slot inside a template expression (#1745), it
2365 // can mess up block tracking, so by default we disable block tracking and
2366 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2367 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2368 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2369 if (renderFnWithContext._d) {
2370 setBlockTracking(-1);
2371 }
2372 const prevInstance = setCurrentRenderingInstance(ctx);
2373 const res = fn(...args);
2374 setCurrentRenderingInstance(prevInstance);
2375 if (renderFnWithContext._d) {
2376 setBlockTracking(1);
2377 }
2378 {
2379 devtoolsComponentUpdated(ctx);
2380 }
2381 return res;
2382 };
2383 // mark normalized to avoid duplicated wrapping
2384 renderFnWithContext._n = true;
2385 // mark this as compiled by default
2386 // this is used in vnode.ts -> normalizeChildren() to set the slot
2387 // rendering flag.
2388 renderFnWithContext._c = true;
2389 // disable block tracking by default
2390 renderFnWithContext._d = true;
2391 return renderFnWithContext;
2392}
2393
2394/**
2395 * dev only flag to track whether $attrs was used during render.
2396 * If $attrs was used during render then the warning for failed attrs
2397 * fallthrough can be suppressed.
2398 */
2399let accessedAttrs = false;
2400function markAttrsAccessed() {
2401 accessedAttrs = true;
2402}
2403function renderComponentRoot(instance) {
2404 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2405 let result;
2406 let fallthroughAttrs;
2407 const prev = setCurrentRenderingInstance(instance);
2408 {
2409 accessedAttrs = false;
2410 }
2411 try {
2412 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2413 // withProxy is a proxy with a different `has` trap only for
2414 // runtime-compiled render functions using `with` block.
2415 const proxyToUse = withProxy || proxy;
2416 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2417 fallthroughAttrs = attrs;
2418 }
2419 else {
2420 // functional
2421 const render = Component;
2422 // in dev, mark attrs accessed if optional props (attrs === props)
2423 if (true && attrs === props) {
2424 markAttrsAccessed();
2425 }
2426 result = normalizeVNode(render.length > 1
2427 ? render(props, true
2428 ? {
2429 get attrs() {
2430 markAttrsAccessed();
2431 return attrs;
2432 },
2433 slots,
2434 emit
2435 }
2436 : { attrs, slots, emit })
2437 : render(props, null /* we know it doesn't need it */));
2438 fallthroughAttrs = Component.props
2439 ? attrs
2440 : getFunctionalFallthrough(attrs);
2441 }
2442 }
2443 catch (err) {
2444 blockStack.length = 0;
2445 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2446 result = createVNode(Comment);
2447 }
2448 // attr merging
2449 // in dev mode, comments are preserved, and it's possible for a template
2450 // to have comments along side the root element which makes it a fragment
2451 let root = result;
2452 let setRoot = undefined;
2453 if (result.patchFlag > 0 &&
2454 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2455 [root, setRoot] = getChildRoot(result);
2456 }
2457 if (fallthroughAttrs && inheritAttrs !== false) {
2458 const keys = Object.keys(fallthroughAttrs);
2459 const { shapeFlag } = root;
2460 if (keys.length) {
2461 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2462 if (propsOptions && keys.some(isModelListener)) {
2463 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2464 // prop, it indicates this component expects to handle v-model and
2465 // it should not fallthrough.
2466 // related: #1543, #1643, #1989
2467 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2468 }
2469 root = cloneVNode(root, fallthroughAttrs);
2470 }
2471 else if (!accessedAttrs && root.type !== Comment) {
2472 const allAttrs = Object.keys(attrs);
2473 const eventAttrs = [];
2474 const extraAttrs = [];
2475 for (let i = 0, l = allAttrs.length; i < l; i++) {
2476 const key = allAttrs[i];
2477 if (isOn(key)) {
2478 // ignore v-model handlers when they fail to fallthrough
2479 if (!isModelListener(key)) {
2480 // remove `on`, lowercase first letter to reflect event casing
2481 // accurately
2482 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2483 }
2484 }
2485 else {
2486 extraAttrs.push(key);
2487 }
2488 }
2489 if (extraAttrs.length) {
2490 warn$1(`Extraneous non-props attributes (` +
2491 `${extraAttrs.join(', ')}) ` +
2492 `were passed to component but could not be automatically inherited ` +
2493 `because component renders fragment or text root nodes.`);
2494 }
2495 if (eventAttrs.length) {
2496 warn$1(`Extraneous non-emits event listeners (` +
2497 `${eventAttrs.join(', ')}) ` +
2498 `were passed to component but could not be automatically inherited ` +
2499 `because component renders fragment or text root nodes. ` +
2500 `If the listener is intended to be a component custom event listener only, ` +
2501 `declare it using the "emits" option.`);
2502 }
2503 }
2504 }
2505 }
2506 // inherit directives
2507 if (vnode.dirs) {
2508 if (!isElementRoot(root)) {
2509 warn$1(`Runtime directive used on component with non-element root node. ` +
2510 `The directives will not function as intended.`);
2511 }
2512 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2513 }
2514 // inherit transition data
2515 if (vnode.transition) {
2516 if (!isElementRoot(root)) {
2517 warn$1(`Component inside <Transition> renders non-element root node ` +
2518 `that cannot be animated.`);
2519 }
2520 root.transition = vnode.transition;
2521 }
2522 if (setRoot) {
2523 setRoot(root);
2524 }
2525 else {
2526 result = root;
2527 }
2528 setCurrentRenderingInstance(prev);
2529 return result;
2530}
2531/**
2532 * dev only
2533 * In dev mode, template root level comments are rendered, which turns the
2534 * template into a fragment root, but we need to locate the single element
2535 * root for attrs and scope id processing.
2536 */
2537const getChildRoot = (vnode) => {
2538 const rawChildren = vnode.children;
2539 const dynamicChildren = vnode.dynamicChildren;
2540 const childRoot = filterSingleRoot(rawChildren);
2541 if (!childRoot) {
2542 return [vnode, undefined];
2543 }
2544 const index = rawChildren.indexOf(childRoot);
2545 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2546 const setRoot = (updatedRoot) => {
2547 rawChildren[index] = updatedRoot;
2548 if (dynamicChildren) {
2549 if (dynamicIndex > -1) {
2550 dynamicChildren[dynamicIndex] = updatedRoot;
2551 }
2552 else if (updatedRoot.patchFlag > 0) {
2553 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2554 }
2555 }
2556 };
2557 return [normalizeVNode(childRoot), setRoot];
2558};
2559function filterSingleRoot(children) {
2560 let singleRoot;
2561 for (let i = 0; i < children.length; i++) {
2562 const child = children[i];
2563 if (isVNode(child)) {
2564 // ignore user comment
2565 if (child.type !== Comment || child.children === 'v-if') {
2566 if (singleRoot) {
2567 // has more than 1 non-comment child, return now
2568 return;
2569 }
2570 else {
2571 singleRoot = child;
2572 }
2573 }
2574 }
2575 else {
2576 return;
2577 }
2578 }
2579 return singleRoot;
2580}
2581const getFunctionalFallthrough = (attrs) => {
2582 let res;
2583 for (const key in attrs) {
2584 if (key === 'class' || key === 'style' || isOn(key)) {
2585 (res || (res = {}))[key] = attrs[key];
2586 }
2587 }
2588 return res;
2589};
2590const filterModelListeners = (attrs, props) => {
2591 const res = {};
2592 for (const key in attrs) {
2593 if (!isModelListener(key) || !(key.slice(9) in props)) {
2594 res[key] = attrs[key];
2595 }
2596 }
2597 return res;
2598};
2599const isElementRoot = (vnode) => {
2600 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2601 vnode.type === Comment // potential v-if branch switch
2602 );
2603};
2604function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2605 const { props: prevProps, children: prevChildren, component } = prevVNode;
2606 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2607 const emits = component.emitsOptions;
2608 // Parent component's render function was hot-updated. Since this may have
2609 // caused the child component's slots content to have changed, we need to
2610 // force the child to update as well.
2611 if ((prevChildren || nextChildren) && isHmrUpdating) {
2612 return true;
2613 }
2614 // force child update for runtime directive or transition on component vnode.
2615 if (nextVNode.dirs || nextVNode.transition) {
2616 return true;
2617 }
2618 if (optimized && patchFlag >= 0) {
2619 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2620 // slot content that references values that might have changed,
2621 // e.g. in a v-for
2622 return true;
2623 }
2624 if (patchFlag & 16 /* FULL_PROPS */) {
2625 if (!prevProps) {
2626 return !!nextProps;
2627 }
2628 // presence of this flag indicates props are always non-null
2629 return hasPropsChanged(prevProps, nextProps, emits);
2630 }
2631 else if (patchFlag & 8 /* PROPS */) {
2632 const dynamicProps = nextVNode.dynamicProps;
2633 for (let i = 0; i < dynamicProps.length; i++) {
2634 const key = dynamicProps[i];
2635 if (nextProps[key] !== prevProps[key] &&
2636 !isEmitListener(emits, key)) {
2637 return true;
2638 }
2639 }
2640 }
2641 }
2642 else {
2643 // this path is only taken by manually written render functions
2644 // so presence of any children leads to a forced update
2645 if (prevChildren || nextChildren) {
2646 if (!nextChildren || !nextChildren.$stable) {
2647 return true;
2648 }
2649 }
2650 if (prevProps === nextProps) {
2651 return false;
2652 }
2653 if (!prevProps) {
2654 return !!nextProps;
2655 }
2656 if (!nextProps) {
2657 return true;
2658 }
2659 return hasPropsChanged(prevProps, nextProps, emits);
2660 }
2661 return false;
2662}
2663function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2664 const nextKeys = Object.keys(nextProps);
2665 if (nextKeys.length !== Object.keys(prevProps).length) {
2666 return true;
2667 }
2668 for (let i = 0; i < nextKeys.length; i++) {
2669 const key = nextKeys[i];
2670 if (nextProps[key] !== prevProps[key] &&
2671 !isEmitListener(emitsOptions, key)) {
2672 return true;
2673 }
2674 }
2675 return false;
2676}
2677function updateHOCHostEl({ vnode, parent }, el // HostNode
2678) {
2679 while (parent && parent.subTree === vnode) {
2680 (vnode = parent.vnode).el = el;
2681 parent = parent.parent;
2682 }
2683}
2684
2685const isSuspense = (type) => type.__isSuspense;
2686// Suspense exposes a component-like API, and is treated like a component
2687// in the compiler, but internally it's a special built-in type that hooks
2688// directly into the renderer.
2689const SuspenseImpl = {
2690 name: 'Suspense',
2691 // In order to make Suspense tree-shakable, we need to avoid importing it
2692 // directly in the renderer. The renderer checks for the __isSuspense flag
2693 // on a vnode's type and calls the `process` method, passing in renderer
2694 // internals.
2695 __isSuspense: true,
2696 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2697 // platform-specific impl passed from renderer
2698 rendererInternals) {
2699 if (n1 == null) {
2700 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2701 }
2702 else {
2703 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2704 }
2705 },
2706 hydrate: hydrateSuspense,
2707 create: createSuspenseBoundary,
2708 normalize: normalizeSuspenseChildren
2709};
2710// Force-casted public typing for h and TSX props inference
2711const Suspense = (SuspenseImpl );
2712function triggerEvent(vnode, name) {
2713 const eventListener = vnode.props && vnode.props[name];
2714 if (isFunction(eventListener)) {
2715 eventListener();
2716 }
2717}
2718function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2719 const { p: patch, o: { createElement } } = rendererInternals;
2720 const hiddenContainer = createElement('div');
2721 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2722 // start mounting the content subtree in an off-dom container
2723 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2724 // now check if we have encountered any async deps
2725 if (suspense.deps > 0) {
2726 // has async
2727 // invoke @fallback event
2728 triggerEvent(vnode, 'onPending');
2729 triggerEvent(vnode, 'onFallback');
2730 // mount the fallback tree
2731 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2732 isSVG, slotScopeIds);
2733 setActiveBranch(suspense, vnode.ssFallback);
2734 }
2735 else {
2736 // Suspense has no async deps. Just resolve.
2737 suspense.resolve();
2738 }
2739}
2740function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2741 const suspense = (n2.suspense = n1.suspense);
2742 suspense.vnode = n2;
2743 n2.el = n1.el;
2744 const newBranch = n2.ssContent;
2745 const newFallback = n2.ssFallback;
2746 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2747 if (pendingBranch) {
2748 suspense.pendingBranch = newBranch;
2749 if (isSameVNodeType(newBranch, pendingBranch)) {
2750 // same root type but content may have changed.
2751 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2752 if (suspense.deps <= 0) {
2753 suspense.resolve();
2754 }
2755 else if (isInFallback) {
2756 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2757 isSVG, slotScopeIds, optimized);
2758 setActiveBranch(suspense, newFallback);
2759 }
2760 }
2761 else {
2762 // toggled before pending tree is resolved
2763 suspense.pendingId++;
2764 if (isHydrating) {
2765 // if toggled before hydration is finished, the current DOM tree is
2766 // no longer valid. set it as the active branch so it will be unmounted
2767 // when resolved
2768 suspense.isHydrating = false;
2769 suspense.activeBranch = pendingBranch;
2770 }
2771 else {
2772 unmount(pendingBranch, parentComponent, suspense);
2773 }
2774 // increment pending ID. this is used to invalidate async callbacks
2775 // reset suspense state
2776 suspense.deps = 0;
2777 // discard effects from pending branch
2778 suspense.effects.length = 0;
2779 // discard previous container
2780 suspense.hiddenContainer = createElement('div');
2781 if (isInFallback) {
2782 // already in fallback state
2783 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2784 if (suspense.deps <= 0) {
2785 suspense.resolve();
2786 }
2787 else {
2788 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2789 isSVG, slotScopeIds, optimized);
2790 setActiveBranch(suspense, newFallback);
2791 }
2792 }
2793 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2794 // toggled "back" to current active branch
2795 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2796 // force resolve
2797 suspense.resolve(true);
2798 }
2799 else {
2800 // switched to a 3rd branch
2801 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2802 if (suspense.deps <= 0) {
2803 suspense.resolve();
2804 }
2805 }
2806 }
2807 }
2808 else {
2809 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2810 // root did not change, just normal patch
2811 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2812 setActiveBranch(suspense, newBranch);
2813 }
2814 else {
2815 // root node toggled
2816 // invoke @pending event
2817 triggerEvent(n2, 'onPending');
2818 // mount pending branch in off-dom container
2819 suspense.pendingBranch = newBranch;
2820 suspense.pendingId++;
2821 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2822 if (suspense.deps <= 0) {
2823 // incoming branch has no async deps, resolve now.
2824 suspense.resolve();
2825 }
2826 else {
2827 const { timeout, pendingId } = suspense;
2828 if (timeout > 0) {
2829 setTimeout(() => {
2830 if (suspense.pendingId === pendingId) {
2831 suspense.fallback(newFallback);
2832 }
2833 }, timeout);
2834 }
2835 else if (timeout === 0) {
2836 suspense.fallback(newFallback);
2837 }
2838 }
2839 }
2840 }
2841}
2842let hasWarned = false;
2843function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2844 /* istanbul ignore if */
2845 if (!hasWarned) {
2846 hasWarned = true;
2847 // @ts-ignore `console.info` cannot be null error
2848 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2849 }
2850 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2851 const timeout = toNumber(vnode.props && vnode.props.timeout);
2852 const suspense = {
2853 vnode,
2854 parent,
2855 parentComponent,
2856 isSVG,
2857 container,
2858 hiddenContainer,
2859 anchor,
2860 deps: 0,
2861 pendingId: 0,
2862 timeout: typeof timeout === 'number' ? timeout : -1,
2863 activeBranch: null,
2864 pendingBranch: null,
2865 isInFallback: true,
2866 isHydrating,
2867 isUnmounted: false,
2868 effects: [],
2869 resolve(resume = false) {
2870 {
2871 if (!resume && !suspense.pendingBranch) {
2872 throw new Error(`suspense.resolve() is called without a pending branch.`);
2873 }
2874 if (suspense.isUnmounted) {
2875 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2876 }
2877 }
2878 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2879 if (suspense.isHydrating) {
2880 suspense.isHydrating = false;
2881 }
2882 else if (!resume) {
2883 const delayEnter = activeBranch &&
2884 pendingBranch.transition &&
2885 pendingBranch.transition.mode === 'out-in';
2886 if (delayEnter) {
2887 activeBranch.transition.afterLeave = () => {
2888 if (pendingId === suspense.pendingId) {
2889 move(pendingBranch, container, anchor, 0 /* ENTER */);
2890 }
2891 };
2892 }
2893 // this is initial anchor on mount
2894 let { anchor } = suspense;
2895 // unmount current active tree
2896 if (activeBranch) {
2897 // if the fallback tree was mounted, it may have been moved
2898 // as part of a parent suspense. get the latest anchor for insertion
2899 anchor = next(activeBranch);
2900 unmount(activeBranch, parentComponent, suspense, true);
2901 }
2902 if (!delayEnter) {
2903 // move content from off-dom container to actual container
2904 move(pendingBranch, container, anchor, 0 /* ENTER */);
2905 }
2906 }
2907 setActiveBranch(suspense, pendingBranch);
2908 suspense.pendingBranch = null;
2909 suspense.isInFallback = false;
2910 // flush buffered effects
2911 // check if there is a pending parent suspense
2912 let parent = suspense.parent;
2913 let hasUnresolvedAncestor = false;
2914 while (parent) {
2915 if (parent.pendingBranch) {
2916 // found a pending parent suspense, merge buffered post jobs
2917 // into that parent
2918 parent.effects.push(...effects);
2919 hasUnresolvedAncestor = true;
2920 break;
2921 }
2922 parent = parent.parent;
2923 }
2924 // no pending parent suspense, flush all jobs
2925 if (!hasUnresolvedAncestor) {
2926 queuePostFlushCb(effects);
2927 }
2928 suspense.effects = [];
2929 // invoke @resolve event
2930 triggerEvent(vnode, 'onResolve');
2931 },
2932 fallback(fallbackVNode) {
2933 if (!suspense.pendingBranch) {
2934 return;
2935 }
2936 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2937 // invoke @fallback event
2938 triggerEvent(vnode, 'onFallback');
2939 const anchor = next(activeBranch);
2940 const mountFallback = () => {
2941 if (!suspense.isInFallback) {
2942 return;
2943 }
2944 // mount the fallback tree
2945 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2946 isSVG, slotScopeIds, optimized);
2947 setActiveBranch(suspense, fallbackVNode);
2948 };
2949 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2950 if (delayEnter) {
2951 activeBranch.transition.afterLeave = mountFallback;
2952 }
2953 suspense.isInFallback = true;
2954 // unmount current active branch
2955 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2956 true // shouldRemove
2957 );
2958 if (!delayEnter) {
2959 mountFallback();
2960 }
2961 },
2962 move(container, anchor, type) {
2963 suspense.activeBranch &&
2964 move(suspense.activeBranch, container, anchor, type);
2965 suspense.container = container;
2966 },
2967 next() {
2968 return suspense.activeBranch && next(suspense.activeBranch);
2969 },
2970 registerDep(instance, setupRenderEffect) {
2971 const isInPendingSuspense = !!suspense.pendingBranch;
2972 if (isInPendingSuspense) {
2973 suspense.deps++;
2974 }
2975 const hydratedEl = instance.vnode.el;
2976 instance
2977 .asyncDep.catch(err => {
2978 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2979 })
2980 .then(asyncSetupResult => {
2981 // retry when the setup() promise resolves.
2982 // component may have been unmounted before resolve.
2983 if (instance.isUnmounted ||
2984 suspense.isUnmounted ||
2985 suspense.pendingId !== instance.suspenseId) {
2986 return;
2987 }
2988 // retry from this component
2989 instance.asyncResolved = true;
2990 const { vnode } = instance;
2991 {
2992 pushWarningContext(vnode);
2993 }
2994 handleSetupResult(instance, asyncSetupResult, false);
2995 if (hydratedEl) {
2996 // vnode may have been replaced if an update happened before the
2997 // async dep is resolved.
2998 vnode.el = hydratedEl;
2999 }
3000 const placeholder = !hydratedEl && instance.subTree.el;
3001 setupRenderEffect(instance, vnode,
3002 // component may have been moved before resolve.
3003 // if this is not a hydration, instance.subTree will be the comment
3004 // placeholder.
3005 parentNode(hydratedEl || instance.subTree.el),
3006 // anchor will not be used if this is hydration, so only need to
3007 // consider the comment placeholder case.
3008 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3009 if (placeholder) {
3010 remove(placeholder);
3011 }
3012 updateHOCHostEl(instance, vnode.el);
3013 {
3014 popWarningContext();
3015 }
3016 // only decrease deps count if suspense is not already resolved
3017 if (isInPendingSuspense && --suspense.deps === 0) {
3018 suspense.resolve();
3019 }
3020 });
3021 },
3022 unmount(parentSuspense, doRemove) {
3023 suspense.isUnmounted = true;
3024 if (suspense.activeBranch) {
3025 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3026 }
3027 if (suspense.pendingBranch) {
3028 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3029 }
3030 }
3031 };
3032 return suspense;
3033}
3034function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3035 /* eslint-disable no-restricted-globals */
3036 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3037 // there are two possible scenarios for server-rendered suspense:
3038 // - success: ssr content should be fully resolved
3039 // - failure: ssr content should be the fallback branch.
3040 // however, on the client we don't really know if it has failed or not
3041 // attempt to hydrate the DOM assuming it has succeeded, but we still
3042 // need to construct a suspense boundary first
3043 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3044 if (suspense.deps === 0) {
3045 suspense.resolve();
3046 }
3047 return result;
3048 /* eslint-enable no-restricted-globals */
3049}
3050function normalizeSuspenseChildren(vnode) {
3051 const { shapeFlag, children } = vnode;
3052 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
3053 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3054 vnode.ssFallback = isSlotChildren
3055 ? normalizeSuspenseSlot(children.fallback)
3056 : createVNode(Comment);
3057}
3058function normalizeSuspenseSlot(s) {
3059 let block;
3060 if (isFunction(s)) {
3061 const trackBlock = isBlockTreeEnabled && s._c;
3062 if (trackBlock) {
3063 // disableTracking: false
3064 // allow block tracking for compiled slots
3065 // (see ./componentRenderContext.ts)
3066 s._d = false;
3067 openBlock();
3068 }
3069 s = s();
3070 if (trackBlock) {
3071 s._d = true;
3072 block = currentBlock;
3073 closeBlock();
3074 }
3075 }
3076 if (isArray(s)) {
3077 const singleChild = filterSingleRoot(s);
3078 if (!singleChild) {
3079 warn$1(`<Suspense> slots expect a single root node.`);
3080 }
3081 s = singleChild;
3082 }
3083 s = normalizeVNode(s);
3084 if (block && !s.dynamicChildren) {
3085 s.dynamicChildren = block.filter(c => c !== s);
3086 }
3087 return s;
3088}
3089function queueEffectWithSuspense(fn, suspense) {
3090 if (suspense && suspense.pendingBranch) {
3091 if (isArray(fn)) {
3092 suspense.effects.push(...fn);
3093 }
3094 else {
3095 suspense.effects.push(fn);
3096 }
3097 }
3098 else {
3099 queuePostFlushCb(fn);
3100 }
3101}
3102function setActiveBranch(suspense, branch) {
3103 suspense.activeBranch = branch;
3104 const { vnode, parentComponent } = suspense;
3105 const el = (vnode.el = branch.el);
3106 // in case suspense is the root node of a component,
3107 // recursively update the HOC el
3108 if (parentComponent && parentComponent.subTree === vnode) {
3109 parentComponent.vnode.el = el;
3110 updateHOCHostEl(parentComponent, el);
3111 }
3112}
3113
3114function provide(key, value) {
3115 if (!currentInstance) {
3116 {
3117 warn$1(`provide() can only be used inside setup().`);
3118 }
3119 }
3120 else {
3121 let provides = currentInstance.provides;
3122 // by default an instance inherits its parent's provides object
3123 // but when it needs to provide values of its own, it creates its
3124 // own provides object using parent provides object as prototype.
3125 // this way in `inject` we can simply look up injections from direct
3126 // parent and let the prototype chain do the work.
3127 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3128 if (parentProvides === provides) {
3129 provides = currentInstance.provides = Object.create(parentProvides);
3130 }
3131 // TS doesn't allow symbol as index type
3132 provides[key] = value;
3133 }
3134}
3135function inject(key, defaultValue, treatDefaultAsFactory = false) {
3136 // fallback to `currentRenderingInstance` so that this can be called in
3137 // a functional component
3138 const instance = currentInstance || currentRenderingInstance;
3139 if (instance) {
3140 // #2400
3141 // to support `app.use` plugins,
3142 // fallback to appContext's `provides` if the instance is at root
3143 const provides = instance.parent == null
3144 ? instance.vnode.appContext && instance.vnode.appContext.provides
3145 : instance.parent.provides;
3146 if (provides && key in provides) {
3147 // TS doesn't allow symbol as index type
3148 return provides[key];
3149 }
3150 else if (arguments.length > 1) {
3151 return treatDefaultAsFactory && isFunction(defaultValue)
3152 ? defaultValue.call(instance.proxy)
3153 : defaultValue;
3154 }
3155 else {
3156 warn$1(`injection "${String(key)}" not found.`);
3157 }
3158 }
3159 else {
3160 warn$1(`inject() can only be used inside setup() or functional components.`);
3161 }
3162}
3163
3164// Simple effect.
3165function watchEffect(effect, options) {
3166 return doWatch(effect, null, options);
3167}
3168function watchPostEffect(effect, options) {
3169 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
3170 ));
3171}
3172function watchSyncEffect(effect, options) {
3173 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
3174 ));
3175}
3176// initial value for watchers to trigger on undefined initial values
3177const INITIAL_WATCHER_VALUE = {};
3178// implementation
3179function watch(source, cb, options) {
3180 if (!isFunction(cb)) {
3181 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3182 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3183 `supports \`watch(source, cb, options?) signature.`);
3184 }
3185 return doWatch(source, cb, options);
3186}
3187function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
3188 if (!cb) {
3189 if (immediate !== undefined) {
3190 warn$1(`watch() "immediate" option is only respected when using the ` +
3191 `watch(source, callback, options?) signature.`);
3192 }
3193 if (deep !== undefined) {
3194 warn$1(`watch() "deep" option is only respected when using the ` +
3195 `watch(source, callback, options?) signature.`);
3196 }
3197 }
3198 const warnInvalidSource = (s) => {
3199 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3200 `a reactive object, or an array of these types.`);
3201 };
3202 const instance = currentInstance;
3203 let getter;
3204 let forceTrigger = false;
3205 let isMultiSource = false;
3206 if (isRef(source)) {
3207 getter = () => source.value;
3208 forceTrigger = isShallow(source);
3209 }
3210 else if (isReactive(source)) {
3211 getter = () => source;
3212 deep = true;
3213 }
3214 else if (isArray(source)) {
3215 isMultiSource = true;
3216 forceTrigger = source.some(isReactive);
3217 getter = () => source.map(s => {
3218 if (isRef(s)) {
3219 return s.value;
3220 }
3221 else if (isReactive(s)) {
3222 return traverse(s);
3223 }
3224 else if (isFunction(s)) {
3225 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
3226 }
3227 else {
3228 warnInvalidSource(s);
3229 }
3230 });
3231 }
3232 else if (isFunction(source)) {
3233 if (cb) {
3234 // getter with cb
3235 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
3236 }
3237 else {
3238 // no cb -> simple effect
3239 getter = () => {
3240 if (instance && instance.isUnmounted) {
3241 return;
3242 }
3243 if (cleanup) {
3244 cleanup();
3245 }
3246 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]);
3247 };
3248 }
3249 }
3250 else {
3251 getter = NOOP;
3252 warnInvalidSource(source);
3253 }
3254 if (cb && deep) {
3255 const baseGetter = getter;
3256 getter = () => traverse(baseGetter());
3257 }
3258 let cleanup;
3259 let onCleanup = (fn) => {
3260 cleanup = effect.onStop = () => {
3261 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3262 };
3263 };
3264 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
3265 const job = () => {
3266 if (!effect.active) {
3267 return;
3268 }
3269 if (cb) {
3270 // watch(source, cb)
3271 const newValue = effect.run();
3272 if (deep ||
3273 forceTrigger ||
3274 (isMultiSource
3275 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3276 : hasChanged(newValue, oldValue)) ||
3277 (false )) {
3278 // cleanup before running cb again
3279 if (cleanup) {
3280 cleanup();
3281 }
3282 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3283 newValue,
3284 // pass undefined as the old value when it's changed for the first time
3285 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3286 onCleanup
3287 ]);
3288 oldValue = newValue;
3289 }
3290 }
3291 else {
3292 // watchEffect
3293 effect.run();
3294 }
3295 };
3296 // important: mark the job as a watcher callback so that scheduler knows
3297 // it is allowed to self-trigger (#1727)
3298 job.allowRecurse = !!cb;
3299 let scheduler;
3300 if (flush === 'sync') {
3301 scheduler = job; // the scheduler function gets called directly
3302 }
3303 else if (flush === 'post') {
3304 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3305 }
3306 else {
3307 // default: 'pre'
3308 scheduler = () => {
3309 if (!instance || instance.isMounted) {
3310 queuePreFlushCb(job);
3311 }
3312 else {
3313 // with 'pre' option, the first call must happen before
3314 // the component is mounted so it is called synchronously.
3315 job();
3316 }
3317 };
3318 }
3319 const effect = new ReactiveEffect(getter, scheduler);
3320 {
3321 effect.onTrack = onTrack;
3322 effect.onTrigger = onTrigger;
3323 }
3324 // initial run
3325 if (cb) {
3326 if (immediate) {
3327 job();
3328 }
3329 else {
3330 oldValue = effect.run();
3331 }
3332 }
3333 else if (flush === 'post') {
3334 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
3335 }
3336 else {
3337 effect.run();
3338 }
3339 return () => {
3340 effect.stop();
3341 if (instance && instance.scope) {
3342 remove(instance.scope.effects, effect);
3343 }
3344 };
3345}
3346// this.$watch
3347function instanceWatch(source, value, options) {
3348 const publicThis = this.proxy;
3349 const getter = isString(source)
3350 ? source.includes('.')
3351 ? createPathGetter(publicThis, source)
3352 : () => publicThis[source]
3353 : source.bind(publicThis, publicThis);
3354 let cb;
3355 if (isFunction(value)) {
3356 cb = value;
3357 }
3358 else {
3359 cb = value.handler;
3360 options = value;
3361 }
3362 const cur = currentInstance;
3363 setCurrentInstance(this);
3364 const res = doWatch(getter, cb.bind(publicThis), options);
3365 if (cur) {
3366 setCurrentInstance(cur);
3367 }
3368 else {
3369 unsetCurrentInstance();
3370 }
3371 return res;
3372}
3373function createPathGetter(ctx, path) {
3374 const segments = path.split('.');
3375 return () => {
3376 let cur = ctx;
3377 for (let i = 0; i < segments.length && cur; i++) {
3378 cur = cur[segments[i]];
3379 }
3380 return cur;
3381 };
3382}
3383function traverse(value, seen) {
3384 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
3385 return value;
3386 }
3387 seen = seen || new Set();
3388 if (seen.has(value)) {
3389 return value;
3390 }
3391 seen.add(value);
3392 if (isRef(value)) {
3393 traverse(value.value, seen);
3394 }
3395 else if (isArray(value)) {
3396 for (let i = 0; i < value.length; i++) {
3397 traverse(value[i], seen);
3398 }
3399 }
3400 else if (isSet(value) || isMap(value)) {
3401 value.forEach((v) => {
3402 traverse(v, seen);
3403 });
3404 }
3405 else if (isPlainObject(value)) {
3406 for (const key in value) {
3407 traverse(value[key], seen);
3408 }
3409 }
3410 return value;
3411}
3412
3413function useTransitionState() {
3414 const state = {
3415 isMounted: false,
3416 isLeaving: false,
3417 isUnmounting: false,
3418 leavingVNodes: new Map()
3419 };
3420 onMounted(() => {
3421 state.isMounted = true;
3422 });
3423 onBeforeUnmount(() => {
3424 state.isUnmounting = true;
3425 });
3426 return state;
3427}
3428const TransitionHookValidator = [Function, Array];
3429const BaseTransitionImpl = {
3430 name: `BaseTransition`,
3431 props: {
3432 mode: String,
3433 appear: Boolean,
3434 persisted: Boolean,
3435 // enter
3436 onBeforeEnter: TransitionHookValidator,
3437 onEnter: TransitionHookValidator,
3438 onAfterEnter: TransitionHookValidator,
3439 onEnterCancelled: TransitionHookValidator,
3440 // leave
3441 onBeforeLeave: TransitionHookValidator,
3442 onLeave: TransitionHookValidator,
3443 onAfterLeave: TransitionHookValidator,
3444 onLeaveCancelled: TransitionHookValidator,
3445 // appear
3446 onBeforeAppear: TransitionHookValidator,
3447 onAppear: TransitionHookValidator,
3448 onAfterAppear: TransitionHookValidator,
3449 onAppearCancelled: TransitionHookValidator
3450 },
3451 setup(props, { slots }) {
3452 const instance = getCurrentInstance();
3453 const state = useTransitionState();
3454 let prevTransitionKey;
3455 return () => {
3456 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3457 if (!children || !children.length) {
3458 return;
3459 }
3460 // warn multiple elements
3461 if (children.length > 1) {
3462 warn$1('<transition> can only be used on a single element or component. Use ' +
3463 '<transition-group> for lists.');
3464 }
3465 // there's no need to track reactivity for these props so use the raw
3466 // props for a bit better perf
3467 const rawProps = toRaw(props);
3468 const { mode } = rawProps;
3469 // check mode
3470 if (mode &&
3471 mode !== 'in-out' && mode !== 'out-in' && mode !== 'default') {
3472 warn$1(`invalid <transition> mode: ${mode}`);
3473 }
3474 // at this point children has a guaranteed length of 1.
3475 const child = children[0];
3476 if (state.isLeaving) {
3477 return emptyPlaceholder(child);
3478 }
3479 // in the case of <transition><keep-alive/></transition>, we need to
3480 // compare the type of the kept-alive children.
3481 const innerChild = getKeepAliveChild(child);
3482 if (!innerChild) {
3483 return emptyPlaceholder(child);
3484 }
3485 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3486 setTransitionHooks(innerChild, enterHooks);
3487 const oldChild = instance.subTree;
3488 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3489 let transitionKeyChanged = false;
3490 const { getTransitionKey } = innerChild.type;
3491 if (getTransitionKey) {
3492 const key = getTransitionKey();
3493 if (prevTransitionKey === undefined) {
3494 prevTransitionKey = key;
3495 }
3496 else if (key !== prevTransitionKey) {
3497 prevTransitionKey = key;
3498 transitionKeyChanged = true;
3499 }
3500 }
3501 // handle mode
3502 if (oldInnerChild &&
3503 oldInnerChild.type !== Comment &&
3504 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3505 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3506 // update old tree's hooks in case of dynamic transition
3507 setTransitionHooks(oldInnerChild, leavingHooks);
3508 // switching between different views
3509 if (mode === 'out-in') {
3510 state.isLeaving = true;
3511 // return placeholder node and queue update when leave finishes
3512 leavingHooks.afterLeave = () => {
3513 state.isLeaving = false;
3514 instance.update();
3515 };
3516 return emptyPlaceholder(child);
3517 }
3518 else if (mode === 'in-out' && innerChild.type !== Comment) {
3519 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3520 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3521 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3522 // early removal callback
3523 el._leaveCb = () => {
3524 earlyRemove();
3525 el._leaveCb = undefined;
3526 delete enterHooks.delayedLeave;
3527 };
3528 enterHooks.delayedLeave = delayedLeave;
3529 };
3530 }
3531 }
3532 return child;
3533 };
3534 }
3535};
3536// export the public type for h/tsx inference
3537// also to avoid inline import() in generated d.ts files
3538const BaseTransition = BaseTransitionImpl;
3539function getLeavingNodesForType(state, vnode) {
3540 const { leavingVNodes } = state;
3541 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3542 if (!leavingVNodesCache) {
3543 leavingVNodesCache = Object.create(null);
3544 leavingVNodes.set(vnode.type, leavingVNodesCache);
3545 }
3546 return leavingVNodesCache;
3547}
3548// The transition hooks are attached to the vnode as vnode.transition
3549// and will be called at appropriate timing in the renderer.
3550function resolveTransitionHooks(vnode, props, state, instance) {
3551 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3552 const key = String(vnode.key);
3553 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3554 const callHook = (hook, args) => {
3555 hook &&
3556 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3557 };
3558 const hooks = {
3559 mode,
3560 persisted,
3561 beforeEnter(el) {
3562 let hook = onBeforeEnter;
3563 if (!state.isMounted) {
3564 if (appear) {
3565 hook = onBeforeAppear || onBeforeEnter;
3566 }
3567 else {
3568 return;
3569 }
3570 }
3571 // for same element (v-show)
3572 if (el._leaveCb) {
3573 el._leaveCb(true /* cancelled */);
3574 }
3575 // for toggled element with same key (v-if)
3576 const leavingVNode = leavingVNodesCache[key];
3577 if (leavingVNode &&
3578 isSameVNodeType(vnode, leavingVNode) &&
3579 leavingVNode.el._leaveCb) {
3580 // force early removal (not cancelled)
3581 leavingVNode.el._leaveCb();
3582 }
3583 callHook(hook, [el]);
3584 },
3585 enter(el) {
3586 let hook = onEnter;
3587 let afterHook = onAfterEnter;
3588 let cancelHook = onEnterCancelled;
3589 if (!state.isMounted) {
3590 if (appear) {
3591 hook = onAppear || onEnter;
3592 afterHook = onAfterAppear || onAfterEnter;
3593 cancelHook = onAppearCancelled || onEnterCancelled;
3594 }
3595 else {
3596 return;
3597 }
3598 }
3599 let called = false;
3600 const done = (el._enterCb = (cancelled) => {
3601 if (called)
3602 return;
3603 called = true;
3604 if (cancelled) {
3605 callHook(cancelHook, [el]);
3606 }
3607 else {
3608 callHook(afterHook, [el]);
3609 }
3610 if (hooks.delayedLeave) {
3611 hooks.delayedLeave();
3612 }
3613 el._enterCb = undefined;
3614 });
3615 if (hook) {
3616 hook(el, done);
3617 if (hook.length <= 1) {
3618 done();
3619 }
3620 }
3621 else {
3622 done();
3623 }
3624 },
3625 leave(el, remove) {
3626 const key = String(vnode.key);
3627 if (el._enterCb) {
3628 el._enterCb(true /* cancelled */);
3629 }
3630 if (state.isUnmounting) {
3631 return remove();
3632 }
3633 callHook(onBeforeLeave, [el]);
3634 let called = false;
3635 const done = (el._leaveCb = (cancelled) => {
3636 if (called)
3637 return;
3638 called = true;
3639 remove();
3640 if (cancelled) {
3641 callHook(onLeaveCancelled, [el]);
3642 }
3643 else {
3644 callHook(onAfterLeave, [el]);
3645 }
3646 el._leaveCb = undefined;
3647 if (leavingVNodesCache[key] === vnode) {
3648 delete leavingVNodesCache[key];
3649 }
3650 });
3651 leavingVNodesCache[key] = vnode;
3652 if (onLeave) {
3653 onLeave(el, done);
3654 if (onLeave.length <= 1) {
3655 done();
3656 }
3657 }
3658 else {
3659 done();
3660 }
3661 },
3662 clone(vnode) {
3663 return resolveTransitionHooks(vnode, props, state, instance);
3664 }
3665 };
3666 return hooks;
3667}
3668// the placeholder really only handles one special case: KeepAlive
3669// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3670// placeholder with empty content to avoid the KeepAlive instance from being
3671// unmounted.
3672function emptyPlaceholder(vnode) {
3673 if (isKeepAlive(vnode)) {
3674 vnode = cloneVNode(vnode);
3675 vnode.children = null;
3676 return vnode;
3677 }
3678}
3679function getKeepAliveChild(vnode) {
3680 return isKeepAlive(vnode)
3681 ? vnode.children
3682 ? vnode.children[0]
3683 : undefined
3684 : vnode;
3685}
3686function setTransitionHooks(vnode, hooks) {
3687 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3688 setTransitionHooks(vnode.component.subTree, hooks);
3689 }
3690 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3691 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3692 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3693 }
3694 else {
3695 vnode.transition = hooks;
3696 }
3697}
3698function getTransitionRawChildren(children, keepComment = false) {
3699 let ret = [];
3700 let keyedFragmentCount = 0;
3701 for (let i = 0; i < children.length; i++) {
3702 const child = children[i];
3703 // handle fragment children case, e.g. v-for
3704 if (child.type === Fragment) {
3705 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3706 keyedFragmentCount++;
3707 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3708 }
3709 // comment placeholders should be skipped, e.g. v-if
3710 else if (keepComment || child.type !== Comment) {
3711 ret.push(child);
3712 }
3713 }
3714 // #1126 if a transition children list contains multiple sub fragments, these
3715 // fragments will be merged into a flat children array. Since each v-for
3716 // fragment may contain different static bindings inside, we need to de-op
3717 // these children to force full diffs to ensure correct behavior.
3718 if (keyedFragmentCount > 1) {
3719 for (let i = 0; i < ret.length; i++) {
3720 ret[i].patchFlag = -2 /* BAIL */;
3721 }
3722 }
3723 return ret;
3724}
3725
3726// implementation, close to no-op
3727function defineComponent(options) {
3728 return isFunction(options) ? { setup: options, name: options.name } : options;
3729}
3730
3731const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3732function defineAsyncComponent(source) {
3733 if (isFunction(source)) {
3734 source = { loader: source };
3735 }
3736 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3737 suspensible = true, onError: userOnError } = source;
3738 let pendingRequest = null;
3739 let resolvedComp;
3740 let retries = 0;
3741 const retry = () => {
3742 retries++;
3743 pendingRequest = null;
3744 return load();
3745 };
3746 const load = () => {
3747 let thisRequest;
3748 return (pendingRequest ||
3749 (thisRequest = pendingRequest =
3750 loader()
3751 .catch(err => {
3752 err = err instanceof Error ? err : new Error(String(err));
3753 if (userOnError) {
3754 return new Promise((resolve, reject) => {
3755 const userRetry = () => resolve(retry());
3756 const userFail = () => reject(err);
3757 userOnError(err, userRetry, userFail, retries + 1);
3758 });
3759 }
3760 else {
3761 throw err;
3762 }
3763 })
3764 .then((comp) => {
3765 if (thisRequest !== pendingRequest && pendingRequest) {
3766 return pendingRequest;
3767 }
3768 if (!comp) {
3769 warn$1(`Async component loader resolved to undefined. ` +
3770 `If you are using retry(), make sure to return its return value.`);
3771 }
3772 // interop module default
3773 if (comp &&
3774 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3775 comp = comp.default;
3776 }
3777 if (comp && !isObject(comp) && !isFunction(comp)) {
3778 throw new Error(`Invalid async component load result: ${comp}`);
3779 }
3780 resolvedComp = comp;
3781 return comp;
3782 })));
3783 };
3784 return defineComponent({
3785 name: 'AsyncComponentWrapper',
3786 __asyncLoader: load,
3787 get __asyncResolved() {
3788 return resolvedComp;
3789 },
3790 setup() {
3791 const instance = currentInstance;
3792 // already resolved
3793 if (resolvedComp) {
3794 return () => createInnerComp(resolvedComp, instance);
3795 }
3796 const onError = (err) => {
3797 pendingRequest = null;
3798 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3799 };
3800 // suspense-controlled or SSR.
3801 if ((suspensible && instance.suspense) ||
3802 (false )) {
3803 return load()
3804 .then(comp => {
3805 return () => createInnerComp(comp, instance);
3806 })
3807 .catch(err => {
3808 onError(err);
3809 return () => errorComponent
3810 ? createVNode(errorComponent, {
3811 error: err
3812 })
3813 : null;
3814 });
3815 }
3816 const loaded = ref(false);
3817 const error = ref();
3818 const delayed = ref(!!delay);
3819 if (delay) {
3820 setTimeout(() => {
3821 delayed.value = false;
3822 }, delay);
3823 }
3824 if (timeout != null) {
3825 setTimeout(() => {
3826 if (!loaded.value && !error.value) {
3827 const err = new Error(`Async component timed out after ${timeout}ms.`);
3828 onError(err);
3829 error.value = err;
3830 }
3831 }, timeout);
3832 }
3833 load()
3834 .then(() => {
3835 loaded.value = true;
3836 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3837 // parent is keep-alive, force update so the loaded component's
3838 // name is taken into account
3839 queueJob(instance.parent.update);
3840 }
3841 })
3842 .catch(err => {
3843 onError(err);
3844 error.value = err;
3845 });
3846 return () => {
3847 if (loaded.value && resolvedComp) {
3848 return createInnerComp(resolvedComp, instance);
3849 }
3850 else if (error.value && errorComponent) {
3851 return createVNode(errorComponent, {
3852 error: error.value
3853 });
3854 }
3855 else if (loadingComponent && !delayed.value) {
3856 return createVNode(loadingComponent);
3857 }
3858 };
3859 }
3860 });
3861}
3862function createInnerComp(comp, { vnode: { ref, props, children } }) {
3863 const vnode = createVNode(comp, props, children);
3864 // ensure inner component inherits the async wrapper's ref owner
3865 vnode.ref = ref;
3866 return vnode;
3867}
3868
3869const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3870const KeepAliveImpl = {
3871 name: `KeepAlive`,
3872 // Marker for special handling inside the renderer. We are not using a ===
3873 // check directly on KeepAlive in the renderer, because importing it directly
3874 // would prevent it from being tree-shaken.
3875 __isKeepAlive: true,
3876 props: {
3877 include: [String, RegExp, Array],
3878 exclude: [String, RegExp, Array],
3879 max: [String, Number]
3880 },
3881 setup(props, { slots }) {
3882 const instance = getCurrentInstance();
3883 // KeepAlive communicates with the instantiated renderer via the
3884 // ctx where the renderer passes in its internals,
3885 // and the KeepAlive instance exposes activate/deactivate implementations.
3886 // The whole point of this is to avoid importing KeepAlive directly in the
3887 // renderer to facilitate tree-shaking.
3888 const sharedContext = instance.ctx;
3889 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3890 // for KeepAlive, we just need to render its children
3891 if (!sharedContext.renderer) {
3892 return slots.default;
3893 }
3894 const cache = new Map();
3895 const keys = new Set();
3896 let current = null;
3897 {
3898 instance.__v_cache = cache;
3899 }
3900 const parentSuspense = instance.suspense;
3901 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3902 const storageContainer = createElement('div');
3903 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3904 const instance = vnode.component;
3905 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3906 // in case props have changed
3907 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3908 queuePostRenderEffect(() => {
3909 instance.isDeactivated = false;
3910 if (instance.a) {
3911 invokeArrayFns(instance.a);
3912 }
3913 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3914 if (vnodeHook) {
3915 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3916 }
3917 }, parentSuspense);
3918 {
3919 // Update components tree
3920 devtoolsComponentAdded(instance);
3921 }
3922 };
3923 sharedContext.deactivate = (vnode) => {
3924 const instance = vnode.component;
3925 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3926 queuePostRenderEffect(() => {
3927 if (instance.da) {
3928 invokeArrayFns(instance.da);
3929 }
3930 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3931 if (vnodeHook) {
3932 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3933 }
3934 instance.isDeactivated = true;
3935 }, parentSuspense);
3936 {
3937 // Update components tree
3938 devtoolsComponentAdded(instance);
3939 }
3940 };
3941 function unmount(vnode) {
3942 // reset the shapeFlag so it can be properly unmounted
3943 resetShapeFlag(vnode);
3944 _unmount(vnode, instance, parentSuspense, true);
3945 }
3946 function pruneCache(filter) {
3947 cache.forEach((vnode, key) => {
3948 const name = getComponentName(vnode.type);
3949 if (name && (!filter || !filter(name))) {
3950 pruneCacheEntry(key);
3951 }
3952 });
3953 }
3954 function pruneCacheEntry(key) {
3955 const cached = cache.get(key);
3956 if (!current || cached.type !== current.type) {
3957 unmount(cached);
3958 }
3959 else if (current) {
3960 // current active instance should no longer be kept-alive.
3961 // we can't unmount it now but it might be later, so reset its flag now.
3962 resetShapeFlag(current);
3963 }
3964 cache.delete(key);
3965 keys.delete(key);
3966 }
3967 // prune cache on include/exclude prop change
3968 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3969 include && pruneCache(name => matches(include, name));
3970 exclude && pruneCache(name => !matches(exclude, name));
3971 },
3972 // prune post-render after `current` has been updated
3973 { flush: 'post', deep: true });
3974 // cache sub tree after render
3975 let pendingCacheKey = null;
3976 const cacheSubtree = () => {
3977 // fix #1621, the pendingCacheKey could be 0
3978 if (pendingCacheKey != null) {
3979 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3980 }
3981 };
3982 onMounted(cacheSubtree);
3983 onUpdated(cacheSubtree);
3984 onBeforeUnmount(() => {
3985 cache.forEach(cached => {
3986 const { subTree, suspense } = instance;
3987 const vnode = getInnerChild(subTree);
3988 if (cached.type === vnode.type) {
3989 // current instance will be unmounted as part of keep-alive's unmount
3990 resetShapeFlag(vnode);
3991 // but invoke its deactivated hook here
3992 const da = vnode.component.da;
3993 da && queuePostRenderEffect(da, suspense);
3994 return;
3995 }
3996 unmount(cached);
3997 });
3998 });
3999 return () => {
4000 pendingCacheKey = null;
4001 if (!slots.default) {
4002 return null;
4003 }
4004 const children = slots.default();
4005 const rawVNode = children[0];
4006 if (children.length > 1) {
4007 {
4008 warn$1(`KeepAlive should contain exactly one component child.`);
4009 }
4010 current = null;
4011 return children;
4012 }
4013 else if (!isVNode(rawVNode) ||
4014 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
4015 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
4016 current = null;
4017 return rawVNode;
4018 }
4019 let vnode = getInnerChild(rawVNode);
4020 const comp = vnode.type;
4021 // for async components, name check should be based in its loaded
4022 // inner component if available
4023 const name = getComponentName(isAsyncWrapper(vnode)
4024 ? vnode.type.__asyncResolved || {}
4025 : comp);
4026 const { include, exclude, max } = props;
4027 if ((include && (!name || !matches(include, name))) ||
4028 (exclude && name && matches(exclude, name))) {
4029 current = vnode;
4030 return rawVNode;
4031 }
4032 const key = vnode.key == null ? comp : vnode.key;
4033 const cachedVNode = cache.get(key);
4034 // clone vnode if it's reused because we are going to mutate it
4035 if (vnode.el) {
4036 vnode = cloneVNode(vnode);
4037 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
4038 rawVNode.ssContent = vnode;
4039 }
4040 }
4041 // #1513 it's possible for the returned vnode to be cloned due to attr
4042 // fallthrough or scopeId, so the vnode here may not be the final vnode
4043 // that is mounted. Instead of caching it directly, we store the pending
4044 // key and cache `instance.subTree` (the normalized vnode) in
4045 // beforeMount/beforeUpdate hooks.
4046 pendingCacheKey = key;
4047 if (cachedVNode) {
4048 // copy over mounted state
4049 vnode.el = cachedVNode.el;
4050 vnode.component = cachedVNode.component;
4051 if (vnode.transition) {
4052 // recursively update transition hooks on subTree
4053 setTransitionHooks(vnode, vnode.transition);
4054 }
4055 // avoid vnode being mounted as fresh
4056 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
4057 // make this key the freshest
4058 keys.delete(key);
4059 keys.add(key);
4060 }
4061 else {
4062 keys.add(key);
4063 // prune oldest entry
4064 if (max && keys.size > parseInt(max, 10)) {
4065 pruneCacheEntry(keys.values().next().value);
4066 }
4067 }
4068 // avoid vnode being unmounted
4069 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4070 current = vnode;
4071 return rawVNode;
4072 };
4073 }
4074};
4075// export the public type for h/tsx inference
4076// also to avoid inline import() in generated d.ts files
4077const KeepAlive = KeepAliveImpl;
4078function matches(pattern, name) {
4079 if (isArray(pattern)) {
4080 return pattern.some((p) => matches(p, name));
4081 }
4082 else if (isString(pattern)) {
4083 return pattern.split(',').includes(name);
4084 }
4085 else if (pattern.test) {
4086 return pattern.test(name);
4087 }
4088 /* istanbul ignore next */
4089 return false;
4090}
4091function onActivated(hook, target) {
4092 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
4093}
4094function onDeactivated(hook, target) {
4095 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
4096}
4097function registerKeepAliveHook(hook, type, target = currentInstance) {
4098 // cache the deactivate branch check wrapper for injected hooks so the same
4099 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4100 // deactivation check".
4101 const wrappedHook = hook.__wdc ||
4102 (hook.__wdc = () => {
4103 // only fire the hook if the target instance is NOT in a deactivated branch.
4104 let current = target;
4105 while (current) {
4106 if (current.isDeactivated) {
4107 return;
4108 }
4109 current = current.parent;
4110 }
4111 return hook();
4112 });
4113 injectHook(type, wrappedHook, target);
4114 // In addition to registering it on the target instance, we walk up the parent
4115 // chain and register it on all ancestor instances that are keep-alive roots.
4116 // This avoids the need to walk the entire component tree when invoking these
4117 // hooks, and more importantly, avoids the need to track child components in
4118 // arrays.
4119 if (target) {
4120 let current = target.parent;
4121 while (current && current.parent) {
4122 if (isKeepAlive(current.parent.vnode)) {
4123 injectToKeepAliveRoot(wrappedHook, type, target, current);
4124 }
4125 current = current.parent;
4126 }
4127 }
4128}
4129function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4130 // injectHook wraps the original for error handling, so make sure to remove
4131 // the wrapped version.
4132 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4133 onUnmounted(() => {
4134 remove(keepAliveRoot[type], injected);
4135 }, target);
4136}
4137function resetShapeFlag(vnode) {
4138 let shapeFlag = vnode.shapeFlag;
4139 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4140 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4141 }
4142 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4143 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4144 }
4145 vnode.shapeFlag = shapeFlag;
4146}
4147function getInnerChild(vnode) {
4148 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4149}
4150
4151function injectHook(type, hook, target = currentInstance, prepend = false) {
4152 if (target) {
4153 const hooks = target[type] || (target[type] = []);
4154 // cache the error handling wrapper for injected hooks so the same hook
4155 // can be properly deduped by the scheduler. "__weh" stands for "with error
4156 // handling".
4157 const wrappedHook = hook.__weh ||
4158 (hook.__weh = (...args) => {
4159 if (target.isUnmounted) {
4160 return;
4161 }
4162 // disable tracking inside all lifecycle hooks
4163 // since they can potentially be called inside effects.
4164 pauseTracking();
4165 // Set currentInstance during hook invocation.
4166 // This assumes the hook does not synchronously trigger other hooks, which
4167 // can only be false when the user does something really funky.
4168 setCurrentInstance(target);
4169 const res = callWithAsyncErrorHandling(hook, target, type, args);
4170 unsetCurrentInstance();
4171 resetTracking();
4172 return res;
4173 });
4174 if (prepend) {
4175 hooks.unshift(wrappedHook);
4176 }
4177 else {
4178 hooks.push(wrappedHook);
4179 }
4180 return wrappedHook;
4181 }
4182 else {
4183 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4184 warn$1(`${apiName} is called when there is no active component instance to be ` +
4185 `associated with. ` +
4186 `Lifecycle injection APIs can only be used during execution of setup().` +
4187 (` If you are using async setup(), make sure to register lifecycle ` +
4188 `hooks before the first await statement.`
4189 ));
4190 }
4191}
4192const createHook = (lifecycle) => (hook, target = currentInstance) =>
4193// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4194(!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
4195 injectHook(lifecycle, hook, target);
4196const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
4197const onMounted = createHook("m" /* MOUNTED */);
4198const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
4199const onUpdated = createHook("u" /* UPDATED */);
4200const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
4201const onUnmounted = createHook("um" /* UNMOUNTED */);
4202const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
4203const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
4204const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
4205function onErrorCaptured(hook, target = currentInstance) {
4206 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
4207}
4208
4209function createDuplicateChecker() {
4210 const cache = Object.create(null);
4211 return (type, key) => {
4212 if (cache[key]) {
4213 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
4214 }
4215 else {
4216 cache[key] = type;
4217 }
4218 };
4219}
4220let shouldCacheAccess = true;
4221function applyOptions(instance) {
4222 const options = resolveMergedOptions(instance);
4223 const publicThis = instance.proxy;
4224 const ctx = instance.ctx;
4225 // do not cache property access on public proxy during state initialization
4226 shouldCacheAccess = false;
4227 // call beforeCreate first before accessing other options since
4228 // the hook may mutate resolved options (#2791)
4229 if (options.beforeCreate) {
4230 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
4231 }
4232 const {
4233 // state
4234 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4235 // lifecycle
4236 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4237 // public API
4238 expose, inheritAttrs,
4239 // assets
4240 components, directives, filters } = options;
4241 const checkDuplicateProperties = createDuplicateChecker() ;
4242 {
4243 const [propsOptions] = instance.propsOptions;
4244 if (propsOptions) {
4245 for (const key in propsOptions) {
4246 checkDuplicateProperties("Props" /* PROPS */, key);
4247 }
4248 }
4249 }
4250 // options initialization order (to be consistent with Vue 2):
4251 // - props (already done outside of this function)
4252 // - inject
4253 // - methods
4254 // - data (deferred since it relies on `this` access)
4255 // - computed
4256 // - watch (deferred since it relies on `this` access)
4257 if (injectOptions) {
4258 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
4259 }
4260 if (methods) {
4261 for (const key in methods) {
4262 const methodHandler = methods[key];
4263 if (isFunction(methodHandler)) {
4264 // In dev mode, we use the `createRenderContext` function to define
4265 // methods to the proxy target, and those are read-only but
4266 // reconfigurable, so it needs to be redefined here
4267 {
4268 Object.defineProperty(ctx, key, {
4269 value: methodHandler.bind(publicThis),
4270 configurable: true,
4271 enumerable: true,
4272 writable: true
4273 });
4274 }
4275 {
4276 checkDuplicateProperties("Methods" /* METHODS */, key);
4277 }
4278 }
4279 else {
4280 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4281 `Did you reference the function correctly?`);
4282 }
4283 }
4284 }
4285 if (dataOptions) {
4286 if (!isFunction(dataOptions)) {
4287 warn$1(`The data option must be a function. ` +
4288 `Plain object usage is no longer supported.`);
4289 }
4290 const data = dataOptions.call(publicThis, publicThis);
4291 if (isPromise(data)) {
4292 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
4293 `intend to perform data fetching before component renders, use ` +
4294 `async setup() + <Suspense>.`);
4295 }
4296 if (!isObject(data)) {
4297 warn$1(`data() should return an object.`);
4298 }
4299 else {
4300 instance.data = reactive(data);
4301 {
4302 for (const key in data) {
4303 checkDuplicateProperties("Data" /* DATA */, key);
4304 // expose data on ctx during dev
4305 if (key[0] !== '$' && key[0] !== '_') {
4306 Object.defineProperty(ctx, key, {
4307 configurable: true,
4308 enumerable: true,
4309 get: () => data[key],
4310 set: NOOP
4311 });
4312 }
4313 }
4314 }
4315 }
4316 }
4317 // state initialization complete at this point - start caching access
4318 shouldCacheAccess = true;
4319 if (computedOptions) {
4320 for (const key in computedOptions) {
4321 const opt = computedOptions[key];
4322 const get = isFunction(opt)
4323 ? opt.bind(publicThis, publicThis)
4324 : isFunction(opt.get)
4325 ? opt.get.bind(publicThis, publicThis)
4326 : NOOP;
4327 if (get === NOOP) {
4328 warn$1(`Computed property "${key}" has no getter.`);
4329 }
4330 const set = !isFunction(opt) && isFunction(opt.set)
4331 ? opt.set.bind(publicThis)
4332 : () => {
4333 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
4334 }
4335 ;
4336 const c = computed$1({
4337 get,
4338 set
4339 });
4340 Object.defineProperty(ctx, key, {
4341 enumerable: true,
4342 configurable: true,
4343 get: () => c.value,
4344 set: v => (c.value = v)
4345 });
4346 {
4347 checkDuplicateProperties("Computed" /* COMPUTED */, key);
4348 }
4349 }
4350 }
4351 if (watchOptions) {
4352 for (const key in watchOptions) {
4353 createWatcher(watchOptions[key], ctx, publicThis, key);
4354 }
4355 }
4356 if (provideOptions) {
4357 const provides = isFunction(provideOptions)
4358 ? provideOptions.call(publicThis)
4359 : provideOptions;
4360 Reflect.ownKeys(provides).forEach(key => {
4361 provide(key, provides[key]);
4362 });
4363 }
4364 if (created) {
4365 callHook(created, instance, "c" /* CREATED */);
4366 }
4367 function registerLifecycleHook(register, hook) {
4368 if (isArray(hook)) {
4369 hook.forEach(_hook => register(_hook.bind(publicThis)));
4370 }
4371 else if (hook) {
4372 register(hook.bind(publicThis));
4373 }
4374 }
4375 registerLifecycleHook(onBeforeMount, beforeMount);
4376 registerLifecycleHook(onMounted, mounted);
4377 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
4378 registerLifecycleHook(onUpdated, updated);
4379 registerLifecycleHook(onActivated, activated);
4380 registerLifecycleHook(onDeactivated, deactivated);
4381 registerLifecycleHook(onErrorCaptured, errorCaptured);
4382 registerLifecycleHook(onRenderTracked, renderTracked);
4383 registerLifecycleHook(onRenderTriggered, renderTriggered);
4384 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
4385 registerLifecycleHook(onUnmounted, unmounted);
4386 registerLifecycleHook(onServerPrefetch, serverPrefetch);
4387 if (isArray(expose)) {
4388 if (expose.length) {
4389 const exposed = instance.exposed || (instance.exposed = {});
4390 expose.forEach(key => {
4391 Object.defineProperty(exposed, key, {
4392 get: () => publicThis[key],
4393 set: val => (publicThis[key] = val)
4394 });
4395 });
4396 }
4397 else if (!instance.exposed) {
4398 instance.exposed = {};
4399 }
4400 }
4401 // options that are handled when creating the instance but also need to be
4402 // applied from mixins
4403 if (render && instance.render === NOOP) {
4404 instance.render = render;
4405 }
4406 if (inheritAttrs != null) {
4407 instance.inheritAttrs = inheritAttrs;
4408 }
4409 // asset options.
4410 if (components)
4411 instance.components = components;
4412 if (directives)
4413 instance.directives = directives;
4414}
4415function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4416 if (isArray(injectOptions)) {
4417 injectOptions = normalizeInject(injectOptions);
4418 }
4419 for (const key in injectOptions) {
4420 const opt = injectOptions[key];
4421 let injected;
4422 if (isObject(opt)) {
4423 if ('default' in opt) {
4424 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4425 }
4426 else {
4427 injected = inject(opt.from || key);
4428 }
4429 }
4430 else {
4431 injected = inject(opt);
4432 }
4433 if (isRef(injected)) {
4434 // TODO remove the check in 3.3
4435 if (unwrapRef) {
4436 Object.defineProperty(ctx, key, {
4437 enumerable: true,
4438 configurable: true,
4439 get: () => injected.value,
4440 set: v => (injected.value = v)
4441 });
4442 }
4443 else {
4444 {
4445 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4446 `and no longer needs \`.value\` in the next minor release. ` +
4447 `To opt-in to the new behavior now, ` +
4448 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4449 `temporary and will not be needed in the future.)`);
4450 }
4451 ctx[key] = injected;
4452 }
4453 }
4454 else {
4455 ctx[key] = injected;
4456 }
4457 {
4458 checkDuplicateProperties("Inject" /* INJECT */, key);
4459 }
4460 }
4461}
4462function callHook(hook, instance, type) {
4463 callWithAsyncErrorHandling(isArray(hook)
4464 ? hook.map(h => h.bind(instance.proxy))
4465 : hook.bind(instance.proxy), instance, type);
4466}
4467function createWatcher(raw, ctx, publicThis, key) {
4468 const getter = key.includes('.')
4469 ? createPathGetter(publicThis, key)
4470 : () => publicThis[key];
4471 if (isString(raw)) {
4472 const handler = ctx[raw];
4473 if (isFunction(handler)) {
4474 watch(getter, handler);
4475 }
4476 else {
4477 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4478 }
4479 }
4480 else if (isFunction(raw)) {
4481 watch(getter, raw.bind(publicThis));
4482 }
4483 else if (isObject(raw)) {
4484 if (isArray(raw)) {
4485 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4486 }
4487 else {
4488 const handler = isFunction(raw.handler)
4489 ? raw.handler.bind(publicThis)
4490 : ctx[raw.handler];
4491 if (isFunction(handler)) {
4492 watch(getter, handler, raw);
4493 }
4494 else {
4495 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4496 }
4497 }
4498 }
4499 else {
4500 warn$1(`Invalid watch option: "${key}"`, raw);
4501 }
4502}
4503/**
4504 * Resolve merged options and cache it on the component.
4505 * This is done only once per-component since the merging does not involve
4506 * instances.
4507 */
4508function resolveMergedOptions(instance) {
4509 const base = instance.type;
4510 const { mixins, extends: extendsOptions } = base;
4511 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4512 const cached = cache.get(base);
4513 let resolved;
4514 if (cached) {
4515 resolved = cached;
4516 }
4517 else if (!globalMixins.length && !mixins && !extendsOptions) {
4518 {
4519 resolved = base;
4520 }
4521 }
4522 else {
4523 resolved = {};
4524 if (globalMixins.length) {
4525 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4526 }
4527 mergeOptions(resolved, base, optionMergeStrategies);
4528 }
4529 cache.set(base, resolved);
4530 return resolved;
4531}
4532function mergeOptions(to, from, strats, asMixin = false) {
4533 const { mixins, extends: extendsOptions } = from;
4534 if (extendsOptions) {
4535 mergeOptions(to, extendsOptions, strats, true);
4536 }
4537 if (mixins) {
4538 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4539 }
4540 for (const key in from) {
4541 if (asMixin && key === 'expose') {
4542 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4543 `It should only be declared in the base component itself.`);
4544 }
4545 else {
4546 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4547 to[key] = strat ? strat(to[key], from[key]) : from[key];
4548 }
4549 }
4550 return to;
4551}
4552const internalOptionMergeStrats = {
4553 data: mergeDataFn,
4554 props: mergeObjectOptions,
4555 emits: mergeObjectOptions,
4556 // objects
4557 methods: mergeObjectOptions,
4558 computed: mergeObjectOptions,
4559 // lifecycle
4560 beforeCreate: mergeAsArray,
4561 created: mergeAsArray,
4562 beforeMount: mergeAsArray,
4563 mounted: mergeAsArray,
4564 beforeUpdate: mergeAsArray,
4565 updated: mergeAsArray,
4566 beforeDestroy: mergeAsArray,
4567 beforeUnmount: mergeAsArray,
4568 destroyed: mergeAsArray,
4569 unmounted: mergeAsArray,
4570 activated: mergeAsArray,
4571 deactivated: mergeAsArray,
4572 errorCaptured: mergeAsArray,
4573 serverPrefetch: mergeAsArray,
4574 // assets
4575 components: mergeObjectOptions,
4576 directives: mergeObjectOptions,
4577 // watch
4578 watch: mergeWatchOptions,
4579 // provide / inject
4580 provide: mergeDataFn,
4581 inject: mergeInject
4582};
4583function mergeDataFn(to, from) {
4584 if (!from) {
4585 return to;
4586 }
4587 if (!to) {
4588 return from;
4589 }
4590 return function mergedDataFn() {
4591 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4592 };
4593}
4594function mergeInject(to, from) {
4595 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4596}
4597function normalizeInject(raw) {
4598 if (isArray(raw)) {
4599 const res = {};
4600 for (let i = 0; i < raw.length; i++) {
4601 res[raw[i]] = raw[i];
4602 }
4603 return res;
4604 }
4605 return raw;
4606}
4607function mergeAsArray(to, from) {
4608 return to ? [...new Set([].concat(to, from))] : from;
4609}
4610function mergeObjectOptions(to, from) {
4611 return to ? extend(extend(Object.create(null), to), from) : from;
4612}
4613function mergeWatchOptions(to, from) {
4614 if (!to)
4615 return from;
4616 if (!from)
4617 return to;
4618 const merged = extend(Object.create(null), to);
4619 for (const key in from) {
4620 merged[key] = mergeAsArray(to[key], from[key]);
4621 }
4622 return merged;
4623}
4624
4625function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4626isSSR = false) {
4627 const props = {};
4628 const attrs = {};
4629 def(attrs, InternalObjectKey, 1);
4630 instance.propsDefaults = Object.create(null);
4631 setFullProps(instance, rawProps, props, attrs);
4632 // ensure all declared prop keys are present
4633 for (const key in instance.propsOptions[0]) {
4634 if (!(key in props)) {
4635 props[key] = undefined;
4636 }
4637 }
4638 // validation
4639 {
4640 validateProps(rawProps || {}, props, instance);
4641 }
4642 if (isStateful) {
4643 // stateful
4644 instance.props = isSSR ? props : shallowReactive(props);
4645 }
4646 else {
4647 if (!instance.type.props) {
4648 // functional w/ optional props, props === attrs
4649 instance.props = attrs;
4650 }
4651 else {
4652 // functional w/ declared props
4653 instance.props = props;
4654 }
4655 }
4656 instance.attrs = attrs;
4657}
4658function updateProps(instance, rawProps, rawPrevProps, optimized) {
4659 const { props, attrs, vnode: { patchFlag } } = instance;
4660 const rawCurrentProps = toRaw(props);
4661 const [options] = instance.propsOptions;
4662 let hasAttrsChanged = false;
4663 if (
4664 // always force full diff in dev
4665 // - #1942 if hmr is enabled with sfc component
4666 // - vite#872 non-sfc component used by sfc component
4667 !((instance.type.__hmrId ||
4668 (instance.parent && instance.parent.type.__hmrId))) &&
4669 (optimized || patchFlag > 0) &&
4670 !(patchFlag & 16 /* FULL_PROPS */)) {
4671 if (patchFlag & 8 /* PROPS */) {
4672 // Compiler-generated props & no keys change, just set the updated
4673 // the props.
4674 const propsToUpdate = instance.vnode.dynamicProps;
4675 for (let i = 0; i < propsToUpdate.length; i++) {
4676 let key = propsToUpdate[i];
4677 // PROPS flag guarantees rawProps to be non-null
4678 const value = rawProps[key];
4679 if (options) {
4680 // attr / props separation was done on init and will be consistent
4681 // in this code path, so just check if attrs have it.
4682 if (hasOwn(attrs, key)) {
4683 if (value !== attrs[key]) {
4684 attrs[key] = value;
4685 hasAttrsChanged = true;
4686 }
4687 }
4688 else {
4689 const camelizedKey = camelize(key);
4690 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4691 }
4692 }
4693 else {
4694 if (value !== attrs[key]) {
4695 attrs[key] = value;
4696 hasAttrsChanged = true;
4697 }
4698 }
4699 }
4700 }
4701 }
4702 else {
4703 // full props update.
4704 if (setFullProps(instance, rawProps, props, attrs)) {
4705 hasAttrsChanged = true;
4706 }
4707 // in case of dynamic props, check if we need to delete keys from
4708 // the props object
4709 let kebabKey;
4710 for (const key in rawCurrentProps) {
4711 if (!rawProps ||
4712 // for camelCase
4713 (!hasOwn(rawProps, key) &&
4714 // it's possible the original props was passed in as kebab-case
4715 // and converted to camelCase (#955)
4716 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4717 if (options) {
4718 if (rawPrevProps &&
4719 // for camelCase
4720 (rawPrevProps[key] !== undefined ||
4721 // for kebab-case
4722 rawPrevProps[kebabKey] !== undefined)) {
4723 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4724 }
4725 }
4726 else {
4727 delete props[key];
4728 }
4729 }
4730 }
4731 // in the case of functional component w/o props declaration, props and
4732 // attrs point to the same object so it should already have been updated.
4733 if (attrs !== rawCurrentProps) {
4734 for (const key in attrs) {
4735 if (!rawProps ||
4736 (!hasOwn(rawProps, key) &&
4737 (!false ))) {
4738 delete attrs[key];
4739 hasAttrsChanged = true;
4740 }
4741 }
4742 }
4743 }
4744 // trigger updates for $attrs in case it's used in component slots
4745 if (hasAttrsChanged) {
4746 trigger(instance, "set" /* SET */, '$attrs');
4747 }
4748 {
4749 validateProps(rawProps || {}, props, instance);
4750 }
4751}
4752function setFullProps(instance, rawProps, props, attrs) {
4753 const [options, needCastKeys] = instance.propsOptions;
4754 let hasAttrsChanged = false;
4755 let rawCastValues;
4756 if (rawProps) {
4757 for (let key in rawProps) {
4758 // key, ref are reserved and never passed down
4759 if (isReservedProp(key)) {
4760 continue;
4761 }
4762 const value = rawProps[key];
4763 // prop option names are camelized during normalization, so to support
4764 // kebab -> camel conversion here we need to camelize the key.
4765 let camelKey;
4766 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4767 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4768 props[camelKey] = value;
4769 }
4770 else {
4771 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4772 }
4773 }
4774 else if (!isEmitListener(instance.emitsOptions, key)) {
4775 if (!(key in attrs) || value !== attrs[key]) {
4776 attrs[key] = value;
4777 hasAttrsChanged = true;
4778 }
4779 }
4780 }
4781 }
4782 if (needCastKeys) {
4783 const rawCurrentProps = toRaw(props);
4784 const castValues = rawCastValues || EMPTY_OBJ;
4785 for (let i = 0; i < needCastKeys.length; i++) {
4786 const key = needCastKeys[i];
4787 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4788 }
4789 }
4790 return hasAttrsChanged;
4791}
4792function resolvePropValue(options, props, key, value, instance, isAbsent) {
4793 const opt = options[key];
4794 if (opt != null) {
4795 const hasDefault = hasOwn(opt, 'default');
4796 // default values
4797 if (hasDefault && value === undefined) {
4798 const defaultValue = opt.default;
4799 if (opt.type !== Function && isFunction(defaultValue)) {
4800 const { propsDefaults } = instance;
4801 if (key in propsDefaults) {
4802 value = propsDefaults[key];
4803 }
4804 else {
4805 setCurrentInstance(instance);
4806 value = propsDefaults[key] = defaultValue.call(null, props);
4807 unsetCurrentInstance();
4808 }
4809 }
4810 else {
4811 value = defaultValue;
4812 }
4813 }
4814 // boolean casting
4815 if (opt[0 /* shouldCast */]) {
4816 if (isAbsent && !hasDefault) {
4817 value = false;
4818 }
4819 else if (opt[1 /* shouldCastTrue */] &&
4820 (value === '' || value === hyphenate(key))) {
4821 value = true;
4822 }
4823 }
4824 }
4825 return value;
4826}
4827function normalizePropsOptions(comp, appContext, asMixin = false) {
4828 const cache = appContext.propsCache;
4829 const cached = cache.get(comp);
4830 if (cached) {
4831 return cached;
4832 }
4833 const raw = comp.props;
4834 const normalized = {};
4835 const needCastKeys = [];
4836 // apply mixin/extends props
4837 let hasExtends = false;
4838 if (!isFunction(comp)) {
4839 const extendProps = (raw) => {
4840 hasExtends = true;
4841 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4842 extend(normalized, props);
4843 if (keys)
4844 needCastKeys.push(...keys);
4845 };
4846 if (!asMixin && appContext.mixins.length) {
4847 appContext.mixins.forEach(extendProps);
4848 }
4849 if (comp.extends) {
4850 extendProps(comp.extends);
4851 }
4852 if (comp.mixins) {
4853 comp.mixins.forEach(extendProps);
4854 }
4855 }
4856 if (!raw && !hasExtends) {
4857 cache.set(comp, EMPTY_ARR);
4858 return EMPTY_ARR;
4859 }
4860 if (isArray(raw)) {
4861 for (let i = 0; i < raw.length; i++) {
4862 if (!isString(raw[i])) {
4863 warn$1(`props must be strings when using array syntax.`, raw[i]);
4864 }
4865 const normalizedKey = camelize(raw[i]);
4866 if (validatePropName(normalizedKey)) {
4867 normalized[normalizedKey] = EMPTY_OBJ;
4868 }
4869 }
4870 }
4871 else if (raw) {
4872 if (!isObject(raw)) {
4873 warn$1(`invalid props options`, raw);
4874 }
4875 for (const key in raw) {
4876 const normalizedKey = camelize(key);
4877 if (validatePropName(normalizedKey)) {
4878 const opt = raw[key];
4879 const prop = (normalized[normalizedKey] =
4880 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4881 if (prop) {
4882 const booleanIndex = getTypeIndex(Boolean, prop.type);
4883 const stringIndex = getTypeIndex(String, prop.type);
4884 prop[0 /* shouldCast */] = booleanIndex > -1;
4885 prop[1 /* shouldCastTrue */] =
4886 stringIndex < 0 || booleanIndex < stringIndex;
4887 // if the prop needs boolean casting or default value
4888 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4889 needCastKeys.push(normalizedKey);
4890 }
4891 }
4892 }
4893 }
4894 }
4895 const res = [normalized, needCastKeys];
4896 cache.set(comp, res);
4897 return res;
4898}
4899function validatePropName(key) {
4900 if (key[0] !== '$') {
4901 return true;
4902 }
4903 else {
4904 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4905 }
4906 return false;
4907}
4908// use function string name to check type constructors
4909// so that it works across vms / iframes.
4910function getType(ctor) {
4911 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4912 return match ? match[1] : ctor === null ? 'null' : '';
4913}
4914function isSameType(a, b) {
4915 return getType(a) === getType(b);
4916}
4917function getTypeIndex(type, expectedTypes) {
4918 if (isArray(expectedTypes)) {
4919 return expectedTypes.findIndex(t => isSameType(t, type));
4920 }
4921 else if (isFunction(expectedTypes)) {
4922 return isSameType(expectedTypes, type) ? 0 : -1;
4923 }
4924 return -1;
4925}
4926/**
4927 * dev only
4928 */
4929function validateProps(rawProps, props, instance) {
4930 const resolvedValues = toRaw(props);
4931 const options = instance.propsOptions[0];
4932 for (const key in options) {
4933 let opt = options[key];
4934 if (opt == null)
4935 continue;
4936 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4937 }
4938}
4939/**
4940 * dev only
4941 */
4942function validateProp(name, value, prop, isAbsent) {
4943 const { type, required, validator } = prop;
4944 // required!
4945 if (required && isAbsent) {
4946 warn$1('Missing required prop: "' + name + '"');
4947 return;
4948 }
4949 // missing but optional
4950 if (value == null && !prop.required) {
4951 return;
4952 }
4953 // type check
4954 if (type != null && type !== true) {
4955 let isValid = false;
4956 const types = isArray(type) ? type : [type];
4957 const expectedTypes = [];
4958 // value is valid as long as one of the specified types match
4959 for (let i = 0; i < types.length && !isValid; i++) {
4960 const { valid, expectedType } = assertType(value, types[i]);
4961 expectedTypes.push(expectedType || '');
4962 isValid = valid;
4963 }
4964 if (!isValid) {
4965 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
4966 return;
4967 }
4968 }
4969 // custom validator
4970 if (validator && !validator(value)) {
4971 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
4972 }
4973}
4974const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4975/**
4976 * dev only
4977 */
4978function assertType(value, type) {
4979 let valid;
4980 const expectedType = getType(type);
4981 if (isSimpleType(expectedType)) {
4982 const t = typeof value;
4983 valid = t === expectedType.toLowerCase();
4984 // for primitive wrapper objects
4985 if (!valid && t === 'object') {
4986 valid = value instanceof type;
4987 }
4988 }
4989 else if (expectedType === 'Object') {
4990 valid = isObject(value);
4991 }
4992 else if (expectedType === 'Array') {
4993 valid = isArray(value);
4994 }
4995 else if (expectedType === 'null') {
4996 valid = value === null;
4997 }
4998 else {
4999 valid = value instanceof type;
5000 }
5001 return {
5002 valid,
5003 expectedType
5004 };
5005}
5006/**
5007 * dev only
5008 */
5009function getInvalidTypeMessage(name, value, expectedTypes) {
5010 let message = `Invalid prop: type check failed for prop "${name}".` +
5011 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
5012 const expectedType = expectedTypes[0];
5013 const receivedType = toRawType(value);
5014 const expectedValue = styleValue(value, expectedType);
5015 const receivedValue = styleValue(value, receivedType);
5016 // check if we need to specify expected value
5017 if (expectedTypes.length === 1 &&
5018 isExplicable(expectedType) &&
5019 !isBoolean(expectedType, receivedType)) {
5020 message += ` with value ${expectedValue}`;
5021 }
5022 message += `, got ${receivedType} `;
5023 // check if we need to specify received value
5024 if (isExplicable(receivedType)) {
5025 message += `with value ${receivedValue}.`;
5026 }
5027 return message;
5028}
5029/**
5030 * dev only
5031 */
5032function styleValue(value, type) {
5033 if (type === 'String') {
5034 return `"${value}"`;
5035 }
5036 else if (type === 'Number') {
5037 return `${Number(value)}`;
5038 }
5039 else {
5040 return `${value}`;
5041 }
5042}
5043/**
5044 * dev only
5045 */
5046function isExplicable(type) {
5047 const explicitTypes = ['string', 'number', 'boolean'];
5048 return explicitTypes.some(elem => type.toLowerCase() === elem);
5049}
5050/**
5051 * dev only
5052 */
5053function isBoolean(...args) {
5054 return args.some(elem => elem.toLowerCase() === 'boolean');
5055}
5056
5057const isInternalKey = (key) => key[0] === '_' || key === '$stable';
5058const normalizeSlotValue = (value) => isArray(value)
5059 ? value.map(normalizeVNode)
5060 : [normalizeVNode(value)];
5061const normalizeSlot = (key, rawSlot, ctx) => {
5062 const normalized = withCtx((...args) => {
5063 if (currentInstance) {
5064 warn$1(`Slot "${key}" invoked outside of the render function: ` +
5065 `this will not track dependencies used in the slot. ` +
5066 `Invoke the slot function inside the render function instead.`);
5067 }
5068 return normalizeSlotValue(rawSlot(...args));
5069 }, ctx);
5070 normalized._c = false;
5071 return normalized;
5072};
5073const normalizeObjectSlots = (rawSlots, slots, instance) => {
5074 const ctx = rawSlots._ctx;
5075 for (const key in rawSlots) {
5076 if (isInternalKey(key))
5077 continue;
5078 const value = rawSlots[key];
5079 if (isFunction(value)) {
5080 slots[key] = normalizeSlot(key, value, ctx);
5081 }
5082 else if (value != null) {
5083 {
5084 warn$1(`Non-function value encountered for slot "${key}". ` +
5085 `Prefer function slots for better performance.`);
5086 }
5087 const normalized = normalizeSlotValue(value);
5088 slots[key] = () => normalized;
5089 }
5090 }
5091};
5092const normalizeVNodeSlots = (instance, children) => {
5093 if (!isKeepAlive(instance.vnode) &&
5094 !(false )) {
5095 warn$1(`Non-function value encountered for default slot. ` +
5096 `Prefer function slots for better performance.`);
5097 }
5098 const normalized = normalizeSlotValue(children);
5099 instance.slots.default = () => normalized;
5100};
5101const initSlots = (instance, children) => {
5102 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5103 const type = children._;
5104 if (type) {
5105 // users can get the shallow readonly version of the slots object through `this.$slots`,
5106 // we should avoid the proxy object polluting the slots of the internal instance
5107 instance.slots = toRaw(children);
5108 // make compiler marker non-enumerable
5109 def(children, '_', type);
5110 }
5111 else {
5112 normalizeObjectSlots(children, (instance.slots = {}));
5113 }
5114 }
5115 else {
5116 instance.slots = {};
5117 if (children) {
5118 normalizeVNodeSlots(instance, children);
5119 }
5120 }
5121 def(instance.slots, InternalObjectKey, 1);
5122};
5123const updateSlots = (instance, children, optimized) => {
5124 const { vnode, slots } = instance;
5125 let needDeletionCheck = true;
5126 let deletionComparisonTarget = EMPTY_OBJ;
5127 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5128 const type = children._;
5129 if (type) {
5130 // compiled slots.
5131 if (isHmrUpdating) {
5132 // Parent was HMR updated so slot content may have changed.
5133 // force update slots and mark instance for hmr as well
5134 extend(slots, children);
5135 }
5136 else if (optimized && type === 1 /* STABLE */) {
5137 // compiled AND stable.
5138 // no need to update, and skip stale slots removal.
5139 needDeletionCheck = false;
5140 }
5141 else {
5142 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5143 // normalization.
5144 extend(slots, children);
5145 // #2893
5146 // when rendering the optimized slots by manually written render function,
5147 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5148 // i.e. let the `renderSlot` create the bailed Fragment
5149 if (!optimized && type === 1 /* STABLE */) {
5150 delete slots._;
5151 }
5152 }
5153 }
5154 else {
5155 needDeletionCheck = !children.$stable;
5156 normalizeObjectSlots(children, slots);
5157 }
5158 deletionComparisonTarget = children;
5159 }
5160 else if (children) {
5161 // non slot object children (direct value) passed to a component
5162 normalizeVNodeSlots(instance, children);
5163 deletionComparisonTarget = { default: 1 };
5164 }
5165 // delete stale slots
5166 if (needDeletionCheck) {
5167 for (const key in slots) {
5168 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5169 delete slots[key];
5170 }
5171 }
5172 }
5173};
5174
5175/**
5176Runtime helper for applying directives to a vnode. Example usage:
5177
5178const comp = resolveComponent('comp')
5179const foo = resolveDirective('foo')
5180const bar = resolveDirective('bar')
5181
5182return withDirectives(h(comp), [
5183 [foo, this.x],
5184 [bar, this.y]
5185])
5186*/
5187const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
5188function validateDirectiveName(name) {
5189 if (isBuiltInDirective(name)) {
5190 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
5191 }
5192}
5193/**
5194 * Adds directives to a VNode.
5195 */
5196function withDirectives(vnode, directives) {
5197 const internalInstance = currentRenderingInstance;
5198 if (internalInstance === null) {
5199 warn$1(`withDirectives can only be used inside render functions.`);
5200 return vnode;
5201 }
5202 const instance = internalInstance.proxy;
5203 const bindings = vnode.dirs || (vnode.dirs = []);
5204 for (let i = 0; i < directives.length; i++) {
5205 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
5206 if (isFunction(dir)) {
5207 dir = {
5208 mounted: dir,
5209 updated: dir
5210 };
5211 }
5212 if (dir.deep) {
5213 traverse(value);
5214 }
5215 bindings.push({
5216 dir,
5217 instance,
5218 value,
5219 oldValue: void 0,
5220 arg,
5221 modifiers
5222 });
5223 }
5224 return vnode;
5225}
5226function invokeDirectiveHook(vnode, prevVNode, instance, name) {
5227 const bindings = vnode.dirs;
5228 const oldBindings = prevVNode && prevVNode.dirs;
5229 for (let i = 0; i < bindings.length; i++) {
5230 const binding = bindings[i];
5231 if (oldBindings) {
5232 binding.oldValue = oldBindings[i].value;
5233 }
5234 let hook = binding.dir[name];
5235 if (hook) {
5236 // disable tracking inside all lifecycle hooks
5237 // since they can potentially be called inside effects.
5238 pauseTracking();
5239 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
5240 vnode.el,
5241 binding,
5242 vnode,
5243 prevVNode
5244 ]);
5245 resetTracking();
5246 }
5247 }
5248}
5249
5250function createAppContext() {
5251 return {
5252 app: null,
5253 config: {
5254 isNativeTag: NO,
5255 performance: false,
5256 globalProperties: {},
5257 optionMergeStrategies: {},
5258 errorHandler: undefined,
5259 warnHandler: undefined,
5260 compilerOptions: {}
5261 },
5262 mixins: [],
5263 components: {},
5264 directives: {},
5265 provides: Object.create(null),
5266 optionsCache: new WeakMap(),
5267 propsCache: new WeakMap(),
5268 emitsCache: new WeakMap()
5269 };
5270}
5271let uid = 0;
5272function createAppAPI(render, hydrate) {
5273 return function createApp(rootComponent, rootProps = null) {
5274 if (rootProps != null && !isObject(rootProps)) {
5275 warn$1(`root props passed to app.mount() must be an object.`);
5276 rootProps = null;
5277 }
5278 const context = createAppContext();
5279 const installedPlugins = new Set();
5280 let isMounted = false;
5281 const app = (context.app = {
5282 _uid: uid++,
5283 _component: rootComponent,
5284 _props: rootProps,
5285 _container: null,
5286 _context: context,
5287 _instance: null,
5288 version,
5289 get config() {
5290 return context.config;
5291 },
5292 set config(v) {
5293 {
5294 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
5295 }
5296 },
5297 use(plugin, ...options) {
5298 if (installedPlugins.has(plugin)) {
5299 warn$1(`Plugin has already been applied to target app.`);
5300 }
5301 else if (plugin && isFunction(plugin.install)) {
5302 installedPlugins.add(plugin);
5303 plugin.install(app, ...options);
5304 }
5305 else if (isFunction(plugin)) {
5306 installedPlugins.add(plugin);
5307 plugin(app, ...options);
5308 }
5309 else {
5310 warn$1(`A plugin must either be a function or an object with an "install" ` +
5311 `function.`);
5312 }
5313 return app;
5314 },
5315 mixin(mixin) {
5316 {
5317 if (!context.mixins.includes(mixin)) {
5318 context.mixins.push(mixin);
5319 }
5320 else {
5321 warn$1('Mixin has already been applied to target app' +
5322 (mixin.name ? `: ${mixin.name}` : ''));
5323 }
5324 }
5325 return app;
5326 },
5327 component(name, component) {
5328 {
5329 validateComponentName(name, context.config);
5330 }
5331 if (!component) {
5332 return context.components[name];
5333 }
5334 if (context.components[name]) {
5335 warn$1(`Component "${name}" has already been registered in target app.`);
5336 }
5337 context.components[name] = component;
5338 return app;
5339 },
5340 directive(name, directive) {
5341 {
5342 validateDirectiveName(name);
5343 }
5344 if (!directive) {
5345 return context.directives[name];
5346 }
5347 if (context.directives[name]) {
5348 warn$1(`Directive "${name}" has already been registered in target app.`);
5349 }
5350 context.directives[name] = directive;
5351 return app;
5352 },
5353 mount(rootContainer, isHydrate, isSVG) {
5354 if (!isMounted) {
5355 const vnode = createVNode(rootComponent, rootProps);
5356 // store app context on the root VNode.
5357 // this will be set on the root instance on initial mount.
5358 vnode.appContext = context;
5359 // HMR root reload
5360 {
5361 context.reload = () => {
5362 render(cloneVNode(vnode), rootContainer, isSVG);
5363 };
5364 }
5365 if (isHydrate && hydrate) {
5366 hydrate(vnode, rootContainer);
5367 }
5368 else {
5369 render(vnode, rootContainer, isSVG);
5370 }
5371 isMounted = true;
5372 app._container = rootContainer;
5373 rootContainer.__vue_app__ = app;
5374 {
5375 app._instance = vnode.component;
5376 devtoolsInitApp(app, version);
5377 }
5378 return getExposeProxy(vnode.component) || vnode.component.proxy;
5379 }
5380 else {
5381 warn$1(`App has already been mounted.\n` +
5382 `If you want to remount the same app, move your app creation logic ` +
5383 `into a factory function and create fresh app instances for each ` +
5384 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5385 }
5386 },
5387 unmount() {
5388 if (isMounted) {
5389 render(null, app._container);
5390 {
5391 app._instance = null;
5392 devtoolsUnmountApp(app);
5393 }
5394 delete app._container.__vue_app__;
5395 }
5396 else {
5397 warn$1(`Cannot unmount an app that is not mounted.`);
5398 }
5399 },
5400 provide(key, value) {
5401 if (key in context.provides) {
5402 warn$1(`App already provides property with key "${String(key)}". ` +
5403 `It will be overwritten with the new value.`);
5404 }
5405 // TypeScript doesn't allow symbols as index type
5406 // https://github.com/Microsoft/TypeScript/issues/24587
5407 context.provides[key] = value;
5408 return app;
5409 }
5410 });
5411 return app;
5412 };
5413}
5414
5415/**
5416 * Function for handling a template ref
5417 */
5418function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
5419 if (isArray(rawRef)) {
5420 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
5421 return;
5422 }
5423 if (isAsyncWrapper(vnode) && !isUnmount) {
5424 // when mounting async components, nothing needs to be done,
5425 // because the template ref is forwarded to inner component
5426 return;
5427 }
5428 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
5429 ? getExposeProxy(vnode.component) || vnode.component.proxy
5430 : vnode.el;
5431 const value = isUnmount ? null : refValue;
5432 const { i: owner, r: ref } = rawRef;
5433 if (!owner) {
5434 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
5435 `A vnode with ref must be created inside the render function.`);
5436 return;
5437 }
5438 const oldRef = oldRawRef && oldRawRef.r;
5439 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
5440 const setupState = owner.setupState;
5441 // dynamic ref changed. unset old ref
5442 if (oldRef != null && oldRef !== ref) {
5443 if (isString(oldRef)) {
5444 refs[oldRef] = null;
5445 if (hasOwn(setupState, oldRef)) {
5446 setupState[oldRef] = null;
5447 }
5448 }
5449 else if (isRef(oldRef)) {
5450 oldRef.value = null;
5451 }
5452 }
5453 if (isFunction(ref)) {
5454 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
5455 }
5456 else {
5457 const _isString = isString(ref);
5458 const _isRef = isRef(ref);
5459 if (_isString || _isRef) {
5460 const doSet = () => {
5461 if (rawRef.f) {
5462 const existing = _isString ? refs[ref] : ref.value;
5463 if (isUnmount) {
5464 isArray(existing) && remove(existing, refValue);
5465 }
5466 else {
5467 if (!isArray(existing)) {
5468 if (_isString) {
5469 refs[ref] = [refValue];
5470 }
5471 else {
5472 ref.value = [refValue];
5473 if (rawRef.k)
5474 refs[rawRef.k] = ref.value;
5475 }
5476 }
5477 else if (!existing.includes(refValue)) {
5478 existing.push(refValue);
5479 }
5480 }
5481 }
5482 else if (_isString) {
5483 refs[ref] = value;
5484 if (hasOwn(setupState, ref)) {
5485 setupState[ref] = value;
5486 }
5487 }
5488 else if (isRef(ref)) {
5489 ref.value = value;
5490 if (rawRef.k)
5491 refs[rawRef.k] = value;
5492 }
5493 else {
5494 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5495 }
5496 };
5497 if (value) {
5498 doSet.id = -1;
5499 queuePostRenderEffect(doSet, parentSuspense);
5500 }
5501 else {
5502 doSet();
5503 }
5504 }
5505 else {
5506 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
5507 }
5508 }
5509}
5510
5511let hasMismatch = false;
5512const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5513const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5514// Note: hydration is DOM-specific
5515// But we have to place it in core due to tight coupling with core - splitting
5516// it out creates a ton of unnecessary complexity.
5517// Hydration also depends on some renderer internal logic which needs to be
5518// passed in via arguments.
5519function createHydrationFunctions(rendererInternals) {
5520 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5521 const hydrate = (vnode, container) => {
5522 if (!container.hasChildNodes()) {
5523 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5524 `Performing full mount instead.`);
5525 patch(null, vnode, container);
5526 flushPostFlushCbs();
5527 return;
5528 }
5529 hasMismatch = false;
5530 hydrateNode(container.firstChild, vnode, null, null, null);
5531 flushPostFlushCbs();
5532 if (hasMismatch && !false) {
5533 // this error should show up in production
5534 console.error(`Hydration completed but contains mismatches.`);
5535 }
5536 };
5537 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5538 const isFragmentStart = isComment(node) && node.data === '[';
5539 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5540 const { type, ref, shapeFlag } = vnode;
5541 const domType = node.nodeType;
5542 vnode.el = node;
5543 let nextNode = null;
5544 switch (type) {
5545 case Text:
5546 if (domType !== 3 /* TEXT */) {
5547 nextNode = onMismatch();
5548 }
5549 else {
5550 if (node.data !== vnode.children) {
5551 hasMismatch = true;
5552 warn$1(`Hydration text mismatch:` +
5553 `\n- Client: ${JSON.stringify(node.data)}` +
5554 `\n- Server: ${JSON.stringify(vnode.children)}`);
5555 node.data = vnode.children;
5556 }
5557 nextNode = nextSibling(node);
5558 }
5559 break;
5560 case Comment:
5561 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5562 nextNode = onMismatch();
5563 }
5564 else {
5565 nextNode = nextSibling(node);
5566 }
5567 break;
5568 case Static:
5569 if (domType !== 1 /* ELEMENT */) {
5570 nextNode = onMismatch();
5571 }
5572 else {
5573 // determine anchor, adopt content
5574 nextNode = node;
5575 // if the static vnode has its content stripped during build,
5576 // adopt it from the server-rendered HTML.
5577 const needToAdoptContent = !vnode.children.length;
5578 for (let i = 0; i < vnode.staticCount; i++) {
5579 if (needToAdoptContent)
5580 vnode.children += nextNode.outerHTML;
5581 if (i === vnode.staticCount - 1) {
5582 vnode.anchor = nextNode;
5583 }
5584 nextNode = nextSibling(nextNode);
5585 }
5586 return nextNode;
5587 }
5588 break;
5589 case Fragment:
5590 if (!isFragmentStart) {
5591 nextNode = onMismatch();
5592 }
5593 else {
5594 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5595 }
5596 break;
5597 default:
5598 if (shapeFlag & 1 /* ELEMENT */) {
5599 if (domType !== 1 /* ELEMENT */ ||
5600 vnode.type.toLowerCase() !==
5601 node.tagName.toLowerCase()) {
5602 nextNode = onMismatch();
5603 }
5604 else {
5605 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5606 }
5607 }
5608 else if (shapeFlag & 6 /* COMPONENT */) {
5609 // when setting up the render effect, if the initial vnode already
5610 // has .el set, the component will perform hydration instead of mount
5611 // on its sub-tree.
5612 vnode.slotScopeIds = slotScopeIds;
5613 const container = parentNode(node);
5614 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5615 // component may be async, so in the case of fragments we cannot rely
5616 // on component's rendered output to determine the end of the fragment
5617 // instead, we do a lookahead to find the end anchor node.
5618 nextNode = isFragmentStart
5619 ? locateClosingAsyncAnchor(node)
5620 : nextSibling(node);
5621 // #3787
5622 // if component is async, it may get moved / unmounted before its
5623 // inner component is loaded, so we need to give it a placeholder
5624 // vnode that matches its adopted DOM.
5625 if (isAsyncWrapper(vnode)) {
5626 let subTree;
5627 if (isFragmentStart) {
5628 subTree = createVNode(Fragment);
5629 subTree.anchor = nextNode
5630 ? nextNode.previousSibling
5631 : container.lastChild;
5632 }
5633 else {
5634 subTree =
5635 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5636 }
5637 subTree.el = node;
5638 vnode.component.subTree = subTree;
5639 }
5640 }
5641 else if (shapeFlag & 64 /* TELEPORT */) {
5642 if (domType !== 8 /* COMMENT */) {
5643 nextNode = onMismatch();
5644 }
5645 else {
5646 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5647 }
5648 }
5649 else if (shapeFlag & 128 /* SUSPENSE */) {
5650 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5651 }
5652 else {
5653 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5654 }
5655 }
5656 if (ref != null) {
5657 setRef(ref, null, parentSuspense, vnode);
5658 }
5659 return nextNode;
5660 };
5661 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5662 optimized = optimized || !!vnode.dynamicChildren;
5663 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5664 // #4006 for form elements with non-string v-model value bindings
5665 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5666 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5667 // skip props & children if this is hoisted static nodes
5668 if (forcePatchValue || patchFlag !== -1 /* HOISTED */) {
5669 if (dirs) {
5670 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5671 }
5672 // props
5673 if (props) {
5674 if (forcePatchValue ||
5675 !optimized ||
5676 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5677 for (const key in props) {
5678 if ((forcePatchValue && key.endsWith('value')) ||
5679 (isOn(key) && !isReservedProp(key))) {
5680 patchProp(el, key, null, props[key], false, undefined, parentComponent);
5681 }
5682 }
5683 }
5684 else if (props.onClick) {
5685 // Fast path for click listeners (which is most often) to avoid
5686 // iterating through props.
5687 patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
5688 }
5689 }
5690 // vnode / directive hooks
5691 let vnodeHooks;
5692 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5693 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5694 }
5695 if (dirs) {
5696 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5697 }
5698 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5699 queueEffectWithSuspense(() => {
5700 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5701 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5702 }, parentSuspense);
5703 }
5704 // children
5705 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5706 // skip if element has innerHTML / textContent
5707 !(props && (props.innerHTML || props.textContent))) {
5708 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5709 let hasWarned = false;
5710 while (next) {
5711 hasMismatch = true;
5712 if (!hasWarned) {
5713 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5714 `server rendered element contains more child nodes than client vdom.`);
5715 hasWarned = true;
5716 }
5717 // The SSRed DOM contains more nodes than it should. Remove them.
5718 const cur = next;
5719 next = next.nextSibling;
5720 remove(cur);
5721 }
5722 }
5723 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5724 if (el.textContent !== vnode.children) {
5725 hasMismatch = true;
5726 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5727 `- Client: ${el.textContent}\n` +
5728 `- Server: ${vnode.children}`);
5729 el.textContent = vnode.children;
5730 }
5731 }
5732 }
5733 return el.nextSibling;
5734 };
5735 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5736 optimized = optimized || !!parentVNode.dynamicChildren;
5737 const children = parentVNode.children;
5738 const l = children.length;
5739 let hasWarned = false;
5740 for (let i = 0; i < l; i++) {
5741 const vnode = optimized
5742 ? children[i]
5743 : (children[i] = normalizeVNode(children[i]));
5744 if (node) {
5745 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5746 }
5747 else if (vnode.type === Text && !vnode.children) {
5748 continue;
5749 }
5750 else {
5751 hasMismatch = true;
5752 if (!hasWarned) {
5753 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5754 `server rendered element contains fewer child nodes than client vdom.`);
5755 hasWarned = true;
5756 }
5757 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5758 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5759 }
5760 }
5761 return node;
5762 };
5763 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5764 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5765 if (fragmentSlotScopeIds) {
5766 slotScopeIds = slotScopeIds
5767 ? slotScopeIds.concat(fragmentSlotScopeIds)
5768 : fragmentSlotScopeIds;
5769 }
5770 const container = parentNode(node);
5771 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5772 if (next && isComment(next) && next.data === ']') {
5773 return nextSibling((vnode.anchor = next));
5774 }
5775 else {
5776 // fragment didn't hydrate successfully, since we didn't get a end anchor
5777 // back. This should have led to node/children mismatch warnings.
5778 hasMismatch = true;
5779 // since the anchor is missing, we need to create one and insert it
5780 insert((vnode.anchor = createComment(`]`)), container, next);
5781 return next;
5782 }
5783 };
5784 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5785 hasMismatch = true;
5786 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5787 ? `(text)`
5788 : isComment(node) && node.data === '['
5789 ? `(start of fragment)`
5790 : ``);
5791 vnode.el = null;
5792 if (isFragment) {
5793 // remove excessive fragment nodes
5794 const end = locateClosingAsyncAnchor(node);
5795 while (true) {
5796 const next = nextSibling(node);
5797 if (next && next !== end) {
5798 remove(next);
5799 }
5800 else {
5801 break;
5802 }
5803 }
5804 }
5805 const next = nextSibling(node);
5806 const container = parentNode(node);
5807 remove(node);
5808 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5809 return next;
5810 };
5811 const locateClosingAsyncAnchor = (node) => {
5812 let match = 0;
5813 while (node) {
5814 node = nextSibling(node);
5815 if (node && isComment(node)) {
5816 if (node.data === '[')
5817 match++;
5818 if (node.data === ']') {
5819 if (match === 0) {
5820 return nextSibling(node);
5821 }
5822 else {
5823 match--;
5824 }
5825 }
5826 }
5827 }
5828 return node;
5829 };
5830 return [hydrate, hydrateNode];
5831}
5832
5833/* eslint-disable no-restricted-globals */
5834let supported;
5835let perf;
5836function startMeasure(instance, type) {
5837 if (instance.appContext.config.performance && isSupported()) {
5838 perf.mark(`vue-${type}-${instance.uid}`);
5839 }
5840 {
5841 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5842 }
5843}
5844function endMeasure(instance, type) {
5845 if (instance.appContext.config.performance && isSupported()) {
5846 const startTag = `vue-${type}-${instance.uid}`;
5847 const endTag = startTag + `:end`;
5848 perf.mark(endTag);
5849 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5850 perf.clearMarks(startTag);
5851 perf.clearMarks(endTag);
5852 }
5853 {
5854 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5855 }
5856}
5857function isSupported() {
5858 if (supported !== undefined) {
5859 return supported;
5860 }
5861 if (typeof window !== 'undefined' && window.performance) {
5862 supported = true;
5863 perf = window.performance;
5864 }
5865 else {
5866 supported = false;
5867 }
5868 return supported;
5869}
5870
5871const queuePostRenderEffect = queueEffectWithSuspense
5872 ;
5873/**
5874 * The createRenderer function accepts two generic arguments:
5875 * HostNode and HostElement, corresponding to Node and Element types in the
5876 * host environment. For example, for runtime-dom, HostNode would be the DOM
5877 * `Node` interface and HostElement would be the DOM `Element` interface.
5878 *
5879 * Custom renderers can pass in the platform specific types like this:
5880 *
5881 * ``` js
5882 * const { render, createApp } = createRenderer<Node, Element>({
5883 * patchProp,
5884 * ...nodeOps
5885 * })
5886 * ```
5887 */
5888function createRenderer(options) {
5889 return baseCreateRenderer(options);
5890}
5891// Separate API for creating hydration-enabled renderer.
5892// Hydration logic is only used when calling this function, making it
5893// tree-shakable.
5894function createHydrationRenderer(options) {
5895 return baseCreateRenderer(options, createHydrationFunctions);
5896}
5897// implementation
5898function baseCreateRenderer(options, createHydrationFns) {
5899 const target = getGlobalThis();
5900 target.__VUE__ = true;
5901 {
5902 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
5903 }
5904 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;
5905 // Note: functions inside this closure should use `const xxx = () => {}`
5906 // style in order to prevent being inlined by minifiers.
5907 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5908 if (n1 === n2) {
5909 return;
5910 }
5911 // patching & not same type, unmount old tree
5912 if (n1 && !isSameVNodeType(n1, n2)) {
5913 anchor = getNextHostNode(n1);
5914 unmount(n1, parentComponent, parentSuspense, true);
5915 n1 = null;
5916 }
5917 if (n2.patchFlag === -2 /* BAIL */) {
5918 optimized = false;
5919 n2.dynamicChildren = null;
5920 }
5921 const { type, ref, shapeFlag } = n2;
5922 switch (type) {
5923 case Text:
5924 processText(n1, n2, container, anchor);
5925 break;
5926 case Comment:
5927 processCommentNode(n1, n2, container, anchor);
5928 break;
5929 case Static:
5930 if (n1 == null) {
5931 mountStaticNode(n2, container, anchor, isSVG);
5932 }
5933 else {
5934 patchStaticNode(n1, n2, container, isSVG);
5935 }
5936 break;
5937 case Fragment:
5938 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5939 break;
5940 default:
5941 if (shapeFlag & 1 /* ELEMENT */) {
5942 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5943 }
5944 else if (shapeFlag & 6 /* COMPONENT */) {
5945 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5946 }
5947 else if (shapeFlag & 64 /* TELEPORT */) {
5948 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5949 }
5950 else if (shapeFlag & 128 /* SUSPENSE */) {
5951 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5952 }
5953 else {
5954 warn$1('Invalid VNode type:', type, `(${typeof type})`);
5955 }
5956 }
5957 // set ref
5958 if (ref != null && parentComponent) {
5959 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5960 }
5961 };
5962 const processText = (n1, n2, container, anchor) => {
5963 if (n1 == null) {
5964 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5965 }
5966 else {
5967 const el = (n2.el = n1.el);
5968 if (n2.children !== n1.children) {
5969 hostSetText(el, n2.children);
5970 }
5971 }
5972 };
5973 const processCommentNode = (n1, n2, container, anchor) => {
5974 if (n1 == null) {
5975 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5976 }
5977 else {
5978 // there's no support for dynamic comments
5979 n2.el = n1.el;
5980 }
5981 };
5982 const mountStaticNode = (n2, container, anchor, isSVG) => {
5983 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
5984 };
5985 /**
5986 * Dev / HMR only
5987 */
5988 const patchStaticNode = (n1, n2, container, isSVG) => {
5989 // static nodes are only patched during dev for HMR
5990 if (n2.children !== n1.children) {
5991 const anchor = hostNextSibling(n1.anchor);
5992 // remove existing
5993 removeStaticNode(n1);
5994 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5995 }
5996 else {
5997 n2.el = n1.el;
5998 n2.anchor = n1.anchor;
5999 }
6000 };
6001 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
6002 let next;
6003 while (el && el !== anchor) {
6004 next = hostNextSibling(el);
6005 hostInsert(el, container, nextSibling);
6006 el = next;
6007 }
6008 hostInsert(anchor, container, nextSibling);
6009 };
6010 const removeStaticNode = ({ el, anchor }) => {
6011 let next;
6012 while (el && el !== anchor) {
6013 next = hostNextSibling(el);
6014 hostRemove(el);
6015 el = next;
6016 }
6017 hostRemove(anchor);
6018 };
6019 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6020 isSVG = isSVG || n2.type === 'svg';
6021 if (n1 == null) {
6022 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6023 }
6024 else {
6025 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6026 }
6027 };
6028 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6029 let el;
6030 let vnodeHook;
6031 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
6032 {
6033 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
6034 // mount children first, since some props may rely on child content
6035 // being already rendered, e.g. `<select value>`
6036 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6037 hostSetElementText(el, vnode.children);
6038 }
6039 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6040 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
6041 }
6042 if (dirs) {
6043 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6044 }
6045 // props
6046 if (props) {
6047 for (const key in props) {
6048 if (key !== 'value' && !isReservedProp(key)) {
6049 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6050 }
6051 }
6052 /**
6053 * Special case for setting value on DOM elements:
6054 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
6055 * - it needs to be forced (#1471)
6056 * #2353 proposes adding another renderer option to configure this, but
6057 * the properties affects are so finite it is worth special casing it
6058 * here to reduce the complexity. (Special casing it also should not
6059 * affect non-DOM renderers)
6060 */
6061 if ('value' in props) {
6062 hostPatchProp(el, 'value', null, props.value);
6063 }
6064 if ((vnodeHook = props.onVnodeBeforeMount)) {
6065 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6066 }
6067 }
6068 // scopeId
6069 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
6070 }
6071 {
6072 Object.defineProperty(el, '__vnode', {
6073 value: vnode,
6074 enumerable: false
6075 });
6076 Object.defineProperty(el, '__vueParentComponent', {
6077 value: parentComponent,
6078 enumerable: false
6079 });
6080 }
6081 if (dirs) {
6082 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6083 }
6084 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
6085 // #1689 For inside suspense + suspense resolved case, just call it
6086 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
6087 transition &&
6088 !transition.persisted;
6089 if (needCallTransitionHooks) {
6090 transition.beforeEnter(el);
6091 }
6092 hostInsert(el, container, anchor);
6093 if ((vnodeHook = props && props.onVnodeMounted) ||
6094 needCallTransitionHooks ||
6095 dirs) {
6096 queuePostRenderEffect(() => {
6097 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6098 needCallTransitionHooks && transition.enter(el);
6099 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6100 }, parentSuspense);
6101 }
6102 };
6103 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6104 if (scopeId) {
6105 hostSetScopeId(el, scopeId);
6106 }
6107 if (slotScopeIds) {
6108 for (let i = 0; i < slotScopeIds.length; i++) {
6109 hostSetScopeId(el, slotScopeIds[i]);
6110 }
6111 }
6112 if (parentComponent) {
6113 let subTree = parentComponent.subTree;
6114 if (subTree.patchFlag > 0 &&
6115 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
6116 subTree =
6117 filterSingleRoot(subTree.children) || subTree;
6118 }
6119 if (vnode === subTree) {
6120 const parentVNode = parentComponent.vnode;
6121 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6122 }
6123 }
6124 };
6125 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6126 for (let i = start; i < children.length; i++) {
6127 const child = (children[i] = optimized
6128 ? cloneIfMounted(children[i])
6129 : normalizeVNode(children[i]));
6130 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6131 }
6132 };
6133 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6134 const el = (n2.el = n1.el);
6135 let { patchFlag, dynamicChildren, dirs } = n2;
6136 // #1426 take the old vnode's patch flag into account since user may clone a
6137 // compiler-generated vnode, which de-opts to FULL_PROPS
6138 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
6139 const oldProps = n1.props || EMPTY_OBJ;
6140 const newProps = n2.props || EMPTY_OBJ;
6141 let vnodeHook;
6142 // disable recurse in beforeUpdate hooks
6143 parentComponent && toggleRecurse(parentComponent, false);
6144 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6145 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6146 }
6147 if (dirs) {
6148 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6149 }
6150 parentComponent && toggleRecurse(parentComponent, true);
6151 if (isHmrUpdating) {
6152 // HMR updated, force full diff
6153 patchFlag = 0;
6154 optimized = false;
6155 dynamicChildren = null;
6156 }
6157 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6158 if (dynamicChildren) {
6159 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6160 if (parentComponent && parentComponent.type.__hmrId) {
6161 traverseStaticChildren(n1, n2);
6162 }
6163 }
6164 else if (!optimized) {
6165 // full diff
6166 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6167 }
6168 if (patchFlag > 0) {
6169 // the presence of a patchFlag means this element's render code was
6170 // generated by the compiler and can take the fast path.
6171 // in this path old node and new node are guaranteed to have the same shape
6172 // (i.e. at the exact same position in the source template)
6173 if (patchFlag & 16 /* FULL_PROPS */) {
6174 // element props contain dynamic keys, full diff needed
6175 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6176 }
6177 else {
6178 // class
6179 // this flag is matched when the element has dynamic class bindings.
6180 if (patchFlag & 2 /* CLASS */) {
6181 if (oldProps.class !== newProps.class) {
6182 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6183 }
6184 }
6185 // style
6186 // this flag is matched when the element has dynamic style bindings
6187 if (patchFlag & 4 /* STYLE */) {
6188 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6189 }
6190 // props
6191 // This flag is matched when the element has dynamic prop/attr bindings
6192 // other than class and style. The keys of dynamic prop/attrs are saved for
6193 // faster iteration.
6194 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6195 // bail out and go through a full diff because we need to unset the old key
6196 if (patchFlag & 8 /* PROPS */) {
6197 // if the flag is present then dynamicProps must be non-null
6198 const propsToUpdate = n2.dynamicProps;
6199 for (let i = 0; i < propsToUpdate.length; i++) {
6200 const key = propsToUpdate[i];
6201 const prev = oldProps[key];
6202 const next = newProps[key];
6203 // #1471 force patch value
6204 if (next !== prev || key === 'value') {
6205 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6206 }
6207 }
6208 }
6209 }
6210 // text
6211 // This flag is matched when the element has only dynamic text children.
6212 if (patchFlag & 1 /* TEXT */) {
6213 if (n1.children !== n2.children) {
6214 hostSetElementText(el, n2.children);
6215 }
6216 }
6217 }
6218 else if (!optimized && dynamicChildren == null) {
6219 // unoptimized, full diff
6220 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6221 }
6222 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6223 queuePostRenderEffect(() => {
6224 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6225 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6226 }, parentSuspense);
6227 }
6228 };
6229 // The fast path for blocks.
6230 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6231 for (let i = 0; i < newChildren.length; i++) {
6232 const oldVNode = oldChildren[i];
6233 const newVNode = newChildren[i];
6234 // Determine the container (parent element) for the patch.
6235 const container =
6236 // oldVNode may be an errored async setup() component inside Suspense
6237 // which will not have a mounted element
6238 oldVNode.el &&
6239 // - In the case of a Fragment, we need to provide the actual parent
6240 // of the Fragment itself so it can move its children.
6241 (oldVNode.type === Fragment ||
6242 // - In the case of different nodes, there is going to be a replacement
6243 // which also requires the correct parent container
6244 !isSameVNodeType(oldVNode, newVNode) ||
6245 // - In the case of a component, it could contain anything.
6246 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
6247 ? hostParentNode(oldVNode.el)
6248 : // In other cases, the parent container is not actually used so we
6249 // just pass the block element here to avoid a DOM parentNode call.
6250 fallbackContainer;
6251 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6252 }
6253 };
6254 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6255 if (oldProps !== newProps) {
6256 for (const key in newProps) {
6257 // empty string is not valid prop
6258 if (isReservedProp(key))
6259 continue;
6260 const next = newProps[key];
6261 const prev = oldProps[key];
6262 // defer patching value
6263 if (next !== prev && key !== 'value') {
6264 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6265 }
6266 }
6267 if (oldProps !== EMPTY_OBJ) {
6268 for (const key in oldProps) {
6269 if (!isReservedProp(key) && !(key in newProps)) {
6270 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6271 }
6272 }
6273 }
6274 if ('value' in newProps) {
6275 hostPatchProp(el, 'value', oldProps.value, newProps.value);
6276 }
6277 }
6278 };
6279 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6280 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6281 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6282 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6283 if (isHmrUpdating) {
6284 // HMR updated, force full diff
6285 patchFlag = 0;
6286 optimized = false;
6287 dynamicChildren = null;
6288 }
6289 // check if this is a slot fragment with :slotted scope ids
6290 if (fragmentSlotScopeIds) {
6291 slotScopeIds = slotScopeIds
6292 ? slotScopeIds.concat(fragmentSlotScopeIds)
6293 : fragmentSlotScopeIds;
6294 }
6295 if (n1 == null) {
6296 hostInsert(fragmentStartAnchor, container, anchor);
6297 hostInsert(fragmentEndAnchor, container, anchor);
6298 // a fragment can only have array children
6299 // since they are either generated by the compiler, or implicitly created
6300 // from arrays.
6301 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6302 }
6303 else {
6304 if (patchFlag > 0 &&
6305 patchFlag & 64 /* STABLE_FRAGMENT */ &&
6306 dynamicChildren &&
6307 // #2715 the previous fragment could've been a BAILed one as a result
6308 // of renderSlot() with no valid children
6309 n1.dynamicChildren) {
6310 // a stable fragment (template root or <template v-for>) doesn't need to
6311 // patch children order, but it may contain dynamicChildren.
6312 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6313 if (parentComponent && parentComponent.type.__hmrId) {
6314 traverseStaticChildren(n1, n2);
6315 }
6316 else if (
6317 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6318 // get moved around. Make sure all root level vnodes inherit el.
6319 // #2134 or if it's a component root, it may also get moved around
6320 // as the component is being moved.
6321 n2.key != null ||
6322 (parentComponent && n2 === parentComponent.subTree)) {
6323 traverseStaticChildren(n1, n2, true /* shallow */);
6324 }
6325 }
6326 else {
6327 // keyed / unkeyed, or manual fragments.
6328 // for keyed & unkeyed, since they are compiler generated from v-for,
6329 // each child is guaranteed to be a block so the fragment will never
6330 // have dynamicChildren.
6331 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6332 }
6333 }
6334 };
6335 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6336 n2.slotScopeIds = slotScopeIds;
6337 if (n1 == null) {
6338 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
6339 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6340 }
6341 else {
6342 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6343 }
6344 }
6345 else {
6346 updateComponent(n1, n2, optimized);
6347 }
6348 };
6349 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6350 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6351 if (instance.type.__hmrId) {
6352 registerHMR(instance);
6353 }
6354 {
6355 pushWarningContext(initialVNode);
6356 startMeasure(instance, `mount`);
6357 }
6358 // inject renderer internals for keepAlive
6359 if (isKeepAlive(initialVNode)) {
6360 instance.ctx.renderer = internals;
6361 }
6362 // resolve props and slots for setup context
6363 {
6364 {
6365 startMeasure(instance, `init`);
6366 }
6367 setupComponent(instance);
6368 {
6369 endMeasure(instance, `init`);
6370 }
6371 }
6372 // setup() is async. This component relies on async logic to be resolved
6373 // before proceeding
6374 if (instance.asyncDep) {
6375 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
6376 // Give it a placeholder if this is not hydration
6377 // TODO handle self-defined fallback
6378 if (!initialVNode.el) {
6379 const placeholder = (instance.subTree = createVNode(Comment));
6380 processCommentNode(null, placeholder, container, anchor);
6381 }
6382 return;
6383 }
6384 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
6385 {
6386 popWarningContext();
6387 endMeasure(instance, `mount`);
6388 }
6389 };
6390 const updateComponent = (n1, n2, optimized) => {
6391 const instance = (n2.component = n1.component);
6392 if (shouldUpdateComponent(n1, n2, optimized)) {
6393 if (instance.asyncDep &&
6394 !instance.asyncResolved) {
6395 // async & still pending - just update props and slots
6396 // since the component's reactive effect for render isn't set-up yet
6397 {
6398 pushWarningContext(n2);
6399 }
6400 updateComponentPreRender(instance, n2, optimized);
6401 {
6402 popWarningContext();
6403 }
6404 return;
6405 }
6406 else {
6407 // normal update
6408 instance.next = n2;
6409 // in case the child component is also queued, remove it to avoid
6410 // double updating the same child component in the same flush.
6411 invalidateJob(instance.update);
6412 // instance.update is the reactive effect.
6413 instance.update();
6414 }
6415 }
6416 else {
6417 // no update needed. just copy over properties
6418 n2.component = n1.component;
6419 n2.el = n1.el;
6420 instance.vnode = n2;
6421 }
6422 };
6423 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
6424 const componentUpdateFn = () => {
6425 if (!instance.isMounted) {
6426 let vnodeHook;
6427 const { el, props } = initialVNode;
6428 const { bm, m, parent } = instance;
6429 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
6430 toggleRecurse(instance, false);
6431 // beforeMount hook
6432 if (bm) {
6433 invokeArrayFns(bm);
6434 }
6435 // onVnodeBeforeMount
6436 if (!isAsyncWrapperVNode &&
6437 (vnodeHook = props && props.onVnodeBeforeMount)) {
6438 invokeVNodeHook(vnodeHook, parent, initialVNode);
6439 }
6440 toggleRecurse(instance, true);
6441 if (el && hydrateNode) {
6442 // vnode has adopted host node - perform hydration instead of mount.
6443 const hydrateSubTree = () => {
6444 {
6445 startMeasure(instance, `render`);
6446 }
6447 instance.subTree = renderComponentRoot(instance);
6448 {
6449 endMeasure(instance, `render`);
6450 }
6451 {
6452 startMeasure(instance, `hydrate`);
6453 }
6454 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
6455 {
6456 endMeasure(instance, `hydrate`);
6457 }
6458 };
6459 if (isAsyncWrapperVNode) {
6460 initialVNode.type.__asyncLoader().then(
6461 // note: we are moving the render call into an async callback,
6462 // which means it won't track dependencies - but it's ok because
6463 // a server-rendered async wrapper is already in resolved state
6464 // and it will never need to change.
6465 () => !instance.isUnmounted && hydrateSubTree());
6466 }
6467 else {
6468 hydrateSubTree();
6469 }
6470 }
6471 else {
6472 {
6473 startMeasure(instance, `render`);
6474 }
6475 const subTree = (instance.subTree = renderComponentRoot(instance));
6476 {
6477 endMeasure(instance, `render`);
6478 }
6479 {
6480 startMeasure(instance, `patch`);
6481 }
6482 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
6483 {
6484 endMeasure(instance, `patch`);
6485 }
6486 initialVNode.el = subTree.el;
6487 }
6488 // mounted hook
6489 if (m) {
6490 queuePostRenderEffect(m, parentSuspense);
6491 }
6492 // onVnodeMounted
6493 if (!isAsyncWrapperVNode &&
6494 (vnodeHook = props && props.onVnodeMounted)) {
6495 const scopedInitialVNode = initialVNode;
6496 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
6497 }
6498 // activated hook for keep-alive roots.
6499 // #1742 activated hook must be accessed after first render
6500 // since the hook may be injected by a child keep-alive
6501 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6502 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
6503 }
6504 instance.isMounted = true;
6505 {
6506 devtoolsComponentAdded(instance);
6507 }
6508 // #2458: deference mount-only object parameters to prevent memleaks
6509 initialVNode = container = anchor = null;
6510 }
6511 else {
6512 // updateComponent
6513 // This is triggered by mutation of component's own state (next: null)
6514 // OR parent calling processComponent (next: VNode)
6515 let { next, bu, u, parent, vnode } = instance;
6516 let originNext = next;
6517 let vnodeHook;
6518 {
6519 pushWarningContext(next || instance.vnode);
6520 }
6521 // Disallow component effect recursion during pre-lifecycle hooks.
6522 toggleRecurse(instance, false);
6523 if (next) {
6524 next.el = vnode.el;
6525 updateComponentPreRender(instance, next, optimized);
6526 }
6527 else {
6528 next = vnode;
6529 }
6530 // beforeUpdate hook
6531 if (bu) {
6532 invokeArrayFns(bu);
6533 }
6534 // onVnodeBeforeUpdate
6535 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6536 invokeVNodeHook(vnodeHook, parent, next, vnode);
6537 }
6538 toggleRecurse(instance, true);
6539 // render
6540 {
6541 startMeasure(instance, `render`);
6542 }
6543 const nextTree = renderComponentRoot(instance);
6544 {
6545 endMeasure(instance, `render`);
6546 }
6547 const prevTree = instance.subTree;
6548 instance.subTree = nextTree;
6549 {
6550 startMeasure(instance, `patch`);
6551 }
6552 patch(prevTree, nextTree,
6553 // parent may have changed if it's in a teleport
6554 hostParentNode(prevTree.el),
6555 // anchor may have changed if it's in a fragment
6556 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6557 {
6558 endMeasure(instance, `patch`);
6559 }
6560 next.el = nextTree.el;
6561 if (originNext === null) {
6562 // self-triggered update. In case of HOC, update parent component
6563 // vnode el. HOC is indicated by parent instance's subTree pointing
6564 // to child component's vnode
6565 updateHOCHostEl(instance, nextTree.el);
6566 }
6567 // updated hook
6568 if (u) {
6569 queuePostRenderEffect(u, parentSuspense);
6570 }
6571 // onVnodeUpdated
6572 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6573 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6574 }
6575 {
6576 devtoolsComponentUpdated(instance);
6577 }
6578 {
6579 popWarningContext();
6580 }
6581 }
6582 };
6583 // create reactive effect for rendering
6584 const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6585 ));
6586 const update = (instance.update = effect.run.bind(effect));
6587 update.id = instance.uid;
6588 // allowRecurse
6589 // #1801, #2043 component render effects should allow recursive updates
6590 toggleRecurse(instance, true);
6591 {
6592 effect.onTrack = instance.rtc
6593 ? e => invokeArrayFns(instance.rtc, e)
6594 : void 0;
6595 effect.onTrigger = instance.rtg
6596 ? e => invokeArrayFns(instance.rtg, e)
6597 : void 0;
6598 // @ts-ignore (for scheduler)
6599 update.ownerInstance = instance;
6600 }
6601 update();
6602 };
6603 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6604 nextVNode.component = instance;
6605 const prevProps = instance.vnode.props;
6606 instance.vnode = nextVNode;
6607 instance.next = null;
6608 updateProps(instance, nextVNode.props, prevProps, optimized);
6609 updateSlots(instance, nextVNode.children, optimized);
6610 pauseTracking();
6611 // props update may have triggered pre-flush watchers.
6612 // flush them before the render update.
6613 flushPreFlushCbs(undefined, instance.update);
6614 resetTracking();
6615 };
6616 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6617 const c1 = n1 && n1.children;
6618 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6619 const c2 = n2.children;
6620 const { patchFlag, shapeFlag } = n2;
6621 // fast path
6622 if (patchFlag > 0) {
6623 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6624 // this could be either fully-keyed or mixed (some keyed some not)
6625 // presence of patchFlag means children are guaranteed to be arrays
6626 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6627 return;
6628 }
6629 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6630 // unkeyed
6631 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6632 return;
6633 }
6634 }
6635 // children has 3 possibilities: text, array or no children.
6636 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6637 // text children fast path
6638 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6639 unmountChildren(c1, parentComponent, parentSuspense);
6640 }
6641 if (c2 !== c1) {
6642 hostSetElementText(container, c2);
6643 }
6644 }
6645 else {
6646 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6647 // prev children was array
6648 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6649 // two arrays, cannot assume anything, do full diff
6650 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6651 }
6652 else {
6653 // no new children, just unmount old
6654 unmountChildren(c1, parentComponent, parentSuspense, true);
6655 }
6656 }
6657 else {
6658 // prev children was text OR null
6659 // new children is array OR null
6660 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6661 hostSetElementText(container, '');
6662 }
6663 // mount new if array
6664 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6665 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6666 }
6667 }
6668 }
6669 };
6670 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6671 c1 = c1 || EMPTY_ARR;
6672 c2 = c2 || EMPTY_ARR;
6673 const oldLength = c1.length;
6674 const newLength = c2.length;
6675 const commonLength = Math.min(oldLength, newLength);
6676 let i;
6677 for (i = 0; i < commonLength; i++) {
6678 const nextChild = (c2[i] = optimized
6679 ? cloneIfMounted(c2[i])
6680 : normalizeVNode(c2[i]));
6681 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6682 }
6683 if (oldLength > newLength) {
6684 // remove old
6685 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6686 }
6687 else {
6688 // mount new
6689 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6690 }
6691 };
6692 // can be all-keyed or mixed
6693 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6694 let i = 0;
6695 const l2 = c2.length;
6696 let e1 = c1.length - 1; // prev ending index
6697 let e2 = l2 - 1; // next ending index
6698 // 1. sync from start
6699 // (a b) c
6700 // (a b) d e
6701 while (i <= e1 && i <= e2) {
6702 const n1 = c1[i];
6703 const n2 = (c2[i] = optimized
6704 ? cloneIfMounted(c2[i])
6705 : normalizeVNode(c2[i]));
6706 if (isSameVNodeType(n1, n2)) {
6707 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6708 }
6709 else {
6710 break;
6711 }
6712 i++;
6713 }
6714 // 2. sync from end
6715 // a (b c)
6716 // d e (b c)
6717 while (i <= e1 && i <= e2) {
6718 const n1 = c1[e1];
6719 const n2 = (c2[e2] = optimized
6720 ? cloneIfMounted(c2[e2])
6721 : normalizeVNode(c2[e2]));
6722 if (isSameVNodeType(n1, n2)) {
6723 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6724 }
6725 else {
6726 break;
6727 }
6728 e1--;
6729 e2--;
6730 }
6731 // 3. common sequence + mount
6732 // (a b)
6733 // (a b) c
6734 // i = 2, e1 = 1, e2 = 2
6735 // (a b)
6736 // c (a b)
6737 // i = 0, e1 = -1, e2 = 0
6738 if (i > e1) {
6739 if (i <= e2) {
6740 const nextPos = e2 + 1;
6741 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6742 while (i <= e2) {
6743 patch(null, (c2[i] = optimized
6744 ? cloneIfMounted(c2[i])
6745 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6746 i++;
6747 }
6748 }
6749 }
6750 // 4. common sequence + unmount
6751 // (a b) c
6752 // (a b)
6753 // i = 2, e1 = 2, e2 = 1
6754 // a (b c)
6755 // (b c)
6756 // i = 0, e1 = 0, e2 = -1
6757 else if (i > e2) {
6758 while (i <= e1) {
6759 unmount(c1[i], parentComponent, parentSuspense, true);
6760 i++;
6761 }
6762 }
6763 // 5. unknown sequence
6764 // [i ... e1 + 1]: a b [c d e] f g
6765 // [i ... e2 + 1]: a b [e d c h] f g
6766 // i = 2, e1 = 4, e2 = 5
6767 else {
6768 const s1 = i; // prev starting index
6769 const s2 = i; // next starting index
6770 // 5.1 build key:index map for newChildren
6771 const keyToNewIndexMap = new Map();
6772 for (i = s2; i <= e2; i++) {
6773 const nextChild = (c2[i] = optimized
6774 ? cloneIfMounted(c2[i])
6775 : normalizeVNode(c2[i]));
6776 if (nextChild.key != null) {
6777 if (keyToNewIndexMap.has(nextChild.key)) {
6778 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6779 }
6780 keyToNewIndexMap.set(nextChild.key, i);
6781 }
6782 }
6783 // 5.2 loop through old children left to be patched and try to patch
6784 // matching nodes & remove nodes that are no longer present
6785 let j;
6786 let patched = 0;
6787 const toBePatched = e2 - s2 + 1;
6788 let moved = false;
6789 // used to track whether any node has moved
6790 let maxNewIndexSoFar = 0;
6791 // works as Map<newIndex, oldIndex>
6792 // Note that oldIndex is offset by +1
6793 // and oldIndex = 0 is a special value indicating the new node has
6794 // no corresponding old node.
6795 // used for determining longest stable subsequence
6796 const newIndexToOldIndexMap = new Array(toBePatched);
6797 for (i = 0; i < toBePatched; i++)
6798 newIndexToOldIndexMap[i] = 0;
6799 for (i = s1; i <= e1; i++) {
6800 const prevChild = c1[i];
6801 if (patched >= toBePatched) {
6802 // all new children have been patched so this can only be a removal
6803 unmount(prevChild, parentComponent, parentSuspense, true);
6804 continue;
6805 }
6806 let newIndex;
6807 if (prevChild.key != null) {
6808 newIndex = keyToNewIndexMap.get(prevChild.key);
6809 }
6810 else {
6811 // key-less node, try to locate a key-less node of the same type
6812 for (j = s2; j <= e2; j++) {
6813 if (newIndexToOldIndexMap[j - s2] === 0 &&
6814 isSameVNodeType(prevChild, c2[j])) {
6815 newIndex = j;
6816 break;
6817 }
6818 }
6819 }
6820 if (newIndex === undefined) {
6821 unmount(prevChild, parentComponent, parentSuspense, true);
6822 }
6823 else {
6824 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6825 if (newIndex >= maxNewIndexSoFar) {
6826 maxNewIndexSoFar = newIndex;
6827 }
6828 else {
6829 moved = true;
6830 }
6831 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6832 patched++;
6833 }
6834 }
6835 // 5.3 move and mount
6836 // generate longest stable subsequence only when nodes have moved
6837 const increasingNewIndexSequence = moved
6838 ? getSequence(newIndexToOldIndexMap)
6839 : EMPTY_ARR;
6840 j = increasingNewIndexSequence.length - 1;
6841 // looping backwards so that we can use last patched node as anchor
6842 for (i = toBePatched - 1; i >= 0; i--) {
6843 const nextIndex = s2 + i;
6844 const nextChild = c2[nextIndex];
6845 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6846 if (newIndexToOldIndexMap[i] === 0) {
6847 // mount new
6848 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6849 }
6850 else if (moved) {
6851 // move if:
6852 // There is no stable subsequence (e.g. a reverse)
6853 // OR current node is not among the stable sequence
6854 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6855 move(nextChild, container, anchor, 2 /* REORDER */);
6856 }
6857 else {
6858 j--;
6859 }
6860 }
6861 }
6862 }
6863 };
6864 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6865 const { el, type, transition, children, shapeFlag } = vnode;
6866 if (shapeFlag & 6 /* COMPONENT */) {
6867 move(vnode.component.subTree, container, anchor, moveType);
6868 return;
6869 }
6870 if (shapeFlag & 128 /* SUSPENSE */) {
6871 vnode.suspense.move(container, anchor, moveType);
6872 return;
6873 }
6874 if (shapeFlag & 64 /* TELEPORT */) {
6875 type.move(vnode, container, anchor, internals);
6876 return;
6877 }
6878 if (type === Fragment) {
6879 hostInsert(el, container, anchor);
6880 for (let i = 0; i < children.length; i++) {
6881 move(children[i], container, anchor, moveType);
6882 }
6883 hostInsert(vnode.anchor, container, anchor);
6884 return;
6885 }
6886 if (type === Static) {
6887 moveStaticNode(vnode, container, anchor);
6888 return;
6889 }
6890 // single nodes
6891 const needTransition = moveType !== 2 /* REORDER */ &&
6892 shapeFlag & 1 /* ELEMENT */ &&
6893 transition;
6894 if (needTransition) {
6895 if (moveType === 0 /* ENTER */) {
6896 transition.beforeEnter(el);
6897 hostInsert(el, container, anchor);
6898 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6899 }
6900 else {
6901 const { leave, delayLeave, afterLeave } = transition;
6902 const remove = () => hostInsert(el, container, anchor);
6903 const performLeave = () => {
6904 leave(el, () => {
6905 remove();
6906 afterLeave && afterLeave();
6907 });
6908 };
6909 if (delayLeave) {
6910 delayLeave(el, remove, performLeave);
6911 }
6912 else {
6913 performLeave();
6914 }
6915 }
6916 }
6917 else {
6918 hostInsert(el, container, anchor);
6919 }
6920 };
6921 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6922 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6923 // unset ref
6924 if (ref != null) {
6925 setRef(ref, null, parentSuspense, vnode, true);
6926 }
6927 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6928 parentComponent.ctx.deactivate(vnode);
6929 return;
6930 }
6931 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6932 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6933 let vnodeHook;
6934 if (shouldInvokeVnodeHook &&
6935 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6936 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6937 }
6938 if (shapeFlag & 6 /* COMPONENT */) {
6939 unmountComponent(vnode.component, parentSuspense, doRemove);
6940 }
6941 else {
6942 if (shapeFlag & 128 /* SUSPENSE */) {
6943 vnode.suspense.unmount(parentSuspense, doRemove);
6944 return;
6945 }
6946 if (shouldInvokeDirs) {
6947 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6948 }
6949 if (shapeFlag & 64 /* TELEPORT */) {
6950 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6951 }
6952 else if (dynamicChildren &&
6953 // #1153: fast path should not be taken for non-stable (v-for) fragments
6954 (type !== Fragment ||
6955 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6956 // fast path for block nodes: only need to unmount dynamic children.
6957 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6958 }
6959 else if ((type === Fragment &&
6960 patchFlag &
6961 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
6962 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6963 unmountChildren(children, parentComponent, parentSuspense);
6964 }
6965 if (doRemove) {
6966 remove(vnode);
6967 }
6968 }
6969 if ((shouldInvokeVnodeHook &&
6970 (vnodeHook = props && props.onVnodeUnmounted)) ||
6971 shouldInvokeDirs) {
6972 queuePostRenderEffect(() => {
6973 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6974 shouldInvokeDirs &&
6975 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6976 }, parentSuspense);
6977 }
6978 };
6979 const remove = vnode => {
6980 const { type, el, anchor, transition } = vnode;
6981 if (type === Fragment) {
6982 removeFragment(el, anchor);
6983 return;
6984 }
6985 if (type === Static) {
6986 removeStaticNode(vnode);
6987 return;
6988 }
6989 const performRemove = () => {
6990 hostRemove(el);
6991 if (transition && !transition.persisted && transition.afterLeave) {
6992 transition.afterLeave();
6993 }
6994 };
6995 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6996 transition &&
6997 !transition.persisted) {
6998 const { leave, delayLeave } = transition;
6999 const performLeave = () => leave(el, performRemove);
7000 if (delayLeave) {
7001 delayLeave(vnode.el, performRemove, performLeave);
7002 }
7003 else {
7004 performLeave();
7005 }
7006 }
7007 else {
7008 performRemove();
7009 }
7010 };
7011 const removeFragment = (cur, end) => {
7012 // For fragments, directly remove all contained DOM nodes.
7013 // (fragment child nodes cannot have transition)
7014 let next;
7015 while (cur !== end) {
7016 next = hostNextSibling(cur);
7017 hostRemove(cur);
7018 cur = next;
7019 }
7020 hostRemove(end);
7021 };
7022 const unmountComponent = (instance, parentSuspense, doRemove) => {
7023 if (instance.type.__hmrId) {
7024 unregisterHMR(instance);
7025 }
7026 const { bum, scope, update, subTree, um } = instance;
7027 // beforeUnmount hook
7028 if (bum) {
7029 invokeArrayFns(bum);
7030 }
7031 // stop effects in component scope
7032 scope.stop();
7033 // update may be null if a component is unmounted before its async
7034 // setup has resolved.
7035 if (update) {
7036 // so that scheduler will no longer invoke it
7037 update.active = false;
7038 unmount(subTree, instance, parentSuspense, doRemove);
7039 }
7040 // unmounted hook
7041 if (um) {
7042 queuePostRenderEffect(um, parentSuspense);
7043 }
7044 queuePostRenderEffect(() => {
7045 instance.isUnmounted = true;
7046 }, parentSuspense);
7047 // A component with async dep inside a pending suspense is unmounted before
7048 // its async dep resolves. This should remove the dep from the suspense, and
7049 // cause the suspense to resolve immediately if that was the last dep.
7050 if (parentSuspense &&
7051 parentSuspense.pendingBranch &&
7052 !parentSuspense.isUnmounted &&
7053 instance.asyncDep &&
7054 !instance.asyncResolved &&
7055 instance.suspenseId === parentSuspense.pendingId) {
7056 parentSuspense.deps--;
7057 if (parentSuspense.deps === 0) {
7058 parentSuspense.resolve();
7059 }
7060 }
7061 {
7062 devtoolsComponentRemoved(instance);
7063 }
7064 };
7065 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
7066 for (let i = start; i < children.length; i++) {
7067 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
7068 }
7069 };
7070 const getNextHostNode = vnode => {
7071 if (vnode.shapeFlag & 6 /* COMPONENT */) {
7072 return getNextHostNode(vnode.component.subTree);
7073 }
7074 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
7075 return vnode.suspense.next();
7076 }
7077 return hostNextSibling((vnode.anchor || vnode.el));
7078 };
7079 const render = (vnode, container, isSVG) => {
7080 if (vnode == null) {
7081 if (container._vnode) {
7082 unmount(container._vnode, null, null, true);
7083 }
7084 }
7085 else {
7086 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
7087 }
7088 flushPostFlushCbs();
7089 container._vnode = vnode;
7090 };
7091 const internals = {
7092 p: patch,
7093 um: unmount,
7094 m: move,
7095 r: remove,
7096 mt: mountComponent,
7097 mc: mountChildren,
7098 pc: patchChildren,
7099 pbc: patchBlockChildren,
7100 n: getNextHostNode,
7101 o: options
7102 };
7103 let hydrate;
7104 let hydrateNode;
7105 if (createHydrationFns) {
7106 [hydrate, hydrateNode] = createHydrationFns(internals);
7107 }
7108 return {
7109 render,
7110 hydrate,
7111 createApp: createAppAPI(render, hydrate)
7112 };
7113}
7114function toggleRecurse({ effect, update }, allowed) {
7115 effect.allowRecurse = update.allowRecurse = allowed;
7116}
7117/**
7118 * #1156
7119 * When a component is HMR-enabled, we need to make sure that all static nodes
7120 * inside a block also inherit the DOM element from the previous tree so that
7121 * HMR updates (which are full updates) can retrieve the element for patching.
7122 *
7123 * #2080
7124 * Inside keyed `template` fragment static children, if a fragment is moved,
7125 * the children will always be moved. Therefore, in order to ensure correct move
7126 * position, el should be inherited from previous nodes.
7127 */
7128function traverseStaticChildren(n1, n2, shallow = false) {
7129 const ch1 = n1.children;
7130 const ch2 = n2.children;
7131 if (isArray(ch1) && isArray(ch2)) {
7132 for (let i = 0; i < ch1.length; i++) {
7133 // this is only called in the optimized path so array children are
7134 // guaranteed to be vnodes
7135 const c1 = ch1[i];
7136 let c2 = ch2[i];
7137 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
7138 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
7139 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7140 c2.el = c1.el;
7141 }
7142 if (!shallow)
7143 traverseStaticChildren(c1, c2);
7144 }
7145 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7146 // would have received .el during block patch)
7147 if (c2.type === Comment && !c2.el) {
7148 c2.el = c1.el;
7149 }
7150 }
7151 }
7152}
7153// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7154function getSequence(arr) {
7155 const p = arr.slice();
7156 const result = [0];
7157 let i, j, u, v, c;
7158 const len = arr.length;
7159 for (i = 0; i < len; i++) {
7160 const arrI = arr[i];
7161 if (arrI !== 0) {
7162 j = result[result.length - 1];
7163 if (arr[j] < arrI) {
7164 p[i] = j;
7165 result.push(i);
7166 continue;
7167 }
7168 u = 0;
7169 v = result.length - 1;
7170 while (u < v) {
7171 c = (u + v) >> 1;
7172 if (arr[result[c]] < arrI) {
7173 u = c + 1;
7174 }
7175 else {
7176 v = c;
7177 }
7178 }
7179 if (arrI < arr[result[u]]) {
7180 if (u > 0) {
7181 p[i] = result[u - 1];
7182 }
7183 result[u] = i;
7184 }
7185 }
7186 }
7187 u = result.length;
7188 v = result[u - 1];
7189 while (u-- > 0) {
7190 result[u] = v;
7191 v = p[v];
7192 }
7193 return result;
7194}
7195
7196const isTeleport = (type) => type.__isTeleport;
7197const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7198const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7199const resolveTarget = (props, select) => {
7200 const targetSelector = props && props.to;
7201 if (isString(targetSelector)) {
7202 if (!select) {
7203 warn$1(`Current renderer does not support string target for Teleports. ` +
7204 `(missing querySelector renderer option)`);
7205 return null;
7206 }
7207 else {
7208 const target = select(targetSelector);
7209 if (!target) {
7210 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7211 `Note the target element must exist before the component is mounted - ` +
7212 `i.e. the target cannot be rendered by the component itself, and ` +
7213 `ideally should be outside of the entire Vue component tree.`);
7214 }
7215 return target;
7216 }
7217 }
7218 else {
7219 if (!targetSelector && !isTeleportDisabled(props)) {
7220 warn$1(`Invalid Teleport target: ${targetSelector}`);
7221 }
7222 return targetSelector;
7223 }
7224};
7225const TeleportImpl = {
7226 __isTeleport: true,
7227 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7228 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7229 const disabled = isTeleportDisabled(n2.props);
7230 let { shapeFlag, children, dynamicChildren } = n2;
7231 // #3302
7232 // HMR updated, force full diff
7233 if (isHmrUpdating) {
7234 optimized = false;
7235 dynamicChildren = null;
7236 }
7237 if (n1 == null) {
7238 // insert anchors in the main view
7239 const placeholder = (n2.el = createComment('teleport start')
7240 );
7241 const mainAnchor = (n2.anchor = createComment('teleport end')
7242 );
7243 insert(placeholder, container, anchor);
7244 insert(mainAnchor, container, anchor);
7245 const target = (n2.target = resolveTarget(n2.props, querySelector));
7246 const targetAnchor = (n2.targetAnchor = createText(''));
7247 if (target) {
7248 insert(targetAnchor, target);
7249 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7250 isSVG = isSVG || isTargetSVG(target);
7251 }
7252 else if (!disabled) {
7253 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
7254 }
7255 const mount = (container, anchor) => {
7256 // Teleport *always* has Array children. This is enforced in both the
7257 // compiler and vnode children normalization.
7258 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7259 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7260 }
7261 };
7262 if (disabled) {
7263 mount(container, mainAnchor);
7264 }
7265 else if (target) {
7266 mount(target, targetAnchor);
7267 }
7268 }
7269 else {
7270 // update content
7271 n2.el = n1.el;
7272 const mainAnchor = (n2.anchor = n1.anchor);
7273 const target = (n2.target = n1.target);
7274 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7275 const wasDisabled = isTeleportDisabled(n1.props);
7276 const currentContainer = wasDisabled ? container : target;
7277 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7278 isSVG = isSVG || isTargetSVG(target);
7279 if (dynamicChildren) {
7280 // fast path when the teleport happens to be a block root
7281 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7282 // even in block tree mode we need to make sure all root-level nodes
7283 // in the teleport inherit previous DOM references so that they can
7284 // be moved in future patches.
7285 traverseStaticChildren(n1, n2, true);
7286 }
7287 else if (!optimized) {
7288 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7289 }
7290 if (disabled) {
7291 if (!wasDisabled) {
7292 // enabled -> disabled
7293 // move into main container
7294 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
7295 }
7296 }
7297 else {
7298 // target changed
7299 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7300 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7301 if (nextTarget) {
7302 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
7303 }
7304 else {
7305 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
7306 }
7307 }
7308 else if (wasDisabled) {
7309 // disabled -> enabled
7310 // move into teleport target
7311 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
7312 }
7313 }
7314 }
7315 },
7316 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7317 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7318 if (target) {
7319 hostRemove(targetAnchor);
7320 }
7321 // an unmounted teleport should always remove its children if not disabled
7322 if (doRemove || !isTeleportDisabled(props)) {
7323 hostRemove(anchor);
7324 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7325 for (let i = 0; i < children.length; i++) {
7326 const child = children[i];
7327 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7328 }
7329 }
7330 }
7331 },
7332 move: moveTeleport,
7333 hydrate: hydrateTeleport
7334};
7335function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
7336 // move target anchor if this is a target change.
7337 if (moveType === 0 /* TARGET_CHANGE */) {
7338 insert(vnode.targetAnchor, container, parentAnchor);
7339 }
7340 const { el, anchor, shapeFlag, children, props } = vnode;
7341 const isReorder = moveType === 2 /* REORDER */;
7342 // move main view anchor if this is a re-order.
7343 if (isReorder) {
7344 insert(el, container, parentAnchor);
7345 }
7346 // if this is a re-order and teleport is enabled (content is in target)
7347 // do not move children. So the opposite is: only move children if this
7348 // is not a reorder, or the teleport is disabled
7349 if (!isReorder || isTeleportDisabled(props)) {
7350 // Teleport has either Array children or no children.
7351 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7352 for (let i = 0; i < children.length; i++) {
7353 move(children[i], container, parentAnchor, 2 /* REORDER */);
7354 }
7355 }
7356 }
7357 // move main view anchor if this is a re-order.
7358 if (isReorder) {
7359 insert(anchor, container, parentAnchor);
7360 }
7361}
7362function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
7363 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
7364 if (target) {
7365 // if multiple teleports rendered to the same target element, we need to
7366 // pick up from where the last teleport finished instead of the first node
7367 const targetNode = target._lpa || target.firstChild;
7368 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
7369 if (isTeleportDisabled(vnode.props)) {
7370 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
7371 vnode.targetAnchor = targetNode;
7372 }
7373 else {
7374 vnode.anchor = nextSibling(node);
7375 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
7376 }
7377 target._lpa =
7378 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
7379 }
7380 }
7381 return vnode.anchor && nextSibling(vnode.anchor);
7382}
7383// Force-casted public typing for h and TSX props inference
7384const Teleport = TeleportImpl;
7385
7386const COMPONENTS = 'components';
7387const DIRECTIVES = 'directives';
7388/**
7389 * @private
7390 */
7391function resolveComponent(name, maybeSelfReference) {
7392 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
7393}
7394const NULL_DYNAMIC_COMPONENT = Symbol();
7395/**
7396 * @private
7397 */
7398function resolveDynamicComponent(component) {
7399 if (isString(component)) {
7400 return resolveAsset(COMPONENTS, component, false) || component;
7401 }
7402 else {
7403 // invalid types will fallthrough to createVNode and raise warning
7404 return (component || NULL_DYNAMIC_COMPONENT);
7405 }
7406}
7407/**
7408 * @private
7409 */
7410function resolveDirective(name) {
7411 return resolveAsset(DIRECTIVES, name);
7412}
7413// implementation
7414function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
7415 const instance = currentRenderingInstance || currentInstance;
7416 if (instance) {
7417 const Component = instance.type;
7418 // explicit self name has highest priority
7419 if (type === COMPONENTS) {
7420 const selfName = getComponentName(Component);
7421 if (selfName &&
7422 (selfName === name ||
7423 selfName === camelize(name) ||
7424 selfName === capitalize(camelize(name)))) {
7425 return Component;
7426 }
7427 }
7428 const res =
7429 // local registration
7430 // check instance[type] first which is resolved for options API
7431 resolve(instance[type] || Component[type], name) ||
7432 // global registration
7433 resolve(instance.appContext[type], name);
7434 if (!res && maybeSelfReference) {
7435 // fallback to implicit self-reference
7436 return Component;
7437 }
7438 if (warnMissing && !res) {
7439 const extra = type === COMPONENTS
7440 ? `\nIf this is a native custom element, make sure to exclude it from ` +
7441 `component resolution via compilerOptions.isCustomElement.`
7442 : ``;
7443 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
7444 }
7445 return res;
7446 }
7447 else {
7448 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7449 `can only be used in render() or setup().`);
7450 }
7451}
7452function resolve(registry, name) {
7453 return (registry &&
7454 (registry[name] ||
7455 registry[camelize(name)] ||
7456 registry[capitalize(camelize(name))]));
7457}
7458
7459const Fragment = Symbol('Fragment' );
7460const Text = Symbol('Text' );
7461const Comment = Symbol('Comment' );
7462const Static = Symbol('Static' );
7463// Since v-if and v-for are the two possible ways node structure can dynamically
7464// change, once we consider v-if branches and each v-for fragment a block, we
7465// can divide a template into nested blocks, and within each block the node
7466// structure would be stable. This allows us to skip most children diffing
7467// and only worry about the dynamic nodes (indicated by patch flags).
7468const blockStack = [];
7469let currentBlock = null;
7470/**
7471 * Open a block.
7472 * This must be called before `createBlock`. It cannot be part of `createBlock`
7473 * because the children of the block are evaluated before `createBlock` itself
7474 * is called. The generated code typically looks like this:
7475 *
7476 * ```js
7477 * function render() {
7478 * return (openBlock(),createBlock('div', null, [...]))
7479 * }
7480 * ```
7481 * disableTracking is true when creating a v-for fragment block, since a v-for
7482 * fragment always diffs its children.
7483 *
7484 * @private
7485 */
7486function openBlock(disableTracking = false) {
7487 blockStack.push((currentBlock = disableTracking ? null : []));
7488}
7489function closeBlock() {
7490 blockStack.pop();
7491 currentBlock = blockStack[blockStack.length - 1] || null;
7492}
7493// Whether we should be tracking dynamic child nodes inside a block.
7494// Only tracks when this value is > 0
7495// We are not using a simple boolean because this value may need to be
7496// incremented/decremented by nested usage of v-once (see below)
7497let isBlockTreeEnabled = 1;
7498/**
7499 * Block tracking sometimes needs to be disabled, for example during the
7500 * creation of a tree that needs to be cached by v-once. The compiler generates
7501 * code like this:
7502 *
7503 * ``` js
7504 * _cache[1] || (
7505 * setBlockTracking(-1),
7506 * _cache[1] = createVNode(...),
7507 * setBlockTracking(1),
7508 * _cache[1]
7509 * )
7510 * ```
7511 *
7512 * @private
7513 */
7514function setBlockTracking(value) {
7515 isBlockTreeEnabled += value;
7516}
7517function setupBlock(vnode) {
7518 // save current block children on the block vnode
7519 vnode.dynamicChildren =
7520 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7521 // close block
7522 closeBlock();
7523 // a block is always going to be patched, so track it as a child of its
7524 // parent block
7525 if (isBlockTreeEnabled > 0 && currentBlock) {
7526 currentBlock.push(vnode);
7527 }
7528 return vnode;
7529}
7530/**
7531 * @private
7532 */
7533function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7534 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7535}
7536/**
7537 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7538 * A block root keeps track of dynamic nodes within the block in the
7539 * `dynamicChildren` array.
7540 *
7541 * @private
7542 */
7543function createBlock(type, props, children, patchFlag, dynamicProps) {
7544 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7545}
7546function isVNode(value) {
7547 return value ? value.__v_isVNode === true : false;
7548}
7549function isSameVNodeType(n1, n2) {
7550 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7551 hmrDirtyComponents.has(n2.type)) {
7552 // HMR only: if the component has been hot-updated, force a reload.
7553 return false;
7554 }
7555 return n1.type === n2.type && n1.key === n2.key;
7556}
7557let vnodeArgsTransformer;
7558/**
7559 * Internal API for registering an arguments transform for createVNode
7560 * used for creating stubs in the test-utils
7561 * It is *internal* but needs to be exposed for test-utils to pick up proper
7562 * typings
7563 */
7564function transformVNodeArgs(transformer) {
7565 vnodeArgsTransformer = transformer;
7566}
7567const createVNodeWithArgsTransform = (...args) => {
7568 return _createVNode(...(vnodeArgsTransformer
7569 ? vnodeArgsTransformer(args, currentRenderingInstance)
7570 : args));
7571};
7572const InternalObjectKey = `__vInternal`;
7573const normalizeKey = ({ key }) => key != null ? key : null;
7574const normalizeRef = ({ ref, ref_key, ref_for }) => {
7575 return (ref != null
7576 ? isString(ref) || isRef(ref) || isFunction(ref)
7577 ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
7578 : ref
7579 : null);
7580};
7581function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7582 const vnode = {
7583 __v_isVNode: true,
7584 __v_skip: true,
7585 type,
7586 props,
7587 key: props && normalizeKey(props),
7588 ref: props && normalizeRef(props),
7589 scopeId: currentScopeId,
7590 slotScopeIds: null,
7591 children,
7592 component: null,
7593 suspense: null,
7594 ssContent: null,
7595 ssFallback: null,
7596 dirs: null,
7597 transition: null,
7598 el: null,
7599 anchor: null,
7600 target: null,
7601 targetAnchor: null,
7602 staticCount: 0,
7603 shapeFlag,
7604 patchFlag,
7605 dynamicProps,
7606 dynamicChildren: null,
7607 appContext: null
7608 };
7609 if (needFullChildrenNormalization) {
7610 normalizeChildren(vnode, children);
7611 // normalize suspense children
7612 if (shapeFlag & 128 /* SUSPENSE */) {
7613 type.normalize(vnode);
7614 }
7615 }
7616 else if (children) {
7617 // compiled element vnode - if children is passed, only possible types are
7618 // string or Array.
7619 vnode.shapeFlag |= isString(children)
7620 ? 8 /* TEXT_CHILDREN */
7621 : 16 /* ARRAY_CHILDREN */;
7622 }
7623 // validate key
7624 if (vnode.key !== vnode.key) {
7625 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7626 }
7627 // track vnode for block tree
7628 if (isBlockTreeEnabled > 0 &&
7629 // avoid a block node from tracking itself
7630 !isBlockNode &&
7631 // has current parent block
7632 currentBlock &&
7633 // presence of a patch flag indicates this node needs patching on updates.
7634 // component nodes also should always be patched, because even if the
7635 // component doesn't need to update, it needs to persist the instance on to
7636 // the next vnode so that it can be properly unmounted later.
7637 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7638 // the EVENTS flag is only for hydration and if it is the only flag, the
7639 // vnode should not be considered dynamic due to handler caching.
7640 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7641 currentBlock.push(vnode);
7642 }
7643 return vnode;
7644}
7645const createVNode = (createVNodeWithArgsTransform );
7646function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7647 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7648 if (!type) {
7649 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7650 }
7651 type = Comment;
7652 }
7653 if (isVNode(type)) {
7654 // createVNode receiving an existing vnode. This happens in cases like
7655 // <component :is="vnode"/>
7656 // #2078 make sure to merge refs during the clone instead of overwriting it
7657 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7658 if (children) {
7659 normalizeChildren(cloned, children);
7660 }
7661 return cloned;
7662 }
7663 // class component normalization.
7664 if (isClassComponent(type)) {
7665 type = type.__vccOpts;
7666 }
7667 // class & style normalization.
7668 if (props) {
7669 // for reactive or proxy objects, we need to clone it to enable mutation.
7670 props = guardReactiveProps(props);
7671 let { class: klass, style } = props;
7672 if (klass && !isString(klass)) {
7673 props.class = normalizeClass(klass);
7674 }
7675 if (isObject(style)) {
7676 // reactive state objects need to be cloned since they are likely to be
7677 // mutated
7678 if (isProxy(style) && !isArray(style)) {
7679 style = extend({}, style);
7680 }
7681 props.style = normalizeStyle(style);
7682 }
7683 }
7684 // encode the vnode type information into a bitmap
7685 const shapeFlag = isString(type)
7686 ? 1 /* ELEMENT */
7687 : isSuspense(type)
7688 ? 128 /* SUSPENSE */
7689 : isTeleport(type)
7690 ? 64 /* TELEPORT */
7691 : isObject(type)
7692 ? 4 /* STATEFUL_COMPONENT */
7693 : isFunction(type)
7694 ? 2 /* FUNCTIONAL_COMPONENT */
7695 : 0;
7696 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7697 type = toRaw(type);
7698 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7699 `lead to unnecessary performance overhead, and should be avoided by ` +
7700 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7701 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7702 }
7703 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7704}
7705function guardReactiveProps(props) {
7706 if (!props)
7707 return null;
7708 return isProxy(props) || InternalObjectKey in props
7709 ? extend({}, props)
7710 : props;
7711}
7712function cloneVNode(vnode, extraProps, mergeRef = false) {
7713 // This is intentionally NOT using spread or extend to avoid the runtime
7714 // key enumeration cost.
7715 const { props, ref, patchFlag, children } = vnode;
7716 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7717 const cloned = {
7718 __v_isVNode: true,
7719 __v_skip: true,
7720 type: vnode.type,
7721 props: mergedProps,
7722 key: mergedProps && normalizeKey(mergedProps),
7723 ref: extraProps && extraProps.ref
7724 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7725 // if the vnode itself already has a ref, cloneVNode will need to merge
7726 // the refs so the single vnode can be set on multiple refs
7727 mergeRef && ref
7728 ? isArray(ref)
7729 ? ref.concat(normalizeRef(extraProps))
7730 : [ref, normalizeRef(extraProps)]
7731 : normalizeRef(extraProps)
7732 : ref,
7733 scopeId: vnode.scopeId,
7734 slotScopeIds: vnode.slotScopeIds,
7735 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7736 ? children.map(deepCloneVNode)
7737 : children,
7738 target: vnode.target,
7739 targetAnchor: vnode.targetAnchor,
7740 staticCount: vnode.staticCount,
7741 shapeFlag: vnode.shapeFlag,
7742 // if the vnode is cloned with extra props, we can no longer assume its
7743 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7744 // note: preserve flag for fragments since they use the flag for children
7745 // fast paths only.
7746 patchFlag: extraProps && vnode.type !== Fragment
7747 ? patchFlag === -1 // hoisted node
7748 ? 16 /* FULL_PROPS */
7749 : patchFlag | 16 /* FULL_PROPS */
7750 : patchFlag,
7751 dynamicProps: vnode.dynamicProps,
7752 dynamicChildren: vnode.dynamicChildren,
7753 appContext: vnode.appContext,
7754 dirs: vnode.dirs,
7755 transition: vnode.transition,
7756 // These should technically only be non-null on mounted VNodes. However,
7757 // they *should* be copied for kept-alive vnodes. So we just always copy
7758 // them since them being non-null during a mount doesn't affect the logic as
7759 // they will simply be overwritten.
7760 component: vnode.component,
7761 suspense: vnode.suspense,
7762 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7763 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7764 el: vnode.el,
7765 anchor: vnode.anchor
7766 };
7767 return cloned;
7768}
7769/**
7770 * Dev only, for HMR of hoisted vnodes reused in v-for
7771 * https://github.com/vitejs/vite/issues/2022
7772 */
7773function deepCloneVNode(vnode) {
7774 const cloned = cloneVNode(vnode);
7775 if (isArray(vnode.children)) {
7776 cloned.children = vnode.children.map(deepCloneVNode);
7777 }
7778 return cloned;
7779}
7780/**
7781 * @private
7782 */
7783function createTextVNode(text = ' ', flag = 0) {
7784 return createVNode(Text, null, text, flag);
7785}
7786/**
7787 * @private
7788 */
7789function createStaticVNode(content, numberOfNodes) {
7790 // A static vnode can contain multiple stringified elements, and the number
7791 // of elements is necessary for hydration.
7792 const vnode = createVNode(Static, null, content);
7793 vnode.staticCount = numberOfNodes;
7794 return vnode;
7795}
7796/**
7797 * @private
7798 */
7799function createCommentVNode(text = '',
7800// when used as the v-else branch, the comment node must be created as a
7801// block to ensure correct updates.
7802asBlock = false) {
7803 return asBlock
7804 ? (openBlock(), createBlock(Comment, null, text))
7805 : createVNode(Comment, null, text);
7806}
7807function normalizeVNode(child) {
7808 if (child == null || typeof child === 'boolean') {
7809 // empty placeholder
7810 return createVNode(Comment);
7811 }
7812 else if (isArray(child)) {
7813 // fragment
7814 return createVNode(Fragment, null,
7815 // #3666, avoid reference pollution when reusing vnode
7816 child.slice());
7817 }
7818 else if (typeof child === 'object') {
7819 // already vnode, this should be the most common since compiled templates
7820 // always produce all-vnode children arrays
7821 return cloneIfMounted(child);
7822 }
7823 else {
7824 // strings and numbers
7825 return createVNode(Text, null, String(child));
7826 }
7827}
7828// optimized normalization for template-compiled render fns
7829function cloneIfMounted(child) {
7830 return child.el === null || child.memo ? child : cloneVNode(child);
7831}
7832function normalizeChildren(vnode, children) {
7833 let type = 0;
7834 const { shapeFlag } = vnode;
7835 if (children == null) {
7836 children = null;
7837 }
7838 else if (isArray(children)) {
7839 type = 16 /* ARRAY_CHILDREN */;
7840 }
7841 else if (typeof children === 'object') {
7842 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7843 // Normalize slot to plain children for plain element and Teleport
7844 const slot = children.default;
7845 if (slot) {
7846 // _c marker is added by withCtx() indicating this is a compiled slot
7847 slot._c && (slot._d = false);
7848 normalizeChildren(vnode, slot());
7849 slot._c && (slot._d = true);
7850 }
7851 return;
7852 }
7853 else {
7854 type = 32 /* SLOTS_CHILDREN */;
7855 const slotFlag = children._;
7856 if (!slotFlag && !(InternalObjectKey in children)) {
7857 children._ctx = currentRenderingInstance;
7858 }
7859 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7860 // a child component receives forwarded slots from the parent.
7861 // its slot type is determined by its parent's slot type.
7862 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7863 children._ = 1 /* STABLE */;
7864 }
7865 else {
7866 children._ = 2 /* DYNAMIC */;
7867 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7868 }
7869 }
7870 }
7871 }
7872 else if (isFunction(children)) {
7873 children = { default: children, _ctx: currentRenderingInstance };
7874 type = 32 /* SLOTS_CHILDREN */;
7875 }
7876 else {
7877 children = String(children);
7878 // force teleport children to array so it can be moved around
7879 if (shapeFlag & 64 /* TELEPORT */) {
7880 type = 16 /* ARRAY_CHILDREN */;
7881 children = [createTextVNode(children)];
7882 }
7883 else {
7884 type = 8 /* TEXT_CHILDREN */;
7885 }
7886 }
7887 vnode.children = children;
7888 vnode.shapeFlag |= type;
7889}
7890function mergeProps(...args) {
7891 const ret = {};
7892 for (let i = 0; i < args.length; i++) {
7893 const toMerge = args[i];
7894 for (const key in toMerge) {
7895 if (key === 'class') {
7896 if (ret.class !== toMerge.class) {
7897 ret.class = normalizeClass([ret.class, toMerge.class]);
7898 }
7899 }
7900 else if (key === 'style') {
7901 ret.style = normalizeStyle([ret.style, toMerge.style]);
7902 }
7903 else if (isOn(key)) {
7904 const existing = ret[key];
7905 const incoming = toMerge[key];
7906 if (incoming &&
7907 existing !== incoming &&
7908 !(isArray(existing) && existing.includes(incoming))) {
7909 ret[key] = existing
7910 ? [].concat(existing, incoming)
7911 : incoming;
7912 }
7913 }
7914 else if (key !== '') {
7915 ret[key] = toMerge[key];
7916 }
7917 }
7918 }
7919 return ret;
7920}
7921function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
7922 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
7923 vnode,
7924 prevVNode
7925 ]);
7926}
7927
7928/**
7929 * Actual implementation
7930 */
7931function renderList(source, renderItem, cache, index) {
7932 let ret;
7933 const cached = (cache && cache[index]);
7934 if (isArray(source) || isString(source)) {
7935 ret = new Array(source.length);
7936 for (let i = 0, l = source.length; i < l; i++) {
7937 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
7938 }
7939 }
7940 else if (typeof source === 'number') {
7941 if (!Number.isInteger(source)) {
7942 warn$1(`The v-for range expect an integer value but got ${source}.`);
7943 return [];
7944 }
7945 ret = new Array(source);
7946 for (let i = 0; i < source; i++) {
7947 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
7948 }
7949 }
7950 else if (isObject(source)) {
7951 if (source[Symbol.iterator]) {
7952 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
7953 }
7954 else {
7955 const keys = Object.keys(source);
7956 ret = new Array(keys.length);
7957 for (let i = 0, l = keys.length; i < l; i++) {
7958 const key = keys[i];
7959 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
7960 }
7961 }
7962 }
7963 else {
7964 ret = [];
7965 }
7966 if (cache) {
7967 cache[index] = ret;
7968 }
7969 return ret;
7970}
7971
7972/**
7973 * Compiler runtime helper for creating dynamic slots object
7974 * @private
7975 */
7976function createSlots(slots, dynamicSlots) {
7977 for (let i = 0; i < dynamicSlots.length; i++) {
7978 const slot = dynamicSlots[i];
7979 // array of dynamic slot generated by <template v-for="..." #[...]>
7980 if (isArray(slot)) {
7981 for (let j = 0; j < slot.length; j++) {
7982 slots[slot[j].name] = slot[j].fn;
7983 }
7984 }
7985 else if (slot) {
7986 // conditional single slot generated by <template v-if="..." #foo>
7987 slots[slot.name] = slot.fn;
7988 }
7989 }
7990 return slots;
7991}
7992
7993/**
7994 * Compiler runtime helper for rendering `<slot/>`
7995 * @private
7996 */
7997function renderSlot(slots, name, props = {},
7998// this is not a user-facing function, so the fallback is always generated by
7999// the compiler and guaranteed to be a function returning an array
8000fallback, noSlotted) {
8001 if (currentRenderingInstance.isCE) {
8002 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
8003 }
8004 let slot = slots[name];
8005 if (slot && slot.length > 1) {
8006 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
8007 `function. You need to mark this component with $dynamic-slots in the ` +
8008 `parent template.`);
8009 slot = () => [];
8010 }
8011 // a compiled slot disables block tracking by default to avoid manual
8012 // invocation interfering with template-based block tracking, but in
8013 // `renderSlot` we can be sure that it's template-based so we can force
8014 // enable it.
8015 if (slot && slot._c) {
8016 slot._d = false;
8017 }
8018 openBlock();
8019 const validSlotContent = slot && ensureValidVNode(slot(props));
8020 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
8021 ? 64 /* STABLE_FRAGMENT */
8022 : -2 /* BAIL */);
8023 if (!noSlotted && rendered.scopeId) {
8024 rendered.slotScopeIds = [rendered.scopeId + '-s'];
8025 }
8026 if (slot && slot._c) {
8027 slot._d = true;
8028 }
8029 return rendered;
8030}
8031function ensureValidVNode(vnodes) {
8032 return vnodes.some(child => {
8033 if (!isVNode(child))
8034 return true;
8035 if (child.type === Comment)
8036 return false;
8037 if (child.type === Fragment &&
8038 !ensureValidVNode(child.children))
8039 return false;
8040 return true;
8041 })
8042 ? vnodes
8043 : null;
8044}
8045
8046/**
8047 * For prefixing keys in v-on="obj" with "on"
8048 * @private
8049 */
8050function toHandlers(obj) {
8051 const ret = {};
8052 if (!isObject(obj)) {
8053 warn$1(`v-on with no argument expects an object value.`);
8054 return ret;
8055 }
8056 for (const key in obj) {
8057 ret[toHandlerKey(key)] = obj[key];
8058 }
8059 return ret;
8060}
8061
8062/**
8063 * #2437 In Vue 3, functional components do not have a public instance proxy but
8064 * they exist in the internal parent chain. For code that relies on traversing
8065 * public $parent chains, skip functional ones and go to the parent instead.
8066 */
8067const getPublicInstance = (i) => {
8068 if (!i)
8069 return null;
8070 if (isStatefulComponent(i))
8071 return getExposeProxy(i) || i.proxy;
8072 return getPublicInstance(i.parent);
8073};
8074const publicPropertiesMap = extend(Object.create(null), {
8075 $: i => i,
8076 $el: i => i.vnode.el,
8077 $data: i => i.data,
8078 $props: i => (shallowReadonly(i.props) ),
8079 $attrs: i => (shallowReadonly(i.attrs) ),
8080 $slots: i => (shallowReadonly(i.slots) ),
8081 $refs: i => (shallowReadonly(i.refs) ),
8082 $parent: i => getPublicInstance(i.parent),
8083 $root: i => getPublicInstance(i.root),
8084 $emit: i => i.emit,
8085 $options: i => (resolveMergedOptions(i) ),
8086 $forceUpdate: i => () => queueJob(i.update),
8087 $nextTick: i => nextTick.bind(i.proxy),
8088 $watch: i => (instanceWatch.bind(i) )
8089});
8090const PublicInstanceProxyHandlers = {
8091 get({ _: instance }, key) {
8092 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
8093 // for internal formatters to know that this is a Vue instance
8094 if (key === '__isVue') {
8095 return true;
8096 }
8097 // prioritize <script setup> bindings during dev.
8098 // this allows even properties that start with _ or $ to be used - so that
8099 // it aligns with the production behavior where the render fn is inlined and
8100 // indeed has access to all declared variables.
8101 if (setupState !== EMPTY_OBJ &&
8102 setupState.__isScriptSetup &&
8103 hasOwn(setupState, key)) {
8104 return setupState[key];
8105 }
8106 // data / props / ctx
8107 // This getter gets called for every property access on the render context
8108 // during render and is a major hotspot. The most expensive part of this
8109 // is the multiple hasOwn() calls. It's much faster to do a simple property
8110 // access on a plain object, so we use an accessCache object (with null
8111 // prototype) to memoize what access type a key corresponds to.
8112 let normalizedProps;
8113 if (key[0] !== '$') {
8114 const n = accessCache[key];
8115 if (n !== undefined) {
8116 switch (n) {
8117 case 1 /* SETUP */:
8118 return setupState[key];
8119 case 2 /* DATA */:
8120 return data[key];
8121 case 4 /* CONTEXT */:
8122 return ctx[key];
8123 case 3 /* PROPS */:
8124 return props[key];
8125 // default: just fallthrough
8126 }
8127 }
8128 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8129 accessCache[key] = 1 /* SETUP */;
8130 return setupState[key];
8131 }
8132 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8133 accessCache[key] = 2 /* DATA */;
8134 return data[key];
8135 }
8136 else if (
8137 // only cache other properties when instance has declared (thus stable)
8138 // props
8139 (normalizedProps = instance.propsOptions[0]) &&
8140 hasOwn(normalizedProps, key)) {
8141 accessCache[key] = 3 /* PROPS */;
8142 return props[key];
8143 }
8144 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8145 accessCache[key] = 4 /* CONTEXT */;
8146 return ctx[key];
8147 }
8148 else if (shouldCacheAccess) {
8149 accessCache[key] = 0 /* OTHER */;
8150 }
8151 }
8152 const publicGetter = publicPropertiesMap[key];
8153 let cssModule, globalProperties;
8154 // public $xxx properties
8155 if (publicGetter) {
8156 if (key === '$attrs') {
8157 track(instance, "get" /* GET */, key);
8158 markAttrsAccessed();
8159 }
8160 return publicGetter(instance);
8161 }
8162 else if (
8163 // css module (injected by vue-loader)
8164 (cssModule = type.__cssModules) &&
8165 (cssModule = cssModule[key])) {
8166 return cssModule;
8167 }
8168 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
8169 // user may set custom properties to `this` that start with `$`
8170 accessCache[key] = 4 /* CONTEXT */;
8171 return ctx[key];
8172 }
8173 else if (
8174 // global properties
8175 ((globalProperties = appContext.config.globalProperties),
8176 hasOwn(globalProperties, key))) {
8177 {
8178 return globalProperties[key];
8179 }
8180 }
8181 else if (currentRenderingInstance &&
8182 (!isString(key) ||
8183 // #1091 avoid internal isRef/isVNode checks on component instance leading
8184 // to infinite warning loop
8185 key.indexOf('__v') !== 0)) {
8186 if (data !== EMPTY_OBJ &&
8187 (key[0] === '$' || key[0] === '_') &&
8188 hasOwn(data, key)) {
8189 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
8190 `character ("$" or "_") and is not proxied on the render context.`);
8191 }
8192 else if (instance === currentRenderingInstance) {
8193 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
8194 `but is not defined on instance.`);
8195 }
8196 }
8197 },
8198 set({ _: instance }, key, value) {
8199 const { data, setupState, ctx } = instance;
8200 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8201 setupState[key] = value;
8202 }
8203 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8204 data[key] = value;
8205 }
8206 else if (hasOwn(instance.props, key)) {
8207 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
8208 return false;
8209 }
8210 if (key[0] === '$' && key.slice(1) in instance) {
8211 warn$1(`Attempting to mutate public property "${key}". ` +
8212 `Properties starting with $ are reserved and readonly.`, instance);
8213 return false;
8214 }
8215 else {
8216 if (key in instance.appContext.config.globalProperties) {
8217 Object.defineProperty(ctx, key, {
8218 enumerable: true,
8219 configurable: true,
8220 value
8221 });
8222 }
8223 else {
8224 ctx[key] = value;
8225 }
8226 }
8227 return true;
8228 },
8229 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
8230 let normalizedProps;
8231 return (!!accessCache[key] ||
8232 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
8233 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
8234 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
8235 hasOwn(ctx, key) ||
8236 hasOwn(publicPropertiesMap, key) ||
8237 hasOwn(appContext.config.globalProperties, key));
8238 }
8239};
8240{
8241 PublicInstanceProxyHandlers.ownKeys = (target) => {
8242 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
8243 `The keys will be empty in production mode to avoid performance overhead.`);
8244 return Reflect.ownKeys(target);
8245 };
8246}
8247const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
8248 get(target, key) {
8249 // fast path for unscopables when using `with` block
8250 if (key === Symbol.unscopables) {
8251 return;
8252 }
8253 return PublicInstanceProxyHandlers.get(target, key, target);
8254 },
8255 has(_, key) {
8256 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
8257 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
8258 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
8259 }
8260 return has;
8261 }
8262});
8263// dev only
8264// In dev mode, the proxy target exposes the same properties as seen on `this`
8265// for easier console inspection. In prod mode it will be an empty object so
8266// these properties definitions can be skipped.
8267function createDevRenderContext(instance) {
8268 const target = {};
8269 // expose internal instance for proxy handlers
8270 Object.defineProperty(target, `_`, {
8271 configurable: true,
8272 enumerable: false,
8273 get: () => instance
8274 });
8275 // expose public properties
8276 Object.keys(publicPropertiesMap).forEach(key => {
8277 Object.defineProperty(target, key, {
8278 configurable: true,
8279 enumerable: false,
8280 get: () => publicPropertiesMap[key](instance),
8281 // intercepted by the proxy so no need for implementation,
8282 // but needed to prevent set errors
8283 set: NOOP
8284 });
8285 });
8286 return target;
8287}
8288// dev only
8289function exposePropsOnRenderContext(instance) {
8290 const { ctx, propsOptions: [propsOptions] } = instance;
8291 if (propsOptions) {
8292 Object.keys(propsOptions).forEach(key => {
8293 Object.defineProperty(ctx, key, {
8294 enumerable: true,
8295 configurable: true,
8296 get: () => instance.props[key],
8297 set: NOOP
8298 });
8299 });
8300 }
8301}
8302// dev only
8303function exposeSetupStateOnRenderContext(instance) {
8304 const { ctx, setupState } = instance;
8305 Object.keys(toRaw(setupState)).forEach(key => {
8306 if (!setupState.__isScriptSetup) {
8307 if (key[0] === '$' || key[0] === '_') {
8308 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
8309 `which are reserved prefixes for Vue internals.`);
8310 return;
8311 }
8312 Object.defineProperty(ctx, key, {
8313 enumerable: true,
8314 configurable: true,
8315 get: () => setupState[key],
8316 set: NOOP
8317 });
8318 }
8319 });
8320}
8321
8322const emptyAppContext = createAppContext();
8323let uid$1 = 0;
8324function createComponentInstance(vnode, parent, suspense) {
8325 const type = vnode.type;
8326 // inherit parent app context - or - if root, adopt from root vnode
8327 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8328 const instance = {
8329 uid: uid$1++,
8330 vnode,
8331 type,
8332 parent,
8333 appContext,
8334 root: null,
8335 next: null,
8336 subTree: null,
8337 effect: null,
8338 update: null,
8339 scope: new EffectScope(true /* detached */),
8340 render: null,
8341 proxy: null,
8342 exposed: null,
8343 exposeProxy: null,
8344 withProxy: null,
8345 provides: parent ? parent.provides : Object.create(appContext.provides),
8346 accessCache: null,
8347 renderCache: [],
8348 // local resovled assets
8349 components: null,
8350 directives: null,
8351 // resolved props and emits options
8352 propsOptions: normalizePropsOptions(type, appContext),
8353 emitsOptions: normalizeEmitsOptions(type, appContext),
8354 // emit
8355 emit: null,
8356 emitted: null,
8357 // props default value
8358 propsDefaults: EMPTY_OBJ,
8359 // inheritAttrs
8360 inheritAttrs: type.inheritAttrs,
8361 // state
8362 ctx: EMPTY_OBJ,
8363 data: EMPTY_OBJ,
8364 props: EMPTY_OBJ,
8365 attrs: EMPTY_OBJ,
8366 slots: EMPTY_OBJ,
8367 refs: EMPTY_OBJ,
8368 setupState: EMPTY_OBJ,
8369 setupContext: null,
8370 // suspense related
8371 suspense,
8372 suspenseId: suspense ? suspense.pendingId : 0,
8373 asyncDep: null,
8374 asyncResolved: false,
8375 // lifecycle hooks
8376 // not using enums here because it results in computed properties
8377 isMounted: false,
8378 isUnmounted: false,
8379 isDeactivated: false,
8380 bc: null,
8381 c: null,
8382 bm: null,
8383 m: null,
8384 bu: null,
8385 u: null,
8386 um: null,
8387 bum: null,
8388 da: null,
8389 a: null,
8390 rtg: null,
8391 rtc: null,
8392 ec: null,
8393 sp: null
8394 };
8395 {
8396 instance.ctx = createDevRenderContext(instance);
8397 }
8398 instance.root = parent ? parent.root : instance;
8399 instance.emit = emit$1.bind(null, instance);
8400 // apply custom element special handling
8401 if (vnode.ce) {
8402 vnode.ce(instance);
8403 }
8404 return instance;
8405}
8406let currentInstance = null;
8407const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8408const setCurrentInstance = (instance) => {
8409 currentInstance = instance;
8410 instance.scope.on();
8411};
8412const unsetCurrentInstance = () => {
8413 currentInstance && currentInstance.scope.off();
8414 currentInstance = null;
8415};
8416const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8417function validateComponentName(name, config) {
8418 const appIsNativeTag = config.isNativeTag || NO;
8419 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8420 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
8421 }
8422}
8423function isStatefulComponent(instance) {
8424 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
8425}
8426let isInSSRComponentSetup = false;
8427function setupComponent(instance, isSSR = false) {
8428 isInSSRComponentSetup = isSSR;
8429 const { props, children } = instance.vnode;
8430 const isStateful = isStatefulComponent(instance);
8431 initProps(instance, props, isStateful, isSSR);
8432 initSlots(instance, children);
8433 const setupResult = isStateful
8434 ? setupStatefulComponent(instance, isSSR)
8435 : undefined;
8436 isInSSRComponentSetup = false;
8437 return setupResult;
8438}
8439function setupStatefulComponent(instance, isSSR) {
8440 const Component = instance.type;
8441 {
8442 if (Component.name) {
8443 validateComponentName(Component.name, instance.appContext.config);
8444 }
8445 if (Component.components) {
8446 const names = Object.keys(Component.components);
8447 for (let i = 0; i < names.length; i++) {
8448 validateComponentName(names[i], instance.appContext.config);
8449 }
8450 }
8451 if (Component.directives) {
8452 const names = Object.keys(Component.directives);
8453 for (let i = 0; i < names.length; i++) {
8454 validateDirectiveName(names[i]);
8455 }
8456 }
8457 if (Component.compilerOptions && isRuntimeOnly()) {
8458 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8459 `includes the runtime compiler. Since you are using a runtime-only ` +
8460 `build, the options should be passed via your build tool config instead.`);
8461 }
8462 }
8463 // 0. create render proxy property access cache
8464 instance.accessCache = Object.create(null);
8465 // 1. create public instance / render proxy
8466 // also mark it raw so it's never observed
8467 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8468 {
8469 exposePropsOnRenderContext(instance);
8470 }
8471 // 2. call setup()
8472 const { setup } = Component;
8473 if (setup) {
8474 const setupContext = (instance.setupContext =
8475 setup.length > 1 ? createSetupContext(instance) : null);
8476 setCurrentInstance(instance);
8477 pauseTracking();
8478 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8479 resetTracking();
8480 unsetCurrentInstance();
8481 if (isPromise(setupResult)) {
8482 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8483 if (isSSR) {
8484 // return the promise so server-renderer can wait on it
8485 return setupResult
8486 .then((resolvedResult) => {
8487 handleSetupResult(instance, resolvedResult, isSSR);
8488 })
8489 .catch(e => {
8490 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8491 });
8492 }
8493 else {
8494 // async setup returned Promise.
8495 // bail here and wait for re-entry.
8496 instance.asyncDep = setupResult;
8497 }
8498 }
8499 else {
8500 handleSetupResult(instance, setupResult, isSSR);
8501 }
8502 }
8503 else {
8504 finishComponentSetup(instance, isSSR);
8505 }
8506}
8507function handleSetupResult(instance, setupResult, isSSR) {
8508 if (isFunction(setupResult)) {
8509 // setup returned an inline render function
8510 {
8511 instance.render = setupResult;
8512 }
8513 }
8514 else if (isObject(setupResult)) {
8515 if (isVNode(setupResult)) {
8516 warn$1(`setup() should not return VNodes directly - ` +
8517 `return a render function instead.`);
8518 }
8519 // setup returned bindings.
8520 // assuming a render function compiled from template is present.
8521 {
8522 instance.devtoolsRawSetupState = setupResult;
8523 }
8524 instance.setupState = proxyRefs(setupResult);
8525 {
8526 exposeSetupStateOnRenderContext(instance);
8527 }
8528 }
8529 else if (setupResult !== undefined) {
8530 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8531 }
8532 finishComponentSetup(instance, isSSR);
8533}
8534let compile;
8535let installWithProxy;
8536/**
8537 * For runtime-dom to register the compiler.
8538 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8539 */
8540function registerRuntimeCompiler(_compile) {
8541 compile = _compile;
8542 installWithProxy = i => {
8543 if (i.render._rc) {
8544 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8545 }
8546 };
8547}
8548// dev only
8549const isRuntimeOnly = () => !compile;
8550function finishComponentSetup(instance, isSSR, skipOptions) {
8551 const Component = instance.type;
8552 // template / render function normalization
8553 // could be already set when returned from setup()
8554 if (!instance.render) {
8555 // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
8556 // is done by server-renderer
8557 if (!isSSR && compile && !Component.render) {
8558 const template = Component.template;
8559 if (template) {
8560 {
8561 startMeasure(instance, `compile`);
8562 }
8563 const { isCustomElement, compilerOptions } = instance.appContext.config;
8564 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8565 const finalCompilerOptions = extend(extend({
8566 isCustomElement,
8567 delimiters
8568 }, compilerOptions), componentCompilerOptions);
8569 Component.render = compile(template, finalCompilerOptions);
8570 {
8571 endMeasure(instance, `compile`);
8572 }
8573 }
8574 }
8575 instance.render = (Component.render || NOOP);
8576 // for runtime-compiled render functions using `with` blocks, the render
8577 // proxy used needs a different `has` handler which is more performant and
8578 // also only allows a whitelist of globals to fallthrough.
8579 if (installWithProxy) {
8580 installWithProxy(instance);
8581 }
8582 }
8583 // support for 2.x options
8584 {
8585 setCurrentInstance(instance);
8586 pauseTracking();
8587 applyOptions(instance);
8588 resetTracking();
8589 unsetCurrentInstance();
8590 }
8591 // warn missing template/render
8592 // the runtime compilation of template in SSR is done by server-render
8593 if (!Component.render && instance.render === NOOP && !isSSR) {
8594 /* istanbul ignore if */
8595 if (!compile && Component.template) {
8596 warn$1(`Component provided template option but ` +
8597 `runtime compilation is not supported in this build of Vue.` +
8598 (` Use "vue.esm-browser.js" instead.`
8599 ) /* should not happen */);
8600 }
8601 else {
8602 warn$1(`Component is missing template or render function.`);
8603 }
8604 }
8605}
8606function createAttrsProxy(instance) {
8607 return new Proxy(instance.attrs, {
8608 get(target, key) {
8609 markAttrsAccessed();
8610 track(instance, "get" /* GET */, '$attrs');
8611 return target[key];
8612 },
8613 set() {
8614 warn$1(`setupContext.attrs is readonly.`);
8615 return false;
8616 },
8617 deleteProperty() {
8618 warn$1(`setupContext.attrs is readonly.`);
8619 return false;
8620 }
8621 }
8622 );
8623}
8624function createSetupContext(instance) {
8625 const expose = exposed => {
8626 if (instance.exposed) {
8627 warn$1(`expose() should be called only once per setup().`);
8628 }
8629 instance.exposed = exposed || {};
8630 };
8631 let attrs;
8632 {
8633 // We use getters in dev in case libs like test-utils overwrite instance
8634 // properties (overwrites should not be done in prod)
8635 return Object.freeze({
8636 get attrs() {
8637 return attrs || (attrs = createAttrsProxy(instance));
8638 },
8639 get slots() {
8640 return shallowReadonly(instance.slots);
8641 },
8642 get emit() {
8643 return (event, ...args) => instance.emit(event, ...args);
8644 },
8645 expose
8646 });
8647 }
8648}
8649function getExposeProxy(instance) {
8650 if (instance.exposed) {
8651 return (instance.exposeProxy ||
8652 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8653 get(target, key) {
8654 if (key in target) {
8655 return target[key];
8656 }
8657 else if (key in publicPropertiesMap) {
8658 return publicPropertiesMap[key](instance);
8659 }
8660 }
8661 })));
8662 }
8663}
8664const classifyRE = /(?:^|[-_])(\w)/g;
8665const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8666function getComponentName(Component) {
8667 return isFunction(Component)
8668 ? Component.displayName || Component.name
8669 : Component.name;
8670}
8671/* istanbul ignore next */
8672function formatComponentName(instance, Component, isRoot = false) {
8673 let name = getComponentName(Component);
8674 if (!name && Component.__file) {
8675 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8676 if (match) {
8677 name = match[1];
8678 }
8679 }
8680 if (!name && instance && instance.parent) {
8681 // try to infer the name based on reverse resolution
8682 const inferFromRegistry = (registry) => {
8683 for (const key in registry) {
8684 if (registry[key] === Component) {
8685 return key;
8686 }
8687 }
8688 };
8689 name =
8690 inferFromRegistry(instance.components ||
8691 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8692 }
8693 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8694}
8695function isClassComponent(value) {
8696 return isFunction(value) && '__vccOpts' in value;
8697}
8698
8699const computed$1 = ((getterOrOptions, debugOptions) => {
8700 // @ts-ignore
8701 return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
8702});
8703
8704// dev only
8705const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8706 `<script setup> of a single file component. Its arguments should be ` +
8707 `compiled away and passing it at runtime has no effect.`);
8708// implementation
8709function defineProps() {
8710 {
8711 warnRuntimeUsage(`defineProps`);
8712 }
8713 return null;
8714}
8715// implementation
8716function defineEmits() {
8717 {
8718 warnRuntimeUsage(`defineEmits`);
8719 }
8720 return null;
8721}
8722/**
8723 * Vue `<script setup>` compiler macro for declaring a component's exposed
8724 * instance properties when it is accessed by a parent component via template
8725 * refs.
8726 *
8727 * `<script setup>` components are closed by default - i.e. variables inside
8728 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8729 * via `defineExpose`.
8730 *
8731 * This is only usable inside `<script setup>`, is compiled away in the
8732 * output and should **not** be actually called at runtime.
8733 */
8734function defineExpose(exposed) {
8735 {
8736 warnRuntimeUsage(`defineExpose`);
8737 }
8738}
8739/**
8740 * Vue `<script setup>` compiler macro for providing props default values when
8741 * using type-based `defineProps` declaration.
8742 *
8743 * Example usage:
8744 * ```ts
8745 * withDefaults(defineProps<{
8746 * size?: number
8747 * labels?: string[]
8748 * }>(), {
8749 * size: 3,
8750 * labels: () => ['default label']
8751 * })
8752 * ```
8753 *
8754 * This is only usable inside `<script setup>`, is compiled away in the output
8755 * and should **not** be actually called at runtime.
8756 */
8757function withDefaults(props, defaults) {
8758 {
8759 warnRuntimeUsage(`withDefaults`);
8760 }
8761 return null;
8762}
8763function useSlots() {
8764 return getContext().slots;
8765}
8766function useAttrs() {
8767 return getContext().attrs;
8768}
8769function getContext() {
8770 const i = getCurrentInstance();
8771 if (!i) {
8772 warn$1(`useContext() called without active instance.`);
8773 }
8774 return i.setupContext || (i.setupContext = createSetupContext(i));
8775}
8776/**
8777 * Runtime helper for merging default declarations. Imported by compiled code
8778 * only.
8779 * @internal
8780 */
8781function mergeDefaults(raw, defaults) {
8782 const props = isArray(raw)
8783 ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
8784 : raw;
8785 for (const key in defaults) {
8786 const opt = props[key];
8787 if (opt) {
8788 if (isArray(opt) || isFunction(opt)) {
8789 props[key] = { type: opt, default: defaults[key] };
8790 }
8791 else {
8792 opt.default = defaults[key];
8793 }
8794 }
8795 else if (opt === null) {
8796 props[key] = { default: defaults[key] };
8797 }
8798 else {
8799 warn$1(`props default key "${key}" has no corresponding declaration.`);
8800 }
8801 }
8802 return props;
8803}
8804/**
8805 * Used to create a proxy for the rest element when destructuring props with
8806 * defineProps().
8807 * @internal
8808 */
8809function createPropsRestProxy(props, excludedKeys) {
8810 const ret = {};
8811 for (const key in props) {
8812 if (!excludedKeys.includes(key)) {
8813 Object.defineProperty(ret, key, {
8814 enumerable: true,
8815 get: () => props[key]
8816 });
8817 }
8818 }
8819 return ret;
8820}
8821/**
8822 * `<script setup>` helper for persisting the current instance context over
8823 * async/await flows.
8824 *
8825 * `@vue/compiler-sfc` converts the following:
8826 *
8827 * ```ts
8828 * const x = await foo()
8829 * ```
8830 *
8831 * into:
8832 *
8833 * ```ts
8834 * let __temp, __restore
8835 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
8836 * ```
8837 * @internal
8838 */
8839function withAsyncContext(getAwaitable) {
8840 const ctx = getCurrentInstance();
8841 if (!ctx) {
8842 warn$1(`withAsyncContext called without active current instance. ` +
8843 `This is likely a bug.`);
8844 }
8845 let awaitable = getAwaitable();
8846 unsetCurrentInstance();
8847 if (isPromise(awaitable)) {
8848 awaitable = awaitable.catch(e => {
8849 setCurrentInstance(ctx);
8850 throw e;
8851 });
8852 }
8853 return [awaitable, () => setCurrentInstance(ctx)];
8854}
8855
8856// Actual implementation
8857function h(type, propsOrChildren, children) {
8858 const l = arguments.length;
8859 if (l === 2) {
8860 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
8861 // single vnode without props
8862 if (isVNode(propsOrChildren)) {
8863 return createVNode(type, null, [propsOrChildren]);
8864 }
8865 // props without children
8866 return createVNode(type, propsOrChildren);
8867 }
8868 else {
8869 // omit props
8870 return createVNode(type, null, propsOrChildren);
8871 }
8872 }
8873 else {
8874 if (l > 3) {
8875 children = Array.prototype.slice.call(arguments, 2);
8876 }
8877 else if (l === 3 && isVNode(children)) {
8878 children = [children];
8879 }
8880 return createVNode(type, propsOrChildren, children);
8881 }
8882}
8883
8884const ssrContextKey = Symbol(`ssrContext` );
8885const useSSRContext = () => {
8886 {
8887 const ctx = inject(ssrContextKey);
8888 if (!ctx) {
8889 warn$1(`Server rendering context not provided. Make sure to only call ` +
8890 `useSSRContext() conditionally in the server build.`);
8891 }
8892 return ctx;
8893 }
8894};
8895
8896function initCustomFormatter() {
8897 /* eslint-disable no-restricted-globals */
8898 if (typeof window === 'undefined') {
8899 return;
8900 }
8901 const vueStyle = { style: 'color:#3ba776' };
8902 const numberStyle = { style: 'color:#0b1bc9' };
8903 const stringStyle = { style: 'color:#b62e24' };
8904 const keywordStyle = { style: 'color:#9d288c' };
8905 // custom formatter for Chrome
8906 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
8907 const formatter = {
8908 header(obj) {
8909 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
8910 if (!isObject(obj)) {
8911 return null;
8912 }
8913 if (obj.__isVue) {
8914 return ['div', vueStyle, `VueInstance`];
8915 }
8916 else if (isRef(obj)) {
8917 return [
8918 'div',
8919 {},
8920 ['span', vueStyle, genRefFlag(obj)],
8921 '<',
8922 formatValue(obj.value),
8923 `>`
8924 ];
8925 }
8926 else if (isReactive(obj)) {
8927 return [
8928 'div',
8929 {},
8930 ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
8931 '<',
8932 formatValue(obj),
8933 `>${isReadonly(obj) ? ` (readonly)` : ``}`
8934 ];
8935 }
8936 else if (isReadonly(obj)) {
8937 return [
8938 'div',
8939 {},
8940 ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
8941 '<',
8942 formatValue(obj),
8943 '>'
8944 ];
8945 }
8946 return null;
8947 },
8948 hasBody(obj) {
8949 return obj && obj.__isVue;
8950 },
8951 body(obj) {
8952 if (obj && obj.__isVue) {
8953 return [
8954 'div',
8955 {},
8956 ...formatInstance(obj.$)
8957 ];
8958 }
8959 }
8960 };
8961 function formatInstance(instance) {
8962 const blocks = [];
8963 if (instance.type.props && instance.props) {
8964 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
8965 }
8966 if (instance.setupState !== EMPTY_OBJ) {
8967 blocks.push(createInstanceBlock('setup', instance.setupState));
8968 }
8969 if (instance.data !== EMPTY_OBJ) {
8970 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
8971 }
8972 const computed = extractKeys(instance, 'computed');
8973 if (computed) {
8974 blocks.push(createInstanceBlock('computed', computed));
8975 }
8976 const injected = extractKeys(instance, 'inject');
8977 if (injected) {
8978 blocks.push(createInstanceBlock('injected', injected));
8979 }
8980 blocks.push([
8981 'div',
8982 {},
8983 [
8984 'span',
8985 {
8986 style: keywordStyle.style + ';opacity:0.66'
8987 },
8988 '$ (internal): '
8989 ],
8990 ['object', { object: instance }]
8991 ]);
8992 return blocks;
8993 }
8994 function createInstanceBlock(type, target) {
8995 target = extend({}, target);
8996 if (!Object.keys(target).length) {
8997 return ['span', {}];
8998 }
8999 return [
9000 'div',
9001 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9002 [
9003 'div',
9004 {
9005 style: 'color:#476582'
9006 },
9007 type
9008 ],
9009 [
9010 'div',
9011 {
9012 style: 'padding-left:1.25em'
9013 },
9014 ...Object.keys(target).map(key => {
9015 return [
9016 'div',
9017 {},
9018 ['span', keywordStyle, key + ': '],
9019 formatValue(target[key], false)
9020 ];
9021 })
9022 ]
9023 ];
9024 }
9025 function formatValue(v, asRaw = true) {
9026 if (typeof v === 'number') {
9027 return ['span', numberStyle, v];
9028 }
9029 else if (typeof v === 'string') {
9030 return ['span', stringStyle, JSON.stringify(v)];
9031 }
9032 else if (typeof v === 'boolean') {
9033 return ['span', keywordStyle, v];
9034 }
9035 else if (isObject(v)) {
9036 return ['object', { object: asRaw ? toRaw(v) : v }];
9037 }
9038 else {
9039 return ['span', stringStyle, String(v)];
9040 }
9041 }
9042 function extractKeys(instance, type) {
9043 const Comp = instance.type;
9044 if (isFunction(Comp)) {
9045 return;
9046 }
9047 const extracted = {};
9048 for (const key in instance.ctx) {
9049 if (isKeyOfType(Comp, key, type)) {
9050 extracted[key] = instance.ctx[key];
9051 }
9052 }
9053 return extracted;
9054 }
9055 function isKeyOfType(Comp, key, type) {
9056 const opts = Comp[type];
9057 if ((isArray(opts) && opts.includes(key)) ||
9058 (isObject(opts) && key in opts)) {
9059 return true;
9060 }
9061 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9062 return true;
9063 }
9064 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9065 return true;
9066 }
9067 }
9068 function genRefFlag(v) {
9069 if (isShallow(v)) {
9070 return `ShallowRef`;
9071 }
9072 if (v.effect) {
9073 return `ComputedRef`;
9074 }
9075 return `Ref`;
9076 }
9077 if (window.devtoolsFormatters) {
9078 window.devtoolsFormatters.push(formatter);
9079 }
9080 else {
9081 window.devtoolsFormatters = [formatter];
9082 }
9083}
9084
9085function withMemo(memo, render, cache, index) {
9086 const cached = cache[index];
9087 if (cached && isMemoSame(cached, memo)) {
9088 return cached;
9089 }
9090 const ret = render();
9091 // shallow clone
9092 ret.memo = memo.slice();
9093 return (cache[index] = ret);
9094}
9095function isMemoSame(cached, memo) {
9096 const prev = cached.memo;
9097 if (prev.length != memo.length) {
9098 return false;
9099 }
9100 for (let i = 0; i < prev.length; i++) {
9101 if (prev[i] !== memo[i]) {
9102 return false;
9103 }
9104 }
9105 // make sure to let parent block track it when returning cached
9106 if (isBlockTreeEnabled > 0 && currentBlock) {
9107 currentBlock.push(cached);
9108 }
9109 return true;
9110}
9111
9112// Core API ------------------------------------------------------------------
9113const version = "3.2.29";
9114/**
9115 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9116 * @internal
9117 */
9118const ssrUtils = (null);
9119/**
9120 * @internal only exposed in compat builds
9121 */
9122const resolveFilter = null;
9123/**
9124 * @internal only exposed in compat builds.
9125 */
9126const compatUtils = (null);
9127
9128const svgNS = 'http://www.w3.org/2000/svg';
9129const doc = (typeof document !== 'undefined' ? document : null);
9130const templateContainer = doc && doc.createElement('template');
9131const nodeOps = {
9132 insert: (child, parent, anchor) => {
9133 parent.insertBefore(child, anchor || null);
9134 },
9135 remove: child => {
9136 const parent = child.parentNode;
9137 if (parent) {
9138 parent.removeChild(child);
9139 }
9140 },
9141 createElement: (tag, isSVG, is, props) => {
9142 const el = isSVG
9143 ? doc.createElementNS(svgNS, tag)
9144 : doc.createElement(tag, is ? { is } : undefined);
9145 if (tag === 'select' && props && props.multiple != null) {
9146 el.setAttribute('multiple', props.multiple);
9147 }
9148 return el;
9149 },
9150 createText: text => doc.createTextNode(text),
9151 createComment: text => doc.createComment(text),
9152 setText: (node, text) => {
9153 node.nodeValue = text;
9154 },
9155 setElementText: (el, text) => {
9156 el.textContent = text;
9157 },
9158 parentNode: node => node.parentNode,
9159 nextSibling: node => node.nextSibling,
9160 querySelector: selector => doc.querySelector(selector),
9161 setScopeId(el, id) {
9162 el.setAttribute(id, '');
9163 },
9164 cloneNode(el) {
9165 const cloned = el.cloneNode(true);
9166 // #3072
9167 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9168 // - normally, elements using `:value` bindings will not be hoisted, but if
9169 // the bound value is a constant, e.g. `:value="true"` - they do get
9170 // hoisted.
9171 // - in production, hoisted nodes are cloned when subsequent inserts, but
9172 // cloneNode() does not copy the custom property we attached.
9173 // - This may need to account for other custom DOM properties we attach to
9174 // elements in addition to `_value` in the future.
9175 if (`_value` in el) {
9176 cloned._value = el._value;
9177 }
9178 return cloned;
9179 },
9180 // __UNSAFE__
9181 // Reason: innerHTML.
9182 // Static content here can only come from compiled templates.
9183 // As long as the user only uses trusted templates, this is safe.
9184 insertStaticContent(content, parent, anchor, isSVG, start, end) {
9185 // <parent> before | first ... last | anchor </parent>
9186 const before = anchor ? anchor.previousSibling : parent.lastChild;
9187 // #5308 can only take cached path if:
9188 // - has a single root node
9189 // - nextSibling info is still available
9190 if (start && (start === end || start.nextSibling)) {
9191 // cached
9192 while (true) {
9193 parent.insertBefore(start.cloneNode(true), anchor);
9194 if (start === end || !(start = start.nextSibling))
9195 break;
9196 }
9197 }
9198 else {
9199 // fresh insert
9200 templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9201 const template = templateContainer.content;
9202 if (isSVG) {
9203 // remove outer svg wrapper
9204 const wrapper = template.firstChild;
9205 while (wrapper.firstChild) {
9206 template.appendChild(wrapper.firstChild);
9207 }
9208 template.removeChild(wrapper);
9209 }
9210 parent.insertBefore(template, anchor);
9211 }
9212 return [
9213 // first
9214 before ? before.nextSibling : parent.firstChild,
9215 // last
9216 anchor ? anchor.previousSibling : parent.lastChild
9217 ];
9218 }
9219};
9220
9221// compiler should normalize class + :class bindings on the same element
9222// into a single binding ['staticClass', dynamic]
9223function patchClass(el, value, isSVG) {
9224 // directly setting className should be faster than setAttribute in theory
9225 // if this is an element during a transition, take the temporary transition
9226 // classes into account.
9227 const transitionClasses = el._vtc;
9228 if (transitionClasses) {
9229 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9230 }
9231 if (value == null) {
9232 el.removeAttribute('class');
9233 }
9234 else if (isSVG) {
9235 el.setAttribute('class', value);
9236 }
9237 else {
9238 el.className = value;
9239 }
9240}
9241
9242function patchStyle(el, prev, next) {
9243 const style = el.style;
9244 const isCssString = isString(next);
9245 if (next && !isCssString) {
9246 for (const key in next) {
9247 setStyle(style, key, next[key]);
9248 }
9249 if (prev && !isString(prev)) {
9250 for (const key in prev) {
9251 if (next[key] == null) {
9252 setStyle(style, key, '');
9253 }
9254 }
9255 }
9256 }
9257 else {
9258 const currentDisplay = style.display;
9259 if (isCssString) {
9260 if (prev !== next) {
9261 style.cssText = next;
9262 }
9263 }
9264 else if (prev) {
9265 el.removeAttribute('style');
9266 }
9267 // indicates that the `display` of the element is controlled by `v-show`,
9268 // so we always keep the current `display` value regardless of the `style`
9269 // value, thus handing over control to `v-show`.
9270 if ('_vod' in el) {
9271 style.display = currentDisplay;
9272 }
9273 }
9274}
9275const importantRE = /\s*!important$/;
9276function setStyle(style, name, val) {
9277 if (isArray(val)) {
9278 val.forEach(v => setStyle(style, name, v));
9279 }
9280 else {
9281 if (name.startsWith('--')) {
9282 // custom property definition
9283 style.setProperty(name, val);
9284 }
9285 else {
9286 const prefixed = autoPrefix(style, name);
9287 if (importantRE.test(val)) {
9288 // !important
9289 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9290 }
9291 else {
9292 style[prefixed] = val;
9293 }
9294 }
9295 }
9296}
9297const prefixes = ['Webkit', 'Moz', 'ms'];
9298const prefixCache = {};
9299function autoPrefix(style, rawName) {
9300 const cached = prefixCache[rawName];
9301 if (cached) {
9302 return cached;
9303 }
9304 let name = camelize(rawName);
9305 if (name !== 'filter' && name in style) {
9306 return (prefixCache[rawName] = name);
9307 }
9308 name = capitalize(name);
9309 for (let i = 0; i < prefixes.length; i++) {
9310 const prefixed = prefixes[i] + name;
9311 if (prefixed in style) {
9312 return (prefixCache[rawName] = prefixed);
9313 }
9314 }
9315 return rawName;
9316}
9317
9318const xlinkNS = 'http://www.w3.org/1999/xlink';
9319function patchAttr(el, key, value, isSVG, instance) {
9320 if (isSVG && key.startsWith('xlink:')) {
9321 if (value == null) {
9322 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9323 }
9324 else {
9325 el.setAttributeNS(xlinkNS, key, value);
9326 }
9327 }
9328 else {
9329 // note we are only checking boolean attributes that don't have a
9330 // corresponding dom prop of the same name here.
9331 const isBoolean = isSpecialBooleanAttr(key);
9332 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9333 el.removeAttribute(key);
9334 }
9335 else {
9336 el.setAttribute(key, isBoolean ? '' : value);
9337 }
9338 }
9339}
9340
9341// __UNSAFE__
9342// functions. The user is responsible for using them with only trusted content.
9343function patchDOMProp(el, key, value,
9344// the following args are passed only due to potential innerHTML/textContent
9345// overriding existing VNodes, in which case the old tree must be properly
9346// unmounted.
9347prevChildren, parentComponent, parentSuspense, unmountChildren) {
9348 if (key === 'innerHTML' || key === 'textContent') {
9349 if (prevChildren) {
9350 unmountChildren(prevChildren, parentComponent, parentSuspense);
9351 }
9352 el[key] = value == null ? '' : value;
9353 return;
9354 }
9355 if (key === 'value' &&
9356 el.tagName !== 'PROGRESS' &&
9357 // custom elements may use _value internally
9358 !el.tagName.includes('-')) {
9359 // store value as _value as well since
9360 // non-string values will be stringified.
9361 el._value = value;
9362 const newValue = value == null ? '' : value;
9363 if (el.value !== newValue ||
9364 // #4956: always set for OPTION elements because its value falls back to
9365 // textContent if no value attribute is present. And setting .value for
9366 // OPTION has no side effect
9367 el.tagName === 'OPTION') {
9368 el.value = newValue;
9369 }
9370 if (value == null) {
9371 el.removeAttribute(key);
9372 }
9373 return;
9374 }
9375 if (value === '' || value == null) {
9376 const type = typeof el[key];
9377 if (type === 'boolean') {
9378 // e.g. <select multiple> compiles to { multiple: '' }
9379 el[key] = includeBooleanAttr(value);
9380 return;
9381 }
9382 else if (value == null && type === 'string') {
9383 // e.g. <div :id="null">
9384 el[key] = '';
9385 el.removeAttribute(key);
9386 return;
9387 }
9388 else if (type === 'number') {
9389 // e.g. <img :width="null">
9390 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9391 try {
9392 el[key] = 0;
9393 }
9394 catch (_a) { }
9395 el.removeAttribute(key);
9396 return;
9397 }
9398 }
9399 // some properties perform value validation and throw
9400 try {
9401 el[key] = value;
9402 }
9403 catch (e) {
9404 {
9405 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9406 `value ${value} is invalid.`, e);
9407 }
9408 }
9409}
9410
9411// Async edge case fix requires storing an event listener's attach timestamp.
9412let _getNow = Date.now;
9413let skipTimestampCheck = false;
9414if (typeof window !== 'undefined') {
9415 // Determine what event timestamp the browser is using. Annoyingly, the
9416 // timestamp can either be hi-res (relative to page load) or low-res
9417 // (relative to UNIX epoch), so in order to compare time we have to use the
9418 // same timestamp type when saving the flush timestamp.
9419 if (_getNow() > document.createEvent('Event').timeStamp) {
9420 // if the low-res timestamp which is bigger than the event timestamp
9421 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9422 // and we need to use the hi-res version for event listeners as well.
9423 _getNow = () => performance.now();
9424 }
9425 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9426 // and does not fire microtasks in between event propagation, so safe to exclude.
9427 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9428 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9429}
9430// To avoid the overhead of repeatedly calling performance.now(), we cache
9431// and use the same timestamp for all event listeners attached in the same tick.
9432let cachedNow = 0;
9433const p = Promise.resolve();
9434const reset = () => {
9435 cachedNow = 0;
9436};
9437const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9438function addEventListener(el, event, handler, options) {
9439 el.addEventListener(event, handler, options);
9440}
9441function removeEventListener(el, event, handler, options) {
9442 el.removeEventListener(event, handler, options);
9443}
9444function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9445 // vei = vue event invokers
9446 const invokers = el._vei || (el._vei = {});
9447 const existingInvoker = invokers[rawName];
9448 if (nextValue && existingInvoker) {
9449 // patch
9450 existingInvoker.value = nextValue;
9451 }
9452 else {
9453 const [name, options] = parseName(rawName);
9454 if (nextValue) {
9455 // add
9456 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9457 addEventListener(el, name, invoker, options);
9458 }
9459 else if (existingInvoker) {
9460 // remove
9461 removeEventListener(el, name, existingInvoker, options);
9462 invokers[rawName] = undefined;
9463 }
9464 }
9465}
9466const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9467function parseName(name) {
9468 let options;
9469 if (optionsModifierRE.test(name)) {
9470 options = {};
9471 let m;
9472 while ((m = name.match(optionsModifierRE))) {
9473 name = name.slice(0, name.length - m[0].length);
9474 options[m[0].toLowerCase()] = true;
9475 }
9476 }
9477 return [hyphenate(name.slice(2)), options];
9478}
9479function createInvoker(initialValue, instance) {
9480 const invoker = (e) => {
9481 // async edge case #6566: inner click event triggers patch, event handler
9482 // attached to outer element during patch, and triggered again. This
9483 // happens because browsers fire microtask ticks between event propagation.
9484 // the solution is simple: we save the timestamp when a handler is attached,
9485 // and the handler would only fire if the event passed to it was fired
9486 // AFTER it was attached.
9487 const timeStamp = e.timeStamp || _getNow();
9488 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9489 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9490 }
9491 };
9492 invoker.value = initialValue;
9493 invoker.attached = getNow();
9494 return invoker;
9495}
9496function patchStopImmediatePropagation(e, value) {
9497 if (isArray(value)) {
9498 const originalStop = e.stopImmediatePropagation;
9499 e.stopImmediatePropagation = () => {
9500 originalStop.call(e);
9501 e._stopped = true;
9502 };
9503 return value.map(fn => (e) => !e._stopped && fn && fn(e));
9504 }
9505 else {
9506 return value;
9507 }
9508}
9509
9510const nativeOnRE = /^on[a-z]/;
9511const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9512 if (key === 'class') {
9513 patchClass(el, nextValue, isSVG);
9514 }
9515 else if (key === 'style') {
9516 patchStyle(el, prevValue, nextValue);
9517 }
9518 else if (isOn(key)) {
9519 // ignore v-model listeners
9520 if (!isModelListener(key)) {
9521 patchEvent(el, key, prevValue, nextValue, parentComponent);
9522 }
9523 }
9524 else if (key[0] === '.'
9525 ? ((key = key.slice(1)), true)
9526 : key[0] === '^'
9527 ? ((key = key.slice(1)), false)
9528 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9529 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9530 }
9531 else {
9532 // special case for <input v-model type="checkbox"> with
9533 // :true-value & :false-value
9534 // store value as dom properties since non-string values will be
9535 // stringified.
9536 if (key === 'true-value') {
9537 el._trueValue = nextValue;
9538 }
9539 else if (key === 'false-value') {
9540 el._falseValue = nextValue;
9541 }
9542 patchAttr(el, key, nextValue, isSVG);
9543 }
9544};
9545function shouldSetAsProp(el, key, value, isSVG) {
9546 if (isSVG) {
9547 // most keys must be set as attribute on svg elements to work
9548 // ...except innerHTML & textContent
9549 if (key === 'innerHTML' || key === 'textContent') {
9550 return true;
9551 }
9552 // or native onclick with function values
9553 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9554 return true;
9555 }
9556 return false;
9557 }
9558 // spellcheck and draggable are numerated attrs, however their
9559 // corresponding DOM properties are actually booleans - this leads to
9560 // setting it with a string "false" value leading it to be coerced to
9561 // `true`, so we need to always treat them as attributes.
9562 // Note that `contentEditable` doesn't have this problem: its DOM
9563 // property is also enumerated string values.
9564 if (key === 'spellcheck' || key === 'draggable') {
9565 return false;
9566 }
9567 // #1787, #2840 form property on form elements is readonly and must be set as
9568 // attribute.
9569 if (key === 'form') {
9570 return false;
9571 }
9572 // #1526 <input list> must be set as attribute
9573 if (key === 'list' && el.tagName === 'INPUT') {
9574 return false;
9575 }
9576 // #2766 <textarea type> must be set as attribute
9577 if (key === 'type' && el.tagName === 'TEXTAREA') {
9578 return false;
9579 }
9580 // native onclick with string value, must be set as attribute
9581 if (nativeOnRE.test(key) && isString(value)) {
9582 return false;
9583 }
9584 return key in el;
9585}
9586
9587function defineCustomElement(options, hydate) {
9588 const Comp = defineComponent(options);
9589 class VueCustomElement extends VueElement {
9590 constructor(initialProps) {
9591 super(Comp, initialProps, hydate);
9592 }
9593 }
9594 VueCustomElement.def = Comp;
9595 return VueCustomElement;
9596}
9597const defineSSRCustomElement = ((options) => {
9598 // @ts-ignore
9599 return defineCustomElement(options, hydrate);
9600});
9601const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9602});
9603class VueElement extends BaseClass {
9604 constructor(_def, _props = {}, hydrate) {
9605 super();
9606 this._def = _def;
9607 this._props = _props;
9608 /**
9609 * @internal
9610 */
9611 this._instance = null;
9612 this._connected = false;
9613 this._resolved = false;
9614 this._numberProps = null;
9615 if (this.shadowRoot && hydrate) {
9616 hydrate(this._createVNode(), this.shadowRoot);
9617 }
9618 else {
9619 if (this.shadowRoot) {
9620 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9621 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9622 }
9623 this.attachShadow({ mode: 'open' });
9624 }
9625 }
9626 connectedCallback() {
9627 this._connected = true;
9628 if (!this._instance) {
9629 this._resolveDef();
9630 }
9631 }
9632 disconnectedCallback() {
9633 this._connected = false;
9634 nextTick(() => {
9635 if (!this._connected) {
9636 render(null, this.shadowRoot);
9637 this._instance = null;
9638 }
9639 });
9640 }
9641 /**
9642 * resolve inner component definition (handle possible async component)
9643 */
9644 _resolveDef() {
9645 if (this._resolved) {
9646 return;
9647 }
9648 this._resolved = true;
9649 // set initial attrs
9650 for (let i = 0; i < this.attributes.length; i++) {
9651 this._setAttr(this.attributes[i].name);
9652 }
9653 // watch future attr changes
9654 new MutationObserver(mutations => {
9655 for (const m of mutations) {
9656 this._setAttr(m.attributeName);
9657 }
9658 }).observe(this, { attributes: true });
9659 const resolve = (def) => {
9660 const { props, styles } = def;
9661 const hasOptions = !isArray(props);
9662 const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
9663 // cast Number-type props set before resolve
9664 let numberProps;
9665 if (hasOptions) {
9666 for (const key in this._props) {
9667 const opt = props[key];
9668 if (opt === Number || (opt && opt.type === Number)) {
9669 this._props[key] = toNumber(this._props[key]);
9670 (numberProps || (numberProps = Object.create(null)))[key] = true;
9671 }
9672 }
9673 }
9674 this._numberProps = numberProps;
9675 // check if there are props set pre-upgrade or connect
9676 for (const key of Object.keys(this)) {
9677 if (key[0] !== '_') {
9678 this._setProp(key, this[key], true, false);
9679 }
9680 }
9681 // defining getter/setters on prototype
9682 for (const key of rawKeys.map(camelize)) {
9683 Object.defineProperty(this, key, {
9684 get() {
9685 return this._getProp(key);
9686 },
9687 set(val) {
9688 this._setProp(key, val);
9689 }
9690 });
9691 }
9692 // apply CSS
9693 this._applyStyles(styles);
9694 // initial render
9695 this._update();
9696 };
9697 const asyncDef = this._def.__asyncLoader;
9698 if (asyncDef) {
9699 asyncDef().then(resolve);
9700 }
9701 else {
9702 resolve(this._def);
9703 }
9704 }
9705 _setAttr(key) {
9706 let value = this.getAttribute(key);
9707 if (this._numberProps && this._numberProps[key]) {
9708 value = toNumber(value);
9709 }
9710 this._setProp(camelize(key), value, false);
9711 }
9712 /**
9713 * @internal
9714 */
9715 _getProp(key) {
9716 return this._props[key];
9717 }
9718 /**
9719 * @internal
9720 */
9721 _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
9722 if (val !== this._props[key]) {
9723 this._props[key] = val;
9724 if (shouldUpdate && this._instance) {
9725 this._update();
9726 }
9727 // reflect
9728 if (shouldReflect) {
9729 if (val === true) {
9730 this.setAttribute(hyphenate(key), '');
9731 }
9732 else if (typeof val === 'string' || typeof val === 'number') {
9733 this.setAttribute(hyphenate(key), val + '');
9734 }
9735 else if (!val) {
9736 this.removeAttribute(hyphenate(key));
9737 }
9738 }
9739 }
9740 }
9741 _update() {
9742 render(this._createVNode(), this.shadowRoot);
9743 }
9744 _createVNode() {
9745 const vnode = createVNode(this._def, extend({}, this._props));
9746 if (!this._instance) {
9747 vnode.ce = instance => {
9748 this._instance = instance;
9749 instance.isCE = true;
9750 // HMR
9751 {
9752 instance.ceReload = newStyles => {
9753 // always reset styles
9754 if (this._styles) {
9755 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9756 this._styles.length = 0;
9757 }
9758 this._applyStyles(newStyles);
9759 // if this is an async component, ceReload is called from the inner
9760 // component so no need to reload the async wrapper
9761 if (!this._def.__asyncLoader) {
9762 // reload
9763 this._instance = null;
9764 this._update();
9765 }
9766 };
9767 }
9768 // intercept emit
9769 instance.emit = (event, ...args) => {
9770 this.dispatchEvent(new CustomEvent(event, {
9771 detail: args
9772 }));
9773 };
9774 // locate nearest Vue custom element parent for provide/inject
9775 let parent = this;
9776 while ((parent =
9777 parent && (parent.parentNode || parent.host))) {
9778 if (parent instanceof VueElement) {
9779 instance.parent = parent._instance;
9780 break;
9781 }
9782 }
9783 };
9784 }
9785 return vnode;
9786 }
9787 _applyStyles(styles) {
9788 if (styles) {
9789 styles.forEach(css => {
9790 const s = document.createElement('style');
9791 s.textContent = css;
9792 this.shadowRoot.appendChild(s);
9793 // record for HMR
9794 {
9795 (this._styles || (this._styles = [])).push(s);
9796 }
9797 });
9798 }
9799 }
9800}
9801
9802function useCssModule(name = '$style') {
9803 /* istanbul ignore else */
9804 {
9805 const instance = getCurrentInstance();
9806 if (!instance) {
9807 warn$1(`useCssModule must be called inside setup()`);
9808 return EMPTY_OBJ;
9809 }
9810 const modules = instance.type.__cssModules;
9811 if (!modules) {
9812 warn$1(`Current instance does not have CSS modules injected.`);
9813 return EMPTY_OBJ;
9814 }
9815 const mod = modules[name];
9816 if (!mod) {
9817 warn$1(`Current instance does not have CSS module named "${name}".`);
9818 return EMPTY_OBJ;
9819 }
9820 return mod;
9821 }
9822}
9823
9824/**
9825 * Runtime helper for SFC's CSS variable injection feature.
9826 * @private
9827 */
9828function useCssVars(getter) {
9829 const instance = getCurrentInstance();
9830 /* istanbul ignore next */
9831 if (!instance) {
9832 warn$1(`useCssVars is called without current active component instance.`);
9833 return;
9834 }
9835 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9836 watchPostEffect(setVars);
9837 onMounted(() => {
9838 const ob = new MutationObserver(setVars);
9839 ob.observe(instance.subTree.el.parentNode, { childList: true });
9840 onUnmounted(() => ob.disconnect());
9841 });
9842}
9843function setVarsOnVNode(vnode, vars) {
9844 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9845 const suspense = vnode.suspense;
9846 vnode = suspense.activeBranch;
9847 if (suspense.pendingBranch && !suspense.isHydrating) {
9848 suspense.effects.push(() => {
9849 setVarsOnVNode(suspense.activeBranch, vars);
9850 });
9851 }
9852 }
9853 // drill down HOCs until it's a non-component vnode
9854 while (vnode.component) {
9855 vnode = vnode.component.subTree;
9856 }
9857 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
9858 setVarsOnNode(vnode.el, vars);
9859 }
9860 else if (vnode.type === Fragment) {
9861 vnode.children.forEach(c => setVarsOnVNode(c, vars));
9862 }
9863 else if (vnode.type === Static) {
9864 let { el, anchor } = vnode;
9865 while (el) {
9866 setVarsOnNode(el, vars);
9867 if (el === anchor)
9868 break;
9869 el = el.nextSibling;
9870 }
9871 }
9872}
9873function setVarsOnNode(el, vars) {
9874 if (el.nodeType === 1) {
9875 const style = el.style;
9876 for (const key in vars) {
9877 style.setProperty(`--${key}`, vars[key]);
9878 }
9879 }
9880}
9881
9882const TRANSITION = 'transition';
9883const ANIMATION = 'animation';
9884// DOM Transition is a higher-order-component based on the platform-agnostic
9885// base Transition component, with DOM-specific logic.
9886const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
9887Transition.displayName = 'Transition';
9888const DOMTransitionPropsValidators = {
9889 name: String,
9890 type: String,
9891 css: {
9892 type: Boolean,
9893 default: true
9894 },
9895 duration: [String, Number, Object],
9896 enterFromClass: String,
9897 enterActiveClass: String,
9898 enterToClass: String,
9899 appearFromClass: String,
9900 appearActiveClass: String,
9901 appearToClass: String,
9902 leaveFromClass: String,
9903 leaveActiveClass: String,
9904 leaveToClass: String
9905};
9906const TransitionPropsValidators = (Transition.props =
9907 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
9908/**
9909 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
9910 * with custom HOCs.
9911 */
9912const callHook$1 = (hook, args = []) => {
9913 if (isArray(hook)) {
9914 hook.forEach(h => h(...args));
9915 }
9916 else if (hook) {
9917 hook(...args);
9918 }
9919};
9920/**
9921 * Check if a hook expects a callback (2nd arg), which means the user
9922 * intends to explicitly control the end of the transition.
9923 */
9924const hasExplicitCallback = (hook) => {
9925 return hook
9926 ? isArray(hook)
9927 ? hook.some(h => h.length > 1)
9928 : hook.length > 1
9929 : false;
9930};
9931function resolveTransitionProps(rawProps) {
9932 const baseProps = {};
9933 for (const key in rawProps) {
9934 if (!(key in DOMTransitionPropsValidators)) {
9935 baseProps[key] = rawProps[key];
9936 }
9937 }
9938 if (rawProps.css === false) {
9939 return baseProps;
9940 }
9941 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;
9942 const durations = normalizeDuration(duration);
9943 const enterDuration = durations && durations[0];
9944 const leaveDuration = durations && durations[1];
9945 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
9946 const finishEnter = (el, isAppear, done) => {
9947 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
9948 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
9949 done && done();
9950 };
9951 const finishLeave = (el, done) => {
9952 removeTransitionClass(el, leaveToClass);
9953 removeTransitionClass(el, leaveActiveClass);
9954 done && done();
9955 };
9956 const makeEnterHook = (isAppear) => {
9957 return (el, done) => {
9958 const hook = isAppear ? onAppear : onEnter;
9959 const resolve = () => finishEnter(el, isAppear, done);
9960 callHook$1(hook, [el, resolve]);
9961 nextFrame(() => {
9962 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
9963 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
9964 if (!hasExplicitCallback(hook)) {
9965 whenTransitionEnds(el, type, enterDuration, resolve);
9966 }
9967 });
9968 };
9969 };
9970 return extend(baseProps, {
9971 onBeforeEnter(el) {
9972 callHook$1(onBeforeEnter, [el]);
9973 addTransitionClass(el, enterFromClass);
9974 addTransitionClass(el, enterActiveClass);
9975 },
9976 onBeforeAppear(el) {
9977 callHook$1(onBeforeAppear, [el]);
9978 addTransitionClass(el, appearFromClass);
9979 addTransitionClass(el, appearActiveClass);
9980 },
9981 onEnter: makeEnterHook(false),
9982 onAppear: makeEnterHook(true),
9983 onLeave(el, done) {
9984 const resolve = () => finishLeave(el, done);
9985 addTransitionClass(el, leaveFromClass);
9986 // force reflow so *-leave-from classes immediately take effect (#2593)
9987 forceReflow();
9988 addTransitionClass(el, leaveActiveClass);
9989 nextFrame(() => {
9990 removeTransitionClass(el, leaveFromClass);
9991 addTransitionClass(el, leaveToClass);
9992 if (!hasExplicitCallback(onLeave)) {
9993 whenTransitionEnds(el, type, leaveDuration, resolve);
9994 }
9995 });
9996 callHook$1(onLeave, [el, resolve]);
9997 },
9998 onEnterCancelled(el) {
9999 finishEnter(el, false);
10000 callHook$1(onEnterCancelled, [el]);
10001 },
10002 onAppearCancelled(el) {
10003 finishEnter(el, true);
10004 callHook$1(onAppearCancelled, [el]);
10005 },
10006 onLeaveCancelled(el) {
10007 finishLeave(el);
10008 callHook$1(onLeaveCancelled, [el]);
10009 }
10010 });
10011}
10012function normalizeDuration(duration) {
10013 if (duration == null) {
10014 return null;
10015 }
10016 else if (isObject(duration)) {
10017 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10018 }
10019 else {
10020 const n = NumberOf(duration);
10021 return [n, n];
10022 }
10023}
10024function NumberOf(val) {
10025 const res = toNumber(val);
10026 validateDuration(res);
10027 return res;
10028}
10029function validateDuration(val) {
10030 if (typeof val !== 'number') {
10031 warn$1(`<transition> explicit duration is not a valid number - ` +
10032 `got ${JSON.stringify(val)}.`);
10033 }
10034 else if (isNaN(val)) {
10035 warn$1(`<transition> explicit duration is NaN - ` +
10036 'the duration expression might be incorrect.');
10037 }
10038}
10039function addTransitionClass(el, cls) {
10040 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10041 (el._vtc ||
10042 (el._vtc = new Set())).add(cls);
10043}
10044function removeTransitionClass(el, cls) {
10045 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10046 const { _vtc } = el;
10047 if (_vtc) {
10048 _vtc.delete(cls);
10049 if (!_vtc.size) {
10050 el._vtc = undefined;
10051 }
10052 }
10053}
10054function nextFrame(cb) {
10055 requestAnimationFrame(() => {
10056 requestAnimationFrame(cb);
10057 });
10058}
10059let endId = 0;
10060function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10061 const id = (el._endId = ++endId);
10062 const resolveIfNotStale = () => {
10063 if (id === el._endId) {
10064 resolve();
10065 }
10066 };
10067 if (explicitTimeout) {
10068 return setTimeout(resolveIfNotStale, explicitTimeout);
10069 }
10070 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10071 if (!type) {
10072 return resolve();
10073 }
10074 const endEvent = type + 'end';
10075 let ended = 0;
10076 const end = () => {
10077 el.removeEventListener(endEvent, onEnd);
10078 resolveIfNotStale();
10079 };
10080 const onEnd = (e) => {
10081 if (e.target === el && ++ended >= propCount) {
10082 end();
10083 }
10084 };
10085 setTimeout(() => {
10086 if (ended < propCount) {
10087 end();
10088 }
10089 }, timeout + 1);
10090 el.addEventListener(endEvent, onEnd);
10091}
10092function getTransitionInfo(el, expectedType) {
10093 const styles = window.getComputedStyle(el);
10094 // JSDOM may return undefined for transition properties
10095 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10096 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10097 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10098 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10099 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10100 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10101 const animationTimeout = getTimeout(animationDelays, animationDurations);
10102 let type = null;
10103 let timeout = 0;
10104 let propCount = 0;
10105 /* istanbul ignore if */
10106 if (expectedType === TRANSITION) {
10107 if (transitionTimeout > 0) {
10108 type = TRANSITION;
10109 timeout = transitionTimeout;
10110 propCount = transitionDurations.length;
10111 }
10112 }
10113 else if (expectedType === ANIMATION) {
10114 if (animationTimeout > 0) {
10115 type = ANIMATION;
10116 timeout = animationTimeout;
10117 propCount = animationDurations.length;
10118 }
10119 }
10120 else {
10121 timeout = Math.max(transitionTimeout, animationTimeout);
10122 type =
10123 timeout > 0
10124 ? transitionTimeout > animationTimeout
10125 ? TRANSITION
10126 : ANIMATION
10127 : null;
10128 propCount = type
10129 ? type === TRANSITION
10130 ? transitionDurations.length
10131 : animationDurations.length
10132 : 0;
10133 }
10134 const hasTransform = type === TRANSITION &&
10135 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10136 return {
10137 type,
10138 timeout,
10139 propCount,
10140 hasTransform
10141 };
10142}
10143function getTimeout(delays, durations) {
10144 while (delays.length < durations.length) {
10145 delays = delays.concat(delays);
10146 }
10147 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10148}
10149// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10150// numbers in a locale-dependent way, using a comma instead of a dot.
10151// If comma is not replaced with a dot, the input will be rounded down
10152// (i.e. acting as a floor function) causing unexpected behaviors
10153function toMs(s) {
10154 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10155}
10156// synchronously force layout to put elements into a certain state
10157function forceReflow() {
10158 return document.body.offsetHeight;
10159}
10160
10161const positionMap = new WeakMap();
10162const newPositionMap = new WeakMap();
10163const TransitionGroupImpl = {
10164 name: 'TransitionGroup',
10165 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10166 tag: String,
10167 moveClass: String
10168 }),
10169 setup(props, { slots }) {
10170 const instance = getCurrentInstance();
10171 const state = useTransitionState();
10172 let prevChildren;
10173 let children;
10174 onUpdated(() => {
10175 // children is guaranteed to exist after initial render
10176 if (!prevChildren.length) {
10177 return;
10178 }
10179 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10180 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10181 return;
10182 }
10183 // we divide the work into three loops to avoid mixing DOM reads and writes
10184 // in each iteration - which helps prevent layout thrashing.
10185 prevChildren.forEach(callPendingCbs);
10186 prevChildren.forEach(recordPosition);
10187 const movedChildren = prevChildren.filter(applyTranslation);
10188 // force reflow to put everything in position
10189 forceReflow();
10190 movedChildren.forEach(c => {
10191 const el = c.el;
10192 const style = el.style;
10193 addTransitionClass(el, moveClass);
10194 style.transform = style.webkitTransform = style.transitionDuration = '';
10195 const cb = (el._moveCb = (e) => {
10196 if (e && e.target !== el) {
10197 return;
10198 }
10199 if (!e || /transform$/.test(e.propertyName)) {
10200 el.removeEventListener('transitionend', cb);
10201 el._moveCb = null;
10202 removeTransitionClass(el, moveClass);
10203 }
10204 });
10205 el.addEventListener('transitionend', cb);
10206 });
10207 });
10208 return () => {
10209 const rawProps = toRaw(props);
10210 const cssTransitionProps = resolveTransitionProps(rawProps);
10211 let tag = rawProps.tag || Fragment;
10212 prevChildren = children;
10213 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10214 for (let i = 0; i < children.length; i++) {
10215 const child = children[i];
10216 if (child.key != null) {
10217 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10218 }
10219 else {
10220 warn$1(`<TransitionGroup> children must be keyed.`);
10221 }
10222 }
10223 if (prevChildren) {
10224 for (let i = 0; i < prevChildren.length; i++) {
10225 const child = prevChildren[i];
10226 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10227 positionMap.set(child, child.el.getBoundingClientRect());
10228 }
10229 }
10230 return createVNode(tag, null, children);
10231 };
10232 }
10233};
10234const TransitionGroup = TransitionGroupImpl;
10235function callPendingCbs(c) {
10236 const el = c.el;
10237 if (el._moveCb) {
10238 el._moveCb();
10239 }
10240 if (el._enterCb) {
10241 el._enterCb();
10242 }
10243}
10244function recordPosition(c) {
10245 newPositionMap.set(c, c.el.getBoundingClientRect());
10246}
10247function applyTranslation(c) {
10248 const oldPos = positionMap.get(c);
10249 const newPos = newPositionMap.get(c);
10250 const dx = oldPos.left - newPos.left;
10251 const dy = oldPos.top - newPos.top;
10252 if (dx || dy) {
10253 const s = c.el.style;
10254 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10255 s.transitionDuration = '0s';
10256 return c;
10257 }
10258}
10259function hasCSSTransform(el, root, moveClass) {
10260 // Detect whether an element with the move class applied has
10261 // CSS transitions. Since the element may be inside an entering
10262 // transition at this very moment, we make a clone of it and remove
10263 // all other transition classes applied to ensure only the move class
10264 // is applied.
10265 const clone = el.cloneNode();
10266 if (el._vtc) {
10267 el._vtc.forEach(cls => {
10268 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10269 });
10270 }
10271 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10272 clone.style.display = 'none';
10273 const container = (root.nodeType === 1 ? root : root.parentNode);
10274 container.appendChild(clone);
10275 const { hasTransform } = getTransitionInfo(clone);
10276 container.removeChild(clone);
10277 return hasTransform;
10278}
10279
10280const getModelAssigner = (vnode) => {
10281 const fn = vnode.props['onUpdate:modelValue'];
10282 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10283};
10284function onCompositionStart(e) {
10285 e.target.composing = true;
10286}
10287function onCompositionEnd(e) {
10288 const target = e.target;
10289 if (target.composing) {
10290 target.composing = false;
10291 trigger$1(target, 'input');
10292 }
10293}
10294function trigger$1(el, type) {
10295 const e = document.createEvent('HTMLEvents');
10296 e.initEvent(type, true, true);
10297 el.dispatchEvent(e);
10298}
10299// We are exporting the v-model runtime directly as vnode hooks so that it can
10300// be tree-shaken in case v-model is never used.
10301const vModelText = {
10302 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10303 el._assign = getModelAssigner(vnode);
10304 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10305 addEventListener(el, lazy ? 'change' : 'input', e => {
10306 if (e.target.composing)
10307 return;
10308 let domValue = el.value;
10309 if (trim) {
10310 domValue = domValue.trim();
10311 }
10312 else if (castToNumber) {
10313 domValue = toNumber(domValue);
10314 }
10315 el._assign(domValue);
10316 });
10317 if (trim) {
10318 addEventListener(el, 'change', () => {
10319 el.value = el.value.trim();
10320 });
10321 }
10322 if (!lazy) {
10323 addEventListener(el, 'compositionstart', onCompositionStart);
10324 addEventListener(el, 'compositionend', onCompositionEnd);
10325 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10326 // switching focus before confirming composition choice
10327 // this also fixes the issue where some browsers e.g. iOS Chrome
10328 // fires "change" instead of "input" on autocomplete.
10329 addEventListener(el, 'change', onCompositionEnd);
10330 }
10331 },
10332 // set value on mounted so it's after min/max for type="range"
10333 mounted(el, { value }) {
10334 el.value = value == null ? '' : value;
10335 },
10336 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10337 el._assign = getModelAssigner(vnode);
10338 // avoid clearing unresolved text. #2302
10339 if (el.composing)
10340 return;
10341 if (document.activeElement === el) {
10342 if (lazy) {
10343 return;
10344 }
10345 if (trim && el.value.trim() === value) {
10346 return;
10347 }
10348 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10349 return;
10350 }
10351 }
10352 const newValue = value == null ? '' : value;
10353 if (el.value !== newValue) {
10354 el.value = newValue;
10355 }
10356 }
10357};
10358const vModelCheckbox = {
10359 // #4096 array checkboxes need to be deep traversed
10360 deep: true,
10361 created(el, _, vnode) {
10362 el._assign = getModelAssigner(vnode);
10363 addEventListener(el, 'change', () => {
10364 const modelValue = el._modelValue;
10365 const elementValue = getValue(el);
10366 const checked = el.checked;
10367 const assign = el._assign;
10368 if (isArray(modelValue)) {
10369 const index = looseIndexOf(modelValue, elementValue);
10370 const found = index !== -1;
10371 if (checked && !found) {
10372 assign(modelValue.concat(elementValue));
10373 }
10374 else if (!checked && found) {
10375 const filtered = [...modelValue];
10376 filtered.splice(index, 1);
10377 assign(filtered);
10378 }
10379 }
10380 else if (isSet(modelValue)) {
10381 const cloned = new Set(modelValue);
10382 if (checked) {
10383 cloned.add(elementValue);
10384 }
10385 else {
10386 cloned.delete(elementValue);
10387 }
10388 assign(cloned);
10389 }
10390 else {
10391 assign(getCheckboxValue(el, checked));
10392 }
10393 });
10394 },
10395 // set initial checked on mount to wait for true-value/false-value
10396 mounted: setChecked,
10397 beforeUpdate(el, binding, vnode) {
10398 el._assign = getModelAssigner(vnode);
10399 setChecked(el, binding, vnode);
10400 }
10401};
10402function setChecked(el, { value, oldValue }, vnode) {
10403 el._modelValue = value;
10404 if (isArray(value)) {
10405 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10406 }
10407 else if (isSet(value)) {
10408 el.checked = value.has(vnode.props.value);
10409 }
10410 else if (value !== oldValue) {
10411 el.checked = looseEqual(value, getCheckboxValue(el, true));
10412 }
10413}
10414const vModelRadio = {
10415 created(el, { value }, vnode) {
10416 el.checked = looseEqual(value, vnode.props.value);
10417 el._assign = getModelAssigner(vnode);
10418 addEventListener(el, 'change', () => {
10419 el._assign(getValue(el));
10420 });
10421 },
10422 beforeUpdate(el, { value, oldValue }, vnode) {
10423 el._assign = getModelAssigner(vnode);
10424 if (value !== oldValue) {
10425 el.checked = looseEqual(value, vnode.props.value);
10426 }
10427 }
10428};
10429const vModelSelect = {
10430 // <select multiple> value need to be deep traversed
10431 deep: true,
10432 created(el, { value, modifiers: { number } }, vnode) {
10433 const isSetModel = isSet(value);
10434 addEventListener(el, 'change', () => {
10435 const selectedVal = Array.prototype.filter
10436 .call(el.options, (o) => o.selected)
10437 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10438 el._assign(el.multiple
10439 ? isSetModel
10440 ? new Set(selectedVal)
10441 : selectedVal
10442 : selectedVal[0]);
10443 });
10444 el._assign = getModelAssigner(vnode);
10445 },
10446 // set value in mounted & updated because <select> relies on its children
10447 // <option>s.
10448 mounted(el, { value }) {
10449 setSelected(el, value);
10450 },
10451 beforeUpdate(el, _binding, vnode) {
10452 el._assign = getModelAssigner(vnode);
10453 },
10454 updated(el, { value }) {
10455 setSelected(el, value);
10456 }
10457};
10458function setSelected(el, value) {
10459 const isMultiple = el.multiple;
10460 if (isMultiple && !isArray(value) && !isSet(value)) {
10461 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10462 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10463 return;
10464 }
10465 for (let i = 0, l = el.options.length; i < l; i++) {
10466 const option = el.options[i];
10467 const optionValue = getValue(option);
10468 if (isMultiple) {
10469 if (isArray(value)) {
10470 option.selected = looseIndexOf(value, optionValue) > -1;
10471 }
10472 else {
10473 option.selected = value.has(optionValue);
10474 }
10475 }
10476 else {
10477 if (looseEqual(getValue(option), value)) {
10478 if (el.selectedIndex !== i)
10479 el.selectedIndex = i;
10480 return;
10481 }
10482 }
10483 }
10484 if (!isMultiple && el.selectedIndex !== -1) {
10485 el.selectedIndex = -1;
10486 }
10487}
10488// retrieve raw value set via :value bindings
10489function getValue(el) {
10490 return '_value' in el ? el._value : el.value;
10491}
10492// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10493function getCheckboxValue(el, checked) {
10494 const key = checked ? '_trueValue' : '_falseValue';
10495 return key in el ? el[key] : checked;
10496}
10497const vModelDynamic = {
10498 created(el, binding, vnode) {
10499 callModelHook(el, binding, vnode, null, 'created');
10500 },
10501 mounted(el, binding, vnode) {
10502 callModelHook(el, binding, vnode, null, 'mounted');
10503 },
10504 beforeUpdate(el, binding, vnode, prevVNode) {
10505 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10506 },
10507 updated(el, binding, vnode, prevVNode) {
10508 callModelHook(el, binding, vnode, prevVNode, 'updated');
10509 }
10510};
10511function callModelHook(el, binding, vnode, prevVNode, hook) {
10512 let modelToUse;
10513 switch (el.tagName) {
10514 case 'SELECT':
10515 modelToUse = vModelSelect;
10516 break;
10517 case 'TEXTAREA':
10518 modelToUse = vModelText;
10519 break;
10520 default:
10521 switch (vnode.props && vnode.props.type) {
10522 case 'checkbox':
10523 modelToUse = vModelCheckbox;
10524 break;
10525 case 'radio':
10526 modelToUse = vModelRadio;
10527 break;
10528 default:
10529 modelToUse = vModelText;
10530 }
10531 }
10532 const fn = modelToUse[hook];
10533 fn && fn(el, binding, vnode, prevVNode);
10534}
10535
10536const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10537const modifierGuards = {
10538 stop: e => e.stopPropagation(),
10539 prevent: e => e.preventDefault(),
10540 self: e => e.target !== e.currentTarget,
10541 ctrl: e => !e.ctrlKey,
10542 shift: e => !e.shiftKey,
10543 alt: e => !e.altKey,
10544 meta: e => !e.metaKey,
10545 left: e => 'button' in e && e.button !== 0,
10546 middle: e => 'button' in e && e.button !== 1,
10547 right: e => 'button' in e && e.button !== 2,
10548 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10549};
10550/**
10551 * @private
10552 */
10553const withModifiers = (fn, modifiers) => {
10554 return (event, ...args) => {
10555 for (let i = 0; i < modifiers.length; i++) {
10556 const guard = modifierGuards[modifiers[i]];
10557 if (guard && guard(event, modifiers))
10558 return;
10559 }
10560 return fn(event, ...args);
10561 };
10562};
10563// Kept for 2.x compat.
10564// Note: IE11 compat for `spacebar` and `del` is removed for now.
10565const keyNames = {
10566 esc: 'escape',
10567 space: ' ',
10568 up: 'arrow-up',
10569 left: 'arrow-left',
10570 right: 'arrow-right',
10571 down: 'arrow-down',
10572 delete: 'backspace'
10573};
10574/**
10575 * @private
10576 */
10577const withKeys = (fn, modifiers) => {
10578 return (event) => {
10579 if (!('key' in event)) {
10580 return;
10581 }
10582 const eventKey = hyphenate(event.key);
10583 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10584 return fn(event);
10585 }
10586 };
10587};
10588
10589const vShow = {
10590 beforeMount(el, { value }, { transition }) {
10591 el._vod = el.style.display === 'none' ? '' : el.style.display;
10592 if (transition && value) {
10593 transition.beforeEnter(el);
10594 }
10595 else {
10596 setDisplay(el, value);
10597 }
10598 },
10599 mounted(el, { value }, { transition }) {
10600 if (transition && value) {
10601 transition.enter(el);
10602 }
10603 },
10604 updated(el, { value, oldValue }, { transition }) {
10605 if (!value === !oldValue)
10606 return;
10607 if (transition) {
10608 if (value) {
10609 transition.beforeEnter(el);
10610 setDisplay(el, true);
10611 transition.enter(el);
10612 }
10613 else {
10614 transition.leave(el, () => {
10615 setDisplay(el, false);
10616 });
10617 }
10618 }
10619 else {
10620 setDisplay(el, value);
10621 }
10622 },
10623 beforeUnmount(el, { value }) {
10624 setDisplay(el, value);
10625 }
10626};
10627function setDisplay(el, value) {
10628 el.style.display = value ? el._vod : 'none';
10629}
10630
10631const rendererOptions = extend({ patchProp }, nodeOps);
10632// lazy create the renderer - this makes core renderer logic tree-shakable
10633// in case the user only imports reactivity utilities from Vue.
10634let renderer;
10635let enabledHydration = false;
10636function ensureRenderer() {
10637 return (renderer ||
10638 (renderer = createRenderer(rendererOptions)));
10639}
10640function ensureHydrationRenderer() {
10641 renderer = enabledHydration
10642 ? renderer
10643 : createHydrationRenderer(rendererOptions);
10644 enabledHydration = true;
10645 return renderer;
10646}
10647// use explicit type casts here to avoid import() calls in rolled-up d.ts
10648const render = ((...args) => {
10649 ensureRenderer().render(...args);
10650});
10651const hydrate = ((...args) => {
10652 ensureHydrationRenderer().hydrate(...args);
10653});
10654const createApp = ((...args) => {
10655 const app = ensureRenderer().createApp(...args);
10656 {
10657 injectNativeTagCheck(app);
10658 injectCompilerOptionsCheck(app);
10659 }
10660 const { mount } = app;
10661 app.mount = (containerOrSelector) => {
10662 const container = normalizeContainer(containerOrSelector);
10663 if (!container)
10664 return;
10665 const component = app._component;
10666 if (!isFunction(component) && !component.render && !component.template) {
10667 // __UNSAFE__
10668 // Reason: potential execution of JS expressions in in-DOM template.
10669 // The user must make sure the in-DOM template is trusted. If it's
10670 // rendered by the server, the template should not contain any user data.
10671 component.template = container.innerHTML;
10672 }
10673 // clear content before mounting
10674 container.innerHTML = '';
10675 const proxy = mount(container, false, container instanceof SVGElement);
10676 if (container instanceof Element) {
10677 container.removeAttribute('v-cloak');
10678 container.setAttribute('data-v-app', '');
10679 }
10680 return proxy;
10681 };
10682 return app;
10683});
10684const createSSRApp = ((...args) => {
10685 const app = ensureHydrationRenderer().createApp(...args);
10686 {
10687 injectNativeTagCheck(app);
10688 injectCompilerOptionsCheck(app);
10689 }
10690 const { mount } = app;
10691 app.mount = (containerOrSelector) => {
10692 const container = normalizeContainer(containerOrSelector);
10693 if (container) {
10694 return mount(container, true, container instanceof SVGElement);
10695 }
10696 };
10697 return app;
10698});
10699function injectNativeTagCheck(app) {
10700 // Inject `isNativeTag`
10701 // this is used for component name validation (dev only)
10702 Object.defineProperty(app.config, 'isNativeTag', {
10703 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10704 writable: false
10705 });
10706}
10707// dev only
10708function injectCompilerOptionsCheck(app) {
10709 if (isRuntimeOnly()) {
10710 const isCustomElement = app.config.isCustomElement;
10711 Object.defineProperty(app.config, 'isCustomElement', {
10712 get() {
10713 return isCustomElement;
10714 },
10715 set() {
10716 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10717 `\`compilerOptions.isCustomElement\` instead.`);
10718 }
10719 });
10720 const compilerOptions = app.config.compilerOptions;
10721 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10722 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10723 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10724 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10725 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10726 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10727 `- 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`;
10728 Object.defineProperty(app.config, 'compilerOptions', {
10729 get() {
10730 warn$1(msg);
10731 return compilerOptions;
10732 },
10733 set() {
10734 warn$1(msg);
10735 }
10736 });
10737 }
10738}
10739function normalizeContainer(container) {
10740 if (isString(container)) {
10741 const res = document.querySelector(container);
10742 if (!res) {
10743 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10744 }
10745 return res;
10746 }
10747 if (window.ShadowRoot &&
10748 container instanceof window.ShadowRoot &&
10749 container.mode === 'closed') {
10750 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10751 }
10752 return container;
10753}
10754/**
10755 * @internal
10756 */
10757const initDirectivesForSSR = NOOP;
10758
10759var runtimeDom = /*#__PURE__*/Object.freeze({
10760 __proto__: null,
10761 render: render,
10762 hydrate: hydrate,
10763 createApp: createApp,
10764 createSSRApp: createSSRApp,
10765 initDirectivesForSSR: initDirectivesForSSR,
10766 defineCustomElement: defineCustomElement,
10767 defineSSRCustomElement: defineSSRCustomElement,
10768 VueElement: VueElement,
10769 useCssModule: useCssModule,
10770 useCssVars: useCssVars,
10771 Transition: Transition,
10772 TransitionGroup: TransitionGroup,
10773 vModelText: vModelText,
10774 vModelCheckbox: vModelCheckbox,
10775 vModelRadio: vModelRadio,
10776 vModelSelect: vModelSelect,
10777 vModelDynamic: vModelDynamic,
10778 withModifiers: withModifiers,
10779 withKeys: withKeys,
10780 vShow: vShow,
10781 reactive: reactive,
10782 ref: ref,
10783 readonly: readonly,
10784 unref: unref,
10785 proxyRefs: proxyRefs,
10786 isRef: isRef,
10787 toRef: toRef,
10788 toRefs: toRefs,
10789 isProxy: isProxy,
10790 isReactive: isReactive,
10791 isReadonly: isReadonly,
10792 isShallow: isShallow,
10793 customRef: customRef,
10794 triggerRef: triggerRef,
10795 shallowRef: shallowRef,
10796 shallowReactive: shallowReactive,
10797 shallowReadonly: shallowReadonly,
10798 markRaw: markRaw,
10799 toRaw: toRaw,
10800 effect: effect,
10801 stop: stop,
10802 ReactiveEffect: ReactiveEffect,
10803 effectScope: effectScope,
10804 EffectScope: EffectScope,
10805 getCurrentScope: getCurrentScope,
10806 onScopeDispose: onScopeDispose,
10807 computed: computed$1,
10808 watch: watch,
10809 watchEffect: watchEffect,
10810 watchPostEffect: watchPostEffect,
10811 watchSyncEffect: watchSyncEffect,
10812 onBeforeMount: onBeforeMount,
10813 onMounted: onMounted,
10814 onBeforeUpdate: onBeforeUpdate,
10815 onUpdated: onUpdated,
10816 onBeforeUnmount: onBeforeUnmount,
10817 onUnmounted: onUnmounted,
10818 onActivated: onActivated,
10819 onDeactivated: onDeactivated,
10820 onRenderTracked: onRenderTracked,
10821 onRenderTriggered: onRenderTriggered,
10822 onErrorCaptured: onErrorCaptured,
10823 onServerPrefetch: onServerPrefetch,
10824 provide: provide,
10825 inject: inject,
10826 nextTick: nextTick,
10827 defineComponent: defineComponent,
10828 defineAsyncComponent: defineAsyncComponent,
10829 useAttrs: useAttrs,
10830 useSlots: useSlots,
10831 defineProps: defineProps,
10832 defineEmits: defineEmits,
10833 defineExpose: defineExpose,
10834 withDefaults: withDefaults,
10835 mergeDefaults: mergeDefaults,
10836 createPropsRestProxy: createPropsRestProxy,
10837 withAsyncContext: withAsyncContext,
10838 getCurrentInstance: getCurrentInstance,
10839 h: h,
10840 createVNode: createVNode,
10841 cloneVNode: cloneVNode,
10842 mergeProps: mergeProps,
10843 isVNode: isVNode,
10844 Fragment: Fragment,
10845 Text: Text,
10846 Comment: Comment,
10847 Static: Static,
10848 Teleport: Teleport,
10849 Suspense: Suspense,
10850 KeepAlive: KeepAlive,
10851 BaseTransition: BaseTransition,
10852 withDirectives: withDirectives,
10853 useSSRContext: useSSRContext,
10854 ssrContextKey: ssrContextKey,
10855 createRenderer: createRenderer,
10856 createHydrationRenderer: createHydrationRenderer,
10857 queuePostFlushCb: queuePostFlushCb,
10858 warn: warn$1,
10859 handleError: handleError,
10860 callWithErrorHandling: callWithErrorHandling,
10861 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
10862 resolveComponent: resolveComponent,
10863 resolveDirective: resolveDirective,
10864 resolveDynamicComponent: resolveDynamicComponent,
10865 registerRuntimeCompiler: registerRuntimeCompiler,
10866 isRuntimeOnly: isRuntimeOnly,
10867 useTransitionState: useTransitionState,
10868 resolveTransitionHooks: resolveTransitionHooks,
10869 setTransitionHooks: setTransitionHooks,
10870 getTransitionRawChildren: getTransitionRawChildren,
10871 initCustomFormatter: initCustomFormatter,
10872 get devtools () { return devtools; },
10873 setDevtoolsHook: setDevtoolsHook,
10874 withCtx: withCtx,
10875 pushScopeId: pushScopeId,
10876 popScopeId: popScopeId,
10877 withScopeId: withScopeId,
10878 renderList: renderList,
10879 toHandlers: toHandlers,
10880 renderSlot: renderSlot,
10881 createSlots: createSlots,
10882 withMemo: withMemo,
10883 isMemoSame: isMemoSame,
10884 openBlock: openBlock,
10885 createBlock: createBlock,
10886 setBlockTracking: setBlockTracking,
10887 createTextVNode: createTextVNode,
10888 createCommentVNode: createCommentVNode,
10889 createStaticVNode: createStaticVNode,
10890 createElementVNode: createBaseVNode,
10891 createElementBlock: createElementBlock,
10892 guardReactiveProps: guardReactiveProps,
10893 toDisplayString: toDisplayString,
10894 camelize: camelize,
10895 capitalize: capitalize,
10896 toHandlerKey: toHandlerKey,
10897 normalizeProps: normalizeProps,
10898 normalizeClass: normalizeClass,
10899 normalizeStyle: normalizeStyle,
10900 transformVNodeArgs: transformVNodeArgs,
10901 version: version,
10902 ssrUtils: ssrUtils,
10903 resolveFilter: resolveFilter,
10904 compatUtils: compatUtils
10905});
10906
10907function initDev() {
10908 {
10909 {
10910 console.info(`You are running a development build of Vue.\n` +
10911 `Make sure to use the production build (*.prod.js) when deploying for production.`);
10912 }
10913 initCustomFormatter();
10914 }
10915}
10916
10917function defaultOnError(error) {
10918 throw error;
10919}
10920function defaultOnWarn(msg) {
10921 console.warn(`[Vue warn] ${msg.message}`);
10922}
10923function createCompilerError(code, loc, messages, additionalMessage) {
10924 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
10925 ;
10926 const error = new SyntaxError(String(msg));
10927 error.code = code;
10928 error.loc = loc;
10929 return error;
10930}
10931const errorMessages = {
10932 // parse errors
10933 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
10934 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
10935 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
10936 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
10937 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
10938 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
10939 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
10940 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
10941 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
10942 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
10943 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
10944 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
10945 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
10946 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
10947 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
10948 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
10949 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
10950 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
10951 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
10952 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
10953 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
10954 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
10955 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
10956 // Vue-specific parse errors
10957 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
10958 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
10959 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
10960 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
10961 'Note that dynamic directive argument cannot contain spaces.',
10962 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
10963 // transform errors
10964 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
10965 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
10966 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
10967 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
10968 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
10969 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
10970 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
10971 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
10972 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
10973 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
10974 `When there are multiple named slots, all slots should use <template> ` +
10975 `syntax to avoid scope ambiguity.`,
10976 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
10977 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
10978 `default slot. These children will be ignored.`,
10979 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
10980 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
10981 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
10982 [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.`,
10983 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
10984 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
10985 // generic errors
10986 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
10987 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
10988 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
10989 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
10990 // just to fulfill types
10991 [50 /* __EXTEND_POINT__ */]: ``
10992};
10993
10994const FRAGMENT = Symbol(`Fragment` );
10995const TELEPORT = Symbol(`Teleport` );
10996const SUSPENSE = Symbol(`Suspense` );
10997const KEEP_ALIVE = Symbol(`KeepAlive` );
10998const BASE_TRANSITION = Symbol(`BaseTransition` );
10999const OPEN_BLOCK = Symbol(`openBlock` );
11000const CREATE_BLOCK = Symbol(`createBlock` );
11001const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11002const CREATE_VNODE = Symbol(`createVNode` );
11003const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11004const CREATE_COMMENT = Symbol(`createCommentVNode` );
11005const CREATE_TEXT = Symbol(`createTextVNode` );
11006const CREATE_STATIC = Symbol(`createStaticVNode` );
11007const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11008const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11009const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11010const RESOLVE_FILTER = Symbol(`resolveFilter` );
11011const WITH_DIRECTIVES = Symbol(`withDirectives` );
11012const RENDER_LIST = Symbol(`renderList` );
11013const RENDER_SLOT = Symbol(`renderSlot` );
11014const CREATE_SLOTS = Symbol(`createSlots` );
11015const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11016const MERGE_PROPS = Symbol(`mergeProps` );
11017const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11018const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11019const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11020const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11021const TO_HANDLERS = Symbol(`toHandlers` );
11022const CAMELIZE = Symbol(`camelize` );
11023const CAPITALIZE = Symbol(`capitalize` );
11024const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11025const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11026const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11027const POP_SCOPE_ID = Symbol(`popScopeId` );
11028const WITH_CTX = Symbol(`withCtx` );
11029const UNREF = Symbol(`unref` );
11030const IS_REF = Symbol(`isRef` );
11031const WITH_MEMO = Symbol(`withMemo` );
11032const IS_MEMO_SAME = Symbol(`isMemoSame` );
11033// Name mapping for runtime helpers that need to be imported from 'vue' in
11034// generated code. Make sure these are correctly exported in the runtime!
11035// Using `any` here because TS doesn't allow symbols as index type.
11036const helperNameMap = {
11037 [FRAGMENT]: `Fragment`,
11038 [TELEPORT]: `Teleport`,
11039 [SUSPENSE]: `Suspense`,
11040 [KEEP_ALIVE]: `KeepAlive`,
11041 [BASE_TRANSITION]: `BaseTransition`,
11042 [OPEN_BLOCK]: `openBlock`,
11043 [CREATE_BLOCK]: `createBlock`,
11044 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11045 [CREATE_VNODE]: `createVNode`,
11046 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11047 [CREATE_COMMENT]: `createCommentVNode`,
11048 [CREATE_TEXT]: `createTextVNode`,
11049 [CREATE_STATIC]: `createStaticVNode`,
11050 [RESOLVE_COMPONENT]: `resolveComponent`,
11051 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11052 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11053 [RESOLVE_FILTER]: `resolveFilter`,
11054 [WITH_DIRECTIVES]: `withDirectives`,
11055 [RENDER_LIST]: `renderList`,
11056 [RENDER_SLOT]: `renderSlot`,
11057 [CREATE_SLOTS]: `createSlots`,
11058 [TO_DISPLAY_STRING]: `toDisplayString`,
11059 [MERGE_PROPS]: `mergeProps`,
11060 [NORMALIZE_CLASS]: `normalizeClass`,
11061 [NORMALIZE_STYLE]: `normalizeStyle`,
11062 [NORMALIZE_PROPS]: `normalizeProps`,
11063 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11064 [TO_HANDLERS]: `toHandlers`,
11065 [CAMELIZE]: `camelize`,
11066 [CAPITALIZE]: `capitalize`,
11067 [TO_HANDLER_KEY]: `toHandlerKey`,
11068 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11069 [PUSH_SCOPE_ID]: `pushScopeId`,
11070 [POP_SCOPE_ID]: `popScopeId`,
11071 [WITH_CTX]: `withCtx`,
11072 [UNREF]: `unref`,
11073 [IS_REF]: `isRef`,
11074 [WITH_MEMO]: `withMemo`,
11075 [IS_MEMO_SAME]: `isMemoSame`
11076};
11077function registerRuntimeHelpers(helpers) {
11078 Object.getOwnPropertySymbols(helpers).forEach(s => {
11079 helperNameMap[s] = helpers[s];
11080 });
11081}
11082
11083// AST Utilities ---------------------------------------------------------------
11084// Some expressions, e.g. sequence and conditional expressions, are never
11085// associated with template nodes, so their source locations are just a stub.
11086// Container types like CompoundExpression also don't need a real location.
11087const locStub = {
11088 source: '',
11089 start: { line: 1, column: 1, offset: 0 },
11090 end: { line: 1, column: 1, offset: 0 }
11091};
11092function createRoot(children, loc = locStub) {
11093 return {
11094 type: 0 /* ROOT */,
11095 children,
11096 helpers: [],
11097 components: [],
11098 directives: [],
11099 hoists: [],
11100 imports: [],
11101 cached: 0,
11102 temps: 0,
11103 codegenNode: undefined,
11104 loc
11105 };
11106}
11107function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11108 if (context) {
11109 if (isBlock) {
11110 context.helper(OPEN_BLOCK);
11111 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11112 }
11113 else {
11114 context.helper(getVNodeHelper(context.inSSR, isComponent));
11115 }
11116 if (directives) {
11117 context.helper(WITH_DIRECTIVES);
11118 }
11119 }
11120 return {
11121 type: 13 /* VNODE_CALL */,
11122 tag,
11123 props,
11124 children,
11125 patchFlag,
11126 dynamicProps,
11127 directives,
11128 isBlock,
11129 disableTracking,
11130 isComponent,
11131 loc
11132 };
11133}
11134function createArrayExpression(elements, loc = locStub) {
11135 return {
11136 type: 17 /* JS_ARRAY_EXPRESSION */,
11137 loc,
11138 elements
11139 };
11140}
11141function createObjectExpression(properties, loc = locStub) {
11142 return {
11143 type: 15 /* JS_OBJECT_EXPRESSION */,
11144 loc,
11145 properties
11146 };
11147}
11148function createObjectProperty(key, value) {
11149 return {
11150 type: 16 /* JS_PROPERTY */,
11151 loc: locStub,
11152 key: isString(key) ? createSimpleExpression(key, true) : key,
11153 value
11154 };
11155}
11156function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11157 return {
11158 type: 4 /* SIMPLE_EXPRESSION */,
11159 loc,
11160 content,
11161 isStatic,
11162 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11163 };
11164}
11165function createCompoundExpression(children, loc = locStub) {
11166 return {
11167 type: 8 /* COMPOUND_EXPRESSION */,
11168 loc,
11169 children
11170 };
11171}
11172function createCallExpression(callee, args = [], loc = locStub) {
11173 return {
11174 type: 14 /* JS_CALL_EXPRESSION */,
11175 loc,
11176 callee,
11177 arguments: args
11178 };
11179}
11180function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11181 return {
11182 type: 18 /* JS_FUNCTION_EXPRESSION */,
11183 params,
11184 returns,
11185 newline,
11186 isSlot,
11187 loc
11188 };
11189}
11190function createConditionalExpression(test, consequent, alternate, newline = true) {
11191 return {
11192 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11193 test,
11194 consequent,
11195 alternate,
11196 newline,
11197 loc: locStub
11198 };
11199}
11200function createCacheExpression(index, value, isVNode = false) {
11201 return {
11202 type: 20 /* JS_CACHE_EXPRESSION */,
11203 index,
11204 value,
11205 isVNode,
11206 loc: locStub
11207 };
11208}
11209function createBlockStatement(body) {
11210 return {
11211 type: 21 /* JS_BLOCK_STATEMENT */,
11212 body,
11213 loc: locStub
11214 };
11215}
11216
11217const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11218const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11219function isCoreComponent(tag) {
11220 if (isBuiltInType(tag, 'Teleport')) {
11221 return TELEPORT;
11222 }
11223 else if (isBuiltInType(tag, 'Suspense')) {
11224 return SUSPENSE;
11225 }
11226 else if (isBuiltInType(tag, 'KeepAlive')) {
11227 return KEEP_ALIVE;
11228 }
11229 else if (isBuiltInType(tag, 'BaseTransition')) {
11230 return BASE_TRANSITION;
11231 }
11232}
11233const nonIdentifierRE = /^\d|[^\$\w]/;
11234const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11235const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11236const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11237const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11238/**
11239 * Simple lexer to check if an expression is a member expression. This is
11240 * lax and only checks validity at the root level (i.e. does not validate exps
11241 * inside square brackets), but it's ok since these are only used on template
11242 * expressions and false positives are invalid expressions in the first place.
11243 */
11244const isMemberExpressionBrowser = (path) => {
11245 // remove whitespaces around . or [ first
11246 path = path.trim().replace(whitespaceRE, s => s.trim());
11247 let state = 0 /* inMemberExp */;
11248 let stateStack = [];
11249 let currentOpenBracketCount = 0;
11250 let currentOpenParensCount = 0;
11251 let currentStringType = null;
11252 for (let i = 0; i < path.length; i++) {
11253 const char = path.charAt(i);
11254 switch (state) {
11255 case 0 /* inMemberExp */:
11256 if (char === '[') {
11257 stateStack.push(state);
11258 state = 1 /* inBrackets */;
11259 currentOpenBracketCount++;
11260 }
11261 else if (char === '(') {
11262 stateStack.push(state);
11263 state = 2 /* inParens */;
11264 currentOpenParensCount++;
11265 }
11266 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11267 return false;
11268 }
11269 break;
11270 case 1 /* inBrackets */:
11271 if (char === `'` || char === `"` || char === '`') {
11272 stateStack.push(state);
11273 state = 3 /* inString */;
11274 currentStringType = char;
11275 }
11276 else if (char === `[`) {
11277 currentOpenBracketCount++;
11278 }
11279 else if (char === `]`) {
11280 if (!--currentOpenBracketCount) {
11281 state = stateStack.pop();
11282 }
11283 }
11284 break;
11285 case 2 /* inParens */:
11286 if (char === `'` || char === `"` || char === '`') {
11287 stateStack.push(state);
11288 state = 3 /* inString */;
11289 currentStringType = char;
11290 }
11291 else if (char === `(`) {
11292 currentOpenParensCount++;
11293 }
11294 else if (char === `)`) {
11295 // if the exp ends as a call then it should not be considered valid
11296 if (i === path.length - 1) {
11297 return false;
11298 }
11299 if (!--currentOpenParensCount) {
11300 state = stateStack.pop();
11301 }
11302 }
11303 break;
11304 case 3 /* inString */:
11305 if (char === currentStringType) {
11306 state = stateStack.pop();
11307 currentStringType = null;
11308 }
11309 break;
11310 }
11311 }
11312 return !currentOpenBracketCount && !currentOpenParensCount;
11313};
11314const isMemberExpression = isMemberExpressionBrowser
11315 ;
11316function getInnerRange(loc, offset, length) {
11317 const source = loc.source.slice(offset, offset + length);
11318 const newLoc = {
11319 source,
11320 start: advancePositionWithClone(loc.start, loc.source, offset),
11321 end: loc.end
11322 };
11323 if (length != null) {
11324 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11325 }
11326 return newLoc;
11327}
11328function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11329 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11330}
11331// advance by mutation without cloning (for performance reasons), since this
11332// gets called a lot in the parser
11333function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11334 let linesCount = 0;
11335 let lastNewLinePos = -1;
11336 for (let i = 0; i < numberOfCharacters; i++) {
11337 if (source.charCodeAt(i) === 10 /* newline char code */) {
11338 linesCount++;
11339 lastNewLinePos = i;
11340 }
11341 }
11342 pos.offset += numberOfCharacters;
11343 pos.line += linesCount;
11344 pos.column =
11345 lastNewLinePos === -1
11346 ? pos.column + numberOfCharacters
11347 : numberOfCharacters - lastNewLinePos;
11348 return pos;
11349}
11350function assert(condition, msg) {
11351 /* istanbul ignore if */
11352 if (!condition) {
11353 throw new Error(msg || `unexpected compiler condition`);
11354 }
11355}
11356function findDir(node, name, allowEmpty = false) {
11357 for (let i = 0; i < node.props.length; i++) {
11358 const p = node.props[i];
11359 if (p.type === 7 /* DIRECTIVE */ &&
11360 (allowEmpty || p.exp) &&
11361 (isString(name) ? p.name === name : name.test(p.name))) {
11362 return p;
11363 }
11364 }
11365}
11366function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11367 for (let i = 0; i < node.props.length; i++) {
11368 const p = node.props[i];
11369 if (p.type === 6 /* ATTRIBUTE */) {
11370 if (dynamicOnly)
11371 continue;
11372 if (p.name === name && (p.value || allowEmpty)) {
11373 return p;
11374 }
11375 }
11376 else if (p.name === 'bind' &&
11377 (p.exp || allowEmpty) &&
11378 isStaticArgOf(p.arg, name)) {
11379 return p;
11380 }
11381 }
11382}
11383function isStaticArgOf(arg, name) {
11384 return !!(arg && isStaticExp(arg) && arg.content === name);
11385}
11386function hasDynamicKeyVBind(node) {
11387 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11388 p.name === 'bind' &&
11389 (!p.arg || // v-bind="obj"
11390 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11391 !p.arg.isStatic) // v-bind:[foo]
11392 );
11393}
11394function isText(node) {
11395 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11396}
11397function isVSlot(p) {
11398 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11399}
11400function isTemplateNode(node) {
11401 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11402}
11403function isSlotOutlet(node) {
11404 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11405}
11406function getVNodeHelper(ssr, isComponent) {
11407 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11408}
11409function getVNodeBlockHelper(ssr, isComponent) {
11410 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11411}
11412const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11413function getUnnormalizedProps(props, callPath = []) {
11414 if (props &&
11415 !isString(props) &&
11416 props.type === 14 /* JS_CALL_EXPRESSION */) {
11417 const callee = props.callee;
11418 if (!isString(callee) && propsHelperSet.has(callee)) {
11419 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11420 }
11421 }
11422 return [props, callPath];
11423}
11424function injectProp(node, prop, context) {
11425 let propsWithInjection;
11426 /**
11427 * 1. mergeProps(...)
11428 * 2. toHandlers(...)
11429 * 3. normalizeProps(...)
11430 * 4. normalizeProps(guardReactiveProps(...))
11431 *
11432 * we need to get the real props before normalization
11433 */
11434 let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11435 let callPath = [];
11436 let parentCall;
11437 if (props &&
11438 !isString(props) &&
11439 props.type === 14 /* JS_CALL_EXPRESSION */) {
11440 const ret = getUnnormalizedProps(props);
11441 props = ret[0];
11442 callPath = ret[1];
11443 parentCall = callPath[callPath.length - 1];
11444 }
11445 if (props == null || isString(props)) {
11446 propsWithInjection = createObjectExpression([prop]);
11447 }
11448 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11449 // merged props... add ours
11450 // only inject key to object literal if it's the first argument so that
11451 // if doesn't override user provided keys
11452 const first = props.arguments[0];
11453 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11454 first.properties.unshift(prop);
11455 }
11456 else {
11457 if (props.callee === TO_HANDLERS) {
11458 // #2366
11459 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11460 createObjectExpression([prop]),
11461 props
11462 ]);
11463 }
11464 else {
11465 props.arguments.unshift(createObjectExpression([prop]));
11466 }
11467 }
11468 !propsWithInjection && (propsWithInjection = props);
11469 }
11470 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11471 let alreadyExists = false;
11472 // check existing key to avoid overriding user provided keys
11473 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11474 const propKeyName = prop.key.content;
11475 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11476 p.key.content === propKeyName);
11477 }
11478 if (!alreadyExists) {
11479 props.properties.unshift(prop);
11480 }
11481 propsWithInjection = props;
11482 }
11483 else {
11484 // single v-bind with expression, return a merged replacement
11485 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11486 createObjectExpression([prop]),
11487 props
11488 ]);
11489 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11490 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11491 // the `guardReactiveProps` will no longer be needed
11492 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11493 parentCall = callPath[callPath.length - 2];
11494 }
11495 }
11496 if (node.type === 13 /* VNODE_CALL */) {
11497 if (parentCall) {
11498 parentCall.arguments[0] = propsWithInjection;
11499 }
11500 else {
11501 node.props = propsWithInjection;
11502 }
11503 }
11504 else {
11505 if (parentCall) {
11506 parentCall.arguments[0] = propsWithInjection;
11507 }
11508 else {
11509 node.arguments[2] = propsWithInjection;
11510 }
11511 }
11512}
11513function toValidAssetId(name, type) {
11514 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11515 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11516 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11517 })}`;
11518}
11519function getMemoedVNodeCall(node) {
11520 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11521 return node.arguments[1].returns;
11522 }
11523 else {
11524 return node;
11525 }
11526}
11527function makeBlock(node, { helper, removeHelper, inSSR }) {
11528 if (!node.isBlock) {
11529 node.isBlock = true;
11530 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11531 helper(OPEN_BLOCK);
11532 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11533 }
11534}
11535
11536const deprecationData = {
11537 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11538 message: `Platform-native elements with "is" prop will no longer be ` +
11539 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11540 `prefixed with "vue:".`,
11541 link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
11542 },
11543 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11544 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11545 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11546 `\`v-model:${key}\`.`,
11547 link: `https://v3.vuejs.org/guide/migration/v-model.html`
11548 },
11549 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11550 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11551 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11552 },
11553 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11554 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11555 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11556 `that appears before v-bind in the case of conflict. ` +
11557 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11558 `You can also suppress this warning if the usage is intended.`,
11559 link: `https://v3.vuejs.org/guide/migration/v-bind.html`
11560 },
11561 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11562 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11563 link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
11564 },
11565 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11566 message: `v-if / v-for precedence when used on the same element has changed ` +
11567 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11568 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11569 `with <template> tags or use a computed property that filters v-for ` +
11570 `data source.`,
11571 link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
11572 },
11573 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11574 message: `<template> with no special directives will render as a native template ` +
11575 `element instead of its inner content in Vue 3.`
11576 },
11577 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11578 message: `"inline-template" has been removed in Vue 3.`,
11579 link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
11580 },
11581 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11582 message: `filters have been removed in Vue 3. ` +
11583 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11584 `Use method calls or computed properties instead.`,
11585 link: `https://v3.vuejs.org/guide/migration/filters.html`
11586 }
11587};
11588function getCompatValue(key, context) {
11589 const config = context.options
11590 ? context.options.compatConfig
11591 : context.compatConfig;
11592 const value = config && config[key];
11593 if (key === 'MODE') {
11594 return value || 3; // compiler defaults to v3 behavior
11595 }
11596 else {
11597 return value;
11598 }
11599}
11600function isCompatEnabled(key, context) {
11601 const mode = getCompatValue('MODE', context);
11602 const value = getCompatValue(key, context);
11603 // in v3 mode, only enable if explicitly set to true
11604 // otherwise enable for any non-false value
11605 return mode === 3 ? value === true : value !== false;
11606}
11607function checkCompatEnabled(key, context, loc, ...args) {
11608 const enabled = isCompatEnabled(key, context);
11609 if (enabled) {
11610 warnDeprecation(key, context, loc, ...args);
11611 }
11612 return enabled;
11613}
11614function warnDeprecation(key, context, loc, ...args) {
11615 const val = getCompatValue(key, context);
11616 if (val === 'suppress-warning') {
11617 return;
11618 }
11619 const { message, link } = deprecationData[key];
11620 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11621 const err = new SyntaxError(msg);
11622 err.code = key;
11623 if (loc)
11624 err.loc = loc;
11625 context.onWarn(err);
11626}
11627
11628// The default decoder only provides escapes for characters reserved as part of
11629// the template syntax, and is only used if the custom renderer did not provide
11630// a platform-specific decoder.
11631const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11632const decodeMap = {
11633 gt: '>',
11634 lt: '<',
11635 amp: '&',
11636 apos: "'",
11637 quot: '"'
11638};
11639const defaultParserOptions = {
11640 delimiters: [`{{`, `}}`],
11641 getNamespace: () => 0 /* HTML */,
11642 getTextMode: () => 0 /* DATA */,
11643 isVoidTag: NO,
11644 isPreTag: NO,
11645 isCustomElement: NO,
11646 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11647 onError: defaultOnError,
11648 onWarn: defaultOnWarn,
11649 comments: true
11650};
11651function baseParse(content, options = {}) {
11652 const context = createParserContext(content, options);
11653 const start = getCursor(context);
11654 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11655}
11656function createParserContext(content, rawOptions) {
11657 const options = extend({}, defaultParserOptions);
11658 let key;
11659 for (key in rawOptions) {
11660 // @ts-ignore
11661 options[key] =
11662 rawOptions[key] === undefined
11663 ? defaultParserOptions[key]
11664 : rawOptions[key];
11665 }
11666 return {
11667 options,
11668 column: 1,
11669 line: 1,
11670 offset: 0,
11671 originalSource: content,
11672 source: content,
11673 inPre: false,
11674 inVPre: false,
11675 onWarn: options.onWarn
11676 };
11677}
11678function parseChildren(context, mode, ancestors) {
11679 const parent = last(ancestors);
11680 const ns = parent ? parent.ns : 0 /* HTML */;
11681 const nodes = [];
11682 while (!isEnd(context, mode, ancestors)) {
11683 const s = context.source;
11684 let node = undefined;
11685 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11686 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11687 // '{{'
11688 node = parseInterpolation(context, mode);
11689 }
11690 else if (mode === 0 /* DATA */ && s[0] === '<') {
11691 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11692 if (s.length === 1) {
11693 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11694 }
11695 else if (s[1] === '!') {
11696 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11697 if (startsWith(s, '<!--')) {
11698 node = parseComment(context);
11699 }
11700 else if (startsWith(s, '<!DOCTYPE')) {
11701 // Ignore DOCTYPE by a limitation.
11702 node = parseBogusComment(context);
11703 }
11704 else if (startsWith(s, '<![CDATA[')) {
11705 if (ns !== 0 /* HTML */) {
11706 node = parseCDATA(context, ancestors);
11707 }
11708 else {
11709 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11710 node = parseBogusComment(context);
11711 }
11712 }
11713 else {
11714 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11715 node = parseBogusComment(context);
11716 }
11717 }
11718 else if (s[1] === '/') {
11719 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11720 if (s.length === 2) {
11721 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11722 }
11723 else if (s[2] === '>') {
11724 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11725 advanceBy(context, 3);
11726 continue;
11727 }
11728 else if (/[a-z]/i.test(s[2])) {
11729 emitError(context, 23 /* X_INVALID_END_TAG */);
11730 parseTag(context, 1 /* End */, parent);
11731 continue;
11732 }
11733 else {
11734 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11735 node = parseBogusComment(context);
11736 }
11737 }
11738 else if (/[a-z]/i.test(s[1])) {
11739 node = parseElement(context, ancestors);
11740 }
11741 else if (s[1] === '?') {
11742 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11743 node = parseBogusComment(context);
11744 }
11745 else {
11746 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11747 }
11748 }
11749 }
11750 if (!node) {
11751 node = parseText(context, mode);
11752 }
11753 if (isArray(node)) {
11754 for (let i = 0; i < node.length; i++) {
11755 pushNode(nodes, node[i]);
11756 }
11757 }
11758 else {
11759 pushNode(nodes, node);
11760 }
11761 }
11762 // Whitespace handling strategy like v2
11763 let removedWhitespace = false;
11764 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11765 const shouldCondense = context.options.whitespace !== 'preserve';
11766 for (let i = 0; i < nodes.length; i++) {
11767 const node = nodes[i];
11768 if (!context.inPre && node.type === 2 /* TEXT */) {
11769 if (!/[^\t\r\n\f ]/.test(node.content)) {
11770 const prev = nodes[i - 1];
11771 const next = nodes[i + 1];
11772 // Remove if:
11773 // - the whitespace is the first or last node, or:
11774 // - (condense mode) the whitespace is adjacent to a comment, or:
11775 // - (condense mode) the whitespace is between two elements AND contains newline
11776 if (!prev ||
11777 !next ||
11778 (shouldCondense &&
11779 (prev.type === 3 /* COMMENT */ ||
11780 next.type === 3 /* COMMENT */ ||
11781 (prev.type === 1 /* ELEMENT */ &&
11782 next.type === 1 /* ELEMENT */ &&
11783 /[\r\n]/.test(node.content))))) {
11784 removedWhitespace = true;
11785 nodes[i] = null;
11786 }
11787 else {
11788 // Otherwise, the whitespace is condensed into a single space
11789 node.content = ' ';
11790 }
11791 }
11792 else if (shouldCondense) {
11793 // in condense mode, consecutive whitespaces in text are condensed
11794 // down to a single space.
11795 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11796 }
11797 }
11798 // Remove comment nodes if desired by configuration.
11799 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11800 removedWhitespace = true;
11801 nodes[i] = null;
11802 }
11803 }
11804 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11805 // remove leading newline per html spec
11806 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11807 const first = nodes[0];
11808 if (first && first.type === 2 /* TEXT */) {
11809 first.content = first.content.replace(/^\r?\n/, '');
11810 }
11811 }
11812 }
11813 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11814}
11815function pushNode(nodes, node) {
11816 if (node.type === 2 /* TEXT */) {
11817 const prev = last(nodes);
11818 // Merge if both this and the previous node are text and those are
11819 // consecutive. This happens for cases like "a < b".
11820 if (prev &&
11821 prev.type === 2 /* TEXT */ &&
11822 prev.loc.end.offset === node.loc.start.offset) {
11823 prev.content += node.content;
11824 prev.loc.end = node.loc.end;
11825 prev.loc.source += node.loc.source;
11826 return;
11827 }
11828 }
11829 nodes.push(node);
11830}
11831function parseCDATA(context, ancestors) {
11832 advanceBy(context, 9);
11833 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11834 if (context.source.length === 0) {
11835 emitError(context, 6 /* EOF_IN_CDATA */);
11836 }
11837 else {
11838 advanceBy(context, 3);
11839 }
11840 return nodes;
11841}
11842function parseComment(context) {
11843 const start = getCursor(context);
11844 let content;
11845 // Regular comment.
11846 const match = /--(\!)?>/.exec(context.source);
11847 if (!match) {
11848 content = context.source.slice(4);
11849 advanceBy(context, context.source.length);
11850 emitError(context, 7 /* EOF_IN_COMMENT */);
11851 }
11852 else {
11853 if (match.index <= 3) {
11854 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
11855 }
11856 if (match[1]) {
11857 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
11858 }
11859 content = context.source.slice(4, match.index);
11860 // Advancing with reporting nested comments.
11861 const s = context.source.slice(0, match.index);
11862 let prevIndex = 1, nestedIndex = 0;
11863 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
11864 advanceBy(context, nestedIndex - prevIndex + 1);
11865 if (nestedIndex + 4 < s.length) {
11866 emitError(context, 16 /* NESTED_COMMENT */);
11867 }
11868 prevIndex = nestedIndex + 1;
11869 }
11870 advanceBy(context, match.index + match[0].length - prevIndex + 1);
11871 }
11872 return {
11873 type: 3 /* COMMENT */,
11874 content,
11875 loc: getSelection(context, start)
11876 };
11877}
11878function parseBogusComment(context) {
11879 const start = getCursor(context);
11880 const contentStart = context.source[1] === '?' ? 1 : 2;
11881 let content;
11882 const closeIndex = context.source.indexOf('>');
11883 if (closeIndex === -1) {
11884 content = context.source.slice(contentStart);
11885 advanceBy(context, context.source.length);
11886 }
11887 else {
11888 content = context.source.slice(contentStart, closeIndex);
11889 advanceBy(context, closeIndex + 1);
11890 }
11891 return {
11892 type: 3 /* COMMENT */,
11893 content,
11894 loc: getSelection(context, start)
11895 };
11896}
11897function parseElement(context, ancestors) {
11898 // Start tag.
11899 const wasInPre = context.inPre;
11900 const wasInVPre = context.inVPre;
11901 const parent = last(ancestors);
11902 const element = parseTag(context, 0 /* Start */, parent);
11903 const isPreBoundary = context.inPre && !wasInPre;
11904 const isVPreBoundary = context.inVPre && !wasInVPre;
11905 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
11906 // #4030 self-closing <pre> tag
11907 if (isPreBoundary) {
11908 context.inPre = false;
11909 }
11910 if (isVPreBoundary) {
11911 context.inVPre = false;
11912 }
11913 return element;
11914 }
11915 // Children.
11916 ancestors.push(element);
11917 const mode = context.options.getTextMode(element, parent);
11918 const children = parseChildren(context, mode, ancestors);
11919 ancestors.pop();
11920 element.children = children;
11921 // End tag.
11922 if (startsWithEndTagOpen(context.source, element.tag)) {
11923 parseTag(context, 1 /* End */, parent);
11924 }
11925 else {
11926 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
11927 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
11928 const first = children[0];
11929 if (first && startsWith(first.loc.source, '<!--')) {
11930 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
11931 }
11932 }
11933 }
11934 element.loc = getSelection(context, element.loc.start);
11935 if (isPreBoundary) {
11936 context.inPre = false;
11937 }
11938 if (isVPreBoundary) {
11939 context.inVPre = false;
11940 }
11941 return element;
11942}
11943const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
11944function parseTag(context, type, parent) {
11945 // Tag open.
11946 const start = getCursor(context);
11947 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
11948 const tag = match[1];
11949 const ns = context.options.getNamespace(tag, parent);
11950 advanceBy(context, match[0].length);
11951 advanceSpaces(context);
11952 // save current state in case we need to re-parse attributes with v-pre
11953 const cursor = getCursor(context);
11954 const currentSource = context.source;
11955 // check <pre> tag
11956 if (context.options.isPreTag(tag)) {
11957 context.inPre = true;
11958 }
11959 // Attributes.
11960 let props = parseAttributes(context, type);
11961 // check v-pre
11962 if (type === 0 /* Start */ &&
11963 !context.inVPre &&
11964 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
11965 context.inVPre = true;
11966 // reset context
11967 extend(context, cursor);
11968 context.source = currentSource;
11969 // re-parse attrs and filter out v-pre itself
11970 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
11971 }
11972 // Tag close.
11973 let isSelfClosing = false;
11974 if (context.source.length === 0) {
11975 emitError(context, 9 /* EOF_IN_TAG */);
11976 }
11977 else {
11978 isSelfClosing = startsWith(context.source, '/>');
11979 if (type === 1 /* End */ && isSelfClosing) {
11980 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
11981 }
11982 advanceBy(context, isSelfClosing ? 2 : 1);
11983 }
11984 if (type === 1 /* End */) {
11985 return;
11986 }
11987 let tagType = 0 /* ELEMENT */;
11988 if (!context.inVPre) {
11989 if (tag === 'slot') {
11990 tagType = 2 /* SLOT */;
11991 }
11992 else if (tag === 'template') {
11993 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
11994 tagType = 3 /* TEMPLATE */;
11995 }
11996 }
11997 else if (isComponent(tag, props, context)) {
11998 tagType = 1 /* COMPONENT */;
11999 }
12000 }
12001 return {
12002 type: 1 /* ELEMENT */,
12003 ns,
12004 tag,
12005 tagType,
12006 props,
12007 isSelfClosing,
12008 children: [],
12009 loc: getSelection(context, start),
12010 codegenNode: undefined // to be created during transform phase
12011 };
12012}
12013function isComponent(tag, props, context) {
12014 const options = context.options;
12015 if (options.isCustomElement(tag)) {
12016 return false;
12017 }
12018 if (tag === 'component' ||
12019 /^[A-Z]/.test(tag) ||
12020 isCoreComponent(tag) ||
12021 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12022 (options.isNativeTag && !options.isNativeTag(tag))) {
12023 return true;
12024 }
12025 // at this point the tag should be a native tag, but check for potential "is"
12026 // casting
12027 for (let i = 0; i < props.length; i++) {
12028 const p = props[i];
12029 if (p.type === 6 /* ATTRIBUTE */) {
12030 if (p.name === 'is' && p.value) {
12031 if (p.value.content.startsWith('vue:')) {
12032 return true;
12033 }
12034 }
12035 }
12036 else {
12037 // directive
12038 // v-is (TODO Deprecate)
12039 if (p.name === 'is') {
12040 return true;
12041 }
12042 else if (
12043 // :is on plain element - only treat as component in compat mode
12044 p.name === 'bind' &&
12045 isStaticArgOf(p.arg, 'is') &&
12046 false &&
12047 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12048 return true;
12049 }
12050 }
12051 }
12052}
12053function parseAttributes(context, type) {
12054 const props = [];
12055 const attributeNames = new Set();
12056 while (context.source.length > 0 &&
12057 !startsWith(context.source, '>') &&
12058 !startsWith(context.source, '/>')) {
12059 if (startsWith(context.source, '/')) {
12060 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12061 advanceBy(context, 1);
12062 advanceSpaces(context);
12063 continue;
12064 }
12065 if (type === 1 /* End */) {
12066 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12067 }
12068 const attr = parseAttribute(context, attributeNames);
12069 // Trim whitespace between class
12070 // https://github.com/vuejs/core/issues/4251
12071 if (attr.type === 6 /* ATTRIBUTE */ &&
12072 attr.value &&
12073 attr.name === 'class') {
12074 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12075 }
12076 if (type === 0 /* Start */) {
12077 props.push(attr);
12078 }
12079 if (/^[^\t\r\n\f />]/.test(context.source)) {
12080 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12081 }
12082 advanceSpaces(context);
12083 }
12084 return props;
12085}
12086function parseAttribute(context, nameSet) {
12087 // Name.
12088 const start = getCursor(context);
12089 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12090 const name = match[0];
12091 if (nameSet.has(name)) {
12092 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12093 }
12094 nameSet.add(name);
12095 if (name[0] === '=') {
12096 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12097 }
12098 {
12099 const pattern = /["'<]/g;
12100 let m;
12101 while ((m = pattern.exec(name))) {
12102 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12103 }
12104 }
12105 advanceBy(context, name.length);
12106 // Value
12107 let value = undefined;
12108 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12109 advanceSpaces(context);
12110 advanceBy(context, 1);
12111 advanceSpaces(context);
12112 value = parseAttributeValue(context);
12113 if (!value) {
12114 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12115 }
12116 }
12117 const loc = getSelection(context, start);
12118 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12119 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12120 let isPropShorthand = startsWith(name, '.');
12121 let dirName = match[1] ||
12122 (isPropShorthand || startsWith(name, ':')
12123 ? 'bind'
12124 : startsWith(name, '@')
12125 ? 'on'
12126 : 'slot');
12127 let arg;
12128 if (match[2]) {
12129 const isSlot = dirName === 'slot';
12130 const startOffset = name.lastIndexOf(match[2]);
12131 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12132 let content = match[2];
12133 let isStatic = true;
12134 if (content.startsWith('[')) {
12135 isStatic = false;
12136 if (!content.endsWith(']')) {
12137 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12138 content = content.slice(1);
12139 }
12140 else {
12141 content = content.slice(1, content.length - 1);
12142 }
12143 }
12144 else if (isSlot) {
12145 // #1241 special case for v-slot: vuetify relies extensively on slot
12146 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12147 // supports such usage so we are keeping it consistent with 2.x.
12148 content += match[3] || '';
12149 }
12150 arg = {
12151 type: 4 /* SIMPLE_EXPRESSION */,
12152 content,
12153 isStatic,
12154 constType: isStatic
12155 ? 3 /* CAN_STRINGIFY */
12156 : 0 /* NOT_CONSTANT */,
12157 loc
12158 };
12159 }
12160 if (value && value.isQuoted) {
12161 const valueLoc = value.loc;
12162 valueLoc.start.offset++;
12163 valueLoc.start.column++;
12164 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12165 valueLoc.source = valueLoc.source.slice(1, -1);
12166 }
12167 const modifiers = match[3] ? match[3].slice(1).split('.') : [];
12168 if (isPropShorthand)
12169 modifiers.push('prop');
12170 return {
12171 type: 7 /* DIRECTIVE */,
12172 name: dirName,
12173 exp: value && {
12174 type: 4 /* SIMPLE_EXPRESSION */,
12175 content: value.content,
12176 isStatic: false,
12177 // Treat as non-constant by default. This can be potentially set to
12178 // other values by `transformExpression` to make it eligible for hoisting.
12179 constType: 0 /* NOT_CONSTANT */,
12180 loc: value.loc
12181 },
12182 arg,
12183 modifiers,
12184 loc
12185 };
12186 }
12187 // missing directive name or illegal directive name
12188 if (!context.inVPre && startsWith(name, 'v-')) {
12189 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12190 }
12191 return {
12192 type: 6 /* ATTRIBUTE */,
12193 name,
12194 value: value && {
12195 type: 2 /* TEXT */,
12196 content: value.content,
12197 loc: value.loc
12198 },
12199 loc
12200 };
12201}
12202function parseAttributeValue(context) {
12203 const start = getCursor(context);
12204 let content;
12205 const quote = context.source[0];
12206 const isQuoted = quote === `"` || quote === `'`;
12207 if (isQuoted) {
12208 // Quoted value.
12209 advanceBy(context, 1);
12210 const endIndex = context.source.indexOf(quote);
12211 if (endIndex === -1) {
12212 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12213 }
12214 else {
12215 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12216 advanceBy(context, 1);
12217 }
12218 }
12219 else {
12220 // Unquoted
12221 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12222 if (!match) {
12223 return undefined;
12224 }
12225 const unexpectedChars = /["'<=`]/g;
12226 let m;
12227 while ((m = unexpectedChars.exec(match[0]))) {
12228 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12229 }
12230 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12231 }
12232 return { content, isQuoted, loc: getSelection(context, start) };
12233}
12234function parseInterpolation(context, mode) {
12235 const [open, close] = context.options.delimiters;
12236 const closeIndex = context.source.indexOf(close, open.length);
12237 if (closeIndex === -1) {
12238 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12239 return undefined;
12240 }
12241 const start = getCursor(context);
12242 advanceBy(context, open.length);
12243 const innerStart = getCursor(context);
12244 const innerEnd = getCursor(context);
12245 const rawContentLength = closeIndex - open.length;
12246 const rawContent = context.source.slice(0, rawContentLength);
12247 const preTrimContent = parseTextData(context, rawContentLength, mode);
12248 const content = preTrimContent.trim();
12249 const startOffset = preTrimContent.indexOf(content);
12250 if (startOffset > 0) {
12251 advancePositionWithMutation(innerStart, rawContent, startOffset);
12252 }
12253 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12254 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12255 advanceBy(context, close.length);
12256 return {
12257 type: 5 /* INTERPOLATION */,
12258 content: {
12259 type: 4 /* SIMPLE_EXPRESSION */,
12260 isStatic: false,
12261 // Set `isConstant` to false by default and will decide in transformExpression
12262 constType: 0 /* NOT_CONSTANT */,
12263 content,
12264 loc: getSelection(context, innerStart, innerEnd)
12265 },
12266 loc: getSelection(context, start)
12267 };
12268}
12269function parseText(context, mode) {
12270 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12271 let endIndex = context.source.length;
12272 for (let i = 0; i < endTokens.length; i++) {
12273 const index = context.source.indexOf(endTokens[i], 1);
12274 if (index !== -1 && endIndex > index) {
12275 endIndex = index;
12276 }
12277 }
12278 const start = getCursor(context);
12279 const content = parseTextData(context, endIndex, mode);
12280 return {
12281 type: 2 /* TEXT */,
12282 content,
12283 loc: getSelection(context, start)
12284 };
12285}
12286/**
12287 * Get text data with a given length from the current location.
12288 * This translates HTML entities in the text data.
12289 */
12290function parseTextData(context, length, mode) {
12291 const rawText = context.source.slice(0, length);
12292 advanceBy(context, length);
12293 if (mode === 2 /* RAWTEXT */ ||
12294 mode === 3 /* CDATA */ ||
12295 !rawText.includes('&')) {
12296 return rawText;
12297 }
12298 else {
12299 // DATA or RCDATA containing "&"". Entity decoding required.
12300 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12301 }
12302}
12303function getCursor(context) {
12304 const { column, line, offset } = context;
12305 return { column, line, offset };
12306}
12307function getSelection(context, start, end) {
12308 end = end || getCursor(context);
12309 return {
12310 start,
12311 end,
12312 source: context.originalSource.slice(start.offset, end.offset)
12313 };
12314}
12315function last(xs) {
12316 return xs[xs.length - 1];
12317}
12318function startsWith(source, searchString) {
12319 return source.startsWith(searchString);
12320}
12321function advanceBy(context, numberOfCharacters) {
12322 const { source } = context;
12323 advancePositionWithMutation(context, source, numberOfCharacters);
12324 context.source = source.slice(numberOfCharacters);
12325}
12326function advanceSpaces(context) {
12327 const match = /^[\t\r\n\f ]+/.exec(context.source);
12328 if (match) {
12329 advanceBy(context, match[0].length);
12330 }
12331}
12332function getNewPosition(context, start, numberOfCharacters) {
12333 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12334}
12335function emitError(context, code, offset, loc = getCursor(context)) {
12336 if (offset) {
12337 loc.offset += offset;
12338 loc.column += offset;
12339 }
12340 context.options.onError(createCompilerError(code, {
12341 start: loc,
12342 end: loc,
12343 source: ''
12344 }));
12345}
12346function isEnd(context, mode, ancestors) {
12347 const s = context.source;
12348 switch (mode) {
12349 case 0 /* DATA */:
12350 if (startsWith(s, '</')) {
12351 // TODO: probably bad performance
12352 for (let i = ancestors.length - 1; i >= 0; --i) {
12353 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12354 return true;
12355 }
12356 }
12357 }
12358 break;
12359 case 1 /* RCDATA */:
12360 case 2 /* RAWTEXT */: {
12361 const parent = last(ancestors);
12362 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12363 return true;
12364 }
12365 break;
12366 }
12367 case 3 /* CDATA */:
12368 if (startsWith(s, ']]>')) {
12369 return true;
12370 }
12371 break;
12372 }
12373 return !s;
12374}
12375function startsWithEndTagOpen(source, tag) {
12376 return (startsWith(source, '</') &&
12377 source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
12378 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12379}
12380
12381function hoistStatic(root, context) {
12382 walk(root, context,
12383 // Root node is unfortunately non-hoistable due to potential parent
12384 // fallthrough attributes.
12385 isSingleElementRoot(root, root.children[0]));
12386}
12387function isSingleElementRoot(root, child) {
12388 const { children } = root;
12389 return (children.length === 1 &&
12390 child.type === 1 /* ELEMENT */ &&
12391 !isSlotOutlet(child));
12392}
12393function walk(node, context, doNotHoistNode = false) {
12394 const { children } = node;
12395 const originalCount = children.length;
12396 let hoistedCount = 0;
12397 for (let i = 0; i < children.length; i++) {
12398 const child = children[i];
12399 // only plain elements & text calls are eligible for hoisting.
12400 if (child.type === 1 /* ELEMENT */ &&
12401 child.tagType === 0 /* ELEMENT */) {
12402 const constantType = doNotHoistNode
12403 ? 0 /* NOT_CONSTANT */
12404 : getConstantType(child, context);
12405 if (constantType > 0 /* NOT_CONSTANT */) {
12406 if (constantType >= 2 /* CAN_HOIST */) {
12407 child.codegenNode.patchFlag =
12408 -1 /* HOISTED */ + (` /* HOISTED */` );
12409 child.codegenNode = context.hoist(child.codegenNode);
12410 hoistedCount++;
12411 continue;
12412 }
12413 }
12414 else {
12415 // node may contain dynamic children, but its props may be eligible for
12416 // hoisting.
12417 const codegenNode = child.codegenNode;
12418 if (codegenNode.type === 13 /* VNODE_CALL */) {
12419 const flag = getPatchFlag(codegenNode);
12420 if ((!flag ||
12421 flag === 512 /* NEED_PATCH */ ||
12422 flag === 1 /* TEXT */) &&
12423 getGeneratedPropsConstantType(child, context) >=
12424 2 /* CAN_HOIST */) {
12425 const props = getNodeProps(child);
12426 if (props) {
12427 codegenNode.props = context.hoist(props);
12428 }
12429 }
12430 if (codegenNode.dynamicProps) {
12431 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12432 }
12433 }
12434 }
12435 }
12436 else if (child.type === 12 /* TEXT_CALL */ &&
12437 getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
12438 child.codegenNode = context.hoist(child.codegenNode);
12439 hoistedCount++;
12440 }
12441 // walk further
12442 if (child.type === 1 /* ELEMENT */) {
12443 const isComponent = child.tagType === 1 /* COMPONENT */;
12444 if (isComponent) {
12445 context.scopes.vSlot++;
12446 }
12447 walk(child, context);
12448 if (isComponent) {
12449 context.scopes.vSlot--;
12450 }
12451 }
12452 else if (child.type === 11 /* FOR */) {
12453 // Do not hoist v-for single child because it has to be a block
12454 walk(child, context, child.children.length === 1);
12455 }
12456 else if (child.type === 9 /* IF */) {
12457 for (let i = 0; i < child.branches.length; i++) {
12458 // Do not hoist v-if single child because it has to be a block
12459 walk(child.branches[i], context, child.branches[i].children.length === 1);
12460 }
12461 }
12462 }
12463 if (hoistedCount && context.transformHoist) {
12464 context.transformHoist(children, context, node);
12465 }
12466 // all children were hoisted - the entire children array is hoistable.
12467 if (hoistedCount &&
12468 hoistedCount === originalCount &&
12469 node.type === 1 /* ELEMENT */ &&
12470 node.tagType === 0 /* ELEMENT */ &&
12471 node.codegenNode &&
12472 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12473 isArray(node.codegenNode.children)) {
12474 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12475 }
12476}
12477function getConstantType(node, context) {
12478 const { constantCache } = context;
12479 switch (node.type) {
12480 case 1 /* ELEMENT */:
12481 if (node.tagType !== 0 /* ELEMENT */) {
12482 return 0 /* NOT_CONSTANT */;
12483 }
12484 const cached = constantCache.get(node);
12485 if (cached !== undefined) {
12486 return cached;
12487 }
12488 const codegenNode = node.codegenNode;
12489 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12490 return 0 /* NOT_CONSTANT */;
12491 }
12492 if (codegenNode.isBlock &&
12493 node.tag !== 'svg' &&
12494 node.tag !== 'foreignObject') {
12495 return 0 /* NOT_CONSTANT */;
12496 }
12497 const flag = getPatchFlag(codegenNode);
12498 if (!flag) {
12499 let returnType = 3 /* CAN_STRINGIFY */;
12500 // Element itself has no patch flag. However we still need to check:
12501 // 1. Even for a node with no patch flag, it is possible for it to contain
12502 // non-hoistable expressions that refers to scope variables, e.g. compiler
12503 // injected keys or cached event handlers. Therefore we need to always
12504 // check the codegenNode's props to be sure.
12505 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12506 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12507 constantCache.set(node, 0 /* NOT_CONSTANT */);
12508 return 0 /* NOT_CONSTANT */;
12509 }
12510 if (generatedPropsType < returnType) {
12511 returnType = generatedPropsType;
12512 }
12513 // 2. its children.
12514 for (let i = 0; i < node.children.length; i++) {
12515 const childType = getConstantType(node.children[i], context);
12516 if (childType === 0 /* NOT_CONSTANT */) {
12517 constantCache.set(node, 0 /* NOT_CONSTANT */);
12518 return 0 /* NOT_CONSTANT */;
12519 }
12520 if (childType < returnType) {
12521 returnType = childType;
12522 }
12523 }
12524 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12525 // type, check if any of the props can cause the type to be lowered
12526 // we can skip can_patch because it's guaranteed by the absence of a
12527 // patchFlag.
12528 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12529 for (let i = 0; i < node.props.length; i++) {
12530 const p = node.props[i];
12531 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12532 const expType = getConstantType(p.exp, context);
12533 if (expType === 0 /* NOT_CONSTANT */) {
12534 constantCache.set(node, 0 /* NOT_CONSTANT */);
12535 return 0 /* NOT_CONSTANT */;
12536 }
12537 if (expType < returnType) {
12538 returnType = expType;
12539 }
12540 }
12541 }
12542 }
12543 // only svg/foreignObject could be block here, however if they are
12544 // static then they don't need to be blocks since there will be no
12545 // nested updates.
12546 if (codegenNode.isBlock) {
12547 context.removeHelper(OPEN_BLOCK);
12548 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12549 codegenNode.isBlock = false;
12550 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12551 }
12552 constantCache.set(node, returnType);
12553 return returnType;
12554 }
12555 else {
12556 constantCache.set(node, 0 /* NOT_CONSTANT */);
12557 return 0 /* NOT_CONSTANT */;
12558 }
12559 case 2 /* TEXT */:
12560 case 3 /* COMMENT */:
12561 return 3 /* CAN_STRINGIFY */;
12562 case 9 /* IF */:
12563 case 11 /* FOR */:
12564 case 10 /* IF_BRANCH */:
12565 return 0 /* NOT_CONSTANT */;
12566 case 5 /* INTERPOLATION */:
12567 case 12 /* TEXT_CALL */:
12568 return getConstantType(node.content, context);
12569 case 4 /* SIMPLE_EXPRESSION */:
12570 return node.constType;
12571 case 8 /* COMPOUND_EXPRESSION */:
12572 let returnType = 3 /* CAN_STRINGIFY */;
12573 for (let i = 0; i < node.children.length; i++) {
12574 const child = node.children[i];
12575 if (isString(child) || isSymbol(child)) {
12576 continue;
12577 }
12578 const childType = getConstantType(child, context);
12579 if (childType === 0 /* NOT_CONSTANT */) {
12580 return 0 /* NOT_CONSTANT */;
12581 }
12582 else if (childType < returnType) {
12583 returnType = childType;
12584 }
12585 }
12586 return returnType;
12587 default:
12588 return 0 /* NOT_CONSTANT */;
12589 }
12590}
12591const allowHoistedHelperSet = new Set([
12592 NORMALIZE_CLASS,
12593 NORMALIZE_STYLE,
12594 NORMALIZE_PROPS,
12595 GUARD_REACTIVE_PROPS
12596]);
12597function getConstantTypeOfHelperCall(value, context) {
12598 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12599 !isString(value.callee) &&
12600 allowHoistedHelperSet.has(value.callee)) {
12601 const arg = value.arguments[0];
12602 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12603 return getConstantType(arg, context);
12604 }
12605 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12606 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12607 return getConstantTypeOfHelperCall(arg, context);
12608 }
12609 }
12610 return 0 /* NOT_CONSTANT */;
12611}
12612function getGeneratedPropsConstantType(node, context) {
12613 let returnType = 3 /* CAN_STRINGIFY */;
12614 const props = getNodeProps(node);
12615 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12616 const { properties } = props;
12617 for (let i = 0; i < properties.length; i++) {
12618 const { key, value } = properties[i];
12619 const keyType = getConstantType(key, context);
12620 if (keyType === 0 /* NOT_CONSTANT */) {
12621 return keyType;
12622 }
12623 if (keyType < returnType) {
12624 returnType = keyType;
12625 }
12626 let valueType;
12627 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12628 valueType = getConstantType(value, context);
12629 }
12630 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12631 // some helper calls can be hoisted,
12632 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12633 // in this case we need to respect the ConstantType of the helper's arguments
12634 valueType = getConstantTypeOfHelperCall(value, context);
12635 }
12636 else {
12637 valueType = 0 /* NOT_CONSTANT */;
12638 }
12639 if (valueType === 0 /* NOT_CONSTANT */) {
12640 return valueType;
12641 }
12642 if (valueType < returnType) {
12643 returnType = valueType;
12644 }
12645 }
12646 }
12647 return returnType;
12648}
12649function getNodeProps(node) {
12650 const codegenNode = node.codegenNode;
12651 if (codegenNode.type === 13 /* VNODE_CALL */) {
12652 return codegenNode.props;
12653 }
12654}
12655function getPatchFlag(node) {
12656 const flag = node.patchFlag;
12657 return flag ? parseInt(flag, 10) : undefined;
12658}
12659
12660function 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 }) {
12661 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12662 const context = {
12663 // options
12664 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12665 prefixIdentifiers,
12666 hoistStatic,
12667 cacheHandlers,
12668 nodeTransforms,
12669 directiveTransforms,
12670 transformHoist,
12671 isBuiltInComponent,
12672 isCustomElement,
12673 expressionPlugins,
12674 scopeId,
12675 slotted,
12676 ssr,
12677 inSSR,
12678 ssrCssVars,
12679 bindingMetadata,
12680 inline,
12681 isTS,
12682 onError,
12683 onWarn,
12684 compatConfig,
12685 // state
12686 root,
12687 helpers: new Map(),
12688 components: new Set(),
12689 directives: new Set(),
12690 hoists: [],
12691 imports: [],
12692 constantCache: new Map(),
12693 temps: 0,
12694 cached: 0,
12695 identifiers: Object.create(null),
12696 scopes: {
12697 vFor: 0,
12698 vSlot: 0,
12699 vPre: 0,
12700 vOnce: 0
12701 },
12702 parent: null,
12703 currentNode: root,
12704 childIndex: 0,
12705 inVOnce: false,
12706 // methods
12707 helper(name) {
12708 const count = context.helpers.get(name) || 0;
12709 context.helpers.set(name, count + 1);
12710 return name;
12711 },
12712 removeHelper(name) {
12713 const count = context.helpers.get(name);
12714 if (count) {
12715 const currentCount = count - 1;
12716 if (!currentCount) {
12717 context.helpers.delete(name);
12718 }
12719 else {
12720 context.helpers.set(name, currentCount);
12721 }
12722 }
12723 },
12724 helperString(name) {
12725 return `_${helperNameMap[context.helper(name)]}`;
12726 },
12727 replaceNode(node) {
12728 /* istanbul ignore if */
12729 {
12730 if (!context.currentNode) {
12731 throw new Error(`Node being replaced is already removed.`);
12732 }
12733 if (!context.parent) {
12734 throw new Error(`Cannot replace root node.`);
12735 }
12736 }
12737 context.parent.children[context.childIndex] = context.currentNode = node;
12738 },
12739 removeNode(node) {
12740 if (!context.parent) {
12741 throw new Error(`Cannot remove root node.`);
12742 }
12743 const list = context.parent.children;
12744 const removalIndex = node
12745 ? list.indexOf(node)
12746 : context.currentNode
12747 ? context.childIndex
12748 : -1;
12749 /* istanbul ignore if */
12750 if (removalIndex < 0) {
12751 throw new Error(`node being removed is not a child of current parent`);
12752 }
12753 if (!node || node === context.currentNode) {
12754 // current node removed
12755 context.currentNode = null;
12756 context.onNodeRemoved();
12757 }
12758 else {
12759 // sibling node removed
12760 if (context.childIndex > removalIndex) {
12761 context.childIndex--;
12762 context.onNodeRemoved();
12763 }
12764 }
12765 context.parent.children.splice(removalIndex, 1);
12766 },
12767 onNodeRemoved: () => { },
12768 addIdentifiers(exp) {
12769 },
12770 removeIdentifiers(exp) {
12771 },
12772 hoist(exp) {
12773 if (isString(exp))
12774 exp = createSimpleExpression(exp);
12775 context.hoists.push(exp);
12776 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12777 identifier.hoisted = exp;
12778 return identifier;
12779 },
12780 cache(exp, isVNode = false) {
12781 return createCacheExpression(context.cached++, exp, isVNode);
12782 }
12783 };
12784 return context;
12785}
12786function transform(root, options) {
12787 const context = createTransformContext(root, options);
12788 traverseNode(root, context);
12789 if (options.hoistStatic) {
12790 hoistStatic(root, context);
12791 }
12792 if (!options.ssr) {
12793 createRootCodegen(root, context);
12794 }
12795 // finalize meta information
12796 root.helpers = [...context.helpers.keys()];
12797 root.components = [...context.components];
12798 root.directives = [...context.directives];
12799 root.imports = context.imports;
12800 root.hoists = context.hoists;
12801 root.temps = context.temps;
12802 root.cached = context.cached;
12803}
12804function createRootCodegen(root, context) {
12805 const { helper } = context;
12806 const { children } = root;
12807 if (children.length === 1) {
12808 const child = children[0];
12809 // if the single child is an element, turn it into a block.
12810 if (isSingleElementRoot(root, child) && child.codegenNode) {
12811 // single element root is never hoisted so codegenNode will never be
12812 // SimpleExpressionNode
12813 const codegenNode = child.codegenNode;
12814 if (codegenNode.type === 13 /* VNODE_CALL */) {
12815 makeBlock(codegenNode, context);
12816 }
12817 root.codegenNode = codegenNode;
12818 }
12819 else {
12820 // - single <slot/>, IfNode, ForNode: already blocks.
12821 // - single text node: always patched.
12822 // root codegen falls through via genNode()
12823 root.codegenNode = child;
12824 }
12825 }
12826 else if (children.length > 1) {
12827 // root has multiple nodes - return a fragment block.
12828 let patchFlag = 64 /* STABLE_FRAGMENT */;
12829 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12830 // check if the fragment actually contains a single valid child with
12831 // the rest being comments
12832 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12833 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12834 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12835 }
12836 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12837 }
12838 else ;
12839}
12840function traverseChildren(parent, context) {
12841 let i = 0;
12842 const nodeRemoved = () => {
12843 i--;
12844 };
12845 for (; i < parent.children.length; i++) {
12846 const child = parent.children[i];
12847 if (isString(child))
12848 continue;
12849 context.parent = parent;
12850 context.childIndex = i;
12851 context.onNodeRemoved = nodeRemoved;
12852 traverseNode(child, context);
12853 }
12854}
12855function traverseNode(node, context) {
12856 context.currentNode = node;
12857 // apply transform plugins
12858 const { nodeTransforms } = context;
12859 const exitFns = [];
12860 for (let i = 0; i < nodeTransforms.length; i++) {
12861 const onExit = nodeTransforms[i](node, context);
12862 if (onExit) {
12863 if (isArray(onExit)) {
12864 exitFns.push(...onExit);
12865 }
12866 else {
12867 exitFns.push(onExit);
12868 }
12869 }
12870 if (!context.currentNode) {
12871 // node was removed
12872 return;
12873 }
12874 else {
12875 // node may have been replaced
12876 node = context.currentNode;
12877 }
12878 }
12879 switch (node.type) {
12880 case 3 /* COMMENT */:
12881 if (!context.ssr) {
12882 // inject import for the Comment symbol, which is needed for creating
12883 // comment nodes with `createVNode`
12884 context.helper(CREATE_COMMENT);
12885 }
12886 break;
12887 case 5 /* INTERPOLATION */:
12888 // no need to traverse, but we need to inject toString helper
12889 if (!context.ssr) {
12890 context.helper(TO_DISPLAY_STRING);
12891 }
12892 break;
12893 // for container types, further traverse downwards
12894 case 9 /* IF */:
12895 for (let i = 0; i < node.branches.length; i++) {
12896 traverseNode(node.branches[i], context);
12897 }
12898 break;
12899 case 10 /* IF_BRANCH */:
12900 case 11 /* FOR */:
12901 case 1 /* ELEMENT */:
12902 case 0 /* ROOT */:
12903 traverseChildren(node, context);
12904 break;
12905 }
12906 // exit transforms
12907 context.currentNode = node;
12908 let i = exitFns.length;
12909 while (i--) {
12910 exitFns[i]();
12911 }
12912}
12913function createStructuralDirectiveTransform(name, fn) {
12914 const matches = isString(name)
12915 ? (n) => n === name
12916 : (n) => name.test(n);
12917 return (node, context) => {
12918 if (node.type === 1 /* ELEMENT */) {
12919 const { props } = node;
12920 // structural directive transforms are not concerned with slots
12921 // as they are handled separately in vSlot.ts
12922 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
12923 return;
12924 }
12925 const exitFns = [];
12926 for (let i = 0; i < props.length; i++) {
12927 const prop = props[i];
12928 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
12929 // structural directives are removed to avoid infinite recursion
12930 // also we remove them *before* applying so that it can further
12931 // traverse itself in case it moves the node around
12932 props.splice(i, 1);
12933 i--;
12934 const onExit = fn(node, prop, context);
12935 if (onExit)
12936 exitFns.push(onExit);
12937 }
12938 }
12939 return exitFns;
12940 }
12941 };
12942}
12943
12944const PURE_ANNOTATION = `/*#__PURE__*/`;
12945function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
12946 const context = {
12947 mode,
12948 prefixIdentifiers,
12949 sourceMap,
12950 filename,
12951 scopeId,
12952 optimizeImports,
12953 runtimeGlobalName,
12954 runtimeModuleName,
12955 ssrRuntimeModuleName,
12956 ssr,
12957 isTS,
12958 inSSR,
12959 source: ast.loc.source,
12960 code: ``,
12961 column: 1,
12962 line: 1,
12963 offset: 0,
12964 indentLevel: 0,
12965 pure: false,
12966 map: undefined,
12967 helper(key) {
12968 return `_${helperNameMap[key]}`;
12969 },
12970 push(code, node) {
12971 context.code += code;
12972 },
12973 indent() {
12974 newline(++context.indentLevel);
12975 },
12976 deindent(withoutNewLine = false) {
12977 if (withoutNewLine) {
12978 --context.indentLevel;
12979 }
12980 else {
12981 newline(--context.indentLevel);
12982 }
12983 },
12984 newline() {
12985 newline(context.indentLevel);
12986 }
12987 };
12988 function newline(n) {
12989 context.push('\n' + ` `.repeat(n));
12990 }
12991 return context;
12992}
12993function generate(ast, options = {}) {
12994 const context = createCodegenContext(ast, options);
12995 if (options.onContextCreated)
12996 options.onContextCreated(context);
12997 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
12998 const hasHelpers = ast.helpers.length > 0;
12999 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13000 // preambles
13001 // in setup() inline mode, the preamble is generated in a sub context
13002 // and returned separately.
13003 const preambleContext = context;
13004 {
13005 genFunctionPreamble(ast, preambleContext);
13006 }
13007 // enter render function
13008 const functionName = ssr ? `ssrRender` : `render`;
13009 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13010 const signature = args.join(', ');
13011 {
13012 push(`function ${functionName}(${signature}) {`);
13013 }
13014 indent();
13015 if (useWithBlock) {
13016 push(`with (_ctx) {`);
13017 indent();
13018 // function mode const declarations should be inside with block
13019 // also they should be renamed to avoid collision with user properties
13020 if (hasHelpers) {
13021 push(`const { ${ast.helpers
13022 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
13023 .join(', ')} } = _Vue`);
13024 push(`\n`);
13025 newline();
13026 }
13027 }
13028 // generate asset resolution statements
13029 if (ast.components.length) {
13030 genAssets(ast.components, 'component', context);
13031 if (ast.directives.length || ast.temps > 0) {
13032 newline();
13033 }
13034 }
13035 if (ast.directives.length) {
13036 genAssets(ast.directives, 'directive', context);
13037 if (ast.temps > 0) {
13038 newline();
13039 }
13040 }
13041 if (ast.temps > 0) {
13042 push(`let `);
13043 for (let i = 0; i < ast.temps; i++) {
13044 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13045 }
13046 }
13047 if (ast.components.length || ast.directives.length || ast.temps) {
13048 push(`\n`);
13049 newline();
13050 }
13051 // generate the VNode tree expression
13052 if (!ssr) {
13053 push(`return `);
13054 }
13055 if (ast.codegenNode) {
13056 genNode(ast.codegenNode, context);
13057 }
13058 else {
13059 push(`null`);
13060 }
13061 if (useWithBlock) {
13062 deindent();
13063 push(`}`);
13064 }
13065 deindent();
13066 push(`}`);
13067 return {
13068 ast,
13069 code: context.code,
13070 preamble: ``,
13071 // SourceMapGenerator does have toJSON() method but it's not in the types
13072 map: context.map ? context.map.toJSON() : undefined
13073 };
13074}
13075function genFunctionPreamble(ast, context) {
13076 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
13077 const VueBinding = runtimeGlobalName;
13078 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13079 // Generate const declaration for helpers
13080 // In prefix mode, we place the const declaration at top so it's done
13081 // only once; But if we not prefixing, we place the declaration inside the
13082 // with block so it doesn't incur the `in` check cost for every helper access.
13083 if (ast.helpers.length > 0) {
13084 {
13085 // "with" mode.
13086 // save Vue in a separate variable to avoid collision
13087 push(`const _Vue = ${VueBinding}\n`);
13088 // in "with" mode, helpers are declared inside the with block to avoid
13089 // has check cost, but hoists are lifted out of the function - we need
13090 // to provide the helper here.
13091 if (ast.hoists.length) {
13092 const staticHelpers = [
13093 CREATE_VNODE,
13094 CREATE_ELEMENT_VNODE,
13095 CREATE_COMMENT,
13096 CREATE_TEXT,
13097 CREATE_STATIC
13098 ]
13099 .filter(helper => ast.helpers.includes(helper))
13100 .map(aliasHelper)
13101 .join(', ');
13102 push(`const { ${staticHelpers} } = _Vue\n`);
13103 }
13104 }
13105 }
13106 genHoists(ast.hoists, context);
13107 newline();
13108 push(`return `);
13109}
13110function genAssets(assets, type, { helper, push, newline, isTS }) {
13111 const resolver = helper(type === 'component'
13112 ? RESOLVE_COMPONENT
13113 : RESOLVE_DIRECTIVE);
13114 for (let i = 0; i < assets.length; i++) {
13115 let id = assets[i];
13116 // potential component implicit self-reference inferred from SFC filename
13117 const maybeSelfReference = id.endsWith('__self');
13118 if (maybeSelfReference) {
13119 id = id.slice(0, -6);
13120 }
13121 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13122 if (i < assets.length - 1) {
13123 newline();
13124 }
13125 }
13126}
13127function genHoists(hoists, context) {
13128 if (!hoists.length) {
13129 return;
13130 }
13131 context.pure = true;
13132 const { push, newline, helper, scopeId, mode } = context;
13133 newline();
13134 for (let i = 0; i < hoists.length; i++) {
13135 const exp = hoists[i];
13136 if (exp) {
13137 push(`const _hoisted_${i + 1} = ${``}`);
13138 genNode(exp, context);
13139 newline();
13140 }
13141 }
13142 context.pure = false;
13143}
13144function isText$1(n) {
13145 return (isString(n) ||
13146 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13147 n.type === 2 /* TEXT */ ||
13148 n.type === 5 /* INTERPOLATION */ ||
13149 n.type === 8 /* COMPOUND_EXPRESSION */);
13150}
13151function genNodeListAsArray(nodes, context) {
13152 const multilines = nodes.length > 3 ||
13153 (nodes.some(n => isArray(n) || !isText$1(n)));
13154 context.push(`[`);
13155 multilines && context.indent();
13156 genNodeList(nodes, context, multilines);
13157 multilines && context.deindent();
13158 context.push(`]`);
13159}
13160function genNodeList(nodes, context, multilines = false, comma = true) {
13161 const { push, newline } = context;
13162 for (let i = 0; i < nodes.length; i++) {
13163 const node = nodes[i];
13164 if (isString(node)) {
13165 push(node);
13166 }
13167 else if (isArray(node)) {
13168 genNodeListAsArray(node, context);
13169 }
13170 else {
13171 genNode(node, context);
13172 }
13173 if (i < nodes.length - 1) {
13174 if (multilines) {
13175 comma && push(',');
13176 newline();
13177 }
13178 else {
13179 comma && push(', ');
13180 }
13181 }
13182 }
13183}
13184function genNode(node, context) {
13185 if (isString(node)) {
13186 context.push(node);
13187 return;
13188 }
13189 if (isSymbol(node)) {
13190 context.push(context.helper(node));
13191 return;
13192 }
13193 switch (node.type) {
13194 case 1 /* ELEMENT */:
13195 case 9 /* IF */:
13196 case 11 /* FOR */:
13197 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13198 `Apply appropriate transforms first.`);
13199 genNode(node.codegenNode, context);
13200 break;
13201 case 2 /* TEXT */:
13202 genText(node, context);
13203 break;
13204 case 4 /* SIMPLE_EXPRESSION */:
13205 genExpression(node, context);
13206 break;
13207 case 5 /* INTERPOLATION */:
13208 genInterpolation(node, context);
13209 break;
13210 case 12 /* TEXT_CALL */:
13211 genNode(node.codegenNode, context);
13212 break;
13213 case 8 /* COMPOUND_EXPRESSION */:
13214 genCompoundExpression(node, context);
13215 break;
13216 case 3 /* COMMENT */:
13217 genComment(node, context);
13218 break;
13219 case 13 /* VNODE_CALL */:
13220 genVNodeCall(node, context);
13221 break;
13222 case 14 /* JS_CALL_EXPRESSION */:
13223 genCallExpression(node, context);
13224 break;
13225 case 15 /* JS_OBJECT_EXPRESSION */:
13226 genObjectExpression(node, context);
13227 break;
13228 case 17 /* JS_ARRAY_EXPRESSION */:
13229 genArrayExpression(node, context);
13230 break;
13231 case 18 /* JS_FUNCTION_EXPRESSION */:
13232 genFunctionExpression(node, context);
13233 break;
13234 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13235 genConditionalExpression(node, context);
13236 break;
13237 case 20 /* JS_CACHE_EXPRESSION */:
13238 genCacheExpression(node, context);
13239 break;
13240 case 21 /* JS_BLOCK_STATEMENT */:
13241 genNodeList(node.body, context, true, false);
13242 break;
13243 // SSR only types
13244 case 22 /* JS_TEMPLATE_LITERAL */:
13245 break;
13246 case 23 /* JS_IF_STATEMENT */:
13247 break;
13248 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13249 break;
13250 case 25 /* JS_SEQUENCE_EXPRESSION */:
13251 break;
13252 case 26 /* JS_RETURN_STATEMENT */:
13253 break;
13254 /* istanbul ignore next */
13255 case 10 /* IF_BRANCH */:
13256 // noop
13257 break;
13258 default:
13259 {
13260 assert(false, `unhandled codegen node type: ${node.type}`);
13261 // make sure we exhaust all possible types
13262 const exhaustiveCheck = node;
13263 return exhaustiveCheck;
13264 }
13265 }
13266}
13267function genText(node, context) {
13268 context.push(JSON.stringify(node.content), node);
13269}
13270function genExpression(node, context) {
13271 const { content, isStatic } = node;
13272 context.push(isStatic ? JSON.stringify(content) : content, node);
13273}
13274function genInterpolation(node, context) {
13275 const { push, helper, pure } = context;
13276 if (pure)
13277 push(PURE_ANNOTATION);
13278 push(`${helper(TO_DISPLAY_STRING)}(`);
13279 genNode(node.content, context);
13280 push(`)`);
13281}
13282function genCompoundExpression(node, context) {
13283 for (let i = 0; i < node.children.length; i++) {
13284 const child = node.children[i];
13285 if (isString(child)) {
13286 context.push(child);
13287 }
13288 else {
13289 genNode(child, context);
13290 }
13291 }
13292}
13293function genExpressionAsPropertyKey(node, context) {
13294 const { push } = context;
13295 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13296 push(`[`);
13297 genCompoundExpression(node, context);
13298 push(`]`);
13299 }
13300 else if (node.isStatic) {
13301 // only quote keys if necessary
13302 const text = isSimpleIdentifier(node.content)
13303 ? node.content
13304 : JSON.stringify(node.content);
13305 push(text, node);
13306 }
13307 else {
13308 push(`[${node.content}]`, node);
13309 }
13310}
13311function genComment(node, context) {
13312 const { push, helper, pure } = context;
13313 if (pure) {
13314 push(PURE_ANNOTATION);
13315 }
13316 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13317}
13318function genVNodeCall(node, context) {
13319 const { push, helper, pure } = context;
13320 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13321 if (directives) {
13322 push(helper(WITH_DIRECTIVES) + `(`);
13323 }
13324 if (isBlock) {
13325 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13326 }
13327 if (pure) {
13328 push(PURE_ANNOTATION);
13329 }
13330 const callHelper = isBlock
13331 ? getVNodeBlockHelper(context.inSSR, isComponent)
13332 : getVNodeHelper(context.inSSR, isComponent);
13333 push(helper(callHelper) + `(`, node);
13334 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13335 push(`)`);
13336 if (isBlock) {
13337 push(`)`);
13338 }
13339 if (directives) {
13340 push(`, `);
13341 genNode(directives, context);
13342 push(`)`);
13343 }
13344}
13345function genNullableArgs(args) {
13346 let i = args.length;
13347 while (i--) {
13348 if (args[i] != null)
13349 break;
13350 }
13351 return args.slice(0, i + 1).map(arg => arg || `null`);
13352}
13353// JavaScript
13354function genCallExpression(node, context) {
13355 const { push, helper, pure } = context;
13356 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13357 if (pure) {
13358 push(PURE_ANNOTATION);
13359 }
13360 push(callee + `(`, node);
13361 genNodeList(node.arguments, context);
13362 push(`)`);
13363}
13364function genObjectExpression(node, context) {
13365 const { push, indent, deindent, newline } = context;
13366 const { properties } = node;
13367 if (!properties.length) {
13368 push(`{}`, node);
13369 return;
13370 }
13371 const multilines = properties.length > 1 ||
13372 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13373 push(multilines ? `{` : `{ `);
13374 multilines && indent();
13375 for (let i = 0; i < properties.length; i++) {
13376 const { key, value } = properties[i];
13377 // key
13378 genExpressionAsPropertyKey(key, context);
13379 push(`: `);
13380 // value
13381 genNode(value, context);
13382 if (i < properties.length - 1) {
13383 // will only reach this if it's multilines
13384 push(`,`);
13385 newline();
13386 }
13387 }
13388 multilines && deindent();
13389 push(multilines ? `}` : ` }`);
13390}
13391function genArrayExpression(node, context) {
13392 genNodeListAsArray(node.elements, context);
13393}
13394function genFunctionExpression(node, context) {
13395 const { push, indent, deindent } = context;
13396 const { params, returns, body, newline, isSlot } = node;
13397 if (isSlot) {
13398 // wrap slot functions with owner context
13399 push(`_${helperNameMap[WITH_CTX]}(`);
13400 }
13401 push(`(`, node);
13402 if (isArray(params)) {
13403 genNodeList(params, context);
13404 }
13405 else if (params) {
13406 genNode(params, context);
13407 }
13408 push(`) => `);
13409 if (newline || body) {
13410 push(`{`);
13411 indent();
13412 }
13413 if (returns) {
13414 if (newline) {
13415 push(`return `);
13416 }
13417 if (isArray(returns)) {
13418 genNodeListAsArray(returns, context);
13419 }
13420 else {
13421 genNode(returns, context);
13422 }
13423 }
13424 else if (body) {
13425 genNode(body, context);
13426 }
13427 if (newline || body) {
13428 deindent();
13429 push(`}`);
13430 }
13431 if (isSlot) {
13432 push(`)`);
13433 }
13434}
13435function genConditionalExpression(node, context) {
13436 const { test, consequent, alternate, newline: needNewline } = node;
13437 const { push, indent, deindent, newline } = context;
13438 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13439 const needsParens = !isSimpleIdentifier(test.content);
13440 needsParens && push(`(`);
13441 genExpression(test, context);
13442 needsParens && push(`)`);
13443 }
13444 else {
13445 push(`(`);
13446 genNode(test, context);
13447 push(`)`);
13448 }
13449 needNewline && indent();
13450 context.indentLevel++;
13451 needNewline || push(` `);
13452 push(`? `);
13453 genNode(consequent, context);
13454 context.indentLevel--;
13455 needNewline && newline();
13456 needNewline || push(` `);
13457 push(`: `);
13458 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13459 if (!isNested) {
13460 context.indentLevel++;
13461 }
13462 genNode(alternate, context);
13463 if (!isNested) {
13464 context.indentLevel--;
13465 }
13466 needNewline && deindent(true /* without newline */);
13467}
13468function genCacheExpression(node, context) {
13469 const { push, helper, indent, deindent, newline } = context;
13470 push(`_cache[${node.index}] || (`);
13471 if (node.isVNode) {
13472 indent();
13473 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13474 newline();
13475 }
13476 push(`_cache[${node.index}] = `);
13477 genNode(node.value, context);
13478 if (node.isVNode) {
13479 push(`,`);
13480 newline();
13481 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13482 newline();
13483 push(`_cache[${node.index}]`);
13484 deindent();
13485 }
13486 push(`)`);
13487}
13488
13489// these keywords should not appear inside expressions, but operators like
13490// typeof, instanceof and in are allowed
13491const prohibitedKeywordRE = new RegExp('\\b' +
13492 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13493 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13494 'extends,finally,continue,debugger,function,arguments,typeof,void')
13495 .split(',')
13496 .join('\\b|\\b') +
13497 '\\b');
13498// strip strings in expressions
13499const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13500/**
13501 * Validate a non-prefixed expression.
13502 * This is only called when using the in-browser runtime compiler since it
13503 * doesn't prefix expressions.
13504 */
13505function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13506 const exp = node.content;
13507 // empty expressions are validated per-directive since some directives
13508 // do allow empty expressions.
13509 if (!exp.trim()) {
13510 return;
13511 }
13512 try {
13513 new Function(asRawStatements
13514 ? ` ${exp} `
13515 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13516 }
13517 catch (e) {
13518 let message = e.message;
13519 const keywordMatch = exp
13520 .replace(stripStringRE, '')
13521 .match(prohibitedKeywordRE);
13522 if (keywordMatch) {
13523 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13524 }
13525 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13526 }
13527}
13528
13529const transformExpression = (node, context) => {
13530 if (node.type === 5 /* INTERPOLATION */) {
13531 node.content = processExpression(node.content, context);
13532 }
13533 else if (node.type === 1 /* ELEMENT */) {
13534 // handle directives on element
13535 for (let i = 0; i < node.props.length; i++) {
13536 const dir = node.props[i];
13537 // do not process for v-on & v-for since they are special handled
13538 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13539 const exp = dir.exp;
13540 const arg = dir.arg;
13541 // do not process exp if this is v-on:arg - we need special handling
13542 // for wrapping inline statements.
13543 if (exp &&
13544 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13545 !(dir.name === 'on' && arg)) {
13546 dir.exp = processExpression(exp, context,
13547 // slot args must be processed as function params
13548 dir.name === 'slot');
13549 }
13550 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13551 dir.arg = processExpression(arg, context);
13552 }
13553 }
13554 }
13555 }
13556};
13557// Important: since this function uses Node.js only dependencies, it should
13558// always be used with a leading !true check so that it can be
13559// tree-shaken from the browser build.
13560function processExpression(node, context,
13561// some expressions like v-slot props & v-for aliases should be parsed as
13562// function params
13563asParams = false,
13564// v-on handler values may contain multiple statements
13565asRawStatements = false, localVars = Object.create(context.identifiers)) {
13566 {
13567 {
13568 // simple in-browser validation (same logic in 2.x)
13569 validateBrowserExpression(node, context, asParams, asRawStatements);
13570 }
13571 return node;
13572 }
13573}
13574
13575const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13576 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13577 // #1587: We need to dynamically increment the key based on the current
13578 // node's sibling nodes, since chained v-if/else branches are
13579 // rendered at the same depth
13580 const siblings = context.parent.children;
13581 let i = siblings.indexOf(ifNode);
13582 let key = 0;
13583 while (i-- >= 0) {
13584 const sibling = siblings[i];
13585 if (sibling && sibling.type === 9 /* IF */) {
13586 key += sibling.branches.length;
13587 }
13588 }
13589 // Exit callback. Complete the codegenNode when all children have been
13590 // transformed.
13591 return () => {
13592 if (isRoot) {
13593 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13594 }
13595 else {
13596 // attach this branch's codegen node to the v-if root.
13597 const parentCondition = getParentCondition(ifNode.codegenNode);
13598 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13599 }
13600 };
13601 });
13602});
13603// target-agnostic transform used for both Client and SSR
13604function processIf(node, dir, context, processCodegen) {
13605 if (dir.name !== 'else' &&
13606 (!dir.exp || !dir.exp.content.trim())) {
13607 const loc = dir.exp ? dir.exp.loc : node.loc;
13608 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13609 dir.exp = createSimpleExpression(`true`, false, loc);
13610 }
13611 if (dir.exp) {
13612 validateBrowserExpression(dir.exp, context);
13613 }
13614 if (dir.name === 'if') {
13615 const branch = createIfBranch(node, dir);
13616 const ifNode = {
13617 type: 9 /* IF */,
13618 loc: node.loc,
13619 branches: [branch]
13620 };
13621 context.replaceNode(ifNode);
13622 if (processCodegen) {
13623 return processCodegen(ifNode, branch, true);
13624 }
13625 }
13626 else {
13627 // locate the adjacent v-if
13628 const siblings = context.parent.children;
13629 const comments = [];
13630 let i = siblings.indexOf(node);
13631 while (i-- >= -1) {
13632 const sibling = siblings[i];
13633 if (sibling && sibling.type === 3 /* COMMENT */) {
13634 context.removeNode(sibling);
13635 comments.unshift(sibling);
13636 continue;
13637 }
13638 if (sibling &&
13639 sibling.type === 2 /* TEXT */ &&
13640 !sibling.content.trim().length) {
13641 context.removeNode(sibling);
13642 continue;
13643 }
13644 if (sibling && sibling.type === 9 /* IF */) {
13645 // Check if v-else was followed by v-else-if
13646 if (dir.name === 'else-if' &&
13647 sibling.branches[sibling.branches.length - 1].condition === undefined) {
13648 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13649 }
13650 // move the node to the if node's branches
13651 context.removeNode();
13652 const branch = createIfBranch(node, dir);
13653 if (comments.length &&
13654 // #3619 ignore comments if the v-if is direct child of <transition>
13655 !(context.parent &&
13656 context.parent.type === 1 /* ELEMENT */ &&
13657 isBuiltInType(context.parent.tag, 'transition'))) {
13658 branch.children = [...comments, ...branch.children];
13659 }
13660 // check if user is forcing same key on different branches
13661 {
13662 const key = branch.userKey;
13663 if (key) {
13664 sibling.branches.forEach(({ userKey }) => {
13665 if (isSameKey(userKey, key)) {
13666 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13667 }
13668 });
13669 }
13670 }
13671 sibling.branches.push(branch);
13672 const onExit = processCodegen && processCodegen(sibling, branch, false);
13673 // since the branch was removed, it will not be traversed.
13674 // make sure to traverse here.
13675 traverseNode(branch, context);
13676 // call on exit
13677 if (onExit)
13678 onExit();
13679 // make sure to reset currentNode after traversal to indicate this
13680 // node has been removed.
13681 context.currentNode = null;
13682 }
13683 else {
13684 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13685 }
13686 break;
13687 }
13688 }
13689}
13690function createIfBranch(node, dir) {
13691 return {
13692 type: 10 /* IF_BRANCH */,
13693 loc: node.loc,
13694 condition: dir.name === 'else' ? undefined : dir.exp,
13695 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13696 ? node.children
13697 : [node],
13698 userKey: findProp(node, `key`)
13699 };
13700}
13701function createCodegenNodeForBranch(branch, keyIndex, context) {
13702 if (branch.condition) {
13703 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13704 // make sure to pass in asBlock: true so that the comment node call
13705 // closes the current block.
13706 createCallExpression(context.helper(CREATE_COMMENT), [
13707 '"v-if"' ,
13708 'true'
13709 ]));
13710 }
13711 else {
13712 return createChildrenCodegenNode(branch, keyIndex, context);
13713 }
13714}
13715function createChildrenCodegenNode(branch, keyIndex, context) {
13716 const { helper } = context;
13717 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13718 const { children } = branch;
13719 const firstChild = children[0];
13720 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13721 if (needFragmentWrapper) {
13722 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13723 // optimize away nested fragments when child is a ForNode
13724 const vnodeCall = firstChild.codegenNode;
13725 injectProp(vnodeCall, keyProperty, context);
13726 return vnodeCall;
13727 }
13728 else {
13729 let patchFlag = 64 /* STABLE_FRAGMENT */;
13730 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13731 // check if the fragment actually contains a single valid child with
13732 // the rest being comments
13733 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13734 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13735 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13736 }
13737 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13738 }
13739 }
13740 else {
13741 const ret = firstChild.codegenNode;
13742 const vnodeCall = getMemoedVNodeCall(ret);
13743 // Change createVNode to createBlock.
13744 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13745 makeBlock(vnodeCall, context);
13746 }
13747 // inject branch key
13748 injectProp(vnodeCall, keyProperty, context);
13749 return ret;
13750 }
13751}
13752function isSameKey(a, b) {
13753 if (!a || a.type !== b.type) {
13754 return false;
13755 }
13756 if (a.type === 6 /* ATTRIBUTE */) {
13757 if (a.value.content !== b.value.content) {
13758 return false;
13759 }
13760 }
13761 else {
13762 // directive
13763 const exp = a.exp;
13764 const branchExp = b.exp;
13765 if (exp.type !== branchExp.type) {
13766 return false;
13767 }
13768 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13769 exp.isStatic !== branchExp.isStatic ||
13770 exp.content !== branchExp.content) {
13771 return false;
13772 }
13773 }
13774 return true;
13775}
13776function getParentCondition(node) {
13777 while (true) {
13778 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13779 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13780 node = node.alternate;
13781 }
13782 else {
13783 return node;
13784 }
13785 }
13786 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13787 node = node.value;
13788 }
13789 }
13790}
13791
13792const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13793 const { helper, removeHelper } = context;
13794 return processFor(node, dir, context, forNode => {
13795 // create the loop render function expression now, and add the
13796 // iterator on exit after all children have been traversed
13797 const renderExp = createCallExpression(helper(RENDER_LIST), [
13798 forNode.source
13799 ]);
13800 const isTemplate = isTemplateNode(node);
13801 const memo = findDir(node, 'memo');
13802 const keyProp = findProp(node, `key`);
13803 const keyExp = keyProp &&
13804 (keyProp.type === 6 /* ATTRIBUTE */
13805 ? createSimpleExpression(keyProp.value.content, true)
13806 : keyProp.exp);
13807 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13808 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13809 forNode.source.constType > 0 /* NOT_CONSTANT */;
13810 const fragmentFlag = isStableFragment
13811 ? 64 /* STABLE_FRAGMENT */
13812 : keyProp
13813 ? 128 /* KEYED_FRAGMENT */
13814 : 256 /* UNKEYED_FRAGMENT */;
13815 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13816 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13817 return () => {
13818 // finish the codegen now that all children have been traversed
13819 let childBlock;
13820 const { children } = forNode;
13821 // check <template v-for> key placement
13822 if (isTemplate) {
13823 node.children.some(c => {
13824 if (c.type === 1 /* ELEMENT */) {
13825 const key = findProp(c, 'key');
13826 if (key) {
13827 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13828 return true;
13829 }
13830 }
13831 });
13832 }
13833 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13834 const slotOutlet = isSlotOutlet(node)
13835 ? node
13836 : isTemplate &&
13837 node.children.length === 1 &&
13838 isSlotOutlet(node.children[0])
13839 ? node.children[0] // api-extractor somehow fails to infer this
13840 : null;
13841 if (slotOutlet) {
13842 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13843 childBlock = slotOutlet.codegenNode;
13844 if (isTemplate && keyProperty) {
13845 // <template v-for="..." :key="..."><slot/></template>
13846 // we need to inject the key to the renderSlot() call.
13847 // the props for renderSlot is passed as the 3rd argument.
13848 injectProp(childBlock, keyProperty, context);
13849 }
13850 }
13851 else if (needFragmentWrapper) {
13852 // <template v-for="..."> with text or multi-elements
13853 // should generate a fragment block for each loop
13854 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
13855 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
13856 ), undefined, undefined, true, undefined, false /* isComponent */);
13857 }
13858 else {
13859 // Normal element v-for. Directly use the child's codegenNode
13860 // but mark it as a block.
13861 childBlock = children[0]
13862 .codegenNode;
13863 if (isTemplate && keyProperty) {
13864 injectProp(childBlock, keyProperty, context);
13865 }
13866 if (childBlock.isBlock !== !isStableFragment) {
13867 if (childBlock.isBlock) {
13868 // switch from block to vnode
13869 removeHelper(OPEN_BLOCK);
13870 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13871 }
13872 else {
13873 // switch from vnode to block
13874 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13875 }
13876 }
13877 childBlock.isBlock = !isStableFragment;
13878 if (childBlock.isBlock) {
13879 helper(OPEN_BLOCK);
13880 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13881 }
13882 else {
13883 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13884 }
13885 }
13886 if (memo) {
13887 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
13888 createSimpleExpression(`_cached`)
13889 ]));
13890 loop.body = createBlockStatement([
13891 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
13892 createCompoundExpression([
13893 `if (_cached`,
13894 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
13895 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
13896 ]),
13897 createCompoundExpression([`const _item = `, childBlock]),
13898 createSimpleExpression(`_item.memo = _memo`),
13899 createSimpleExpression(`return _item`)
13900 ]);
13901 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
13902 }
13903 else {
13904 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
13905 }
13906 };
13907 });
13908});
13909// target-agnostic transform used for both Client and SSR
13910function processFor(node, dir, context, processCodegen) {
13911 if (!dir.exp) {
13912 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
13913 return;
13914 }
13915 const parseResult = parseForExpression(
13916 // can only be simple expression because vFor transform is applied
13917 // before expression transform.
13918 dir.exp, context);
13919 if (!parseResult) {
13920 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
13921 return;
13922 }
13923 const { addIdentifiers, removeIdentifiers, scopes } = context;
13924 const { source, value, key, index } = parseResult;
13925 const forNode = {
13926 type: 11 /* FOR */,
13927 loc: dir.loc,
13928 source,
13929 valueAlias: value,
13930 keyAlias: key,
13931 objectIndexAlias: index,
13932 parseResult,
13933 children: isTemplateNode(node) ? node.children : [node]
13934 };
13935 context.replaceNode(forNode);
13936 // bookkeeping
13937 scopes.vFor++;
13938 const onExit = processCodegen && processCodegen(forNode);
13939 return () => {
13940 scopes.vFor--;
13941 if (onExit)
13942 onExit();
13943 };
13944}
13945const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
13946// This regex doesn't cover the case if key or index aliases have destructuring,
13947// but those do not make sense in the first place, so this works in practice.
13948const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
13949const stripParensRE = /^\(|\)$/g;
13950function parseForExpression(input, context) {
13951 const loc = input.loc;
13952 const exp = input.content;
13953 const inMatch = exp.match(forAliasRE);
13954 if (!inMatch)
13955 return;
13956 const [, LHS, RHS] = inMatch;
13957 const result = {
13958 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
13959 value: undefined,
13960 key: undefined,
13961 index: undefined
13962 };
13963 {
13964 validateBrowserExpression(result.source, context);
13965 }
13966 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
13967 const trimmedOffset = LHS.indexOf(valueContent);
13968 const iteratorMatch = valueContent.match(forIteratorRE);
13969 if (iteratorMatch) {
13970 valueContent = valueContent.replace(forIteratorRE, '').trim();
13971 const keyContent = iteratorMatch[1].trim();
13972 let keyOffset;
13973 if (keyContent) {
13974 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
13975 result.key = createAliasExpression(loc, keyContent, keyOffset);
13976 {
13977 validateBrowserExpression(result.key, context, true);
13978 }
13979 }
13980 if (iteratorMatch[2]) {
13981 const indexContent = iteratorMatch[2].trim();
13982 if (indexContent) {
13983 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
13984 ? keyOffset + keyContent.length
13985 : trimmedOffset + valueContent.length));
13986 {
13987 validateBrowserExpression(result.index, context, true);
13988 }
13989 }
13990 }
13991 }
13992 if (valueContent) {
13993 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
13994 {
13995 validateBrowserExpression(result.value, context, true);
13996 }
13997 }
13998 return result;
13999}
14000function createAliasExpression(range, content, offset) {
14001 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14002}
14003function createForLoopParams({ value, key, index }, memoArgs = []) {
14004 return createParamsList([value, key, index, ...memoArgs]);
14005}
14006function createParamsList(args) {
14007 let i = args.length;
14008 while (i--) {
14009 if (args[i])
14010 break;
14011 }
14012 return args
14013 .slice(0, i + 1)
14014 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14015}
14016
14017const defaultFallback = createSimpleExpression(`undefined`, false);
14018// A NodeTransform that:
14019// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14020// by transformExpression. This is only applied in non-browser builds with
14021// { prefixIdentifiers: true }.
14022// 2. Track v-slot depths so that we know a slot is inside another slot.
14023// Note the exit callback is executed before buildSlots() on the same node,
14024// so only nested slots see positive numbers.
14025const trackSlotScopes = (node, context) => {
14026 if (node.type === 1 /* ELEMENT */ &&
14027 (node.tagType === 1 /* COMPONENT */ ||
14028 node.tagType === 3 /* TEMPLATE */)) {
14029 // We are only checking non-empty v-slot here
14030 // since we only care about slots that introduce scope variables.
14031 const vSlot = findDir(node, 'slot');
14032 if (vSlot) {
14033 vSlot.exp;
14034 context.scopes.vSlot++;
14035 return () => {
14036 context.scopes.vSlot--;
14037 };
14038 }
14039 }
14040};
14041const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14042// Instead of being a DirectiveTransform, v-slot processing is called during
14043// transformElement to build the slots object for a component.
14044function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14045 context.helper(WITH_CTX);
14046 const { children, loc } = node;
14047 const slotsProperties = [];
14048 const dynamicSlots = [];
14049 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14050 // since it likely uses a scope variable.
14051 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14052 // 1. Check for slot with slotProps on component itself.
14053 // <Comp v-slot="{ prop }"/>
14054 const onComponentSlot = findDir(node, 'slot', true);
14055 if (onComponentSlot) {
14056 const { arg, exp } = onComponentSlot;
14057 if (arg && !isStaticExp(arg)) {
14058 hasDynamicSlots = true;
14059 }
14060 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14061 }
14062 // 2. Iterate through children and check for template slots
14063 // <template v-slot:foo="{ prop }">
14064 let hasTemplateSlots = false;
14065 let hasNamedDefaultSlot = false;
14066 const implicitDefaultChildren = [];
14067 const seenSlotNames = new Set();
14068 for (let i = 0; i < children.length; i++) {
14069 const slotElement = children[i];
14070 let slotDir;
14071 if (!isTemplateNode(slotElement) ||
14072 !(slotDir = findDir(slotElement, 'slot', true))) {
14073 // not a <template v-slot>, skip.
14074 if (slotElement.type !== 3 /* COMMENT */) {
14075 implicitDefaultChildren.push(slotElement);
14076 }
14077 continue;
14078 }
14079 if (onComponentSlot) {
14080 // already has on-component slot - this is incorrect usage.
14081 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14082 break;
14083 }
14084 hasTemplateSlots = true;
14085 const { children: slotChildren, loc: slotLoc } = slotElement;
14086 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14087 // check if name is dynamic.
14088 let staticSlotName;
14089 if (isStaticExp(slotName)) {
14090 staticSlotName = slotName ? slotName.content : `default`;
14091 }
14092 else {
14093 hasDynamicSlots = true;
14094 }
14095 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14096 // check if this slot is conditional (v-if/v-for)
14097 let vIf;
14098 let vElse;
14099 let vFor;
14100 if ((vIf = findDir(slotElement, 'if'))) {
14101 hasDynamicSlots = true;
14102 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14103 }
14104 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14105 // find adjacent v-if
14106 let j = i;
14107 let prev;
14108 while (j--) {
14109 prev = children[j];
14110 if (prev.type !== 3 /* COMMENT */) {
14111 break;
14112 }
14113 }
14114 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14115 // remove node
14116 children.splice(i, 1);
14117 i--;
14118 // attach this slot to previous conditional
14119 let conditional = dynamicSlots[dynamicSlots.length - 1];
14120 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14121 conditional = conditional.alternate;
14122 }
14123 conditional.alternate = vElse.exp
14124 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14125 : buildDynamicSlot(slotName, slotFunction);
14126 }
14127 else {
14128 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14129 }
14130 }
14131 else if ((vFor = findDir(slotElement, 'for'))) {
14132 hasDynamicSlots = true;
14133 const parseResult = vFor.parseResult ||
14134 parseForExpression(vFor.exp, context);
14135 if (parseResult) {
14136 // Render the dynamic slots as an array and add it to the createSlot()
14137 // args. The runtime knows how to handle it appropriately.
14138 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14139 parseResult.source,
14140 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14141 ]));
14142 }
14143 else {
14144 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14145 }
14146 }
14147 else {
14148 // check duplicate static names
14149 if (staticSlotName) {
14150 if (seenSlotNames.has(staticSlotName)) {
14151 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14152 continue;
14153 }
14154 seenSlotNames.add(staticSlotName);
14155 if (staticSlotName === 'default') {
14156 hasNamedDefaultSlot = true;
14157 }
14158 }
14159 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14160 }
14161 }
14162 if (!onComponentSlot) {
14163 const buildDefaultSlotProperty = (props, children) => {
14164 const fn = buildSlotFn(props, children, loc);
14165 return createObjectProperty(`default`, fn);
14166 };
14167 if (!hasTemplateSlots) {
14168 // implicit default slot (on component)
14169 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14170 }
14171 else if (implicitDefaultChildren.length &&
14172 // #3766
14173 // with whitespace: 'preserve', whitespaces between slots will end up in
14174 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14175 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14176 // implicit default slot (mixed with named slots)
14177 if (hasNamedDefaultSlot) {
14178 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14179 }
14180 else {
14181 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14182 }
14183 }
14184 }
14185 const slotFlag = hasDynamicSlots
14186 ? 2 /* DYNAMIC */
14187 : hasForwardedSlots(node.children)
14188 ? 3 /* FORWARDED */
14189 : 1 /* STABLE */;
14190 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14191 // 2 = compiled but dynamic = can skip normalization, but must run diff
14192 // 1 = compiled and static = can skip normalization AND diff as optimized
14193 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14194 if (dynamicSlots.length) {
14195 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14196 slots,
14197 createArrayExpression(dynamicSlots)
14198 ]);
14199 }
14200 return {
14201 slots,
14202 hasDynamicSlots
14203 };
14204}
14205function buildDynamicSlot(name, fn) {
14206 return createObjectExpression([
14207 createObjectProperty(`name`, name),
14208 createObjectProperty(`fn`, fn)
14209 ]);
14210}
14211function hasForwardedSlots(children) {
14212 for (let i = 0; i < children.length; i++) {
14213 const child = children[i];
14214 switch (child.type) {
14215 case 1 /* ELEMENT */:
14216 if (child.tagType === 2 /* SLOT */ ||
14217 hasForwardedSlots(child.children)) {
14218 return true;
14219 }
14220 break;
14221 case 9 /* IF */:
14222 if (hasForwardedSlots(child.branches))
14223 return true;
14224 break;
14225 case 10 /* IF_BRANCH */:
14226 case 11 /* FOR */:
14227 if (hasForwardedSlots(child.children))
14228 return true;
14229 break;
14230 }
14231 }
14232 return false;
14233}
14234function isNonWhitespaceContent(node) {
14235 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14236 return true;
14237 return node.type === 2 /* TEXT */
14238 ? !!node.content.trim()
14239 : isNonWhitespaceContent(node.content);
14240}
14241
14242// some directive transforms (e.g. v-model) may return a symbol for runtime
14243// import, which should be used instead of a resolveDirective call.
14244const directiveImportMap = new WeakMap();
14245// generate a JavaScript AST for this element's codegen
14246const transformElement = (node, context) => {
14247 // perform the work on exit, after all child expressions have been
14248 // processed and merged.
14249 return function postTransformElement() {
14250 node = context.currentNode;
14251 if (!(node.type === 1 /* ELEMENT */ &&
14252 (node.tagType === 0 /* ELEMENT */ ||
14253 node.tagType === 1 /* COMPONENT */))) {
14254 return;
14255 }
14256 const { tag, props } = node;
14257 const isComponent = node.tagType === 1 /* COMPONENT */;
14258 // The goal of the transform is to create a codegenNode implementing the
14259 // VNodeCall interface.
14260 let vnodeTag = isComponent
14261 ? resolveComponentType(node, context)
14262 : `"${tag}"`;
14263 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14264 let vnodeProps;
14265 let vnodeChildren;
14266 let vnodePatchFlag;
14267 let patchFlag = 0;
14268 let vnodeDynamicProps;
14269 let dynamicPropNames;
14270 let vnodeDirectives;
14271 let shouldUseBlock =
14272 // dynamic component may resolve to plain elements
14273 isDynamicComponent ||
14274 vnodeTag === TELEPORT ||
14275 vnodeTag === SUSPENSE ||
14276 (!isComponent &&
14277 // <svg> and <foreignObject> must be forced into blocks so that block
14278 // updates inside get proper isSVG flag at runtime. (#639, #643)
14279 // This is technically web-specific, but splitting the logic out of core
14280 // leads to too much unnecessary complexity.
14281 (tag === 'svg' || tag === 'foreignObject'));
14282 // props
14283 if (props.length > 0) {
14284 const propsBuildResult = buildProps(node, context);
14285 vnodeProps = propsBuildResult.props;
14286 patchFlag = propsBuildResult.patchFlag;
14287 dynamicPropNames = propsBuildResult.dynamicPropNames;
14288 const directives = propsBuildResult.directives;
14289 vnodeDirectives =
14290 directives && directives.length
14291 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14292 : undefined;
14293 if (propsBuildResult.shouldUseBlock) {
14294 shouldUseBlock = true;
14295 }
14296 }
14297 // children
14298 if (node.children.length > 0) {
14299 if (vnodeTag === KEEP_ALIVE) {
14300 // Although a built-in component, we compile KeepAlive with raw children
14301 // instead of slot functions so that it can be used inside Transition
14302 // or other Transition-wrapping HOCs.
14303 // To ensure correct updates with block optimizations, we need to:
14304 // 1. Force keep-alive into a block. This avoids its children being
14305 // collected by a parent block.
14306 shouldUseBlock = true;
14307 // 2. Force keep-alive to always be updated, since it uses raw children.
14308 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14309 if (node.children.length > 1) {
14310 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14311 start: node.children[0].loc.start,
14312 end: node.children[node.children.length - 1].loc.end,
14313 source: ''
14314 }));
14315 }
14316 }
14317 const shouldBuildAsSlots = isComponent &&
14318 // Teleport is not a real component and has dedicated runtime handling
14319 vnodeTag !== TELEPORT &&
14320 // explained above.
14321 vnodeTag !== KEEP_ALIVE;
14322 if (shouldBuildAsSlots) {
14323 const { slots, hasDynamicSlots } = buildSlots(node, context);
14324 vnodeChildren = slots;
14325 if (hasDynamicSlots) {
14326 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14327 }
14328 }
14329 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14330 const child = node.children[0];
14331 const type = child.type;
14332 // check for dynamic text children
14333 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14334 type === 8 /* COMPOUND_EXPRESSION */;
14335 if (hasDynamicTextChild &&
14336 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14337 patchFlag |= 1 /* TEXT */;
14338 }
14339 // pass directly if the only child is a text node
14340 // (plain / interpolation / expression)
14341 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14342 vnodeChildren = child;
14343 }
14344 else {
14345 vnodeChildren = node.children;
14346 }
14347 }
14348 else {
14349 vnodeChildren = node.children;
14350 }
14351 }
14352 // patchFlag & dynamicPropNames
14353 if (patchFlag !== 0) {
14354 {
14355 if (patchFlag < 0) {
14356 // special flags (negative and mutually exclusive)
14357 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14358 }
14359 else {
14360 // bitwise flags
14361 const flagNames = Object.keys(PatchFlagNames)
14362 .map(Number)
14363 .filter(n => n > 0 && patchFlag & n)
14364 .map(n => PatchFlagNames[n])
14365 .join(`, `);
14366 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14367 }
14368 }
14369 if (dynamicPropNames && dynamicPropNames.length) {
14370 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14371 }
14372 }
14373 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14374 };
14375};
14376function resolveComponentType(node, context, ssr = false) {
14377 let { tag } = node;
14378 // 1. dynamic component
14379 const isExplicitDynamic = isComponentTag(tag);
14380 const isProp = findProp(node, 'is');
14381 if (isProp) {
14382 if (isExplicitDynamic ||
14383 (false )) {
14384 const exp = isProp.type === 6 /* ATTRIBUTE */
14385 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14386 : isProp.exp;
14387 if (exp) {
14388 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14389 exp
14390 ]);
14391 }
14392 }
14393 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14394 isProp.value.content.startsWith('vue:')) {
14395 // <button is="vue:xxx">
14396 // if not <component>, only is value that starts with "vue:" will be
14397 // treated as component by the parse phase and reach here, unless it's
14398 // compat mode where all is values are considered components
14399 tag = isProp.value.content.slice(4);
14400 }
14401 }
14402 // 1.5 v-is (TODO: Deprecate)
14403 const isDir = !isExplicitDynamic && findDir(node, 'is');
14404 if (isDir && isDir.exp) {
14405 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14406 isDir.exp
14407 ]);
14408 }
14409 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14410 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14411 if (builtIn) {
14412 // built-ins are simply fallthroughs / have special handling during ssr
14413 // so we don't need to import their runtime equivalents
14414 if (!ssr)
14415 context.helper(builtIn);
14416 return builtIn;
14417 }
14418 // 5. user component (resolve)
14419 context.helper(RESOLVE_COMPONENT);
14420 context.components.add(tag);
14421 return toValidAssetId(tag, `component`);
14422}
14423function buildProps(node, context, props = node.props, ssr = false) {
14424 const { tag, loc: elementLoc, children } = node;
14425 const isComponent = node.tagType === 1 /* COMPONENT */;
14426 let properties = [];
14427 const mergeArgs = [];
14428 const runtimeDirectives = [];
14429 const hasChildren = children.length > 0;
14430 let shouldUseBlock = false;
14431 // patchFlag analysis
14432 let patchFlag = 0;
14433 let hasRef = false;
14434 let hasClassBinding = false;
14435 let hasStyleBinding = false;
14436 let hasHydrationEventBinding = false;
14437 let hasDynamicKeys = false;
14438 let hasVnodeHook = false;
14439 const dynamicPropNames = [];
14440 const analyzePatchFlag = ({ key, value }) => {
14441 if (isStaticExp(key)) {
14442 const name = key.content;
14443 const isEventHandler = isOn(name);
14444 if (!isComponent &&
14445 isEventHandler &&
14446 // omit the flag for click handlers because hydration gives click
14447 // dedicated fast path.
14448 name.toLowerCase() !== 'onclick' &&
14449 // omit v-model handlers
14450 name !== 'onUpdate:modelValue' &&
14451 // omit onVnodeXXX hooks
14452 !isReservedProp(name)) {
14453 hasHydrationEventBinding = true;
14454 }
14455 if (isEventHandler && isReservedProp(name)) {
14456 hasVnodeHook = true;
14457 }
14458 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14459 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14460 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14461 getConstantType(value, context) > 0)) {
14462 // skip if the prop is a cached handler or has constant value
14463 return;
14464 }
14465 if (name === 'ref') {
14466 hasRef = true;
14467 }
14468 else if (name === 'class') {
14469 hasClassBinding = true;
14470 }
14471 else if (name === 'style') {
14472 hasStyleBinding = true;
14473 }
14474 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14475 dynamicPropNames.push(name);
14476 }
14477 // treat the dynamic class and style binding of the component as dynamic props
14478 if (isComponent &&
14479 (name === 'class' || name === 'style') &&
14480 !dynamicPropNames.includes(name)) {
14481 dynamicPropNames.push(name);
14482 }
14483 }
14484 else {
14485 hasDynamicKeys = true;
14486 }
14487 };
14488 for (let i = 0; i < props.length; i++) {
14489 // static attribute
14490 const prop = props[i];
14491 if (prop.type === 6 /* ATTRIBUTE */) {
14492 const { loc, name, value } = prop;
14493 let isStatic = true;
14494 if (name === 'ref') {
14495 hasRef = true;
14496 if (context.scopes.vFor > 0) {
14497 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14498 }
14499 }
14500 // skip is on <component>, or is="vue:xxx"
14501 if (name === 'is' &&
14502 (isComponentTag(tag) ||
14503 (value && value.content.startsWith('vue:')) ||
14504 (false ))) {
14505 continue;
14506 }
14507 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
14508 }
14509 else {
14510 // directives
14511 const { name, arg, exp, loc } = prop;
14512 const isVBind = name === 'bind';
14513 const isVOn = name === 'on';
14514 // skip v-slot - it is handled by its dedicated transform.
14515 if (name === 'slot') {
14516 if (!isComponent) {
14517 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14518 }
14519 continue;
14520 }
14521 // skip v-once/v-memo - they are handled by dedicated transforms.
14522 if (name === 'once' || name === 'memo') {
14523 continue;
14524 }
14525 // skip v-is and :is on <component>
14526 if (name === 'is' ||
14527 (isVBind &&
14528 isStaticArgOf(arg, 'is') &&
14529 (isComponentTag(tag) ||
14530 (false )))) {
14531 continue;
14532 }
14533 // skip v-on in SSR compilation
14534 if (isVOn && ssr) {
14535 continue;
14536 }
14537 if (
14538 // #938: elements with dynamic keys should be forced into blocks
14539 (isVBind && isStaticArgOf(arg, 'key')) ||
14540 // inline before-update hooks need to force block so that it is invoked
14541 // before children
14542 (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
14543 shouldUseBlock = true;
14544 }
14545 if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
14546 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14547 }
14548 // special case for v-bind and v-on with no argument
14549 if (!arg && (isVBind || isVOn)) {
14550 hasDynamicKeys = true;
14551 if (exp) {
14552 if (properties.length) {
14553 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14554 properties = [];
14555 }
14556 if (isVBind) {
14557 mergeArgs.push(exp);
14558 }
14559 else {
14560 // v-on="obj" -> toHandlers(obj)
14561 mergeArgs.push({
14562 type: 14 /* JS_CALL_EXPRESSION */,
14563 loc,
14564 callee: context.helper(TO_HANDLERS),
14565 arguments: [exp]
14566 });
14567 }
14568 }
14569 else {
14570 context.onError(createCompilerError(isVBind
14571 ? 34 /* X_V_BIND_NO_EXPRESSION */
14572 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14573 }
14574 continue;
14575 }
14576 const directiveTransform = context.directiveTransforms[name];
14577 if (directiveTransform) {
14578 // has built-in directive transform.
14579 const { props, needRuntime } = directiveTransform(prop, node, context);
14580 !ssr && props.forEach(analyzePatchFlag);
14581 properties.push(...props);
14582 if (needRuntime) {
14583 runtimeDirectives.push(prop);
14584 if (isSymbol(needRuntime)) {
14585 directiveImportMap.set(prop, needRuntime);
14586 }
14587 }
14588 }
14589 else {
14590 // no built-in transform, this is a user custom directive.
14591 runtimeDirectives.push(prop);
14592 // custom dirs may use beforeUpdate so they need to force blocks
14593 // to ensure before-update gets called before children update
14594 if (hasChildren) {
14595 shouldUseBlock = true;
14596 }
14597 }
14598 }
14599 }
14600 let propsExpression = undefined;
14601 // has v-bind="object" or v-on="object", wrap with mergeProps
14602 if (mergeArgs.length) {
14603 if (properties.length) {
14604 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14605 }
14606 if (mergeArgs.length > 1) {
14607 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14608 }
14609 else {
14610 // single v-bind with nothing else - no need for a mergeProps call
14611 propsExpression = mergeArgs[0];
14612 }
14613 }
14614 else if (properties.length) {
14615 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14616 }
14617 // patchFlag analysis
14618 if (hasDynamicKeys) {
14619 patchFlag |= 16 /* FULL_PROPS */;
14620 }
14621 else {
14622 if (hasClassBinding && !isComponent) {
14623 patchFlag |= 2 /* CLASS */;
14624 }
14625 if (hasStyleBinding && !isComponent) {
14626 patchFlag |= 4 /* STYLE */;
14627 }
14628 if (dynamicPropNames.length) {
14629 patchFlag |= 8 /* PROPS */;
14630 }
14631 if (hasHydrationEventBinding) {
14632 patchFlag |= 32 /* HYDRATE_EVENTS */;
14633 }
14634 }
14635 if (!shouldUseBlock &&
14636 (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14637 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14638 patchFlag |= 512 /* NEED_PATCH */;
14639 }
14640 // pre-normalize props, SSR is skipped for now
14641 if (!context.inSSR && propsExpression) {
14642 switch (propsExpression.type) {
14643 case 15 /* JS_OBJECT_EXPRESSION */:
14644 // means that there is no v-bind,
14645 // but still need to deal with dynamic key binding
14646 let classKeyIndex = -1;
14647 let styleKeyIndex = -1;
14648 let hasDynamicKey = false;
14649 for (let i = 0; i < propsExpression.properties.length; i++) {
14650 const key = propsExpression.properties[i].key;
14651 if (isStaticExp(key)) {
14652 if (key.content === 'class') {
14653 classKeyIndex = i;
14654 }
14655 else if (key.content === 'style') {
14656 styleKeyIndex = i;
14657 }
14658 }
14659 else if (!key.isHandlerKey) {
14660 hasDynamicKey = true;
14661 }
14662 }
14663 const classProp = propsExpression.properties[classKeyIndex];
14664 const styleProp = propsExpression.properties[styleKeyIndex];
14665 // no dynamic key
14666 if (!hasDynamicKey) {
14667 if (classProp && !isStaticExp(classProp.value)) {
14668 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14669 }
14670 if (styleProp &&
14671 !isStaticExp(styleProp.value) &&
14672 // the static style is compiled into an object,
14673 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14674 (hasStyleBinding ||
14675 // v-bind:style and style both exist,
14676 // v-bind:style with static literal object
14677 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14678 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14679 }
14680 }
14681 else {
14682 // dynamic key binding, wrap with `normalizeProps`
14683 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14684 }
14685 break;
14686 case 14 /* JS_CALL_EXPRESSION */:
14687 // mergeProps call, do nothing
14688 break;
14689 default:
14690 // single v-bind
14691 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14692 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14693 propsExpression
14694 ])
14695 ]);
14696 break;
14697 }
14698 }
14699 return {
14700 props: propsExpression,
14701 directives: runtimeDirectives,
14702 patchFlag,
14703 dynamicPropNames,
14704 shouldUseBlock
14705 };
14706}
14707// Dedupe props in an object literal.
14708// Literal duplicated attributes would have been warned during the parse phase,
14709// however, it's possible to encounter duplicated `onXXX` handlers with different
14710// modifiers. We also need to merge static and dynamic class / style attributes.
14711// - onXXX handlers / style: merge into array
14712// - class: merge into single expression with concatenation
14713function dedupeProperties(properties) {
14714 const knownProps = new Map();
14715 const deduped = [];
14716 for (let i = 0; i < properties.length; i++) {
14717 const prop = properties[i];
14718 // dynamic keys are always allowed
14719 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14720 deduped.push(prop);
14721 continue;
14722 }
14723 const name = prop.key.content;
14724 const existing = knownProps.get(name);
14725 if (existing) {
14726 if (name === 'style' || name === 'class' || isOn(name)) {
14727 mergeAsArray$1(existing, prop);
14728 }
14729 // unexpected duplicate, should have emitted error during parse
14730 }
14731 else {
14732 knownProps.set(name, prop);
14733 deduped.push(prop);
14734 }
14735 }
14736 return deduped;
14737}
14738function mergeAsArray$1(existing, incoming) {
14739 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14740 existing.value.elements.push(incoming.value);
14741 }
14742 else {
14743 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14744 }
14745}
14746function buildDirectiveArgs(dir, context) {
14747 const dirArgs = [];
14748 const runtime = directiveImportMap.get(dir);
14749 if (runtime) {
14750 // built-in directive with runtime
14751 dirArgs.push(context.helperString(runtime));
14752 }
14753 else {
14754 {
14755 // inject statement for resolving directive
14756 context.helper(RESOLVE_DIRECTIVE);
14757 context.directives.add(dir.name);
14758 dirArgs.push(toValidAssetId(dir.name, `directive`));
14759 }
14760 }
14761 const { loc } = dir;
14762 if (dir.exp)
14763 dirArgs.push(dir.exp);
14764 if (dir.arg) {
14765 if (!dir.exp) {
14766 dirArgs.push(`void 0`);
14767 }
14768 dirArgs.push(dir.arg);
14769 }
14770 if (Object.keys(dir.modifiers).length) {
14771 if (!dir.arg) {
14772 if (!dir.exp) {
14773 dirArgs.push(`void 0`);
14774 }
14775 dirArgs.push(`void 0`);
14776 }
14777 const trueExpression = createSimpleExpression(`true`, false, loc);
14778 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14779 }
14780 return createArrayExpression(dirArgs, dir.loc);
14781}
14782function stringifyDynamicPropNames(props) {
14783 let propsNamesString = `[`;
14784 for (let i = 0, l = props.length; i < l; i++) {
14785 propsNamesString += JSON.stringify(props[i]);
14786 if (i < l - 1)
14787 propsNamesString += ', ';
14788 }
14789 return propsNamesString + `]`;
14790}
14791function isComponentTag(tag) {
14792 return tag === 'component' || tag === 'Component';
14793}
14794
14795const transformSlotOutlet = (node, context) => {
14796 if (isSlotOutlet(node)) {
14797 const { children, loc } = node;
14798 const { slotName, slotProps } = processSlotOutlet(node, context);
14799 const slotArgs = [
14800 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14801 slotName,
14802 '{}',
14803 'undefined',
14804 'true'
14805 ];
14806 let expectedLen = 2;
14807 if (slotProps) {
14808 slotArgs[2] = slotProps;
14809 expectedLen = 3;
14810 }
14811 if (children.length) {
14812 slotArgs[3] = createFunctionExpression([], children, false, false, loc);
14813 expectedLen = 4;
14814 }
14815 if (context.scopeId && !context.slotted) {
14816 expectedLen = 5;
14817 }
14818 slotArgs.splice(expectedLen); // remove unused arguments
14819 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14820 }
14821};
14822function processSlotOutlet(node, context) {
14823 let slotName = `"default"`;
14824 let slotProps = undefined;
14825 const nonNameProps = [];
14826 for (let i = 0; i < node.props.length; i++) {
14827 const p = node.props[i];
14828 if (p.type === 6 /* ATTRIBUTE */) {
14829 if (p.value) {
14830 if (p.name === 'name') {
14831 slotName = JSON.stringify(p.value.content);
14832 }
14833 else {
14834 p.name = camelize(p.name);
14835 nonNameProps.push(p);
14836 }
14837 }
14838 }
14839 else {
14840 if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
14841 if (p.exp)
14842 slotName = p.exp;
14843 }
14844 else {
14845 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14846 p.arg.content = camelize(p.arg.content);
14847 }
14848 nonNameProps.push(p);
14849 }
14850 }
14851 }
14852 if (nonNameProps.length > 0) {
14853 const { props, directives } = buildProps(node, context, nonNameProps);
14854 slotProps = props;
14855 if (directives.length) {
14856 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14857 }
14858 }
14859 return {
14860 slotName,
14861 slotProps
14862 };
14863}
14864
14865const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
14866const transformOn = (dir, node, context, augmentor) => {
14867 const { loc, modifiers, arg } = dir;
14868 if (!dir.exp && !modifiers.length) {
14869 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
14870 }
14871 let eventName;
14872 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14873 if (arg.isStatic) {
14874 let rawName = arg.content;
14875 // TODO deprecate @vnodeXXX usage
14876 if (rawName.startsWith('vue:')) {
14877 rawName = `vnode-${rawName.slice(4)}`;
14878 }
14879 // for all event listeners, auto convert it to camelCase. See issue #2249
14880 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
14881 }
14882 else {
14883 // #2388
14884 eventName = createCompoundExpression([
14885 `${context.helperString(TO_HANDLER_KEY)}(`,
14886 arg,
14887 `)`
14888 ]);
14889 }
14890 }
14891 else {
14892 // already a compound expression.
14893 eventName = arg;
14894 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
14895 eventName.children.push(`)`);
14896 }
14897 // handler processing
14898 let exp = dir.exp;
14899 if (exp && !exp.content.trim()) {
14900 exp = undefined;
14901 }
14902 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
14903 if (exp) {
14904 const isMemberExp = isMemberExpression(exp.content);
14905 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
14906 const hasMultipleStatements = exp.content.includes(`;`);
14907 {
14908 validateBrowserExpression(exp, context, false, hasMultipleStatements);
14909 }
14910 if (isInlineStatement || (shouldCache && isMemberExp)) {
14911 // wrap inline statement in a function expression
14912 exp = createCompoundExpression([
14913 `${isInlineStatement
14914 ? `$event`
14915 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
14916 exp,
14917 hasMultipleStatements ? `}` : `)`
14918 ]);
14919 }
14920 }
14921 let ret = {
14922 props: [
14923 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
14924 ]
14925 };
14926 // apply extended compiler augmentor
14927 if (augmentor) {
14928 ret = augmentor(ret);
14929 }
14930 if (shouldCache) {
14931 // cache handlers so that it's always the same handler being passed down.
14932 // this avoids unnecessary re-renders when users use inline handlers on
14933 // components.
14934 ret.props[0].value = context.cache(ret.props[0].value);
14935 }
14936 // mark the key as handler for props normalization check
14937 ret.props.forEach(p => (p.key.isHandlerKey = true));
14938 return ret;
14939};
14940
14941// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
14942// codegen for the entire props object. This transform here is only for v-bind
14943// *with* args.
14944const transformBind = (dir, _node, context) => {
14945 const { exp, modifiers, loc } = dir;
14946 const arg = dir.arg;
14947 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
14948 arg.children.unshift(`(`);
14949 arg.children.push(`) || ""`);
14950 }
14951 else if (!arg.isStatic) {
14952 arg.content = `${arg.content} || ""`;
14953 }
14954 // .sync is replaced by v-model:arg
14955 if (modifiers.includes('camel')) {
14956 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14957 if (arg.isStatic) {
14958 arg.content = camelize(arg.content);
14959 }
14960 else {
14961 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
14962 }
14963 }
14964 else {
14965 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
14966 arg.children.push(`)`);
14967 }
14968 }
14969 if (!context.inSSR) {
14970 if (modifiers.includes('prop')) {
14971 injectPrefix(arg, '.');
14972 }
14973 if (modifiers.includes('attr')) {
14974 injectPrefix(arg, '^');
14975 }
14976 }
14977 if (!exp ||
14978 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
14979 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
14980 return {
14981 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
14982 };
14983 }
14984 return {
14985 props: [createObjectProperty(arg, exp)]
14986 };
14987};
14988const injectPrefix = (arg, prefix) => {
14989 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14990 if (arg.isStatic) {
14991 arg.content = prefix + arg.content;
14992 }
14993 else {
14994 arg.content = `\`${prefix}\${${arg.content}}\``;
14995 }
14996 }
14997 else {
14998 arg.children.unshift(`'${prefix}' + (`);
14999 arg.children.push(`)`);
15000 }
15001};
15002
15003// Merge adjacent text nodes and expressions into a single expression
15004// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15005const transformText = (node, context) => {
15006 if (node.type === 0 /* ROOT */ ||
15007 node.type === 1 /* ELEMENT */ ||
15008 node.type === 11 /* FOR */ ||
15009 node.type === 10 /* IF_BRANCH */) {
15010 // perform the transform on node exit so that all expressions have already
15011 // been processed.
15012 return () => {
15013 const children = node.children;
15014 let currentContainer = undefined;
15015 let hasText = false;
15016 for (let i = 0; i < children.length; i++) {
15017 const child = children[i];
15018 if (isText(child)) {
15019 hasText = true;
15020 for (let j = i + 1; j < children.length; j++) {
15021 const next = children[j];
15022 if (isText(next)) {
15023 if (!currentContainer) {
15024 currentContainer = children[i] = {
15025 type: 8 /* COMPOUND_EXPRESSION */,
15026 loc: child.loc,
15027 children: [child]
15028 };
15029 }
15030 // merge adjacent text node into current
15031 currentContainer.children.push(` + `, next);
15032 children.splice(j, 1);
15033 j--;
15034 }
15035 else {
15036 currentContainer = undefined;
15037 break;
15038 }
15039 }
15040 }
15041 }
15042 if (!hasText ||
15043 // if this is a plain element with a single text child, leave it
15044 // as-is since the runtime has dedicated fast path for this by directly
15045 // setting textContent of the element.
15046 // for component root it's always normalized anyway.
15047 (children.length === 1 &&
15048 (node.type === 0 /* ROOT */ ||
15049 (node.type === 1 /* ELEMENT */ &&
15050 node.tagType === 0 /* ELEMENT */ &&
15051 // #3756
15052 // custom directives can potentially add DOM elements arbitrarily,
15053 // we need to avoid setting textContent of the element at runtime
15054 // to avoid accidentally overwriting the DOM elements added
15055 // by the user through custom directives.
15056 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15057 !context.directiveTransforms[p.name]) &&
15058 // in compat mode, <template> tags with no special directives
15059 // will be rendered as a fragment so its children must be
15060 // converted into vnodes.
15061 !(false ))))) {
15062 return;
15063 }
15064 // pre-convert text nodes into createTextVNode(text) calls to avoid
15065 // runtime normalization.
15066 for (let i = 0; i < children.length; i++) {
15067 const child = children[i];
15068 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15069 const callArgs = [];
15070 // createTextVNode defaults to single whitespace, so if it is a
15071 // single space the code could be an empty call to save bytes.
15072 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15073 callArgs.push(child);
15074 }
15075 // mark dynamic text with flag so it gets patched inside a block
15076 if (!context.ssr &&
15077 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15078 callArgs.push(1 /* TEXT */ +
15079 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15080 }
15081 children[i] = {
15082 type: 12 /* TEXT_CALL */,
15083 content: child,
15084 loc: child.loc,
15085 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15086 };
15087 }
15088 }
15089 };
15090 }
15091};
15092
15093const seen = new WeakSet();
15094const transformOnce = (node, context) => {
15095 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15096 if (seen.has(node) || context.inVOnce) {
15097 return;
15098 }
15099 seen.add(node);
15100 context.inVOnce = true;
15101 context.helper(SET_BLOCK_TRACKING);
15102 return () => {
15103 context.inVOnce = false;
15104 const cur = context.currentNode;
15105 if (cur.codegenNode) {
15106 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15107 }
15108 };
15109 }
15110};
15111
15112const transformModel = (dir, node, context) => {
15113 const { exp, arg } = dir;
15114 if (!exp) {
15115 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15116 return createTransformProps();
15117 }
15118 const rawExp = exp.loc.source;
15119 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15120 // im SFC <script setup> inline mode, the exp may have been transformed into
15121 // _unref(exp)
15122 context.bindingMetadata[rawExp];
15123 const maybeRef = !true /* SETUP_CONST */;
15124 if (!expString.trim() ||
15125 (!isMemberExpression(expString) && !maybeRef)) {
15126 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15127 return createTransformProps();
15128 }
15129 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15130 const eventName = arg
15131 ? isStaticExp(arg)
15132 ? `onUpdate:${arg.content}`
15133 : createCompoundExpression(['"onUpdate:" + ', arg])
15134 : `onUpdate:modelValue`;
15135 let assignmentExp;
15136 const eventArg = context.isTS ? `($event: any)` : `$event`;
15137 {
15138 assignmentExp = createCompoundExpression([
15139 `${eventArg} => ((`,
15140 exp,
15141 `) = $event)`
15142 ]);
15143 }
15144 const props = [
15145 // modelValue: foo
15146 createObjectProperty(propName, dir.exp),
15147 // "onUpdate:modelValue": $event => (foo = $event)
15148 createObjectProperty(eventName, assignmentExp)
15149 ];
15150 // modelModifiers: { foo: true, "bar-baz": true }
15151 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15152 const modifiers = dir.modifiers
15153 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15154 .join(`, `);
15155 const modifiersKey = arg
15156 ? isStaticExp(arg)
15157 ? `${arg.content}Modifiers`
15158 : createCompoundExpression([arg, ' + "Modifiers"'])
15159 : `modelModifiers`;
15160 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15161 }
15162 return createTransformProps(props);
15163};
15164function createTransformProps(props = []) {
15165 return { props };
15166}
15167
15168const seen$1 = new WeakSet();
15169const transformMemo = (node, context) => {
15170 if (node.type === 1 /* ELEMENT */) {
15171 const dir = findDir(node, 'memo');
15172 if (!dir || seen$1.has(node)) {
15173 return;
15174 }
15175 seen$1.add(node);
15176 return () => {
15177 const codegenNode = node.codegenNode ||
15178 context.currentNode.codegenNode;
15179 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15180 // non-component sub tree should be turned into a block
15181 if (node.tagType !== 1 /* COMPONENT */) {
15182 makeBlock(codegenNode, context);
15183 }
15184 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15185 dir.exp,
15186 createFunctionExpression(undefined, codegenNode),
15187 `_cache`,
15188 String(context.cached++)
15189 ]);
15190 }
15191 };
15192 }
15193};
15194
15195function getBaseTransformPreset(prefixIdentifiers) {
15196 return [
15197 [
15198 transformOnce,
15199 transformIf,
15200 transformMemo,
15201 transformFor,
15202 ...([]),
15203 ...([transformExpression]
15204 ),
15205 transformSlotOutlet,
15206 transformElement,
15207 trackSlotScopes,
15208 transformText
15209 ],
15210 {
15211 on: transformOn,
15212 bind: transformBind,
15213 model: transformModel
15214 }
15215 ];
15216}
15217// we name it `baseCompile` so that higher order compilers like
15218// @vue/compiler-dom can export `compile` while re-exporting everything else.
15219function baseCompile(template, options = {}) {
15220 const onError = options.onError || defaultOnError;
15221 const isModuleMode = options.mode === 'module';
15222 /* istanbul ignore if */
15223 {
15224 if (options.prefixIdentifiers === true) {
15225 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15226 }
15227 else if (isModuleMode) {
15228 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15229 }
15230 }
15231 const prefixIdentifiers = !true ;
15232 if (options.cacheHandlers) {
15233 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15234 }
15235 if (options.scopeId && !isModuleMode) {
15236 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15237 }
15238 const ast = isString(template) ? baseParse(template, options) : template;
15239 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15240 transform(ast, extend({}, options, {
15241 prefixIdentifiers,
15242 nodeTransforms: [
15243 ...nodeTransforms,
15244 ...(options.nodeTransforms || []) // user transforms
15245 ],
15246 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15247 )
15248 }));
15249 return generate(ast, extend({}, options, {
15250 prefixIdentifiers
15251 }));
15252}
15253
15254const noopDirectiveTransform = () => ({ props: [] });
15255
15256const V_MODEL_RADIO = Symbol(`vModelRadio` );
15257const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15258const V_MODEL_TEXT = Symbol(`vModelText` );
15259const V_MODEL_SELECT = Symbol(`vModelSelect` );
15260const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15261const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15262const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15263const V_SHOW = Symbol(`vShow` );
15264const TRANSITION$1 = Symbol(`Transition` );
15265const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15266registerRuntimeHelpers({
15267 [V_MODEL_RADIO]: `vModelRadio`,
15268 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15269 [V_MODEL_TEXT]: `vModelText`,
15270 [V_MODEL_SELECT]: `vModelSelect`,
15271 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15272 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15273 [V_ON_WITH_KEYS]: `withKeys`,
15274 [V_SHOW]: `vShow`,
15275 [TRANSITION$1]: `Transition`,
15276 [TRANSITION_GROUP]: `TransitionGroup`
15277});
15278
15279/* eslint-disable no-restricted-globals */
15280let decoder;
15281function decodeHtmlBrowser(raw, asAttr = false) {
15282 if (!decoder) {
15283 decoder = document.createElement('div');
15284 }
15285 if (asAttr) {
15286 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15287 return decoder.children[0].getAttribute('foo');
15288 }
15289 else {
15290 decoder.innerHTML = raw;
15291 return decoder.textContent;
15292 }
15293}
15294
15295const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15296const parserOptions = {
15297 isVoidTag,
15298 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15299 isPreTag: tag => tag === 'pre',
15300 decodeEntities: decodeHtmlBrowser ,
15301 isBuiltInComponent: (tag) => {
15302 if (isBuiltInType(tag, `Transition`)) {
15303 return TRANSITION$1;
15304 }
15305 else if (isBuiltInType(tag, `TransitionGroup`)) {
15306 return TRANSITION_GROUP;
15307 }
15308 },
15309 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15310 getNamespace(tag, parent) {
15311 let ns = parent ? parent.ns : 0 /* HTML */;
15312 if (parent && ns === 2 /* MATH_ML */) {
15313 if (parent.tag === 'annotation-xml') {
15314 if (tag === 'svg') {
15315 return 1 /* SVG */;
15316 }
15317 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15318 a.name === 'encoding' &&
15319 a.value != null &&
15320 (a.value.content === 'text/html' ||
15321 a.value.content === 'application/xhtml+xml'))) {
15322 ns = 0 /* HTML */;
15323 }
15324 }
15325 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15326 tag !== 'mglyph' &&
15327 tag !== 'malignmark') {
15328 ns = 0 /* HTML */;
15329 }
15330 }
15331 else if (parent && ns === 1 /* SVG */) {
15332 if (parent.tag === 'foreignObject' ||
15333 parent.tag === 'desc' ||
15334 parent.tag === 'title') {
15335 ns = 0 /* HTML */;
15336 }
15337 }
15338 if (ns === 0 /* HTML */) {
15339 if (tag === 'svg') {
15340 return 1 /* SVG */;
15341 }
15342 if (tag === 'math') {
15343 return 2 /* MATH_ML */;
15344 }
15345 }
15346 return ns;
15347 },
15348 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15349 getTextMode({ tag, ns }) {
15350 if (ns === 0 /* HTML */) {
15351 if (tag === 'textarea' || tag === 'title') {
15352 return 1 /* RCDATA */;
15353 }
15354 if (isRawTextContainer(tag)) {
15355 return 2 /* RAWTEXT */;
15356 }
15357 }
15358 return 0 /* DATA */;
15359 }
15360};
15361
15362// Parse inline CSS strings for static style attributes into an object.
15363// This is a NodeTransform since it works on the static `style` attribute and
15364// converts it into a dynamic equivalent:
15365// style="color: red" -> :style='{ "color": "red" }'
15366// It is then processed by `transformElement` and included in the generated
15367// props.
15368const transformStyle = node => {
15369 if (node.type === 1 /* ELEMENT */) {
15370 node.props.forEach((p, i) => {
15371 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15372 // replace p with an expression node
15373 node.props[i] = {
15374 type: 7 /* DIRECTIVE */,
15375 name: `bind`,
15376 arg: createSimpleExpression(`style`, true, p.loc),
15377 exp: parseInlineCSS(p.value.content, p.loc),
15378 modifiers: [],
15379 loc: p.loc
15380 };
15381 }
15382 });
15383 }
15384};
15385const parseInlineCSS = (cssText, loc) => {
15386 const normalized = parseStringStyle(cssText);
15387 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15388};
15389
15390function createDOMCompilerError(code, loc) {
15391 return createCompilerError(code, loc, DOMErrorMessages );
15392}
15393const DOMErrorMessages = {
15394 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15395 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15396 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15397 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15398 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15399 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15400 [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.`,
15401 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15402 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15403 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15404 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15405};
15406
15407const transformVHtml = (dir, node, context) => {
15408 const { exp, loc } = dir;
15409 if (!exp) {
15410 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15411 }
15412 if (node.children.length) {
15413 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15414 node.children.length = 0;
15415 }
15416 return {
15417 props: [
15418 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15419 ]
15420 };
15421};
15422
15423const transformVText = (dir, node, context) => {
15424 const { exp, loc } = dir;
15425 if (!exp) {
15426 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15427 }
15428 if (node.children.length) {
15429 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15430 node.children.length = 0;
15431 }
15432 return {
15433 props: [
15434 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15435 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15436 : createSimpleExpression('', true))
15437 ]
15438 };
15439};
15440
15441const transformModel$1 = (dir, node, context) => {
15442 const baseResult = transformModel(dir, node, context);
15443 // base transform has errors OR component v-model (only need props)
15444 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15445 return baseResult;
15446 }
15447 if (dir.arg) {
15448 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15449 }
15450 function checkDuplicatedValue() {
15451 const value = findProp(node, 'value');
15452 if (value) {
15453 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15454 }
15455 }
15456 const { tag } = node;
15457 const isCustomElement = context.isCustomElement(tag);
15458 if (tag === 'input' ||
15459 tag === 'textarea' ||
15460 tag === 'select' ||
15461 isCustomElement) {
15462 let directiveToUse = V_MODEL_TEXT;
15463 let isInvalidType = false;
15464 if (tag === 'input' || isCustomElement) {
15465 const type = findProp(node, `type`);
15466 if (type) {
15467 if (type.type === 7 /* DIRECTIVE */) {
15468 // :type="foo"
15469 directiveToUse = V_MODEL_DYNAMIC;
15470 }
15471 else if (type.value) {
15472 switch (type.value.content) {
15473 case 'radio':
15474 directiveToUse = V_MODEL_RADIO;
15475 break;
15476 case 'checkbox':
15477 directiveToUse = V_MODEL_CHECKBOX;
15478 break;
15479 case 'file':
15480 isInvalidType = true;
15481 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15482 break;
15483 default:
15484 // text type
15485 checkDuplicatedValue();
15486 break;
15487 }
15488 }
15489 }
15490 else if (hasDynamicKeyVBind(node)) {
15491 // element has bindings with dynamic keys, which can possibly contain
15492 // "type".
15493 directiveToUse = V_MODEL_DYNAMIC;
15494 }
15495 else {
15496 // text type
15497 checkDuplicatedValue();
15498 }
15499 }
15500 else if (tag === 'select') {
15501 directiveToUse = V_MODEL_SELECT;
15502 }
15503 else {
15504 // textarea
15505 checkDuplicatedValue();
15506 }
15507 // inject runtime directive
15508 // by returning the helper symbol via needRuntime
15509 // the import will replaced a resolveDirective call.
15510 if (!isInvalidType) {
15511 baseResult.needRuntime = context.helper(directiveToUse);
15512 }
15513 }
15514 else {
15515 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15516 }
15517 // native vmodel doesn't need the `modelValue` props since they are also
15518 // passed to the runtime as `binding.value`. removing it reduces code size.
15519 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15520 p.key.content === 'modelValue'));
15521 return baseResult;
15522};
15523
15524const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15525const isNonKeyModifier = /*#__PURE__*/ makeMap(
15526// event propagation management
15527`stop,prevent,self,` +
15528 // system modifiers + exact
15529 `ctrl,shift,alt,meta,exact,` +
15530 // mouse
15531 `middle`);
15532// left & right could be mouse or key modifiers based on event type
15533const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15534const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15535const resolveModifiers = (key, modifiers, context, loc) => {
15536 const keyModifiers = [];
15537 const nonKeyModifiers = [];
15538 const eventOptionModifiers = [];
15539 for (let i = 0; i < modifiers.length; i++) {
15540 const modifier = modifiers[i];
15541 if (isEventOptionModifier(modifier)) {
15542 // eventOptionModifiers: modifiers for addEventListener() options,
15543 // e.g. .passive & .capture
15544 eventOptionModifiers.push(modifier);
15545 }
15546 else {
15547 // runtimeModifiers: modifiers that needs runtime guards
15548 if (maybeKeyModifier(modifier)) {
15549 if (isStaticExp(key)) {
15550 if (isKeyboardEvent(key.content)) {
15551 keyModifiers.push(modifier);
15552 }
15553 else {
15554 nonKeyModifiers.push(modifier);
15555 }
15556 }
15557 else {
15558 keyModifiers.push(modifier);
15559 nonKeyModifiers.push(modifier);
15560 }
15561 }
15562 else {
15563 if (isNonKeyModifier(modifier)) {
15564 nonKeyModifiers.push(modifier);
15565 }
15566 else {
15567 keyModifiers.push(modifier);
15568 }
15569 }
15570 }
15571 }
15572 return {
15573 keyModifiers,
15574 nonKeyModifiers,
15575 eventOptionModifiers
15576 };
15577};
15578const transformClick = (key, event) => {
15579 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15580 return isStaticClick
15581 ? createSimpleExpression(event, true)
15582 : key.type !== 4 /* SIMPLE_EXPRESSION */
15583 ? createCompoundExpression([
15584 `(`,
15585 key,
15586 `) === "onClick" ? "${event}" : (`,
15587 key,
15588 `)`
15589 ])
15590 : key;
15591};
15592const transformOn$1 = (dir, node, context) => {
15593 return transformOn(dir, node, context, baseResult => {
15594 const { modifiers } = dir;
15595 if (!modifiers.length)
15596 return baseResult;
15597 let { key, value: handlerExp } = baseResult.props[0];
15598 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15599 // normalize click.right and click.middle since they don't actually fire
15600 if (nonKeyModifiers.includes('right')) {
15601 key = transformClick(key, `onContextmenu`);
15602 }
15603 if (nonKeyModifiers.includes('middle')) {
15604 key = transformClick(key, `onMouseup`);
15605 }
15606 if (nonKeyModifiers.length) {
15607 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15608 handlerExp,
15609 JSON.stringify(nonKeyModifiers)
15610 ]);
15611 }
15612 if (keyModifiers.length &&
15613 // if event name is dynamic, always wrap with keys guard
15614 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15615 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15616 handlerExp,
15617 JSON.stringify(keyModifiers)
15618 ]);
15619 }
15620 if (eventOptionModifiers.length) {
15621 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15622 key = isStaticExp(key)
15623 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15624 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15625 }
15626 return {
15627 props: [createObjectProperty(key, handlerExp)]
15628 };
15629 });
15630};
15631
15632const transformShow = (dir, node, context) => {
15633 const { exp, loc } = dir;
15634 if (!exp) {
15635 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15636 }
15637 return {
15638 props: [],
15639 needRuntime: context.helper(V_SHOW)
15640 };
15641};
15642
15643const warnTransitionChildren = (node, context) => {
15644 if (node.type === 1 /* ELEMENT */ &&
15645 node.tagType === 1 /* COMPONENT */) {
15646 const component = context.isBuiltInComponent(node.tag);
15647 if (component === TRANSITION$1) {
15648 return () => {
15649 if (node.children.length && hasMultipleChildren(node)) {
15650 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15651 start: node.children[0].loc.start,
15652 end: node.children[node.children.length - 1].loc.end,
15653 source: ''
15654 }));
15655 }
15656 };
15657 }
15658 }
15659};
15660function hasMultipleChildren(node) {
15661 // #1352 filter out potential comment nodes.
15662 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
15663 !(c.type === 2 /* TEXT */ && !c.content.trim())));
15664 const child = children[0];
15665 return (children.length !== 1 ||
15666 child.type === 11 /* FOR */ ||
15667 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15668}
15669
15670const ignoreSideEffectTags = (node, context) => {
15671 if (node.type === 1 /* ELEMENT */ &&
15672 node.tagType === 0 /* ELEMENT */ &&
15673 (node.tag === 'script' || node.tag === 'style')) {
15674 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15675 context.removeNode();
15676 }
15677};
15678
15679const DOMNodeTransforms = [
15680 transformStyle,
15681 ...([warnTransitionChildren] )
15682];
15683const DOMDirectiveTransforms = {
15684 cloak: noopDirectiveTransform,
15685 html: transformVHtml,
15686 text: transformVText,
15687 model: transformModel$1,
15688 on: transformOn$1,
15689 show: transformShow
15690};
15691function compile$1(template, options = {}) {
15692 return baseCompile(template, extend({}, parserOptions, options, {
15693 nodeTransforms: [
15694 // ignore <script> and <tag>
15695 // this is not put inside DOMNodeTransforms because that list is used
15696 // by compiler-ssr to generate vnode fallback branches
15697 ignoreSideEffectTags,
15698 ...DOMNodeTransforms,
15699 ...(options.nodeTransforms || [])
15700 ],
15701 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15702 transformHoist: null
15703 }));
15704}
15705
15706// This entry is the "full-build" that includes both the runtime
15707{
15708 initDev();
15709}
15710const compileCache = Object.create(null);
15711function compileToFunction(template, options) {
15712 if (!isString(template)) {
15713 if (template.nodeType) {
15714 template = template.innerHTML;
15715 }
15716 else {
15717 warn$1(`invalid template option: `, template);
15718 return NOOP;
15719 }
15720 }
15721 const key = template;
15722 const cached = compileCache[key];
15723 if (cached) {
15724 return cached;
15725 }
15726 if (template[0] === '#') {
15727 const el = document.querySelector(template);
15728 if (!el) {
15729 warn$1(`Template element not found or is empty: ${template}`);
15730 }
15731 // __UNSAFE__
15732 // Reason: potential execution of JS expressions in in-DOM template.
15733 // The user must make sure the in-DOM template is trusted. If it's rendered
15734 // by the server, the template should not contain any user data.
15735 template = el ? el.innerHTML : ``;
15736 }
15737 const { code } = compile$1(template, extend({
15738 hoistStatic: true,
15739 onError: onError ,
15740 onWarn: e => onError(e, true)
15741 }, options));
15742 function onError(err, asWarning = false) {
15743 const message = asWarning
15744 ? err.message
15745 : `Template compilation error: ${err.message}`;
15746 const codeFrame = err.loc &&
15747 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15748 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15749 }
15750 // The wildcard import results in a huge object with every export
15751 // with keys that cannot be mangled, and can be quite heavy size-wise.
15752 // In the global build we know `Vue` is available globally so we can avoid
15753 // the wildcard object.
15754 const render = (new Function('Vue', code)(runtimeDom));
15755 render._rc = true;
15756 return (compileCache[key] = render);
15757}
15758registerRuntimeCompiler(compileToFunction);
15759
15760export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed$1 as computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createPropsRestProxy, 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, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, 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 };