UNPKG

642 kBJavaScriptView Raw
1var Vue = (function (exports) {
2 'use strict';
3
4 /**
5 * Make a map and return a function for checking if a key
6 * is in that map.
7 * IMPORTANT: all calls of this function must be prefixed with
8 * \/\*#\_\_PURE\_\_\*\/
9 * So that rollup can tree-shake them if necessary.
10 */
11 function makeMap(str, expectsLowerCase) {
12 const map = Object.create(null);
13 const list = str.split(',');
14 for (let i = 0; i < list.length; i++) {
15 map[list[i]] = true;
16 }
17 return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
18 }
19
20 /**
21 * dev only flag -> name mapping
22 */
23 const PatchFlagNames = {
24 [1 /* TEXT */]: `TEXT`,
25 [2 /* CLASS */]: `CLASS`,
26 [4 /* STYLE */]: `STYLE`,
27 [8 /* PROPS */]: `PROPS`,
28 [16 /* FULL_PROPS */]: `FULL_PROPS`,
29 [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
30 [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
31 [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
32 [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
33 [512 /* NEED_PATCH */]: `NEED_PATCH`,
34 [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
35 [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
36 [-1 /* HOISTED */]: `HOISTED`,
37 [-2 /* BAIL */]: `BAIL`
38 };
39
40 /**
41 * Dev only
42 */
43 const slotFlagsText = {
44 [1 /* STABLE */]: 'STABLE',
45 [2 /* DYNAMIC */]: 'DYNAMIC',
46 [3 /* FORWARDED */]: 'FORWARDED'
47 };
48
49 const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
50 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
51 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
52 const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
53
54 const range = 2;
55 function generateCodeFrame(source, start = 0, end = source.length) {
56 // Split the content into individual lines but capture the newline sequence
57 // that separated each line. This is important because the actual sequence is
58 // needed to properly take into account the full line length for offset
59 // comparison
60 let lines = source.split(/(\r?\n)/);
61 // Separate the lines and newline sequences into separate arrays for easier referencing
62 const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
63 lines = lines.filter((_, idx) => idx % 2 === 0);
64 let count = 0;
65 const res = [];
66 for (let i = 0; i < lines.length; i++) {
67 count +=
68 lines[i].length +
69 ((newlineSequences[i] && newlineSequences[i].length) || 0);
70 if (count >= start) {
71 for (let j = i - range; j <= i + range || end > count; j++) {
72 if (j < 0 || j >= lines.length)
73 continue;
74 const line = j + 1;
75 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
76 const lineLength = lines[j].length;
77 const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
78 if (j === i) {
79 // push underline
80 const pad = start - (count - (lineLength + newLineSeqLength));
81 const length = Math.max(1, end > count ? lineLength - pad : end - start);
82 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
83 }
84 else if (j > i) {
85 if (end > count) {
86 const length = Math.max(Math.min(end - count, lineLength), 1);
87 res.push(` | ` + '^'.repeat(length));
88 }
89 count += lineLength + newLineSeqLength;
90 }
91 }
92 break;
93 }
94 }
95 return res.join('\n');
96 }
97
98 /**
99 * On the client we only need to offer special cases for boolean attributes that
100 * have different names from their corresponding dom properties:
101 * - itemscope -> N/A
102 * - allowfullscreen -> allowFullscreen
103 * - formnovalidate -> formNoValidate
104 * - ismap -> isMap
105 * - nomodule -> noModule
106 * - novalidate -> noValidate
107 * - readonly -> readOnly
108 */
109 const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
110 const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
111 /**
112 * Boolean attributes should be included if the value is truthy or ''.
113 * e.g. <select multiple> compiles to { multiple: '' }
114 */
115 function includeBooleanAttr(value) {
116 return !!value || value === '';
117 }
118
119 function normalizeStyle(value) {
120 if (isArray(value)) {
121 const res = {};
122 for (let i = 0; i < value.length; i++) {
123 const item = value[i];
124 const normalized = isString(item)
125 ? parseStringStyle(item)
126 : normalizeStyle(item);
127 if (normalized) {
128 for (const key in normalized) {
129 res[key] = normalized[key];
130 }
131 }
132 }
133 return res;
134 }
135 else if (isString(value)) {
136 return value;
137 }
138 else if (isObject(value)) {
139 return value;
140 }
141 }
142 const listDelimiterRE = /;(?![^(]*\))/g;
143 const propertyDelimiterRE = /:(.+)/;
144 function parseStringStyle(cssText) {
145 const ret = {};
146 cssText.split(listDelimiterRE).forEach(item => {
147 if (item) {
148 const tmp = item.split(propertyDelimiterRE);
149 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
150 }
151 });
152 return ret;
153 }
154 function normalizeClass(value) {
155 let res = '';
156 if (isString(value)) {
157 res = value;
158 }
159 else if (isArray(value)) {
160 for (let i = 0; i < value.length; i++) {
161 const normalized = normalizeClass(value[i]);
162 if (normalized) {
163 res += normalized + ' ';
164 }
165 }
166 }
167 else if (isObject(value)) {
168 for (const name in value) {
169 if (value[name]) {
170 res += name + ' ';
171 }
172 }
173 }
174 return res.trim();
175 }
176 function normalizeProps(props) {
177 if (!props)
178 return null;
179 let { class: klass, style } = props;
180 if (klass && !isString(klass)) {
181 props.class = normalizeClass(klass);
182 }
183 if (style) {
184 props.style = normalizeStyle(style);
185 }
186 return props;
187 }
188
189 // These tag configs are shared between compiler-dom and runtime-dom, so they
190 // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
191 const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
192 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
193 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
194 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
195 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
196 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
197 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
198 'option,output,progress,select,textarea,details,dialog,menu,' +
199 'summary,template,blockquote,iframe,tfoot';
200 // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
201 const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
202 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
203 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
204 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
205 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
206 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
207 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
208 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
209 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
210 'text,textPath,title,tspan,unknown,use,view';
211 const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
212 const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
213 const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
214 const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
215
216 function looseCompareArrays(a, b) {
217 if (a.length !== b.length)
218 return false;
219 let equal = true;
220 for (let i = 0; equal && i < a.length; i++) {
221 equal = looseEqual(a[i], b[i]);
222 }
223 return equal;
224 }
225 function looseEqual(a, b) {
226 if (a === b)
227 return true;
228 let aValidType = isDate(a);
229 let bValidType = isDate(b);
230 if (aValidType || bValidType) {
231 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
232 }
233 aValidType = isArray(a);
234 bValidType = isArray(b);
235 if (aValidType || bValidType) {
236 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
237 }
238 aValidType = isObject(a);
239 bValidType = isObject(b);
240 if (aValidType || bValidType) {
241 /* istanbul ignore if: this if will probably never be called */
242 if (!aValidType || !bValidType) {
243 return false;
244 }
245 const aKeysCount = Object.keys(a).length;
246 const bKeysCount = Object.keys(b).length;
247 if (aKeysCount !== bKeysCount) {
248 return false;
249 }
250 for (const key in a) {
251 const aHasKey = a.hasOwnProperty(key);
252 const bHasKey = b.hasOwnProperty(key);
253 if ((aHasKey && !bHasKey) ||
254 (!aHasKey && bHasKey) ||
255 !looseEqual(a[key], b[key])) {
256 return false;
257 }
258 }
259 }
260 return String(a) === String(b);
261 }
262 function looseIndexOf(arr, val) {
263 return arr.findIndex(item => looseEqual(item, val));
264 }
265
266 /**
267 * For converting {{ interpolation }} values to displayed strings.
268 * @private
269 */
270 const toDisplayString = (val) => {
271 return val == null
272 ? ''
273 : isArray(val) ||
274 (isObject(val) &&
275 (val.toString === objectToString || !isFunction(val.toString)))
276 ? JSON.stringify(val, replacer, 2)
277 : String(val);
278 };
279 const replacer = (_key, val) => {
280 // can't use isRef here since @vue/shared has no deps
281 if (val && val.__v_isRef) {
282 return replacer(_key, val.value);
283 }
284 else if (isMap(val)) {
285 return {
286 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
287 entries[`${key} =>`] = val;
288 return entries;
289 }, {})
290 };
291 }
292 else if (isSet(val)) {
293 return {
294 [`Set(${val.size})`]: [...val.values()]
295 };
296 }
297 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
298 return String(val);
299 }
300 return val;
301 };
302
303 const EMPTY_OBJ = Object.freeze({})
304 ;
305 const EMPTY_ARR = Object.freeze([]) ;
306 const NOOP = () => { };
307 /**
308 * Always return false.
309 */
310 const NO = () => false;
311 const onRE = /^on[^a-z]/;
312 const isOn = (key) => onRE.test(key);
313 const isModelListener = (key) => key.startsWith('onUpdate:');
314 const extend = Object.assign;
315 const remove = (arr, el) => {
316 const i = arr.indexOf(el);
317 if (i > -1) {
318 arr.splice(i, 1);
319 }
320 };
321 const hasOwnProperty = Object.prototype.hasOwnProperty;
322 const hasOwn = (val, key) => hasOwnProperty.call(val, key);
323 const isArray = Array.isArray;
324 const isMap = (val) => toTypeString(val) === '[object Map]';
325 const isSet = (val) => toTypeString(val) === '[object Set]';
326 const isDate = (val) => val instanceof Date;
327 const isFunction = (val) => typeof val === 'function';
328 const isString = (val) => typeof val === 'string';
329 const isSymbol = (val) => typeof val === 'symbol';
330 const isObject = (val) => val !== null && typeof val === 'object';
331 const isPromise = (val) => {
332 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
333 };
334 const objectToString = Object.prototype.toString;
335 const toTypeString = (value) => objectToString.call(value);
336 const toRawType = (value) => {
337 // extract "RawType" from strings like "[object RawType]"
338 return toTypeString(value).slice(8, -1);
339 };
340 const isPlainObject = (val) => toTypeString(val) === '[object Object]';
341 const isIntegerKey = (key) => isString(key) &&
342 key !== 'NaN' &&
343 key[0] !== '-' &&
344 '' + parseInt(key, 10) === key;
345 const isReservedProp = /*#__PURE__*/ makeMap(
346 // the leading comma is intentional so empty string "" is also included
347 ',key,ref,' +
348 'onVnodeBeforeMount,onVnodeMounted,' +
349 'onVnodeBeforeUpdate,onVnodeUpdated,' +
350 'onVnodeBeforeUnmount,onVnodeUnmounted');
351 const cacheStringFunction = (fn) => {
352 const cache = Object.create(null);
353 return ((str) => {
354 const hit = cache[str];
355 return hit || (cache[str] = fn(str));
356 });
357 };
358 const camelizeRE = /-(\w)/g;
359 /**
360 * @private
361 */
362 const camelize = cacheStringFunction((str) => {
363 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
364 });
365 const hyphenateRE = /\B([A-Z])/g;
366 /**
367 * @private
368 */
369 const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
370 /**
371 * @private
372 */
373 const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
374 /**
375 * @private
376 */
377 const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
378 // compare whether a value has changed, accounting for NaN.
379 const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
380 const invokeArrayFns = (fns, arg) => {
381 for (let i = 0; i < fns.length; i++) {
382 fns[i](arg);
383 }
384 };
385 const def = (obj, key, value) => {
386 Object.defineProperty(obj, key, {
387 configurable: true,
388 enumerable: false,
389 value
390 });
391 };
392 const toNumber = (val) => {
393 const n = parseFloat(val);
394 return isNaN(n) ? val : n;
395 };
396 let _globalThis;
397 const getGlobalThis = () => {
398 return (_globalThis ||
399 (_globalThis =
400 typeof globalThis !== 'undefined'
401 ? globalThis
402 : typeof self !== 'undefined'
403 ? self
404 : typeof window !== 'undefined'
405 ? window
406 : typeof global !== 'undefined'
407 ? global
408 : {}));
409 };
410
411 function warn(msg, ...args) {
412 console.warn(`[Vue warn] ${msg}`, ...args);
413 }
414
415 let activeEffectScope;
416 const effectScopeStack = [];
417 class EffectScope {
418 constructor(detached = false) {
419 this.active = true;
420 this.effects = [];
421 this.cleanups = [];
422 if (!detached && activeEffectScope) {
423 this.parent = activeEffectScope;
424 this.index =
425 (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
426 }
427 }
428 run(fn) {
429 if (this.active) {
430 try {
431 this.on();
432 return fn();
433 }
434 finally {
435 this.off();
436 }
437 }
438 else {
439 warn(`cannot run an inactive effect scope.`);
440 }
441 }
442 on() {
443 if (this.active) {
444 effectScopeStack.push(this);
445 activeEffectScope = this;
446 }
447 }
448 off() {
449 if (this.active) {
450 effectScopeStack.pop();
451 activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
452 }
453 }
454 stop(fromParent) {
455 if (this.active) {
456 this.effects.forEach(e => e.stop());
457 this.cleanups.forEach(cleanup => cleanup());
458 if (this.scopes) {
459 this.scopes.forEach(e => e.stop(true));
460 }
461 // nested scope, dereference from parent to avoid memory leaks
462 if (this.parent && !fromParent) {
463 // optimized O(1) removal
464 const last = this.parent.scopes.pop();
465 if (last && last !== this) {
466 this.parent.scopes[this.index] = last;
467 last.index = this.index;
468 }
469 }
470 this.active = false;
471 }
472 }
473 }
474 function effectScope(detached) {
475 return new EffectScope(detached);
476 }
477 function recordEffectScope(effect, scope) {
478 scope = scope || activeEffectScope;
479 if (scope && scope.active) {
480 scope.effects.push(effect);
481 }
482 }
483 function getCurrentScope() {
484 return activeEffectScope;
485 }
486 function onScopeDispose(fn) {
487 if (activeEffectScope) {
488 activeEffectScope.cleanups.push(fn);
489 }
490 else {
491 warn(`onScopeDispose() is called when there is no active effect scope` +
492 ` to be associated with.`);
493 }
494 }
495
496 const createDep = (effects) => {
497 const dep = new Set(effects);
498 dep.w = 0;
499 dep.n = 0;
500 return dep;
501 };
502 const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
503 const newTracked = (dep) => (dep.n & trackOpBit) > 0;
504 const initDepMarkers = ({ deps }) => {
505 if (deps.length) {
506 for (let i = 0; i < deps.length; i++) {
507 deps[i].w |= trackOpBit; // set was tracked
508 }
509 }
510 };
511 const finalizeDepMarkers = (effect) => {
512 const { deps } = effect;
513 if (deps.length) {
514 let ptr = 0;
515 for (let i = 0; i < deps.length; i++) {
516 const dep = deps[i];
517 if (wasTracked(dep) && !newTracked(dep)) {
518 dep.delete(effect);
519 }
520 else {
521 deps[ptr++] = dep;
522 }
523 // clear bits
524 dep.w &= ~trackOpBit;
525 dep.n &= ~trackOpBit;
526 }
527 deps.length = ptr;
528 }
529 };
530
531 const targetMap = new WeakMap();
532 // The number of effects currently being tracked recursively.
533 let effectTrackDepth = 0;
534 let trackOpBit = 1;
535 /**
536 * The bitwise track markers support at most 30 levels op recursion.
537 * This value is chosen to enable modern JS engines to use a SMI on all platforms.
538 * When recursion depth is greater, fall back to using a full cleanup.
539 */
540 const maxMarkerBits = 30;
541 const effectStack = [];
542 let activeEffect;
543 const ITERATE_KEY = Symbol('iterate' );
544 const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
545 class ReactiveEffect {
546 constructor(fn, scheduler = null, scope) {
547 this.fn = fn;
548 this.scheduler = scheduler;
549 this.active = true;
550 this.deps = [];
551 recordEffectScope(this, scope);
552 }
553 run() {
554 if (!this.active) {
555 return this.fn();
556 }
557 if (!effectStack.includes(this)) {
558 try {
559 effectStack.push((activeEffect = this));
560 enableTracking();
561 trackOpBit = 1 << ++effectTrackDepth;
562 if (effectTrackDepth <= maxMarkerBits) {
563 initDepMarkers(this);
564 }
565 else {
566 cleanupEffect(this);
567 }
568 return this.fn();
569 }
570 finally {
571 if (effectTrackDepth <= maxMarkerBits) {
572 finalizeDepMarkers(this);
573 }
574 trackOpBit = 1 << --effectTrackDepth;
575 resetTracking();
576 effectStack.pop();
577 const n = effectStack.length;
578 activeEffect = n > 0 ? effectStack[n - 1] : undefined;
579 }
580 }
581 }
582 stop() {
583 if (this.active) {
584 cleanupEffect(this);
585 if (this.onStop) {
586 this.onStop();
587 }
588 this.active = false;
589 }
590 }
591 }
592 function cleanupEffect(effect) {
593 const { deps } = effect;
594 if (deps.length) {
595 for (let i = 0; i < deps.length; i++) {
596 deps[i].delete(effect);
597 }
598 deps.length = 0;
599 }
600 }
601 function effect(fn, options) {
602 if (fn.effect) {
603 fn = fn.effect.fn;
604 }
605 const _effect = new ReactiveEffect(fn);
606 if (options) {
607 extend(_effect, options);
608 if (options.scope)
609 recordEffectScope(_effect, options.scope);
610 }
611 if (!options || !options.lazy) {
612 _effect.run();
613 }
614 const runner = _effect.run.bind(_effect);
615 runner.effect = _effect;
616 return runner;
617 }
618 function stop(runner) {
619 runner.effect.stop();
620 }
621 let shouldTrack = true;
622 const trackStack = [];
623 function pauseTracking() {
624 trackStack.push(shouldTrack);
625 shouldTrack = false;
626 }
627 function enableTracking() {
628 trackStack.push(shouldTrack);
629 shouldTrack = true;
630 }
631 function resetTracking() {
632 const last = trackStack.pop();
633 shouldTrack = last === undefined ? true : last;
634 }
635 function track(target, type, key) {
636 if (!isTracking()) {
637 return;
638 }
639 let depsMap = targetMap.get(target);
640 if (!depsMap) {
641 targetMap.set(target, (depsMap = new Map()));
642 }
643 let dep = depsMap.get(key);
644 if (!dep) {
645 depsMap.set(key, (dep = createDep()));
646 }
647 const eventInfo = { effect: activeEffect, target, type, key }
648 ;
649 trackEffects(dep, eventInfo);
650 }
651 function isTracking() {
652 return shouldTrack && activeEffect !== undefined;
653 }
654 function trackEffects(dep, debuggerEventExtraInfo) {
655 let shouldTrack = false;
656 if (effectTrackDepth <= maxMarkerBits) {
657 if (!newTracked(dep)) {
658 dep.n |= trackOpBit; // set newly tracked
659 shouldTrack = !wasTracked(dep);
660 }
661 }
662 else {
663 // Full cleanup mode.
664 shouldTrack = !dep.has(activeEffect);
665 }
666 if (shouldTrack) {
667 dep.add(activeEffect);
668 activeEffect.deps.push(dep);
669 if (activeEffect.onTrack) {
670 activeEffect.onTrack(Object.assign({
671 effect: activeEffect
672 }, debuggerEventExtraInfo));
673 }
674 }
675 }
676 function trigger(target, type, key, newValue, oldValue, oldTarget) {
677 const depsMap = targetMap.get(target);
678 if (!depsMap) {
679 // never been tracked
680 return;
681 }
682 let deps = [];
683 if (type === "clear" /* CLEAR */) {
684 // collection being cleared
685 // trigger all effects for target
686 deps = [...depsMap.values()];
687 }
688 else if (key === 'length' && isArray(target)) {
689 depsMap.forEach((dep, key) => {
690 if (key === 'length' || key >= newValue) {
691 deps.push(dep);
692 }
693 });
694 }
695 else {
696 // schedule runs for SET | ADD | DELETE
697 if (key !== void 0) {
698 deps.push(depsMap.get(key));
699 }
700 // also run for iteration key on ADD | DELETE | Map.SET
701 switch (type) {
702 case "add" /* ADD */:
703 if (!isArray(target)) {
704 deps.push(depsMap.get(ITERATE_KEY));
705 if (isMap(target)) {
706 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
707 }
708 }
709 else if (isIntegerKey(key)) {
710 // new index added to array -> length changes
711 deps.push(depsMap.get('length'));
712 }
713 break;
714 case "delete" /* DELETE */:
715 if (!isArray(target)) {
716 deps.push(depsMap.get(ITERATE_KEY));
717 if (isMap(target)) {
718 deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
719 }
720 }
721 break;
722 case "set" /* SET */:
723 if (isMap(target)) {
724 deps.push(depsMap.get(ITERATE_KEY));
725 }
726 break;
727 }
728 }
729 const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
730 ;
731 if (deps.length === 1) {
732 if (deps[0]) {
733 {
734 triggerEffects(deps[0], eventInfo);
735 }
736 }
737 }
738 else {
739 const effects = [];
740 for (const dep of deps) {
741 if (dep) {
742 effects.push(...dep);
743 }
744 }
745 {
746 triggerEffects(createDep(effects), eventInfo);
747 }
748 }
749 }
750 function triggerEffects(dep, debuggerEventExtraInfo) {
751 // spread into array for stabilization
752 for (const effect of isArray(dep) ? dep : [...dep]) {
753 if (effect !== activeEffect || effect.allowRecurse) {
754 if (effect.onTrigger) {
755 effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
756 }
757 if (effect.scheduler) {
758 effect.scheduler();
759 }
760 else {
761 effect.run();
762 }
763 }
764 }
765 }
766
767 const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
768 const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
769 .map(key => Symbol[key])
770 .filter(isSymbol));
771 const get = /*#__PURE__*/ createGetter();
772 const shallowGet = /*#__PURE__*/ createGetter(false, true);
773 const readonlyGet = /*#__PURE__*/ createGetter(true);
774 const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
775 const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
776 function createArrayInstrumentations() {
777 const instrumentations = {};
778 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
779 instrumentations[key] = function (...args) {
780 const arr = toRaw(this);
781 for (let i = 0, l = this.length; i < l; i++) {
782 track(arr, "get" /* GET */, i + '');
783 }
784 // we run the method using the original args first (which may be reactive)
785 const res = arr[key](...args);
786 if (res === -1 || res === false) {
787 // if that didn't work, run it again using raw values.
788 return arr[key](...args.map(toRaw));
789 }
790 else {
791 return res;
792 }
793 };
794 });
795 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
796 instrumentations[key] = function (...args) {
797 pauseTracking();
798 const res = toRaw(this)[key].apply(this, args);
799 resetTracking();
800 return res;
801 };
802 });
803 return instrumentations;
804 }
805 function createGetter(isReadonly = false, shallow = false) {
806 return function get(target, key, receiver) {
807 if (key === "__v_isReactive" /* IS_REACTIVE */) {
808 return !isReadonly;
809 }
810 else if (key === "__v_isReadonly" /* IS_READONLY */) {
811 return isReadonly;
812 }
813 else if (key === "__v_raw" /* RAW */ &&
814 receiver ===
815 (isReadonly
816 ? shallow
817 ? shallowReadonlyMap
818 : readonlyMap
819 : shallow
820 ? shallowReactiveMap
821 : reactiveMap).get(target)) {
822 return target;
823 }
824 const targetIsArray = isArray(target);
825 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
826 return Reflect.get(arrayInstrumentations, key, receiver);
827 }
828 const res = Reflect.get(target, key, receiver);
829 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
830 return res;
831 }
832 if (!isReadonly) {
833 track(target, "get" /* GET */, key);
834 }
835 if (shallow) {
836 return res;
837 }
838 if (isRef(res)) {
839 // ref unwrapping - does not apply for Array + integer key.
840 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
841 return shouldUnwrap ? res.value : res;
842 }
843 if (isObject(res)) {
844 // Convert returned value into a proxy as well. we do the isObject check
845 // here to avoid invalid value warning. Also need to lazy access readonly
846 // and reactive here to avoid circular dependency.
847 return isReadonly ? readonly(res) : reactive(res);
848 }
849 return res;
850 };
851 }
852 const set = /*#__PURE__*/ createSetter();
853 const shallowSet = /*#__PURE__*/ createSetter(true);
854 function createSetter(shallow = false) {
855 return function set(target, key, value, receiver) {
856 let oldValue = target[key];
857 if (!shallow) {
858 value = toRaw(value);
859 oldValue = toRaw(oldValue);
860 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
861 oldValue.value = value;
862 return true;
863 }
864 }
865 const hadKey = isArray(target) && isIntegerKey(key)
866 ? Number(key) < target.length
867 : hasOwn(target, key);
868 const result = Reflect.set(target, key, value, receiver);
869 // don't trigger if target is something up in the prototype chain of original
870 if (target === toRaw(receiver)) {
871 if (!hadKey) {
872 trigger(target, "add" /* ADD */, key, value);
873 }
874 else if (hasChanged(value, oldValue)) {
875 trigger(target, "set" /* SET */, key, value, oldValue);
876 }
877 }
878 return result;
879 };
880 }
881 function deleteProperty(target, key) {
882 const hadKey = hasOwn(target, key);
883 const oldValue = target[key];
884 const result = Reflect.deleteProperty(target, key);
885 if (result && hadKey) {
886 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
887 }
888 return result;
889 }
890 function has(target, key) {
891 const result = Reflect.has(target, key);
892 if (!isSymbol(key) || !builtInSymbols.has(key)) {
893 track(target, "has" /* HAS */, key);
894 }
895 return result;
896 }
897 function ownKeys(target) {
898 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
899 return Reflect.ownKeys(target);
900 }
901 const mutableHandlers = {
902 get,
903 set,
904 deleteProperty,
905 has,
906 ownKeys
907 };
908 const readonlyHandlers = {
909 get: readonlyGet,
910 set(target, key) {
911 {
912 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
913 }
914 return true;
915 },
916 deleteProperty(target, key) {
917 {
918 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
919 }
920 return true;
921 }
922 };
923 const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
924 get: shallowGet,
925 set: shallowSet
926 });
927 // Props handlers are special in the sense that it should not unwrap top-level
928 // refs (in order to allow refs to be explicitly passed down), but should
929 // retain the reactivity of the normal readonly object.
930 const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
931 get: shallowReadonlyGet
932 });
933
934 const toReactive = (value) => isObject(value) ? reactive(value) : value;
935 const toReadonly = (value) => isObject(value) ? readonly(value) : value;
936 const toShallow = (value) => value;
937 const getProto = (v) => Reflect.getPrototypeOf(v);
938 function get$1(target, key, isReadonly = false, isShallow = false) {
939 // #1772: readonly(reactive(Map)) should return readonly + reactive version
940 // of the value
941 target = target["__v_raw" /* RAW */];
942 const rawTarget = toRaw(target);
943 const rawKey = toRaw(key);
944 if (key !== rawKey) {
945 !isReadonly && track(rawTarget, "get" /* GET */, key);
946 }
947 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
948 const { has } = getProto(rawTarget);
949 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
950 if (has.call(rawTarget, key)) {
951 return wrap(target.get(key));
952 }
953 else if (has.call(rawTarget, rawKey)) {
954 return wrap(target.get(rawKey));
955 }
956 else if (target !== rawTarget) {
957 // #3602 readonly(reactive(Map))
958 // ensure that the nested reactive `Map` can do tracking for itself
959 target.get(key);
960 }
961 }
962 function has$1(key, isReadonly = false) {
963 const target = this["__v_raw" /* RAW */];
964 const rawTarget = toRaw(target);
965 const rawKey = toRaw(key);
966 if (key !== rawKey) {
967 !isReadonly && track(rawTarget, "has" /* HAS */, key);
968 }
969 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
970 return key === rawKey
971 ? target.has(key)
972 : target.has(key) || target.has(rawKey);
973 }
974 function size(target, isReadonly = false) {
975 target = target["__v_raw" /* RAW */];
976 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
977 return Reflect.get(target, 'size', target);
978 }
979 function add(value) {
980 value = toRaw(value);
981 const target = toRaw(this);
982 const proto = getProto(target);
983 const hadKey = proto.has.call(target, value);
984 if (!hadKey) {
985 target.add(value);
986 trigger(target, "add" /* ADD */, value, value);
987 }
988 return this;
989 }
990 function set$1(key, value) {
991 value = toRaw(value);
992 const target = toRaw(this);
993 const { has, get } = getProto(target);
994 let hadKey = has.call(target, key);
995 if (!hadKey) {
996 key = toRaw(key);
997 hadKey = has.call(target, key);
998 }
999 else {
1000 checkIdentityKeys(target, has, key);
1001 }
1002 const oldValue = get.call(target, key);
1003 target.set(key, value);
1004 if (!hadKey) {
1005 trigger(target, "add" /* ADD */, key, value);
1006 }
1007 else if (hasChanged(value, oldValue)) {
1008 trigger(target, "set" /* SET */, key, value, oldValue);
1009 }
1010 return this;
1011 }
1012 function deleteEntry(key) {
1013 const target = toRaw(this);
1014 const { has, get } = getProto(target);
1015 let hadKey = has.call(target, key);
1016 if (!hadKey) {
1017 key = toRaw(key);
1018 hadKey = has.call(target, key);
1019 }
1020 else {
1021 checkIdentityKeys(target, has, key);
1022 }
1023 const oldValue = get ? get.call(target, key) : undefined;
1024 // forward the operation before queueing reactions
1025 const result = target.delete(key);
1026 if (hadKey) {
1027 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
1028 }
1029 return result;
1030 }
1031 function clear() {
1032 const target = toRaw(this);
1033 const hadItems = target.size !== 0;
1034 const oldTarget = isMap(target)
1035 ? new Map(target)
1036 : new Set(target)
1037 ;
1038 // forward the operation before queueing reactions
1039 const result = target.clear();
1040 if (hadItems) {
1041 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
1042 }
1043 return result;
1044 }
1045 function createForEach(isReadonly, isShallow) {
1046 return function forEach(callback, thisArg) {
1047 const observed = this;
1048 const target = observed["__v_raw" /* RAW */];
1049 const rawTarget = toRaw(target);
1050 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1051 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
1052 return target.forEach((value, key) => {
1053 // important: make sure the callback is
1054 // 1. invoked with the reactive map as `this` and 3rd arg
1055 // 2. the value received should be a corresponding reactive/readonly.
1056 return callback.call(thisArg, wrap(value), wrap(key), observed);
1057 });
1058 };
1059 }
1060 function createIterableMethod(method, isReadonly, isShallow) {
1061 return function (...args) {
1062 const target = this["__v_raw" /* RAW */];
1063 const rawTarget = toRaw(target);
1064 const targetIsMap = isMap(rawTarget);
1065 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
1066 const isKeyOnly = method === 'keys' && targetIsMap;
1067 const innerIterator = target[method](...args);
1068 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
1069 !isReadonly &&
1070 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
1071 // return a wrapped iterator which returns observed versions of the
1072 // values emitted from the real iterator
1073 return {
1074 // iterator protocol
1075 next() {
1076 const { value, done } = innerIterator.next();
1077 return done
1078 ? { value, done }
1079 : {
1080 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
1081 done
1082 };
1083 },
1084 // iterable protocol
1085 [Symbol.iterator]() {
1086 return this;
1087 }
1088 };
1089 };
1090 }
1091 function createReadonlyMethod(type) {
1092 return function (...args) {
1093 {
1094 const key = args[0] ? `on key "${args[0]}" ` : ``;
1095 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
1096 }
1097 return type === "delete" /* DELETE */ ? false : this;
1098 };
1099 }
1100 function createInstrumentations() {
1101 const mutableInstrumentations = {
1102 get(key) {
1103 return get$1(this, key);
1104 },
1105 get size() {
1106 return size(this);
1107 },
1108 has: has$1,
1109 add,
1110 set: set$1,
1111 delete: deleteEntry,
1112 clear,
1113 forEach: createForEach(false, false)
1114 };
1115 const shallowInstrumentations = {
1116 get(key) {
1117 return get$1(this, key, false, true);
1118 },
1119 get size() {
1120 return size(this);
1121 },
1122 has: has$1,
1123 add,
1124 set: set$1,
1125 delete: deleteEntry,
1126 clear,
1127 forEach: createForEach(false, true)
1128 };
1129 const readonlyInstrumentations = {
1130 get(key) {
1131 return get$1(this, key, true);
1132 },
1133 get size() {
1134 return size(this, true);
1135 },
1136 has(key) {
1137 return has$1.call(this, key, true);
1138 },
1139 add: createReadonlyMethod("add" /* ADD */),
1140 set: createReadonlyMethod("set" /* SET */),
1141 delete: createReadonlyMethod("delete" /* DELETE */),
1142 clear: createReadonlyMethod("clear" /* CLEAR */),
1143 forEach: createForEach(true, false)
1144 };
1145 const shallowReadonlyInstrumentations = {
1146 get(key) {
1147 return get$1(this, key, true, true);
1148 },
1149 get size() {
1150 return size(this, true);
1151 },
1152 has(key) {
1153 return has$1.call(this, key, true);
1154 },
1155 add: createReadonlyMethod("add" /* ADD */),
1156 set: createReadonlyMethod("set" /* SET */),
1157 delete: createReadonlyMethod("delete" /* DELETE */),
1158 clear: createReadonlyMethod("clear" /* CLEAR */),
1159 forEach: createForEach(true, true)
1160 };
1161 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
1162 iteratorMethods.forEach(method => {
1163 mutableInstrumentations[method] = createIterableMethod(method, false, false);
1164 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
1165 shallowInstrumentations[method] = createIterableMethod(method, false, true);
1166 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
1167 });
1168 return [
1169 mutableInstrumentations,
1170 readonlyInstrumentations,
1171 shallowInstrumentations,
1172 shallowReadonlyInstrumentations
1173 ];
1174 }
1175 const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
1176 function createInstrumentationGetter(isReadonly, shallow) {
1177 const instrumentations = shallow
1178 ? isReadonly
1179 ? shallowReadonlyInstrumentations
1180 : shallowInstrumentations
1181 : isReadonly
1182 ? readonlyInstrumentations
1183 : mutableInstrumentations;
1184 return (target, key, receiver) => {
1185 if (key === "__v_isReactive" /* IS_REACTIVE */) {
1186 return !isReadonly;
1187 }
1188 else if (key === "__v_isReadonly" /* IS_READONLY */) {
1189 return isReadonly;
1190 }
1191 else if (key === "__v_raw" /* RAW */) {
1192 return target;
1193 }
1194 return Reflect.get(hasOwn(instrumentations, key) && key in target
1195 ? instrumentations
1196 : target, key, receiver);
1197 };
1198 }
1199 const mutableCollectionHandlers = {
1200 get: /*#__PURE__*/ createInstrumentationGetter(false, false)
1201 };
1202 const shallowCollectionHandlers = {
1203 get: /*#__PURE__*/ createInstrumentationGetter(false, true)
1204 };
1205 const readonlyCollectionHandlers = {
1206 get: /*#__PURE__*/ createInstrumentationGetter(true, false)
1207 };
1208 const shallowReadonlyCollectionHandlers = {
1209 get: /*#__PURE__*/ createInstrumentationGetter(true, true)
1210 };
1211 function checkIdentityKeys(target, has, key) {
1212 const rawKey = toRaw(key);
1213 if (rawKey !== key && has.call(target, rawKey)) {
1214 const type = toRawType(target);
1215 console.warn(`Reactive ${type} contains both the raw and reactive ` +
1216 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
1217 `which can lead to inconsistencies. ` +
1218 `Avoid differentiating between the raw and reactive versions ` +
1219 `of an object and only use the reactive version if possible.`);
1220 }
1221 }
1222
1223 const reactiveMap = new WeakMap();
1224 const shallowReactiveMap = new WeakMap();
1225 const readonlyMap = new WeakMap();
1226 const shallowReadonlyMap = new WeakMap();
1227 function targetTypeMap(rawType) {
1228 switch (rawType) {
1229 case 'Object':
1230 case 'Array':
1231 return 1 /* COMMON */;
1232 case 'Map':
1233 case 'Set':
1234 case 'WeakMap':
1235 case 'WeakSet':
1236 return 2 /* COLLECTION */;
1237 default:
1238 return 0 /* INVALID */;
1239 }
1240 }
1241 function getTargetType(value) {
1242 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1243 ? 0 /* INVALID */
1244 : targetTypeMap(toRawType(value));
1245 }
1246 function reactive(target) {
1247 // if trying to observe a readonly proxy, return the readonly version.
1248 if (target && target["__v_isReadonly" /* IS_READONLY */]) {
1249 return target;
1250 }
1251 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1252 }
1253 /**
1254 * Return a shallowly-reactive copy of the original object, where only the root
1255 * level properties are reactive. It also does not auto-unwrap refs (even at the
1256 * root level).
1257 */
1258 function shallowReactive(target) {
1259 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1260 }
1261 /**
1262 * Creates a readonly copy of the original object. Note the returned copy is not
1263 * made reactive, but `readonly` can be called on an already reactive object.
1264 */
1265 function readonly(target) {
1266 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1267 }
1268 /**
1269 * Returns a reactive-copy of the original object, where only the root level
1270 * properties are readonly, and does NOT unwrap refs nor recursively convert
1271 * returned properties.
1272 * This is used for creating the props proxy object for stateful components.
1273 */
1274 function shallowReadonly(target) {
1275 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1276 }
1277 function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1278 if (!isObject(target)) {
1279 {
1280 console.warn(`value cannot be made reactive: ${String(target)}`);
1281 }
1282 return target;
1283 }
1284 // target is already a Proxy, return it.
1285 // exception: calling readonly() on a reactive object
1286 if (target["__v_raw" /* RAW */] &&
1287 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1288 return target;
1289 }
1290 // target already has corresponding Proxy
1291 const existingProxy = proxyMap.get(target);
1292 if (existingProxy) {
1293 return existingProxy;
1294 }
1295 // only a whitelist of value types can be observed.
1296 const targetType = getTargetType(target);
1297 if (targetType === 0 /* INVALID */) {
1298 return target;
1299 }
1300 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1301 proxyMap.set(target, proxy);
1302 return proxy;
1303 }
1304 function isReactive(value) {
1305 if (isReadonly(value)) {
1306 return isReactive(value["__v_raw" /* RAW */]);
1307 }
1308 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1309 }
1310 function isReadonly(value) {
1311 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1312 }
1313 function isProxy(value) {
1314 return isReactive(value) || isReadonly(value);
1315 }
1316 function toRaw(observed) {
1317 const raw = observed && observed["__v_raw" /* RAW */];
1318 return raw ? toRaw(raw) : observed;
1319 }
1320 function markRaw(value) {
1321 def(value, "__v_skip" /* SKIP */, true);
1322 return value;
1323 }
1324
1325 function trackRefValue(ref) {
1326 if (isTracking()) {
1327 ref = toRaw(ref);
1328 if (!ref.dep) {
1329 ref.dep = createDep();
1330 }
1331 {
1332 trackEffects(ref.dep, {
1333 target: ref,
1334 type: "get" /* GET */,
1335 key: 'value'
1336 });
1337 }
1338 }
1339 }
1340 function triggerRefValue(ref, newVal) {
1341 ref = toRaw(ref);
1342 if (ref.dep) {
1343 {
1344 triggerEffects(ref.dep, {
1345 target: ref,
1346 type: "set" /* SET */,
1347 key: 'value',
1348 newValue: newVal
1349 });
1350 }
1351 }
1352 }
1353 const convert = (val) => isObject(val) ? reactive(val) : val;
1354 function isRef(r) {
1355 return Boolean(r && r.__v_isRef === true);
1356 }
1357 function ref(value) {
1358 return createRef(value, false);
1359 }
1360 function shallowRef(value) {
1361 return createRef(value, true);
1362 }
1363 class RefImpl {
1364 constructor(value, _shallow) {
1365 this._shallow = _shallow;
1366 this.dep = undefined;
1367 this.__v_isRef = true;
1368 this._rawValue = _shallow ? value : toRaw(value);
1369 this._value = _shallow ? value : convert(value);
1370 }
1371 get value() {
1372 trackRefValue(this);
1373 return this._value;
1374 }
1375 set value(newVal) {
1376 newVal = this._shallow ? newVal : toRaw(newVal);
1377 if (hasChanged(newVal, this._rawValue)) {
1378 this._rawValue = newVal;
1379 this._value = this._shallow ? newVal : convert(newVal);
1380 triggerRefValue(this, newVal);
1381 }
1382 }
1383 }
1384 function createRef(rawValue, shallow) {
1385 if (isRef(rawValue)) {
1386 return rawValue;
1387 }
1388 return new RefImpl(rawValue, shallow);
1389 }
1390 function triggerRef(ref) {
1391 triggerRefValue(ref, ref.value );
1392 }
1393 function unref(ref) {
1394 return isRef(ref) ? ref.value : ref;
1395 }
1396 const shallowUnwrapHandlers = {
1397 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1398 set: (target, key, value, receiver) => {
1399 const oldValue = target[key];
1400 if (isRef(oldValue) && !isRef(value)) {
1401 oldValue.value = value;
1402 return true;
1403 }
1404 else {
1405 return Reflect.set(target, key, value, receiver);
1406 }
1407 }
1408 };
1409 function proxyRefs(objectWithRefs) {
1410 return isReactive(objectWithRefs)
1411 ? objectWithRefs
1412 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1413 }
1414 class CustomRefImpl {
1415 constructor(factory) {
1416 this.dep = undefined;
1417 this.__v_isRef = true;
1418 const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
1419 this._get = get;
1420 this._set = set;
1421 }
1422 get value() {
1423 return this._get();
1424 }
1425 set value(newVal) {
1426 this._set(newVal);
1427 }
1428 }
1429 function customRef(factory) {
1430 return new CustomRefImpl(factory);
1431 }
1432 function toRefs(object) {
1433 if (!isProxy(object)) {
1434 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1435 }
1436 const ret = isArray(object) ? new Array(object.length) : {};
1437 for (const key in object) {
1438 ret[key] = toRef(object, key);
1439 }
1440 return ret;
1441 }
1442 class ObjectRefImpl {
1443 constructor(_object, _key) {
1444 this._object = _object;
1445 this._key = _key;
1446 this.__v_isRef = true;
1447 }
1448 get value() {
1449 return this._object[this._key];
1450 }
1451 set value(newVal) {
1452 this._object[this._key] = newVal;
1453 }
1454 }
1455 function toRef(object, key) {
1456 const val = object[key];
1457 return isRef(val) ? val : new ObjectRefImpl(object, key);
1458 }
1459
1460 class ComputedRefImpl {
1461 constructor(getter, _setter, isReadonly) {
1462 this._setter = _setter;
1463 this.dep = undefined;
1464 this._dirty = true;
1465 this.__v_isRef = true;
1466 this.effect = new ReactiveEffect(getter, () => {
1467 if (!this._dirty) {
1468 this._dirty = true;
1469 triggerRefValue(this);
1470 }
1471 });
1472 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1473 }
1474 get value() {
1475 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1476 const self = toRaw(this);
1477 trackRefValue(self);
1478 if (self._dirty) {
1479 self._dirty = false;
1480 self._value = self.effect.run();
1481 }
1482 return self._value;
1483 }
1484 set value(newValue) {
1485 this._setter(newValue);
1486 }
1487 }
1488 function computed(getterOrOptions, debugOptions) {
1489 let getter;
1490 let setter;
1491 if (isFunction(getterOrOptions)) {
1492 getter = getterOrOptions;
1493 setter = () => {
1494 console.warn('Write operation failed: computed value is readonly');
1495 }
1496 ;
1497 }
1498 else {
1499 getter = getterOrOptions.get;
1500 setter = getterOrOptions.set;
1501 }
1502 const cRef = new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
1503 if (debugOptions) {
1504 cRef.effect.onTrack = debugOptions.onTrack;
1505 cRef.effect.onTrigger = debugOptions.onTrigger;
1506 }
1507 return cRef;
1508 }
1509
1510 /* eslint-disable no-restricted-globals */
1511 let isHmrUpdating = false;
1512 const hmrDirtyComponents = new Set();
1513 // Expose the HMR runtime on the global object
1514 // This makes it entirely tree-shakable without polluting the exports and makes
1515 // it easier to be used in toolings like vue-loader
1516 // Note: for a component to be eligible for HMR it also needs the __hmrId option
1517 // to be set so that its instances can be registered / removed.
1518 {
1519 const globalObject = typeof global !== 'undefined'
1520 ? global
1521 : typeof self !== 'undefined'
1522 ? self
1523 : typeof window !== 'undefined'
1524 ? window
1525 : {};
1526 globalObject.__VUE_HMR_RUNTIME__ = {
1527 createRecord: tryWrap(createRecord),
1528 rerender: tryWrap(rerender),
1529 reload: tryWrap(reload)
1530 };
1531 }
1532 const map = new Map();
1533 function registerHMR(instance) {
1534 const id = instance.type.__hmrId;
1535 let record = map.get(id);
1536 if (!record) {
1537 createRecord(id);
1538 record = map.get(id);
1539 }
1540 record.add(instance);
1541 }
1542 function unregisterHMR(instance) {
1543 map.get(instance.type.__hmrId).delete(instance);
1544 }
1545 function createRecord(id) {
1546 if (map.has(id)) {
1547 return false;
1548 }
1549 map.set(id, new Set());
1550 return true;
1551 }
1552 function normalizeClassComponent(component) {
1553 return isClassComponent(component) ? component.__vccOpts : component;
1554 }
1555 function rerender(id, newRender) {
1556 const record = map.get(id);
1557 if (!record) {
1558 return;
1559 }
1560 [...record].forEach(instance => {
1561 if (newRender) {
1562 instance.render = newRender;
1563 normalizeClassComponent(instance.type).render = newRender;
1564 }
1565 instance.renderCache = [];
1566 // this flag forces child components with slot content to update
1567 isHmrUpdating = true;
1568 instance.update();
1569 isHmrUpdating = false;
1570 });
1571 }
1572 function reload(id, newComp) {
1573 const record = map.get(id);
1574 if (!record)
1575 return;
1576 newComp = normalizeClassComponent(newComp);
1577 // create a snapshot which avoids the set being mutated during updates
1578 const instances = [...record];
1579 for (const instance of instances) {
1580 const oldComp = normalizeClassComponent(instance.type);
1581 if (!hmrDirtyComponents.has(oldComp)) {
1582 // 1. Update existing comp definition to match new one
1583 extend(oldComp, newComp);
1584 for (const key in oldComp) {
1585 if (key !== '__file' && !(key in newComp)) {
1586 delete oldComp[key];
1587 }
1588 }
1589 // 2. mark definition dirty. This forces the renderer to replace the
1590 // component on patch.
1591 hmrDirtyComponents.add(oldComp);
1592 }
1593 // 3. invalidate options resolution cache
1594 instance.appContext.optionsCache.delete(instance.type);
1595 // 4. actually update
1596 if (instance.ceReload) {
1597 // custom element
1598 hmrDirtyComponents.add(oldComp);
1599 instance.ceReload(newComp.styles);
1600 hmrDirtyComponents.delete(oldComp);
1601 }
1602 else if (instance.parent) {
1603 // 4. Force the parent instance to re-render. This will cause all updated
1604 // components to be unmounted and re-mounted. Queue the update so that we
1605 // don't end up forcing the same parent to re-render multiple times.
1606 queueJob(instance.parent.update);
1607 // instance is the inner component of an async custom element
1608 // invoke to reset styles
1609 if (instance.parent.type.__asyncLoader &&
1610 instance.parent.ceReload) {
1611 instance.parent.ceReload(newComp.styles);
1612 }
1613 }
1614 else if (instance.appContext.reload) {
1615 // root instance mounted via createApp() has a reload method
1616 instance.appContext.reload();
1617 }
1618 else if (typeof window !== 'undefined') {
1619 // root instance inside tree created via raw render(). Force reload.
1620 window.location.reload();
1621 }
1622 else {
1623 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1624 }
1625 }
1626 // 5. make sure to cleanup dirty hmr components after update
1627 queuePostFlushCb(() => {
1628 for (const instance of instances) {
1629 hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
1630 }
1631 });
1632 }
1633 function tryWrap(fn) {
1634 return (id, arg) => {
1635 try {
1636 return fn(id, arg);
1637 }
1638 catch (e) {
1639 console.error(e);
1640 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1641 `Full reload required.`);
1642 }
1643 };
1644 }
1645
1646 function setDevtoolsHook(hook) {
1647 exports.devtools = hook;
1648 }
1649 function devtoolsInitApp(app, version) {
1650 // TODO queue if devtools is undefined
1651 if (!exports.devtools)
1652 return;
1653 exports.devtools.emit("app:init" /* APP_INIT */, app, version, {
1654 Fragment,
1655 Text,
1656 Comment,
1657 Static
1658 });
1659 }
1660 function devtoolsUnmountApp(app) {
1661 if (!exports.devtools)
1662 return;
1663 exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1664 }
1665 const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1666 const devtoolsComponentUpdated =
1667 /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1668 const devtoolsComponentRemoved =
1669 /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1670 function createDevtoolsComponentHook(hook) {
1671 return (component) => {
1672 if (!exports.devtools)
1673 return;
1674 exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1675 };
1676 }
1677 const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
1678 const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
1679 function createDevtoolsPerformanceHook(hook) {
1680 return (component, type, time) => {
1681 if (!exports.devtools)
1682 return;
1683 exports.devtools.emit(hook, component.appContext.app, component.uid, component, type, time);
1684 };
1685 }
1686 function devtoolsComponentEmit(component, event, params) {
1687 if (!exports.devtools)
1688 return;
1689 exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1690 }
1691
1692 const deprecationData = {
1693 ["GLOBAL_MOUNT" /* GLOBAL_MOUNT */]: {
1694 message: `The global app bootstrapping API has changed: vm.$mount() and the "el" ` +
1695 `option have been removed. Use createApp(RootComponent).mount() instead.`,
1696 link: `https://v3.vuejs.org/guide/migration/global-api.html#mounting-app-instance`
1697 },
1698 ["GLOBAL_MOUNT_CONTAINER" /* GLOBAL_MOUNT_CONTAINER */]: {
1699 message: `Vue detected directives on the mount container. ` +
1700 `In Vue 3, the container is no longer considered part of the template ` +
1701 `and will not be processed/replaced.`,
1702 link: `https://v3.vuejs.org/guide/migration/mount-changes.html`
1703 },
1704 ["GLOBAL_EXTEND" /* GLOBAL_EXTEND */]: {
1705 message: `Vue.extend() has been removed in Vue 3. ` +
1706 `Use defineComponent() instead.`,
1707 link: `https://v3.vuejs.org/api/global-api.html#definecomponent`
1708 },
1709 ["GLOBAL_PROTOTYPE" /* GLOBAL_PROTOTYPE */]: {
1710 message: `Vue.prototype is no longer available in Vue 3. ` +
1711 `Use app.config.globalProperties instead.`,
1712 link: `https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties`
1713 },
1714 ["GLOBAL_SET" /* GLOBAL_SET */]: {
1715 message: `Vue.set() has been removed as it is no longer needed in Vue 3. ` +
1716 `Simply use native JavaScript mutations.`
1717 },
1718 ["GLOBAL_DELETE" /* GLOBAL_DELETE */]: {
1719 message: `Vue.delete() has been removed as it is no longer needed in Vue 3. ` +
1720 `Simply use native JavaScript mutations.`
1721 },
1722 ["GLOBAL_OBSERVABLE" /* GLOBAL_OBSERVABLE */]: {
1723 message: `Vue.observable() has been removed. ` +
1724 `Use \`import { reactive } from "vue"\` from Composition API instead.`,
1725 link: `https://v3.vuejs.org/api/basic-reactivity.html`
1726 },
1727 ["GLOBAL_PRIVATE_UTIL" /* GLOBAL_PRIVATE_UTIL */]: {
1728 message: `Vue.util has been removed. Please refactor to avoid its usage ` +
1729 `since it was an internal API even in Vue 2.`
1730 },
1731 ["CONFIG_SILENT" /* CONFIG_SILENT */]: {
1732 message: `config.silent has been removed because it is not good practice to ` +
1733 `intentionally suppress warnings. You can use your browser console's ` +
1734 `filter features to focus on relevant messages.`
1735 },
1736 ["CONFIG_DEVTOOLS" /* CONFIG_DEVTOOLS */]: {
1737 message: `config.devtools has been removed. To enable devtools for ` +
1738 `production, configure the __VUE_PROD_DEVTOOLS__ compile-time flag.`,
1739 link: `https://github.com/vuejs/vue-next/tree/master/packages/vue#bundler-build-feature-flags`
1740 },
1741 ["CONFIG_KEY_CODES" /* CONFIG_KEY_CODES */]: {
1742 message: `config.keyCodes has been removed. ` +
1743 `In Vue 3, you can directly use the kebab-case key names as v-on modifiers.`,
1744 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1745 },
1746 ["CONFIG_PRODUCTION_TIP" /* CONFIG_PRODUCTION_TIP */]: {
1747 message: `config.productionTip has been removed.`,
1748 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-productiontip-removed`
1749 },
1750 ["CONFIG_IGNORED_ELEMENTS" /* CONFIG_IGNORED_ELEMENTS */]: {
1751 message: () => {
1752 let msg = `config.ignoredElements has been removed.`;
1753 if (isRuntimeOnly()) {
1754 msg += ` Pass the "isCustomElement" option to @vue/compiler-dom instead.`;
1755 }
1756 else {
1757 msg += ` Use config.isCustomElement instead.`;
1758 }
1759 return msg;
1760 },
1761 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-ignoredelements-is-now-config-iscustomelement`
1762 },
1763 ["CONFIG_WHITESPACE" /* CONFIG_WHITESPACE */]: {
1764 // this warning is only relevant in the full build when using runtime
1765 // compilation, so it's put in the runtime compatConfig list.
1766 message: `Vue 3 compiler's whitespace option will default to "condense" instead of ` +
1767 `"preserve". To suppress this warning, provide an explicit value for ` +
1768 `\`config.compilerOptions.whitespace\`.`
1769 },
1770 ["CONFIG_OPTION_MERGE_STRATS" /* CONFIG_OPTION_MERGE_STRATS */]: {
1771 message: `config.optionMergeStrategies no longer exposes internal strategies. ` +
1772 `Use custom merge functions instead.`
1773 },
1774 ["INSTANCE_SET" /* INSTANCE_SET */]: {
1775 message: `vm.$set() has been removed as it is no longer needed in Vue 3. ` +
1776 `Simply use native JavaScript mutations.`
1777 },
1778 ["INSTANCE_DELETE" /* INSTANCE_DELETE */]: {
1779 message: `vm.$delete() has been removed as it is no longer needed in Vue 3. ` +
1780 `Simply use native JavaScript mutations.`
1781 },
1782 ["INSTANCE_DESTROY" /* INSTANCE_DESTROY */]: {
1783 message: `vm.$destroy() has been removed. Use app.unmount() instead.`,
1784 link: `https://v3.vuejs.org/api/application-api.html#unmount`
1785 },
1786 ["INSTANCE_EVENT_EMITTER" /* INSTANCE_EVENT_EMITTER */]: {
1787 message: `vm.$on/$once/$off() have been removed. ` +
1788 `Use an external event emitter library instead.`,
1789 link: `https://v3.vuejs.org/guide/migration/events-api.html`
1790 },
1791 ["INSTANCE_EVENT_HOOKS" /* INSTANCE_EVENT_HOOKS */]: {
1792 message: event => `"${event}" lifecycle events are no longer supported. From templates, ` +
1793 `use the "vnode" prefix instead of "hook:". For example, @${event} ` +
1794 `should be changed to @vnode-${event.slice(5)}. ` +
1795 `From JavaScript, use Composition API to dynamically register lifecycle ` +
1796 `hooks.`,
1797 link: `https://v3.vuejs.org/guide/migration/vnode-lifecycle-events.html`
1798 },
1799 ["INSTANCE_CHILDREN" /* INSTANCE_CHILDREN */]: {
1800 message: `vm.$children has been removed. Consider refactoring your logic ` +
1801 `to avoid relying on direct access to child components.`,
1802 link: `https://v3.vuejs.org/guide/migration/children.html`
1803 },
1804 ["INSTANCE_LISTENERS" /* INSTANCE_LISTENERS */]: {
1805 message: `vm.$listeners has been removed. In Vue 3, parent v-on listeners are ` +
1806 `included in vm.$attrs and it is no longer necessary to separately use ` +
1807 `v-on="$listeners" if you are already using v-bind="$attrs". ` +
1808 `(Note: the Vue 3 behavior only applies if this compat config is disabled)`,
1809 link: `https://v3.vuejs.org/guide/migration/listeners-removed.html`
1810 },
1811 ["INSTANCE_SCOPED_SLOTS" /* INSTANCE_SCOPED_SLOTS */]: {
1812 message: `vm.$scopedSlots has been removed. Use vm.$slots instead.`,
1813 link: `https://v3.vuejs.org/guide/migration/slots-unification.html`
1814 },
1815 ["INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */]: {
1816 message: componentName => `Component <${componentName || 'Anonymous'}> has \`inheritAttrs: false\` but is ` +
1817 `relying on class/style fallthrough from parent. In Vue 3, class/style ` +
1818 `are now included in $attrs and will no longer fallthrough when ` +
1819 `inheritAttrs is false. If you are already using v-bind="$attrs" on ` +
1820 `component root it should render the same end result. ` +
1821 `If you are binding $attrs to a non-root element and expecting ` +
1822 `class/style to fallthrough on root, you will need to now manually bind ` +
1823 `them on root via :class="$attrs.class".`,
1824 link: `https://v3.vuejs.org/guide/migration/attrs-includes-class-style.html`
1825 },
1826 ["OPTIONS_DATA_FN" /* OPTIONS_DATA_FN */]: {
1827 message: `The "data" option can no longer be a plain object. ` +
1828 `Always use a function.`,
1829 link: `https://v3.vuejs.org/guide/migration/data-option.html`
1830 },
1831 ["OPTIONS_DATA_MERGE" /* OPTIONS_DATA_MERGE */]: {
1832 message: (key) => `Detected conflicting key "${key}" when merging data option values. ` +
1833 `In Vue 3, data keys are merged shallowly and will override one another.`,
1834 link: `https://v3.vuejs.org/guide/migration/data-option.html#mixin-merge-behavior-change`
1835 },
1836 ["OPTIONS_BEFORE_DESTROY" /* OPTIONS_BEFORE_DESTROY */]: {
1837 message: `\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`
1838 },
1839 ["OPTIONS_DESTROYED" /* OPTIONS_DESTROYED */]: {
1840 message: `\`destroyed\` has been renamed to \`unmounted\`.`
1841 },
1842 ["WATCH_ARRAY" /* WATCH_ARRAY */]: {
1843 message: `"watch" option or vm.$watch on an array value will no longer ` +
1844 `trigger on array mutation unless the "deep" option is specified. ` +
1845 `If current usage is intended, you can disable the compat behavior and ` +
1846 `suppress this warning with:` +
1847 `\n\n configureCompat({ ${"WATCH_ARRAY" /* WATCH_ARRAY */}: false })\n`,
1848 link: `https://v3.vuejs.org/guide/migration/watch.html`
1849 },
1850 ["PROPS_DEFAULT_THIS" /* PROPS_DEFAULT_THIS */]: {
1851 message: (key) => `props default value function no longer has access to "this". The compat ` +
1852 `build only offers access to this.$options.` +
1853 `(found in prop "${key}")`,
1854 link: `https://v3.vuejs.org/guide/migration/props-default-this.html`
1855 },
1856 ["CUSTOM_DIR" /* CUSTOM_DIR */]: {
1857 message: (legacyHook, newHook) => `Custom directive hook "${legacyHook}" has been removed. ` +
1858 `Use "${newHook}" instead.`,
1859 link: `https://v3.vuejs.org/guide/migration/custom-directives.html`
1860 },
1861 ["V_FOR_REF" /* V_FOR_REF */]: {
1862 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
1863 `Consider using function refs or refactor to avoid ref usage altogether.`,
1864 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
1865 },
1866 ["V_ON_KEYCODE_MODIFIER" /* V_ON_KEYCODE_MODIFIER */]: {
1867 message: `Using keyCode as v-on modifier is no longer supported. ` +
1868 `Use kebab-case key name modifiers instead.`,
1869 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1870 },
1871 ["ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */]: {
1872 message: (name) => `Attribute "${name}" with v-bind value \`false\` will render ` +
1873 `${name}="false" instead of removing it in Vue 3. To remove the attribute, ` +
1874 `use \`null\` or \`undefined\` instead. If the usage is intended, ` +
1875 `you can disable the compat behavior and suppress this warning with:` +
1876 `\n\n configureCompat({ ${"ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */}: false })\n`,
1877 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
1878 },
1879 ["ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */]: {
1880 message: (name, value, coerced) => `Enumerated attribute "${name}" with v-bind value \`${value}\` will ` +
1881 `${value === null ? `be removed` : `render the value as-is`} instead of coercing the value to "${coerced}" in Vue 3. ` +
1882 `Always use explicit "true" or "false" values for enumerated attributes. ` +
1883 `If the usage is intended, ` +
1884 `you can disable the compat behavior and suppress this warning with:` +
1885 `\n\n configureCompat({ ${"ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */}: false })\n`,
1886 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
1887 },
1888 ["TRANSITION_CLASSES" /* TRANSITION_CLASSES */]: {
1889 message: `` // this feature cannot be runtime-detected
1890 },
1891 ["TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */]: {
1892 message: `<TransitionGroup> no longer renders a root <span> element by ` +
1893 `default if no "tag" prop is specified. If you do not rely on the span ` +
1894 `for styling, you can disable the compat behavior and suppress this ` +
1895 `warning with:` +
1896 `\n\n configureCompat({ ${"TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */}: false })\n`,
1897 link: `https://v3.vuejs.org/guide/migration/transition-group.html`
1898 },
1899 ["COMPONENT_ASYNC" /* COMPONENT_ASYNC */]: {
1900 message: (comp) => {
1901 const name = getComponentName(comp);
1902 return (`Async component${name ? ` <${name}>` : `s`} should be explicitly created via \`defineAsyncComponent()\` ` +
1903 `in Vue 3. Plain functions will be treated as functional components in ` +
1904 `non-compat build. If you have already migrated all async component ` +
1905 `usage and intend to use plain functions for functional components, ` +
1906 `you can disable the compat behavior and suppress this ` +
1907 `warning with:` +
1908 `\n\n configureCompat({ ${"COMPONENT_ASYNC" /* COMPONENT_ASYNC */}: false })\n`);
1909 },
1910 link: `https://v3.vuejs.org/guide/migration/async-components.html`
1911 },
1912 ["COMPONENT_FUNCTIONAL" /* COMPONENT_FUNCTIONAL */]: {
1913 message: (comp) => {
1914 const name = getComponentName(comp);
1915 return (`Functional component${name ? ` <${name}>` : `s`} should be defined as a plain function in Vue 3. The "functional" ` +
1916 `option has been removed. NOTE: Before migrating to use plain ` +
1917 `functions for functional components, first make sure that all async ` +
1918 `components usage have been migrated and its compat behavior has ` +
1919 `been disabled.`);
1920 },
1921 link: `https://v3.vuejs.org/guide/migration/functional-components.html`
1922 },
1923 ["COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */]: {
1924 message: (comp) => {
1925 const configMsg = `opt-in to ` +
1926 `Vue 3 behavior on a per-component basis with \`compatConfig: { ${"COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */}: false }\`.`;
1927 if (comp.props &&
1928 (isArray(comp.props)
1929 ? comp.props.includes('modelValue')
1930 : hasOwn(comp.props, 'modelValue'))) {
1931 return (`Component delcares "modelValue" prop, which is Vue 3 usage, but ` +
1932 `is running under Vue 2 compat v-model behavior. You can ${configMsg}`);
1933 }
1934 return (`v-model usage on component has changed in Vue 3. Component that expects ` +
1935 `to work with v-model should now use the "modelValue" prop and emit the ` +
1936 `"update:modelValue" event. You can update the usage and then ${configMsg}`);
1937 },
1938 link: `https://v3.vuejs.org/guide/migration/v-model.html`
1939 },
1940 ["RENDER_FUNCTION" /* RENDER_FUNCTION */]: {
1941 message: `Vue 3's render function API has changed. ` +
1942 `You can opt-in to the new API with:` +
1943 `\n\n configureCompat({ ${"RENDER_FUNCTION" /* RENDER_FUNCTION */}: false })\n` +
1944 `\n (This can also be done per-component via the "compatConfig" option.)`,
1945 link: `https://v3.vuejs.org/guide/migration/render-function-api.html`
1946 },
1947 ["FILTERS" /* FILTERS */]: {
1948 message: `filters have been removed in Vue 3. ` +
1949 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
1950 `Use method calls or computed properties instead.`,
1951 link: `https://v3.vuejs.org/guide/migration/filters.html`
1952 },
1953 ["PRIVATE_APIS" /* PRIVATE_APIS */]: {
1954 message: name => `"${name}" is a Vue 2 private API that no longer exists in Vue 3. ` +
1955 `If you are seeing this warning only due to a dependency, you can ` +
1956 `suppress this warning via { PRIVATE_APIS: 'supress-warning' }.`
1957 }
1958 };
1959 const instanceWarned = Object.create(null);
1960 const warnCount = Object.create(null);
1961 function warnDeprecation(key, instance, ...args) {
1962 instance = instance || getCurrentInstance();
1963 // check user config
1964 const config = getCompatConfigForKey(key, instance);
1965 if (config === 'suppress-warning') {
1966 return;
1967 }
1968 const dupKey = key + args.join('');
1969 let compId = instance && formatComponentName(instance, instance.type);
1970 if (compId === 'Anonymous' && instance) {
1971 compId = instance.uid;
1972 }
1973 // skip if the same warning is emitted for the same component type
1974 const componentDupKey = dupKey + compId;
1975 if (componentDupKey in instanceWarned) {
1976 return;
1977 }
1978 instanceWarned[componentDupKey] = true;
1979 // same warning, but different component. skip the long message and just
1980 // log the key and count.
1981 if (dupKey in warnCount) {
1982 warn$1(`(deprecation ${key}) (${++warnCount[dupKey] + 1})`);
1983 return;
1984 }
1985 warnCount[dupKey] = 0;
1986 const { message, link } = deprecationData[key];
1987 warn$1(`(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`);
1988 if (!isCompatEnabled(key, instance, true)) {
1989 console.error(`^ The above deprecation's compat behavior is disabled and will likely ` +
1990 `lead to runtime errors.`);
1991 }
1992 }
1993 const globalCompatConfig = {
1994 MODE: 2
1995 };
1996 function getCompatConfigForKey(key, instance) {
1997 const instanceConfig = instance && instance.type.compatConfig;
1998 if (instanceConfig && key in instanceConfig) {
1999 return instanceConfig[key];
2000 }
2001 return globalCompatConfig[key];
2002 }
2003 function isCompatEnabled(key, instance, enableForBuiltIn = false) {
2004 // skip compat for built-in components
2005 if (!enableForBuiltIn && instance && instance.type.__isBuiltIn) {
2006 return false;
2007 }
2008 const rawMode = getCompatConfigForKey('MODE', instance) || 2;
2009 const val = getCompatConfigForKey(key, instance);
2010 const mode = isFunction(rawMode)
2011 ? rawMode(instance && instance.type)
2012 : rawMode;
2013 if (mode === 2) {
2014 return val !== false;
2015 }
2016 else {
2017 return val === true || val === 'suppress-warning';
2018 }
2019 }
2020
2021 function emit(instance, event, ...rawArgs) {
2022 const props = instance.vnode.props || EMPTY_OBJ;
2023 {
2024 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2025 if (emitsOptions) {
2026 if (!(event in emitsOptions) &&
2027 !(false )) {
2028 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2029 warn$1(`Component emitted event "${event}" but it is neither declared in ` +
2030 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2031 }
2032 }
2033 else {
2034 const validator = emitsOptions[event];
2035 if (isFunction(validator)) {
2036 const isValid = validator(...rawArgs);
2037 if (!isValid) {
2038 warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
2039 }
2040 }
2041 }
2042 }
2043 }
2044 let args = rawArgs;
2045 const isModelListener = event.startsWith('update:');
2046 // for v-model update:xxx events, apply modifiers on args
2047 const modelArg = isModelListener && event.slice(7);
2048 if (modelArg && modelArg in props) {
2049 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2050 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2051 if (trim) {
2052 args = rawArgs.map(a => a.trim());
2053 }
2054 else if (number) {
2055 args = rawArgs.map(toNumber);
2056 }
2057 }
2058 {
2059 devtoolsComponentEmit(instance, event, args);
2060 }
2061 {
2062 const lowerCaseEvent = event.toLowerCase();
2063 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2064 warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
2065 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2066 `Note that HTML attributes are case-insensitive and you cannot use ` +
2067 `v-on to listen to camelCase events when using in-DOM templates. ` +
2068 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2069 }
2070 }
2071 let handlerName;
2072 let handler = props[(handlerName = toHandlerKey(event))] ||
2073 // also try camelCase event handler (#2249)
2074 props[(handlerName = toHandlerKey(camelize(event)))];
2075 // for v-model update:xxx events, also trigger kebab-case equivalent
2076 // for props passed via kebab-case
2077 if (!handler && isModelListener) {
2078 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2079 }
2080 if (handler) {
2081 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2082 }
2083 const onceHandler = props[handlerName + `Once`];
2084 if (onceHandler) {
2085 if (!instance.emitted) {
2086 instance.emitted = {};
2087 }
2088 else if (instance.emitted[handlerName]) {
2089 return;
2090 }
2091 instance.emitted[handlerName] = true;
2092 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2093 }
2094 }
2095 function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2096 const cache = appContext.emitsCache;
2097 const cached = cache.get(comp);
2098 if (cached !== undefined) {
2099 return cached;
2100 }
2101 const raw = comp.emits;
2102 let normalized = {};
2103 // apply mixin/extends props
2104 let hasExtends = false;
2105 if (!isFunction(comp)) {
2106 const extendEmits = (raw) => {
2107 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2108 if (normalizedFromExtend) {
2109 hasExtends = true;
2110 extend(normalized, normalizedFromExtend);
2111 }
2112 };
2113 if (!asMixin && appContext.mixins.length) {
2114 appContext.mixins.forEach(extendEmits);
2115 }
2116 if (comp.extends) {
2117 extendEmits(comp.extends);
2118 }
2119 if (comp.mixins) {
2120 comp.mixins.forEach(extendEmits);
2121 }
2122 }
2123 if (!raw && !hasExtends) {
2124 cache.set(comp, null);
2125 return null;
2126 }
2127 if (isArray(raw)) {
2128 raw.forEach(key => (normalized[key] = null));
2129 }
2130 else {
2131 extend(normalized, raw);
2132 }
2133 cache.set(comp, normalized);
2134 return normalized;
2135 }
2136 // Check if an incoming prop key is a declared emit event listener.
2137 // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2138 // both considered matched listeners.
2139 function isEmitListener(options, key) {
2140 if (!options || !isOn(key)) {
2141 return false;
2142 }
2143 key = key.slice(2).replace(/Once$/, '');
2144 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2145 hasOwn(options, hyphenate(key)) ||
2146 hasOwn(options, key));
2147 }
2148
2149 /**
2150 * mark the current rendering instance for asset resolution (e.g.
2151 * resolveComponent, resolveDirective) during render
2152 */
2153 let currentRenderingInstance = null;
2154 let currentScopeId = null;
2155 /**
2156 * Note: rendering calls maybe nested. The function returns the parent rendering
2157 * instance if present, which should be restored after the render is done:
2158 *
2159 * ```js
2160 * const prev = setCurrentRenderingInstance(i)
2161 * // ...render
2162 * setCurrentRenderingInstance(prev)
2163 * ```
2164 */
2165 function setCurrentRenderingInstance(instance) {
2166 const prev = currentRenderingInstance;
2167 currentRenderingInstance = instance;
2168 currentScopeId = (instance && instance.type.__scopeId) || null;
2169 return prev;
2170 }
2171 /**
2172 * Set scope id when creating hoisted vnodes.
2173 * @private compiler helper
2174 */
2175 function pushScopeId(id) {
2176 currentScopeId = id;
2177 }
2178 /**
2179 * Technically we no longer need this after 3.0.8 but we need to keep the same
2180 * API for backwards compat w/ code generated by compilers.
2181 * @private
2182 */
2183 function popScopeId() {
2184 currentScopeId = null;
2185 }
2186 /**
2187 * Only for backwards compat
2188 * @private
2189 */
2190 const withScopeId = (_id) => withCtx;
2191 /**
2192 * Wrap a slot function to memoize current rendering instance
2193 * @private compiler helper
2194 */
2195 function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2196 ) {
2197 if (!ctx)
2198 return fn;
2199 // already normalized
2200 if (fn._n) {
2201 return fn;
2202 }
2203 const renderFnWithContext = (...args) => {
2204 // If a user calls a compiled slot inside a template expression (#1745), it
2205 // can mess up block tracking, so by default we disable block tracking and
2206 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2207 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2208 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2209 if (renderFnWithContext._d) {
2210 setBlockTracking(-1);
2211 }
2212 const prevInstance = setCurrentRenderingInstance(ctx);
2213 const res = fn(...args);
2214 setCurrentRenderingInstance(prevInstance);
2215 if (renderFnWithContext._d) {
2216 setBlockTracking(1);
2217 }
2218 {
2219 devtoolsComponentUpdated(ctx);
2220 }
2221 return res;
2222 };
2223 // mark normalized to avoid duplicated wrapping
2224 renderFnWithContext._n = true;
2225 // mark this as compiled by default
2226 // this is used in vnode.ts -> normalizeChildren() to set the slot
2227 // rendering flag.
2228 renderFnWithContext._c = true;
2229 // disable block tracking by default
2230 renderFnWithContext._d = true;
2231 return renderFnWithContext;
2232 }
2233
2234 /**
2235 * dev only flag to track whether $attrs was used during render.
2236 * If $attrs was used during render then the warning for failed attrs
2237 * fallthrough can be suppressed.
2238 */
2239 let accessedAttrs = false;
2240 function markAttrsAccessed() {
2241 accessedAttrs = true;
2242 }
2243 function renderComponentRoot(instance) {
2244 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2245 let result;
2246 const prev = setCurrentRenderingInstance(instance);
2247 {
2248 accessedAttrs = false;
2249 }
2250 try {
2251 let fallthroughAttrs;
2252 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2253 // withProxy is a proxy with a different `has` trap only for
2254 // runtime-compiled render functions using `with` block.
2255 const proxyToUse = withProxy || proxy;
2256 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2257 fallthroughAttrs = attrs;
2258 }
2259 else {
2260 // functional
2261 const render = Component;
2262 // in dev, mark attrs accessed if optional props (attrs === props)
2263 if (true && attrs === props) {
2264 markAttrsAccessed();
2265 }
2266 result = normalizeVNode(render.length > 1
2267 ? render(props, true
2268 ? {
2269 get attrs() {
2270 markAttrsAccessed();
2271 return attrs;
2272 },
2273 slots,
2274 emit
2275 }
2276 : { attrs, slots, emit })
2277 : render(props, null /* we know it doesn't need it */));
2278 fallthroughAttrs = Component.props
2279 ? attrs
2280 : getFunctionalFallthrough(attrs);
2281 }
2282 // attr merging
2283 // in dev mode, comments are preserved, and it's possible for a template
2284 // to have comments along side the root element which makes it a fragment
2285 let root = result;
2286 let setRoot = undefined;
2287 if (true &&
2288 result.patchFlag > 0 &&
2289 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2290 ;
2291 [root, setRoot] = getChildRoot(result);
2292 }
2293 if (fallthroughAttrs && inheritAttrs !== false) {
2294 const keys = Object.keys(fallthroughAttrs);
2295 const { shapeFlag } = root;
2296 if (keys.length) {
2297 if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
2298 if (propsOptions && keys.some(isModelListener)) {
2299 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2300 // prop, it indicates this component expects to handle v-model and
2301 // it should not fallthrough.
2302 // related: #1543, #1643, #1989
2303 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2304 }
2305 root = cloneVNode(root, fallthroughAttrs);
2306 }
2307 else if (true && !accessedAttrs && root.type !== Comment) {
2308 const allAttrs = Object.keys(attrs);
2309 const eventAttrs = [];
2310 const extraAttrs = [];
2311 for (let i = 0, l = allAttrs.length; i < l; i++) {
2312 const key = allAttrs[i];
2313 if (isOn(key)) {
2314 // ignore v-model handlers when they fail to fallthrough
2315 if (!isModelListener(key)) {
2316 // remove `on`, lowercase first letter to reflect event casing
2317 // accurately
2318 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2319 }
2320 }
2321 else {
2322 extraAttrs.push(key);
2323 }
2324 }
2325 if (extraAttrs.length) {
2326 warn$1(`Extraneous non-props attributes (` +
2327 `${extraAttrs.join(', ')}) ` +
2328 `were passed to component but could not be automatically inherited ` +
2329 `because component renders fragment or text root nodes.`);
2330 }
2331 if (eventAttrs.length) {
2332 warn$1(`Extraneous non-emits event listeners (` +
2333 `${eventAttrs.join(', ')}) ` +
2334 `were passed to component but could not be automatically inherited ` +
2335 `because component renders fragment or text root nodes. ` +
2336 `If the listener is intended to be a component custom event listener only, ` +
2337 `declare it using the "emits" option.`);
2338 }
2339 }
2340 }
2341 }
2342 if (false &&
2343 isCompatEnabled("INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */, instance) &&
2344 vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */ &&
2345 root.shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) ;
2346 // inherit directives
2347 if (vnode.dirs) {
2348 if (true && !isElementRoot(root)) {
2349 warn$1(`Runtime directive used on component with non-element root node. ` +
2350 `The directives will not function as intended.`);
2351 }
2352 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2353 }
2354 // inherit transition data
2355 if (vnode.transition) {
2356 if (true && !isElementRoot(root)) {
2357 warn$1(`Component inside <Transition> renders non-element root node ` +
2358 `that cannot be animated.`);
2359 }
2360 root.transition = vnode.transition;
2361 }
2362 if (true && setRoot) {
2363 setRoot(root);
2364 }
2365 else {
2366 result = root;
2367 }
2368 }
2369 catch (err) {
2370 blockStack.length = 0;
2371 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2372 result = createVNode(Comment);
2373 }
2374 setCurrentRenderingInstance(prev);
2375 return result;
2376 }
2377 /**
2378 * dev only
2379 * In dev mode, template root level comments are rendered, which turns the
2380 * template into a fragment root, but we need to locate the single element
2381 * root for attrs and scope id processing.
2382 */
2383 const getChildRoot = (vnode) => {
2384 const rawChildren = vnode.children;
2385 const dynamicChildren = vnode.dynamicChildren;
2386 const childRoot = filterSingleRoot(rawChildren);
2387 if (!childRoot) {
2388 return [vnode, undefined];
2389 }
2390 const index = rawChildren.indexOf(childRoot);
2391 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2392 const setRoot = (updatedRoot) => {
2393 rawChildren[index] = updatedRoot;
2394 if (dynamicChildren) {
2395 if (dynamicIndex > -1) {
2396 dynamicChildren[dynamicIndex] = updatedRoot;
2397 }
2398 else if (updatedRoot.patchFlag > 0) {
2399 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2400 }
2401 }
2402 };
2403 return [normalizeVNode(childRoot), setRoot];
2404 };
2405 function filterSingleRoot(children) {
2406 let singleRoot;
2407 for (let i = 0; i < children.length; i++) {
2408 const child = children[i];
2409 if (isVNode(child)) {
2410 // ignore user comment
2411 if (child.type !== Comment || child.children === 'v-if') {
2412 if (singleRoot) {
2413 // has more than 1 non-comment child, return now
2414 return;
2415 }
2416 else {
2417 singleRoot = child;
2418 }
2419 }
2420 }
2421 else {
2422 return;
2423 }
2424 }
2425 return singleRoot;
2426 }
2427 const getFunctionalFallthrough = (attrs) => {
2428 let res;
2429 for (const key in attrs) {
2430 if (key === 'class' || key === 'style' || isOn(key)) {
2431 (res || (res = {}))[key] = attrs[key];
2432 }
2433 }
2434 return res;
2435 };
2436 const filterModelListeners = (attrs, props) => {
2437 const res = {};
2438 for (const key in attrs) {
2439 if (!isModelListener(key) || !(key.slice(9) in props)) {
2440 res[key] = attrs[key];
2441 }
2442 }
2443 return res;
2444 };
2445 const isElementRoot = (vnode) => {
2446 return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
2447 vnode.type === Comment // potential v-if branch switch
2448 );
2449 };
2450 function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2451 const { props: prevProps, children: prevChildren, component } = prevVNode;
2452 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2453 const emits = component.emitsOptions;
2454 // Parent component's render function was hot-updated. Since this may have
2455 // caused the child component's slots content to have changed, we need to
2456 // force the child to update as well.
2457 if ((prevChildren || nextChildren) && isHmrUpdating) {
2458 return true;
2459 }
2460 // force child update for runtime directive or transition on component vnode.
2461 if (nextVNode.dirs || nextVNode.transition) {
2462 return true;
2463 }
2464 if (optimized && patchFlag >= 0) {
2465 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2466 // slot content that references values that might have changed,
2467 // e.g. in a v-for
2468 return true;
2469 }
2470 if (patchFlag & 16 /* FULL_PROPS */) {
2471 if (!prevProps) {
2472 return !!nextProps;
2473 }
2474 // presence of this flag indicates props are always non-null
2475 return hasPropsChanged(prevProps, nextProps, emits);
2476 }
2477 else if (patchFlag & 8 /* PROPS */) {
2478 const dynamicProps = nextVNode.dynamicProps;
2479 for (let i = 0; i < dynamicProps.length; i++) {
2480 const key = dynamicProps[i];
2481 if (nextProps[key] !== prevProps[key] &&
2482 !isEmitListener(emits, key)) {
2483 return true;
2484 }
2485 }
2486 }
2487 }
2488 else {
2489 // this path is only taken by manually written render functions
2490 // so presence of any children leads to a forced update
2491 if (prevChildren || nextChildren) {
2492 if (!nextChildren || !nextChildren.$stable) {
2493 return true;
2494 }
2495 }
2496 if (prevProps === nextProps) {
2497 return false;
2498 }
2499 if (!prevProps) {
2500 return !!nextProps;
2501 }
2502 if (!nextProps) {
2503 return true;
2504 }
2505 return hasPropsChanged(prevProps, nextProps, emits);
2506 }
2507 return false;
2508 }
2509 function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2510 const nextKeys = Object.keys(nextProps);
2511 if (nextKeys.length !== Object.keys(prevProps).length) {
2512 return true;
2513 }
2514 for (let i = 0; i < nextKeys.length; i++) {
2515 const key = nextKeys[i];
2516 if (nextProps[key] !== prevProps[key] &&
2517 !isEmitListener(emitsOptions, key)) {
2518 return true;
2519 }
2520 }
2521 return false;
2522 }
2523 function updateHOCHostEl({ vnode, parent }, el // HostNode
2524 ) {
2525 while (parent && parent.subTree === vnode) {
2526 (vnode = parent.vnode).el = el;
2527 parent = parent.parent;
2528 }
2529 }
2530
2531 const isSuspense = (type) => type.__isSuspense;
2532 // Suspense exposes a component-like API, and is treated like a component
2533 // in the compiler, but internally it's a special built-in type that hooks
2534 // directly into the renderer.
2535 const SuspenseImpl = {
2536 name: 'Suspense',
2537 // In order to make Suspense tree-shakable, we need to avoid importing it
2538 // directly in the renderer. The renderer checks for the __isSuspense flag
2539 // on a vnode's type and calls the `process` method, passing in renderer
2540 // internals.
2541 __isSuspense: true,
2542 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2543 // platform-specific impl passed from renderer
2544 rendererInternals) {
2545 if (n1 == null) {
2546 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2547 }
2548 else {
2549 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2550 }
2551 },
2552 hydrate: hydrateSuspense,
2553 create: createSuspenseBoundary,
2554 normalize: normalizeSuspenseChildren
2555 };
2556 // Force-casted public typing for h and TSX props inference
2557 const Suspense = (SuspenseImpl );
2558 function triggerEvent(vnode, name) {
2559 const eventListener = vnode.props && vnode.props[name];
2560 if (isFunction(eventListener)) {
2561 eventListener();
2562 }
2563 }
2564 function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2565 const { p: patch, o: { createElement } } = rendererInternals;
2566 const hiddenContainer = createElement('div');
2567 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2568 // start mounting the content subtree in an off-dom container
2569 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2570 // now check if we have encountered any async deps
2571 if (suspense.deps > 0) {
2572 // has async
2573 // invoke @fallback event
2574 triggerEvent(vnode, 'onPending');
2575 triggerEvent(vnode, 'onFallback');
2576 // mount the fallback tree
2577 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2578 isSVG, slotScopeIds);
2579 setActiveBranch(suspense, vnode.ssFallback);
2580 }
2581 else {
2582 // Suspense has no async deps. Just resolve.
2583 suspense.resolve();
2584 }
2585 }
2586 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2587 const suspense = (n2.suspense = n1.suspense);
2588 suspense.vnode = n2;
2589 n2.el = n1.el;
2590 const newBranch = n2.ssContent;
2591 const newFallback = n2.ssFallback;
2592 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2593 if (pendingBranch) {
2594 suspense.pendingBranch = newBranch;
2595 if (isSameVNodeType(newBranch, pendingBranch)) {
2596 // same root type but content may have changed.
2597 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2598 if (suspense.deps <= 0) {
2599 suspense.resolve();
2600 }
2601 else if (isInFallback) {
2602 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2603 isSVG, slotScopeIds, optimized);
2604 setActiveBranch(suspense, newFallback);
2605 }
2606 }
2607 else {
2608 // toggled before pending tree is resolved
2609 suspense.pendingId++;
2610 if (isHydrating) {
2611 // if toggled before hydration is finished, the current DOM tree is
2612 // no longer valid. set it as the active branch so it will be unmounted
2613 // when resolved
2614 suspense.isHydrating = false;
2615 suspense.activeBranch = pendingBranch;
2616 }
2617 else {
2618 unmount(pendingBranch, parentComponent, suspense);
2619 }
2620 // increment pending ID. this is used to invalidate async callbacks
2621 // reset suspense state
2622 suspense.deps = 0;
2623 // discard effects from pending branch
2624 suspense.effects.length = 0;
2625 // discard previous container
2626 suspense.hiddenContainer = createElement('div');
2627 if (isInFallback) {
2628 // already in fallback state
2629 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2630 if (suspense.deps <= 0) {
2631 suspense.resolve();
2632 }
2633 else {
2634 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2635 isSVG, slotScopeIds, optimized);
2636 setActiveBranch(suspense, newFallback);
2637 }
2638 }
2639 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2640 // toggled "back" to current active branch
2641 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2642 // force resolve
2643 suspense.resolve(true);
2644 }
2645 else {
2646 // switched to a 3rd branch
2647 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2648 if (suspense.deps <= 0) {
2649 suspense.resolve();
2650 }
2651 }
2652 }
2653 }
2654 else {
2655 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2656 // root did not change, just normal patch
2657 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2658 setActiveBranch(suspense, newBranch);
2659 }
2660 else {
2661 // root node toggled
2662 // invoke @pending event
2663 triggerEvent(n2, 'onPending');
2664 // mount pending branch in off-dom container
2665 suspense.pendingBranch = newBranch;
2666 suspense.pendingId++;
2667 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2668 if (suspense.deps <= 0) {
2669 // incoming branch has no async deps, resolve now.
2670 suspense.resolve();
2671 }
2672 else {
2673 const { timeout, pendingId } = suspense;
2674 if (timeout > 0) {
2675 setTimeout(() => {
2676 if (suspense.pendingId === pendingId) {
2677 suspense.fallback(newFallback);
2678 }
2679 }, timeout);
2680 }
2681 else if (timeout === 0) {
2682 suspense.fallback(newFallback);
2683 }
2684 }
2685 }
2686 }
2687 }
2688 let hasWarned = false;
2689 function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2690 /* istanbul ignore if */
2691 if (!hasWarned) {
2692 hasWarned = true;
2693 // @ts-ignore `console.info` cannot be null error
2694 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2695 }
2696 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2697 const timeout = toNumber(vnode.props && vnode.props.timeout);
2698 const suspense = {
2699 vnode,
2700 parent,
2701 parentComponent,
2702 isSVG,
2703 container,
2704 hiddenContainer,
2705 anchor,
2706 deps: 0,
2707 pendingId: 0,
2708 timeout: typeof timeout === 'number' ? timeout : -1,
2709 activeBranch: null,
2710 pendingBranch: null,
2711 isInFallback: true,
2712 isHydrating,
2713 isUnmounted: false,
2714 effects: [],
2715 resolve(resume = false) {
2716 {
2717 if (!resume && !suspense.pendingBranch) {
2718 throw new Error(`suspense.resolve() is called without a pending branch.`);
2719 }
2720 if (suspense.isUnmounted) {
2721 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2722 }
2723 }
2724 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2725 if (suspense.isHydrating) {
2726 suspense.isHydrating = false;
2727 }
2728 else if (!resume) {
2729 const delayEnter = activeBranch &&
2730 pendingBranch.transition &&
2731 pendingBranch.transition.mode === 'out-in';
2732 if (delayEnter) {
2733 activeBranch.transition.afterLeave = () => {
2734 if (pendingId === suspense.pendingId) {
2735 move(pendingBranch, container, anchor, 0 /* ENTER */);
2736 }
2737 };
2738 }
2739 // this is initial anchor on mount
2740 let { anchor } = suspense;
2741 // unmount current active tree
2742 if (activeBranch) {
2743 // if the fallback tree was mounted, it may have been moved
2744 // as part of a parent suspense. get the latest anchor for insertion
2745 anchor = next(activeBranch);
2746 unmount(activeBranch, parentComponent, suspense, true);
2747 }
2748 if (!delayEnter) {
2749 // move content from off-dom container to actual container
2750 move(pendingBranch, container, anchor, 0 /* ENTER */);
2751 }
2752 }
2753 setActiveBranch(suspense, pendingBranch);
2754 suspense.pendingBranch = null;
2755 suspense.isInFallback = false;
2756 // flush buffered effects
2757 // check if there is a pending parent suspense
2758 let parent = suspense.parent;
2759 let hasUnresolvedAncestor = false;
2760 while (parent) {
2761 if (parent.pendingBranch) {
2762 // found a pending parent suspense, merge buffered post jobs
2763 // into that parent
2764 parent.effects.push(...effects);
2765 hasUnresolvedAncestor = true;
2766 break;
2767 }
2768 parent = parent.parent;
2769 }
2770 // no pending parent suspense, flush all jobs
2771 if (!hasUnresolvedAncestor) {
2772 queuePostFlushCb(effects);
2773 }
2774 suspense.effects = [];
2775 // invoke @resolve event
2776 triggerEvent(vnode, 'onResolve');
2777 },
2778 fallback(fallbackVNode) {
2779 if (!suspense.pendingBranch) {
2780 return;
2781 }
2782 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2783 // invoke @fallback event
2784 triggerEvent(vnode, 'onFallback');
2785 const anchor = next(activeBranch);
2786 const mountFallback = () => {
2787 if (!suspense.isInFallback) {
2788 return;
2789 }
2790 // mount the fallback tree
2791 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2792 isSVG, slotScopeIds, optimized);
2793 setActiveBranch(suspense, fallbackVNode);
2794 };
2795 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2796 if (delayEnter) {
2797 activeBranch.transition.afterLeave = mountFallback;
2798 }
2799 suspense.isInFallback = true;
2800 // unmount current active branch
2801 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2802 true // shouldRemove
2803 );
2804 if (!delayEnter) {
2805 mountFallback();
2806 }
2807 },
2808 move(container, anchor, type) {
2809 suspense.activeBranch &&
2810 move(suspense.activeBranch, container, anchor, type);
2811 suspense.container = container;
2812 },
2813 next() {
2814 return suspense.activeBranch && next(suspense.activeBranch);
2815 },
2816 registerDep(instance, setupRenderEffect) {
2817 const isInPendingSuspense = !!suspense.pendingBranch;
2818 if (isInPendingSuspense) {
2819 suspense.deps++;
2820 }
2821 const hydratedEl = instance.vnode.el;
2822 instance
2823 .asyncDep.catch(err => {
2824 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2825 })
2826 .then(asyncSetupResult => {
2827 // retry when the setup() promise resolves.
2828 // component may have been unmounted before resolve.
2829 if (instance.isUnmounted ||
2830 suspense.isUnmounted ||
2831 suspense.pendingId !== instance.suspenseId) {
2832 return;
2833 }
2834 // retry from this component
2835 instance.asyncResolved = true;
2836 const { vnode } = instance;
2837 {
2838 pushWarningContext(vnode);
2839 }
2840 handleSetupResult(instance, asyncSetupResult, false);
2841 if (hydratedEl) {
2842 // vnode may have been replaced if an update happened before the
2843 // async dep is resolved.
2844 vnode.el = hydratedEl;
2845 }
2846 const placeholder = !hydratedEl && instance.subTree.el;
2847 setupRenderEffect(instance, vnode,
2848 // component may have been moved before resolve.
2849 // if this is not a hydration, instance.subTree will be the comment
2850 // placeholder.
2851 parentNode(hydratedEl || instance.subTree.el),
2852 // anchor will not be used if this is hydration, so only need to
2853 // consider the comment placeholder case.
2854 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
2855 if (placeholder) {
2856 remove(placeholder);
2857 }
2858 updateHOCHostEl(instance, vnode.el);
2859 {
2860 popWarningContext();
2861 }
2862 // only decrease deps count if suspense is not already resolved
2863 if (isInPendingSuspense && --suspense.deps === 0) {
2864 suspense.resolve();
2865 }
2866 });
2867 },
2868 unmount(parentSuspense, doRemove) {
2869 suspense.isUnmounted = true;
2870 if (suspense.activeBranch) {
2871 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
2872 }
2873 if (suspense.pendingBranch) {
2874 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
2875 }
2876 }
2877 };
2878 return suspense;
2879 }
2880 function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
2881 /* eslint-disable no-restricted-globals */
2882 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
2883 // there are two possible scenarios for server-rendered suspense:
2884 // - success: ssr content should be fully resolved
2885 // - failure: ssr content should be the fallback branch.
2886 // however, on the client we don't really know if it has failed or not
2887 // attempt to hydrate the DOM assuming it has succeeded, but we still
2888 // need to construct a suspense boundary first
2889 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
2890 if (suspense.deps === 0) {
2891 suspense.resolve();
2892 }
2893 return result;
2894 /* eslint-enable no-restricted-globals */
2895 }
2896 function normalizeSuspenseChildren(vnode) {
2897 const { shapeFlag, children } = vnode;
2898 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
2899 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
2900 vnode.ssFallback = isSlotChildren
2901 ? normalizeSuspenseSlot(children.fallback)
2902 : createVNode(Comment);
2903 }
2904 function normalizeSuspenseSlot(s) {
2905 let block;
2906 if (isFunction(s)) {
2907 const isCompiledSlot = s._c;
2908 if (isCompiledSlot) {
2909 // disableTracking: false
2910 // allow block tracking for compiled slots
2911 // (see ./componentRenderContext.ts)
2912 s._d = false;
2913 openBlock();
2914 }
2915 s = s();
2916 if (isCompiledSlot) {
2917 s._d = true;
2918 block = currentBlock;
2919 closeBlock();
2920 }
2921 }
2922 if (isArray(s)) {
2923 const singleChild = filterSingleRoot(s);
2924 if (!singleChild) {
2925 warn$1(`<Suspense> slots expect a single root node.`);
2926 }
2927 s = singleChild;
2928 }
2929 s = normalizeVNode(s);
2930 if (block && !s.dynamicChildren) {
2931 s.dynamicChildren = block.filter(c => c !== s);
2932 }
2933 return s;
2934 }
2935 function queueEffectWithSuspense(fn, suspense) {
2936 if (suspense && suspense.pendingBranch) {
2937 if (isArray(fn)) {
2938 suspense.effects.push(...fn);
2939 }
2940 else {
2941 suspense.effects.push(fn);
2942 }
2943 }
2944 else {
2945 queuePostFlushCb(fn);
2946 }
2947 }
2948 function setActiveBranch(suspense, branch) {
2949 suspense.activeBranch = branch;
2950 const { vnode, parentComponent } = suspense;
2951 const el = (vnode.el = branch.el);
2952 // in case suspense is the root node of a component,
2953 // recursively update the HOC el
2954 if (parentComponent && parentComponent.subTree === vnode) {
2955 parentComponent.vnode.el = el;
2956 updateHOCHostEl(parentComponent, el);
2957 }
2958 }
2959
2960 function provide(key, value) {
2961 if (!currentInstance) {
2962 {
2963 warn$1(`provide() can only be used inside setup().`);
2964 }
2965 }
2966 else {
2967 let provides = currentInstance.provides;
2968 // by default an instance inherits its parent's provides object
2969 // but when it needs to provide values of its own, it creates its
2970 // own provides object using parent provides object as prototype.
2971 // this way in `inject` we can simply look up injections from direct
2972 // parent and let the prototype chain do the work.
2973 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
2974 if (parentProvides === provides) {
2975 provides = currentInstance.provides = Object.create(parentProvides);
2976 }
2977 // TS doesn't allow symbol as index type
2978 provides[key] = value;
2979 }
2980 }
2981 function inject(key, defaultValue, treatDefaultAsFactory = false) {
2982 // fallback to `currentRenderingInstance` so that this can be called in
2983 // a functional component
2984 const instance = currentInstance || currentRenderingInstance;
2985 if (instance) {
2986 // #2400
2987 // to support `app.use` plugins,
2988 // fallback to appContext's `provides` if the intance is at root
2989 const provides = instance.parent == null
2990 ? instance.vnode.appContext && instance.vnode.appContext.provides
2991 : instance.parent.provides;
2992 if (provides && key in provides) {
2993 // TS doesn't allow symbol as index type
2994 return provides[key];
2995 }
2996 else if (arguments.length > 1) {
2997 return treatDefaultAsFactory && isFunction(defaultValue)
2998 ? defaultValue.call(instance.proxy)
2999 : defaultValue;
3000 }
3001 else {
3002 warn$1(`injection "${String(key)}" not found.`);
3003 }
3004 }
3005 else {
3006 warn$1(`inject() can only be used inside setup() or functional components.`);
3007 }
3008 }
3009
3010 function useTransitionState() {
3011 const state = {
3012 isMounted: false,
3013 isLeaving: false,
3014 isUnmounting: false,
3015 leavingVNodes: new Map()
3016 };
3017 onMounted(() => {
3018 state.isMounted = true;
3019 });
3020 onBeforeUnmount(() => {
3021 state.isUnmounting = true;
3022 });
3023 return state;
3024 }
3025 const TransitionHookValidator = [Function, Array];
3026 const BaseTransitionImpl = {
3027 name: `BaseTransition`,
3028 props: {
3029 mode: String,
3030 appear: Boolean,
3031 persisted: Boolean,
3032 // enter
3033 onBeforeEnter: TransitionHookValidator,
3034 onEnter: TransitionHookValidator,
3035 onAfterEnter: TransitionHookValidator,
3036 onEnterCancelled: TransitionHookValidator,
3037 // leave
3038 onBeforeLeave: TransitionHookValidator,
3039 onLeave: TransitionHookValidator,
3040 onAfterLeave: TransitionHookValidator,
3041 onLeaveCancelled: TransitionHookValidator,
3042 // appear
3043 onBeforeAppear: TransitionHookValidator,
3044 onAppear: TransitionHookValidator,
3045 onAfterAppear: TransitionHookValidator,
3046 onAppearCancelled: TransitionHookValidator
3047 },
3048 setup(props, { slots }) {
3049 const instance = getCurrentInstance();
3050 const state = useTransitionState();
3051 let prevTransitionKey;
3052 return () => {
3053 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3054 if (!children || !children.length) {
3055 return;
3056 }
3057 // warn multiple elements
3058 if (children.length > 1) {
3059 warn$1('<transition> can only be used on a single element or component. Use ' +
3060 '<transition-group> for lists.');
3061 }
3062 // there's no need to track reactivity for these props so use the raw
3063 // props for a bit better perf
3064 const rawProps = toRaw(props);
3065 const { mode } = rawProps;
3066 // check mode
3067 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3068 warn$1(`invalid <transition> mode: ${mode}`);
3069 }
3070 // at this point children has a guaranteed length of 1.
3071 const child = children[0];
3072 if (state.isLeaving) {
3073 return emptyPlaceholder(child);
3074 }
3075 // in the case of <transition><keep-alive/></transition>, we need to
3076 // compare the type of the kept-alive children.
3077 const innerChild = getKeepAliveChild(child);
3078 if (!innerChild) {
3079 return emptyPlaceholder(child);
3080 }
3081 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3082 setTransitionHooks(innerChild, enterHooks);
3083 const oldChild = instance.subTree;
3084 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3085 let transitionKeyChanged = false;
3086 const { getTransitionKey } = innerChild.type;
3087 if (getTransitionKey) {
3088 const key = getTransitionKey();
3089 if (prevTransitionKey === undefined) {
3090 prevTransitionKey = key;
3091 }
3092 else if (key !== prevTransitionKey) {
3093 prevTransitionKey = key;
3094 transitionKeyChanged = true;
3095 }
3096 }
3097 // handle mode
3098 if (oldInnerChild &&
3099 oldInnerChild.type !== Comment &&
3100 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3101 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3102 // update old tree's hooks in case of dynamic transition
3103 setTransitionHooks(oldInnerChild, leavingHooks);
3104 // switching between different views
3105 if (mode === 'out-in') {
3106 state.isLeaving = true;
3107 // return placeholder node and queue update when leave finishes
3108 leavingHooks.afterLeave = () => {
3109 state.isLeaving = false;
3110 instance.update();
3111 };
3112 return emptyPlaceholder(child);
3113 }
3114 else if (mode === 'in-out' && innerChild.type !== Comment) {
3115 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3116 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3117 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3118 // early removal callback
3119 el._leaveCb = () => {
3120 earlyRemove();
3121 el._leaveCb = undefined;
3122 delete enterHooks.delayedLeave;
3123 };
3124 enterHooks.delayedLeave = delayedLeave;
3125 };
3126 }
3127 }
3128 return child;
3129 };
3130 }
3131 };
3132 // export the public type for h/tsx inference
3133 // also to avoid inline import() in generated d.ts files
3134 const BaseTransition = BaseTransitionImpl;
3135 function getLeavingNodesForType(state, vnode) {
3136 const { leavingVNodes } = state;
3137 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3138 if (!leavingVNodesCache) {
3139 leavingVNodesCache = Object.create(null);
3140 leavingVNodes.set(vnode.type, leavingVNodesCache);
3141 }
3142 return leavingVNodesCache;
3143 }
3144 // The transition hooks are attached to the vnode as vnode.transition
3145 // and will be called at appropriate timing in the renderer.
3146 function resolveTransitionHooks(vnode, props, state, instance) {
3147 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3148 const key = String(vnode.key);
3149 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3150 const callHook = (hook, args) => {
3151 hook &&
3152 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3153 };
3154 const hooks = {
3155 mode,
3156 persisted,
3157 beforeEnter(el) {
3158 let hook = onBeforeEnter;
3159 if (!state.isMounted) {
3160 if (appear) {
3161 hook = onBeforeAppear || onBeforeEnter;
3162 }
3163 else {
3164 return;
3165 }
3166 }
3167 // for same element (v-show)
3168 if (el._leaveCb) {
3169 el._leaveCb(true /* cancelled */);
3170 }
3171 // for toggled element with same key (v-if)
3172 const leavingVNode = leavingVNodesCache[key];
3173 if (leavingVNode &&
3174 isSameVNodeType(vnode, leavingVNode) &&
3175 leavingVNode.el._leaveCb) {
3176 // force early removal (not cancelled)
3177 leavingVNode.el._leaveCb();
3178 }
3179 callHook(hook, [el]);
3180 },
3181 enter(el) {
3182 let hook = onEnter;
3183 let afterHook = onAfterEnter;
3184 let cancelHook = onEnterCancelled;
3185 if (!state.isMounted) {
3186 if (appear) {
3187 hook = onAppear || onEnter;
3188 afterHook = onAfterAppear || onAfterEnter;
3189 cancelHook = onAppearCancelled || onEnterCancelled;
3190 }
3191 else {
3192 return;
3193 }
3194 }
3195 let called = false;
3196 const done = (el._enterCb = (cancelled) => {
3197 if (called)
3198 return;
3199 called = true;
3200 if (cancelled) {
3201 callHook(cancelHook, [el]);
3202 }
3203 else {
3204 callHook(afterHook, [el]);
3205 }
3206 if (hooks.delayedLeave) {
3207 hooks.delayedLeave();
3208 }
3209 el._enterCb = undefined;
3210 });
3211 if (hook) {
3212 hook(el, done);
3213 if (hook.length <= 1) {
3214 done();
3215 }
3216 }
3217 else {
3218 done();
3219 }
3220 },
3221 leave(el, remove) {
3222 const key = String(vnode.key);
3223 if (el._enterCb) {
3224 el._enterCb(true /* cancelled */);
3225 }
3226 if (state.isUnmounting) {
3227 return remove();
3228 }
3229 callHook(onBeforeLeave, [el]);
3230 let called = false;
3231 const done = (el._leaveCb = (cancelled) => {
3232 if (called)
3233 return;
3234 called = true;
3235 remove();
3236 if (cancelled) {
3237 callHook(onLeaveCancelled, [el]);
3238 }
3239 else {
3240 callHook(onAfterLeave, [el]);
3241 }
3242 el._leaveCb = undefined;
3243 if (leavingVNodesCache[key] === vnode) {
3244 delete leavingVNodesCache[key];
3245 }
3246 });
3247 leavingVNodesCache[key] = vnode;
3248 if (onLeave) {
3249 onLeave(el, done);
3250 if (onLeave.length <= 1) {
3251 done();
3252 }
3253 }
3254 else {
3255 done();
3256 }
3257 },
3258 clone(vnode) {
3259 return resolveTransitionHooks(vnode, props, state, instance);
3260 }
3261 };
3262 return hooks;
3263 }
3264 // the placeholder really only handles one special case: KeepAlive
3265 // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3266 // placeholder with empty content to avoid the KeepAlive instance from being
3267 // unmounted.
3268 function emptyPlaceholder(vnode) {
3269 if (isKeepAlive(vnode)) {
3270 vnode = cloneVNode(vnode);
3271 vnode.children = null;
3272 return vnode;
3273 }
3274 }
3275 function getKeepAliveChild(vnode) {
3276 return isKeepAlive(vnode)
3277 ? vnode.children
3278 ? vnode.children[0]
3279 : undefined
3280 : vnode;
3281 }
3282 function setTransitionHooks(vnode, hooks) {
3283 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3284 setTransitionHooks(vnode.component.subTree, hooks);
3285 }
3286 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3287 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3288 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3289 }
3290 else {
3291 vnode.transition = hooks;
3292 }
3293 }
3294 function getTransitionRawChildren(children, keepComment = false) {
3295 let ret = [];
3296 let keyedFragmentCount = 0;
3297 for (let i = 0; i < children.length; i++) {
3298 const child = children[i];
3299 // handle fragment children case, e.g. v-for
3300 if (child.type === Fragment) {
3301 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3302 keyedFragmentCount++;
3303 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3304 }
3305 // comment placeholders should be skipped, e.g. v-if
3306 else if (keepComment || child.type !== Comment) {
3307 ret.push(child);
3308 }
3309 }
3310 // #1126 if a transition children list contains multiple sub fragments, these
3311 // fragments will be merged into a flat children array. Since each v-for
3312 // fragment may contain different static bindings inside, we need to de-op
3313 // these children to force full diffs to ensure correct behavior.
3314 if (keyedFragmentCount > 1) {
3315 for (let i = 0; i < ret.length; i++) {
3316 ret[i].patchFlag = -2 /* BAIL */;
3317 }
3318 }
3319 return ret;
3320 }
3321
3322 // implementation, close to no-op
3323 function defineComponent(options) {
3324 return isFunction(options) ? { setup: options, name: options.name } : options;
3325 }
3326
3327 const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3328 function defineAsyncComponent(source) {
3329 if (isFunction(source)) {
3330 source = { loader: source };
3331 }
3332 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3333 suspensible = true, onError: userOnError } = source;
3334 let pendingRequest = null;
3335 let resolvedComp;
3336 let retries = 0;
3337 const retry = () => {
3338 retries++;
3339 pendingRequest = null;
3340 return load();
3341 };
3342 const load = () => {
3343 let thisRequest;
3344 return (pendingRequest ||
3345 (thisRequest = pendingRequest =
3346 loader()
3347 .catch(err => {
3348 err = err instanceof Error ? err : new Error(String(err));
3349 if (userOnError) {
3350 return new Promise((resolve, reject) => {
3351 const userRetry = () => resolve(retry());
3352 const userFail = () => reject(err);
3353 userOnError(err, userRetry, userFail, retries + 1);
3354 });
3355 }
3356 else {
3357 throw err;
3358 }
3359 })
3360 .then((comp) => {
3361 if (thisRequest !== pendingRequest && pendingRequest) {
3362 return pendingRequest;
3363 }
3364 if (!comp) {
3365 warn$1(`Async component loader resolved to undefined. ` +
3366 `If you are using retry(), make sure to return its return value.`);
3367 }
3368 // interop module default
3369 if (comp &&
3370 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3371 comp = comp.default;
3372 }
3373 if (comp && !isObject(comp) && !isFunction(comp)) {
3374 throw new Error(`Invalid async component load result: ${comp}`);
3375 }
3376 resolvedComp = comp;
3377 return comp;
3378 })));
3379 };
3380 return defineComponent({
3381 name: 'AsyncComponentWrapper',
3382 __asyncLoader: load,
3383 get __asyncResolved() {
3384 return resolvedComp;
3385 },
3386 setup() {
3387 const instance = currentInstance;
3388 // already resolved
3389 if (resolvedComp) {
3390 return () => createInnerComp(resolvedComp, instance);
3391 }
3392 const onError = (err) => {
3393 pendingRequest = null;
3394 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3395 };
3396 // suspense-controlled or SSR.
3397 if ((suspensible && instance.suspense) ||
3398 (false )) {
3399 return load()
3400 .then(comp => {
3401 return () => createInnerComp(comp, instance);
3402 })
3403 .catch(err => {
3404 onError(err);
3405 return () => errorComponent
3406 ? createVNode(errorComponent, {
3407 error: err
3408 })
3409 : null;
3410 });
3411 }
3412 const loaded = ref(false);
3413 const error = ref();
3414 const delayed = ref(!!delay);
3415 if (delay) {
3416 setTimeout(() => {
3417 delayed.value = false;
3418 }, delay);
3419 }
3420 if (timeout != null) {
3421 setTimeout(() => {
3422 if (!loaded.value && !error.value) {
3423 const err = new Error(`Async component timed out after ${timeout}ms.`);
3424 onError(err);
3425 error.value = err;
3426 }
3427 }, timeout);
3428 }
3429 load()
3430 .then(() => {
3431 loaded.value = true;
3432 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3433 // parent is keep-alive, force update so the loaded component's
3434 // name is taken into account
3435 queueJob(instance.parent.update);
3436 }
3437 })
3438 .catch(err => {
3439 onError(err);
3440 error.value = err;
3441 });
3442 return () => {
3443 if (loaded.value && resolvedComp) {
3444 return createInnerComp(resolvedComp, instance);
3445 }
3446 else if (error.value && errorComponent) {
3447 return createVNode(errorComponent, {
3448 error: error.value
3449 });
3450 }
3451 else if (loadingComponent && !delayed.value) {
3452 return createVNode(loadingComponent);
3453 }
3454 };
3455 }
3456 });
3457 }
3458 function createInnerComp(comp, { vnode: { ref, props, children } }) {
3459 const vnode = createVNode(comp, props, children);
3460 // ensure inner component inherits the async wrapper's ref owner
3461 vnode.ref = ref;
3462 return vnode;
3463 }
3464
3465 const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3466 const KeepAliveImpl = {
3467 name: `KeepAlive`,
3468 // Marker for special handling inside the renderer. We are not using a ===
3469 // check directly on KeepAlive in the renderer, because importing it directly
3470 // would prevent it from being tree-shaken.
3471 __isKeepAlive: true,
3472 props: {
3473 include: [String, RegExp, Array],
3474 exclude: [String, RegExp, Array],
3475 max: [String, Number]
3476 },
3477 setup(props, { slots }) {
3478 const instance = getCurrentInstance();
3479 // KeepAlive communicates with the instantiated renderer via the
3480 // ctx where the renderer passes in its internals,
3481 // and the KeepAlive instance exposes activate/deactivate implementations.
3482 // The whole point of this is to avoid importing KeepAlive directly in the
3483 // renderer to facilitate tree-shaking.
3484 const sharedContext = instance.ctx;
3485 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3486 // for KeepAlive, we just need to render its children
3487 if (!sharedContext.renderer) {
3488 return slots.default;
3489 }
3490 const cache = new Map();
3491 const keys = new Set();
3492 let current = null;
3493 {
3494 instance.__v_cache = cache;
3495 }
3496 const parentSuspense = instance.suspense;
3497 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3498 const storageContainer = createElement('div');
3499 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3500 const instance = vnode.component;
3501 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3502 // in case props have changed
3503 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3504 queuePostRenderEffect(() => {
3505 instance.isDeactivated = false;
3506 if (instance.a) {
3507 invokeArrayFns(instance.a);
3508 }
3509 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3510 if (vnodeHook) {
3511 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3512 }
3513 }, parentSuspense);
3514 {
3515 // Update components tree
3516 devtoolsComponentAdded(instance);
3517 }
3518 };
3519 sharedContext.deactivate = (vnode) => {
3520 const instance = vnode.component;
3521 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3522 queuePostRenderEffect(() => {
3523 if (instance.da) {
3524 invokeArrayFns(instance.da);
3525 }
3526 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3527 if (vnodeHook) {
3528 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3529 }
3530 instance.isDeactivated = true;
3531 }, parentSuspense);
3532 {
3533 // Update components tree
3534 devtoolsComponentAdded(instance);
3535 }
3536 };
3537 function unmount(vnode) {
3538 // reset the shapeFlag so it can be properly unmounted
3539 resetShapeFlag(vnode);
3540 _unmount(vnode, instance, parentSuspense);
3541 }
3542 function pruneCache(filter) {
3543 cache.forEach((vnode, key) => {
3544 const name = getComponentName(vnode.type);
3545 if (name && (!filter || !filter(name))) {
3546 pruneCacheEntry(key);
3547 }
3548 });
3549 }
3550 function pruneCacheEntry(key) {
3551 const cached = cache.get(key);
3552 if (!current || cached.type !== current.type) {
3553 unmount(cached);
3554 }
3555 else if (current) {
3556 // current active instance should no longer be kept-alive.
3557 // we can't unmount it now but it might be later, so reset its flag now.
3558 resetShapeFlag(current);
3559 }
3560 cache.delete(key);
3561 keys.delete(key);
3562 }
3563 // prune cache on include/exclude prop change
3564 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3565 include && pruneCache(name => matches(include, name));
3566 exclude && pruneCache(name => !matches(exclude, name));
3567 },
3568 // prune post-render after `current` has been updated
3569 { flush: 'post', deep: true });
3570 // cache sub tree after render
3571 let pendingCacheKey = null;
3572 const cacheSubtree = () => {
3573 // fix #1621, the pendingCacheKey could be 0
3574 if (pendingCacheKey != null) {
3575 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3576 }
3577 };
3578 onMounted(cacheSubtree);
3579 onUpdated(cacheSubtree);
3580 onBeforeUnmount(() => {
3581 cache.forEach(cached => {
3582 const { subTree, suspense } = instance;
3583 const vnode = getInnerChild(subTree);
3584 if (cached.type === vnode.type) {
3585 // current instance will be unmounted as part of keep-alive's unmount
3586 resetShapeFlag(vnode);
3587 // but invoke its deactivated hook here
3588 const da = vnode.component.da;
3589 da && queuePostRenderEffect(da, suspense);
3590 return;
3591 }
3592 unmount(cached);
3593 });
3594 });
3595 return () => {
3596 pendingCacheKey = null;
3597 if (!slots.default) {
3598 return null;
3599 }
3600 const children = slots.default();
3601 const rawVNode = children[0];
3602 if (children.length > 1) {
3603 {
3604 warn$1(`KeepAlive should contain exactly one component child.`);
3605 }
3606 current = null;
3607 return children;
3608 }
3609 else if (!isVNode(rawVNode) ||
3610 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3611 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3612 current = null;
3613 return rawVNode;
3614 }
3615 let vnode = getInnerChild(rawVNode);
3616 const comp = vnode.type;
3617 // for async components, name check should be based in its loaded
3618 // inner component if available
3619 const name = getComponentName(isAsyncWrapper(vnode)
3620 ? vnode.type.__asyncResolved || {}
3621 : comp);
3622 const { include, exclude, max } = props;
3623 if ((include && (!name || !matches(include, name))) ||
3624 (exclude && name && matches(exclude, name))) {
3625 current = vnode;
3626 return rawVNode;
3627 }
3628 const key = vnode.key == null ? comp : vnode.key;
3629 const cachedVNode = cache.get(key);
3630 // clone vnode if it's reused because we are going to mutate it
3631 if (vnode.el) {
3632 vnode = cloneVNode(vnode);
3633 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
3634 rawVNode.ssContent = vnode;
3635 }
3636 }
3637 // #1513 it's possible for the returned vnode to be cloned due to attr
3638 // fallthrough or scopeId, so the vnode here may not be the final vnode
3639 // that is mounted. Instead of caching it directly, we store the pending
3640 // key and cache `instance.subTree` (the normalized vnode) in
3641 // beforeMount/beforeUpdate hooks.
3642 pendingCacheKey = key;
3643 if (cachedVNode) {
3644 // copy over mounted state
3645 vnode.el = cachedVNode.el;
3646 vnode.component = cachedVNode.component;
3647 if (vnode.transition) {
3648 // recursively update transition hooks on subTree
3649 setTransitionHooks(vnode, vnode.transition);
3650 }
3651 // avoid vnode being mounted as fresh
3652 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
3653 // make this key the freshest
3654 keys.delete(key);
3655 keys.add(key);
3656 }
3657 else {
3658 keys.add(key);
3659 // prune oldest entry
3660 if (max && keys.size > parseInt(max, 10)) {
3661 pruneCacheEntry(keys.values().next().value);
3662 }
3663 }
3664 // avoid vnode being unmounted
3665 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3666 current = vnode;
3667 return rawVNode;
3668 };
3669 }
3670 };
3671 // export the public type for h/tsx inference
3672 // also to avoid inline import() in generated d.ts files
3673 const KeepAlive = KeepAliveImpl;
3674 function matches(pattern, name) {
3675 if (isArray(pattern)) {
3676 return pattern.some((p) => matches(p, name));
3677 }
3678 else if (isString(pattern)) {
3679 return pattern.split(',').indexOf(name) > -1;
3680 }
3681 else if (pattern.test) {
3682 return pattern.test(name);
3683 }
3684 /* istanbul ignore next */
3685 return false;
3686 }
3687 function onActivated(hook, target) {
3688 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
3689 }
3690 function onDeactivated(hook, target) {
3691 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
3692 }
3693 function registerKeepAliveHook(hook, type, target = currentInstance) {
3694 // cache the deactivate branch check wrapper for injected hooks so the same
3695 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
3696 // deactivation check".
3697 const wrappedHook = hook.__wdc ||
3698 (hook.__wdc = () => {
3699 // only fire the hook if the target instance is NOT in a deactivated branch.
3700 let current = target;
3701 while (current) {
3702 if (current.isDeactivated) {
3703 return;
3704 }
3705 current = current.parent;
3706 }
3707 hook();
3708 });
3709 injectHook(type, wrappedHook, target);
3710 // In addition to registering it on the target instance, we walk up the parent
3711 // chain and register it on all ancestor instances that are keep-alive roots.
3712 // This avoids the need to walk the entire component tree when invoking these
3713 // hooks, and more importantly, avoids the need to track child components in
3714 // arrays.
3715 if (target) {
3716 let current = target.parent;
3717 while (current && current.parent) {
3718 if (isKeepAlive(current.parent.vnode)) {
3719 injectToKeepAliveRoot(wrappedHook, type, target, current);
3720 }
3721 current = current.parent;
3722 }
3723 }
3724 }
3725 function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
3726 // injectHook wraps the original for error handling, so make sure to remove
3727 // the wrapped version.
3728 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
3729 onUnmounted(() => {
3730 remove(keepAliveRoot[type], injected);
3731 }, target);
3732 }
3733 function resetShapeFlag(vnode) {
3734 let shapeFlag = vnode.shapeFlag;
3735 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
3736 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3737 }
3738 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
3739 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
3740 }
3741 vnode.shapeFlag = shapeFlag;
3742 }
3743 function getInnerChild(vnode) {
3744 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
3745 }
3746
3747 function injectHook(type, hook, target = currentInstance, prepend = false) {
3748 if (target) {
3749 const hooks = target[type] || (target[type] = []);
3750 // cache the error handling wrapper for injected hooks so the same hook
3751 // can be properly deduped by the scheduler. "__weh" stands for "with error
3752 // handling".
3753 const wrappedHook = hook.__weh ||
3754 (hook.__weh = (...args) => {
3755 if (target.isUnmounted) {
3756 return;
3757 }
3758 // disable tracking inside all lifecycle hooks
3759 // since they can potentially be called inside effects.
3760 pauseTracking();
3761 // Set currentInstance during hook invocation.
3762 // This assumes the hook does not synchronously trigger other hooks, which
3763 // can only be false when the user does something really funky.
3764 setCurrentInstance(target);
3765 const res = callWithAsyncErrorHandling(hook, target, type, args);
3766 unsetCurrentInstance();
3767 resetTracking();
3768 return res;
3769 });
3770 if (prepend) {
3771 hooks.unshift(wrappedHook);
3772 }
3773 else {
3774 hooks.push(wrappedHook);
3775 }
3776 return wrappedHook;
3777 }
3778 else {
3779 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
3780 warn$1(`${apiName} is called when there is no active component instance to be ` +
3781 `associated with. ` +
3782 `Lifecycle injection APIs can only be used during execution of setup().` +
3783 (` If you are using async setup(), make sure to register lifecycle ` +
3784 `hooks before the first await statement.`
3785 ));
3786 }
3787 }
3788 const createHook = (lifecycle) => (hook, target = currentInstance) =>
3789 // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
3790 (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
3791 injectHook(lifecycle, hook, target);
3792 const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
3793 const onMounted = createHook("m" /* MOUNTED */);
3794 const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
3795 const onUpdated = createHook("u" /* UPDATED */);
3796 const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
3797 const onUnmounted = createHook("um" /* UNMOUNTED */);
3798 const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
3799 const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
3800 const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
3801 function onErrorCaptured(hook, target = currentInstance) {
3802 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
3803 }
3804
3805 function createDuplicateChecker() {
3806 const cache = Object.create(null);
3807 return (type, key) => {
3808 if (cache[key]) {
3809 warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
3810 }
3811 else {
3812 cache[key] = type;
3813 }
3814 };
3815 }
3816 let shouldCacheAccess = true;
3817 function applyOptions(instance) {
3818 const options = resolveMergedOptions(instance);
3819 const publicThis = instance.proxy;
3820 const ctx = instance.ctx;
3821 // do not cache property access on public proxy during state initialization
3822 shouldCacheAccess = false;
3823 // call beforeCreate first before accessing other options since
3824 // the hook may mutate resolved options (#2791)
3825 if (options.beforeCreate) {
3826 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
3827 }
3828 const {
3829 // state
3830 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
3831 // lifecycle
3832 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
3833 // public API
3834 expose, inheritAttrs,
3835 // assets
3836 components, directives, filters } = options;
3837 const checkDuplicateProperties = createDuplicateChecker() ;
3838 {
3839 const [propsOptions] = instance.propsOptions;
3840 if (propsOptions) {
3841 for (const key in propsOptions) {
3842 checkDuplicateProperties("Props" /* PROPS */, key);
3843 }
3844 }
3845 }
3846 // options initialization order (to be consistent with Vue 2):
3847 // - props (already done outside of this function)
3848 // - inject
3849 // - methods
3850 // - data (deferred since it relies on `this` access)
3851 // - computed
3852 // - watch (deferred since it relies on `this` access)
3853 if (injectOptions) {
3854 resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
3855 }
3856 if (methods) {
3857 for (const key in methods) {
3858 const methodHandler = methods[key];
3859 if (isFunction(methodHandler)) {
3860 // In dev mode, we use the `createRenderContext` function to define
3861 // methods to the proxy target, and those are read-only but
3862 // reconfigurable, so it needs to be redefined here
3863 {
3864 Object.defineProperty(ctx, key, {
3865 value: methodHandler.bind(publicThis),
3866 configurable: true,
3867 enumerable: true,
3868 writable: true
3869 });
3870 }
3871 {
3872 checkDuplicateProperties("Methods" /* METHODS */, key);
3873 }
3874 }
3875 else {
3876 warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
3877 `Did you reference the function correctly?`);
3878 }
3879 }
3880 }
3881 if (dataOptions) {
3882 if (!isFunction(dataOptions)) {
3883 warn$1(`The data option must be a function. ` +
3884 `Plain object usage is no longer supported.`);
3885 }
3886 const data = dataOptions.call(publicThis, publicThis);
3887 if (isPromise(data)) {
3888 warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
3889 `intend to perform data fetching before component renders, use ` +
3890 `async setup() + <Suspense>.`);
3891 }
3892 if (!isObject(data)) {
3893 warn$1(`data() should return an object.`);
3894 }
3895 else {
3896 instance.data = reactive(data);
3897 {
3898 for (const key in data) {
3899 checkDuplicateProperties("Data" /* DATA */, key);
3900 // expose data on ctx during dev
3901 if (key[0] !== '$' && key[0] !== '_') {
3902 Object.defineProperty(ctx, key, {
3903 configurable: true,
3904 enumerable: true,
3905 get: () => data[key],
3906 set: NOOP
3907 });
3908 }
3909 }
3910 }
3911 }
3912 }
3913 // state initialization complete at this point - start caching access
3914 shouldCacheAccess = true;
3915 if (computedOptions) {
3916 for (const key in computedOptions) {
3917 const opt = computedOptions[key];
3918 const get = isFunction(opt)
3919 ? opt.bind(publicThis, publicThis)
3920 : isFunction(opt.get)
3921 ? opt.get.bind(publicThis, publicThis)
3922 : NOOP;
3923 if (get === NOOP) {
3924 warn$1(`Computed property "${key}" has no getter.`);
3925 }
3926 const set = !isFunction(opt) && isFunction(opt.set)
3927 ? opt.set.bind(publicThis)
3928 : () => {
3929 warn$1(`Write operation failed: computed property "${key}" is readonly.`);
3930 }
3931 ;
3932 const c = computed({
3933 get,
3934 set
3935 });
3936 Object.defineProperty(ctx, key, {
3937 enumerable: true,
3938 configurable: true,
3939 get: () => c.value,
3940 set: v => (c.value = v)
3941 });
3942 {
3943 checkDuplicateProperties("Computed" /* COMPUTED */, key);
3944 }
3945 }
3946 }
3947 if (watchOptions) {
3948 for (const key in watchOptions) {
3949 createWatcher(watchOptions[key], ctx, publicThis, key);
3950 }
3951 }
3952 if (provideOptions) {
3953 const provides = isFunction(provideOptions)
3954 ? provideOptions.call(publicThis)
3955 : provideOptions;
3956 Reflect.ownKeys(provides).forEach(key => {
3957 provide(key, provides[key]);
3958 });
3959 }
3960 if (created) {
3961 callHook(created, instance, "c" /* CREATED */);
3962 }
3963 function registerLifecycleHook(register, hook) {
3964 if (isArray(hook)) {
3965 hook.forEach(_hook => register(_hook.bind(publicThis)));
3966 }
3967 else if (hook) {
3968 register(hook.bind(publicThis));
3969 }
3970 }
3971 registerLifecycleHook(onBeforeMount, beforeMount);
3972 registerLifecycleHook(onMounted, mounted);
3973 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
3974 registerLifecycleHook(onUpdated, updated);
3975 registerLifecycleHook(onActivated, activated);
3976 registerLifecycleHook(onDeactivated, deactivated);
3977 registerLifecycleHook(onErrorCaptured, errorCaptured);
3978 registerLifecycleHook(onRenderTracked, renderTracked);
3979 registerLifecycleHook(onRenderTriggered, renderTriggered);
3980 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
3981 registerLifecycleHook(onUnmounted, unmounted);
3982 registerLifecycleHook(onServerPrefetch, serverPrefetch);
3983 if (isArray(expose)) {
3984 if (expose.length) {
3985 const exposed = instance.exposed || (instance.exposed = {});
3986 expose.forEach(key => {
3987 Object.defineProperty(exposed, key, {
3988 get: () => publicThis[key],
3989 set: val => (publicThis[key] = val)
3990 });
3991 });
3992 }
3993 else if (!instance.exposed) {
3994 instance.exposed = {};
3995 }
3996 }
3997 // options that are handled when creating the instance but also need to be
3998 // applied from mixins
3999 if (render && instance.render === NOOP) {
4000 instance.render = render;
4001 }
4002 if (inheritAttrs != null) {
4003 instance.inheritAttrs = inheritAttrs;
4004 }
4005 // asset options.
4006 if (components)
4007 instance.components = components;
4008 if (directives)
4009 instance.directives = directives;
4010 }
4011 function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
4012 if (isArray(injectOptions)) {
4013 injectOptions = normalizeInject(injectOptions);
4014 }
4015 for (const key in injectOptions) {
4016 const opt = injectOptions[key];
4017 let injected;
4018 if (isObject(opt)) {
4019 if ('default' in opt) {
4020 injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4021 }
4022 else {
4023 injected = inject(opt.from || key);
4024 }
4025 }
4026 else {
4027 injected = inject(opt);
4028 }
4029 if (isRef(injected)) {
4030 // TODO remove the check in 3.3
4031 if (unwrapRef) {
4032 Object.defineProperty(ctx, key, {
4033 enumerable: true,
4034 configurable: true,
4035 get: () => injected.value,
4036 set: v => (injected.value = v)
4037 });
4038 }
4039 else {
4040 {
4041 warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
4042 `and no longer needs \`.value\` in the next minor release. ` +
4043 `To opt-in to the new behavior now, ` +
4044 `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
4045 `temporary and will not be needed in the future.)`);
4046 }
4047 ctx[key] = injected;
4048 }
4049 }
4050 else {
4051 ctx[key] = injected;
4052 }
4053 {
4054 checkDuplicateProperties("Inject" /* INJECT */, key);
4055 }
4056 }
4057 }
4058 function callHook(hook, instance, type) {
4059 callWithAsyncErrorHandling(isArray(hook)
4060 ? hook.map(h => h.bind(instance.proxy))
4061 : hook.bind(instance.proxy), instance, type);
4062 }
4063 function createWatcher(raw, ctx, publicThis, key) {
4064 const getter = key.includes('.')
4065 ? createPathGetter(publicThis, key)
4066 : () => publicThis[key];
4067 if (isString(raw)) {
4068 const handler = ctx[raw];
4069 if (isFunction(handler)) {
4070 watch(getter, handler);
4071 }
4072 else {
4073 warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
4074 }
4075 }
4076 else if (isFunction(raw)) {
4077 watch(getter, raw.bind(publicThis));
4078 }
4079 else if (isObject(raw)) {
4080 if (isArray(raw)) {
4081 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4082 }
4083 else {
4084 const handler = isFunction(raw.handler)
4085 ? raw.handler.bind(publicThis)
4086 : ctx[raw.handler];
4087 if (isFunction(handler)) {
4088 watch(getter, handler, raw);
4089 }
4090 else {
4091 warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4092 }
4093 }
4094 }
4095 else {
4096 warn$1(`Invalid watch option: "${key}"`, raw);
4097 }
4098 }
4099 /**
4100 * Resolve merged options and cache it on the component.
4101 * This is done only once per-component since the merging does not involve
4102 * instances.
4103 */
4104 function resolveMergedOptions(instance) {
4105 const base = instance.type;
4106 const { mixins, extends: extendsOptions } = base;
4107 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4108 const cached = cache.get(base);
4109 let resolved;
4110 if (cached) {
4111 resolved = cached;
4112 }
4113 else if (!globalMixins.length && !mixins && !extendsOptions) {
4114 {
4115 resolved = base;
4116 }
4117 }
4118 else {
4119 resolved = {};
4120 if (globalMixins.length) {
4121 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4122 }
4123 mergeOptions(resolved, base, optionMergeStrategies);
4124 }
4125 cache.set(base, resolved);
4126 return resolved;
4127 }
4128 function mergeOptions(to, from, strats, asMixin = false) {
4129 const { mixins, extends: extendsOptions } = from;
4130 if (extendsOptions) {
4131 mergeOptions(to, extendsOptions, strats, true);
4132 }
4133 if (mixins) {
4134 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4135 }
4136 for (const key in from) {
4137 if (asMixin && key === 'expose') {
4138 warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
4139 `It should only be declared in the base component itself.`);
4140 }
4141 else {
4142 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4143 to[key] = strat ? strat(to[key], from[key]) : from[key];
4144 }
4145 }
4146 return to;
4147 }
4148 const internalOptionMergeStrats = {
4149 data: mergeDataFn,
4150 props: mergeObjectOptions,
4151 emits: mergeObjectOptions,
4152 // objects
4153 methods: mergeObjectOptions,
4154 computed: mergeObjectOptions,
4155 // lifecycle
4156 beforeCreate: mergeAsArray,
4157 created: mergeAsArray,
4158 beforeMount: mergeAsArray,
4159 mounted: mergeAsArray,
4160 beforeUpdate: mergeAsArray,
4161 updated: mergeAsArray,
4162 beforeDestroy: mergeAsArray,
4163 beforeUnmount: mergeAsArray,
4164 destroyed: mergeAsArray,
4165 unmounted: mergeAsArray,
4166 activated: mergeAsArray,
4167 deactivated: mergeAsArray,
4168 errorCaptured: mergeAsArray,
4169 serverPrefetch: mergeAsArray,
4170 // assets
4171 components: mergeObjectOptions,
4172 directives: mergeObjectOptions,
4173 // watch
4174 watch: mergeWatchOptions,
4175 // provide / inject
4176 provide: mergeDataFn,
4177 inject: mergeInject
4178 };
4179 function mergeDataFn(to, from) {
4180 if (!from) {
4181 return to;
4182 }
4183 if (!to) {
4184 return from;
4185 }
4186 return function mergedDataFn() {
4187 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4188 };
4189 }
4190 function mergeInject(to, from) {
4191 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4192 }
4193 function normalizeInject(raw) {
4194 if (isArray(raw)) {
4195 const res = {};
4196 for (let i = 0; i < raw.length; i++) {
4197 res[raw[i]] = raw[i];
4198 }
4199 return res;
4200 }
4201 return raw;
4202 }
4203 function mergeAsArray(to, from) {
4204 return to ? [...new Set([].concat(to, from))] : from;
4205 }
4206 function mergeObjectOptions(to, from) {
4207 return to ? extend(extend(Object.create(null), to), from) : from;
4208 }
4209 function mergeWatchOptions(to, from) {
4210 if (!to)
4211 return from;
4212 if (!from)
4213 return to;
4214 const merged = extend(Object.create(null), to);
4215 for (const key in from) {
4216 merged[key] = mergeAsArray(to[key], from[key]);
4217 }
4218 return merged;
4219 }
4220
4221 function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4222 isSSR = false) {
4223 const props = {};
4224 const attrs = {};
4225 def(attrs, InternalObjectKey, 1);
4226 instance.propsDefaults = Object.create(null);
4227 setFullProps(instance, rawProps, props, attrs);
4228 // ensure all declared prop keys are present
4229 for (const key in instance.propsOptions[0]) {
4230 if (!(key in props)) {
4231 props[key] = undefined;
4232 }
4233 }
4234 // validation
4235 {
4236 validateProps(rawProps || {}, props, instance);
4237 }
4238 if (isStateful) {
4239 // stateful
4240 instance.props = isSSR ? props : shallowReactive(props);
4241 }
4242 else {
4243 if (!instance.type.props) {
4244 // functional w/ optional props, props === attrs
4245 instance.props = attrs;
4246 }
4247 else {
4248 // functional w/ declared props
4249 instance.props = props;
4250 }
4251 }
4252 instance.attrs = attrs;
4253 }
4254 function updateProps(instance, rawProps, rawPrevProps, optimized) {
4255 const { props, attrs, vnode: { patchFlag } } = instance;
4256 const rawCurrentProps = toRaw(props);
4257 const [options] = instance.propsOptions;
4258 let hasAttrsChanged = false;
4259 if (
4260 // always force full diff in dev
4261 // - #1942 if hmr is enabled with sfc component
4262 // - vite#872 non-sfc component used by sfc component
4263 !((instance.type.__hmrId ||
4264 (instance.parent && instance.parent.type.__hmrId))) &&
4265 (optimized || patchFlag > 0) &&
4266 !(patchFlag & 16 /* FULL_PROPS */)) {
4267 if (patchFlag & 8 /* PROPS */) {
4268 // Compiler-generated props & no keys change, just set the updated
4269 // the props.
4270 const propsToUpdate = instance.vnode.dynamicProps;
4271 for (let i = 0; i < propsToUpdate.length; i++) {
4272 let key = propsToUpdate[i];
4273 // PROPS flag guarantees rawProps to be non-null
4274 const value = rawProps[key];
4275 if (options) {
4276 // attr / props separation was done on init and will be consistent
4277 // in this code path, so just check if attrs have it.
4278 if (hasOwn(attrs, key)) {
4279 if (value !== attrs[key]) {
4280 attrs[key] = value;
4281 hasAttrsChanged = true;
4282 }
4283 }
4284 else {
4285 const camelizedKey = camelize(key);
4286 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4287 }
4288 }
4289 else {
4290 if (value !== attrs[key]) {
4291 attrs[key] = value;
4292 hasAttrsChanged = true;
4293 }
4294 }
4295 }
4296 }
4297 }
4298 else {
4299 // full props update.
4300 if (setFullProps(instance, rawProps, props, attrs)) {
4301 hasAttrsChanged = true;
4302 }
4303 // in case of dynamic props, check if we need to delete keys from
4304 // the props object
4305 let kebabKey;
4306 for (const key in rawCurrentProps) {
4307 if (!rawProps ||
4308 // for camelCase
4309 (!hasOwn(rawProps, key) &&
4310 // it's possible the original props was passed in as kebab-case
4311 // and converted to camelCase (#955)
4312 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4313 if (options) {
4314 if (rawPrevProps &&
4315 // for camelCase
4316 (rawPrevProps[key] !== undefined ||
4317 // for kebab-case
4318 rawPrevProps[kebabKey] !== undefined)) {
4319 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4320 }
4321 }
4322 else {
4323 delete props[key];
4324 }
4325 }
4326 }
4327 // in the case of functional component w/o props declaration, props and
4328 // attrs point to the same object so it should already have been updated.
4329 if (attrs !== rawCurrentProps) {
4330 for (const key in attrs) {
4331 if (!rawProps || !hasOwn(rawProps, key)) {
4332 delete attrs[key];
4333 hasAttrsChanged = true;
4334 }
4335 }
4336 }
4337 }
4338 // trigger updates for $attrs in case it's used in component slots
4339 if (hasAttrsChanged) {
4340 trigger(instance, "set" /* SET */, '$attrs');
4341 }
4342 {
4343 validateProps(rawProps || {}, props, instance);
4344 }
4345 }
4346 function setFullProps(instance, rawProps, props, attrs) {
4347 const [options, needCastKeys] = instance.propsOptions;
4348 let hasAttrsChanged = false;
4349 let rawCastValues;
4350 if (rawProps) {
4351 for (let key in rawProps) {
4352 // key, ref are reserved and never passed down
4353 if (isReservedProp(key)) {
4354 continue;
4355 }
4356 const value = rawProps[key];
4357 // prop option names are camelized during normalization, so to support
4358 // kebab -> camel conversion here we need to camelize the key.
4359 let camelKey;
4360 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4361 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4362 props[camelKey] = value;
4363 }
4364 else {
4365 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4366 }
4367 }
4368 else if (!isEmitListener(instance.emitsOptions, key)) {
4369 if (value !== attrs[key]) {
4370 attrs[key] = value;
4371 hasAttrsChanged = true;
4372 }
4373 }
4374 }
4375 }
4376 if (needCastKeys) {
4377 const rawCurrentProps = toRaw(props);
4378 const castValues = rawCastValues || EMPTY_OBJ;
4379 for (let i = 0; i < needCastKeys.length; i++) {
4380 const key = needCastKeys[i];
4381 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4382 }
4383 }
4384 return hasAttrsChanged;
4385 }
4386 function resolvePropValue(options, props, key, value, instance, isAbsent) {
4387 const opt = options[key];
4388 if (opt != null) {
4389 const hasDefault = hasOwn(opt, 'default');
4390 // default values
4391 if (hasDefault && value === undefined) {
4392 const defaultValue = opt.default;
4393 if (opt.type !== Function && isFunction(defaultValue)) {
4394 const { propsDefaults } = instance;
4395 if (key in propsDefaults) {
4396 value = propsDefaults[key];
4397 }
4398 else {
4399 setCurrentInstance(instance);
4400 value = propsDefaults[key] = defaultValue.call(null, props);
4401 unsetCurrentInstance();
4402 }
4403 }
4404 else {
4405 value = defaultValue;
4406 }
4407 }
4408 // boolean casting
4409 if (opt[0 /* shouldCast */]) {
4410 if (isAbsent && !hasDefault) {
4411 value = false;
4412 }
4413 else if (opt[1 /* shouldCastTrue */] &&
4414 (value === '' || value === hyphenate(key))) {
4415 value = true;
4416 }
4417 }
4418 }
4419 return value;
4420 }
4421 function normalizePropsOptions(comp, appContext, asMixin = false) {
4422 const cache = appContext.propsCache;
4423 const cached = cache.get(comp);
4424 if (cached) {
4425 return cached;
4426 }
4427 const raw = comp.props;
4428 const normalized = {};
4429 const needCastKeys = [];
4430 // apply mixin/extends props
4431 let hasExtends = false;
4432 if (!isFunction(comp)) {
4433 const extendProps = (raw) => {
4434 hasExtends = true;
4435 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4436 extend(normalized, props);
4437 if (keys)
4438 needCastKeys.push(...keys);
4439 };
4440 if (!asMixin && appContext.mixins.length) {
4441 appContext.mixins.forEach(extendProps);
4442 }
4443 if (comp.extends) {
4444 extendProps(comp.extends);
4445 }
4446 if (comp.mixins) {
4447 comp.mixins.forEach(extendProps);
4448 }
4449 }
4450 if (!raw && !hasExtends) {
4451 cache.set(comp, EMPTY_ARR);
4452 return EMPTY_ARR;
4453 }
4454 if (isArray(raw)) {
4455 for (let i = 0; i < raw.length; i++) {
4456 if (!isString(raw[i])) {
4457 warn$1(`props must be strings when using array syntax.`, raw[i]);
4458 }
4459 const normalizedKey = camelize(raw[i]);
4460 if (validatePropName(normalizedKey)) {
4461 normalized[normalizedKey] = EMPTY_OBJ;
4462 }
4463 }
4464 }
4465 else if (raw) {
4466 if (!isObject(raw)) {
4467 warn$1(`invalid props options`, raw);
4468 }
4469 for (const key in raw) {
4470 const normalizedKey = camelize(key);
4471 if (validatePropName(normalizedKey)) {
4472 const opt = raw[key];
4473 const prop = (normalized[normalizedKey] =
4474 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4475 if (prop) {
4476 const booleanIndex = getTypeIndex(Boolean, prop.type);
4477 const stringIndex = getTypeIndex(String, prop.type);
4478 prop[0 /* shouldCast */] = booleanIndex > -1;
4479 prop[1 /* shouldCastTrue */] =
4480 stringIndex < 0 || booleanIndex < stringIndex;
4481 // if the prop needs boolean casting or default value
4482 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4483 needCastKeys.push(normalizedKey);
4484 }
4485 }
4486 }
4487 }
4488 }
4489 const res = [normalized, needCastKeys];
4490 cache.set(comp, res);
4491 return res;
4492 }
4493 function validatePropName(key) {
4494 if (key[0] !== '$') {
4495 return true;
4496 }
4497 else {
4498 warn$1(`Invalid prop name: "${key}" is a reserved property.`);
4499 }
4500 return false;
4501 }
4502 // use function string name to check type constructors
4503 // so that it works across vms / iframes.
4504 function getType(ctor) {
4505 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4506 return match ? match[1] : ctor === null ? 'null' : '';
4507 }
4508 function isSameType(a, b) {
4509 return getType(a) === getType(b);
4510 }
4511 function getTypeIndex(type, expectedTypes) {
4512 if (isArray(expectedTypes)) {
4513 return expectedTypes.findIndex(t => isSameType(t, type));
4514 }
4515 else if (isFunction(expectedTypes)) {
4516 return isSameType(expectedTypes, type) ? 0 : -1;
4517 }
4518 return -1;
4519 }
4520 /**
4521 * dev only
4522 */
4523 function validateProps(rawProps, props, instance) {
4524 const resolvedValues = toRaw(props);
4525 const options = instance.propsOptions[0];
4526 for (const key in options) {
4527 let opt = options[key];
4528 if (opt == null)
4529 continue;
4530 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4531 }
4532 }
4533 /**
4534 * dev only
4535 */
4536 function validateProp(name, value, prop, isAbsent) {
4537 const { type, required, validator } = prop;
4538 // required!
4539 if (required && isAbsent) {
4540 warn$1('Missing required prop: "' + name + '"');
4541 return;
4542 }
4543 // missing but optional
4544 if (value == null && !prop.required) {
4545 return;
4546 }
4547 // type check
4548 if (type != null && type !== true) {
4549 let isValid = false;
4550 const types = isArray(type) ? type : [type];
4551 const expectedTypes = [];
4552 // value is valid as long as one of the specified types match
4553 for (let i = 0; i < types.length && !isValid; i++) {
4554 const { valid, expectedType } = assertType(value, types[i]);
4555 expectedTypes.push(expectedType || '');
4556 isValid = valid;
4557 }
4558 if (!isValid) {
4559 warn$1(getInvalidTypeMessage(name, value, expectedTypes));
4560 return;
4561 }
4562 }
4563 // custom validator
4564 if (validator && !validator(value)) {
4565 warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
4566 }
4567 }
4568 const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4569 /**
4570 * dev only
4571 */
4572 function assertType(value, type) {
4573 let valid;
4574 const expectedType = getType(type);
4575 if (isSimpleType(expectedType)) {
4576 const t = typeof value;
4577 valid = t === expectedType.toLowerCase();
4578 // for primitive wrapper objects
4579 if (!valid && t === 'object') {
4580 valid = value instanceof type;
4581 }
4582 }
4583 else if (expectedType === 'Object') {
4584 valid = isObject(value);
4585 }
4586 else if (expectedType === 'Array') {
4587 valid = isArray(value);
4588 }
4589 else if (expectedType === 'null') {
4590 valid = value === null;
4591 }
4592 else {
4593 valid = value instanceof type;
4594 }
4595 return {
4596 valid,
4597 expectedType
4598 };
4599 }
4600 /**
4601 * dev only
4602 */
4603 function getInvalidTypeMessage(name, value, expectedTypes) {
4604 let message = `Invalid prop: type check failed for prop "${name}".` +
4605 ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
4606 const expectedType = expectedTypes[0];
4607 const receivedType = toRawType(value);
4608 const expectedValue = styleValue(value, expectedType);
4609 const receivedValue = styleValue(value, receivedType);
4610 // check if we need to specify expected value
4611 if (expectedTypes.length === 1 &&
4612 isExplicable(expectedType) &&
4613 !isBoolean(expectedType, receivedType)) {
4614 message += ` with value ${expectedValue}`;
4615 }
4616 message += `, got ${receivedType} `;
4617 // check if we need to specify received value
4618 if (isExplicable(receivedType)) {
4619 message += `with value ${receivedValue}.`;
4620 }
4621 return message;
4622 }
4623 /**
4624 * dev only
4625 */
4626 function styleValue(value, type) {
4627 if (type === 'String') {
4628 return `"${value}"`;
4629 }
4630 else if (type === 'Number') {
4631 return `${Number(value)}`;
4632 }
4633 else {
4634 return `${value}`;
4635 }
4636 }
4637 /**
4638 * dev only
4639 */
4640 function isExplicable(type) {
4641 const explicitTypes = ['string', 'number', 'boolean'];
4642 return explicitTypes.some(elem => type.toLowerCase() === elem);
4643 }
4644 /**
4645 * dev only
4646 */
4647 function isBoolean(...args) {
4648 return args.some(elem => elem.toLowerCase() === 'boolean');
4649 }
4650
4651 const isInternalKey = (key) => key[0] === '_' || key === '$stable';
4652 const normalizeSlotValue = (value) => isArray(value)
4653 ? value.map(normalizeVNode)
4654 : [normalizeVNode(value)];
4655 const normalizeSlot = (key, rawSlot, ctx) => {
4656 const normalized = withCtx((...args) => {
4657 if (currentInstance) {
4658 warn$1(`Slot "${key}" invoked outside of the render function: ` +
4659 `this will not track dependencies used in the slot. ` +
4660 `Invoke the slot function inside the render function instead.`);
4661 }
4662 return normalizeSlotValue(rawSlot(...args));
4663 }, ctx);
4664 normalized._c = false;
4665 return normalized;
4666 };
4667 const normalizeObjectSlots = (rawSlots, slots, instance) => {
4668 const ctx = rawSlots._ctx;
4669 for (const key in rawSlots) {
4670 if (isInternalKey(key))
4671 continue;
4672 const value = rawSlots[key];
4673 if (isFunction(value)) {
4674 slots[key] = normalizeSlot(key, value, ctx);
4675 }
4676 else if (value != null) {
4677 {
4678 warn$1(`Non-function value encountered for slot "${key}". ` +
4679 `Prefer function slots for better performance.`);
4680 }
4681 const normalized = normalizeSlotValue(value);
4682 slots[key] = () => normalized;
4683 }
4684 }
4685 };
4686 const normalizeVNodeSlots = (instance, children) => {
4687 if (!isKeepAlive(instance.vnode) &&
4688 !(false )) {
4689 warn$1(`Non-function value encountered for default slot. ` +
4690 `Prefer function slots for better performance.`);
4691 }
4692 const normalized = normalizeSlotValue(children);
4693 instance.slots.default = () => normalized;
4694 };
4695 const initSlots = (instance, children) => {
4696 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4697 const type = children._;
4698 if (type) {
4699 // users can get the shallow readonly version of the slots object through `this.$slots`,
4700 // we should avoid the proxy object polluting the slots of the internal instance
4701 instance.slots = toRaw(children);
4702 // make compiler marker non-enumerable
4703 def(children, '_', type);
4704 }
4705 else {
4706 normalizeObjectSlots(children, (instance.slots = {}));
4707 }
4708 }
4709 else {
4710 instance.slots = {};
4711 if (children) {
4712 normalizeVNodeSlots(instance, children);
4713 }
4714 }
4715 def(instance.slots, InternalObjectKey, 1);
4716 };
4717 const updateSlots = (instance, children, optimized) => {
4718 const { vnode, slots } = instance;
4719 let needDeletionCheck = true;
4720 let deletionComparisonTarget = EMPTY_OBJ;
4721 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4722 const type = children._;
4723 if (type) {
4724 // compiled slots.
4725 if (isHmrUpdating) {
4726 // Parent was HMR updated so slot content may have changed.
4727 // force update slots and mark instance for hmr as well
4728 extend(slots, children);
4729 }
4730 else if (optimized && type === 1 /* STABLE */) {
4731 // compiled AND stable.
4732 // no need to update, and skip stale slots removal.
4733 needDeletionCheck = false;
4734 }
4735 else {
4736 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
4737 // normalization.
4738 extend(slots, children);
4739 // #2893
4740 // when rendering the optimized slots by manually written render function,
4741 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
4742 // i.e. let the `renderSlot` create the bailed Fragment
4743 if (!optimized && type === 1 /* STABLE */) {
4744 delete slots._;
4745 }
4746 }
4747 }
4748 else {
4749 needDeletionCheck = !children.$stable;
4750 normalizeObjectSlots(children, slots);
4751 }
4752 deletionComparisonTarget = children;
4753 }
4754 else if (children) {
4755 // non slot object children (direct value) passed to a component
4756 normalizeVNodeSlots(instance, children);
4757 deletionComparisonTarget = { default: 1 };
4758 }
4759 // delete stale slots
4760 if (needDeletionCheck) {
4761 for (const key in slots) {
4762 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
4763 delete slots[key];
4764 }
4765 }
4766 }
4767 };
4768
4769 /**
4770 Runtime helper for applying directives to a vnode. Example usage:
4771
4772 const comp = resolveComponent('comp')
4773 const foo = resolveDirective('foo')
4774 const bar = resolveDirective('bar')
4775
4776 return withDirectives(h(comp), [
4777 [foo, this.x],
4778 [bar, this.y]
4779 ])
4780 */
4781 const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
4782 function validateDirectiveName(name) {
4783 if (isBuiltInDirective(name)) {
4784 warn$1('Do not use built-in directive ids as custom directive id: ' + name);
4785 }
4786 }
4787 /**
4788 * Adds directives to a VNode.
4789 */
4790 function withDirectives(vnode, directives) {
4791 const internalInstance = currentRenderingInstance;
4792 if (internalInstance === null) {
4793 warn$1(`withDirectives can only be used inside render functions.`);
4794 return vnode;
4795 }
4796 const instance = internalInstance.proxy;
4797 const bindings = vnode.dirs || (vnode.dirs = []);
4798 for (let i = 0; i < directives.length; i++) {
4799 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4800 if (isFunction(dir)) {
4801 dir = {
4802 mounted: dir,
4803 updated: dir
4804 };
4805 }
4806 if (dir.deep) {
4807 traverse(value);
4808 }
4809 bindings.push({
4810 dir,
4811 instance,
4812 value,
4813 oldValue: void 0,
4814 arg,
4815 modifiers
4816 });
4817 }
4818 return vnode;
4819 }
4820 function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4821 const bindings = vnode.dirs;
4822 const oldBindings = prevVNode && prevVNode.dirs;
4823 for (let i = 0; i < bindings.length; i++) {
4824 const binding = bindings[i];
4825 if (oldBindings) {
4826 binding.oldValue = oldBindings[i].value;
4827 }
4828 let hook = binding.dir[name];
4829 if (hook) {
4830 // disable tracking inside all lifecycle hooks
4831 // since they can potentially be called inside effects.
4832 pauseTracking();
4833 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4834 vnode.el,
4835 binding,
4836 vnode,
4837 prevVNode
4838 ]);
4839 resetTracking();
4840 }
4841 }
4842 }
4843
4844 function createAppContext() {
4845 return {
4846 app: null,
4847 config: {
4848 isNativeTag: NO,
4849 performance: false,
4850 globalProperties: {},
4851 optionMergeStrategies: {},
4852 errorHandler: undefined,
4853 warnHandler: undefined,
4854 compilerOptions: {}
4855 },
4856 mixins: [],
4857 components: {},
4858 directives: {},
4859 provides: Object.create(null),
4860 optionsCache: new WeakMap(),
4861 propsCache: new WeakMap(),
4862 emitsCache: new WeakMap()
4863 };
4864 }
4865 let uid = 0;
4866 function createAppAPI(render, hydrate) {
4867 return function createApp(rootComponent, rootProps = null) {
4868 if (rootProps != null && !isObject(rootProps)) {
4869 warn$1(`root props passed to app.mount() must be an object.`);
4870 rootProps = null;
4871 }
4872 const context = createAppContext();
4873 const installedPlugins = new Set();
4874 let isMounted = false;
4875 const app = (context.app = {
4876 _uid: uid++,
4877 _component: rootComponent,
4878 _props: rootProps,
4879 _container: null,
4880 _context: context,
4881 _instance: null,
4882 version,
4883 get config() {
4884 return context.config;
4885 },
4886 set config(v) {
4887 {
4888 warn$1(`app.config cannot be replaced. Modify individual options instead.`);
4889 }
4890 },
4891 use(plugin, ...options) {
4892 if (installedPlugins.has(plugin)) {
4893 warn$1(`Plugin has already been applied to target app.`);
4894 }
4895 else if (plugin && isFunction(plugin.install)) {
4896 installedPlugins.add(plugin);
4897 plugin.install(app, ...options);
4898 }
4899 else if (isFunction(plugin)) {
4900 installedPlugins.add(plugin);
4901 plugin(app, ...options);
4902 }
4903 else {
4904 warn$1(`A plugin must either be a function or an object with an "install" ` +
4905 `function.`);
4906 }
4907 return app;
4908 },
4909 mixin(mixin) {
4910 {
4911 if (!context.mixins.includes(mixin)) {
4912 context.mixins.push(mixin);
4913 }
4914 else {
4915 warn$1('Mixin has already been applied to target app' +
4916 (mixin.name ? `: ${mixin.name}` : ''));
4917 }
4918 }
4919 return app;
4920 },
4921 component(name, component) {
4922 {
4923 validateComponentName(name, context.config);
4924 }
4925 if (!component) {
4926 return context.components[name];
4927 }
4928 if (context.components[name]) {
4929 warn$1(`Component "${name}" has already been registered in target app.`);
4930 }
4931 context.components[name] = component;
4932 return app;
4933 },
4934 directive(name, directive) {
4935 {
4936 validateDirectiveName(name);
4937 }
4938 if (!directive) {
4939 return context.directives[name];
4940 }
4941 if (context.directives[name]) {
4942 warn$1(`Directive "${name}" has already been registered in target app.`);
4943 }
4944 context.directives[name] = directive;
4945 return app;
4946 },
4947 mount(rootContainer, isHydrate, isSVG) {
4948 if (!isMounted) {
4949 const vnode = createVNode(rootComponent, rootProps);
4950 // store app context on the root VNode.
4951 // this will be set on the root instance on initial mount.
4952 vnode.appContext = context;
4953 // HMR root reload
4954 {
4955 context.reload = () => {
4956 render(cloneVNode(vnode), rootContainer, isSVG);
4957 };
4958 }
4959 if (isHydrate && hydrate) {
4960 hydrate(vnode, rootContainer);
4961 }
4962 else {
4963 render(vnode, rootContainer, isSVG);
4964 }
4965 isMounted = true;
4966 app._container = rootContainer;
4967 rootContainer.__vue_app__ = app;
4968 {
4969 app._instance = vnode.component;
4970 devtoolsInitApp(app, version);
4971 }
4972 return vnode.component.proxy;
4973 }
4974 else {
4975 warn$1(`App has already been mounted.\n` +
4976 `If you want to remount the same app, move your app creation logic ` +
4977 `into a factory function and create fresh app instances for each ` +
4978 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
4979 }
4980 },
4981 unmount() {
4982 if (isMounted) {
4983 render(null, app._container);
4984 {
4985 app._instance = null;
4986 devtoolsUnmountApp(app);
4987 }
4988 delete app._container.__vue_app__;
4989 }
4990 else {
4991 warn$1(`Cannot unmount an app that is not mounted.`);
4992 }
4993 },
4994 provide(key, value) {
4995 if (key in context.provides) {
4996 warn$1(`App already provides property with key "${String(key)}". ` +
4997 `It will be overwritten with the new value.`);
4998 }
4999 // TypeScript doesn't allow symbols as index type
5000 // https://github.com/Microsoft/TypeScript/issues/24587
5001 context.provides[key] = value;
5002 return app;
5003 }
5004 });
5005 return app;
5006 };
5007 }
5008
5009 let hasMismatch = false;
5010 const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5011 const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5012 // Note: hydration is DOM-specific
5013 // But we have to place it in core due to tight coupling with core - splitting
5014 // it out creates a ton of unnecessary complexity.
5015 // Hydration also depends on some renderer internal logic which needs to be
5016 // passed in via arguments.
5017 function createHydrationFunctions(rendererInternals) {
5018 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5019 const hydrate = (vnode, container) => {
5020 if (!container.hasChildNodes()) {
5021 warn$1(`Attempting to hydrate existing markup but container is empty. ` +
5022 `Performing full mount instead.`);
5023 patch(null, vnode, container);
5024 flushPostFlushCbs();
5025 return;
5026 }
5027 hasMismatch = false;
5028 hydrateNode(container.firstChild, vnode, null, null, null);
5029 flushPostFlushCbs();
5030 if (hasMismatch && !false) {
5031 // this error should show up in production
5032 console.error(`Hydration completed but contains mismatches.`);
5033 }
5034 };
5035 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5036 const isFragmentStart = isComment(node) && node.data === '[';
5037 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5038 const { type, ref, shapeFlag } = vnode;
5039 const domType = node.nodeType;
5040 vnode.el = node;
5041 let nextNode = null;
5042 switch (type) {
5043 case Text:
5044 if (domType !== 3 /* TEXT */) {
5045 nextNode = onMismatch();
5046 }
5047 else {
5048 if (node.data !== vnode.children) {
5049 hasMismatch = true;
5050 warn$1(`Hydration text mismatch:` +
5051 `\n- Client: ${JSON.stringify(node.data)}` +
5052 `\n- Server: ${JSON.stringify(vnode.children)}`);
5053 node.data = vnode.children;
5054 }
5055 nextNode = nextSibling(node);
5056 }
5057 break;
5058 case Comment:
5059 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5060 nextNode = onMismatch();
5061 }
5062 else {
5063 nextNode = nextSibling(node);
5064 }
5065 break;
5066 case Static:
5067 if (domType !== 1 /* ELEMENT */) {
5068 nextNode = onMismatch();
5069 }
5070 else {
5071 // determine anchor, adopt content
5072 nextNode = node;
5073 // if the static vnode has its content stripped during build,
5074 // adopt it from the server-rendered HTML.
5075 const needToAdoptContent = !vnode.children.length;
5076 for (let i = 0; i < vnode.staticCount; i++) {
5077 if (needToAdoptContent)
5078 vnode.children += nextNode.outerHTML;
5079 if (i === vnode.staticCount - 1) {
5080 vnode.anchor = nextNode;
5081 }
5082 nextNode = nextSibling(nextNode);
5083 }
5084 return nextNode;
5085 }
5086 break;
5087 case Fragment:
5088 if (!isFragmentStart) {
5089 nextNode = onMismatch();
5090 }
5091 else {
5092 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5093 }
5094 break;
5095 default:
5096 if (shapeFlag & 1 /* ELEMENT */) {
5097 if (domType !== 1 /* ELEMENT */ ||
5098 vnode.type.toLowerCase() !==
5099 node.tagName.toLowerCase()) {
5100 nextNode = onMismatch();
5101 }
5102 else {
5103 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5104 }
5105 }
5106 else if (shapeFlag & 6 /* COMPONENT */) {
5107 // when setting up the render effect, if the initial vnode already
5108 // has .el set, the component will perform hydration instead of mount
5109 // on its sub-tree.
5110 vnode.slotScopeIds = slotScopeIds;
5111 const container = parentNode(node);
5112 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5113 // component may be async, so in the case of fragments we cannot rely
5114 // on component's rendered output to determine the end of the fragment
5115 // instead, we do a lookahead to find the end anchor node.
5116 nextNode = isFragmentStart
5117 ? locateClosingAsyncAnchor(node)
5118 : nextSibling(node);
5119 // #3787
5120 // if component is async, it may get moved / unmounted before its
5121 // inner component is loaded, so we need to give it a placeholder
5122 // vnode that matches its adopted DOM.
5123 if (isAsyncWrapper(vnode)) {
5124 let subTree;
5125 if (isFragmentStart) {
5126 subTree = createVNode(Fragment);
5127 subTree.anchor = nextNode
5128 ? nextNode.previousSibling
5129 : container.lastChild;
5130 }
5131 else {
5132 subTree =
5133 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5134 }
5135 subTree.el = node;
5136 vnode.component.subTree = subTree;
5137 }
5138 }
5139 else if (shapeFlag & 64 /* TELEPORT */) {
5140 if (domType !== 8 /* COMMENT */) {
5141 nextNode = onMismatch();
5142 }
5143 else {
5144 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5145 }
5146 }
5147 else if (shapeFlag & 128 /* SUSPENSE */) {
5148 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5149 }
5150 else {
5151 warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
5152 }
5153 }
5154 if (ref != null) {
5155 setRef(ref, null, parentSuspense, vnode);
5156 }
5157 return nextNode;
5158 };
5159 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5160 optimized = optimized || !!vnode.dynamicChildren;
5161 const { type, props, patchFlag, shapeFlag, dirs } = vnode;
5162 // #4006 for form elements with non-string v-model value bindings
5163 // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
5164 const forcePatchValue = (type === 'input' && dirs) || type === 'option';
5165 // skip props & children if this is hoisted static nodes
5166 if (forcePatchValue || patchFlag !== -1 /* HOISTED */) {
5167 if (dirs) {
5168 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5169 }
5170 // props
5171 if (props) {
5172 if (forcePatchValue ||
5173 !optimized ||
5174 patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
5175 for (const key in props) {
5176 if ((forcePatchValue && key.endsWith('value')) ||
5177 (isOn(key) && !isReservedProp(key))) {
5178 patchProp(el, key, null, props[key]);
5179 }
5180 }
5181 }
5182 else if (props.onClick) {
5183 // Fast path for click listeners (which is most often) to avoid
5184 // iterating through props.
5185 patchProp(el, 'onClick', null, props.onClick);
5186 }
5187 }
5188 // vnode / directive hooks
5189 let vnodeHooks;
5190 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5191 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5192 }
5193 if (dirs) {
5194 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5195 }
5196 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5197 queueEffectWithSuspense(() => {
5198 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5199 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5200 }, parentSuspense);
5201 }
5202 // children
5203 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5204 // skip if element has innerHTML / textContent
5205 !(props && (props.innerHTML || props.textContent))) {
5206 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5207 let hasWarned = false;
5208 while (next) {
5209 hasMismatch = true;
5210 if (!hasWarned) {
5211 warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
5212 `server rendered element contains more child nodes than client vdom.`);
5213 hasWarned = true;
5214 }
5215 // The SSRed DOM contains more nodes than it should. Remove them.
5216 const cur = next;
5217 next = next.nextSibling;
5218 remove(cur);
5219 }
5220 }
5221 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5222 if (el.textContent !== vnode.children) {
5223 hasMismatch = true;
5224 warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
5225 `- Client: ${el.textContent}\n` +
5226 `- Server: ${vnode.children}`);
5227 el.textContent = vnode.children;
5228 }
5229 }
5230 }
5231 return el.nextSibling;
5232 };
5233 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5234 optimized = optimized || !!parentVNode.dynamicChildren;
5235 const children = parentVNode.children;
5236 const l = children.length;
5237 let hasWarned = false;
5238 for (let i = 0; i < l; i++) {
5239 const vnode = optimized
5240 ? children[i]
5241 : (children[i] = normalizeVNode(children[i]));
5242 if (node) {
5243 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5244 }
5245 else if (vnode.type === Text && !vnode.children) {
5246 continue;
5247 }
5248 else {
5249 hasMismatch = true;
5250 if (!hasWarned) {
5251 warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5252 `server rendered element contains fewer child nodes than client vdom.`);
5253 hasWarned = true;
5254 }
5255 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5256 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5257 }
5258 }
5259 return node;
5260 };
5261 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5262 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5263 if (fragmentSlotScopeIds) {
5264 slotScopeIds = slotScopeIds
5265 ? slotScopeIds.concat(fragmentSlotScopeIds)
5266 : fragmentSlotScopeIds;
5267 }
5268 const container = parentNode(node);
5269 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5270 if (next && isComment(next) && next.data === ']') {
5271 return nextSibling((vnode.anchor = next));
5272 }
5273 else {
5274 // fragment didn't hydrate successfully, since we didn't get a end anchor
5275 // back. This should have led to node/children mismatch warnings.
5276 hasMismatch = true;
5277 // since the anchor is missing, we need to create one and insert it
5278 insert((vnode.anchor = createComment(`]`)), container, next);
5279 return next;
5280 }
5281 };
5282 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5283 hasMismatch = true;
5284 warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5285 ? `(text)`
5286 : isComment(node) && node.data === '['
5287 ? `(start of fragment)`
5288 : ``);
5289 vnode.el = null;
5290 if (isFragment) {
5291 // remove excessive fragment nodes
5292 const end = locateClosingAsyncAnchor(node);
5293 while (true) {
5294 const next = nextSibling(node);
5295 if (next && next !== end) {
5296 remove(next);
5297 }
5298 else {
5299 break;
5300 }
5301 }
5302 }
5303 const next = nextSibling(node);
5304 const container = parentNode(node);
5305 remove(node);
5306 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5307 return next;
5308 };
5309 const locateClosingAsyncAnchor = (node) => {
5310 let match = 0;
5311 while (node) {
5312 node = nextSibling(node);
5313 if (node && isComment(node)) {
5314 if (node.data === '[')
5315 match++;
5316 if (node.data === ']') {
5317 if (match === 0) {
5318 return nextSibling(node);
5319 }
5320 else {
5321 match--;
5322 }
5323 }
5324 }
5325 }
5326 return node;
5327 };
5328 return [hydrate, hydrateNode];
5329 }
5330
5331 let supported;
5332 let perf;
5333 function startMeasure(instance, type) {
5334 if (instance.appContext.config.performance && isSupported()) {
5335 perf.mark(`vue-${type}-${instance.uid}`);
5336 }
5337 {
5338 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5339 }
5340 }
5341 function endMeasure(instance, type) {
5342 if (instance.appContext.config.performance && isSupported()) {
5343 const startTag = `vue-${type}-${instance.uid}`;
5344 const endTag = startTag + `:end`;
5345 perf.mark(endTag);
5346 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5347 perf.clearMarks(startTag);
5348 perf.clearMarks(endTag);
5349 }
5350 {
5351 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5352 }
5353 }
5354 function isSupported() {
5355 if (supported !== undefined) {
5356 return supported;
5357 }
5358 /* eslint-disable no-restricted-globals */
5359 if (typeof window !== 'undefined' && window.performance) {
5360 supported = true;
5361 perf = window.performance;
5362 }
5363 else {
5364 supported = false;
5365 }
5366 /* eslint-enable no-restricted-globals */
5367 return supported;
5368 }
5369
5370 const queuePostRenderEffect = queueEffectWithSuspense
5371 ;
5372 /**
5373 * The createRenderer function accepts two generic arguments:
5374 * HostNode and HostElement, corresponding to Node and Element types in the
5375 * host environment. For example, for runtime-dom, HostNode would be the DOM
5376 * `Node` interface and HostElement would be the DOM `Element` interface.
5377 *
5378 * Custom renderers can pass in the platform specific types like this:
5379 *
5380 * ``` js
5381 * const { render, createApp } = createRenderer<Node, Element>({
5382 * patchProp,
5383 * ...nodeOps
5384 * })
5385 * ```
5386 */
5387 function createRenderer(options) {
5388 return baseCreateRenderer(options);
5389 }
5390 // Separate API for creating hydration-enabled renderer.
5391 // Hydration logic is only used when calling this function, making it
5392 // tree-shakable.
5393 function createHydrationRenderer(options) {
5394 return baseCreateRenderer(options, createHydrationFunctions);
5395 }
5396 // implementation
5397 function baseCreateRenderer(options, createHydrationFns) {
5398 {
5399 const target = getGlobalThis();
5400 target.__VUE__ = true;
5401 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
5402 }
5403 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
5404 // Note: functions inside this closure should use `const xxx = () => {}`
5405 // style in order to prevent being inlined by minifiers.
5406 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
5407 if (n1 === n2) {
5408 return;
5409 }
5410 // patching & not same type, unmount old tree
5411 if (n1 && !isSameVNodeType(n1, n2)) {
5412 anchor = getNextHostNode(n1);
5413 unmount(n1, parentComponent, parentSuspense, true);
5414 n1 = null;
5415 }
5416 if (n2.patchFlag === -2 /* BAIL */) {
5417 optimized = false;
5418 n2.dynamicChildren = null;
5419 }
5420 const { type, ref, shapeFlag } = n2;
5421 switch (type) {
5422 case Text:
5423 processText(n1, n2, container, anchor);
5424 break;
5425 case Comment:
5426 processCommentNode(n1, n2, container, anchor);
5427 break;
5428 case Static:
5429 if (n1 == null) {
5430 mountStaticNode(n2, container, anchor, isSVG);
5431 }
5432 else {
5433 patchStaticNode(n1, n2, container, isSVG);
5434 }
5435 break;
5436 case Fragment:
5437 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5438 break;
5439 default:
5440 if (shapeFlag & 1 /* ELEMENT */) {
5441 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5442 }
5443 else if (shapeFlag & 6 /* COMPONENT */) {
5444 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5445 }
5446 else if (shapeFlag & 64 /* TELEPORT */) {
5447 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5448 }
5449 else if (shapeFlag & 128 /* SUSPENSE */) {
5450 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5451 }
5452 else {
5453 warn$1('Invalid VNode type:', type, `(${typeof type})`);
5454 }
5455 }
5456 // set ref
5457 if (ref != null && parentComponent) {
5458 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5459 }
5460 };
5461 const processText = (n1, n2, container, anchor) => {
5462 if (n1 == null) {
5463 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5464 }
5465 else {
5466 const el = (n2.el = n1.el);
5467 if (n2.children !== n1.children) {
5468 hostSetText(el, n2.children);
5469 }
5470 }
5471 };
5472 const processCommentNode = (n1, n2, container, anchor) => {
5473 if (n1 == null) {
5474 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5475 }
5476 else {
5477 // there's no support for dynamic comments
5478 n2.el = n1.el;
5479 }
5480 };
5481 const mountStaticNode = (n2, container, anchor, isSVG) => {
5482 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5483 };
5484 /**
5485 * Dev / HMR only
5486 */
5487 const patchStaticNode = (n1, n2, container, isSVG) => {
5488 // static nodes are only patched during dev for HMR
5489 if (n2.children !== n1.children) {
5490 const anchor = hostNextSibling(n1.anchor);
5491 // remove existing
5492 removeStaticNode(n1);
5493 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5494 }
5495 else {
5496 n2.el = n1.el;
5497 n2.anchor = n1.anchor;
5498 }
5499 };
5500 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5501 let next;
5502 while (el && el !== anchor) {
5503 next = hostNextSibling(el);
5504 hostInsert(el, container, nextSibling);
5505 el = next;
5506 }
5507 hostInsert(anchor, container, nextSibling);
5508 };
5509 const removeStaticNode = ({ el, anchor }) => {
5510 let next;
5511 while (el && el !== anchor) {
5512 next = hostNextSibling(el);
5513 hostRemove(el);
5514 el = next;
5515 }
5516 hostRemove(anchor);
5517 };
5518 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5519 isSVG = isSVG || n2.type === 'svg';
5520 if (n1 == null) {
5521 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5522 }
5523 else {
5524 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5525 }
5526 };
5527 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5528 let el;
5529 let vnodeHook;
5530 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
5531 {
5532 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
5533 // mount children first, since some props may rely on child content
5534 // being already rendered, e.g. `<select value>`
5535 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5536 hostSetElementText(el, vnode.children);
5537 }
5538 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5539 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
5540 }
5541 if (dirs) {
5542 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5543 }
5544 // props
5545 if (props) {
5546 for (const key in props) {
5547 if (key !== 'value' && !isReservedProp(key)) {
5548 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5549 }
5550 }
5551 /**
5552 * Special case for setting value on DOM elements:
5553 * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
5554 * - it needs to be forced (#1471)
5555 * #2353 proposes adding another renderer option to configure this, but
5556 * the properties affects are so finite it is worth special casing it
5557 * here to reduce the complexity. (Special casing it also should not
5558 * affect non-DOM renderers)
5559 */
5560 if ('value' in props) {
5561 hostPatchProp(el, 'value', null, props.value);
5562 }
5563 if ((vnodeHook = props.onVnodeBeforeMount)) {
5564 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5565 }
5566 }
5567 // scopeId
5568 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
5569 }
5570 {
5571 Object.defineProperty(el, '__vnode', {
5572 value: vnode,
5573 enumerable: false
5574 });
5575 Object.defineProperty(el, '__vueParentComponent', {
5576 value: parentComponent,
5577 enumerable: false
5578 });
5579 }
5580 if (dirs) {
5581 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5582 }
5583 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5584 // #1689 For inside suspense + suspense resolved case, just call it
5585 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5586 transition &&
5587 !transition.persisted;
5588 if (needCallTransitionHooks) {
5589 transition.beforeEnter(el);
5590 }
5591 hostInsert(el, container, anchor);
5592 if ((vnodeHook = props && props.onVnodeMounted) ||
5593 needCallTransitionHooks ||
5594 dirs) {
5595 queuePostRenderEffect(() => {
5596 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5597 needCallTransitionHooks && transition.enter(el);
5598 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5599 }, parentSuspense);
5600 }
5601 };
5602 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
5603 if (scopeId) {
5604 hostSetScopeId(el, scopeId);
5605 }
5606 if (slotScopeIds) {
5607 for (let i = 0; i < slotScopeIds.length; i++) {
5608 hostSetScopeId(el, slotScopeIds[i]);
5609 }
5610 }
5611 if (parentComponent) {
5612 let subTree = parentComponent.subTree;
5613 if (subTree.patchFlag > 0 &&
5614 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
5615 subTree =
5616 filterSingleRoot(subTree.children) || subTree;
5617 }
5618 if (vnode === subTree) {
5619 const parentVNode = parentComponent.vnode;
5620 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
5621 }
5622 }
5623 };
5624 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
5625 for (let i = start; i < children.length; i++) {
5626 const child = (children[i] = optimized
5627 ? cloneIfMounted(children[i])
5628 : normalizeVNode(children[i]));
5629 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5630 }
5631 };
5632 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5633 const el = (n2.el = n1.el);
5634 let { patchFlag, dynamicChildren, dirs } = n2;
5635 // #1426 take the old vnode's patch flag into account since user may clone a
5636 // compiler-generated vnode, which de-opts to FULL_PROPS
5637 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
5638 const oldProps = n1.props || EMPTY_OBJ;
5639 const newProps = n2.props || EMPTY_OBJ;
5640 let vnodeHook;
5641 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
5642 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5643 }
5644 if (dirs) {
5645 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
5646 }
5647 if (isHmrUpdating) {
5648 // HMR updated, force full diff
5649 patchFlag = 0;
5650 optimized = false;
5651 dynamicChildren = null;
5652 }
5653 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
5654 if (dynamicChildren) {
5655 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
5656 if (parentComponent && parentComponent.type.__hmrId) {
5657 traverseStaticChildren(n1, n2);
5658 }
5659 }
5660 else if (!optimized) {
5661 // full diff
5662 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
5663 }
5664 if (patchFlag > 0) {
5665 // the presence of a patchFlag means this element's render code was
5666 // generated by the compiler and can take the fast path.
5667 // in this path old node and new node are guaranteed to have the same shape
5668 // (i.e. at the exact same position in the source template)
5669 if (patchFlag & 16 /* FULL_PROPS */) {
5670 // element props contain dynamic keys, full diff needed
5671 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5672 }
5673 else {
5674 // class
5675 // this flag is matched when the element has dynamic class bindings.
5676 if (patchFlag & 2 /* CLASS */) {
5677 if (oldProps.class !== newProps.class) {
5678 hostPatchProp(el, 'class', null, newProps.class, isSVG);
5679 }
5680 }
5681 // style
5682 // this flag is matched when the element has dynamic style bindings
5683 if (patchFlag & 4 /* STYLE */) {
5684 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
5685 }
5686 // props
5687 // This flag is matched when the element has dynamic prop/attr bindings
5688 // other than class and style. The keys of dynamic prop/attrs are saved for
5689 // faster iteration.
5690 // Note dynamic keys like :[foo]="bar" will cause this optimization to
5691 // bail out and go through a full diff because we need to unset the old key
5692 if (patchFlag & 8 /* PROPS */) {
5693 // if the flag is present then dynamicProps must be non-null
5694 const propsToUpdate = n2.dynamicProps;
5695 for (let i = 0; i < propsToUpdate.length; i++) {
5696 const key = propsToUpdate[i];
5697 const prev = oldProps[key];
5698 const next = newProps[key];
5699 // #1471 force patch value
5700 if (next !== prev || key === 'value') {
5701 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
5702 }
5703 }
5704 }
5705 }
5706 // text
5707 // This flag is matched when the element has only dynamic text children.
5708 if (patchFlag & 1 /* TEXT */) {
5709 if (n1.children !== n2.children) {
5710 hostSetElementText(el, n2.children);
5711 }
5712 }
5713 }
5714 else if (!optimized && dynamicChildren == null) {
5715 // unoptimized, full diff
5716 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5717 }
5718 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
5719 queuePostRenderEffect(() => {
5720 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5721 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
5722 }, parentSuspense);
5723 }
5724 };
5725 // The fast path for blocks.
5726 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
5727 for (let i = 0; i < newChildren.length; i++) {
5728 const oldVNode = oldChildren[i];
5729 const newVNode = newChildren[i];
5730 // Determine the container (parent element) for the patch.
5731 const container =
5732 // oldVNode may be an errored async setup() component inside Suspense
5733 // which will not have a mounted element
5734 oldVNode.el &&
5735 // - In the case of a Fragment, we need to provide the actual parent
5736 // of the Fragment itself so it can move its children.
5737 (oldVNode.type === Fragment ||
5738 // - In the case of different nodes, there is going to be a replacement
5739 // which also requires the correct parent container
5740 !isSameVNodeType(oldVNode, newVNode) ||
5741 // - In the case of a component, it could contain anything.
5742 oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
5743 ? hostParentNode(oldVNode.el)
5744 : // In other cases, the parent container is not actually used so we
5745 // just pass the block element here to avoid a DOM parentNode call.
5746 fallbackContainer;
5747 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
5748 }
5749 };
5750 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
5751 if (oldProps !== newProps) {
5752 for (const key in newProps) {
5753 // empty string is not valid prop
5754 if (isReservedProp(key))
5755 continue;
5756 const next = newProps[key];
5757 const prev = oldProps[key];
5758 // defer patching value
5759 if (next !== prev && key !== 'value') {
5760 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5761 }
5762 }
5763 if (oldProps !== EMPTY_OBJ) {
5764 for (const key in oldProps) {
5765 if (!isReservedProp(key) && !(key in newProps)) {
5766 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5767 }
5768 }
5769 }
5770 if ('value' in newProps) {
5771 hostPatchProp(el, 'value', oldProps.value, newProps.value);
5772 }
5773 }
5774 };
5775 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5776 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
5777 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
5778 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
5779 if (isHmrUpdating) {
5780 // HMR updated, force full diff
5781 patchFlag = 0;
5782 optimized = false;
5783 dynamicChildren = null;
5784 }
5785 // check if this is a slot fragment with :slotted scope ids
5786 if (fragmentSlotScopeIds) {
5787 slotScopeIds = slotScopeIds
5788 ? slotScopeIds.concat(fragmentSlotScopeIds)
5789 : fragmentSlotScopeIds;
5790 }
5791 if (n1 == null) {
5792 hostInsert(fragmentStartAnchor, container, anchor);
5793 hostInsert(fragmentEndAnchor, container, anchor);
5794 // a fragment can only have array children
5795 // since they are either generated by the compiler, or implicitly created
5796 // from arrays.
5797 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5798 }
5799 else {
5800 if (patchFlag > 0 &&
5801 patchFlag & 64 /* STABLE_FRAGMENT */ &&
5802 dynamicChildren &&
5803 // #2715 the previous fragment could've been a BAILed one as a result
5804 // of renderSlot() with no valid children
5805 n1.dynamicChildren) {
5806 // a stable fragment (template root or <template v-for>) doesn't need to
5807 // patch children order, but it may contain dynamicChildren.
5808 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
5809 if (parentComponent && parentComponent.type.__hmrId) {
5810 traverseStaticChildren(n1, n2);
5811 }
5812 else if (
5813 // #2080 if the stable fragment has a key, it's a <template v-for> that may
5814 // get moved around. Make sure all root level vnodes inherit el.
5815 // #2134 or if it's a component root, it may also get moved around
5816 // as the component is being moved.
5817 n2.key != null ||
5818 (parentComponent && n2 === parentComponent.subTree)) {
5819 traverseStaticChildren(n1, n2, true /* shallow */);
5820 }
5821 }
5822 else {
5823 // keyed / unkeyed, or manual fragments.
5824 // for keyed & unkeyed, since they are compiler generated from v-for,
5825 // each child is guaranteed to be a block so the fragment will never
5826 // have dynamicChildren.
5827 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5828 }
5829 }
5830 };
5831 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5832 n2.slotScopeIds = slotScopeIds;
5833 if (n1 == null) {
5834 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
5835 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
5836 }
5837 else {
5838 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5839 }
5840 }
5841 else {
5842 updateComponent(n1, n2, optimized);
5843 }
5844 };
5845 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5846 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
5847 if (instance.type.__hmrId) {
5848 registerHMR(instance);
5849 }
5850 {
5851 pushWarningContext(initialVNode);
5852 startMeasure(instance, `mount`);
5853 }
5854 // inject renderer internals for keepAlive
5855 if (isKeepAlive(initialVNode)) {
5856 instance.ctx.renderer = internals;
5857 }
5858 // resolve props and slots for setup context
5859 {
5860 {
5861 startMeasure(instance, `init`);
5862 }
5863 setupComponent(instance);
5864 {
5865 endMeasure(instance, `init`);
5866 }
5867 }
5868 // setup() is async. This component relies on async logic to be resolved
5869 // before proceeding
5870 if (instance.asyncDep) {
5871 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
5872 // Give it a placeholder if this is not hydration
5873 // TODO handle self-defined fallback
5874 if (!initialVNode.el) {
5875 const placeholder = (instance.subTree = createVNode(Comment));
5876 processCommentNode(null, placeholder, container, anchor);
5877 }
5878 return;
5879 }
5880 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
5881 {
5882 popWarningContext();
5883 endMeasure(instance, `mount`);
5884 }
5885 };
5886 const updateComponent = (n1, n2, optimized) => {
5887 const instance = (n2.component = n1.component);
5888 if (shouldUpdateComponent(n1, n2, optimized)) {
5889 if (instance.asyncDep &&
5890 !instance.asyncResolved) {
5891 // async & still pending - just update props and slots
5892 // since the component's reactive effect for render isn't set-up yet
5893 {
5894 pushWarningContext(n2);
5895 }
5896 updateComponentPreRender(instance, n2, optimized);
5897 {
5898 popWarningContext();
5899 }
5900 return;
5901 }
5902 else {
5903 // normal update
5904 instance.next = n2;
5905 // in case the child component is also queued, remove it to avoid
5906 // double updating the same child component in the same flush.
5907 invalidateJob(instance.update);
5908 // instance.update is the reactive effect.
5909 instance.update();
5910 }
5911 }
5912 else {
5913 // no update needed. just copy over properties
5914 n2.component = n1.component;
5915 n2.el = n1.el;
5916 instance.vnode = n2;
5917 }
5918 };
5919 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
5920 const componentUpdateFn = () => {
5921 if (!instance.isMounted) {
5922 let vnodeHook;
5923 const { el, props } = initialVNode;
5924 const { bm, m, parent } = instance;
5925 const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
5926 effect.allowRecurse = false;
5927 // beforeMount hook
5928 if (bm) {
5929 invokeArrayFns(bm);
5930 }
5931 // onVnodeBeforeMount
5932 if (!isAsyncWrapperVNode &&
5933 (vnodeHook = props && props.onVnodeBeforeMount)) {
5934 invokeVNodeHook(vnodeHook, parent, initialVNode);
5935 }
5936 effect.allowRecurse = true;
5937 if (el && hydrateNode) {
5938 // vnode has adopted host node - perform hydration instead of mount.
5939 const hydrateSubTree = () => {
5940 {
5941 startMeasure(instance, `render`);
5942 }
5943 instance.subTree = renderComponentRoot(instance);
5944 {
5945 endMeasure(instance, `render`);
5946 }
5947 {
5948 startMeasure(instance, `hydrate`);
5949 }
5950 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
5951 {
5952 endMeasure(instance, `hydrate`);
5953 }
5954 };
5955 if (isAsyncWrapperVNode) {
5956 initialVNode.type.__asyncLoader().then(
5957 // note: we are moving the render call into an async callback,
5958 // which means it won't track dependencies - but it's ok because
5959 // a server-rendered async wrapper is already in resolved state
5960 // and it will never need to change.
5961 () => !instance.isUnmounted && hydrateSubTree());
5962 }
5963 else {
5964 hydrateSubTree();
5965 }
5966 }
5967 else {
5968 {
5969 startMeasure(instance, `render`);
5970 }
5971 const subTree = (instance.subTree = renderComponentRoot(instance));
5972 {
5973 endMeasure(instance, `render`);
5974 }
5975 {
5976 startMeasure(instance, `patch`);
5977 }
5978 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
5979 {
5980 endMeasure(instance, `patch`);
5981 }
5982 initialVNode.el = subTree.el;
5983 }
5984 // mounted hook
5985 if (m) {
5986 queuePostRenderEffect(m, parentSuspense);
5987 }
5988 // onVnodeMounted
5989 if (!isAsyncWrapperVNode &&
5990 (vnodeHook = props && props.onVnodeMounted)) {
5991 const scopedInitialVNode = initialVNode;
5992 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
5993 }
5994 // activated hook for keep-alive roots.
5995 // #1742 activated hook must be accessed after first render
5996 // since the hook may be injected by a child keep-alive
5997 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5998 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
5999 }
6000 instance.isMounted = true;
6001 {
6002 devtoolsComponentAdded(instance);
6003 }
6004 // #2458: deference mount-only object parameters to prevent memleaks
6005 initialVNode = container = anchor = null;
6006 }
6007 else {
6008 // updateComponent
6009 // This is triggered by mutation of component's own state (next: null)
6010 // OR parent calling processComponent (next: VNode)
6011 let { next, bu, u, parent, vnode } = instance;
6012 let originNext = next;
6013 let vnodeHook;
6014 {
6015 pushWarningContext(next || instance.vnode);
6016 }
6017 // Disallow component effect recursion during pre-lifecycle hooks.
6018 effect.allowRecurse = false;
6019 if (next) {
6020 next.el = vnode.el;
6021 updateComponentPreRender(instance, next, optimized);
6022 }
6023 else {
6024 next = vnode;
6025 }
6026 // beforeUpdate hook
6027 if (bu) {
6028 invokeArrayFns(bu);
6029 }
6030 // onVnodeBeforeUpdate
6031 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6032 invokeVNodeHook(vnodeHook, parent, next, vnode);
6033 }
6034 effect.allowRecurse = true;
6035 // render
6036 {
6037 startMeasure(instance, `render`);
6038 }
6039 const nextTree = renderComponentRoot(instance);
6040 {
6041 endMeasure(instance, `render`);
6042 }
6043 const prevTree = instance.subTree;
6044 instance.subTree = nextTree;
6045 {
6046 startMeasure(instance, `patch`);
6047 }
6048 patch(prevTree, nextTree,
6049 // parent may have changed if it's in a teleport
6050 hostParentNode(prevTree.el),
6051 // anchor may have changed if it's in a fragment
6052 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6053 {
6054 endMeasure(instance, `patch`);
6055 }
6056 next.el = nextTree.el;
6057 if (originNext === null) {
6058 // self-triggered update. In case of HOC, update parent component
6059 // vnode el. HOC is indicated by parent instance's subTree pointing
6060 // to child component's vnode
6061 updateHOCHostEl(instance, nextTree.el);
6062 }
6063 // updated hook
6064 if (u) {
6065 queuePostRenderEffect(u, parentSuspense);
6066 }
6067 // onVnodeUpdated
6068 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6069 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6070 }
6071 {
6072 devtoolsComponentUpdated(instance);
6073 }
6074 {
6075 popWarningContext();
6076 }
6077 }
6078 };
6079 // create reactive effect for rendering
6080 const effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
6081 );
6082 const update = (instance.update = effect.run.bind(effect));
6083 update.id = instance.uid;
6084 // allowRecurse
6085 // #1801, #2043 component render effects should allow recursive updates
6086 effect.allowRecurse = update.allowRecurse = true;
6087 {
6088 effect.onTrack = instance.rtc
6089 ? e => invokeArrayFns(instance.rtc, e)
6090 : void 0;
6091 effect.onTrigger = instance.rtg
6092 ? e => invokeArrayFns(instance.rtg, e)
6093 : void 0;
6094 // @ts-ignore (for scheduler)
6095 update.ownerInstance = instance;
6096 }
6097 update();
6098 };
6099 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6100 nextVNode.component = instance;
6101 const prevProps = instance.vnode.props;
6102 instance.vnode = nextVNode;
6103 instance.next = null;
6104 updateProps(instance, nextVNode.props, prevProps, optimized);
6105 updateSlots(instance, nextVNode.children, optimized);
6106 pauseTracking();
6107 // props update may have triggered pre-flush watchers.
6108 // flush them before the render update.
6109 flushPreFlushCbs(undefined, instance.update);
6110 resetTracking();
6111 };
6112 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6113 const c1 = n1 && n1.children;
6114 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6115 const c2 = n2.children;
6116 const { patchFlag, shapeFlag } = n2;
6117 // fast path
6118 if (patchFlag > 0) {
6119 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6120 // this could be either fully-keyed or mixed (some keyed some not)
6121 // presence of patchFlag means children are guaranteed to be arrays
6122 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6123 return;
6124 }
6125 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6126 // unkeyed
6127 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6128 return;
6129 }
6130 }
6131 // children has 3 possibilities: text, array or no children.
6132 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6133 // text children fast path
6134 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6135 unmountChildren(c1, parentComponent, parentSuspense);
6136 }
6137 if (c2 !== c1) {
6138 hostSetElementText(container, c2);
6139 }
6140 }
6141 else {
6142 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6143 // prev children was array
6144 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6145 // two arrays, cannot assume anything, do full diff
6146 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6147 }
6148 else {
6149 // no new children, just unmount old
6150 unmountChildren(c1, parentComponent, parentSuspense, true);
6151 }
6152 }
6153 else {
6154 // prev children was text OR null
6155 // new children is array OR null
6156 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6157 hostSetElementText(container, '');
6158 }
6159 // mount new if array
6160 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6161 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6162 }
6163 }
6164 }
6165 };
6166 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6167 c1 = c1 || EMPTY_ARR;
6168 c2 = c2 || EMPTY_ARR;
6169 const oldLength = c1.length;
6170 const newLength = c2.length;
6171 const commonLength = Math.min(oldLength, newLength);
6172 let i;
6173 for (i = 0; i < commonLength; i++) {
6174 const nextChild = (c2[i] = optimized
6175 ? cloneIfMounted(c2[i])
6176 : normalizeVNode(c2[i]));
6177 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6178 }
6179 if (oldLength > newLength) {
6180 // remove old
6181 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6182 }
6183 else {
6184 // mount new
6185 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6186 }
6187 };
6188 // can be all-keyed or mixed
6189 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6190 let i = 0;
6191 const l2 = c2.length;
6192 let e1 = c1.length - 1; // prev ending index
6193 let e2 = l2 - 1; // next ending index
6194 // 1. sync from start
6195 // (a b) c
6196 // (a b) d e
6197 while (i <= e1 && i <= e2) {
6198 const n1 = c1[i];
6199 const n2 = (c2[i] = optimized
6200 ? cloneIfMounted(c2[i])
6201 : normalizeVNode(c2[i]));
6202 if (isSameVNodeType(n1, n2)) {
6203 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6204 }
6205 else {
6206 break;
6207 }
6208 i++;
6209 }
6210 // 2. sync from end
6211 // a (b c)
6212 // d e (b c)
6213 while (i <= e1 && i <= e2) {
6214 const n1 = c1[e1];
6215 const n2 = (c2[e2] = optimized
6216 ? cloneIfMounted(c2[e2])
6217 : normalizeVNode(c2[e2]));
6218 if (isSameVNodeType(n1, n2)) {
6219 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6220 }
6221 else {
6222 break;
6223 }
6224 e1--;
6225 e2--;
6226 }
6227 // 3. common sequence + mount
6228 // (a b)
6229 // (a b) c
6230 // i = 2, e1 = 1, e2 = 2
6231 // (a b)
6232 // c (a b)
6233 // i = 0, e1 = -1, e2 = 0
6234 if (i > e1) {
6235 if (i <= e2) {
6236 const nextPos = e2 + 1;
6237 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6238 while (i <= e2) {
6239 patch(null, (c2[i] = optimized
6240 ? cloneIfMounted(c2[i])
6241 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6242 i++;
6243 }
6244 }
6245 }
6246 // 4. common sequence + unmount
6247 // (a b) c
6248 // (a b)
6249 // i = 2, e1 = 2, e2 = 1
6250 // a (b c)
6251 // (b c)
6252 // i = 0, e1 = 0, e2 = -1
6253 else if (i > e2) {
6254 while (i <= e1) {
6255 unmount(c1[i], parentComponent, parentSuspense, true);
6256 i++;
6257 }
6258 }
6259 // 5. unknown sequence
6260 // [i ... e1 + 1]: a b [c d e] f g
6261 // [i ... e2 + 1]: a b [e d c h] f g
6262 // i = 2, e1 = 4, e2 = 5
6263 else {
6264 const s1 = i; // prev starting index
6265 const s2 = i; // next starting index
6266 // 5.1 build key:index map for newChildren
6267 const keyToNewIndexMap = new Map();
6268 for (i = s2; i <= e2; i++) {
6269 const nextChild = (c2[i] = optimized
6270 ? cloneIfMounted(c2[i])
6271 : normalizeVNode(c2[i]));
6272 if (nextChild.key != null) {
6273 if (keyToNewIndexMap.has(nextChild.key)) {
6274 warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6275 }
6276 keyToNewIndexMap.set(nextChild.key, i);
6277 }
6278 }
6279 // 5.2 loop through old children left to be patched and try to patch
6280 // matching nodes & remove nodes that are no longer present
6281 let j;
6282 let patched = 0;
6283 const toBePatched = e2 - s2 + 1;
6284 let moved = false;
6285 // used to track whether any node has moved
6286 let maxNewIndexSoFar = 0;
6287 // works as Map<newIndex, oldIndex>
6288 // Note that oldIndex is offset by +1
6289 // and oldIndex = 0 is a special value indicating the new node has
6290 // no corresponding old node.
6291 // used for determining longest stable subsequence
6292 const newIndexToOldIndexMap = new Array(toBePatched);
6293 for (i = 0; i < toBePatched; i++)
6294 newIndexToOldIndexMap[i] = 0;
6295 for (i = s1; i <= e1; i++) {
6296 const prevChild = c1[i];
6297 if (patched >= toBePatched) {
6298 // all new children have been patched so this can only be a removal
6299 unmount(prevChild, parentComponent, parentSuspense, true);
6300 continue;
6301 }
6302 let newIndex;
6303 if (prevChild.key != null) {
6304 newIndex = keyToNewIndexMap.get(prevChild.key);
6305 }
6306 else {
6307 // key-less node, try to locate a key-less node of the same type
6308 for (j = s2; j <= e2; j++) {
6309 if (newIndexToOldIndexMap[j - s2] === 0 &&
6310 isSameVNodeType(prevChild, c2[j])) {
6311 newIndex = j;
6312 break;
6313 }
6314 }
6315 }
6316 if (newIndex === undefined) {
6317 unmount(prevChild, parentComponent, parentSuspense, true);
6318 }
6319 else {
6320 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6321 if (newIndex >= maxNewIndexSoFar) {
6322 maxNewIndexSoFar = newIndex;
6323 }
6324 else {
6325 moved = true;
6326 }
6327 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6328 patched++;
6329 }
6330 }
6331 // 5.3 move and mount
6332 // generate longest stable subsequence only when nodes have moved
6333 const increasingNewIndexSequence = moved
6334 ? getSequence(newIndexToOldIndexMap)
6335 : EMPTY_ARR;
6336 j = increasingNewIndexSequence.length - 1;
6337 // looping backwards so that we can use last patched node as anchor
6338 for (i = toBePatched - 1; i >= 0; i--) {
6339 const nextIndex = s2 + i;
6340 const nextChild = c2[nextIndex];
6341 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6342 if (newIndexToOldIndexMap[i] === 0) {
6343 // mount new
6344 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6345 }
6346 else if (moved) {
6347 // move if:
6348 // There is no stable subsequence (e.g. a reverse)
6349 // OR current node is not among the stable sequence
6350 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6351 move(nextChild, container, anchor, 2 /* REORDER */);
6352 }
6353 else {
6354 j--;
6355 }
6356 }
6357 }
6358 }
6359 };
6360 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6361 const { el, type, transition, children, shapeFlag } = vnode;
6362 if (shapeFlag & 6 /* COMPONENT */) {
6363 move(vnode.component.subTree, container, anchor, moveType);
6364 return;
6365 }
6366 if (shapeFlag & 128 /* SUSPENSE */) {
6367 vnode.suspense.move(container, anchor, moveType);
6368 return;
6369 }
6370 if (shapeFlag & 64 /* TELEPORT */) {
6371 type.move(vnode, container, anchor, internals);
6372 return;
6373 }
6374 if (type === Fragment) {
6375 hostInsert(el, container, anchor);
6376 for (let i = 0; i < children.length; i++) {
6377 move(children[i], container, anchor, moveType);
6378 }
6379 hostInsert(vnode.anchor, container, anchor);
6380 return;
6381 }
6382 if (type === Static) {
6383 moveStaticNode(vnode, container, anchor);
6384 return;
6385 }
6386 // single nodes
6387 const needTransition = moveType !== 2 /* REORDER */ &&
6388 shapeFlag & 1 /* ELEMENT */ &&
6389 transition;
6390 if (needTransition) {
6391 if (moveType === 0 /* ENTER */) {
6392 transition.beforeEnter(el);
6393 hostInsert(el, container, anchor);
6394 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6395 }
6396 else {
6397 const { leave, delayLeave, afterLeave } = transition;
6398 const remove = () => hostInsert(el, container, anchor);
6399 const performLeave = () => {
6400 leave(el, () => {
6401 remove();
6402 afterLeave && afterLeave();
6403 });
6404 };
6405 if (delayLeave) {
6406 delayLeave(el, remove, performLeave);
6407 }
6408 else {
6409 performLeave();
6410 }
6411 }
6412 }
6413 else {
6414 hostInsert(el, container, anchor);
6415 }
6416 };
6417 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6418 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6419 // unset ref
6420 if (ref != null) {
6421 setRef(ref, null, parentSuspense, vnode, true);
6422 }
6423 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6424 parentComponent.ctx.deactivate(vnode);
6425 return;
6426 }
6427 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6428 const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
6429 let vnodeHook;
6430 if (shouldInvokeVnodeHook &&
6431 (vnodeHook = props && props.onVnodeBeforeUnmount)) {
6432 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6433 }
6434 if (shapeFlag & 6 /* COMPONENT */) {
6435 unmountComponent(vnode.component, parentSuspense, doRemove);
6436 }
6437 else {
6438 if (shapeFlag & 128 /* SUSPENSE */) {
6439 vnode.suspense.unmount(parentSuspense, doRemove);
6440 return;
6441 }
6442 if (shouldInvokeDirs) {
6443 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6444 }
6445 if (shapeFlag & 64 /* TELEPORT */) {
6446 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6447 }
6448 else if (dynamicChildren &&
6449 // #1153: fast path should not be taken for non-stable (v-for) fragments
6450 (type !== Fragment ||
6451 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6452 // fast path for block nodes: only need to unmount dynamic children.
6453 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6454 }
6455 else if ((type === Fragment &&
6456 patchFlag &
6457 (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
6458 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6459 unmountChildren(children, parentComponent, parentSuspense);
6460 }
6461 if (doRemove) {
6462 remove(vnode);
6463 }
6464 }
6465 if ((shouldInvokeVnodeHook &&
6466 (vnodeHook = props && props.onVnodeUnmounted)) ||
6467 shouldInvokeDirs) {
6468 queuePostRenderEffect(() => {
6469 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6470 shouldInvokeDirs &&
6471 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6472 }, parentSuspense);
6473 }
6474 };
6475 const remove = vnode => {
6476 const { type, el, anchor, transition } = vnode;
6477 if (type === Fragment) {
6478 removeFragment(el, anchor);
6479 return;
6480 }
6481 if (type === Static) {
6482 removeStaticNode(vnode);
6483 return;
6484 }
6485 const performRemove = () => {
6486 hostRemove(el);
6487 if (transition && !transition.persisted && transition.afterLeave) {
6488 transition.afterLeave();
6489 }
6490 };
6491 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6492 transition &&
6493 !transition.persisted) {
6494 const { leave, delayLeave } = transition;
6495 const performLeave = () => leave(el, performRemove);
6496 if (delayLeave) {
6497 delayLeave(vnode.el, performRemove, performLeave);
6498 }
6499 else {
6500 performLeave();
6501 }
6502 }
6503 else {
6504 performRemove();
6505 }
6506 };
6507 const removeFragment = (cur, end) => {
6508 // For fragments, directly remove all contained DOM nodes.
6509 // (fragment child nodes cannot have transition)
6510 let next;
6511 while (cur !== end) {
6512 next = hostNextSibling(cur);
6513 hostRemove(cur);
6514 cur = next;
6515 }
6516 hostRemove(end);
6517 };
6518 const unmountComponent = (instance, parentSuspense, doRemove) => {
6519 if (instance.type.__hmrId) {
6520 unregisterHMR(instance);
6521 }
6522 const { bum, scope, update, subTree, um } = instance;
6523 // beforeUnmount hook
6524 if (bum) {
6525 invokeArrayFns(bum);
6526 }
6527 // stop effects in component scope
6528 scope.stop();
6529 // update may be null if a component is unmounted before its async
6530 // setup has resolved.
6531 if (update) {
6532 // so that scheduler will no longer invoke it
6533 update.active = false;
6534 unmount(subTree, instance, parentSuspense, doRemove);
6535 }
6536 // unmounted hook
6537 if (um) {
6538 queuePostRenderEffect(um, parentSuspense);
6539 }
6540 queuePostRenderEffect(() => {
6541 instance.isUnmounted = true;
6542 }, parentSuspense);
6543 // A component with async dep inside a pending suspense is unmounted before
6544 // its async dep resolves. This should remove the dep from the suspense, and
6545 // cause the suspense to resolve immediately if that was the last dep.
6546 if (parentSuspense &&
6547 parentSuspense.pendingBranch &&
6548 !parentSuspense.isUnmounted &&
6549 instance.asyncDep &&
6550 !instance.asyncResolved &&
6551 instance.suspenseId === parentSuspense.pendingId) {
6552 parentSuspense.deps--;
6553 if (parentSuspense.deps === 0) {
6554 parentSuspense.resolve();
6555 }
6556 }
6557 {
6558 devtoolsComponentRemoved(instance);
6559 }
6560 };
6561 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
6562 for (let i = start; i < children.length; i++) {
6563 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
6564 }
6565 };
6566 const getNextHostNode = vnode => {
6567 if (vnode.shapeFlag & 6 /* COMPONENT */) {
6568 return getNextHostNode(vnode.component.subTree);
6569 }
6570 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
6571 return vnode.suspense.next();
6572 }
6573 return hostNextSibling((vnode.anchor || vnode.el));
6574 };
6575 const render = (vnode, container, isSVG) => {
6576 if (vnode == null) {
6577 if (container._vnode) {
6578 unmount(container._vnode, null, null, true);
6579 }
6580 }
6581 else {
6582 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
6583 }
6584 flushPostFlushCbs();
6585 container._vnode = vnode;
6586 };
6587 const internals = {
6588 p: patch,
6589 um: unmount,
6590 m: move,
6591 r: remove,
6592 mt: mountComponent,
6593 mc: mountChildren,
6594 pc: patchChildren,
6595 pbc: patchBlockChildren,
6596 n: getNextHostNode,
6597 o: options
6598 };
6599 let hydrate;
6600 let hydrateNode;
6601 if (createHydrationFns) {
6602 [hydrate, hydrateNode] = createHydrationFns(internals);
6603 }
6604 return {
6605 render,
6606 hydrate,
6607 createApp: createAppAPI(render, hydrate)
6608 };
6609 }
6610 function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
6611 if (isArray(rawRef)) {
6612 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
6613 return;
6614 }
6615 if (isAsyncWrapper(vnode) && !isUnmount) {
6616 // when mounting async components, nothing needs to be done,
6617 // because the template ref is forwarded to inner component
6618 return;
6619 }
6620 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
6621 ? getExposeProxy(vnode.component) || vnode.component.proxy
6622 : vnode.el;
6623 const value = isUnmount ? null : refValue;
6624 const { i: owner, r: ref } = rawRef;
6625 if (!owner) {
6626 warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
6627 `A vnode with ref must be created inside the render function.`);
6628 return;
6629 }
6630 const oldRef = oldRawRef && oldRawRef.r;
6631 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
6632 const setupState = owner.setupState;
6633 // dynamic ref changed. unset old ref
6634 if (oldRef != null && oldRef !== ref) {
6635 if (isString(oldRef)) {
6636 refs[oldRef] = null;
6637 if (hasOwn(setupState, oldRef)) {
6638 setupState[oldRef] = null;
6639 }
6640 }
6641 else if (isRef(oldRef)) {
6642 oldRef.value = null;
6643 }
6644 }
6645 if (isString(ref)) {
6646 const doSet = () => {
6647 {
6648 refs[ref] = value;
6649 }
6650 if (hasOwn(setupState, ref)) {
6651 setupState[ref] = value;
6652 }
6653 };
6654 // #1789: for non-null values, set them after render
6655 // null values means this is unmount and it should not overwrite another
6656 // ref with the same key
6657 if (value) {
6658 doSet.id = -1;
6659 queuePostRenderEffect(doSet, parentSuspense);
6660 }
6661 else {
6662 doSet();
6663 }
6664 }
6665 else if (isRef(ref)) {
6666 const doSet = () => {
6667 ref.value = value;
6668 };
6669 if (value) {
6670 doSet.id = -1;
6671 queuePostRenderEffect(doSet, parentSuspense);
6672 }
6673 else {
6674 doSet();
6675 }
6676 }
6677 else if (isFunction(ref)) {
6678 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
6679 }
6680 else {
6681 warn$1('Invalid template ref type:', value, `(${typeof value})`);
6682 }
6683 }
6684 function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6685 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6686 vnode,
6687 prevVNode
6688 ]);
6689 }
6690 /**
6691 * #1156
6692 * When a component is HMR-enabled, we need to make sure that all static nodes
6693 * inside a block also inherit the DOM element from the previous tree so that
6694 * HMR updates (which are full updates) can retrieve the element for patching.
6695 *
6696 * #2080
6697 * Inside keyed `template` fragment static children, if a fragment is moved,
6698 * the children will always moved so that need inherit el form previous nodes
6699 * to ensure correct moved position.
6700 */
6701 function traverseStaticChildren(n1, n2, shallow = false) {
6702 const ch1 = n1.children;
6703 const ch2 = n2.children;
6704 if (isArray(ch1) && isArray(ch2)) {
6705 for (let i = 0; i < ch1.length; i++) {
6706 // this is only called in the optimized path so array children are
6707 // guaranteed to be vnodes
6708 const c1 = ch1[i];
6709 let c2 = ch2[i];
6710 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
6711 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
6712 c2 = ch2[i] = cloneIfMounted(ch2[i]);
6713 c2.el = c1.el;
6714 }
6715 if (!shallow)
6716 traverseStaticChildren(c1, c2);
6717 }
6718 // also inherit for comment nodes, but not placeholders (e.g. v-if which
6719 // would have received .el during block patch)
6720 if (c2.type === Comment && !c2.el) {
6721 c2.el = c1.el;
6722 }
6723 }
6724 }
6725 }
6726 // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
6727 function getSequence(arr) {
6728 const p = arr.slice();
6729 const result = [0];
6730 let i, j, u, v, c;
6731 const len = arr.length;
6732 for (i = 0; i < len; i++) {
6733 const arrI = arr[i];
6734 if (arrI !== 0) {
6735 j = result[result.length - 1];
6736 if (arr[j] < arrI) {
6737 p[i] = j;
6738 result.push(i);
6739 continue;
6740 }
6741 u = 0;
6742 v = result.length - 1;
6743 while (u < v) {
6744 c = (u + v) >> 1;
6745 if (arr[result[c]] < arrI) {
6746 u = c + 1;
6747 }
6748 else {
6749 v = c;
6750 }
6751 }
6752 if (arrI < arr[result[u]]) {
6753 if (u > 0) {
6754 p[i] = result[u - 1];
6755 }
6756 result[u] = i;
6757 }
6758 }
6759 }
6760 u = result.length;
6761 v = result[u - 1];
6762 while (u-- > 0) {
6763 result[u] = v;
6764 v = p[v];
6765 }
6766 return result;
6767 }
6768
6769 const isTeleport = (type) => type.__isTeleport;
6770 const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
6771 const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
6772 const resolveTarget = (props, select) => {
6773 const targetSelector = props && props.to;
6774 if (isString(targetSelector)) {
6775 if (!select) {
6776 warn$1(`Current renderer does not support string target for Teleports. ` +
6777 `(missing querySelector renderer option)`);
6778 return null;
6779 }
6780 else {
6781 const target = select(targetSelector);
6782 if (!target) {
6783 warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
6784 `Note the target element must exist before the component is mounted - ` +
6785 `i.e. the target cannot be rendered by the component itself, and ` +
6786 `ideally should be outside of the entire Vue component tree.`);
6787 }
6788 return target;
6789 }
6790 }
6791 else {
6792 if (!targetSelector && !isTeleportDisabled(props)) {
6793 warn$1(`Invalid Teleport target: ${targetSelector}`);
6794 }
6795 return targetSelector;
6796 }
6797 };
6798 const TeleportImpl = {
6799 __isTeleport: true,
6800 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
6801 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
6802 const disabled = isTeleportDisabled(n2.props);
6803 let { shapeFlag, children, dynamicChildren } = n2;
6804 // #3302
6805 // HMR updated, force full diff
6806 if (isHmrUpdating) {
6807 optimized = false;
6808 dynamicChildren = null;
6809 }
6810 if (n1 == null) {
6811 // insert anchors in the main view
6812 const placeholder = (n2.el = createComment('teleport start')
6813 );
6814 const mainAnchor = (n2.anchor = createComment('teleport end')
6815 );
6816 insert(placeholder, container, anchor);
6817 insert(mainAnchor, container, anchor);
6818 const target = (n2.target = resolveTarget(n2.props, querySelector));
6819 const targetAnchor = (n2.targetAnchor = createText(''));
6820 if (target) {
6821 insert(targetAnchor, target);
6822 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
6823 isSVG = isSVG || isTargetSVG(target);
6824 }
6825 else if (!disabled) {
6826 warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
6827 }
6828 const mount = (container, anchor) => {
6829 // Teleport *always* has Array children. This is enforced in both the
6830 // compiler and vnode children normalization.
6831 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6832 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6833 }
6834 };
6835 if (disabled) {
6836 mount(container, mainAnchor);
6837 }
6838 else if (target) {
6839 mount(target, targetAnchor);
6840 }
6841 }
6842 else {
6843 // update content
6844 n2.el = n1.el;
6845 const mainAnchor = (n2.anchor = n1.anchor);
6846 const target = (n2.target = n1.target);
6847 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
6848 const wasDisabled = isTeleportDisabled(n1.props);
6849 const currentContainer = wasDisabled ? container : target;
6850 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
6851 isSVG = isSVG || isTargetSVG(target);
6852 if (dynamicChildren) {
6853 // fast path when the teleport happens to be a block root
6854 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
6855 // even in block tree mode we need to make sure all root-level nodes
6856 // in the teleport inherit previous DOM references so that they can
6857 // be moved in future patches.
6858 traverseStaticChildren(n1, n2, true);
6859 }
6860 else if (!optimized) {
6861 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
6862 }
6863 if (disabled) {
6864 if (!wasDisabled) {
6865 // enabled -> disabled
6866 // move into main container
6867 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
6868 }
6869 }
6870 else {
6871 // target changed
6872 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
6873 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
6874 if (nextTarget) {
6875 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
6876 }
6877 else {
6878 warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
6879 }
6880 }
6881 else if (wasDisabled) {
6882 // disabled -> enabled
6883 // move into teleport target
6884 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
6885 }
6886 }
6887 }
6888 },
6889 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
6890 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
6891 if (target) {
6892 hostRemove(targetAnchor);
6893 }
6894 // an unmounted teleport should always remove its children if not disabled
6895 if (doRemove || !isTeleportDisabled(props)) {
6896 hostRemove(anchor);
6897 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6898 for (let i = 0; i < children.length; i++) {
6899 const child = children[i];
6900 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
6901 }
6902 }
6903 }
6904 },
6905 move: moveTeleport,
6906 hydrate: hydrateTeleport
6907 };
6908 function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
6909 // move target anchor if this is a target change.
6910 if (moveType === 0 /* TARGET_CHANGE */) {
6911 insert(vnode.targetAnchor, container, parentAnchor);
6912 }
6913 const { el, anchor, shapeFlag, children, props } = vnode;
6914 const isReorder = moveType === 2 /* REORDER */;
6915 // move main view anchor if this is a re-order.
6916 if (isReorder) {
6917 insert(el, container, parentAnchor);
6918 }
6919 // if this is a re-order and teleport is enabled (content is in target)
6920 // do not move children. So the opposite is: only move children if this
6921 // is not a reorder, or the teleport is disabled
6922 if (!isReorder || isTeleportDisabled(props)) {
6923 // Teleport has either Array children or no children.
6924 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6925 for (let i = 0; i < children.length; i++) {
6926 move(children[i], container, parentAnchor, 2 /* REORDER */);
6927 }
6928 }
6929 }
6930 // move main view anchor if this is a re-order.
6931 if (isReorder) {
6932 insert(anchor, container, parentAnchor);
6933 }
6934 }
6935 function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
6936 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
6937 if (target) {
6938 // if multiple teleports rendered to the same target element, we need to
6939 // pick up from where the last teleport finished instead of the first node
6940 const targetNode = target._lpa || target.firstChild;
6941 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
6942 if (isTeleportDisabled(vnode.props)) {
6943 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
6944 vnode.targetAnchor = targetNode;
6945 }
6946 else {
6947 vnode.anchor = nextSibling(node);
6948 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
6949 }
6950 target._lpa =
6951 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
6952 }
6953 }
6954 return vnode.anchor && nextSibling(vnode.anchor);
6955 }
6956 // Force-casted public typing for h and TSX props inference
6957 const Teleport = TeleportImpl;
6958
6959 const COMPONENTS = 'components';
6960 const DIRECTIVES = 'directives';
6961 /**
6962 * @private
6963 */
6964 function resolveComponent(name, maybeSelfReference) {
6965 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
6966 }
6967 const NULL_DYNAMIC_COMPONENT = Symbol();
6968 /**
6969 * @private
6970 */
6971 function resolveDynamicComponent(component) {
6972 if (isString(component)) {
6973 return resolveAsset(COMPONENTS, component, false) || component;
6974 }
6975 else {
6976 // invalid types will fallthrough to createVNode and raise warning
6977 return (component || NULL_DYNAMIC_COMPONENT);
6978 }
6979 }
6980 /**
6981 * @private
6982 */
6983 function resolveDirective(name) {
6984 return resolveAsset(DIRECTIVES, name);
6985 }
6986 // implementation
6987 function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
6988 const instance = currentRenderingInstance || currentInstance;
6989 if (instance) {
6990 const Component = instance.type;
6991 // explicit self name has highest priority
6992 if (type === COMPONENTS) {
6993 const selfName = getComponentName(Component);
6994 if (selfName &&
6995 (selfName === name ||
6996 selfName === camelize(name) ||
6997 selfName === capitalize(camelize(name)))) {
6998 return Component;
6999 }
7000 }
7001 const res =
7002 // local registration
7003 // check instance[type] first which is resolved for options API
7004 resolve(instance[type] || Component[type], name) ||
7005 // global registration
7006 resolve(instance.appContext[type], name);
7007 if (!res && maybeSelfReference) {
7008 // fallback to implicit self-reference
7009 return Component;
7010 }
7011 if (warnMissing && !res) {
7012 warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
7013 }
7014 return res;
7015 }
7016 else {
7017 warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
7018 `can only be used in render() or setup().`);
7019 }
7020 }
7021 function resolve(registry, name) {
7022 return (registry &&
7023 (registry[name] ||
7024 registry[camelize(name)] ||
7025 registry[capitalize(camelize(name))]));
7026 }
7027
7028 const Fragment = Symbol('Fragment' );
7029 const Text = Symbol('Text' );
7030 const Comment = Symbol('Comment' );
7031 const Static = Symbol('Static' );
7032 // Since v-if and v-for are the two possible ways node structure can dynamically
7033 // change, once we consider v-if branches and each v-for fragment a block, we
7034 // can divide a template into nested blocks, and within each block the node
7035 // structure would be stable. This allows us to skip most children diffing
7036 // and only worry about the dynamic nodes (indicated by patch flags).
7037 const blockStack = [];
7038 let currentBlock = null;
7039 /**
7040 * Open a block.
7041 * This must be called before `createBlock`. It cannot be part of `createBlock`
7042 * because the children of the block are evaluated before `createBlock` itself
7043 * is called. The generated code typically looks like this:
7044 *
7045 * ```js
7046 * function render() {
7047 * return (openBlock(),createBlock('div', null, [...]))
7048 * }
7049 * ```
7050 * disableTracking is true when creating a v-for fragment block, since a v-for
7051 * fragment always diffs its children.
7052 *
7053 * @private
7054 */
7055 function openBlock(disableTracking = false) {
7056 blockStack.push((currentBlock = disableTracking ? null : []));
7057 }
7058 function closeBlock() {
7059 blockStack.pop();
7060 currentBlock = blockStack[blockStack.length - 1] || null;
7061 }
7062 // Whether we should be tracking dynamic child nodes inside a block.
7063 // Only tracks when this value is > 0
7064 // We are not using a simple boolean because this value may need to be
7065 // incremented/decremented by nested usage of v-once (see below)
7066 let isBlockTreeEnabled = 1;
7067 /**
7068 * Block tracking sometimes needs to be disabled, for example during the
7069 * creation of a tree that needs to be cached by v-once. The compiler generates
7070 * code like this:
7071 *
7072 * ``` js
7073 * _cache[1] || (
7074 * setBlockTracking(-1),
7075 * _cache[1] = createVNode(...),
7076 * setBlockTracking(1),
7077 * _cache[1]
7078 * )
7079 * ```
7080 *
7081 * @private
7082 */
7083 function setBlockTracking(value) {
7084 isBlockTreeEnabled += value;
7085 }
7086 function setupBlock(vnode) {
7087 // save current block children on the block vnode
7088 vnode.dynamicChildren =
7089 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7090 // close block
7091 closeBlock();
7092 // a block is always going to be patched, so track it as a child of its
7093 // parent block
7094 if (isBlockTreeEnabled > 0 && currentBlock) {
7095 currentBlock.push(vnode);
7096 }
7097 return vnode;
7098 }
7099 /**
7100 * @private
7101 */
7102 function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
7103 return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
7104 }
7105 /**
7106 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7107 * A block root keeps track of dynamic nodes within the block in the
7108 * `dynamicChildren` array.
7109 *
7110 * @private
7111 */
7112 function createBlock(type, props, children, patchFlag, dynamicProps) {
7113 return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
7114 }
7115 function isVNode(value) {
7116 return value ? value.__v_isVNode === true : false;
7117 }
7118 function isSameVNodeType(n1, n2) {
7119 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7120 hmrDirtyComponents.has(n2.type)) {
7121 // HMR only: if the component has been hot-updated, force a reload.
7122 return false;
7123 }
7124 return n1.type === n2.type && n1.key === n2.key;
7125 }
7126 let vnodeArgsTransformer;
7127 /**
7128 * Internal API for registering an arguments transform for createVNode
7129 * used for creating stubs in the test-utils
7130 * It is *internal* but needs to be exposed for test-utils to pick up proper
7131 * typings
7132 */
7133 function transformVNodeArgs(transformer) {
7134 vnodeArgsTransformer = transformer;
7135 }
7136 const createVNodeWithArgsTransform = (...args) => {
7137 return _createVNode(...(vnodeArgsTransformer
7138 ? vnodeArgsTransformer(args, currentRenderingInstance)
7139 : args));
7140 };
7141 const InternalObjectKey = `__vInternal`;
7142 const normalizeKey = ({ key }) => key != null ? key : null;
7143 const normalizeRef = ({ ref }) => {
7144 return (ref != null
7145 ? isString(ref) || isRef(ref) || isFunction(ref)
7146 ? { i: currentRenderingInstance, r: ref }
7147 : ref
7148 : null);
7149 };
7150 function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
7151 const vnode = {
7152 __v_isVNode: true,
7153 __v_skip: true,
7154 type,
7155 props,
7156 key: props && normalizeKey(props),
7157 ref: props && normalizeRef(props),
7158 scopeId: currentScopeId,
7159 slotScopeIds: null,
7160 children,
7161 component: null,
7162 suspense: null,
7163 ssContent: null,
7164 ssFallback: null,
7165 dirs: null,
7166 transition: null,
7167 el: null,
7168 anchor: null,
7169 target: null,
7170 targetAnchor: null,
7171 staticCount: 0,
7172 shapeFlag,
7173 patchFlag,
7174 dynamicProps,
7175 dynamicChildren: null,
7176 appContext: null
7177 };
7178 if (needFullChildrenNormalization) {
7179 normalizeChildren(vnode, children);
7180 // normalize suspense children
7181 if (shapeFlag & 128 /* SUSPENSE */) {
7182 type.normalize(vnode);
7183 }
7184 }
7185 else if (children) {
7186 // compiled element vnode - if children is passed, only possible types are
7187 // string or Array.
7188 vnode.shapeFlag |= isString(children)
7189 ? 8 /* TEXT_CHILDREN */
7190 : 16 /* ARRAY_CHILDREN */;
7191 }
7192 // validate key
7193 if (vnode.key !== vnode.key) {
7194 warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7195 }
7196 // track vnode for block tree
7197 if (isBlockTreeEnabled > 0 &&
7198 // avoid a block node from tracking itself
7199 !isBlockNode &&
7200 // has current parent block
7201 currentBlock &&
7202 // presence of a patch flag indicates this node needs patching on updates.
7203 // component nodes also should always be patched, because even if the
7204 // component doesn't need to update, it needs to persist the instance on to
7205 // the next vnode so that it can be properly unmounted later.
7206 (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7207 // the EVENTS flag is only for hydration and if it is the only flag, the
7208 // vnode should not be considered dynamic due to handler caching.
7209 vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
7210 currentBlock.push(vnode);
7211 }
7212 return vnode;
7213 }
7214 const createVNode = (createVNodeWithArgsTransform );
7215 function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7216 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7217 if (!type) {
7218 warn$1(`Invalid vnode type when creating vnode: ${type}.`);
7219 }
7220 type = Comment;
7221 }
7222 if (isVNode(type)) {
7223 // createVNode receiving an existing vnode. This happens in cases like
7224 // <component :is="vnode"/>
7225 // #2078 make sure to merge refs during the clone instead of overwriting it
7226 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7227 if (children) {
7228 normalizeChildren(cloned, children);
7229 }
7230 return cloned;
7231 }
7232 // class component normalization.
7233 if (isClassComponent(type)) {
7234 type = type.__vccOpts;
7235 }
7236 // class & style normalization.
7237 if (props) {
7238 // for reactive or proxy objects, we need to clone it to enable mutation.
7239 props = guardReactiveProps(props);
7240 let { class: klass, style } = props;
7241 if (klass && !isString(klass)) {
7242 props.class = normalizeClass(klass);
7243 }
7244 if (isObject(style)) {
7245 // reactive state objects need to be cloned since they are likely to be
7246 // mutated
7247 if (isProxy(style) && !isArray(style)) {
7248 style = extend({}, style);
7249 }
7250 props.style = normalizeStyle(style);
7251 }
7252 }
7253 // encode the vnode type information into a bitmap
7254 const shapeFlag = isString(type)
7255 ? 1 /* ELEMENT */
7256 : isSuspense(type)
7257 ? 128 /* SUSPENSE */
7258 : isTeleport(type)
7259 ? 64 /* TELEPORT */
7260 : isObject(type)
7261 ? 4 /* STATEFUL_COMPONENT */
7262 : isFunction(type)
7263 ? 2 /* FUNCTIONAL_COMPONENT */
7264 : 0;
7265 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7266 type = toRaw(type);
7267 warn$1(`Vue received a Component which was made a reactive object. This can ` +
7268 `lead to unnecessary performance overhead, and should be avoided by ` +
7269 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7270 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7271 }
7272 return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
7273 }
7274 function guardReactiveProps(props) {
7275 if (!props)
7276 return null;
7277 return isProxy(props) || InternalObjectKey in props
7278 ? extend({}, props)
7279 : props;
7280 }
7281 function cloneVNode(vnode, extraProps, mergeRef = false) {
7282 // This is intentionally NOT using spread or extend to avoid the runtime
7283 // key enumeration cost.
7284 const { props, ref, patchFlag, children } = vnode;
7285 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7286 const cloned = {
7287 __v_isVNode: true,
7288 __v_skip: true,
7289 type: vnode.type,
7290 props: mergedProps,
7291 key: mergedProps && normalizeKey(mergedProps),
7292 ref: extraProps && extraProps.ref
7293 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7294 // if the vnode itself already has a ref, cloneVNode will need to merge
7295 // the refs so the single vnode can be set on multiple refs
7296 mergeRef && ref
7297 ? isArray(ref)
7298 ? ref.concat(normalizeRef(extraProps))
7299 : [ref, normalizeRef(extraProps)]
7300 : normalizeRef(extraProps)
7301 : ref,
7302 scopeId: vnode.scopeId,
7303 slotScopeIds: vnode.slotScopeIds,
7304 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7305 ? children.map(deepCloneVNode)
7306 : children,
7307 target: vnode.target,
7308 targetAnchor: vnode.targetAnchor,
7309 staticCount: vnode.staticCount,
7310 shapeFlag: vnode.shapeFlag,
7311 // if the vnode is cloned with extra props, we can no longer assume its
7312 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7313 // note: perserve flag for fragments since they use the flag for children
7314 // fast paths only.
7315 patchFlag: extraProps && vnode.type !== Fragment
7316 ? patchFlag === -1 // hoisted node
7317 ? 16 /* FULL_PROPS */
7318 : patchFlag | 16 /* FULL_PROPS */
7319 : patchFlag,
7320 dynamicProps: vnode.dynamicProps,
7321 dynamicChildren: vnode.dynamicChildren,
7322 appContext: vnode.appContext,
7323 dirs: vnode.dirs,
7324 transition: vnode.transition,
7325 // These should technically only be non-null on mounted VNodes. However,
7326 // they *should* be copied for kept-alive vnodes. So we just always copy
7327 // them since them being non-null during a mount doesn't affect the logic as
7328 // they will simply be overwritten.
7329 component: vnode.component,
7330 suspense: vnode.suspense,
7331 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7332 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7333 el: vnode.el,
7334 anchor: vnode.anchor
7335 };
7336 return cloned;
7337 }
7338 /**
7339 * Dev only, for HMR of hoisted vnodes reused in v-for
7340 * https://github.com/vitejs/vite/issues/2022
7341 */
7342 function deepCloneVNode(vnode) {
7343 const cloned = cloneVNode(vnode);
7344 if (isArray(vnode.children)) {
7345 cloned.children = vnode.children.map(deepCloneVNode);
7346 }
7347 return cloned;
7348 }
7349 /**
7350 * @private
7351 */
7352 function createTextVNode(text = ' ', flag = 0) {
7353 return createVNode(Text, null, text, flag);
7354 }
7355 /**
7356 * @private
7357 */
7358 function createStaticVNode(content, numberOfNodes) {
7359 // A static vnode can contain multiple stringified elements, and the number
7360 // of elements is necessary for hydration.
7361 const vnode = createVNode(Static, null, content);
7362 vnode.staticCount = numberOfNodes;
7363 return vnode;
7364 }
7365 /**
7366 * @private
7367 */
7368 function createCommentVNode(text = '',
7369 // when used as the v-else branch, the comment node must be created as a
7370 // block to ensure correct updates.
7371 asBlock = false) {
7372 return asBlock
7373 ? (openBlock(), createBlock(Comment, null, text))
7374 : createVNode(Comment, null, text);
7375 }
7376 function normalizeVNode(child) {
7377 if (child == null || typeof child === 'boolean') {
7378 // empty placeholder
7379 return createVNode(Comment);
7380 }
7381 else if (isArray(child)) {
7382 // fragment
7383 return createVNode(Fragment, null,
7384 // #3666, avoid reference pollution when reusing vnode
7385 child.slice());
7386 }
7387 else if (typeof child === 'object') {
7388 // already vnode, this should be the most common since compiled templates
7389 // always produce all-vnode children arrays
7390 return cloneIfMounted(child);
7391 }
7392 else {
7393 // strings and numbers
7394 return createVNode(Text, null, String(child));
7395 }
7396 }
7397 // optimized normalization for template-compiled render fns
7398 function cloneIfMounted(child) {
7399 return child.el === null || child.memo ? child : cloneVNode(child);
7400 }
7401 function normalizeChildren(vnode, children) {
7402 let type = 0;
7403 const { shapeFlag } = vnode;
7404 if (children == null) {
7405 children = null;
7406 }
7407 else if (isArray(children)) {
7408 type = 16 /* ARRAY_CHILDREN */;
7409 }
7410 else if (typeof children === 'object') {
7411 if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
7412 // Normalize slot to plain children for plain element and Teleport
7413 const slot = children.default;
7414 if (slot) {
7415 // _c marker is added by withCtx() indicating this is a compiled slot
7416 slot._c && (slot._d = false);
7417 normalizeChildren(vnode, slot());
7418 slot._c && (slot._d = true);
7419 }
7420 return;
7421 }
7422 else {
7423 type = 32 /* SLOTS_CHILDREN */;
7424 const slotFlag = children._;
7425 if (!slotFlag && !(InternalObjectKey in children)) {
7426 children._ctx = currentRenderingInstance;
7427 }
7428 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7429 // a child component receives forwarded slots from the parent.
7430 // its slot type is determined by its parent's slot type.
7431 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7432 children._ = 1 /* STABLE */;
7433 }
7434 else {
7435 children._ = 2 /* DYNAMIC */;
7436 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7437 }
7438 }
7439 }
7440 }
7441 else if (isFunction(children)) {
7442 children = { default: children, _ctx: currentRenderingInstance };
7443 type = 32 /* SLOTS_CHILDREN */;
7444 }
7445 else {
7446 children = String(children);
7447 // force teleport children to array so it can be moved around
7448 if (shapeFlag & 64 /* TELEPORT */) {
7449 type = 16 /* ARRAY_CHILDREN */;
7450 children = [createTextVNode(children)];
7451 }
7452 else {
7453 type = 8 /* TEXT_CHILDREN */;
7454 }
7455 }
7456 vnode.children = children;
7457 vnode.shapeFlag |= type;
7458 }
7459 function mergeProps(...args) {
7460 const ret = {};
7461 for (let i = 0; i < args.length; i++) {
7462 const toMerge = args[i];
7463 for (const key in toMerge) {
7464 if (key === 'class') {
7465 if (ret.class !== toMerge.class) {
7466 ret.class = normalizeClass([ret.class, toMerge.class]);
7467 }
7468 }
7469 else if (key === 'style') {
7470 ret.style = normalizeStyle([ret.style, toMerge.style]);
7471 }
7472 else if (isOn(key)) {
7473 const existing = ret[key];
7474 const incoming = toMerge[key];
7475 if (existing !== incoming) {
7476 ret[key] = existing
7477 ? [].concat(existing, incoming)
7478 : incoming;
7479 }
7480 }
7481 else if (key !== '') {
7482 ret[key] = toMerge[key];
7483 }
7484 }
7485 }
7486 return ret;
7487 }
7488
7489 /**
7490 * Actual implementation
7491 */
7492 function renderList(source, renderItem, cache, index) {
7493 let ret;
7494 const cached = (cache && cache[index]);
7495 if (isArray(source) || isString(source)) {
7496 ret = new Array(source.length);
7497 for (let i = 0, l = source.length; i < l; i++) {
7498 ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
7499 }
7500 }
7501 else if (typeof source === 'number') {
7502 if (!Number.isInteger(source)) {
7503 warn$1(`The v-for range expect an integer value but got ${source}.`);
7504 return [];
7505 }
7506 ret = new Array(source);
7507 for (let i = 0; i < source; i++) {
7508 ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
7509 }
7510 }
7511 else if (isObject(source)) {
7512 if (source[Symbol.iterator]) {
7513 ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
7514 }
7515 else {
7516 const keys = Object.keys(source);
7517 ret = new Array(keys.length);
7518 for (let i = 0, l = keys.length; i < l; i++) {
7519 const key = keys[i];
7520 ret[i] = renderItem(source[key], key, i, cached && cached[i]);
7521 }
7522 }
7523 }
7524 else {
7525 ret = [];
7526 }
7527 if (cache) {
7528 cache[index] = ret;
7529 }
7530 return ret;
7531 }
7532
7533 /**
7534 * Compiler runtime helper for creating dynamic slots object
7535 * @private
7536 */
7537 function createSlots(slots, dynamicSlots) {
7538 for (let i = 0; i < dynamicSlots.length; i++) {
7539 const slot = dynamicSlots[i];
7540 // array of dynamic slot generated by <template v-for="..." #[...]>
7541 if (isArray(slot)) {
7542 for (let j = 0; j < slot.length; j++) {
7543 slots[slot[j].name] = slot[j].fn;
7544 }
7545 }
7546 else if (slot) {
7547 // conditional single slot generated by <template v-if="..." #foo>
7548 slots[slot.name] = slot.fn;
7549 }
7550 }
7551 return slots;
7552 }
7553
7554 /**
7555 * Compiler runtime helper for rendering `<slot/>`
7556 * @private
7557 */
7558 function renderSlot(slots, name, props = {},
7559 // this is not a user-facing function, so the fallback is always generated by
7560 // the compiler and guaranteed to be a function returning an array
7561 fallback, noSlotted) {
7562 if (currentRenderingInstance.isCE) {
7563 return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
7564 }
7565 let slot = slots[name];
7566 if (slot && slot.length > 1) {
7567 warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
7568 `function. You need to mark this component with $dynamic-slots in the ` +
7569 `parent template.`);
7570 slot = () => [];
7571 }
7572 // a compiled slot disables block tracking by default to avoid manual
7573 // invocation interfering with template-based block tracking, but in
7574 // `renderSlot` we can be sure that it's template-based so we can force
7575 // enable it.
7576 if (slot && slot._c) {
7577 slot._d = false;
7578 }
7579 openBlock();
7580 const validSlotContent = slot && ensureValidVNode(slot(props));
7581 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
7582 ? 64 /* STABLE_FRAGMENT */
7583 : -2 /* BAIL */);
7584 if (!noSlotted && rendered.scopeId) {
7585 rendered.slotScopeIds = [rendered.scopeId + '-s'];
7586 }
7587 if (slot && slot._c) {
7588 slot._d = true;
7589 }
7590 return rendered;
7591 }
7592 function ensureValidVNode(vnodes) {
7593 return vnodes.some(child => {
7594 if (!isVNode(child))
7595 return true;
7596 if (child.type === Comment)
7597 return false;
7598 if (child.type === Fragment &&
7599 !ensureValidVNode(child.children))
7600 return false;
7601 return true;
7602 })
7603 ? vnodes
7604 : null;
7605 }
7606
7607 /**
7608 * For prefixing keys in v-on="obj" with "on"
7609 * @private
7610 */
7611 function toHandlers(obj) {
7612 const ret = {};
7613 if (!isObject(obj)) {
7614 warn$1(`v-on with no argument expects an object value.`);
7615 return ret;
7616 }
7617 for (const key in obj) {
7618 ret[toHandlerKey(key)] = obj[key];
7619 }
7620 return ret;
7621 }
7622
7623 /**
7624 * #2437 In Vue 3, functional components do not have a public instance proxy but
7625 * they exist in the internal parent chain. For code that relies on traversing
7626 * public $parent chains, skip functional ones and go to the parent instead.
7627 */
7628 const getPublicInstance = (i) => {
7629 if (!i)
7630 return null;
7631 if (isStatefulComponent(i))
7632 return getExposeProxy(i) || i.proxy;
7633 return getPublicInstance(i.parent);
7634 };
7635 const publicPropertiesMap = extend(Object.create(null), {
7636 $: i => i,
7637 $el: i => i.vnode.el,
7638 $data: i => i.data,
7639 $props: i => (shallowReadonly(i.props) ),
7640 $attrs: i => (shallowReadonly(i.attrs) ),
7641 $slots: i => (shallowReadonly(i.slots) ),
7642 $refs: i => (shallowReadonly(i.refs) ),
7643 $parent: i => getPublicInstance(i.parent),
7644 $root: i => getPublicInstance(i.root),
7645 $emit: i => i.emit,
7646 $options: i => (resolveMergedOptions(i) ),
7647 $forceUpdate: i => () => queueJob(i.update),
7648 $nextTick: i => nextTick.bind(i.proxy),
7649 $watch: i => (instanceWatch.bind(i) )
7650 });
7651 const PublicInstanceProxyHandlers = {
7652 get({ _: instance }, key) {
7653 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7654 // for internal formatters to know that this is a Vue instance
7655 if (key === '__isVue') {
7656 return true;
7657 }
7658 // prioritize <script setup> bindings during dev.
7659 // this allows even properties that start with _ or $ to be used - so that
7660 // it aligns with the production behavior where the render fn is inlined and
7661 // indeed has access to all declared variables.
7662 if (setupState !== EMPTY_OBJ &&
7663 setupState.__isScriptSetup &&
7664 hasOwn(setupState, key)) {
7665 return setupState[key];
7666 }
7667 // data / props / ctx
7668 // This getter gets called for every property access on the render context
7669 // during render and is a major hotspot. The most expensive part of this
7670 // is the multiple hasOwn() calls. It's much faster to do a simple property
7671 // access on a plain object, so we use an accessCache object (with null
7672 // prototype) to memoize what access type a key corresponds to.
7673 let normalizedProps;
7674 if (key[0] !== '$') {
7675 const n = accessCache[key];
7676 if (n !== undefined) {
7677 switch (n) {
7678 case 0 /* SETUP */:
7679 return setupState[key];
7680 case 1 /* DATA */:
7681 return data[key];
7682 case 3 /* CONTEXT */:
7683 return ctx[key];
7684 case 2 /* PROPS */:
7685 return props[key];
7686 // default: just fallthrough
7687 }
7688 }
7689 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7690 accessCache[key] = 0 /* SETUP */;
7691 return setupState[key];
7692 }
7693 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7694 accessCache[key] = 1 /* DATA */;
7695 return data[key];
7696 }
7697 else if (
7698 // only cache other properties when instance has declared (thus stable)
7699 // props
7700 (normalizedProps = instance.propsOptions[0]) &&
7701 hasOwn(normalizedProps, key)) {
7702 accessCache[key] = 2 /* PROPS */;
7703 return props[key];
7704 }
7705 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7706 accessCache[key] = 3 /* CONTEXT */;
7707 return ctx[key];
7708 }
7709 else if (shouldCacheAccess) {
7710 accessCache[key] = 4 /* OTHER */;
7711 }
7712 }
7713 const publicGetter = publicPropertiesMap[key];
7714 let cssModule, globalProperties;
7715 // public $xxx properties
7716 if (publicGetter) {
7717 if (key === '$attrs') {
7718 track(instance, "get" /* GET */, key);
7719 markAttrsAccessed();
7720 }
7721 return publicGetter(instance);
7722 }
7723 else if (
7724 // css module (injected by vue-loader)
7725 (cssModule = type.__cssModules) &&
7726 (cssModule = cssModule[key])) {
7727 return cssModule;
7728 }
7729 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7730 // user may set custom properties to `this` that start with `$`
7731 accessCache[key] = 3 /* CONTEXT */;
7732 return ctx[key];
7733 }
7734 else if (
7735 // global properties
7736 ((globalProperties = appContext.config.globalProperties),
7737 hasOwn(globalProperties, key))) {
7738 {
7739 return globalProperties[key];
7740 }
7741 }
7742 else if (currentRenderingInstance &&
7743 (!isString(key) ||
7744 // #1091 avoid internal isRef/isVNode checks on component instance leading
7745 // to infinite warning loop
7746 key.indexOf('__v') !== 0)) {
7747 if (data !== EMPTY_OBJ &&
7748 (key[0] === '$' || key[0] === '_') &&
7749 hasOwn(data, key)) {
7750 warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
7751 `character ("$" or "_") and is not proxied on the render context.`);
7752 }
7753 else if (instance === currentRenderingInstance) {
7754 warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
7755 `but is not defined on instance.`);
7756 }
7757 }
7758 },
7759 set({ _: instance }, key, value) {
7760 const { data, setupState, ctx } = instance;
7761 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7762 setupState[key] = value;
7763 }
7764 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7765 data[key] = value;
7766 }
7767 else if (hasOwn(instance.props, key)) {
7768 warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
7769 return false;
7770 }
7771 if (key[0] === '$' && key.slice(1) in instance) {
7772 warn$1(`Attempting to mutate public property "${key}". ` +
7773 `Properties starting with $ are reserved and readonly.`, instance);
7774 return false;
7775 }
7776 else {
7777 if (key in instance.appContext.config.globalProperties) {
7778 Object.defineProperty(ctx, key, {
7779 enumerable: true,
7780 configurable: true,
7781 value
7782 });
7783 }
7784 else {
7785 ctx[key] = value;
7786 }
7787 }
7788 return true;
7789 },
7790 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
7791 let normalizedProps;
7792 return (accessCache[key] !== undefined ||
7793 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
7794 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
7795 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
7796 hasOwn(ctx, key) ||
7797 hasOwn(publicPropertiesMap, key) ||
7798 hasOwn(appContext.config.globalProperties, key));
7799 }
7800 };
7801 {
7802 PublicInstanceProxyHandlers.ownKeys = (target) => {
7803 warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
7804 `The keys will be empty in production mode to avoid performance overhead.`);
7805 return Reflect.ownKeys(target);
7806 };
7807 }
7808 const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
7809 get(target, key) {
7810 // fast path for unscopables when using `with` block
7811 if (key === Symbol.unscopables) {
7812 return;
7813 }
7814 return PublicInstanceProxyHandlers.get(target, key, target);
7815 },
7816 has(_, key) {
7817 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
7818 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
7819 warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
7820 }
7821 return has;
7822 }
7823 });
7824 // dev only
7825 // In dev mode, the proxy target exposes the same properties as seen on `this`
7826 // for easier console inspection. In prod mode it will be an empty object so
7827 // these properties definitions can be skipped.
7828 function createDevRenderContext(instance) {
7829 const target = {};
7830 // expose internal instance for proxy handlers
7831 Object.defineProperty(target, `_`, {
7832 configurable: true,
7833 enumerable: false,
7834 get: () => instance
7835 });
7836 // expose public properties
7837 Object.keys(publicPropertiesMap).forEach(key => {
7838 Object.defineProperty(target, key, {
7839 configurable: true,
7840 enumerable: false,
7841 get: () => publicPropertiesMap[key](instance),
7842 // intercepted by the proxy so no need for implementation,
7843 // but needed to prevent set errors
7844 set: NOOP
7845 });
7846 });
7847 return target;
7848 }
7849 // dev only
7850 function exposePropsOnRenderContext(instance) {
7851 const { ctx, propsOptions: [propsOptions] } = instance;
7852 if (propsOptions) {
7853 Object.keys(propsOptions).forEach(key => {
7854 Object.defineProperty(ctx, key, {
7855 enumerable: true,
7856 configurable: true,
7857 get: () => instance.props[key],
7858 set: NOOP
7859 });
7860 });
7861 }
7862 }
7863 // dev only
7864 function exposeSetupStateOnRenderContext(instance) {
7865 const { ctx, setupState } = instance;
7866 Object.keys(toRaw(setupState)).forEach(key => {
7867 if (!setupState.__isScriptSetup && (key[0] === '$' || key[0] === '_')) {
7868 warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
7869 `which are reserved prefixes for Vue internals.`);
7870 return;
7871 }
7872 Object.defineProperty(ctx, key, {
7873 enumerable: true,
7874 configurable: true,
7875 get: () => setupState[key],
7876 set: NOOP
7877 });
7878 });
7879 }
7880
7881 const emptyAppContext = createAppContext();
7882 let uid$1 = 0;
7883 function createComponentInstance(vnode, parent, suspense) {
7884 const type = vnode.type;
7885 // inherit parent app context - or - if root, adopt from root vnode
7886 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
7887 const instance = {
7888 uid: uid$1++,
7889 vnode,
7890 type,
7891 parent,
7892 appContext,
7893 root: null,
7894 next: null,
7895 subTree: null,
7896 update: null,
7897 scope: new EffectScope(true /* detached */),
7898 render: null,
7899 proxy: null,
7900 exposed: null,
7901 exposeProxy: null,
7902 withProxy: null,
7903 provides: parent ? parent.provides : Object.create(appContext.provides),
7904 accessCache: null,
7905 renderCache: [],
7906 // local resovled assets
7907 components: null,
7908 directives: null,
7909 // resolved props and emits options
7910 propsOptions: normalizePropsOptions(type, appContext),
7911 emitsOptions: normalizeEmitsOptions(type, appContext),
7912 // emit
7913 emit: null,
7914 emitted: null,
7915 // props default value
7916 propsDefaults: EMPTY_OBJ,
7917 // inheritAttrs
7918 inheritAttrs: type.inheritAttrs,
7919 // state
7920 ctx: EMPTY_OBJ,
7921 data: EMPTY_OBJ,
7922 props: EMPTY_OBJ,
7923 attrs: EMPTY_OBJ,
7924 slots: EMPTY_OBJ,
7925 refs: EMPTY_OBJ,
7926 setupState: EMPTY_OBJ,
7927 setupContext: null,
7928 // suspense related
7929 suspense,
7930 suspenseId: suspense ? suspense.pendingId : 0,
7931 asyncDep: null,
7932 asyncResolved: false,
7933 // lifecycle hooks
7934 // not using enums here because it results in computed properties
7935 isMounted: false,
7936 isUnmounted: false,
7937 isDeactivated: false,
7938 bc: null,
7939 c: null,
7940 bm: null,
7941 m: null,
7942 bu: null,
7943 u: null,
7944 um: null,
7945 bum: null,
7946 da: null,
7947 a: null,
7948 rtg: null,
7949 rtc: null,
7950 ec: null,
7951 sp: null
7952 };
7953 {
7954 instance.ctx = createDevRenderContext(instance);
7955 }
7956 instance.root = parent ? parent.root : instance;
7957 instance.emit = emit.bind(null, instance);
7958 // apply custom element special handling
7959 if (vnode.ce) {
7960 vnode.ce(instance);
7961 }
7962 return instance;
7963 }
7964 let currentInstance = null;
7965 const getCurrentInstance = () => currentInstance || currentRenderingInstance;
7966 const setCurrentInstance = (instance) => {
7967 currentInstance = instance;
7968 instance.scope.on();
7969 };
7970 const unsetCurrentInstance = () => {
7971 currentInstance && currentInstance.scope.off();
7972 currentInstance = null;
7973 };
7974 const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
7975 function validateComponentName(name, config) {
7976 const appIsNativeTag = config.isNativeTag || NO;
7977 if (isBuiltInTag(name) || appIsNativeTag(name)) {
7978 warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
7979 }
7980 }
7981 function isStatefulComponent(instance) {
7982 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
7983 }
7984 let isInSSRComponentSetup = false;
7985 function setupComponent(instance, isSSR = false) {
7986 isInSSRComponentSetup = isSSR;
7987 const { props, children } = instance.vnode;
7988 const isStateful = isStatefulComponent(instance);
7989 initProps(instance, props, isStateful, isSSR);
7990 initSlots(instance, children);
7991 const setupResult = isStateful
7992 ? setupStatefulComponent(instance, isSSR)
7993 : undefined;
7994 isInSSRComponentSetup = false;
7995 return setupResult;
7996 }
7997 function setupStatefulComponent(instance, isSSR) {
7998 const Component = instance.type;
7999 {
8000 if (Component.name) {
8001 validateComponentName(Component.name, instance.appContext.config);
8002 }
8003 if (Component.components) {
8004 const names = Object.keys(Component.components);
8005 for (let i = 0; i < names.length; i++) {
8006 validateComponentName(names[i], instance.appContext.config);
8007 }
8008 }
8009 if (Component.directives) {
8010 const names = Object.keys(Component.directives);
8011 for (let i = 0; i < names.length; i++) {
8012 validateDirectiveName(names[i]);
8013 }
8014 }
8015 if (Component.compilerOptions && isRuntimeOnly()) {
8016 warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
8017 `includes the runtime compiler. Since you are using a runtime-only ` +
8018 `build, the options should be passed via your build tool config instead.`);
8019 }
8020 }
8021 // 0. create render proxy property access cache
8022 instance.accessCache = Object.create(null);
8023 // 1. create public instance / render proxy
8024 // also mark it raw so it's never observed
8025 instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
8026 {
8027 exposePropsOnRenderContext(instance);
8028 }
8029 // 2. call setup()
8030 const { setup } = Component;
8031 if (setup) {
8032 const setupContext = (instance.setupContext =
8033 setup.length > 1 ? createSetupContext(instance) : null);
8034 setCurrentInstance(instance);
8035 pauseTracking();
8036 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8037 resetTracking();
8038 unsetCurrentInstance();
8039 if (isPromise(setupResult)) {
8040 setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
8041 if (isSSR) {
8042 // return the promise so server-renderer can wait on it
8043 return setupResult
8044 .then((resolvedResult) => {
8045 handleSetupResult(instance, resolvedResult, isSSR);
8046 })
8047 .catch(e => {
8048 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8049 });
8050 }
8051 else {
8052 // async setup returned Promise.
8053 // bail here and wait for re-entry.
8054 instance.asyncDep = setupResult;
8055 }
8056 }
8057 else {
8058 handleSetupResult(instance, setupResult, isSSR);
8059 }
8060 }
8061 else {
8062 finishComponentSetup(instance, isSSR);
8063 }
8064 }
8065 function handleSetupResult(instance, setupResult, isSSR) {
8066 if (isFunction(setupResult)) {
8067 // setup returned an inline render function
8068 {
8069 instance.render = setupResult;
8070 }
8071 }
8072 else if (isObject(setupResult)) {
8073 if (isVNode(setupResult)) {
8074 warn$1(`setup() should not return VNodes directly - ` +
8075 `return a render function instead.`);
8076 }
8077 // setup returned bindings.
8078 // assuming a render function compiled from template is present.
8079 {
8080 instance.devtoolsRawSetupState = setupResult;
8081 }
8082 instance.setupState = proxyRefs(setupResult);
8083 {
8084 exposeSetupStateOnRenderContext(instance);
8085 }
8086 }
8087 else if (setupResult !== undefined) {
8088 warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8089 }
8090 finishComponentSetup(instance, isSSR);
8091 }
8092 let compile;
8093 let installWithProxy;
8094 /**
8095 * For runtime-dom to register the compiler.
8096 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8097 */
8098 function registerRuntimeCompiler(_compile) {
8099 compile = _compile;
8100 installWithProxy = i => {
8101 if (i.render._rc) {
8102 i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8103 }
8104 };
8105 }
8106 // dev only
8107 const isRuntimeOnly = () => !compile;
8108 function finishComponentSetup(instance, isSSR, skipOptions) {
8109 const Component = instance.type;
8110 // template / render function normalization
8111 if (!instance.render) {
8112 // could be set from setup()
8113 if (compile && !Component.render) {
8114 const template = Component.template;
8115 if (template) {
8116 {
8117 startMeasure(instance, `compile`);
8118 }
8119 const { isCustomElement, compilerOptions } = instance.appContext.config;
8120 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8121 const finalCompilerOptions = extend(extend({
8122 isCustomElement,
8123 delimiters
8124 }, compilerOptions), componentCompilerOptions);
8125 Component.render = compile(template, finalCompilerOptions);
8126 {
8127 endMeasure(instance, `compile`);
8128 }
8129 }
8130 }
8131 instance.render = (Component.render || NOOP);
8132 // for runtime-compiled render functions using `with` blocks, the render
8133 // proxy used needs a different `has` handler which is more performant and
8134 // also only allows a whitelist of globals to fallthrough.
8135 if (installWithProxy) {
8136 installWithProxy(instance);
8137 }
8138 }
8139 // support for 2.x options
8140 {
8141 setCurrentInstance(instance);
8142 pauseTracking();
8143 applyOptions(instance);
8144 resetTracking();
8145 unsetCurrentInstance();
8146 }
8147 // warn missing template/render
8148 // the runtime compilation of template in SSR is done by server-render
8149 if (!Component.render && instance.render === NOOP && !isSSR) {
8150 /* istanbul ignore if */
8151 if (!compile && Component.template) {
8152 warn$1(`Component provided template option but ` +
8153 `runtime compilation is not supported in this build of Vue.` +
8154 (` Use "vue.global.js" instead.`
8155 ) /* should not happen */);
8156 }
8157 else {
8158 warn$1(`Component is missing template or render function.`);
8159 }
8160 }
8161 }
8162 function createAttrsProxy(instance) {
8163 return new Proxy(instance.attrs, {
8164 get(target, key) {
8165 markAttrsAccessed();
8166 track(instance, "get" /* GET */, '$attrs');
8167 return target[key];
8168 },
8169 set() {
8170 warn$1(`setupContext.attrs is readonly.`);
8171 return false;
8172 },
8173 deleteProperty() {
8174 warn$1(`setupContext.attrs is readonly.`);
8175 return false;
8176 }
8177 }
8178 );
8179 }
8180 function createSetupContext(instance) {
8181 const expose = exposed => {
8182 if (instance.exposed) {
8183 warn$1(`expose() should be called only once per setup().`);
8184 }
8185 instance.exposed = exposed || {};
8186 };
8187 let attrs;
8188 {
8189 // We use getters in dev in case libs like test-utils overwrite instance
8190 // properties (overwrites should not be done in prod)
8191 return Object.freeze({
8192 get attrs() {
8193 return attrs || (attrs = createAttrsProxy(instance));
8194 },
8195 get slots() {
8196 return shallowReadonly(instance.slots);
8197 },
8198 get emit() {
8199 return (event, ...args) => instance.emit(event, ...args);
8200 },
8201 expose
8202 });
8203 }
8204 }
8205 function getExposeProxy(instance) {
8206 if (instance.exposed) {
8207 return (instance.exposeProxy ||
8208 (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
8209 get(target, key) {
8210 if (key in target) {
8211 return target[key];
8212 }
8213 else if (key in publicPropertiesMap) {
8214 return publicPropertiesMap[key](instance);
8215 }
8216 }
8217 })));
8218 }
8219 }
8220 const classifyRE = /(?:^|[-_])(\w)/g;
8221 const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8222 function getComponentName(Component) {
8223 return isFunction(Component)
8224 ? Component.displayName || Component.name
8225 : Component.name;
8226 }
8227 /* istanbul ignore next */
8228 function formatComponentName(instance, Component, isRoot = false) {
8229 let name = getComponentName(Component);
8230 if (!name && Component.__file) {
8231 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8232 if (match) {
8233 name = match[1];
8234 }
8235 }
8236 if (!name && instance && instance.parent) {
8237 // try to infer the name based on reverse resolution
8238 const inferFromRegistry = (registry) => {
8239 for (const key in registry) {
8240 if (registry[key] === Component) {
8241 return key;
8242 }
8243 }
8244 };
8245 name =
8246 inferFromRegistry(instance.components ||
8247 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8248 }
8249 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8250 }
8251 function isClassComponent(value) {
8252 return isFunction(value) && '__vccOpts' in value;
8253 }
8254
8255 const stack = [];
8256 function pushWarningContext(vnode) {
8257 stack.push(vnode);
8258 }
8259 function popWarningContext() {
8260 stack.pop();
8261 }
8262 function warn$1(msg, ...args) {
8263 // avoid props formatting or warn handler tracking deps that might be mutated
8264 // during patch, leading to infinite recursion.
8265 pauseTracking();
8266 const instance = stack.length ? stack[stack.length - 1].component : null;
8267 const appWarnHandler = instance && instance.appContext.config.warnHandler;
8268 const trace = getComponentTrace();
8269 if (appWarnHandler) {
8270 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
8271 msg + args.join(''),
8272 instance && instance.proxy,
8273 trace
8274 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
8275 .join('\n'),
8276 trace
8277 ]);
8278 }
8279 else {
8280 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
8281 /* istanbul ignore if */
8282 if (trace.length &&
8283 // avoid spamming console during tests
8284 !false) {
8285 warnArgs.push(`\n`, ...formatTrace(trace));
8286 }
8287 console.warn(...warnArgs);
8288 }
8289 resetTracking();
8290 }
8291 function getComponentTrace() {
8292 let currentVNode = stack[stack.length - 1];
8293 if (!currentVNode) {
8294 return [];
8295 }
8296 // we can't just use the stack because it will be incomplete during updates
8297 // that did not start from the root. Re-construct the parent chain using
8298 // instance parent pointers.
8299 const normalizedStack = [];
8300 while (currentVNode) {
8301 const last = normalizedStack[0];
8302 if (last && last.vnode === currentVNode) {
8303 last.recurseCount++;
8304 }
8305 else {
8306 normalizedStack.push({
8307 vnode: currentVNode,
8308 recurseCount: 0
8309 });
8310 }
8311 const parentInstance = currentVNode.component && currentVNode.component.parent;
8312 currentVNode = parentInstance && parentInstance.vnode;
8313 }
8314 return normalizedStack;
8315 }
8316 /* istanbul ignore next */
8317 function formatTrace(trace) {
8318 const logs = [];
8319 trace.forEach((entry, i) => {
8320 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
8321 });
8322 return logs;
8323 }
8324 function formatTraceEntry({ vnode, recurseCount }) {
8325 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
8326 const isRoot = vnode.component ? vnode.component.parent == null : false;
8327 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
8328 const close = `>` + postfix;
8329 return vnode.props
8330 ? [open, ...formatProps(vnode.props), close]
8331 : [open + close];
8332 }
8333 /* istanbul ignore next */
8334 function formatProps(props) {
8335 const res = [];
8336 const keys = Object.keys(props);
8337 keys.slice(0, 3).forEach(key => {
8338 res.push(...formatProp(key, props[key]));
8339 });
8340 if (keys.length > 3) {
8341 res.push(` ...`);
8342 }
8343 return res;
8344 }
8345 /* istanbul ignore next */
8346 function formatProp(key, value, raw) {
8347 if (isString(value)) {
8348 value = JSON.stringify(value);
8349 return raw ? value : [`${key}=${value}`];
8350 }
8351 else if (typeof value === 'number' ||
8352 typeof value === 'boolean' ||
8353 value == null) {
8354 return raw ? value : [`${key}=${value}`];
8355 }
8356 else if (isRef(value)) {
8357 value = formatProp(key, toRaw(value.value), true);
8358 return raw ? value : [`${key}=Ref<`, value, `>`];
8359 }
8360 else if (isFunction(value)) {
8361 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
8362 }
8363 else {
8364 value = toRaw(value);
8365 return raw ? value : [`${key}=`, value];
8366 }
8367 }
8368
8369 const ErrorTypeStrings = {
8370 ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
8371 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
8372 ["c" /* CREATED */]: 'created hook',
8373 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
8374 ["m" /* MOUNTED */]: 'mounted hook',
8375 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
8376 ["u" /* UPDATED */]: 'updated',
8377 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
8378 ["um" /* UNMOUNTED */]: 'unmounted hook',
8379 ["a" /* ACTIVATED */]: 'activated hook',
8380 ["da" /* DEACTIVATED */]: 'deactivated hook',
8381 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
8382 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
8383 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
8384 [0 /* SETUP_FUNCTION */]: 'setup function',
8385 [1 /* RENDER_FUNCTION */]: 'render function',
8386 [2 /* WATCH_GETTER */]: 'watcher getter',
8387 [3 /* WATCH_CALLBACK */]: 'watcher callback',
8388 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
8389 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
8390 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
8391 [7 /* VNODE_HOOK */]: 'vnode hook',
8392 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
8393 [9 /* TRANSITION_HOOK */]: 'transition hook',
8394 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
8395 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
8396 [12 /* FUNCTION_REF */]: 'ref function',
8397 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
8398 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
8399 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
8400 };
8401 function callWithErrorHandling(fn, instance, type, args) {
8402 let res;
8403 try {
8404 res = args ? fn(...args) : fn();
8405 }
8406 catch (err) {
8407 handleError(err, instance, type);
8408 }
8409 return res;
8410 }
8411 function callWithAsyncErrorHandling(fn, instance, type, args) {
8412 if (isFunction(fn)) {
8413 const res = callWithErrorHandling(fn, instance, type, args);
8414 if (res && isPromise(res)) {
8415 res.catch(err => {
8416 handleError(err, instance, type);
8417 });
8418 }
8419 return res;
8420 }
8421 const values = [];
8422 for (let i = 0; i < fn.length; i++) {
8423 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
8424 }
8425 return values;
8426 }
8427 function handleError(err, instance, type, throwInDev = true) {
8428 const contextVNode = instance ? instance.vnode : null;
8429 if (instance) {
8430 let cur = instance.parent;
8431 // the exposed instance is the render proxy to keep it consistent with 2.x
8432 const exposedInstance = instance.proxy;
8433 // in production the hook receives only the error code
8434 const errorInfo = ErrorTypeStrings[type] ;
8435 while (cur) {
8436 const errorCapturedHooks = cur.ec;
8437 if (errorCapturedHooks) {
8438 for (let i = 0; i < errorCapturedHooks.length; i++) {
8439 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
8440 return;
8441 }
8442 }
8443 }
8444 cur = cur.parent;
8445 }
8446 // app-level handling
8447 const appErrorHandler = instance.appContext.config.errorHandler;
8448 if (appErrorHandler) {
8449 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
8450 return;
8451 }
8452 }
8453 logError(err, type, contextVNode, throwInDev);
8454 }
8455 function logError(err, type, contextVNode, throwInDev = true) {
8456 {
8457 const info = ErrorTypeStrings[type];
8458 if (contextVNode) {
8459 pushWarningContext(contextVNode);
8460 }
8461 warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
8462 if (contextVNode) {
8463 popWarningContext();
8464 }
8465 // crash in dev by default so it's more noticeable
8466 if (throwInDev) {
8467 throw err;
8468 }
8469 else {
8470 console.error(err);
8471 }
8472 }
8473 }
8474
8475 let isFlushing = false;
8476 let isFlushPending = false;
8477 const queue = [];
8478 let flushIndex = 0;
8479 const pendingPreFlushCbs = [];
8480 let activePreFlushCbs = null;
8481 let preFlushIndex = 0;
8482 const pendingPostFlushCbs = [];
8483 let activePostFlushCbs = null;
8484 let postFlushIndex = 0;
8485 const resolvedPromise = Promise.resolve();
8486 let currentFlushPromise = null;
8487 let currentPreFlushParentJob = null;
8488 const RECURSION_LIMIT = 100;
8489 function nextTick(fn) {
8490 const p = currentFlushPromise || resolvedPromise;
8491 return fn ? p.then(this ? fn.bind(this) : fn) : p;
8492 }
8493 // #2768
8494 // Use binary-search to find a suitable position in the queue,
8495 // so that the queue maintains the increasing order of job's id,
8496 // which can prevent the job from being skipped and also can avoid repeated patching.
8497 function findInsertionIndex(id) {
8498 // the start index should be `flushIndex + 1`
8499 let start = flushIndex + 1;
8500 let end = queue.length;
8501 while (start < end) {
8502 const middle = (start + end) >>> 1;
8503 const middleJobId = getId(queue[middle]);
8504 middleJobId < id ? (start = middle + 1) : (end = middle);
8505 }
8506 return start;
8507 }
8508 function queueJob(job) {
8509 // the dedupe search uses the startIndex argument of Array.includes()
8510 // by default the search index includes the current job that is being run
8511 // so it cannot recursively trigger itself again.
8512 // if the job is a watch() callback, the search will start with a +1 index to
8513 // allow it recursively trigger itself - it is the user's responsibility to
8514 // ensure it doesn't end up in an infinite loop.
8515 if ((!queue.length ||
8516 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
8517 job !== currentPreFlushParentJob) {
8518 if (job.id == null) {
8519 queue.push(job);
8520 }
8521 else {
8522 queue.splice(findInsertionIndex(job.id), 0, job);
8523 }
8524 queueFlush();
8525 }
8526 }
8527 function queueFlush() {
8528 if (!isFlushing && !isFlushPending) {
8529 isFlushPending = true;
8530 currentFlushPromise = resolvedPromise.then(flushJobs);
8531 }
8532 }
8533 function invalidateJob(job) {
8534 const i = queue.indexOf(job);
8535 if (i > flushIndex) {
8536 queue.splice(i, 1);
8537 }
8538 }
8539 function queueCb(cb, activeQueue, pendingQueue, index) {
8540 if (!isArray(cb)) {
8541 if (!activeQueue ||
8542 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
8543 pendingQueue.push(cb);
8544 }
8545 }
8546 else {
8547 // if cb is an array, it is a component lifecycle hook which can only be
8548 // triggered by a job, which is already deduped in the main queue, so
8549 // we can skip duplicate check here to improve perf
8550 pendingQueue.push(...cb);
8551 }
8552 queueFlush();
8553 }
8554 function queuePreFlushCb(cb) {
8555 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
8556 }
8557 function queuePostFlushCb(cb) {
8558 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
8559 }
8560 function flushPreFlushCbs(seen, parentJob = null) {
8561 if (pendingPreFlushCbs.length) {
8562 currentPreFlushParentJob = parentJob;
8563 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
8564 pendingPreFlushCbs.length = 0;
8565 {
8566 seen = seen || new Map();
8567 }
8568 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
8569 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
8570 continue;
8571 }
8572 activePreFlushCbs[preFlushIndex]();
8573 }
8574 activePreFlushCbs = null;
8575 preFlushIndex = 0;
8576 currentPreFlushParentJob = null;
8577 // recursively flush until it drains
8578 flushPreFlushCbs(seen, parentJob);
8579 }
8580 }
8581 function flushPostFlushCbs(seen) {
8582 if (pendingPostFlushCbs.length) {
8583 const deduped = [...new Set(pendingPostFlushCbs)];
8584 pendingPostFlushCbs.length = 0;
8585 // #1947 already has active queue, nested flushPostFlushCbs call
8586 if (activePostFlushCbs) {
8587 activePostFlushCbs.push(...deduped);
8588 return;
8589 }
8590 activePostFlushCbs = deduped;
8591 {
8592 seen = seen || new Map();
8593 }
8594 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
8595 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
8596 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
8597 continue;
8598 }
8599 activePostFlushCbs[postFlushIndex]();
8600 }
8601 activePostFlushCbs = null;
8602 postFlushIndex = 0;
8603 }
8604 }
8605 const getId = (job) => job.id == null ? Infinity : job.id;
8606 function flushJobs(seen) {
8607 isFlushPending = false;
8608 isFlushing = true;
8609 {
8610 seen = seen || new Map();
8611 }
8612 flushPreFlushCbs(seen);
8613 // Sort queue before flush.
8614 // This ensures that:
8615 // 1. Components are updated from parent to child. (because parent is always
8616 // created before the child so its render effect will have smaller
8617 // priority number)
8618 // 2. If a component is unmounted during a parent component's update,
8619 // its update can be skipped.
8620 queue.sort((a, b) => getId(a) - getId(b));
8621 try {
8622 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
8623 const job = queue[flushIndex];
8624 if (job && job.active !== false) {
8625 if (true && checkRecursiveUpdates(seen, job)) {
8626 continue;
8627 }
8628 // console.log(`running:`, job.id)
8629 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
8630 }
8631 }
8632 }
8633 finally {
8634 flushIndex = 0;
8635 queue.length = 0;
8636 flushPostFlushCbs(seen);
8637 isFlushing = false;
8638 currentFlushPromise = null;
8639 // some postFlushCb queued jobs!
8640 // keep flushing until it drains.
8641 if (queue.length ||
8642 pendingPreFlushCbs.length ||
8643 pendingPostFlushCbs.length) {
8644 flushJobs(seen);
8645 }
8646 }
8647 }
8648 function checkRecursiveUpdates(seen, fn) {
8649 if (!seen.has(fn)) {
8650 seen.set(fn, 1);
8651 }
8652 else {
8653 const count = seen.get(fn);
8654 if (count > RECURSION_LIMIT) {
8655 const instance = fn.ownerInstance;
8656 const componentName = instance && getComponentName(instance.type);
8657 warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
8658 `This means you have a reactive effect that is mutating its own ` +
8659 `dependencies and thus recursively triggering itself. Possible sources ` +
8660 `include component template, render function, updated hook or ` +
8661 `watcher source function.`);
8662 return true;
8663 }
8664 else {
8665 seen.set(fn, count + 1);
8666 }
8667 }
8668 }
8669
8670 // Simple effect.
8671 function watchEffect(effect, options) {
8672 return doWatch(effect, null, options);
8673 }
8674 function watchPostEffect(effect, options) {
8675 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
8676 ));
8677 }
8678 function watchSyncEffect(effect, options) {
8679 return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
8680 ));
8681 }
8682 // initial value for watchers to trigger on undefined initial values
8683 const INITIAL_WATCHER_VALUE = {};
8684 // implementation
8685 function watch(source, cb, options) {
8686 if (!isFunction(cb)) {
8687 warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
8688 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
8689 `supports \`watch(source, cb, options?) signature.`);
8690 }
8691 return doWatch(source, cb, options);
8692 }
8693 function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
8694 if (!cb) {
8695 if (immediate !== undefined) {
8696 warn$1(`watch() "immediate" option is only respected when using the ` +
8697 `watch(source, callback, options?) signature.`);
8698 }
8699 if (deep !== undefined) {
8700 warn$1(`watch() "deep" option is only respected when using the ` +
8701 `watch(source, callback, options?) signature.`);
8702 }
8703 }
8704 const warnInvalidSource = (s) => {
8705 warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
8706 `a reactive object, or an array of these types.`);
8707 };
8708 const instance = currentInstance;
8709 let getter;
8710 let forceTrigger = false;
8711 let isMultiSource = false;
8712 if (isRef(source)) {
8713 getter = () => source.value;
8714 forceTrigger = !!source._shallow;
8715 }
8716 else if (isReactive(source)) {
8717 getter = () => source;
8718 deep = true;
8719 }
8720 else if (isArray(source)) {
8721 isMultiSource = true;
8722 forceTrigger = source.some(isReactive);
8723 getter = () => source.map(s => {
8724 if (isRef(s)) {
8725 return s.value;
8726 }
8727 else if (isReactive(s)) {
8728 return traverse(s);
8729 }
8730 else if (isFunction(s)) {
8731 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
8732 }
8733 else {
8734 warnInvalidSource(s);
8735 }
8736 });
8737 }
8738 else if (isFunction(source)) {
8739 if (cb) {
8740 // getter with cb
8741 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
8742 }
8743 else {
8744 // no cb -> simple effect
8745 getter = () => {
8746 if (instance && instance.isUnmounted) {
8747 return;
8748 }
8749 if (cleanup) {
8750 cleanup();
8751 }
8752 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
8753 };
8754 }
8755 }
8756 else {
8757 getter = NOOP;
8758 warnInvalidSource(source);
8759 }
8760 if (cb && deep) {
8761 const baseGetter = getter;
8762 getter = () => traverse(baseGetter());
8763 }
8764 let cleanup;
8765 let onInvalidate = (fn) => {
8766 cleanup = effect.onStop = () => {
8767 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
8768 };
8769 };
8770 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
8771 const job = () => {
8772 if (!effect.active) {
8773 return;
8774 }
8775 if (cb) {
8776 // watch(source, cb)
8777 const newValue = effect.run();
8778 if (deep ||
8779 forceTrigger ||
8780 (isMultiSource
8781 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
8782 : hasChanged(newValue, oldValue)) ||
8783 (false )) {
8784 // cleanup before running cb again
8785 if (cleanup) {
8786 cleanup();
8787 }
8788 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
8789 newValue,
8790 // pass undefined as the old value when it's changed for the first time
8791 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
8792 onInvalidate
8793 ]);
8794 oldValue = newValue;
8795 }
8796 }
8797 else {
8798 // watchEffect
8799 effect.run();
8800 }
8801 };
8802 // important: mark the job as a watcher callback so that scheduler knows
8803 // it is allowed to self-trigger (#1727)
8804 job.allowRecurse = !!cb;
8805 let scheduler;
8806 if (flush === 'sync') {
8807 scheduler = job; // the scheduler function gets called directly
8808 }
8809 else if (flush === 'post') {
8810 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
8811 }
8812 else {
8813 // default: 'pre'
8814 scheduler = () => {
8815 if (!instance || instance.isMounted) {
8816 queuePreFlushCb(job);
8817 }
8818 else {
8819 // with 'pre' option, the first call must happen before
8820 // the component is mounted so it is called synchronously.
8821 job();
8822 }
8823 };
8824 }
8825 const effect = new ReactiveEffect(getter, scheduler);
8826 {
8827 effect.onTrack = onTrack;
8828 effect.onTrigger = onTrigger;
8829 }
8830 // initial run
8831 if (cb) {
8832 if (immediate) {
8833 job();
8834 }
8835 else {
8836 oldValue = effect.run();
8837 }
8838 }
8839 else if (flush === 'post') {
8840 queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
8841 }
8842 else {
8843 effect.run();
8844 }
8845 return () => {
8846 effect.stop();
8847 if (instance && instance.scope) {
8848 remove(instance.scope.effects, effect);
8849 }
8850 };
8851 }
8852 // this.$watch
8853 function instanceWatch(source, value, options) {
8854 const publicThis = this.proxy;
8855 const getter = isString(source)
8856 ? source.includes('.')
8857 ? createPathGetter(publicThis, source)
8858 : () => publicThis[source]
8859 : source.bind(publicThis, publicThis);
8860 let cb;
8861 if (isFunction(value)) {
8862 cb = value;
8863 }
8864 else {
8865 cb = value.handler;
8866 options = value;
8867 }
8868 const cur = currentInstance;
8869 setCurrentInstance(this);
8870 const res = doWatch(getter, cb.bind(publicThis), options);
8871 if (cur) {
8872 setCurrentInstance(cur);
8873 }
8874 else {
8875 unsetCurrentInstance();
8876 }
8877 return res;
8878 }
8879 function createPathGetter(ctx, path) {
8880 const segments = path.split('.');
8881 return () => {
8882 let cur = ctx;
8883 for (let i = 0; i < segments.length && cur; i++) {
8884 cur = cur[segments[i]];
8885 }
8886 return cur;
8887 };
8888 }
8889 function traverse(value, seen = new Set()) {
8890 if (!isObject(value) || value["__v_skip" /* SKIP */]) {
8891 return value;
8892 }
8893 seen = seen || new Set();
8894 if (seen.has(value)) {
8895 return value;
8896 }
8897 seen.add(value);
8898 if (isRef(value)) {
8899 traverse(value.value, seen);
8900 }
8901 else if (isArray(value)) {
8902 for (let i = 0; i < value.length; i++) {
8903 traverse(value[i], seen);
8904 }
8905 }
8906 else if (isSet(value) || isMap(value)) {
8907 value.forEach((v) => {
8908 traverse(v, seen);
8909 });
8910 }
8911 else if (isPlainObject(value)) {
8912 for (const key in value) {
8913 traverse(value[key], seen);
8914 }
8915 }
8916 return value;
8917 }
8918
8919 // dev only
8920 const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
8921 `<script setup> of a single file component. Its arguments should be ` +
8922 `compiled away and passing it at runtime has no effect.`);
8923 // implementation
8924 function defineProps() {
8925 {
8926 warnRuntimeUsage(`defineProps`);
8927 }
8928 return null;
8929 }
8930 // implementation
8931 function defineEmits() {
8932 {
8933 warnRuntimeUsage(`defineEmits`);
8934 }
8935 return null;
8936 }
8937 /**
8938 * Vue `<script setup>` compiler macro for declaring a component's exposed
8939 * instance properties when it is accessed by a parent component via template
8940 * refs.
8941 *
8942 * `<script setup>` components are closed by default - i.e. varaibles inside
8943 * the `<script setup>` scope is not exposed to parent unless explicitly exposed
8944 * via `defineExpose`.
8945 *
8946 * This is only usable inside `<script setup>`, is compiled away in the
8947 * output and should **not** be actually called at runtime.
8948 */
8949 function defineExpose(exposed) {
8950 {
8951 warnRuntimeUsage(`defineExpose`);
8952 }
8953 }
8954 /**
8955 * Vue `<script setup>` compiler macro for providing props default values when
8956 * using type-based `defineProps` declaration.
8957 *
8958 * Example usage:
8959 * ```ts
8960 * withDefaults(defineProps<{
8961 * size?: number
8962 * labels?: string[]
8963 * }>(), {
8964 * size: 3,
8965 * labels: () => ['default label']
8966 * })
8967 * ```
8968 *
8969 * This is only usable inside `<script setup>`, is compiled away in the output
8970 * and should **not** be actually called at runtime.
8971 */
8972 function withDefaults(props, defaults) {
8973 {
8974 warnRuntimeUsage(`withDefaults`);
8975 }
8976 return null;
8977 }
8978 function useSlots() {
8979 return getContext().slots;
8980 }
8981 function useAttrs() {
8982 return getContext().attrs;
8983 }
8984 function getContext() {
8985 const i = getCurrentInstance();
8986 if (!i) {
8987 warn$1(`useContext() called without active instance.`);
8988 }
8989 return i.setupContext || (i.setupContext = createSetupContext(i));
8990 }
8991 /**
8992 * Runtime helper for merging default declarations. Imported by compiled code
8993 * only.
8994 * @internal
8995 */
8996 function mergeDefaults(
8997 // the base props is compiler-generated and guaranteed to be in this shape.
8998 props, defaults) {
8999 for (const key in defaults) {
9000 const val = props[key];
9001 if (val) {
9002 val.default = defaults[key];
9003 }
9004 else if (val === null) {
9005 props[key] = { default: defaults[key] };
9006 }
9007 else {
9008 warn$1(`props default key "${key}" has no corresponding declaration.`);
9009 }
9010 }
9011 return props;
9012 }
9013 /**
9014 * `<script setup>` helper for persisting the current instance context over
9015 * async/await flows.
9016 *
9017 * `@vue/compiler-sfc` converts the following:
9018 *
9019 * ```ts
9020 * const x = await foo()
9021 * ```
9022 *
9023 * into:
9024 *
9025 * ```ts
9026 * let __temp, __restore
9027 * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
9028 * ```
9029 * @internal
9030 */
9031 function withAsyncContext(getAwaitable) {
9032 const ctx = getCurrentInstance();
9033 if (!ctx) {
9034 warn$1(`withAsyncContext called without active current instance. ` +
9035 `This is likely a bug.`);
9036 }
9037 let awaitable = getAwaitable();
9038 unsetCurrentInstance();
9039 if (isPromise(awaitable)) {
9040 awaitable = awaitable.catch(e => {
9041 setCurrentInstance(ctx);
9042 throw e;
9043 });
9044 }
9045 return [awaitable, () => setCurrentInstance(ctx)];
9046 }
9047
9048 // Actual implementation
9049 function h(type, propsOrChildren, children) {
9050 const l = arguments.length;
9051 if (l === 2) {
9052 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
9053 // single vnode without props
9054 if (isVNode(propsOrChildren)) {
9055 return createVNode(type, null, [propsOrChildren]);
9056 }
9057 // props without children
9058 return createVNode(type, propsOrChildren);
9059 }
9060 else {
9061 // omit props
9062 return createVNode(type, null, propsOrChildren);
9063 }
9064 }
9065 else {
9066 if (l > 3) {
9067 children = Array.prototype.slice.call(arguments, 2);
9068 }
9069 else if (l === 3 && isVNode(children)) {
9070 children = [children];
9071 }
9072 return createVNode(type, propsOrChildren, children);
9073 }
9074 }
9075
9076 const ssrContextKey = Symbol(`ssrContext` );
9077 const useSSRContext = () => {
9078 {
9079 warn$1(`useSSRContext() is not supported in the global build.`);
9080 }
9081 };
9082
9083 function initCustomFormatter() {
9084 /* eslint-disable no-restricted-globals */
9085 if (typeof window === 'undefined') {
9086 return;
9087 }
9088 const vueStyle = { style: 'color:#3ba776' };
9089 const numberStyle = { style: 'color:#0b1bc9' };
9090 const stringStyle = { style: 'color:#b62e24' };
9091 const keywordStyle = { style: 'color:#9d288c' };
9092 // custom formatter for Chrome
9093 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
9094 const formatter = {
9095 header(obj) {
9096 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
9097 if (!isObject(obj)) {
9098 return null;
9099 }
9100 if (obj.__isVue) {
9101 return ['div', vueStyle, `VueInstance`];
9102 }
9103 else if (isRef(obj)) {
9104 return [
9105 'div',
9106 {},
9107 ['span', vueStyle, genRefFlag(obj)],
9108 '<',
9109 formatValue(obj.value),
9110 `>`
9111 ];
9112 }
9113 else if (isReactive(obj)) {
9114 return [
9115 'div',
9116 {},
9117 ['span', vueStyle, 'Reactive'],
9118 '<',
9119 formatValue(obj),
9120 `>${isReadonly(obj) ? ` (readonly)` : ``}`
9121 ];
9122 }
9123 else if (isReadonly(obj)) {
9124 return [
9125 'div',
9126 {},
9127 ['span', vueStyle, 'Readonly'],
9128 '<',
9129 formatValue(obj),
9130 '>'
9131 ];
9132 }
9133 return null;
9134 },
9135 hasBody(obj) {
9136 return obj && obj.__isVue;
9137 },
9138 body(obj) {
9139 if (obj && obj.__isVue) {
9140 return [
9141 'div',
9142 {},
9143 ...formatInstance(obj.$)
9144 ];
9145 }
9146 }
9147 };
9148 function formatInstance(instance) {
9149 const blocks = [];
9150 if (instance.type.props && instance.props) {
9151 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
9152 }
9153 if (instance.setupState !== EMPTY_OBJ) {
9154 blocks.push(createInstanceBlock('setup', instance.setupState));
9155 }
9156 if (instance.data !== EMPTY_OBJ) {
9157 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
9158 }
9159 const computed = extractKeys(instance, 'computed');
9160 if (computed) {
9161 blocks.push(createInstanceBlock('computed', computed));
9162 }
9163 const injected = extractKeys(instance, 'inject');
9164 if (injected) {
9165 blocks.push(createInstanceBlock('injected', injected));
9166 }
9167 blocks.push([
9168 'div',
9169 {},
9170 [
9171 'span',
9172 {
9173 style: keywordStyle.style + ';opacity:0.66'
9174 },
9175 '$ (internal): '
9176 ],
9177 ['object', { object: instance }]
9178 ]);
9179 return blocks;
9180 }
9181 function createInstanceBlock(type, target) {
9182 target = extend({}, target);
9183 if (!Object.keys(target).length) {
9184 return ['span', {}];
9185 }
9186 return [
9187 'div',
9188 { style: 'line-height:1.25em;margin-bottom:0.6em' },
9189 [
9190 'div',
9191 {
9192 style: 'color:#476582'
9193 },
9194 type
9195 ],
9196 [
9197 'div',
9198 {
9199 style: 'padding-left:1.25em'
9200 },
9201 ...Object.keys(target).map(key => {
9202 return [
9203 'div',
9204 {},
9205 ['span', keywordStyle, key + ': '],
9206 formatValue(target[key], false)
9207 ];
9208 })
9209 ]
9210 ];
9211 }
9212 function formatValue(v, asRaw = true) {
9213 if (typeof v === 'number') {
9214 return ['span', numberStyle, v];
9215 }
9216 else if (typeof v === 'string') {
9217 return ['span', stringStyle, JSON.stringify(v)];
9218 }
9219 else if (typeof v === 'boolean') {
9220 return ['span', keywordStyle, v];
9221 }
9222 else if (isObject(v)) {
9223 return ['object', { object: asRaw ? toRaw(v) : v }];
9224 }
9225 else {
9226 return ['span', stringStyle, String(v)];
9227 }
9228 }
9229 function extractKeys(instance, type) {
9230 const Comp = instance.type;
9231 if (isFunction(Comp)) {
9232 return;
9233 }
9234 const extracted = {};
9235 for (const key in instance.ctx) {
9236 if (isKeyOfType(Comp, key, type)) {
9237 extracted[key] = instance.ctx[key];
9238 }
9239 }
9240 return extracted;
9241 }
9242 function isKeyOfType(Comp, key, type) {
9243 const opts = Comp[type];
9244 if ((isArray(opts) && opts.includes(key)) ||
9245 (isObject(opts) && key in opts)) {
9246 return true;
9247 }
9248 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
9249 return true;
9250 }
9251 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
9252 return true;
9253 }
9254 }
9255 function genRefFlag(v) {
9256 if (v._shallow) {
9257 return `ShallowRef`;
9258 }
9259 if (v.effect) {
9260 return `ComputedRef`;
9261 }
9262 return `Ref`;
9263 }
9264 if (window.devtoolsFormatters) {
9265 window.devtoolsFormatters.push(formatter);
9266 }
9267 else {
9268 window.devtoolsFormatters = [formatter];
9269 }
9270 }
9271
9272 function withMemo(memo, render, cache, index) {
9273 const cached = cache[index];
9274 if (cached && isMemoSame(cached, memo)) {
9275 return cached;
9276 }
9277 const ret = render();
9278 // shallow clone
9279 ret.memo = memo.slice();
9280 return (cache[index] = ret);
9281 }
9282 function isMemoSame(cached, memo) {
9283 const prev = cached.memo;
9284 if (prev.length != memo.length) {
9285 return false;
9286 }
9287 for (let i = 0; i < prev.length; i++) {
9288 if (prev[i] !== memo[i]) {
9289 return false;
9290 }
9291 }
9292 // make sure to let parent block track it when returning cached
9293 if (isBlockTreeEnabled > 0 && currentBlock) {
9294 currentBlock.push(cached);
9295 }
9296 return true;
9297 }
9298
9299 // Core API ------------------------------------------------------------------
9300 const version = "3.2.11";
9301 /**
9302 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
9303 * @internal
9304 */
9305 const ssrUtils = (null);
9306 /**
9307 * @internal only exposed in compat builds
9308 */
9309 const resolveFilter = null;
9310 /**
9311 * @internal only exposed in compat builds.
9312 */
9313 const compatUtils = (null);
9314
9315 const svgNS = 'http://www.w3.org/2000/svg';
9316 const doc = (typeof document !== 'undefined' ? document : null);
9317 const staticTemplateCache = new Map();
9318 const nodeOps = {
9319 insert: (child, parent, anchor) => {
9320 parent.insertBefore(child, anchor || null);
9321 },
9322 remove: child => {
9323 const parent = child.parentNode;
9324 if (parent) {
9325 parent.removeChild(child);
9326 }
9327 },
9328 createElement: (tag, isSVG, is, props) => {
9329 const el = isSVG
9330 ? doc.createElementNS(svgNS, tag)
9331 : doc.createElement(tag, is ? { is } : undefined);
9332 if (tag === 'select' && props && props.multiple != null) {
9333 el.setAttribute('multiple', props.multiple);
9334 }
9335 return el;
9336 },
9337 createText: text => doc.createTextNode(text),
9338 createComment: text => doc.createComment(text),
9339 setText: (node, text) => {
9340 node.nodeValue = text;
9341 },
9342 setElementText: (el, text) => {
9343 el.textContent = text;
9344 },
9345 parentNode: node => node.parentNode,
9346 nextSibling: node => node.nextSibling,
9347 querySelector: selector => doc.querySelector(selector),
9348 setScopeId(el, id) {
9349 el.setAttribute(id, '');
9350 },
9351 cloneNode(el) {
9352 const cloned = el.cloneNode(true);
9353 // #3072
9354 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
9355 // - normally, elements using `:value` bindings will not be hoisted, but if
9356 // the bound value is a constant, e.g. `:value="true"` - they do get
9357 // hoisted.
9358 // - in production, hoisted nodes are cloned when subsequent inserts, but
9359 // cloneNode() does not copy the custom property we attached.
9360 // - This may need to account for other custom DOM properties we attach to
9361 // elements in addition to `_value` in the future.
9362 if (`_value` in el) {
9363 cloned._value = el._value;
9364 }
9365 return cloned;
9366 },
9367 // __UNSAFE__
9368 // Reason: innerHTML.
9369 // Static content here can only come from compiled templates.
9370 // As long as the user only uses trusted templates, this is safe.
9371 insertStaticContent(content, parent, anchor, isSVG) {
9372 // <parent> before | first ... last | anchor </parent>
9373 const before = anchor ? anchor.previousSibling : parent.lastChild;
9374 let template = staticTemplateCache.get(content);
9375 if (!template) {
9376 const t = doc.createElement('template');
9377 t.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
9378 template = t.content;
9379 if (isSVG) {
9380 // remove outer svg wrapper
9381 const wrapper = template.firstChild;
9382 while (wrapper.firstChild) {
9383 template.appendChild(wrapper.firstChild);
9384 }
9385 template.removeChild(wrapper);
9386 }
9387 staticTemplateCache.set(content, template);
9388 }
9389 parent.insertBefore(template.cloneNode(true), anchor);
9390 return [
9391 // first
9392 before ? before.nextSibling : parent.firstChild,
9393 // last
9394 anchor ? anchor.previousSibling : parent.lastChild
9395 ];
9396 }
9397 };
9398
9399 // compiler should normalize class + :class bindings on the same element
9400 // into a single binding ['staticClass', dynamic]
9401 function patchClass(el, value, isSVG) {
9402 // directly setting className should be faster than setAttribute in theory
9403 // if this is an element during a transition, take the temporary transition
9404 // classes into account.
9405 const transitionClasses = el._vtc;
9406 if (transitionClasses) {
9407 value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
9408 }
9409 if (value == null) {
9410 el.removeAttribute('class');
9411 }
9412 else if (isSVG) {
9413 el.setAttribute('class', value);
9414 }
9415 else {
9416 el.className = value;
9417 }
9418 }
9419
9420 function patchStyle(el, prev, next) {
9421 const style = el.style;
9422 const currentDisplay = style.display;
9423 if (!next) {
9424 el.removeAttribute('style');
9425 }
9426 else if (isString(next)) {
9427 if (prev !== next) {
9428 style.cssText = next;
9429 }
9430 }
9431 else {
9432 for (const key in next) {
9433 setStyle(style, key, next[key]);
9434 }
9435 if (prev && !isString(prev)) {
9436 for (const key in prev) {
9437 if (next[key] == null) {
9438 setStyle(style, key, '');
9439 }
9440 }
9441 }
9442 }
9443 // indicates that the `display` of the element is controlled by `v-show`,
9444 // so we always keep the current `display` value regardless of the `style` value,
9445 // thus handing over control to `v-show`.
9446 if ('_vod' in el) {
9447 style.display = currentDisplay;
9448 }
9449 }
9450 const importantRE = /\s*!important$/;
9451 function setStyle(style, name, val) {
9452 if (isArray(val)) {
9453 val.forEach(v => setStyle(style, name, v));
9454 }
9455 else {
9456 if (name.startsWith('--')) {
9457 // custom property definition
9458 style.setProperty(name, val);
9459 }
9460 else {
9461 const prefixed = autoPrefix(style, name);
9462 if (importantRE.test(val)) {
9463 // !important
9464 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
9465 }
9466 else {
9467 style[prefixed] = val;
9468 }
9469 }
9470 }
9471 }
9472 const prefixes = ['Webkit', 'Moz', 'ms'];
9473 const prefixCache = {};
9474 function autoPrefix(style, rawName) {
9475 const cached = prefixCache[rawName];
9476 if (cached) {
9477 return cached;
9478 }
9479 let name = camelize(rawName);
9480 if (name !== 'filter' && name in style) {
9481 return (prefixCache[rawName] = name);
9482 }
9483 name = capitalize(name);
9484 for (let i = 0; i < prefixes.length; i++) {
9485 const prefixed = prefixes[i] + name;
9486 if (prefixed in style) {
9487 return (prefixCache[rawName] = prefixed);
9488 }
9489 }
9490 return rawName;
9491 }
9492
9493 const xlinkNS = 'http://www.w3.org/1999/xlink';
9494 function patchAttr(el, key, value, isSVG, instance) {
9495 if (isSVG && key.startsWith('xlink:')) {
9496 if (value == null) {
9497 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
9498 }
9499 else {
9500 el.setAttributeNS(xlinkNS, key, value);
9501 }
9502 }
9503 else {
9504 // note we are only checking boolean attributes that don't have a
9505 // corresponding dom prop of the same name here.
9506 const isBoolean = isSpecialBooleanAttr(key);
9507 if (value == null || (isBoolean && !includeBooleanAttr(value))) {
9508 el.removeAttribute(key);
9509 }
9510 else {
9511 el.setAttribute(key, isBoolean ? '' : value);
9512 }
9513 }
9514 }
9515
9516 // __UNSAFE__
9517 // functions. The user is responsible for using them with only trusted content.
9518 function patchDOMProp(el, key, value,
9519 // the following args are passed only due to potential innerHTML/textContent
9520 // overriding existing VNodes, in which case the old tree must be properly
9521 // unmounted.
9522 prevChildren, parentComponent, parentSuspense, unmountChildren) {
9523 if (key === 'innerHTML' || key === 'textContent') {
9524 if (prevChildren) {
9525 unmountChildren(prevChildren, parentComponent, parentSuspense);
9526 }
9527 el[key] = value == null ? '' : value;
9528 return;
9529 }
9530 if (key === 'value' && el.tagName !== 'PROGRESS') {
9531 // store value as _value as well since
9532 // non-string values will be stringified.
9533 el._value = value;
9534 const newValue = value == null ? '' : value;
9535 if (el.value !== newValue) {
9536 el.value = newValue;
9537 }
9538 if (value == null) {
9539 el.removeAttribute(key);
9540 }
9541 return;
9542 }
9543 if (value === '' || value == null) {
9544 const type = typeof el[key];
9545 if (type === 'boolean') {
9546 // e.g. <select multiple> compiles to { multiple: '' }
9547 el[key] = includeBooleanAttr(value);
9548 return;
9549 }
9550 else if (value == null && type === 'string') {
9551 // e.g. <div :id="null">
9552 el[key] = '';
9553 el.removeAttribute(key);
9554 return;
9555 }
9556 else if (type === 'number') {
9557 // e.g. <img :width="null">
9558 // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
9559 try {
9560 el[key] = 0;
9561 }
9562 catch (_a) { }
9563 el.removeAttribute(key);
9564 return;
9565 }
9566 }
9567 // some properties perform value validation and throw
9568 try {
9569 el[key] = value;
9570 }
9571 catch (e) {
9572 {
9573 warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9574 `value ${value} is invalid.`, e);
9575 }
9576 }
9577 }
9578
9579 // Async edge case fix requires storing an event listener's attach timestamp.
9580 let _getNow = Date.now;
9581 let skipTimestampCheck = false;
9582 if (typeof window !== 'undefined') {
9583 // Determine what event timestamp the browser is using. Annoyingly, the
9584 // timestamp can either be hi-res (relative to page load) or low-res
9585 // (relative to UNIX epoch), so in order to compare time we have to use the
9586 // same timestamp type when saving the flush timestamp.
9587 if (_getNow() > document.createEvent('Event').timeStamp) {
9588 // if the low-res timestamp which is bigger than the event timestamp
9589 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9590 // and we need to use the hi-res version for event listeners as well.
9591 _getNow = () => performance.now();
9592 }
9593 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9594 // and does not fire microtasks in between event propagation, so safe to exclude.
9595 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9596 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9597 }
9598 // To avoid the overhead of repeatedly calling performance.now(), we cache
9599 // and use the same timestamp for all event listeners attached in the same tick.
9600 let cachedNow = 0;
9601 const p = Promise.resolve();
9602 const reset = () => {
9603 cachedNow = 0;
9604 };
9605 const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9606 function addEventListener(el, event, handler, options) {
9607 el.addEventListener(event, handler, options);
9608 }
9609 function removeEventListener(el, event, handler, options) {
9610 el.removeEventListener(event, handler, options);
9611 }
9612 function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9613 // vei = vue event invokers
9614 const invokers = el._vei || (el._vei = {});
9615 const existingInvoker = invokers[rawName];
9616 if (nextValue && existingInvoker) {
9617 // patch
9618 existingInvoker.value = nextValue;
9619 }
9620 else {
9621 const [name, options] = parseName(rawName);
9622 if (nextValue) {
9623 // add
9624 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9625 addEventListener(el, name, invoker, options);
9626 }
9627 else if (existingInvoker) {
9628 // remove
9629 removeEventListener(el, name, existingInvoker, options);
9630 invokers[rawName] = undefined;
9631 }
9632 }
9633 }
9634 const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9635 function parseName(name) {
9636 let options;
9637 if (optionsModifierRE.test(name)) {
9638 options = {};
9639 let m;
9640 while ((m = name.match(optionsModifierRE))) {
9641 name = name.slice(0, name.length - m[0].length);
9642 options[m[0].toLowerCase()] = true;
9643 }
9644 }
9645 return [hyphenate(name.slice(2)), options];
9646 }
9647 function createInvoker(initialValue, instance) {
9648 const invoker = (e) => {
9649 // async edge case #6566: inner click event triggers patch, event handler
9650 // attached to outer element during patch, and triggered again. This
9651 // happens because browsers fire microtask ticks between event propagation.
9652 // the solution is simple: we save the timestamp when a handler is attached,
9653 // and the handler would only fire if the event passed to it was fired
9654 // AFTER it was attached.
9655 const timeStamp = e.timeStamp || _getNow();
9656 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9657 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9658 }
9659 };
9660 invoker.value = initialValue;
9661 invoker.attached = getNow();
9662 return invoker;
9663 }
9664 function patchStopImmediatePropagation(e, value) {
9665 if (isArray(value)) {
9666 const originalStop = e.stopImmediatePropagation;
9667 e.stopImmediatePropagation = () => {
9668 originalStop.call(e);
9669 e._stopped = true;
9670 };
9671 return value.map(fn => (e) => !e._stopped && fn(e));
9672 }
9673 else {
9674 return value;
9675 }
9676 }
9677
9678 const nativeOnRE = /^on[a-z]/;
9679 const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9680 if (key === 'class') {
9681 patchClass(el, nextValue, isSVG);
9682 }
9683 else if (key === 'style') {
9684 patchStyle(el, prevValue, nextValue);
9685 }
9686 else if (isOn(key)) {
9687 // ignore v-model listeners
9688 if (!isModelListener(key)) {
9689 patchEvent(el, key, prevValue, nextValue, parentComponent);
9690 }
9691 }
9692 else if (key[0] === '.'
9693 ? ((key = key.slice(1)), true)
9694 : key[0] === '^'
9695 ? ((key = key.slice(1)), false)
9696 : shouldSetAsProp(el, key, nextValue, isSVG)) {
9697 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9698 }
9699 else {
9700 // special case for <input v-model type="checkbox"> with
9701 // :true-value & :false-value
9702 // store value as dom properties since non-string values will be
9703 // stringified.
9704 if (key === 'true-value') {
9705 el._trueValue = nextValue;
9706 }
9707 else if (key === 'false-value') {
9708 el._falseValue = nextValue;
9709 }
9710 patchAttr(el, key, nextValue, isSVG);
9711 }
9712 };
9713 function shouldSetAsProp(el, key, value, isSVG) {
9714 if (isSVG) {
9715 // most keys must be set as attribute on svg elements to work
9716 // ...except innerHTML & textContent
9717 if (key === 'innerHTML' || key === 'textContent') {
9718 return true;
9719 }
9720 // or native onclick with function values
9721 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9722 return true;
9723 }
9724 return false;
9725 }
9726 // spellcheck and draggable are numerated attrs, however their
9727 // corresponding DOM properties are actually booleans - this leads to
9728 // setting it with a string "false" value leading it to be coerced to
9729 // `true`, so we need to always treat them as attributes.
9730 // Note that `contentEditable` doesn't have this problem: its DOM
9731 // property is also enumerated string values.
9732 if (key === 'spellcheck' || key === 'draggable') {
9733 return false;
9734 }
9735 // #1787, #2840 form property on form elements is readonly and must be set as
9736 // attribute.
9737 if (key === 'form') {
9738 return false;
9739 }
9740 // #1526 <input list> must be set as attribute
9741 if (key === 'list' && el.tagName === 'INPUT') {
9742 return false;
9743 }
9744 // #2766 <textarea type> must be set as attribute
9745 if (key === 'type' && el.tagName === 'TEXTAREA') {
9746 return false;
9747 }
9748 // native onclick with string value, must be set as attribute
9749 if (nativeOnRE.test(key) && isString(value)) {
9750 return false;
9751 }
9752 return key in el;
9753 }
9754
9755 function defineCustomElement(options, hydate) {
9756 const Comp = defineComponent(options);
9757 class VueCustomElement extends VueElement {
9758 constructor(initialProps) {
9759 super(Comp, initialProps, hydate);
9760 }
9761 }
9762 VueCustomElement.def = Comp;
9763 return VueCustomElement;
9764 }
9765 const defineSSRCustomElement = ((options) => {
9766 // @ts-ignore
9767 return defineCustomElement(options, hydrate);
9768 });
9769 const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
9770 });
9771 class VueElement extends BaseClass {
9772 constructor(_def, _props = {}, hydrate) {
9773 super();
9774 this._def = _def;
9775 this._props = _props;
9776 /**
9777 * @internal
9778 */
9779 this._instance = null;
9780 this._connected = false;
9781 this._resolved = false;
9782 if (this.shadowRoot && hydrate) {
9783 hydrate(this._createVNode(), this.shadowRoot);
9784 }
9785 else {
9786 if (this.shadowRoot) {
9787 warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
9788 `defined as hydratable. Use \`defineSSRCustomElement\`.`);
9789 }
9790 this.attachShadow({ mode: 'open' });
9791 }
9792 // set initial attrs
9793 for (let i = 0; i < this.attributes.length; i++) {
9794 this._setAttr(this.attributes[i].name);
9795 }
9796 // watch future attr changes
9797 const observer = new MutationObserver(mutations => {
9798 for (const m of mutations) {
9799 this._setAttr(m.attributeName);
9800 }
9801 });
9802 observer.observe(this, { attributes: true });
9803 }
9804 connectedCallback() {
9805 this._connected = true;
9806 if (!this._instance) {
9807 this._resolveDef();
9808 render(this._createVNode(), this.shadowRoot);
9809 }
9810 }
9811 disconnectedCallback() {
9812 this._connected = false;
9813 nextTick(() => {
9814 if (!this._connected) {
9815 render(null, this.shadowRoot);
9816 this._instance = null;
9817 }
9818 });
9819 }
9820 /**
9821 * resolve inner component definition (handle possible async component)
9822 */
9823 _resolveDef() {
9824 if (this._resolved) {
9825 return;
9826 }
9827 const resolve = (def) => {
9828 this._resolved = true;
9829 // check if there are props set pre-upgrade or connect
9830 for (const key of Object.keys(this)) {
9831 if (key[0] !== '_') {
9832 this._setProp(key, this[key]);
9833 }
9834 }
9835 const { props, styles } = def;
9836 // defining getter/setters on prototype
9837 const rawKeys = props ? (isArray(props) ? props : Object.keys(props)) : [];
9838 for (const key of rawKeys.map(camelize)) {
9839 Object.defineProperty(this, key, {
9840 get() {
9841 return this._getProp(key);
9842 },
9843 set(val) {
9844 this._setProp(key, val);
9845 }
9846 });
9847 }
9848 this._applyStyles(styles);
9849 };
9850 const asyncDef = this._def.__asyncLoader;
9851 if (asyncDef) {
9852 asyncDef().then(resolve);
9853 }
9854 else {
9855 resolve(this._def);
9856 }
9857 }
9858 _setAttr(key) {
9859 this._setProp(camelize(key), toNumber(this.getAttribute(key)), false);
9860 }
9861 /**
9862 * @internal
9863 */
9864 _getProp(key) {
9865 return this._props[key];
9866 }
9867 /**
9868 * @internal
9869 */
9870 _setProp(key, val, shouldReflect = true) {
9871 if (val !== this._props[key]) {
9872 this._props[key] = val;
9873 if (this._instance) {
9874 render(this._createVNode(), this.shadowRoot);
9875 }
9876 // reflect
9877 if (shouldReflect) {
9878 if (val === true) {
9879 this.setAttribute(hyphenate(key), '');
9880 }
9881 else if (typeof val === 'string' || typeof val === 'number') {
9882 this.setAttribute(hyphenate(key), val + '');
9883 }
9884 else if (!val) {
9885 this.removeAttribute(hyphenate(key));
9886 }
9887 }
9888 }
9889 }
9890 _createVNode() {
9891 const vnode = createVNode(this._def, extend({}, this._props));
9892 if (!this._instance) {
9893 vnode.ce = instance => {
9894 this._instance = instance;
9895 instance.isCE = true;
9896 // HMR
9897 {
9898 instance.ceReload = newStyles => {
9899 // alawys reset styles
9900 if (this._styles) {
9901 this._styles.forEach(s => this.shadowRoot.removeChild(s));
9902 this._styles.length = 0;
9903 }
9904 this._applyStyles(newStyles);
9905 // if this is an async component, ceReload is called from the inner
9906 // component so no need to reload the async wrapper
9907 if (!this._def.__asyncLoader) {
9908 // reload
9909 this._instance = null;
9910 render(this._createVNode(), this.shadowRoot);
9911 }
9912 };
9913 }
9914 // intercept emit
9915 instance.emit = (event, ...args) => {
9916 this.dispatchEvent(new CustomEvent(event, {
9917 detail: args
9918 }));
9919 };
9920 // locate nearest Vue custom element parent for provide/inject
9921 let parent = this;
9922 while ((parent =
9923 parent && (parent.parentNode || parent.host))) {
9924 if (parent instanceof VueElement) {
9925 instance.parent = parent._instance;
9926 break;
9927 }
9928 }
9929 };
9930 }
9931 return vnode;
9932 }
9933 _applyStyles(styles) {
9934 if (styles) {
9935 styles.forEach(css => {
9936 const s = document.createElement('style');
9937 s.textContent = css;
9938 this.shadowRoot.appendChild(s);
9939 // record for HMR
9940 {
9941 (this._styles || (this._styles = [])).push(s);
9942 }
9943 });
9944 }
9945 }
9946 }
9947
9948 function useCssModule(name = '$style') {
9949 /* istanbul ignore else */
9950 {
9951 {
9952 warn$1(`useCssModule() is not supported in the global build.`);
9953 }
9954 return EMPTY_OBJ;
9955 }
9956 }
9957
9958 /**
9959 * Runtime helper for SFC's CSS variable injection feature.
9960 * @private
9961 */
9962 function useCssVars(getter) {
9963 const instance = getCurrentInstance();
9964 /* istanbul ignore next */
9965 if (!instance) {
9966 warn$1(`useCssVars is called without current active component instance.`);
9967 return;
9968 }
9969 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9970 watchPostEffect(setVars);
9971 onMounted(() => {
9972 const ob = new MutationObserver(setVars);
9973 ob.observe(instance.subTree.el.parentNode, { childList: true });
9974 onUnmounted(() => ob.disconnect());
9975 });
9976 }
9977 function setVarsOnVNode(vnode, vars) {
9978 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9979 const suspense = vnode.suspense;
9980 vnode = suspense.activeBranch;
9981 if (suspense.pendingBranch && !suspense.isHydrating) {
9982 suspense.effects.push(() => {
9983 setVarsOnVNode(suspense.activeBranch, vars);
9984 });
9985 }
9986 }
9987 // drill down HOCs until it's a non-component vnode
9988 while (vnode.component) {
9989 vnode = vnode.component.subTree;
9990 }
9991 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
9992 setVarsOnNode(vnode.el, vars);
9993 }
9994 else if (vnode.type === Fragment) {
9995 vnode.children.forEach(c => setVarsOnVNode(c, vars));
9996 }
9997 else if (vnode.type === Static) {
9998 let { el, anchor } = vnode;
9999 while (el) {
10000 setVarsOnNode(el, vars);
10001 if (el === anchor)
10002 break;
10003 el = el.nextSibling;
10004 }
10005 }
10006 }
10007 function setVarsOnNode(el, vars) {
10008 if (el.nodeType === 1) {
10009 const style = el.style;
10010 for (const key in vars) {
10011 style.setProperty(`--${key}`, vars[key]);
10012 }
10013 }
10014 }
10015
10016 const TRANSITION = 'transition';
10017 const ANIMATION = 'animation';
10018 // DOM Transition is a higher-order-component based on the platform-agnostic
10019 // base Transition component, with DOM-specific logic.
10020 const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
10021 Transition.displayName = 'Transition';
10022 const DOMTransitionPropsValidators = {
10023 name: String,
10024 type: String,
10025 css: {
10026 type: Boolean,
10027 default: true
10028 },
10029 duration: [String, Number, Object],
10030 enterFromClass: String,
10031 enterActiveClass: String,
10032 enterToClass: String,
10033 appearFromClass: String,
10034 appearActiveClass: String,
10035 appearToClass: String,
10036 leaveFromClass: String,
10037 leaveActiveClass: String,
10038 leaveToClass: String
10039 };
10040 const TransitionPropsValidators = (Transition.props =
10041 /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
10042 /**
10043 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
10044 * with custom HOCs.
10045 */
10046 const callHook$1 = (hook, args = []) => {
10047 if (isArray(hook)) {
10048 hook.forEach(h => h(...args));
10049 }
10050 else if (hook) {
10051 hook(...args);
10052 }
10053 };
10054 /**
10055 * Check if a hook expects a callback (2nd arg), which means the user
10056 * intends to explicitly control the end of the transition.
10057 */
10058 const hasExplicitCallback = (hook) => {
10059 return hook
10060 ? isArray(hook)
10061 ? hook.some(h => h.length > 1)
10062 : hook.length > 1
10063 : false;
10064 };
10065 function resolveTransitionProps(rawProps) {
10066 const baseProps = {};
10067 for (const key in rawProps) {
10068 if (!(key in DOMTransitionPropsValidators)) {
10069 baseProps[key] = rawProps[key];
10070 }
10071 }
10072 if (rawProps.css === false) {
10073 return baseProps;
10074 }
10075 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;
10076 const durations = normalizeDuration(duration);
10077 const enterDuration = durations && durations[0];
10078 const leaveDuration = durations && durations[1];
10079 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
10080 const finishEnter = (el, isAppear, done) => {
10081 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
10082 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
10083 done && done();
10084 };
10085 const finishLeave = (el, done) => {
10086 removeTransitionClass(el, leaveToClass);
10087 removeTransitionClass(el, leaveActiveClass);
10088 done && done();
10089 };
10090 const makeEnterHook = (isAppear) => {
10091 return (el, done) => {
10092 const hook = isAppear ? onAppear : onEnter;
10093 const resolve = () => finishEnter(el, isAppear, done);
10094 callHook$1(hook, [el, resolve]);
10095 nextFrame(() => {
10096 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
10097 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
10098 if (!hasExplicitCallback(hook)) {
10099 whenTransitionEnds(el, type, enterDuration, resolve);
10100 }
10101 });
10102 };
10103 };
10104 return extend(baseProps, {
10105 onBeforeEnter(el) {
10106 callHook$1(onBeforeEnter, [el]);
10107 addTransitionClass(el, enterFromClass);
10108 addTransitionClass(el, enterActiveClass);
10109 },
10110 onBeforeAppear(el) {
10111 callHook$1(onBeforeAppear, [el]);
10112 addTransitionClass(el, appearFromClass);
10113 addTransitionClass(el, appearActiveClass);
10114 },
10115 onEnter: makeEnterHook(false),
10116 onAppear: makeEnterHook(true),
10117 onLeave(el, done) {
10118 const resolve = () => finishLeave(el, done);
10119 addTransitionClass(el, leaveFromClass);
10120 // force reflow so *-leave-from classes immediately take effect (#2593)
10121 forceReflow();
10122 addTransitionClass(el, leaveActiveClass);
10123 nextFrame(() => {
10124 removeTransitionClass(el, leaveFromClass);
10125 addTransitionClass(el, leaveToClass);
10126 if (!hasExplicitCallback(onLeave)) {
10127 whenTransitionEnds(el, type, leaveDuration, resolve);
10128 }
10129 });
10130 callHook$1(onLeave, [el, resolve]);
10131 },
10132 onEnterCancelled(el) {
10133 finishEnter(el, false);
10134 callHook$1(onEnterCancelled, [el]);
10135 },
10136 onAppearCancelled(el) {
10137 finishEnter(el, true);
10138 callHook$1(onAppearCancelled, [el]);
10139 },
10140 onLeaveCancelled(el) {
10141 finishLeave(el);
10142 callHook$1(onLeaveCancelled, [el]);
10143 }
10144 });
10145 }
10146 function normalizeDuration(duration) {
10147 if (duration == null) {
10148 return null;
10149 }
10150 else if (isObject(duration)) {
10151 return [NumberOf(duration.enter), NumberOf(duration.leave)];
10152 }
10153 else {
10154 const n = NumberOf(duration);
10155 return [n, n];
10156 }
10157 }
10158 function NumberOf(val) {
10159 const res = toNumber(val);
10160 validateDuration(res);
10161 return res;
10162 }
10163 function validateDuration(val) {
10164 if (typeof val !== 'number') {
10165 warn$1(`<transition> explicit duration is not a valid number - ` +
10166 `got ${JSON.stringify(val)}.`);
10167 }
10168 else if (isNaN(val)) {
10169 warn$1(`<transition> explicit duration is NaN - ` +
10170 'the duration expression might be incorrect.');
10171 }
10172 }
10173 function addTransitionClass(el, cls) {
10174 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
10175 (el._vtc ||
10176 (el._vtc = new Set())).add(cls);
10177 }
10178 function removeTransitionClass(el, cls) {
10179 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
10180 const { _vtc } = el;
10181 if (_vtc) {
10182 _vtc.delete(cls);
10183 if (!_vtc.size) {
10184 el._vtc = undefined;
10185 }
10186 }
10187 }
10188 function nextFrame(cb) {
10189 requestAnimationFrame(() => {
10190 requestAnimationFrame(cb);
10191 });
10192 }
10193 let endId = 0;
10194 function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
10195 const id = (el._endId = ++endId);
10196 const resolveIfNotStale = () => {
10197 if (id === el._endId) {
10198 resolve();
10199 }
10200 };
10201 if (explicitTimeout) {
10202 return setTimeout(resolveIfNotStale, explicitTimeout);
10203 }
10204 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
10205 if (!type) {
10206 return resolve();
10207 }
10208 const endEvent = type + 'end';
10209 let ended = 0;
10210 const end = () => {
10211 el.removeEventListener(endEvent, onEnd);
10212 resolveIfNotStale();
10213 };
10214 const onEnd = (e) => {
10215 if (e.target === el && ++ended >= propCount) {
10216 end();
10217 }
10218 };
10219 setTimeout(() => {
10220 if (ended < propCount) {
10221 end();
10222 }
10223 }, timeout + 1);
10224 el.addEventListener(endEvent, onEnd);
10225 }
10226 function getTransitionInfo(el, expectedType) {
10227 const styles = window.getComputedStyle(el);
10228 // JSDOM may return undefined for transition properties
10229 const getStyleProperties = (key) => (styles[key] || '').split(', ');
10230 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
10231 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
10232 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
10233 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
10234 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
10235 const animationTimeout = getTimeout(animationDelays, animationDurations);
10236 let type = null;
10237 let timeout = 0;
10238 let propCount = 0;
10239 /* istanbul ignore if */
10240 if (expectedType === TRANSITION) {
10241 if (transitionTimeout > 0) {
10242 type = TRANSITION;
10243 timeout = transitionTimeout;
10244 propCount = transitionDurations.length;
10245 }
10246 }
10247 else if (expectedType === ANIMATION) {
10248 if (animationTimeout > 0) {
10249 type = ANIMATION;
10250 timeout = animationTimeout;
10251 propCount = animationDurations.length;
10252 }
10253 }
10254 else {
10255 timeout = Math.max(transitionTimeout, animationTimeout);
10256 type =
10257 timeout > 0
10258 ? transitionTimeout > animationTimeout
10259 ? TRANSITION
10260 : ANIMATION
10261 : null;
10262 propCount = type
10263 ? type === TRANSITION
10264 ? transitionDurations.length
10265 : animationDurations.length
10266 : 0;
10267 }
10268 const hasTransform = type === TRANSITION &&
10269 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
10270 return {
10271 type,
10272 timeout,
10273 propCount,
10274 hasTransform
10275 };
10276 }
10277 function getTimeout(delays, durations) {
10278 while (delays.length < durations.length) {
10279 delays = delays.concat(delays);
10280 }
10281 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
10282 }
10283 // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
10284 // numbers in a locale-dependent way, using a comma instead of a dot.
10285 // If comma is not replaced with a dot, the input will be rounded down
10286 // (i.e. acting as a floor function) causing unexpected behaviors
10287 function toMs(s) {
10288 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
10289 }
10290 // synchronously force layout to put elements into a certain state
10291 function forceReflow() {
10292 return document.body.offsetHeight;
10293 }
10294
10295 const positionMap = new WeakMap();
10296 const newPositionMap = new WeakMap();
10297 const TransitionGroupImpl = {
10298 name: 'TransitionGroup',
10299 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
10300 tag: String,
10301 moveClass: String
10302 }),
10303 setup(props, { slots }) {
10304 const instance = getCurrentInstance();
10305 const state = useTransitionState();
10306 let prevChildren;
10307 let children;
10308 onUpdated(() => {
10309 // children is guaranteed to exist after initial render
10310 if (!prevChildren.length) {
10311 return;
10312 }
10313 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
10314 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
10315 return;
10316 }
10317 // we divide the work into three loops to avoid mixing DOM reads and writes
10318 // in each iteration - which helps prevent layout thrashing.
10319 prevChildren.forEach(callPendingCbs);
10320 prevChildren.forEach(recordPosition);
10321 const movedChildren = prevChildren.filter(applyTranslation);
10322 // force reflow to put everything in position
10323 forceReflow();
10324 movedChildren.forEach(c => {
10325 const el = c.el;
10326 const style = el.style;
10327 addTransitionClass(el, moveClass);
10328 style.transform = style.webkitTransform = style.transitionDuration = '';
10329 const cb = (el._moveCb = (e) => {
10330 if (e && e.target !== el) {
10331 return;
10332 }
10333 if (!e || /transform$/.test(e.propertyName)) {
10334 el.removeEventListener('transitionend', cb);
10335 el._moveCb = null;
10336 removeTransitionClass(el, moveClass);
10337 }
10338 });
10339 el.addEventListener('transitionend', cb);
10340 });
10341 });
10342 return () => {
10343 const rawProps = toRaw(props);
10344 const cssTransitionProps = resolveTransitionProps(rawProps);
10345 let tag = rawProps.tag || Fragment;
10346 prevChildren = children;
10347 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
10348 for (let i = 0; i < children.length; i++) {
10349 const child = children[i];
10350 if (child.key != null) {
10351 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10352 }
10353 else {
10354 warn$1(`<TransitionGroup> children must be keyed.`);
10355 }
10356 }
10357 if (prevChildren) {
10358 for (let i = 0; i < prevChildren.length; i++) {
10359 const child = prevChildren[i];
10360 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
10361 positionMap.set(child, child.el.getBoundingClientRect());
10362 }
10363 }
10364 return createVNode(tag, null, children);
10365 };
10366 }
10367 };
10368 const TransitionGroup = TransitionGroupImpl;
10369 function callPendingCbs(c) {
10370 const el = c.el;
10371 if (el._moveCb) {
10372 el._moveCb();
10373 }
10374 if (el._enterCb) {
10375 el._enterCb();
10376 }
10377 }
10378 function recordPosition(c) {
10379 newPositionMap.set(c, c.el.getBoundingClientRect());
10380 }
10381 function applyTranslation(c) {
10382 const oldPos = positionMap.get(c);
10383 const newPos = newPositionMap.get(c);
10384 const dx = oldPos.left - newPos.left;
10385 const dy = oldPos.top - newPos.top;
10386 if (dx || dy) {
10387 const s = c.el.style;
10388 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
10389 s.transitionDuration = '0s';
10390 return c;
10391 }
10392 }
10393 function hasCSSTransform(el, root, moveClass) {
10394 // Detect whether an element with the move class applied has
10395 // CSS transitions. Since the element may be inside an entering
10396 // transition at this very moment, we make a clone of it and remove
10397 // all other transition classes applied to ensure only the move class
10398 // is applied.
10399 const clone = el.cloneNode();
10400 if (el._vtc) {
10401 el._vtc.forEach(cls => {
10402 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
10403 });
10404 }
10405 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
10406 clone.style.display = 'none';
10407 const container = (root.nodeType === 1 ? root : root.parentNode);
10408 container.appendChild(clone);
10409 const { hasTransform } = getTransitionInfo(clone);
10410 container.removeChild(clone);
10411 return hasTransform;
10412 }
10413
10414 const getModelAssigner = (vnode) => {
10415 const fn = vnode.props['onUpdate:modelValue'];
10416 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
10417 };
10418 function onCompositionStart(e) {
10419 e.target.composing = true;
10420 }
10421 function onCompositionEnd(e) {
10422 const target = e.target;
10423 if (target.composing) {
10424 target.composing = false;
10425 trigger$1(target, 'input');
10426 }
10427 }
10428 function trigger$1(el, type) {
10429 const e = document.createEvent('HTMLEvents');
10430 e.initEvent(type, true, true);
10431 el.dispatchEvent(e);
10432 }
10433 // We are exporting the v-model runtime directly as vnode hooks so that it can
10434 // be tree-shaken in case v-model is never used.
10435 const vModelText = {
10436 created(el, { modifiers: { lazy, trim, number } }, vnode) {
10437 el._assign = getModelAssigner(vnode);
10438 const castToNumber = number || (vnode.props && vnode.props.type === 'number');
10439 addEventListener(el, lazy ? 'change' : 'input', e => {
10440 if (e.target.composing)
10441 return;
10442 let domValue = el.value;
10443 if (trim) {
10444 domValue = domValue.trim();
10445 }
10446 else if (castToNumber) {
10447 domValue = toNumber(domValue);
10448 }
10449 el._assign(domValue);
10450 });
10451 if (trim) {
10452 addEventListener(el, 'change', () => {
10453 el.value = el.value.trim();
10454 });
10455 }
10456 if (!lazy) {
10457 addEventListener(el, 'compositionstart', onCompositionStart);
10458 addEventListener(el, 'compositionend', onCompositionEnd);
10459 // Safari < 10.2 & UIWebView doesn't fire compositionend when
10460 // switching focus before confirming composition choice
10461 // this also fixes the issue where some browsers e.g. iOS Chrome
10462 // fires "change" instead of "input" on autocomplete.
10463 addEventListener(el, 'change', onCompositionEnd);
10464 }
10465 },
10466 // set value on mounted so it's after min/max for type="range"
10467 mounted(el, { value }) {
10468 el.value = value == null ? '' : value;
10469 },
10470 beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
10471 el._assign = getModelAssigner(vnode);
10472 // avoid clearing unresolved text. #2302
10473 if (el.composing)
10474 return;
10475 if (document.activeElement === el) {
10476 if (lazy) {
10477 return;
10478 }
10479 if (trim && el.value.trim() === value) {
10480 return;
10481 }
10482 if ((number || el.type === 'number') && toNumber(el.value) === value) {
10483 return;
10484 }
10485 }
10486 const newValue = value == null ? '' : value;
10487 if (el.value !== newValue) {
10488 el.value = newValue;
10489 }
10490 }
10491 };
10492 const vModelCheckbox = {
10493 // #4096 array checkboxes need to be deep traversed
10494 deep: true,
10495 created(el, _, vnode) {
10496 el._assign = getModelAssigner(vnode);
10497 addEventListener(el, 'change', () => {
10498 const modelValue = el._modelValue;
10499 const elementValue = getValue(el);
10500 const checked = el.checked;
10501 const assign = el._assign;
10502 if (isArray(modelValue)) {
10503 const index = looseIndexOf(modelValue, elementValue);
10504 const found = index !== -1;
10505 if (checked && !found) {
10506 assign(modelValue.concat(elementValue));
10507 }
10508 else if (!checked && found) {
10509 const filtered = [...modelValue];
10510 filtered.splice(index, 1);
10511 assign(filtered);
10512 }
10513 }
10514 else if (isSet(modelValue)) {
10515 const cloned = new Set(modelValue);
10516 if (checked) {
10517 cloned.add(elementValue);
10518 }
10519 else {
10520 cloned.delete(elementValue);
10521 }
10522 assign(cloned);
10523 }
10524 else {
10525 assign(getCheckboxValue(el, checked));
10526 }
10527 });
10528 },
10529 // set initial checked on mount to wait for true-value/false-value
10530 mounted: setChecked,
10531 beforeUpdate(el, binding, vnode) {
10532 el._assign = getModelAssigner(vnode);
10533 setChecked(el, binding, vnode);
10534 }
10535 };
10536 function setChecked(el, { value, oldValue }, vnode) {
10537 el._modelValue = value;
10538 if (isArray(value)) {
10539 el.checked = looseIndexOf(value, vnode.props.value) > -1;
10540 }
10541 else if (isSet(value)) {
10542 el.checked = value.has(vnode.props.value);
10543 }
10544 else if (value !== oldValue) {
10545 el.checked = looseEqual(value, getCheckboxValue(el, true));
10546 }
10547 }
10548 const vModelRadio = {
10549 created(el, { value }, vnode) {
10550 el.checked = looseEqual(value, vnode.props.value);
10551 el._assign = getModelAssigner(vnode);
10552 addEventListener(el, 'change', () => {
10553 el._assign(getValue(el));
10554 });
10555 },
10556 beforeUpdate(el, { value, oldValue }, vnode) {
10557 el._assign = getModelAssigner(vnode);
10558 if (value !== oldValue) {
10559 el.checked = looseEqual(value, vnode.props.value);
10560 }
10561 }
10562 };
10563 const vModelSelect = {
10564 // <select multiple> value need to be deep traversed
10565 deep: true,
10566 created(el, { value, modifiers: { number } }, vnode) {
10567 const isSetModel = isSet(value);
10568 addEventListener(el, 'change', () => {
10569 const selectedVal = Array.prototype.filter
10570 .call(el.options, (o) => o.selected)
10571 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
10572 el._assign(el.multiple
10573 ? isSetModel
10574 ? new Set(selectedVal)
10575 : selectedVal
10576 : selectedVal[0]);
10577 });
10578 el._assign = getModelAssigner(vnode);
10579 },
10580 // set value in mounted & updated because <select> relies on its children
10581 // <option>s.
10582 mounted(el, { value }) {
10583 setSelected(el, value);
10584 },
10585 beforeUpdate(el, _binding, vnode) {
10586 el._assign = getModelAssigner(vnode);
10587 },
10588 updated(el, { value }) {
10589 setSelected(el, value);
10590 }
10591 };
10592 function setSelected(el, value) {
10593 const isMultiple = el.multiple;
10594 if (isMultiple && !isArray(value) && !isSet(value)) {
10595 warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
10596 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
10597 return;
10598 }
10599 for (let i = 0, l = el.options.length; i < l; i++) {
10600 const option = el.options[i];
10601 const optionValue = getValue(option);
10602 if (isMultiple) {
10603 if (isArray(value)) {
10604 option.selected = looseIndexOf(value, optionValue) > -1;
10605 }
10606 else {
10607 option.selected = value.has(optionValue);
10608 }
10609 }
10610 else {
10611 if (looseEqual(getValue(option), value)) {
10612 if (el.selectedIndex !== i)
10613 el.selectedIndex = i;
10614 return;
10615 }
10616 }
10617 }
10618 if (!isMultiple && el.selectedIndex !== -1) {
10619 el.selectedIndex = -1;
10620 }
10621 }
10622 // retrieve raw value set via :value bindings
10623 function getValue(el) {
10624 return '_value' in el ? el._value : el.value;
10625 }
10626 // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
10627 function getCheckboxValue(el, checked) {
10628 const key = checked ? '_trueValue' : '_falseValue';
10629 return key in el ? el[key] : checked;
10630 }
10631 const vModelDynamic = {
10632 created(el, binding, vnode) {
10633 callModelHook(el, binding, vnode, null, 'created');
10634 },
10635 mounted(el, binding, vnode) {
10636 callModelHook(el, binding, vnode, null, 'mounted');
10637 },
10638 beforeUpdate(el, binding, vnode, prevVNode) {
10639 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
10640 },
10641 updated(el, binding, vnode, prevVNode) {
10642 callModelHook(el, binding, vnode, prevVNode, 'updated');
10643 }
10644 };
10645 function callModelHook(el, binding, vnode, prevVNode, hook) {
10646 let modelToUse;
10647 switch (el.tagName) {
10648 case 'SELECT':
10649 modelToUse = vModelSelect;
10650 break;
10651 case 'TEXTAREA':
10652 modelToUse = vModelText;
10653 break;
10654 default:
10655 switch (vnode.props && vnode.props.type) {
10656 case 'checkbox':
10657 modelToUse = vModelCheckbox;
10658 break;
10659 case 'radio':
10660 modelToUse = vModelRadio;
10661 break;
10662 default:
10663 modelToUse = vModelText;
10664 }
10665 }
10666 const fn = modelToUse[hook];
10667 fn && fn(el, binding, vnode, prevVNode);
10668 }
10669
10670 const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
10671 const modifierGuards = {
10672 stop: e => e.stopPropagation(),
10673 prevent: e => e.preventDefault(),
10674 self: e => e.target !== e.currentTarget,
10675 ctrl: e => !e.ctrlKey,
10676 shift: e => !e.shiftKey,
10677 alt: e => !e.altKey,
10678 meta: e => !e.metaKey,
10679 left: e => 'button' in e && e.button !== 0,
10680 middle: e => 'button' in e && e.button !== 1,
10681 right: e => 'button' in e && e.button !== 2,
10682 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
10683 };
10684 /**
10685 * @private
10686 */
10687 const withModifiers = (fn, modifiers) => {
10688 return (event, ...args) => {
10689 for (let i = 0; i < modifiers.length; i++) {
10690 const guard = modifierGuards[modifiers[i]];
10691 if (guard && guard(event, modifiers))
10692 return;
10693 }
10694 return fn(event, ...args);
10695 };
10696 };
10697 // Kept for 2.x compat.
10698 // Note: IE11 compat for `spacebar` and `del` is removed for now.
10699 const keyNames = {
10700 esc: 'escape',
10701 space: ' ',
10702 up: 'arrow-up',
10703 left: 'arrow-left',
10704 right: 'arrow-right',
10705 down: 'arrow-down',
10706 delete: 'backspace'
10707 };
10708 /**
10709 * @private
10710 */
10711 const withKeys = (fn, modifiers) => {
10712 return (event) => {
10713 if (!('key' in event)) {
10714 return;
10715 }
10716 const eventKey = hyphenate(event.key);
10717 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
10718 return fn(event);
10719 }
10720 };
10721 };
10722
10723 const vShow = {
10724 beforeMount(el, { value }, { transition }) {
10725 el._vod = el.style.display === 'none' ? '' : el.style.display;
10726 if (transition && value) {
10727 transition.beforeEnter(el);
10728 }
10729 else {
10730 setDisplay(el, value);
10731 }
10732 },
10733 mounted(el, { value }, { transition }) {
10734 if (transition && value) {
10735 transition.enter(el);
10736 }
10737 },
10738 updated(el, { value, oldValue }, { transition }) {
10739 if (!value === !oldValue)
10740 return;
10741 if (transition) {
10742 if (value) {
10743 transition.beforeEnter(el);
10744 setDisplay(el, true);
10745 transition.enter(el);
10746 }
10747 else {
10748 transition.leave(el, () => {
10749 setDisplay(el, false);
10750 });
10751 }
10752 }
10753 else {
10754 setDisplay(el, value);
10755 }
10756 },
10757 beforeUnmount(el, { value }) {
10758 setDisplay(el, value);
10759 }
10760 };
10761 function setDisplay(el, value) {
10762 el.style.display = value ? el._vod : 'none';
10763 }
10764
10765 const rendererOptions = extend({ patchProp }, nodeOps);
10766 // lazy create the renderer - this makes core renderer logic tree-shakable
10767 // in case the user only imports reactivity utilities from Vue.
10768 let renderer;
10769 let enabledHydration = false;
10770 function ensureRenderer() {
10771 return (renderer ||
10772 (renderer = createRenderer(rendererOptions)));
10773 }
10774 function ensureHydrationRenderer() {
10775 renderer = enabledHydration
10776 ? renderer
10777 : createHydrationRenderer(rendererOptions);
10778 enabledHydration = true;
10779 return renderer;
10780 }
10781 // use explicit type casts here to avoid import() calls in rolled-up d.ts
10782 const render = ((...args) => {
10783 ensureRenderer().render(...args);
10784 });
10785 const hydrate = ((...args) => {
10786 ensureHydrationRenderer().hydrate(...args);
10787 });
10788 const createApp = ((...args) => {
10789 const app = ensureRenderer().createApp(...args);
10790 {
10791 injectNativeTagCheck(app);
10792 injectCompilerOptionsCheck(app);
10793 }
10794 const { mount } = app;
10795 app.mount = (containerOrSelector) => {
10796 const container = normalizeContainer(containerOrSelector);
10797 if (!container)
10798 return;
10799 const component = app._component;
10800 if (!isFunction(component) && !component.render && !component.template) {
10801 // __UNSAFE__
10802 // Reason: potential execution of JS expressions in in-DOM template.
10803 // The user must make sure the in-DOM template is trusted. If it's
10804 // rendered by the server, the template should not contain any user data.
10805 component.template = container.innerHTML;
10806 }
10807 // clear content before mounting
10808 container.innerHTML = '';
10809 const proxy = mount(container, false, container instanceof SVGElement);
10810 if (container instanceof Element) {
10811 container.removeAttribute('v-cloak');
10812 container.setAttribute('data-v-app', '');
10813 }
10814 return proxy;
10815 };
10816 return app;
10817 });
10818 const createSSRApp = ((...args) => {
10819 const app = ensureHydrationRenderer().createApp(...args);
10820 {
10821 injectNativeTagCheck(app);
10822 injectCompilerOptionsCheck(app);
10823 }
10824 const { mount } = app;
10825 app.mount = (containerOrSelector) => {
10826 const container = normalizeContainer(containerOrSelector);
10827 if (container) {
10828 return mount(container, true, container instanceof SVGElement);
10829 }
10830 };
10831 return app;
10832 });
10833 function injectNativeTagCheck(app) {
10834 // Inject `isNativeTag`
10835 // this is used for component name validation (dev only)
10836 Object.defineProperty(app.config, 'isNativeTag', {
10837 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10838 writable: false
10839 });
10840 }
10841 // dev only
10842 function injectCompilerOptionsCheck(app) {
10843 if (isRuntimeOnly()) {
10844 const isCustomElement = app.config.isCustomElement;
10845 Object.defineProperty(app.config, 'isCustomElement', {
10846 get() {
10847 return isCustomElement;
10848 },
10849 set() {
10850 warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
10851 `\`compilerOptions.isCustomElement\` instead.`);
10852 }
10853 });
10854 const compilerOptions = app.config.compilerOptions;
10855 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10856 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10857 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10858 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10859 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10860 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10861 `- 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`;
10862 Object.defineProperty(app.config, 'compilerOptions', {
10863 get() {
10864 warn$1(msg);
10865 return compilerOptions;
10866 },
10867 set() {
10868 warn$1(msg);
10869 }
10870 });
10871 }
10872 }
10873 function normalizeContainer(container) {
10874 if (isString(container)) {
10875 const res = document.querySelector(container);
10876 if (!res) {
10877 warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
10878 }
10879 return res;
10880 }
10881 if (window.ShadowRoot &&
10882 container instanceof window.ShadowRoot &&
10883 container.mode === 'closed') {
10884 warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10885 }
10886 return container;
10887 }
10888
10889 function initDev() {
10890 {
10891 {
10892 console.info(`You are running a development build of Vue.\n` +
10893 `Make sure to use the production build (*.prod.js) when deploying for production.`);
10894 }
10895 initCustomFormatter();
10896 }
10897 }
10898
10899 function defaultOnError(error) {
10900 throw error;
10901 }
10902 function defaultOnWarn(msg) {
10903 console.warn(`[Vue warn] ${msg.message}`);
10904 }
10905 function createCompilerError(code, loc, messages, additionalMessage) {
10906 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
10907 ;
10908 const error = new SyntaxError(String(msg));
10909 error.code = code;
10910 error.loc = loc;
10911 return error;
10912 }
10913 const errorMessages = {
10914 // parse errors
10915 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
10916 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
10917 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
10918 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
10919 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
10920 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
10921 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
10922 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
10923 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
10924 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
10925 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
10926 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
10927 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
10928 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
10929 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
10930 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
10931 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
10932 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
10933 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
10934 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
10935 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
10936 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
10937 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
10938 // Vue-specific parse errors
10939 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
10940 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
10941 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
10942 [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
10943 'Note that dynamic directive argument cannot contain spaces.',
10944 [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
10945 // transform errors
10946 [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
10947 [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
10948 [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
10949 [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
10950 [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
10951 [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
10952 [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
10953 [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
10954 [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
10955 [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
10956 `When there are multiple named slots, all slots should use <template> ` +
10957 `syntax to avoid scope ambiguity.`,
10958 [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
10959 [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
10960 `default slot. These children will be ignored.`,
10961 [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
10962 [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
10963 [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
10964 [43 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
10965 [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
10966 [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
10967 // generic errors
10968 [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
10969 [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
10970 [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
10971 [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
10972 // just to fullfill types
10973 [50 /* __EXTEND_POINT__ */]: ``
10974 };
10975
10976 const FRAGMENT = Symbol(`Fragment` );
10977 const TELEPORT = Symbol(`Teleport` );
10978 const SUSPENSE = Symbol(`Suspense` );
10979 const KEEP_ALIVE = Symbol(`KeepAlive` );
10980 const BASE_TRANSITION = Symbol(`BaseTransition` );
10981 const OPEN_BLOCK = Symbol(`openBlock` );
10982 const CREATE_BLOCK = Symbol(`createBlock` );
10983 const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
10984 const CREATE_VNODE = Symbol(`createVNode` );
10985 const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
10986 const CREATE_COMMENT = Symbol(`createCommentVNode` );
10987 const CREATE_TEXT = Symbol(`createTextVNode` );
10988 const CREATE_STATIC = Symbol(`createStaticVNode` );
10989 const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
10990 const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
10991 const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
10992 const RESOLVE_FILTER = Symbol(`resolveFilter` );
10993 const WITH_DIRECTIVES = Symbol(`withDirectives` );
10994 const RENDER_LIST = Symbol(`renderList` );
10995 const RENDER_SLOT = Symbol(`renderSlot` );
10996 const CREATE_SLOTS = Symbol(`createSlots` );
10997 const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
10998 const MERGE_PROPS = Symbol(`mergeProps` );
10999 const NORMALIZE_CLASS = Symbol(`normalizeClass` );
11000 const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
11001 const NORMALIZE_PROPS = Symbol(`normalizeProps` );
11002 const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
11003 const TO_HANDLERS = Symbol(`toHandlers` );
11004 const CAMELIZE = Symbol(`camelize` );
11005 const CAPITALIZE = Symbol(`capitalize` );
11006 const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
11007 const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
11008 const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
11009 const POP_SCOPE_ID = Symbol(`popScopeId` );
11010 const WITH_CTX = Symbol(`withCtx` );
11011 const UNREF = Symbol(`unref` );
11012 const IS_REF = Symbol(`isRef` );
11013 const WITH_MEMO = Symbol(`withMemo` );
11014 const IS_MEMO_SAME = Symbol(`isMemoSame` );
11015 // Name mapping for runtime helpers that need to be imported from 'vue' in
11016 // generated code. Make sure these are correctly exported in the runtime!
11017 // Using `any` here because TS doesn't allow symbols as index type.
11018 const helperNameMap = {
11019 [FRAGMENT]: `Fragment`,
11020 [TELEPORT]: `Teleport`,
11021 [SUSPENSE]: `Suspense`,
11022 [KEEP_ALIVE]: `KeepAlive`,
11023 [BASE_TRANSITION]: `BaseTransition`,
11024 [OPEN_BLOCK]: `openBlock`,
11025 [CREATE_BLOCK]: `createBlock`,
11026 [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
11027 [CREATE_VNODE]: `createVNode`,
11028 [CREATE_ELEMENT_VNODE]: `createElementVNode`,
11029 [CREATE_COMMENT]: `createCommentVNode`,
11030 [CREATE_TEXT]: `createTextVNode`,
11031 [CREATE_STATIC]: `createStaticVNode`,
11032 [RESOLVE_COMPONENT]: `resolveComponent`,
11033 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
11034 [RESOLVE_DIRECTIVE]: `resolveDirective`,
11035 [RESOLVE_FILTER]: `resolveFilter`,
11036 [WITH_DIRECTIVES]: `withDirectives`,
11037 [RENDER_LIST]: `renderList`,
11038 [RENDER_SLOT]: `renderSlot`,
11039 [CREATE_SLOTS]: `createSlots`,
11040 [TO_DISPLAY_STRING]: `toDisplayString`,
11041 [MERGE_PROPS]: `mergeProps`,
11042 [NORMALIZE_CLASS]: `normalizeClass`,
11043 [NORMALIZE_STYLE]: `normalizeStyle`,
11044 [NORMALIZE_PROPS]: `normalizeProps`,
11045 [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
11046 [TO_HANDLERS]: `toHandlers`,
11047 [CAMELIZE]: `camelize`,
11048 [CAPITALIZE]: `capitalize`,
11049 [TO_HANDLER_KEY]: `toHandlerKey`,
11050 [SET_BLOCK_TRACKING]: `setBlockTracking`,
11051 [PUSH_SCOPE_ID]: `pushScopeId`,
11052 [POP_SCOPE_ID]: `popScopeId`,
11053 [WITH_CTX]: `withCtx`,
11054 [UNREF]: `unref`,
11055 [IS_REF]: `isRef`,
11056 [WITH_MEMO]: `withMemo`,
11057 [IS_MEMO_SAME]: `isMemoSame`
11058 };
11059 function registerRuntimeHelpers(helpers) {
11060 Object.getOwnPropertySymbols(helpers).forEach(s => {
11061 helperNameMap[s] = helpers[s];
11062 });
11063 }
11064
11065 // AST Utilities ---------------------------------------------------------------
11066 // Some expressions, e.g. sequence and conditional expressions, are never
11067 // associated with template nodes, so their source locations are just a stub.
11068 // Container types like CompoundExpression also don't need a real location.
11069 const locStub = {
11070 source: '',
11071 start: { line: 1, column: 1, offset: 0 },
11072 end: { line: 1, column: 1, offset: 0 }
11073 };
11074 function createRoot(children, loc = locStub) {
11075 return {
11076 type: 0 /* ROOT */,
11077 children,
11078 helpers: [],
11079 components: [],
11080 directives: [],
11081 hoists: [],
11082 imports: [],
11083 cached: 0,
11084 temps: 0,
11085 codegenNode: undefined,
11086 loc
11087 };
11088 }
11089 function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
11090 if (context) {
11091 if (isBlock) {
11092 context.helper(OPEN_BLOCK);
11093 context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
11094 }
11095 else {
11096 context.helper(getVNodeHelper(context.inSSR, isComponent));
11097 }
11098 if (directives) {
11099 context.helper(WITH_DIRECTIVES);
11100 }
11101 }
11102 return {
11103 type: 13 /* VNODE_CALL */,
11104 tag,
11105 props,
11106 children,
11107 patchFlag,
11108 dynamicProps,
11109 directives,
11110 isBlock,
11111 disableTracking,
11112 isComponent,
11113 loc
11114 };
11115 }
11116 function createArrayExpression(elements, loc = locStub) {
11117 return {
11118 type: 17 /* JS_ARRAY_EXPRESSION */,
11119 loc,
11120 elements
11121 };
11122 }
11123 function createObjectExpression(properties, loc = locStub) {
11124 return {
11125 type: 15 /* JS_OBJECT_EXPRESSION */,
11126 loc,
11127 properties
11128 };
11129 }
11130 function createObjectProperty(key, value) {
11131 return {
11132 type: 16 /* JS_PROPERTY */,
11133 loc: locStub,
11134 key: isString(key) ? createSimpleExpression(key, true) : key,
11135 value
11136 };
11137 }
11138 function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
11139 return {
11140 type: 4 /* SIMPLE_EXPRESSION */,
11141 loc,
11142 content,
11143 isStatic,
11144 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
11145 };
11146 }
11147 function createCompoundExpression(children, loc = locStub) {
11148 return {
11149 type: 8 /* COMPOUND_EXPRESSION */,
11150 loc,
11151 children
11152 };
11153 }
11154 function createCallExpression(callee, args = [], loc = locStub) {
11155 return {
11156 type: 14 /* JS_CALL_EXPRESSION */,
11157 loc,
11158 callee,
11159 arguments: args
11160 };
11161 }
11162 function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
11163 return {
11164 type: 18 /* JS_FUNCTION_EXPRESSION */,
11165 params,
11166 returns,
11167 newline,
11168 isSlot,
11169 loc
11170 };
11171 }
11172 function createConditionalExpression(test, consequent, alternate, newline = true) {
11173 return {
11174 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
11175 test,
11176 consequent,
11177 alternate,
11178 newline,
11179 loc: locStub
11180 };
11181 }
11182 function createCacheExpression(index, value, isVNode = false) {
11183 return {
11184 type: 20 /* JS_CACHE_EXPRESSION */,
11185 index,
11186 value,
11187 isVNode,
11188 loc: locStub
11189 };
11190 }
11191 function createBlockStatement(body) {
11192 return {
11193 type: 21 /* JS_BLOCK_STATEMENT */,
11194 body,
11195 loc: locStub
11196 };
11197 }
11198
11199 const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
11200 const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
11201 function isCoreComponent(tag) {
11202 if (isBuiltInType(tag, 'Teleport')) {
11203 return TELEPORT;
11204 }
11205 else if (isBuiltInType(tag, 'Suspense')) {
11206 return SUSPENSE;
11207 }
11208 else if (isBuiltInType(tag, 'KeepAlive')) {
11209 return KEEP_ALIVE;
11210 }
11211 else if (isBuiltInType(tag, 'BaseTransition')) {
11212 return BASE_TRANSITION;
11213 }
11214 }
11215 const nonIdentifierRE = /^\d|[^\$\w]/;
11216 const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
11217 const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
11218 const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
11219 const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
11220 /**
11221 * Simple lexer to check if an expression is a member expression. This is
11222 * lax and only checks validity at the root level (i.e. does not validate exps
11223 * inside square brackets), but it's ok since these are only used on template
11224 * expressions and false positives are invalid expressions in the first place.
11225 */
11226 const isMemberExpression = (path) => {
11227 // remove whitespaces around . or [ first
11228 path = path.trim().replace(whitespaceRE, s => s.trim());
11229 let state = 0 /* inMemberExp */;
11230 let stateStack = [];
11231 let currentOpenBracketCount = 0;
11232 let currentOpenParensCount = 0;
11233 let currentStringType = null;
11234 for (let i = 0; i < path.length; i++) {
11235 const char = path.charAt(i);
11236 switch (state) {
11237 case 0 /* inMemberExp */:
11238 if (char === '[') {
11239 stateStack.push(state);
11240 state = 1 /* inBrackets */;
11241 currentOpenBracketCount++;
11242 }
11243 else if (char === '(') {
11244 stateStack.push(state);
11245 state = 2 /* inParens */;
11246 currentOpenParensCount++;
11247 }
11248 else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
11249 return false;
11250 }
11251 break;
11252 case 1 /* inBrackets */:
11253 if (char === `'` || char === `"` || char === '`') {
11254 stateStack.push(state);
11255 state = 3 /* inString */;
11256 currentStringType = char;
11257 }
11258 else if (char === `[`) {
11259 currentOpenBracketCount++;
11260 }
11261 else if (char === `]`) {
11262 if (!--currentOpenBracketCount) {
11263 state = stateStack.pop();
11264 }
11265 }
11266 break;
11267 case 2 /* inParens */:
11268 if (char === `'` || char === `"` || char === '`') {
11269 stateStack.push(state);
11270 state = 3 /* inString */;
11271 currentStringType = char;
11272 }
11273 else if (char === `(`) {
11274 currentOpenParensCount++;
11275 }
11276 else if (char === `)`) {
11277 // if the exp ends as a call then it should not be considered valid
11278 if (i === path.length - 1) {
11279 return false;
11280 }
11281 if (!--currentOpenParensCount) {
11282 state = stateStack.pop();
11283 }
11284 }
11285 break;
11286 case 3 /* inString */:
11287 if (char === currentStringType) {
11288 state = stateStack.pop();
11289 currentStringType = null;
11290 }
11291 break;
11292 }
11293 }
11294 return !currentOpenBracketCount && !currentOpenParensCount;
11295 };
11296 function getInnerRange(loc, offset, length) {
11297 const source = loc.source.substr(offset, length);
11298 const newLoc = {
11299 source,
11300 start: advancePositionWithClone(loc.start, loc.source, offset),
11301 end: loc.end
11302 };
11303 if (length != null) {
11304 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
11305 }
11306 return newLoc;
11307 }
11308 function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
11309 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
11310 }
11311 // advance by mutation without cloning (for performance reasons), since this
11312 // gets called a lot in the parser
11313 function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
11314 let linesCount = 0;
11315 let lastNewLinePos = -1;
11316 for (let i = 0; i < numberOfCharacters; i++) {
11317 if (source.charCodeAt(i) === 10 /* newline char code */) {
11318 linesCount++;
11319 lastNewLinePos = i;
11320 }
11321 }
11322 pos.offset += numberOfCharacters;
11323 pos.line += linesCount;
11324 pos.column =
11325 lastNewLinePos === -1
11326 ? pos.column + numberOfCharacters
11327 : numberOfCharacters - lastNewLinePos;
11328 return pos;
11329 }
11330 function assert(condition, msg) {
11331 /* istanbul ignore if */
11332 if (!condition) {
11333 throw new Error(msg || `unexpected compiler condition`);
11334 }
11335 }
11336 function findDir(node, name, allowEmpty = false) {
11337 for (let i = 0; i < node.props.length; i++) {
11338 const p = node.props[i];
11339 if (p.type === 7 /* DIRECTIVE */ &&
11340 (allowEmpty || p.exp) &&
11341 (isString(name) ? p.name === name : name.test(p.name))) {
11342 return p;
11343 }
11344 }
11345 }
11346 function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
11347 for (let i = 0; i < node.props.length; i++) {
11348 const p = node.props[i];
11349 if (p.type === 6 /* ATTRIBUTE */) {
11350 if (dynamicOnly)
11351 continue;
11352 if (p.name === name && (p.value || allowEmpty)) {
11353 return p;
11354 }
11355 }
11356 else if (p.name === 'bind' &&
11357 (p.exp || allowEmpty) &&
11358 isBindKey(p.arg, name)) {
11359 return p;
11360 }
11361 }
11362 }
11363 function isBindKey(arg, name) {
11364 return !!(arg && isStaticExp(arg) && arg.content === name);
11365 }
11366 function hasDynamicKeyVBind(node) {
11367 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
11368 p.name === 'bind' &&
11369 (!p.arg || // v-bind="obj"
11370 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
11371 !p.arg.isStatic) // v-bind:[foo]
11372 );
11373 }
11374 function isText(node) {
11375 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
11376 }
11377 function isVSlot(p) {
11378 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
11379 }
11380 function isTemplateNode(node) {
11381 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
11382 }
11383 function isSlotOutlet(node) {
11384 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
11385 }
11386 function getVNodeHelper(ssr, isComponent) {
11387 return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
11388 }
11389 function getVNodeBlockHelper(ssr, isComponent) {
11390 return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
11391 }
11392 const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
11393 function getUnnormalizedProps(props, callPath = []) {
11394 if (props &&
11395 !isString(props) &&
11396 props.type === 14 /* JS_CALL_EXPRESSION */) {
11397 const callee = props.callee;
11398 if (!isString(callee) && propsHelperSet.has(callee)) {
11399 return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
11400 }
11401 }
11402 return [props, callPath];
11403 }
11404 function injectProp(node, prop, context) {
11405 let propsWithInjection;
11406 const originalProps = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
11407 /**
11408 * 1. mergeProps(...)
11409 * 2. toHandlers(...)
11410 * 3. normalizeProps(...)
11411 * 4. normalizeProps(guardReactiveProps(...))
11412 *
11413 * we need to get the real props before normalization
11414 */
11415 let props = originalProps;
11416 let callPath = [];
11417 let parentCall;
11418 if (props &&
11419 !isString(props) &&
11420 props.type === 14 /* JS_CALL_EXPRESSION */) {
11421 const ret = getUnnormalizedProps(props);
11422 props = ret[0];
11423 callPath = ret[1];
11424 parentCall = callPath[callPath.length - 1];
11425 }
11426 if (props == null || isString(props)) {
11427 propsWithInjection = createObjectExpression([prop]);
11428 }
11429 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
11430 // merged props... add ours
11431 // only inject key to object literal if it's the first argument so that
11432 // if doesn't override user provided keys
11433 const first = props.arguments[0];
11434 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
11435 first.properties.unshift(prop);
11436 }
11437 else {
11438 if (props.callee === TO_HANDLERS) {
11439 // #2366
11440 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11441 createObjectExpression([prop]),
11442 props
11443 ]);
11444 }
11445 else {
11446 props.arguments.unshift(createObjectExpression([prop]));
11447 }
11448 }
11449 !propsWithInjection && (propsWithInjection = props);
11450 }
11451 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11452 let alreadyExists = false;
11453 // check existing key to avoid overriding user provided keys
11454 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
11455 const propKeyName = prop.key.content;
11456 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
11457 p.key.content === propKeyName);
11458 }
11459 if (!alreadyExists) {
11460 props.properties.unshift(prop);
11461 }
11462 propsWithInjection = props;
11463 }
11464 else {
11465 // single v-bind with expression, return a merged replacement
11466 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
11467 createObjectExpression([prop]),
11468 props
11469 ]);
11470 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
11471 // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
11472 // the `guardReactiveProps` will no longer be needed
11473 if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
11474 parentCall = callPath[callPath.length - 2];
11475 }
11476 }
11477 if (node.type === 13 /* VNODE_CALL */) {
11478 if (parentCall) {
11479 parentCall.arguments[0] = propsWithInjection;
11480 }
11481 else {
11482 node.props = propsWithInjection;
11483 }
11484 }
11485 else {
11486 if (parentCall) {
11487 parentCall.arguments[0] = propsWithInjection;
11488 }
11489 else {
11490 node.arguments[2] = propsWithInjection;
11491 }
11492 }
11493 }
11494 function toValidAssetId(name, type) {
11495 // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
11496 return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
11497 return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
11498 })}`;
11499 }
11500 function getMemoedVNodeCall(node) {
11501 if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
11502 return node.arguments[1].returns;
11503 }
11504 else {
11505 return node;
11506 }
11507 }
11508 function makeBlock(node, { helper, removeHelper, inSSR }) {
11509 if (!node.isBlock) {
11510 node.isBlock = true;
11511 removeHelper(getVNodeHelper(inSSR, node.isComponent));
11512 helper(OPEN_BLOCK);
11513 helper(getVNodeBlockHelper(inSSR, node.isComponent));
11514 }
11515 }
11516
11517 const deprecationData$1 = {
11518 ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
11519 message: `Platform-native elements with "is" prop will no longer be ` +
11520 `treated as components in Vue 3 unless the "is" value is explicitly ` +
11521 `prefixed with "vue:".`,
11522 link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
11523 },
11524 ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
11525 message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
11526 `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
11527 `\`v-model:${key}\`.`,
11528 link: `https://v3.vuejs.org/guide/migration/v-model.html`
11529 },
11530 ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
11531 message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
11532 `Vue 3 will automatically set a binding as DOM property when appropriate.`
11533 },
11534 ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
11535 message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
11536 `object spread: it will now overwrite an existing non-mergeable attribute ` +
11537 `that appears before v-bind in the case of conflict. ` +
11538 `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
11539 `You can also suppress this warning if the usage is intended.`,
11540 link: `https://v3.vuejs.org/guide/migration/v-bind.html`
11541 },
11542 ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
11543 message: `.native modifier for v-on has been removed as is no longer necessary.`,
11544 link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
11545 },
11546 ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
11547 message: `v-if / v-for precedence when used on the same element has changed ` +
11548 `in Vue 3: v-if now takes higher precedence and will no longer have ` +
11549 `access to v-for scope variables. It is best to avoid the ambiguity ` +
11550 `with <template> tags or use a computed property that filters v-for ` +
11551 `data source.`,
11552 link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
11553 },
11554 ["COMPILER_V_FOR_REF" /* COMPILER_V_FOR_REF */]: {
11555 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
11556 `Consider using function refs or refactor to avoid ref usage altogether.`,
11557 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
11558 },
11559 ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
11560 message: `<template> with no special directives will render as a native template ` +
11561 `element instead of its inner content in Vue 3.`
11562 },
11563 ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
11564 message: `"inline-template" has been removed in Vue 3.`,
11565 link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
11566 },
11567 ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
11568 message: `filters have been removed in Vue 3. ` +
11569 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
11570 `Use method calls or computed properties instead.`,
11571 link: `https://v3.vuejs.org/guide/migration/filters.html`
11572 }
11573 };
11574 function getCompatValue(key, context) {
11575 const config = context.options
11576 ? context.options.compatConfig
11577 : context.compatConfig;
11578 const value = config && config[key];
11579 if (key === 'MODE') {
11580 return value || 3; // compiler defaults to v3 behavior
11581 }
11582 else {
11583 return value;
11584 }
11585 }
11586 function isCompatEnabled$1(key, context) {
11587 const mode = getCompatValue('MODE', context);
11588 const value = getCompatValue(key, context);
11589 // in v3 mode, only enable if explicitly set to true
11590 // otherwise enable for any non-false value
11591 return mode === 3 ? value === true : value !== false;
11592 }
11593 function checkCompatEnabled(key, context, loc, ...args) {
11594 const enabled = isCompatEnabled$1(key, context);
11595 if (enabled) {
11596 warnDeprecation$1(key, context, loc, ...args);
11597 }
11598 return enabled;
11599 }
11600 function warnDeprecation$1(key, context, loc, ...args) {
11601 const val = getCompatValue(key, context);
11602 if (val === 'suppress-warning') {
11603 return;
11604 }
11605 const { message, link } = deprecationData$1[key];
11606 const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
11607 const err = new SyntaxError(msg);
11608 err.code = key;
11609 if (loc)
11610 err.loc = loc;
11611 context.onWarn(err);
11612 }
11613
11614 // The default decoder only provides escapes for characters reserved as part of
11615 // the template syntax, and is only used if the custom renderer did not provide
11616 // a platform-specific decoder.
11617 const decodeRE = /&(gt|lt|amp|apos|quot);/g;
11618 const decodeMap = {
11619 gt: '>',
11620 lt: '<',
11621 amp: '&',
11622 apos: "'",
11623 quot: '"'
11624 };
11625 const defaultParserOptions = {
11626 delimiters: [`{{`, `}}`],
11627 getNamespace: () => 0 /* HTML */,
11628 getTextMode: () => 0 /* DATA */,
11629 isVoidTag: NO,
11630 isPreTag: NO,
11631 isCustomElement: NO,
11632 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
11633 onError: defaultOnError,
11634 onWarn: defaultOnWarn,
11635 comments: true
11636 };
11637 function baseParse(content, options = {}) {
11638 const context = createParserContext(content, options);
11639 const start = getCursor(context);
11640 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
11641 }
11642 function createParserContext(content, rawOptions) {
11643 const options = extend({}, defaultParserOptions);
11644 let key;
11645 for (key in rawOptions) {
11646 // @ts-ignore
11647 options[key] =
11648 rawOptions[key] === undefined
11649 ? defaultParserOptions[key]
11650 : rawOptions[key];
11651 }
11652 return {
11653 options,
11654 column: 1,
11655 line: 1,
11656 offset: 0,
11657 originalSource: content,
11658 source: content,
11659 inPre: false,
11660 inVPre: false,
11661 onWarn: options.onWarn
11662 };
11663 }
11664 function parseChildren(context, mode, ancestors) {
11665 const parent = last(ancestors);
11666 const ns = parent ? parent.ns : 0 /* HTML */;
11667 const nodes = [];
11668 while (!isEnd(context, mode, ancestors)) {
11669 const s = context.source;
11670 let node = undefined;
11671 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
11672 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
11673 // '{{'
11674 node = parseInterpolation(context, mode);
11675 }
11676 else if (mode === 0 /* DATA */ && s[0] === '<') {
11677 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
11678 if (s.length === 1) {
11679 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
11680 }
11681 else if (s[1] === '!') {
11682 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
11683 if (startsWith(s, '<!--')) {
11684 node = parseComment(context);
11685 }
11686 else if (startsWith(s, '<!DOCTYPE')) {
11687 // Ignore DOCTYPE by a limitation.
11688 node = parseBogusComment(context);
11689 }
11690 else if (startsWith(s, '<![CDATA[')) {
11691 if (ns !== 0 /* HTML */) {
11692 node = parseCDATA(context, ancestors);
11693 }
11694 else {
11695 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
11696 node = parseBogusComment(context);
11697 }
11698 }
11699 else {
11700 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
11701 node = parseBogusComment(context);
11702 }
11703 }
11704 else if (s[1] === '/') {
11705 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
11706 if (s.length === 2) {
11707 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
11708 }
11709 else if (s[2] === '>') {
11710 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
11711 advanceBy(context, 3);
11712 continue;
11713 }
11714 else if (/[a-z]/i.test(s[2])) {
11715 emitError(context, 23 /* X_INVALID_END_TAG */);
11716 parseTag(context, 1 /* End */, parent);
11717 continue;
11718 }
11719 else {
11720 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
11721 node = parseBogusComment(context);
11722 }
11723 }
11724 else if (/[a-z]/i.test(s[1])) {
11725 node = parseElement(context, ancestors);
11726 }
11727 else if (s[1] === '?') {
11728 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
11729 node = parseBogusComment(context);
11730 }
11731 else {
11732 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
11733 }
11734 }
11735 }
11736 if (!node) {
11737 node = parseText(context, mode);
11738 }
11739 if (isArray(node)) {
11740 for (let i = 0; i < node.length; i++) {
11741 pushNode(nodes, node[i]);
11742 }
11743 }
11744 else {
11745 pushNode(nodes, node);
11746 }
11747 }
11748 // Whitespace handling strategy like v2
11749 let removedWhitespace = false;
11750 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
11751 const shouldCondense = context.options.whitespace !== 'preserve';
11752 for (let i = 0; i < nodes.length; i++) {
11753 const node = nodes[i];
11754 if (!context.inPre && node.type === 2 /* TEXT */) {
11755 if (!/[^\t\r\n\f ]/.test(node.content)) {
11756 const prev = nodes[i - 1];
11757 const next = nodes[i + 1];
11758 // Remove if:
11759 // - the whitespace is the first or last node, or:
11760 // - (condense mode) the whitespace is adjacent to a comment, or:
11761 // - (condense mode) the whitespace is between two elements AND contains newline
11762 if (!prev ||
11763 !next ||
11764 (shouldCondense &&
11765 (prev.type === 3 /* COMMENT */ ||
11766 next.type === 3 /* COMMENT */ ||
11767 (prev.type === 1 /* ELEMENT */ &&
11768 next.type === 1 /* ELEMENT */ &&
11769 /[\r\n]/.test(node.content))))) {
11770 removedWhitespace = true;
11771 nodes[i] = null;
11772 }
11773 else {
11774 // Otherwise, the whitespace is condensed into a single space
11775 node.content = ' ';
11776 }
11777 }
11778 else if (shouldCondense) {
11779 // in condense mode, consecutive whitespaces in text are condensed
11780 // down to a single space.
11781 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
11782 }
11783 }
11784 // Remove comment nodes if desired by configuration.
11785 else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
11786 removedWhitespace = true;
11787 nodes[i] = null;
11788 }
11789 }
11790 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
11791 // remove leading newline per html spec
11792 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
11793 const first = nodes[0];
11794 if (first && first.type === 2 /* TEXT */) {
11795 first.content = first.content.replace(/^\r?\n/, '');
11796 }
11797 }
11798 }
11799 return removedWhitespace ? nodes.filter(Boolean) : nodes;
11800 }
11801 function pushNode(nodes, node) {
11802 if (node.type === 2 /* TEXT */) {
11803 const prev = last(nodes);
11804 // Merge if both this and the previous node are text and those are
11805 // consecutive. This happens for cases like "a < b".
11806 if (prev &&
11807 prev.type === 2 /* TEXT */ &&
11808 prev.loc.end.offset === node.loc.start.offset) {
11809 prev.content += node.content;
11810 prev.loc.end = node.loc.end;
11811 prev.loc.source += node.loc.source;
11812 return;
11813 }
11814 }
11815 nodes.push(node);
11816 }
11817 function parseCDATA(context, ancestors) {
11818 advanceBy(context, 9);
11819 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
11820 if (context.source.length === 0) {
11821 emitError(context, 6 /* EOF_IN_CDATA */);
11822 }
11823 else {
11824 advanceBy(context, 3);
11825 }
11826 return nodes;
11827 }
11828 function parseComment(context) {
11829 const start = getCursor(context);
11830 let content;
11831 // Regular comment.
11832 const match = /--(\!)?>/.exec(context.source);
11833 if (!match) {
11834 content = context.source.slice(4);
11835 advanceBy(context, context.source.length);
11836 emitError(context, 7 /* EOF_IN_COMMENT */);
11837 }
11838 else {
11839 if (match.index <= 3) {
11840 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
11841 }
11842 if (match[1]) {
11843 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
11844 }
11845 content = context.source.slice(4, match.index);
11846 // Advancing with reporting nested comments.
11847 const s = context.source.slice(0, match.index);
11848 let prevIndex = 1, nestedIndex = 0;
11849 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
11850 advanceBy(context, nestedIndex - prevIndex + 1);
11851 if (nestedIndex + 4 < s.length) {
11852 emitError(context, 16 /* NESTED_COMMENT */);
11853 }
11854 prevIndex = nestedIndex + 1;
11855 }
11856 advanceBy(context, match.index + match[0].length - prevIndex + 1);
11857 }
11858 return {
11859 type: 3 /* COMMENT */,
11860 content,
11861 loc: getSelection(context, start)
11862 };
11863 }
11864 function parseBogusComment(context) {
11865 const start = getCursor(context);
11866 const contentStart = context.source[1] === '?' ? 1 : 2;
11867 let content;
11868 const closeIndex = context.source.indexOf('>');
11869 if (closeIndex === -1) {
11870 content = context.source.slice(contentStart);
11871 advanceBy(context, context.source.length);
11872 }
11873 else {
11874 content = context.source.slice(contentStart, closeIndex);
11875 advanceBy(context, closeIndex + 1);
11876 }
11877 return {
11878 type: 3 /* COMMENT */,
11879 content,
11880 loc: getSelection(context, start)
11881 };
11882 }
11883 function parseElement(context, ancestors) {
11884 // Start tag.
11885 const wasInPre = context.inPre;
11886 const wasInVPre = context.inVPre;
11887 const parent = last(ancestors);
11888 const element = parseTag(context, 0 /* Start */, parent);
11889 const isPreBoundary = context.inPre && !wasInPre;
11890 const isVPreBoundary = context.inVPre && !wasInVPre;
11891 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
11892 // #4030 self-closing <pre> tag
11893 if (isPreBoundary) {
11894 context.inPre = false;
11895 }
11896 if (isVPreBoundary) {
11897 context.inVPre = false;
11898 }
11899 return element;
11900 }
11901 // Children.
11902 ancestors.push(element);
11903 const mode = context.options.getTextMode(element, parent);
11904 const children = parseChildren(context, mode, ancestors);
11905 ancestors.pop();
11906 element.children = children;
11907 // End tag.
11908 if (startsWithEndTagOpen(context.source, element.tag)) {
11909 parseTag(context, 1 /* End */, parent);
11910 }
11911 else {
11912 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
11913 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
11914 const first = children[0];
11915 if (first && startsWith(first.loc.source, '<!--')) {
11916 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
11917 }
11918 }
11919 }
11920 element.loc = getSelection(context, element.loc.start);
11921 if (isPreBoundary) {
11922 context.inPre = false;
11923 }
11924 if (isVPreBoundary) {
11925 context.inVPre = false;
11926 }
11927 return element;
11928 }
11929 const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
11930 function parseTag(context, type, parent) {
11931 // Tag open.
11932 const start = getCursor(context);
11933 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
11934 const tag = match[1];
11935 const ns = context.options.getNamespace(tag, parent);
11936 advanceBy(context, match[0].length);
11937 advanceSpaces(context);
11938 // save current state in case we need to re-parse attributes with v-pre
11939 const cursor = getCursor(context);
11940 const currentSource = context.source;
11941 // check <pre> tag
11942 if (context.options.isPreTag(tag)) {
11943 context.inPre = true;
11944 }
11945 // Attributes.
11946 let props = parseAttributes(context, type);
11947 // check v-pre
11948 if (type === 0 /* Start */ &&
11949 !context.inVPre &&
11950 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
11951 context.inVPre = true;
11952 // reset context
11953 extend(context, cursor);
11954 context.source = currentSource;
11955 // re-parse attrs and filter out v-pre itself
11956 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
11957 }
11958 // Tag close.
11959 let isSelfClosing = false;
11960 if (context.source.length === 0) {
11961 emitError(context, 9 /* EOF_IN_TAG */);
11962 }
11963 else {
11964 isSelfClosing = startsWith(context.source, '/>');
11965 if (type === 1 /* End */ && isSelfClosing) {
11966 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
11967 }
11968 advanceBy(context, isSelfClosing ? 2 : 1);
11969 }
11970 if (type === 1 /* End */) {
11971 return;
11972 }
11973 let tagType = 0 /* ELEMENT */;
11974 if (!context.inVPre) {
11975 if (tag === 'slot') {
11976 tagType = 2 /* SLOT */;
11977 }
11978 else if (tag === 'template') {
11979 if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
11980 tagType = 3 /* TEMPLATE */;
11981 }
11982 }
11983 else if (isComponent(tag, props, context)) {
11984 tagType = 1 /* COMPONENT */;
11985 }
11986 }
11987 return {
11988 type: 1 /* ELEMENT */,
11989 ns,
11990 tag,
11991 tagType,
11992 props,
11993 isSelfClosing,
11994 children: [],
11995 loc: getSelection(context, start),
11996 codegenNode: undefined // to be created during transform phase
11997 };
11998 }
11999 function isComponent(tag, props, context) {
12000 const options = context.options;
12001 if (options.isCustomElement(tag)) {
12002 return false;
12003 }
12004 if (tag === 'component' ||
12005 /^[A-Z]/.test(tag) ||
12006 isCoreComponent(tag) ||
12007 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
12008 (options.isNativeTag && !options.isNativeTag(tag))) {
12009 return true;
12010 }
12011 // at this point the tag should be a native tag, but check for potential "is"
12012 // casting
12013 for (let i = 0; i < props.length; i++) {
12014 const p = props[i];
12015 if (p.type === 6 /* ATTRIBUTE */) {
12016 if (p.name === 'is' && p.value) {
12017 if (p.value.content.startsWith('vue:')) {
12018 return true;
12019 }
12020 }
12021 }
12022 else {
12023 // directive
12024 // v-is (TODO Deprecate)
12025 if (p.name === 'is') {
12026 return true;
12027 }
12028 else if (
12029 // :is on plain element - only treat as component in compat mode
12030 p.name === 'bind' &&
12031 isBindKey(p.arg, 'is') &&
12032 false &&
12033 checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
12034 return true;
12035 }
12036 }
12037 }
12038 }
12039 function parseAttributes(context, type) {
12040 const props = [];
12041 const attributeNames = new Set();
12042 while (context.source.length > 0 &&
12043 !startsWith(context.source, '>') &&
12044 !startsWith(context.source, '/>')) {
12045 if (startsWith(context.source, '/')) {
12046 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
12047 advanceBy(context, 1);
12048 advanceSpaces(context);
12049 continue;
12050 }
12051 if (type === 1 /* End */) {
12052 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
12053 }
12054 const attr = parseAttribute(context, attributeNames);
12055 // Trim whitespace between class
12056 // https://github.com/vuejs/vue-next/issues/4251
12057 if (attr.type === 6 /* ATTRIBUTE */ &&
12058 attr.value &&
12059 attr.name === 'class') {
12060 attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
12061 }
12062 if (type === 0 /* Start */) {
12063 props.push(attr);
12064 }
12065 if (/^[^\t\r\n\f />]/.test(context.source)) {
12066 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
12067 }
12068 advanceSpaces(context);
12069 }
12070 return props;
12071 }
12072 function parseAttribute(context, nameSet) {
12073 // Name.
12074 const start = getCursor(context);
12075 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
12076 const name = match[0];
12077 if (nameSet.has(name)) {
12078 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
12079 }
12080 nameSet.add(name);
12081 if (name[0] === '=') {
12082 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
12083 }
12084 {
12085 const pattern = /["'<]/g;
12086 let m;
12087 while ((m = pattern.exec(name))) {
12088 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
12089 }
12090 }
12091 advanceBy(context, name.length);
12092 // Value
12093 let value = undefined;
12094 if (/^[\t\r\n\f ]*=/.test(context.source)) {
12095 advanceSpaces(context);
12096 advanceBy(context, 1);
12097 advanceSpaces(context);
12098 value = parseAttributeValue(context);
12099 if (!value) {
12100 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
12101 }
12102 }
12103 const loc = getSelection(context, start);
12104 if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
12105 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
12106 let isPropShorthand = startsWith(name, '.');
12107 let dirName = match[1] ||
12108 (isPropShorthand || startsWith(name, ':')
12109 ? 'bind'
12110 : startsWith(name, '@')
12111 ? 'on'
12112 : 'slot');
12113 let arg;
12114 if (match[2]) {
12115 const isSlot = dirName === 'slot';
12116 const startOffset = name.lastIndexOf(match[2]);
12117 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
12118 let content = match[2];
12119 let isStatic = true;
12120 if (content.startsWith('[')) {
12121 isStatic = false;
12122 if (!content.endsWith(']')) {
12123 emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
12124 content = content.substr(1);
12125 }
12126 else {
12127 content = content.substr(1, content.length - 2);
12128 }
12129 }
12130 else if (isSlot) {
12131 // #1241 special case for v-slot: vuetify relies extensively on slot
12132 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
12133 // supports such usage so we are keeping it consistent with 2.x.
12134 content += match[3] || '';
12135 }
12136 arg = {
12137 type: 4 /* SIMPLE_EXPRESSION */,
12138 content,
12139 isStatic,
12140 constType: isStatic
12141 ? 3 /* CAN_STRINGIFY */
12142 : 0 /* NOT_CONSTANT */,
12143 loc
12144 };
12145 }
12146 if (value && value.isQuoted) {
12147 const valueLoc = value.loc;
12148 valueLoc.start.offset++;
12149 valueLoc.start.column++;
12150 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
12151 valueLoc.source = valueLoc.source.slice(1, -1);
12152 }
12153 const modifiers = match[3] ? match[3].substr(1).split('.') : [];
12154 if (isPropShorthand)
12155 modifiers.push('prop');
12156 return {
12157 type: 7 /* DIRECTIVE */,
12158 name: dirName,
12159 exp: value && {
12160 type: 4 /* SIMPLE_EXPRESSION */,
12161 content: value.content,
12162 isStatic: false,
12163 // Treat as non-constant by default. This can be potentially set to
12164 // other values by `transformExpression` to make it eligible for hoisting.
12165 constType: 0 /* NOT_CONSTANT */,
12166 loc: value.loc
12167 },
12168 arg,
12169 modifiers,
12170 loc
12171 };
12172 }
12173 // missing directive name or illegal directive name
12174 if (!context.inVPre && startsWith(name, 'v-')) {
12175 emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
12176 }
12177 return {
12178 type: 6 /* ATTRIBUTE */,
12179 name,
12180 value: value && {
12181 type: 2 /* TEXT */,
12182 content: value.content,
12183 loc: value.loc
12184 },
12185 loc
12186 };
12187 }
12188 function parseAttributeValue(context) {
12189 const start = getCursor(context);
12190 let content;
12191 const quote = context.source[0];
12192 const isQuoted = quote === `"` || quote === `'`;
12193 if (isQuoted) {
12194 // Quoted value.
12195 advanceBy(context, 1);
12196 const endIndex = context.source.indexOf(quote);
12197 if (endIndex === -1) {
12198 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
12199 }
12200 else {
12201 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
12202 advanceBy(context, 1);
12203 }
12204 }
12205 else {
12206 // Unquoted
12207 const match = /^[^\t\r\n\f >]+/.exec(context.source);
12208 if (!match) {
12209 return undefined;
12210 }
12211 const unexpectedChars = /["'<=`]/g;
12212 let m;
12213 while ((m = unexpectedChars.exec(match[0]))) {
12214 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
12215 }
12216 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
12217 }
12218 return { content, isQuoted, loc: getSelection(context, start) };
12219 }
12220 function parseInterpolation(context, mode) {
12221 const [open, close] = context.options.delimiters;
12222 const closeIndex = context.source.indexOf(close, open.length);
12223 if (closeIndex === -1) {
12224 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
12225 return undefined;
12226 }
12227 const start = getCursor(context);
12228 advanceBy(context, open.length);
12229 const innerStart = getCursor(context);
12230 const innerEnd = getCursor(context);
12231 const rawContentLength = closeIndex - open.length;
12232 const rawContent = context.source.slice(0, rawContentLength);
12233 const preTrimContent = parseTextData(context, rawContentLength, mode);
12234 const content = preTrimContent.trim();
12235 const startOffset = preTrimContent.indexOf(content);
12236 if (startOffset > 0) {
12237 advancePositionWithMutation(innerStart, rawContent, startOffset);
12238 }
12239 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
12240 advancePositionWithMutation(innerEnd, rawContent, endOffset);
12241 advanceBy(context, close.length);
12242 return {
12243 type: 5 /* INTERPOLATION */,
12244 content: {
12245 type: 4 /* SIMPLE_EXPRESSION */,
12246 isStatic: false,
12247 // Set `isConstant` to false by default and will decide in transformExpression
12248 constType: 0 /* NOT_CONSTANT */,
12249 content,
12250 loc: getSelection(context, innerStart, innerEnd)
12251 },
12252 loc: getSelection(context, start)
12253 };
12254 }
12255 function parseText(context, mode) {
12256 const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
12257 let endIndex = context.source.length;
12258 for (let i = 0; i < endTokens.length; i++) {
12259 const index = context.source.indexOf(endTokens[i], 1);
12260 if (index !== -1 && endIndex > index) {
12261 endIndex = index;
12262 }
12263 }
12264 const start = getCursor(context);
12265 const content = parseTextData(context, endIndex, mode);
12266 return {
12267 type: 2 /* TEXT */,
12268 content,
12269 loc: getSelection(context, start)
12270 };
12271 }
12272 /**
12273 * Get text data with a given length from the current location.
12274 * This translates HTML entities in the text data.
12275 */
12276 function parseTextData(context, length, mode) {
12277 const rawText = context.source.slice(0, length);
12278 advanceBy(context, length);
12279 if (mode === 2 /* RAWTEXT */ ||
12280 mode === 3 /* CDATA */ ||
12281 rawText.indexOf('&') === -1) {
12282 return rawText;
12283 }
12284 else {
12285 // DATA or RCDATA containing "&"". Entity decoding required.
12286 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
12287 }
12288 }
12289 function getCursor(context) {
12290 const { column, line, offset } = context;
12291 return { column, line, offset };
12292 }
12293 function getSelection(context, start, end) {
12294 end = end || getCursor(context);
12295 return {
12296 start,
12297 end,
12298 source: context.originalSource.slice(start.offset, end.offset)
12299 };
12300 }
12301 function last(xs) {
12302 return xs[xs.length - 1];
12303 }
12304 function startsWith(source, searchString) {
12305 return source.startsWith(searchString);
12306 }
12307 function advanceBy(context, numberOfCharacters) {
12308 const { source } = context;
12309 advancePositionWithMutation(context, source, numberOfCharacters);
12310 context.source = source.slice(numberOfCharacters);
12311 }
12312 function advanceSpaces(context) {
12313 const match = /^[\t\r\n\f ]+/.exec(context.source);
12314 if (match) {
12315 advanceBy(context, match[0].length);
12316 }
12317 }
12318 function getNewPosition(context, start, numberOfCharacters) {
12319 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
12320 }
12321 function emitError(context, code, offset, loc = getCursor(context)) {
12322 if (offset) {
12323 loc.offset += offset;
12324 loc.column += offset;
12325 }
12326 context.options.onError(createCompilerError(code, {
12327 start: loc,
12328 end: loc,
12329 source: ''
12330 }));
12331 }
12332 function isEnd(context, mode, ancestors) {
12333 const s = context.source;
12334 switch (mode) {
12335 case 0 /* DATA */:
12336 if (startsWith(s, '</')) {
12337 // TODO: probably bad performance
12338 for (let i = ancestors.length - 1; i >= 0; --i) {
12339 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
12340 return true;
12341 }
12342 }
12343 }
12344 break;
12345 case 1 /* RCDATA */:
12346 case 2 /* RAWTEXT */: {
12347 const parent = last(ancestors);
12348 if (parent && startsWithEndTagOpen(s, parent.tag)) {
12349 return true;
12350 }
12351 break;
12352 }
12353 case 3 /* CDATA */:
12354 if (startsWith(s, ']]>')) {
12355 return true;
12356 }
12357 break;
12358 }
12359 return !s;
12360 }
12361 function startsWithEndTagOpen(source, tag) {
12362 return (startsWith(source, '</') &&
12363 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
12364 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
12365 }
12366
12367 function hoistStatic(root, context) {
12368 walk(root, context,
12369 // Root node is unfortunately non-hoistable due to potential parent
12370 // fallthrough attributes.
12371 isSingleElementRoot(root, root.children[0]));
12372 }
12373 function isSingleElementRoot(root, child) {
12374 const { children } = root;
12375 return (children.length === 1 &&
12376 child.type === 1 /* ELEMENT */ &&
12377 !isSlotOutlet(child));
12378 }
12379 function walk(node, context, doNotHoistNode = false) {
12380 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
12381 // static bindings with expressions. These expressions are guaranteed to be
12382 // constant so they are still eligible for hoisting, but they are only
12383 // available at runtime and therefore cannot be evaluated ahead of time.
12384 // This is only a concern for pre-stringification (via transformHoist by
12385 // @vue/compiler-dom), but doing it here allows us to perform only one full
12386 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
12387 // stringficiation threshold is met.
12388 let canStringify = true;
12389 const { children } = node;
12390 const originalCount = children.length;
12391 let hoistedCount = 0;
12392 for (let i = 0; i < children.length; i++) {
12393 const child = children[i];
12394 // only plain elements & text calls are eligible for hoisting.
12395 if (child.type === 1 /* ELEMENT */ &&
12396 child.tagType === 0 /* ELEMENT */) {
12397 const constantType = doNotHoistNode
12398 ? 0 /* NOT_CONSTANT */
12399 : getConstantType(child, context);
12400 if (constantType > 0 /* NOT_CONSTANT */) {
12401 if (constantType < 3 /* CAN_STRINGIFY */) {
12402 canStringify = false;
12403 }
12404 if (constantType >= 2 /* CAN_HOIST */) {
12405 child.codegenNode.patchFlag =
12406 -1 /* HOISTED */ + (` /* HOISTED */` );
12407 child.codegenNode = context.hoist(child.codegenNode);
12408 hoistedCount++;
12409 continue;
12410 }
12411 }
12412 else {
12413 // node may contain dynamic children, but its props may be eligible for
12414 // hoisting.
12415 const codegenNode = child.codegenNode;
12416 if (codegenNode.type === 13 /* VNODE_CALL */) {
12417 const flag = getPatchFlag(codegenNode);
12418 if ((!flag ||
12419 flag === 512 /* NEED_PATCH */ ||
12420 flag === 1 /* TEXT */) &&
12421 getGeneratedPropsConstantType(child, context) >=
12422 2 /* CAN_HOIST */) {
12423 const props = getNodeProps(child);
12424 if (props) {
12425 codegenNode.props = context.hoist(props);
12426 }
12427 }
12428 if (codegenNode.dynamicProps) {
12429 codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
12430 }
12431 }
12432 }
12433 }
12434 else if (child.type === 12 /* TEXT_CALL */) {
12435 const contentType = getConstantType(child.content, context);
12436 if (contentType > 0) {
12437 if (contentType < 3 /* CAN_STRINGIFY */) {
12438 canStringify = false;
12439 }
12440 if (contentType >= 2 /* CAN_HOIST */) {
12441 child.codegenNode = context.hoist(child.codegenNode);
12442 hoistedCount++;
12443 }
12444 }
12445 }
12446 // walk further
12447 if (child.type === 1 /* ELEMENT */) {
12448 const isComponent = child.tagType === 1 /* COMPONENT */;
12449 if (isComponent) {
12450 context.scopes.vSlot++;
12451 }
12452 walk(child, context);
12453 if (isComponent) {
12454 context.scopes.vSlot--;
12455 }
12456 }
12457 else if (child.type === 11 /* FOR */) {
12458 // Do not hoist v-for single child because it has to be a block
12459 walk(child, context, child.children.length === 1);
12460 }
12461 else if (child.type === 9 /* IF */) {
12462 for (let i = 0; i < child.branches.length; i++) {
12463 // Do not hoist v-if single child because it has to be a block
12464 walk(child.branches[i], context, child.branches[i].children.length === 1);
12465 }
12466 }
12467 }
12468 if (canStringify && hoistedCount && context.transformHoist) {
12469 context.transformHoist(children, context, node);
12470 }
12471 // all children were hoisted - the entire children array is hoistable.
12472 if (hoistedCount &&
12473 hoistedCount === originalCount &&
12474 node.type === 1 /* ELEMENT */ &&
12475 node.tagType === 0 /* ELEMENT */ &&
12476 node.codegenNode &&
12477 node.codegenNode.type === 13 /* VNODE_CALL */ &&
12478 isArray(node.codegenNode.children)) {
12479 node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
12480 }
12481 }
12482 function getConstantType(node, context) {
12483 const { constantCache } = context;
12484 switch (node.type) {
12485 case 1 /* ELEMENT */:
12486 if (node.tagType !== 0 /* ELEMENT */) {
12487 return 0 /* NOT_CONSTANT */;
12488 }
12489 const cached = constantCache.get(node);
12490 if (cached !== undefined) {
12491 return cached;
12492 }
12493 const codegenNode = node.codegenNode;
12494 if (codegenNode.type !== 13 /* VNODE_CALL */) {
12495 return 0 /* NOT_CONSTANT */;
12496 }
12497 const flag = getPatchFlag(codegenNode);
12498 if (!flag) {
12499 let returnType = 3 /* CAN_STRINGIFY */;
12500 // Element itself has no patch flag. However we still need to check:
12501 // 1. Even for a node with no patch flag, it is possible for it to contain
12502 // non-hoistable expressions that refers to scope variables, e.g. compiler
12503 // injected keys or cached event handlers. Therefore we need to always
12504 // check the codegenNode's props to be sure.
12505 const generatedPropsType = getGeneratedPropsConstantType(node, context);
12506 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
12507 constantCache.set(node, 0 /* NOT_CONSTANT */);
12508 return 0 /* NOT_CONSTANT */;
12509 }
12510 if (generatedPropsType < returnType) {
12511 returnType = generatedPropsType;
12512 }
12513 // 2. its children.
12514 for (let i = 0; i < node.children.length; i++) {
12515 const childType = getConstantType(node.children[i], context);
12516 if (childType === 0 /* NOT_CONSTANT */) {
12517 constantCache.set(node, 0 /* NOT_CONSTANT */);
12518 return 0 /* NOT_CONSTANT */;
12519 }
12520 if (childType < returnType) {
12521 returnType = childType;
12522 }
12523 }
12524 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
12525 // type, check if any of the props can cause the type to be lowered
12526 // we can skip can_patch because it's guaranteed by the absence of a
12527 // patchFlag.
12528 if (returnType > 1 /* CAN_SKIP_PATCH */) {
12529 for (let i = 0; i < node.props.length; i++) {
12530 const p = node.props[i];
12531 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
12532 const expType = getConstantType(p.exp, context);
12533 if (expType === 0 /* NOT_CONSTANT */) {
12534 constantCache.set(node, 0 /* NOT_CONSTANT */);
12535 return 0 /* NOT_CONSTANT */;
12536 }
12537 if (expType < returnType) {
12538 returnType = expType;
12539 }
12540 }
12541 }
12542 }
12543 // only svg/foreignObject could be block here, however if they are
12544 // static then they don't need to be blocks since there will be no
12545 // nested updates.
12546 if (codegenNode.isBlock) {
12547 context.removeHelper(OPEN_BLOCK);
12548 context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
12549 codegenNode.isBlock = false;
12550 context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
12551 }
12552 constantCache.set(node, returnType);
12553 return returnType;
12554 }
12555 else {
12556 constantCache.set(node, 0 /* NOT_CONSTANT */);
12557 return 0 /* NOT_CONSTANT */;
12558 }
12559 case 2 /* TEXT */:
12560 case 3 /* COMMENT */:
12561 return 3 /* CAN_STRINGIFY */;
12562 case 9 /* IF */:
12563 case 11 /* FOR */:
12564 case 10 /* IF_BRANCH */:
12565 return 0 /* NOT_CONSTANT */;
12566 case 5 /* INTERPOLATION */:
12567 case 12 /* TEXT_CALL */:
12568 return getConstantType(node.content, context);
12569 case 4 /* SIMPLE_EXPRESSION */:
12570 return node.constType;
12571 case 8 /* COMPOUND_EXPRESSION */:
12572 let returnType = 3 /* CAN_STRINGIFY */;
12573 for (let i = 0; i < node.children.length; i++) {
12574 const child = node.children[i];
12575 if (isString(child) || isSymbol(child)) {
12576 continue;
12577 }
12578 const childType = getConstantType(child, context);
12579 if (childType === 0 /* NOT_CONSTANT */) {
12580 return 0 /* NOT_CONSTANT */;
12581 }
12582 else if (childType < returnType) {
12583 returnType = childType;
12584 }
12585 }
12586 return returnType;
12587 default:
12588 return 0 /* NOT_CONSTANT */;
12589 }
12590 }
12591 const allowHoistedHelperSet = new Set([
12592 NORMALIZE_CLASS,
12593 NORMALIZE_STYLE,
12594 NORMALIZE_PROPS,
12595 GUARD_REACTIVE_PROPS
12596 ]);
12597 function getConstantTypeOfHelperCall(value, context) {
12598 if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
12599 !isString(value.callee) &&
12600 allowHoistedHelperSet.has(value.callee)) {
12601 const arg = value.arguments[0];
12602 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12603 return getConstantType(arg, context);
12604 }
12605 else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
12606 // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
12607 return getConstantTypeOfHelperCall(arg, context);
12608 }
12609 }
12610 return 0 /* NOT_CONSTANT */;
12611 }
12612 function getGeneratedPropsConstantType(node, context) {
12613 let returnType = 3 /* CAN_STRINGIFY */;
12614 const props = getNodeProps(node);
12615 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
12616 const { properties } = props;
12617 for (let i = 0; i < properties.length; i++) {
12618 const { key, value } = properties[i];
12619 const keyType = getConstantType(key, context);
12620 if (keyType === 0 /* NOT_CONSTANT */) {
12621 return keyType;
12622 }
12623 if (keyType < returnType) {
12624 returnType = keyType;
12625 }
12626 let valueType;
12627 if (value.type === 4 /* SIMPLE_EXPRESSION */) {
12628 valueType = getConstantType(value, context);
12629 }
12630 else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
12631 // some helper calls can be hoisted,
12632 // such as the `normalizeProps` generated by the compiler for pre-normalize class,
12633 // in this case we need to respect the ConstanType of the helper's argments
12634 valueType = getConstantTypeOfHelperCall(value, context);
12635 }
12636 else {
12637 valueType = 0 /* NOT_CONSTANT */;
12638 }
12639 if (valueType === 0 /* NOT_CONSTANT */) {
12640 return valueType;
12641 }
12642 if (valueType < returnType) {
12643 returnType = valueType;
12644 }
12645 }
12646 }
12647 return returnType;
12648 }
12649 function getNodeProps(node) {
12650 const codegenNode = node.codegenNode;
12651 if (codegenNode.type === 13 /* VNODE_CALL */) {
12652 return codegenNode.props;
12653 }
12654 }
12655 function getPatchFlag(node) {
12656 const flag = node.patchFlag;
12657 return flag ? parseInt(flag, 10) : undefined;
12658 }
12659
12660 function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
12661 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
12662 const context = {
12663 // options
12664 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
12665 prefixIdentifiers,
12666 hoistStatic,
12667 cacheHandlers,
12668 nodeTransforms,
12669 directiveTransforms,
12670 transformHoist,
12671 isBuiltInComponent,
12672 isCustomElement,
12673 expressionPlugins,
12674 scopeId,
12675 slotted,
12676 ssr,
12677 inSSR,
12678 ssrCssVars,
12679 bindingMetadata,
12680 inline,
12681 isTS,
12682 onError,
12683 onWarn,
12684 compatConfig,
12685 // state
12686 root,
12687 helpers: new Map(),
12688 components: new Set(),
12689 directives: new Set(),
12690 hoists: [],
12691 imports: [],
12692 constantCache: new Map(),
12693 temps: 0,
12694 cached: 0,
12695 identifiers: Object.create(null),
12696 scopes: {
12697 vFor: 0,
12698 vSlot: 0,
12699 vPre: 0,
12700 vOnce: 0
12701 },
12702 parent: null,
12703 currentNode: root,
12704 childIndex: 0,
12705 inVOnce: false,
12706 // methods
12707 helper(name) {
12708 const count = context.helpers.get(name) || 0;
12709 context.helpers.set(name, count + 1);
12710 return name;
12711 },
12712 removeHelper(name) {
12713 const count = context.helpers.get(name);
12714 if (count) {
12715 const currentCount = count - 1;
12716 if (!currentCount) {
12717 context.helpers.delete(name);
12718 }
12719 else {
12720 context.helpers.set(name, currentCount);
12721 }
12722 }
12723 },
12724 helperString(name) {
12725 return `_${helperNameMap[context.helper(name)]}`;
12726 },
12727 replaceNode(node) {
12728 /* istanbul ignore if */
12729 {
12730 if (!context.currentNode) {
12731 throw new Error(`Node being replaced is already removed.`);
12732 }
12733 if (!context.parent) {
12734 throw new Error(`Cannot replace root node.`);
12735 }
12736 }
12737 context.parent.children[context.childIndex] = context.currentNode = node;
12738 },
12739 removeNode(node) {
12740 if (!context.parent) {
12741 throw new Error(`Cannot remove root node.`);
12742 }
12743 const list = context.parent.children;
12744 const removalIndex = node
12745 ? list.indexOf(node)
12746 : context.currentNode
12747 ? context.childIndex
12748 : -1;
12749 /* istanbul ignore if */
12750 if (removalIndex < 0) {
12751 throw new Error(`node being removed is not a child of current parent`);
12752 }
12753 if (!node || node === context.currentNode) {
12754 // current node removed
12755 context.currentNode = null;
12756 context.onNodeRemoved();
12757 }
12758 else {
12759 // sibling node removed
12760 if (context.childIndex > removalIndex) {
12761 context.childIndex--;
12762 context.onNodeRemoved();
12763 }
12764 }
12765 context.parent.children.splice(removalIndex, 1);
12766 },
12767 onNodeRemoved: () => { },
12768 addIdentifiers(exp) {
12769 },
12770 removeIdentifiers(exp) {
12771 },
12772 hoist(exp) {
12773 if (isString(exp))
12774 exp = createSimpleExpression(exp);
12775 context.hoists.push(exp);
12776 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
12777 identifier.hoisted = exp;
12778 return identifier;
12779 },
12780 cache(exp, isVNode = false) {
12781 return createCacheExpression(context.cached++, exp, isVNode);
12782 }
12783 };
12784 return context;
12785 }
12786 function transform(root, options) {
12787 const context = createTransformContext(root, options);
12788 traverseNode(root, context);
12789 if (options.hoistStatic) {
12790 hoistStatic(root, context);
12791 }
12792 if (!options.ssr) {
12793 createRootCodegen(root, context);
12794 }
12795 // finalize meta information
12796 root.helpers = [...context.helpers.keys()];
12797 root.components = [...context.components];
12798 root.directives = [...context.directives];
12799 root.imports = context.imports;
12800 root.hoists = context.hoists;
12801 root.temps = context.temps;
12802 root.cached = context.cached;
12803 }
12804 function createRootCodegen(root, context) {
12805 const { helper } = context;
12806 const { children } = root;
12807 if (children.length === 1) {
12808 const child = children[0];
12809 // if the single child is an element, turn it into a block.
12810 if (isSingleElementRoot(root, child) && child.codegenNode) {
12811 // single element root is never hoisted so codegenNode will never be
12812 // SimpleExpressionNode
12813 const codegenNode = child.codegenNode;
12814 if (codegenNode.type === 13 /* VNODE_CALL */) {
12815 makeBlock(codegenNode, context);
12816 }
12817 root.codegenNode = codegenNode;
12818 }
12819 else {
12820 // - single <slot/>, IfNode, ForNode: already blocks.
12821 // - single text node: always patched.
12822 // root codegen falls through via genNode()
12823 root.codegenNode = child;
12824 }
12825 }
12826 else if (children.length > 1) {
12827 // root has multiple nodes - return a fragment block.
12828 let patchFlag = 64 /* STABLE_FRAGMENT */;
12829 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12830 // check if the fragment actually contains a single valid child with
12831 // the rest being comments
12832 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12833 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12834 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12835 }
12836 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
12837 }
12838 else ;
12839 }
12840 function traverseChildren(parent, context) {
12841 let i = 0;
12842 const nodeRemoved = () => {
12843 i--;
12844 };
12845 for (; i < parent.children.length; i++) {
12846 const child = parent.children[i];
12847 if (isString(child))
12848 continue;
12849 context.parent = parent;
12850 context.childIndex = i;
12851 context.onNodeRemoved = nodeRemoved;
12852 traverseNode(child, context);
12853 }
12854 }
12855 function traverseNode(node, context) {
12856 context.currentNode = node;
12857 // apply transform plugins
12858 const { nodeTransforms } = context;
12859 const exitFns = [];
12860 for (let i = 0; i < nodeTransforms.length; i++) {
12861 const onExit = nodeTransforms[i](node, context);
12862 if (onExit) {
12863 if (isArray(onExit)) {
12864 exitFns.push(...onExit);
12865 }
12866 else {
12867 exitFns.push(onExit);
12868 }
12869 }
12870 if (!context.currentNode) {
12871 // node was removed
12872 return;
12873 }
12874 else {
12875 // node may have been replaced
12876 node = context.currentNode;
12877 }
12878 }
12879 switch (node.type) {
12880 case 3 /* COMMENT */:
12881 if (!context.ssr) {
12882 // inject import for the Comment symbol, which is needed for creating
12883 // comment nodes with `createVNode`
12884 context.helper(CREATE_COMMENT);
12885 }
12886 break;
12887 case 5 /* INTERPOLATION */:
12888 // no need to traverse, but we need to inject toString helper
12889 if (!context.ssr) {
12890 context.helper(TO_DISPLAY_STRING);
12891 }
12892 break;
12893 // for container types, further traverse downwards
12894 case 9 /* IF */:
12895 for (let i = 0; i < node.branches.length; i++) {
12896 traverseNode(node.branches[i], context);
12897 }
12898 break;
12899 case 10 /* IF_BRANCH */:
12900 case 11 /* FOR */:
12901 case 1 /* ELEMENT */:
12902 case 0 /* ROOT */:
12903 traverseChildren(node, context);
12904 break;
12905 }
12906 // exit transforms
12907 context.currentNode = node;
12908 let i = exitFns.length;
12909 while (i--) {
12910 exitFns[i]();
12911 }
12912 }
12913 function createStructuralDirectiveTransform(name, fn) {
12914 const matches = isString(name)
12915 ? (n) => n === name
12916 : (n) => name.test(n);
12917 return (node, context) => {
12918 if (node.type === 1 /* ELEMENT */) {
12919 const { props } = node;
12920 // structural directive transforms are not concerned with slots
12921 // as they are handled separately in vSlot.ts
12922 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
12923 return;
12924 }
12925 const exitFns = [];
12926 for (let i = 0; i < props.length; i++) {
12927 const prop = props[i];
12928 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
12929 // structural directives are removed to avoid infinite recursion
12930 // also we remove them *before* applying so that it can further
12931 // traverse itself in case it moves the node around
12932 props.splice(i, 1);
12933 i--;
12934 const onExit = fn(node, prop, context);
12935 if (onExit)
12936 exitFns.push(onExit);
12937 }
12938 }
12939 return exitFns;
12940 }
12941 };
12942 }
12943
12944 const PURE_ANNOTATION = `/*#__PURE__*/`;
12945 function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false, isTS = false, inSSR = false }) {
12946 const context = {
12947 mode,
12948 prefixIdentifiers,
12949 sourceMap,
12950 filename,
12951 scopeId,
12952 optimizeImports,
12953 runtimeGlobalName,
12954 runtimeModuleName,
12955 ssr,
12956 isTS,
12957 inSSR,
12958 source: ast.loc.source,
12959 code: ``,
12960 column: 1,
12961 line: 1,
12962 offset: 0,
12963 indentLevel: 0,
12964 pure: false,
12965 map: undefined,
12966 helper(key) {
12967 return `_${helperNameMap[key]}`;
12968 },
12969 push(code, node) {
12970 context.code += code;
12971 },
12972 indent() {
12973 newline(++context.indentLevel);
12974 },
12975 deindent(withoutNewLine = false) {
12976 if (withoutNewLine) {
12977 --context.indentLevel;
12978 }
12979 else {
12980 newline(--context.indentLevel);
12981 }
12982 },
12983 newline() {
12984 newline(context.indentLevel);
12985 }
12986 };
12987 function newline(n) {
12988 context.push('\n' + ` `.repeat(n));
12989 }
12990 return context;
12991 }
12992 function generate(ast, options = {}) {
12993 const context = createCodegenContext(ast, options);
12994 if (options.onContextCreated)
12995 options.onContextCreated(context);
12996 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
12997 const hasHelpers = ast.helpers.length > 0;
12998 const useWithBlock = !prefixIdentifiers && mode !== 'module';
12999 // preambles
13000 // in setup() inline mode, the preamble is generated in a sub context
13001 // and returned separately.
13002 const preambleContext = context;
13003 {
13004 genFunctionPreamble(ast, preambleContext);
13005 }
13006 // enter render function
13007 const functionName = ssr ? `ssrRender` : `render`;
13008 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
13009 const signature = args.join(', ');
13010 {
13011 push(`function ${functionName}(${signature}) {`);
13012 }
13013 indent();
13014 if (useWithBlock) {
13015 push(`with (_ctx) {`);
13016 indent();
13017 // function mode const declarations should be inside with block
13018 // also they should be renamed to avoid collision with user properties
13019 if (hasHelpers) {
13020 push(`const { ${ast.helpers
13021 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
13022 .join(', ')} } = _Vue`);
13023 push(`\n`);
13024 newline();
13025 }
13026 }
13027 // generate asset resolution statements
13028 if (ast.components.length) {
13029 genAssets(ast.components, 'component', context);
13030 if (ast.directives.length || ast.temps > 0) {
13031 newline();
13032 }
13033 }
13034 if (ast.directives.length) {
13035 genAssets(ast.directives, 'directive', context);
13036 if (ast.temps > 0) {
13037 newline();
13038 }
13039 }
13040 if (ast.temps > 0) {
13041 push(`let `);
13042 for (let i = 0; i < ast.temps; i++) {
13043 push(`${i > 0 ? `, ` : ``}_temp${i}`);
13044 }
13045 }
13046 if (ast.components.length || ast.directives.length || ast.temps) {
13047 push(`\n`);
13048 newline();
13049 }
13050 // generate the VNode tree expression
13051 if (!ssr) {
13052 push(`return `);
13053 }
13054 if (ast.codegenNode) {
13055 genNode(ast.codegenNode, context);
13056 }
13057 else {
13058 push(`null`);
13059 }
13060 if (useWithBlock) {
13061 deindent();
13062 push(`}`);
13063 }
13064 deindent();
13065 push(`}`);
13066 return {
13067 ast,
13068 code: context.code,
13069 preamble: ``,
13070 // SourceMapGenerator does have toJSON() method but it's not in the types
13071 map: context.map ? context.map.toJSON() : undefined
13072 };
13073 }
13074 function genFunctionPreamble(ast, context) {
13075 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
13076 const VueBinding = runtimeGlobalName;
13077 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
13078 // Generate const declaration for helpers
13079 // In prefix mode, we place the const declaration at top so it's done
13080 // only once; But if we not prefixing, we place the declaration inside the
13081 // with block so it doesn't incur the `in` check cost for every helper access.
13082 if (ast.helpers.length > 0) {
13083 {
13084 // "with" mode.
13085 // save Vue in a separate variable to avoid collision
13086 push(`const _Vue = ${VueBinding}\n`);
13087 // in "with" mode, helpers are declared inside the with block to avoid
13088 // has check cost, but hoists are lifted out of the function - we need
13089 // to provide the helper here.
13090 if (ast.hoists.length) {
13091 const staticHelpers = [
13092 CREATE_VNODE,
13093 CREATE_ELEMENT_VNODE,
13094 CREATE_COMMENT,
13095 CREATE_TEXT,
13096 CREATE_STATIC
13097 ]
13098 .filter(helper => ast.helpers.includes(helper))
13099 .map(aliasHelper)
13100 .join(', ');
13101 push(`const { ${staticHelpers} } = _Vue\n`);
13102 }
13103 }
13104 }
13105 genHoists(ast.hoists, context);
13106 newline();
13107 push(`return `);
13108 }
13109 function genAssets(assets, type, { helper, push, newline, isTS }) {
13110 const resolver = helper(type === 'component'
13111 ? RESOLVE_COMPONENT
13112 : RESOLVE_DIRECTIVE);
13113 for (let i = 0; i < assets.length; i++) {
13114 let id = assets[i];
13115 // potential component implicit self-reference inferred from SFC filename
13116 const maybeSelfReference = id.endsWith('__self');
13117 if (maybeSelfReference) {
13118 id = id.slice(0, -6);
13119 }
13120 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
13121 if (i < assets.length - 1) {
13122 newline();
13123 }
13124 }
13125 }
13126 function genHoists(hoists, context) {
13127 if (!hoists.length) {
13128 return;
13129 }
13130 context.pure = true;
13131 const { push, newline, helper, scopeId, mode } = context;
13132 newline();
13133 hoists.forEach((exp, i) => {
13134 if (exp) {
13135 push(`const _hoisted_${i + 1} = `);
13136 genNode(exp, context);
13137 newline();
13138 }
13139 });
13140 context.pure = false;
13141 }
13142 function isText$1(n) {
13143 return (isString(n) ||
13144 n.type === 4 /* SIMPLE_EXPRESSION */ ||
13145 n.type === 2 /* TEXT */ ||
13146 n.type === 5 /* INTERPOLATION */ ||
13147 n.type === 8 /* COMPOUND_EXPRESSION */);
13148 }
13149 function genNodeListAsArray(nodes, context) {
13150 const multilines = nodes.length > 3 ||
13151 (nodes.some(n => isArray(n) || !isText$1(n)));
13152 context.push(`[`);
13153 multilines && context.indent();
13154 genNodeList(nodes, context, multilines);
13155 multilines && context.deindent();
13156 context.push(`]`);
13157 }
13158 function genNodeList(nodes, context, multilines = false, comma = true) {
13159 const { push, newline } = context;
13160 for (let i = 0; i < nodes.length; i++) {
13161 const node = nodes[i];
13162 if (isString(node)) {
13163 push(node);
13164 }
13165 else if (isArray(node)) {
13166 genNodeListAsArray(node, context);
13167 }
13168 else {
13169 genNode(node, context);
13170 }
13171 if (i < nodes.length - 1) {
13172 if (multilines) {
13173 comma && push(',');
13174 newline();
13175 }
13176 else {
13177 comma && push(', ');
13178 }
13179 }
13180 }
13181 }
13182 function genNode(node, context) {
13183 if (isString(node)) {
13184 context.push(node);
13185 return;
13186 }
13187 if (isSymbol(node)) {
13188 context.push(context.helper(node));
13189 return;
13190 }
13191 switch (node.type) {
13192 case 1 /* ELEMENT */:
13193 case 9 /* IF */:
13194 case 11 /* FOR */:
13195 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
13196 `Apply appropriate transforms first.`);
13197 genNode(node.codegenNode, context);
13198 break;
13199 case 2 /* TEXT */:
13200 genText(node, context);
13201 break;
13202 case 4 /* SIMPLE_EXPRESSION */:
13203 genExpression(node, context);
13204 break;
13205 case 5 /* INTERPOLATION */:
13206 genInterpolation(node, context);
13207 break;
13208 case 12 /* TEXT_CALL */:
13209 genNode(node.codegenNode, context);
13210 break;
13211 case 8 /* COMPOUND_EXPRESSION */:
13212 genCompoundExpression(node, context);
13213 break;
13214 case 3 /* COMMENT */:
13215 genComment(node, context);
13216 break;
13217 case 13 /* VNODE_CALL */:
13218 genVNodeCall(node, context);
13219 break;
13220 case 14 /* JS_CALL_EXPRESSION */:
13221 genCallExpression(node, context);
13222 break;
13223 case 15 /* JS_OBJECT_EXPRESSION */:
13224 genObjectExpression(node, context);
13225 break;
13226 case 17 /* JS_ARRAY_EXPRESSION */:
13227 genArrayExpression(node, context);
13228 break;
13229 case 18 /* JS_FUNCTION_EXPRESSION */:
13230 genFunctionExpression(node, context);
13231 break;
13232 case 19 /* JS_CONDITIONAL_EXPRESSION */:
13233 genConditionalExpression(node, context);
13234 break;
13235 case 20 /* JS_CACHE_EXPRESSION */:
13236 genCacheExpression(node, context);
13237 break;
13238 case 21 /* JS_BLOCK_STATEMENT */:
13239 genNodeList(node.body, context, true, false);
13240 break;
13241 // SSR only types
13242 case 22 /* JS_TEMPLATE_LITERAL */:
13243 break;
13244 case 23 /* JS_IF_STATEMENT */:
13245 break;
13246 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
13247 break;
13248 case 25 /* JS_SEQUENCE_EXPRESSION */:
13249 break;
13250 case 26 /* JS_RETURN_STATEMENT */:
13251 break;
13252 /* istanbul ignore next */
13253 case 10 /* IF_BRANCH */:
13254 // noop
13255 break;
13256 default:
13257 {
13258 assert(false, `unhandled codegen node type: ${node.type}`);
13259 // make sure we exhaust all possible types
13260 const exhaustiveCheck = node;
13261 return exhaustiveCheck;
13262 }
13263 }
13264 }
13265 function genText(node, context) {
13266 context.push(JSON.stringify(node.content), node);
13267 }
13268 function genExpression(node, context) {
13269 const { content, isStatic } = node;
13270 context.push(isStatic ? JSON.stringify(content) : content, node);
13271 }
13272 function genInterpolation(node, context) {
13273 const { push, helper, pure } = context;
13274 if (pure)
13275 push(PURE_ANNOTATION);
13276 push(`${helper(TO_DISPLAY_STRING)}(`);
13277 genNode(node.content, context);
13278 push(`)`);
13279 }
13280 function genCompoundExpression(node, context) {
13281 for (let i = 0; i < node.children.length; i++) {
13282 const child = node.children[i];
13283 if (isString(child)) {
13284 context.push(child);
13285 }
13286 else {
13287 genNode(child, context);
13288 }
13289 }
13290 }
13291 function genExpressionAsPropertyKey(node, context) {
13292 const { push } = context;
13293 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
13294 push(`[`);
13295 genCompoundExpression(node, context);
13296 push(`]`);
13297 }
13298 else if (node.isStatic) {
13299 // only quote keys if necessary
13300 const text = isSimpleIdentifier(node.content)
13301 ? node.content
13302 : JSON.stringify(node.content);
13303 push(text, node);
13304 }
13305 else {
13306 push(`[${node.content}]`, node);
13307 }
13308 }
13309 function genComment(node, context) {
13310 const { push, helper, pure } = context;
13311 if (pure) {
13312 push(PURE_ANNOTATION);
13313 }
13314 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
13315 }
13316 function genVNodeCall(node, context) {
13317 const { push, helper, pure } = context;
13318 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
13319 if (directives) {
13320 push(helper(WITH_DIRECTIVES) + `(`);
13321 }
13322 if (isBlock) {
13323 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
13324 }
13325 if (pure) {
13326 push(PURE_ANNOTATION);
13327 }
13328 const callHelper = isBlock
13329 ? getVNodeBlockHelper(context.inSSR, isComponent)
13330 : getVNodeHelper(context.inSSR, isComponent);
13331 push(helper(callHelper) + `(`, node);
13332 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
13333 push(`)`);
13334 if (isBlock) {
13335 push(`)`);
13336 }
13337 if (directives) {
13338 push(`, `);
13339 genNode(directives, context);
13340 push(`)`);
13341 }
13342 }
13343 function genNullableArgs(args) {
13344 let i = args.length;
13345 while (i--) {
13346 if (args[i] != null)
13347 break;
13348 }
13349 return args.slice(0, i + 1).map(arg => arg || `null`);
13350 }
13351 // JavaScript
13352 function genCallExpression(node, context) {
13353 const { push, helper, pure } = context;
13354 const callee = isString(node.callee) ? node.callee : helper(node.callee);
13355 if (pure) {
13356 push(PURE_ANNOTATION);
13357 }
13358 push(callee + `(`, node);
13359 genNodeList(node.arguments, context);
13360 push(`)`);
13361 }
13362 function genObjectExpression(node, context) {
13363 const { push, indent, deindent, newline } = context;
13364 const { properties } = node;
13365 if (!properties.length) {
13366 push(`{}`, node);
13367 return;
13368 }
13369 const multilines = properties.length > 1 ||
13370 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
13371 push(multilines ? `{` : `{ `);
13372 multilines && indent();
13373 for (let i = 0; i < properties.length; i++) {
13374 const { key, value } = properties[i];
13375 // key
13376 genExpressionAsPropertyKey(key, context);
13377 push(`: `);
13378 // value
13379 genNode(value, context);
13380 if (i < properties.length - 1) {
13381 // will only reach this if it's multilines
13382 push(`,`);
13383 newline();
13384 }
13385 }
13386 multilines && deindent();
13387 push(multilines ? `}` : ` }`);
13388 }
13389 function genArrayExpression(node, context) {
13390 genNodeListAsArray(node.elements, context);
13391 }
13392 function genFunctionExpression(node, context) {
13393 const { push, indent, deindent } = context;
13394 const { params, returns, body, newline, isSlot } = node;
13395 if (isSlot) {
13396 // wrap slot functions with owner context
13397 push(`_${helperNameMap[WITH_CTX]}(`);
13398 }
13399 push(`(`, node);
13400 if (isArray(params)) {
13401 genNodeList(params, context);
13402 }
13403 else if (params) {
13404 genNode(params, context);
13405 }
13406 push(`) => `);
13407 if (newline || body) {
13408 push(`{`);
13409 indent();
13410 }
13411 if (returns) {
13412 if (newline) {
13413 push(`return `);
13414 }
13415 if (isArray(returns)) {
13416 genNodeListAsArray(returns, context);
13417 }
13418 else {
13419 genNode(returns, context);
13420 }
13421 }
13422 else if (body) {
13423 genNode(body, context);
13424 }
13425 if (newline || body) {
13426 deindent();
13427 push(`}`);
13428 }
13429 if (isSlot) {
13430 push(`)`);
13431 }
13432 }
13433 function genConditionalExpression(node, context) {
13434 const { test, consequent, alternate, newline: needNewline } = node;
13435 const { push, indent, deindent, newline } = context;
13436 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
13437 const needsParens = !isSimpleIdentifier(test.content);
13438 needsParens && push(`(`);
13439 genExpression(test, context);
13440 needsParens && push(`)`);
13441 }
13442 else {
13443 push(`(`);
13444 genNode(test, context);
13445 push(`)`);
13446 }
13447 needNewline && indent();
13448 context.indentLevel++;
13449 needNewline || push(` `);
13450 push(`? `);
13451 genNode(consequent, context);
13452 context.indentLevel--;
13453 needNewline && newline();
13454 needNewline || push(` `);
13455 push(`: `);
13456 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
13457 if (!isNested) {
13458 context.indentLevel++;
13459 }
13460 genNode(alternate, context);
13461 if (!isNested) {
13462 context.indentLevel--;
13463 }
13464 needNewline && deindent(true /* without newline */);
13465 }
13466 function genCacheExpression(node, context) {
13467 const { push, helper, indent, deindent, newline } = context;
13468 push(`_cache[${node.index}] || (`);
13469 if (node.isVNode) {
13470 indent();
13471 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
13472 newline();
13473 }
13474 push(`_cache[${node.index}] = `);
13475 genNode(node.value, context);
13476 if (node.isVNode) {
13477 push(`,`);
13478 newline();
13479 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
13480 newline();
13481 push(`_cache[${node.index}]`);
13482 deindent();
13483 }
13484 push(`)`);
13485 }
13486
13487 // these keywords should not appear inside expressions, but operators like
13488 // typeof, instanceof and in are allowed
13489 const prohibitedKeywordRE = new RegExp('\\b' +
13490 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
13491 'super,throw,while,yield,delete,export,import,return,switch,default,' +
13492 'extends,finally,continue,debugger,function,arguments,typeof,void')
13493 .split(',')
13494 .join('\\b|\\b') +
13495 '\\b');
13496 // strip strings in expressions
13497 const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
13498 /**
13499 * Validate a non-prefixed expression.
13500 * This is only called when using the in-browser runtime compiler since it
13501 * doesn't prefix expressions.
13502 */
13503 function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
13504 const exp = node.content;
13505 // empty expressions are validated per-directive since some directives
13506 // do allow empty expressions.
13507 if (!exp.trim()) {
13508 return;
13509 }
13510 try {
13511 new Function(asRawStatements
13512 ? ` ${exp} `
13513 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
13514 }
13515 catch (e) {
13516 let message = e.message;
13517 const keywordMatch = exp
13518 .replace(stripStringRE, '')
13519 .match(prohibitedKeywordRE);
13520 if (keywordMatch) {
13521 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
13522 }
13523 context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
13524 }
13525 }
13526
13527 const transformExpression = (node, context) => {
13528 if (node.type === 5 /* INTERPOLATION */) {
13529 node.content = processExpression(node.content, context);
13530 }
13531 else if (node.type === 1 /* ELEMENT */) {
13532 // handle directives on element
13533 for (let i = 0; i < node.props.length; i++) {
13534 const dir = node.props[i];
13535 // do not process for v-on & v-for since they are special handled
13536 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
13537 const exp = dir.exp;
13538 const arg = dir.arg;
13539 // do not process exp if this is v-on:arg - we need special handling
13540 // for wrapping inline statements.
13541 if (exp &&
13542 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
13543 !(dir.name === 'on' && arg)) {
13544 dir.exp = processExpression(exp, context,
13545 // slot args must be processed as function params
13546 dir.name === 'slot');
13547 }
13548 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
13549 dir.arg = processExpression(arg, context);
13550 }
13551 }
13552 }
13553 }
13554 };
13555 // Important: since this function uses Node.js only dependencies, it should
13556 // always be used with a leading !true check so that it can be
13557 // tree-shaken from the browser build.
13558 function processExpression(node, context,
13559 // some expressions like v-slot props & v-for aliases should be parsed as
13560 // function params
13561 asParams = false,
13562 // v-on handler values may contain multiple statements
13563 asRawStatements = false, localVars = Object.create(context.identifiers)) {
13564 {
13565 {
13566 // simple in-browser validation (same logic in 2.x)
13567 validateBrowserExpression(node, context, asParams, asRawStatements);
13568 }
13569 return node;
13570 }
13571 }
13572
13573 const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
13574 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
13575 // #1587: We need to dynamically increment the key based on the current
13576 // node's sibling nodes, since chained v-if/else branches are
13577 // rendered at the same depth
13578 const siblings = context.parent.children;
13579 let i = siblings.indexOf(ifNode);
13580 let key = 0;
13581 while (i-- >= 0) {
13582 const sibling = siblings[i];
13583 if (sibling && sibling.type === 9 /* IF */) {
13584 key += sibling.branches.length;
13585 }
13586 }
13587 // Exit callback. Complete the codegenNode when all children have been
13588 // transformed.
13589 return () => {
13590 if (isRoot) {
13591 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
13592 }
13593 else {
13594 // attach this branch's codegen node to the v-if root.
13595 const parentCondition = getParentCondition(ifNode.codegenNode);
13596 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
13597 }
13598 };
13599 });
13600 });
13601 // target-agnostic transform used for both Client and SSR
13602 function processIf(node, dir, context, processCodegen) {
13603 if (dir.name !== 'else' &&
13604 (!dir.exp || !dir.exp.content.trim())) {
13605 const loc = dir.exp ? dir.exp.loc : node.loc;
13606 context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
13607 dir.exp = createSimpleExpression(`true`, false, loc);
13608 }
13609 if (dir.exp) {
13610 validateBrowserExpression(dir.exp, context);
13611 }
13612 if (dir.name === 'if') {
13613 const branch = createIfBranch(node, dir);
13614 const ifNode = {
13615 type: 9 /* IF */,
13616 loc: node.loc,
13617 branches: [branch]
13618 };
13619 context.replaceNode(ifNode);
13620 if (processCodegen) {
13621 return processCodegen(ifNode, branch, true);
13622 }
13623 }
13624 else {
13625 // locate the adjacent v-if
13626 const siblings = context.parent.children;
13627 const comments = [];
13628 let i = siblings.indexOf(node);
13629 while (i-- >= -1) {
13630 const sibling = siblings[i];
13631 if (sibling && sibling.type === 3 /* COMMENT */) {
13632 context.removeNode(sibling);
13633 comments.unshift(sibling);
13634 continue;
13635 }
13636 if (sibling &&
13637 sibling.type === 2 /* TEXT */ &&
13638 !sibling.content.trim().length) {
13639 context.removeNode(sibling);
13640 continue;
13641 }
13642 if (sibling && sibling.type === 9 /* IF */) {
13643 // move the node to the if node's branches
13644 context.removeNode();
13645 const branch = createIfBranch(node, dir);
13646 if (comments.length &&
13647 // #3619 ignore comments if the v-if is direct child of <transition>
13648 !(context.parent &&
13649 context.parent.type === 1 /* ELEMENT */ &&
13650 isBuiltInType(context.parent.tag, 'transition'))) {
13651 branch.children = [...comments, ...branch.children];
13652 }
13653 // check if user is forcing same key on different branches
13654 {
13655 const key = branch.userKey;
13656 if (key) {
13657 sibling.branches.forEach(({ userKey }) => {
13658 if (isSameKey(userKey, key)) {
13659 context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
13660 }
13661 });
13662 }
13663 }
13664 sibling.branches.push(branch);
13665 const onExit = processCodegen && processCodegen(sibling, branch, false);
13666 // since the branch was removed, it will not be traversed.
13667 // make sure to traverse here.
13668 traverseNode(branch, context);
13669 // call on exit
13670 if (onExit)
13671 onExit();
13672 // make sure to reset currentNode after traversal to indicate this
13673 // node has been removed.
13674 context.currentNode = null;
13675 }
13676 else {
13677 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
13678 }
13679 break;
13680 }
13681 }
13682 }
13683 function createIfBranch(node, dir) {
13684 return {
13685 type: 10 /* IF_BRANCH */,
13686 loc: node.loc,
13687 condition: dir.name === 'else' ? undefined : dir.exp,
13688 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
13689 ? node.children
13690 : [node],
13691 userKey: findProp(node, `key`)
13692 };
13693 }
13694 function createCodegenNodeForBranch(branch, keyIndex, context) {
13695 if (branch.condition) {
13696 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
13697 // make sure to pass in asBlock: true so that the comment node call
13698 // closes the current block.
13699 createCallExpression(context.helper(CREATE_COMMENT), [
13700 '"v-if"' ,
13701 'true'
13702 ]));
13703 }
13704 else {
13705 return createChildrenCodegenNode(branch, keyIndex, context);
13706 }
13707 }
13708 function createChildrenCodegenNode(branch, keyIndex, context) {
13709 const { helper } = context;
13710 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
13711 const { children } = branch;
13712 const firstChild = children[0];
13713 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
13714 if (needFragmentWrapper) {
13715 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
13716 // optimize away nested fragments when child is a ForNode
13717 const vnodeCall = firstChild.codegenNode;
13718 injectProp(vnodeCall, keyProperty, context);
13719 return vnodeCall;
13720 }
13721 else {
13722 let patchFlag = 64 /* STABLE_FRAGMENT */;
13723 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
13724 // check if the fragment actually contains a single valid child with
13725 // the rest being comments
13726 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
13727 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
13728 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
13729 }
13730 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
13731 }
13732 }
13733 else {
13734 const ret = firstChild.codegenNode;
13735 const vnodeCall = getMemoedVNodeCall(ret);
13736 // Change createVNode to createBlock.
13737 if (vnodeCall.type === 13 /* VNODE_CALL */) {
13738 makeBlock(vnodeCall, context);
13739 }
13740 // inject branch key
13741 injectProp(vnodeCall, keyProperty, context);
13742 return ret;
13743 }
13744 }
13745 function isSameKey(a, b) {
13746 if (!a || a.type !== b.type) {
13747 return false;
13748 }
13749 if (a.type === 6 /* ATTRIBUTE */) {
13750 if (a.value.content !== b.value.content) {
13751 return false;
13752 }
13753 }
13754 else {
13755 // directive
13756 const exp = a.exp;
13757 const branchExp = b.exp;
13758 if (exp.type !== branchExp.type) {
13759 return false;
13760 }
13761 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
13762 exp.isStatic !== branchExp.isStatic ||
13763 exp.content !== branchExp.content) {
13764 return false;
13765 }
13766 }
13767 return true;
13768 }
13769 function getParentCondition(node) {
13770 while (true) {
13771 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13772 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
13773 node = node.alternate;
13774 }
13775 else {
13776 return node;
13777 }
13778 }
13779 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
13780 node = node.value;
13781 }
13782 }
13783 }
13784
13785 const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
13786 const { helper, removeHelper } = context;
13787 return processFor(node, dir, context, forNode => {
13788 // create the loop render function expression now, and add the
13789 // iterator on exit after all children have been traversed
13790 const renderExp = createCallExpression(helper(RENDER_LIST), [
13791 forNode.source
13792 ]);
13793 const memo = findDir(node, 'memo');
13794 const keyProp = findProp(node, `key`);
13795 const keyExp = keyProp &&
13796 (keyProp.type === 6 /* ATTRIBUTE */
13797 ? createSimpleExpression(keyProp.value.content, true)
13798 : keyProp.exp);
13799 const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
13800 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
13801 forNode.source.constType > 0 /* NOT_CONSTANT */;
13802 const fragmentFlag = isStableFragment
13803 ? 64 /* STABLE_FRAGMENT */
13804 : keyProp
13805 ? 128 /* KEYED_FRAGMENT */
13806 : 256 /* UNKEYED_FRAGMENT */;
13807 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
13808 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
13809 return () => {
13810 // finish the codegen now that all children have been traversed
13811 let childBlock;
13812 const isTemplate = isTemplateNode(node);
13813 const { children } = forNode;
13814 // check <template v-for> key placement
13815 if (isTemplate) {
13816 node.children.some(c => {
13817 if (c.type === 1 /* ELEMENT */) {
13818 const key = findProp(c, 'key');
13819 if (key) {
13820 context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
13821 return true;
13822 }
13823 }
13824 });
13825 }
13826 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
13827 const slotOutlet = isSlotOutlet(node)
13828 ? node
13829 : isTemplate &&
13830 node.children.length === 1 &&
13831 isSlotOutlet(node.children[0])
13832 ? node.children[0] // api-extractor somehow fails to infer this
13833 : null;
13834 if (slotOutlet) {
13835 // <slot v-for="..."> or <template v-for="..."><slot/></template>
13836 childBlock = slotOutlet.codegenNode;
13837 if (isTemplate && keyProperty) {
13838 // <template v-for="..." :key="..."><slot/></template>
13839 // we need to inject the key to the renderSlot() call.
13840 // the props for renderSlot is passed as the 3rd argument.
13841 injectProp(childBlock, keyProperty, context);
13842 }
13843 }
13844 else if (needFragmentWrapper) {
13845 // <template v-for="..."> with text or multi-elements
13846 // should generate a fragment block for each loop
13847 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
13848 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
13849 ), undefined, undefined, true, undefined, false /* isComponent */);
13850 }
13851 else {
13852 // Normal element v-for. Directly use the child's codegenNode
13853 // but mark it as a block.
13854 childBlock = children[0]
13855 .codegenNode;
13856 if (isTemplate && keyProperty) {
13857 injectProp(childBlock, keyProperty, context);
13858 }
13859 if (childBlock.isBlock !== !isStableFragment) {
13860 if (childBlock.isBlock) {
13861 // switch from block to vnode
13862 removeHelper(OPEN_BLOCK);
13863 removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13864 }
13865 else {
13866 // switch from vnode to block
13867 removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13868 }
13869 }
13870 childBlock.isBlock = !isStableFragment;
13871 if (childBlock.isBlock) {
13872 helper(OPEN_BLOCK);
13873 helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
13874 }
13875 else {
13876 helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
13877 }
13878 }
13879 if (memo) {
13880 const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
13881 createSimpleExpression(`_cached`)
13882 ]));
13883 loop.body = createBlockStatement([
13884 createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
13885 createCompoundExpression([
13886 `if (_cached`,
13887 ...(keyExp ? [` && _cached.key === `, keyExp] : []),
13888 ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
13889 ]),
13890 createCompoundExpression([`const _item = `, childBlock]),
13891 createSimpleExpression(`_item.memo = _memo`),
13892 createSimpleExpression(`return _item`)
13893 ]);
13894 renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
13895 }
13896 else {
13897 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
13898 }
13899 };
13900 });
13901 });
13902 // target-agnostic transform used for both Client and SSR
13903 function processFor(node, dir, context, processCodegen) {
13904 if (!dir.exp) {
13905 context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
13906 return;
13907 }
13908 const parseResult = parseForExpression(
13909 // can only be simple expression because vFor transform is applied
13910 // before expression transform.
13911 dir.exp, context);
13912 if (!parseResult) {
13913 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
13914 return;
13915 }
13916 const { addIdentifiers, removeIdentifiers, scopes } = context;
13917 const { source, value, key, index } = parseResult;
13918 const forNode = {
13919 type: 11 /* FOR */,
13920 loc: dir.loc,
13921 source,
13922 valueAlias: value,
13923 keyAlias: key,
13924 objectIndexAlias: index,
13925 parseResult,
13926 children: isTemplateNode(node) ? node.children : [node]
13927 };
13928 context.replaceNode(forNode);
13929 // bookkeeping
13930 scopes.vFor++;
13931 const onExit = processCodegen && processCodegen(forNode);
13932 return () => {
13933 scopes.vFor--;
13934 if (onExit)
13935 onExit();
13936 };
13937 }
13938 const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
13939 // This regex doesn't cover the case if key or index aliases have destructuring,
13940 // but those do not make sense in the first place, so this works in practice.
13941 const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
13942 const stripParensRE = /^\(|\)$/g;
13943 function parseForExpression(input, context) {
13944 const loc = input.loc;
13945 const exp = input.content;
13946 const inMatch = exp.match(forAliasRE);
13947 if (!inMatch)
13948 return;
13949 const [, LHS, RHS] = inMatch;
13950 const result = {
13951 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
13952 value: undefined,
13953 key: undefined,
13954 index: undefined
13955 };
13956 {
13957 validateBrowserExpression(result.source, context);
13958 }
13959 let valueContent = LHS.trim().replace(stripParensRE, '').trim();
13960 const trimmedOffset = LHS.indexOf(valueContent);
13961 const iteratorMatch = valueContent.match(forIteratorRE);
13962 if (iteratorMatch) {
13963 valueContent = valueContent.replace(forIteratorRE, '').trim();
13964 const keyContent = iteratorMatch[1].trim();
13965 let keyOffset;
13966 if (keyContent) {
13967 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
13968 result.key = createAliasExpression(loc, keyContent, keyOffset);
13969 {
13970 validateBrowserExpression(result.key, context, true);
13971 }
13972 }
13973 if (iteratorMatch[2]) {
13974 const indexContent = iteratorMatch[2].trim();
13975 if (indexContent) {
13976 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
13977 ? keyOffset + keyContent.length
13978 : trimmedOffset + valueContent.length));
13979 {
13980 validateBrowserExpression(result.index, context, true);
13981 }
13982 }
13983 }
13984 }
13985 if (valueContent) {
13986 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
13987 {
13988 validateBrowserExpression(result.value, context, true);
13989 }
13990 }
13991 return result;
13992 }
13993 function createAliasExpression(range, content, offset) {
13994 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
13995 }
13996 function createForLoopParams({ value, key, index }, memoArgs = []) {
13997 return createParamsList([value, key, index, ...memoArgs]);
13998 }
13999 function createParamsList(args) {
14000 let i = args.length;
14001 while (i--) {
14002 if (args[i])
14003 break;
14004 }
14005 return args
14006 .slice(0, i + 1)
14007 .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
14008 }
14009
14010 const defaultFallback = createSimpleExpression(`undefined`, false);
14011 // A NodeTransform that:
14012 // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
14013 // by transformExpression. This is only applied in non-browser builds with
14014 // { prefixIdentifiers: true }.
14015 // 2. Track v-slot depths so that we know a slot is inside another slot.
14016 // Note the exit callback is executed before buildSlots() on the same node,
14017 // so only nested slots see positive numbers.
14018 const trackSlotScopes = (node, context) => {
14019 if (node.type === 1 /* ELEMENT */ &&
14020 (node.tagType === 1 /* COMPONENT */ ||
14021 node.tagType === 3 /* TEMPLATE */)) {
14022 // We are only checking non-empty v-slot here
14023 // since we only care about slots that introduce scope variables.
14024 const vSlot = findDir(node, 'slot');
14025 if (vSlot) {
14026 vSlot.exp;
14027 context.scopes.vSlot++;
14028 return () => {
14029 context.scopes.vSlot--;
14030 };
14031 }
14032 }
14033 };
14034 const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
14035 // Instead of being a DirectiveTransform, v-slot processing is called during
14036 // transformElement to build the slots object for a component.
14037 function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
14038 context.helper(WITH_CTX);
14039 const { children, loc } = node;
14040 const slotsProperties = [];
14041 const dynamicSlots = [];
14042 // If the slot is inside a v-for or another v-slot, force it to be dynamic
14043 // since it likely uses a scope variable.
14044 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
14045 // 1. Check for slot with slotProps on component itself.
14046 // <Comp v-slot="{ prop }"/>
14047 const onComponentSlot = findDir(node, 'slot', true);
14048 if (onComponentSlot) {
14049 const { arg, exp } = onComponentSlot;
14050 if (arg && !isStaticExp(arg)) {
14051 hasDynamicSlots = true;
14052 }
14053 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
14054 }
14055 // 2. Iterate through children and check for template slots
14056 // <template v-slot:foo="{ prop }">
14057 let hasTemplateSlots = false;
14058 let hasNamedDefaultSlot = false;
14059 const implicitDefaultChildren = [];
14060 const seenSlotNames = new Set();
14061 for (let i = 0; i < children.length; i++) {
14062 const slotElement = children[i];
14063 let slotDir;
14064 if (!isTemplateNode(slotElement) ||
14065 !(slotDir = findDir(slotElement, 'slot', true))) {
14066 // not a <template v-slot>, skip.
14067 if (slotElement.type !== 3 /* COMMENT */) {
14068 implicitDefaultChildren.push(slotElement);
14069 }
14070 continue;
14071 }
14072 if (onComponentSlot) {
14073 // already has on-component slot - this is incorrect usage.
14074 context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
14075 break;
14076 }
14077 hasTemplateSlots = true;
14078 const { children: slotChildren, loc: slotLoc } = slotElement;
14079 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
14080 // check if name is dynamic.
14081 let staticSlotName;
14082 if (isStaticExp(slotName)) {
14083 staticSlotName = slotName ? slotName.content : `default`;
14084 }
14085 else {
14086 hasDynamicSlots = true;
14087 }
14088 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
14089 // check if this slot is conditional (v-if/v-for)
14090 let vIf;
14091 let vElse;
14092 let vFor;
14093 if ((vIf = findDir(slotElement, 'if'))) {
14094 hasDynamicSlots = true;
14095 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
14096 }
14097 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
14098 // find adjacent v-if
14099 let j = i;
14100 let prev;
14101 while (j--) {
14102 prev = children[j];
14103 if (prev.type !== 3 /* COMMENT */) {
14104 break;
14105 }
14106 }
14107 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
14108 // remove node
14109 children.splice(i, 1);
14110 i--;
14111 // attach this slot to previous conditional
14112 let conditional = dynamicSlots[dynamicSlots.length - 1];
14113 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
14114 conditional = conditional.alternate;
14115 }
14116 conditional.alternate = vElse.exp
14117 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
14118 : buildDynamicSlot(slotName, slotFunction);
14119 }
14120 else {
14121 context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
14122 }
14123 }
14124 else if ((vFor = findDir(slotElement, 'for'))) {
14125 hasDynamicSlots = true;
14126 const parseResult = vFor.parseResult ||
14127 parseForExpression(vFor.exp, context);
14128 if (parseResult) {
14129 // Render the dynamic slots as an array and add it to the createSlot()
14130 // args. The runtime knows how to handle it appropriately.
14131 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
14132 parseResult.source,
14133 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
14134 ]));
14135 }
14136 else {
14137 context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
14138 }
14139 }
14140 else {
14141 // check duplicate static names
14142 if (staticSlotName) {
14143 if (seenSlotNames.has(staticSlotName)) {
14144 context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
14145 continue;
14146 }
14147 seenSlotNames.add(staticSlotName);
14148 if (staticSlotName === 'default') {
14149 hasNamedDefaultSlot = true;
14150 }
14151 }
14152 slotsProperties.push(createObjectProperty(slotName, slotFunction));
14153 }
14154 }
14155 if (!onComponentSlot) {
14156 const buildDefaultSlotProperty = (props, children) => {
14157 const fn = buildSlotFn(props, children, loc);
14158 return createObjectProperty(`default`, fn);
14159 };
14160 if (!hasTemplateSlots) {
14161 // implicit default slot (on component)
14162 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
14163 }
14164 else if (implicitDefaultChildren.length &&
14165 // #3766
14166 // with whitespace: 'preserve', whitespaces between slots will end up in
14167 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
14168 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
14169 // implicit default slot (mixed with named slots)
14170 if (hasNamedDefaultSlot) {
14171 context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
14172 }
14173 else {
14174 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
14175 }
14176 }
14177 }
14178 const slotFlag = hasDynamicSlots
14179 ? 2 /* DYNAMIC */
14180 : hasForwardedSlots(node.children)
14181 ? 3 /* FORWARDED */
14182 : 1 /* STABLE */;
14183 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
14184 // 2 = compiled but dynamic = can skip normalization, but must run diff
14185 // 1 = compiled and static = can skip normalization AND diff as optimized
14186 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
14187 if (dynamicSlots.length) {
14188 slots = createCallExpression(context.helper(CREATE_SLOTS), [
14189 slots,
14190 createArrayExpression(dynamicSlots)
14191 ]);
14192 }
14193 return {
14194 slots,
14195 hasDynamicSlots
14196 };
14197 }
14198 function buildDynamicSlot(name, fn) {
14199 return createObjectExpression([
14200 createObjectProperty(`name`, name),
14201 createObjectProperty(`fn`, fn)
14202 ]);
14203 }
14204 function hasForwardedSlots(children) {
14205 for (let i = 0; i < children.length; i++) {
14206 const child = children[i];
14207 switch (child.type) {
14208 case 1 /* ELEMENT */:
14209 if (child.tagType === 2 /* SLOT */ ||
14210 hasForwardedSlots(child.children)) {
14211 return true;
14212 }
14213 break;
14214 case 9 /* IF */:
14215 if (hasForwardedSlots(child.branches))
14216 return true;
14217 break;
14218 case 10 /* IF_BRANCH */:
14219 case 11 /* FOR */:
14220 if (hasForwardedSlots(child.children))
14221 return true;
14222 break;
14223 }
14224 }
14225 return false;
14226 }
14227 function isNonWhitespaceContent(node) {
14228 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
14229 return true;
14230 return node.type === 2 /* TEXT */
14231 ? !!node.content.trim()
14232 : isNonWhitespaceContent(node.content);
14233 }
14234
14235 // some directive transforms (e.g. v-model) may return a symbol for runtime
14236 // import, which should be used instead of a resolveDirective call.
14237 const directiveImportMap = new WeakMap();
14238 // generate a JavaScript AST for this element's codegen
14239 const transformElement = (node, context) => {
14240 // perform the work on exit, after all child expressions have been
14241 // processed and merged.
14242 return function postTransformElement() {
14243 node = context.currentNode;
14244 if (!(node.type === 1 /* ELEMENT */ &&
14245 (node.tagType === 0 /* ELEMENT */ ||
14246 node.tagType === 1 /* COMPONENT */))) {
14247 return;
14248 }
14249 const { tag, props } = node;
14250 const isComponent = node.tagType === 1 /* COMPONENT */;
14251 // The goal of the transform is to create a codegenNode implementing the
14252 // VNodeCall interface.
14253 let vnodeTag = isComponent
14254 ? resolveComponentType(node, context)
14255 : `"${tag}"`;
14256 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
14257 let vnodeProps;
14258 let vnodeChildren;
14259 let vnodePatchFlag;
14260 let patchFlag = 0;
14261 let vnodeDynamicProps;
14262 let dynamicPropNames;
14263 let vnodeDirectives;
14264 let shouldUseBlock =
14265 // dynamic component may resolve to plain elements
14266 isDynamicComponent ||
14267 vnodeTag === TELEPORT ||
14268 vnodeTag === SUSPENSE ||
14269 (!isComponent &&
14270 // <svg> and <foreignObject> must be forced into blocks so that block
14271 // updates inside get proper isSVG flag at runtime. (#639, #643)
14272 // This is technically web-specific, but splitting the logic out of core
14273 // leads to too much unnecessary complexity.
14274 (tag === 'svg' ||
14275 tag === 'foreignObject' ||
14276 // #938: elements with dynamic keys should be forced into blocks
14277 findProp(node, 'key', true)));
14278 // props
14279 if (props.length > 0) {
14280 const propsBuildResult = buildProps(node, context);
14281 vnodeProps = propsBuildResult.props;
14282 patchFlag = propsBuildResult.patchFlag;
14283 dynamicPropNames = propsBuildResult.dynamicPropNames;
14284 const directives = propsBuildResult.directives;
14285 vnodeDirectives =
14286 directives && directives.length
14287 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
14288 : undefined;
14289 }
14290 // children
14291 if (node.children.length > 0) {
14292 if (vnodeTag === KEEP_ALIVE) {
14293 // Although a built-in component, we compile KeepAlive with raw children
14294 // instead of slot functions so that it can be used inside Transition
14295 // or other Transition-wrapping HOCs.
14296 // To ensure correct updates with block optimizations, we need to:
14297 // 1. Force keep-alive into a block. This avoids its children being
14298 // collected by a parent block.
14299 shouldUseBlock = true;
14300 // 2. Force keep-alive to always be updated, since it uses raw children.
14301 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14302 if (node.children.length > 1) {
14303 context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
14304 start: node.children[0].loc.start,
14305 end: node.children[node.children.length - 1].loc.end,
14306 source: ''
14307 }));
14308 }
14309 }
14310 const shouldBuildAsSlots = isComponent &&
14311 // Teleport is not a real component and has dedicated runtime handling
14312 vnodeTag !== TELEPORT &&
14313 // explained above.
14314 vnodeTag !== KEEP_ALIVE;
14315 if (shouldBuildAsSlots) {
14316 const { slots, hasDynamicSlots } = buildSlots(node, context);
14317 vnodeChildren = slots;
14318 if (hasDynamicSlots) {
14319 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
14320 }
14321 }
14322 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
14323 const child = node.children[0];
14324 const type = child.type;
14325 // check for dynamic text children
14326 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
14327 type === 8 /* COMPOUND_EXPRESSION */;
14328 if (hasDynamicTextChild &&
14329 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
14330 patchFlag |= 1 /* TEXT */;
14331 }
14332 // pass directly if the only child is a text node
14333 // (plain / interpolation / expression)
14334 if (hasDynamicTextChild || type === 2 /* TEXT */) {
14335 vnodeChildren = child;
14336 }
14337 else {
14338 vnodeChildren = node.children;
14339 }
14340 }
14341 else {
14342 vnodeChildren = node.children;
14343 }
14344 }
14345 // patchFlag & dynamicPropNames
14346 if (patchFlag !== 0) {
14347 {
14348 if (patchFlag < 0) {
14349 // special flags (negative and mutually exclusive)
14350 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
14351 }
14352 else {
14353 // bitwise flags
14354 const flagNames = Object.keys(PatchFlagNames)
14355 .map(Number)
14356 .filter(n => n > 0 && patchFlag & n)
14357 .map(n => PatchFlagNames[n])
14358 .join(`, `);
14359 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
14360 }
14361 }
14362 if (dynamicPropNames && dynamicPropNames.length) {
14363 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
14364 }
14365 }
14366 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
14367 };
14368 };
14369 function resolveComponentType(node, context, ssr = false) {
14370 let { tag } = node;
14371 // 1. dynamic component
14372 const isExplicitDynamic = isComponentTag(tag);
14373 const isProp = findProp(node, 'is');
14374 if (isProp) {
14375 if (isExplicitDynamic ||
14376 (false )) {
14377 const exp = isProp.type === 6 /* ATTRIBUTE */
14378 ? isProp.value && createSimpleExpression(isProp.value.content, true)
14379 : isProp.exp;
14380 if (exp) {
14381 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14382 exp
14383 ]);
14384 }
14385 }
14386 else if (isProp.type === 6 /* ATTRIBUTE */ &&
14387 isProp.value.content.startsWith('vue:')) {
14388 // <button is="vue:xxx">
14389 // if not <component>, only is value that starts with "vue:" will be
14390 // treated as component by the parse phase and reach here, unless it's
14391 // compat mode where all is values are considered components
14392 tag = isProp.value.content.slice(4);
14393 }
14394 }
14395 // 1.5 v-is (TODO: Deprecate)
14396 const isDir = !isExplicitDynamic && findDir(node, 'is');
14397 if (isDir && isDir.exp) {
14398 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
14399 isDir.exp
14400 ]);
14401 }
14402 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
14403 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
14404 if (builtIn) {
14405 // built-ins are simply fallthroughs / have special handling during ssr
14406 // so we don't need to import their runtime equivalents
14407 if (!ssr)
14408 context.helper(builtIn);
14409 return builtIn;
14410 }
14411 // 5. user component (resolve)
14412 context.helper(RESOLVE_COMPONENT);
14413 context.components.add(tag);
14414 return toValidAssetId(tag, `component`);
14415 }
14416 function buildProps(node, context, props = node.props, ssr = false) {
14417 const { tag, loc: elementLoc } = node;
14418 const isComponent = node.tagType === 1 /* COMPONENT */;
14419 let properties = [];
14420 const mergeArgs = [];
14421 const runtimeDirectives = [];
14422 // patchFlag analysis
14423 let patchFlag = 0;
14424 let hasRef = false;
14425 let hasClassBinding = false;
14426 let hasStyleBinding = false;
14427 let hasHydrationEventBinding = false;
14428 let hasDynamicKeys = false;
14429 let hasVnodeHook = false;
14430 const dynamicPropNames = [];
14431 const analyzePatchFlag = ({ key, value }) => {
14432 if (isStaticExp(key)) {
14433 const name = key.content;
14434 const isEventHandler = isOn(name);
14435 if (!isComponent &&
14436 isEventHandler &&
14437 // omit the flag for click handlers because hydration gives click
14438 // dedicated fast path.
14439 name.toLowerCase() !== 'onclick' &&
14440 // omit v-model handlers
14441 name !== 'onUpdate:modelValue' &&
14442 // omit onVnodeXXX hooks
14443 !isReservedProp(name)) {
14444 hasHydrationEventBinding = true;
14445 }
14446 if (isEventHandler && isReservedProp(name)) {
14447 hasVnodeHook = true;
14448 }
14449 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
14450 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
14451 value.type === 8 /* COMPOUND_EXPRESSION */) &&
14452 getConstantType(value, context) > 0)) {
14453 // skip if the prop is a cached handler or has constant value
14454 return;
14455 }
14456 if (name === 'ref') {
14457 hasRef = true;
14458 }
14459 else if (name === 'class') {
14460 hasClassBinding = true;
14461 }
14462 else if (name === 'style') {
14463 hasStyleBinding = true;
14464 }
14465 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
14466 dynamicPropNames.push(name);
14467 }
14468 // treat the dynamic class and style binding of the component as dynamic props
14469 if (isComponent &&
14470 (name === 'class' || name === 'style') &&
14471 !dynamicPropNames.includes(name)) {
14472 dynamicPropNames.push(name);
14473 }
14474 }
14475 else {
14476 hasDynamicKeys = true;
14477 }
14478 };
14479 for (let i = 0; i < props.length; i++) {
14480 // static attribute
14481 const prop = props[i];
14482 if (prop.type === 6 /* ATTRIBUTE */) {
14483 const { loc, name, value } = prop;
14484 let valueNode = createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc);
14485 if (name === 'ref') {
14486 hasRef = true;
14487 }
14488 // skip is on <component>, or is="vue:xxx"
14489 if (name === 'is' &&
14490 (isComponentTag(tag) ||
14491 (value && value.content.startsWith('vue:')) ||
14492 (false ))) {
14493 continue;
14494 }
14495 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), valueNode));
14496 }
14497 else {
14498 // directives
14499 const { name, arg, exp, loc } = prop;
14500 const isVBind = name === 'bind';
14501 const isVOn = name === 'on';
14502 // skip v-slot - it is handled by its dedicated transform.
14503 if (name === 'slot') {
14504 if (!isComponent) {
14505 context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
14506 }
14507 continue;
14508 }
14509 // skip v-once/v-memo - they are handled by dedicated transforms.
14510 if (name === 'once' || name === 'memo') {
14511 continue;
14512 }
14513 // skip v-is and :is on <component>
14514 if (name === 'is' ||
14515 (isVBind &&
14516 isBindKey(arg, 'is') &&
14517 (isComponentTag(tag) ||
14518 (false )))) {
14519 continue;
14520 }
14521 // skip v-on in SSR compilation
14522 if (isVOn && ssr) {
14523 continue;
14524 }
14525 // special case for v-bind and v-on with no argument
14526 if (!arg && (isVBind || isVOn)) {
14527 hasDynamicKeys = true;
14528 if (exp) {
14529 if (properties.length) {
14530 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14531 properties = [];
14532 }
14533 if (isVBind) {
14534 mergeArgs.push(exp);
14535 }
14536 else {
14537 // v-on="obj" -> toHandlers(obj)
14538 mergeArgs.push({
14539 type: 14 /* JS_CALL_EXPRESSION */,
14540 loc,
14541 callee: context.helper(TO_HANDLERS),
14542 arguments: [exp]
14543 });
14544 }
14545 }
14546 else {
14547 context.onError(createCompilerError(isVBind
14548 ? 34 /* X_V_BIND_NO_EXPRESSION */
14549 : 35 /* X_V_ON_NO_EXPRESSION */, loc));
14550 }
14551 continue;
14552 }
14553 const directiveTransform = context.directiveTransforms[name];
14554 if (directiveTransform) {
14555 // has built-in directive transform.
14556 const { props, needRuntime } = directiveTransform(prop, node, context);
14557 !ssr && props.forEach(analyzePatchFlag);
14558 properties.push(...props);
14559 if (needRuntime) {
14560 runtimeDirectives.push(prop);
14561 if (isSymbol(needRuntime)) {
14562 directiveImportMap.set(prop, needRuntime);
14563 }
14564 }
14565 }
14566 else {
14567 // no built-in transform, this is a user custom directive.
14568 runtimeDirectives.push(prop);
14569 }
14570 }
14571 }
14572 let propsExpression = undefined;
14573 // has v-bind="object" or v-on="object", wrap with mergeProps
14574 if (mergeArgs.length) {
14575 if (properties.length) {
14576 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
14577 }
14578 if (mergeArgs.length > 1) {
14579 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
14580 }
14581 else {
14582 // single v-bind with nothing else - no need for a mergeProps call
14583 propsExpression = mergeArgs[0];
14584 }
14585 }
14586 else if (properties.length) {
14587 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
14588 }
14589 // patchFlag analysis
14590 if (hasDynamicKeys) {
14591 patchFlag |= 16 /* FULL_PROPS */;
14592 }
14593 else {
14594 if (hasClassBinding && !isComponent) {
14595 patchFlag |= 2 /* CLASS */;
14596 }
14597 if (hasStyleBinding && !isComponent) {
14598 patchFlag |= 4 /* STYLE */;
14599 }
14600 if (dynamicPropNames.length) {
14601 patchFlag |= 8 /* PROPS */;
14602 }
14603 if (hasHydrationEventBinding) {
14604 patchFlag |= 32 /* HYDRATE_EVENTS */;
14605 }
14606 }
14607 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
14608 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
14609 patchFlag |= 512 /* NEED_PATCH */;
14610 }
14611 // pre-normalize props, SSR is skipped for now
14612 if (!context.inSSR && propsExpression) {
14613 switch (propsExpression.type) {
14614 case 15 /* JS_OBJECT_EXPRESSION */:
14615 // means that there is no v-bind,
14616 // but still need to deal with dynamic key binding
14617 let classKeyIndex = -1;
14618 let styleKeyIndex = -1;
14619 let hasDynamicKey = false;
14620 for (let i = 0; i < propsExpression.properties.length; i++) {
14621 const key = propsExpression.properties[i].key;
14622 if (isStaticExp(key)) {
14623 if (key.content === 'class') {
14624 classKeyIndex = i;
14625 }
14626 else if (key.content === 'style') {
14627 styleKeyIndex = i;
14628 }
14629 }
14630 else if (!key.isHandlerKey) {
14631 hasDynamicKey = true;
14632 }
14633 }
14634 const classProp = propsExpression.properties[classKeyIndex];
14635 const styleProp = propsExpression.properties[styleKeyIndex];
14636 // no dynamic key
14637 if (!hasDynamicKey) {
14638 if (classProp && !isStaticExp(classProp.value)) {
14639 classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
14640 }
14641 if (styleProp &&
14642 !isStaticExp(styleProp.value) &&
14643 // the static style is compiled into an object,
14644 // so use `hasStyleBinding` to ensure that it is a dynamic style binding
14645 (hasStyleBinding ||
14646 // v-bind:style and style both exist,
14647 // v-bind:style with static literal object
14648 styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
14649 styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
14650 }
14651 }
14652 else {
14653 // dynamic key binding, wrap with `normalizeProps`
14654 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
14655 }
14656 break;
14657 case 14 /* JS_CALL_EXPRESSION */:
14658 // mergeProps call, do nothing
14659 break;
14660 default:
14661 // single v-bind
14662 propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
14663 createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
14664 propsExpression
14665 ])
14666 ]);
14667 break;
14668 }
14669 }
14670 return {
14671 props: propsExpression,
14672 directives: runtimeDirectives,
14673 patchFlag,
14674 dynamicPropNames
14675 };
14676 }
14677 // Dedupe props in an object literal.
14678 // Literal duplicated attributes would have been warned during the parse phase,
14679 // however, it's possible to encounter duplicated `onXXX` handlers with different
14680 // modifiers. We also need to merge static and dynamic class / style attributes.
14681 // - onXXX handlers / style: merge into array
14682 // - class: merge into single expression with concatenation
14683 function dedupeProperties(properties) {
14684 const knownProps = new Map();
14685 const deduped = [];
14686 for (let i = 0; i < properties.length; i++) {
14687 const prop = properties[i];
14688 // dynamic keys are always allowed
14689 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
14690 deduped.push(prop);
14691 continue;
14692 }
14693 const name = prop.key.content;
14694 const existing = knownProps.get(name);
14695 if (existing) {
14696 if (name === 'style' || name === 'class' || name.startsWith('on')) {
14697 mergeAsArray$1(existing, prop);
14698 }
14699 // unexpected duplicate, should have emitted error during parse
14700 }
14701 else {
14702 knownProps.set(name, prop);
14703 deduped.push(prop);
14704 }
14705 }
14706 return deduped;
14707 }
14708 function mergeAsArray$1(existing, incoming) {
14709 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
14710 existing.value.elements.push(incoming.value);
14711 }
14712 else {
14713 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
14714 }
14715 }
14716 function buildDirectiveArgs(dir, context) {
14717 const dirArgs = [];
14718 const runtime = directiveImportMap.get(dir);
14719 if (runtime) {
14720 // built-in directive with runtime
14721 dirArgs.push(context.helperString(runtime));
14722 }
14723 else {
14724 {
14725 // inject statement for resolving directive
14726 context.helper(RESOLVE_DIRECTIVE);
14727 context.directives.add(dir.name);
14728 dirArgs.push(toValidAssetId(dir.name, `directive`));
14729 }
14730 }
14731 const { loc } = dir;
14732 if (dir.exp)
14733 dirArgs.push(dir.exp);
14734 if (dir.arg) {
14735 if (!dir.exp) {
14736 dirArgs.push(`void 0`);
14737 }
14738 dirArgs.push(dir.arg);
14739 }
14740 if (Object.keys(dir.modifiers).length) {
14741 if (!dir.arg) {
14742 if (!dir.exp) {
14743 dirArgs.push(`void 0`);
14744 }
14745 dirArgs.push(`void 0`);
14746 }
14747 const trueExpression = createSimpleExpression(`true`, false, loc);
14748 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
14749 }
14750 return createArrayExpression(dirArgs, dir.loc);
14751 }
14752 function stringifyDynamicPropNames(props) {
14753 let propsNamesString = `[`;
14754 for (let i = 0, l = props.length; i < l; i++) {
14755 propsNamesString += JSON.stringify(props[i]);
14756 if (i < l - 1)
14757 propsNamesString += ', ';
14758 }
14759 return propsNamesString + `]`;
14760 }
14761 function isComponentTag(tag) {
14762 return tag[0].toLowerCase() + tag.slice(1) === 'component';
14763 }
14764
14765 const transformSlotOutlet = (node, context) => {
14766 if (isSlotOutlet(node)) {
14767 const { children, loc } = node;
14768 const { slotName, slotProps } = processSlotOutlet(node, context);
14769 const slotArgs = [
14770 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
14771 slotName
14772 ];
14773 if (slotProps) {
14774 slotArgs.push(slotProps);
14775 }
14776 if (children.length) {
14777 if (!slotProps) {
14778 slotArgs.push(`{}`);
14779 }
14780 slotArgs.push(createFunctionExpression([], children, false, false, loc));
14781 }
14782 if (context.scopeId && !context.slotted) {
14783 if (!slotProps) {
14784 slotArgs.push(`{}`);
14785 }
14786 if (!children.length) {
14787 slotArgs.push(`undefined`);
14788 }
14789 slotArgs.push(`true`);
14790 }
14791 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
14792 }
14793 };
14794 function processSlotOutlet(node, context) {
14795 let slotName = `"default"`;
14796 let slotProps = undefined;
14797 const nonNameProps = [];
14798 for (let i = 0; i < node.props.length; i++) {
14799 const p = node.props[i];
14800 if (p.type === 6 /* ATTRIBUTE */) {
14801 if (p.value) {
14802 if (p.name === 'name') {
14803 slotName = JSON.stringify(p.value.content);
14804 }
14805 else {
14806 p.name = camelize(p.name);
14807 nonNameProps.push(p);
14808 }
14809 }
14810 }
14811 else {
14812 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
14813 if (p.exp)
14814 slotName = p.exp;
14815 }
14816 else {
14817 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
14818 p.arg.content = camelize(p.arg.content);
14819 }
14820 nonNameProps.push(p);
14821 }
14822 }
14823 }
14824 if (nonNameProps.length > 0) {
14825 const { props, directives } = buildProps(node, context, nonNameProps);
14826 slotProps = props;
14827 if (directives.length) {
14828 context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
14829 }
14830 }
14831 return {
14832 slotName,
14833 slotProps
14834 };
14835 }
14836
14837 const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
14838 const transformOn = (dir, node, context, augmentor) => {
14839 const { loc, modifiers, arg } = dir;
14840 if (!dir.exp && !modifiers.length) {
14841 context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
14842 }
14843 let eventName;
14844 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14845 if (arg.isStatic) {
14846 const rawName = arg.content;
14847 // for all event listeners, auto convert it to camelCase. See issue #2249
14848 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
14849 }
14850 else {
14851 // #2388
14852 eventName = createCompoundExpression([
14853 `${context.helperString(TO_HANDLER_KEY)}(`,
14854 arg,
14855 `)`
14856 ]);
14857 }
14858 }
14859 else {
14860 // already a compound expression.
14861 eventName = arg;
14862 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
14863 eventName.children.push(`)`);
14864 }
14865 // handler processing
14866 let exp = dir.exp;
14867 if (exp && !exp.content.trim()) {
14868 exp = undefined;
14869 }
14870 let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
14871 if (exp) {
14872 const isMemberExp = isMemberExpression(exp.content);
14873 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
14874 const hasMultipleStatements = exp.content.includes(`;`);
14875 {
14876 validateBrowserExpression(exp, context, false, hasMultipleStatements);
14877 }
14878 if (isInlineStatement || (shouldCache && isMemberExp)) {
14879 // wrap inline statement in a function expression
14880 exp = createCompoundExpression([
14881 `${isInlineStatement
14882 ? `$event`
14883 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
14884 exp,
14885 hasMultipleStatements ? `}` : `)`
14886 ]);
14887 }
14888 }
14889 let ret = {
14890 props: [
14891 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
14892 ]
14893 };
14894 // apply extended compiler augmentor
14895 if (augmentor) {
14896 ret = augmentor(ret);
14897 }
14898 if (shouldCache) {
14899 // cache handlers so that it's always the same handler being passed down.
14900 // this avoids unnecessary re-renders when users use inline handlers on
14901 // components.
14902 ret.props[0].value = context.cache(ret.props[0].value);
14903 }
14904 // mark the key as handler for props normalization check
14905 ret.props.forEach(p => (p.key.isHandlerKey = true));
14906 return ret;
14907 };
14908
14909 // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
14910 // codegen for the entire props object. This transform here is only for v-bind
14911 // *with* args.
14912 const transformBind = (dir, _node, context) => {
14913 const { exp, modifiers, loc } = dir;
14914 const arg = dir.arg;
14915 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
14916 arg.children.unshift(`(`);
14917 arg.children.push(`) || ""`);
14918 }
14919 else if (!arg.isStatic) {
14920 arg.content = `${arg.content} || ""`;
14921 }
14922 // .sync is replaced by v-model:arg
14923 if (modifiers.includes('camel')) {
14924 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14925 if (arg.isStatic) {
14926 arg.content = camelize(arg.content);
14927 }
14928 else {
14929 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
14930 }
14931 }
14932 else {
14933 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
14934 arg.children.push(`)`);
14935 }
14936 }
14937 if (!context.inSSR) {
14938 if (modifiers.includes('prop')) {
14939 injectPrefix(arg, '.');
14940 }
14941 if (modifiers.includes('attr')) {
14942 injectPrefix(arg, '^');
14943 }
14944 }
14945 if (!exp ||
14946 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
14947 context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
14948 return {
14949 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
14950 };
14951 }
14952 return {
14953 props: [createObjectProperty(arg, exp)]
14954 };
14955 };
14956 const injectPrefix = (arg, prefix) => {
14957 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
14958 if (arg.isStatic) {
14959 arg.content = prefix + arg.content;
14960 }
14961 else {
14962 arg.content = `\`${prefix}\${${arg.content}}\``;
14963 }
14964 }
14965 else {
14966 arg.children.unshift(`'${prefix}' + (`);
14967 arg.children.push(`)`);
14968 }
14969 };
14970
14971 // Merge adjacent text nodes and expressions into a single expression
14972 // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
14973 const transformText = (node, context) => {
14974 if (node.type === 0 /* ROOT */ ||
14975 node.type === 1 /* ELEMENT */ ||
14976 node.type === 11 /* FOR */ ||
14977 node.type === 10 /* IF_BRANCH */) {
14978 // perform the transform on node exit so that all expressions have already
14979 // been processed.
14980 return () => {
14981 const children = node.children;
14982 let currentContainer = undefined;
14983 let hasText = false;
14984 for (let i = 0; i < children.length; i++) {
14985 const child = children[i];
14986 if (isText(child)) {
14987 hasText = true;
14988 for (let j = i + 1; j < children.length; j++) {
14989 const next = children[j];
14990 if (isText(next)) {
14991 if (!currentContainer) {
14992 currentContainer = children[i] = {
14993 type: 8 /* COMPOUND_EXPRESSION */,
14994 loc: child.loc,
14995 children: [child]
14996 };
14997 }
14998 // merge adjacent text node into current
14999 currentContainer.children.push(` + `, next);
15000 children.splice(j, 1);
15001 j--;
15002 }
15003 else {
15004 currentContainer = undefined;
15005 break;
15006 }
15007 }
15008 }
15009 }
15010 if (!hasText ||
15011 // if this is a plain element with a single text child, leave it
15012 // as-is since the runtime has dedicated fast path for this by directly
15013 // setting textContent of the element.
15014 // for component root it's always normalized anyway.
15015 (children.length === 1 &&
15016 (node.type === 0 /* ROOT */ ||
15017 (node.type === 1 /* ELEMENT */ &&
15018 node.tagType === 0 /* ELEMENT */ &&
15019 // #3756
15020 // custom directives can potentially add DOM elements arbitrarily,
15021 // we need to avoid setting textContent of the element at runtime
15022 // to avoid accidentally overwriting the DOM elements added
15023 // by the user through custom directives.
15024 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
15025 !context.directiveTransforms[p.name]) &&
15026 // in compat mode, <template> tags with no special directives
15027 // will be rendered as a fragment so its children must be
15028 // converted into vnodes.
15029 !(false ))))) {
15030 return;
15031 }
15032 // pre-convert text nodes into createTextVNode(text) calls to avoid
15033 // runtime normalization.
15034 for (let i = 0; i < children.length; i++) {
15035 const child = children[i];
15036 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
15037 const callArgs = [];
15038 // createTextVNode defaults to single whitespace, so if it is a
15039 // single space the code could be an empty call to save bytes.
15040 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
15041 callArgs.push(child);
15042 }
15043 // mark dynamic text with flag so it gets patched inside a block
15044 if (!context.ssr &&
15045 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
15046 callArgs.push(1 /* TEXT */ +
15047 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
15048 }
15049 children[i] = {
15050 type: 12 /* TEXT_CALL */,
15051 content: child,
15052 loc: child.loc,
15053 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
15054 };
15055 }
15056 }
15057 };
15058 }
15059 };
15060
15061 const seen = new WeakSet();
15062 const transformOnce = (node, context) => {
15063 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
15064 if (seen.has(node) || context.inVOnce) {
15065 return;
15066 }
15067 seen.add(node);
15068 context.inVOnce = true;
15069 context.helper(SET_BLOCK_TRACKING);
15070 return () => {
15071 context.inVOnce = false;
15072 const cur = context.currentNode;
15073 if (cur.codegenNode) {
15074 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
15075 }
15076 };
15077 }
15078 };
15079
15080 const transformModel = (dir, node, context) => {
15081 const { exp, arg } = dir;
15082 if (!exp) {
15083 context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
15084 return createTransformProps();
15085 }
15086 const rawExp = exp.loc.source;
15087 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
15088 // im SFC <script setup> inline mode, the exp may have been transformed into
15089 // _unref(exp)
15090 context.bindingMetadata[rawExp];
15091 const maybeRef = !true /* SETUP_CONST */;
15092 if (!expString.trim() || (!isMemberExpression(expString) && !maybeRef)) {
15093 context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
15094 return createTransformProps();
15095 }
15096 const propName = arg ? arg : createSimpleExpression('modelValue', true);
15097 const eventName = arg
15098 ? isStaticExp(arg)
15099 ? `onUpdate:${arg.content}`
15100 : createCompoundExpression(['"onUpdate:" + ', arg])
15101 : `onUpdate:modelValue`;
15102 let assignmentExp;
15103 const eventArg = context.isTS ? `($event: any)` : `$event`;
15104 {
15105 assignmentExp = createCompoundExpression([
15106 `${eventArg} => (`,
15107 exp,
15108 ` = $event)`
15109 ]);
15110 }
15111 const props = [
15112 // modelValue: foo
15113 createObjectProperty(propName, dir.exp),
15114 // "onUpdate:modelValue": $event => (foo = $event)
15115 createObjectProperty(eventName, assignmentExp)
15116 ];
15117 // modelModifiers: { foo: true, "bar-baz": true }
15118 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
15119 const modifiers = dir.modifiers
15120 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
15121 .join(`, `);
15122 const modifiersKey = arg
15123 ? isStaticExp(arg)
15124 ? `${arg.content}Modifiers`
15125 : createCompoundExpression([arg, ' + "Modifiers"'])
15126 : `modelModifiers`;
15127 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
15128 }
15129 return createTransformProps(props);
15130 };
15131 function createTransformProps(props = []) {
15132 return { props };
15133 }
15134
15135 const seen$1 = new WeakSet();
15136 const transformMemo = (node, context) => {
15137 if (node.type === 1 /* ELEMENT */) {
15138 const dir = findDir(node, 'memo');
15139 if (!dir || seen$1.has(node)) {
15140 return;
15141 }
15142 seen$1.add(node);
15143 return () => {
15144 const codegenNode = node.codegenNode ||
15145 context.currentNode.codegenNode;
15146 if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
15147 // non-component sub tree should be turned into a block
15148 if (node.tagType !== 1 /* COMPONENT */) {
15149 makeBlock(codegenNode, context);
15150 }
15151 node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
15152 dir.exp,
15153 createFunctionExpression(undefined, codegenNode),
15154 `_cache`,
15155 String(context.cached++)
15156 ]);
15157 }
15158 };
15159 }
15160 };
15161
15162 function getBaseTransformPreset(prefixIdentifiers) {
15163 return [
15164 [
15165 transformOnce,
15166 transformIf,
15167 transformMemo,
15168 transformFor,
15169 ...([]),
15170 ...([transformExpression]
15171 ),
15172 transformSlotOutlet,
15173 transformElement,
15174 trackSlotScopes,
15175 transformText
15176 ],
15177 {
15178 on: transformOn,
15179 bind: transformBind,
15180 model: transformModel
15181 }
15182 ];
15183 }
15184 // we name it `baseCompile` so that higher order compilers like
15185 // @vue/compiler-dom can export `compile` while re-exporting everything else.
15186 function baseCompile(template, options = {}) {
15187 const onError = options.onError || defaultOnError;
15188 const isModuleMode = options.mode === 'module';
15189 /* istanbul ignore if */
15190 {
15191 if (options.prefixIdentifiers === true) {
15192 onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
15193 }
15194 else if (isModuleMode) {
15195 onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
15196 }
15197 }
15198 const prefixIdentifiers = !true ;
15199 if (options.cacheHandlers) {
15200 onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
15201 }
15202 if (options.scopeId && !isModuleMode) {
15203 onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
15204 }
15205 const ast = isString(template) ? baseParse(template, options) : template;
15206 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
15207 transform(ast, extend({}, options, {
15208 prefixIdentifiers,
15209 nodeTransforms: [
15210 ...nodeTransforms,
15211 ...(options.nodeTransforms || []) // user transforms
15212 ],
15213 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
15214 )
15215 }));
15216 return generate(ast, extend({}, options, {
15217 prefixIdentifiers
15218 }));
15219 }
15220
15221 const noopDirectiveTransform = () => ({ props: [] });
15222
15223 const V_MODEL_RADIO = Symbol(`vModelRadio` );
15224 const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
15225 const V_MODEL_TEXT = Symbol(`vModelText` );
15226 const V_MODEL_SELECT = Symbol(`vModelSelect` );
15227 const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
15228 const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
15229 const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
15230 const V_SHOW = Symbol(`vShow` );
15231 const TRANSITION$1 = Symbol(`Transition` );
15232 const TRANSITION_GROUP = Symbol(`TransitionGroup` );
15233 registerRuntimeHelpers({
15234 [V_MODEL_RADIO]: `vModelRadio`,
15235 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
15236 [V_MODEL_TEXT]: `vModelText`,
15237 [V_MODEL_SELECT]: `vModelSelect`,
15238 [V_MODEL_DYNAMIC]: `vModelDynamic`,
15239 [V_ON_WITH_MODIFIERS]: `withModifiers`,
15240 [V_ON_WITH_KEYS]: `withKeys`,
15241 [V_SHOW]: `vShow`,
15242 [TRANSITION$1]: `Transition`,
15243 [TRANSITION_GROUP]: `TransitionGroup`
15244 });
15245
15246 /* eslint-disable no-restricted-globals */
15247 let decoder;
15248 function decodeHtmlBrowser(raw, asAttr = false) {
15249 if (!decoder) {
15250 decoder = document.createElement('div');
15251 }
15252 if (asAttr) {
15253 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
15254 return decoder.children[0].getAttribute('foo');
15255 }
15256 else {
15257 decoder.innerHTML = raw;
15258 return decoder.textContent;
15259 }
15260 }
15261
15262 const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
15263 const parserOptions = {
15264 isVoidTag,
15265 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
15266 isPreTag: tag => tag === 'pre',
15267 decodeEntities: decodeHtmlBrowser ,
15268 isBuiltInComponent: (tag) => {
15269 if (isBuiltInType(tag, `Transition`)) {
15270 return TRANSITION$1;
15271 }
15272 else if (isBuiltInType(tag, `TransitionGroup`)) {
15273 return TRANSITION_GROUP;
15274 }
15275 },
15276 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
15277 getNamespace(tag, parent) {
15278 let ns = parent ? parent.ns : 0 /* HTML */;
15279 if (parent && ns === 2 /* MATH_ML */) {
15280 if (parent.tag === 'annotation-xml') {
15281 if (tag === 'svg') {
15282 return 1 /* SVG */;
15283 }
15284 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
15285 a.name === 'encoding' &&
15286 a.value != null &&
15287 (a.value.content === 'text/html' ||
15288 a.value.content === 'application/xhtml+xml'))) {
15289 ns = 0 /* HTML */;
15290 }
15291 }
15292 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
15293 tag !== 'mglyph' &&
15294 tag !== 'malignmark') {
15295 ns = 0 /* HTML */;
15296 }
15297 }
15298 else if (parent && ns === 1 /* SVG */) {
15299 if (parent.tag === 'foreignObject' ||
15300 parent.tag === 'desc' ||
15301 parent.tag === 'title') {
15302 ns = 0 /* HTML */;
15303 }
15304 }
15305 if (ns === 0 /* HTML */) {
15306 if (tag === 'svg') {
15307 return 1 /* SVG */;
15308 }
15309 if (tag === 'math') {
15310 return 2 /* MATH_ML */;
15311 }
15312 }
15313 return ns;
15314 },
15315 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
15316 getTextMode({ tag, ns }) {
15317 if (ns === 0 /* HTML */) {
15318 if (tag === 'textarea' || tag === 'title') {
15319 return 1 /* RCDATA */;
15320 }
15321 if (isRawTextContainer(tag)) {
15322 return 2 /* RAWTEXT */;
15323 }
15324 }
15325 return 0 /* DATA */;
15326 }
15327 };
15328
15329 // Parse inline CSS strings for static style attributes into an object.
15330 // This is a NodeTransform since it works on the static `style` attribute and
15331 // converts it into a dynamic equivalent:
15332 // style="color: red" -> :style='{ "color": "red" }'
15333 // It is then processed by `transformElement` and included in the generated
15334 // props.
15335 const transformStyle = node => {
15336 if (node.type === 1 /* ELEMENT */) {
15337 node.props.forEach((p, i) => {
15338 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
15339 // replace p with an expression node
15340 node.props[i] = {
15341 type: 7 /* DIRECTIVE */,
15342 name: `bind`,
15343 arg: createSimpleExpression(`style`, true, p.loc),
15344 exp: parseInlineCSS(p.value.content, p.loc),
15345 modifiers: [],
15346 loc: p.loc
15347 };
15348 }
15349 });
15350 }
15351 };
15352 const parseInlineCSS = (cssText, loc) => {
15353 const normalized = parseStringStyle(cssText);
15354 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
15355 };
15356
15357 function createDOMCompilerError(code, loc) {
15358 return createCompilerError(code, loc, DOMErrorMessages );
15359 }
15360 const DOMErrorMessages = {
15361 [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
15362 [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
15363 [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
15364 [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
15365 [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
15366 [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
15367 [56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
15368 [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
15369 [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
15370 [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
15371 [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
15372 };
15373
15374 const transformVHtml = (dir, node, context) => {
15375 const { exp, loc } = dir;
15376 if (!exp) {
15377 context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
15378 }
15379 if (node.children.length) {
15380 context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
15381 node.children.length = 0;
15382 }
15383 return {
15384 props: [
15385 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
15386 ]
15387 };
15388 };
15389
15390 const transformVText = (dir, node, context) => {
15391 const { exp, loc } = dir;
15392 if (!exp) {
15393 context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
15394 }
15395 if (node.children.length) {
15396 context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
15397 node.children.length = 0;
15398 }
15399 return {
15400 props: [
15401 createObjectProperty(createSimpleExpression(`textContent`, true), exp
15402 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
15403 : createSimpleExpression('', true))
15404 ]
15405 };
15406 };
15407
15408 const transformModel$1 = (dir, node, context) => {
15409 const baseResult = transformModel(dir, node, context);
15410 // base transform has errors OR component v-model (only need props)
15411 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
15412 return baseResult;
15413 }
15414 if (dir.arg) {
15415 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
15416 }
15417 function checkDuplicatedValue() {
15418 const value = findProp(node, 'value');
15419 if (value) {
15420 context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
15421 }
15422 }
15423 const { tag } = node;
15424 const isCustomElement = context.isCustomElement(tag);
15425 if (tag === 'input' ||
15426 tag === 'textarea' ||
15427 tag === 'select' ||
15428 isCustomElement) {
15429 let directiveToUse = V_MODEL_TEXT;
15430 let isInvalidType = false;
15431 if (tag === 'input' || isCustomElement) {
15432 const type = findProp(node, `type`);
15433 if (type) {
15434 if (type.type === 7 /* DIRECTIVE */) {
15435 // :type="foo"
15436 directiveToUse = V_MODEL_DYNAMIC;
15437 }
15438 else if (type.value) {
15439 switch (type.value.content) {
15440 case 'radio':
15441 directiveToUse = V_MODEL_RADIO;
15442 break;
15443 case 'checkbox':
15444 directiveToUse = V_MODEL_CHECKBOX;
15445 break;
15446 case 'file':
15447 isInvalidType = true;
15448 context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
15449 break;
15450 default:
15451 // text type
15452 checkDuplicatedValue();
15453 break;
15454 }
15455 }
15456 }
15457 else if (hasDynamicKeyVBind(node)) {
15458 // element has bindings with dynamic keys, which can possibly contain
15459 // "type".
15460 directiveToUse = V_MODEL_DYNAMIC;
15461 }
15462 else {
15463 // text type
15464 checkDuplicatedValue();
15465 }
15466 }
15467 else if (tag === 'select') {
15468 directiveToUse = V_MODEL_SELECT;
15469 }
15470 else {
15471 // textarea
15472 checkDuplicatedValue();
15473 }
15474 // inject runtime directive
15475 // by returning the helper symbol via needRuntime
15476 // the import will replaced a resolveDirective call.
15477 if (!isInvalidType) {
15478 baseResult.needRuntime = context.helper(directiveToUse);
15479 }
15480 }
15481 else {
15482 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
15483 }
15484 // native vmodel doesn't need the `modelValue` props since they are also
15485 // passed to the runtime as `binding.value`. removing it reduces code size.
15486 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
15487 p.key.content === 'modelValue'));
15488 return baseResult;
15489 };
15490
15491 const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
15492 const isNonKeyModifier = /*#__PURE__*/ makeMap(
15493 // event propagation management
15494`stop,prevent,self,` +
15495 // system modifiers + exact
15496 `ctrl,shift,alt,meta,exact,` +
15497 // mouse
15498 `middle`);
15499 // left & right could be mouse or key modifiers based on event type
15500 const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
15501 const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
15502 const resolveModifiers = (key, modifiers, context, loc) => {
15503 const keyModifiers = [];
15504 const nonKeyModifiers = [];
15505 const eventOptionModifiers = [];
15506 for (let i = 0; i < modifiers.length; i++) {
15507 const modifier = modifiers[i];
15508 if (isEventOptionModifier(modifier)) {
15509 // eventOptionModifiers: modifiers for addEventListener() options,
15510 // e.g. .passive & .capture
15511 eventOptionModifiers.push(modifier);
15512 }
15513 else {
15514 // runtimeModifiers: modifiers that needs runtime guards
15515 if (maybeKeyModifier(modifier)) {
15516 if (isStaticExp(key)) {
15517 if (isKeyboardEvent(key.content)) {
15518 keyModifiers.push(modifier);
15519 }
15520 else {
15521 nonKeyModifiers.push(modifier);
15522 }
15523 }
15524 else {
15525 keyModifiers.push(modifier);
15526 nonKeyModifiers.push(modifier);
15527 }
15528 }
15529 else {
15530 if (isNonKeyModifier(modifier)) {
15531 nonKeyModifiers.push(modifier);
15532 }
15533 else {
15534 keyModifiers.push(modifier);
15535 }
15536 }
15537 }
15538 }
15539 return {
15540 keyModifiers,
15541 nonKeyModifiers,
15542 eventOptionModifiers
15543 };
15544 };
15545 const transformClick = (key, event) => {
15546 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
15547 return isStaticClick
15548 ? createSimpleExpression(event, true)
15549 : key.type !== 4 /* SIMPLE_EXPRESSION */
15550 ? createCompoundExpression([
15551 `(`,
15552 key,
15553 `) === "onClick" ? "${event}" : (`,
15554 key,
15555 `)`
15556 ])
15557 : key;
15558 };
15559 const transformOn$1 = (dir, node, context) => {
15560 return transformOn(dir, node, context, baseResult => {
15561 const { modifiers } = dir;
15562 if (!modifiers.length)
15563 return baseResult;
15564 let { key, value: handlerExp } = baseResult.props[0];
15565 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
15566 // normalize click.right and click.middle since they don't actually fire
15567 if (nonKeyModifiers.includes('right')) {
15568 key = transformClick(key, `onContextmenu`);
15569 }
15570 if (nonKeyModifiers.includes('middle')) {
15571 key = transformClick(key, `onMouseup`);
15572 }
15573 if (nonKeyModifiers.length) {
15574 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
15575 handlerExp,
15576 JSON.stringify(nonKeyModifiers)
15577 ]);
15578 }
15579 if (keyModifiers.length &&
15580 // if event name is dynamic, always wrap with keys guard
15581 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
15582 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
15583 handlerExp,
15584 JSON.stringify(keyModifiers)
15585 ]);
15586 }
15587 if (eventOptionModifiers.length) {
15588 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
15589 key = isStaticExp(key)
15590 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
15591 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
15592 }
15593 return {
15594 props: [createObjectProperty(key, handlerExp)]
15595 };
15596 });
15597 };
15598
15599 const transformShow = (dir, node, context) => {
15600 const { exp, loc } = dir;
15601 if (!exp) {
15602 context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
15603 }
15604 return {
15605 props: [],
15606 needRuntime: context.helper(V_SHOW)
15607 };
15608 };
15609
15610 const warnTransitionChildren = (node, context) => {
15611 if (node.type === 1 /* ELEMENT */ &&
15612 node.tagType === 1 /* COMPONENT */) {
15613 const component = context.isBuiltInComponent(node.tag);
15614 if (component === TRANSITION$1) {
15615 return () => {
15616 if (node.children.length && hasMultipleChildren(node)) {
15617 context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
15618 start: node.children[0].loc.start,
15619 end: node.children[node.children.length - 1].loc.end,
15620 source: ''
15621 }));
15622 }
15623 };
15624 }
15625 }
15626 };
15627 function hasMultipleChildren(node) {
15628 // #1352 filter out potential comment nodes.
15629 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
15630 const child = children[0];
15631 return (children.length !== 1 ||
15632 child.type === 11 /* FOR */ ||
15633 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
15634 }
15635
15636 const ignoreSideEffectTags = (node, context) => {
15637 if (node.type === 1 /* ELEMENT */ &&
15638 node.tagType === 0 /* ELEMENT */ &&
15639 (node.tag === 'script' || node.tag === 'style')) {
15640 context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
15641 context.removeNode();
15642 }
15643 };
15644
15645 const DOMNodeTransforms = [
15646 transformStyle,
15647 ...([warnTransitionChildren] )
15648 ];
15649 const DOMDirectiveTransforms = {
15650 cloak: noopDirectiveTransform,
15651 html: transformVHtml,
15652 text: transformVText,
15653 model: transformModel$1,
15654 on: transformOn$1,
15655 show: transformShow
15656 };
15657 function compile$1(template, options = {}) {
15658 return baseCompile(template, extend({}, parserOptions, options, {
15659 nodeTransforms: [
15660 // ignore <script> and <tag>
15661 // this is not put inside DOMNodeTransforms because that list is used
15662 // by compiler-ssr to generate vnode fallback branches
15663 ignoreSideEffectTags,
15664 ...DOMNodeTransforms,
15665 ...(options.nodeTransforms || [])
15666 ],
15667 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
15668 transformHoist: null
15669 }));
15670 }
15671
15672 // This entry is the "full-build" that includes both the runtime
15673 {
15674 initDev();
15675 }
15676 const compileCache = Object.create(null);
15677 function compileToFunction(template, options) {
15678 if (!isString(template)) {
15679 if (template.nodeType) {
15680 template = template.innerHTML;
15681 }
15682 else {
15683 warn$1(`invalid template option: `, template);
15684 return NOOP;
15685 }
15686 }
15687 const key = template;
15688 const cached = compileCache[key];
15689 if (cached) {
15690 return cached;
15691 }
15692 if (template[0] === '#') {
15693 const el = document.querySelector(template);
15694 if (!el) {
15695 warn$1(`Template element not found or is empty: ${template}`);
15696 }
15697 // __UNSAFE__
15698 // Reason: potential execution of JS expressions in in-DOM template.
15699 // The user must make sure the in-DOM template is trusted. If it's rendered
15700 // by the server, the template should not contain any user data.
15701 template = el ? el.innerHTML : ``;
15702 }
15703 const { code } = compile$1(template, extend({
15704 hoistStatic: true,
15705 onError: onError ,
15706 onWarn: e => onError(e, true)
15707 }, options));
15708 function onError(err, asWarning = false) {
15709 const message = asWarning
15710 ? err.message
15711 : `Template compilation error: ${err.message}`;
15712 const codeFrame = err.loc &&
15713 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
15714 warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
15715 }
15716 // The wildcard import results in a huge object with every export
15717 // with keys that cannot be mangled, and can be quite heavy size-wise.
15718 // In the global build we know `Vue` is available globally so we can avoid
15719 // the wildcard object.
15720 const render = (new Function(code)() );
15721 render._rc = true;
15722 return (compileCache[key] = render);
15723 }
15724 registerRuntimeCompiler(compileToFunction);
15725
15726 exports.BaseTransition = BaseTransition;
15727 exports.Comment = Comment;
15728 exports.EffectScope = EffectScope;
15729 exports.Fragment = Fragment;
15730 exports.KeepAlive = KeepAlive;
15731 exports.ReactiveEffect = ReactiveEffect;
15732 exports.Static = Static;
15733 exports.Suspense = Suspense;
15734 exports.Teleport = Teleport;
15735 exports.Text = Text;
15736 exports.Transition = Transition;
15737 exports.TransitionGroup = TransitionGroup;
15738 exports.VueElement = VueElement;
15739 exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
15740 exports.callWithErrorHandling = callWithErrorHandling;
15741 exports.camelize = camelize;
15742 exports.capitalize = capitalize;
15743 exports.cloneVNode = cloneVNode;
15744 exports.compatUtils = compatUtils;
15745 exports.compile = compileToFunction;
15746 exports.computed = computed;
15747 exports.createApp = createApp;
15748 exports.createBlock = createBlock;
15749 exports.createCommentVNode = createCommentVNode;
15750 exports.createElementBlock = createElementBlock;
15751 exports.createElementVNode = createBaseVNode;
15752 exports.createHydrationRenderer = createHydrationRenderer;
15753 exports.createRenderer = createRenderer;
15754 exports.createSSRApp = createSSRApp;
15755 exports.createSlots = createSlots;
15756 exports.createStaticVNode = createStaticVNode;
15757 exports.createTextVNode = createTextVNode;
15758 exports.createVNode = createVNode;
15759 exports.customRef = customRef;
15760 exports.defineAsyncComponent = defineAsyncComponent;
15761 exports.defineComponent = defineComponent;
15762 exports.defineCustomElement = defineCustomElement;
15763 exports.defineEmits = defineEmits;
15764 exports.defineExpose = defineExpose;
15765 exports.defineProps = defineProps;
15766 exports.defineSSRCustomElement = defineSSRCustomElement;
15767 exports.effect = effect;
15768 exports.effectScope = effectScope;
15769 exports.getCurrentInstance = getCurrentInstance;
15770 exports.getCurrentScope = getCurrentScope;
15771 exports.getTransitionRawChildren = getTransitionRawChildren;
15772 exports.guardReactiveProps = guardReactiveProps;
15773 exports.h = h;
15774 exports.handleError = handleError;
15775 exports.hydrate = hydrate;
15776 exports.initCustomFormatter = initCustomFormatter;
15777 exports.inject = inject;
15778 exports.isMemoSame = isMemoSame;
15779 exports.isProxy = isProxy;
15780 exports.isReactive = isReactive;
15781 exports.isReadonly = isReadonly;
15782 exports.isRef = isRef;
15783 exports.isRuntimeOnly = isRuntimeOnly;
15784 exports.isVNode = isVNode;
15785 exports.markRaw = markRaw;
15786 exports.mergeDefaults = mergeDefaults;
15787 exports.mergeProps = mergeProps;
15788 exports.nextTick = nextTick;
15789 exports.normalizeClass = normalizeClass;
15790 exports.normalizeProps = normalizeProps;
15791 exports.normalizeStyle = normalizeStyle;
15792 exports.onActivated = onActivated;
15793 exports.onBeforeMount = onBeforeMount;
15794 exports.onBeforeUnmount = onBeforeUnmount;
15795 exports.onBeforeUpdate = onBeforeUpdate;
15796 exports.onDeactivated = onDeactivated;
15797 exports.onErrorCaptured = onErrorCaptured;
15798 exports.onMounted = onMounted;
15799 exports.onRenderTracked = onRenderTracked;
15800 exports.onRenderTriggered = onRenderTriggered;
15801 exports.onScopeDispose = onScopeDispose;
15802 exports.onServerPrefetch = onServerPrefetch;
15803 exports.onUnmounted = onUnmounted;
15804 exports.onUpdated = onUpdated;
15805 exports.openBlock = openBlock;
15806 exports.popScopeId = popScopeId;
15807 exports.provide = provide;
15808 exports.proxyRefs = proxyRefs;
15809 exports.pushScopeId = pushScopeId;
15810 exports.queuePostFlushCb = queuePostFlushCb;
15811 exports.reactive = reactive;
15812 exports.readonly = readonly;
15813 exports.ref = ref;
15814 exports.registerRuntimeCompiler = registerRuntimeCompiler;
15815 exports.render = render;
15816 exports.renderList = renderList;
15817 exports.renderSlot = renderSlot;
15818 exports.resolveComponent = resolveComponent;
15819 exports.resolveDirective = resolveDirective;
15820 exports.resolveDynamicComponent = resolveDynamicComponent;
15821 exports.resolveFilter = resolveFilter;
15822 exports.resolveTransitionHooks = resolveTransitionHooks;
15823 exports.setBlockTracking = setBlockTracking;
15824 exports.setDevtoolsHook = setDevtoolsHook;
15825 exports.setTransitionHooks = setTransitionHooks;
15826 exports.shallowReactive = shallowReactive;
15827 exports.shallowReadonly = shallowReadonly;
15828 exports.shallowRef = shallowRef;
15829 exports.ssrContextKey = ssrContextKey;
15830 exports.ssrUtils = ssrUtils;
15831 exports.stop = stop;
15832 exports.toDisplayString = toDisplayString;
15833 exports.toHandlerKey = toHandlerKey;
15834 exports.toHandlers = toHandlers;
15835 exports.toRaw = toRaw;
15836 exports.toRef = toRef;
15837 exports.toRefs = toRefs;
15838 exports.transformVNodeArgs = transformVNodeArgs;
15839 exports.triggerRef = triggerRef;
15840 exports.unref = unref;
15841 exports.useAttrs = useAttrs;
15842 exports.useCssModule = useCssModule;
15843 exports.useCssVars = useCssVars;
15844 exports.useSSRContext = useSSRContext;
15845 exports.useSlots = useSlots;
15846 exports.useTransitionState = useTransitionState;
15847 exports.vModelCheckbox = vModelCheckbox;
15848 exports.vModelDynamic = vModelDynamic;
15849 exports.vModelRadio = vModelRadio;
15850 exports.vModelSelect = vModelSelect;
15851 exports.vModelText = vModelText;
15852 exports.vShow = vShow;
15853 exports.version = version;
15854 exports.warn = warn$1;
15855 exports.watch = watch;
15856 exports.watchEffect = watchEffect;
15857 exports.watchPostEffect = watchPostEffect;
15858 exports.watchSyncEffect = watchSyncEffect;
15859 exports.withAsyncContext = withAsyncContext;
15860 exports.withCtx = withCtx;
15861 exports.withDefaults = withDefaults;
15862 exports.withDirectives = withDirectives;
15863 exports.withKeys = withKeys;
15864 exports.withMemo = withMemo;
15865 exports.withModifiers = withModifiers;
15866 exports.withScopeId = withScopeId;
15867
15868 Object.defineProperty(exports, '__esModule', { value: true });
15869
15870 return exports;
15871
15872}({}));