UNPKG

610 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 /* PatchFlags.TEXT */]: `TEXT`,
22 [2 /* PatchFlags.CLASS */]: `CLASS`,
23 [4 /* PatchFlags.STYLE */]: `STYLE`,
24 [8 /* PatchFlags.PROPS */]: `PROPS`,
25 [16 /* PatchFlags.FULL_PROPS */]: `FULL_PROPS`,
26 [32 /* PatchFlags.HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
27 [64 /* PatchFlags.STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
28 [128 /* PatchFlags.KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
29 [256 /* PatchFlags.UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
30 [512 /* PatchFlags.NEED_PATCH */]: `NEED_PATCH`,
31 [1024 /* PatchFlags.DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
32 [2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
33 [-1 /* PatchFlags.HOISTED */]: `HOISTED`,
34 [-2 /* PatchFlags.BAIL */]: `BAIL`
35};
36
37/**
38 * Dev only
39 */
40const slotFlagsText = {
41 [1 /* SlotFlags.STABLE */]: 'STABLE',
42 [2 /* SlotFlags.DYNAMIC */]: 'DYNAMIC',
43 [3 /* SlotFlags.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
95function normalizeStyle(value) {
96 if (isArray(value)) {
97 const res = {};
98 for (let i = 0; i < value.length; i++) {
99 const item = value[i];
100 const normalized = isString(item)
101 ? parseStringStyle(item)
102 : normalizeStyle(item);
103 if (normalized) {
104 for (const key in normalized) {
105 res[key] = normalized[key];
106 }
107 }
108 }
109 return res;
110 }
111 else if (isString(value)) {
112 return value;
113 }
114 else if (isObject(value)) {
115 return value;
116 }
117}
118const listDelimiterRE = /;(?![^(]*\))/g;
119const propertyDelimiterRE = /:([^]+)/;
120const styleCommentRE = /\/\*.*?\*\//gs;
121function parseStringStyle(cssText) {
122 const ret = {};
123 cssText
124 .replace(styleCommentRE, '')
125 .split(listDelimiterRE)
126 .forEach(item => {
127 if (item) {
128 const tmp = item.split(propertyDelimiterRE);
129 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
130 }
131 });
132 return ret;
133}
134function normalizeClass(value) {
135 let res = '';
136 if (isString(value)) {
137 res = value;
138 }
139 else if (isArray(value)) {
140 for (let i = 0; i < value.length; i++) {
141 const normalized = normalizeClass(value[i]);
142 if (normalized) {
143 res += normalized + ' ';
144 }
145 }
146 }
147 else if (isObject(value)) {
148 for (const name in value) {
149 if (value[name]) {
150 res += name + ' ';
151 }
152 }
153 }
154 return res.trim();
155}
156function normalizeProps(props) {
157 if (!props)
158 return null;
159 let { class: klass, style } = props;
160 if (klass && !isString(klass)) {
161 props.class = normalizeClass(klass);
162 }
163 if (style) {
164 props.style = normalizeStyle(style);
165 }
166 return props;
167}
168
169// These tag configs are shared between compiler-dom and runtime-dom, so they
170// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
171const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
172 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
173 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
174 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
175 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
176 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
177 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
178 'option,output,progress,select,textarea,details,dialog,menu,' +
179 'summary,template,blockquote,iframe,tfoot';
180// https://developer.mozilla.org/en-US/docs/Web/SVG/Element
181const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
182 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
183 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
184 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
185 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
186 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
187 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
188 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
189 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
190 'text,textPath,title,tspan,unknown,use,view';
191const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
192/**
193 * Compiler only.
194 * Do NOT use in runtime code paths unless behind `true` flag.
195 */
196const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
197/**
198 * Compiler only.
199 * Do NOT use in runtime code paths unless behind `true` flag.
200 */
201const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
202/**
203 * Compiler only.
204 * Do NOT use in runtime code paths unless behind `true` flag.
205 */
206const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
207
208/**
209 * On the client we only need to offer special cases for boolean attributes that
210 * have different names from their corresponding dom properties:
211 * - itemscope -> N/A
212 * - allowfullscreen -> allowFullscreen
213 * - formnovalidate -> formNoValidate
214 * - ismap -> isMap
215 * - nomodule -> noModule
216 * - novalidate -> noValidate
217 * - readonly -> readOnly
218 */
219const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
220const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
221/**
222 * Boolean attributes should be included if the value is truthy or ''.
223 * e.g. `<select multiple>` compiles to `{ multiple: '' }`
224 */
225function includeBooleanAttr(value) {
226 return !!value || value === '';
227}
228
229function looseCompareArrays(a, b) {
230 if (a.length !== b.length)
231 return false;
232 let equal = true;
233 for (let i = 0; equal && i < a.length; i++) {
234 equal = looseEqual(a[i], b[i]);
235 }
236 return equal;
237}
238function looseEqual(a, b) {
239 if (a === b)
240 return true;
241 let aValidType = isDate(a);
242 let bValidType = isDate(b);
243 if (aValidType || bValidType) {
244 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
245 }
246 aValidType = isSymbol(a);
247 bValidType = isSymbol(b);
248 if (aValidType || bValidType) {
249 return a === b;
250 }
251 aValidType = isArray(a);
252 bValidType = isArray(b);
253 if (aValidType || bValidType) {
254 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
255 }
256 aValidType = isObject(a);
257 bValidType = isObject(b);
258 if (aValidType || bValidType) {
259 /* istanbul ignore if: this if will probably never be called */
260 if (!aValidType || !bValidType) {
261 return false;
262 }
263 const aKeysCount = Object.keys(a).length;
264 const bKeysCount = Object.keys(b).length;
265 if (aKeysCount !== bKeysCount) {
266 return false;
267 }
268 for (const key in a) {
269 const aHasKey = a.hasOwnProperty(key);
270 const bHasKey = b.hasOwnProperty(key);
271 if ((aHasKey && !bHasKey) ||
272 (!aHasKey && bHasKey) ||
273 !looseEqual(a[key], b[key])) {
274 return false;
275 }
276 }
277 }
278 return String(a) === String(b);
279}
280function looseIndexOf(arr, val) {
281 return arr.findIndex(item => looseEqual(item, val));
282}
283
284/**
285 * For converting {{ interpolation }} values to displayed strings.
286 * @private
287 */
288const toDisplayString = (val) => {
289 return isString(val)
290 ? val
291 : val == null
292 ? ''
293 : isArray(val) ||
294 (isObject(val) &&
295 (val.toString === objectToString || !isFunction(val.toString)))
296 ? JSON.stringify(val, replacer, 2)
297 : String(val);
298};
299const replacer = (_key, val) => {
300 // can't use isRef here since @vue/shared has no deps
301 if (val && val.__v_isRef) {
302 return replacer(_key, val.value);
303 }
304 else if (isMap(val)) {
305 return {
306 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
307 entries[`${key} =>`] = val;
308 return entries;
309 }, {})
310 };
311 }
312 else if (isSet(val)) {
313 return {
314 [`Set(${val.size})`]: [...val.values()]
315 };
316 }
317 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
318 return String(val);
319 }
320 return val;
321};
322
323const EMPTY_OBJ = Object.freeze({})
324 ;
325const EMPTY_ARR = Object.freeze([]) ;
326const NOOP = () => { };
327/**
328 * Always return false.
329 */
330const NO = () => false;
331const onRE = /^on[^a-z]/;
332const isOn = (key) => onRE.test(key);
333const isModelListener = (key) => key.startsWith('onUpdate:');
334const extend = Object.assign;
335const remove = (arr, el) => {
336 const i = arr.indexOf(el);
337 if (i > -1) {
338 arr.splice(i, 1);
339 }
340};
341const hasOwnProperty = Object.prototype.hasOwnProperty;
342const hasOwn = (val, key) => hasOwnProperty.call(val, key);
343const isArray = Array.isArray;
344const isMap = (val) => toTypeString(val) === '[object Map]';
345const isSet = (val) => toTypeString(val) === '[object Set]';
346const isDate = (val) => toTypeString(val) === '[object Date]';
347const isFunction = (val) => typeof val === 'function';
348const isString = (val) => typeof val === 'string';
349const isSymbol = (val) => typeof val === 'symbol';
350const isObject = (val) => val !== null && typeof val === 'object';
351const isPromise = (val) => {
352 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
353};
354const objectToString = Object.prototype.toString;
355const toTypeString = (value) => objectToString.call(value);
356const toRawType = (value) => {
357 // extract "RawType" from strings like "[object RawType]"
358 return toTypeString(value).slice(8, -1);
359};
360const isPlainObject = (val) => toTypeString(val) === '[object Object]';
361const isIntegerKey = (key) => isString(key) &&
362 key !== 'NaN' &&
363 key[0] !== '-' &&
364 '' + parseInt(key, 10) === key;
365const isReservedProp = /*#__PURE__*/ makeMap(
366// the leading comma is intentional so empty string "" is also included
367',key,ref,ref_for,ref_key,' +
368 'onVnodeBeforeMount,onVnodeMounted,' +
369 'onVnodeBeforeUpdate,onVnodeUpdated,' +
370 'onVnodeBeforeUnmount,onVnodeUnmounted');
371const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
372const cacheStringFunction = (fn) => {
373 const cache = Object.create(null);
374 return ((str) => {
375 const hit = cache[str];
376 return hit || (cache[str] = fn(str));
377 });
378};
379const camelizeRE = /-(\w)/g;
380/**
381 * @private
382 */
383const camelize = cacheStringFunction((str) => {
384 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
385});
386const hyphenateRE = /\B([A-Z])/g;
387/**
388 * @private
389 */
390const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
391/**
392 * @private
393 */
394const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
395/**
396 * @private
397 */
398const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
399// compare whether a value has changed, accounting for NaN.
400const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
401const invokeArrayFns = (fns, arg) => {
402 for (let i = 0; i < fns.length; i++) {
403 fns[i](arg);
404 }
405};
406const def = (obj, key, value) => {
407 Object.defineProperty(obj, key, {
408 configurable: true,
409 enumerable: false,
410 value
411 });
412};
413const toNumber = (val) => {
414 const n = parseFloat(val);
415 return isNaN(n) ? val : n;
416};
417let _globalThis;
418const getGlobalThis = () => {
419 return (_globalThis ||
420 (_globalThis =
421 typeof globalThis !== 'undefined'
422 ? globalThis
423 : typeof self !== 'undefined'
424 ? self
425 : typeof window !== 'undefined'
426 ? window
427 : typeof global !== 'undefined'
428 ? global
429 : {}));
430};
431
432function warn(msg, ...args) {
433 console.warn(`[Vue warn] ${msg}`, ...args);
434}
435
436let activeEffectScope;
437class EffectScope {
438 constructor(detached = false) {
439 this.detached = detached;
440 /**
441 * @internal
442 */
443 this.active = true;
444 /**
445 * @internal
446 */
447 this.effects = [];
448 /**
449 * @internal
450 */
451 this.cleanups = [];
452 this.parent = activeEffectScope;
453 if (!detached && activeEffectScope) {
454 this.index =
455 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
456 }
457 }
458 run(fn) {
459 if (this.active) {
460 const currentEffectScope = activeEffectScope;
461 try {
462 activeEffectScope = this;
463 return fn();
464 }
465 finally {
466 activeEffectScope = currentEffectScope;
467 }
468 }
469 else {
470 warn(`cannot run an inactive effect scope.`);
471 }
472 }
473 /**
474 * This should only be called on non-detached scopes
475 * @internal
476 */
477 on() {
478 activeEffectScope = this;
479 }
480 /**
481 * This should only be called on non-detached scopes
482 * @internal
483 */
484 off() {
485 activeEffectScope = this.parent;
486 }
487 stop(fromParent) {
488 if (this.active) {
489 let i, l;
490 for (i = 0, l = this.effects.length; i < l; i++) {
491 this.effects[i].stop();
492 }
493 for (i = 0, l = this.cleanups.length; i < l; i++) {
494 this.cleanups[i]();
495 }
496 if (this.scopes) {
497 for (i = 0, l = this.scopes.length; i < l; i++) {
498 this.scopes[i].stop(true);
499 }
500 }
501 // nested scope, dereference from parent to avoid memory leaks
502 if (!this.detached && this.parent && !fromParent) {
503 // optimized O(1) removal
504 const last = this.parent.scopes.pop();
505 if (last && last !== this) {
506 this.parent.scopes[this.index] = last;
507 last.index = this.index;
508 }
509 }
510 this.parent = undefined;
511 this.active = false;
512 }
513 }
514}
515function effectScope(detached) {
516 return new EffectScope(detached);
517}
518function recordEffectScope(effect, scope = activeEffectScope) {
519 if (scope && scope.active) {
520 scope.effects.push(effect);
521 }
522}
523function getCurrentScope() {
524 return activeEffectScope;
525}
526function onScopeDispose(fn) {
527 if (activeEffectScope) {
528 activeEffectScope.cleanups.push(fn);
529 }
530 else {
531 warn(`onScopeDispose() is called when there is no active effect scope` +
532 ` to be associated with.`);
533 }
534}
535
536const createDep = (effects) => {
537 const dep = new Set(effects);
538 dep.w = 0;
539 dep.n = 0;
540 return dep;
541};
542const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
543const newTracked = (dep) => (dep.n & trackOpBit) > 0;
544const initDepMarkers = ({ deps }) => {
545 if (deps.length) {
546 for (let i = 0; i < deps.length; i++) {
547 deps[i].w |= trackOpBit; // set was tracked
548 }
549 }
550};
551const finalizeDepMarkers = (effect) => {
552 const { deps } = effect;
553 if (deps.length) {
554 let ptr = 0;
555 for (let i = 0; i < deps.length; i++) {
556 const dep = deps[i];
557 if (wasTracked(dep) && !newTracked(dep)) {
558 dep.delete(effect);
559 }
560 else {
561 deps[ptr++] = dep;
562 }
563 // clear bits
564 dep.w &= ~trackOpBit;
565 dep.n &= ~trackOpBit;
566 }
567 deps.length = ptr;
568 }
569};
570
571const targetMap = new WeakMap();
572// The number of effects currently being tracked recursively.
573let effectTrackDepth = 0;
574let trackOpBit = 1;
575/**
576 * The bitwise track markers support at most 30 levels of recursion.
577 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
578 * When recursion depth is greater, fall back to using a full cleanup.
579 */
580const maxMarkerBits = 30;
581let activeEffect;
582const ITERATE_KEY = Symbol('iterate' );
583const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
584class ReactiveEffect {
585 constructor(fn, scheduler = null, scope) {
586 this.fn = fn;
587 this.scheduler = scheduler;
588 this.active = true;
589 this.deps = [];
590 this.parent = undefined;
591 recordEffectScope(this, scope);
592 }
593 run() {
594 if (!this.active) {
595 return this.fn();
596 }
597 let parent = activeEffect;
598 let lastShouldTrack = shouldTrack;
599 while (parent) {
600 if (parent === this) {
601 return;
602 }
603 parent = parent.parent;
604 }
605 try {
606 this.parent = activeEffect;
607 activeEffect = this;
608 shouldTrack = true;
609 trackOpBit = 1 << ++effectTrackDepth;
610 if (effectTrackDepth <= maxMarkerBits) {
611 initDepMarkers(this);
612 }
613 else {
614 cleanupEffect(this);
615 }
616 return this.fn();
617 }
618 finally {
619 if (effectTrackDepth <= maxMarkerBits) {
620 finalizeDepMarkers(this);
621 }
622 trackOpBit = 1 << --effectTrackDepth;
623 activeEffect = this.parent;
624 shouldTrack = lastShouldTrack;
625 this.parent = undefined;
626 if (this.deferStop) {
627 this.stop();
628 }
629 }
630 }
631 stop() {
632 // stopped while running itself - defer the cleanup
633 if (activeEffect === this) {
634 this.deferStop = true;
635 }
636 else if (this.active) {
637 cleanupEffect(this);
638 if (this.onStop) {
639 this.onStop();
640 }
641 this.active = false;
642 }
643 }
644}
645function cleanupEffect(effect) {
646 const { deps } = effect;
647 if (deps.length) {
648 for (let i = 0; i < deps.length; i++) {
649 deps[i].delete(effect);
650 }
651 deps.length = 0;
652 }
653}
654function effect(fn, options) {
655 if (fn.effect) {
656 fn = fn.effect.fn;
657 }
658 const _effect = new ReactiveEffect(fn);
659 if (options) {
660 extend(_effect, options);
661 if (options.scope)
662 recordEffectScope(_effect, options.scope);
663 }
664 if (!options || !options.lazy) {
665 _effect.run();
666 }
667 const runner = _effect.run.bind(_effect);
668 runner.effect = _effect;
669 return runner;
670}
671function stop(runner) {
672 runner.effect.stop();
673}
674let shouldTrack = true;
675const trackStack = [];
676function pauseTracking() {
677 trackStack.push(shouldTrack);
678 shouldTrack = false;
679}
680function resetTracking() {
681 const last = trackStack.pop();
682 shouldTrack = last === undefined ? true : last;
683}
684function track(target, type, key) {
685 if (shouldTrack && activeEffect) {
686 let depsMap = targetMap.get(target);
687 if (!depsMap) {
688 targetMap.set(target, (depsMap = new Map()));
689 }
690 let dep = depsMap.get(key);
691 if (!dep) {
692 depsMap.set(key, (dep = createDep()));
693 }
694 const eventInfo = { effect: activeEffect, target, type, key }
695 ;
696 trackEffects(dep, eventInfo);
697 }
698}
699function trackEffects(dep, debuggerEventExtraInfo) {
700 let shouldTrack = false;
701 if (effectTrackDepth <= maxMarkerBits) {
702 if (!newTracked(dep)) {
703 dep.n |= trackOpBit; // set newly tracked
704 shouldTrack = !wasTracked(dep);
705 }
706 }
707 else {
708 // Full cleanup mode.
709 shouldTrack = !dep.has(activeEffect);
710 }
711 if (shouldTrack) {
712 dep.add(activeEffect);
713 activeEffect.deps.push(dep);
714 if (activeEffect.onTrack) {
715 activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo));
716 }
717 }
718}
719function trigger(target, type, key, newValue, oldValue, oldTarget) {
720 const depsMap = targetMap.get(target);
721 if (!depsMap) {
722 // never been tracked
723 return;
724 }
725 let deps = [];
726 if (type === "clear" /* TriggerOpTypes.CLEAR */) {
727 // collection being cleared
728 // trigger all effects for target
729 deps = [...depsMap.values()];
730 }
731 else if (key === 'length' && isArray(target)) {
732 const newLength = toNumber(newValue);
733 depsMap.forEach((dep, key) => {
734 if (key === 'length' || key >= newLength) {
735 deps.push(dep);
736 }
737 });
738 }
739 else {
740 // schedule runs for SET | ADD | DELETE
741 if (key !== void 0) {
742 deps.push(depsMap.get(key));
743 }
744 // also run for iteration key on ADD | DELETE | Map.SET
745 switch (type) {
746 case "add" /* TriggerOpTypes.ADD */:
747 if (!isArray(target)) {
748 deps.push(depsMap.get(ITERATE_KEY));
749 if (isMap(target)) {
750 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
751 }
752 }
753 else if (isIntegerKey(key)) {
754 // new index added to array -> length changes
755 deps.push(depsMap.get('length'));
756 }
757 break;
758 case "delete" /* TriggerOpTypes.DELETE */:
759 if (!isArray(target)) {
760 deps.push(depsMap.get(ITERATE_KEY));
761 if (isMap(target)) {
762 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
763 }
764 }
765 break;
766 case "set" /* TriggerOpTypes.SET */:
767 if (isMap(target)) {
768 deps.push(depsMap.get(ITERATE_KEY));
769 }
770 break;
771 }
772 }
773 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
774 ;
775 if (deps.length === 1) {
776 if (deps[0]) {
777 {
778 triggerEffects(deps[0], eventInfo);
779 }
780 }
781 }
782 else {
783 const effects = [];
784 for (const dep of deps) {
785 if (dep) {
786 effects.push(...dep);
787 }
788 }
789 {
790 triggerEffects(createDep(effects), eventInfo);
791 }
792 }
793}
794function triggerEffects(dep, debuggerEventExtraInfo) {
795 // spread into array for stabilization
796 const effects = isArray(dep) ? dep : [...dep];
797 for (const effect of effects) {
798 if (effect.computed) {
799 triggerEffect(effect, debuggerEventExtraInfo);
800 }
801 }
802 for (const effect of effects) {
803 if (!effect.computed) {
804 triggerEffect(effect, debuggerEventExtraInfo);
805 }
806 }
807}
808function triggerEffect(effect, debuggerEventExtraInfo) {
809 if (effect !== activeEffect || effect.allowRecurse) {
810 if (effect.onTrigger) {
811 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
812 }
813 if (effect.scheduler) {
814 effect.scheduler();
815 }
816 else {
817 effect.run();
818 }
819 }
820}
821
822const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
823const builtInSymbols = new Set(
824/*#__PURE__*/
825Object.getOwnPropertyNames(Symbol)
826 // ios10.x Object.getOwnPropertyNames(Symbol) can enumerate 'arguments' and 'caller'
827 // but accessing them on Symbol leads to TypeError because Symbol is a strict mode
828 // function
829 .filter(key => key !== 'arguments' && key !== 'caller')
830 .map(key => Symbol[key])
831 .filter(isSymbol));
832const get = /*#__PURE__*/ createGetter();
833const shallowGet = /*#__PURE__*/ createGetter(false, true);
834const readonlyGet = /*#__PURE__*/ createGetter(true);
835const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
836const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
837function createArrayInstrumentations() {
838 const instrumentations = {};
839 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
840 instrumentations[key] = function (...args) {
841 const arr = toRaw(this);
842 for (let i = 0, l = this.length; i < l; i++) {
843 track(arr, "get" /* TrackOpTypes.GET */, i + '');
844 }
845 // we run the method using the original args first (which may be reactive)
846 const res = arr[key](...args);
847 if (res === -1 || res === false) {
848 // if that didn't work, run it again using raw values.
849 return arr[key](...args.map(toRaw));
850 }
851 else {
852 return res;
853 }
854 };
855 });
856 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
857 instrumentations[key] = function (...args) {
858 pauseTracking();
859 const res = toRaw(this)[key].apply(this, args);
860 resetTracking();
861 return res;
862 };
863 });
864 return instrumentations;
865}
866function createGetter(isReadonly = false, shallow = false) {
867 return function get(target, key, receiver) {
868 if (key === "__v_isReactive" /* ReactiveFlags.IS_REACTIVE */) {
869 return !isReadonly;
870 }
871 else if (key === "__v_isReadonly" /* ReactiveFlags.IS_READONLY */) {
872 return isReadonly;
873 }
874 else if (key === "__v_isShallow" /* ReactiveFlags.IS_SHALLOW */) {
875 return shallow;
876 }
877 else if (key === "__v_raw" /* ReactiveFlags.RAW */ &&
878 receiver ===
879 (isReadonly
880 ? shallow
881 ? shallowReadonlyMap
882 : readonlyMap
883 : shallow
884 ? shallowReactiveMap
885 : reactiveMap).get(target)) {
886 return target;
887 }
888 const targetIsArray = isArray(target);
889 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
890 return Reflect.get(arrayInstrumentations, key, receiver);
891 }
892 const res = Reflect.get(target, key, receiver);
893 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
894 return res;
895 }
896 if (!isReadonly) {
897 track(target, "get" /* TrackOpTypes.GET */, key);
898 }
899 if (shallow) {
900 return res;
901 }
902 if (isRef(res)) {
903 // ref unwrapping - skip unwrap for Array + integer key.
904 return targetIsArray && isIntegerKey(key) ? res : res.value;
905 }
906 if (isObject(res)) {
907 // Convert returned value into a proxy as well. we do the isObject check
908 // here to avoid invalid value warning. Also need to lazy access readonly
909 // and reactive here to avoid circular dependency.
910 return isReadonly ? readonly(res) : reactive(res);
911 }
912 return res;
913 };
914}
915const set = /*#__PURE__*/ createSetter();
916const shallowSet = /*#__PURE__*/ createSetter(true);
917function createSetter(shallow = false) {
918 return function set(target, key, value, receiver) {
919 let oldValue = target[key];
920 if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
921 return false;
922 }
923 if (!shallow) {
924 if (!isShallow(value) && !isReadonly(value)) {
925 oldValue = toRaw(oldValue);
926 value = toRaw(value);
927 }
928 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
929 oldValue.value = value;
930 return true;
931 }
932 }
933 const hadKey = isArray(target) && isIntegerKey(key)
934 ? Number(key) < target.length
935 : hasOwn(target, key);
936 const result = Reflect.set(target, key, value, receiver);
937 // don't trigger if target is something up in the prototype chain of original
938 if (target === toRaw(receiver)) {
939 if (!hadKey) {
940 trigger(target, "add" /* TriggerOpTypes.ADD */, key, value);
941 }
942 else if (hasChanged(value, oldValue)) {
943 trigger(target, "set" /* TriggerOpTypes.SET */, key, value, oldValue);
944 }
945 }
946 return result;
947 };
948}
949function deleteProperty(target, key) {
950 const hadKey = hasOwn(target, key);
951 const oldValue = target[key];
952 const result = Reflect.deleteProperty(target, key);
953 if (result && hadKey) {
954 trigger(target, "delete" /* TriggerOpTypes.DELETE */, key, undefined, oldValue);
955 }
956 return result;
957}
958function has(target, key) {
959 const result = Reflect.has(target, key);
960 if (!isSymbol(key) || !builtInSymbols.has(key)) {
961 track(target, "has" /* TrackOpTypes.HAS */, key);
962 }
963 return result;
964}
965function ownKeys(target) {
966 track(target, "iterate" /* TrackOpTypes.ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
967 return Reflect.ownKeys(target);
968}
969const mutableHandlers = {
970 get,
971 set,
972 deleteProperty,
973 has,
974 ownKeys
975};
976const readonlyHandlers = {
977 get: readonlyGet,
978 set(target, key) {
979 {
980 warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
981 }
982 return true;
983 },
984 deleteProperty(target, key) {
985 {
986 warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
987 }
988 return true;
989 }
990};
991const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
992 get: shallowGet,
993 set: shallowSet
994});
995// Props handlers are special in the sense that it should not unwrap top-level
996// refs (in order to allow refs to be explicitly passed down), but should
997// retain the reactivity of the normal readonly object.
998const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
999 get: shallowReadonlyGet
1000});
1001
1002const toShallow = (value) => value;
1003const getProto = (v) => Reflect.getPrototypeOf(v);
1004function get$1(target, key, isReadonly = false, isShallow = false) {
1005 // #1772: readonly(reactive(Map)) should return readonly + reactive version
1006 // of the value
1007 target = target["__v_raw" /* ReactiveFlags.RAW */];
1008 const rawTarget = toRaw(target);
1009 const rawKey = toRaw(key);
1010 if (!isReadonly) {
1011 if (key !== rawKey) {
1012 track(rawTarget, "get" /* TrackOpTypes.GET */, key);
1013 }
1014 track(rawTarget, "get" /* TrackOpTypes.GET */, rawKey);
1015 }
1016 const { has } = getProto(rawTarget);
1017 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1018 if (has.call(rawTarget, key)) {
1019 return wrap(target.get(key));
1020 }
1021 else if (has.call(rawTarget, rawKey)) {
1022 return wrap(target.get(rawKey));
1023 }
1024 else if (target !== rawTarget) {
1025 // #3602 readonly(reactive(Map))
1026 // ensure that the nested reactive `Map` can do tracking for itself
1027 target.get(key);
1028 }
1029}
1030function has$1(key, isReadonly = false) {
1031 const target = this["__v_raw" /* ReactiveFlags.RAW */];
1032 const rawTarget = toRaw(target);
1033 const rawKey = toRaw(key);
1034 if (!isReadonly) {
1035 if (key !== rawKey) {
1036 track(rawTarget, "has" /* TrackOpTypes.HAS */, key);
1037 }
1038 track(rawTarget, "has" /* TrackOpTypes.HAS */, rawKey);
1039 }
1040 return key === rawKey
1041 ? target.has(key)
1042 : target.has(key) || target.has(rawKey);
1043}
1044function size(target, isReadonly = false) {
1045 target = target["__v_raw" /* ReactiveFlags.RAW */];
1046 !isReadonly && track(toRaw(target), "iterate" /* TrackOpTypes.ITERATE */, ITERATE_KEY);
1047 return Reflect.get(target, 'size', target);
1048}
1049function add(value) {
1050 value = toRaw(value);
1051 const target = toRaw(this);
1052 const proto = getProto(target);
1053 const hadKey = proto.has.call(target, value);
1054 if (!hadKey) {
1055 target.add(value);
1056 trigger(target, "add" /* TriggerOpTypes.ADD */, value, value);
1057 }
1058 return this;
1059}
1060function set$1(key, value) {
1061 value = toRaw(value);
1062 const target = toRaw(this);
1063 const { has, get } = getProto(target);
1064 let hadKey = has.call(target, key);
1065 if (!hadKey) {
1066 key = toRaw(key);
1067 hadKey = has.call(target, key);
1068 }
1069 else {
1070 checkIdentityKeys(target, has, key);
1071 }
1072 const oldValue = get.call(target, key);
1073 target.set(key, value);
1074 if (!hadKey) {
1075 trigger(target, "add" /* TriggerOpTypes.ADD */, key, value);
1076 }
1077 else if (hasChanged(value, oldValue)) {
1078 trigger(target, "set" /* TriggerOpTypes.SET */, key, value, oldValue);
1079 }
1080 return this;
1081}
1082function deleteEntry(key) {
1083 const target = toRaw(this);
1084 const { has, get } = getProto(target);
1085 let hadKey = has.call(target, key);
1086 if (!hadKey) {
1087 key = toRaw(key);
1088 hadKey = has.call(target, key);
1089 }
1090 else {
1091 checkIdentityKeys(target, has, key);
1092 }
1093 const oldValue = get ? get.call(target, key) : undefined;
1094 // forward the operation before queueing reactions
1095 const result = target.delete(key);
1096 if (hadKey) {
1097 trigger(target, "delete" /* TriggerOpTypes.DELETE */, key, undefined, oldValue);
1098 }
1099 return result;
1100}
1101function clear() {
1102 const target = toRaw(this);
1103 const hadItems = target.size !== 0;
1104 const oldTarget = isMap(target)
1105 ? new Map(target)
1106 : new Set(target)
1107 ;
1108 // forward the operation before queueing reactions
1109 const result = target.clear();
1110 if (hadItems) {
1111 trigger(target, "clear" /* TriggerOpTypes.CLEAR */, undefined, undefined, oldTarget);
1112 }
1113 return result;
1114}
1115function createForEach(isReadonly, isShallow) {
1116 return function forEach(callback, thisArg) {
1117 const observed = this;
1118 const target = observed["__v_raw" /* ReactiveFlags.RAW */];
1119 const rawTarget = toRaw(target);
1120 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1121 !isReadonly && track(rawTarget, "iterate" /* TrackOpTypes.ITERATE */, ITERATE_KEY);
1122 return target.forEach((value, key) => {
1123 // important: make sure the callback is
1124 // 1. invoked with the reactive map as `this` and 3rd arg
1125 // 2. the value received should be a corresponding reactive/readonly.
1126 return callback.call(thisArg, wrap(value), wrap(key), observed);
1127 });
1128 };
1129}
1130function createIterableMethod(method, isReadonly, isShallow) {
1131 return function (...args) {
1132 const target = this["__v_raw" /* ReactiveFlags.RAW */];
1133 const rawTarget = toRaw(target);
1134 const targetIsMap = isMap(rawTarget);
1135 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1136 const isKeyOnly = method === 'keys' && targetIsMap;
1137 const innerIterator = target[method](...args);
1138 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1139 !isReadonly &&
1140 track(rawTarget, "iterate" /* TrackOpTypes.ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1141 // return a wrapped iterator which returns observed versions of the
1142 // values emitted from the real iterator
1143 return {
1144 // iterator protocol
1145 next() {
1146 const { value, done } = innerIterator.next();
1147 return done
1148 ? { value, done }
1149 : {
1150 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1151 done
1152 };
1153 },
1154 // iterable protocol
1155 [Symbol.iterator]() {
1156 return this;
1157 }
1158 };
1159 };
1160}
1161function createReadonlyMethod(type) {
1162 return function (...args) {
1163 {
1164 const key = args[0] ? `on key "${args[0]}" ` : ``;
1165 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1166 }
1167 return type === "delete" /* TriggerOpTypes.DELETE */ ? false : this;
1168 };
1169}
1170function createInstrumentations() {
1171 const mutableInstrumentations = {
1172 get(key) {
1173 return get$1(this, key);
1174 },
1175 get size() {
1176 return size(this);
1177 },
1178 has: has$1,
1179 add,
1180 set: set$1,
1181 delete: deleteEntry,
1182 clear,
1183 forEach: createForEach(false, false)
1184 };
1185 const shallowInstrumentations = {
1186 get(key) {
1187 return get$1(this, key, false, true);
1188 },
1189 get size() {
1190 return size(this);
1191 },
1192 has: has$1,
1193 add,
1194 set: set$1,
1195 delete: deleteEntry,
1196 clear,
1197 forEach: createForEach(false, true)
1198 };
1199 const readonlyInstrumentations = {
1200 get(key) {
1201 return get$1(this, key, true);
1202 },
1203 get size() {
1204 return size(this, true);
1205 },
1206 has(key) {
1207 return has$1.call(this, key, true);
1208 },
1209 add: createReadonlyMethod("add" /* TriggerOpTypes.ADD */),
1210 set: createReadonlyMethod("set" /* TriggerOpTypes.SET */),
1211 delete: createReadonlyMethod("delete" /* TriggerOpTypes.DELETE */),
1212 clear: createReadonlyMethod("clear" /* TriggerOpTypes.CLEAR */),
1213 forEach: createForEach(true, false)
1214 };
1215 const shallowReadonlyInstrumentations = {
1216 get(key) {
1217 return get$1(this, key, true, true);
1218 },
1219 get size() {
1220 return size(this, true);
1221 },
1222 has(key) {
1223 return has$1.call(this, key, true);
1224 },
1225 add: createReadonlyMethod("add" /* TriggerOpTypes.ADD */),
1226 set: createReadonlyMethod("set" /* TriggerOpTypes.SET */),
1227 delete: createReadonlyMethod("delete" /* TriggerOpTypes.DELETE */),
1228 clear: createReadonlyMethod("clear" /* TriggerOpTypes.CLEAR */),
1229 forEach: createForEach(true, true)
1230 };
1231 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1232 iteratorMethods.forEach(method => {
1233 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1234 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1235 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1236 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1237 });
1238 return [
1239 mutableInstrumentations,
1240 readonlyInstrumentations,
1241 shallowInstrumentations,
1242 shallowReadonlyInstrumentations
1243 ];
1244}
1245const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1246function createInstrumentationGetter(isReadonly, shallow) {
1247 const instrumentations = shallow
1248 ? isReadonly
1249 ? shallowReadonlyInstrumentations
1250 : shallowInstrumentations
1251 : isReadonly
1252 ? readonlyInstrumentations
1253 : mutableInstrumentations;
1254 return (target, key, receiver) => {
1255 if (key === "__v_isReactive" /* ReactiveFlags.IS_REACTIVE */) {
1256 return !isReadonly;
1257 }
1258 else if (key === "__v_isReadonly" /* ReactiveFlags.IS_READONLY */) {
1259 return isReadonly;
1260 }
1261 else if (key === "__v_raw" /* ReactiveFlags.RAW */) {
1262 return target;
1263 }
1264 return Reflect.get(hasOwn(instrumentations, key) && key in target
1265 ? instrumentations
1266 : target, key, receiver);
1267 };
1268}
1269const mutableCollectionHandlers = {
1270 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1271};
1272const shallowCollectionHandlers = {
1273 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1274};
1275const readonlyCollectionHandlers = {
1276 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1277};
1278const shallowReadonlyCollectionHandlers = {
1279 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1280};
1281function checkIdentityKeys(target, has, key) {
1282 const rawKey = toRaw(key);
1283 if (rawKey !== key && has.call(target, rawKey)) {
1284 const type = toRawType(target);
1285 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1286 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1287 `which can lead to inconsistencies. ` +
1288 `Avoid differentiating between the raw and reactive versions ` +
1289 `of an object and only use the reactive version if possible.`);
1290 }
1291}
1292
1293const reactiveMap = new WeakMap();
1294const shallowReactiveMap = new WeakMap();
1295const readonlyMap = new WeakMap();
1296const shallowReadonlyMap = new WeakMap();
1297function targetTypeMap(rawType) {
1298 switch (rawType) {
1299 case 'Object':
1300 case 'Array':
1301 return 1 /* TargetType.COMMON */;
1302 case 'Map':
1303 case 'Set':
1304 case 'WeakMap':
1305 case 'WeakSet':
1306 return 2 /* TargetType.COLLECTION */;
1307 default:
1308 return 0 /* TargetType.INVALID */;
1309 }
1310}
1311function getTargetType(value) {
1312 return value["__v_skip" /* ReactiveFlags.SKIP */] || !Object.isExtensible(value)
1313 ? 0 /* TargetType.INVALID */
1314 : targetTypeMap(toRawType(value));
1315}
1316function reactive(target) {
1317 // if trying to observe a readonly proxy, return the readonly version.
1318 if (isReadonly(target)) {
1319 return target;
1320 }
1321 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1322}
1323/**
1324 * Return a shallowly-reactive copy of the original object, where only the root
1325 * level properties are reactive. It also does not auto-unwrap refs (even at the
1326 * root level).
1327 */
1328function shallowReactive(target) {
1329 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1330}
1331/**
1332 * Creates a readonly copy of the original object. Note the returned copy is not
1333 * made reactive, but `readonly` can be called on an already reactive object.
1334 */
1335function readonly(target) {
1336 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1337}
1338/**
1339 * Returns a reactive-copy of the original object, where only the root level
1340 * properties are readonly, and does NOT unwrap refs nor recursively convert
1341 * returned properties.
1342 * This is used for creating the props proxy object for stateful components.
1343 */
1344function shallowReadonly(target) {
1345 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1346}
1347function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1348 if (!isObject(target)) {
1349 {
1350 console.warn(`value cannot be made reactive: ${String(target)}`);
1351 }
1352 return target;
1353 }
1354 // target is already a Proxy, return it.
1355 // exception: calling readonly() on a reactive object
1356 if (target["__v_raw" /* ReactiveFlags.RAW */] &&
1357 !(isReadonly && target["__v_isReactive" /* ReactiveFlags.IS_REACTIVE */])) {
1358 return target;
1359 }
1360 // target already has corresponding Proxy
1361 const existingProxy = proxyMap.get(target);
1362 if (existingProxy) {
1363 return existingProxy;
1364 }
1365 // only specific value types can be observed.
1366 const targetType = getTargetType(target);
1367 if (targetType === 0 /* TargetType.INVALID */) {
1368 return target;
1369 }
1370 const proxy = new Proxy(target, targetType === 2 /* TargetType.COLLECTION */ ? collectionHandlers : baseHandlers);
1371 proxyMap.set(target, proxy);
1372 return proxy;
1373}
1374function isReactive(value) {
1375 if (isReadonly(value)) {
1376 return isReactive(value["__v_raw" /* ReactiveFlags.RAW */]);
1377 }
1378 return !!(value && value["__v_isReactive" /* ReactiveFlags.IS_REACTIVE */]);
1379}
1380function isReadonly(value) {
1381 return !!(value && value["__v_isReadonly" /* ReactiveFlags.IS_READONLY */]);
1382}
1383function isShallow(value) {
1384 return !!(value && value["__v_isShallow" /* ReactiveFlags.IS_SHALLOW */]);
1385}
1386function isProxy(value) {
1387 return isReactive(value) || isReadonly(value);
1388}
1389function toRaw(observed) {
1390 const raw = observed && observed["__v_raw" /* ReactiveFlags.RAW */];
1391 return raw ? toRaw(raw) : observed;
1392}
1393function markRaw(value) {
1394 def(value, "__v_skip" /* ReactiveFlags.SKIP */, true);
1395 return value;
1396}
1397const toReactive = (value) => isObject(value) ? reactive(value) : value;
1398const toReadonly = (value) => isObject(value) ? readonly(value) : value;
1399
1400function trackRefValue(ref) {
1401 if (shouldTrack && activeEffect) {
1402 ref = toRaw(ref);
1403 {
1404 trackEffects(ref.dep || (ref.dep = createDep()), {
1405 target: ref,
1406 type: "get" /* TrackOpTypes.GET */,
1407 key: 'value'
1408 });
1409 }
1410 }
1411}
1412function triggerRefValue(ref, newVal) {
1413 ref = toRaw(ref);
1414 if (ref.dep) {
1415 {
1416 triggerEffects(ref.dep, {
1417 target: ref,
1418 type: "set" /* TriggerOpTypes.SET */,
1419 key: 'value',
1420 newValue: newVal
1421 });
1422 }
1423 }
1424}
1425function isRef(r) {
1426 return !!(r && r.__v_isRef === true);
1427}
1428function ref(value) {
1429 return createRef(value, false);
1430}
1431function shallowRef(value) {
1432 return createRef(value, true);
1433}
1434function createRef(rawValue, shallow) {
1435 if (isRef(rawValue)) {
1436 return rawValue;
1437 }
1438 return new RefImpl(rawValue, shallow);
1439}
1440class RefImpl {
1441 constructor(value, __v_isShallow) {
1442 this.__v_isShallow = __v_isShallow;
1443 this.dep = undefined;
1444 this.__v_isRef = true;
1445 this._rawValue = __v_isShallow ? value : toRaw(value);
1446 this._value = __v_isShallow ? value : toReactive(value);
1447 }
1448 get value() {
1449 trackRefValue(this);
1450 return this._value;
1451 }
1452 set value(newVal) {
1453 const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal);
1454 newVal = useDirectValue ? newVal : toRaw(newVal);
1455 if (hasChanged(newVal, this._rawValue)) {
1456 this._rawValue = newVal;
1457 this._value = useDirectValue ? newVal : toReactive(newVal);
1458 triggerRefValue(this, newVal);
1459 }
1460 }
1461}
1462function triggerRef(ref) {
1463 triggerRefValue(ref, ref.value );
1464}
1465function unref(ref) {
1466 return isRef(ref) ? ref.value : ref;
1467}
1468const shallowUnwrapHandlers = {
1469 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1470 set: (target, key, value, receiver) => {
1471 const oldValue = target[key];
1472 if (isRef(oldValue) && !isRef(value)) {
1473 oldValue.value = value;
1474 return true;
1475 }
1476 else {
1477 return Reflect.set(target, key, value, receiver);
1478 }
1479 }
1480};
1481function proxyRefs(objectWithRefs) {
1482 return isReactive(objectWithRefs)
1483 ? objectWithRefs
1484 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1485}
1486class CustomRefImpl {
1487 constructor(factory) {
1488 this.dep = undefined;
1489 this.__v_isRef = true;
1490 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1491 this._get = get;
1492 this._set = set;
1493 }
1494 get value() {
1495 return this._get();
1496 }
1497 set value(newVal) {
1498 this._set(newVal);
1499 }
1500}
1501function customRef(factory) {
1502 return new CustomRefImpl(factory);
1503}
1504function toRefs(object) {
1505 if (!isProxy(object)) {
1506 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1507 }
1508 const ret = isArray(object) ? new Array(object.length) : {};
1509 for (const key in object) {
1510 ret[key] = toRef(object, key);
1511 }
1512 return ret;
1513}
1514class ObjectRefImpl {
1515 constructor(_object, _key, _defaultValue) {
1516 this._object = _object;
1517 this._key = _key;
1518 this._defaultValue = _defaultValue;
1519 this.__v_isRef = true;
1520 }
1521 get value() {
1522 const val = this._object[this._key];
1523 return val === undefined ? this._defaultValue : val;
1524 }
1525 set value(newVal) {
1526 this._object[this._key] = newVal;
1527 }
1528}
1529function toRef(object, key, defaultValue) {
1530 const val = object[key];
1531 return isRef(val)
1532 ? val
1533 : new ObjectRefImpl(object, key, defaultValue);
1534}
1535
1536var _a;
1537class ComputedRefImpl {
1538 constructor(getter, _setter, isReadonly, isSSR) {
1539 this._setter = _setter;
1540 this.dep = undefined;
1541 this.__v_isRef = true;
1542 this[_a] = false;
1543 this._dirty = true;
1544 this.effect = new ReactiveEffect(getter, () => {
1545 if (!this._dirty) {
1546 this._dirty = true;
1547 triggerRefValue(this);
1548 }
1549 });
1550 this.effect.computed = this;
1551 this.effect.active = this._cacheable = !isSSR;
1552 this["__v_isReadonly" /* ReactiveFlags.IS_READONLY */] = isReadonly;
1553 }
1554 get value() {
1555 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1556 const self = toRaw(this);
1557 trackRefValue(self);
1558 if (self._dirty || !self._cacheable) {
1559 self._dirty = false;
1560 self._value = self.effect.run();
1561 }
1562 return self._value;
1563 }
1564 set value(newValue) {
1565 this._setter(newValue);
1566 }
1567}
1568_a = "__v_isReadonly" /* ReactiveFlags.IS_READONLY */;
1569function computed(getterOrOptions, debugOptions, isSSR = false) {
1570 let getter;
1571 let setter;
1572 const onlyGetter = isFunction(getterOrOptions);
1573 if (onlyGetter) {
1574 getter = getterOrOptions;
1575 setter = () => {
1576 console.warn('Write operation failed: computed value is readonly');
1577 }
1578 ;
1579 }
1580 else {
1581 getter = getterOrOptions.get;
1582 setter = getterOrOptions.set;
1583 }
1584 const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
1585 if (debugOptions && !isSSR) {
1586 cRef.effect.onTrack = debugOptions.onTrack;
1587 cRef.effect.onTrigger = debugOptions.onTrigger;
1588 }
1589 return cRef;
1590}
1591
1592const stack = [];
1593function pushWarningContext(vnode) {
1594 stack.push(vnode);
1595}
1596function popWarningContext() {
1597 stack.pop();
1598}
1599function warn$1(msg, ...args) {
1600 // avoid props formatting or warn handler tracking deps that might be mutated
1601 // during patch, leading to infinite recursion.
1602 pauseTracking();
1603 const instance = stack.length ? stack[stack.length - 1].component : null;
1604 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1605 const trace = getComponentTrace();
1606 if (appWarnHandler) {
1607 callWithErrorHandling(appWarnHandler, instance, 11 /* ErrorCodes.APP_WARN_HANDLER */, [
1608 msg + args.join(''),
1609 instance && instance.proxy,
1610 trace
1611 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1612 .join('\n'),
1613 trace
1614 ]);
1615 }
1616 else {
1617 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1618 /* istanbul ignore if */
1619 if (trace.length &&
1620 // avoid spamming console during tests
1621 !false) {
1622 warnArgs.push(`\n`, ...formatTrace(trace));
1623 }
1624 console.warn(...warnArgs);
1625 }
1626 resetTracking();
1627}
1628function getComponentTrace() {
1629 let currentVNode = stack[stack.length - 1];
1630 if (!currentVNode) {
1631 return [];
1632 }
1633 // we can't just use the stack because it will be incomplete during updates
1634 // that did not start from the root. Re-construct the parent chain using
1635 // instance parent pointers.
1636 const normalizedStack = [];
1637 while (currentVNode) {
1638 const last = normalizedStack[0];
1639 if (last && last.vnode === currentVNode) {
1640 last.recurseCount++;
1641 }
1642 else {
1643 normalizedStack.push({
1644 vnode: currentVNode,
1645 recurseCount: 0
1646 });
1647 }
1648 const parentInstance = currentVNode.component && currentVNode.component.parent;
1649 currentVNode = parentInstance && parentInstance.vnode;
1650 }
1651 return normalizedStack;
1652}
1653/* istanbul ignore next */
1654function formatTrace(trace) {
1655 const logs = [];
1656 trace.forEach((entry, i) => {
1657 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1658 });
1659 return logs;
1660}
1661function formatTraceEntry({ vnode, recurseCount }) {
1662 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1663 const isRoot = vnode.component ? vnode.component.parent == null : false;
1664 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1665 const close = `>` + postfix;
1666 return vnode.props
1667 ? [open, ...formatProps(vnode.props), close]
1668 : [open + close];
1669}
1670/* istanbul ignore next */
1671function formatProps(props) {
1672 const res = [];
1673 const keys = Object.keys(props);
1674 keys.slice(0, 3).forEach(key => {
1675 res.push(...formatProp(key, props[key]));
1676 });
1677 if (keys.length > 3) {
1678 res.push(` ...`);
1679 }
1680 return res;
1681}
1682/* istanbul ignore next */
1683function formatProp(key, value, raw) {
1684 if (isString(value)) {
1685 value = JSON.stringify(value);
1686 return raw ? value : [`${key}=${value}`];
1687 }
1688 else if (typeof value === 'number' ||
1689 typeof value === 'boolean' ||
1690 value == null) {
1691 return raw ? value : [`${key}=${value}`];
1692 }
1693 else if (isRef(value)) {
1694 value = formatProp(key, toRaw(value.value), true);
1695 return raw ? value : [`${key}=Ref<`, value, `>`];
1696 }
1697 else if (isFunction(value)) {
1698 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1699 }
1700 else {
1701 value = toRaw(value);
1702 return raw ? value : [`${key}=`, value];
1703 }
1704}
1705
1706const ErrorTypeStrings = {
1707 ["sp" /* LifecycleHooks.SERVER_PREFETCH */]: 'serverPrefetch hook',
1708 ["bc" /* LifecycleHooks.BEFORE_CREATE */]: 'beforeCreate hook',
1709 ["c" /* LifecycleHooks.CREATED */]: 'created hook',
1710 ["bm" /* LifecycleHooks.BEFORE_MOUNT */]: 'beforeMount hook',
1711 ["m" /* LifecycleHooks.MOUNTED */]: 'mounted hook',
1712 ["bu" /* LifecycleHooks.BEFORE_UPDATE */]: 'beforeUpdate hook',
1713 ["u" /* LifecycleHooks.UPDATED */]: 'updated',
1714 ["bum" /* LifecycleHooks.BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1715 ["um" /* LifecycleHooks.UNMOUNTED */]: 'unmounted hook',
1716 ["a" /* LifecycleHooks.ACTIVATED */]: 'activated hook',
1717 ["da" /* LifecycleHooks.DEACTIVATED */]: 'deactivated hook',
1718 ["ec" /* LifecycleHooks.ERROR_CAPTURED */]: 'errorCaptured hook',
1719 ["rtc" /* LifecycleHooks.RENDER_TRACKED */]: 'renderTracked hook',
1720 ["rtg" /* LifecycleHooks.RENDER_TRIGGERED */]: 'renderTriggered hook',
1721 [0 /* ErrorCodes.SETUP_FUNCTION */]: 'setup function',
1722 [1 /* ErrorCodes.RENDER_FUNCTION */]: 'render function',
1723 [2 /* ErrorCodes.WATCH_GETTER */]: 'watcher getter',
1724 [3 /* ErrorCodes.WATCH_CALLBACK */]: 'watcher callback',
1725 [4 /* ErrorCodes.WATCH_CLEANUP */]: 'watcher cleanup function',
1726 [5 /* ErrorCodes.NATIVE_EVENT_HANDLER */]: 'native event handler',
1727 [6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */]: 'component event handler',
1728 [7 /* ErrorCodes.VNODE_HOOK */]: 'vnode hook',
1729 [8 /* ErrorCodes.DIRECTIVE_HOOK */]: 'directive hook',
1730 [9 /* ErrorCodes.TRANSITION_HOOK */]: 'transition hook',
1731 [10 /* ErrorCodes.APP_ERROR_HANDLER */]: 'app errorHandler',
1732 [11 /* ErrorCodes.APP_WARN_HANDLER */]: 'app warnHandler',
1733 [12 /* ErrorCodes.FUNCTION_REF */]: 'ref function',
1734 [13 /* ErrorCodes.ASYNC_COMPONENT_LOADER */]: 'async component loader',
1735 [14 /* ErrorCodes.SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1736 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
1737};
1738function callWithErrorHandling(fn, instance, type, args) {
1739 let res;
1740 try {
1741 res = args ? fn(...args) : fn();
1742 }
1743 catch (err) {
1744 handleError(err, instance, type);
1745 }
1746 return res;
1747}
1748function callWithAsyncErrorHandling(fn, instance, type, args) {
1749 if (isFunction(fn)) {
1750 const res = callWithErrorHandling(fn, instance, type, args);
1751 if (res && isPromise(res)) {
1752 res.catch(err => {
1753 handleError(err, instance, type);
1754 });
1755 }
1756 return res;
1757 }
1758 const values = [];
1759 for (let i = 0; i < fn.length; i++) {
1760 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1761 }
1762 return values;
1763}
1764function handleError(err, instance, type, throwInDev = true) {
1765 const contextVNode = instance ? instance.vnode : null;
1766 if (instance) {
1767 let cur = instance.parent;
1768 // the exposed instance is the render proxy to keep it consistent with 2.x
1769 const exposedInstance = instance.proxy;
1770 // in production the hook receives only the error code
1771 const errorInfo = ErrorTypeStrings[type] ;
1772 while (cur) {
1773 const errorCapturedHooks = cur.ec;
1774 if (errorCapturedHooks) {
1775 for (let i = 0; i < errorCapturedHooks.length; i++) {
1776 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1777 return;
1778 }
1779 }
1780 }
1781 cur = cur.parent;
1782 }
1783 // app-level handling
1784 const appErrorHandler = instance.appContext.config.errorHandler;
1785 if (appErrorHandler) {
1786 callWithErrorHandling(appErrorHandler, null, 10 /* ErrorCodes.APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1787 return;
1788 }
1789 }
1790 logError(err, type, contextVNode, throwInDev);
1791}
1792function logError(err, type, contextVNode, throwInDev = true) {
1793 {
1794 const info = ErrorTypeStrings[type];
1795 if (contextVNode) {
1796 pushWarningContext(contextVNode);
1797 }
1798 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1799 if (contextVNode) {
1800 popWarningContext();
1801 }
1802 // crash in dev by default so it's more noticeable
1803 if (throwInDev) {
1804 throw err;
1805 }
1806 else {
1807 console.error(err);
1808 }
1809 }
1810}
1811
1812let isFlushing = false;
1813let isFlushPending = false;
1814const queue = [];
1815let flushIndex = 0;
1816const pendingPostFlushCbs = [];
1817let activePostFlushCbs = null;
1818let postFlushIndex = 0;
1819const resolvedPromise = /*#__PURE__*/ Promise.resolve();
1820let currentFlushPromise = null;
1821const RECURSION_LIMIT = 100;
1822function nextTick(fn) {
1823 const p = currentFlushPromise || resolvedPromise;
1824 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1825}
1826// #2768
1827// Use binary-search to find a suitable position in the queue,
1828// so that the queue maintains the increasing order of job's id,
1829// which can prevent the job from being skipped and also can avoid repeated patching.
1830function findInsertionIndex(id) {
1831 // the start index should be `flushIndex + 1`
1832 let start = flushIndex + 1;
1833 let end = queue.length;
1834 while (start < end) {
1835 const middle = (start + end) >>> 1;
1836 const middleJobId = getId(queue[middle]);
1837 middleJobId < id ? (start = middle + 1) : (end = middle);
1838 }
1839 return start;
1840}
1841function queueJob(job) {
1842 // the dedupe search uses the startIndex argument of Array.includes()
1843 // by default the search index includes the current job that is being run
1844 // so it cannot recursively trigger itself again.
1845 // if the job is a watch() callback, the search will start with a +1 index to
1846 // allow it recursively trigger itself - it is the user's responsibility to
1847 // ensure it doesn't end up in an infinite loop.
1848 if (!queue.length ||
1849 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) {
1850 if (job.id == null) {
1851 queue.push(job);
1852 }
1853 else {
1854 queue.splice(findInsertionIndex(job.id), 0, job);
1855 }
1856 queueFlush();
1857 }
1858}
1859function queueFlush() {
1860 if (!isFlushing && !isFlushPending) {
1861 isFlushPending = true;
1862 currentFlushPromise = resolvedPromise.then(flushJobs);
1863 }
1864}
1865function invalidateJob(job) {
1866 const i = queue.indexOf(job);
1867 if (i > flushIndex) {
1868 queue.splice(i, 1);
1869 }
1870}
1871function queuePostFlushCb(cb) {
1872 if (!isArray(cb)) {
1873 if (!activePostFlushCbs ||
1874 !activePostFlushCbs.includes(cb, cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex)) {
1875 pendingPostFlushCbs.push(cb);
1876 }
1877 }
1878 else {
1879 // if cb is an array, it is a component lifecycle hook which can only be
1880 // triggered by a job, which is already deduped in the main queue, so
1881 // we can skip duplicate check here to improve perf
1882 pendingPostFlushCbs.push(...cb);
1883 }
1884 queueFlush();
1885}
1886function flushPreFlushCbs(seen,
1887// if currently flushing, skip the current job itself
1888i = isFlushing ? flushIndex + 1 : 0) {
1889 {
1890 seen = seen || new Map();
1891 }
1892 for (; i < queue.length; i++) {
1893 const cb = queue[i];
1894 if (cb && cb.pre) {
1895 if (checkRecursiveUpdates(seen, cb)) {
1896 continue;
1897 }
1898 queue.splice(i, 1);
1899 i--;
1900 cb();
1901 }
1902 }
1903}
1904function flushPostFlushCbs(seen) {
1905 if (pendingPostFlushCbs.length) {
1906 const deduped = [...new Set(pendingPostFlushCbs)];
1907 pendingPostFlushCbs.length = 0;
1908 // #1947 already has active queue, nested flushPostFlushCbs call
1909 if (activePostFlushCbs) {
1910 activePostFlushCbs.push(...deduped);
1911 return;
1912 }
1913 activePostFlushCbs = deduped;
1914 {
1915 seen = seen || new Map();
1916 }
1917 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1918 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1919 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1920 continue;
1921 }
1922 activePostFlushCbs[postFlushIndex]();
1923 }
1924 activePostFlushCbs = null;
1925 postFlushIndex = 0;
1926 }
1927}
1928const getId = (job) => job.id == null ? Infinity : job.id;
1929const comparator = (a, b) => {
1930 const diff = getId(a) - getId(b);
1931 if (diff === 0) {
1932 if (a.pre && !b.pre)
1933 return -1;
1934 if (b.pre && !a.pre)
1935 return 1;
1936 }
1937 return diff;
1938};
1939function flushJobs(seen) {
1940 isFlushPending = false;
1941 isFlushing = true;
1942 {
1943 seen = seen || new Map();
1944 }
1945 // Sort queue before flush.
1946 // This ensures that:
1947 // 1. Components are updated from parent to child. (because parent is always
1948 // created before the child so its render effect will have smaller
1949 // priority number)
1950 // 2. If a component is unmounted during a parent component's update,
1951 // its update can be skipped.
1952 queue.sort(comparator);
1953 // conditional usage of checkRecursiveUpdate must be determined out of
1954 // try ... catch block since Rollup by default de-optimizes treeshaking
1955 // inside try-catch. This can leave all warning code unshaked. Although
1956 // they would get eventually shaken by a minifier like terser, some minifiers
1957 // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
1958 const check = (job) => checkRecursiveUpdates(seen, job)
1959 ;
1960 try {
1961 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1962 const job = queue[flushIndex];
1963 if (job && job.active !== false) {
1964 if (true && check(job)) {
1965 continue;
1966 }
1967 // console.log(`running:`, job.id)
1968 callWithErrorHandling(job, null, 14 /* ErrorCodes.SCHEDULER */);
1969 }
1970 }
1971 }
1972 finally {
1973 flushIndex = 0;
1974 queue.length = 0;
1975 flushPostFlushCbs(seen);
1976 isFlushing = false;
1977 currentFlushPromise = null;
1978 // some postFlushCb queued jobs!
1979 // keep flushing until it drains.
1980 if (queue.length || pendingPostFlushCbs.length) {
1981 flushJobs(seen);
1982 }
1983 }
1984}
1985function checkRecursiveUpdates(seen, fn) {
1986 if (!seen.has(fn)) {
1987 seen.set(fn, 1);
1988 }
1989 else {
1990 const count = seen.get(fn);
1991 if (count > RECURSION_LIMIT) {
1992 const instance = fn.ownerInstance;
1993 const componentName = instance && getComponentName(instance.type);
1994 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1995 `This means you have a reactive effect that is mutating its own ` +
1996 `dependencies and thus recursively triggering itself. Possible sources ` +
1997 `include component template, render function, updated hook or ` +
1998 `watcher source function.`);
1999 return true;
2000 }
2001 else {
2002 seen.set(fn, count + 1);
2003 }
2004 }
2005}
2006
2007/* eslint-disable no-restricted-globals */
2008let isHmrUpdating = false;
2009const hmrDirtyComponents = new Set();
2010// Expose the HMR runtime on the global object
2011// This makes it entirely tree-shakable without polluting the exports and makes
2012// it easier to be used in toolings like vue-loader
2013// Note: for a component to be eligible for HMR it also needs the __hmrId option
2014// to be set so that its instances can be registered / removed.
2015{
2016 getGlobalThis().__VUE_HMR_RUNTIME__ = {
2017 createRecord: tryWrap(createRecord),
2018 rerender: tryWrap(rerender),
2019 reload: tryWrap(reload)
2020 };
2021}
2022const map = new Map();
2023function registerHMR(instance) {
2024 const id = instance.type.__hmrId;
2025 let record = map.get(id);
2026 if (!record) {
2027 createRecord(id, instance.type);
2028 record = map.get(id);
2029 }
2030 record.instances.add(instance);
2031}
2032function unregisterHMR(instance) {
2033 map.get(instance.type.__hmrId).instances.delete(instance);
2034}
2035function createRecord(id, initialDef) {
2036 if (map.has(id)) {
2037 return false;
2038 }
2039 map.set(id, {
2040 initialDef: normalizeClassComponent(initialDef),
2041 instances: new Set()
2042 });
2043 return true;
2044}
2045function normalizeClassComponent(component) {
2046 return isClassComponent(component) ? component.__vccOpts : component;
2047}
2048function rerender(id, newRender) {
2049 const record = map.get(id);
2050 if (!record) {
2051 return;
2052 }
2053 // update initial record (for not-yet-rendered component)
2054 record.initialDef.render = newRender;
2055 [...record.instances].forEach(instance => {
2056 if (newRender) {
2057 instance.render = newRender;
2058 normalizeClassComponent(instance.type).render = newRender;
2059 }
2060 instance.renderCache = [];
2061 // this flag forces child components with slot content to update
2062 isHmrUpdating = true;
2063 instance.update();
2064 isHmrUpdating = false;
2065 });
2066}
2067function reload(id, newComp) {
2068 const record = map.get(id);
2069 if (!record)
2070 return;
2071 newComp = normalizeClassComponent(newComp);
2072 // update initial def (for not-yet-rendered components)
2073 updateComponentDef(record.initialDef, newComp);
2074 // create a snapshot which avoids the set being mutated during updates
2075 const instances = [...record.instances];
2076 for (const instance of instances) {
2077 const oldComp = normalizeClassComponent(instance.type);
2078 if (!hmrDirtyComponents.has(oldComp)) {
2079 // 1. Update existing comp definition to match new one
2080 if (oldComp !== record.initialDef) {
2081 updateComponentDef(oldComp, newComp);
2082 }
2083 // 2. mark definition dirty. This forces the renderer to replace the
2084 // component on patch.
2085 hmrDirtyComponents.add(oldComp);
2086 }
2087 // 3. invalidate options resolution cache
2088 instance.appContext.optionsCache.delete(instance.type);
2089 // 4. actually update
2090 if (instance.ceReload) {
2091 // custom element
2092 hmrDirtyComponents.add(oldComp);
2093 instance.ceReload(newComp.styles);
2094 hmrDirtyComponents.delete(oldComp);
2095 }
2096 else if (instance.parent) {
2097 // 4. Force the parent instance to re-render. This will cause all updated
2098 // components to be unmounted and re-mounted. Queue the update so that we
2099 // don't end up forcing the same parent to re-render multiple times.
2100 queueJob(instance.parent.update);
2101 }
2102 else if (instance.appContext.reload) {
2103 // root instance mounted via createApp() has a reload method
2104 instance.appContext.reload();
2105 }
2106 else if (typeof window !== 'undefined') {
2107 // root instance inside tree created via raw render(). Force reload.
2108 window.location.reload();
2109 }
2110 else {
2111 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
2112 }
2113 }
2114 // 5. make sure to cleanup dirty hmr components after update
2115 queuePostFlushCb(() => {
2116 for (const instance of instances) {
2117 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
2118 }
2119 });
2120}
2121function updateComponentDef(oldComp, newComp) {
2122 extend(oldComp, newComp);
2123 for (const key in oldComp) {
2124 if (key !== '__file' && !(key in newComp)) {
2125 delete oldComp[key];
2126 }
2127 }
2128}
2129function tryWrap(fn) {
2130 return (id, arg) => {
2131 try {
2132 return fn(id, arg);
2133 }
2134 catch (e) {
2135 console.error(e);
2136 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
2137 `Full reload required.`);
2138 }
2139 };
2140}
2141
2142let devtools;
2143let buffer = [];
2144let devtoolsNotInstalled = false;
2145function emit(event, ...args) {
2146 if (devtools) {
2147 devtools.emit(event, ...args);
2148 }
2149 else if (!devtoolsNotInstalled) {
2150 buffer.push({ event, args });
2151 }
2152}
2153function setDevtoolsHook(hook, target) {
2154 var _a, _b;
2155 devtools = hook;
2156 if (devtools) {
2157 devtools.enabled = true;
2158 buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
2159 buffer = [];
2160 }
2161 else if (
2162 // handle late devtools injection - only do this if we are in an actual
2163 // browser environment to avoid the timer handle stalling test runner exit
2164 // (#4815)
2165 typeof window !== 'undefined' &&
2166 // some envs mock window but not fully
2167 window.HTMLElement &&
2168 // also exclude jsdom
2169 !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
2170 const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
2171 target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
2172 replay.push((newHook) => {
2173 setDevtoolsHook(newHook, target);
2174 });
2175 // clear buffer after 3s - the user probably doesn't have devtools installed
2176 // at all, and keeping the buffer will cause memory leaks (#4738)
2177 setTimeout(() => {
2178 if (!devtools) {
2179 target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
2180 devtoolsNotInstalled = true;
2181 buffer = [];
2182 }
2183 }, 3000);
2184 }
2185 else {
2186 // non-browser env, assume not installed
2187 devtoolsNotInstalled = true;
2188 buffer = [];
2189 }
2190}
2191function devtoolsInitApp(app, version) {
2192 emit("app:init" /* DevtoolsHooks.APP_INIT */, app, version, {
2193 Fragment,
2194 Text,
2195 Comment,
2196 Static
2197 });
2198}
2199function devtoolsUnmountApp(app) {
2200 emit("app:unmount" /* DevtoolsHooks.APP_UNMOUNT */, app);
2201}
2202const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* DevtoolsHooks.COMPONENT_ADDED */);
2203const devtoolsComponentUpdated =
2204/*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* DevtoolsHooks.COMPONENT_UPDATED */);
2205const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* DevtoolsHooks.COMPONENT_REMOVED */);
2206const devtoolsComponentRemoved = (component) => {
2207 if (devtools &&
2208 typeof devtools.cleanupBuffer === 'function' &&
2209 // remove the component if it wasn't buffered
2210 !devtools.cleanupBuffer(component)) {
2211 _devtoolsComponentRemoved(component);
2212 }
2213};
2214function createDevtoolsComponentHook(hook) {
2215 return (component) => {
2216 emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
2217 };
2218}
2219const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* DevtoolsHooks.PERFORMANCE_START */);
2220const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* DevtoolsHooks.PERFORMANCE_END */);
2221function createDevtoolsPerformanceHook(hook) {
2222 return (component, type, time) => {
2223 emit(hook, component.appContext.app, component.uid, component, type, time);
2224 };
2225}
2226function devtoolsComponentEmit(component, event, params) {
2227 emit("component:emit" /* DevtoolsHooks.COMPONENT_EMIT */, component.appContext.app, component, event, params);
2228}
2229
2230function emit$1(instance, event, ...rawArgs) {
2231 if (instance.isUnmounted)
2232 return;
2233 const props = instance.vnode.props || EMPTY_OBJ;
2234 {
2235 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2236 if (emitsOptions) {
2237 if (!(event in emitsOptions) &&
2238 !(false )) {
2239 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2240 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2241 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2242 }
2243 }
2244 else {
2245 const validator = emitsOptions[event];
2246 if (isFunction(validator)) {
2247 const isValid = validator(...rawArgs);
2248 if (!isValid) {
2249 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2250 }
2251 }
2252 }
2253 }
2254 }
2255 let args = rawArgs;
2256 const isModelListener = event.startsWith('update:');
2257 // for v-model update:xxx events, apply modifiers on args
2258 const modelArg = isModelListener && event.slice(7);
2259 if (modelArg && modelArg in props) {
2260 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2261 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2262 if (trim) {
2263 args = rawArgs.map(a => (isString(a) ? a.trim() : a));
2264 }
2265 if (number) {
2266 args = rawArgs.map(toNumber);
2267 }
2268 }
2269 {
2270 devtoolsComponentEmit(instance, event, args);
2271 }
2272 {
2273 const lowerCaseEvent = event.toLowerCase();
2274 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2275 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2276 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2277 `Note that HTML attributes are case-insensitive and you cannot use ` +
2278 `v-on to listen to camelCase events when using in-DOM templates. ` +
2279 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2280 }
2281 }
2282 let handlerName;
2283 let handler = props[(handlerName = toHandlerKey(event))] ||
2284 // also try camelCase event handler (#2249)
2285 props[(handlerName = toHandlerKey(camelize(event)))];
2286 // for v-model update:xxx events, also trigger kebab-case equivalent
2287 // for props passed via kebab-case
2288 if (!handler && isModelListener) {
2289 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2290 }
2291 if (handler) {
2292 callWithAsyncErrorHandling(handler, instance, 6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */, args);
2293 }
2294 const onceHandler = props[handlerName + `Once`];
2295 if (onceHandler) {
2296 if (!instance.emitted) {
2297 instance.emitted = {};
2298 }
2299 else if (instance.emitted[handlerName]) {
2300 return;
2301 }
2302 instance.emitted[handlerName] = true;
2303 callWithAsyncErrorHandling(onceHandler, instance, 6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */, args);
2304 }
2305}
2306function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2307 const cache = appContext.emitsCache;
2308 const cached = cache.get(comp);
2309 if (cached !== undefined) {
2310 return cached;
2311 }
2312 const raw = comp.emits;
2313 let normalized = {};
2314 // apply mixin/extends props
2315 let hasExtends = false;
2316 if (!isFunction(comp)) {
2317 const extendEmits = (raw) => {
2318 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2319 if (normalizedFromExtend) {
2320 hasExtends = true;
2321 extend(normalized, normalizedFromExtend);
2322 }
2323 };
2324 if (!asMixin && appContext.mixins.length) {
2325 appContext.mixins.forEach(extendEmits);
2326 }
2327 if (comp.extends) {
2328 extendEmits(comp.extends);
2329 }
2330 if (comp.mixins) {
2331 comp.mixins.forEach(extendEmits);
2332 }
2333 }
2334 if (!raw && !hasExtends) {
2335 if (isObject(comp)) {
2336 cache.set(comp, null);
2337 }
2338 return null;
2339 }
2340 if (isArray(raw)) {
2341 raw.forEach(key => (normalized[key] = null));
2342 }
2343 else {
2344 extend(normalized, raw);
2345 }
2346 if (isObject(comp)) {
2347 cache.set(comp, normalized);
2348 }
2349 return normalized;
2350}
2351// Check if an incoming prop key is a declared emit event listener.
2352// e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2353// both considered matched listeners.
2354function isEmitListener(options, key) {
2355 if (!options || !isOn(key)) {
2356 return false;
2357 }
2358 key = key.slice(2).replace(/Once$/, '');
2359 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2360 hasOwn(options, hyphenate(key)) ||
2361 hasOwn(options, key));
2362}
2363
2364/**
2365 * mark the current rendering instance for asset resolution (e.g.
2366 * resolveComponent, resolveDirective) during render
2367 */
2368let currentRenderingInstance = null;
2369let currentScopeId = null;
2370/**
2371 * Note: rendering calls maybe nested. The function returns the parent rendering
2372 * instance if present, which should be restored after the render is done:
2373 *
2374 * ```js
2375 * const prev = setCurrentRenderingInstance(i)
2376 * // ...render
2377 * setCurrentRenderingInstance(prev)
2378 * ```
2379 */
2380function setCurrentRenderingInstance(instance) {
2381 const prev = currentRenderingInstance;
2382 currentRenderingInstance = instance;
2383 currentScopeId = (instance && instance.type.__scopeId) || null;
2384 return prev;
2385}
2386/**
2387 * Set scope id when creating hoisted vnodes.
2388 * @private compiler helper
2389 */
2390function pushScopeId(id) {
2391 currentScopeId = id;
2392}
2393/**
2394 * Technically we no longer need this after 3.0.8 but we need to keep the same
2395 * API for backwards compat w/ code generated by compilers.
2396 * @private
2397 */
2398function popScopeId() {
2399 currentScopeId = null;
2400}
2401/**
2402 * Only for backwards compat
2403 * @private
2404 */
2405const withScopeId = (_id) => withCtx;
2406/**
2407 * Wrap a slot function to memoize current rendering instance
2408 * @private compiler helper
2409 */
2410function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2411) {
2412 if (!ctx)
2413 return fn;
2414 // already normalized
2415 if (fn._n) {
2416 return fn;
2417 }
2418 const renderFnWithContext = (...args) => {
2419 // If a user calls a compiled slot inside a template expression (#1745), it
2420 // can mess up block tracking, so by default we disable block tracking and
2421 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2422 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2423 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2424 if (renderFnWithContext._d) {
2425 setBlockTracking(-1);
2426 }
2427 const prevInstance = setCurrentRenderingInstance(ctx);
2428 let res;
2429 try {
2430 res = fn(...args);
2431 }
2432 finally {
2433 setCurrentRenderingInstance(prevInstance);
2434 if (renderFnWithContext._d) {
2435 setBlockTracking(1);
2436 }
2437 }
2438 {
2439 devtoolsComponentUpdated(ctx);
2440 }
2441 return res;
2442 };
2443 // mark normalized to avoid duplicated wrapping
2444 renderFnWithContext._n = true;
2445 // mark this as compiled by default
2446 // this is used in vnode.ts -> normalizeChildren() to set the slot
2447 // rendering flag.
2448 renderFnWithContext._c = true;
2449 // disable block tracking by default
2450 renderFnWithContext._d = true;
2451 return renderFnWithContext;
2452}
2453
2454/**
2455 * dev only flag to track whether $attrs was used during render.
2456 * If $attrs was used during render then the warning for failed attrs
2457 * fallthrough can be suppressed.
2458 */
2459let accessedAttrs = false;
2460function markAttrsAccessed() {
2461 accessedAttrs = true;
2462}
2463function renderComponentRoot(instance) {
2464 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2465 let result;
2466 let fallthroughAttrs;
2467 const prev = setCurrentRenderingInstance(instance);
2468 {
2469 accessedAttrs = false;
2470 }
2471 try {
2472 if (vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */) {
2473 // withProxy is a proxy with a different `has` trap only for
2474 // runtime-compiled render functions using `with` block.
2475 const proxyToUse = withProxy || proxy;
2476 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2477 fallthroughAttrs = attrs;
2478 }
2479 else {
2480 // functional
2481 const render = Component;
2482 // in dev, mark attrs accessed if optional props (attrs === props)
2483 if (true && attrs === props) {
2484 markAttrsAccessed();
2485 }
2486 result = normalizeVNode(render.length > 1
2487 ? render(props, true
2488 ? {
2489 get attrs() {
2490 markAttrsAccessed();
2491 return attrs;
2492 },
2493 slots,
2494 emit
2495 }
2496 : { attrs, slots, emit })
2497 : render(props, null /* we know it doesn't need it */));
2498 fallthroughAttrs = Component.props
2499 ? attrs
2500 : getFunctionalFallthrough(attrs);
2501 }
2502 }
2503 catch (err) {
2504 blockStack.length = 0;
2505 handleError(err, instance, 1 /* ErrorCodes.RENDER_FUNCTION */);
2506 result = createVNode(Comment);
2507 }
2508 // attr merging
2509 // in dev mode, comments are preserved, and it's possible for a template
2510 // to have comments along side the root element which makes it a fragment
2511 let root = result;
2512 let setRoot = undefined;
2513 if (result.patchFlag > 0 &&
2514 result.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */) {
2515 [root, setRoot] = getChildRoot(result);
2516 }
2517 if (fallthroughAttrs && inheritAttrs !== false) {
2518 const keys = Object.keys(fallthroughAttrs);
2519 const { shapeFlag } = root;
2520 if (keys.length) {
2521 if (shapeFlag & (1 /* ShapeFlags.ELEMENT */ | 6 /* ShapeFlags.COMPONENT */)) {
2522 if (propsOptions && keys.some(isModelListener)) {
2523 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2524 // prop, it indicates this component expects to handle v-model and
2525 // it should not fallthrough.
2526 // related: #1543, #1643, #1989
2527 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2528 }
2529 root = cloneVNode(root, fallthroughAttrs);
2530 }
2531 else if (!accessedAttrs && root.type !== Comment) {
2532 const allAttrs = Object.keys(attrs);
2533 const eventAttrs = [];
2534 const extraAttrs = [];
2535 for (let i = 0, l = allAttrs.length; i < l; i++) {
2536 const key = allAttrs[i];
2537 if (isOn(key)) {
2538 // ignore v-model handlers when they fail to fallthrough
2539 if (!isModelListener(key)) {
2540 // remove `on`, lowercase first letter to reflect event casing
2541 // accurately
2542 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2543 }
2544 }
2545 else {
2546 extraAttrs.push(key);
2547 }
2548 }
2549 if (extraAttrs.length) {
2550 warn$1(`Extraneous non-props attributes (` +
2551 `${extraAttrs.join(', ')}) ` +
2552 `were passed to component but could not be automatically inherited ` +
2553 `because component renders fragment or text root nodes.`);
2554 }
2555 if (eventAttrs.length) {
2556 warn$1(`Extraneous non-emits event listeners (` +
2557 `${eventAttrs.join(', ')}) ` +
2558 `were passed to component but could not be automatically inherited ` +
2559 `because component renders fragment or text root nodes. ` +
2560 `If the listener is intended to be a component custom event listener only, ` +
2561 `declare it using the "emits" option.`);
2562 }
2563 }
2564 }
2565 }
2566 // inherit directives
2567 if (vnode.dirs) {
2568 if (!isElementRoot(root)) {
2569 warn$1(`Runtime directive used on component with non-element root node. ` +
2570 `The directives will not function as intended.`);
2571 }
2572 // clone before mutating since the root may be a hoisted vnode
2573 root = cloneVNode(root);
2574 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2575 }
2576 // inherit transition data
2577 if (vnode.transition) {
2578 if (!isElementRoot(root)) {
2579 warn$1(`Component inside <Transition> renders non-element root node ` +
2580 `that cannot be animated.`);
2581 }
2582 root.transition = vnode.transition;
2583 }
2584 if (setRoot) {
2585 setRoot(root);
2586 }
2587 else {
2588 result = root;
2589 }
2590 setCurrentRenderingInstance(prev);
2591 return result;
2592}
2593/**
2594 * dev only
2595 * In dev mode, template root level comments are rendered, which turns the
2596 * template into a fragment root, but we need to locate the single element
2597 * root for attrs and scope id processing.
2598 */
2599const getChildRoot = (vnode) => {
2600 const rawChildren = vnode.children;
2601 const dynamicChildren = vnode.dynamicChildren;
2602 const childRoot = filterSingleRoot(rawChildren);
2603 if (!childRoot) {
2604 return [vnode, undefined];
2605 }
2606 const index = rawChildren.indexOf(childRoot);
2607 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2608 const setRoot = (updatedRoot) => {
2609 rawChildren[index] = updatedRoot;
2610 if (dynamicChildren) {
2611 if (dynamicIndex > -1) {
2612 dynamicChildren[dynamicIndex] = updatedRoot;
2613 }
2614 else if (updatedRoot.patchFlag > 0) {
2615 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2616 }
2617 }
2618 };
2619 return [normalizeVNode(childRoot), setRoot];
2620};
2621function filterSingleRoot(children) {
2622 let singleRoot;
2623 for (let i = 0; i < children.length; i++) {
2624 const child = children[i];
2625 if (isVNode(child)) {
2626 // ignore user comment
2627 if (child.type !== Comment || child.children === 'v-if') {
2628 if (singleRoot) {
2629 // has more than 1 non-comment child, return now
2630 return;
2631 }
2632 else {
2633 singleRoot = child;
2634 }
2635 }
2636 }
2637 else {
2638 return;
2639 }
2640 }
2641 return singleRoot;
2642}
2643const getFunctionalFallthrough = (attrs) => {
2644 let res;
2645 for (const key in attrs) {
2646 if (key === 'class' || key === 'style' || isOn(key)) {
2647 (res || (res = {}))[key] = attrs[key];
2648 }
2649 }
2650 return res;
2651};
2652const filterModelListeners = (attrs, props) => {
2653 const res = {};
2654 for (const key in attrs) {
2655 if (!isModelListener(key) || !(key.slice(9) in props)) {
2656 res[key] = attrs[key];
2657 }
2658 }
2659 return res;
2660};
2661const isElementRoot = (vnode) => {
2662 return (vnode.shapeFlag & (6 /* ShapeFlags.COMPONENT */ | 1 /* ShapeFlags.ELEMENT */) ||
2663 vnode.type === Comment // potential v-if branch switch
2664 );
2665};
2666function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2667 const { props: prevProps, children: prevChildren, component } = prevVNode;
2668 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2669 const emits = component.emitsOptions;
2670 // Parent component's render function was hot-updated. Since this may have
2671 // caused the child component's slots content to have changed, we need to
2672 // force the child to update as well.
2673 if ((prevChildren || nextChildren) && isHmrUpdating) {
2674 return true;
2675 }
2676 // force child update for runtime directive or transition on component vnode.
2677 if (nextVNode.dirs || nextVNode.transition) {
2678 return true;
2679 }
2680 if (optimized && patchFlag >= 0) {
2681 if (patchFlag & 1024 /* PatchFlags.DYNAMIC_SLOTS */) {
2682 // slot content that references values that might have changed,
2683 // e.g. in a v-for
2684 return true;
2685 }
2686 if (patchFlag & 16 /* PatchFlags.FULL_PROPS */) {
2687 if (!prevProps) {
2688 return !!nextProps;
2689 }
2690 // presence of this flag indicates props are always non-null
2691 return hasPropsChanged(prevProps, nextProps, emits);
2692 }
2693 else if (patchFlag & 8 /* PatchFlags.PROPS */) {
2694 const dynamicProps = nextVNode.dynamicProps;
2695 for (let i = 0; i < dynamicProps.length; i++) {
2696 const key = dynamicProps[i];
2697 if (nextProps[key] !== prevProps[key] &&
2698 !isEmitListener(emits, key)) {
2699 return true;
2700 }
2701 }
2702 }
2703 }
2704 else {
2705 // this path is only taken by manually written render functions
2706 // so presence of any children leads to a forced update
2707 if (prevChildren || nextChildren) {
2708 if (!nextChildren || !nextChildren.$stable) {
2709 return true;
2710 }
2711 }
2712 if (prevProps === nextProps) {
2713 return false;
2714 }
2715 if (!prevProps) {
2716 return !!nextProps;
2717 }
2718 if (!nextProps) {
2719 return true;
2720 }
2721 return hasPropsChanged(prevProps, nextProps, emits);
2722 }
2723 return false;
2724}
2725function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2726 const nextKeys = Object.keys(nextProps);
2727 if (nextKeys.length !== Object.keys(prevProps).length) {
2728 return true;
2729 }
2730 for (let i = 0; i < nextKeys.length; i++) {
2731 const key = nextKeys[i];
2732 if (nextProps[key] !== prevProps[key] &&
2733 !isEmitListener(emitsOptions, key)) {
2734 return true;
2735 }
2736 }
2737 return false;
2738}
2739function updateHOCHostEl({ vnode, parent }, el // HostNode
2740) {
2741 while (parent && parent.subTree === vnode) {
2742 (vnode = parent.vnode).el = el;
2743 parent = parent.parent;
2744 }
2745}
2746
2747const isSuspense = (type) => type.__isSuspense;
2748// Suspense exposes a component-like API, and is treated like a component
2749// in the compiler, but internally it's a special built-in type that hooks
2750// directly into the renderer.
2751const SuspenseImpl = {
2752 name: 'Suspense',
2753 // In order to make Suspense tree-shakable, we need to avoid importing it
2754 // directly in the renderer. The renderer checks for the __isSuspense flag
2755 // on a vnode's type and calls the `process` method, passing in renderer
2756 // internals.
2757 __isSuspense: true,
2758 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2759 // platform-specific impl passed from renderer
2760 rendererInternals) {
2761 if (n1 == null) {
2762 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2763 }
2764 else {
2765 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2766 }
2767 },
2768 hydrate: hydrateSuspense,
2769 create: createSuspenseBoundary,
2770 normalize: normalizeSuspenseChildren
2771};
2772// Force-casted public typing for h and TSX props inference
2773const Suspense = (SuspenseImpl
2774 );
2775function triggerEvent(vnode, name) {
2776 const eventListener = vnode.props && vnode.props[name];
2777 if (isFunction(eventListener)) {
2778 eventListener();
2779 }
2780}
2781function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2782 const { p: patch, o: { createElement } } = rendererInternals;
2783 const hiddenContainer = createElement('div');
2784 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2785 // start mounting the content subtree in an off-dom container
2786 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2787 // now check if we have encountered any async deps
2788 if (suspense.deps > 0) {
2789 // has async
2790 // invoke @fallback event
2791 triggerEvent(vnode, 'onPending');
2792 triggerEvent(vnode, 'onFallback');
2793 // mount the fallback tree
2794 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2795 isSVG, slotScopeIds);
2796 setActiveBranch(suspense, vnode.ssFallback);
2797 }
2798 else {
2799 // Suspense has no async deps. Just resolve.
2800 suspense.resolve();
2801 }
2802}
2803function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2804 const suspense = (n2.suspense = n1.suspense);
2805 suspense.vnode = n2;
2806 n2.el = n1.el;
2807 const newBranch = n2.ssContent;
2808 const newFallback = n2.ssFallback;
2809 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2810 if (pendingBranch) {
2811 suspense.pendingBranch = newBranch;
2812 if (isSameVNodeType(newBranch, pendingBranch)) {
2813 // same root type but content may have changed.
2814 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2815 if (suspense.deps <= 0) {
2816 suspense.resolve();
2817 }
2818 else if (isInFallback) {
2819 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2820 isSVG, slotScopeIds, optimized);
2821 setActiveBranch(suspense, newFallback);
2822 }
2823 }
2824 else {
2825 // toggled before pending tree is resolved
2826 suspense.pendingId++;
2827 if (isHydrating) {
2828 // if toggled before hydration is finished, the current DOM tree is
2829 // no longer valid. set it as the active branch so it will be unmounted
2830 // when resolved
2831 suspense.isHydrating = false;
2832 suspense.activeBranch = pendingBranch;
2833 }
2834 else {
2835 unmount(pendingBranch, parentComponent, suspense);
2836 }
2837 // increment pending ID. this is used to invalidate async callbacks
2838 // reset suspense state
2839 suspense.deps = 0;
2840 // discard effects from pending branch
2841 suspense.effects.length = 0;
2842 // discard previous container
2843 suspense.hiddenContainer = createElement('div');
2844 if (isInFallback) {
2845 // already in fallback state
2846 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2847 if (suspense.deps <= 0) {
2848 suspense.resolve();
2849 }
2850 else {
2851 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2852 isSVG, slotScopeIds, optimized);
2853 setActiveBranch(suspense, newFallback);
2854 }
2855 }
2856 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2857 // toggled "back" to current active branch
2858 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2859 // force resolve
2860 suspense.resolve(true);
2861 }
2862 else {
2863 // switched to a 3rd branch
2864 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2865 if (suspense.deps <= 0) {
2866 suspense.resolve();
2867 }
2868 }
2869 }
2870 }
2871 else {
2872 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2873 // root did not change, just normal patch
2874 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2875 setActiveBranch(suspense, newBranch);
2876 }
2877 else {
2878 // root node toggled
2879 // invoke @pending event
2880 triggerEvent(n2, 'onPending');
2881 // mount pending branch in off-dom container
2882 suspense.pendingBranch = newBranch;
2883 suspense.pendingId++;
2884 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2885 if (suspense.deps <= 0) {
2886 // incoming branch has no async deps, resolve now.
2887 suspense.resolve();
2888 }
2889 else {
2890 const { timeout, pendingId } = suspense;
2891 if (timeout > 0) {
2892 setTimeout(() => {
2893 if (suspense.pendingId === pendingId) {
2894 suspense.fallback(newFallback);
2895 }
2896 }, timeout);
2897 }
2898 else if (timeout === 0) {
2899 suspense.fallback(newFallback);
2900 }
2901 }
2902 }
2903 }
2904}
2905let hasWarned = false;
2906function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2907 /* istanbul ignore if */
2908 if (!hasWarned) {
2909 hasWarned = true;
2910 // @ts-ignore `console.info` cannot be null error
2911 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2912 }
2913 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2914 const timeout = toNumber(vnode.props && vnode.props.timeout);
2915 const suspense = {
2916 vnode,
2917 parent,
2918 parentComponent,
2919 isSVG,
2920 container,
2921 hiddenContainer,
2922 anchor,
2923 deps: 0,
2924 pendingId: 0,
2925 timeout: typeof timeout === 'number' ? timeout : -1,
2926 activeBranch: null,
2927 pendingBranch: null,
2928 isInFallback: true,
2929 isHydrating,
2930 isUnmounted: false,
2931 effects: [],
2932 resolve(resume = false) {
2933 {
2934 if (!resume && !suspense.pendingBranch) {
2935 throw new Error(`suspense.resolve() is called without a pending branch.`);
2936 }
2937 if (suspense.isUnmounted) {
2938 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2939 }
2940 }
2941 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2942 if (suspense.isHydrating) {
2943 suspense.isHydrating = false;
2944 }
2945 else if (!resume) {
2946 const delayEnter = activeBranch &&
2947 pendingBranch.transition &&
2948 pendingBranch.transition.mode === 'out-in';
2949 if (delayEnter) {
2950 activeBranch.transition.afterLeave = () => {
2951 if (pendingId === suspense.pendingId) {
2952 move(pendingBranch, container, anchor, 0 /* MoveType.ENTER */);
2953 }
2954 };
2955 }
2956 // this is initial anchor on mount
2957 let { anchor } = suspense;
2958 // unmount current active tree
2959 if (activeBranch) {
2960 // if the fallback tree was mounted, it may have been moved
2961 // as part of a parent suspense. get the latest anchor for insertion
2962 anchor = next(activeBranch);
2963 unmount(activeBranch, parentComponent, suspense, true);
2964 }
2965 if (!delayEnter) {
2966 // move content from off-dom container to actual container
2967 move(pendingBranch, container, anchor, 0 /* MoveType.ENTER */);
2968 }
2969 }
2970 setActiveBranch(suspense, pendingBranch);
2971 suspense.pendingBranch = null;
2972 suspense.isInFallback = false;
2973 // flush buffered effects
2974 // check if there is a pending parent suspense
2975 let parent = suspense.parent;
2976 let hasUnresolvedAncestor = false;
2977 while (parent) {
2978 if (parent.pendingBranch) {
2979 // found a pending parent suspense, merge buffered post jobs
2980 // into that parent
2981 parent.effects.push(...effects);
2982 hasUnresolvedAncestor = true;
2983 break;
2984 }
2985 parent = parent.parent;
2986 }
2987 // no pending parent suspense, flush all jobs
2988 if (!hasUnresolvedAncestor) {
2989 queuePostFlushCb(effects);
2990 }
2991 suspense.effects = [];
2992 // invoke @resolve event
2993 triggerEvent(vnode, 'onResolve');
2994 },
2995 fallback(fallbackVNode) {
2996 if (!suspense.pendingBranch) {
2997 return;
2998 }
2999 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
3000 // invoke @fallback event
3001 triggerEvent(vnode, 'onFallback');
3002 const anchor = next(activeBranch);
3003 const mountFallback = () => {
3004 if (!suspense.isInFallback) {
3005 return;
3006 }
3007 // mount the fallback tree
3008 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
3009 isSVG, slotScopeIds, optimized);
3010 setActiveBranch(suspense, fallbackVNode);
3011 };
3012 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
3013 if (delayEnter) {
3014 activeBranch.transition.afterLeave = mountFallback;
3015 }
3016 suspense.isInFallback = true;
3017 // unmount current active branch
3018 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
3019 true // shouldRemove
3020 );
3021 if (!delayEnter) {
3022 mountFallback();
3023 }
3024 },
3025 move(container, anchor, type) {
3026 suspense.activeBranch &&
3027 move(suspense.activeBranch, container, anchor, type);
3028 suspense.container = container;
3029 },
3030 next() {
3031 return suspense.activeBranch && next(suspense.activeBranch);
3032 },
3033 registerDep(instance, setupRenderEffect) {
3034 const isInPendingSuspense = !!suspense.pendingBranch;
3035 if (isInPendingSuspense) {
3036 suspense.deps++;
3037 }
3038 const hydratedEl = instance.vnode.el;
3039 instance
3040 .asyncDep.catch(err => {
3041 handleError(err, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
3042 })
3043 .then(asyncSetupResult => {
3044 // retry when the setup() promise resolves.
3045 // component may have been unmounted before resolve.
3046 if (instance.isUnmounted ||
3047 suspense.isUnmounted ||
3048 suspense.pendingId !== instance.suspenseId) {
3049 return;
3050 }
3051 // retry from this component
3052 instance.asyncResolved = true;
3053 const { vnode } = instance;
3054 {
3055 pushWarningContext(vnode);
3056 }
3057 handleSetupResult(instance, asyncSetupResult, false);
3058 if (hydratedEl) {
3059 // vnode may have been replaced if an update happened before the
3060 // async dep is resolved.
3061 vnode.el = hydratedEl;
3062 }
3063 const placeholder = !hydratedEl && instance.subTree.el;
3064 setupRenderEffect(instance, vnode,
3065 // component may have been moved before resolve.
3066 // if this is not a hydration, instance.subTree will be the comment
3067 // placeholder.
3068 parentNode(hydratedEl || instance.subTree.el),
3069 // anchor will not be used if this is hydration, so only need to
3070 // consider the comment placeholder case.
3071 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3072 if (placeholder) {
3073 remove(placeholder);
3074 }
3075 updateHOCHostEl(instance, vnode.el);
3076 {
3077 popWarningContext();
3078 }
3079 // only decrease deps count if suspense is not already resolved
3080 if (isInPendingSuspense && --suspense.deps === 0) {
3081 suspense.resolve();
3082 }
3083 });
3084 },
3085 unmount(parentSuspense, doRemove) {
3086 suspense.isUnmounted = true;
3087 if (suspense.activeBranch) {
3088 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3089 }
3090 if (suspense.pendingBranch) {
3091 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3092 }
3093 }
3094 };
3095 return suspense;
3096}
3097function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3098 /* eslint-disable no-restricted-globals */
3099 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3100 // there are two possible scenarios for server-rendered suspense:
3101 // - success: ssr content should be fully resolved
3102 // - failure: ssr content should be the fallback branch.
3103 // however, on the client we don't really know if it has failed or not
3104 // attempt to hydrate the DOM assuming it has succeeded, but we still
3105 // need to construct a suspense boundary first
3106 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3107 if (suspense.deps === 0) {
3108 suspense.resolve();
3109 }
3110 return result;
3111 /* eslint-enable no-restricted-globals */
3112}
3113function normalizeSuspenseChildren(vnode) {
3114 const { shapeFlag, children } = vnode;
3115 const isSlotChildren = shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */;
3116 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3117 vnode.ssFallback = isSlotChildren
3118 ? normalizeSuspenseSlot(children.fallback)
3119 : createVNode(Comment);
3120}
3121function normalizeSuspenseSlot(s) {
3122 let block;
3123 if (isFunction(s)) {
3124 const trackBlock = isBlockTreeEnabled && s._c;
3125 if (trackBlock) {
3126 // disableTracking: false
3127 // allow block tracking for compiled slots
3128 // (see ./componentRenderContext.ts)
3129 s._d = false;
3130 openBlock();
3131 }
3132 s = s();
3133 if (trackBlock) {
3134 s._d = true;
3135 block = currentBlock;
3136 closeBlock();
3137 }
3138 }
3139 if (isArray(s)) {
3140 const singleChild = filterSingleRoot(s);
3141 if (!singleChild) {
3142 warn$1(`<Suspense> slots expect a single root node.`);
3143 }
3144 s = singleChild;
3145 }
3146 s = normalizeVNode(s);
3147 if (block && !s.dynamicChildren) {
3148 s.dynamicChildren = block.filter(c => c !== s);
3149 }
3150 return s;
3151}
3152function queueEffectWithSuspense(fn, suspense) {
3153 if (suspense && suspense.pendingBranch) {
3154 if (isArray(fn)) {
3155 suspense.effects.push(...fn);
3156 }
3157 else {
3158 suspense.effects.push(fn);
3159 }
3160 }
3161 else {
3162 queuePostFlushCb(fn);
3163 }
3164}
3165function setActiveBranch(suspense, branch) {
3166 suspense.activeBranch = branch;
3167 const { vnode, parentComponent } = suspense;
3168 const el = (vnode.el = branch.el);
3169 // in case suspense is the root node of a component,
3170 // recursively update the HOC el
3171 if (parentComponent && parentComponent.subTree === vnode) {
3172 parentComponent.vnode.el = el;
3173 updateHOCHostEl(parentComponent, el);
3174 }
3175}
3176
3177function provide(key, value) {
3178 if (!currentInstance) {
3179 {
3180 warn$1(`provide() can only be used inside setup().`);
3181 }
3182 }
3183 else {
3184 let provides = currentInstance.provides;
3185 // by default an instance inherits its parent's provides object
3186 // but when it needs to provide values of its own, it creates its
3187 // own provides object using parent provides object as prototype.
3188 // this way in `inject` we can simply look up injections from direct
3189 // parent and let the prototype chain do the work.
3190 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3191 if (parentProvides === provides) {
3192 provides = currentInstance.provides = Object.create(parentProvides);
3193 }
3194 // TS doesn't allow symbol as index type
3195 provides[key] = value;
3196 }
3197}
3198function inject(key, defaultValue, treatDefaultAsFactory = false) {
3199 // fallback to `currentRenderingInstance` so that this can be called in
3200 // a functional component
3201 const instance = currentInstance || currentRenderingInstance;
3202 if (instance) {
3203 // #2400
3204 // to support `app.use` plugins,
3205 // fallback to appContext's `provides` if the instance is at root
3206 const provides = instance.parent == null
3207 ? instance.vnode.appContext && instance.vnode.appContext.provides
3208 : instance.parent.provides;
3209 if (provides && key in provides) {
3210 // TS doesn't allow symbol as index type
3211 return provides[key];
3212 }
3213 else if (arguments.length > 1) {
3214 return treatDefaultAsFactory && isFunction(defaultValue)
3215 ? defaultValue.call(instance.proxy)
3216 : defaultValue;
3217 }
3218 else {
3219 warn$1(`injection "${String(key)}" not found.`);
3220 }
3221 }
3222 else {
3223 warn$1(`inject() can only be used inside setup() or functional components.`);
3224 }
3225}
3226
3227// Simple effect.
3228function watchEffect(effect, options) {
3229 return doWatch(effect, null, options);
3230}
3231function watchPostEffect(effect, options) {
3232 return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'post' }) ));
3233}
3234function watchSyncEffect(effect, options) {
3235 return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'sync' }) ));
3236}
3237// initial value for watchers to trigger on undefined initial values
3238const INITIAL_WATCHER_VALUE = {};
3239// implementation
3240function watch(source, cb, options) {
3241 if (!isFunction(cb)) {
3242 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3243 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3244 `supports \`watch(source, cb, options?) signature.`);
3245 }
3246 return doWatch(source, cb, options);
3247}
3248function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
3249 if (!cb) {
3250 if (immediate !== undefined) {
3251 warn$1(`watch() "immediate" option is only respected when using the ` +
3252 `watch(source, callback, options?) signature.`);
3253 }
3254 if (deep !== undefined) {
3255 warn$1(`watch() "deep" option is only respected when using the ` +
3256 `watch(source, callback, options?) signature.`);
3257 }
3258 }
3259 const warnInvalidSource = (s) => {
3260 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3261 `a reactive object, or an array of these types.`);
3262 };
3263 const instance = currentInstance;
3264 let getter;
3265 let forceTrigger = false;
3266 let isMultiSource = false;
3267 if (isRef(source)) {
3268 getter = () => source.value;
3269 forceTrigger = isShallow(source);
3270 }
3271 else if (isReactive(source)) {
3272 getter = () => source;
3273 deep = true;
3274 }
3275 else if (isArray(source)) {
3276 isMultiSource = true;
3277 forceTrigger = source.some(s => isReactive(s) || isShallow(s));
3278 getter = () => source.map(s => {
3279 if (isRef(s)) {
3280 return s.value;
3281 }
3282 else if (isReactive(s)) {
3283 return traverse(s);
3284 }
3285 else if (isFunction(s)) {
3286 return callWithErrorHandling(s, instance, 2 /* ErrorCodes.WATCH_GETTER */);
3287 }
3288 else {
3289 warnInvalidSource(s);
3290 }
3291 });
3292 }
3293 else if (isFunction(source)) {
3294 if (cb) {
3295 // getter with cb
3296 getter = () => callWithErrorHandling(source, instance, 2 /* ErrorCodes.WATCH_GETTER */);
3297 }
3298 else {
3299 // no cb -> simple effect
3300 getter = () => {
3301 if (instance && instance.isUnmounted) {
3302 return;
3303 }
3304 if (cleanup) {
3305 cleanup();
3306 }
3307 return callWithAsyncErrorHandling(source, instance, 3 /* ErrorCodes.WATCH_CALLBACK */, [onCleanup]);
3308 };
3309 }
3310 }
3311 else {
3312 getter = NOOP;
3313 warnInvalidSource(source);
3314 }
3315 if (cb && deep) {
3316 const baseGetter = getter;
3317 getter = () => traverse(baseGetter());
3318 }
3319 let cleanup;
3320 let onCleanup = (fn) => {
3321 cleanup = effect.onStop = () => {
3322 callWithErrorHandling(fn, instance, 4 /* ErrorCodes.WATCH_CLEANUP */);
3323 };
3324 };
3325 let oldValue = isMultiSource
3326 ? new Array(source.length).fill(INITIAL_WATCHER_VALUE)
3327 : INITIAL_WATCHER_VALUE;
3328 const job = () => {
3329 if (!effect.active) {
3330 return;
3331 }
3332 if (cb) {
3333 // watch(source, cb)
3334 const newValue = effect.run();
3335 if (deep ||
3336 forceTrigger ||
3337 (isMultiSource
3338 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3339 : hasChanged(newValue, oldValue)) ||
3340 (false )) {
3341 // cleanup before running cb again
3342 if (cleanup) {
3343 cleanup();
3344 }
3345 callWithAsyncErrorHandling(cb, instance, 3 /* ErrorCodes.WATCH_CALLBACK */, [
3346 newValue,
3347 // pass undefined as the old value when it's changed for the first time
3348 oldValue === INITIAL_WATCHER_VALUE
3349 ? undefined
3350 : (isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE)
3351 ? []
3352 : oldValue,
3353 onCleanup
3354 ]);
3355 oldValue = newValue;
3356 }
3357 }
3358 else {
3359 // watchEffect
3360 effect.run();
3361 }
3362 };
3363 // important: mark the job as a watcher callback so that scheduler knows
3364 // it is allowed to self-trigger (#1727)
3365 job.allowRecurse = !!cb;
3366 let scheduler;
3367 if (flush === 'sync') {
3368 scheduler = job; // the scheduler function gets called directly
3369 }
3370 else if (flush === 'post') {
3371 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3372 }
3373 else {
3374 // default: 'pre'
3375 job.pre = true;
3376 if (instance)
3377 job.id = instance.uid;
3378 scheduler = () => queueJob(job);
3379 }
3380 const effect = new ReactiveEffect(getter, scheduler);
3381 {
3382 effect.onTrack = onTrack;
3383 effect.onTrigger = onTrigger;
3384 }
3385 // initial run
3386 if (cb) {
3387 if (immediate) {
3388 job();
3389 }
3390 else {
3391 oldValue = effect.run();
3392 }
3393 }
3394 else if (flush === 'post') {
3395 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
3396 }
3397 else {
3398 effect.run();
3399 }
3400 const unwatch = () => {
3401 effect.stop();
3402 if (instance && instance.scope) {
3403 remove(instance.scope.effects, effect);
3404 }
3405 };
3406 return unwatch;
3407}
3408// this.$watch
3409function instanceWatch(source, value, options) {
3410 const publicThis = this.proxy;
3411 const getter = isString(source)
3412 ? source.includes('.')
3413 ? createPathGetter(publicThis, source)
3414 : () => publicThis[source]
3415 : source.bind(publicThis, publicThis);
3416 let cb;
3417 if (isFunction(value)) {
3418 cb = value;
3419 }
3420 else {
3421 cb = value.handler;
3422 options = value;
3423 }
3424 const cur = currentInstance;
3425 setCurrentInstance(this);
3426 const res = doWatch(getter, cb.bind(publicThis), options);
3427 if (cur) {
3428 setCurrentInstance(cur);
3429 }
3430 else {
3431 unsetCurrentInstance();
3432 }
3433 return res;
3434}
3435function createPathGetter(ctx, path) {
3436 const segments = path.split('.');
3437 return () => {
3438 let cur = ctx;
3439 for (let i = 0; i < segments.length && cur; i++) {
3440 cur = cur[segments[i]];
3441 }
3442 return cur;
3443 };
3444}
3445function traverse(value, seen) {
3446 if (!isObject(value) || value["__v_skip" /* ReactiveFlags.SKIP */]) {
3447 return value;
3448 }
3449 seen = seen || new Set();
3450 if (seen.has(value)) {
3451 return value;
3452 }
3453 seen.add(value);
3454 if (isRef(value)) {
3455 traverse(value.value, seen);
3456 }
3457 else if (isArray(value)) {
3458 for (let i = 0; i < value.length; i++) {
3459 traverse(value[i], seen);
3460 }
3461 }
3462 else if (isSet(value) || isMap(value)) {
3463 value.forEach((v) => {
3464 traverse(v, seen);
3465 });
3466 }
3467 else if (isPlainObject(value)) {
3468 for (const key in value) {
3469 traverse(value[key], seen);
3470 }
3471 }
3472 return value;
3473}
3474
3475function useTransitionState() {
3476 const state = {
3477 isMounted: false,
3478 isLeaving: false,
3479 isUnmounting: false,
3480 leavingVNodes: new Map()
3481 };
3482 onMounted(() => {
3483 state.isMounted = true;
3484 });
3485 onBeforeUnmount(() => {
3486 state.isUnmounting = true;
3487 });
3488 return state;
3489}
3490const TransitionHookValidator = [Function, Array];
3491const BaseTransitionImpl = {
3492 name: `BaseTransition`,
3493 props: {
3494 mode: String,
3495 appear: Boolean,
3496 persisted: Boolean,
3497 // enter
3498 onBeforeEnter: TransitionHookValidator,
3499 onEnter: TransitionHookValidator,
3500 onAfterEnter: TransitionHookValidator,
3501 onEnterCancelled: TransitionHookValidator,
3502 // leave
3503 onBeforeLeave: TransitionHookValidator,
3504 onLeave: TransitionHookValidator,
3505 onAfterLeave: TransitionHookValidator,
3506 onLeaveCancelled: TransitionHookValidator,
3507 // appear
3508 onBeforeAppear: TransitionHookValidator,
3509 onAppear: TransitionHookValidator,
3510 onAfterAppear: TransitionHookValidator,
3511 onAppearCancelled: TransitionHookValidator
3512 },
3513 setup(props, { slots }) {
3514 const instance = getCurrentInstance();
3515 const state = useTransitionState();
3516 let prevTransitionKey;
3517 return () => {
3518 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3519 if (!children || !children.length) {
3520 return;
3521 }
3522 let child = children[0];
3523 if (children.length > 1) {
3524 let hasFound = false;
3525 // locate first non-comment child
3526 for (const c of children) {
3527 if (c.type !== Comment) {
3528 if (hasFound) {
3529 // warn more than one non-comment child
3530 warn$1('<transition> can only be used on a single element or component. ' +
3531 'Use <transition-group> for lists.');
3532 break;
3533 }
3534 child = c;
3535 hasFound = true;
3536 }
3537 }
3538 }
3539 // there's no need to track reactivity for these props so use the raw
3540 // props for a bit better perf
3541 const rawProps = toRaw(props);
3542 const { mode } = rawProps;
3543 // check mode
3544 if (mode &&
3545 mode !== 'in-out' &&
3546 mode !== 'out-in' &&
3547 mode !== 'default') {
3548 warn$1(`invalid <transition> mode: ${mode}`);
3549 }
3550 if (state.isLeaving) {
3551 return emptyPlaceholder(child);
3552 }
3553 // in the case of <transition><keep-alive/></transition>, we need to
3554 // compare the type of the kept-alive children.
3555 const innerChild = getKeepAliveChild(child);
3556 if (!innerChild) {
3557 return emptyPlaceholder(child);
3558 }
3559 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3560 setTransitionHooks(innerChild, enterHooks);
3561 const oldChild = instance.subTree;
3562 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3563 let transitionKeyChanged = false;
3564 const { getTransitionKey } = innerChild.type;
3565 if (getTransitionKey) {
3566 const key = getTransitionKey();
3567 if (prevTransitionKey === undefined) {
3568 prevTransitionKey = key;
3569 }
3570 else if (key !== prevTransitionKey) {
3571 prevTransitionKey = key;
3572 transitionKeyChanged = true;
3573 }
3574 }
3575 // handle mode
3576 if (oldInnerChild &&
3577 oldInnerChild.type !== Comment &&
3578 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3579 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3580 // update old tree's hooks in case of dynamic transition
3581 setTransitionHooks(oldInnerChild, leavingHooks);
3582 // switching between different views
3583 if (mode === 'out-in') {
3584 state.isLeaving = true;
3585 // return placeholder node and queue update when leave finishes
3586 leavingHooks.afterLeave = () => {
3587 state.isLeaving = false;
3588 // #6835
3589 // it also needs to be updated when active is undefined
3590 if (instance.update.active !== false) {
3591 instance.update();
3592 }
3593 };
3594 return emptyPlaceholder(child);
3595 }
3596 else if (mode === 'in-out' && innerChild.type !== Comment) {
3597 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3598 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3599 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3600 // early removal callback
3601 el._leaveCb = () => {
3602 earlyRemove();
3603 el._leaveCb = undefined;
3604 delete enterHooks.delayedLeave;
3605 };
3606 enterHooks.delayedLeave = delayedLeave;
3607 };
3608 }
3609 }
3610 return child;
3611 };
3612 }
3613};
3614// export the public type for h/tsx inference
3615// also to avoid inline import() in generated d.ts files
3616const BaseTransition = BaseTransitionImpl;
3617function getLeavingNodesForType(state, vnode) {
3618 const { leavingVNodes } = state;
3619 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3620 if (!leavingVNodesCache) {
3621 leavingVNodesCache = Object.create(null);
3622 leavingVNodes.set(vnode.type, leavingVNodesCache);
3623 }
3624 return leavingVNodesCache;
3625}
3626// The transition hooks are attached to the vnode as vnode.transition
3627// and will be called at appropriate timing in the renderer.
3628function resolveTransitionHooks(vnode, props, state, instance) {
3629 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3630 const key = String(vnode.key);
3631 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3632 const callHook = (hook, args) => {
3633 hook &&
3634 callWithAsyncErrorHandling(hook, instance, 9 /* ErrorCodes.TRANSITION_HOOK */, args);
3635 };
3636 const callAsyncHook = (hook, args) => {
3637 const done = args[1];
3638 callHook(hook, args);
3639 if (isArray(hook)) {
3640 if (hook.every(hook => hook.length <= 1))
3641 done();
3642 }
3643 else if (hook.length <= 1) {
3644 done();
3645 }
3646 };
3647 const hooks = {
3648 mode,
3649 persisted,
3650 beforeEnter(el) {
3651 let hook = onBeforeEnter;
3652 if (!state.isMounted) {
3653 if (appear) {
3654 hook = onBeforeAppear || onBeforeEnter;
3655 }
3656 else {
3657 return;
3658 }
3659 }
3660 // for same element (v-show)
3661 if (el._leaveCb) {
3662 el._leaveCb(true /* cancelled */);
3663 }
3664 // for toggled element with same key (v-if)
3665 const leavingVNode = leavingVNodesCache[key];
3666 if (leavingVNode &&
3667 isSameVNodeType(vnode, leavingVNode) &&
3668 leavingVNode.el._leaveCb) {
3669 // force early removal (not cancelled)
3670 leavingVNode.el._leaveCb();
3671 }
3672 callHook(hook, [el]);
3673 },
3674 enter(el) {
3675 let hook = onEnter;
3676 let afterHook = onAfterEnter;
3677 let cancelHook = onEnterCancelled;
3678 if (!state.isMounted) {
3679 if (appear) {
3680 hook = onAppear || onEnter;
3681 afterHook = onAfterAppear || onAfterEnter;
3682 cancelHook = onAppearCancelled || onEnterCancelled;
3683 }
3684 else {
3685 return;
3686 }
3687 }
3688 let called = false;
3689 const done = (el._enterCb = (cancelled) => {
3690 if (called)
3691 return;
3692 called = true;
3693 if (cancelled) {
3694 callHook(cancelHook, [el]);
3695 }
3696 else {
3697 callHook(afterHook, [el]);
3698 }
3699 if (hooks.delayedLeave) {
3700 hooks.delayedLeave();
3701 }
3702 el._enterCb = undefined;
3703 });
3704 if (hook) {
3705 callAsyncHook(hook, [el, done]);
3706 }
3707 else {
3708 done();
3709 }
3710 },
3711 leave(el, remove) {
3712 const key = String(vnode.key);
3713 if (el._enterCb) {
3714 el._enterCb(true /* cancelled */);
3715 }
3716 if (state.isUnmounting) {
3717 return remove();
3718 }
3719 callHook(onBeforeLeave, [el]);
3720 let called = false;
3721 const done = (el._leaveCb = (cancelled) => {
3722 if (called)
3723 return;
3724 called = true;
3725 remove();
3726 if (cancelled) {
3727 callHook(onLeaveCancelled, [el]);
3728 }
3729 else {
3730 callHook(onAfterLeave, [el]);
3731 }
3732 el._leaveCb = undefined;
3733 if (leavingVNodesCache[key] === vnode) {
3734 delete leavingVNodesCache[key];
3735 }
3736 });
3737 leavingVNodesCache[key] = vnode;
3738 if (onLeave) {
3739 callAsyncHook(onLeave, [el, done]);
3740 }
3741 else {
3742 done();
3743 }
3744 },
3745 clone(vnode) {
3746 return resolveTransitionHooks(vnode, props, state, instance);
3747 }
3748 };
3749 return hooks;
3750}
3751// the placeholder really only handles one special case: KeepAlive
3752// in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3753// placeholder with empty content to avoid the KeepAlive instance from being
3754// unmounted.
3755function emptyPlaceholder(vnode) {
3756 if (isKeepAlive(vnode)) {
3757 vnode = cloneVNode(vnode);
3758 vnode.children = null;
3759 return vnode;
3760 }
3761}
3762function getKeepAliveChild(vnode) {
3763 return isKeepAlive(vnode)
3764 ? vnode.children
3765 ? vnode.children[0]
3766 : undefined
3767 : vnode;
3768}
3769function setTransitionHooks(vnode, hooks) {
3770 if (vnode.shapeFlag & 6 /* ShapeFlags.COMPONENT */ && vnode.component) {
3771 setTransitionHooks(vnode.component.subTree, hooks);
3772 }
3773 else if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
3774 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3775 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3776 }
3777 else {
3778 vnode.transition = hooks;
3779 }
3780}
3781function getTransitionRawChildren(children, keepComment = false, parentKey) {
3782 let ret = [];
3783 let keyedFragmentCount = 0;
3784 for (let i = 0; i < children.length; i++) {
3785 let child = children[i];
3786 // #5360 inherit parent key in case of <template v-for>
3787 const key = parentKey == null
3788 ? child.key
3789 : String(parentKey) + String(child.key != null ? child.key : i);
3790 // handle fragment children case, e.g. v-for
3791 if (child.type === Fragment) {
3792 if (child.patchFlag & 128 /* PatchFlags.KEYED_FRAGMENT */)
3793 keyedFragmentCount++;
3794 ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
3795 }
3796 // comment placeholders should be skipped, e.g. v-if
3797 else if (keepComment || child.type !== Comment) {
3798 ret.push(key != null ? cloneVNode(child, { key }) : child);
3799 }
3800 }
3801 // #1126 if a transition children list contains multiple sub fragments, these
3802 // fragments will be merged into a flat children array. Since each v-for
3803 // fragment may contain different static bindings inside, we need to de-op
3804 // these children to force full diffs to ensure correct behavior.
3805 if (keyedFragmentCount > 1) {
3806 for (let i = 0; i < ret.length; i++) {
3807 ret[i].patchFlag = -2 /* PatchFlags.BAIL */;
3808 }
3809 }
3810 return ret;
3811}
3812
3813// implementation, close to no-op
3814function defineComponent(options) {
3815 return isFunction(options) ? { setup: options, name: options.name } : options;
3816}
3817
3818const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3819function defineAsyncComponent(source) {
3820 if (isFunction(source)) {
3821 source = { loader: source };
3822 }
3823 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3824 suspensible = true, onError: userOnError } = source;
3825 let pendingRequest = null;
3826 let resolvedComp;
3827 let retries = 0;
3828 const retry = () => {
3829 retries++;
3830 pendingRequest = null;
3831 return load();
3832 };
3833 const load = () => {
3834 let thisRequest;
3835 return (pendingRequest ||
3836 (thisRequest = pendingRequest =
3837 loader()
3838 .catch(err => {
3839 err = err instanceof Error ? err : new Error(String(err));
3840 if (userOnError) {
3841 return new Promise((resolve, reject) => {
3842 const userRetry = () => resolve(retry());
3843 const userFail = () => reject(err);
3844 userOnError(err, userRetry, userFail, retries + 1);
3845 });
3846 }
3847 else {
3848 throw err;
3849 }
3850 })
3851 .then((comp) => {
3852 if (thisRequest !== pendingRequest && pendingRequest) {
3853 return pendingRequest;
3854 }
3855 if (!comp) {
3856 warn$1(`Async component loader resolved to undefined. ` +
3857 `If you are using retry(), make sure to return its return value.`);
3858 }
3859 // interop module default
3860 if (comp &&
3861 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3862 comp = comp.default;
3863 }
3864 if (comp && !isObject(comp) && !isFunction(comp)) {
3865 throw new Error(`Invalid async component load result: ${comp}`);
3866 }
3867 resolvedComp = comp;
3868 return comp;
3869 })));
3870 };
3871 return defineComponent({
3872 name: 'AsyncComponentWrapper',
3873 __asyncLoader: load,
3874 get __asyncResolved() {
3875 return resolvedComp;
3876 },
3877 setup() {
3878 const instance = currentInstance;
3879 // already resolved
3880 if (resolvedComp) {
3881 return () => createInnerComp(resolvedComp, instance);
3882 }
3883 const onError = (err) => {
3884 pendingRequest = null;
3885 handleError(err, instance, 13 /* ErrorCodes.ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3886 };
3887 // suspense-controlled or SSR.
3888 if ((suspensible && instance.suspense) ||
3889 (false )) {
3890 return load()
3891 .then(comp => {
3892 return () => createInnerComp(comp, instance);
3893 })
3894 .catch(err => {
3895 onError(err);
3896 return () => errorComponent
3897 ? createVNode(errorComponent, {
3898 error: err
3899 })
3900 : null;
3901 });
3902 }
3903 const loaded = ref(false);
3904 const error = ref();
3905 const delayed = ref(!!delay);
3906 if (delay) {
3907 setTimeout(() => {
3908 delayed.value = false;
3909 }, delay);
3910 }
3911 if (timeout != null) {
3912 setTimeout(() => {
3913 if (!loaded.value && !error.value) {
3914 const err = new Error(`Async component timed out after ${timeout}ms.`);
3915 onError(err);
3916 error.value = err;
3917 }
3918 }, timeout);
3919 }
3920 load()
3921 .then(() => {
3922 loaded.value = true;
3923 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3924 // parent is keep-alive, force update so the loaded component's
3925 // name is taken into account
3926 queueJob(instance.parent.update);
3927 }
3928 })
3929 .catch(err => {
3930 onError(err);
3931 error.value = err;
3932 });
3933 return () => {
3934 if (loaded.value && resolvedComp) {
3935 return createInnerComp(resolvedComp, instance);
3936 }
3937 else if (error.value && errorComponent) {
3938 return createVNode(errorComponent, {
3939 error: error.value
3940 });
3941 }
3942 else if (loadingComponent && !delayed.value) {
3943 return createVNode(loadingComponent);
3944 }
3945 };
3946 }
3947 });
3948}
3949function createInnerComp(comp, parent) {
3950 const { ref, props, children, ce } = parent.vnode;
3951 const vnode = createVNode(comp, props, children);
3952 // ensure inner component inherits the async wrapper's ref owner
3953 vnode.ref = ref;
3954 // pass the custom element callback on to the inner comp
3955 // and remove it from the async wrapper
3956 vnode.ce = ce;
3957 delete parent.vnode.ce;
3958 return vnode;
3959}
3960
3961const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3962const KeepAliveImpl = {
3963 name: `KeepAlive`,
3964 // Marker for special handling inside the renderer. We are not using a ===
3965 // check directly on KeepAlive in the renderer, because importing it directly
3966 // would prevent it from being tree-shaken.
3967 __isKeepAlive: true,
3968 props: {
3969 include: [String, RegExp, Array],
3970 exclude: [String, RegExp, Array],
3971 max: [String, Number]
3972 },
3973 setup(props, { slots }) {
3974 const instance = getCurrentInstance();
3975 // KeepAlive communicates with the instantiated renderer via the
3976 // ctx where the renderer passes in its internals,
3977 // and the KeepAlive instance exposes activate/deactivate implementations.
3978 // The whole point of this is to avoid importing KeepAlive directly in the
3979 // renderer to facilitate tree-shaking.
3980 const sharedContext = instance.ctx;
3981 const cache = new Map();
3982 const keys = new Set();
3983 let current = null;
3984 {
3985 instance.__v_cache = cache;
3986 }
3987 const parentSuspense = instance.suspense;
3988 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3989 const storageContainer = createElement('div');
3990 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3991 const instance = vnode.component;
3992 move(vnode, container, anchor, 0 /* MoveType.ENTER */, parentSuspense);
3993 // in case props have changed
3994 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3995 queuePostRenderEffect(() => {
3996 instance.isDeactivated = false;
3997 if (instance.a) {
3998 invokeArrayFns(instance.a);
3999 }
4000 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
4001 if (vnodeHook) {
4002 invokeVNodeHook(vnodeHook, instance.parent, vnode);
4003 }
4004 }, parentSuspense);
4005 {
4006 // Update components tree
4007 devtoolsComponentAdded(instance);
4008 }
4009 };
4010 sharedContext.deactivate = (vnode) => {
4011 const instance = vnode.component;
4012 move(vnode, storageContainer, null, 1 /* MoveType.LEAVE */, parentSuspense);
4013 queuePostRenderEffect(() => {
4014 if (instance.da) {
4015 invokeArrayFns(instance.da);
4016 }
4017 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
4018 if (vnodeHook) {
4019 invokeVNodeHook(vnodeHook, instance.parent, vnode);
4020 }
4021 instance.isDeactivated = true;
4022 }, parentSuspense);
4023 {
4024 // Update components tree
4025 devtoolsComponentAdded(instance);
4026 }
4027 };
4028 function unmount(vnode) {
4029 // reset the shapeFlag so it can be properly unmounted
4030 resetShapeFlag(vnode);
4031 _unmount(vnode, instance, parentSuspense, true);
4032 }
4033 function pruneCache(filter) {
4034 cache.forEach((vnode, key) => {
4035 const name = getComponentName(vnode.type);
4036 if (name && (!filter || !filter(name))) {
4037 pruneCacheEntry(key);
4038 }
4039 });
4040 }
4041 function pruneCacheEntry(key) {
4042 const cached = cache.get(key);
4043 if (!current || cached.type !== current.type) {
4044 unmount(cached);
4045 }
4046 else if (current) {
4047 // current active instance should no longer be kept-alive.
4048 // we can't unmount it now but it might be later, so reset its flag now.
4049 resetShapeFlag(current);
4050 }
4051 cache.delete(key);
4052 keys.delete(key);
4053 }
4054 // prune cache on include/exclude prop change
4055 watch(() => [props.include, props.exclude], ([include, exclude]) => {
4056 include && pruneCache(name => matches(include, name));
4057 exclude && pruneCache(name => !matches(exclude, name));
4058 },
4059 // prune post-render after `current` has been updated
4060 { flush: 'post', deep: true });
4061 // cache sub tree after render
4062 let pendingCacheKey = null;
4063 const cacheSubtree = () => {
4064 // fix #1621, the pendingCacheKey could be 0
4065 if (pendingCacheKey != null) {
4066 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
4067 }
4068 };
4069 onMounted(cacheSubtree);
4070 onUpdated(cacheSubtree);
4071 onBeforeUnmount(() => {
4072 cache.forEach(cached => {
4073 const { subTree, suspense } = instance;
4074 const vnode = getInnerChild(subTree);
4075 if (cached.type === vnode.type) {
4076 // current instance will be unmounted as part of keep-alive's unmount
4077 resetShapeFlag(vnode);
4078 // but invoke its deactivated hook here
4079 const da = vnode.component.da;
4080 da && queuePostRenderEffect(da, suspense);
4081 return;
4082 }
4083 unmount(cached);
4084 });
4085 });
4086 return () => {
4087 pendingCacheKey = null;
4088 if (!slots.default) {
4089 return null;
4090 }
4091 const children = slots.default();
4092 const rawVNode = children[0];
4093 if (children.length > 1) {
4094 {
4095 warn$1(`KeepAlive should contain exactly one component child.`);
4096 }
4097 current = null;
4098 return children;
4099 }
4100 else if (!isVNode(rawVNode) ||
4101 (!(rawVNode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */) &&
4102 !(rawVNode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */))) {
4103 current = null;
4104 return rawVNode;
4105 }
4106 let vnode = getInnerChild(rawVNode);
4107 const comp = vnode.type;
4108 // for async components, name check should be based in its loaded
4109 // inner component if available
4110 const name = getComponentName(isAsyncWrapper(vnode)
4111 ? vnode.type.__asyncResolved || {}
4112 : comp);
4113 const { include, exclude, max } = props;
4114 if ((include && (!name || !matches(include, name))) ||
4115 (exclude && name && matches(exclude, name))) {
4116 current = vnode;
4117 return rawVNode;
4118 }
4119 const key = vnode.key == null ? comp : vnode.key;
4120 const cachedVNode = cache.get(key);
4121 // clone vnode if it's reused because we are going to mutate it
4122 if (vnode.el) {
4123 vnode = cloneVNode(vnode);
4124 if (rawVNode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
4125 rawVNode.ssContent = vnode;
4126 }
4127 }
4128 // #1513 it's possible for the returned vnode to be cloned due to attr
4129 // fallthrough or scopeId, so the vnode here may not be the final vnode
4130 // that is mounted. Instead of caching it directly, we store the pending
4131 // key and cache `instance.subTree` (the normalized vnode) in
4132 // beforeMount/beforeUpdate hooks.
4133 pendingCacheKey = key;
4134 if (cachedVNode) {
4135 // copy over mounted state
4136 vnode.el = cachedVNode.el;
4137 vnode.component = cachedVNode.component;
4138 if (vnode.transition) {
4139 // recursively update transition hooks on subTree
4140 setTransitionHooks(vnode, vnode.transition);
4141 }
4142 // avoid vnode being mounted as fresh
4143 vnode.shapeFlag |= 512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
4144 // make this key the freshest
4145 keys.delete(key);
4146 keys.add(key);
4147 }
4148 else {
4149 keys.add(key);
4150 // prune oldest entry
4151 if (max && keys.size > parseInt(max, 10)) {
4152 pruneCacheEntry(keys.values().next().value);
4153 }
4154 }
4155 // avoid vnode being unmounted
4156 vnode.shapeFlag |= 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
4157 current = vnode;
4158 return isSuspense(rawVNode.type) ? rawVNode : vnode;
4159 };
4160 }
4161};
4162// export the public type for h/tsx inference
4163// also to avoid inline import() in generated d.ts files
4164const KeepAlive = KeepAliveImpl;
4165function matches(pattern, name) {
4166 if (isArray(pattern)) {
4167 return pattern.some((p) => matches(p, name));
4168 }
4169 else if (isString(pattern)) {
4170 return pattern.split(',').includes(name);
4171 }
4172 else if (pattern.test) {
4173 return pattern.test(name);
4174 }
4175 /* istanbul ignore next */
4176 return false;
4177}
4178function onActivated(hook, target) {
4179 registerKeepAliveHook(hook, "a" /* LifecycleHooks.ACTIVATED */, target);
4180}
4181function onDeactivated(hook, target) {
4182 registerKeepAliveHook(hook, "da" /* LifecycleHooks.DEACTIVATED */, target);
4183}
4184function registerKeepAliveHook(hook, type, target = currentInstance) {
4185 // cache the deactivate branch check wrapper for injected hooks so the same
4186 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4187 // deactivation check".
4188 const wrappedHook = hook.__wdc ||
4189 (hook.__wdc = () => {
4190 // only fire the hook if the target instance is NOT in a deactivated branch.
4191 let current = target;
4192 while (current) {
4193 if (current.isDeactivated) {
4194 return;
4195 }
4196 current = current.parent;
4197 }
4198 return hook();
4199 });
4200 injectHook(type, wrappedHook, target);
4201 // In addition to registering it on the target instance, we walk up the parent
4202 // chain and register it on all ancestor instances that are keep-alive roots.
4203 // This avoids the need to walk the entire component tree when invoking these
4204 // hooks, and more importantly, avoids the need to track child components in
4205 // arrays.
4206 if (target) {
4207 let current = target.parent;
4208 while (current && current.parent) {
4209 if (isKeepAlive(current.parent.vnode)) {
4210 injectToKeepAliveRoot(wrappedHook, type, target, current);
4211 }
4212 current = current.parent;
4213 }
4214 }
4215}
4216function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4217 // injectHook wraps the original for error handling, so make sure to remove
4218 // the wrapped version.
4219 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4220 onUnmounted(() => {
4221 remove(keepAliveRoot[type], injected);
4222 }, target);
4223}
4224function resetShapeFlag(vnode) {
4225 // bitwise operations to remove keep alive flags
4226 vnode.shapeFlag &= ~256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
4227 vnode.shapeFlag &= ~512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
4228}
4229function getInnerChild(vnode) {
4230 return vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */ ? vnode.ssContent : vnode;
4231}
4232
4233function injectHook(type, hook, target = currentInstance, prepend = false) {
4234 if (target) {
4235 const hooks = target[type] || (target[type] = []);
4236 // cache the error handling wrapper for injected hooks so the same hook
4237 // can be properly deduped by the scheduler. "__weh" stands for "with error
4238 // handling".
4239 const wrappedHook = hook.__weh ||
4240 (hook.__weh = (...args) => {
4241 if (target.isUnmounted) {
4242 return;
4243 }
4244 // disable tracking inside all lifecycle hooks
4245 // since they can potentially be called inside effects.
4246 pauseTracking();
4247 // Set currentInstance during hook invocation.
4248 // This assumes the hook does not synchronously trigger other hooks, which
4249 // can only be false when the user does something really funky.
4250 setCurrentInstance(target);
4251 const res = callWithAsyncErrorHandling(hook, target, type, args);
4252 unsetCurrentInstance();
4253 resetTracking();
4254 return res;
4255 });
4256 if (prepend) {
4257 hooks.unshift(wrappedHook);
4258 }
4259 else {
4260 hooks.push(wrappedHook);
4261 }
4262 return wrappedHook;
4263 }
4264 else {
4265 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4266 warn$1(`${apiName} is called when there is no active component instance to be ` +
4267 `associated with. ` +
4268 `Lifecycle injection APIs can only be used during execution of setup().` +
4269 (` If you are using async setup(), make sure to register lifecycle ` +
4270 `hooks before the first await statement.`
4271 ));
4272 }
4273}
4274const createHook = (lifecycle) => (hook, target = currentInstance) =>
4275// post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4276(!isInSSRComponentSetup || lifecycle === "sp" /* LifecycleHooks.SERVER_PREFETCH */) &&
4277 injectHook(lifecycle, (...args) => hook(...args), target);
4278const onBeforeMount = createHook("bm" /* LifecycleHooks.BEFORE_MOUNT */);
4279const onMounted = createHook("m" /* LifecycleHooks.MOUNTED */);
4280const onBeforeUpdate = createHook("bu" /* LifecycleHooks.BEFORE_UPDATE */);
4281const onUpdated = createHook("u" /* LifecycleHooks.UPDATED */);
4282const onBeforeUnmount = createHook("bum" /* LifecycleHooks.BEFORE_UNMOUNT */);
4283const onUnmounted = createHook("um" /* LifecycleHooks.UNMOUNTED */);
4284const onServerPrefetch = createHook("sp" /* LifecycleHooks.SERVER_PREFETCH */);
4285const onRenderTriggered = createHook("rtg" /* LifecycleHooks.RENDER_TRIGGERED */);
4286const onRenderTracked = createHook("rtc" /* LifecycleHooks.RENDER_TRACKED */);
4287function onErrorCaptured(hook, target = currentInstance) {
4288 injectHook("ec" /* LifecycleHooks.ERROR_CAPTURED */, hook, target);
4289}
4290
4291/**
4292Runtime helper for applying directives to a vnode. Example usage:
4293
4294const comp = resolveComponent('comp')
4295const foo = resolveDirective('foo')
4296const bar = resolveDirective('bar')
4297
4298return withDirectives(h(comp), [
4299 [foo, this.x],
4300 [bar, this.y]
4301])
4302*/
4303function validateDirectiveName(name) {
4304 if (isBuiltInDirective(name)) {
4305 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
4306 }
4307}
4308/**
4309 * Adds directives to a VNode.
4310 */
4311function withDirectives(vnode, directives) {
4312 const internalInstance = currentRenderingInstance;
4313 if (internalInstance === null) {
4314 warn$1(`withDirectives can only be used inside render functions.`);
4315 return vnode;
4316 }
4317 const instance = getExposeProxy(internalInstance) ||
4318 internalInstance.proxy;
4319 const bindings = vnode.dirs || (vnode.dirs = []);
4320 for (let i = 0; i < directives.length; i++) {
4321 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4322 if (dir) {
4323 if (isFunction(dir)) {
4324 dir = {
4325 mounted: dir,
4326 updated: dir
4327 };
4328 }
4329 if (dir.deep) {
4330 traverse(value);
4331 }
4332 bindings.push({
4333 dir,
4334 instance,
4335 value,
4336 oldValue: void 0,
4337 arg,
4338 modifiers
4339 });
4340 }
4341 }
4342 return vnode;
4343}
4344function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4345 const bindings = vnode.dirs;
4346 const oldBindings = prevVNode && prevVNode.dirs;
4347 for (let i = 0; i < bindings.length; i++) {
4348 const binding = bindings[i];
4349 if (oldBindings) {
4350 binding.oldValue = oldBindings[i].value;
4351 }
4352 let hook = binding.dir[name];
4353 if (hook) {
4354 // disable tracking inside all lifecycle hooks
4355 // since they can potentially be called inside effects.
4356 pauseTracking();
4357 callWithAsyncErrorHandling(hook, instance, 8 /* ErrorCodes.DIRECTIVE_HOOK */, [
4358 vnode.el,
4359 binding,
4360 vnode,
4361 prevVNode
4362 ]);
4363 resetTracking();
4364 }
4365 }
4366}
4367
4368const COMPONENTS = 'components';
4369const DIRECTIVES = 'directives';
4370/**
4371 * @private
4372 */
4373function resolveComponent(name, maybeSelfReference) {
4374 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
4375}
4376const NULL_DYNAMIC_COMPONENT = Symbol();
4377/**
4378 * @private
4379 */
4380function resolveDynamicComponent(component) {
4381 if (isString(component)) {
4382 return resolveAsset(COMPONENTS, component, false) || component;
4383 }
4384 else {
4385 // invalid types will fallthrough to createVNode and raise warning
4386 return (component || NULL_DYNAMIC_COMPONENT);
4387 }
4388}
4389/**
4390 * @private
4391 */
4392function resolveDirective(name) {
4393 return resolveAsset(DIRECTIVES, name);
4394}
4395// implementation
4396function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
4397 const instance = currentRenderingInstance || currentInstance;
4398 if (instance) {
4399 const Component = instance.type;
4400 // explicit self name has highest priority
4401 if (type === COMPONENTS) {
4402 const selfName = getComponentName(Component, false /* do not include inferred name to avoid breaking existing code */);
4403 if (selfName &&
4404 (selfName === name ||
4405 selfName === camelize(name) ||
4406 selfName === capitalize(camelize(name)))) {
4407 return Component;
4408 }
4409 }
4410 const res =
4411 // local registration
4412 // check instance[type] first which is resolved for options API
4413 resolve(instance[type] || Component[type], name) ||
4414 // global registration
4415 resolve(instance.appContext[type], name);
4416 if (!res && maybeSelfReference) {
4417 // fallback to implicit self-reference
4418 return Component;
4419 }
4420 if (warnMissing && !res) {
4421 const extra = type === COMPONENTS
4422 ? `\nIf this is a native custom element, make sure to exclude it from ` +
4423 `component resolution via compilerOptions.isCustomElement.`
4424 : ``;
4425 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
4426 }
4427 return res;
4428 }
4429 else {
4430 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
4431 `can only be used in render() or setup().`);
4432 }
4433}
4434function resolve(registry, name) {
4435 return (registry &&
4436 (registry[name] ||
4437 registry[camelize(name)] ||
4438 registry[capitalize(camelize(name))]));
4439}
4440
4441/**
4442 * Actual implementation
4443 */
4444function renderList(source, renderItem, cache, index) {
4445 let ret;
4446 const cached = (cache && cache[index]);
4447 if (isArray(source) || isString(source)) {
4448 ret = new Array(source.length);
4449 for (let i = 0, l = source.length; i < l; i++) {
4450 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
4451 }
4452 }
4453 else if (typeof source === 'number') {
4454 if (!Number.isInteger(source)) {
4455 warn$1(`The v-for range expect an integer value but got ${source}.`);
4456 }
4457 ret = new Array(source);
4458 for (let i = 0; i < source; i++) {
4459 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
4460 }
4461 }
4462 else if (isObject(source)) {
4463 if (source[Symbol.iterator]) {
4464 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
4465 }
4466 else {
4467 const keys = Object.keys(source);
4468 ret = new Array(keys.length);
4469 for (let i = 0, l = keys.length; i < l; i++) {
4470 const key = keys[i];
4471 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
4472 }
4473 }
4474 }
4475 else {
4476 ret = [];
4477 }
4478 if (cache) {
4479 cache[index] = ret;
4480 }
4481 return ret;
4482}
4483
4484/**
4485 * Compiler runtime helper for creating dynamic slots object
4486 * @private
4487 */
4488function createSlots(slots, dynamicSlots) {
4489 for (let i = 0; i < dynamicSlots.length; i++) {
4490 const slot = dynamicSlots[i];
4491 // array of dynamic slot generated by <template v-for="..." #[...]>
4492 if (isArray(slot)) {
4493 for (let j = 0; j < slot.length; j++) {
4494 slots[slot[j].name] = slot[j].fn;
4495 }
4496 }
4497 else if (slot) {
4498 // conditional single slot generated by <template v-if="..." #foo>
4499 slots[slot.name] = slot.key
4500 ? (...args) => {
4501 const res = slot.fn(...args);
4502 // attach branch key so each conditional branch is considered a
4503 // different fragment
4504 if (res)
4505 res.key = slot.key;
4506 return res;
4507 }
4508 : slot.fn;
4509 }
4510 }
4511 return slots;
4512}
4513
4514/**
4515 * Compiler runtime helper for rendering `<slot/>`
4516 * @private
4517 */
4518function renderSlot(slots, name, props = {},
4519// this is not a user-facing function, so the fallback is always generated by
4520// the compiler and guaranteed to be a function returning an array
4521fallback, noSlotted) {
4522 if (currentRenderingInstance.isCE ||
4523 (currentRenderingInstance.parent &&
4524 isAsyncWrapper(currentRenderingInstance.parent) &&
4525 currentRenderingInstance.parent.isCE)) {
4526 if (name !== 'default')
4527 props.name = name;
4528 return createVNode('slot', props, fallback && fallback());
4529 }
4530 let slot = slots[name];
4531 if (slot && slot.length > 1) {
4532 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
4533 `function. You need to mark this component with $dynamic-slots in the ` +
4534 `parent template.`);
4535 slot = () => [];
4536 }
4537 // a compiled slot disables block tracking by default to avoid manual
4538 // invocation interfering with template-based block tracking, but in
4539 // `renderSlot` we can be sure that it's template-based so we can force
4540 // enable it.
4541 if (slot && slot._c) {
4542 slot._d = false;
4543 }
4544 openBlock();
4545 const validSlotContent = slot && ensureValidVNode(slot(props));
4546 const rendered = createBlock(Fragment, {
4547 key: props.key ||
4548 // slot content array of a dynamic conditional slot may have a branch
4549 // key attached in the `createSlots` helper, respect that
4550 (validSlotContent && validSlotContent.key) ||
4551 `_${name}`
4552 }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* SlotFlags.STABLE */
4553 ? 64 /* PatchFlags.STABLE_FRAGMENT */
4554 : -2 /* PatchFlags.BAIL */);
4555 if (!noSlotted && rendered.scopeId) {
4556 rendered.slotScopeIds = [rendered.scopeId + '-s'];
4557 }
4558 if (slot && slot._c) {
4559 slot._d = true;
4560 }
4561 return rendered;
4562}
4563function ensureValidVNode(vnodes) {
4564 return vnodes.some(child => {
4565 if (!isVNode(child))
4566 return true;
4567 if (child.type === Comment)
4568 return false;
4569 if (child.type === Fragment &&
4570 !ensureValidVNode(child.children))
4571 return false;
4572 return true;
4573 })
4574 ? vnodes
4575 : null;
4576}
4577
4578/**
4579 * For prefixing keys in v-on="obj" with "on"
4580 * @private
4581 */
4582function toHandlers(obj, preserveCaseIfNecessary) {
4583 const ret = {};
4584 if (!isObject(obj)) {
4585 warn$1(`v-on with no argument expects an object value.`);
4586 return ret;
4587 }
4588 for (const key in obj) {
4589 ret[preserveCaseIfNecessary && /[A-Z]/.test(key)
4590 ? `on:${key}`
4591 : toHandlerKey(key)] = obj[key];
4592 }
4593 return ret;
4594}
4595
4596/**
4597 * #2437 In Vue 3, functional components do not have a public instance proxy but
4598 * they exist in the internal parent chain. For code that relies on traversing
4599 * public $parent chains, skip functional ones and go to the parent instead.
4600 */
4601const getPublicInstance = (i) => {
4602 if (!i)
4603 return null;
4604 if (isStatefulComponent(i))
4605 return getExposeProxy(i) || i.proxy;
4606 return getPublicInstance(i.parent);
4607};
4608const publicPropertiesMap =
4609// Move PURE marker to new line to workaround compiler discarding it
4610// due to type annotation
4611/*#__PURE__*/ extend(Object.create(null), {
4612 $: i => i,
4613 $el: i => i.vnode.el,
4614 $data: i => i.data,
4615 $props: i => (shallowReadonly(i.props) ),
4616 $attrs: i => (shallowReadonly(i.attrs) ),
4617 $slots: i => (shallowReadonly(i.slots) ),
4618 $refs: i => (shallowReadonly(i.refs) ),
4619 $parent: i => getPublicInstance(i.parent),
4620 $root: i => getPublicInstance(i.root),
4621 $emit: i => i.emit,
4622 $options: i => (resolveMergedOptions(i) ),
4623 $forceUpdate: i => i.f || (i.f = () => queueJob(i.update)),
4624 $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy)),
4625 $watch: i => (instanceWatch.bind(i) )
4626});
4627const isReservedPrefix = (key) => key === '_' || key === '$';
4628const hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key);
4629const PublicInstanceProxyHandlers = {
4630 get({ _: instance }, key) {
4631 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
4632 // for internal formatters to know that this is a Vue instance
4633 if (key === '__isVue') {
4634 return true;
4635 }
4636 // data / props / ctx
4637 // This getter gets called for every property access on the render context
4638 // during render and is a major hotspot. The most expensive part of this
4639 // is the multiple hasOwn() calls. It's much faster to do a simple property
4640 // access on a plain object, so we use an accessCache object (with null
4641 // prototype) to memoize what access type a key corresponds to.
4642 let normalizedProps;
4643 if (key[0] !== '$') {
4644 const n = accessCache[key];
4645 if (n !== undefined) {
4646 switch (n) {
4647 case 1 /* AccessTypes.SETUP */:
4648 return setupState[key];
4649 case 2 /* AccessTypes.DATA */:
4650 return data[key];
4651 case 4 /* AccessTypes.CONTEXT */:
4652 return ctx[key];
4653 case 3 /* AccessTypes.PROPS */:
4654 return props[key];
4655 // default: just fallthrough
4656 }
4657 }
4658 else if (hasSetupBinding(setupState, key)) {
4659 accessCache[key] = 1 /* AccessTypes.SETUP */;
4660 return setupState[key];
4661 }
4662 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
4663 accessCache[key] = 2 /* AccessTypes.DATA */;
4664 return data[key];
4665 }
4666 else if (
4667 // only cache other properties when instance has declared (thus stable)
4668 // props
4669 (normalizedProps = instance.propsOptions[0]) &&
4670 hasOwn(normalizedProps, key)) {
4671 accessCache[key] = 3 /* AccessTypes.PROPS */;
4672 return props[key];
4673 }
4674 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
4675 accessCache[key] = 4 /* AccessTypes.CONTEXT */;
4676 return ctx[key];
4677 }
4678 else if (shouldCacheAccess) {
4679 accessCache[key] = 0 /* AccessTypes.OTHER */;
4680 }
4681 }
4682 const publicGetter = publicPropertiesMap[key];
4683 let cssModule, globalProperties;
4684 // public $xxx properties
4685 if (publicGetter) {
4686 if (key === '$attrs') {
4687 track(instance, "get" /* TrackOpTypes.GET */, key);
4688 markAttrsAccessed();
4689 }
4690 return publicGetter(instance);
4691 }
4692 else if (
4693 // css module (injected by vue-loader)
4694 (cssModule = type.__cssModules) &&
4695 (cssModule = cssModule[key])) {
4696 return cssModule;
4697 }
4698 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
4699 // user may set custom properties to `this` that start with `$`
4700 accessCache[key] = 4 /* AccessTypes.CONTEXT */;
4701 return ctx[key];
4702 }
4703 else if (
4704 // global properties
4705 ((globalProperties = appContext.config.globalProperties),
4706 hasOwn(globalProperties, key))) {
4707 {
4708 return globalProperties[key];
4709 }
4710 }
4711 else if (currentRenderingInstance &&
4712 (!isString(key) ||
4713 // #1091 avoid internal isRef/isVNode checks on component instance leading
4714 // to infinite warning loop
4715 key.indexOf('__v') !== 0)) {
4716 if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {
4717 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
4718 `character ("$" or "_") and is not proxied on the render context.`);
4719 }
4720 else if (instance === currentRenderingInstance) {
4721 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
4722 `but is not defined on instance.`);
4723 }
4724 }
4725 },
4726 set({ _: instance }, key, value) {
4727 const { data, setupState, ctx } = instance;
4728 if (hasSetupBinding(setupState, key)) {
4729 setupState[key] = value;
4730 return true;
4731 }
4732 else if (setupState.__isScriptSetup &&
4733 hasOwn(setupState, key)) {
4734 warn$1(`Cannot mutate <script setup> binding "${key}" from Options API.`);
4735 return false;
4736 }
4737 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
4738 data[key] = value;
4739 return true;
4740 }
4741 else if (hasOwn(instance.props, key)) {
4742 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`);
4743 return false;
4744 }
4745 if (key[0] === '$' && key.slice(1) in instance) {
4746 warn$1(`Attempting to mutate public property "${key}". ` +
4747 `Properties starting with $ are reserved and readonly.`);
4748 return false;
4749 }
4750 else {
4751 if (key in instance.appContext.config.globalProperties) {
4752 Object.defineProperty(ctx, key, {
4753 enumerable: true,
4754 configurable: true,
4755 value
4756 });
4757 }
4758 else {
4759 ctx[key] = value;
4760 }
4761 }
4762 return true;
4763 },
4764 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
4765 let normalizedProps;
4766 return (!!accessCache[key] ||
4767 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
4768 hasSetupBinding(setupState, key) ||
4769 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
4770 hasOwn(ctx, key) ||
4771 hasOwn(publicPropertiesMap, key) ||
4772 hasOwn(appContext.config.globalProperties, key));
4773 },
4774 defineProperty(target, key, descriptor) {
4775 if (descriptor.get != null) {
4776 // invalidate key cache of a getter based property #5417
4777 target._.accessCache[key] = 0;
4778 }
4779 else if (hasOwn(descriptor, 'value')) {
4780 this.set(target, key, descriptor.value, null);
4781 }
4782 return Reflect.defineProperty(target, key, descriptor);
4783 }
4784};
4785{
4786 PublicInstanceProxyHandlers.ownKeys = (target) => {
4787 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
4788 `The keys will be empty in production mode to avoid performance overhead.`);
4789 return Reflect.ownKeys(target);
4790 };
4791}
4792const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
4793 get(target, key) {
4794 // fast path for unscopables when using `with` block
4795 if (key === Symbol.unscopables) {
4796 return;
4797 }
4798 return PublicInstanceProxyHandlers.get(target, key, target);
4799 },
4800 has(_, key) {
4801 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
4802 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
4803 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
4804 }
4805 return has;
4806 }
4807});
4808// dev only
4809// In dev mode, the proxy target exposes the same properties as seen on `this`
4810// for easier console inspection. In prod mode it will be an empty object so
4811// these properties definitions can be skipped.
4812function createDevRenderContext(instance) {
4813 const target = {};
4814 // expose internal instance for proxy handlers
4815 Object.defineProperty(target, `_`, {
4816 configurable: true,
4817 enumerable: false,
4818 get: () => instance
4819 });
4820 // expose public properties
4821 Object.keys(publicPropertiesMap).forEach(key => {
4822 Object.defineProperty(target, key, {
4823 configurable: true,
4824 enumerable: false,
4825 get: () => publicPropertiesMap[key](instance),
4826 // intercepted by the proxy so no need for implementation,
4827 // but needed to prevent set errors
4828 set: NOOP
4829 });
4830 });
4831 return target;
4832}
4833// dev only
4834function exposePropsOnRenderContext(instance) {
4835 const { ctx, propsOptions: [propsOptions] } = instance;
4836 if (propsOptions) {
4837 Object.keys(propsOptions).forEach(key => {
4838 Object.defineProperty(ctx, key, {
4839 enumerable: true,
4840 configurable: true,
4841 get: () => instance.props[key],
4842 set: NOOP
4843 });
4844 });
4845 }
4846}
4847// dev only
4848function exposeSetupStateOnRenderContext(instance) {
4849 const { ctx, setupState } = instance;
4850 Object.keys(toRaw(setupState)).forEach(key => {
4851 if (!setupState.__isScriptSetup) {
4852 if (isReservedPrefix(key[0])) {
4853 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
4854 `which are reserved prefixes for Vue internals.`);
4855 return;
4856 }
4857 Object.defineProperty(ctx, key, {
4858 enumerable: true,
4859 configurable: true,
4860 get: () => setupState[key],
4861 set: NOOP
4862 });
4863 }
4864 });
4865}
4866
4867function createDuplicateChecker() {
4868 const cache = Object.create(null);
4869 return (type, key) => {
4870 if (cache[key]) {
4871 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
4872 }
4873 else {
4874 cache[key] = type;
4875 }
4876 };
4877}
4878let shouldCacheAccess = true;
4879function applyOptions(instance) {
4880 const options = resolveMergedOptions(instance);
4881 const publicThis = instance.proxy;
4882 const ctx = instance.ctx;
4883 // do not cache property access on public proxy during state initialization
4884 shouldCacheAccess = false;
4885 // call beforeCreate first before accessing other options since
4886 // the hook may mutate resolved options (#2791)
4887 if (options.beforeCreate) {
4888 callHook(options.beforeCreate, instance, "bc" /* LifecycleHooks.BEFORE_CREATE */);
4889 }
4890 const {
4891 // state
4892 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4893 // lifecycle
4894 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4895 // public API
4896 expose, inheritAttrs,
4897 // assets
4898 components, directives, filters } = options;
4899 const checkDuplicateProperties = createDuplicateChecker() ;
4900 {
4901 const [propsOptions] = instance.propsOptions;
4902 if (propsOptions) {
4903 for (const key in propsOptions) {
4904 checkDuplicateProperties("Props" /* OptionTypes.PROPS */, key);
4905 }
4906 }
4907 }
4908 // options initialization order (to be consistent with Vue 2):
4909 // - props (already done outside of this function)
4910 // - inject
4911 // - methods
4912 // - data (deferred since it relies on `this` access)
4913 // - computed
4914 // - watch (deferred since it relies on `this` access)
4915 if (injectOptions) {
4916 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
4917 }
4918 if (methods) {
4919 for (const key in methods) {
4920 const methodHandler = methods[key];
4921 if (isFunction(methodHandler)) {
4922 // In dev mode, we use the `createRenderContext` function to define
4923 // methods to the proxy target, and those are read-only but
4924 // reconfigurable, so it needs to be redefined here
4925 {
4926 Object.defineProperty(ctx, key, {
4927 value: methodHandler.bind(publicThis),
4928 configurable: true,
4929 enumerable: true,
4930 writable: true
4931 });
4932 }
4933 {
4934 checkDuplicateProperties("Methods" /* OptionTypes.METHODS */, key);
4935 }
4936 }
4937 else {
4938 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4939 `Did you reference the function correctly?`);
4940 }
4941 }
4942 }
4943 if (dataOptions) {
4944 if (!isFunction(dataOptions)) {
4945 warn$1(`The data option must be a function. ` +
4946 `Plain object usage is no longer supported.`);
4947 }
4948 const data = dataOptions.call(publicThis, publicThis);
4949 if (isPromise(data)) {
4950 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
4951 `intend to perform data fetching before component renders, use ` +
4952 `async setup() + <Suspense>.`);
4953 }
4954 if (!isObject(data)) {
4955 warn$1(`data() should return an object.`);
4956 }
4957 else {
4958 instance.data = reactive(data);
4959 {
4960 for (const key in data) {
4961 checkDuplicateProperties("Data" /* OptionTypes.DATA */, key);
4962 // expose data on ctx during dev
4963 if (!isReservedPrefix(key[0])) {
4964 Object.defineProperty(ctx, key, {
4965 configurable: true,
4966 enumerable: true,
4967 get: () => data[key],
4968 set: NOOP
4969 });
4970 }
4971 }
4972 }
4973 }
4974 }
4975 // state initialization complete at this point - start caching access
4976 shouldCacheAccess = true;
4977 if (computedOptions) {
4978 for (const key in computedOptions) {
4979 const opt = computedOptions[key];
4980 const get = isFunction(opt)
4981 ? opt.bind(publicThis, publicThis)
4982 : isFunction(opt.get)
4983 ? opt.get.bind(publicThis, publicThis)
4984 : NOOP;
4985 if (get === NOOP) {
4986 warn$1(`Computed property "${key}" has no getter.`);
4987 }
4988 const set = !isFunction(opt) && isFunction(opt.set)
4989 ? opt.set.bind(publicThis)
4990 : () => {
4991 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
4992 }
4993 ;
4994 const c = computed$1({
4995 get,
4996 set
4997 });
4998 Object.defineProperty(ctx, key, {
4999 enumerable: true,
5000 configurable: true,
5001 get: () => c.value,
5002 set: v => (c.value = v)
5003 });
5004 {
5005 checkDuplicateProperties("Computed" /* OptionTypes.COMPUTED */, key);
5006 }
5007 }
5008 }
5009 if (watchOptions) {
5010 for (const key in watchOptions) {
5011 createWatcher(watchOptions[key], ctx, publicThis, key);
5012 }
5013 }
5014 if (provideOptions) {
5015 const provides = isFunction(provideOptions)
5016 ? provideOptions.call(publicThis)
5017 : provideOptions;
5018 Reflect.ownKeys(provides).forEach(key => {
5019 provide(key, provides[key]);
5020 });
5021 }
5022 if (created) {
5023 callHook(created, instance, "c" /* LifecycleHooks.CREATED */);
5024 }
5025 function registerLifecycleHook(register, hook) {
5026 if (isArray(hook)) {
5027 hook.forEach(_hook => register(_hook.bind(publicThis)));
5028 }
5029 else if (hook) {
5030 register(hook.bind(publicThis));
5031 }
5032 }
5033 registerLifecycleHook(onBeforeMount, beforeMount);
5034 registerLifecycleHook(onMounted, mounted);
5035 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
5036 registerLifecycleHook(onUpdated, updated);
5037 registerLifecycleHook(onActivated, activated);
5038 registerLifecycleHook(onDeactivated, deactivated);
5039 registerLifecycleHook(onErrorCaptured, errorCaptured);
5040 registerLifecycleHook(onRenderTracked, renderTracked);
5041 registerLifecycleHook(onRenderTriggered, renderTriggered);
5042 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
5043 registerLifecycleHook(onUnmounted, unmounted);
5044 registerLifecycleHook(onServerPrefetch, serverPrefetch);
5045 if (isArray(expose)) {
5046 if (expose.length) {
5047 const exposed = instance.exposed || (instance.exposed = {});
5048 expose.forEach(key => {
5049 Object.defineProperty(exposed, key, {
5050 get: () => publicThis[key],
5051 set: val => (publicThis[key] = val)
5052 });
5053 });
5054 }
5055 else if (!instance.exposed) {
5056 instance.exposed = {};
5057 }
5058 }
5059 // options that are handled when creating the instance but also need to be
5060 // applied from mixins
5061 if (render && instance.render === NOOP) {
5062 instance.render = render;
5063 }
5064 if (inheritAttrs != null) {
5065 instance.inheritAttrs = inheritAttrs;
5066 }
5067 // asset options.
5068 if (components)
5069 instance.components = components;
5070 if (directives)
5071 instance.directives = directives;
5072}
5073function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
5074 if (isArray(injectOptions)) {
5075 injectOptions = normalizeInject(injectOptions);
5076 }
5077 for (const key in injectOptions) {
5078 const opt = injectOptions[key];
5079 let injected;
5080 if (isObject(opt)) {
5081 if ('default' in opt) {
5082 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
5083 }
5084 else {
5085 injected = inject(opt.from || key);
5086 }
5087 }
5088 else {
5089 injected = inject(opt);
5090 }
5091 if (isRef(injected)) {
5092 // TODO remove the check in 3.3
5093 if (unwrapRef) {
5094 Object.defineProperty(ctx, key, {
5095 enumerable: true,
5096 configurable: true,
5097 get: () => injected.value,
5098 set: v => (injected.value = v)
5099 });
5100 }
5101 else {
5102 {
5103 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
5104 `and no longer needs \`.value\` in the next minor release. ` +
5105 `To opt-in to the new behavior now, ` +
5106 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
5107 `temporary and will not be needed in the future.)`);
5108 }
5109 ctx[key] = injected;
5110 }
5111 }
5112 else {
5113 ctx[key] = injected;
5114 }
5115 {
5116 checkDuplicateProperties("Inject" /* OptionTypes.INJECT */, key);
5117 }
5118 }
5119}
5120function callHook(hook, instance, type) {
5121 callWithAsyncErrorHandling(isArray(hook)
5122 ? hook.map(h => h.bind(instance.proxy))
5123 : hook.bind(instance.proxy), instance, type);
5124}
5125function createWatcher(raw, ctx, publicThis, key) {
5126 const getter = key.includes('.')
5127 ? createPathGetter(publicThis, key)
5128 : () => publicThis[key];
5129 if (isString(raw)) {
5130 const handler = ctx[raw];
5131 if (isFunction(handler)) {
5132 watch(getter, handler);
5133 }
5134 else {
5135 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
5136 }
5137 }
5138 else if (isFunction(raw)) {
5139 watch(getter, raw.bind(publicThis));
5140 }
5141 else if (isObject(raw)) {
5142 if (isArray(raw)) {
5143 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
5144 }
5145 else {
5146 const handler = isFunction(raw.handler)
5147 ? raw.handler.bind(publicThis)
5148 : ctx[raw.handler];
5149 if (isFunction(handler)) {
5150 watch(getter, handler, raw);
5151 }
5152 else {
5153 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
5154 }
5155 }
5156 }
5157 else {
5158 warn$1(`Invalid watch option: "${key}"`, raw);
5159 }
5160}
5161/**
5162 * Resolve merged options and cache it on the component.
5163 * This is done only once per-component since the merging does not involve
5164 * instances.
5165 */
5166function resolveMergedOptions(instance) {
5167 const base = instance.type;
5168 const { mixins, extends: extendsOptions } = base;
5169 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
5170 const cached = cache.get(base);
5171 let resolved;
5172 if (cached) {
5173 resolved = cached;
5174 }
5175 else if (!globalMixins.length && !mixins && !extendsOptions) {
5176 {
5177 resolved = base;
5178 }
5179 }
5180 else {
5181 resolved = {};
5182 if (globalMixins.length) {
5183 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
5184 }
5185 mergeOptions(resolved, base, optionMergeStrategies);
5186 }
5187 if (isObject(base)) {
5188 cache.set(base, resolved);
5189 }
5190 return resolved;
5191}
5192function mergeOptions(to, from, strats, asMixin = false) {
5193 const { mixins, extends: extendsOptions } = from;
5194 if (extendsOptions) {
5195 mergeOptions(to, extendsOptions, strats, true);
5196 }
5197 if (mixins) {
5198 mixins.forEach((m) => mergeOptions(to, m, strats, true));
5199 }
5200 for (const key in from) {
5201 if (asMixin && key === 'expose') {
5202 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
5203 `It should only be declared in the base component itself.`);
5204 }
5205 else {
5206 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
5207 to[key] = strat ? strat(to[key], from[key]) : from[key];
5208 }
5209 }
5210 return to;
5211}
5212const internalOptionMergeStrats = {
5213 data: mergeDataFn,
5214 props: mergeObjectOptions,
5215 emits: mergeObjectOptions,
5216 // objects
5217 methods: mergeObjectOptions,
5218 computed: mergeObjectOptions,
5219 // lifecycle
5220 beforeCreate: mergeAsArray,
5221 created: mergeAsArray,
5222 beforeMount: mergeAsArray,
5223 mounted: mergeAsArray,
5224 beforeUpdate: mergeAsArray,
5225 updated: mergeAsArray,
5226 beforeDestroy: mergeAsArray,
5227 beforeUnmount: mergeAsArray,
5228 destroyed: mergeAsArray,
5229 unmounted: mergeAsArray,
5230 activated: mergeAsArray,
5231 deactivated: mergeAsArray,
5232 errorCaptured: mergeAsArray,
5233 serverPrefetch: mergeAsArray,
5234 // assets
5235 components: mergeObjectOptions,
5236 directives: mergeObjectOptions,
5237 // watch
5238 watch: mergeWatchOptions,
5239 // provide / inject
5240 provide: mergeDataFn,
5241 inject: mergeInject
5242};
5243function mergeDataFn(to, from) {
5244 if (!from) {
5245 return to;
5246 }
5247 if (!to) {
5248 return from;
5249 }
5250 return function mergedDataFn() {
5251 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
5252 };
5253}
5254function mergeInject(to, from) {
5255 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
5256}
5257function normalizeInject(raw) {
5258 if (isArray(raw)) {
5259 const res = {};
5260 for (let i = 0; i < raw.length; i++) {
5261 res[raw[i]] = raw[i];
5262 }
5263 return res;
5264 }
5265 return raw;
5266}
5267function mergeAsArray(to, from) {
5268 return to ? [...new Set([].concat(to, from))] : from;
5269}
5270function mergeObjectOptions(to, from) {
5271 return to ? extend(extend(Object.create(null), to), from) : from;
5272}
5273function mergeWatchOptions(to, from) {
5274 if (!to)
5275 return from;
5276 if (!from)
5277 return to;
5278 const merged = extend(Object.create(null), to);
5279 for (const key in from) {
5280 merged[key] = mergeAsArray(to[key], from[key]);
5281 }
5282 return merged;
5283}
5284
5285function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
5286isSSR = false) {
5287 const props = {};
5288 const attrs = {};
5289 def(attrs, InternalObjectKey, 1);
5290 instance.propsDefaults = Object.create(null);
5291 setFullProps(instance, rawProps, props, attrs);
5292 // ensure all declared prop keys are present
5293 for (const key in instance.propsOptions[0]) {
5294 if (!(key in props)) {
5295 props[key] = undefined;
5296 }
5297 }
5298 // validation
5299 {
5300 validateProps(rawProps || {}, props, instance);
5301 }
5302 if (isStateful) {
5303 // stateful
5304 instance.props = isSSR ? props : shallowReactive(props);
5305 }
5306 else {
5307 if (!instance.type.props) {
5308 // functional w/ optional props, props === attrs
5309 instance.props = attrs;
5310 }
5311 else {
5312 // functional w/ declared props
5313 instance.props = props;
5314 }
5315 }
5316 instance.attrs = attrs;
5317}
5318function isInHmrContext(instance) {
5319 while (instance) {
5320 if (instance.type.__hmrId)
5321 return true;
5322 instance = instance.parent;
5323 }
5324}
5325function updateProps(instance, rawProps, rawPrevProps, optimized) {
5326 const { props, attrs, vnode: { patchFlag } } = instance;
5327 const rawCurrentProps = toRaw(props);
5328 const [options] = instance.propsOptions;
5329 let hasAttrsChanged = false;
5330 if (
5331 // always force full diff in dev
5332 // - #1942 if hmr is enabled with sfc component
5333 // - vite#872 non-sfc component used by sfc component
5334 !(isInHmrContext(instance)) &&
5335 (optimized || patchFlag > 0) &&
5336 !(patchFlag & 16 /* PatchFlags.FULL_PROPS */)) {
5337 if (patchFlag & 8 /* PatchFlags.PROPS */) {
5338 // Compiler-generated props & no keys change, just set the updated
5339 // the props.
5340 const propsToUpdate = instance.vnode.dynamicProps;
5341 for (let i = 0; i < propsToUpdate.length; i++) {
5342 let key = propsToUpdate[i];
5343 // skip if the prop key is a declared emit event listener
5344 if (isEmitListener(instance.emitsOptions, key)) {
5345 continue;
5346 }
5347 // PROPS flag guarantees rawProps to be non-null
5348 const value = rawProps[key];
5349 if (options) {
5350 // attr / props separation was done on init and will be consistent
5351 // in this code path, so just check if attrs have it.
5352 if (hasOwn(attrs, key)) {
5353 if (value !== attrs[key]) {
5354 attrs[key] = value;
5355 hasAttrsChanged = true;
5356 }
5357 }
5358 else {
5359 const camelizedKey = camelize(key);
5360 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
5361 }
5362 }
5363 else {
5364 if (value !== attrs[key]) {
5365 attrs[key] = value;
5366 hasAttrsChanged = true;
5367 }
5368 }
5369 }
5370 }
5371 }
5372 else {
5373 // full props update.
5374 if (setFullProps(instance, rawProps, props, attrs)) {
5375 hasAttrsChanged = true;
5376 }
5377 // in case of dynamic props, check if we need to delete keys from
5378 // the props object
5379 let kebabKey;
5380 for (const key in rawCurrentProps) {
5381 if (!rawProps ||
5382 // for camelCase
5383 (!hasOwn(rawProps, key) &&
5384 // it's possible the original props was passed in as kebab-case
5385 // and converted to camelCase (#955)
5386 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
5387 if (options) {
5388 if (rawPrevProps &&
5389 // for camelCase
5390 (rawPrevProps[key] !== undefined ||
5391 // for kebab-case
5392 rawPrevProps[kebabKey] !== undefined)) {
5393 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
5394 }
5395 }
5396 else {
5397 delete props[key];
5398 }
5399 }
5400 }
5401 // in the case of functional component w/o props declaration, props and
5402 // attrs point to the same object so it should already have been updated.
5403 if (attrs !== rawCurrentProps) {
5404 for (const key in attrs) {
5405 if (!rawProps ||
5406 (!hasOwn(rawProps, key) &&
5407 (!false ))) {
5408 delete attrs[key];
5409 hasAttrsChanged = true;
5410 }
5411 }
5412 }
5413 }
5414 // trigger updates for $attrs in case it's used in component slots
5415 if (hasAttrsChanged) {
5416 trigger(instance, "set" /* TriggerOpTypes.SET */, '$attrs');
5417 }
5418 {
5419 validateProps(rawProps || {}, props, instance);
5420 }
5421}
5422function setFullProps(instance, rawProps, props, attrs) {
5423 const [options, needCastKeys] = instance.propsOptions;
5424 let hasAttrsChanged = false;
5425 let rawCastValues;
5426 if (rawProps) {
5427 for (let key in rawProps) {
5428 // key, ref are reserved and never passed down
5429 if (isReservedProp(key)) {
5430 continue;
5431 }
5432 const value = rawProps[key];
5433 // prop option names are camelized during normalization, so to support
5434 // kebab -> camel conversion here we need to camelize the key.
5435 let camelKey;
5436 if (options && hasOwn(options, (camelKey = camelize(key)))) {
5437 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
5438 props[camelKey] = value;
5439 }
5440 else {
5441 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
5442 }
5443 }
5444 else if (!isEmitListener(instance.emitsOptions, key)) {
5445 if (!(key in attrs) || value !== attrs[key]) {
5446 attrs[key] = value;
5447 hasAttrsChanged = true;
5448 }
5449 }
5450 }
5451 }
5452 if (needCastKeys) {
5453 const rawCurrentProps = toRaw(props);
5454 const castValues = rawCastValues || EMPTY_OBJ;
5455 for (let i = 0; i < needCastKeys.length; i++) {
5456 const key = needCastKeys[i];
5457 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
5458 }
5459 }
5460 return hasAttrsChanged;
5461}
5462function resolvePropValue(options, props, key, value, instance, isAbsent) {
5463 const opt = options[key];
5464 if (opt != null) {
5465 const hasDefault = hasOwn(opt, 'default');
5466 // default values
5467 if (hasDefault && value === undefined) {
5468 const defaultValue = opt.default;
5469 if (opt.type !== Function && isFunction(defaultValue)) {
5470 const { propsDefaults } = instance;
5471 if (key in propsDefaults) {
5472 value = propsDefaults[key];
5473 }
5474 else {
5475 setCurrentInstance(instance);
5476 value = propsDefaults[key] = defaultValue.call(null, props);
5477 unsetCurrentInstance();
5478 }
5479 }
5480 else {
5481 value = defaultValue;
5482 }
5483 }
5484 // boolean casting
5485 if (opt[0 /* BooleanFlags.shouldCast */]) {
5486 if (isAbsent && !hasDefault) {
5487 value = false;
5488 }
5489 else if (opt[1 /* BooleanFlags.shouldCastTrue */] &&
5490 (value === '' || value === hyphenate(key))) {
5491 value = true;
5492 }
5493 }
5494 }
5495 return value;
5496}
5497function normalizePropsOptions(comp, appContext, asMixin = false) {
5498 const cache = appContext.propsCache;
5499 const cached = cache.get(comp);
5500 if (cached) {
5501 return cached;
5502 }
5503 const raw = comp.props;
5504 const normalized = {};
5505 const needCastKeys = [];
5506 // apply mixin/extends props
5507 let hasExtends = false;
5508 if (!isFunction(comp)) {
5509 const extendProps = (raw) => {
5510 hasExtends = true;
5511 const [props, keys] = normalizePropsOptions(raw, appContext, true);
5512 extend(normalized, props);
5513 if (keys)
5514 needCastKeys.push(...keys);
5515 };
5516 if (!asMixin && appContext.mixins.length) {
5517 appContext.mixins.forEach(extendProps);
5518 }
5519 if (comp.extends) {
5520 extendProps(comp.extends);
5521 }
5522 if (comp.mixins) {
5523 comp.mixins.forEach(extendProps);
5524 }
5525 }
5526 if (!raw && !hasExtends) {
5527 if (isObject(comp)) {
5528 cache.set(comp, EMPTY_ARR);
5529 }
5530 return EMPTY_ARR;
5531 }
5532 if (isArray(raw)) {
5533 for (let i = 0; i < raw.length; i++) {
5534 if (!isString(raw[i])) {
5535 warn$1(`props must be strings when using array syntax.`, raw[i]);
5536 }
5537 const normalizedKey = camelize(raw[i]);
5538 if (validatePropName(normalizedKey)) {
5539 normalized[normalizedKey] = EMPTY_OBJ;
5540 }
5541 }
5542 }
5543 else if (raw) {
5544 if (!isObject(raw)) {
5545 warn$1(`invalid props options`, raw);
5546 }
5547 for (const key in raw) {
5548 const normalizedKey = camelize(key);
5549 if (validatePropName(normalizedKey)) {
5550 const opt = raw[key];
5551 const prop = (normalized[normalizedKey] =
5552 isArray(opt) || isFunction(opt) ? { type: opt } : Object.assign({}, opt));
5553 if (prop) {
5554 const booleanIndex = getTypeIndex(Boolean, prop.type);
5555 const stringIndex = getTypeIndex(String, prop.type);
5556 prop[0 /* BooleanFlags.shouldCast */] = booleanIndex > -1;
5557 prop[1 /* BooleanFlags.shouldCastTrue */] =
5558 stringIndex < 0 || booleanIndex < stringIndex;
5559 // if the prop needs boolean casting or default value
5560 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
5561 needCastKeys.push(normalizedKey);
5562 }
5563 }
5564 }
5565 }
5566 }
5567 const res = [normalized, needCastKeys];
5568 if (isObject(comp)) {
5569 cache.set(comp, res);
5570 }
5571 return res;
5572}
5573function validatePropName(key) {
5574 if (key[0] !== '$') {
5575 return true;
5576 }
5577 else {
5578 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
5579 }
5580 return false;
5581}
5582// use function string name to check type constructors
5583// so that it works across vms / iframes.
5584function getType(ctor) {
5585 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
5586 return match ? match[1] : ctor === null ? 'null' : '';
5587}
5588function isSameType(a, b) {
5589 return getType(a) === getType(b);
5590}
5591function getTypeIndex(type, expectedTypes) {
5592 if (isArray(expectedTypes)) {
5593 return expectedTypes.findIndex(t => isSameType(t, type));
5594 }
5595 else if (isFunction(expectedTypes)) {
5596 return isSameType(expectedTypes, type) ? 0 : -1;
5597 }
5598 return -1;
5599}
5600/**
5601 * dev only
5602 */
5603function validateProps(rawProps, props, instance) {
5604 const resolvedValues = toRaw(props);
5605 const options = instance.propsOptions[0];
5606 for (const key in options) {
5607 let opt = options[key];
5608 if (opt == null)
5609 continue;
5610 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
5611 }
5612}
5613/**
5614 * dev only
5615 */
5616function validateProp(name, value, prop, isAbsent) {
5617 const { type, required, validator } = prop;
5618 // required!
5619 if (required && isAbsent) {
5620 warn$1('Missing required prop: "' + name + '"');
5621 return;
5622 }
5623 // missing but optional
5624 if (value == null && !prop.required) {
5625 return;
5626 }
5627 // type check
5628 if (type != null && type !== true) {
5629 let isValid = false;
5630 const types = isArray(type) ? type : [type];
5631 const expectedTypes = [];
5632 // value is valid as long as one of the specified types match
5633 for (let i = 0; i < types.length && !isValid; i++) {
5634 const { valid, expectedType } = assertType(value, types[i]);
5635 expectedTypes.push(expectedType || '');
5636 isValid = valid;
5637 }
5638 if (!isValid) {
5639 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
5640 return;
5641 }
5642 }
5643 // custom validator
5644 if (validator && !validator(value)) {
5645 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
5646 }
5647}
5648const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
5649/**
5650 * dev only
5651 */
5652function assertType(value, type) {
5653 let valid;
5654 const expectedType = getType(type);
5655 if (isSimpleType(expectedType)) {
5656 const t = typeof value;
5657 valid = t === expectedType.toLowerCase();
5658 // for primitive wrapper objects
5659 if (!valid && t === 'object') {
5660 valid = value instanceof type;
5661 }
5662 }
5663 else if (expectedType === 'Object') {
5664 valid = isObject(value);
5665 }
5666 else if (expectedType === 'Array') {
5667 valid = isArray(value);
5668 }
5669 else if (expectedType === 'null') {
5670 valid = value === null;
5671 }
5672 else {
5673 valid = value instanceof type;
5674 }
5675 return {
5676 valid,
5677 expectedType
5678 };
5679}
5680/**
5681 * dev only
5682 */
5683function getInvalidTypeMessage(name, value, expectedTypes) {
5684 let message = `Invalid prop: type check failed for prop "${name}".` +
5685 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
5686 const expectedType = expectedTypes[0];
5687 const receivedType = toRawType(value);
5688 const expectedValue = styleValue(value, expectedType);
5689 const receivedValue = styleValue(value, receivedType);
5690 // check if we need to specify expected value
5691 if (expectedTypes.length === 1 &&
5692 isExplicable(expectedType) &&
5693 !isBoolean(expectedType, receivedType)) {
5694 message += ` with value ${expectedValue}`;
5695 }
5696 message += `, got ${receivedType} `;
5697 // check if we need to specify received value
5698 if (isExplicable(receivedType)) {
5699 message += `with value ${receivedValue}.`;
5700 }
5701 return message;
5702}
5703/**
5704 * dev only
5705 */
5706function styleValue(value, type) {
5707 if (type === 'String') {
5708 return `"${value}"`;
5709 }
5710 else if (type === 'Number') {
5711 return `${Number(value)}`;
5712 }
5713 else {
5714 return `${value}`;
5715 }
5716}
5717/**
5718 * dev only
5719 */
5720function isExplicable(type) {
5721 const explicitTypes = ['string', 'number', 'boolean'];
5722 return explicitTypes.some(elem => type.toLowerCase() === elem);
5723}
5724/**
5725 * dev only
5726 */
5727function isBoolean(...args) {
5728 return args.some(elem => elem.toLowerCase() === 'boolean');
5729}
5730
5731const isInternalKey = (key) => key[0] === '_' || key === '$stable';
5732const normalizeSlotValue = (value) => isArray(value)
5733 ? value.map(normalizeVNode)
5734 : [normalizeVNode(value)];
5735const normalizeSlot = (key, rawSlot, ctx) => {
5736 if (rawSlot._n) {
5737 // already normalized - #5353
5738 return rawSlot;
5739 }
5740 const normalized = withCtx((...args) => {
5741 if (true && currentInstance) {
5742 warn$1(`Slot "${key}" invoked outside of the render function: ` +
5743 `this will not track dependencies used in the slot. ` +
5744 `Invoke the slot function inside the render function instead.`);
5745 }
5746 return normalizeSlotValue(rawSlot(...args));
5747 }, ctx);
5748 normalized._c = false;
5749 return normalized;
5750};
5751const normalizeObjectSlots = (rawSlots, slots, instance) => {
5752 const ctx = rawSlots._ctx;
5753 for (const key in rawSlots) {
5754 if (isInternalKey(key))
5755 continue;
5756 const value = rawSlots[key];
5757 if (isFunction(value)) {
5758 slots[key] = normalizeSlot(key, value, ctx);
5759 }
5760 else if (value != null) {
5761 {
5762 warn$1(`Non-function value encountered for slot "${key}". ` +
5763 `Prefer function slots for better performance.`);
5764 }
5765 const normalized = normalizeSlotValue(value);
5766 slots[key] = () => normalized;
5767 }
5768 }
5769};
5770const normalizeVNodeSlots = (instance, children) => {
5771 if (!isKeepAlive(instance.vnode) &&
5772 !(false )) {
5773 warn$1(`Non-function value encountered for default slot. ` +
5774 `Prefer function slots for better performance.`);
5775 }
5776 const normalized = normalizeSlotValue(children);
5777 instance.slots.default = () => normalized;
5778};
5779const initSlots = (instance, children) => {
5780 if (instance.vnode.shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */) {
5781 const type = children._;
5782 if (type) {
5783 // users can get the shallow readonly version of the slots object through `this.$slots`,
5784 // we should avoid the proxy object polluting the slots of the internal instance
5785 instance.slots = toRaw(children);
5786 // make compiler marker non-enumerable
5787 def(children, '_', type);
5788 }
5789 else {
5790 normalizeObjectSlots(children, (instance.slots = {}));
5791 }
5792 }
5793 else {
5794 instance.slots = {};
5795 if (children) {
5796 normalizeVNodeSlots(instance, children);
5797 }
5798 }
5799 def(instance.slots, InternalObjectKey, 1);
5800};
5801const updateSlots = (instance, children, optimized) => {
5802 const { vnode, slots } = instance;
5803 let needDeletionCheck = true;
5804 let deletionComparisonTarget = EMPTY_OBJ;
5805 if (vnode.shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */) {
5806 const type = children._;
5807 if (type) {
5808 // compiled slots.
5809 if (isHmrUpdating) {
5810 // Parent was HMR updated so slot content may have changed.
5811 // force update slots and mark instance for hmr as well
5812 extend(slots, children);
5813 }
5814 else if (optimized && type === 1 /* SlotFlags.STABLE */) {
5815 // compiled AND stable.
5816 // no need to update, and skip stale slots removal.
5817 needDeletionCheck = false;
5818 }
5819 else {
5820 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5821 // normalization.
5822 extend(slots, children);
5823 // #2893
5824 // when rendering the optimized slots by manually written render function,
5825 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5826 // i.e. let the `renderSlot` create the bailed Fragment
5827 if (!optimized && type === 1 /* SlotFlags.STABLE */) {
5828 delete slots._;
5829 }
5830 }
5831 }
5832 else {
5833 needDeletionCheck = !children.$stable;
5834 normalizeObjectSlots(children, slots);
5835 }
5836 deletionComparisonTarget = children;
5837 }
5838 else if (children) {
5839 // non slot object children (direct value) passed to a component
5840 normalizeVNodeSlots(instance, children);
5841 deletionComparisonTarget = { default: 1 };
5842 }
5843 // delete stale slots
5844 if (needDeletionCheck) {
5845 for (const key in slots) {
5846 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5847 delete slots[key];
5848 }
5849 }
5850 }
5851};
5852
5853function createAppContext() {
5854 return {
5855 app: null,
5856 config: {
5857 isNativeTag: NO,
5858 performance: false,
5859 globalProperties: {},
5860 optionMergeStrategies: {},
5861 errorHandler: undefined,
5862 warnHandler: undefined,
5863 compilerOptions: {}
5864 },
5865 mixins: [],
5866 components: {},
5867 directives: {},
5868 provides: Object.create(null),
5869 optionsCache: new WeakMap(),
5870 propsCache: new WeakMap(),
5871 emitsCache: new WeakMap()
5872 };
5873}
5874let uid = 0;
5875function createAppAPI(render, hydrate) {
5876 return function createApp(rootComponent, rootProps = null) {
5877 if (!isFunction(rootComponent)) {
5878 rootComponent = Object.assign({}, rootComponent);
5879 }
5880 if (rootProps != null && !isObject(rootProps)) {
5881 warn$1(`root props passed to app.mount() must be an object.`);
5882 rootProps = null;
5883 }
5884 const context = createAppContext();
5885 const installedPlugins = new Set();
5886 let isMounted = false;
5887 const app = (context.app = {
5888 _uid: uid++,
5889 _component: rootComponent,
5890 _props: rootProps,
5891 _container: null,
5892 _context: context,
5893 _instance: null,
5894 version,
5895 get config() {
5896 return context.config;
5897 },
5898 set config(v) {
5899 {
5900 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
5901 }
5902 },
5903 use(plugin, ...options) {
5904 if (installedPlugins.has(plugin)) {
5905 warn$1(`Plugin has already been applied to target app.`);
5906 }
5907 else if (plugin && isFunction(plugin.install)) {
5908 installedPlugins.add(plugin);
5909 plugin.install(app, ...options);
5910 }
5911 else if (isFunction(plugin)) {
5912 installedPlugins.add(plugin);
5913 plugin(app, ...options);
5914 }
5915 else {
5916 warn$1(`A plugin must either be a function or an object with an "install" ` +
5917 `function.`);
5918 }
5919 return app;
5920 },
5921 mixin(mixin) {
5922 {
5923 if (!context.mixins.includes(mixin)) {
5924 context.mixins.push(mixin);
5925 }
5926 else {
5927 warn$1('Mixin has already been applied to target app' +
5928 (mixin.name ? `: ${mixin.name}` : ''));
5929 }
5930 }
5931 return app;
5932 },
5933 component(name, component) {
5934 {
5935 validateComponentName(name, context.config);
5936 }
5937 if (!component) {
5938 return context.components[name];
5939 }
5940 if (context.components[name]) {
5941 warn$1(`Component "${name}" has already been registered in target app.`);
5942 }
5943 context.components[name] = component;
5944 return app;
5945 },
5946 directive(name, directive) {
5947 {
5948 validateDirectiveName(name);
5949 }
5950 if (!directive) {
5951 return context.directives[name];
5952 }
5953 if (context.directives[name]) {
5954 warn$1(`Directive "${name}" has already been registered in target app.`);
5955 }
5956 context.directives[name] = directive;
5957 return app;
5958 },
5959 mount(rootContainer, isHydrate, isSVG) {
5960 if (!isMounted) {
5961 // #5571
5962 if (rootContainer.__vue_app__) {
5963 warn$1(`There is already an app instance mounted on the host container.\n` +
5964 ` If you want to mount another app on the same host container,` +
5965 ` you need to unmount the previous app by calling \`app.unmount()\` first.`);
5966 }
5967 const vnode = createVNode(rootComponent, rootProps);
5968 // store app context on the root VNode.
5969 // this will be set on the root instance on initial mount.
5970 vnode.appContext = context;
5971 // HMR root reload
5972 {
5973 context.reload = () => {
5974 render(cloneVNode(vnode), rootContainer, isSVG);
5975 };
5976 }
5977 if (isHydrate && hydrate) {
5978 hydrate(vnode, rootContainer);
5979 }
5980 else {
5981 render(vnode, rootContainer, isSVG);
5982 }
5983 isMounted = true;
5984 app._container = rootContainer;
5985 rootContainer.__vue_app__ = app;
5986 {
5987 app._instance = vnode.component;
5988 devtoolsInitApp(app, version);
5989 }
5990 return getExposeProxy(vnode.component) || vnode.component.proxy;
5991 }
5992 else {
5993 warn$1(`App has already been mounted.\n` +
5994 `If you want to remount the same app, move your app creation logic ` +
5995 `into a factory function and create fresh app instances for each ` +
5996 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5997 }
5998 },
5999 unmount() {
6000 if (isMounted) {
6001 render(null, app._container);
6002 {
6003 app._instance = null;
6004 devtoolsUnmountApp(app);
6005 }
6006 delete app._container.__vue_app__;
6007 }
6008 else {
6009 warn$1(`Cannot unmount an app that is not mounted.`);
6010 }
6011 },
6012 provide(key, value) {
6013 if (key in context.provides) {
6014 warn$1(`App already provides property with key "${String(key)}". ` +
6015 `It will be overwritten with the new value.`);
6016 }
6017 context.provides[key] = value;
6018 return app;
6019 }
6020 });
6021 return app;
6022 };
6023}
6024
6025/**
6026 * Function for handling a template ref
6027 */
6028function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
6029 if (isArray(rawRef)) {
6030 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
6031 return;
6032 }
6033 if (isAsyncWrapper(vnode) && !isUnmount) {
6034 // when mounting async components, nothing needs to be done,
6035 // because the template ref is forwarded to inner component
6036 return;
6037 }
6038 const refValue = vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */
6039 ? getExposeProxy(vnode.component) || vnode.component.proxy
6040 : vnode.el;
6041 const value = isUnmount ? null : refValue;
6042 const { i: owner, r: ref } = rawRef;
6043 if (!owner) {
6044 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
6045 `A vnode with ref must be created inside the render function.`);
6046 return;
6047 }
6048 const oldRef = oldRawRef && oldRawRef.r;
6049 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
6050 const setupState = owner.setupState;
6051 // dynamic ref changed. unset old ref
6052 if (oldRef != null && oldRef !== ref) {
6053 if (isString(oldRef)) {
6054 refs[oldRef] = null;
6055 if (hasOwn(setupState, oldRef)) {
6056 setupState[oldRef] = null;
6057 }
6058 }
6059 else if (isRef(oldRef)) {
6060 oldRef.value = null;
6061 }
6062 }
6063 if (isFunction(ref)) {
6064 callWithErrorHandling(ref, owner, 12 /* ErrorCodes.FUNCTION_REF */, [value, refs]);
6065 }
6066 else {
6067 const _isString = isString(ref);
6068 const _isRef = isRef(ref);
6069 if (_isString || _isRef) {
6070 const doSet = () => {
6071 if (rawRef.f) {
6072 const existing = _isString
6073 ? hasOwn(setupState, ref)
6074 ? setupState[ref]
6075 : refs[ref]
6076 : ref.value;
6077 if (isUnmount) {
6078 isArray(existing) && remove(existing, refValue);
6079 }
6080 else {
6081 if (!isArray(existing)) {
6082 if (_isString) {
6083 refs[ref] = [refValue];
6084 if (hasOwn(setupState, ref)) {
6085 setupState[ref] = refs[ref];
6086 }
6087 }
6088 else {
6089 ref.value = [refValue];
6090 if (rawRef.k)
6091 refs[rawRef.k] = ref.value;
6092 }
6093 }
6094 else if (!existing.includes(refValue)) {
6095 existing.push(refValue);
6096 }
6097 }
6098 }
6099 else if (_isString) {
6100 refs[ref] = value;
6101 if (hasOwn(setupState, ref)) {
6102 setupState[ref] = value;
6103 }
6104 }
6105 else if (_isRef) {
6106 ref.value = value;
6107 if (rawRef.k)
6108 refs[rawRef.k] = value;
6109 }
6110 else {
6111 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
6112 }
6113 };
6114 if (value) {
6115 doSet.id = -1;
6116 queuePostRenderEffect(doSet, parentSuspense);
6117 }
6118 else {
6119 doSet();
6120 }
6121 }
6122 else {
6123 warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
6124 }
6125 }
6126}
6127
6128let hasMismatch = false;
6129const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
6130const isComment = (node) => node.nodeType === 8 /* DOMNodeTypes.COMMENT */;
6131// Note: hydration is DOM-specific
6132// But we have to place it in core due to tight coupling with core - splitting
6133// it out creates a ton of unnecessary complexity.
6134// Hydration also depends on some renderer internal logic which needs to be
6135// passed in via arguments.
6136function createHydrationFunctions(rendererInternals) {
6137 const { mt: mountComponent, p: patch, o: { patchProp, createText, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
6138 const hydrate = (vnode, container) => {
6139 if (!container.hasChildNodes()) {
6140 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
6141 `Performing full mount instead.`);
6142 patch(null, vnode, container);
6143 flushPostFlushCbs();
6144 container._vnode = vnode;
6145 return;
6146 }
6147 hasMismatch = false;
6148 hydrateNode(container.firstChild, vnode, null, null, null);
6149 flushPostFlushCbs();
6150 container._vnode = vnode;
6151 if (hasMismatch && !false) {
6152 // this error should show up in production
6153 console.error(`Hydration completed but contains mismatches.`);
6154 }
6155 };
6156 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
6157 const isFragmentStart = isComment(node) && node.data === '[';
6158 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
6159 const { type, ref, shapeFlag, patchFlag } = vnode;
6160 let domType = node.nodeType;
6161 vnode.el = node;
6162 if (patchFlag === -2 /* PatchFlags.BAIL */) {
6163 optimized = false;
6164 vnode.dynamicChildren = null;
6165 }
6166 let nextNode = null;
6167 switch (type) {
6168 case Text:
6169 if (domType !== 3 /* DOMNodeTypes.TEXT */) {
6170 // #5728 empty text node inside a slot can cause hydration failure
6171 // because the server rendered HTML won't contain a text node
6172 if (vnode.children === '') {
6173 insert((vnode.el = createText('')), parentNode(node), node);
6174 nextNode = node;
6175 }
6176 else {
6177 nextNode = onMismatch();
6178 }
6179 }
6180 else {
6181 if (node.data !== vnode.children) {
6182 hasMismatch = true;
6183 warn$1(`Hydration text mismatch:` +
6184 `\n- Client: ${JSON.stringify(node.data)}` +
6185 `\n- Server: ${JSON.stringify(vnode.children)}`);
6186 node.data = vnode.children;
6187 }
6188 nextNode = nextSibling(node);
6189 }
6190 break;
6191 case Comment:
6192 if (domType !== 8 /* DOMNodeTypes.COMMENT */ || isFragmentStart) {
6193 nextNode = onMismatch();
6194 }
6195 else {
6196 nextNode = nextSibling(node);
6197 }
6198 break;
6199 case Static:
6200 if (isFragmentStart) {
6201 // entire template is static but SSRed as a fragment
6202 node = nextSibling(node);
6203 domType = node.nodeType;
6204 }
6205 if (domType === 1 /* DOMNodeTypes.ELEMENT */ || domType === 3 /* DOMNodeTypes.TEXT */) {
6206 // determine anchor, adopt content
6207 nextNode = node;
6208 // if the static vnode has its content stripped during build,
6209 // adopt it from the server-rendered HTML.
6210 const needToAdoptContent = !vnode.children.length;
6211 for (let i = 0; i < vnode.staticCount; i++) {
6212 if (needToAdoptContent)
6213 vnode.children +=
6214 nextNode.nodeType === 1 /* DOMNodeTypes.ELEMENT */
6215 ? nextNode.outerHTML
6216 : nextNode.data;
6217 if (i === vnode.staticCount - 1) {
6218 vnode.anchor = nextNode;
6219 }
6220 nextNode = nextSibling(nextNode);
6221 }
6222 return isFragmentStart ? nextSibling(nextNode) : nextNode;
6223 }
6224 else {
6225 onMismatch();
6226 }
6227 break;
6228 case Fragment:
6229 if (!isFragmentStart) {
6230 nextNode = onMismatch();
6231 }
6232 else {
6233 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
6234 }
6235 break;
6236 default:
6237 if (shapeFlag & 1 /* ShapeFlags.ELEMENT */) {
6238 if (domType !== 1 /* DOMNodeTypes.ELEMENT */ ||
6239 vnode.type.toLowerCase() !==
6240 node.tagName.toLowerCase()) {
6241 nextNode = onMismatch();
6242 }
6243 else {
6244 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
6245 }
6246 }
6247 else if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
6248 // when setting up the render effect, if the initial vnode already
6249 // has .el set, the component will perform hydration instead of mount
6250 // on its sub-tree.
6251 vnode.slotScopeIds = slotScopeIds;
6252 const container = parentNode(node);
6253 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
6254 // component may be async, so in the case of fragments we cannot rely
6255 // on component's rendered output to determine the end of the fragment
6256 // instead, we do a lookahead to find the end anchor node.
6257 nextNode = isFragmentStart
6258 ? locateClosingAsyncAnchor(node)
6259 : nextSibling(node);
6260 // #4293 teleport as component root
6261 if (nextNode &&
6262 isComment(nextNode) &&
6263 nextNode.data === 'teleport end') {
6264 nextNode = nextSibling(nextNode);
6265 }
6266 // #3787
6267 // if component is async, it may get moved / unmounted before its
6268 // inner component is loaded, so we need to give it a placeholder
6269 // vnode that matches its adopted DOM.
6270 if (isAsyncWrapper(vnode)) {
6271 let subTree;
6272 if (isFragmentStart) {
6273 subTree = createVNode(Fragment);
6274 subTree.anchor = nextNode
6275 ? nextNode.previousSibling
6276 : container.lastChild;
6277 }
6278 else {
6279 subTree =
6280 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
6281 }
6282 subTree.el = node;
6283 vnode.component.subTree = subTree;
6284 }
6285 }
6286 else if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
6287 if (domType !== 8 /* DOMNodeTypes.COMMENT */) {
6288 nextNode = onMismatch();
6289 }
6290 else {
6291 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
6292 }
6293 }
6294 else if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
6295 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
6296 }
6297 else {
6298 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
6299 }
6300 }
6301 if (ref != null) {
6302 setRef(ref, null, parentSuspense, vnode);
6303 }
6304 return nextNode;
6305 };
6306 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
6307 optimized = optimized || !!vnode.dynamicChildren;
6308 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
6309 // #4006 for form elements with non-string v-model value bindings
6310 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
6311 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
6312 // skip props & children if this is hoisted static nodes
6313 // #5405 in dev, always hydrate children for HMR
6314 {
6315 if (dirs) {
6316 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6317 }
6318 // props
6319 if (props) {
6320 if (forcePatchValue ||
6321 !optimized ||
6322 patchFlag & (16 /* PatchFlags.FULL_PROPS */ | 32 /* PatchFlags.HYDRATE_EVENTS */)) {
6323 for (const key in props) {
6324 if ((forcePatchValue && key.endsWith('value')) ||
6325 (isOn(key) && !isReservedProp(key))) {
6326 patchProp(el, key, null, props[key], false, undefined, parentComponent);
6327 }
6328 }
6329 }
6330 else if (props.onClick) {
6331 // Fast path for click listeners (which is most often) to avoid
6332 // iterating through props.
6333 patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
6334 }
6335 }
6336 // vnode / directive hooks
6337 let vnodeHooks;
6338 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
6339 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
6340 }
6341 if (dirs) {
6342 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6343 }
6344 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
6345 queueEffectWithSuspense(() => {
6346 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
6347 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6348 }, parentSuspense);
6349 }
6350 // children
6351 if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */ &&
6352 // skip if element has innerHTML / textContent
6353 !(props && (props.innerHTML || props.textContent))) {
6354 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
6355 let hasWarned = false;
6356 while (next) {
6357 hasMismatch = true;
6358 if (!hasWarned) {
6359 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
6360 `server rendered element contains more child nodes than client vdom.`);
6361 hasWarned = true;
6362 }
6363 // The SSRed DOM contains more nodes than it should. Remove them.
6364 const cur = next;
6365 next = next.nextSibling;
6366 remove(cur);
6367 }
6368 }
6369 else if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
6370 if (el.textContent !== vnode.children) {
6371 hasMismatch = true;
6372 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
6373 `- Client: ${el.textContent}\n` +
6374 `- Server: ${vnode.children}`);
6375 el.textContent = vnode.children;
6376 }
6377 }
6378 }
6379 return el.nextSibling;
6380 };
6381 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
6382 optimized = optimized || !!parentVNode.dynamicChildren;
6383 const children = parentVNode.children;
6384 const l = children.length;
6385 let hasWarned = false;
6386 for (let i = 0; i < l; i++) {
6387 const vnode = optimized
6388 ? children[i]
6389 : (children[i] = normalizeVNode(children[i]));
6390 if (node) {
6391 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
6392 }
6393 else if (vnode.type === Text && !vnode.children) {
6394 continue;
6395 }
6396 else {
6397 hasMismatch = true;
6398 if (!hasWarned) {
6399 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
6400 `server rendered element contains fewer child nodes than client vdom.`);
6401 hasWarned = true;
6402 }
6403 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
6404 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
6405 }
6406 }
6407 return node;
6408 };
6409 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
6410 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
6411 if (fragmentSlotScopeIds) {
6412 slotScopeIds = slotScopeIds
6413 ? slotScopeIds.concat(fragmentSlotScopeIds)
6414 : fragmentSlotScopeIds;
6415 }
6416 const container = parentNode(node);
6417 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
6418 if (next && isComment(next) && next.data === ']') {
6419 return nextSibling((vnode.anchor = next));
6420 }
6421 else {
6422 // fragment didn't hydrate successfully, since we didn't get a end anchor
6423 // back. This should have led to node/children mismatch warnings.
6424 hasMismatch = true;
6425 // since the anchor is missing, we need to create one and insert it
6426 insert((vnode.anchor = createComment(`]`)), container, next);
6427 return next;
6428 }
6429 };
6430 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
6431 hasMismatch = true;
6432 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* DOMNodeTypes.TEXT */
6433 ? `(text)`
6434 : isComment(node) && node.data === '['
6435 ? `(start of fragment)`
6436 : ``);
6437 vnode.el = null;
6438 if (isFragment) {
6439 // remove excessive fragment nodes
6440 const end = locateClosingAsyncAnchor(node);
6441 while (true) {
6442 const next = nextSibling(node);
6443 if (next && next !== end) {
6444 remove(next);
6445 }
6446 else {
6447 break;
6448 }
6449 }
6450 }
6451 const next = nextSibling(node);
6452 const container = parentNode(node);
6453 remove(node);
6454 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
6455 return next;
6456 };
6457 const locateClosingAsyncAnchor = (node) => {
6458 let match = 0;
6459 while (node) {
6460 node = nextSibling(node);
6461 if (node && isComment(node)) {
6462 if (node.data === '[')
6463 match++;
6464 if (node.data === ']') {
6465 if (match === 0) {
6466 return nextSibling(node);
6467 }
6468 else {
6469 match--;
6470 }
6471 }
6472 }
6473 }
6474 return node;
6475 };
6476 return [hydrate, hydrateNode];
6477}
6478
6479/* eslint-disable no-restricted-globals */
6480let supported;
6481let perf;
6482function startMeasure(instance, type) {
6483 if (instance.appContext.config.performance && isSupported()) {
6484 perf.mark(`vue-${type}-${instance.uid}`);
6485 }
6486 {
6487 devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now());
6488 }
6489}
6490function endMeasure(instance, type) {
6491 if (instance.appContext.config.performance && isSupported()) {
6492 const startTag = `vue-${type}-${instance.uid}`;
6493 const endTag = startTag + `:end`;
6494 perf.mark(endTag);
6495 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
6496 perf.clearMarks(startTag);
6497 perf.clearMarks(endTag);
6498 }
6499 {
6500 devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now());
6501 }
6502}
6503function isSupported() {
6504 if (supported !== undefined) {
6505 return supported;
6506 }
6507 if (typeof window !== 'undefined' && window.performance) {
6508 supported = true;
6509 perf = window.performance;
6510 }
6511 else {
6512 supported = false;
6513 }
6514 return supported;
6515}
6516
6517const queuePostRenderEffect = queueEffectWithSuspense
6518 ;
6519/**
6520 * The createRenderer function accepts two generic arguments:
6521 * HostNode and HostElement, corresponding to Node and Element types in the
6522 * host environment. For example, for runtime-dom, HostNode would be the DOM
6523 * `Node` interface and HostElement would be the DOM `Element` interface.
6524 *
6525 * Custom renderers can pass in the platform specific types like this:
6526 *
6527 * ``` js
6528 * const { render, createApp } = createRenderer<Node, Element>({
6529 * patchProp,
6530 * ...nodeOps
6531 * })
6532 * ```
6533 */
6534function createRenderer(options) {
6535 return baseCreateRenderer(options);
6536}
6537// Separate API for creating hydration-enabled renderer.
6538// Hydration logic is only used when calling this function, making it
6539// tree-shakable.
6540function createHydrationRenderer(options) {
6541 return baseCreateRenderer(options, createHydrationFunctions);
6542}
6543// implementation
6544function baseCreateRenderer(options, createHydrationFns) {
6545 const target = getGlobalThis();
6546 target.__VUE__ = true;
6547 {
6548 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
6549 }
6550 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent } = options;
6551 // Note: functions inside this closure should use `const xxx = () => {}`
6552 // style in order to prevent being inlined by minifiers.
6553 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
6554 if (n1 === n2) {
6555 return;
6556 }
6557 // patching & not same type, unmount old tree
6558 if (n1 && !isSameVNodeType(n1, n2)) {
6559 anchor = getNextHostNode(n1);
6560 unmount(n1, parentComponent, parentSuspense, true);
6561 n1 = null;
6562 }
6563 if (n2.patchFlag === -2 /* PatchFlags.BAIL */) {
6564 optimized = false;
6565 n2.dynamicChildren = null;
6566 }
6567 const { type, ref, shapeFlag } = n2;
6568 switch (type) {
6569 case Text:
6570 processText(n1, n2, container, anchor);
6571 break;
6572 case Comment:
6573 processCommentNode(n1, n2, container, anchor);
6574 break;
6575 case Static:
6576 if (n1 == null) {
6577 mountStaticNode(n2, container, anchor, isSVG);
6578 }
6579 else {
6580 patchStaticNode(n1, n2, container, isSVG);
6581 }
6582 break;
6583 case Fragment:
6584 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6585 break;
6586 default:
6587 if (shapeFlag & 1 /* ShapeFlags.ELEMENT */) {
6588 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6589 }
6590 else if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
6591 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6592 }
6593 else if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
6594 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
6595 }
6596 else if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
6597 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
6598 }
6599 else {
6600 warn$1('Invalid VNode type:', type, `(${typeof type})`);
6601 }
6602 }
6603 // set ref
6604 if (ref != null && parentComponent) {
6605 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
6606 }
6607 };
6608 const processText = (n1, n2, container, anchor) => {
6609 if (n1 == null) {
6610 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
6611 }
6612 else {
6613 const el = (n2.el = n1.el);
6614 if (n2.children !== n1.children) {
6615 hostSetText(el, n2.children);
6616 }
6617 }
6618 };
6619 const processCommentNode = (n1, n2, container, anchor) => {
6620 if (n1 == null) {
6621 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
6622 }
6623 else {
6624 // there's no support for dynamic comments
6625 n2.el = n1.el;
6626 }
6627 };
6628 const mountStaticNode = (n2, container, anchor, isSVG) => {
6629 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
6630 };
6631 /**
6632 * Dev / HMR only
6633 */
6634 const patchStaticNode = (n1, n2, container, isSVG) => {
6635 // static nodes are only patched during dev for HMR
6636 if (n2.children !== n1.children) {
6637 const anchor = hostNextSibling(n1.anchor);
6638 // remove existing
6639 removeStaticNode(n1);
6640 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
6641 }
6642 else {
6643 n2.el = n1.el;
6644 n2.anchor = n1.anchor;
6645 }
6646 };
6647 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
6648 let next;
6649 while (el && el !== anchor) {
6650 next = hostNextSibling(el);
6651 hostInsert(el, container, nextSibling);
6652 el = next;
6653 }
6654 hostInsert(anchor, container, nextSibling);
6655 };
6656 const removeStaticNode = ({ el, anchor }) => {
6657 let next;
6658 while (el && el !== anchor) {
6659 next = hostNextSibling(el);
6660 hostRemove(el);
6661 el = next;
6662 }
6663 hostRemove(anchor);
6664 };
6665 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6666 isSVG = isSVG || n2.type === 'svg';
6667 if (n1 == null) {
6668 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6669 }
6670 else {
6671 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6672 }
6673 };
6674 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6675 let el;
6676 let vnodeHook;
6677 const { type, props, shapeFlag, transition, dirs } = vnode;
6678 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
6679 // mount children first, since some props may rely on child content
6680 // being already rendered, e.g. `<select value>`
6681 if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
6682 hostSetElementText(el, vnode.children);
6683 }
6684 else if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
6685 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
6686 }
6687 if (dirs) {
6688 invokeDirectiveHook(vnode, null, parentComponent, 'created');
6689 }
6690 // props
6691 if (props) {
6692 for (const key in props) {
6693 if (key !== 'value' && !isReservedProp(key)) {
6694 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6695 }
6696 }
6697 /**
6698 * Special case for setting value on DOM elements:
6699 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
6700 * - it needs to be forced (#1471)
6701 * #2353 proposes adding another renderer option to configure this, but
6702 * the properties affects are so finite it is worth special casing it
6703 * here to reduce the complexity. (Special casing it also should not
6704 * affect non-DOM renderers)
6705 */
6706 if ('value' in props) {
6707 hostPatchProp(el, 'value', null, props.value);
6708 }
6709 if ((vnodeHook = props.onVnodeBeforeMount)) {
6710 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6711 }
6712 }
6713 // scopeId
6714 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
6715 {
6716 Object.defineProperty(el, '__vnode', {
6717 value: vnode,
6718 enumerable: false
6719 });
6720 Object.defineProperty(el, '__vueParentComponent', {
6721 value: parentComponent,
6722 enumerable: false
6723 });
6724 }
6725 if (dirs) {
6726 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
6727 }
6728 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
6729 // #1689 For inside suspense + suspense resolved case, just call it
6730 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
6731 transition &&
6732 !transition.persisted;
6733 if (needCallTransitionHooks) {
6734 transition.beforeEnter(el);
6735 }
6736 hostInsert(el, container, anchor);
6737 if ((vnodeHook = props && props.onVnodeMounted) ||
6738 needCallTransitionHooks ||
6739 dirs) {
6740 queuePostRenderEffect(() => {
6741 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6742 needCallTransitionHooks && transition.enter(el);
6743 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
6744 }, parentSuspense);
6745 }
6746 };
6747 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6748 if (scopeId) {
6749 hostSetScopeId(el, scopeId);
6750 }
6751 if (slotScopeIds) {
6752 for (let i = 0; i < slotScopeIds.length; i++) {
6753 hostSetScopeId(el, slotScopeIds[i]);
6754 }
6755 }
6756 if (parentComponent) {
6757 let subTree = parentComponent.subTree;
6758 if (subTree.patchFlag > 0 &&
6759 subTree.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */) {
6760 subTree =
6761 filterSingleRoot(subTree.children) || subTree;
6762 }
6763 if (vnode === subTree) {
6764 const parentVNode = parentComponent.vnode;
6765 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6766 }
6767 }
6768 };
6769 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6770 for (let i = start; i < children.length; i++) {
6771 const child = (children[i] = optimized
6772 ? cloneIfMounted(children[i])
6773 : normalizeVNode(children[i]));
6774 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6775 }
6776 };
6777 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6778 const el = (n2.el = n1.el);
6779 let { patchFlag, dynamicChildren, dirs } = n2;
6780 // #1426 take the old vnode's patch flag into account since user may clone a
6781 // compiler-generated vnode, which de-opts to FULL_PROPS
6782 patchFlag |= n1.patchFlag & 16 /* PatchFlags.FULL_PROPS */;
6783 const oldProps = n1.props || EMPTY_OBJ;
6784 const newProps = n2.props || EMPTY_OBJ;
6785 let vnodeHook;
6786 // disable recurse in beforeUpdate hooks
6787 parentComponent && toggleRecurse(parentComponent, false);
6788 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6789 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6790 }
6791 if (dirs) {
6792 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6793 }
6794 parentComponent && toggleRecurse(parentComponent, true);
6795 if (isHmrUpdating) {
6796 // HMR updated, force full diff
6797 patchFlag = 0;
6798 optimized = false;
6799 dynamicChildren = null;
6800 }
6801 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6802 if (dynamicChildren) {
6803 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6804 if (parentComponent && parentComponent.type.__hmrId) {
6805 traverseStaticChildren(n1, n2);
6806 }
6807 }
6808 else if (!optimized) {
6809 // full diff
6810 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6811 }
6812 if (patchFlag > 0) {
6813 // the presence of a patchFlag means this element's render code was
6814 // generated by the compiler and can take the fast path.
6815 // in this path old node and new node are guaranteed to have the same shape
6816 // (i.e. at the exact same position in the source template)
6817 if (patchFlag & 16 /* PatchFlags.FULL_PROPS */) {
6818 // element props contain dynamic keys, full diff needed
6819 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6820 }
6821 else {
6822 // class
6823 // this flag is matched when the element has dynamic class bindings.
6824 if (patchFlag & 2 /* PatchFlags.CLASS */) {
6825 if (oldProps.class !== newProps.class) {
6826 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6827 }
6828 }
6829 // style
6830 // this flag is matched when the element has dynamic style bindings
6831 if (patchFlag & 4 /* PatchFlags.STYLE */) {
6832 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6833 }
6834 // props
6835 // This flag is matched when the element has dynamic prop/attr bindings
6836 // other than class and style. The keys of dynamic prop/attrs are saved for
6837 // faster iteration.
6838 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6839 // bail out and go through a full diff because we need to unset the old key
6840 if (patchFlag & 8 /* PatchFlags.PROPS */) {
6841 // if the flag is present then dynamicProps must be non-null
6842 const propsToUpdate = n2.dynamicProps;
6843 for (let i = 0; i < propsToUpdate.length; i++) {
6844 const key = propsToUpdate[i];
6845 const prev = oldProps[key];
6846 const next = newProps[key];
6847 // #1471 force patch value
6848 if (next !== prev || key === 'value') {
6849 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6850 }
6851 }
6852 }
6853 }
6854 // text
6855 // This flag is matched when the element has only dynamic text children.
6856 if (patchFlag & 1 /* PatchFlags.TEXT */) {
6857 if (n1.children !== n2.children) {
6858 hostSetElementText(el, n2.children);
6859 }
6860 }
6861 }
6862 else if (!optimized && dynamicChildren == null) {
6863 // unoptimized, full diff
6864 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6865 }
6866 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6867 queuePostRenderEffect(() => {
6868 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6869 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6870 }, parentSuspense);
6871 }
6872 };
6873 // The fast path for blocks.
6874 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6875 for (let i = 0; i < newChildren.length; i++) {
6876 const oldVNode = oldChildren[i];
6877 const newVNode = newChildren[i];
6878 // Determine the container (parent element) for the patch.
6879 const container =
6880 // oldVNode may be an errored async setup() component inside Suspense
6881 // which will not have a mounted element
6882 oldVNode.el &&
6883 // - In the case of a Fragment, we need to provide the actual parent
6884 // of the Fragment itself so it can move its children.
6885 (oldVNode.type === Fragment ||
6886 // - In the case of different nodes, there is going to be a replacement
6887 // which also requires the correct parent container
6888 !isSameVNodeType(oldVNode, newVNode) ||
6889 // - In the case of a component, it could contain anything.
6890 oldVNode.shapeFlag & (6 /* ShapeFlags.COMPONENT */ | 64 /* ShapeFlags.TELEPORT */))
6891 ? hostParentNode(oldVNode.el)
6892 : // In other cases, the parent container is not actually used so we
6893 // just pass the block element here to avoid a DOM parentNode call.
6894 fallbackContainer;
6895 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6896 }
6897 };
6898 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6899 if (oldProps !== newProps) {
6900 if (oldProps !== EMPTY_OBJ) {
6901 for (const key in oldProps) {
6902 if (!isReservedProp(key) && !(key in newProps)) {
6903 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6904 }
6905 }
6906 }
6907 for (const key in newProps) {
6908 // empty string is not valid prop
6909 if (isReservedProp(key))
6910 continue;
6911 const next = newProps[key];
6912 const prev = oldProps[key];
6913 // defer patching value
6914 if (next !== prev && key !== 'value') {
6915 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6916 }
6917 }
6918 if ('value' in newProps) {
6919 hostPatchProp(el, 'value', oldProps.value, newProps.value);
6920 }
6921 }
6922 };
6923 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6924 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6925 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6926 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6927 if (// #5523 dev root fragment may inherit directives
6928 (isHmrUpdating || patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */)) {
6929 // HMR updated / Dev root fragment (w/ comments), force full diff
6930 patchFlag = 0;
6931 optimized = false;
6932 dynamicChildren = null;
6933 }
6934 // check if this is a slot fragment with :slotted scope ids
6935 if (fragmentSlotScopeIds) {
6936 slotScopeIds = slotScopeIds
6937 ? slotScopeIds.concat(fragmentSlotScopeIds)
6938 : fragmentSlotScopeIds;
6939 }
6940 if (n1 == null) {
6941 hostInsert(fragmentStartAnchor, container, anchor);
6942 hostInsert(fragmentEndAnchor, container, anchor);
6943 // a fragment can only have array children
6944 // since they are either generated by the compiler, or implicitly created
6945 // from arrays.
6946 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6947 }
6948 else {
6949 if (patchFlag > 0 &&
6950 patchFlag & 64 /* PatchFlags.STABLE_FRAGMENT */ &&
6951 dynamicChildren &&
6952 // #2715 the previous fragment could've been a BAILed one as a result
6953 // of renderSlot() with no valid children
6954 n1.dynamicChildren) {
6955 // a stable fragment (template root or <template v-for>) doesn't need to
6956 // patch children order, but it may contain dynamicChildren.
6957 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6958 if (parentComponent && parentComponent.type.__hmrId) {
6959 traverseStaticChildren(n1, n2);
6960 }
6961 else if (
6962 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6963 // get moved around. Make sure all root level vnodes inherit el.
6964 // #2134 or if it's a component root, it may also get moved around
6965 // as the component is being moved.
6966 n2.key != null ||
6967 (parentComponent && n2 === parentComponent.subTree)) {
6968 traverseStaticChildren(n1, n2, true /* shallow */);
6969 }
6970 }
6971 else {
6972 // keyed / unkeyed, or manual fragments.
6973 // for keyed & unkeyed, since they are compiler generated from v-for,
6974 // each child is guaranteed to be a block so the fragment will never
6975 // have dynamicChildren.
6976 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6977 }
6978 }
6979 };
6980 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6981 n2.slotScopeIds = slotScopeIds;
6982 if (n1 == null) {
6983 if (n2.shapeFlag & 512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */) {
6984 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6985 }
6986 else {
6987 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6988 }
6989 }
6990 else {
6991 updateComponent(n1, n2, optimized);
6992 }
6993 };
6994 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6995 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6996 if (instance.type.__hmrId) {
6997 registerHMR(instance);
6998 }
6999 {
7000 pushWarningContext(initialVNode);
7001 startMeasure(instance, `mount`);
7002 }
7003 // inject renderer internals for keepAlive
7004 if (isKeepAlive(initialVNode)) {
7005 instance.ctx.renderer = internals;
7006 }
7007 // resolve props and slots for setup context
7008 {
7009 {
7010 startMeasure(instance, `init`);
7011 }
7012 setupComponent(instance);
7013 {
7014 endMeasure(instance, `init`);
7015 }
7016 }
7017 // setup() is async. This component relies on async logic to be resolved
7018 // before proceeding
7019 if (instance.asyncDep) {
7020 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
7021 // Give it a placeholder if this is not hydration
7022 // TODO handle self-defined fallback
7023 if (!initialVNode.el) {
7024 const placeholder = (instance.subTree = createVNode(Comment));
7025 processCommentNode(null, placeholder, container, anchor);
7026 }
7027 return;
7028 }
7029 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
7030 {
7031 popWarningContext();
7032 endMeasure(instance, `mount`);
7033 }
7034 };
7035 const updateComponent = (n1, n2, optimized) => {
7036 const instance = (n2.component = n1.component);
7037 if (shouldUpdateComponent(n1, n2, optimized)) {
7038 if (instance.asyncDep &&
7039 !instance.asyncResolved) {
7040 // async & still pending - just update props and slots
7041 // since the component's reactive effect for render isn't set-up yet
7042 {
7043 pushWarningContext(n2);
7044 }
7045 updateComponentPreRender(instance, n2, optimized);
7046 {
7047 popWarningContext();
7048 }
7049 return;
7050 }
7051 else {
7052 // normal update
7053 instance.next = n2;
7054 // in case the child component is also queued, remove it to avoid
7055 // double updating the same child component in the same flush.
7056 invalidateJob(instance.update);
7057 // instance.update is the reactive effect.
7058 instance.update();
7059 }
7060 }
7061 else {
7062 // no update needed. just copy over properties
7063 n2.el = n1.el;
7064 instance.vnode = n2;
7065 }
7066 };
7067 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
7068 const componentUpdateFn = () => {
7069 if (!instance.isMounted) {
7070 let vnodeHook;
7071 const { el, props } = initialVNode;
7072 const { bm, m, parent } = instance;
7073 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
7074 toggleRecurse(instance, false);
7075 // beforeMount hook
7076 if (bm) {
7077 invokeArrayFns(bm);
7078 }
7079 // onVnodeBeforeMount
7080 if (!isAsyncWrapperVNode &&
7081 (vnodeHook = props && props.onVnodeBeforeMount)) {
7082 invokeVNodeHook(vnodeHook, parent, initialVNode);
7083 }
7084 toggleRecurse(instance, true);
7085 if (el && hydrateNode) {
7086 // vnode has adopted host node - perform hydration instead of mount.
7087 const hydrateSubTree = () => {
7088 {
7089 startMeasure(instance, `render`);
7090 }
7091 instance.subTree = renderComponentRoot(instance);
7092 {
7093 endMeasure(instance, `render`);
7094 }
7095 {
7096 startMeasure(instance, `hydrate`);
7097 }
7098 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
7099 {
7100 endMeasure(instance, `hydrate`);
7101 }
7102 };
7103 if (isAsyncWrapperVNode) {
7104 initialVNode.type.__asyncLoader().then(
7105 // note: we are moving the render call into an async callback,
7106 // which means it won't track dependencies - but it's ok because
7107 // a server-rendered async wrapper is already in resolved state
7108 // and it will never need to change.
7109 () => !instance.isUnmounted && hydrateSubTree());
7110 }
7111 else {
7112 hydrateSubTree();
7113 }
7114 }
7115 else {
7116 {
7117 startMeasure(instance, `render`);
7118 }
7119 const subTree = (instance.subTree = renderComponentRoot(instance));
7120 {
7121 endMeasure(instance, `render`);
7122 }
7123 {
7124 startMeasure(instance, `patch`);
7125 }
7126 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
7127 {
7128 endMeasure(instance, `patch`);
7129 }
7130 initialVNode.el = subTree.el;
7131 }
7132 // mounted hook
7133 if (m) {
7134 queuePostRenderEffect(m, parentSuspense);
7135 }
7136 // onVnodeMounted
7137 if (!isAsyncWrapperVNode &&
7138 (vnodeHook = props && props.onVnodeMounted)) {
7139 const scopedInitialVNode = initialVNode;
7140 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
7141 }
7142 // activated hook for keep-alive roots.
7143 // #1742 activated hook must be accessed after first render
7144 // since the hook may be injected by a child keep-alive
7145 if (initialVNode.shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */ ||
7146 (parent &&
7147 isAsyncWrapper(parent.vnode) &&
7148 parent.vnode.shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */)) {
7149 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
7150 }
7151 instance.isMounted = true;
7152 {
7153 devtoolsComponentAdded(instance);
7154 }
7155 // #2458: deference mount-only object parameters to prevent memleaks
7156 initialVNode = container = anchor = null;
7157 }
7158 else {
7159 // updateComponent
7160 // This is triggered by mutation of component's own state (next: null)
7161 // OR parent calling processComponent (next: VNode)
7162 let { next, bu, u, parent, vnode } = instance;
7163 let originNext = next;
7164 let vnodeHook;
7165 {
7166 pushWarningContext(next || instance.vnode);
7167 }
7168 // Disallow component effect recursion during pre-lifecycle hooks.
7169 toggleRecurse(instance, false);
7170 if (next) {
7171 next.el = vnode.el;
7172 updateComponentPreRender(instance, next, optimized);
7173 }
7174 else {
7175 next = vnode;
7176 }
7177 // beforeUpdate hook
7178 if (bu) {
7179 invokeArrayFns(bu);
7180 }
7181 // onVnodeBeforeUpdate
7182 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
7183 invokeVNodeHook(vnodeHook, parent, next, vnode);
7184 }
7185 toggleRecurse(instance, true);
7186 // render
7187 {
7188 startMeasure(instance, `render`);
7189 }
7190 const nextTree = renderComponentRoot(instance);
7191 {
7192 endMeasure(instance, `render`);
7193 }
7194 const prevTree = instance.subTree;
7195 instance.subTree = nextTree;
7196 {
7197 startMeasure(instance, `patch`);
7198 }
7199 patch(prevTree, nextTree,
7200 // parent may have changed if it's in a teleport
7201 hostParentNode(prevTree.el),
7202 // anchor may have changed if it's in a fragment
7203 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
7204 {
7205 endMeasure(instance, `patch`);
7206 }
7207 next.el = nextTree.el;
7208 if (originNext === null) {
7209 // self-triggered update. In case of HOC, update parent component
7210 // vnode el. HOC is indicated by parent instance's subTree pointing
7211 // to child component's vnode
7212 updateHOCHostEl(instance, nextTree.el);
7213 }
7214 // updated hook
7215 if (u) {
7216 queuePostRenderEffect(u, parentSuspense);
7217 }
7218 // onVnodeUpdated
7219 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
7220 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
7221 }
7222 {
7223 devtoolsComponentUpdated(instance);
7224 }
7225 {
7226 popWarningContext();
7227 }
7228 }
7229 };
7230 // create reactive effect for rendering
7231 const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(update), instance.scope // track it in component's effect scope
7232 ));
7233 const update = (instance.update = () => effect.run());
7234 update.id = instance.uid;
7235 // allowRecurse
7236 // #1801, #2043 component render effects should allow recursive updates
7237 toggleRecurse(instance, true);
7238 {
7239 effect.onTrack = instance.rtc
7240 ? e => invokeArrayFns(instance.rtc, e)
7241 : void 0;
7242 effect.onTrigger = instance.rtg
7243 ? e => invokeArrayFns(instance.rtg, e)
7244 : void 0;
7245 update.ownerInstance = instance;
7246 }
7247 update();
7248 };
7249 const updateComponentPreRender = (instance, nextVNode, optimized) => {
7250 nextVNode.component = instance;
7251 const prevProps = instance.vnode.props;
7252 instance.vnode = nextVNode;
7253 instance.next = null;
7254 updateProps(instance, nextVNode.props, prevProps, optimized);
7255 updateSlots(instance, nextVNode.children, optimized);
7256 pauseTracking();
7257 // props update may have triggered pre-flush watchers.
7258 // flush them before the render update.
7259 flushPreFlushCbs();
7260 resetTracking();
7261 };
7262 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
7263 const c1 = n1 && n1.children;
7264 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
7265 const c2 = n2.children;
7266 const { patchFlag, shapeFlag } = n2;
7267 // fast path
7268 if (patchFlag > 0) {
7269 if (patchFlag & 128 /* PatchFlags.KEYED_FRAGMENT */) {
7270 // this could be either fully-keyed or mixed (some keyed some not)
7271 // presence of patchFlag means children are guaranteed to be arrays
7272 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7273 return;
7274 }
7275 else if (patchFlag & 256 /* PatchFlags.UNKEYED_FRAGMENT */) {
7276 // unkeyed
7277 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7278 return;
7279 }
7280 }
7281 // children has 3 possibilities: text, array or no children.
7282 if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
7283 // text children fast path
7284 if (prevShapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
7285 unmountChildren(c1, parentComponent, parentSuspense);
7286 }
7287 if (c2 !== c1) {
7288 hostSetElementText(container, c2);
7289 }
7290 }
7291 else {
7292 if (prevShapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
7293 // prev children was array
7294 if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
7295 // two arrays, cannot assume anything, do full diff
7296 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7297 }
7298 else {
7299 // no new children, just unmount old
7300 unmountChildren(c1, parentComponent, parentSuspense, true);
7301 }
7302 }
7303 else {
7304 // prev children was text OR null
7305 // new children is array OR null
7306 if (prevShapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
7307 hostSetElementText(container, '');
7308 }
7309 // mount new if array
7310 if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
7311 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7312 }
7313 }
7314 }
7315 };
7316 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
7317 c1 = c1 || EMPTY_ARR;
7318 c2 = c2 || EMPTY_ARR;
7319 const oldLength = c1.length;
7320 const newLength = c2.length;
7321 const commonLength = Math.min(oldLength, newLength);
7322 let i;
7323 for (i = 0; i < commonLength; i++) {
7324 const nextChild = (c2[i] = optimized
7325 ? cloneIfMounted(c2[i])
7326 : normalizeVNode(c2[i]));
7327 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7328 }
7329 if (oldLength > newLength) {
7330 // remove old
7331 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
7332 }
7333 else {
7334 // mount new
7335 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
7336 }
7337 };
7338 // can be all-keyed or mixed
7339 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
7340 let i = 0;
7341 const l2 = c2.length;
7342 let e1 = c1.length - 1; // prev ending index
7343 let e2 = l2 - 1; // next ending index
7344 // 1. sync from start
7345 // (a b) c
7346 // (a b) d e
7347 while (i <= e1 && i <= e2) {
7348 const n1 = c1[i];
7349 const n2 = (c2[i] = optimized
7350 ? cloneIfMounted(c2[i])
7351 : normalizeVNode(c2[i]));
7352 if (isSameVNodeType(n1, n2)) {
7353 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7354 }
7355 else {
7356 break;
7357 }
7358 i++;
7359 }
7360 // 2. sync from end
7361 // a (b c)
7362 // d e (b c)
7363 while (i <= e1 && i <= e2) {
7364 const n1 = c1[e1];
7365 const n2 = (c2[e2] = optimized
7366 ? cloneIfMounted(c2[e2])
7367 : normalizeVNode(c2[e2]));
7368 if (isSameVNodeType(n1, n2)) {
7369 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7370 }
7371 else {
7372 break;
7373 }
7374 e1--;
7375 e2--;
7376 }
7377 // 3. common sequence + mount
7378 // (a b)
7379 // (a b) c
7380 // i = 2, e1 = 1, e2 = 2
7381 // (a b)
7382 // c (a b)
7383 // i = 0, e1 = -1, e2 = 0
7384 if (i > e1) {
7385 if (i <= e2) {
7386 const nextPos = e2 + 1;
7387 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
7388 while (i <= e2) {
7389 patch(null, (c2[i] = optimized
7390 ? cloneIfMounted(c2[i])
7391 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7392 i++;
7393 }
7394 }
7395 }
7396 // 4. common sequence + unmount
7397 // (a b) c
7398 // (a b)
7399 // i = 2, e1 = 2, e2 = 1
7400 // a (b c)
7401 // (b c)
7402 // i = 0, e1 = 0, e2 = -1
7403 else if (i > e2) {
7404 while (i <= e1) {
7405 unmount(c1[i], parentComponent, parentSuspense, true);
7406 i++;
7407 }
7408 }
7409 // 5. unknown sequence
7410 // [i ... e1 + 1]: a b [c d e] f g
7411 // [i ... e2 + 1]: a b [e d c h] f g
7412 // i = 2, e1 = 4, e2 = 5
7413 else {
7414 const s1 = i; // prev starting index
7415 const s2 = i; // next starting index
7416 // 5.1 build key:index map for newChildren
7417 const keyToNewIndexMap = new Map();
7418 for (i = s2; i <= e2; i++) {
7419 const nextChild = (c2[i] = optimized
7420 ? cloneIfMounted(c2[i])
7421 : normalizeVNode(c2[i]));
7422 if (nextChild.key != null) {
7423 if (keyToNewIndexMap.has(nextChild.key)) {
7424 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
7425 }
7426 keyToNewIndexMap.set(nextChild.key, i);
7427 }
7428 }
7429 // 5.2 loop through old children left to be patched and try to patch
7430 // matching nodes & remove nodes that are no longer present
7431 let j;
7432 let patched = 0;
7433 const toBePatched = e2 - s2 + 1;
7434 let moved = false;
7435 // used to track whether any node has moved
7436 let maxNewIndexSoFar = 0;
7437 // works as Map<newIndex, oldIndex>
7438 // Note that oldIndex is offset by +1
7439 // and oldIndex = 0 is a special value indicating the new node has
7440 // no corresponding old node.
7441 // used for determining longest stable subsequence
7442 const newIndexToOldIndexMap = new Array(toBePatched);
7443 for (i = 0; i < toBePatched; i++)
7444 newIndexToOldIndexMap[i] = 0;
7445 for (i = s1; i <= e1; i++) {
7446 const prevChild = c1[i];
7447 if (patched >= toBePatched) {
7448 // all new children have been patched so this can only be a removal
7449 unmount(prevChild, parentComponent, parentSuspense, true);
7450 continue;
7451 }
7452 let newIndex;
7453 if (prevChild.key != null) {
7454 newIndex = keyToNewIndexMap.get(prevChild.key);
7455 }
7456 else {
7457 // key-less node, try to locate a key-less node of the same type
7458 for (j = s2; j <= e2; j++) {
7459 if (newIndexToOldIndexMap[j - s2] === 0 &&
7460 isSameVNodeType(prevChild, c2[j])) {
7461 newIndex = j;
7462 break;
7463 }
7464 }
7465 }
7466 if (newIndex === undefined) {
7467 unmount(prevChild, parentComponent, parentSuspense, true);
7468 }
7469 else {
7470 newIndexToOldIndexMap[newIndex - s2] = i + 1;
7471 if (newIndex >= maxNewIndexSoFar) {
7472 maxNewIndexSoFar = newIndex;
7473 }
7474 else {
7475 moved = true;
7476 }
7477 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7478 patched++;
7479 }
7480 }
7481 // 5.3 move and mount
7482 // generate longest stable subsequence only when nodes have moved
7483 const increasingNewIndexSequence = moved
7484 ? getSequence(newIndexToOldIndexMap)
7485 : EMPTY_ARR;
7486 j = increasingNewIndexSequence.length - 1;
7487 // looping backwards so that we can use last patched node as anchor
7488 for (i = toBePatched - 1; i >= 0; i--) {
7489 const nextIndex = s2 + i;
7490 const nextChild = c2[nextIndex];
7491 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
7492 if (newIndexToOldIndexMap[i] === 0) {
7493 // mount new
7494 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7495 }
7496 else if (moved) {
7497 // move if:
7498 // There is no stable subsequence (e.g. a reverse)
7499 // OR current node is not among the stable sequence
7500 if (j < 0 || i !== increasingNewIndexSequence[j]) {
7501 move(nextChild, container, anchor, 2 /* MoveType.REORDER */);
7502 }
7503 else {
7504 j--;
7505 }
7506 }
7507 }
7508 }
7509 };
7510 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
7511 const { el, type, transition, children, shapeFlag } = vnode;
7512 if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
7513 move(vnode.component.subTree, container, anchor, moveType);
7514 return;
7515 }
7516 if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
7517 vnode.suspense.move(container, anchor, moveType);
7518 return;
7519 }
7520 if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
7521 type.move(vnode, container, anchor, internals);
7522 return;
7523 }
7524 if (type === Fragment) {
7525 hostInsert(el, container, anchor);
7526 for (let i = 0; i < children.length; i++) {
7527 move(children[i], container, anchor, moveType);
7528 }
7529 hostInsert(vnode.anchor, container, anchor);
7530 return;
7531 }
7532 if (type === Static) {
7533 moveStaticNode(vnode, container, anchor);
7534 return;
7535 }
7536 // single nodes
7537 const needTransition = moveType !== 2 /* MoveType.REORDER */ &&
7538 shapeFlag & 1 /* ShapeFlags.ELEMENT */ &&
7539 transition;
7540 if (needTransition) {
7541 if (moveType === 0 /* MoveType.ENTER */) {
7542 transition.beforeEnter(el);
7543 hostInsert(el, container, anchor);
7544 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
7545 }
7546 else {
7547 const { leave, delayLeave, afterLeave } = transition;
7548 const remove = () => hostInsert(el, container, anchor);
7549 const performLeave = () => {
7550 leave(el, () => {
7551 remove();
7552 afterLeave && afterLeave();
7553 });
7554 };
7555 if (delayLeave) {
7556 delayLeave(el, remove, performLeave);
7557 }
7558 else {
7559 performLeave();
7560 }
7561 }
7562 }
7563 else {
7564 hostInsert(el, container, anchor);
7565 }
7566 };
7567 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
7568 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
7569 // unset ref
7570 if (ref != null) {
7571 setRef(ref, null, parentSuspense, vnode, true);
7572 }
7573 if (shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */) {
7574 parentComponent.ctx.deactivate(vnode);
7575 return;
7576 }
7577 const shouldInvokeDirs = shapeFlag & 1 /* ShapeFlags.ELEMENT */ && dirs;
7578 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
7579 let vnodeHook;
7580 if (shouldInvokeVnodeHook &&
7581 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
7582 invokeVNodeHook(vnodeHook, parentComponent, vnode);
7583 }
7584 if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
7585 unmountComponent(vnode.component, parentSuspense, doRemove);
7586 }
7587 else {
7588 if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
7589 vnode.suspense.unmount(parentSuspense, doRemove);
7590 return;
7591 }
7592 if (shouldInvokeDirs) {
7593 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
7594 }
7595 if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
7596 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
7597 }
7598 else if (dynamicChildren &&
7599 // #1153: fast path should not be taken for non-stable (v-for) fragments
7600 (type !== Fragment ||
7601 (patchFlag > 0 && patchFlag & 64 /* PatchFlags.STABLE_FRAGMENT */))) {
7602 // fast path for block nodes: only need to unmount dynamic children.
7603 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
7604 }
7605 else if ((type === Fragment &&
7606 patchFlag &
7607 (128 /* PatchFlags.KEYED_FRAGMENT */ | 256 /* PatchFlags.UNKEYED_FRAGMENT */)) ||
7608 (!optimized && shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */)) {
7609 unmountChildren(children, parentComponent, parentSuspense);
7610 }
7611 if (doRemove) {
7612 remove(vnode);
7613 }
7614 }
7615 if ((shouldInvokeVnodeHook &&
7616 (vnodeHook = props && props.onVnodeUnmounted)) ||
7617 shouldInvokeDirs) {
7618 queuePostRenderEffect(() => {
7619 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
7620 shouldInvokeDirs &&
7621 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
7622 }, parentSuspense);
7623 }
7624 };
7625 const remove = vnode => {
7626 const { type, el, anchor, transition } = vnode;
7627 if (type === Fragment) {
7628 if (vnode.patchFlag > 0 &&
7629 vnode.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */ &&
7630 transition &&
7631 !transition.persisted) {
7632 vnode.children.forEach(child => {
7633 if (child.type === Comment) {
7634 hostRemove(child.el);
7635 }
7636 else {
7637 remove(child);
7638 }
7639 });
7640 }
7641 else {
7642 removeFragment(el, anchor);
7643 }
7644 return;
7645 }
7646 if (type === Static) {
7647 removeStaticNode(vnode);
7648 return;
7649 }
7650 const performRemove = () => {
7651 hostRemove(el);
7652 if (transition && !transition.persisted && transition.afterLeave) {
7653 transition.afterLeave();
7654 }
7655 };
7656 if (vnode.shapeFlag & 1 /* ShapeFlags.ELEMENT */ &&
7657 transition &&
7658 !transition.persisted) {
7659 const { leave, delayLeave } = transition;
7660 const performLeave = () => leave(el, performRemove);
7661 if (delayLeave) {
7662 delayLeave(vnode.el, performRemove, performLeave);
7663 }
7664 else {
7665 performLeave();
7666 }
7667 }
7668 else {
7669 performRemove();
7670 }
7671 };
7672 const removeFragment = (cur, end) => {
7673 // For fragments, directly remove all contained DOM nodes.
7674 // (fragment child nodes cannot have transition)
7675 let next;
7676 while (cur !== end) {
7677 next = hostNextSibling(cur);
7678 hostRemove(cur);
7679 cur = next;
7680 }
7681 hostRemove(end);
7682 };
7683 const unmountComponent = (instance, parentSuspense, doRemove) => {
7684 if (instance.type.__hmrId) {
7685 unregisterHMR(instance);
7686 }
7687 const { bum, scope, update, subTree, um } = instance;
7688 // beforeUnmount hook
7689 if (bum) {
7690 invokeArrayFns(bum);
7691 }
7692 // stop effects in component scope
7693 scope.stop();
7694 // update may be null if a component is unmounted before its async
7695 // setup has resolved.
7696 if (update) {
7697 // so that scheduler will no longer invoke it
7698 update.active = false;
7699 unmount(subTree, instance, parentSuspense, doRemove);
7700 }
7701 // unmounted hook
7702 if (um) {
7703 queuePostRenderEffect(um, parentSuspense);
7704 }
7705 queuePostRenderEffect(() => {
7706 instance.isUnmounted = true;
7707 }, parentSuspense);
7708 // A component with async dep inside a pending suspense is unmounted before
7709 // its async dep resolves. This should remove the dep from the suspense, and
7710 // cause the suspense to resolve immediately if that was the last dep.
7711 if (parentSuspense &&
7712 parentSuspense.pendingBranch &&
7713 !parentSuspense.isUnmounted &&
7714 instance.asyncDep &&
7715 !instance.asyncResolved &&
7716 instance.suspenseId === parentSuspense.pendingId) {
7717 parentSuspense.deps--;
7718 if (parentSuspense.deps === 0) {
7719 parentSuspense.resolve();
7720 }
7721 }
7722 {
7723 devtoolsComponentRemoved(instance);
7724 }
7725 };
7726 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
7727 for (let i = start; i < children.length; i++) {
7728 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
7729 }
7730 };
7731 const getNextHostNode = vnode => {
7732 if (vnode.shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
7733 return getNextHostNode(vnode.component.subTree);
7734 }
7735 if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
7736 return vnode.suspense.next();
7737 }
7738 return hostNextSibling((vnode.anchor || vnode.el));
7739 };
7740 const render = (vnode, container, isSVG) => {
7741 if (vnode == null) {
7742 if (container._vnode) {
7743 unmount(container._vnode, null, null, true);
7744 }
7745 }
7746 else {
7747 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
7748 }
7749 flushPreFlushCbs();
7750 flushPostFlushCbs();
7751 container._vnode = vnode;
7752 };
7753 const internals = {
7754 p: patch,
7755 um: unmount,
7756 m: move,
7757 r: remove,
7758 mt: mountComponent,
7759 mc: mountChildren,
7760 pc: patchChildren,
7761 pbc: patchBlockChildren,
7762 n: getNextHostNode,
7763 o: options
7764 };
7765 let hydrate;
7766 let hydrateNode;
7767 if (createHydrationFns) {
7768 [hydrate, hydrateNode] = createHydrationFns(internals);
7769 }
7770 return {
7771 render,
7772 hydrate,
7773 createApp: createAppAPI(render, hydrate)
7774 };
7775}
7776function toggleRecurse({ effect, update }, allowed) {
7777 effect.allowRecurse = update.allowRecurse = allowed;
7778}
7779/**
7780 * #1156
7781 * When a component is HMR-enabled, we need to make sure that all static nodes
7782 * inside a block also inherit the DOM element from the previous tree so that
7783 * HMR updates (which are full updates) can retrieve the element for patching.
7784 *
7785 * #2080
7786 * Inside keyed `template` fragment static children, if a fragment is moved,
7787 * the children will always be moved. Therefore, in order to ensure correct move
7788 * position, el should be inherited from previous nodes.
7789 */
7790function traverseStaticChildren(n1, n2, shallow = false) {
7791 const ch1 = n1.children;
7792 const ch2 = n2.children;
7793 if (isArray(ch1) && isArray(ch2)) {
7794 for (let i = 0; i < ch1.length; i++) {
7795 // this is only called in the optimized path so array children are
7796 // guaranteed to be vnodes
7797 const c1 = ch1[i];
7798 let c2 = ch2[i];
7799 if (c2.shapeFlag & 1 /* ShapeFlags.ELEMENT */ && !c2.dynamicChildren) {
7800 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) {
7801 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7802 c2.el = c1.el;
7803 }
7804 if (!shallow)
7805 traverseStaticChildren(c1, c2);
7806 }
7807 // #6852 also inherit for text nodes
7808 if (c2.type === Text) {
7809 c2.el = c1.el;
7810 }
7811 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7812 // would have received .el during block patch)
7813 if (c2.type === Comment && !c2.el) {
7814 c2.el = c1.el;
7815 }
7816 }
7817 }
7818}
7819// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7820function getSequence(arr) {
7821 const p = arr.slice();
7822 const result = [0];
7823 let i, j, u, v, c;
7824 const len = arr.length;
7825 for (i = 0; i < len; i++) {
7826 const arrI = arr[i];
7827 if (arrI !== 0) {
7828 j = result[result.length - 1];
7829 if (arr[j] < arrI) {
7830 p[i] = j;
7831 result.push(i);
7832 continue;
7833 }
7834 u = 0;
7835 v = result.length - 1;
7836 while (u < v) {
7837 c = (u + v) >> 1;
7838 if (arr[result[c]] < arrI) {
7839 u = c + 1;
7840 }
7841 else {
7842 v = c;
7843 }
7844 }
7845 if (arrI < arr[result[u]]) {
7846 if (u > 0) {
7847 p[i] = result[u - 1];
7848 }
7849 result[u] = i;
7850 }
7851 }
7852 }
7853 u = result.length;
7854 v = result[u - 1];
7855 while (u-- > 0) {
7856 result[u] = v;
7857 v = p[v];
7858 }
7859 return result;
7860}
7861
7862const isTeleport = (type) => type.__isTeleport;
7863const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7864const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7865const resolveTarget = (props, select) => {
7866 const targetSelector = props && props.to;
7867 if (isString(targetSelector)) {
7868 if (!select) {
7869 warn$1(`Current renderer does not support string target for Teleports. ` +
7870 `(missing querySelector renderer option)`);
7871 return null;
7872 }
7873 else {
7874 const target = select(targetSelector);
7875 if (!target) {
7876 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7877 `Note the target element must exist before the component is mounted - ` +
7878 `i.e. the target cannot be rendered by the component itself, and ` +
7879 `ideally should be outside of the entire Vue component tree.`);
7880 }
7881 return target;
7882 }
7883 }
7884 else {
7885 if (!targetSelector && !isTeleportDisabled(props)) {
7886 warn$1(`Invalid Teleport target: ${targetSelector}`);
7887 }
7888 return targetSelector;
7889 }
7890};
7891const TeleportImpl = {
7892 __isTeleport: true,
7893 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7894 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7895 const disabled = isTeleportDisabled(n2.props);
7896 let { shapeFlag, children, dynamicChildren } = n2;
7897 // #3302
7898 // HMR updated, force full diff
7899 if (isHmrUpdating) {
7900 optimized = false;
7901 dynamicChildren = null;
7902 }
7903 if (n1 == null) {
7904 // insert anchors in the main view
7905 const placeholder = (n2.el = createComment('teleport start')
7906 );
7907 const mainAnchor = (n2.anchor = createComment('teleport end')
7908 );
7909 insert(placeholder, container, anchor);
7910 insert(mainAnchor, container, anchor);
7911 const target = (n2.target = resolveTarget(n2.props, querySelector));
7912 const targetAnchor = (n2.targetAnchor = createText(''));
7913 if (target) {
7914 insert(targetAnchor, target);
7915 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7916 isSVG = isSVG || isTargetSVG(target);
7917 }
7918 else if (!disabled) {
7919 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
7920 }
7921 const mount = (container, anchor) => {
7922 // Teleport *always* has Array children. This is enforced in both the
7923 // compiler and vnode children normalization.
7924 if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
7925 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7926 }
7927 };
7928 if (disabled) {
7929 mount(container, mainAnchor);
7930 }
7931 else if (target) {
7932 mount(target, targetAnchor);
7933 }
7934 }
7935 else {
7936 // update content
7937 n2.el = n1.el;
7938 const mainAnchor = (n2.anchor = n1.anchor);
7939 const target = (n2.target = n1.target);
7940 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7941 const wasDisabled = isTeleportDisabled(n1.props);
7942 const currentContainer = wasDisabled ? container : target;
7943 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7944 isSVG = isSVG || isTargetSVG(target);
7945 if (dynamicChildren) {
7946 // fast path when the teleport happens to be a block root
7947 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7948 // even in block tree mode we need to make sure all root-level nodes
7949 // in the teleport inherit previous DOM references so that they can
7950 // be moved in future patches.
7951 traverseStaticChildren(n1, n2, true);
7952 }
7953 else if (!optimized) {
7954 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7955 }
7956 if (disabled) {
7957 if (!wasDisabled) {
7958 // enabled -> disabled
7959 // move into main container
7960 moveTeleport(n2, container, mainAnchor, internals, 1 /* TeleportMoveTypes.TOGGLE */);
7961 }
7962 }
7963 else {
7964 // target changed
7965 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7966 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7967 if (nextTarget) {
7968 moveTeleport(n2, nextTarget, null, internals, 0 /* TeleportMoveTypes.TARGET_CHANGE */);
7969 }
7970 else {
7971 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
7972 }
7973 }
7974 else if (wasDisabled) {
7975 // disabled -> enabled
7976 // move into teleport target
7977 moveTeleport(n2, target, targetAnchor, internals, 1 /* TeleportMoveTypes.TOGGLE */);
7978 }
7979 }
7980 }
7981 updateCssVars(n2);
7982 },
7983 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7984 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7985 if (target) {
7986 hostRemove(targetAnchor);
7987 }
7988 // an unmounted teleport should always remove its children if not disabled
7989 if (doRemove || !isTeleportDisabled(props)) {
7990 hostRemove(anchor);
7991 if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
7992 for (let i = 0; i < children.length; i++) {
7993 const child = children[i];
7994 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7995 }
7996 }
7997 }
7998 },
7999 move: moveTeleport,
8000 hydrate: hydrateTeleport
8001};
8002function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* TeleportMoveTypes.REORDER */) {
8003 // move target anchor if this is a target change.
8004 if (moveType === 0 /* TeleportMoveTypes.TARGET_CHANGE */) {
8005 insert(vnode.targetAnchor, container, parentAnchor);
8006 }
8007 const { el, anchor, shapeFlag, children, props } = vnode;
8008 const isReorder = moveType === 2 /* TeleportMoveTypes.REORDER */;
8009 // move main view anchor if this is a re-order.
8010 if (isReorder) {
8011 insert(el, container, parentAnchor);
8012 }
8013 // if this is a re-order and teleport is enabled (content is in target)
8014 // do not move children. So the opposite is: only move children if this
8015 // is not a reorder, or the teleport is disabled
8016 if (!isReorder || isTeleportDisabled(props)) {
8017 // Teleport has either Array children or no children.
8018 if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
8019 for (let i = 0; i < children.length; i++) {
8020 move(children[i], container, parentAnchor, 2 /* MoveType.REORDER */);
8021 }
8022 }
8023 }
8024 // move main view anchor if this is a re-order.
8025 if (isReorder) {
8026 insert(anchor, container, parentAnchor);
8027 }
8028}
8029function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
8030 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
8031 if (target) {
8032 // if multiple teleports rendered to the same target element, we need to
8033 // pick up from where the last teleport finished instead of the first node
8034 const targetNode = target._lpa || target.firstChild;
8035 if (vnode.shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
8036 if (isTeleportDisabled(vnode.props)) {
8037 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
8038 vnode.targetAnchor = targetNode;
8039 }
8040 else {
8041 vnode.anchor = nextSibling(node);
8042 // lookahead until we find the target anchor
8043 // we cannot rely on return value of hydrateChildren() because there
8044 // could be nested teleports
8045 let targetAnchor = targetNode;
8046 while (targetAnchor) {
8047 targetAnchor = nextSibling(targetAnchor);
8048 if (targetAnchor &&
8049 targetAnchor.nodeType === 8 &&
8050 targetAnchor.data === 'teleport anchor') {
8051 vnode.targetAnchor = targetAnchor;
8052 target._lpa =
8053 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
8054 break;
8055 }
8056 }
8057 hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
8058 }
8059 }
8060 updateCssVars(vnode);
8061 }
8062 return vnode.anchor && nextSibling(vnode.anchor);
8063}
8064// Force-casted public typing for h and TSX props inference
8065const Teleport = TeleportImpl;
8066function updateCssVars(vnode) {
8067 // presence of .ut method indicates owner component uses css vars.
8068 // code path here can assume browser environment.
8069 const ctx = vnode.ctx;
8070 if (ctx && ctx.ut) {
8071 let node = vnode.children[0].el;
8072 while (node !== vnode.targetAnchor) {
8073 if (node.nodeType === 1)
8074 node.setAttribute('data-v-owner', ctx.uid);
8075 node = node.nextSibling;
8076 }
8077 ctx.ut();
8078 }
8079}
8080
8081const Fragment = Symbol('Fragment' );
8082const Text = Symbol('Text' );
8083const Comment = Symbol('Comment' );
8084const Static = Symbol('Static' );
8085// Since v-if and v-for are the two possible ways node structure can dynamically
8086// change, once we consider v-if branches and each v-for fragment a block, we
8087// can divide a template into nested blocks, and within each block the node
8088// structure would be stable. This allows us to skip most children diffing
8089// and only worry about the dynamic nodes (indicated by patch flags).
8090const blockStack = [];
8091let currentBlock = null;
8092/**
8093 * Open a block.
8094 * This must be called before `createBlock`. It cannot be part of `createBlock`
8095 * because the children of the block are evaluated before `createBlock` itself
8096 * is called. The generated code typically looks like this:
8097 *
8098 * ```js
8099 * function render() {
8100 * return (openBlock(),createBlock('div', null, [...]))
8101 * }
8102 * ```
8103 * disableTracking is true when creating a v-for fragment block, since a v-for
8104 * fragment always diffs its children.
8105 *
8106 * @private
8107 */
8108function openBlock(disableTracking = false) {
8109 blockStack.push((currentBlock = disableTracking ? null : []));
8110}
8111function closeBlock() {
8112 blockStack.pop();
8113 currentBlock = blockStack[blockStack.length - 1] || null;
8114}
8115// Whether we should be tracking dynamic child nodes inside a block.
8116// Only tracks when this value is > 0
8117// We are not using a simple boolean because this value may need to be
8118// incremented/decremented by nested usage of v-once (see below)
8119let isBlockTreeEnabled = 1;
8120/**
8121 * Block tracking sometimes needs to be disabled, for example during the
8122 * creation of a tree that needs to be cached by v-once. The compiler generates
8123 * code like this:
8124 *
8125 * ``` js
8126 * _cache[1] || (
8127 * setBlockTracking(-1),
8128 * _cache[1] = createVNode(...),
8129 * setBlockTracking(1),
8130 * _cache[1]
8131 * )
8132 * ```
8133 *
8134 * @private
8135 */
8136function setBlockTracking(value) {
8137 isBlockTreeEnabled += value;
8138}
8139function setupBlock(vnode) {
8140 // save current block children on the block vnode
8141 vnode.dynamicChildren =
8142 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
8143 // close block
8144 closeBlock();
8145 // a block is always going to be patched, so track it as a child of its
8146 // parent block
8147 if (isBlockTreeEnabled > 0 && currentBlock) {
8148 currentBlock.push(vnode);
8149 }
8150 return vnode;
8151}
8152/**
8153 * @private
8154 */
8155function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
8156 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
8157}
8158/**
8159 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
8160 * A block root keeps track of dynamic nodes within the block in the
8161 * `dynamicChildren` array.
8162 *
8163 * @private
8164 */
8165function createBlock(type, props, children, patchFlag, dynamicProps) {
8166 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
8167}
8168function isVNode(value) {
8169 return value ? value.__v_isVNode === true : false;
8170}
8171function isSameVNodeType(n1, n2) {
8172 if (n2.shapeFlag & 6 /* ShapeFlags.COMPONENT */ &&
8173 hmrDirtyComponents.has(n2.type)) {
8174 // #7042, ensure the vnode being unmounted during HMR
8175 // bitwise operations to remove keep alive flags
8176 n1.shapeFlag &= ~256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
8177 n2.shapeFlag &= ~512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
8178 // HMR only: if the component has been hot-updated, force a reload.
8179 return false;
8180 }
8181 return n1.type === n2.type && n1.key === n2.key;
8182}
8183let vnodeArgsTransformer;
8184/**
8185 * Internal API for registering an arguments transform for createVNode
8186 * used for creating stubs in the test-utils
8187 * It is *internal* but needs to be exposed for test-utils to pick up proper
8188 * typings
8189 */
8190function transformVNodeArgs(transformer) {
8191 vnodeArgsTransformer = transformer;
8192}
8193const createVNodeWithArgsTransform = (...args) => {
8194 return _createVNode(...(vnodeArgsTransformer
8195 ? vnodeArgsTransformer(args, currentRenderingInstance)
8196 : args));
8197};
8198const InternalObjectKey = `__vInternal`;
8199const normalizeKey = ({ key }) => key != null ? key : null;
8200const normalizeRef = ({ ref, ref_key, ref_for }) => {
8201 return (ref != null
8202 ? isString(ref) || isRef(ref) || isFunction(ref)
8203 ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
8204 : ref
8205 : null);
8206};
8207function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ShapeFlags.ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
8208 const vnode = {
8209 __v_isVNode: true,
8210 __v_skip: true,
8211 type,
8212 props,
8213 key: props && normalizeKey(props),
8214 ref: props && normalizeRef(props),
8215 scopeId: currentScopeId,
8216 slotScopeIds: null,
8217 children,
8218 component: null,
8219 suspense: null,
8220 ssContent: null,
8221 ssFallback: null,
8222 dirs: null,
8223 transition: null,
8224 el: null,
8225 anchor: null,
8226 target: null,
8227 targetAnchor: null,
8228 staticCount: 0,
8229 shapeFlag,
8230 patchFlag,
8231 dynamicProps,
8232 dynamicChildren: null,
8233 appContext: null,
8234 ctx: currentRenderingInstance
8235 };
8236 if (needFullChildrenNormalization) {
8237 normalizeChildren(vnode, children);
8238 // normalize suspense children
8239 if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
8240 type.normalize(vnode);
8241 }
8242 }
8243 else if (children) {
8244 // compiled element vnode - if children is passed, only possible types are
8245 // string or Array.
8246 vnode.shapeFlag |= isString(children)
8247 ? 8 /* ShapeFlags.TEXT_CHILDREN */
8248 : 16 /* ShapeFlags.ARRAY_CHILDREN */;
8249 }
8250 // validate key
8251 if (vnode.key !== vnode.key) {
8252 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
8253 }
8254 // track vnode for block tree
8255 if (isBlockTreeEnabled > 0 &&
8256 // avoid a block node from tracking itself
8257 !isBlockNode &&
8258 // has current parent block
8259 currentBlock &&
8260 // presence of a patch flag indicates this node needs patching on updates.
8261 // component nodes also should always be patched, because even if the
8262 // component doesn't need to update, it needs to persist the instance on to
8263 // the next vnode so that it can be properly unmounted later.
8264 (vnode.patchFlag > 0 || shapeFlag & 6 /* ShapeFlags.COMPONENT */) &&
8265 // the EVENTS flag is only for hydration and if it is the only flag, the
8266 // vnode should not be considered dynamic due to handler caching.
8267 vnode.patchFlag !== 32 /* PatchFlags.HYDRATE_EVENTS */) {
8268 currentBlock.push(vnode);
8269 }
8270 return vnode;
8271}
8272const createVNode = (createVNodeWithArgsTransform );
8273function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
8274 if (!type || type === NULL_DYNAMIC_COMPONENT) {
8275 if (!type) {
8276 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
8277 }
8278 type = Comment;
8279 }
8280 if (isVNode(type)) {
8281 // createVNode receiving an existing vnode. This happens in cases like
8282 // <component :is="vnode"/>
8283 // #2078 make sure to merge refs during the clone instead of overwriting it
8284 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
8285 if (children) {
8286 normalizeChildren(cloned, children);
8287 }
8288 if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
8289 if (cloned.shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
8290 currentBlock[currentBlock.indexOf(type)] = cloned;
8291 }
8292 else {
8293 currentBlock.push(cloned);
8294 }
8295 }
8296 cloned.patchFlag |= -2 /* PatchFlags.BAIL */;
8297 return cloned;
8298 }
8299 // class component normalization.
8300 if (isClassComponent(type)) {
8301 type = type.__vccOpts;
8302 }
8303 // class & style normalization.
8304 if (props) {
8305 // for reactive or proxy objects, we need to clone it to enable mutation.
8306 props = guardReactiveProps(props);
8307 let { class: klass, style } = props;
8308 if (klass && !isString(klass)) {
8309 props.class = normalizeClass(klass);
8310 }
8311 if (isObject(style)) {
8312 // reactive state objects need to be cloned since they are likely to be
8313 // mutated
8314 if (isProxy(style) && !isArray(style)) {
8315 style = extend({}, style);
8316 }
8317 props.style = normalizeStyle(style);
8318 }
8319 }
8320 // encode the vnode type information into a bitmap
8321 const shapeFlag = isString(type)
8322 ? 1 /* ShapeFlags.ELEMENT */
8323 : isSuspense(type)
8324 ? 128 /* ShapeFlags.SUSPENSE */
8325 : isTeleport(type)
8326 ? 64 /* ShapeFlags.TELEPORT */
8327 : isObject(type)
8328 ? 4 /* ShapeFlags.STATEFUL_COMPONENT */
8329 : isFunction(type)
8330 ? 2 /* ShapeFlags.FUNCTIONAL_COMPONENT */
8331 : 0;
8332 if (shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */ && isProxy(type)) {
8333 type = toRaw(type);
8334 warn$1(`Vue received a Component which was made a reactive object. This can ` +
8335 `lead to unnecessary performance overhead, and should be avoided by ` +
8336 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
8337 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
8338 }
8339 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
8340}
8341function guardReactiveProps(props) {
8342 if (!props)
8343 return null;
8344 return isProxy(props) || InternalObjectKey in props
8345 ? extend({}, props)
8346 : props;
8347}
8348function cloneVNode(vnode, extraProps, mergeRef = false) {
8349 // This is intentionally NOT using spread or extend to avoid the runtime
8350 // key enumeration cost.
8351 const { props, ref, patchFlag, children } = vnode;
8352 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
8353 const cloned = {
8354 __v_isVNode: true,
8355 __v_skip: true,
8356 type: vnode.type,
8357 props: mergedProps,
8358 key: mergedProps && normalizeKey(mergedProps),
8359 ref: extraProps && extraProps.ref
8360 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
8361 // if the vnode itself already has a ref, cloneVNode will need to merge
8362 // the refs so the single vnode can be set on multiple refs
8363 mergeRef && ref
8364 ? isArray(ref)
8365 ? ref.concat(normalizeRef(extraProps))
8366 : [ref, normalizeRef(extraProps)]
8367 : normalizeRef(extraProps)
8368 : ref,
8369 scopeId: vnode.scopeId,
8370 slotScopeIds: vnode.slotScopeIds,
8371 children: patchFlag === -1 /* PatchFlags.HOISTED */ && isArray(children)
8372 ? children.map(deepCloneVNode)
8373 : children,
8374 target: vnode.target,
8375 targetAnchor: vnode.targetAnchor,
8376 staticCount: vnode.staticCount,
8377 shapeFlag: vnode.shapeFlag,
8378 // if the vnode is cloned with extra props, we can no longer assume its
8379 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
8380 // note: preserve flag for fragments since they use the flag for children
8381 // fast paths only.
8382 patchFlag: extraProps && vnode.type !== Fragment
8383 ? patchFlag === -1 // hoisted node
8384 ? 16 /* PatchFlags.FULL_PROPS */
8385 : patchFlag | 16 /* PatchFlags.FULL_PROPS */
8386 : patchFlag,
8387 dynamicProps: vnode.dynamicProps,
8388 dynamicChildren: vnode.dynamicChildren,
8389 appContext: vnode.appContext,
8390 dirs: vnode.dirs,
8391 transition: vnode.transition,
8392 // These should technically only be non-null on mounted VNodes. However,
8393 // they *should* be copied for kept-alive vnodes. So we just always copy
8394 // them since them being non-null during a mount doesn't affect the logic as
8395 // they will simply be overwritten.
8396 component: vnode.component,
8397 suspense: vnode.suspense,
8398 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
8399 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
8400 el: vnode.el,
8401 anchor: vnode.anchor,
8402 ctx: vnode.ctx
8403 };
8404 return cloned;
8405}
8406/**
8407 * Dev only, for HMR of hoisted vnodes reused in v-for
8408 * https://github.com/vitejs/vite/issues/2022
8409 */
8410function deepCloneVNode(vnode) {
8411 const cloned = cloneVNode(vnode);
8412 if (isArray(vnode.children)) {
8413 cloned.children = vnode.children.map(deepCloneVNode);
8414 }
8415 return cloned;
8416}
8417/**
8418 * @private
8419 */
8420function createTextVNode(text = ' ', flag = 0) {
8421 return createVNode(Text, null, text, flag);
8422}
8423/**
8424 * @private
8425 */
8426function createStaticVNode(content, numberOfNodes) {
8427 // A static vnode can contain multiple stringified elements, and the number
8428 // of elements is necessary for hydration.
8429 const vnode = createVNode(Static, null, content);
8430 vnode.staticCount = numberOfNodes;
8431 return vnode;
8432}
8433/**
8434 * @private
8435 */
8436function createCommentVNode(text = '',
8437// when used as the v-else branch, the comment node must be created as a
8438// block to ensure correct updates.
8439asBlock = false) {
8440 return asBlock
8441 ? (openBlock(), createBlock(Comment, null, text))
8442 : createVNode(Comment, null, text);
8443}
8444function normalizeVNode(child) {
8445 if (child == null || typeof child === 'boolean') {
8446 // empty placeholder
8447 return createVNode(Comment);
8448 }
8449 else if (isArray(child)) {
8450 // fragment
8451 return createVNode(Fragment, null,
8452 // #3666, avoid reference pollution when reusing vnode
8453 child.slice());
8454 }
8455 else if (typeof child === 'object') {
8456 // already vnode, this should be the most common since compiled templates
8457 // always produce all-vnode children arrays
8458 return cloneIfMounted(child);
8459 }
8460 else {
8461 // strings and numbers
8462 return createVNode(Text, null, String(child));
8463 }
8464}
8465// optimized normalization for template-compiled render fns
8466function cloneIfMounted(child) {
8467 return (child.el === null && child.patchFlag !== -1 /* PatchFlags.HOISTED */) ||
8468 child.memo
8469 ? child
8470 : cloneVNode(child);
8471}
8472function normalizeChildren(vnode, children) {
8473 let type = 0;
8474 const { shapeFlag } = vnode;
8475 if (children == null) {
8476 children = null;
8477 }
8478 else if (isArray(children)) {
8479 type = 16 /* ShapeFlags.ARRAY_CHILDREN */;
8480 }
8481 else if (typeof children === 'object') {
8482 if (shapeFlag & (1 /* ShapeFlags.ELEMENT */ | 64 /* ShapeFlags.TELEPORT */)) {
8483 // Normalize slot to plain children for plain element and Teleport
8484 const slot = children.default;
8485 if (slot) {
8486 // _c marker is added by withCtx() indicating this is a compiled slot
8487 slot._c && (slot._d = false);
8488 normalizeChildren(vnode, slot());
8489 slot._c && (slot._d = true);
8490 }
8491 return;
8492 }
8493 else {
8494 type = 32 /* ShapeFlags.SLOTS_CHILDREN */;
8495 const slotFlag = children._;
8496 if (!slotFlag && !(InternalObjectKey in children)) {
8497 children._ctx = currentRenderingInstance;
8498 }
8499 else if (slotFlag === 3 /* SlotFlags.FORWARDED */ && currentRenderingInstance) {
8500 // a child component receives forwarded slots from the parent.
8501 // its slot type is determined by its parent's slot type.
8502 if (currentRenderingInstance.slots._ === 1 /* SlotFlags.STABLE */) {
8503 children._ = 1 /* SlotFlags.STABLE */;
8504 }
8505 else {
8506 children._ = 2 /* SlotFlags.DYNAMIC */;
8507 vnode.patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
8508 }
8509 }
8510 }
8511 }
8512 else if (isFunction(children)) {
8513 children = { default: children, _ctx: currentRenderingInstance };
8514 type = 32 /* ShapeFlags.SLOTS_CHILDREN */;
8515 }
8516 else {
8517 children = String(children);
8518 // force teleport children to array so it can be moved around
8519 if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
8520 type = 16 /* ShapeFlags.ARRAY_CHILDREN */;
8521 children = [createTextVNode(children)];
8522 }
8523 else {
8524 type = 8 /* ShapeFlags.TEXT_CHILDREN */;
8525 }
8526 }
8527 vnode.children = children;
8528 vnode.shapeFlag |= type;
8529}
8530function mergeProps(...args) {
8531 const ret = {};
8532 for (let i = 0; i < args.length; i++) {
8533 const toMerge = args[i];
8534 for (const key in toMerge) {
8535 if (key === 'class') {
8536 if (ret.class !== toMerge.class) {
8537 ret.class = normalizeClass([ret.class, toMerge.class]);
8538 }
8539 }
8540 else if (key === 'style') {
8541 ret.style = normalizeStyle([ret.style, toMerge.style]);
8542 }
8543 else if (isOn(key)) {
8544 const existing = ret[key];
8545 const incoming = toMerge[key];
8546 if (incoming &&
8547 existing !== incoming &&
8548 !(isArray(existing) && existing.includes(incoming))) {
8549 ret[key] = existing
8550 ? [].concat(existing, incoming)
8551 : incoming;
8552 }
8553 }
8554 else if (key !== '') {
8555 ret[key] = toMerge[key];
8556 }
8557 }
8558 }
8559 return ret;
8560}
8561function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
8562 callWithAsyncErrorHandling(hook, instance, 7 /* ErrorCodes.VNODE_HOOK */, [
8563 vnode,
8564 prevVNode
8565 ]);
8566}
8567
8568const emptyAppContext = createAppContext();
8569let uid$1 = 0;
8570function createComponentInstance(vnode, parent, suspense) {
8571 const type = vnode.type;
8572 // inherit parent app context - or - if root, adopt from root vnode
8573 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8574 const instance = {
8575 uid: uid$1++,
8576 vnode,
8577 type,
8578 parent,
8579 appContext,
8580 root: null,
8581 next: null,
8582 subTree: null,
8583 effect: null,
8584 update: null,
8585 scope: new EffectScope(true /* detached */),
8586 render: null,
8587 proxy: null,
8588 exposed: null,
8589 exposeProxy: null,
8590 withProxy: null,
8591 provides: parent ? parent.provides : Object.create(appContext.provides),
8592 accessCache: null,
8593 renderCache: [],
8594 // local resolved assets
8595 components: null,
8596 directives: null,
8597 // resolved props and emits options
8598 propsOptions: normalizePropsOptions(type, appContext),
8599 emitsOptions: normalizeEmitsOptions(type, appContext),
8600 // emit
8601 emit: null,
8602 emitted: null,
8603 // props default value
8604 propsDefaults: EMPTY_OBJ,
8605 // inheritAttrs
8606 inheritAttrs: type.inheritAttrs,
8607 // state
8608 ctx: EMPTY_OBJ,
8609 data: EMPTY_OBJ,
8610 props: EMPTY_OBJ,
8611 attrs: EMPTY_OBJ,
8612 slots: EMPTY_OBJ,
8613 refs: EMPTY_OBJ,
8614 setupState: EMPTY_OBJ,
8615 setupContext: null,
8616 // suspense related
8617 suspense,
8618 suspenseId: suspense ? suspense.pendingId : 0,
8619 asyncDep: null,
8620 asyncResolved: false,
8621 // lifecycle hooks
8622 // not using enums here because it results in computed properties
8623 isMounted: false,
8624 isUnmounted: false,
8625 isDeactivated: false,
8626 bc: null,
8627 c: null,
8628 bm: null,
8629 m: null,
8630 bu: null,
8631 u: null,
8632 um: null,
8633 bum: null,
8634 da: null,
8635 a: null,
8636 rtg: null,
8637 rtc: null,
8638 ec: null,
8639 sp: null
8640 };
8641 {
8642 instance.ctx = createDevRenderContext(instance);
8643 }
8644 instance.root = parent ? parent.root : instance;
8645 instance.emit = emit$1.bind(null, instance);
8646 // apply custom element special handling
8647 if (vnode.ce) {
8648 vnode.ce(instance);
8649 }
8650 return instance;
8651}
8652let currentInstance = null;
8653const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8654const setCurrentInstance = (instance) => {
8655 currentInstance = instance;
8656 instance.scope.on();
8657};
8658const unsetCurrentInstance = () => {
8659 currentInstance && currentInstance.scope.off();
8660 currentInstance = null;
8661};
8662const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8663function validateComponentName(name, config) {
8664 const appIsNativeTag = config.isNativeTag || NO;
8665 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8666 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
8667 }
8668}
8669function isStatefulComponent(instance) {
8670 return instance.vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */;
8671}
8672let isInSSRComponentSetup = false;
8673function setupComponent(instance, isSSR = false) {
8674 isInSSRComponentSetup = isSSR;
8675 const { props, children } = instance.vnode;
8676 const isStateful = isStatefulComponent(instance);
8677 initProps(instance, props, isStateful, isSSR);
8678 initSlots(instance, children);
8679 const setupResult = isStateful
8680 ? setupStatefulComponent(instance, isSSR)
8681 : undefined;
8682 isInSSRComponentSetup = false;
8683 return setupResult;
8684}
8685function setupStatefulComponent(instance, isSSR) {
8686 var _a;
8687 const Component = instance.type;
8688 {
8689 if (Component.name) {
8690 validateComponentName(Component.name, instance.appContext.config);
8691 }
8692 if (Component.components) {
8693 const names = Object.keys(Component.components);
8694 for (let i = 0; i < names.length; i++) {
8695 validateComponentName(names[i], instance.appContext.config);
8696 }
8697 }
8698 if (Component.directives) {
8699 const names = Object.keys(Component.directives);
8700 for (let i = 0; i < names.length; i++) {
8701 validateDirectiveName(names[i]);
8702 }
8703 }
8704 if (Component.compilerOptions && isRuntimeOnly()) {
8705 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8706 `includes the runtime compiler. Since you are using a runtime-only ` +
8707 `build, the options should be passed via your build tool config instead.`);
8708 }
8709 }
8710 // 0. create render proxy property access cache
8711 instance.accessCache = Object.create(null);
8712 // 1. create public instance / render proxy
8713 // also mark it raw so it's never observed
8714 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8715 {
8716 exposePropsOnRenderContext(instance);
8717 }
8718 // 2. call setup()
8719 const { setup } = Component;
8720 if (setup) {
8721 const setupContext = (instance.setupContext =
8722 setup.length > 1 ? createSetupContext(instance) : null);
8723 setCurrentInstance(instance);
8724 pauseTracking();
8725 const setupResult = callWithErrorHandling(setup, instance, 0 /* ErrorCodes.SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8726 resetTracking();
8727 unsetCurrentInstance();
8728 if (isPromise(setupResult)) {
8729 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8730 if (isSSR) {
8731 // return the promise so server-renderer can wait on it
8732 return setupResult
8733 .then((resolvedResult) => {
8734 handleSetupResult(instance, resolvedResult, isSSR);
8735 })
8736 .catch(e => {
8737 handleError(e, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
8738 });
8739 }
8740 else {
8741 // async setup returned Promise.
8742 // bail here and wait for re-entry.
8743 instance.asyncDep = setupResult;
8744 if (!instance.suspense) {
8745 const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
8746 warn$1(`Component <${name}>: setup function returned a promise, but no ` +
8747 `<Suspense> boundary was found in the parent component tree. ` +
8748 `A component with async setup() must be nested in a <Suspense> ` +
8749 `in order to be rendered.`);
8750 }
8751 }
8752 }
8753 else {
8754 handleSetupResult(instance, setupResult, isSSR);
8755 }
8756 }
8757 else {
8758 finishComponentSetup(instance, isSSR);
8759 }
8760}
8761function handleSetupResult(instance, setupResult, isSSR) {
8762 if (isFunction(setupResult)) {
8763 // setup returned an inline render function
8764 {
8765 instance.render = setupResult;
8766 }
8767 }
8768 else if (isObject(setupResult)) {
8769 if (isVNode(setupResult)) {
8770 warn$1(`setup() should not return VNodes directly - ` +
8771 `return a render function instead.`);
8772 }
8773 // setup returned bindings.
8774 // assuming a render function compiled from template is present.
8775 {
8776 instance.devtoolsRawSetupState = setupResult;
8777 }
8778 instance.setupState = proxyRefs(setupResult);
8779 {
8780 exposeSetupStateOnRenderContext(instance);
8781 }
8782 }
8783 else if (setupResult !== undefined) {
8784 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8785 }
8786 finishComponentSetup(instance, isSSR);
8787}
8788let compile;
8789let installWithProxy;
8790/**
8791 * For runtime-dom to register the compiler.
8792 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8793 */
8794function registerRuntimeCompiler(_compile) {
8795 compile = _compile;
8796 installWithProxy = i => {
8797 if (i.render._rc) {
8798 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8799 }
8800 };
8801}
8802// dev only
8803const isRuntimeOnly = () => !compile;
8804function finishComponentSetup(instance, isSSR, skipOptions) {
8805 const Component = instance.type;
8806 // template / render function normalization
8807 // could be already set when returned from setup()
8808 if (!instance.render) {
8809 // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
8810 // is done by server-renderer
8811 if (!isSSR && compile && !Component.render) {
8812 const template = Component.template ||
8813 resolveMergedOptions(instance).template;
8814 if (template) {
8815 {
8816 startMeasure(instance, `compile`);
8817 }
8818 const { isCustomElement, compilerOptions } = instance.appContext.config;
8819 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8820 const finalCompilerOptions = extend(extend({
8821 isCustomElement,
8822 delimiters
8823 }, compilerOptions), componentCompilerOptions);
8824 Component.render = compile(template, finalCompilerOptions);
8825 {
8826 endMeasure(instance, `compile`);
8827 }
8828 }
8829 }
8830 instance.render = (Component.render || NOOP);
8831 // for runtime-compiled render functions using `with` blocks, the render
8832 // proxy used needs a different `has` handler which is more performant and
8833 // also only allows a whitelist of globals to fallthrough.
8834 if (installWithProxy) {
8835 installWithProxy(instance);
8836 }
8837 }
8838 // support for 2.x options
8839 {
8840 setCurrentInstance(instance);
8841 pauseTracking();
8842 applyOptions(instance);
8843 resetTracking();
8844 unsetCurrentInstance();
8845 }
8846 // warn missing template/render
8847 // the runtime compilation of template in SSR is done by server-render
8848 if (!Component.render && instance.render === NOOP && !isSSR) {
8849 /* istanbul ignore if */
8850 if (!compile && Component.template) {
8851 warn$1(`Component provided template option but ` +
8852 `runtime compilation is not supported in this build of Vue.` +
8853 (` Use "vue.esm-browser.js" instead.`
8854 ) /* should not happen */);
8855 }
8856 else {
8857 warn$1(`Component is missing template or render function.`);
8858 }
8859 }
8860}
8861function createAttrsProxy(instance) {
8862 return new Proxy(instance.attrs, {
8863 get(target, key) {
8864 markAttrsAccessed();
8865 track(instance, "get" /* TrackOpTypes.GET */, '$attrs');
8866 return target[key];
8867 },
8868 set() {
8869 warn$1(`setupContext.attrs is readonly.`);
8870 return false;
8871 },
8872 deleteProperty() {
8873 warn$1(`setupContext.attrs is readonly.`);
8874 return false;
8875 }
8876 }
8877 );
8878}
8879function createSetupContext(instance) {
8880 const expose = exposed => {
8881 if (instance.exposed) {
8882 warn$1(`expose() should be called only once per setup().`);
8883 }
8884 instance.exposed = exposed || {};
8885 };
8886 let attrs;
8887 {
8888 // We use getters in dev in case libs like test-utils overwrite instance
8889 // properties (overwrites should not be done in prod)
8890 return Object.freeze({
8891 get attrs() {
8892 return attrs || (attrs = createAttrsProxy(instance));
8893 },
8894 get slots() {
8895 return shallowReadonly(instance.slots);
8896 },
8897 get emit() {
8898 return (event, ...args) => instance.emit(event, ...args);
8899 },
8900 expose
8901 });
8902 }
8903}
8904function getExposeProxy(instance) {
8905 if (instance.exposed) {
8906 return (instance.exposeProxy ||
8907 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8908 get(target, key) {
8909 if (key in target) {
8910 return target[key];
8911 }
8912 else if (key in publicPropertiesMap) {
8913 return publicPropertiesMap[key](instance);
8914 }
8915 },
8916 has(target, key) {
8917 return key in target || key in publicPropertiesMap;
8918 }
8919 })));
8920 }
8921}
8922const classifyRE = /(?:^|[-_])(\w)/g;
8923const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8924function getComponentName(Component, includeInferred = true) {
8925 return isFunction(Component)
8926 ? Component.displayName || Component.name
8927 : Component.name || (includeInferred && Component.__name);
8928}
8929/* istanbul ignore next */
8930function formatComponentName(instance, Component, isRoot = false) {
8931 let name = getComponentName(Component);
8932 if (!name && Component.__file) {
8933 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8934 if (match) {
8935 name = match[1];
8936 }
8937 }
8938 if (!name && instance && instance.parent) {
8939 // try to infer the name based on reverse resolution
8940 const inferFromRegistry = (registry) => {
8941 for (const key in registry) {
8942 if (registry[key] === Component) {
8943 return key;
8944 }
8945 }
8946 };
8947 name =
8948 inferFromRegistry(instance.components ||
8949 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8950 }
8951 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8952}
8953function isClassComponent(value) {
8954 return isFunction(value) && '__vccOpts' in value;
8955}
8956
8957const computed$1 = ((getterOrOptions, debugOptions) => {
8958 // @ts-ignore
8959 return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
8960});
8961
8962// dev only
8963const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8964 `<script setup> of a single file component. Its arguments should be ` +
8965 `compiled away and passing it at runtime has no effect.`);
8966// implementation
8967function defineProps() {
8968 {
8969 warnRuntimeUsage(`defineProps`);
8970 }
8971 return null;
8972}
8973// implementation
8974function defineEmits() {
8975 {
8976 warnRuntimeUsage(`defineEmits`);
8977 }
8978 return null;
8979}
8980/**
8981 * Vue `<script setup>` compiler macro for declaring a component's exposed
8982 * instance properties when it is accessed by a parent component via template
8983 * refs.
8984 *
8985 * `<script setup>` components are closed by default - i.e. variables inside
8986 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8987 * via `defineExpose`.
8988 *
8989 * This is only usable inside `<script setup>`, is compiled away in the
8990 * output and should **not** be actually called at runtime.
8991 */
8992function defineExpose(exposed) {
8993 {
8994 warnRuntimeUsage(`defineExpose`);
8995 }
8996}
8997/**
8998 * Vue `<script setup>` compiler macro for providing props default values when
8999 * using type-based `defineProps` declaration.
9000 *
9001 * Example usage:
9002 * ```ts
9003 * withDefaults(defineProps<{
9004 * size?: number
9005 * labels?: string[]
9006 * }>(), {
9007 * size: 3,
9008 * labels: () => ['default label']
9009 * })
9010 * ```
9011 *
9012 * This is only usable inside `<script setup>`, is compiled away in the output
9013 * and should **not** be actually called at runtime.
9014 */
9015function withDefaults(props, defaults) {
9016 {
9017 warnRuntimeUsage(`withDefaults`);
9018 }
9019 return null;
9020}
9021function useSlots() {
9022 return getContext().slots;
9023}
9024function useAttrs() {
9025 return getContext().attrs;
9026}
9027function getContext() {
9028 const i = getCurrentInstance();
9029 if (!i) {
9030 warn$1(`useContext() called without active instance.`);
9031 }
9032 return i.setupContext || (i.setupContext = createSetupContext(i));
9033}
9034/**
9035 * Runtime helper for merging default declarations. Imported by compiled code
9036 * only.
9037 * @internal
9038 */
9039function mergeDefaults(raw, defaults) {
9040 const props = isArray(raw)
9041 ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
9042 : raw;
9043 for (const key in defaults) {
9044 const opt = props[key];
9045 if (opt) {
9046 if (isArray(opt) || isFunction(opt)) {
9047 props[key] = { type: opt, default: defaults[key] };
9048 }
9049 else {
9050 opt.default = defaults[key];
9051 }
9052 }
9053 else if (opt === null) {
9054 props[key] = { default: defaults[key] };
9055 }
9056 else {
9057 warn$1(`props default key "${key}" has no corresponding declaration.`);
9058 }
9059 }
9060 return props;
9061}
9062/**
9063 * Used to create a proxy for the rest element when destructuring props with
9064 * defineProps().
9065 * @internal
9066 */
9067function createPropsRestProxy(props, excludedKeys) {
9068 const ret = {};
9069 for (const key in props) {
9070 if (!excludedKeys.includes(key)) {
9071 Object.defineProperty(ret, key, {
9072 enumerable: true,
9073 get: () => props[key]
9074 });
9075 }
9076 }
9077 return ret;
9078}
9079/**
9080 * `<script setup>` helper for persisting the current instance context over
9081 * async/await flows.
9082 *
9083 * `@vue/compiler-sfc` converts the following:
9084 *
9085 * ```ts
9086 * const x = await foo()
9087 * ```
9088 *
9089 * into:
9090 *
9091 * ```ts
9092 * let __temp, __restore
9093 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
9094 * ```
9095 * @internal
9096 */
9097function withAsyncContext(getAwaitable) {
9098 const ctx = getCurrentInstance();
9099 if (!ctx) {
9100 warn$1(`withAsyncContext called without active current instance. ` +
9101 `This is likely a bug.`);
9102 }
9103 let awaitable = getAwaitable();
9104 unsetCurrentInstance();
9105 if (isPromise(awaitable)) {
9106 awaitable = awaitable.catch(e => {
9107 setCurrentInstance(ctx);
9108 throw e;
9109 });
9110 }
9111 return [awaitable, () => setCurrentInstance(ctx)];
9112}
9113
9114// Actual implementation
9115function h(type, propsOrChildren, children) {
9116 const l = arguments.length;
9117 if (l === 2) {
9118 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
9119 // single vnode without props
9120 if (isVNode(propsOrChildren)) {
9121 return createVNode(type, null, [propsOrChildren]);
9122 }
9123 // props without children
9124 return createVNode(type, propsOrChildren);
9125 }
9126 else {
9127 // omit props
9128 return createVNode(type, null, propsOrChildren);
9129 }
9130 }
9131 else {
9132 if (l > 3) {
9133 children = Array.prototype.slice.call(arguments, 2);
9134 }
9135 else if (l === 3 && isVNode(children)) {
9136 children = [children];
9137 }
9138 return createVNode(type, propsOrChildren, children);
9139 }
9140}
9141
9142const ssrContextKey = Symbol(`ssrContext` );
9143const useSSRContext = () => {
9144 {
9145 const ctx = inject(ssrContextKey);
9146 if (!ctx) {
9147 warn$1(`Server rendering context not provided. Make sure to only call ` +
9148 `useSSRContext() conditionally in the server build.`);
9149 }
9150 return ctx;
9151 }
9152};
9153
9154function initCustomFormatter() {
9155 /* eslint-disable no-restricted-globals */
9156 if (typeof window === 'undefined') {
9157 return;
9158 }
9159 const vueStyle = { style: 'color:#3ba776' };
9160 const numberStyle = { style: 'color:#0b1bc9' };
9161 const stringStyle = { style: 'color:#b62e24' };
9162 const keywordStyle = { style: 'color:#9d288c' };
9163 // custom formatter for Chrome
9164 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
9165 const formatter = {
9166 header(obj) {
9167 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
9168 if (!isObject(obj)) {
9169 return null;
9170 }
9171 if (obj.__isVue) {
9172 return ['div', vueStyle, `VueInstance`];
9173 }
9174 else if (isRef(obj)) {
9175 return [
9176 'div',
9177 {},
9178 ['span', vueStyle, genRefFlag(obj)],
9179 '<',
9180 formatValue(obj.value),
9181 `>`
9182 ];
9183 }
9184 else if (isReactive(obj)) {
9185 return [
9186 'div',
9187 {},
9188 ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
9189 '<',
9190 formatValue(obj),
9191 `>${isReadonly(obj) ? ` (readonly)` : ``}`
9192 ];
9193 }
9194 else if (isReadonly(obj)) {
9195 return [
9196 'div',
9197 {},
9198 ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
9199 '<',
9200 formatValue(obj),
9201 '>'
9202 ];
9203 }
9204 return null;
9205 },
9206 hasBody(obj) {
9207 return obj && obj.__isVue;
9208 },
9209 body(obj) {
9210 if (obj && obj.__isVue) {
9211 return [
9212 'div',
9213 {},
9214 ...formatInstance(obj.$)
9215 ];
9216 }
9217 }
9218 };
9219 function formatInstance(instance) {
9220 const blocks = [];
9221 if (instance.type.props && instance.props) {
9222 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
9223 }
9224 if (instance.setupState !== EMPTY_OBJ) {
9225 blocks.push(createInstanceBlock('setup', instance.setupState));
9226 }
9227 if (instance.data !== EMPTY_OBJ) {
9228 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
9229 }
9230 const computed = extractKeys(instance, 'computed');
9231 if (computed) {
9232 blocks.push(createInstanceBlock('computed', computed));
9233 }
9234 const injected = extractKeys(instance, 'inject');
9235 if (injected) {
9236 blocks.push(createInstanceBlock('injected', injected));
9237 }
9238 blocks.push([
9239 'div',
9240 {},
9241 [
9242 'span',
9243 {
9244 style: keywordStyle.style + ';opacity:0.66'
9245 },
9246 '$ (internal): '
9247 ],
9248 ['object', { object: instance }]
9249 ]);
9250 return blocks;
9251 }
9252 function createInstanceBlock(type, target) {
9253 target = extend({}, target);
9254 if (!Object.keys(target).length) {
9255 return ['span', {}];
9256 }
9257 return [
9258 'div',
9259 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9260 [
9261 'div',
9262 {
9263 style: 'color:#476582'
9264 },
9265 type
9266 ],
9267 [
9268 'div',
9269 {
9270 style: 'padding-left:1.25em'
9271 },
9272 ...Object.keys(target).map(key => {
9273 return [
9274 'div',
9275 {},
9276 ['span', keywordStyle, key + ': '],
9277 formatValue(target[key], false)
9278 ];
9279 })
9280 ]
9281 ];
9282 }
9283 function formatValue(v, asRaw = true) {
9284 if (typeof v === 'number') {
9285 return ['span', numberStyle, v];
9286 }
9287 else if (typeof v === 'string') {
9288 return ['span', stringStyle, JSON.stringify(v)];
9289 }
9290 else if (typeof v === 'boolean') {
9291 return ['span', keywordStyle, v];
9292 }
9293 else if (isObject(v)) {
9294 return ['object', { object: asRaw ? toRaw(v) : v }];
9295 }
9296 else {
9297 return ['span', stringStyle, String(v)];
9298 }
9299 }
9300 function extractKeys(instance, type) {
9301 const Comp = instance.type;
9302 if (isFunction(Comp)) {
9303 return;
9304 }
9305 const extracted = {};
9306 for (const key in instance.ctx) {
9307 if (isKeyOfType(Comp, key, type)) {
9308 extracted[key] = instance.ctx[key];
9309 }
9310 }
9311 return extracted;
9312 }
9313 function isKeyOfType(Comp, key, type) {
9314 const opts = Comp[type];
9315 if ((isArray(opts) && opts.includes(key)) ||
9316 (isObject(opts) && key in opts)) {
9317 return true;
9318 }
9319 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9320 return true;
9321 }
9322 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9323 return true;
9324 }
9325 }
9326 function genRefFlag(v) {
9327 if (isShallow(v)) {
9328 return `ShallowRef`;
9329 }
9330 if (v.effect) {
9331 return `ComputedRef`;
9332 }
9333 return `Ref`;
9334 }
9335 if (window.devtoolsFormatters) {
9336 window.devtoolsFormatters.push(formatter);
9337 }
9338 else {
9339 window.devtoolsFormatters = [formatter];
9340 }
9341}
9342
9343function withMemo(memo, render, cache, index) {
9344 const cached = cache[index];
9345 if (cached && isMemoSame(cached, memo)) {
9346 return cached;
9347 }
9348 const ret = render();
9349 // shallow clone
9350 ret.memo = memo.slice();
9351 return (cache[index] = ret);
9352}
9353function isMemoSame(cached, memo) {
9354 const prev = cached.memo;
9355 if (prev.length != memo.length) {
9356 return false;
9357 }
9358 for (let i = 0; i < prev.length; i++) {
9359 if (hasChanged(prev[i], memo[i])) {
9360 return false;
9361 }
9362 }
9363 // make sure to let parent block track it when returning cached
9364 if (isBlockTreeEnabled > 0 && currentBlock) {
9365 currentBlock.push(cached);
9366 }
9367 return true;
9368}
9369
9370// Core API ------------------------------------------------------------------
9371const version = "3.2.45";
9372/**
9373 * SSR utils for \@vue/server-renderer. Only exposed in ssr-possible builds.
9374 * @internal
9375 */
9376const ssrUtils = (null);
9377/**
9378 * @internal only exposed in compat builds
9379 */
9380const resolveFilter = null;
9381/**
9382 * @internal only exposed in compat builds.
9383 */
9384const compatUtils = (null);
9385
9386const svgNS = 'http://www.w3.org/2000/svg';
9387const doc = (typeof document !== 'undefined' ? document : null);
9388const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
9389const nodeOps = {
9390 insert: (child, parent, anchor) => {
9391 parent.insertBefore(child, anchor || null);
9392 },
9393 remove: child => {
9394 const parent = child.parentNode;
9395 if (parent) {
9396 parent.removeChild(child);
9397 }
9398 },
9399 createElement: (tag, isSVG, is, props) => {
9400 const el = isSVG
9401 ? doc.createElementNS(svgNS, tag)
9402 : doc.createElement(tag, is ? { is } : undefined);
9403 if (tag === 'select' && props && props.multiple != null) {
9404 el.setAttribute('multiple', props.multiple);
9405 }
9406 return el;
9407 },
9408 createText: text => doc.createTextNode(text),
9409 createComment: text => doc.createComment(text),
9410 setText: (node, text) => {
9411 node.nodeValue = text;
9412 },
9413 setElementText: (el, text) => {
9414 el.textContent = text;
9415 },
9416 parentNode: node => node.parentNode,
9417 nextSibling: node => node.nextSibling,
9418 querySelector: selector => doc.querySelector(selector),
9419 setScopeId(el, id) {
9420 el.setAttribute(id, '');
9421 },
9422 // __UNSAFE__
9423 // Reason: innerHTML.
9424 // Static content here can only come from compiled templates.
9425 // As long as the user only uses trusted templates, this is safe.
9426 insertStaticContent(content, parent, anchor, isSVG, start, end) {
9427 // <parent> before | first ... last | anchor </parent>
9428 const before = anchor ? anchor.previousSibling : parent.lastChild;
9429 // #5308 can only take cached path if:
9430 // - has a single root node
9431 // - nextSibling info is still available
9432 if (start && (start === end || start.nextSibling)) {
9433 // cached
9434 while (true) {
9435 parent.insertBefore(start.cloneNode(true), anchor);
9436 if (start === end || !(start = start.nextSibling))
9437 break;
9438 }
9439 }
9440 else {
9441 // fresh insert
9442 templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9443 const template = templateContainer.content;
9444 if (isSVG) {
9445 // remove outer svg wrapper
9446 const wrapper = template.firstChild;
9447 while (wrapper.firstChild) {
9448 template.appendChild(wrapper.firstChild);
9449 }
9450 template.removeChild(wrapper);
9451 }
9452 parent.insertBefore(template, anchor);
9453 }
9454 return [
9455 // first
9456 before ? before.nextSibling : parent.firstChild,
9457 // last
9458 anchor ? anchor.previousSibling : parent.lastChild
9459 ];
9460 }
9461};
9462
9463// compiler should normalize class + :class bindings on the same element
9464// into a single binding ['staticClass', dynamic]
9465function patchClass(el, value, isSVG) {
9466 // directly setting className should be faster than setAttribute in theory
9467 // if this is an element during a transition, take the temporary transition
9468 // classes into account.
9469 const transitionClasses = el._vtc;
9470 if (transitionClasses) {
9471 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9472 }
9473 if (value == null) {
9474 el.removeAttribute('class');
9475 }
9476 else if (isSVG) {
9477 el.setAttribute('class', value);
9478 }
9479 else {
9480 el.className = value;
9481 }
9482}
9483
9484function patchStyle(el, prev, next) {
9485 const style = el.style;
9486 const isCssString = isString(next);
9487 if (next && !isCssString) {
9488 for (const key in next) {
9489 setStyle(style, key, next[key]);
9490 }
9491 if (prev && !isString(prev)) {
9492 for (const key in prev) {
9493 if (next[key] == null) {
9494 setStyle(style, key, '');
9495 }
9496 }
9497 }
9498 }
9499 else {
9500 const currentDisplay = style.display;
9501 if (isCssString) {
9502 if (prev !== next) {
9503 style.cssText = next;
9504 }
9505 }
9506 else if (prev) {
9507 el.removeAttribute('style');
9508 }
9509 // indicates that the `display` of the element is controlled by `v-show`,
9510 // so we always keep the current `display` value regardless of the `style`
9511 // value, thus handing over control to `v-show`.
9512 if ('_vod' in el) {
9513 style.display = currentDisplay;
9514 }
9515 }
9516}
9517const semicolonRE = /[^\\];\s*$/;
9518const importantRE = /\s*!important$/;
9519function setStyle(style, name, val) {
9520 if (isArray(val)) {
9521 val.forEach(v => setStyle(style, name, v));
9522 }
9523 else {
9524 if (val == null)
9525 val = '';
9526 {
9527 if (semicolonRE.test(val)) {
9528 warn$1(`Unexpected semicolon at the end of '${name}' style value: '${val}'`);
9529 }
9530 }
9531 if (name.startsWith('--')) {
9532 // custom property definition
9533 style.setProperty(name, val);
9534 }
9535 else {
9536 const prefixed = autoPrefix(style, name);
9537 if (importantRE.test(val)) {
9538 // !important
9539 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9540 }
9541 else {
9542 style[prefixed] = val;
9543 }
9544 }
9545 }
9546}
9547const prefixes = ['Webkit', 'Moz', 'ms'];
9548const prefixCache = {};
9549function autoPrefix(style, rawName) {
9550 const cached = prefixCache[rawName];
9551 if (cached) {
9552 return cached;
9553 }
9554 let name = camelize(rawName);
9555 if (name !== 'filter' && name in style) {
9556 return (prefixCache[rawName] = name);
9557 }
9558 name = capitalize(name);
9559 for (let i = 0; i < prefixes.length; i++) {
9560 const prefixed = prefixes[i] + name;
9561 if (prefixed in style) {
9562 return (prefixCache[rawName] = prefixed);
9563 }
9564 }
9565 return rawName;
9566}
9567
9568const xlinkNS = 'http://www.w3.org/1999/xlink';
9569function patchAttr(el, key, value, isSVG, instance) {
9570 if (isSVG && key.startsWith('xlink:')) {
9571 if (value == null) {
9572 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9573 }
9574 else {
9575 el.setAttributeNS(xlinkNS, key, value);
9576 }
9577 }
9578 else {
9579 // note we are only checking boolean attributes that don't have a
9580 // corresponding dom prop of the same name here.
9581 const isBoolean = isSpecialBooleanAttr(key);
9582 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9583 el.removeAttribute(key);
9584 }
9585 else {
9586 el.setAttribute(key, isBoolean ? '' : value);
9587 }
9588 }
9589}
9590
9591// __UNSAFE__
9592// functions. The user is responsible for using them with only trusted content.
9593function patchDOMProp(el, key, value,
9594// the following args are passed only due to potential innerHTML/textContent
9595// overriding existing VNodes, in which case the old tree must be properly
9596// unmounted.
9597prevChildren, parentComponent, parentSuspense, unmountChildren) {
9598 if (key === 'innerHTML' || key === 'textContent') {
9599 if (prevChildren) {
9600 unmountChildren(prevChildren, parentComponent, parentSuspense);
9601 }
9602 el[key] = value == null ? '' : value;
9603 return;
9604 }
9605 if (key === 'value' &&
9606 el.tagName !== 'PROGRESS' &&
9607 // custom elements may use _value internally
9608 !el.tagName.includes('-')) {
9609 // store value as _value as well since
9610 // non-string values will be stringified.
9611 el._value = value;
9612 const newValue = value == null ? '' : value;
9613 if (el.value !== newValue ||
9614 // #4956: always set for OPTION elements because its value falls back to
9615 // textContent if no value attribute is present. And setting .value for
9616 // OPTION has no side effect
9617 el.tagName === 'OPTION') {
9618 el.value = newValue;
9619 }
9620 if (value == null) {
9621 el.removeAttribute(key);
9622 }
9623 return;
9624 }
9625 let needRemove = false;
9626 if (value === '' || value == null) {
9627 const type = typeof el[key];
9628 if (type === 'boolean') {
9629 // e.g. <select multiple> compiles to { multiple: '' }
9630 value = includeBooleanAttr(value);
9631 }
9632 else if (value == null && type === 'string') {
9633 // e.g. <div :id="null">
9634 value = '';
9635 needRemove = true;
9636 }
9637 else if (type === 'number') {
9638 // e.g. <img :width="null">
9639 value = 0;
9640 needRemove = true;
9641 }
9642 }
9643 // some properties perform value validation and throw,
9644 // some properties has getter, no setter, will error in 'use strict'
9645 // eg. <select :type="null"></select> <select :willValidate="null"></select>
9646 try {
9647 el[key] = value;
9648 }
9649 catch (e) {
9650 // do not warn if value is auto-coerced from nullish values
9651 if (!needRemove) {
9652 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9653 `value ${value} is invalid.`, e);
9654 }
9655 }
9656 needRemove && el.removeAttribute(key);
9657}
9658
9659function addEventListener(el, event, handler, options) {
9660 el.addEventListener(event, handler, options);
9661}
9662function removeEventListener(el, event, handler, options) {
9663 el.removeEventListener(event, handler, options);
9664}
9665function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9666 // vei = vue event invokers
9667 const invokers = el._vei || (el._vei = {});
9668 const existingInvoker = invokers[rawName];
9669 if (nextValue && existingInvoker) {
9670 // patch
9671 existingInvoker.value = nextValue;
9672 }
9673 else {
9674 const [name, options] = parseName(rawName);
9675 if (nextValue) {
9676 // add
9677 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9678 addEventListener(el, name, invoker, options);
9679 }
9680 else if (existingInvoker) {
9681 // remove
9682 removeEventListener(el, name, existingInvoker, options);
9683 invokers[rawName] = undefined;
9684 }
9685 }
9686}
9687const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9688function parseName(name) {
9689 let options;
9690 if (optionsModifierRE.test(name)) {
9691 options = {};
9692 let m;
9693 while ((m = name.match(optionsModifierRE))) {
9694 name = name.slice(0, name.length - m[0].length);
9695 options[m[0].toLowerCase()] = true;
9696 }
9697 }
9698 const event = name[2] === ':' ? name.slice(3) : hyphenate(name.slice(2));
9699 return [event, options];
9700}
9701// To avoid the overhead of repeatedly calling Date.now(), we cache
9702// and use the same timestamp for all event listeners attached in the same tick.
9703let cachedNow = 0;
9704const p = /*#__PURE__*/ Promise.resolve();
9705const getNow = () => cachedNow || (p.then(() => (cachedNow = 0)), (cachedNow = Date.now()));
9706function createInvoker(initialValue, instance) {
9707 const invoker = (e) => {
9708 // async edge case vuejs/vue#6566
9709 // inner click event triggers patch, event handler
9710 // attached to outer element during patch, and triggered again. This
9711 // happens because browsers fire microtask ticks between event propagation.
9712 // this no longer happens for templates in Vue 3, but could still be
9713 // theoretically possible for hand-written render functions.
9714 // the solution: we save the timestamp when a handler is attached,
9715 // and also attach the timestamp to any event that was handled by vue
9716 // for the first time (to avoid inconsistent event timestamp implementations
9717 // or events fired from iframes, e.g. #2513)
9718 // The handler would only fire if the event passed to it was fired
9719 // AFTER it was attached.
9720 if (!e._vts) {
9721 e._vts = Date.now();
9722 }
9723 else if (e._vts <= invoker.attached) {
9724 return;
9725 }
9726 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* ErrorCodes.NATIVE_EVENT_HANDLER */, [e]);
9727 };
9728 invoker.value = initialValue;
9729 invoker.attached = getNow();
9730 return invoker;
9731}
9732function patchStopImmediatePropagation(e, value) {
9733 if (isArray(value)) {
9734 const originalStop = e.stopImmediatePropagation;
9735 e.stopImmediatePropagation = () => {
9736 originalStop.call(e);
9737 e._stopped = true;
9738 };
9739 return value.map(fn => (e) => !e._stopped && fn && fn(e));
9740 }
9741 else {
9742 return value;
9743 }
9744}
9745
9746const nativeOnRE = /^on[a-z]/;
9747const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9748 if (key === 'class') {
9749 patchClass(el, nextValue, isSVG);
9750 }
9751 else if (key === 'style') {
9752 patchStyle(el, prevValue, nextValue);
9753 }
9754 else if (isOn(key)) {
9755 // ignore v-model listeners
9756 if (!isModelListener(key)) {
9757 patchEvent(el, key, prevValue, nextValue, parentComponent);
9758 }
9759 }
9760 else if (key[0] === '.'
9761 ? ((key = key.slice(1)), true)
9762 : key[0] === '^'
9763 ? ((key = key.slice(1)), false)
9764 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9765 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9766 }
9767 else {
9768 // special case for <input v-model type="checkbox"> with
9769 // :true-value & :false-value
9770 // store value as dom properties since non-string values will be
9771 // stringified.
9772 if (key === 'true-value') {
9773 el._trueValue = nextValue;
9774 }
9775 else if (key === 'false-value') {
9776 el._falseValue = nextValue;
9777 }
9778 patchAttr(el, key, nextValue, isSVG);
9779 }
9780};
9781function shouldSetAsProp(el, key, value, isSVG) {
9782 if (isSVG) {
9783 // most keys must be set as attribute on svg elements to work
9784 // ...except innerHTML & textContent
9785 if (key === 'innerHTML' || key === 'textContent') {
9786 return true;
9787 }
9788 // or native onclick with function values
9789 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9790 return true;
9791 }
9792 return false;
9793 }
9794 // these are enumerated attrs, however their corresponding DOM properties
9795 // are actually booleans - this leads to setting it with a string "false"
9796 // value leading it to be coerced to `true`, so we need to always treat
9797 // them as attributes.
9798 // Note that `contentEditable` doesn't have this problem: its DOM
9799 // property is also enumerated string values.
9800 if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
9801 return false;
9802 }
9803 // #1787, #2840 form property on form elements is readonly and must be set as
9804 // attribute.
9805 if (key === 'form') {
9806 return false;
9807 }
9808 // #1526 <input list> must be set as attribute
9809 if (key === 'list' && el.tagName === 'INPUT') {
9810 return false;
9811 }
9812 // #2766 <textarea type> must be set as attribute
9813 if (key === 'type' && el.tagName === 'TEXTAREA') {
9814 return false;
9815 }
9816 // native onclick with string value, must be set as attribute
9817 if (nativeOnRE.test(key) && isString(value)) {
9818 return false;
9819 }
9820 return key in el;
9821}
9822
9823function defineCustomElement(options, hydrate) {
9824 const Comp = defineComponent(options);
9825 class VueCustomElement extends VueElement {
9826 constructor(initialProps) {
9827 super(Comp, initialProps, hydrate);
9828 }
9829 }
9830 VueCustomElement.def = Comp;
9831 return VueCustomElement;
9832}
9833const defineSSRCustomElement = ((options) => {
9834 // @ts-ignore
9835 return defineCustomElement(options, hydrate);
9836});
9837const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9838});
9839class VueElement extends BaseClass {
9840 constructor(_def, _props = {}, hydrate) {
9841 super();
9842 this._def = _def;
9843 this._props = _props;
9844 /**
9845 * @internal
9846 */
9847 this._instance = null;
9848 this._connected = false;
9849 this._resolved = false;
9850 this._numberProps = null;
9851 if (this.shadowRoot && hydrate) {
9852 hydrate(this._createVNode(), this.shadowRoot);
9853 }
9854 else {
9855 if (this.shadowRoot) {
9856 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9857 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9858 }
9859 this.attachShadow({ mode: 'open' });
9860 if (!this._def.__asyncLoader) {
9861 // for sync component defs we can immediately resolve props
9862 this._resolveProps(this._def);
9863 }
9864 }
9865 }
9866 connectedCallback() {
9867 this._connected = true;
9868 if (!this._instance) {
9869 if (this._resolved) {
9870 this._update();
9871 }
9872 else {
9873 this._resolveDef();
9874 }
9875 }
9876 }
9877 disconnectedCallback() {
9878 this._connected = false;
9879 nextTick(() => {
9880 if (!this._connected) {
9881 render(null, this.shadowRoot);
9882 this._instance = null;
9883 }
9884 });
9885 }
9886 /**
9887 * resolve inner component definition (handle possible async component)
9888 */
9889 _resolveDef() {
9890 this._resolved = true;
9891 // set initial attrs
9892 for (let i = 0; i < this.attributes.length; i++) {
9893 this._setAttr(this.attributes[i].name);
9894 }
9895 // watch future attr changes
9896 new MutationObserver(mutations => {
9897 for (const m of mutations) {
9898 this._setAttr(m.attributeName);
9899 }
9900 }).observe(this, { attributes: true });
9901 const resolve = (def, isAsync = false) => {
9902 const { props, styles } = def;
9903 // cast Number-type props set before resolve
9904 let numberProps;
9905 if (props && !isArray(props)) {
9906 for (const key in props) {
9907 const opt = props[key];
9908 if (opt === Number || (opt && opt.type === Number)) {
9909 if (key in this._props) {
9910 this._props[key] = toNumber(this._props[key]);
9911 }
9912 (numberProps || (numberProps = Object.create(null)))[camelize(key)] = true;
9913 }
9914 }
9915 }
9916 this._numberProps = numberProps;
9917 if (isAsync) {
9918 // defining getter/setters on prototype
9919 // for sync defs, this already happened in the constructor
9920 this._resolveProps(def);
9921 }
9922 // apply CSS
9923 this._applyStyles(styles);
9924 // initial render
9925 this._update();
9926 };
9927 const asyncDef = this._def.__asyncLoader;
9928 if (asyncDef) {
9929 asyncDef().then(def => resolve(def, true));
9930 }
9931 else {
9932 resolve(this._def);
9933 }
9934 }
9935 _resolveProps(def) {
9936 const { props } = def;
9937 const declaredPropKeys = isArray(props) ? props : Object.keys(props || {});
9938 // check if there are props set pre-upgrade or connect
9939 for (const key of Object.keys(this)) {
9940 if (key[0] !== '_' && declaredPropKeys.includes(key)) {
9941 this._setProp(key, this[key], true, false);
9942 }
9943 }
9944 // defining getter/setters on prototype
9945 for (const key of declaredPropKeys.map(camelize)) {
9946 Object.defineProperty(this, key, {
9947 get() {
9948 return this._getProp(key);
9949 },
9950 set(val) {
9951 this._setProp(key, val);
9952 }
9953 });
9954 }
9955 }
9956 _setAttr(key) {
9957 let value = this.getAttribute(key);
9958 const camelKey = camelize(key);
9959 if (this._numberProps && this._numberProps[camelKey]) {
9960 value = toNumber(value);
9961 }
9962 this._setProp(camelKey, value, false);
9963 }
9964 /**
9965 * @internal
9966 */
9967 _getProp(key) {
9968 return this._props[key];
9969 }
9970 /**
9971 * @internal
9972 */
9973 _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
9974 if (val !== this._props[key]) {
9975 this._props[key] = val;
9976 if (shouldUpdate && this._instance) {
9977 this._update();
9978 }
9979 // reflect
9980 if (shouldReflect) {
9981 if (val === true) {
9982 this.setAttribute(hyphenate(key), '');
9983 }
9984 else if (typeof val === 'string' || typeof val === 'number') {
9985 this.setAttribute(hyphenate(key), val + '');
9986 }
9987 else if (!val) {
9988 this.removeAttribute(hyphenate(key));
9989 }
9990 }
9991 }
9992 }
9993 _update() {
9994 render(this._createVNode(), this.shadowRoot);
9995 }
9996 _createVNode() {
9997 const vnode = createVNode(this._def, extend({}, this._props));
9998 if (!this._instance) {
9999 vnode.ce = instance => {
10000 this._instance = instance;
10001 instance.isCE = true;
10002 // HMR
10003 {
10004 instance.ceReload = newStyles => {
10005 // always reset styles
10006 if (this._styles) {
10007 this._styles.forEach(s => this.shadowRoot.removeChild(s));
10008 this._styles.length = 0;
10009 }
10010 this._applyStyles(newStyles);
10011 this._instance = null;
10012 this._update();
10013 };
10014 }
10015 const dispatch = (event, args) => {
10016 this.dispatchEvent(new CustomEvent(event, {
10017 detail: args
10018 }));
10019 };
10020 // intercept emit
10021 instance.emit = (event, ...args) => {
10022 // dispatch both the raw and hyphenated versions of an event
10023 // to match Vue behavior
10024 dispatch(event, args);
10025 if (hyphenate(event) !== event) {
10026 dispatch(hyphenate(event), args);
10027 }
10028 };
10029 // locate nearest Vue custom element parent for provide/inject
10030 let parent = this;
10031 while ((parent =
10032 parent && (parent.parentNode || parent.host))) {
10033 if (parent instanceof VueElement) {
10034 instance.parent = parent._instance;
10035 instance.provides = parent._instance.provides;
10036 break;
10037 }
10038 }
10039 };
10040 }
10041 return vnode;
10042 }
10043 _applyStyles(styles) {
10044 if (styles) {
10045 styles.forEach(css => {
10046 const s = document.createElement('style');
10047 s.textContent = css;
10048 this.shadowRoot.appendChild(s);
10049 // record for HMR
10050 {
10051 (this._styles || (this._styles = [])).push(s);
10052 }
10053 });
10054 }
10055 }
10056}
10057
10058function useCssModule(name = '$style') {
10059 /* istanbul ignore else */
10060 {
10061 const instance = getCurrentInstance();
10062 if (!instance) {
10063 warn$1(`useCssModule must be called inside setup()`);
10064 return EMPTY_OBJ;
10065 }
10066 const modules = instance.type.__cssModules;
10067 if (!modules) {
10068 warn$1(`Current instance does not have CSS modules injected.`);
10069 return EMPTY_OBJ;
10070 }
10071 const mod = modules[name];
10072 if (!mod) {
10073 warn$1(`Current instance does not have CSS module named "${name}".`);
10074 return EMPTY_OBJ;
10075 }
10076 return mod;
10077 }
10078}
10079
10080/**
10081 * Runtime helper for SFC's CSS variable injection feature.
10082 * @private
10083 */
10084function useCssVars(getter) {
10085 const instance = getCurrentInstance();
10086 /* istanbul ignore next */
10087 if (!instance) {
10088 warn$1(`useCssVars is called without current active component instance.`);
10089 return;
10090 }
10091 const updateTeleports = (instance.ut = (vars = getter(instance.proxy)) => {
10092 Array.from(document.querySelectorAll(`[data-v-owner="${instance.uid}"]`)).forEach(node => setVarsOnNode(node, vars));
10093 });
10094 const setVars = () => {
10095 const vars = getter(instance.proxy);
10096 setVarsOnVNode(instance.subTree, vars);
10097 updateTeleports(vars);
10098 };
10099 watchPostEffect(setVars);
10100 onMounted(() => {
10101 const ob = new MutationObserver(setVars);
10102 ob.observe(instance.subTree.el.parentNode, { childList: true });
10103 onUnmounted(() => ob.disconnect());
10104 });
10105}
10106function setVarsOnVNode(vnode, vars) {
10107 if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
10108 const suspense = vnode.suspense;
10109 vnode = suspense.activeBranch;
10110 if (suspense.pendingBranch && !suspense.isHydrating) {
10111 suspense.effects.push(() => {
10112 setVarsOnVNode(suspense.activeBranch, vars);
10113 });
10114 }
10115 }
10116 // drill down HOCs until it's a non-component vnode
10117 while (vnode.component) {
10118 vnode = vnode.component.subTree;
10119 }
10120 if (vnode.shapeFlag & 1 /* ShapeFlags.ELEMENT */ && vnode.el) {
10121 setVarsOnNode(vnode.el, vars);
10122 }
10123 else if (vnode.type === Fragment) {
10124 vnode.children.forEach(c => setVarsOnVNode(c, vars));
10125 }
10126 else if (vnode.type === Static) {
10127 let { el, anchor } = vnode;
10128 while (el) {
10129 setVarsOnNode(el, vars);
10130 if (el === anchor)
10131 break;
10132 el = el.nextSibling;
10133 }
10134 }
10135}
10136function setVarsOnNode(el, vars) {
10137 if (el.nodeType === 1) {
10138 const style = el.style;
10139 for (const key in vars) {
10140 style.setProperty(`--${key}`, vars[key]);
10141 }
10142 }
10143}
10144
10145const TRANSITION = 'transition';
10146const ANIMATION = 'animation';
10147// DOM Transition is a higher-order-component based on the platform-agnostic
10148// base Transition component, with DOM-specific logic.
10149const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
10150Transition.displayName = 'Transition';
10151const DOMTransitionPropsValidators = {
10152 name: String,
10153 type: String,
10154 css: {
10155 type: Boolean,
10156 default: true
10157 },
10158 duration: [String, Number, Object],
10159 enterFromClass: String,
10160 enterActiveClass: String,
10161 enterToClass: String,
10162 appearFromClass: String,
10163 appearActiveClass: String,
10164 appearToClass: String,
10165 leaveFromClass: String,
10166 leaveActiveClass: String,
10167 leaveToClass: String
10168};
10169const TransitionPropsValidators = (Transition.props =
10170 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
10171/**
10172 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
10173 * with custom HOCs.
10174 */
10175const callHook$1 = (hook, args = []) => {
10176 if (isArray(hook)) {
10177 hook.forEach(h => h(...args));
10178 }
10179 else if (hook) {
10180 hook(...args);
10181 }
10182};
10183/**
10184 * Check if a hook expects a callback (2nd arg), which means the user
10185 * intends to explicitly control the end of the transition.
10186 */
10187const hasExplicitCallback = (hook) => {
10188 return hook
10189 ? isArray(hook)
10190 ? hook.some(h => h.length > 1)
10191 : hook.length > 1
10192 : false;
10193};
10194function resolveTransitionProps(rawProps) {
10195 const baseProps = {};
10196 for (const key in rawProps) {
10197 if (!(key in DOMTransitionPropsValidators)) {
10198 baseProps[key] = rawProps[key];
10199 }
10200 }
10201 if (rawProps.css === false) {
10202 return baseProps;
10203 }
10204 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;
10205 const durations = normalizeDuration(duration);
10206 const enterDuration = durations && durations[0];
10207 const leaveDuration = durations && durations[1];
10208 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
10209 const finishEnter = (el, isAppear, done) => {
10210 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
10211 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
10212 done && done();
10213 };
10214 const finishLeave = (el, done) => {
10215 el._isLeaving = false;
10216 removeTransitionClass(el, leaveFromClass);
10217 removeTransitionClass(el, leaveToClass);
10218 removeTransitionClass(el, leaveActiveClass);
10219 done && done();
10220 };
10221 const makeEnterHook = (isAppear) => {
10222 return (el, done) => {
10223 const hook = isAppear ? onAppear : onEnter;
10224 const resolve = () => finishEnter(el, isAppear, done);
10225 callHook$1(hook, [el, resolve]);
10226 nextFrame(() => {
10227 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
10228 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
10229 if (!hasExplicitCallback(hook)) {
10230 whenTransitionEnds(el, type, enterDuration, resolve);
10231 }
10232 });
10233 };
10234 };
10235 return extend(baseProps, {
10236 onBeforeEnter(el) {
10237 callHook$1(onBeforeEnter, [el]);
10238 addTransitionClass(el, enterFromClass);
10239 addTransitionClass(el, enterActiveClass);
10240 },
10241 onBeforeAppear(el) {
10242 callHook$1(onBeforeAppear, [el]);
10243 addTransitionClass(el, appearFromClass);
10244 addTransitionClass(el, appearActiveClass);
10245 },
10246 onEnter: makeEnterHook(false),
10247 onAppear: makeEnterHook(true),
10248 onLeave(el, done) {
10249 el._isLeaving = true;
10250 const resolve = () => finishLeave(el, done);
10251 addTransitionClass(el, leaveFromClass);
10252 // force reflow so *-leave-from classes immediately take effect (#2593)
10253 forceReflow();
10254 addTransitionClass(el, leaveActiveClass);
10255 nextFrame(() => {
10256 if (!el._isLeaving) {
10257 // cancelled
10258 return;
10259 }
10260 removeTransitionClass(el, leaveFromClass);
10261 addTransitionClass(el, leaveToClass);
10262 if (!hasExplicitCallback(onLeave)) {
10263 whenTransitionEnds(el, type, leaveDuration, resolve);
10264 }
10265 });
10266 callHook$1(onLeave, [el, resolve]);
10267 },
10268 onEnterCancelled(el) {
10269 finishEnter(el, false);
10270 callHook$1(onEnterCancelled, [el]);
10271 },
10272 onAppearCancelled(el) {
10273 finishEnter(el, true);
10274 callHook$1(onAppearCancelled, [el]);
10275 },
10276 onLeaveCancelled(el) {
10277 finishLeave(el);
10278 callHook$1(onLeaveCancelled, [el]);
10279 }
10280 });
10281}
10282function normalizeDuration(duration) {
10283 if (duration == null) {
10284 return null;
10285 }
10286 else if (isObject(duration)) {
10287 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10288 }
10289 else {
10290 const n = NumberOf(duration);
10291 return [n, n];
10292 }
10293}
10294function NumberOf(val) {
10295 const res = toNumber(val);
10296 validateDuration(res);
10297 return res;
10298}
10299function validateDuration(val) {
10300 if (typeof val !== 'number') {
10301 warn$1(`<transition> explicit duration is not a valid number - ` +
10302 `got ${JSON.stringify(val)}.`);
10303 }
10304 else if (isNaN(val)) {
10305 warn$1(`<transition> explicit duration is NaN - ` +
10306 'the duration expression might be incorrect.');
10307 }
10308}
10309function addTransitionClass(el, cls) {
10310 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10311 (el._vtc ||
10312 (el._vtc = new Set())).add(cls);
10313}
10314function removeTransitionClass(el, cls) {
10315 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10316 const { _vtc } = el;
10317 if (_vtc) {
10318 _vtc.delete(cls);
10319 if (!_vtc.size) {
10320 el._vtc = undefined;
10321 }
10322 }
10323}
10324function nextFrame(cb) {
10325 requestAnimationFrame(() => {
10326 requestAnimationFrame(cb);
10327 });
10328}
10329let endId = 0;
10330function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10331 const id = (el._endId = ++endId);
10332 const resolveIfNotStale = () => {
10333 if (id === el._endId) {
10334 resolve();
10335 }
10336 };
10337 if (explicitTimeout) {
10338 return setTimeout(resolveIfNotStale, explicitTimeout);
10339 }
10340 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10341 if (!type) {
10342 return resolve();
10343 }
10344 const endEvent = type + 'end';
10345 let ended = 0;
10346 const end = () => {
10347 el.removeEventListener(endEvent, onEnd);
10348 resolveIfNotStale();
10349 };
10350 const onEnd = (e) => {
10351 if (e.target === el && ++ended >= propCount) {
10352 end();
10353 }
10354 };
10355 setTimeout(() => {
10356 if (ended < propCount) {
10357 end();
10358 }
10359 }, timeout + 1);
10360 el.addEventListener(endEvent, onEnd);
10361}
10362function getTransitionInfo(el, expectedType) {
10363 const styles = window.getComputedStyle(el);
10364 // JSDOM may return undefined for transition properties
10365 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10366 const transitionDelays = getStyleProperties(`${TRANSITION}Delay`);
10367 const transitionDurations = getStyleProperties(`${TRANSITION}Duration`);
10368 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10369 const animationDelays = getStyleProperties(`${ANIMATION}Delay`);
10370 const animationDurations = getStyleProperties(`${ANIMATION}Duration`);
10371 const animationTimeout = getTimeout(animationDelays, animationDurations);
10372 let type = null;
10373 let timeout = 0;
10374 let propCount = 0;
10375 /* istanbul ignore if */
10376 if (expectedType === TRANSITION) {
10377 if (transitionTimeout > 0) {
10378 type = TRANSITION;
10379 timeout = transitionTimeout;
10380 propCount = transitionDurations.length;
10381 }
10382 }
10383 else if (expectedType === ANIMATION) {
10384 if (animationTimeout > 0) {
10385 type = ANIMATION;
10386 timeout = animationTimeout;
10387 propCount = animationDurations.length;
10388 }
10389 }
10390 else {
10391 timeout = Math.max(transitionTimeout, animationTimeout);
10392 type =
10393 timeout > 0
10394 ? transitionTimeout > animationTimeout
10395 ? TRANSITION
10396 : ANIMATION
10397 : null;
10398 propCount = type
10399 ? type === TRANSITION
10400 ? transitionDurations.length
10401 : animationDurations.length
10402 : 0;
10403 }
10404 const hasTransform = type === TRANSITION &&
10405 /\b(transform|all)(,|$)/.test(getStyleProperties(`${TRANSITION}Property`).toString());
10406 return {
10407 type,
10408 timeout,
10409 propCount,
10410 hasTransform
10411 };
10412}
10413function getTimeout(delays, durations) {
10414 while (delays.length < durations.length) {
10415 delays = delays.concat(delays);
10416 }
10417 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10418}
10419// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10420// numbers in a locale-dependent way, using a comma instead of a dot.
10421// If comma is not replaced with a dot, the input will be rounded down
10422// (i.e. acting as a floor function) causing unexpected behaviors
10423function toMs(s) {
10424 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10425}
10426// synchronously force layout to put elements into a certain state
10427function forceReflow() {
10428 return document.body.offsetHeight;
10429}
10430
10431const positionMap = new WeakMap();
10432const newPositionMap = new WeakMap();
10433const TransitionGroupImpl = {
10434 name: 'TransitionGroup',
10435 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10436 tag: String,
10437 moveClass: String
10438 }),
10439 setup(props, { slots }) {
10440 const instance = getCurrentInstance();
10441 const state = useTransitionState();
10442 let prevChildren;
10443 let children;
10444 onUpdated(() => {
10445 // children is guaranteed to exist after initial render
10446 if (!prevChildren.length) {
10447 return;
10448 }
10449 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10450 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10451 return;
10452 }
10453 // we divide the work into three loops to avoid mixing DOM reads and writes
10454 // in each iteration - which helps prevent layout thrashing.
10455 prevChildren.forEach(callPendingCbs);
10456 prevChildren.forEach(recordPosition);
10457 const movedChildren = prevChildren.filter(applyTranslation);
10458 // force reflow to put everything in position
10459 forceReflow();
10460 movedChildren.forEach(c => {
10461 const el = c.el;
10462 const style = el.style;
10463 addTransitionClass(el, moveClass);
10464 style.transform = style.webkitTransform = style.transitionDuration = '';
10465 const cb = (el._moveCb = (e) => {
10466 if (e && e.target !== el) {
10467 return;
10468 }
10469 if (!e || /transform$/.test(e.propertyName)) {
10470 el.removeEventListener('transitionend', cb);
10471 el._moveCb = null;
10472 removeTransitionClass(el, moveClass);
10473 }
10474 });
10475 el.addEventListener('transitionend', cb);
10476 });
10477 });
10478 return () => {
10479 const rawProps = toRaw(props);
10480 const cssTransitionProps = resolveTransitionProps(rawProps);
10481 let tag = rawProps.tag || Fragment;
10482 prevChildren = children;
10483 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10484 for (let i = 0; i < children.length; i++) {
10485 const child = children[i];
10486 if (child.key != null) {
10487 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10488 }
10489 else {
10490 warn$1(`<TransitionGroup> children must be keyed.`);
10491 }
10492 }
10493 if (prevChildren) {
10494 for (let i = 0; i < prevChildren.length; i++) {
10495 const child = prevChildren[i];
10496 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10497 positionMap.set(child, child.el.getBoundingClientRect());
10498 }
10499 }
10500 return createVNode(tag, null, children);
10501 };
10502 }
10503};
10504const TransitionGroup = TransitionGroupImpl;
10505function callPendingCbs(c) {
10506 const el = c.el;
10507 if (el._moveCb) {
10508 el._moveCb();
10509 }
10510 if (el._enterCb) {
10511 el._enterCb();
10512 }
10513}
10514function recordPosition(c) {
10515 newPositionMap.set(c, c.el.getBoundingClientRect());
10516}
10517function applyTranslation(c) {
10518 const oldPos = positionMap.get(c);
10519 const newPos = newPositionMap.get(c);
10520 const dx = oldPos.left - newPos.left;
10521 const dy = oldPos.top - newPos.top;
10522 if (dx || dy) {
10523 const s = c.el.style;
10524 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10525 s.transitionDuration = '0s';
10526 return c;
10527 }
10528}
10529function hasCSSTransform(el, root, moveClass) {
10530 // Detect whether an element with the move class applied has
10531 // CSS transitions. Since the element may be inside an entering
10532 // transition at this very moment, we make a clone of it and remove
10533 // all other transition classes applied to ensure only the move class
10534 // is applied.
10535 const clone = el.cloneNode();
10536 if (el._vtc) {
10537 el._vtc.forEach(cls => {
10538 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10539 });
10540 }
10541 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10542 clone.style.display = 'none';
10543 const container = (root.nodeType === 1 ? root : root.parentNode);
10544 container.appendChild(clone);
10545 const { hasTransform } = getTransitionInfo(clone);
10546 container.removeChild(clone);
10547 return hasTransform;
10548}
10549
10550const getModelAssigner = (vnode) => {
10551 const fn = vnode.props['onUpdate:modelValue'] ||
10552 (false );
10553 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10554};
10555function onCompositionStart(e) {
10556 e.target.composing = true;
10557}
10558function onCompositionEnd(e) {
10559 const target = e.target;
10560 if (target.composing) {
10561 target.composing = false;
10562 target.dispatchEvent(new Event('input'));
10563 }
10564}
10565// We are exporting the v-model runtime directly as vnode hooks so that it can
10566// be tree-shaken in case v-model is never used.
10567const vModelText = {
10568 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10569 el._assign = getModelAssigner(vnode);
10570 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10571 addEventListener(el, lazy ? 'change' : 'input', e => {
10572 if (e.target.composing)
10573 return;
10574 let domValue = el.value;
10575 if (trim) {
10576 domValue = domValue.trim();
10577 }
10578 if (castToNumber) {
10579 domValue = toNumber(domValue);
10580 }
10581 el._assign(domValue);
10582 });
10583 if (trim) {
10584 addEventListener(el, 'change', () => {
10585 el.value = el.value.trim();
10586 });
10587 }
10588 if (!lazy) {
10589 addEventListener(el, 'compositionstart', onCompositionStart);
10590 addEventListener(el, 'compositionend', onCompositionEnd);
10591 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10592 // switching focus before confirming composition choice
10593 // this also fixes the issue where some browsers e.g. iOS Chrome
10594 // fires "change" instead of "input" on autocomplete.
10595 addEventListener(el, 'change', onCompositionEnd);
10596 }
10597 },
10598 // set value on mounted so it's after min/max for type="range"
10599 mounted(el, { value }) {
10600 el.value = value == null ? '' : value;
10601 },
10602 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10603 el._assign = getModelAssigner(vnode);
10604 // avoid clearing unresolved text. #2302
10605 if (el.composing)
10606 return;
10607 if (document.activeElement === el && el.type !== 'range') {
10608 if (lazy) {
10609 return;
10610 }
10611 if (trim && el.value.trim() === value) {
10612 return;
10613 }
10614 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10615 return;
10616 }
10617 }
10618 const newValue = value == null ? '' : value;
10619 if (el.value !== newValue) {
10620 el.value = newValue;
10621 }
10622 }
10623};
10624const vModelCheckbox = {
10625 // #4096 array checkboxes need to be deep traversed
10626 deep: true,
10627 created(el, _, vnode) {
10628 el._assign = getModelAssigner(vnode);
10629 addEventListener(el, 'change', () => {
10630 const modelValue = el._modelValue;
10631 const elementValue = getValue(el);
10632 const checked = el.checked;
10633 const assign = el._assign;
10634 if (isArray(modelValue)) {
10635 const index = looseIndexOf(modelValue, elementValue);
10636 const found = index !== -1;
10637 if (checked && !found) {
10638 assign(modelValue.concat(elementValue));
10639 }
10640 else if (!checked && found) {
10641 const filtered = [...modelValue];
10642 filtered.splice(index, 1);
10643 assign(filtered);
10644 }
10645 }
10646 else if (isSet(modelValue)) {
10647 const cloned = new Set(modelValue);
10648 if (checked) {
10649 cloned.add(elementValue);
10650 }
10651 else {
10652 cloned.delete(elementValue);
10653 }
10654 assign(cloned);
10655 }
10656 else {
10657 assign(getCheckboxValue(el, checked));
10658 }
10659 });
10660 },
10661 // set initial checked on mount to wait for true-value/false-value
10662 mounted: setChecked,
10663 beforeUpdate(el, binding, vnode) {
10664 el._assign = getModelAssigner(vnode);
10665 setChecked(el, binding, vnode);
10666 }
10667};
10668function setChecked(el, { value, oldValue }, vnode) {
10669 el._modelValue = value;
10670 if (isArray(value)) {
10671 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10672 }
10673 else if (isSet(value)) {
10674 el.checked = value.has(vnode.props.value);
10675 }
10676 else if (value !== oldValue) {
10677 el.checked = looseEqual(value, getCheckboxValue(el, true));
10678 }
10679}
10680const vModelRadio = {
10681 created(el, { value }, vnode) {
10682 el.checked = looseEqual(value, vnode.props.value);
10683 el._assign = getModelAssigner(vnode);
10684 addEventListener(el, 'change', () => {
10685 el._assign(getValue(el));
10686 });
10687 },
10688 beforeUpdate(el, { value, oldValue }, vnode) {
10689 el._assign = getModelAssigner(vnode);
10690 if (value !== oldValue) {
10691 el.checked = looseEqual(value, vnode.props.value);
10692 }
10693 }
10694};
10695const vModelSelect = {
10696 // <select multiple> value need to be deep traversed
10697 deep: true,
10698 created(el, { value, modifiers: { number } }, vnode) {
10699 const isSetModel = isSet(value);
10700 addEventListener(el, 'change', () => {
10701 const selectedVal = Array.prototype.filter
10702 .call(el.options, (o) => o.selected)
10703 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10704 el._assign(el.multiple
10705 ? isSetModel
10706 ? new Set(selectedVal)
10707 : selectedVal
10708 : selectedVal[0]);
10709 });
10710 el._assign = getModelAssigner(vnode);
10711 },
10712 // set value in mounted & updated because <select> relies on its children
10713 // <option>s.
10714 mounted(el, { value }) {
10715 setSelected(el, value);
10716 },
10717 beforeUpdate(el, _binding, vnode) {
10718 el._assign = getModelAssigner(vnode);
10719 },
10720 updated(el, { value }) {
10721 setSelected(el, value);
10722 }
10723};
10724function setSelected(el, value) {
10725 const isMultiple = el.multiple;
10726 if (isMultiple && !isArray(value) && !isSet(value)) {
10727 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10728 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10729 return;
10730 }
10731 for (let i = 0, l = el.options.length; i < l; i++) {
10732 const option = el.options[i];
10733 const optionValue = getValue(option);
10734 if (isMultiple) {
10735 if (isArray(value)) {
10736 option.selected = looseIndexOf(value, optionValue) > -1;
10737 }
10738 else {
10739 option.selected = value.has(optionValue);
10740 }
10741 }
10742 else {
10743 if (looseEqual(getValue(option), value)) {
10744 if (el.selectedIndex !== i)
10745 el.selectedIndex = i;
10746 return;
10747 }
10748 }
10749 }
10750 if (!isMultiple && el.selectedIndex !== -1) {
10751 el.selectedIndex = -1;
10752 }
10753}
10754// retrieve raw value set via :value bindings
10755function getValue(el) {
10756 return '_value' in el ? el._value : el.value;
10757}
10758// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10759function getCheckboxValue(el, checked) {
10760 const key = checked ? '_trueValue' : '_falseValue';
10761 return key in el ? el[key] : checked;
10762}
10763const vModelDynamic = {
10764 created(el, binding, vnode) {
10765 callModelHook(el, binding, vnode, null, 'created');
10766 },
10767 mounted(el, binding, vnode) {
10768 callModelHook(el, binding, vnode, null, 'mounted');
10769 },
10770 beforeUpdate(el, binding, vnode, prevVNode) {
10771 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10772 },
10773 updated(el, binding, vnode, prevVNode) {
10774 callModelHook(el, binding, vnode, prevVNode, 'updated');
10775 }
10776};
10777function resolveDynamicModel(tagName, type) {
10778 switch (tagName) {
10779 case 'SELECT':
10780 return vModelSelect;
10781 case 'TEXTAREA':
10782 return vModelText;
10783 default:
10784 switch (type) {
10785 case 'checkbox':
10786 return vModelCheckbox;
10787 case 'radio':
10788 return vModelRadio;
10789 default:
10790 return vModelText;
10791 }
10792 }
10793}
10794function callModelHook(el, binding, vnode, prevVNode, hook) {
10795 const modelToUse = resolveDynamicModel(el.tagName, vnode.props && vnode.props.type);
10796 const fn = modelToUse[hook];
10797 fn && fn(el, binding, vnode, prevVNode);
10798}
10799
10800const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10801const modifierGuards = {
10802 stop: e => e.stopPropagation(),
10803 prevent: e => e.preventDefault(),
10804 self: e => e.target !== e.currentTarget,
10805 ctrl: e => !e.ctrlKey,
10806 shift: e => !e.shiftKey,
10807 alt: e => !e.altKey,
10808 meta: e => !e.metaKey,
10809 left: e => 'button' in e && e.button !== 0,
10810 middle: e => 'button' in e && e.button !== 1,
10811 right: e => 'button' in e && e.button !== 2,
10812 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10813};
10814/**
10815 * @private
10816 */
10817const withModifiers = (fn, modifiers) => {
10818 return (event, ...args) => {
10819 for (let i = 0; i < modifiers.length; i++) {
10820 const guard = modifierGuards[modifiers[i]];
10821 if (guard && guard(event, modifiers))
10822 return;
10823 }
10824 return fn(event, ...args);
10825 };
10826};
10827// Kept for 2.x compat.
10828// Note: IE11 compat for `spacebar` and `del` is removed for now.
10829const keyNames = {
10830 esc: 'escape',
10831 space: ' ',
10832 up: 'arrow-up',
10833 left: 'arrow-left',
10834 right: 'arrow-right',
10835 down: 'arrow-down',
10836 delete: 'backspace'
10837};
10838/**
10839 * @private
10840 */
10841const withKeys = (fn, modifiers) => {
10842 return (event) => {
10843 if (!('key' in event)) {
10844 return;
10845 }
10846 const eventKey = hyphenate(event.key);
10847 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10848 return fn(event);
10849 }
10850 };
10851};
10852
10853const vShow = {
10854 beforeMount(el, { value }, { transition }) {
10855 el._vod = el.style.display === 'none' ? '' : el.style.display;
10856 if (transition && value) {
10857 transition.beforeEnter(el);
10858 }
10859 else {
10860 setDisplay(el, value);
10861 }
10862 },
10863 mounted(el, { value }, { transition }) {
10864 if (transition && value) {
10865 transition.enter(el);
10866 }
10867 },
10868 updated(el, { value, oldValue }, { transition }) {
10869 if (!value === !oldValue)
10870 return;
10871 if (transition) {
10872 if (value) {
10873 transition.beforeEnter(el);
10874 setDisplay(el, true);
10875 transition.enter(el);
10876 }
10877 else {
10878 transition.leave(el, () => {
10879 setDisplay(el, false);
10880 });
10881 }
10882 }
10883 else {
10884 setDisplay(el, value);
10885 }
10886 },
10887 beforeUnmount(el, { value }) {
10888 setDisplay(el, value);
10889 }
10890};
10891function setDisplay(el, value) {
10892 el.style.display = value ? el._vod : 'none';
10893}
10894
10895const rendererOptions = /*#__PURE__*/ extend({ patchProp }, nodeOps);
10896// lazy create the renderer - this makes core renderer logic tree-shakable
10897// in case the user only imports reactivity utilities from Vue.
10898let renderer;
10899let enabledHydration = false;
10900function ensureRenderer() {
10901 return (renderer ||
10902 (renderer = createRenderer(rendererOptions)));
10903}
10904function ensureHydrationRenderer() {
10905 renderer = enabledHydration
10906 ? renderer
10907 : createHydrationRenderer(rendererOptions);
10908 enabledHydration = true;
10909 return renderer;
10910}
10911// use explicit type casts here to avoid import() calls in rolled-up d.ts
10912const render = ((...args) => {
10913 ensureRenderer().render(...args);
10914});
10915const hydrate = ((...args) => {
10916 ensureHydrationRenderer().hydrate(...args);
10917});
10918const createApp = ((...args) => {
10919 const app = ensureRenderer().createApp(...args);
10920 {
10921 injectNativeTagCheck(app);
10922 injectCompilerOptionsCheck(app);
10923 }
10924 const { mount } = app;
10925 app.mount = (containerOrSelector) => {
10926 const container = normalizeContainer(containerOrSelector);
10927 if (!container)
10928 return;
10929 const component = app._component;
10930 if (!isFunction(component) && !component.render && !component.template) {
10931 // __UNSAFE__
10932 // Reason: potential execution of JS expressions in in-DOM template.
10933 // The user must make sure the in-DOM template is trusted. If it's
10934 // rendered by the server, the template should not contain any user data.
10935 component.template = container.innerHTML;
10936 }
10937 // clear content before mounting
10938 container.innerHTML = '';
10939 const proxy = mount(container, false, container instanceof SVGElement);
10940 if (container instanceof Element) {
10941 container.removeAttribute('v-cloak');
10942 container.setAttribute('data-v-app', '');
10943 }
10944 return proxy;
10945 };
10946 return app;
10947});
10948const createSSRApp = ((...args) => {
10949 const app = ensureHydrationRenderer().createApp(...args);
10950 {
10951 injectNativeTagCheck(app);
10952 injectCompilerOptionsCheck(app);
10953 }
10954 const { mount } = app;
10955 app.mount = (containerOrSelector) => {
10956 const container = normalizeContainer(containerOrSelector);
10957 if (container) {
10958 return mount(container, true, container instanceof SVGElement);
10959 }
10960 };
10961 return app;
10962});
10963function injectNativeTagCheck(app) {
10964 // Inject `isNativeTag`
10965 // this is used for component name validation (dev only)
10966 Object.defineProperty(app.config, 'isNativeTag', {
10967 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10968 writable: false
10969 });
10970}
10971// dev only
10972function injectCompilerOptionsCheck(app) {
10973 if (isRuntimeOnly()) {
10974 const isCustomElement = app.config.isCustomElement;
10975 Object.defineProperty(app.config, 'isCustomElement', {
10976 get() {
10977 return isCustomElement;
10978 },
10979 set() {
10980 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10981 `\`compilerOptions.isCustomElement\` instead.`);
10982 }
10983 });
10984 const compilerOptions = app.config.compilerOptions;
10985 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10986 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10987 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10988 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10989 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10990 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10991 `- 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`;
10992 Object.defineProperty(app.config, 'compilerOptions', {
10993 get() {
10994 warn$1(msg);
10995 return compilerOptions;
10996 },
10997 set() {
10998 warn$1(msg);
10999 }
11000 });
11001 }
11002}
11003function normalizeContainer(container) {
11004 if (isString(container)) {
11005 const res = document.querySelector(container);
11006 if (!res) {
11007 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
11008 }
11009 return res;
11010 }
11011 if (window.ShadowRoot &&
11012 container instanceof window.ShadowRoot &&
11013 container.mode === 'closed') {
11014 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
11015 }
11016 return container;
11017}
11018/**
11019 * @internal
11020 */
11021const initDirectivesForSSR = NOOP;
11022
11023var runtimeDom = /*#__PURE__*/Object.freeze({
11024 __proto__: null,
11025 render: render,
11026 hydrate: hydrate,
11027 createApp: createApp,
11028 createSSRApp: createSSRApp,
11029 initDirectivesForSSR: initDirectivesForSSR,
11030 defineCustomElement: defineCustomElement,
11031 defineSSRCustomElement: defineSSRCustomElement,
11032 VueElement: VueElement,
11033 useCssModule: useCssModule,
11034 useCssVars: useCssVars,
11035 Transition: Transition,
11036 TransitionGroup: TransitionGroup,
11037 vModelText: vModelText,
11038 vModelCheckbox: vModelCheckbox,
11039 vModelRadio: vModelRadio,
11040 vModelSelect: vModelSelect,
11041 vModelDynamic: vModelDynamic,
11042 withModifiers: withModifiers,
11043 withKeys: withKeys,
11044 vShow: vShow,
11045 reactive: reactive,
11046 ref: ref,
11047 readonly: readonly,
11048 unref: unref,
11049 proxyRefs: proxyRefs,
11050 isRef: isRef,
11051 toRef: toRef,
11052 toRefs: toRefs,
11053 isProxy: isProxy,
11054 isReactive: isReactive,
11055 isReadonly: isReadonly,
11056 isShallow: isShallow,
11057 customRef: customRef,
11058 triggerRef: triggerRef,
11059 shallowRef: shallowRef,
11060 shallowReactive: shallowReactive,
11061 shallowReadonly: shallowReadonly,
11062 markRaw: markRaw,
11063 toRaw: toRaw,
11064 effect: effect,
11065 stop: stop,
11066 ReactiveEffect: ReactiveEffect,
11067 effectScope: effectScope,
11068 EffectScope: EffectScope,
11069 getCurrentScope: getCurrentScope,
11070 onScopeDispose: onScopeDispose,
11071 computed: computed$1,
11072 watch: watch,
11073 watchEffect: watchEffect,
11074 watchPostEffect: watchPostEffect,
11075 watchSyncEffect: watchSyncEffect,
11076 onBeforeMount: onBeforeMount,
11077 onMounted: onMounted,
11078 onBeforeUpdate: onBeforeUpdate,
11079 onUpdated: onUpdated,
11080 onBeforeUnmount: onBeforeUnmount,
11081 onUnmounted: onUnmounted,
11082 onActivated: onActivated,
11083 onDeactivated: onDeactivated,
11084 onRenderTracked: onRenderTracked,
11085 onRenderTriggered: onRenderTriggered,
11086 onErrorCaptured: onErrorCaptured,
11087 onServerPrefetch: onServerPrefetch,
11088 provide: provide,
11089 inject: inject,
11090 nextTick: nextTick,
11091 defineComponent: defineComponent,
11092 defineAsyncComponent: defineAsyncComponent,
11093 useAttrs: useAttrs,
11094 useSlots: useSlots,
11095 defineProps: defineProps,
11096 defineEmits: defineEmits,
11097 defineExpose: defineExpose,
11098 withDefaults: withDefaults,
11099 mergeDefaults: mergeDefaults,
11100 createPropsRestProxy: createPropsRestProxy,
11101 withAsyncContext: withAsyncContext,
11102 getCurrentInstance: getCurrentInstance,
11103 h: h,
11104 createVNode: createVNode,
11105 cloneVNode: cloneVNode,
11106 mergeProps: mergeProps,
11107 isVNode: isVNode,
11108 Fragment: Fragment,
11109 Text: Text,
11110 Comment: Comment,
11111 Static: Static,
11112 Teleport: Teleport,
11113 Suspense: Suspense,
11114 KeepAlive: KeepAlive,
11115 BaseTransition: BaseTransition,
11116 withDirectives: withDirectives,
11117 useSSRContext: useSSRContext,
11118 ssrContextKey: ssrContextKey,
11119 createRenderer: createRenderer,
11120 createHydrationRenderer: createHydrationRenderer,
11121 queuePostFlushCb: queuePostFlushCb,
11122 warn: warn$1,
11123 handleError: handleError,
11124 callWithErrorHandling: callWithErrorHandling,
11125 callWithAsyncErrorHandling: callWithAsyncErrorHandling,
11126 resolveComponent: resolveComponent,
11127 resolveDirective: resolveDirective,
11128 resolveDynamicComponent: resolveDynamicComponent,
11129 registerRuntimeCompiler: registerRuntimeCompiler,
11130 isRuntimeOnly: isRuntimeOnly,
11131 useTransitionState: useTransitionState,
11132 resolveTransitionHooks: resolveTransitionHooks,
11133 setTransitionHooks: setTransitionHooks,
11134 getTransitionRawChildren: getTransitionRawChildren,
11135 initCustomFormatter: initCustomFormatter,
11136 get devtools () { return devtools; },
11137 setDevtoolsHook: setDevtoolsHook,
11138 withCtx: withCtx,
11139 pushScopeId: pushScopeId,
11140 popScopeId: popScopeId,
11141 withScopeId: withScopeId,
11142 renderList: renderList,
11143 toHandlers: toHandlers,
11144 renderSlot: renderSlot,
11145 createSlots: createSlots,
11146 withMemo: withMemo,
11147 isMemoSame: isMemoSame,
11148 openBlock: openBlock,
11149 createBlock: createBlock,
11150 setBlockTracking: setBlockTracking,
11151 createTextVNode: createTextVNode,
11152 createCommentVNode: createCommentVNode,
11153 createStaticVNode: createStaticVNode,
11154 createElementVNode: createBaseVNode,
11155 createElementBlock: createElementBlock,
11156 guardReactiveProps: guardReactiveProps,
11157 toDisplayString: toDisplayString,
11158 camelize: camelize,
11159 capitalize: capitalize,
11160 toHandlerKey: toHandlerKey,
11161 normalizeProps: normalizeProps,
11162 normalizeClass: normalizeClass,
11163 normalizeStyle: normalizeStyle,
11164 transformVNodeArgs: transformVNodeArgs,
11165 version: version,
11166 ssrUtils: ssrUtils,
11167 resolveFilter: resolveFilter,
11168 compatUtils: compatUtils
11169});
11170
11171function initDev() {
11172 {
11173 {
11174 console.info(`You are running a development build of Vue.\n` +
11175 `Make sure to use the production build (*.prod.js) when deploying for production.`);
11176 }
11177 initCustomFormatter();
11178 }
11179}
11180
11181function defaultOnError(error) {
11182 throw error;
11183}
11184function defaultOnWarn(msg) {
11185 console.warn(`[Vue warn] ${msg.message}`);
11186}
11187function createCompilerError(code, loc, messages, additionalMessage) {
11188 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
11189 ;
11190 const error = new SyntaxError(String(msg));
11191 error.code = code;
11192 error.loc = loc;
11193 return error;
11194}
11195const errorMessages = {
11196 // parse errors
11197 [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
11198 [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
11199 [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
11200 [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
11201 [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
11202 [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
11203 [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
11204 [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
11205 [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
11206 [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
11207 [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
11208 [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
11209 [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
11210 [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
11211 [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
11212 [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
11213 [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
11214 [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
11215 [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
11216 [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
11217 [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
11218 [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
11219 [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
11220 // Vue-specific parse errors
11221 [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
11222 [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
11223 [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
11224 [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
11225 'Note that dynamic directive argument cannot contain spaces.',
11226 [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
11227 // transform errors
11228 [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
11229 [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
11230 [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
11231 [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
11232 [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
11233 [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
11234 [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
11235 [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
11236 [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
11237 [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
11238 `When there are multiple named slots, all slots should use <template> ` +
11239 `syntax to avoid scope ambiguity.`,
11240 [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
11241 [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
11242 `default slot. These children will be ignored.`,
11243 [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
11244 [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
11245 [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
11246 [43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
11247 [44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
11248 [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
11249 [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
11250 // generic errors
11251 [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
11252 [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
11253 [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
11254 [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
11255 // just to fulfill types
11256 [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
11257};
11258
11259const FRAGMENT = Symbol(`Fragment` );
11260const TELEPORT = Symbol(`Teleport` );
11261const SUSPENSE = Symbol(`Suspense` );
11262const KEEP_ALIVE = Symbol(`KeepAlive` );
11263const BASE_TRANSITION = Symbol(`BaseTransition` );
11264const OPEN_BLOCK = Symbol(`openBlock` );
11265const CREATE_BLOCK = Symbol(`createBlock` );
11266const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
11267const CREATE_VNODE = Symbol(`createVNode` );
11268const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
11269const CREATE_COMMENT = Symbol(`createCommentVNode` );
11270const CREATE_TEXT = Symbol(`createTextVNode` );
11271const CREATE_STATIC = Symbol(`createStaticVNode` );
11272const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
11273const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
11274const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
11275const RESOLVE_FILTER = Symbol(`resolveFilter` );
11276const WITH_DIRECTIVES = Symbol(`withDirectives` );
11277const RENDER_LIST = Symbol(`renderList` );
11278const RENDER_SLOT = Symbol(`renderSlot` );
11279const CREATE_SLOTS = Symbol(`createSlots` );
11280const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
11281const MERGE_PROPS = Symbol(`mergeProps` );
11282const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11283const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11284const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11285const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11286const TO_HANDLERS = Symbol(`toHandlers` );
11287const CAMELIZE = Symbol(`camelize` );
11288const CAPITALIZE = Symbol(`capitalize` );
11289const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11290const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11291const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11292const POP_SCOPE_ID = Symbol(`popScopeId` );
11293const WITH_CTX = Symbol(`withCtx` );
11294const UNREF = Symbol(`unref` );
11295const IS_REF = Symbol(`isRef` );
11296const WITH_MEMO = Symbol(`withMemo` );
11297const IS_MEMO_SAME = Symbol(`isMemoSame` );
11298// Name mapping for runtime helpers that need to be imported from 'vue' in
11299// generated code. Make sure these are correctly exported in the runtime!
11300const helperNameMap = {
11301 [FRAGMENT]: `Fragment`,
11302 [TELEPORT]: `Teleport`,
11303 [SUSPENSE]: `Suspense`,
11304 [KEEP_ALIVE]: `KeepAlive`,
11305 [BASE_TRANSITION]: `BaseTransition`,
11306 [OPEN_BLOCK]: `openBlock`,
11307 [CREATE_BLOCK]: `createBlock`,
11308 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11309 [CREATE_VNODE]: `createVNode`,
11310 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11311 [CREATE_COMMENT]: `createCommentVNode`,
11312 [CREATE_TEXT]: `createTextVNode`,
11313 [CREATE_STATIC]: `createStaticVNode`,
11314 [RESOLVE_COMPONENT]: `resolveComponent`,
11315 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11316 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11317 [RESOLVE_FILTER]: `resolveFilter`,
11318 [WITH_DIRECTIVES]: `withDirectives`,
11319 [RENDER_LIST]: `renderList`,
11320 [RENDER_SLOT]: `renderSlot`,
11321 [CREATE_SLOTS]: `createSlots`,
11322 [TO_DISPLAY_STRING]: `toDisplayString`,
11323 [MERGE_PROPS]: `mergeProps`,
11324 [NORMALIZE_CLASS]: `normalizeClass`,
11325 [NORMALIZE_STYLE]: `normalizeStyle`,
11326 [NORMALIZE_PROPS]: `normalizeProps`,
11327 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11328 [TO_HANDLERS]: `toHandlers`,
11329 [CAMELIZE]: `camelize`,
11330 [CAPITALIZE]: `capitalize`,
11331 [TO_HANDLER_KEY]: `toHandlerKey`,
11332 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11333 [PUSH_SCOPE_ID]: `pushScopeId`,
11334 [POP_SCOPE_ID]: `popScopeId`,
11335 [WITH_CTX]: `withCtx`,
11336 [UNREF]: `unref`,
11337 [IS_REF]: `isRef`,
11338 [WITH_MEMO]: `withMemo`,
11339 [IS_MEMO_SAME]: `isMemoSame`
11340};
11341function registerRuntimeHelpers(helpers) {
11342 Object.getOwnPropertySymbols(helpers).forEach(s => {
11343 helperNameMap[s] = helpers[s];
11344 });
11345}
11346
11347// AST Utilities ---------------------------------------------------------------
11348// Some expressions, e.g. sequence and conditional expressions, are never
11349// associated with template nodes, so their source locations are just a stub.
11350// Container types like CompoundExpression also don't need a real location.
11351const locStub = {
11352 source: '',
11353 start: { line: 1, column: 1, offset: 0 },
11354 end: { line: 1, column: 1, offset: 0 }
11355};
11356function createRoot(children, loc = locStub) {
11357 return {
11358 type: 0 /* NodeTypes.ROOT */,
11359 children,
11360 helpers: [],
11361 components: [],
11362 directives: [],
11363 hoists: [],
11364 imports: [],
11365 cached: 0,
11366 temps: 0,
11367 codegenNode: undefined,
11368 loc
11369 };
11370}
11371function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11372 if (context) {
11373 if (isBlock) {
11374 context.helper(OPEN_BLOCK);
11375 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11376 }
11377 else {
11378 context.helper(getVNodeHelper(context.inSSR, isComponent));
11379 }
11380 if (directives) {
11381 context.helper(WITH_DIRECTIVES);
11382 }
11383 }
11384 return {
11385 type: 13 /* NodeTypes.VNODE_CALL */,
11386 tag,
11387 props,
11388 children,
11389 patchFlag,
11390 dynamicProps,
11391 directives,
11392 isBlock,
11393 disableTracking,
11394 isComponent,
11395 loc
11396 };
11397}
11398function createArrayExpression(elements, loc = locStub) {
11399 return {
11400 type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
11401 loc,
11402 elements
11403 };
11404}
11405function createObjectExpression(properties, loc = locStub) {
11406 return {
11407 type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
11408 loc,
11409 properties
11410 };
11411}
11412function createObjectProperty(key, value) {
11413 return {
11414 type: 16 /* NodeTypes.JS_PROPERTY */,
11415 loc: locStub,
11416 key: isString(key) ? createSimpleExpression(key, true) : key,
11417 value
11418 };
11419}
11420function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
11421 return {
11422 type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
11423 loc,
11424 content,
11425 isStatic,
11426 constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
11427 };
11428}
11429function createCompoundExpression(children, loc = locStub) {
11430 return {
11431 type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
11432 loc,
11433 children
11434 };
11435}
11436function createCallExpression(callee, args = [], loc = locStub) {
11437 return {
11438 type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
11439 loc,
11440 callee,
11441 arguments: args
11442 };
11443}
11444function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11445 return {
11446 type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
11447 params,
11448 returns,
11449 newline,
11450 isSlot,
11451 loc
11452 };
11453}
11454function createConditionalExpression(test, consequent, alternate, newline = true) {
11455 return {
11456 type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
11457 test,
11458 consequent,
11459 alternate,
11460 newline,
11461 loc: locStub
11462 };
11463}
11464function createCacheExpression(index, value, isVNode = false) {
11465 return {
11466 type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
11467 index,
11468 value,
11469 isVNode,
11470 loc: locStub
11471 };
11472}
11473function createBlockStatement(body) {
11474 return {
11475 type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
11476 body,
11477 loc: locStub
11478 };
11479}
11480
11481const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
11482const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11483function isCoreComponent(tag) {
11484 if (isBuiltInType(tag, 'Teleport')) {
11485 return TELEPORT;
11486 }
11487 else if (isBuiltInType(tag, 'Suspense')) {
11488 return SUSPENSE;
11489 }
11490 else if (isBuiltInType(tag, 'KeepAlive')) {
11491 return KEEP_ALIVE;
11492 }
11493 else if (isBuiltInType(tag, 'BaseTransition')) {
11494 return BASE_TRANSITION;
11495 }
11496}
11497const nonIdentifierRE = /^\d|[^\$\w]/;
11498const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11499const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11500const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11501const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11502/**
11503 * Simple lexer to check if an expression is a member expression. This is
11504 * lax and only checks validity at the root level (i.e. does not validate exps
11505 * inside square brackets), but it's ok since these are only used on template
11506 * expressions and false positives are invalid expressions in the first place.
11507 */
11508const isMemberExpressionBrowser = (path) => {
11509 // remove whitespaces around . or [ first
11510 path = path.trim().replace(whitespaceRE, s => s.trim());
11511 let state = 0 /* MemberExpLexState.inMemberExp */;
11512 let stateStack = [];
11513 let currentOpenBracketCount = 0;
11514 let currentOpenParensCount = 0;
11515 let currentStringType = null;
11516 for (let i = 0; i < path.length; i++) {
11517 const char = path.charAt(i);
11518 switch (state) {
11519 case 0 /* MemberExpLexState.inMemberExp */:
11520 if (char === '[') {
11521 stateStack.push(state);
11522 state = 1 /* MemberExpLexState.inBrackets */;
11523 currentOpenBracketCount++;
11524 }
11525 else if (char === '(') {
11526 stateStack.push(state);
11527 state = 2 /* MemberExpLexState.inParens */;
11528 currentOpenParensCount++;
11529 }
11530 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11531 return false;
11532 }
11533 break;
11534 case 1 /* MemberExpLexState.inBrackets */:
11535 if (char === `'` || char === `"` || char === '`') {
11536 stateStack.push(state);
11537 state = 3 /* MemberExpLexState.inString */;
11538 currentStringType = char;
11539 }
11540 else if (char === `[`) {
11541 currentOpenBracketCount++;
11542 }
11543 else if (char === `]`) {
11544 if (!--currentOpenBracketCount) {
11545 state = stateStack.pop();
11546 }
11547 }
11548 break;
11549 case 2 /* MemberExpLexState.inParens */:
11550 if (char === `'` || char === `"` || char === '`') {
11551 stateStack.push(state);
11552 state = 3 /* MemberExpLexState.inString */;
11553 currentStringType = char;
11554 }
11555 else if (char === `(`) {
11556 currentOpenParensCount++;
11557 }
11558 else if (char === `)`) {
11559 // if the exp ends as a call then it should not be considered valid
11560 if (i === path.length - 1) {
11561 return false;
11562 }
11563 if (!--currentOpenParensCount) {
11564 state = stateStack.pop();
11565 }
11566 }
11567 break;
11568 case 3 /* MemberExpLexState.inString */:
11569 if (char === currentStringType) {
11570 state = stateStack.pop();
11571 currentStringType = null;
11572 }
11573 break;
11574 }
11575 }
11576 return !currentOpenBracketCount && !currentOpenParensCount;
11577};
11578const isMemberExpression = isMemberExpressionBrowser
11579 ;
11580function getInnerRange(loc, offset, length) {
11581 const source = loc.source.slice(offset, offset + length);
11582 const newLoc = {
11583 source,
11584 start: advancePositionWithClone(loc.start, loc.source, offset),
11585 end: loc.end
11586 };
11587 if (length != null) {
11588 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11589 }
11590 return newLoc;
11591}
11592function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11593 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11594}
11595// advance by mutation without cloning (for performance reasons), since this
11596// gets called a lot in the parser
11597function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11598 let linesCount = 0;
11599 let lastNewLinePos = -1;
11600 for (let i = 0; i < numberOfCharacters; i++) {
11601 if (source.charCodeAt(i) === 10 /* newline char code */) {
11602 linesCount++;
11603 lastNewLinePos = i;
11604 }
11605 }
11606 pos.offset += numberOfCharacters;
11607 pos.line += linesCount;
11608 pos.column =
11609 lastNewLinePos === -1
11610 ? pos.column + numberOfCharacters
11611 : numberOfCharacters - lastNewLinePos;
11612 return pos;
11613}
11614function assert(condition, msg) {
11615 /* istanbul ignore if */
11616 if (!condition) {
11617 throw new Error(msg || `unexpected compiler condition`);
11618 }
11619}
11620function findDir(node, name, allowEmpty = false) {
11621 for (let i = 0; i < node.props.length; i++) {
11622 const p = node.props[i];
11623 if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
11624 (allowEmpty || p.exp) &&
11625 (isString(name) ? p.name === name : name.test(p.name))) {
11626 return p;
11627 }
11628 }
11629}
11630function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11631 for (let i = 0; i < node.props.length; i++) {
11632 const p = node.props[i];
11633 if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
11634 if (dynamicOnly)
11635 continue;
11636 if (p.name === name && (p.value || allowEmpty)) {
11637 return p;
11638 }
11639 }
11640 else if (p.name === 'bind' &&
11641 (p.exp || allowEmpty) &&
11642 isStaticArgOf(p.arg, name)) {
11643 return p;
11644 }
11645 }
11646}
11647function isStaticArgOf(arg, name) {
11648 return !!(arg && isStaticExp(arg) && arg.content === name);
11649}
11650function hasDynamicKeyVBind(node) {
11651 return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
11652 p.name === 'bind' &&
11653 (!p.arg || // v-bind="obj"
11654 p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11655 !p.arg.isStatic) // v-bind:[foo]
11656 );
11657}
11658function isText(node) {
11659 return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
11660}
11661function isVSlot(p) {
11662 return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
11663}
11664function isTemplateNode(node) {
11665 return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
11666}
11667function isSlotOutlet(node) {
11668 return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
11669}
11670function getVNodeHelper(ssr, isComponent) {
11671 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11672}
11673function getVNodeBlockHelper(ssr, isComponent) {
11674 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11675}
11676const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11677function getUnnormalizedProps(props, callPath = []) {
11678 if (props &&
11679 !isString(props) &&
11680 props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
11681 const callee = props.callee;
11682 if (!isString(callee) && propsHelperSet.has(callee)) {
11683 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11684 }
11685 }
11686 return [props, callPath];
11687}
11688function injectProp(node, prop, context) {
11689 let propsWithInjection;
11690 /**
11691 * 1. mergeProps(...)
11692 * 2. toHandlers(...)
11693 * 3. normalizeProps(...)
11694 * 4. normalizeProps(guardReactiveProps(...))
11695 *
11696 * we need to get the real props before normalization
11697 */
11698 let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
11699 let callPath = [];
11700 let parentCall;
11701 if (props &&
11702 !isString(props) &&
11703 props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
11704 const ret = getUnnormalizedProps(props);
11705 props = ret[0];
11706 callPath = ret[1];
11707 parentCall = callPath[callPath.length - 1];
11708 }
11709 if (props == null || isString(props)) {
11710 propsWithInjection = createObjectExpression([prop]);
11711 }
11712 else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
11713 // merged props... add ours
11714 // only inject key to object literal if it's the first argument so that
11715 // if doesn't override user provided keys
11716 const first = props.arguments[0];
11717 if (!isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
11718 // #6631
11719 if (!hasProp(prop, first)) {
11720 first.properties.unshift(prop);
11721 }
11722 }
11723 else {
11724 if (props.callee === TO_HANDLERS) {
11725 // #2366
11726 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11727 createObjectExpression([prop]),
11728 props
11729 ]);
11730 }
11731 else {
11732 props.arguments.unshift(createObjectExpression([prop]));
11733 }
11734 }
11735 !propsWithInjection && (propsWithInjection = props);
11736 }
11737 else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
11738 if (!hasProp(prop, props)) {
11739 props.properties.unshift(prop);
11740 }
11741 propsWithInjection = props;
11742 }
11743 else {
11744 // single v-bind with expression, return a merged replacement
11745 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11746 createObjectExpression([prop]),
11747 props
11748 ]);
11749 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11750 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11751 // the `guardReactiveProps` will no longer be needed
11752 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11753 parentCall = callPath[callPath.length - 2];
11754 }
11755 }
11756 if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
11757 if (parentCall) {
11758 parentCall.arguments[0] = propsWithInjection;
11759 }
11760 else {
11761 node.props = propsWithInjection;
11762 }
11763 }
11764 else {
11765 if (parentCall) {
11766 parentCall.arguments[0] = propsWithInjection;
11767 }
11768 else {
11769 node.arguments[2] = propsWithInjection;
11770 }
11771 }
11772}
11773// check existing key to avoid overriding user provided keys
11774function hasProp(prop, props) {
11775 let result = false;
11776 if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
11777 const propKeyName = prop.key.content;
11778 result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
11779 p.key.content === propKeyName);
11780 }
11781 return result;
11782}
11783function toValidAssetId(name, type) {
11784 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11785 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11786 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11787 })}`;
11788}
11789function getMemoedVNodeCall(node) {
11790 if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11791 return node.arguments[1].returns;
11792 }
11793 else {
11794 return node;
11795 }
11796}
11797function makeBlock(node, { helper, removeHelper, inSSR }) {
11798 if (!node.isBlock) {
11799 node.isBlock = true;
11800 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11801 helper(OPEN_BLOCK);
11802 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11803 }
11804}
11805
11806const deprecationData = {
11807 ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
11808 message: `Platform-native elements with "is" prop will no longer be ` +
11809 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11810 `prefixed with "vue:".`,
11811 link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
11812 },
11813 ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
11814 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11815 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11816 `\`v-model:${key}\`.`,
11817 link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
11818 },
11819 ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
11820 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11821 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11822 },
11823 ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
11824 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11825 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11826 `that appears before v-bind in the case of conflict. ` +
11827 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11828 `You can also suppress this warning if the usage is intended.`,
11829 link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
11830 },
11831 ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
11832 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11833 link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
11834 },
11835 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11836 message: `v-if / v-for precedence when used on the same element has changed ` +
11837 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11838 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11839 `with <template> tags or use a computed property that filters v-for ` +
11840 `data source.`,
11841 link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
11842 },
11843 ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
11844 message: `<template> with no special directives will render as a native template ` +
11845 `element instead of its inner content in Vue 3.`
11846 },
11847 ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
11848 message: `"inline-template" has been removed in Vue 3.`,
11849 link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
11850 },
11851 ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
11852 message: `filters have been removed in Vue 3. ` +
11853 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11854 `Use method calls or computed properties instead.`,
11855 link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
11856 }
11857};
11858function getCompatValue(key, context) {
11859 const config = context.options
11860 ? context.options.compatConfig
11861 : context.compatConfig;
11862 const value = config && config[key];
11863 if (key === 'MODE') {
11864 return value || 3; // compiler defaults to v3 behavior
11865 }
11866 else {
11867 return value;
11868 }
11869}
11870function isCompatEnabled(key, context) {
11871 const mode = getCompatValue('MODE', context);
11872 const value = getCompatValue(key, context);
11873 // in v3 mode, only enable if explicitly set to true
11874 // otherwise enable for any non-false value
11875 return mode === 3 ? value === true : value !== false;
11876}
11877function checkCompatEnabled(key, context, loc, ...args) {
11878 const enabled = isCompatEnabled(key, context);
11879 if (enabled) {
11880 warnDeprecation(key, context, loc, ...args);
11881 }
11882 return enabled;
11883}
11884function warnDeprecation(key, context, loc, ...args) {
11885 const val = getCompatValue(key, context);
11886 if (val === 'suppress-warning') {
11887 return;
11888 }
11889 const { message, link } = deprecationData[key];
11890 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11891 const err = new SyntaxError(msg);
11892 err.code = key;
11893 if (loc)
11894 err.loc = loc;
11895 context.onWarn(err);
11896}
11897
11898// The default decoder only provides escapes for characters reserved as part of
11899// the template syntax, and is only used if the custom renderer did not provide
11900// a platform-specific decoder.
11901const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11902const decodeMap = {
11903 gt: '>',
11904 lt: '<',
11905 amp: '&',
11906 apos: "'",
11907 quot: '"'
11908};
11909const defaultParserOptions = {
11910 delimiters: [`{{`, `}}`],
11911 getNamespace: () => 0 /* Namespaces.HTML */,
11912 getTextMode: () => 0 /* TextModes.DATA */,
11913 isVoidTag: NO,
11914 isPreTag: NO,
11915 isCustomElement: NO,
11916 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11917 onError: defaultOnError,
11918 onWarn: defaultOnWarn,
11919 comments: true
11920};
11921function baseParse(content, options = {}) {
11922 const context = createParserContext(content, options);
11923 const start = getCursor(context);
11924 return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
11925}
11926function createParserContext(content, rawOptions) {
11927 const options = extend({}, defaultParserOptions);
11928 let key;
11929 for (key in rawOptions) {
11930 // @ts-ignore
11931 options[key] =
11932 rawOptions[key] === undefined
11933 ? defaultParserOptions[key]
11934 : rawOptions[key];
11935 }
11936 return {
11937 options,
11938 column: 1,
11939 line: 1,
11940 offset: 0,
11941 originalSource: content,
11942 source: content,
11943 inPre: false,
11944 inVPre: false,
11945 onWarn: options.onWarn
11946 };
11947}
11948function parseChildren(context, mode, ancestors) {
11949 const parent = last(ancestors);
11950 const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
11951 const nodes = [];
11952 while (!isEnd(context, mode, ancestors)) {
11953 const s = context.source;
11954 let node = undefined;
11955 if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
11956 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11957 // '{{'
11958 node = parseInterpolation(context, mode);
11959 }
11960 else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
11961 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11962 if (s.length === 1) {
11963 emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
11964 }
11965 else if (s[1] === '!') {
11966 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11967 if (startsWith(s, '<!--')) {
11968 node = parseComment(context);
11969 }
11970 else if (startsWith(s, '<!DOCTYPE')) {
11971 // Ignore DOCTYPE by a limitation.
11972 node = parseBogusComment(context);
11973 }
11974 else if (startsWith(s, '<![CDATA[')) {
11975 if (ns !== 0 /* Namespaces.HTML */) {
11976 node = parseCDATA(context, ancestors);
11977 }
11978 else {
11979 emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
11980 node = parseBogusComment(context);
11981 }
11982 }
11983 else {
11984 emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
11985 node = parseBogusComment(context);
11986 }
11987 }
11988 else if (s[1] === '/') {
11989 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11990 if (s.length === 2) {
11991 emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
11992 }
11993 else if (s[2] === '>') {
11994 emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
11995 advanceBy(context, 3);
11996 continue;
11997 }
11998 else if (/[a-z]/i.test(s[2])) {
11999 emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
12000 parseTag(context, 1 /* TagType.End */, parent);
12001 continue;
12002 }
12003 else {
12004 emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
12005 node = parseBogusComment(context);
12006 }
12007 }
12008 else if (/[a-z]/i.test(s[1])) {
12009 node = parseElement(context, ancestors);
12010 }
12011 else if (s[1] === '?') {
12012 emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
12013 node = parseBogusComment(context);
12014 }
12015 else {
12016 emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
12017 }
12018 }
12019 }
12020 if (!node) {
12021 node = parseText(context, mode);
12022 }
12023 if (isArray(node)) {
12024 for (let i = 0; i < node.length; i++) {
12025 pushNode(nodes, node[i]);
12026 }
12027 }
12028 else {
12029 pushNode(nodes, node);
12030 }
12031 }
12032 // Whitespace handling strategy like v2
12033 let removedWhitespace = false;
12034 if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
12035 const shouldCondense = context.options.whitespace !== 'preserve';
12036 for (let i = 0; i < nodes.length; i++) {
12037 const node = nodes[i];
12038 if (node.type === 2 /* NodeTypes.TEXT */) {
12039 if (!context.inPre) {
12040 if (!/[^\t\r\n\f ]/.test(node.content)) {
12041 const prev = nodes[i - 1];
12042 const next = nodes[i + 1];
12043 // Remove if:
12044 // - the whitespace is the first or last node, or:
12045 // - (condense mode) the whitespace is between twos comments, or:
12046 // - (condense mode) the whitespace is between comment and element, or:
12047 // - (condense mode) the whitespace is between two elements AND contains newline
12048 if (!prev ||
12049 !next ||
12050 (shouldCondense &&
12051 ((prev.type === 3 /* NodeTypes.COMMENT */ &&
12052 next.type === 3 /* NodeTypes.COMMENT */) ||
12053 (prev.type === 3 /* NodeTypes.COMMENT */ &&
12054 next.type === 1 /* NodeTypes.ELEMENT */) ||
12055 (prev.type === 1 /* NodeTypes.ELEMENT */ &&
12056 next.type === 3 /* NodeTypes.COMMENT */) ||
12057 (prev.type === 1 /* NodeTypes.ELEMENT */ &&
12058 next.type === 1 /* NodeTypes.ELEMENT */ &&
12059 /[\r\n]/.test(node.content))))) {
12060 removedWhitespace = true;
12061 nodes[i] = null;
12062 }
12063 else {
12064 // Otherwise, the whitespace is condensed into a single space
12065 node.content = ' ';
12066 }
12067 }
12068 else if (shouldCondense) {
12069 // in condense mode, consecutive whitespaces in text are condensed
12070 // down to a single space.
12071 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
12072 }
12073 }
12074 else {
12075 // #6410 normalize windows newlines in <pre>:
12076 // in SSR, browsers normalize server-rendered \r\n into a single \n
12077 // in the DOM
12078 node.content = node.content.replace(/\r\n/g, '\n');
12079 }
12080 }
12081 // Remove comment nodes if desired by configuration.
12082 else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
12083 removedWhitespace = true;
12084 nodes[i] = null;
12085 }
12086 }
12087 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
12088 // remove leading newline per html spec
12089 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
12090 const first = nodes[0];
12091 if (first && first.type === 2 /* NodeTypes.TEXT */) {
12092 first.content = first.content.replace(/^\r?\n/, '');
12093 }
12094 }
12095 }
12096 return removedWhitespace ? nodes.filter(Boolean) : nodes;
12097}
12098function pushNode(nodes, node) {
12099 if (node.type === 2 /* NodeTypes.TEXT */) {
12100 const prev = last(nodes);
12101 // Merge if both this and the previous node are text and those are
12102 // consecutive. This happens for cases like "a < b".
12103 if (prev &&
12104 prev.type === 2 /* NodeTypes.TEXT */ &&
12105 prev.loc.end.offset === node.loc.start.offset) {
12106 prev.content += node.content;
12107 prev.loc.end = node.loc.end;
12108 prev.loc.source += node.loc.source;
12109 return;
12110 }
12111 }
12112 nodes.push(node);
12113}
12114function parseCDATA(context, ancestors) {
12115 advanceBy(context, 9);
12116 const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
12117 if (context.source.length === 0) {
12118 emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
12119 }
12120 else {
12121 advanceBy(context, 3);
12122 }
12123 return nodes;
12124}
12125function parseComment(context) {
12126 const start = getCursor(context);
12127 let content;
12128 // Regular comment.
12129 const match = /--(\!)?>/.exec(context.source);
12130 if (!match) {
12131 content = context.source.slice(4);
12132 advanceBy(context, context.source.length);
12133 emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
12134 }
12135 else {
12136 if (match.index <= 3) {
12137 emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
12138 }
12139 if (match[1]) {
12140 emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
12141 }
12142 content = context.source.slice(4, match.index);
12143 // Advancing with reporting nested comments.
12144 const s = context.source.slice(0, match.index);
12145 let prevIndex = 1, nestedIndex = 0;
12146 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
12147 advanceBy(context, nestedIndex - prevIndex + 1);
12148 if (nestedIndex + 4 < s.length) {
12149 emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
12150 }
12151 prevIndex = nestedIndex + 1;
12152 }
12153 advanceBy(context, match.index + match[0].length - prevIndex + 1);
12154 }
12155 return {
12156 type: 3 /* NodeTypes.COMMENT */,
12157 content,
12158 loc: getSelection(context, start)
12159 };
12160}
12161function parseBogusComment(context) {
12162 const start = getCursor(context);
12163 const contentStart = context.source[1] === '?' ? 1 : 2;
12164 let content;
12165 const closeIndex = context.source.indexOf('>');
12166 if (closeIndex === -1) {
12167 content = context.source.slice(contentStart);
12168 advanceBy(context, context.source.length);
12169 }
12170 else {
12171 content = context.source.slice(contentStart, closeIndex);
12172 advanceBy(context, closeIndex + 1);
12173 }
12174 return {
12175 type: 3 /* NodeTypes.COMMENT */,
12176 content,
12177 loc: getSelection(context, start)
12178 };
12179}
12180function parseElement(context, ancestors) {
12181 // Start tag.
12182 const wasInPre = context.inPre;
12183 const wasInVPre = context.inVPre;
12184 const parent = last(ancestors);
12185 const element = parseTag(context, 0 /* TagType.Start */, parent);
12186 const isPreBoundary = context.inPre && !wasInPre;
12187 const isVPreBoundary = context.inVPre && !wasInVPre;
12188 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
12189 // #4030 self-closing <pre> tag
12190 if (isPreBoundary) {
12191 context.inPre = false;
12192 }
12193 if (isVPreBoundary) {
12194 context.inVPre = false;
12195 }
12196 return element;
12197 }
12198 // Children.
12199 ancestors.push(element);
12200 const mode = context.options.getTextMode(element, parent);
12201 const children = parseChildren(context, mode, ancestors);
12202 ancestors.pop();
12203 element.children = children;
12204 // End tag.
12205 if (startsWithEndTagOpen(context.source, element.tag)) {
12206 parseTag(context, 1 /* TagType.End */, parent);
12207 }
12208 else {
12209 emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
12210 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
12211 const first = children[0];
12212 if (first && startsWith(first.loc.source, '<!--')) {
12213 emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
12214 }
12215 }
12216 }
12217 element.loc = getSelection(context, element.loc.start);
12218 if (isPreBoundary) {
12219 context.inPre = false;
12220 }
12221 if (isVPreBoundary) {
12222 context.inVPre = false;
12223 }
12224 return element;
12225}
12226const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
12227function parseTag(context, type, parent) {
12228 // Tag open.
12229 const start = getCursor(context);
12230 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
12231 const tag = match[1];
12232 const ns = context.options.getNamespace(tag, parent);
12233 advanceBy(context, match[0].length);
12234 advanceSpaces(context);
12235 // save current state in case we need to re-parse attributes with v-pre
12236 const cursor = getCursor(context);
12237 const currentSource = context.source;
12238 // check <pre> tag
12239 if (context.options.isPreTag(tag)) {
12240 context.inPre = true;
12241 }
12242 // Attributes.
12243 let props = parseAttributes(context, type);
12244 // check v-pre
12245 if (type === 0 /* TagType.Start */ &&
12246 !context.inVPre &&
12247 props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
12248 context.inVPre = true;
12249 // reset context
12250 extend(context, cursor);
12251 context.source = currentSource;
12252 // re-parse attrs and filter out v-pre itself
12253 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
12254 }
12255 // Tag close.
12256 let isSelfClosing = false;
12257 if (context.source.length === 0) {
12258 emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
12259 }
12260 else {
12261 isSelfClosing = startsWith(context.source, '/>');
12262 if (type === 1 /* TagType.End */ && isSelfClosing) {
12263 emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
12264 }
12265 advanceBy(context, isSelfClosing ? 2 : 1);
12266 }
12267 if (type === 1 /* TagType.End */) {
12268 return;
12269 }
12270 let tagType = 0 /* ElementTypes.ELEMENT */;
12271 if (!context.inVPre) {
12272 if (tag === 'slot') {
12273 tagType = 2 /* ElementTypes.SLOT */;
12274 }
12275 else if (tag === 'template') {
12276 if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
12277 tagType = 3 /* ElementTypes.TEMPLATE */;
12278 }
12279 }
12280 else if (isComponent(tag, props, context)) {
12281 tagType = 1 /* ElementTypes.COMPONENT */;
12282 }
12283 }
12284 return {
12285 type: 1 /* NodeTypes.ELEMENT */,
12286 ns,
12287 tag,
12288 tagType,
12289 props,
12290 isSelfClosing,
12291 children: [],
12292 loc: getSelection(context, start),
12293 codegenNode: undefined // to be created during transform phase
12294 };
12295}
12296function isComponent(tag, props, context) {
12297 const options = context.options;
12298 if (options.isCustomElement(tag)) {
12299 return false;
12300 }
12301 if (tag === 'component' ||
12302 /^[A-Z]/.test(tag) ||
12303 isCoreComponent(tag) ||
12304 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12305 (options.isNativeTag && !options.isNativeTag(tag))) {
12306 return true;
12307 }
12308 // at this point the tag should be a native tag, but check for potential "is"
12309 // casting
12310 for (let i = 0; i < props.length; i++) {
12311 const p = props[i];
12312 if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
12313 if (p.name === 'is' && p.value) {
12314 if (p.value.content.startsWith('vue:')) {
12315 return true;
12316 }
12317 }
12318 }
12319 else {
12320 // directive
12321 // v-is (TODO Deprecate)
12322 if (p.name === 'is') {
12323 return true;
12324 }
12325 else if (
12326 // :is on plain element - only treat as component in compat mode
12327 p.name === 'bind' &&
12328 isStaticArgOf(p.arg, 'is') &&
12329 false &&
12330 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12331 return true;
12332 }
12333 }
12334 }
12335}
12336function parseAttributes(context, type) {
12337 const props = [];
12338 const attributeNames = new Set();
12339 while (context.source.length > 0 &&
12340 !startsWith(context.source, '>') &&
12341 !startsWith(context.source, '/>')) {
12342 if (startsWith(context.source, '/')) {
12343 emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
12344 advanceBy(context, 1);
12345 advanceSpaces(context);
12346 continue;
12347 }
12348 if (type === 1 /* TagType.End */) {
12349 emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
12350 }
12351 const attr = parseAttribute(context, attributeNames);
12352 // Trim whitespace between class
12353 // https://github.com/vuejs/core/issues/4251
12354 if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
12355 attr.value &&
12356 attr.name === 'class') {
12357 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12358 }
12359 if (type === 0 /* TagType.Start */) {
12360 props.push(attr);
12361 }
12362 if (/^[^\t\r\n\f />]/.test(context.source)) {
12363 emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12364 }
12365 advanceSpaces(context);
12366 }
12367 return props;
12368}
12369function parseAttribute(context, nameSet) {
12370 // Name.
12371 const start = getCursor(context);
12372 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12373 const name = match[0];
12374 if (nameSet.has(name)) {
12375 emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
12376 }
12377 nameSet.add(name);
12378 if (name[0] === '=') {
12379 emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12380 }
12381 {
12382 const pattern = /["'<]/g;
12383 let m;
12384 while ((m = pattern.exec(name))) {
12385 emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12386 }
12387 }
12388 advanceBy(context, name.length);
12389 // Value
12390 let value = undefined;
12391 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12392 advanceSpaces(context);
12393 advanceBy(context, 1);
12394 advanceSpaces(context);
12395 value = parseAttributeValue(context);
12396 if (!value) {
12397 emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
12398 }
12399 }
12400 const loc = getSelection(context, start);
12401 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12402 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12403 let isPropShorthand = startsWith(name, '.');
12404 let dirName = match[1] ||
12405 (isPropShorthand || startsWith(name, ':')
12406 ? 'bind'
12407 : startsWith(name, '@')
12408 ? 'on'
12409 : 'slot');
12410 let arg;
12411 if (match[2]) {
12412 const isSlot = dirName === 'slot';
12413 const startOffset = name.lastIndexOf(match[2]);
12414 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12415 let content = match[2];
12416 let isStatic = true;
12417 if (content.startsWith('[')) {
12418 isStatic = false;
12419 if (!content.endsWith(']')) {
12420 emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12421 content = content.slice(1);
12422 }
12423 else {
12424 content = content.slice(1, content.length - 1);
12425 }
12426 }
12427 else if (isSlot) {
12428 // #1241 special case for v-slot: vuetify relies extensively on slot
12429 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12430 // supports such usage so we are keeping it consistent with 2.x.
12431 content += match[3] || '';
12432 }
12433 arg = {
12434 type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
12435 content,
12436 isStatic,
12437 constType: isStatic
12438 ? 3 /* ConstantTypes.CAN_STRINGIFY */
12439 : 0 /* ConstantTypes.NOT_CONSTANT */,
12440 loc
12441 };
12442 }
12443 if (value && value.isQuoted) {
12444 const valueLoc = value.loc;
12445 valueLoc.start.offset++;
12446 valueLoc.start.column++;
12447 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12448 valueLoc.source = valueLoc.source.slice(1, -1);
12449 }
12450 const modifiers = match[3] ? match[3].slice(1).split('.') : [];
12451 if (isPropShorthand)
12452 modifiers.push('prop');
12453 return {
12454 type: 7 /* NodeTypes.DIRECTIVE */,
12455 name: dirName,
12456 exp: value && {
12457 type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
12458 content: value.content,
12459 isStatic: false,
12460 // Treat as non-constant by default. This can be potentially set to
12461 // other values by `transformExpression` to make it eligible for hoisting.
12462 constType: 0 /* ConstantTypes.NOT_CONSTANT */,
12463 loc: value.loc
12464 },
12465 arg,
12466 modifiers,
12467 loc
12468 };
12469 }
12470 // missing directive name or illegal directive name
12471 if (!context.inVPre && startsWith(name, 'v-')) {
12472 emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
12473 }
12474 return {
12475 type: 6 /* NodeTypes.ATTRIBUTE */,
12476 name,
12477 value: value && {
12478 type: 2 /* NodeTypes.TEXT */,
12479 content: value.content,
12480 loc: value.loc
12481 },
12482 loc
12483 };
12484}
12485function parseAttributeValue(context) {
12486 const start = getCursor(context);
12487 let content;
12488 const quote = context.source[0];
12489 const isQuoted = quote === `"` || quote === `'`;
12490 if (isQuoted) {
12491 // Quoted value.
12492 advanceBy(context, 1);
12493 const endIndex = context.source.indexOf(quote);
12494 if (endIndex === -1) {
12495 content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
12496 }
12497 else {
12498 content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
12499 advanceBy(context, 1);
12500 }
12501 }
12502 else {
12503 // Unquoted
12504 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12505 if (!match) {
12506 return undefined;
12507 }
12508 const unexpectedChars = /["'<=`]/g;
12509 let m;
12510 while ((m = unexpectedChars.exec(match[0]))) {
12511 emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12512 }
12513 content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
12514 }
12515 return { content, isQuoted, loc: getSelection(context, start) };
12516}
12517function parseInterpolation(context, mode) {
12518 const [open, close] = context.options.delimiters;
12519 const closeIndex = context.source.indexOf(close, open.length);
12520 if (closeIndex === -1) {
12521 emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
12522 return undefined;
12523 }
12524 const start = getCursor(context);
12525 advanceBy(context, open.length);
12526 const innerStart = getCursor(context);
12527 const innerEnd = getCursor(context);
12528 const rawContentLength = closeIndex - open.length;
12529 const rawContent = context.source.slice(0, rawContentLength);
12530 const preTrimContent = parseTextData(context, rawContentLength, mode);
12531 const content = preTrimContent.trim();
12532 const startOffset = preTrimContent.indexOf(content);
12533 if (startOffset > 0) {
12534 advancePositionWithMutation(innerStart, rawContent, startOffset);
12535 }
12536 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12537 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12538 advanceBy(context, close.length);
12539 return {
12540 type: 5 /* NodeTypes.INTERPOLATION */,
12541 content: {
12542 type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
12543 isStatic: false,
12544 // Set `isConstant` to false by default and will decide in transformExpression
12545 constType: 0 /* ConstantTypes.NOT_CONSTANT */,
12546 content,
12547 loc: getSelection(context, innerStart, innerEnd)
12548 },
12549 loc: getSelection(context, start)
12550 };
12551}
12552function parseText(context, mode) {
12553 const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12554 let endIndex = context.source.length;
12555 for (let i = 0; i < endTokens.length; i++) {
12556 const index = context.source.indexOf(endTokens[i], 1);
12557 if (index !== -1 && endIndex > index) {
12558 endIndex = index;
12559 }
12560 }
12561 const start = getCursor(context);
12562 const content = parseTextData(context, endIndex, mode);
12563 return {
12564 type: 2 /* NodeTypes.TEXT */,
12565 content,
12566 loc: getSelection(context, start)
12567 };
12568}
12569/**
12570 * Get text data with a given length from the current location.
12571 * This translates HTML entities in the text data.
12572 */
12573function parseTextData(context, length, mode) {
12574 const rawText = context.source.slice(0, length);
12575 advanceBy(context, length);
12576 if (mode === 2 /* TextModes.RAWTEXT */ ||
12577 mode === 3 /* TextModes.CDATA */ ||
12578 !rawText.includes('&')) {
12579 return rawText;
12580 }
12581 else {
12582 // DATA or RCDATA containing "&"". Entity decoding required.
12583 return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
12584 }
12585}
12586function getCursor(context) {
12587 const { column, line, offset } = context;
12588 return { column, line, offset };
12589}
12590function getSelection(context, start, end) {
12591 end = end || getCursor(context);
12592 return {
12593 start,
12594 end,
12595 source: context.originalSource.slice(start.offset, end.offset)
12596 };
12597}
12598function last(xs) {
12599 return xs[xs.length - 1];
12600}
12601function startsWith(source, searchString) {
12602 return source.startsWith(searchString);
12603}
12604function advanceBy(context, numberOfCharacters) {
12605 const { source } = context;
12606 advancePositionWithMutation(context, source, numberOfCharacters);
12607 context.source = source.slice(numberOfCharacters);
12608}
12609function advanceSpaces(context) {
12610 const match = /^[\t\r\n\f ]+/.exec(context.source);
12611 if (match) {
12612 advanceBy(context, match[0].length);
12613 }
12614}
12615function getNewPosition(context, start, numberOfCharacters) {
12616 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12617}
12618function emitError(context, code, offset, loc = getCursor(context)) {
12619 if (offset) {
12620 loc.offset += offset;
12621 loc.column += offset;
12622 }
12623 context.options.onError(createCompilerError(code, {
12624 start: loc,
12625 end: loc,
12626 source: ''
12627 }));
12628}
12629function isEnd(context, mode, ancestors) {
12630 const s = context.source;
12631 switch (mode) {
12632 case 0 /* TextModes.DATA */:
12633 if (startsWith(s, '</')) {
12634 // TODO: probably bad performance
12635 for (let i = ancestors.length - 1; i >= 0; --i) {
12636 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12637 return true;
12638 }
12639 }
12640 }
12641 break;
12642 case 1 /* TextModes.RCDATA */:
12643 case 2 /* TextModes.RAWTEXT */: {
12644 const parent = last(ancestors);
12645 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12646 return true;
12647 }
12648 break;
12649 }
12650 case 3 /* TextModes.CDATA */:
12651 if (startsWith(s, ']]>')) {
12652 return true;
12653 }
12654 break;
12655 }
12656 return !s;
12657}
12658function startsWithEndTagOpen(source, tag) {
12659 return (startsWith(source, '</') &&
12660 source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
12661 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12662}
12663
12664function hoistStatic(root, context) {
12665 walk(root, context,
12666 // Root node is unfortunately non-hoistable due to potential parent
12667 // fallthrough attributes.
12668 isSingleElementRoot(root, root.children[0]));
12669}
12670function isSingleElementRoot(root, child) {
12671 const { children } = root;
12672 return (children.length === 1 &&
12673 child.type === 1 /* NodeTypes.ELEMENT */ &&
12674 !isSlotOutlet(child));
12675}
12676function walk(node, context, doNotHoistNode = false) {
12677 const { children } = node;
12678 const originalCount = children.length;
12679 let hoistedCount = 0;
12680 for (let i = 0; i < children.length; i++) {
12681 const child = children[i];
12682 // only plain elements & text calls are eligible for hoisting.
12683 if (child.type === 1 /* NodeTypes.ELEMENT */ &&
12684 child.tagType === 0 /* ElementTypes.ELEMENT */) {
12685 const constantType = doNotHoistNode
12686 ? 0 /* ConstantTypes.NOT_CONSTANT */
12687 : getConstantType(child, context);
12688 if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
12689 if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
12690 child.codegenNode.patchFlag =
12691 -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
12692 child.codegenNode = context.hoist(child.codegenNode);
12693 hoistedCount++;
12694 continue;
12695 }
12696 }
12697 else {
12698 // node may contain dynamic children, but its props may be eligible for
12699 // hoisting.
12700 const codegenNode = child.codegenNode;
12701 if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
12702 const flag = getPatchFlag(codegenNode);
12703 if ((!flag ||
12704 flag === 512 /* PatchFlags.NEED_PATCH */ ||
12705 flag === 1 /* PatchFlags.TEXT */) &&
12706 getGeneratedPropsConstantType(child, context) >=
12707 2 /* ConstantTypes.CAN_HOIST */) {
12708 const props = getNodeProps(child);
12709 if (props) {
12710 codegenNode.props = context.hoist(props);
12711 }
12712 }
12713 if (codegenNode.dynamicProps) {
12714 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12715 }
12716 }
12717 }
12718 }
12719 // walk further
12720 if (child.type === 1 /* NodeTypes.ELEMENT */) {
12721 const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
12722 if (isComponent) {
12723 context.scopes.vSlot++;
12724 }
12725 walk(child, context);
12726 if (isComponent) {
12727 context.scopes.vSlot--;
12728 }
12729 }
12730 else if (child.type === 11 /* NodeTypes.FOR */) {
12731 // Do not hoist v-for single child because it has to be a block
12732 walk(child, context, child.children.length === 1);
12733 }
12734 else if (child.type === 9 /* NodeTypes.IF */) {
12735 for (let i = 0; i < child.branches.length; i++) {
12736 // Do not hoist v-if single child because it has to be a block
12737 walk(child.branches[i], context, child.branches[i].children.length === 1);
12738 }
12739 }
12740 }
12741 if (hoistedCount && context.transformHoist) {
12742 context.transformHoist(children, context, node);
12743 }
12744 // all children were hoisted - the entire children array is hoistable.
12745 if (hoistedCount &&
12746 hoistedCount === originalCount &&
12747 node.type === 1 /* NodeTypes.ELEMENT */ &&
12748 node.tagType === 0 /* ElementTypes.ELEMENT */ &&
12749 node.codegenNode &&
12750 node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
12751 isArray(node.codegenNode.children)) {
12752 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12753 }
12754}
12755function getConstantType(node, context) {
12756 const { constantCache } = context;
12757 switch (node.type) {
12758 case 1 /* NodeTypes.ELEMENT */:
12759 if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
12760 return 0 /* ConstantTypes.NOT_CONSTANT */;
12761 }
12762 const cached = constantCache.get(node);
12763 if (cached !== undefined) {
12764 return cached;
12765 }
12766 const codegenNode = node.codegenNode;
12767 if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
12768 return 0 /* ConstantTypes.NOT_CONSTANT */;
12769 }
12770 if (codegenNode.isBlock &&
12771 node.tag !== 'svg' &&
12772 node.tag !== 'foreignObject') {
12773 return 0 /* ConstantTypes.NOT_CONSTANT */;
12774 }
12775 const flag = getPatchFlag(codegenNode);
12776 if (!flag) {
12777 let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
12778 // Element itself has no patch flag. However we still need to check:
12779 // 1. Even for a node with no patch flag, it is possible for it to contain
12780 // non-hoistable expressions that refers to scope variables, e.g. compiler
12781 // injected keys or cached event handlers. Therefore we need to always
12782 // check the codegenNode's props to be sure.
12783 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12784 if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
12785 constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
12786 return 0 /* ConstantTypes.NOT_CONSTANT */;
12787 }
12788 if (generatedPropsType < returnType) {
12789 returnType = generatedPropsType;
12790 }
12791 // 2. its children.
12792 for (let i = 0; i < node.children.length; i++) {
12793 const childType = getConstantType(node.children[i], context);
12794 if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
12795 constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
12796 return 0 /* ConstantTypes.NOT_CONSTANT */;
12797 }
12798 if (childType < returnType) {
12799 returnType = childType;
12800 }
12801 }
12802 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12803 // type, check if any of the props can cause the type to be lowered
12804 // we can skip can_patch because it's guaranteed by the absence of a
12805 // patchFlag.
12806 if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
12807 for (let i = 0; i < node.props.length; i++) {
12808 const p = node.props[i];
12809 if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
12810 const expType = getConstantType(p.exp, context);
12811 if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
12812 constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
12813 return 0 /* ConstantTypes.NOT_CONSTANT */;
12814 }
12815 if (expType < returnType) {
12816 returnType = expType;
12817 }
12818 }
12819 }
12820 }
12821 // only svg/foreignObject could be block here, however if they are
12822 // static then they don't need to be blocks since there will be no
12823 // nested updates.
12824 if (codegenNode.isBlock) {
12825 // except set custom directives.
12826 for (let i = 0; i < node.props.length; i++) {
12827 const p = node.props[i];
12828 if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
12829 constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
12830 return 0 /* ConstantTypes.NOT_CONSTANT */;
12831 }
12832 }
12833 context.removeHelper(OPEN_BLOCK);
12834 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12835 codegenNode.isBlock = false;
12836 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12837 }
12838 constantCache.set(node, returnType);
12839 return returnType;
12840 }
12841 else {
12842 constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
12843 return 0 /* ConstantTypes.NOT_CONSTANT */;
12844 }
12845 case 2 /* NodeTypes.TEXT */:
12846 case 3 /* NodeTypes.COMMENT */:
12847 return 3 /* ConstantTypes.CAN_STRINGIFY */;
12848 case 9 /* NodeTypes.IF */:
12849 case 11 /* NodeTypes.FOR */:
12850 case 10 /* NodeTypes.IF_BRANCH */:
12851 return 0 /* ConstantTypes.NOT_CONSTANT */;
12852 case 5 /* NodeTypes.INTERPOLATION */:
12853 case 12 /* NodeTypes.TEXT_CALL */:
12854 return getConstantType(node.content, context);
12855 case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
12856 return node.constType;
12857 case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
12858 let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
12859 for (let i = 0; i < node.children.length; i++) {
12860 const child = node.children[i];
12861 if (isString(child) || isSymbol(child)) {
12862 continue;
12863 }
12864 const childType = getConstantType(child, context);
12865 if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
12866 return 0 /* ConstantTypes.NOT_CONSTANT */;
12867 }
12868 else if (childType < returnType) {
12869 returnType = childType;
12870 }
12871 }
12872 return returnType;
12873 default:
12874 return 0 /* ConstantTypes.NOT_CONSTANT */;
12875 }
12876}
12877const allowHoistedHelperSet = new Set([
12878 NORMALIZE_CLASS,
12879 NORMALIZE_STYLE,
12880 NORMALIZE_PROPS,
12881 GUARD_REACTIVE_PROPS
12882]);
12883function getConstantTypeOfHelperCall(value, context) {
12884 if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
12885 !isString(value.callee) &&
12886 allowHoistedHelperSet.has(value.callee)) {
12887 const arg = value.arguments[0];
12888 if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
12889 return getConstantType(arg, context);
12890 }
12891 else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
12892 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12893 return getConstantTypeOfHelperCall(arg, context);
12894 }
12895 }
12896 return 0 /* ConstantTypes.NOT_CONSTANT */;
12897}
12898function getGeneratedPropsConstantType(node, context) {
12899 let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
12900 const props = getNodeProps(node);
12901 if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
12902 const { properties } = props;
12903 for (let i = 0; i < properties.length; i++) {
12904 const { key, value } = properties[i];
12905 const keyType = getConstantType(key, context);
12906 if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
12907 return keyType;
12908 }
12909 if (keyType < returnType) {
12910 returnType = keyType;
12911 }
12912 let valueType;
12913 if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
12914 valueType = getConstantType(value, context);
12915 }
12916 else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
12917 // some helper calls can be hoisted,
12918 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12919 // in this case we need to respect the ConstantType of the helper's arguments
12920 valueType = getConstantTypeOfHelperCall(value, context);
12921 }
12922 else {
12923 valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
12924 }
12925 if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
12926 return valueType;
12927 }
12928 if (valueType < returnType) {
12929 returnType = valueType;
12930 }
12931 }
12932 }
12933 return returnType;
12934}
12935function getNodeProps(node) {
12936 const codegenNode = node.codegenNode;
12937 if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
12938 return codegenNode.props;
12939 }
12940}
12941function getPatchFlag(node) {
12942 const flag = node.patchFlag;
12943 return flag ? parseInt(flag, 10) : undefined;
12944}
12945
12946function 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 }) {
12947 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12948 const context = {
12949 // options
12950 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12951 prefixIdentifiers,
12952 hoistStatic,
12953 cacheHandlers,
12954 nodeTransforms,
12955 directiveTransforms,
12956 transformHoist,
12957 isBuiltInComponent,
12958 isCustomElement,
12959 expressionPlugins,
12960 scopeId,
12961 slotted,
12962 ssr,
12963 inSSR,
12964 ssrCssVars,
12965 bindingMetadata,
12966 inline,
12967 isTS,
12968 onError,
12969 onWarn,
12970 compatConfig,
12971 // state
12972 root,
12973 helpers: new Map(),
12974 components: new Set(),
12975 directives: new Set(),
12976 hoists: [],
12977 imports: [],
12978 constantCache: new Map(),
12979 temps: 0,
12980 cached: 0,
12981 identifiers: Object.create(null),
12982 scopes: {
12983 vFor: 0,
12984 vSlot: 0,
12985 vPre: 0,
12986 vOnce: 0
12987 },
12988 parent: null,
12989 currentNode: root,
12990 childIndex: 0,
12991 inVOnce: false,
12992 // methods
12993 helper(name) {
12994 const count = context.helpers.get(name) || 0;
12995 context.helpers.set(name, count + 1);
12996 return name;
12997 },
12998 removeHelper(name) {
12999 const count = context.helpers.get(name);
13000 if (count) {
13001 const currentCount = count - 1;
13002 if (!currentCount) {
13003 context.helpers.delete(name);
13004 }
13005 else {
13006 context.helpers.set(name, currentCount);
13007 }
13008 }
13009 },
13010 helperString(name) {
13011 return `_${helperNameMap[context.helper(name)]}`;
13012 },
13013 replaceNode(node) {
13014 /* istanbul ignore if */
13015 {
13016 if (!context.currentNode) {
13017 throw new Error(`Node being replaced is already removed.`);
13018 }
13019 if (!context.parent) {
13020 throw new Error(`Cannot replace root node.`);
13021 }
13022 }
13023 context.parent.children[context.childIndex] = context.currentNode = node;
13024 },
13025 removeNode(node) {
13026 if (!context.parent) {
13027 throw new Error(`Cannot remove root node.`);
13028 }
13029 const list = context.parent.children;
13030 const removalIndex = node
13031 ? list.indexOf(node)
13032 : context.currentNode
13033 ? context.childIndex
13034 : -1;
13035 /* istanbul ignore if */
13036 if (removalIndex < 0) {
13037 throw new Error(`node being removed is not a child of current parent`);
13038 }
13039 if (!node || node === context.currentNode) {
13040 // current node removed
13041 context.currentNode = null;
13042 context.onNodeRemoved();
13043 }
13044 else {
13045 // sibling node removed
13046 if (context.childIndex > removalIndex) {
13047 context.childIndex--;
13048 context.onNodeRemoved();
13049 }
13050 }
13051 context.parent.children.splice(removalIndex, 1);
13052 },
13053 onNodeRemoved: () => { },
13054 addIdentifiers(exp) {
13055 },
13056 removeIdentifiers(exp) {
13057 },
13058 hoist(exp) {
13059 if (isString(exp))
13060 exp = createSimpleExpression(exp);
13061 context.hoists.push(exp);
13062 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
13063 identifier.hoisted = exp;
13064 return identifier;
13065 },
13066 cache(exp, isVNode = false) {
13067 return createCacheExpression(context.cached++, exp, isVNode);
13068 }
13069 };
13070 return context;
13071}
13072function transform(root, options) {
13073 const context = createTransformContext(root, options);
13074 traverseNode(root, context);
13075 if (options.hoistStatic) {
13076 hoistStatic(root, context);
13077 }
13078 if (!options.ssr) {
13079 createRootCodegen(root, context);
13080 }
13081 // finalize meta information
13082 root.helpers = [...context.helpers.keys()];
13083 root.components = [...context.components];
13084 root.directives = [...context.directives];
13085 root.imports = context.imports;
13086 root.hoists = context.hoists;
13087 root.temps = context.temps;
13088 root.cached = context.cached;
13089}
13090function createRootCodegen(root, context) {
13091 const { helper } = context;
13092 const { children } = root;
13093 if (children.length === 1) {
13094 const child = children[0];
13095 // if the single child is an element, turn it into a block.
13096 if (isSingleElementRoot(root, child) && child.codegenNode) {
13097 // single element root is never hoisted so codegenNode will never be
13098 // SimpleExpressionNode
13099 const codegenNode = child.codegenNode;
13100 if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
13101 makeBlock(codegenNode, context);
13102 }
13103 root.codegenNode = codegenNode;
13104 }
13105 else {
13106 // - single <slot/>, IfNode, ForNode: already blocks.
13107 // - single text node: always patched.
13108 // root codegen falls through via genNode()
13109 root.codegenNode = child;
13110 }
13111 }
13112 else if (children.length > 1) {
13113 // root has multiple nodes - return a fragment block.
13114 let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
13115 let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
13116 // check if the fragment actually contains a single valid child with
13117 // the rest being comments
13118 if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
13119 patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
13120 patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
13121 }
13122 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
13123 }
13124 else ;
13125}
13126function traverseChildren(parent, context) {
13127 let i = 0;
13128 const nodeRemoved = () => {
13129 i--;
13130 };
13131 for (; i < parent.children.length; i++) {
13132 const child = parent.children[i];
13133 if (isString(child))
13134 continue;
13135 context.parent = parent;
13136 context.childIndex = i;
13137 context.onNodeRemoved = nodeRemoved;
13138 traverseNode(child, context);
13139 }
13140}
13141function traverseNode(node, context) {
13142 context.currentNode = node;
13143 // apply transform plugins
13144 const { nodeTransforms } = context;
13145 const exitFns = [];
13146 for (let i = 0; i < nodeTransforms.length; i++) {
13147 const onExit = nodeTransforms[i](node, context);
13148 if (onExit) {
13149 if (isArray(onExit)) {
13150 exitFns.push(...onExit);
13151 }
13152 else {
13153 exitFns.push(onExit);
13154 }
13155 }
13156 if (!context.currentNode) {
13157 // node was removed
13158 return;
13159 }
13160 else {
13161 // node may have been replaced
13162 node = context.currentNode;
13163 }
13164 }
13165 switch (node.type) {
13166 case 3 /* NodeTypes.COMMENT */:
13167 if (!context.ssr) {
13168 // inject import for the Comment symbol, which is needed for creating
13169 // comment nodes with `createVNode`
13170 context.helper(CREATE_COMMENT);
13171 }
13172 break;
13173 case 5 /* NodeTypes.INTERPOLATION */:
13174 // no need to traverse, but we need to inject toString helper
13175 if (!context.ssr) {
13176 context.helper(TO_DISPLAY_STRING);
13177 }
13178 break;
13179 // for container types, further traverse downwards
13180 case 9 /* NodeTypes.IF */:
13181 for (let i = 0; i < node.branches.length; i++) {
13182 traverseNode(node.branches[i], context);
13183 }
13184 break;
13185 case 10 /* NodeTypes.IF_BRANCH */:
13186 case 11 /* NodeTypes.FOR */:
13187 case 1 /* NodeTypes.ELEMENT */:
13188 case 0 /* NodeTypes.ROOT */:
13189 traverseChildren(node, context);
13190 break;
13191 }
13192 // exit transforms
13193 context.currentNode = node;
13194 let i = exitFns.length;
13195 while (i--) {
13196 exitFns[i]();
13197 }
13198}
13199function createStructuralDirectiveTransform(name, fn) {
13200 const matches = isString(name)
13201 ? (n) => n === name
13202 : (n) => name.test(n);
13203 return (node, context) => {
13204 if (node.type === 1 /* NodeTypes.ELEMENT */) {
13205 const { props } = node;
13206 // structural directive transforms are not concerned with slots
13207 // as they are handled separately in vSlot.ts
13208 if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
13209 return;
13210 }
13211 const exitFns = [];
13212 for (let i = 0; i < props.length; i++) {
13213 const prop = props[i];
13214 if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
13215 // structural directives are removed to avoid infinite recursion
13216 // also we remove them *before* applying so that it can further
13217 // traverse itself in case it moves the node around
13218 props.splice(i, 1);
13219 i--;
13220 const onExit = fn(node, prop, context);
13221 if (onExit)
13222 exitFns.push(onExit);
13223 }
13224 }
13225 return exitFns;
13226 }
13227 };
13228}
13229
13230const PURE_ANNOTATION = `/*#__PURE__*/`;
13231const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13232function 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 }) {
13233 const context = {
13234 mode,
13235 prefixIdentifiers,
13236 sourceMap,
13237 filename,
13238 scopeId,
13239 optimizeImports,
13240 runtimeGlobalName,
13241 runtimeModuleName,
13242 ssrRuntimeModuleName,
13243 ssr,
13244 isTS,
13245 inSSR,
13246 source: ast.loc.source,
13247 code: ``,
13248 column: 1,
13249 line: 1,
13250 offset: 0,
13251 indentLevel: 0,
13252 pure: false,
13253 map: undefined,
13254 helper(key) {
13255 return `_${helperNameMap[key]}`;
13256 },
13257 push(code, node) {
13258 context.code += code;
13259 },
13260 indent() {
13261 newline(++context.indentLevel);
13262 },
13263 deindent(withoutNewLine = false) {
13264 if (withoutNewLine) {
13265 --context.indentLevel;
13266 }
13267 else {
13268 newline(--context.indentLevel);
13269 }
13270 },
13271 newline() {
13272 newline(context.indentLevel);
13273 }
13274 };
13275 function newline(n) {
13276 context.push('\n' + ` `.repeat(n));
13277 }
13278 return context;
13279}
13280function generate(ast, options = {}) {
13281 const context = createCodegenContext(ast, options);
13282 if (options.onContextCreated)
13283 options.onContextCreated(context);
13284 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
13285 const hasHelpers = ast.helpers.length > 0;
13286 const useWithBlock = !prefixIdentifiers && mode !== 'module';
13287 // preambles
13288 // in setup() inline mode, the preamble is generated in a sub context
13289 // and returned separately.
13290 const preambleContext = context;
13291 {
13292 genFunctionPreamble(ast, preambleContext);
13293 }
13294 // enter render function
13295 const functionName = ssr ? `ssrRender` : `render`;
13296 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13297 const signature = args.join(', ');
13298 {
13299 push(`function ${functionName}(${signature}) {`);
13300 }
13301 indent();
13302 if (useWithBlock) {
13303 push(`with (_ctx) {`);
13304 indent();
13305 // function mode const declarations should be inside with block
13306 // also they should be renamed to avoid collision with user properties
13307 if (hasHelpers) {
13308 push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
13309 push(`\n`);
13310 newline();
13311 }
13312 }
13313 // generate asset resolution statements
13314 if (ast.components.length) {
13315 genAssets(ast.components, 'component', context);
13316 if (ast.directives.length || ast.temps > 0) {
13317 newline();
13318 }
13319 }
13320 if (ast.directives.length) {
13321 genAssets(ast.directives, 'directive', context);
13322 if (ast.temps > 0) {
13323 newline();
13324 }
13325 }
13326 if (ast.temps > 0) {
13327 push(`let `);
13328 for (let i = 0; i < ast.temps; i++) {
13329 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13330 }
13331 }
13332 if (ast.components.length || ast.directives.length || ast.temps) {
13333 push(`\n`);
13334 newline();
13335 }
13336 // generate the VNode tree expression
13337 if (!ssr) {
13338 push(`return `);
13339 }
13340 if (ast.codegenNode) {
13341 genNode(ast.codegenNode, context);
13342 }
13343 else {
13344 push(`null`);
13345 }
13346 if (useWithBlock) {
13347 deindent();
13348 push(`}`);
13349 }
13350 deindent();
13351 push(`}`);
13352 return {
13353 ast,
13354 code: context.code,
13355 preamble: ``,
13356 // SourceMapGenerator does have toJSON() method but it's not in the types
13357 map: context.map ? context.map.toJSON() : undefined
13358 };
13359}
13360function genFunctionPreamble(ast, context) {
13361 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
13362 const VueBinding = runtimeGlobalName;
13363 // Generate const declaration for helpers
13364 // In prefix mode, we place the const declaration at top so it's done
13365 // only once; But if we not prefixing, we place the declaration inside the
13366 // with block so it doesn't incur the `in` check cost for every helper access.
13367 if (ast.helpers.length > 0) {
13368 {
13369 // "with" mode.
13370 // save Vue in a separate variable to avoid collision
13371 push(`const _Vue = ${VueBinding}\n`);
13372 // in "with" mode, helpers are declared inside the with block to avoid
13373 // has check cost, but hoists are lifted out of the function - we need
13374 // to provide the helper here.
13375 if (ast.hoists.length) {
13376 const staticHelpers = [
13377 CREATE_VNODE,
13378 CREATE_ELEMENT_VNODE,
13379 CREATE_COMMENT,
13380 CREATE_TEXT,
13381 CREATE_STATIC
13382 ]
13383 .filter(helper => ast.helpers.includes(helper))
13384 .map(aliasHelper)
13385 .join(', ');
13386 push(`const { ${staticHelpers} } = _Vue\n`);
13387 }
13388 }
13389 }
13390 genHoists(ast.hoists, context);
13391 newline();
13392 push(`return `);
13393}
13394function genAssets(assets, type, { helper, push, newline, isTS }) {
13395 const resolver = helper(type === 'component'
13396 ? RESOLVE_COMPONENT
13397 : RESOLVE_DIRECTIVE);
13398 for (let i = 0; i < assets.length; i++) {
13399 let id = assets[i];
13400 // potential component implicit self-reference inferred from SFC filename
13401 const maybeSelfReference = id.endsWith('__self');
13402 if (maybeSelfReference) {
13403 id = id.slice(0, -6);
13404 }
13405 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13406 if (i < assets.length - 1) {
13407 newline();
13408 }
13409 }
13410}
13411function genHoists(hoists, context) {
13412 if (!hoists.length) {
13413 return;
13414 }
13415 context.pure = true;
13416 const { push, newline, helper, scopeId, mode } = context;
13417 newline();
13418 for (let i = 0; i < hoists.length; i++) {
13419 const exp = hoists[i];
13420 if (exp) {
13421 push(`const _hoisted_${i + 1} = ${``}`);
13422 genNode(exp, context);
13423 newline();
13424 }
13425 }
13426 context.pure = false;
13427}
13428function isText$1(n) {
13429 return (isString(n) ||
13430 n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
13431 n.type === 2 /* NodeTypes.TEXT */ ||
13432 n.type === 5 /* NodeTypes.INTERPOLATION */ ||
13433 n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
13434}
13435function genNodeListAsArray(nodes, context) {
13436 const multilines = nodes.length > 3 ||
13437 (nodes.some(n => isArray(n) || !isText$1(n)));
13438 context.push(`[`);
13439 multilines && context.indent();
13440 genNodeList(nodes, context, multilines);
13441 multilines && context.deindent();
13442 context.push(`]`);
13443}
13444function genNodeList(nodes, context, multilines = false, comma = true) {
13445 const { push, newline } = context;
13446 for (let i = 0; i < nodes.length; i++) {
13447 const node = nodes[i];
13448 if (isString(node)) {
13449 push(node);
13450 }
13451 else if (isArray(node)) {
13452 genNodeListAsArray(node, context);
13453 }
13454 else {
13455 genNode(node, context);
13456 }
13457 if (i < nodes.length - 1) {
13458 if (multilines) {
13459 comma && push(',');
13460 newline();
13461 }
13462 else {
13463 comma && push(', ');
13464 }
13465 }
13466 }
13467}
13468function genNode(node, context) {
13469 if (isString(node)) {
13470 context.push(node);
13471 return;
13472 }
13473 if (isSymbol(node)) {
13474 context.push(context.helper(node));
13475 return;
13476 }
13477 switch (node.type) {
13478 case 1 /* NodeTypes.ELEMENT */:
13479 case 9 /* NodeTypes.IF */:
13480 case 11 /* NodeTypes.FOR */:
13481 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13482 `Apply appropriate transforms first.`);
13483 genNode(node.codegenNode, context);
13484 break;
13485 case 2 /* NodeTypes.TEXT */:
13486 genText(node, context);
13487 break;
13488 case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
13489 genExpression(node, context);
13490 break;
13491 case 5 /* NodeTypes.INTERPOLATION */:
13492 genInterpolation(node, context);
13493 break;
13494 case 12 /* NodeTypes.TEXT_CALL */:
13495 genNode(node.codegenNode, context);
13496 break;
13497 case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
13498 genCompoundExpression(node, context);
13499 break;
13500 case 3 /* NodeTypes.COMMENT */:
13501 genComment(node, context);
13502 break;
13503 case 13 /* NodeTypes.VNODE_CALL */:
13504 genVNodeCall(node, context);
13505 break;
13506 case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
13507 genCallExpression(node, context);
13508 break;
13509 case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
13510 genObjectExpression(node, context);
13511 break;
13512 case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
13513 genArrayExpression(node, context);
13514 break;
13515 case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
13516 genFunctionExpression(node, context);
13517 break;
13518 case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
13519 genConditionalExpression(node, context);
13520 break;
13521 case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
13522 genCacheExpression(node, context);
13523 break;
13524 case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
13525 genNodeList(node.body, context, true, false);
13526 break;
13527 // SSR only types
13528 case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
13529 break;
13530 case 23 /* NodeTypes.JS_IF_STATEMENT */:
13531 break;
13532 case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
13533 break;
13534 case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
13535 break;
13536 case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
13537 break;
13538 /* istanbul ignore next */
13539 case 10 /* NodeTypes.IF_BRANCH */:
13540 // noop
13541 break;
13542 default:
13543 {
13544 assert(false, `unhandled codegen node type: ${node.type}`);
13545 // make sure we exhaust all possible types
13546 const exhaustiveCheck = node;
13547 return exhaustiveCheck;
13548 }
13549 }
13550}
13551function genText(node, context) {
13552 context.push(JSON.stringify(node.content), node);
13553}
13554function genExpression(node, context) {
13555 const { content, isStatic } = node;
13556 context.push(isStatic ? JSON.stringify(content) : content, node);
13557}
13558function genInterpolation(node, context) {
13559 const { push, helper, pure } = context;
13560 if (pure)
13561 push(PURE_ANNOTATION);
13562 push(`${helper(TO_DISPLAY_STRING)}(`);
13563 genNode(node.content, context);
13564 push(`)`);
13565}
13566function genCompoundExpression(node, context) {
13567 for (let i = 0; i < node.children.length; i++) {
13568 const child = node.children[i];
13569 if (isString(child)) {
13570 context.push(child);
13571 }
13572 else {
13573 genNode(child, context);
13574 }
13575 }
13576}
13577function genExpressionAsPropertyKey(node, context) {
13578 const { push } = context;
13579 if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
13580 push(`[`);
13581 genCompoundExpression(node, context);
13582 push(`]`);
13583 }
13584 else if (node.isStatic) {
13585 // only quote keys if necessary
13586 const text = isSimpleIdentifier(node.content)
13587 ? node.content
13588 : JSON.stringify(node.content);
13589 push(text, node);
13590 }
13591 else {
13592 push(`[${node.content}]`, node);
13593 }
13594}
13595function genComment(node, context) {
13596 const { push, helper, pure } = context;
13597 if (pure) {
13598 push(PURE_ANNOTATION);
13599 }
13600 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13601}
13602function genVNodeCall(node, context) {
13603 const { push, helper, pure } = context;
13604 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13605 if (directives) {
13606 push(helper(WITH_DIRECTIVES) + `(`);
13607 }
13608 if (isBlock) {
13609 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13610 }
13611 if (pure) {
13612 push(PURE_ANNOTATION);
13613 }
13614 const callHelper = isBlock
13615 ? getVNodeBlockHelper(context.inSSR, isComponent)
13616 : getVNodeHelper(context.inSSR, isComponent);
13617 push(helper(callHelper) + `(`, node);
13618 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13619 push(`)`);
13620 if (isBlock) {
13621 push(`)`);
13622 }
13623 if (directives) {
13624 push(`, `);
13625 genNode(directives, context);
13626 push(`)`);
13627 }
13628}
13629function genNullableArgs(args) {
13630 let i = args.length;
13631 while (i--) {
13632 if (args[i] != null)
13633 break;
13634 }
13635 return args.slice(0, i + 1).map(arg => arg || `null`);
13636}
13637// JavaScript
13638function genCallExpression(node, context) {
13639 const { push, helper, pure } = context;
13640 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13641 if (pure) {
13642 push(PURE_ANNOTATION);
13643 }
13644 push(callee + `(`, node);
13645 genNodeList(node.arguments, context);
13646 push(`)`);
13647}
13648function genObjectExpression(node, context) {
13649 const { push, indent, deindent, newline } = context;
13650 const { properties } = node;
13651 if (!properties.length) {
13652 push(`{}`, node);
13653 return;
13654 }
13655 const multilines = properties.length > 1 ||
13656 (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
13657 push(multilines ? `{` : `{ `);
13658 multilines && indent();
13659 for (let i = 0; i < properties.length; i++) {
13660 const { key, value } = properties[i];
13661 // key
13662 genExpressionAsPropertyKey(key, context);
13663 push(`: `);
13664 // value
13665 genNode(value, context);
13666 if (i < properties.length - 1) {
13667 // will only reach this if it's multilines
13668 push(`,`);
13669 newline();
13670 }
13671 }
13672 multilines && deindent();
13673 push(multilines ? `}` : ` }`);
13674}
13675function genArrayExpression(node, context) {
13676 genNodeListAsArray(node.elements, context);
13677}
13678function genFunctionExpression(node, context) {
13679 const { push, indent, deindent } = context;
13680 const { params, returns, body, newline, isSlot } = node;
13681 if (isSlot) {
13682 // wrap slot functions with owner context
13683 push(`_${helperNameMap[WITH_CTX]}(`);
13684 }
13685 push(`(`, node);
13686 if (isArray(params)) {
13687 genNodeList(params, context);
13688 }
13689 else if (params) {
13690 genNode(params, context);
13691 }
13692 push(`) => `);
13693 if (newline || body) {
13694 push(`{`);
13695 indent();
13696 }
13697 if (returns) {
13698 if (newline) {
13699 push(`return `);
13700 }
13701 if (isArray(returns)) {
13702 genNodeListAsArray(returns, context);
13703 }
13704 else {
13705 genNode(returns, context);
13706 }
13707 }
13708 else if (body) {
13709 genNode(body, context);
13710 }
13711 if (newline || body) {
13712 deindent();
13713 push(`}`);
13714 }
13715 if (isSlot) {
13716 push(`)`);
13717 }
13718}
13719function genConditionalExpression(node, context) {
13720 const { test, consequent, alternate, newline: needNewline } = node;
13721 const { push, indent, deindent, newline } = context;
13722 if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
13723 const needsParens = !isSimpleIdentifier(test.content);
13724 needsParens && push(`(`);
13725 genExpression(test, context);
13726 needsParens && push(`)`);
13727 }
13728 else {
13729 push(`(`);
13730 genNode(test, context);
13731 push(`)`);
13732 }
13733 needNewline && indent();
13734 context.indentLevel++;
13735 needNewline || push(` `);
13736 push(`? `);
13737 genNode(consequent, context);
13738 context.indentLevel--;
13739 needNewline && newline();
13740 needNewline || push(` `);
13741 push(`: `);
13742 const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
13743 if (!isNested) {
13744 context.indentLevel++;
13745 }
13746 genNode(alternate, context);
13747 if (!isNested) {
13748 context.indentLevel--;
13749 }
13750 needNewline && deindent(true /* without newline */);
13751}
13752function genCacheExpression(node, context) {
13753 const { push, helper, indent, deindent, newline } = context;
13754 push(`_cache[${node.index}] || (`);
13755 if (node.isVNode) {
13756 indent();
13757 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13758 newline();
13759 }
13760 push(`_cache[${node.index}] = `);
13761 genNode(node.value, context);
13762 if (node.isVNode) {
13763 push(`,`);
13764 newline();
13765 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13766 newline();
13767 push(`_cache[${node.index}]`);
13768 deindent();
13769 }
13770 push(`)`);
13771}
13772
13773// these keywords should not appear inside expressions, but operators like
13774// typeof, instanceof and in are allowed
13775const prohibitedKeywordRE = new RegExp('\\b' +
13776 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13777 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13778 'extends,finally,continue,debugger,function,arguments,typeof,void')
13779 .split(',')
13780 .join('\\b|\\b') +
13781 '\\b');
13782// strip strings in expressions
13783const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13784/**
13785 * Validate a non-prefixed expression.
13786 * This is only called when using the in-browser runtime compiler since it
13787 * doesn't prefix expressions.
13788 */
13789function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13790 const exp = node.content;
13791 // empty expressions are validated per-directive since some directives
13792 // do allow empty expressions.
13793 if (!exp.trim()) {
13794 return;
13795 }
13796 try {
13797 new Function(asRawStatements
13798 ? ` ${exp} `
13799 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13800 }
13801 catch (e) {
13802 let message = e.message;
13803 const keywordMatch = exp
13804 .replace(stripStringRE, '')
13805 .match(prohibitedKeywordRE);
13806 if (keywordMatch) {
13807 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13808 }
13809 context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, message));
13810 }
13811}
13812
13813const transformExpression = (node, context) => {
13814 if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
13815 node.content = processExpression(node.content, context);
13816 }
13817 else if (node.type === 1 /* NodeTypes.ELEMENT */) {
13818 // handle directives on element
13819 for (let i = 0; i < node.props.length; i++) {
13820 const dir = node.props[i];
13821 // do not process for v-on & v-for since they are special handled
13822 if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
13823 const exp = dir.exp;
13824 const arg = dir.arg;
13825 // do not process exp if this is v-on:arg - we need special handling
13826 // for wrapping inline statements.
13827 if (exp &&
13828 exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
13829 !(dir.name === 'on' && arg)) {
13830 dir.exp = processExpression(exp, context,
13831 // slot args must be processed as function params
13832 dir.name === 'slot');
13833 }
13834 if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
13835 dir.arg = processExpression(arg, context);
13836 }
13837 }
13838 }
13839 }
13840};
13841// Important: since this function uses Node.js only dependencies, it should
13842// always be used with a leading !true check so that it can be
13843// tree-shaken from the browser build.
13844function processExpression(node, context,
13845// some expressions like v-slot props & v-for aliases should be parsed as
13846// function params
13847asParams = false,
13848// v-on handler values may contain multiple statements
13849asRawStatements = false, localVars = Object.create(context.identifiers)) {
13850 {
13851 {
13852 // simple in-browser validation (same logic in 2.x)
13853 validateBrowserExpression(node, context, asParams, asRawStatements);
13854 }
13855 return node;
13856 }
13857}
13858
13859const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13860 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13861 // #1587: We need to dynamically increment the key based on the current
13862 // node's sibling nodes, since chained v-if/else branches are
13863 // rendered at the same depth
13864 const siblings = context.parent.children;
13865 let i = siblings.indexOf(ifNode);
13866 let key = 0;
13867 while (i-- >= 0) {
13868 const sibling = siblings[i];
13869 if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
13870 key += sibling.branches.length;
13871 }
13872 }
13873 // Exit callback. Complete the codegenNode when all children have been
13874 // transformed.
13875 return () => {
13876 if (isRoot) {
13877 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13878 }
13879 else {
13880 // attach this branch's codegen node to the v-if root.
13881 const parentCondition = getParentCondition(ifNode.codegenNode);
13882 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13883 }
13884 };
13885 });
13886});
13887// target-agnostic transform used for both Client and SSR
13888function processIf(node, dir, context, processCodegen) {
13889 if (dir.name !== 'else' &&
13890 (!dir.exp || !dir.exp.content.trim())) {
13891 const loc = dir.exp ? dir.exp.loc : node.loc;
13892 context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
13893 dir.exp = createSimpleExpression(`true`, false, loc);
13894 }
13895 if (dir.exp) {
13896 validateBrowserExpression(dir.exp, context);
13897 }
13898 if (dir.name === 'if') {
13899 const branch = createIfBranch(node, dir);
13900 const ifNode = {
13901 type: 9 /* NodeTypes.IF */,
13902 loc: node.loc,
13903 branches: [branch]
13904 };
13905 context.replaceNode(ifNode);
13906 if (processCodegen) {
13907 return processCodegen(ifNode, branch, true);
13908 }
13909 }
13910 else {
13911 // locate the adjacent v-if
13912 const siblings = context.parent.children;
13913 const comments = [];
13914 let i = siblings.indexOf(node);
13915 while (i-- >= -1) {
13916 const sibling = siblings[i];
13917 if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
13918 context.removeNode(sibling);
13919 comments.unshift(sibling);
13920 continue;
13921 }
13922 if (sibling &&
13923 sibling.type === 2 /* NodeTypes.TEXT */ &&
13924 !sibling.content.trim().length) {
13925 context.removeNode(sibling);
13926 continue;
13927 }
13928 if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
13929 // Check if v-else was followed by v-else-if
13930 if (dir.name === 'else-if' &&
13931 sibling.branches[sibling.branches.length - 1].condition === undefined) {
13932 context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13933 }
13934 // move the node to the if node's branches
13935 context.removeNode();
13936 const branch = createIfBranch(node, dir);
13937 if (comments.length &&
13938 // #3619 ignore comments if the v-if is direct child of <transition>
13939 !(context.parent &&
13940 context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
13941 isBuiltInType(context.parent.tag, 'transition'))) {
13942 branch.children = [...comments, ...branch.children];
13943 }
13944 // check if user is forcing same key on different branches
13945 {
13946 const key = branch.userKey;
13947 if (key) {
13948 sibling.branches.forEach(({ userKey }) => {
13949 if (isSameKey(userKey, key)) {
13950 context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
13951 }
13952 });
13953 }
13954 }
13955 sibling.branches.push(branch);
13956 const onExit = processCodegen && processCodegen(sibling, branch, false);
13957 // since the branch was removed, it will not be traversed.
13958 // make sure to traverse here.
13959 traverseNode(branch, context);
13960 // call on exit
13961 if (onExit)
13962 onExit();
13963 // make sure to reset currentNode after traversal to indicate this
13964 // node has been removed.
13965 context.currentNode = null;
13966 }
13967 else {
13968 context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13969 }
13970 break;
13971 }
13972 }
13973}
13974function createIfBranch(node, dir) {
13975 const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
13976 return {
13977 type: 10 /* NodeTypes.IF_BRANCH */,
13978 loc: node.loc,
13979 condition: dir.name === 'else' ? undefined : dir.exp,
13980 children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
13981 userKey: findProp(node, `key`),
13982 isTemplateIf
13983 };
13984}
13985function createCodegenNodeForBranch(branch, keyIndex, context) {
13986 if (branch.condition) {
13987 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13988 // make sure to pass in asBlock: true so that the comment node call
13989 // closes the current block.
13990 createCallExpression(context.helper(CREATE_COMMENT), [
13991 '"v-if"' ,
13992 'true'
13993 ]));
13994 }
13995 else {
13996 return createChildrenCodegenNode(branch, keyIndex, context);
13997 }
13998}
13999function createChildrenCodegenNode(branch, keyIndex, context) {
14000 const { helper } = context;
14001 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
14002 const { children } = branch;
14003 const firstChild = children[0];
14004 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
14005 if (needFragmentWrapper) {
14006 if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
14007 // optimize away nested fragments when child is a ForNode
14008 const vnodeCall = firstChild.codegenNode;
14009 injectProp(vnodeCall, keyProperty, context);
14010 return vnodeCall;
14011 }
14012 else {
14013 let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
14014 let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
14015 // check if the fragment actually contains a single valid child with
14016 // the rest being comments
14017 if (!branch.isTemplateIf &&
14018 children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
14019 patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
14020 patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
14021 }
14022 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
14023 }
14024 }
14025 else {
14026 const ret = firstChild.codegenNode;
14027 const vnodeCall = getMemoedVNodeCall(ret);
14028 // Change createVNode to createBlock.
14029 if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
14030 makeBlock(vnodeCall, context);
14031 }
14032 // inject branch key
14033 injectProp(vnodeCall, keyProperty, context);
14034 return ret;
14035 }
14036}
14037function isSameKey(a, b) {
14038 if (!a || a.type !== b.type) {
14039 return false;
14040 }
14041 if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
14042 if (a.value.content !== b.value.content) {
14043 return false;
14044 }
14045 }
14046 else {
14047 // directive
14048 const exp = a.exp;
14049 const branchExp = b.exp;
14050 if (exp.type !== branchExp.type) {
14051 return false;
14052 }
14053 if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
14054 exp.isStatic !== branchExp.isStatic ||
14055 exp.content !== branchExp.content) {
14056 return false;
14057 }
14058 }
14059 return true;
14060}
14061function getParentCondition(node) {
14062 while (true) {
14063 if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
14064 if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
14065 node = node.alternate;
14066 }
14067 else {
14068 return node;
14069 }
14070 }
14071 else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
14072 node = node.value;
14073 }
14074 }
14075}
14076
14077const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
14078 const { helper, removeHelper } = context;
14079 return processFor(node, dir, context, forNode => {
14080 // create the loop render function expression now, and add the
14081 // iterator on exit after all children have been traversed
14082 const renderExp = createCallExpression(helper(RENDER_LIST), [
14083 forNode.source
14084 ]);
14085 const isTemplate = isTemplateNode(node);
14086 const memo = findDir(node, 'memo');
14087 const keyProp = findProp(node, `key`);
14088 const keyExp = keyProp &&
14089 (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
14090 ? createSimpleExpression(keyProp.value.content, true)
14091 : keyProp.exp);
14092 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
14093 const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
14094 forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
14095 const fragmentFlag = isStableFragment
14096 ? 64 /* PatchFlags.STABLE_FRAGMENT */
14097 : keyProp
14098 ? 128 /* PatchFlags.KEYED_FRAGMENT */
14099 : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
14100 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
14101 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
14102 return () => {
14103 // finish the codegen now that all children have been traversed
14104 let childBlock;
14105 const { children } = forNode;
14106 // check <template v-for> key placement
14107 if (isTemplate) {
14108 node.children.some(c => {
14109 if (c.type === 1 /* NodeTypes.ELEMENT */) {
14110 const key = findProp(c, 'key');
14111 if (key) {
14112 context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
14113 return true;
14114 }
14115 }
14116 });
14117 }
14118 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
14119 const slotOutlet = isSlotOutlet(node)
14120 ? node
14121 : isTemplate &&
14122 node.children.length === 1 &&
14123 isSlotOutlet(node.children[0])
14124 ? node.children[0] // api-extractor somehow fails to infer this
14125 : null;
14126 if (slotOutlet) {
14127 // <slot v-for="..."> or <template v-for="..."><slot/></template>
14128 childBlock = slotOutlet.codegenNode;
14129 if (isTemplate && keyProperty) {
14130 // <template v-for="..." :key="..."><slot/></template>
14131 // we need to inject the key to the renderSlot() call.
14132 // the props for renderSlot is passed as the 3rd argument.
14133 injectProp(childBlock, keyProperty, context);
14134 }
14135 }
14136 else if (needFragmentWrapper) {
14137 // <template v-for="..."> with text or multi-elements
14138 // should generate a fragment block for each loop
14139 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
14140 (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
14141 ), undefined, undefined, true, undefined, false /* isComponent */);
14142 }
14143 else {
14144 // Normal element v-for. Directly use the child's codegenNode
14145 // but mark it as a block.
14146 childBlock = children[0]
14147 .codegenNode;
14148 if (isTemplate && keyProperty) {
14149 injectProp(childBlock, keyProperty, context);
14150 }
14151 if (childBlock.isBlock !== !isStableFragment) {
14152 if (childBlock.isBlock) {
14153 // switch from block to vnode
14154 removeHelper(OPEN_BLOCK);
14155 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
14156 }
14157 else {
14158 // switch from vnode to block
14159 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
14160 }
14161 }
14162 childBlock.isBlock = !isStableFragment;
14163 if (childBlock.isBlock) {
14164 helper(OPEN_BLOCK);
14165 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
14166 }
14167 else {
14168 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
14169 }
14170 }
14171 if (memo) {
14172 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
14173 createSimpleExpression(`_cached`)
14174 ]));
14175 loop.body = createBlockStatement([
14176 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
14177 createCompoundExpression([
14178 `if (_cached`,
14179 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
14180 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
14181 ]),
14182 createCompoundExpression([`const _item = `, childBlock]),
14183 createSimpleExpression(`_item.memo = _memo`),
14184 createSimpleExpression(`return _item`)
14185 ]);
14186 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
14187 }
14188 else {
14189 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
14190 }
14191 };
14192 });
14193});
14194// target-agnostic transform used for both Client and SSR
14195function processFor(node, dir, context, processCodegen) {
14196 if (!dir.exp) {
14197 context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
14198 return;
14199 }
14200 const parseResult = parseForExpression(
14201 // can only be simple expression because vFor transform is applied
14202 // before expression transform.
14203 dir.exp, context);
14204 if (!parseResult) {
14205 context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
14206 return;
14207 }
14208 const { addIdentifiers, removeIdentifiers, scopes } = context;
14209 const { source, value, key, index } = parseResult;
14210 const forNode = {
14211 type: 11 /* NodeTypes.FOR */,
14212 loc: dir.loc,
14213 source,
14214 valueAlias: value,
14215 keyAlias: key,
14216 objectIndexAlias: index,
14217 parseResult,
14218 children: isTemplateNode(node) ? node.children : [node]
14219 };
14220 context.replaceNode(forNode);
14221 // bookkeeping
14222 scopes.vFor++;
14223 const onExit = processCodegen && processCodegen(forNode);
14224 return () => {
14225 scopes.vFor--;
14226 if (onExit)
14227 onExit();
14228 };
14229}
14230const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
14231// This regex doesn't cover the case if key or index aliases have destructuring,
14232// but those do not make sense in the first place, so this works in practice.
14233const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
14234const stripParensRE = /^\(|\)$/g;
14235function parseForExpression(input, context) {
14236 const loc = input.loc;
14237 const exp = input.content;
14238 const inMatch = exp.match(forAliasRE);
14239 if (!inMatch)
14240 return;
14241 const [, LHS, RHS] = inMatch;
14242 const result = {
14243 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
14244 value: undefined,
14245 key: undefined,
14246 index: undefined
14247 };
14248 {
14249 validateBrowserExpression(result.source, context);
14250 }
14251 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
14252 const trimmedOffset = LHS.indexOf(valueContent);
14253 const iteratorMatch = valueContent.match(forIteratorRE);
14254 if (iteratorMatch) {
14255 valueContent = valueContent.replace(forIteratorRE, '').trim();
14256 const keyContent = iteratorMatch[1].trim();
14257 let keyOffset;
14258 if (keyContent) {
14259 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
14260 result.key = createAliasExpression(loc, keyContent, keyOffset);
14261 {
14262 validateBrowserExpression(result.key, context, true);
14263 }
14264 }
14265 if (iteratorMatch[2]) {
14266 const indexContent = iteratorMatch[2].trim();
14267 if (indexContent) {
14268 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
14269 ? keyOffset + keyContent.length
14270 : trimmedOffset + valueContent.length));
14271 {
14272 validateBrowserExpression(result.index, context, true);
14273 }
14274 }
14275 }
14276 }
14277 if (valueContent) {
14278 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
14279 {
14280 validateBrowserExpression(result.value, context, true);
14281 }
14282 }
14283 return result;
14284}
14285function createAliasExpression(range, content, offset) {
14286 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
14287}
14288function createForLoopParams({ value, key, index }, memoArgs = []) {
14289 return createParamsList([value, key, index, ...memoArgs]);
14290}
14291function createParamsList(args) {
14292 let i = args.length;
14293 while (i--) {
14294 if (args[i])
14295 break;
14296 }
14297 return args
14298 .slice(0, i + 1)
14299 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14300}
14301
14302const defaultFallback = createSimpleExpression(`undefined`, false);
14303// A NodeTransform that:
14304// 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14305// by transformExpression. This is only applied in non-browser builds with
14306// { prefixIdentifiers: true }.
14307// 2. Track v-slot depths so that we know a slot is inside another slot.
14308// Note the exit callback is executed before buildSlots() on the same node,
14309// so only nested slots see positive numbers.
14310const trackSlotScopes = (node, context) => {
14311 if (node.type === 1 /* NodeTypes.ELEMENT */ &&
14312 (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
14313 node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
14314 // We are only checking non-empty v-slot here
14315 // since we only care about slots that introduce scope variables.
14316 const vSlot = findDir(node, 'slot');
14317 if (vSlot) {
14318 vSlot.exp;
14319 context.scopes.vSlot++;
14320 return () => {
14321 context.scopes.vSlot--;
14322 };
14323 }
14324 }
14325};
14326const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14327// Instead of being a DirectiveTransform, v-slot processing is called during
14328// transformElement to build the slots object for a component.
14329function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14330 context.helper(WITH_CTX);
14331 const { children, loc } = node;
14332 const slotsProperties = [];
14333 const dynamicSlots = [];
14334 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14335 // since it likely uses a scope variable.
14336 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14337 // 1. Check for slot with slotProps on component itself.
14338 // <Comp v-slot="{ prop }"/>
14339 const onComponentSlot = findDir(node, 'slot', true);
14340 if (onComponentSlot) {
14341 const { arg, exp } = onComponentSlot;
14342 if (arg && !isStaticExp(arg)) {
14343 hasDynamicSlots = true;
14344 }
14345 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14346 }
14347 // 2. Iterate through children and check for template slots
14348 // <template v-slot:foo="{ prop }">
14349 let hasTemplateSlots = false;
14350 let hasNamedDefaultSlot = false;
14351 const implicitDefaultChildren = [];
14352 const seenSlotNames = new Set();
14353 let conditionalBranchIndex = 0;
14354 for (let i = 0; i < children.length; i++) {
14355 const slotElement = children[i];
14356 let slotDir;
14357 if (!isTemplateNode(slotElement) ||
14358 !(slotDir = findDir(slotElement, 'slot', true))) {
14359 // not a <template v-slot>, skip.
14360 if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
14361 implicitDefaultChildren.push(slotElement);
14362 }
14363 continue;
14364 }
14365 if (onComponentSlot) {
14366 // already has on-component slot - this is incorrect usage.
14367 context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14368 break;
14369 }
14370 hasTemplateSlots = true;
14371 const { children: slotChildren, loc: slotLoc } = slotElement;
14372 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14373 // check if name is dynamic.
14374 let staticSlotName;
14375 if (isStaticExp(slotName)) {
14376 staticSlotName = slotName ? slotName.content : `default`;
14377 }
14378 else {
14379 hasDynamicSlots = true;
14380 }
14381 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14382 // check if this slot is conditional (v-if/v-for)
14383 let vIf;
14384 let vElse;
14385 let vFor;
14386 if ((vIf = findDir(slotElement, 'if'))) {
14387 hasDynamicSlots = true;
14388 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
14389 }
14390 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14391 // find adjacent v-if
14392 let j = i;
14393 let prev;
14394 while (j--) {
14395 prev = children[j];
14396 if (prev.type !== 3 /* NodeTypes.COMMENT */) {
14397 break;
14398 }
14399 }
14400 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14401 // remove node
14402 children.splice(i, 1);
14403 i--;
14404 // attach this slot to previous conditional
14405 let conditional = dynamicSlots[dynamicSlots.length - 1];
14406 while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
14407 conditional = conditional.alternate;
14408 }
14409 conditional.alternate = vElse.exp
14410 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
14411 : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
14412 }
14413 else {
14414 context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14415 }
14416 }
14417 else if ((vFor = findDir(slotElement, 'for'))) {
14418 hasDynamicSlots = true;
14419 const parseResult = vFor.parseResult ||
14420 parseForExpression(vFor.exp, context);
14421 if (parseResult) {
14422 // Render the dynamic slots as an array and add it to the createSlot()
14423 // args. The runtime knows how to handle it appropriately.
14424 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14425 parseResult.source,
14426 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14427 ]));
14428 }
14429 else {
14430 context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14431 }
14432 }
14433 else {
14434 // check duplicate static names
14435 if (staticSlotName) {
14436 if (seenSlotNames.has(staticSlotName)) {
14437 context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14438 continue;
14439 }
14440 seenSlotNames.add(staticSlotName);
14441 if (staticSlotName === 'default') {
14442 hasNamedDefaultSlot = true;
14443 }
14444 }
14445 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14446 }
14447 }
14448 if (!onComponentSlot) {
14449 const buildDefaultSlotProperty = (props, children) => {
14450 const fn = buildSlotFn(props, children, loc);
14451 return createObjectProperty(`default`, fn);
14452 };
14453 if (!hasTemplateSlots) {
14454 // implicit default slot (on component)
14455 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14456 }
14457 else if (implicitDefaultChildren.length &&
14458 // #3766
14459 // with whitespace: 'preserve', whitespaces between slots will end up in
14460 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14461 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14462 // implicit default slot (mixed with named slots)
14463 if (hasNamedDefaultSlot) {
14464 context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14465 }
14466 else {
14467 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14468 }
14469 }
14470 }
14471 const slotFlag = hasDynamicSlots
14472 ? 2 /* SlotFlags.DYNAMIC */
14473 : hasForwardedSlots(node.children)
14474 ? 3 /* SlotFlags.FORWARDED */
14475 : 1 /* SlotFlags.STABLE */;
14476 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14477 // 2 = compiled but dynamic = can skip normalization, but must run diff
14478 // 1 = compiled and static = can skip normalization AND diff as optimized
14479 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14480 if (dynamicSlots.length) {
14481 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14482 slots,
14483 createArrayExpression(dynamicSlots)
14484 ]);
14485 }
14486 return {
14487 slots,
14488 hasDynamicSlots
14489 };
14490}
14491function buildDynamicSlot(name, fn, index) {
14492 const props = [
14493 createObjectProperty(`name`, name),
14494 createObjectProperty(`fn`, fn)
14495 ];
14496 if (index != null) {
14497 props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
14498 }
14499 return createObjectExpression(props);
14500}
14501function hasForwardedSlots(children) {
14502 for (let i = 0; i < children.length; i++) {
14503 const child = children[i];
14504 switch (child.type) {
14505 case 1 /* NodeTypes.ELEMENT */:
14506 if (child.tagType === 2 /* ElementTypes.SLOT */ ||
14507 hasForwardedSlots(child.children)) {
14508 return true;
14509 }
14510 break;
14511 case 9 /* NodeTypes.IF */:
14512 if (hasForwardedSlots(child.branches))
14513 return true;
14514 break;
14515 case 10 /* NodeTypes.IF_BRANCH */:
14516 case 11 /* NodeTypes.FOR */:
14517 if (hasForwardedSlots(child.children))
14518 return true;
14519 break;
14520 }
14521 }
14522 return false;
14523}
14524function isNonWhitespaceContent(node) {
14525 if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
14526 return true;
14527 return node.type === 2 /* NodeTypes.TEXT */
14528 ? !!node.content.trim()
14529 : isNonWhitespaceContent(node.content);
14530}
14531
14532// some directive transforms (e.g. v-model) may return a symbol for runtime
14533// import, which should be used instead of a resolveDirective call.
14534const directiveImportMap = new WeakMap();
14535// generate a JavaScript AST for this element's codegen
14536const transformElement = (node, context) => {
14537 // perform the work on exit, after all child expressions have been
14538 // processed and merged.
14539 return function postTransformElement() {
14540 node = context.currentNode;
14541 if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
14542 (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
14543 node.tagType === 1 /* ElementTypes.COMPONENT */))) {
14544 return;
14545 }
14546 const { tag, props } = node;
14547 const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
14548 // The goal of the transform is to create a codegenNode implementing the
14549 // VNodeCall interface.
14550 let vnodeTag = isComponent
14551 ? resolveComponentType(node, context)
14552 : `"${tag}"`;
14553 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14554 let vnodeProps;
14555 let vnodeChildren;
14556 let vnodePatchFlag;
14557 let patchFlag = 0;
14558 let vnodeDynamicProps;
14559 let dynamicPropNames;
14560 let vnodeDirectives;
14561 let shouldUseBlock =
14562 // dynamic component may resolve to plain elements
14563 isDynamicComponent ||
14564 vnodeTag === TELEPORT ||
14565 vnodeTag === SUSPENSE ||
14566 (!isComponent &&
14567 // <svg> and <foreignObject> must be forced into blocks so that block
14568 // updates inside get proper isSVG flag at runtime. (#639, #643)
14569 // This is technically web-specific, but splitting the logic out of core
14570 // leads to too much unnecessary complexity.
14571 (tag === 'svg' || tag === 'foreignObject'));
14572 // props
14573 if (props.length > 0) {
14574 const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
14575 vnodeProps = propsBuildResult.props;
14576 patchFlag = propsBuildResult.patchFlag;
14577 dynamicPropNames = propsBuildResult.dynamicPropNames;
14578 const directives = propsBuildResult.directives;
14579 vnodeDirectives =
14580 directives && directives.length
14581 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14582 : undefined;
14583 if (propsBuildResult.shouldUseBlock) {
14584 shouldUseBlock = true;
14585 }
14586 }
14587 // children
14588 if (node.children.length > 0) {
14589 if (vnodeTag === KEEP_ALIVE) {
14590 // Although a built-in component, we compile KeepAlive with raw children
14591 // instead of slot functions so that it can be used inside Transition
14592 // or other Transition-wrapping HOCs.
14593 // To ensure correct updates with block optimizations, we need to:
14594 // 1. Force keep-alive into a block. This avoids its children being
14595 // collected by a parent block.
14596 shouldUseBlock = true;
14597 // 2. Force keep-alive to always be updated, since it uses raw children.
14598 patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
14599 if (node.children.length > 1) {
14600 context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
14601 start: node.children[0].loc.start,
14602 end: node.children[node.children.length - 1].loc.end,
14603 source: ''
14604 }));
14605 }
14606 }
14607 const shouldBuildAsSlots = isComponent &&
14608 // Teleport is not a real component and has dedicated runtime handling
14609 vnodeTag !== TELEPORT &&
14610 // explained above.
14611 vnodeTag !== KEEP_ALIVE;
14612 if (shouldBuildAsSlots) {
14613 const { slots, hasDynamicSlots } = buildSlots(node, context);
14614 vnodeChildren = slots;
14615 if (hasDynamicSlots) {
14616 patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
14617 }
14618 }
14619 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14620 const child = node.children[0];
14621 const type = child.type;
14622 // check for dynamic text children
14623 const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
14624 type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
14625 if (hasDynamicTextChild &&
14626 getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
14627 patchFlag |= 1 /* PatchFlags.TEXT */;
14628 }
14629 // pass directly if the only child is a text node
14630 // (plain / interpolation / expression)
14631 if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
14632 vnodeChildren = child;
14633 }
14634 else {
14635 vnodeChildren = node.children;
14636 }
14637 }
14638 else {
14639 vnodeChildren = node.children;
14640 }
14641 }
14642 // patchFlag & dynamicPropNames
14643 if (patchFlag !== 0) {
14644 {
14645 if (patchFlag < 0) {
14646 // special flags (negative and mutually exclusive)
14647 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14648 }
14649 else {
14650 // bitwise flags
14651 const flagNames = Object.keys(PatchFlagNames)
14652 .map(Number)
14653 .filter(n => n > 0 && patchFlag & n)
14654 .map(n => PatchFlagNames[n])
14655 .join(`, `);
14656 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14657 }
14658 }
14659 if (dynamicPropNames && dynamicPropNames.length) {
14660 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14661 }
14662 }
14663 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14664 };
14665};
14666function resolveComponentType(node, context, ssr = false) {
14667 let { tag } = node;
14668 // 1. dynamic component
14669 const isExplicitDynamic = isComponentTag(tag);
14670 const isProp = findProp(node, 'is');
14671 if (isProp) {
14672 if (isExplicitDynamic ||
14673 (false )) {
14674 const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
14675 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14676 : isProp.exp;
14677 if (exp) {
14678 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14679 exp
14680 ]);
14681 }
14682 }
14683 else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
14684 isProp.value.content.startsWith('vue:')) {
14685 // <button is="vue:xxx">
14686 // if not <component>, only is value that starts with "vue:" will be
14687 // treated as component by the parse phase and reach here, unless it's
14688 // compat mode where all is values are considered components
14689 tag = isProp.value.content.slice(4);
14690 }
14691 }
14692 // 1.5 v-is (TODO: Deprecate)
14693 const isDir = !isExplicitDynamic && findDir(node, 'is');
14694 if (isDir && isDir.exp) {
14695 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14696 isDir.exp
14697 ]);
14698 }
14699 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14700 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14701 if (builtIn) {
14702 // built-ins are simply fallthroughs / have special handling during ssr
14703 // so we don't need to import their runtime equivalents
14704 if (!ssr)
14705 context.helper(builtIn);
14706 return builtIn;
14707 }
14708 // 5. user component (resolve)
14709 context.helper(RESOLVE_COMPONENT);
14710 context.components.add(tag);
14711 return toValidAssetId(tag, `component`);
14712}
14713function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
14714 const { tag, loc: elementLoc, children } = node;
14715 let properties = [];
14716 const mergeArgs = [];
14717 const runtimeDirectives = [];
14718 const hasChildren = children.length > 0;
14719 let shouldUseBlock = false;
14720 // patchFlag analysis
14721 let patchFlag = 0;
14722 let hasRef = false;
14723 let hasClassBinding = false;
14724 let hasStyleBinding = false;
14725 let hasHydrationEventBinding = false;
14726 let hasDynamicKeys = false;
14727 let hasVnodeHook = false;
14728 const dynamicPropNames = [];
14729 const pushMergeArg = (arg) => {
14730 if (properties.length) {
14731 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14732 properties = [];
14733 }
14734 if (arg)
14735 mergeArgs.push(arg);
14736 };
14737 const analyzePatchFlag = ({ key, value }) => {
14738 if (isStaticExp(key)) {
14739 const name = key.content;
14740 const isEventHandler = isOn(name);
14741 if (isEventHandler &&
14742 (!isComponent || isDynamicComponent) &&
14743 // omit the flag for click handlers because hydration gives click
14744 // dedicated fast path.
14745 name.toLowerCase() !== 'onclick' &&
14746 // omit v-model handlers
14747 name !== 'onUpdate:modelValue' &&
14748 // omit onVnodeXXX hooks
14749 !isReservedProp(name)) {
14750 hasHydrationEventBinding = true;
14751 }
14752 if (isEventHandler && isReservedProp(name)) {
14753 hasVnodeHook = true;
14754 }
14755 if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
14756 ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
14757 value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
14758 getConstantType(value, context) > 0)) {
14759 // skip if the prop is a cached handler or has constant value
14760 return;
14761 }
14762 if (name === 'ref') {
14763 hasRef = true;
14764 }
14765 else if (name === 'class') {
14766 hasClassBinding = true;
14767 }
14768 else if (name === 'style') {
14769 hasStyleBinding = true;
14770 }
14771 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14772 dynamicPropNames.push(name);
14773 }
14774 // treat the dynamic class and style binding of the component as dynamic props
14775 if (isComponent &&
14776 (name === 'class' || name === 'style') &&
14777 !dynamicPropNames.includes(name)) {
14778 dynamicPropNames.push(name);
14779 }
14780 }
14781 else {
14782 hasDynamicKeys = true;
14783 }
14784 };
14785 for (let i = 0; i < props.length; i++) {
14786 // static attribute
14787 const prop = props[i];
14788 if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
14789 const { loc, name, value } = prop;
14790 let isStatic = true;
14791 if (name === 'ref') {
14792 hasRef = true;
14793 if (context.scopes.vFor > 0) {
14794 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14795 }
14796 }
14797 // skip is on <component>, or is="vue:xxx"
14798 if (name === 'is' &&
14799 (isComponentTag(tag) ||
14800 (value && value.content.startsWith('vue:')) ||
14801 (false ))) {
14802 continue;
14803 }
14804 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
14805 }
14806 else {
14807 // directives
14808 const { name, arg, exp, loc } = prop;
14809 const isVBind = name === 'bind';
14810 const isVOn = name === 'on';
14811 // skip v-slot - it is handled by its dedicated transform.
14812 if (name === 'slot') {
14813 if (!isComponent) {
14814 context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
14815 }
14816 continue;
14817 }
14818 // skip v-once/v-memo - they are handled by dedicated transforms.
14819 if (name === 'once' || name === 'memo') {
14820 continue;
14821 }
14822 // skip v-is and :is on <component>
14823 if (name === 'is' ||
14824 (isVBind &&
14825 isStaticArgOf(arg, 'is') &&
14826 (isComponentTag(tag) ||
14827 (false )))) {
14828 continue;
14829 }
14830 // skip v-on in SSR compilation
14831 if (isVOn && ssr) {
14832 continue;
14833 }
14834 if (
14835 // #938: elements with dynamic keys should be forced into blocks
14836 (isVBind && isStaticArgOf(arg, 'key')) ||
14837 // inline before-update hooks need to force block so that it is invoked
14838 // before children
14839 (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
14840 shouldUseBlock = true;
14841 }
14842 if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
14843 properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
14844 }
14845 // special case for v-bind and v-on with no argument
14846 if (!arg && (isVBind || isVOn)) {
14847 hasDynamicKeys = true;
14848 if (exp) {
14849 if (isVBind) {
14850 // have to merge early for compat build check
14851 pushMergeArg();
14852 mergeArgs.push(exp);
14853 }
14854 else {
14855 // v-on="obj" -> toHandlers(obj)
14856 pushMergeArg({
14857 type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
14858 loc,
14859 callee: context.helper(TO_HANDLERS),
14860 arguments: isComponent ? [exp] : [exp, `true`]
14861 });
14862 }
14863 }
14864 else {
14865 context.onError(createCompilerError(isVBind
14866 ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
14867 : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
14868 }
14869 continue;
14870 }
14871 const directiveTransform = context.directiveTransforms[name];
14872 if (directiveTransform) {
14873 // has built-in directive transform.
14874 const { props, needRuntime } = directiveTransform(prop, node, context);
14875 !ssr && props.forEach(analyzePatchFlag);
14876 if (isVOn && arg && !isStaticExp(arg)) {
14877 pushMergeArg(createObjectExpression(props, elementLoc));
14878 }
14879 else {
14880 properties.push(...props);
14881 }
14882 if (needRuntime) {
14883 runtimeDirectives.push(prop);
14884 if (isSymbol(needRuntime)) {
14885 directiveImportMap.set(prop, needRuntime);
14886 }
14887 }
14888 }
14889 else if (!isBuiltInDirective(name)) {
14890 // no built-in transform, this is a user custom directive.
14891 runtimeDirectives.push(prop);
14892 // custom dirs may use beforeUpdate so they need to force blocks
14893 // to ensure before-update gets called before children update
14894 if (hasChildren) {
14895 shouldUseBlock = true;
14896 }
14897 }
14898 }
14899 }
14900 let propsExpression = undefined;
14901 // has v-bind="object" or v-on="object", wrap with mergeProps
14902 if (mergeArgs.length) {
14903 // close up any not-yet-merged props
14904 pushMergeArg();
14905 if (mergeArgs.length > 1) {
14906 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14907 }
14908 else {
14909 // single v-bind with nothing else - no need for a mergeProps call
14910 propsExpression = mergeArgs[0];
14911 }
14912 }
14913 else if (properties.length) {
14914 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14915 }
14916 // patchFlag analysis
14917 if (hasDynamicKeys) {
14918 patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
14919 }
14920 else {
14921 if (hasClassBinding && !isComponent) {
14922 patchFlag |= 2 /* PatchFlags.CLASS */;
14923 }
14924 if (hasStyleBinding && !isComponent) {
14925 patchFlag |= 4 /* PatchFlags.STYLE */;
14926 }
14927 if (dynamicPropNames.length) {
14928 patchFlag |= 8 /* PatchFlags.PROPS */;
14929 }
14930 if (hasHydrationEventBinding) {
14931 patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
14932 }
14933 }
14934 if (!shouldUseBlock &&
14935 (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
14936 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14937 patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
14938 }
14939 // pre-normalize props, SSR is skipped for now
14940 if (!context.inSSR && propsExpression) {
14941 switch (propsExpression.type) {
14942 case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
14943 // means that there is no v-bind,
14944 // but still need to deal with dynamic key binding
14945 let classKeyIndex = -1;
14946 let styleKeyIndex = -1;
14947 let hasDynamicKey = false;
14948 for (let i = 0; i < propsExpression.properties.length; i++) {
14949 const key = propsExpression.properties[i].key;
14950 if (isStaticExp(key)) {
14951 if (key.content === 'class') {
14952 classKeyIndex = i;
14953 }
14954 else if (key.content === 'style') {
14955 styleKeyIndex = i;
14956 }
14957 }
14958 else if (!key.isHandlerKey) {
14959 hasDynamicKey = true;
14960 }
14961 }
14962 const classProp = propsExpression.properties[classKeyIndex];
14963 const styleProp = propsExpression.properties[styleKeyIndex];
14964 // no dynamic key
14965 if (!hasDynamicKey) {
14966 if (classProp && !isStaticExp(classProp.value)) {
14967 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14968 }
14969 if (styleProp &&
14970 // the static style is compiled into an object,
14971 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14972 (hasStyleBinding ||
14973 (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
14974 styleProp.value.content.trim()[0] === `[`) ||
14975 // v-bind:style and style both exist,
14976 // v-bind:style with static literal object
14977 styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
14978 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14979 }
14980 }
14981 else {
14982 // dynamic key binding, wrap with `normalizeProps`
14983 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14984 }
14985 break;
14986 case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
14987 // mergeProps call, do nothing
14988 break;
14989 default:
14990 // single v-bind
14991 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14992 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14993 propsExpression
14994 ])
14995 ]);
14996 break;
14997 }
14998 }
14999 return {
15000 props: propsExpression,
15001 directives: runtimeDirectives,
15002 patchFlag,
15003 dynamicPropNames,
15004 shouldUseBlock
15005 };
15006}
15007// Dedupe props in an object literal.
15008// Literal duplicated attributes would have been warned during the parse phase,
15009// however, it's possible to encounter duplicated `onXXX` handlers with different
15010// modifiers. We also need to merge static and dynamic class / style attributes.
15011// - onXXX handlers / style: merge into array
15012// - class: merge into single expression with concatenation
15013function dedupeProperties(properties) {
15014 const knownProps = new Map();
15015 const deduped = [];
15016 for (let i = 0; i < properties.length; i++) {
15017 const prop = properties[i];
15018 // dynamic keys are always allowed
15019 if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
15020 deduped.push(prop);
15021 continue;
15022 }
15023 const name = prop.key.content;
15024 const existing = knownProps.get(name);
15025 if (existing) {
15026 if (name === 'style' || name === 'class' || isOn(name)) {
15027 mergeAsArray$1(existing, prop);
15028 }
15029 // unexpected duplicate, should have emitted error during parse
15030 }
15031 else {
15032 knownProps.set(name, prop);
15033 deduped.push(prop);
15034 }
15035 }
15036 return deduped;
15037}
15038function mergeAsArray$1(existing, incoming) {
15039 if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
15040 existing.value.elements.push(incoming.value);
15041 }
15042 else {
15043 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
15044 }
15045}
15046function buildDirectiveArgs(dir, context) {
15047 const dirArgs = [];
15048 const runtime = directiveImportMap.get(dir);
15049 if (runtime) {
15050 // built-in directive with runtime
15051 dirArgs.push(context.helperString(runtime));
15052 }
15053 else {
15054 {
15055 // inject statement for resolving directive
15056 context.helper(RESOLVE_DIRECTIVE);
15057 context.directives.add(dir.name);
15058 dirArgs.push(toValidAssetId(dir.name, `directive`));
15059 }
15060 }
15061 const { loc } = dir;
15062 if (dir.exp)
15063 dirArgs.push(dir.exp);
15064 if (dir.arg) {
15065 if (!dir.exp) {
15066 dirArgs.push(`void 0`);
15067 }
15068 dirArgs.push(dir.arg);
15069 }
15070 if (Object.keys(dir.modifiers).length) {
15071 if (!dir.arg) {
15072 if (!dir.exp) {
15073 dirArgs.push(`void 0`);
15074 }
15075 dirArgs.push(`void 0`);
15076 }
15077 const trueExpression = createSimpleExpression(`true`, false, loc);
15078 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
15079 }
15080 return createArrayExpression(dirArgs, dir.loc);
15081}
15082function stringifyDynamicPropNames(props) {
15083 let propsNamesString = `[`;
15084 for (let i = 0, l = props.length; i < l; i++) {
15085 propsNamesString += JSON.stringify(props[i]);
15086 if (i < l - 1)
15087 propsNamesString += ', ';
15088 }
15089 return propsNamesString + `]`;
15090}
15091function isComponentTag(tag) {
15092 return tag === 'component' || tag === 'Component';
15093}
15094
15095const transformSlotOutlet = (node, context) => {
15096 if (isSlotOutlet(node)) {
15097 const { children, loc } = node;
15098 const { slotName, slotProps } = processSlotOutlet(node, context);
15099 const slotArgs = [
15100 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
15101 slotName,
15102 '{}',
15103 'undefined',
15104 'true'
15105 ];
15106 let expectedLen = 2;
15107 if (slotProps) {
15108 slotArgs[2] = slotProps;
15109 expectedLen = 3;
15110 }
15111 if (children.length) {
15112 slotArgs[3] = createFunctionExpression([], children, false, false, loc);
15113 expectedLen = 4;
15114 }
15115 if (context.scopeId && !context.slotted) {
15116 expectedLen = 5;
15117 }
15118 slotArgs.splice(expectedLen); // remove unused arguments
15119 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
15120 }
15121};
15122function processSlotOutlet(node, context) {
15123 let slotName = `"default"`;
15124 let slotProps = undefined;
15125 const nonNameProps = [];
15126 for (let i = 0; i < node.props.length; i++) {
15127 const p = node.props[i];
15128 if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
15129 if (p.value) {
15130 if (p.name === 'name') {
15131 slotName = JSON.stringify(p.value.content);
15132 }
15133 else {
15134 p.name = camelize(p.name);
15135 nonNameProps.push(p);
15136 }
15137 }
15138 }
15139 else {
15140 if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
15141 if (p.exp)
15142 slotName = p.exp;
15143 }
15144 else {
15145 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
15146 p.arg.content = camelize(p.arg.content);
15147 }
15148 nonNameProps.push(p);
15149 }
15150 }
15151 }
15152 if (nonNameProps.length > 0) {
15153 const { props, directives } = buildProps(node, context, nonNameProps, false, false);
15154 slotProps = props;
15155 if (directives.length) {
15156 context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
15157 }
15158 }
15159 return {
15160 slotName,
15161 slotProps
15162 };
15163}
15164
15165const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
15166const transformOn = (dir, node, context, augmentor) => {
15167 const { loc, modifiers, arg } = dir;
15168 if (!dir.exp && !modifiers.length) {
15169 context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
15170 }
15171 let eventName;
15172 if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
15173 if (arg.isStatic) {
15174 let rawName = arg.content;
15175 // TODO deprecate @vnodeXXX usage
15176 if (rawName.startsWith('vue:')) {
15177 rawName = `vnode-${rawName.slice(4)}`;
15178 }
15179 const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
15180 rawName.startsWith('vnode') ||
15181 !/[A-Z]/.test(rawName)
15182 ? // for non-element and vnode lifecycle event listeners, auto convert
15183 // it to camelCase. See issue #2249
15184 toHandlerKey(camelize(rawName))
15185 : // preserve case for plain element listeners that have uppercase
15186 // letters, as these may be custom elements' custom events
15187 `on:${rawName}`;
15188 eventName = createSimpleExpression(eventString, true, arg.loc);
15189 }
15190 else {
15191 // #2388
15192 eventName = createCompoundExpression([
15193 `${context.helperString(TO_HANDLER_KEY)}(`,
15194 arg,
15195 `)`
15196 ]);
15197 }
15198 }
15199 else {
15200 // already a compound expression.
15201 eventName = arg;
15202 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
15203 eventName.children.push(`)`);
15204 }
15205 // handler processing
15206 let exp = dir.exp;
15207 if (exp && !exp.content.trim()) {
15208 exp = undefined;
15209 }
15210 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
15211 if (exp) {
15212 const isMemberExp = isMemberExpression(exp.content);
15213 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
15214 const hasMultipleStatements = exp.content.includes(`;`);
15215 {
15216 validateBrowserExpression(exp, context, false, hasMultipleStatements);
15217 }
15218 if (isInlineStatement || (shouldCache && isMemberExp)) {
15219 // wrap inline statement in a function expression
15220 exp = createCompoundExpression([
15221 `${isInlineStatement
15222 ? `$event`
15223 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
15224 exp,
15225 hasMultipleStatements ? `}` : `)`
15226 ]);
15227 }
15228 }
15229 let ret = {
15230 props: [
15231 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
15232 ]
15233 };
15234 // apply extended compiler augmentor
15235 if (augmentor) {
15236 ret = augmentor(ret);
15237 }
15238 if (shouldCache) {
15239 // cache handlers so that it's always the same handler being passed down.
15240 // this avoids unnecessary re-renders when users use inline handlers on
15241 // components.
15242 ret.props[0].value = context.cache(ret.props[0].value);
15243 }
15244 // mark the key as handler for props normalization check
15245 ret.props.forEach(p => (p.key.isHandlerKey = true));
15246 return ret;
15247};
15248
15249// v-bind without arg is handled directly in ./transformElements.ts due to it affecting
15250// codegen for the entire props object. This transform here is only for v-bind
15251// *with* args.
15252const transformBind = (dir, _node, context) => {
15253 const { exp, modifiers, loc } = dir;
15254 const arg = dir.arg;
15255 if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
15256 arg.children.unshift(`(`);
15257 arg.children.push(`) || ""`);
15258 }
15259 else if (!arg.isStatic) {
15260 arg.content = `${arg.content} || ""`;
15261 }
15262 // .sync is replaced by v-model:arg
15263 if (modifiers.includes('camel')) {
15264 if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
15265 if (arg.isStatic) {
15266 arg.content = camelize(arg.content);
15267 }
15268 else {
15269 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
15270 }
15271 }
15272 else {
15273 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
15274 arg.children.push(`)`);
15275 }
15276 }
15277 if (!context.inSSR) {
15278 if (modifiers.includes('prop')) {
15279 injectPrefix(arg, '.');
15280 }
15281 if (modifiers.includes('attr')) {
15282 injectPrefix(arg, '^');
15283 }
15284 }
15285 if (!exp ||
15286 (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
15287 context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
15288 return {
15289 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
15290 };
15291 }
15292 return {
15293 props: [createObjectProperty(arg, exp)]
15294 };
15295};
15296const injectPrefix = (arg, prefix) => {
15297 if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
15298 if (arg.isStatic) {
15299 arg.content = prefix + arg.content;
15300 }
15301 else {
15302 arg.content = `\`${prefix}\${${arg.content}}\``;
15303 }
15304 }
15305 else {
15306 arg.children.unshift(`'${prefix}' + (`);
15307 arg.children.push(`)`);
15308 }
15309};
15310
15311// Merge adjacent text nodes and expressions into a single expression
15312// e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
15313const transformText = (node, context) => {
15314 if (node.type === 0 /* NodeTypes.ROOT */ ||
15315 node.type === 1 /* NodeTypes.ELEMENT */ ||
15316 node.type === 11 /* NodeTypes.FOR */ ||
15317 node.type === 10 /* NodeTypes.IF_BRANCH */) {
15318 // perform the transform on node exit so that all expressions have already
15319 // been processed.
15320 return () => {
15321 const children = node.children;
15322 let currentContainer = undefined;
15323 let hasText = false;
15324 for (let i = 0; i < children.length; i++) {
15325 const child = children[i];
15326 if (isText(child)) {
15327 hasText = true;
15328 for (let j = i + 1; j < children.length; j++) {
15329 const next = children[j];
15330 if (isText(next)) {
15331 if (!currentContainer) {
15332 currentContainer = children[i] = createCompoundExpression([child], child.loc);
15333 }
15334 // merge adjacent text node into current
15335 currentContainer.children.push(` + `, next);
15336 children.splice(j, 1);
15337 j--;
15338 }
15339 else {
15340 currentContainer = undefined;
15341 break;
15342 }
15343 }
15344 }
15345 }
15346 if (!hasText ||
15347 // if this is a plain element with a single text child, leave it
15348 // as-is since the runtime has dedicated fast path for this by directly
15349 // setting textContent of the element.
15350 // for component root it's always normalized anyway.
15351 (children.length === 1 &&
15352 (node.type === 0 /* NodeTypes.ROOT */ ||
15353 (node.type === 1 /* NodeTypes.ELEMENT */ &&
15354 node.tagType === 0 /* ElementTypes.ELEMENT */ &&
15355 // #3756
15356 // custom directives can potentially add DOM elements arbitrarily,
15357 // we need to avoid setting textContent of the element at runtime
15358 // to avoid accidentally overwriting the DOM elements added
15359 // by the user through custom directives.
15360 !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
15361 !context.directiveTransforms[p.name]) &&
15362 // in compat mode, <template> tags with no special directives
15363 // will be rendered as a fragment so its children must be
15364 // converted into vnodes.
15365 !(false ))))) {
15366 return;
15367 }
15368 // pre-convert text nodes into createTextVNode(text) calls to avoid
15369 // runtime normalization.
15370 for (let i = 0; i < children.length; i++) {
15371 const child = children[i];
15372 if (isText(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
15373 const callArgs = [];
15374 // createTextVNode defaults to single whitespace, so if it is a
15375 // single space the code could be an empty call to save bytes.
15376 if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
15377 callArgs.push(child);
15378 }
15379 // mark dynamic text with flag so it gets patched inside a block
15380 if (!context.ssr &&
15381 getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
15382 callArgs.push(1 /* PatchFlags.TEXT */ +
15383 (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
15384 }
15385 children[i] = {
15386 type: 12 /* NodeTypes.TEXT_CALL */,
15387 content: child,
15388 loc: child.loc,
15389 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15390 };
15391 }
15392 }
15393 };
15394 }
15395};
15396
15397const seen = new WeakSet();
15398const transformOnce = (node, context) => {
15399 if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
15400 if (seen.has(node) || context.inVOnce) {
15401 return;
15402 }
15403 seen.add(node);
15404 context.inVOnce = true;
15405 context.helper(SET_BLOCK_TRACKING);
15406 return () => {
15407 context.inVOnce = false;
15408 const cur = context.currentNode;
15409 if (cur.codegenNode) {
15410 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15411 }
15412 };
15413 }
15414};
15415
15416const transformModel = (dir, node, context) => {
15417 const { exp, arg } = dir;
15418 if (!exp) {
15419 context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
15420 return createTransformProps();
15421 }
15422 const rawExp = exp.loc.source;
15423 const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15424 // im SFC <script setup> inline mode, the exp may have been transformed into
15425 // _unref(exp)
15426 const bindingType = context.bindingMetadata[rawExp];
15427 // check props
15428 if (bindingType === "props" /* BindingTypes.PROPS */ ||
15429 bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
15430 context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
15431 return createTransformProps();
15432 }
15433 const maybeRef = !true ;
15434 if (!expString.trim() ||
15435 (!isMemberExpression(expString) && !maybeRef)) {
15436 context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15437 return createTransformProps();
15438 }
15439 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15440 const eventName = arg
15441 ? isStaticExp(arg)
15442 ? `onUpdate:${arg.content}`
15443 : createCompoundExpression(['"onUpdate:" + ', arg])
15444 : `onUpdate:modelValue`;
15445 let assignmentExp;
15446 const eventArg = context.isTS ? `($event: any)` : `$event`;
15447 {
15448 assignmentExp = createCompoundExpression([
15449 `${eventArg} => ((`,
15450 exp,
15451 `) = $event)`
15452 ]);
15453 }
15454 const props = [
15455 // modelValue: foo
15456 createObjectProperty(propName, dir.exp),
15457 // "onUpdate:modelValue": $event => (foo = $event)
15458 createObjectProperty(eventName, assignmentExp)
15459 ];
15460 // modelModifiers: { foo: true, "bar-baz": true }
15461 if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
15462 const modifiers = dir.modifiers
15463 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15464 .join(`, `);
15465 const modifiersKey = arg
15466 ? isStaticExp(arg)
15467 ? `${arg.content}Modifiers`
15468 : createCompoundExpression([arg, ' + "Modifiers"'])
15469 : `modelModifiers`;
15470 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
15471 }
15472 return createTransformProps(props);
15473};
15474function createTransformProps(props = []) {
15475 return { props };
15476}
15477
15478const seen$1 = new WeakSet();
15479const transformMemo = (node, context) => {
15480 if (node.type === 1 /* NodeTypes.ELEMENT */) {
15481 const dir = findDir(node, 'memo');
15482 if (!dir || seen$1.has(node)) {
15483 return;
15484 }
15485 seen$1.add(node);
15486 return () => {
15487 const codegenNode = node.codegenNode ||
15488 context.currentNode.codegenNode;
15489 if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
15490 // non-component sub tree should be turned into a block
15491 if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
15492 makeBlock(codegenNode, context);
15493 }
15494 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15495 dir.exp,
15496 createFunctionExpression(undefined, codegenNode),
15497 `_cache`,
15498 String(context.cached++)
15499 ]);
15500 }
15501 };
15502 }
15503};
15504
15505function getBaseTransformPreset(prefixIdentifiers) {
15506 return [
15507 [
15508 transformOnce,
15509 transformIf,
15510 transformMemo,
15511 transformFor,
15512 ...([]),
15513 ...([transformExpression]
15514 ),
15515 transformSlotOutlet,
15516 transformElement,
15517 trackSlotScopes,
15518 transformText
15519 ],
15520 {
15521 on: transformOn,
15522 bind: transformBind,
15523 model: transformModel
15524 }
15525 ];
15526}
15527// we name it `baseCompile` so that higher order compilers like
15528// @vue/compiler-dom can export `compile` while re-exporting everything else.
15529function baseCompile(template, options = {}) {
15530 const onError = options.onError || defaultOnError;
15531 const isModuleMode = options.mode === 'module';
15532 /* istanbul ignore if */
15533 {
15534 if (options.prefixIdentifiers === true) {
15535 onError(createCompilerError(47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */));
15536 }
15537 else if (isModuleMode) {
15538 onError(createCompilerError(48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */));
15539 }
15540 }
15541 const prefixIdentifiers = !true ;
15542 if (options.cacheHandlers) {
15543 onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
15544 }
15545 if (options.scopeId && !isModuleMode) {
15546 onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
15547 }
15548 const ast = isString(template) ? baseParse(template, options) : template;
15549 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15550 transform(ast, extend({}, options, {
15551 prefixIdentifiers,
15552 nodeTransforms: [
15553 ...nodeTransforms,
15554 ...(options.nodeTransforms || []) // user transforms
15555 ],
15556 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15557 )
15558 }));
15559 return generate(ast, extend({}, options, {
15560 prefixIdentifiers
15561 }));
15562}
15563
15564const noopDirectiveTransform = () => ({ props: [] });
15565
15566const V_MODEL_RADIO = Symbol(`vModelRadio` );
15567const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15568const V_MODEL_TEXT = Symbol(`vModelText` );
15569const V_MODEL_SELECT = Symbol(`vModelSelect` );
15570const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15571const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15572const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15573const V_SHOW = Symbol(`vShow` );
15574const TRANSITION$1 = Symbol(`Transition` );
15575const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15576registerRuntimeHelpers({
15577 [V_MODEL_RADIO]: `vModelRadio`,
15578 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15579 [V_MODEL_TEXT]: `vModelText`,
15580 [V_MODEL_SELECT]: `vModelSelect`,
15581 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15582 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15583 [V_ON_WITH_KEYS]: `withKeys`,
15584 [V_SHOW]: `vShow`,
15585 [TRANSITION$1]: `Transition`,
15586 [TRANSITION_GROUP]: `TransitionGroup`
15587});
15588
15589/* eslint-disable no-restricted-globals */
15590let decoder;
15591function decodeHtmlBrowser(raw, asAttr = false) {
15592 if (!decoder) {
15593 decoder = document.createElement('div');
15594 }
15595 if (asAttr) {
15596 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15597 return decoder.children[0].getAttribute('foo');
15598 }
15599 else {
15600 decoder.innerHTML = raw;
15601 return decoder.textContent;
15602 }
15603}
15604
15605const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15606const parserOptions = {
15607 isVoidTag,
15608 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15609 isPreTag: tag => tag === 'pre',
15610 decodeEntities: decodeHtmlBrowser ,
15611 isBuiltInComponent: (tag) => {
15612 if (isBuiltInType(tag, `Transition`)) {
15613 return TRANSITION$1;
15614 }
15615 else if (isBuiltInType(tag, `TransitionGroup`)) {
15616 return TRANSITION_GROUP;
15617 }
15618 },
15619 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15620 getNamespace(tag, parent) {
15621 let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
15622 if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
15623 if (parent.tag === 'annotation-xml') {
15624 if (tag === 'svg') {
15625 return 1 /* DOMNamespaces.SVG */;
15626 }
15627 if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
15628 a.name === 'encoding' &&
15629 a.value != null &&
15630 (a.value.content === 'text/html' ||
15631 a.value.content === 'application/xhtml+xml'))) {
15632 ns = 0 /* DOMNamespaces.HTML */;
15633 }
15634 }
15635 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15636 tag !== 'mglyph' &&
15637 tag !== 'malignmark') {
15638 ns = 0 /* DOMNamespaces.HTML */;
15639 }
15640 }
15641 else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
15642 if (parent.tag === 'foreignObject' ||
15643 parent.tag === 'desc' ||
15644 parent.tag === 'title') {
15645 ns = 0 /* DOMNamespaces.HTML */;
15646 }
15647 }
15648 if (ns === 0 /* DOMNamespaces.HTML */) {
15649 if (tag === 'svg') {
15650 return 1 /* DOMNamespaces.SVG */;
15651 }
15652 if (tag === 'math') {
15653 return 2 /* DOMNamespaces.MATH_ML */;
15654 }
15655 }
15656 return ns;
15657 },
15658 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15659 getTextMode({ tag, ns }) {
15660 if (ns === 0 /* DOMNamespaces.HTML */) {
15661 if (tag === 'textarea' || tag === 'title') {
15662 return 1 /* TextModes.RCDATA */;
15663 }
15664 if (isRawTextContainer(tag)) {
15665 return 2 /* TextModes.RAWTEXT */;
15666 }
15667 }
15668 return 0 /* TextModes.DATA */;
15669 }
15670};
15671
15672// Parse inline CSS strings for static style attributes into an object.
15673// This is a NodeTransform since it works on the static `style` attribute and
15674// converts it into a dynamic equivalent:
15675// style="color: red" -> :style='{ "color": "red" }'
15676// It is then processed by `transformElement` and included in the generated
15677// props.
15678const transformStyle = node => {
15679 if (node.type === 1 /* NodeTypes.ELEMENT */) {
15680 node.props.forEach((p, i) => {
15681 if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
15682 // replace p with an expression node
15683 node.props[i] = {
15684 type: 7 /* NodeTypes.DIRECTIVE */,
15685 name: `bind`,
15686 arg: createSimpleExpression(`style`, true, p.loc),
15687 exp: parseInlineCSS(p.value.content, p.loc),
15688 modifiers: [],
15689 loc: p.loc
15690 };
15691 }
15692 });
15693 }
15694};
15695const parseInlineCSS = (cssText, loc) => {
15696 const normalized = parseStringStyle(cssText);
15697 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
15698};
15699
15700function createDOMCompilerError(code, loc) {
15701 return createCompilerError(code, loc, DOMErrorMessages );
15702}
15703const DOMErrorMessages = {
15704 [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15705 [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15706 [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15707 [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15708 [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15709 [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15710 [57 /* DOMErrorCodes.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.`,
15711 [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15712 [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15713 [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15714 [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15715};
15716
15717const transformVHtml = (dir, node, context) => {
15718 const { exp, loc } = dir;
15719 if (!exp) {
15720 context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
15721 }
15722 if (node.children.length) {
15723 context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
15724 node.children.length = 0;
15725 }
15726 return {
15727 props: [
15728 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15729 ]
15730 };
15731};
15732
15733const transformVText = (dir, node, context) => {
15734 const { exp, loc } = dir;
15735 if (!exp) {
15736 context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
15737 }
15738 if (node.children.length) {
15739 context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
15740 node.children.length = 0;
15741 }
15742 return {
15743 props: [
15744 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15745 ? getConstantType(exp, context) > 0
15746 ? exp
15747 : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15748 : createSimpleExpression('', true))
15749 ]
15750 };
15751};
15752
15753const transformModel$1 = (dir, node, context) => {
15754 const baseResult = transformModel(dir, node, context);
15755 // base transform has errors OR component v-model (only need props)
15756 if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
15757 return baseResult;
15758 }
15759 if (dir.arg) {
15760 context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15761 }
15762 function checkDuplicatedValue() {
15763 const value = findProp(node, 'value');
15764 if (value) {
15765 context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15766 }
15767 }
15768 const { tag } = node;
15769 const isCustomElement = context.isCustomElement(tag);
15770 if (tag === 'input' ||
15771 tag === 'textarea' ||
15772 tag === 'select' ||
15773 isCustomElement) {
15774 let directiveToUse = V_MODEL_TEXT;
15775 let isInvalidType = false;
15776 if (tag === 'input' || isCustomElement) {
15777 const type = findProp(node, `type`);
15778 if (type) {
15779 if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
15780 // :type="foo"
15781 directiveToUse = V_MODEL_DYNAMIC;
15782 }
15783 else if (type.value) {
15784 switch (type.value.content) {
15785 case 'radio':
15786 directiveToUse = V_MODEL_RADIO;
15787 break;
15788 case 'checkbox':
15789 directiveToUse = V_MODEL_CHECKBOX;
15790 break;
15791 case 'file':
15792 isInvalidType = true;
15793 context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15794 break;
15795 default:
15796 // text type
15797 checkDuplicatedValue();
15798 break;
15799 }
15800 }
15801 }
15802 else if (hasDynamicKeyVBind(node)) {
15803 // element has bindings with dynamic keys, which can possibly contain
15804 // "type".
15805 directiveToUse = V_MODEL_DYNAMIC;
15806 }
15807 else {
15808 // text type
15809 checkDuplicatedValue();
15810 }
15811 }
15812 else if (tag === 'select') {
15813 directiveToUse = V_MODEL_SELECT;
15814 }
15815 else {
15816 // textarea
15817 checkDuplicatedValue();
15818 }
15819 // inject runtime directive
15820 // by returning the helper symbol via needRuntime
15821 // the import will replaced a resolveDirective call.
15822 if (!isInvalidType) {
15823 baseResult.needRuntime = context.helper(directiveToUse);
15824 }
15825 }
15826 else {
15827 context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15828 }
15829 // native vmodel doesn't need the `modelValue` props since they are also
15830 // passed to the runtime as `binding.value`. removing it reduces code size.
15831 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
15832 p.key.content === 'modelValue'));
15833 return baseResult;
15834};
15835
15836const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15837const isNonKeyModifier = /*#__PURE__*/ makeMap(
15838// event propagation management
15839`stop,prevent,self,` +
15840 // system modifiers + exact
15841 `ctrl,shift,alt,meta,exact,` +
15842 // mouse
15843 `middle`);
15844// left & right could be mouse or key modifiers based on event type
15845const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15846const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15847const resolveModifiers = (key, modifiers, context, loc) => {
15848 const keyModifiers = [];
15849 const nonKeyModifiers = [];
15850 const eventOptionModifiers = [];
15851 for (let i = 0; i < modifiers.length; i++) {
15852 const modifier = modifiers[i];
15853 if (isEventOptionModifier(modifier)) {
15854 // eventOptionModifiers: modifiers for addEventListener() options,
15855 // e.g. .passive & .capture
15856 eventOptionModifiers.push(modifier);
15857 }
15858 else {
15859 // runtimeModifiers: modifiers that needs runtime guards
15860 if (maybeKeyModifier(modifier)) {
15861 if (isStaticExp(key)) {
15862 if (isKeyboardEvent(key.content)) {
15863 keyModifiers.push(modifier);
15864 }
15865 else {
15866 nonKeyModifiers.push(modifier);
15867 }
15868 }
15869 else {
15870 keyModifiers.push(modifier);
15871 nonKeyModifiers.push(modifier);
15872 }
15873 }
15874 else {
15875 if (isNonKeyModifier(modifier)) {
15876 nonKeyModifiers.push(modifier);
15877 }
15878 else {
15879 keyModifiers.push(modifier);
15880 }
15881 }
15882 }
15883 }
15884 return {
15885 keyModifiers,
15886 nonKeyModifiers,
15887 eventOptionModifiers
15888 };
15889};
15890const transformClick = (key, event) => {
15891 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15892 return isStaticClick
15893 ? createSimpleExpression(event, true)
15894 : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
15895 ? createCompoundExpression([
15896 `(`,
15897 key,
15898 `) === "onClick" ? "${event}" : (`,
15899 key,
15900 `)`
15901 ])
15902 : key;
15903};
15904const transformOn$1 = (dir, node, context) => {
15905 return transformOn(dir, node, context, baseResult => {
15906 const { modifiers } = dir;
15907 if (!modifiers.length)
15908 return baseResult;
15909 let { key, value: handlerExp } = baseResult.props[0];
15910 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15911 // normalize click.right and click.middle since they don't actually fire
15912 if (nonKeyModifiers.includes('right')) {
15913 key = transformClick(key, `onContextmenu`);
15914 }
15915 if (nonKeyModifiers.includes('middle')) {
15916 key = transformClick(key, `onMouseup`);
15917 }
15918 if (nonKeyModifiers.length) {
15919 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15920 handlerExp,
15921 JSON.stringify(nonKeyModifiers)
15922 ]);
15923 }
15924 if (keyModifiers.length &&
15925 // if event name is dynamic, always wrap with keys guard
15926 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15927 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15928 handlerExp,
15929 JSON.stringify(keyModifiers)
15930 ]);
15931 }
15932 if (eventOptionModifiers.length) {
15933 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15934 key = isStaticExp(key)
15935 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15936 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15937 }
15938 return {
15939 props: [createObjectProperty(key, handlerExp)]
15940 };
15941 });
15942};
15943
15944const transformShow = (dir, node, context) => {
15945 const { exp, loc } = dir;
15946 if (!exp) {
15947 context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
15948 }
15949 return {
15950 props: [],
15951 needRuntime: context.helper(V_SHOW)
15952 };
15953};
15954
15955const transformTransition = (node, context) => {
15956 if (node.type === 1 /* NodeTypes.ELEMENT */ &&
15957 node.tagType === 1 /* ElementTypes.COMPONENT */) {
15958 const component = context.isBuiltInComponent(node.tag);
15959 if (component === TRANSITION$1) {
15960 return () => {
15961 if (!node.children.length) {
15962 return;
15963 }
15964 // warn multiple transition children
15965 if (hasMultipleChildren(node)) {
15966 context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
15967 start: node.children[0].loc.start,
15968 end: node.children[node.children.length - 1].loc.end,
15969 source: ''
15970 }));
15971 }
15972 // check if it's s single child w/ v-show
15973 // if yes, inject "persisted: true" to the transition props
15974 const child = node.children[0];
15975 if (child.type === 1 /* NodeTypes.ELEMENT */) {
15976 for (const p of child.props) {
15977 if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
15978 node.props.push({
15979 type: 6 /* NodeTypes.ATTRIBUTE */,
15980 name: 'persisted',
15981 value: undefined,
15982 loc: node.loc
15983 });
15984 }
15985 }
15986 }
15987 };
15988 }
15989 }
15990};
15991function hasMultipleChildren(node) {
15992 // #1352 filter out potential comment nodes.
15993 const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
15994 !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
15995 const child = children[0];
15996 return (children.length !== 1 ||
15997 child.type === 11 /* NodeTypes.FOR */ ||
15998 (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
15999}
16000
16001const ignoreSideEffectTags = (node, context) => {
16002 if (node.type === 1 /* NodeTypes.ELEMENT */ &&
16003 node.tagType === 0 /* ElementTypes.ELEMENT */ &&
16004 (node.tag === 'script' || node.tag === 'style')) {
16005 context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
16006 context.removeNode();
16007 }
16008};
16009
16010const DOMNodeTransforms = [
16011 transformStyle,
16012 ...([transformTransition] )
16013];
16014const DOMDirectiveTransforms = {
16015 cloak: noopDirectiveTransform,
16016 html: transformVHtml,
16017 text: transformVText,
16018 model: transformModel$1,
16019 on: transformOn$1,
16020 show: transformShow
16021};
16022function compile$1(template, options = {}) {
16023 return baseCompile(template, extend({}, parserOptions, options, {
16024 nodeTransforms: [
16025 // ignore <script> and <tag>
16026 // this is not put inside DOMNodeTransforms because that list is used
16027 // by compiler-ssr to generate vnode fallback branches
16028 ignoreSideEffectTags,
16029 ...DOMNodeTransforms,
16030 ...(options.nodeTransforms || [])
16031 ],
16032 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
16033 transformHoist: null
16034 }));
16035}
16036
16037// This entry is the "full-build" that includes both the runtime
16038{
16039 initDev();
16040}
16041const compileCache = Object.create(null);
16042function compileToFunction(template, options) {
16043 if (!isString(template)) {
16044 if (template.nodeType) {
16045 template = template.innerHTML;
16046 }
16047 else {
16048 warn$1(`invalid template option: `, template);
16049 return NOOP;
16050 }
16051 }
16052 const key = template;
16053 const cached = compileCache[key];
16054 if (cached) {
16055 return cached;
16056 }
16057 if (template[0] === '#') {
16058 const el = document.querySelector(template);
16059 if (!el) {
16060 warn$1(`Template element not found or is empty: ${template}`);
16061 }
16062 // __UNSAFE__
16063 // Reason: potential execution of JS expressions in in-DOM template.
16064 // The user must make sure the in-DOM template is trusted. If it's rendered
16065 // by the server, the template should not contain any user data.
16066 template = el ? el.innerHTML : ``;
16067 }
16068 const opts = extend({
16069 hoistStatic: true,
16070 onError: onError ,
16071 onWarn: e => onError(e, true)
16072 }, options);
16073 if (!opts.isCustomElement && typeof customElements !== 'undefined') {
16074 opts.isCustomElement = tag => !!customElements.get(tag);
16075 }
16076 const { code } = compile$1(template, opts);
16077 function onError(err, asWarning = false) {
16078 const message = asWarning
16079 ? err.message
16080 : `Template compilation error: ${err.message}`;
16081 const codeFrame = err.loc &&
16082 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
16083 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
16084 }
16085 // The wildcard import results in a huge object with every export
16086 // with keys that cannot be mangled, and can be quite heavy size-wise.
16087 // In the global build we know `Vue` is available globally so we can avoid
16088 // the wildcard object.
16089 const render = (new Function('Vue', code)(runtimeDom));
16090 render._rc = true;
16091 return (compileCache[key] = render);
16092}
16093registerRuntimeCompiler(compileToFunction);
16094
16095export { 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 };