UNPKG

556 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 const lines = source.split(/\r?\n/);
57 let count = 0;
58 const res = [];
59 for (let i = 0; i < lines.length; i++) {
60 count += lines[i].length + 1;
61 if (count >= start) {
62 for (let j = i - range; j <= i + range || end > count; j++) {
63 if (j < 0 || j >= lines.length)
64 continue;
65 const line = j + 1;
66 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
67 const lineLength = lines[j].length;
68 if (j === i) {
69 // push underline
70 const pad = start - (count - lineLength) + 1;
71 const length = Math.max(1, end > count ? lineLength - pad : end - start);
72 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
73 }
74 else if (j > i) {
75 if (end > count) {
76 const length = Math.max(Math.min(end - count, lineLength), 1);
77 res.push(` | ` + '^'.repeat(length));
78 }
79 count += lineLength + 1;
80 }
81 }
82 break;
83 }
84 }
85 return res.join('\n');
86 }
87
88 /**
89 * On the client we only need to offer special cases for boolean attributes that
90 * have different names from their corresponding dom properties:
91 * - itemscope -> N/A
92 * - allowfullscreen -> allowFullscreen
93 * - formnovalidate -> formNoValidate
94 * - ismap -> isMap
95 * - nomodule -> noModule
96 * - novalidate -> noValidate
97 * - readonly -> readOnly
98 */
99 const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
100 const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
101
102 function normalizeStyle(value) {
103 if (isArray(value)) {
104 const res = {};
105 for (let i = 0; i < value.length; i++) {
106 const item = value[i];
107 const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
108 if (normalized) {
109 for (const key in normalized) {
110 res[key] = normalized[key];
111 }
112 }
113 }
114 return res;
115 }
116 else if (isObject(value)) {
117 return value;
118 }
119 }
120 const listDelimiterRE = /;(?![^(]*\))/g;
121 const propertyDelimiterRE = /:(.+)/;
122 function parseStringStyle(cssText) {
123 const ret = {};
124 cssText.split(listDelimiterRE).forEach(item => {
125 if (item) {
126 const tmp = item.split(propertyDelimiterRE);
127 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
128 }
129 });
130 return ret;
131 }
132 function normalizeClass(value) {
133 let res = '';
134 if (isString(value)) {
135 res = value;
136 }
137 else if (isArray(value)) {
138 for (let i = 0; i < value.length; i++) {
139 const normalized = normalizeClass(value[i]);
140 if (normalized) {
141 res += normalized + ' ';
142 }
143 }
144 }
145 else if (isObject(value)) {
146 for (const name in value) {
147 if (value[name]) {
148 res += name + ' ';
149 }
150 }
151 }
152 return res.trim();
153 }
154
155 // These tag configs are shared between compiler-dom and runtime-dom, so they
156 // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
157 const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
158 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
159 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
160 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
161 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
162 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
163 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
164 'option,output,progress,select,textarea,details,dialog,menu,' +
165 'summary,template,blockquote,iframe,tfoot';
166 // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
167 const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
168 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
169 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
170 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
171 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
172 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
173 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
174 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
175 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
176 'text,textPath,title,tspan,unknown,use,view';
177 const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
178 const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
179 const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
180 const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
181
182 function looseCompareArrays(a, b) {
183 if (a.length !== b.length)
184 return false;
185 let equal = true;
186 for (let i = 0; equal && i < a.length; i++) {
187 equal = looseEqual(a[i], b[i]);
188 }
189 return equal;
190 }
191 function looseEqual(a, b) {
192 if (a === b)
193 return true;
194 let aValidType = isDate(a);
195 let bValidType = isDate(b);
196 if (aValidType || bValidType) {
197 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
198 }
199 aValidType = isArray(a);
200 bValidType = isArray(b);
201 if (aValidType || bValidType) {
202 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
203 }
204 aValidType = isObject(a);
205 bValidType = isObject(b);
206 if (aValidType || bValidType) {
207 /* istanbul ignore if: this if will probably never be called */
208 if (!aValidType || !bValidType) {
209 return false;
210 }
211 const aKeysCount = Object.keys(a).length;
212 const bKeysCount = Object.keys(b).length;
213 if (aKeysCount !== bKeysCount) {
214 return false;
215 }
216 for (const key in a) {
217 const aHasKey = a.hasOwnProperty(key);
218 const bHasKey = b.hasOwnProperty(key);
219 if ((aHasKey && !bHasKey) ||
220 (!aHasKey && bHasKey) ||
221 !looseEqual(a[key], b[key])) {
222 return false;
223 }
224 }
225 }
226 return String(a) === String(b);
227 }
228 function looseIndexOf(arr, val) {
229 return arr.findIndex(item => looseEqual(item, val));
230 }
231
232 /**
233 * For converting {{ interpolation }} values to displayed strings.
234 * @private
235 */
236 const toDisplayString = (val) => {
237 return val == null
238 ? ''
239 : isObject(val)
240 ? JSON.stringify(val, replacer, 2)
241 : String(val);
242 };
243 const replacer = (_key, val) => {
244 if (isMap(val)) {
245 return {
246 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
247 entries[`${key} =>`] = val;
248 return entries;
249 }, {})
250 };
251 }
252 else if (isSet(val)) {
253 return {
254 [`Set(${val.size})`]: [...val.values()]
255 };
256 }
257 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
258 return String(val);
259 }
260 return val;
261 };
262
263 const EMPTY_OBJ = Object.freeze({})
264 ;
265 const EMPTY_ARR = Object.freeze([]) ;
266 const NOOP = () => { };
267 /**
268 * Always return false.
269 */
270 const NO = () => false;
271 const onRE = /^on[^a-z]/;
272 const isOn = (key) => onRE.test(key);
273 const isModelListener = (key) => key.startsWith('onUpdate:');
274 const extend = Object.assign;
275 const remove = (arr, el) => {
276 const i = arr.indexOf(el);
277 if (i > -1) {
278 arr.splice(i, 1);
279 }
280 };
281 const hasOwnProperty = Object.prototype.hasOwnProperty;
282 const hasOwn = (val, key) => hasOwnProperty.call(val, key);
283 const isArray = Array.isArray;
284 const isMap = (val) => toTypeString(val) === '[object Map]';
285 const isSet = (val) => toTypeString(val) === '[object Set]';
286 const isDate = (val) => val instanceof Date;
287 const isFunction = (val) => typeof val === 'function';
288 const isString = (val) => typeof val === 'string';
289 const isSymbol = (val) => typeof val === 'symbol';
290 const isObject = (val) => val !== null && typeof val === 'object';
291 const isPromise = (val) => {
292 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
293 };
294 const objectToString = Object.prototype.toString;
295 const toTypeString = (value) => objectToString.call(value);
296 const toRawType = (value) => {
297 // extract "RawType" from strings like "[object RawType]"
298 return toTypeString(value).slice(8, -1);
299 };
300 const isPlainObject = (val) => toTypeString(val) === '[object Object]';
301 const isIntegerKey = (key) => isString(key) &&
302 key !== 'NaN' &&
303 key[0] !== '-' &&
304 '' + parseInt(key, 10) === key;
305 const isReservedProp = /*#__PURE__*/ makeMap(
306 // the leading comma is intentional so empty string "" is also included
307 ',key,ref,' +
308 'onVnodeBeforeMount,onVnodeMounted,' +
309 'onVnodeBeforeUpdate,onVnodeUpdated,' +
310 'onVnodeBeforeUnmount,onVnodeUnmounted');
311 const cacheStringFunction = (fn) => {
312 const cache = Object.create(null);
313 return ((str) => {
314 const hit = cache[str];
315 return hit || (cache[str] = fn(str));
316 });
317 };
318 const camelizeRE = /-(\w)/g;
319 /**
320 * @private
321 */
322 const camelize = cacheStringFunction((str) => {
323 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
324 });
325 const hyphenateRE = /\B([A-Z])/g;
326 /**
327 * @private
328 */
329 const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
330 /**
331 * @private
332 */
333 const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
334 /**
335 * @private
336 */
337 const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
338 // compare whether a value has changed, accounting for NaN.
339 const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
340 const invokeArrayFns = (fns, arg) => {
341 for (let i = 0; i < fns.length; i++) {
342 fns[i](arg);
343 }
344 };
345 const def = (obj, key, value) => {
346 Object.defineProperty(obj, key, {
347 configurable: true,
348 enumerable: false,
349 value
350 });
351 };
352 const toNumber = (val) => {
353 const n = parseFloat(val);
354 return isNaN(n) ? val : n;
355 };
356 let _globalThis;
357 const getGlobalThis = () => {
358 return (_globalThis ||
359 (_globalThis =
360 typeof globalThis !== 'undefined'
361 ? globalThis
362 : typeof self !== 'undefined'
363 ? self
364 : typeof window !== 'undefined'
365 ? window
366 : typeof global !== 'undefined'
367 ? global
368 : {}));
369 };
370
371 const targetMap = new WeakMap();
372 const effectStack = [];
373 let activeEffect;
374 const ITERATE_KEY = Symbol('iterate' );
375 const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
376 function isEffect(fn) {
377 return fn && fn._isEffect === true;
378 }
379 function effect(fn, options = EMPTY_OBJ) {
380 if (isEffect(fn)) {
381 fn = fn.raw;
382 }
383 const effect = createReactiveEffect(fn, options);
384 if (!options.lazy) {
385 effect();
386 }
387 return effect;
388 }
389 function stop(effect) {
390 if (effect.active) {
391 cleanup(effect);
392 if (effect.options.onStop) {
393 effect.options.onStop();
394 }
395 effect.active = false;
396 }
397 }
398 let uid = 0;
399 function createReactiveEffect(fn, options) {
400 const effect = function reactiveEffect() {
401 if (!effect.active) {
402 return options.scheduler ? undefined : fn();
403 }
404 if (!effectStack.includes(effect)) {
405 cleanup(effect);
406 try {
407 enableTracking();
408 effectStack.push(effect);
409 activeEffect = effect;
410 return fn();
411 }
412 finally {
413 effectStack.pop();
414 resetTracking();
415 activeEffect = effectStack[effectStack.length - 1];
416 }
417 }
418 };
419 effect.id = uid++;
420 effect.allowRecurse = !!options.allowRecurse;
421 effect._isEffect = true;
422 effect.active = true;
423 effect.raw = fn;
424 effect.deps = [];
425 effect.options = options;
426 return effect;
427 }
428 function cleanup(effect) {
429 const { deps } = effect;
430 if (deps.length) {
431 for (let i = 0; i < deps.length; i++) {
432 deps[i].delete(effect);
433 }
434 deps.length = 0;
435 }
436 }
437 let shouldTrack = true;
438 const trackStack = [];
439 function pauseTracking() {
440 trackStack.push(shouldTrack);
441 shouldTrack = false;
442 }
443 function enableTracking() {
444 trackStack.push(shouldTrack);
445 shouldTrack = true;
446 }
447 function resetTracking() {
448 const last = trackStack.pop();
449 shouldTrack = last === undefined ? true : last;
450 }
451 function track(target, type, key) {
452 if (!shouldTrack || activeEffect === undefined) {
453 return;
454 }
455 let depsMap = targetMap.get(target);
456 if (!depsMap) {
457 targetMap.set(target, (depsMap = new Map()));
458 }
459 let dep = depsMap.get(key);
460 if (!dep) {
461 depsMap.set(key, (dep = new Set()));
462 }
463 if (!dep.has(activeEffect)) {
464 dep.add(activeEffect);
465 activeEffect.deps.push(dep);
466 if (activeEffect.options.onTrack) {
467 activeEffect.options.onTrack({
468 effect: activeEffect,
469 target,
470 type,
471 key
472 });
473 }
474 }
475 }
476 function trigger(target, type, key, newValue, oldValue, oldTarget) {
477 const depsMap = targetMap.get(target);
478 if (!depsMap) {
479 // never been tracked
480 return;
481 }
482 const effects = new Set();
483 const add = (effectsToAdd) => {
484 if (effectsToAdd) {
485 effectsToAdd.forEach(effect => {
486 if (effect !== activeEffect || effect.allowRecurse) {
487 effects.add(effect);
488 }
489 });
490 }
491 };
492 if (type === "clear" /* CLEAR */) {
493 // collection being cleared
494 // trigger all effects for target
495 depsMap.forEach(add);
496 }
497 else if (key === 'length' && isArray(target)) {
498 depsMap.forEach((dep, key) => {
499 if (key === 'length' || key >= newValue) {
500 add(dep);
501 }
502 });
503 }
504 else {
505 // schedule runs for SET | ADD | DELETE
506 if (key !== void 0) {
507 add(depsMap.get(key));
508 }
509 // also run for iteration key on ADD | DELETE | Map.SET
510 switch (type) {
511 case "add" /* ADD */:
512 if (!isArray(target)) {
513 add(depsMap.get(ITERATE_KEY));
514 if (isMap(target)) {
515 add(depsMap.get(MAP_KEY_ITERATE_KEY));
516 }
517 }
518 else if (isIntegerKey(key)) {
519 // new index added to array -> length changes
520 add(depsMap.get('length'));
521 }
522 break;
523 case "delete" /* DELETE */:
524 if (!isArray(target)) {
525 add(depsMap.get(ITERATE_KEY));
526 if (isMap(target)) {
527 add(depsMap.get(MAP_KEY_ITERATE_KEY));
528 }
529 }
530 break;
531 case "set" /* SET */:
532 if (isMap(target)) {
533 add(depsMap.get(ITERATE_KEY));
534 }
535 break;
536 }
537 }
538 const run = (effect) => {
539 if (effect.options.onTrigger) {
540 effect.options.onTrigger({
541 effect,
542 target,
543 key,
544 type,
545 newValue,
546 oldValue,
547 oldTarget
548 });
549 }
550 if (effect.options.scheduler) {
551 effect.options.scheduler(effect);
552 }
553 else {
554 effect();
555 }
556 };
557 effects.forEach(run);
558 }
559
560 const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
561 const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
562 .map(key => Symbol[key])
563 .filter(isSymbol));
564 const get = /*#__PURE__*/ createGetter();
565 const shallowGet = /*#__PURE__*/ createGetter(false, true);
566 const readonlyGet = /*#__PURE__*/ createGetter(true);
567 const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
568 const arrayInstrumentations = {};
569 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
570 const method = Array.prototype[key];
571 arrayInstrumentations[key] = function (...args) {
572 const arr = toRaw(this);
573 for (let i = 0, l = this.length; i < l; i++) {
574 track(arr, "get" /* GET */, i + '');
575 }
576 // we run the method using the original args first (which may be reactive)
577 const res = method.apply(arr, args);
578 if (res === -1 || res === false) {
579 // if that didn't work, run it again using raw values.
580 return method.apply(arr, args.map(toRaw));
581 }
582 else {
583 return res;
584 }
585 };
586 });
587 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
588 const method = Array.prototype[key];
589 arrayInstrumentations[key] = function (...args) {
590 pauseTracking();
591 const res = method.apply(this, args);
592 resetTracking();
593 return res;
594 };
595 });
596 function createGetter(isReadonly = false, shallow = false) {
597 return function get(target, key, receiver) {
598 if (key === "__v_isReactive" /* IS_REACTIVE */) {
599 return !isReadonly;
600 }
601 else if (key === "__v_isReadonly" /* IS_READONLY */) {
602 return isReadonly;
603 }
604 else if (key === "__v_raw" /* RAW */ &&
605 receiver ===
606 (isReadonly
607 ? shallow
608 ? shallowReadonlyMap
609 : readonlyMap
610 : shallow
611 ? shallowReactiveMap
612 : reactiveMap).get(target)) {
613 return target;
614 }
615 const targetIsArray = isArray(target);
616 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
617 return Reflect.get(arrayInstrumentations, key, receiver);
618 }
619 const res = Reflect.get(target, key, receiver);
620 if (isSymbol(key)
621 ? builtInSymbols.has(key)
622 : isNonTrackableKeys(key)) {
623 return res;
624 }
625 if (!isReadonly) {
626 track(target, "get" /* GET */, key);
627 }
628 if (shallow) {
629 return res;
630 }
631 if (isRef(res)) {
632 // ref unwrapping - does not apply for Array + integer key.
633 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
634 return shouldUnwrap ? res.value : res;
635 }
636 if (isObject(res)) {
637 // Convert returned value into a proxy as well. we do the isObject check
638 // here to avoid invalid value warning. Also need to lazy access readonly
639 // and reactive here to avoid circular dependency.
640 return isReadonly ? readonly(res) : reactive(res);
641 }
642 return res;
643 };
644 }
645 const set = /*#__PURE__*/ createSetter();
646 const shallowSet = /*#__PURE__*/ createSetter(true);
647 function createSetter(shallow = false) {
648 return function set(target, key, value, receiver) {
649 let oldValue = target[key];
650 if (!shallow) {
651 value = toRaw(value);
652 oldValue = toRaw(oldValue);
653 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
654 oldValue.value = value;
655 return true;
656 }
657 }
658 const hadKey = isArray(target) && isIntegerKey(key)
659 ? Number(key) < target.length
660 : hasOwn(target, key);
661 const result = Reflect.set(target, key, value, receiver);
662 // don't trigger if target is something up in the prototype chain of original
663 if (target === toRaw(receiver)) {
664 if (!hadKey) {
665 trigger(target, "add" /* ADD */, key, value);
666 }
667 else if (hasChanged(value, oldValue)) {
668 trigger(target, "set" /* SET */, key, value, oldValue);
669 }
670 }
671 return result;
672 };
673 }
674 function deleteProperty(target, key) {
675 const hadKey = hasOwn(target, key);
676 const oldValue = target[key];
677 const result = Reflect.deleteProperty(target, key);
678 if (result && hadKey) {
679 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
680 }
681 return result;
682 }
683 function has(target, key) {
684 const result = Reflect.has(target, key);
685 if (!isSymbol(key) || !builtInSymbols.has(key)) {
686 track(target, "has" /* HAS */, key);
687 }
688 return result;
689 }
690 function ownKeys(target) {
691 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
692 return Reflect.ownKeys(target);
693 }
694 const mutableHandlers = {
695 get,
696 set,
697 deleteProperty,
698 has,
699 ownKeys
700 };
701 const readonlyHandlers = {
702 get: readonlyGet,
703 set(target, key) {
704 {
705 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
706 }
707 return true;
708 },
709 deleteProperty(target, key) {
710 {
711 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
712 }
713 return true;
714 }
715 };
716 const shallowReactiveHandlers = extend({}, mutableHandlers, {
717 get: shallowGet,
718 set: shallowSet
719 });
720 // Props handlers are special in the sense that it should not unwrap top-level
721 // refs (in order to allow refs to be explicitly passed down), but should
722 // retain the reactivity of the normal readonly object.
723 const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
724 get: shallowReadonlyGet
725 });
726
727 const toReactive = (value) => isObject(value) ? reactive(value) : value;
728 const toReadonly = (value) => isObject(value) ? readonly(value) : value;
729 const toShallow = (value) => value;
730 const getProto = (v) => Reflect.getPrototypeOf(v);
731 function get$1(target, key, isReadonly = false, isShallow = false) {
732 // #1772: readonly(reactive(Map)) should return readonly + reactive version
733 // of the value
734 target = target["__v_raw" /* RAW */];
735 const rawTarget = toRaw(target);
736 const rawKey = toRaw(key);
737 if (key !== rawKey) {
738 !isReadonly && track(rawTarget, "get" /* GET */, key);
739 }
740 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
741 const { has } = getProto(rawTarget);
742 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
743 if (has.call(rawTarget, key)) {
744 return wrap(target.get(key));
745 }
746 else if (has.call(rawTarget, rawKey)) {
747 return wrap(target.get(rawKey));
748 }
749 }
750 function has$1(key, isReadonly = false) {
751 const target = this["__v_raw" /* RAW */];
752 const rawTarget = toRaw(target);
753 const rawKey = toRaw(key);
754 if (key !== rawKey) {
755 !isReadonly && track(rawTarget, "has" /* HAS */, key);
756 }
757 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
758 return key === rawKey
759 ? target.has(key)
760 : target.has(key) || target.has(rawKey);
761 }
762 function size(target, isReadonly = false) {
763 target = target["__v_raw" /* RAW */];
764 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
765 return Reflect.get(target, 'size', target);
766 }
767 function add(value) {
768 value = toRaw(value);
769 const target = toRaw(this);
770 const proto = getProto(target);
771 const hadKey = proto.has.call(target, value);
772 if (!hadKey) {
773 target.add(value);
774 trigger(target, "add" /* ADD */, value, value);
775 }
776 return this;
777 }
778 function set$1(key, value) {
779 value = toRaw(value);
780 const target = toRaw(this);
781 const { has, get } = getProto(target);
782 let hadKey = has.call(target, key);
783 if (!hadKey) {
784 key = toRaw(key);
785 hadKey = has.call(target, key);
786 }
787 else {
788 checkIdentityKeys(target, has, key);
789 }
790 const oldValue = get.call(target, key);
791 target.set(key, value);
792 if (!hadKey) {
793 trigger(target, "add" /* ADD */, key, value);
794 }
795 else if (hasChanged(value, oldValue)) {
796 trigger(target, "set" /* SET */, key, value, oldValue);
797 }
798 return this;
799 }
800 function deleteEntry(key) {
801 const target = toRaw(this);
802 const { has, get } = getProto(target);
803 let hadKey = has.call(target, key);
804 if (!hadKey) {
805 key = toRaw(key);
806 hadKey = has.call(target, key);
807 }
808 else {
809 checkIdentityKeys(target, has, key);
810 }
811 const oldValue = get ? get.call(target, key) : undefined;
812 // forward the operation before queueing reactions
813 const result = target.delete(key);
814 if (hadKey) {
815 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
816 }
817 return result;
818 }
819 function clear() {
820 const target = toRaw(this);
821 const hadItems = target.size !== 0;
822 const oldTarget = isMap(target)
823 ? new Map(target)
824 : new Set(target)
825 ;
826 // forward the operation before queueing reactions
827 const result = target.clear();
828 if (hadItems) {
829 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
830 }
831 return result;
832 }
833 function createForEach(isReadonly, isShallow) {
834 return function forEach(callback, thisArg) {
835 const observed = this;
836 const target = observed["__v_raw" /* RAW */];
837 const rawTarget = toRaw(target);
838 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
839 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
840 return target.forEach((value, key) => {
841 // important: make sure the callback is
842 // 1. invoked with the reactive map as `this` and 3rd arg
843 // 2. the value received should be a corresponding reactive/readonly.
844 return callback.call(thisArg, wrap(value), wrap(key), observed);
845 });
846 };
847 }
848 function createIterableMethod(method, isReadonly, isShallow) {
849 return function (...args) {
850 const target = this["__v_raw" /* RAW */];
851 const rawTarget = toRaw(target);
852 const targetIsMap = isMap(rawTarget);
853 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
854 const isKeyOnly = method === 'keys' && targetIsMap;
855 const innerIterator = target[method](...args);
856 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
857 !isReadonly &&
858 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
859 // return a wrapped iterator which returns observed versions of the
860 // values emitted from the real iterator
861 return {
862 // iterator protocol
863 next() {
864 const { value, done } = innerIterator.next();
865 return done
866 ? { value, done }
867 : {
868 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
869 done
870 };
871 },
872 // iterable protocol
873 [Symbol.iterator]() {
874 return this;
875 }
876 };
877 };
878 }
879 function createReadonlyMethod(type) {
880 return function (...args) {
881 {
882 const key = args[0] ? `on key "${args[0]}" ` : ``;
883 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
884 }
885 return type === "delete" /* DELETE */ ? false : this;
886 };
887 }
888 const mutableInstrumentations = {
889 get(key) {
890 return get$1(this, key);
891 },
892 get size() {
893 return size(this);
894 },
895 has: has$1,
896 add,
897 set: set$1,
898 delete: deleteEntry,
899 clear,
900 forEach: createForEach(false, false)
901 };
902 const shallowInstrumentations = {
903 get(key) {
904 return get$1(this, key, false, true);
905 },
906 get size() {
907 return size(this);
908 },
909 has: has$1,
910 add,
911 set: set$1,
912 delete: deleteEntry,
913 clear,
914 forEach: createForEach(false, true)
915 };
916 const readonlyInstrumentations = {
917 get(key) {
918 return get$1(this, key, true);
919 },
920 get size() {
921 return size(this, true);
922 },
923 has(key) {
924 return has$1.call(this, key, true);
925 },
926 add: createReadonlyMethod("add" /* ADD */),
927 set: createReadonlyMethod("set" /* SET */),
928 delete: createReadonlyMethod("delete" /* DELETE */),
929 clear: createReadonlyMethod("clear" /* CLEAR */),
930 forEach: createForEach(true, false)
931 };
932 const shallowReadonlyInstrumentations = {
933 get(key) {
934 return get$1(this, key, true, true);
935 },
936 get size() {
937 return size(this, true);
938 },
939 has(key) {
940 return has$1.call(this, key, true);
941 },
942 add: createReadonlyMethod("add" /* ADD */),
943 set: createReadonlyMethod("set" /* SET */),
944 delete: createReadonlyMethod("delete" /* DELETE */),
945 clear: createReadonlyMethod("clear" /* CLEAR */),
946 forEach: createForEach(true, true)
947 };
948 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
949 iteratorMethods.forEach(method => {
950 mutableInstrumentations[method] = createIterableMethod(method, false, false);
951 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
952 shallowInstrumentations[method] = createIterableMethod(method, false, true);
953 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
954 });
955 function createInstrumentationGetter(isReadonly, shallow) {
956 const instrumentations = shallow
957 ? isReadonly
958 ? shallowReadonlyInstrumentations
959 : shallowInstrumentations
960 : isReadonly
961 ? readonlyInstrumentations
962 : mutableInstrumentations;
963 return (target, key, receiver) => {
964 if (key === "__v_isReactive" /* IS_REACTIVE */) {
965 return !isReadonly;
966 }
967 else if (key === "__v_isReadonly" /* IS_READONLY */) {
968 return isReadonly;
969 }
970 else if (key === "__v_raw" /* RAW */) {
971 return target;
972 }
973 return Reflect.get(hasOwn(instrumentations, key) && key in target
974 ? instrumentations
975 : target, key, receiver);
976 };
977 }
978 const mutableCollectionHandlers = {
979 get: createInstrumentationGetter(false, false)
980 };
981 const shallowCollectionHandlers = {
982 get: createInstrumentationGetter(false, true)
983 };
984 const readonlyCollectionHandlers = {
985 get: createInstrumentationGetter(true, false)
986 };
987 const shallowReadonlyCollectionHandlers = {
988 get: createInstrumentationGetter(true, true)
989 };
990 function checkIdentityKeys(target, has, key) {
991 const rawKey = toRaw(key);
992 if (rawKey !== key && has.call(target, rawKey)) {
993 const type = toRawType(target);
994 console.warn(`Reactive ${type} contains both the raw and reactive ` +
995 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
996 `which can lead to inconsistencies. ` +
997 `Avoid differentiating between the raw and reactive versions ` +
998 `of an object and only use the reactive version if possible.`);
999 }
1000 }
1001
1002 const reactiveMap = new WeakMap();
1003 const shallowReactiveMap = new WeakMap();
1004 const readonlyMap = new WeakMap();
1005 const shallowReadonlyMap = new WeakMap();
1006 function targetTypeMap(rawType) {
1007 switch (rawType) {
1008 case 'Object':
1009 case 'Array':
1010 return 1 /* COMMON */;
1011 case 'Map':
1012 case 'Set':
1013 case 'WeakMap':
1014 case 'WeakSet':
1015 return 2 /* COLLECTION */;
1016 default:
1017 return 0 /* INVALID */;
1018 }
1019 }
1020 function getTargetType(value) {
1021 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1022 ? 0 /* INVALID */
1023 : targetTypeMap(toRawType(value));
1024 }
1025 function reactive(target) {
1026 // if trying to observe a readonly proxy, return the readonly version.
1027 if (target && target["__v_isReadonly" /* IS_READONLY */]) {
1028 return target;
1029 }
1030 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1031 }
1032 /**
1033 * Return a shallowly-reactive copy of the original object, where only the root
1034 * level properties are reactive. It also does not auto-unwrap refs (even at the
1035 * root level).
1036 */
1037 function shallowReactive(target) {
1038 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1039 }
1040 /**
1041 * Creates a readonly copy of the original object. Note the returned copy is not
1042 * made reactive, but `readonly` can be called on an already reactive object.
1043 */
1044 function readonly(target) {
1045 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1046 }
1047 /**
1048 * Returns a reactive-copy of the original object, where only the root level
1049 * properties are readonly, and does NOT unwrap refs nor recursively convert
1050 * returned properties.
1051 * This is used for creating the props proxy object for stateful components.
1052 */
1053 function shallowReadonly(target) {
1054 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1055 }
1056 function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1057 if (!isObject(target)) {
1058 {
1059 console.warn(`value cannot be made reactive: ${String(target)}`);
1060 }
1061 return target;
1062 }
1063 // target is already a Proxy, return it.
1064 // exception: calling readonly() on a reactive object
1065 if (target["__v_raw" /* RAW */] &&
1066 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1067 return target;
1068 }
1069 // target already has corresponding Proxy
1070 const existingProxy = proxyMap.get(target);
1071 if (existingProxy) {
1072 return existingProxy;
1073 }
1074 // only a whitelist of value types can be observed.
1075 const targetType = getTargetType(target);
1076 if (targetType === 0 /* INVALID */) {
1077 return target;
1078 }
1079 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1080 proxyMap.set(target, proxy);
1081 return proxy;
1082 }
1083 function isReactive(value) {
1084 if (isReadonly(value)) {
1085 return isReactive(value["__v_raw" /* RAW */]);
1086 }
1087 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1088 }
1089 function isReadonly(value) {
1090 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1091 }
1092 function isProxy(value) {
1093 return isReactive(value) || isReadonly(value);
1094 }
1095 function toRaw(observed) {
1096 return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
1097 }
1098 function markRaw(value) {
1099 def(value, "__v_skip" /* SKIP */, true);
1100 return value;
1101 }
1102
1103 const convert = (val) => isObject(val) ? reactive(val) : val;
1104 function isRef(r) {
1105 return Boolean(r && r.__v_isRef === true);
1106 }
1107 function ref(value) {
1108 return createRef(value);
1109 }
1110 function shallowRef(value) {
1111 return createRef(value, true);
1112 }
1113 class RefImpl {
1114 constructor(_rawValue, _shallow = false) {
1115 this._rawValue = _rawValue;
1116 this._shallow = _shallow;
1117 this.__v_isRef = true;
1118 this._value = _shallow ? _rawValue : convert(_rawValue);
1119 }
1120 get value() {
1121 track(toRaw(this), "get" /* GET */, 'value');
1122 return this._value;
1123 }
1124 set value(newVal) {
1125 if (hasChanged(toRaw(newVal), this._rawValue)) {
1126 this._rawValue = newVal;
1127 this._value = this._shallow ? newVal : convert(newVal);
1128 trigger(toRaw(this), "set" /* SET */, 'value', newVal);
1129 }
1130 }
1131 }
1132 function createRef(rawValue, shallow = false) {
1133 if (isRef(rawValue)) {
1134 return rawValue;
1135 }
1136 return new RefImpl(rawValue, shallow);
1137 }
1138 function triggerRef(ref) {
1139 trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
1140 }
1141 function unref(ref) {
1142 return isRef(ref) ? ref.value : ref;
1143 }
1144 const shallowUnwrapHandlers = {
1145 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1146 set: (target, key, value, receiver) => {
1147 const oldValue = target[key];
1148 if (isRef(oldValue) && !isRef(value)) {
1149 oldValue.value = value;
1150 return true;
1151 }
1152 else {
1153 return Reflect.set(target, key, value, receiver);
1154 }
1155 }
1156 };
1157 function proxyRefs(objectWithRefs) {
1158 return isReactive(objectWithRefs)
1159 ? objectWithRefs
1160 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1161 }
1162 class CustomRefImpl {
1163 constructor(factory) {
1164 this.__v_isRef = true;
1165 const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
1166 this._get = get;
1167 this._set = set;
1168 }
1169 get value() {
1170 return this._get();
1171 }
1172 set value(newVal) {
1173 this._set(newVal);
1174 }
1175 }
1176 function customRef(factory) {
1177 return new CustomRefImpl(factory);
1178 }
1179 function toRefs(object) {
1180 if (!isProxy(object)) {
1181 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1182 }
1183 const ret = isArray(object) ? new Array(object.length) : {};
1184 for (const key in object) {
1185 ret[key] = toRef(object, key);
1186 }
1187 return ret;
1188 }
1189 class ObjectRefImpl {
1190 constructor(_object, _key) {
1191 this._object = _object;
1192 this._key = _key;
1193 this.__v_isRef = true;
1194 }
1195 get value() {
1196 return this._object[this._key];
1197 }
1198 set value(newVal) {
1199 this._object[this._key] = newVal;
1200 }
1201 }
1202 function toRef(object, key) {
1203 return isRef(object[key])
1204 ? object[key]
1205 : new ObjectRefImpl(object, key);
1206 }
1207
1208 class ComputedRefImpl {
1209 constructor(getter, _setter, isReadonly) {
1210 this._setter = _setter;
1211 this._dirty = true;
1212 this.__v_isRef = true;
1213 this.effect = effect(getter, {
1214 lazy: true,
1215 scheduler: () => {
1216 if (!this._dirty) {
1217 this._dirty = true;
1218 trigger(toRaw(this), "set" /* SET */, 'value');
1219 }
1220 }
1221 });
1222 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1223 }
1224 get value() {
1225 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1226 const self = toRaw(this);
1227 if (self._dirty) {
1228 self._value = this.effect();
1229 self._dirty = false;
1230 }
1231 track(self, "get" /* GET */, 'value');
1232 return self._value;
1233 }
1234 set value(newValue) {
1235 this._setter(newValue);
1236 }
1237 }
1238 function computed(getterOrOptions) {
1239 let getter;
1240 let setter;
1241 if (isFunction(getterOrOptions)) {
1242 getter = getterOrOptions;
1243 setter = () => {
1244 console.warn('Write operation failed: computed value is readonly');
1245 }
1246 ;
1247 }
1248 else {
1249 getter = getterOrOptions.get;
1250 setter = getterOrOptions.set;
1251 }
1252 return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
1253 }
1254
1255 const stack = [];
1256 function pushWarningContext(vnode) {
1257 stack.push(vnode);
1258 }
1259 function popWarningContext() {
1260 stack.pop();
1261 }
1262 function warn(msg, ...args) {
1263 // avoid props formatting or warn handler tracking deps that might be mutated
1264 // during patch, leading to infinite recursion.
1265 pauseTracking();
1266 const instance = stack.length ? stack[stack.length - 1].component : null;
1267 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1268 const trace = getComponentTrace();
1269 if (appWarnHandler) {
1270 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1271 msg + args.join(''),
1272 instance && instance.proxy,
1273 trace
1274 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1275 .join('\n'),
1276 trace
1277 ]);
1278 }
1279 else {
1280 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1281 /* istanbul ignore if */
1282 if (trace.length &&
1283 // avoid spamming console during tests
1284 !false) {
1285 warnArgs.push(`\n`, ...formatTrace(trace));
1286 }
1287 console.warn(...warnArgs);
1288 }
1289 resetTracking();
1290 }
1291 function getComponentTrace() {
1292 let currentVNode = stack[stack.length - 1];
1293 if (!currentVNode) {
1294 return [];
1295 }
1296 // we can't just use the stack because it will be incomplete during updates
1297 // that did not start from the root. Re-construct the parent chain using
1298 // instance parent pointers.
1299 const normalizedStack = [];
1300 while (currentVNode) {
1301 const last = normalizedStack[0];
1302 if (last && last.vnode === currentVNode) {
1303 last.recurseCount++;
1304 }
1305 else {
1306 normalizedStack.push({
1307 vnode: currentVNode,
1308 recurseCount: 0
1309 });
1310 }
1311 const parentInstance = currentVNode.component && currentVNode.component.parent;
1312 currentVNode = parentInstance && parentInstance.vnode;
1313 }
1314 return normalizedStack;
1315 }
1316 /* istanbul ignore next */
1317 function formatTrace(trace) {
1318 const logs = [];
1319 trace.forEach((entry, i) => {
1320 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1321 });
1322 return logs;
1323 }
1324 function formatTraceEntry({ vnode, recurseCount }) {
1325 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1326 const isRoot = vnode.component ? vnode.component.parent == null : false;
1327 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1328 const close = `>` + postfix;
1329 return vnode.props
1330 ? [open, ...formatProps(vnode.props), close]
1331 : [open + close];
1332 }
1333 /* istanbul ignore next */
1334 function formatProps(props) {
1335 const res = [];
1336 const keys = Object.keys(props);
1337 keys.slice(0, 3).forEach(key => {
1338 res.push(...formatProp(key, props[key]));
1339 });
1340 if (keys.length > 3) {
1341 res.push(` ...`);
1342 }
1343 return res;
1344 }
1345 /* istanbul ignore next */
1346 function formatProp(key, value, raw) {
1347 if (isString(value)) {
1348 value = JSON.stringify(value);
1349 return raw ? value : [`${key}=${value}`];
1350 }
1351 else if (typeof value === 'number' ||
1352 typeof value === 'boolean' ||
1353 value == null) {
1354 return raw ? value : [`${key}=${value}`];
1355 }
1356 else if (isRef(value)) {
1357 value = formatProp(key, toRaw(value.value), true);
1358 return raw ? value : [`${key}=Ref<`, value, `>`];
1359 }
1360 else if (isFunction(value)) {
1361 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1362 }
1363 else {
1364 value = toRaw(value);
1365 return raw ? value : [`${key}=`, value];
1366 }
1367 }
1368
1369 const ErrorTypeStrings = {
1370 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1371 ["c" /* CREATED */]: 'created hook',
1372 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1373 ["m" /* MOUNTED */]: 'mounted hook',
1374 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1375 ["u" /* UPDATED */]: 'updated',
1376 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1377 ["um" /* UNMOUNTED */]: 'unmounted hook',
1378 ["a" /* ACTIVATED */]: 'activated hook',
1379 ["da" /* DEACTIVATED */]: 'deactivated hook',
1380 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1381 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1382 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1383 [0 /* SETUP_FUNCTION */]: 'setup function',
1384 [1 /* RENDER_FUNCTION */]: 'render function',
1385 [2 /* WATCH_GETTER */]: 'watcher getter',
1386 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1387 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1388 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1389 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1390 [7 /* VNODE_HOOK */]: 'vnode hook',
1391 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1392 [9 /* TRANSITION_HOOK */]: 'transition hook',
1393 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1394 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1395 [12 /* FUNCTION_REF */]: 'ref function',
1396 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1397 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1398 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
1399 };
1400 function callWithErrorHandling(fn, instance, type, args) {
1401 let res;
1402 try {
1403 res = args ? fn(...args) : fn();
1404 }
1405 catch (err) {
1406 handleError(err, instance, type);
1407 }
1408 return res;
1409 }
1410 function callWithAsyncErrorHandling(fn, instance, type, args) {
1411 if (isFunction(fn)) {
1412 const res = callWithErrorHandling(fn, instance, type, args);
1413 if (res && isPromise(res)) {
1414 res.catch(err => {
1415 handleError(err, instance, type);
1416 });
1417 }
1418 return res;
1419 }
1420 const values = [];
1421 for (let i = 0; i < fn.length; i++) {
1422 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1423 }
1424 return values;
1425 }
1426 function handleError(err, instance, type, throwInDev = true) {
1427 const contextVNode = instance ? instance.vnode : null;
1428 if (instance) {
1429 let cur = instance.parent;
1430 // the exposed instance is the render proxy to keep it consistent with 2.x
1431 const exposedInstance = instance.proxy;
1432 // in production the hook receives only the error code
1433 const errorInfo = ErrorTypeStrings[type] ;
1434 while (cur) {
1435 const errorCapturedHooks = cur.ec;
1436 if (errorCapturedHooks) {
1437 for (let i = 0; i < errorCapturedHooks.length; i++) {
1438 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1439 return;
1440 }
1441 }
1442 }
1443 cur = cur.parent;
1444 }
1445 // app-level handling
1446 const appErrorHandler = instance.appContext.config.errorHandler;
1447 if (appErrorHandler) {
1448 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1449 return;
1450 }
1451 }
1452 logError(err, type, contextVNode, throwInDev);
1453 }
1454 function logError(err, type, contextVNode, throwInDev = true) {
1455 {
1456 const info = ErrorTypeStrings[type];
1457 if (contextVNode) {
1458 pushWarningContext(contextVNode);
1459 }
1460 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1461 if (contextVNode) {
1462 popWarningContext();
1463 }
1464 // crash in dev by default so it's more noticeable
1465 if (throwInDev) {
1466 throw err;
1467 }
1468 else {
1469 console.error(err);
1470 }
1471 }
1472 }
1473
1474 let isFlushing = false;
1475 let isFlushPending = false;
1476 const queue = [];
1477 let flushIndex = 0;
1478 const pendingPreFlushCbs = [];
1479 let activePreFlushCbs = null;
1480 let preFlushIndex = 0;
1481 const pendingPostFlushCbs = [];
1482 let activePostFlushCbs = null;
1483 let postFlushIndex = 0;
1484 const resolvedPromise = Promise.resolve();
1485 let currentFlushPromise = null;
1486 let currentPreFlushParentJob = null;
1487 const RECURSION_LIMIT = 100;
1488 function nextTick(fn) {
1489 const p = currentFlushPromise || resolvedPromise;
1490 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1491 }
1492 // #2768
1493 // Use binary-search to find a suitable position in the queue,
1494 // so that the queue maintains the increasing order of job's id,
1495 // which can prevent the job from being skipped and also can avoid repeated patching.
1496 function findInsertionIndex(job) {
1497 // the start index should be `flushIndex + 1`
1498 let start = flushIndex + 1;
1499 let end = queue.length;
1500 const jobId = getId(job);
1501 while (start < end) {
1502 const middle = (start + end) >>> 1;
1503 const middleJobId = getId(queue[middle]);
1504 middleJobId < jobId ? (start = middle + 1) : (end = middle);
1505 }
1506 return start;
1507 }
1508 function queueJob(job) {
1509 // the dedupe search uses the startIndex argument of Array.includes()
1510 // by default the search index includes the current job that is being run
1511 // so it cannot recursively trigger itself again.
1512 // if the job is a watch() callback, the search will start with a +1 index to
1513 // allow it recursively trigger itself - it is the user's responsibility to
1514 // ensure it doesn't end up in an infinite loop.
1515 if ((!queue.length ||
1516 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1517 job !== currentPreFlushParentJob) {
1518 const pos = findInsertionIndex(job);
1519 if (pos > -1) {
1520 queue.splice(pos, 0, job);
1521 }
1522 else {
1523 queue.push(job);
1524 }
1525 queueFlush();
1526 }
1527 }
1528 function queueFlush() {
1529 if (!isFlushing && !isFlushPending) {
1530 isFlushPending = true;
1531 currentFlushPromise = resolvedPromise.then(flushJobs);
1532 }
1533 }
1534 function invalidateJob(job) {
1535 const i = queue.indexOf(job);
1536 if (i > flushIndex) {
1537 queue.splice(i, 1);
1538 }
1539 }
1540 function queueCb(cb, activeQueue, pendingQueue, index) {
1541 if (!isArray(cb)) {
1542 if (!activeQueue ||
1543 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1544 pendingQueue.push(cb);
1545 }
1546 }
1547 else {
1548 // if cb is an array, it is a component lifecycle hook which can only be
1549 // triggered by a job, which is already deduped in the main queue, so
1550 // we can skip duplicate check here to improve perf
1551 pendingQueue.push(...cb);
1552 }
1553 queueFlush();
1554 }
1555 function queuePreFlushCb(cb) {
1556 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1557 }
1558 function queuePostFlushCb(cb) {
1559 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1560 }
1561 function flushPreFlushCbs(seen, parentJob = null) {
1562 if (pendingPreFlushCbs.length) {
1563 currentPreFlushParentJob = parentJob;
1564 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1565 pendingPreFlushCbs.length = 0;
1566 {
1567 seen = seen || new Map();
1568 }
1569 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1570 {
1571 checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]);
1572 }
1573 activePreFlushCbs[preFlushIndex]();
1574 }
1575 activePreFlushCbs = null;
1576 preFlushIndex = 0;
1577 currentPreFlushParentJob = null;
1578 // recursively flush until it drains
1579 flushPreFlushCbs(seen, parentJob);
1580 }
1581 }
1582 function flushPostFlushCbs(seen) {
1583 if (pendingPostFlushCbs.length) {
1584 const deduped = [...new Set(pendingPostFlushCbs)];
1585 pendingPostFlushCbs.length = 0;
1586 // #1947 already has active queue, nested flushPostFlushCbs call
1587 if (activePostFlushCbs) {
1588 activePostFlushCbs.push(...deduped);
1589 return;
1590 }
1591 activePostFlushCbs = deduped;
1592 {
1593 seen = seen || new Map();
1594 }
1595 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1596 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1597 {
1598 checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]);
1599 }
1600 activePostFlushCbs[postFlushIndex]();
1601 }
1602 activePostFlushCbs = null;
1603 postFlushIndex = 0;
1604 }
1605 }
1606 const getId = (job) => job.id == null ? Infinity : job.id;
1607 function flushJobs(seen) {
1608 isFlushPending = false;
1609 isFlushing = true;
1610 {
1611 seen = seen || new Map();
1612 }
1613 flushPreFlushCbs(seen);
1614 // Sort queue before flush.
1615 // This ensures that:
1616 // 1. Components are updated from parent to child. (because parent is always
1617 // created before the child so its render effect will have smaller
1618 // priority number)
1619 // 2. If a component is unmounted during a parent component's update,
1620 // its update can be skipped.
1621 queue.sort((a, b) => getId(a) - getId(b));
1622 try {
1623 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1624 const job = queue[flushIndex];
1625 if (job) {
1626 if (true) {
1627 checkRecursiveUpdates(seen, job);
1628 }
1629 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1630 }
1631 }
1632 }
1633 finally {
1634 flushIndex = 0;
1635 queue.length = 0;
1636 flushPostFlushCbs(seen);
1637 isFlushing = false;
1638 currentFlushPromise = null;
1639 // some postFlushCb queued jobs!
1640 // keep flushing until it drains.
1641 if (queue.length || pendingPostFlushCbs.length) {
1642 flushJobs(seen);
1643 }
1644 }
1645 }
1646 function checkRecursiveUpdates(seen, fn) {
1647 if (!seen.has(fn)) {
1648 seen.set(fn, 1);
1649 }
1650 else {
1651 const count = seen.get(fn);
1652 if (count > RECURSION_LIMIT) {
1653 throw new Error(`Maximum recursive updates exceeded. ` +
1654 `This means you have a reactive effect that is mutating its own ` +
1655 `dependencies and thus recursively triggering itself. Possible sources ` +
1656 `include component template, render function, updated hook or ` +
1657 `watcher source function.`);
1658 }
1659 else {
1660 seen.set(fn, count + 1);
1661 }
1662 }
1663 }
1664
1665 /* eslint-disable no-restricted-globals */
1666 let isHmrUpdating = false;
1667 const hmrDirtyComponents = new Set();
1668 // Expose the HMR runtime on the global object
1669 // This makes it entirely tree-shakable without polluting the exports and makes
1670 // it easier to be used in toolings like vue-loader
1671 // Note: for a component to be eligible for HMR it also needs the __hmrId option
1672 // to be set so that its instances can be registered / removed.
1673 {
1674 const globalObject = typeof global !== 'undefined'
1675 ? global
1676 : typeof self !== 'undefined'
1677 ? self
1678 : typeof window !== 'undefined'
1679 ? window
1680 : {};
1681 globalObject.__VUE_HMR_RUNTIME__ = {
1682 createRecord: tryWrap(createRecord),
1683 rerender: tryWrap(rerender),
1684 reload: tryWrap(reload)
1685 };
1686 }
1687 const map = new Map();
1688 function registerHMR(instance) {
1689 const id = instance.type.__hmrId;
1690 let record = map.get(id);
1691 if (!record) {
1692 createRecord(id, instance.type);
1693 record = map.get(id);
1694 }
1695 record.instances.add(instance);
1696 }
1697 function unregisterHMR(instance) {
1698 map.get(instance.type.__hmrId).instances.delete(instance);
1699 }
1700 function createRecord(id, component) {
1701 if (!component) {
1702 warn(`HMR API usage is out of date.\n` +
1703 `Please upgrade vue-loader/vite/rollup-plugin-vue or other relevant ` +
1704 `dependency that handles Vue SFC compilation.`);
1705 component = {};
1706 }
1707 if (map.has(id)) {
1708 return false;
1709 }
1710 map.set(id, {
1711 component: isClassComponent(component) ? component.__vccOpts : component,
1712 instances: new Set()
1713 });
1714 return true;
1715 }
1716 function rerender(id, newRender) {
1717 const record = map.get(id);
1718 if (!record)
1719 return;
1720 if (newRender)
1721 record.component.render = newRender;
1722 // Array.from creates a snapshot which avoids the set being mutated during
1723 // updates
1724 Array.from(record.instances).forEach(instance => {
1725 if (newRender) {
1726 instance.render = newRender;
1727 }
1728 instance.renderCache = [];
1729 // this flag forces child components with slot content to update
1730 isHmrUpdating = true;
1731 instance.update();
1732 isHmrUpdating = false;
1733 });
1734 }
1735 function reload(id, newComp) {
1736 const record = map.get(id);
1737 if (!record)
1738 return;
1739 // Array.from creates a snapshot which avoids the set being mutated during
1740 // updates
1741 const { component, instances } = record;
1742 if (!hmrDirtyComponents.has(component)) {
1743 // 1. Update existing comp definition to match new one
1744 newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
1745 extend(component, newComp);
1746 for (const key in component) {
1747 if (!(key in newComp)) {
1748 delete component[key];
1749 }
1750 }
1751 // 2. Mark component dirty. This forces the renderer to replace the component
1752 // on patch.
1753 hmrDirtyComponents.add(component);
1754 // 3. Make sure to unmark the component after the reload.
1755 queuePostFlushCb(() => {
1756 hmrDirtyComponents.delete(component);
1757 });
1758 }
1759 Array.from(instances).forEach(instance => {
1760 if (instance.parent) {
1761 // 4. Force the parent instance to re-render. This will cause all updated
1762 // components to be unmounted and re-mounted. Queue the update so that we
1763 // don't end up forcing the same parent to re-render multiple times.
1764 queueJob(instance.parent.update);
1765 }
1766 else if (instance.appContext.reload) {
1767 // root instance mounted via createApp() has a reload method
1768 instance.appContext.reload();
1769 }
1770 else if (typeof window !== 'undefined') {
1771 // root instance inside tree created via raw render(). Force reload.
1772 window.location.reload();
1773 }
1774 else {
1775 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1776 }
1777 });
1778 }
1779 function tryWrap(fn) {
1780 return (id, arg) => {
1781 try {
1782 return fn(id, arg);
1783 }
1784 catch (e) {
1785 console.error(e);
1786 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1787 `Full reload required.`);
1788 }
1789 };
1790 }
1791
1792 function setDevtoolsHook(hook) {
1793 exports.devtools = hook;
1794 }
1795 function devtoolsInitApp(app, version) {
1796 // TODO queue if devtools is undefined
1797 if (!exports.devtools)
1798 return;
1799 exports.devtools.emit("app:init" /* APP_INIT */, app, version, {
1800 Fragment,
1801 Text,
1802 Comment,
1803 Static
1804 });
1805 }
1806 function devtoolsUnmountApp(app) {
1807 if (!exports.devtools)
1808 return;
1809 exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1810 }
1811 const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1812 const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1813 const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1814 function createDevtoolsComponentHook(hook) {
1815 return (component) => {
1816 if (!exports.devtools)
1817 return;
1818 exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1819 };
1820 }
1821 function devtoolsComponentEmit(component, event, params) {
1822 if (!exports.devtools)
1823 return;
1824 exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1825 }
1826
1827 function emit(instance, event, ...rawArgs) {
1828 const props = instance.vnode.props || EMPTY_OBJ;
1829 {
1830 const { emitsOptions, propsOptions: [propsOptions] } = instance;
1831 if (emitsOptions) {
1832 if (!(event in emitsOptions)) {
1833 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
1834 warn(`Component emitted event "${event}" but it is neither declared in ` +
1835 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
1836 }
1837 }
1838 else {
1839 const validator = emitsOptions[event];
1840 if (isFunction(validator)) {
1841 const isValid = validator(...rawArgs);
1842 if (!isValid) {
1843 warn(`Invalid event arguments: event validation failed for event "${event}".`);
1844 }
1845 }
1846 }
1847 }
1848 }
1849 let args = rawArgs;
1850 const isModelListener = event.startsWith('update:');
1851 // for v-model update:xxx events, apply modifiers on args
1852 const modelArg = isModelListener && event.slice(7);
1853 if (modelArg && modelArg in props) {
1854 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
1855 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
1856 if (trim) {
1857 args = rawArgs.map(a => a.trim());
1858 }
1859 else if (number) {
1860 args = rawArgs.map(toNumber);
1861 }
1862 }
1863 {
1864 devtoolsComponentEmit(instance, event, args);
1865 }
1866 {
1867 const lowerCaseEvent = event.toLowerCase();
1868 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
1869 warn(`Event "${lowerCaseEvent}" is emitted in component ` +
1870 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
1871 `Note that HTML attributes are case-insensitive and you cannot use ` +
1872 `v-on to listen to camelCase events when using in-DOM templates. ` +
1873 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
1874 }
1875 }
1876 // convert handler name to camelCase. See issue #2249
1877 let handlerName = toHandlerKey(camelize(event));
1878 let handler = props[handlerName];
1879 // for v-model update:xxx events, also trigger kebab-case equivalent
1880 // for props passed via kebab-case
1881 if (!handler && isModelListener) {
1882 handlerName = toHandlerKey(hyphenate(event));
1883 handler = props[handlerName];
1884 }
1885 if (handler) {
1886 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
1887 }
1888 const onceHandler = props[handlerName + `Once`];
1889 if (onceHandler) {
1890 if (!instance.emitted) {
1891 (instance.emitted = {})[handlerName] = true;
1892 }
1893 else if (instance.emitted[handlerName]) {
1894 return;
1895 }
1896 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
1897 }
1898 }
1899 function normalizeEmitsOptions(comp, appContext, asMixin = false) {
1900 if (!appContext.deopt && comp.__emits !== undefined) {
1901 return comp.__emits;
1902 }
1903 const raw = comp.emits;
1904 let normalized = {};
1905 // apply mixin/extends props
1906 let hasExtends = false;
1907 if (!isFunction(comp)) {
1908 const extendEmits = (raw) => {
1909 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
1910 if (normalizedFromExtend) {
1911 hasExtends = true;
1912 extend(normalized, normalizedFromExtend);
1913 }
1914 };
1915 if (!asMixin && appContext.mixins.length) {
1916 appContext.mixins.forEach(extendEmits);
1917 }
1918 if (comp.extends) {
1919 extendEmits(comp.extends);
1920 }
1921 if (comp.mixins) {
1922 comp.mixins.forEach(extendEmits);
1923 }
1924 }
1925 if (!raw && !hasExtends) {
1926 return (comp.__emits = null);
1927 }
1928 if (isArray(raw)) {
1929 raw.forEach(key => (normalized[key] = null));
1930 }
1931 else {
1932 extend(normalized, raw);
1933 }
1934 return (comp.__emits = normalized);
1935 }
1936 // Check if an incoming prop key is a declared emit event listener.
1937 // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
1938 // both considered matched listeners.
1939 function isEmitListener(options, key) {
1940 if (!options || !isOn(key)) {
1941 return false;
1942 }
1943 key = key.slice(2).replace(/Once$/, '');
1944 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
1945 hasOwn(options, hyphenate(key)) ||
1946 hasOwn(options, key));
1947 }
1948
1949 let isRenderingCompiledSlot = 0;
1950 const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n);
1951 /**
1952 * Compiler runtime helper for rendering `<slot/>`
1953 * @private
1954 */
1955 function renderSlot(slots, name, props = {},
1956 // this is not a user-facing function, so the fallback is always generated by
1957 // the compiler and guaranteed to be a function returning an array
1958 fallback, noSlotted) {
1959 let slot = slots[name];
1960 if (slot && slot.length > 1) {
1961 warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
1962 `function. You need to mark this component with $dynamic-slots in the ` +
1963 `parent template.`);
1964 slot = () => [];
1965 }
1966 // a compiled slot disables block tracking by default to avoid manual
1967 // invocation interfering with template-based block tracking, but in
1968 // `renderSlot` we can be sure that it's template-based so we can force
1969 // enable it.
1970 isRenderingCompiledSlot++;
1971 openBlock();
1972 const validSlotContent = slot && ensureValidVNode(slot(props));
1973 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
1974 ? 64 /* STABLE_FRAGMENT */
1975 : -2 /* BAIL */);
1976 if (!noSlotted && rendered.scopeId) {
1977 rendered.slotScopeIds = [rendered.scopeId + '-s'];
1978 }
1979 isRenderingCompiledSlot--;
1980 return rendered;
1981 }
1982 function ensureValidVNode(vnodes) {
1983 return vnodes.some(child => {
1984 if (!isVNode(child))
1985 return true;
1986 if (child.type === Comment)
1987 return false;
1988 if (child.type === Fragment &&
1989 !ensureValidVNode(child.children))
1990 return false;
1991 return true;
1992 })
1993 ? vnodes
1994 : null;
1995 }
1996
1997 /**
1998 * mark the current rendering instance for asset resolution (e.g.
1999 * resolveComponent, resolveDirective) during render
2000 */
2001 let currentRenderingInstance = null;
2002 let currentScopeId = null;
2003 /**
2004 * Note: rendering calls maybe nested. The function returns the parent rendering
2005 * instance if present, which should be restored after the render is done:
2006 *
2007 * ```js
2008 * const prev = setCurrentRenderingInstance(i)
2009 * // ...render
2010 * setCurrentRenderingInstance(prev)
2011 * ```
2012 */
2013 function setCurrentRenderingInstance(instance) {
2014 const prev = currentRenderingInstance;
2015 currentRenderingInstance = instance;
2016 currentScopeId = (instance && instance.type.__scopeId) || null;
2017 return prev;
2018 }
2019 /**
2020 * Set scope id when creating hoisted vnodes.
2021 * @private compiler helper
2022 */
2023 function pushScopeId(id) {
2024 currentScopeId = id;
2025 }
2026 /**
2027 * Technically we no longer need this after 3.0.8 but we need to keep the same
2028 * API for backwards compat w/ code generated by compilers.
2029 * @private
2030 */
2031 function popScopeId() {
2032 currentScopeId = null;
2033 }
2034 /**
2035 * Only for backwards compat
2036 * @private
2037 */
2038 const withScopeId = (_id) => withCtx;
2039 /**
2040 * Wrap a slot function to memoize current rendering instance
2041 * @private compiler helper
2042 */
2043 function withCtx(fn, ctx = currentRenderingInstance) {
2044 if (!ctx)
2045 return fn;
2046 const renderFnWithContext = (...args) => {
2047 // If a user calls a compiled slot inside a template expression (#1745), it
2048 // can mess up block tracking, so by default we need to push a null block to
2049 // avoid that. This isn't necessary if rendering a compiled `<slot>`.
2050 if (!isRenderingCompiledSlot) {
2051 openBlock(true /* null block that disables tracking */);
2052 }
2053 const prevInstance = setCurrentRenderingInstance(ctx);
2054 const res = fn(...args);
2055 setCurrentRenderingInstance(prevInstance);
2056 if (!isRenderingCompiledSlot) {
2057 closeBlock();
2058 }
2059 return res;
2060 };
2061 // mark this as a compiled slot function.
2062 // this is used in vnode.ts -> normalizeChildren() to set the slot
2063 // rendering flag.
2064 renderFnWithContext._c = true;
2065 return renderFnWithContext;
2066 }
2067
2068 /**
2069 * dev only flag to track whether $attrs was used during render.
2070 * If $attrs was used during render then the warning for failed attrs
2071 * fallthrough can be suppressed.
2072 */
2073 let accessedAttrs = false;
2074 function markAttrsAccessed() {
2075 accessedAttrs = true;
2076 }
2077 function renderComponentRoot(instance) {
2078 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance;
2079 let result;
2080 const prev = setCurrentRenderingInstance(instance);
2081 {
2082 accessedAttrs = false;
2083 }
2084 try {
2085 let fallthroughAttrs;
2086 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2087 // withProxy is a proxy with a different `has` trap only for
2088 // runtime-compiled render functions using `with` block.
2089 const proxyToUse = withProxy || proxy;
2090 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2091 fallthroughAttrs = attrs;
2092 }
2093 else {
2094 // functional
2095 const render = Component;
2096 // in dev, mark attrs accessed if optional props (attrs === props)
2097 if (true && attrs === props) {
2098 markAttrsAccessed();
2099 }
2100 result = normalizeVNode(render.length > 1
2101 ? render(props, true
2102 ? {
2103 get attrs() {
2104 markAttrsAccessed();
2105 return attrs;
2106 },
2107 slots,
2108 emit
2109 }
2110 : { attrs, slots, emit })
2111 : render(props, null /* we know it doesn't need it */));
2112 fallthroughAttrs = Component.props
2113 ? attrs
2114 : getFunctionalFallthrough(attrs);
2115 }
2116 // attr merging
2117 // in dev mode, comments are preserved, and it's possible for a template
2118 // to have comments along side the root element which makes it a fragment
2119 let root = result;
2120 let setRoot = undefined;
2121 if (true &&
2122 result.patchFlag > 0 &&
2123 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2124 ;
2125 [root, setRoot] = getChildRoot(result);
2126 }
2127 if (Component.inheritAttrs !== false && fallthroughAttrs) {
2128 const keys = Object.keys(fallthroughAttrs);
2129 const { shapeFlag } = root;
2130 if (keys.length) {
2131 if (shapeFlag & 1 /* ELEMENT */ ||
2132 shapeFlag & 6 /* COMPONENT */) {
2133 if (propsOptions && keys.some(isModelListener)) {
2134 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2135 // prop, it indicates this component expects to handle v-model and
2136 // it should not fallthrough.
2137 // related: #1543, #1643, #1989
2138 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2139 }
2140 root = cloneVNode(root, fallthroughAttrs);
2141 }
2142 else if (true && !accessedAttrs && root.type !== Comment) {
2143 const allAttrs = Object.keys(attrs);
2144 const eventAttrs = [];
2145 const extraAttrs = [];
2146 for (let i = 0, l = allAttrs.length; i < l; i++) {
2147 const key = allAttrs[i];
2148 if (isOn(key)) {
2149 // ignore v-model handlers when they fail to fallthrough
2150 if (!isModelListener(key)) {
2151 // remove `on`, lowercase first letter to reflect event casing
2152 // accurately
2153 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2154 }
2155 }
2156 else {
2157 extraAttrs.push(key);
2158 }
2159 }
2160 if (extraAttrs.length) {
2161 warn(`Extraneous non-props attributes (` +
2162 `${extraAttrs.join(', ')}) ` +
2163 `were passed to component but could not be automatically inherited ` +
2164 `because component renders fragment or text root nodes.`);
2165 }
2166 if (eventAttrs.length) {
2167 warn(`Extraneous non-emits event listeners (` +
2168 `${eventAttrs.join(', ')}) ` +
2169 `were passed to component but could not be automatically inherited ` +
2170 `because component renders fragment or text root nodes. ` +
2171 `If the listener is intended to be a component custom event listener only, ` +
2172 `declare it using the "emits" option.`);
2173 }
2174 }
2175 }
2176 }
2177 // inherit directives
2178 if (vnode.dirs) {
2179 if (true && !isElementRoot(root)) {
2180 warn(`Runtime directive used on component with non-element root node. ` +
2181 `The directives will not function as intended.`);
2182 }
2183 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2184 }
2185 // inherit transition data
2186 if (vnode.transition) {
2187 if (true && !isElementRoot(root)) {
2188 warn(`Component inside <Transition> renders non-element root node ` +
2189 `that cannot be animated.`);
2190 }
2191 root.transition = vnode.transition;
2192 }
2193 if (true && setRoot) {
2194 setRoot(root);
2195 }
2196 else {
2197 result = root;
2198 }
2199 }
2200 catch (err) {
2201 blockStack.length = 0;
2202 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2203 result = createVNode(Comment);
2204 }
2205 setCurrentRenderingInstance(prev);
2206 return result;
2207 }
2208 /**
2209 * dev only
2210 * In dev mode, template root level comments are rendered, which turns the
2211 * template into a fragment root, but we need to locate the single element
2212 * root for attrs and scope id processing.
2213 */
2214 const getChildRoot = (vnode) => {
2215 const rawChildren = vnode.children;
2216 const dynamicChildren = vnode.dynamicChildren;
2217 const childRoot = filterSingleRoot(rawChildren);
2218 if (!childRoot) {
2219 return [vnode, undefined];
2220 }
2221 const index = rawChildren.indexOf(childRoot);
2222 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2223 const setRoot = (updatedRoot) => {
2224 rawChildren[index] = updatedRoot;
2225 if (dynamicChildren) {
2226 if (dynamicIndex > -1) {
2227 dynamicChildren[dynamicIndex] = updatedRoot;
2228 }
2229 else if (updatedRoot.patchFlag > 0) {
2230 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2231 }
2232 }
2233 };
2234 return [normalizeVNode(childRoot), setRoot];
2235 };
2236 function filterSingleRoot(children) {
2237 let singleRoot;
2238 for (let i = 0; i < children.length; i++) {
2239 const child = children[i];
2240 if (isVNode(child)) {
2241 // ignore user comment
2242 if (child.type !== Comment || child.children === 'v-if') {
2243 if (singleRoot) {
2244 // has more than 1 non-comment child, return now
2245 return;
2246 }
2247 else {
2248 singleRoot = child;
2249 }
2250 }
2251 }
2252 else {
2253 return;
2254 }
2255 }
2256 return singleRoot;
2257 }
2258 const getFunctionalFallthrough = (attrs) => {
2259 let res;
2260 for (const key in attrs) {
2261 if (key === 'class' || key === 'style' || isOn(key)) {
2262 (res || (res = {}))[key] = attrs[key];
2263 }
2264 }
2265 return res;
2266 };
2267 const filterModelListeners = (attrs, props) => {
2268 const res = {};
2269 for (const key in attrs) {
2270 if (!isModelListener(key) || !(key.slice(9) in props)) {
2271 res[key] = attrs[key];
2272 }
2273 }
2274 return res;
2275 };
2276 const isElementRoot = (vnode) => {
2277 return (vnode.shapeFlag & 6 /* COMPONENT */ ||
2278 vnode.shapeFlag & 1 /* ELEMENT */ ||
2279 vnode.type === Comment // potential v-if branch switch
2280 );
2281 };
2282 function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2283 const { props: prevProps, children: prevChildren, component } = prevVNode;
2284 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2285 const emits = component.emitsOptions;
2286 // Parent component's render function was hot-updated. Since this may have
2287 // caused the child component's slots content to have changed, we need to
2288 // force the child to update as well.
2289 if ((prevChildren || nextChildren) && isHmrUpdating) {
2290 return true;
2291 }
2292 // force child update for runtime directive or transition on component vnode.
2293 if (nextVNode.dirs || nextVNode.transition) {
2294 return true;
2295 }
2296 if (optimized && patchFlag >= 0) {
2297 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2298 // slot content that references values that might have changed,
2299 // e.g. in a v-for
2300 return true;
2301 }
2302 if (patchFlag & 16 /* FULL_PROPS */) {
2303 if (!prevProps) {
2304 return !!nextProps;
2305 }
2306 // presence of this flag indicates props are always non-null
2307 return hasPropsChanged(prevProps, nextProps, emits);
2308 }
2309 else if (patchFlag & 8 /* PROPS */) {
2310 const dynamicProps = nextVNode.dynamicProps;
2311 for (let i = 0; i < dynamicProps.length; i++) {
2312 const key = dynamicProps[i];
2313 if (nextProps[key] !== prevProps[key] &&
2314 !isEmitListener(emits, key)) {
2315 return true;
2316 }
2317 }
2318 }
2319 }
2320 else {
2321 // this path is only taken by manually written render functions
2322 // so presence of any children leads to a forced update
2323 if (prevChildren || nextChildren) {
2324 if (!nextChildren || !nextChildren.$stable) {
2325 return true;
2326 }
2327 }
2328 if (prevProps === nextProps) {
2329 return false;
2330 }
2331 if (!prevProps) {
2332 return !!nextProps;
2333 }
2334 if (!nextProps) {
2335 return true;
2336 }
2337 return hasPropsChanged(prevProps, nextProps, emits);
2338 }
2339 return false;
2340 }
2341 function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2342 const nextKeys = Object.keys(nextProps);
2343 if (nextKeys.length !== Object.keys(prevProps).length) {
2344 return true;
2345 }
2346 for (let i = 0; i < nextKeys.length; i++) {
2347 const key = nextKeys[i];
2348 if (nextProps[key] !== prevProps[key] &&
2349 !isEmitListener(emitsOptions, key)) {
2350 return true;
2351 }
2352 }
2353 return false;
2354 }
2355 function updateHOCHostEl({ vnode, parent }, el // HostNode
2356 ) {
2357 while (parent && parent.subTree === vnode) {
2358 (vnode = parent.vnode).el = el;
2359 parent = parent.parent;
2360 }
2361 }
2362
2363 const isSuspense = (type) => type.__isSuspense;
2364 // Suspense exposes a component-like API, and is treated like a component
2365 // in the compiler, but internally it's a special built-in type that hooks
2366 // directly into the renderer.
2367 const SuspenseImpl = {
2368 name: 'Suspense',
2369 // In order to make Suspense tree-shakable, we need to avoid importing it
2370 // directly in the renderer. The renderer checks for the __isSuspense flag
2371 // on a vnode's type and calls the `process` method, passing in renderer
2372 // internals.
2373 __isSuspense: true,
2374 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2375 // platform-specific impl passed from renderer
2376 rendererInternals) {
2377 if (n1 == null) {
2378 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2379 }
2380 else {
2381 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2382 }
2383 },
2384 hydrate: hydrateSuspense,
2385 create: createSuspenseBoundary
2386 };
2387 // Force-casted public typing for h and TSX props inference
2388 const Suspense = (SuspenseImpl
2389 );
2390 function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2391 const { p: patch, o: { createElement } } = rendererInternals;
2392 const hiddenContainer = createElement('div');
2393 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2394 // start mounting the content subtree in an off-dom container
2395 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2396 // now check if we have encountered any async deps
2397 if (suspense.deps > 0) {
2398 // has async
2399 // mount the fallback tree
2400 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2401 isSVG, slotScopeIds);
2402 setActiveBranch(suspense, vnode.ssFallback);
2403 }
2404 else {
2405 // Suspense has no async deps. Just resolve.
2406 suspense.resolve();
2407 }
2408 }
2409 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2410 const suspense = (n2.suspense = n1.suspense);
2411 suspense.vnode = n2;
2412 n2.el = n1.el;
2413 const newBranch = n2.ssContent;
2414 const newFallback = n2.ssFallback;
2415 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2416 if (pendingBranch) {
2417 suspense.pendingBranch = newBranch;
2418 if (isSameVNodeType(newBranch, pendingBranch)) {
2419 // same root type but content may have changed.
2420 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2421 if (suspense.deps <= 0) {
2422 suspense.resolve();
2423 }
2424 else if (isInFallback) {
2425 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2426 isSVG, slotScopeIds, optimized);
2427 setActiveBranch(suspense, newFallback);
2428 }
2429 }
2430 else {
2431 // toggled before pending tree is resolved
2432 suspense.pendingId++;
2433 if (isHydrating) {
2434 // if toggled before hydration is finished, the current DOM tree is
2435 // no longer valid. set it as the active branch so it will be unmounted
2436 // when resolved
2437 suspense.isHydrating = false;
2438 suspense.activeBranch = pendingBranch;
2439 }
2440 else {
2441 unmount(pendingBranch, parentComponent, suspense);
2442 }
2443 // increment pending ID. this is used to invalidate async callbacks
2444 // reset suspense state
2445 suspense.deps = 0;
2446 // discard effects from pending branch
2447 suspense.effects.length = 0;
2448 // discard previous container
2449 suspense.hiddenContainer = createElement('div');
2450 if (isInFallback) {
2451 // already in fallback state
2452 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2453 if (suspense.deps <= 0) {
2454 suspense.resolve();
2455 }
2456 else {
2457 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2458 isSVG, slotScopeIds, optimized);
2459 setActiveBranch(suspense, newFallback);
2460 }
2461 }
2462 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2463 // toggled "back" to current active branch
2464 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2465 // force resolve
2466 suspense.resolve(true);
2467 }
2468 else {
2469 // switched to a 3rd branch
2470 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2471 if (suspense.deps <= 0) {
2472 suspense.resolve();
2473 }
2474 }
2475 }
2476 }
2477 else {
2478 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2479 // root did not change, just normal patch
2480 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2481 setActiveBranch(suspense, newBranch);
2482 }
2483 else {
2484 // root node toggled
2485 // invoke @pending event
2486 const onPending = n2.props && n2.props.onPending;
2487 if (isFunction(onPending)) {
2488 onPending();
2489 }
2490 // mount pending branch in off-dom container
2491 suspense.pendingBranch = newBranch;
2492 suspense.pendingId++;
2493 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2494 if (suspense.deps <= 0) {
2495 // incoming branch has no async deps, resolve now.
2496 suspense.resolve();
2497 }
2498 else {
2499 const { timeout, pendingId } = suspense;
2500 if (timeout > 0) {
2501 setTimeout(() => {
2502 if (suspense.pendingId === pendingId) {
2503 suspense.fallback(newFallback);
2504 }
2505 }, timeout);
2506 }
2507 else if (timeout === 0) {
2508 suspense.fallback(newFallback);
2509 }
2510 }
2511 }
2512 }
2513 }
2514 let hasWarned = false;
2515 function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2516 /* istanbul ignore if */
2517 if (!hasWarned) {
2518 hasWarned = true;
2519 // @ts-ignore `console.info` cannot be null error
2520 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2521 }
2522 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2523 const timeout = toNumber(vnode.props && vnode.props.timeout);
2524 const suspense = {
2525 vnode,
2526 parent,
2527 parentComponent,
2528 isSVG,
2529 container,
2530 hiddenContainer,
2531 anchor,
2532 deps: 0,
2533 pendingId: 0,
2534 timeout: typeof timeout === 'number' ? timeout : -1,
2535 activeBranch: null,
2536 pendingBranch: null,
2537 isInFallback: true,
2538 isHydrating,
2539 isUnmounted: false,
2540 effects: [],
2541 resolve(resume = false) {
2542 {
2543 if (!resume && !suspense.pendingBranch) {
2544 throw new Error(`suspense.resolve() is called without a pending branch.`);
2545 }
2546 if (suspense.isUnmounted) {
2547 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2548 }
2549 }
2550 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2551 if (suspense.isHydrating) {
2552 suspense.isHydrating = false;
2553 }
2554 else if (!resume) {
2555 const delayEnter = activeBranch &&
2556 pendingBranch.transition &&
2557 pendingBranch.transition.mode === 'out-in';
2558 if (delayEnter) {
2559 activeBranch.transition.afterLeave = () => {
2560 if (pendingId === suspense.pendingId) {
2561 move(pendingBranch, container, anchor, 0 /* ENTER */);
2562 }
2563 };
2564 }
2565 // this is initial anchor on mount
2566 let { anchor } = suspense;
2567 // unmount current active tree
2568 if (activeBranch) {
2569 // if the fallback tree was mounted, it may have been moved
2570 // as part of a parent suspense. get the latest anchor for insertion
2571 anchor = next(activeBranch);
2572 unmount(activeBranch, parentComponent, suspense, true);
2573 }
2574 if (!delayEnter) {
2575 // move content from off-dom container to actual container
2576 move(pendingBranch, container, anchor, 0 /* ENTER */);
2577 }
2578 }
2579 setActiveBranch(suspense, pendingBranch);
2580 suspense.pendingBranch = null;
2581 suspense.isInFallback = false;
2582 // flush buffered effects
2583 // check if there is a pending parent suspense
2584 let parent = suspense.parent;
2585 let hasUnresolvedAncestor = false;
2586 while (parent) {
2587 if (parent.pendingBranch) {
2588 // found a pending parent suspense, merge buffered post jobs
2589 // into that parent
2590 parent.effects.push(...effects);
2591 hasUnresolvedAncestor = true;
2592 break;
2593 }
2594 parent = parent.parent;
2595 }
2596 // no pending parent suspense, flush all jobs
2597 if (!hasUnresolvedAncestor) {
2598 queuePostFlushCb(effects);
2599 }
2600 suspense.effects = [];
2601 // invoke @resolve event
2602 const onResolve = vnode.props && vnode.props.onResolve;
2603 if (isFunction(onResolve)) {
2604 onResolve();
2605 }
2606 },
2607 fallback(fallbackVNode) {
2608 if (!suspense.pendingBranch) {
2609 return;
2610 }
2611 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2612 // invoke @fallback event
2613 const onFallback = vnode.props && vnode.props.onFallback;
2614 if (isFunction(onFallback)) {
2615 onFallback();
2616 }
2617 const anchor = next(activeBranch);
2618 const mountFallback = () => {
2619 if (!suspense.isInFallback) {
2620 return;
2621 }
2622 // mount the fallback tree
2623 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2624 isSVG, slotScopeIds, optimized);
2625 setActiveBranch(suspense, fallbackVNode);
2626 };
2627 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2628 if (delayEnter) {
2629 activeBranch.transition.afterLeave = mountFallback;
2630 }
2631 // unmount current active branch
2632 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2633 true // shouldRemove
2634 );
2635 suspense.isInFallback = true;
2636 if (!delayEnter) {
2637 mountFallback();
2638 }
2639 },
2640 move(container, anchor, type) {
2641 suspense.activeBranch &&
2642 move(suspense.activeBranch, container, anchor, type);
2643 suspense.container = container;
2644 },
2645 next() {
2646 return suspense.activeBranch && next(suspense.activeBranch);
2647 },
2648 registerDep(instance, setupRenderEffect) {
2649 const isInPendingSuspense = !!suspense.pendingBranch;
2650 if (isInPendingSuspense) {
2651 suspense.deps++;
2652 }
2653 const hydratedEl = instance.vnode.el;
2654 instance
2655 .asyncDep.catch(err => {
2656 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2657 })
2658 .then(asyncSetupResult => {
2659 // retry when the setup() promise resolves.
2660 // component may have been unmounted before resolve.
2661 if (instance.isUnmounted ||
2662 suspense.isUnmounted ||
2663 suspense.pendingId !== instance.suspenseId) {
2664 return;
2665 }
2666 // retry from this component
2667 instance.asyncResolved = true;
2668 const { vnode } = instance;
2669 {
2670 pushWarningContext(vnode);
2671 }
2672 handleSetupResult(instance, asyncSetupResult, false);
2673 if (hydratedEl) {
2674 // vnode may have been replaced if an update happened before the
2675 // async dep is resolved.
2676 vnode.el = hydratedEl;
2677 }
2678 const placeholder = !hydratedEl && instance.subTree.el;
2679 setupRenderEffect(instance, vnode,
2680 // component may have been moved before resolve.
2681 // if this is not a hydration, instance.subTree will be the comment
2682 // placeholder.
2683 parentNode(hydratedEl || instance.subTree.el),
2684 // anchor will not be used if this is hydration, so only need to
2685 // consider the comment placeholder case.
2686 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
2687 if (placeholder) {
2688 remove(placeholder);
2689 }
2690 updateHOCHostEl(instance, vnode.el);
2691 {
2692 popWarningContext();
2693 }
2694 // only decrease deps count if suspense is not already resolved
2695 if (isInPendingSuspense && --suspense.deps === 0) {
2696 suspense.resolve();
2697 }
2698 });
2699 },
2700 unmount(parentSuspense, doRemove) {
2701 suspense.isUnmounted = true;
2702 if (suspense.activeBranch) {
2703 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
2704 }
2705 if (suspense.pendingBranch) {
2706 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
2707 }
2708 }
2709 };
2710 return suspense;
2711 }
2712 function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
2713 /* eslint-disable no-restricted-globals */
2714 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
2715 // there are two possible scenarios for server-rendered suspense:
2716 // - success: ssr content should be fully resolved
2717 // - failure: ssr content should be the fallback branch.
2718 // however, on the client we don't really know if it has failed or not
2719 // attempt to hydrate the DOM assuming it has succeeded, but we still
2720 // need to construct a suspense boundary first
2721 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
2722 if (suspense.deps === 0) {
2723 suspense.resolve();
2724 }
2725 return result;
2726 /* eslint-enable no-restricted-globals */
2727 }
2728 function normalizeSuspenseChildren(vnode) {
2729 const { shapeFlag, children } = vnode;
2730 let content;
2731 let fallback;
2732 if (shapeFlag & 32 /* SLOTS_CHILDREN */) {
2733 content = normalizeSuspenseSlot(children.default);
2734 fallback = normalizeSuspenseSlot(children.fallback);
2735 }
2736 else {
2737 content = normalizeSuspenseSlot(children);
2738 fallback = normalizeVNode(null);
2739 }
2740 return {
2741 content,
2742 fallback
2743 };
2744 }
2745 function normalizeSuspenseSlot(s) {
2746 if (isFunction(s)) {
2747 s = s();
2748 }
2749 if (isArray(s)) {
2750 const singleChild = filterSingleRoot(s);
2751 if (!singleChild) {
2752 warn(`<Suspense> slots expect a single root node.`);
2753 }
2754 s = singleChild;
2755 }
2756 return normalizeVNode(s);
2757 }
2758 function queueEffectWithSuspense(fn, suspense) {
2759 if (suspense && suspense.pendingBranch) {
2760 if (isArray(fn)) {
2761 suspense.effects.push(...fn);
2762 }
2763 else {
2764 suspense.effects.push(fn);
2765 }
2766 }
2767 else {
2768 queuePostFlushCb(fn);
2769 }
2770 }
2771 function setActiveBranch(suspense, branch) {
2772 suspense.activeBranch = branch;
2773 const { vnode, parentComponent } = suspense;
2774 const el = (vnode.el = branch.el);
2775 // in case suspense is the root node of a component,
2776 // recursively update the HOC el
2777 if (parentComponent && parentComponent.subTree === vnode) {
2778 parentComponent.vnode.el = el;
2779 updateHOCHostEl(parentComponent, el);
2780 }
2781 }
2782
2783 function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
2784 isSSR = false) {
2785 const props = {};
2786 const attrs = {};
2787 def(attrs, InternalObjectKey, 1);
2788 instance.propsDefaults = Object.create(null);
2789 setFullProps(instance, rawProps, props, attrs);
2790 // validation
2791 {
2792 validateProps(rawProps || {}, props, instance);
2793 }
2794 if (isStateful) {
2795 // stateful
2796 instance.props = isSSR ? props : shallowReactive(props);
2797 }
2798 else {
2799 if (!instance.type.props) {
2800 // functional w/ optional props, props === attrs
2801 instance.props = attrs;
2802 }
2803 else {
2804 // functional w/ declared props
2805 instance.props = props;
2806 }
2807 }
2808 instance.attrs = attrs;
2809 }
2810 function updateProps(instance, rawProps, rawPrevProps, optimized) {
2811 const { props, attrs, vnode: { patchFlag } } = instance;
2812 const rawCurrentProps = toRaw(props);
2813 const [options] = instance.propsOptions;
2814 if (
2815 // always force full diff in dev
2816 // - #1942 if hmr is enabled with sfc component
2817 // - vite#872 non-sfc component used by sfc component
2818 !((instance.type.__hmrId ||
2819 (instance.parent && instance.parent.type.__hmrId))) &&
2820 (optimized || patchFlag > 0) &&
2821 !(patchFlag & 16 /* FULL_PROPS */)) {
2822 if (patchFlag & 8 /* PROPS */) {
2823 // Compiler-generated props & no keys change, just set the updated
2824 // the props.
2825 const propsToUpdate = instance.vnode.dynamicProps;
2826 for (let i = 0; i < propsToUpdate.length; i++) {
2827 const key = propsToUpdate[i];
2828 // PROPS flag guarantees rawProps to be non-null
2829 const value = rawProps[key];
2830 if (options) {
2831 // attr / props separation was done on init and will be consistent
2832 // in this code path, so just check if attrs have it.
2833 if (hasOwn(attrs, key)) {
2834 attrs[key] = value;
2835 }
2836 else {
2837 const camelizedKey = camelize(key);
2838 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance);
2839 }
2840 }
2841 else {
2842 attrs[key] = value;
2843 }
2844 }
2845 }
2846 }
2847 else {
2848 // full props update.
2849 setFullProps(instance, rawProps, props, attrs);
2850 // in case of dynamic props, check if we need to delete keys from
2851 // the props object
2852 let kebabKey;
2853 for (const key in rawCurrentProps) {
2854 if (!rawProps ||
2855 // for camelCase
2856 (!hasOwn(rawProps, key) &&
2857 // it's possible the original props was passed in as kebab-case
2858 // and converted to camelCase (#955)
2859 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
2860 if (options) {
2861 if (rawPrevProps &&
2862 // for camelCase
2863 (rawPrevProps[key] !== undefined ||
2864 // for kebab-case
2865 rawPrevProps[kebabKey] !== undefined)) {
2866 props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance);
2867 }
2868 }
2869 else {
2870 delete props[key];
2871 }
2872 }
2873 }
2874 // in the case of functional component w/o props declaration, props and
2875 // attrs point to the same object so it should already have been updated.
2876 if (attrs !== rawCurrentProps) {
2877 for (const key in attrs) {
2878 if (!rawProps || !hasOwn(rawProps, key)) {
2879 delete attrs[key];
2880 }
2881 }
2882 }
2883 }
2884 // trigger updates for $attrs in case it's used in component slots
2885 trigger(instance, "set" /* SET */, '$attrs');
2886 {
2887 validateProps(rawProps || {}, props, instance);
2888 }
2889 }
2890 function setFullProps(instance, rawProps, props, attrs) {
2891 const [options, needCastKeys] = instance.propsOptions;
2892 if (rawProps) {
2893 for (const key in rawProps) {
2894 const value = rawProps[key];
2895 // key, ref are reserved and never passed down
2896 if (isReservedProp(key)) {
2897 continue;
2898 }
2899 // prop option names are camelized during normalization, so to support
2900 // kebab -> camel conversion here we need to camelize the key.
2901 let camelKey;
2902 if (options && hasOwn(options, (camelKey = camelize(key)))) {
2903 props[camelKey] = value;
2904 }
2905 else if (!isEmitListener(instance.emitsOptions, key)) {
2906 // Any non-declared (either as a prop or an emitted event) props are put
2907 // into a separate `attrs` object for spreading. Make sure to preserve
2908 // original key casing
2909 attrs[key] = value;
2910 }
2911 }
2912 }
2913 if (needCastKeys) {
2914 const rawCurrentProps = toRaw(props);
2915 for (let i = 0; i < needCastKeys.length; i++) {
2916 const key = needCastKeys[i];
2917 props[key] = resolvePropValue(options, rawCurrentProps, key, rawCurrentProps[key], instance);
2918 }
2919 }
2920 }
2921 function resolvePropValue(options, props, key, value, instance) {
2922 const opt = options[key];
2923 if (opt != null) {
2924 const hasDefault = hasOwn(opt, 'default');
2925 // default values
2926 if (hasDefault && value === undefined) {
2927 const defaultValue = opt.default;
2928 if (opt.type !== Function && isFunction(defaultValue)) {
2929 const { propsDefaults } = instance;
2930 if (key in propsDefaults) {
2931 value = propsDefaults[key];
2932 }
2933 else {
2934 setCurrentInstance(instance);
2935 value = propsDefaults[key] = defaultValue(props);
2936 setCurrentInstance(null);
2937 }
2938 }
2939 else {
2940 value = defaultValue;
2941 }
2942 }
2943 // boolean casting
2944 if (opt[0 /* shouldCast */]) {
2945 if (!hasOwn(props, key) && !hasDefault) {
2946 value = false;
2947 }
2948 else if (opt[1 /* shouldCastTrue */] &&
2949 (value === '' || value === hyphenate(key))) {
2950 value = true;
2951 }
2952 }
2953 }
2954 return value;
2955 }
2956 function normalizePropsOptions(comp, appContext, asMixin = false) {
2957 if (!appContext.deopt && comp.__props) {
2958 return comp.__props;
2959 }
2960 const raw = comp.props;
2961 const normalized = {};
2962 const needCastKeys = [];
2963 // apply mixin/extends props
2964 let hasExtends = false;
2965 if (!isFunction(comp)) {
2966 const extendProps = (raw) => {
2967 hasExtends = true;
2968 const [props, keys] = normalizePropsOptions(raw, appContext, true);
2969 extend(normalized, props);
2970 if (keys)
2971 needCastKeys.push(...keys);
2972 };
2973 if (!asMixin && appContext.mixins.length) {
2974 appContext.mixins.forEach(extendProps);
2975 }
2976 if (comp.extends) {
2977 extendProps(comp.extends);
2978 }
2979 if (comp.mixins) {
2980 comp.mixins.forEach(extendProps);
2981 }
2982 }
2983 if (!raw && !hasExtends) {
2984 return (comp.__props = EMPTY_ARR);
2985 }
2986 if (isArray(raw)) {
2987 for (let i = 0; i < raw.length; i++) {
2988 if (!isString(raw[i])) {
2989 warn(`props must be strings when using array syntax.`, raw[i]);
2990 }
2991 const normalizedKey = camelize(raw[i]);
2992 if (validatePropName(normalizedKey)) {
2993 normalized[normalizedKey] = EMPTY_OBJ;
2994 }
2995 }
2996 }
2997 else if (raw) {
2998 if (!isObject(raw)) {
2999 warn(`invalid props options`, raw);
3000 }
3001 for (const key in raw) {
3002 const normalizedKey = camelize(key);
3003 if (validatePropName(normalizedKey)) {
3004 const opt = raw[key];
3005 const prop = (normalized[normalizedKey] =
3006 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
3007 if (prop) {
3008 const booleanIndex = getTypeIndex(Boolean, prop.type);
3009 const stringIndex = getTypeIndex(String, prop.type);
3010 prop[0 /* shouldCast */] = booleanIndex > -1;
3011 prop[1 /* shouldCastTrue */] =
3012 stringIndex < 0 || booleanIndex < stringIndex;
3013 // if the prop needs boolean casting or default value
3014 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
3015 needCastKeys.push(normalizedKey);
3016 }
3017 }
3018 }
3019 }
3020 }
3021 return (comp.__props = [normalized, needCastKeys]);
3022 }
3023 function validatePropName(key) {
3024 if (key[0] !== '$') {
3025 return true;
3026 }
3027 else {
3028 warn(`Invalid prop name: "${key}" is a reserved property.`);
3029 }
3030 return false;
3031 }
3032 // use function string name to check type constructors
3033 // so that it works across vms / iframes.
3034 function getType(ctor) {
3035 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
3036 return match ? match[1] : '';
3037 }
3038 function isSameType(a, b) {
3039 return getType(a) === getType(b);
3040 }
3041 function getTypeIndex(type, expectedTypes) {
3042 if (isArray(expectedTypes)) {
3043 return expectedTypes.findIndex(t => isSameType(t, type));
3044 }
3045 else if (isFunction(expectedTypes)) {
3046 return isSameType(expectedTypes, type) ? 0 : -1;
3047 }
3048 return -1;
3049 }
3050 /**
3051 * dev only
3052 */
3053 function validateProps(rawProps, props, instance) {
3054 const resolvedValues = toRaw(props);
3055 const options = instance.propsOptions[0];
3056 for (const key in options) {
3057 let opt = options[key];
3058 if (opt == null)
3059 continue;
3060 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
3061 }
3062 }
3063 /**
3064 * dev only
3065 */
3066 function validateProp(name, value, prop, isAbsent) {
3067 const { type, required, validator } = prop;
3068 // required!
3069 if (required && isAbsent) {
3070 warn('Missing required prop: "' + name + '"');
3071 return;
3072 }
3073 // missing but optional
3074 if (value == null && !prop.required) {
3075 return;
3076 }
3077 // type check
3078 if (type != null && type !== true) {
3079 let isValid = false;
3080 const types = isArray(type) ? type : [type];
3081 const expectedTypes = [];
3082 // value is valid as long as one of the specified types match
3083 for (let i = 0; i < types.length && !isValid; i++) {
3084 const { valid, expectedType } = assertType(value, types[i]);
3085 expectedTypes.push(expectedType || '');
3086 isValid = valid;
3087 }
3088 if (!isValid) {
3089 warn(getInvalidTypeMessage(name, value, expectedTypes));
3090 return;
3091 }
3092 }
3093 // custom validator
3094 if (validator && !validator(value)) {
3095 warn('Invalid prop: custom validator check failed for prop "' + name + '".');
3096 }
3097 }
3098 const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
3099 /**
3100 * dev only
3101 */
3102 function assertType(value, type) {
3103 let valid;
3104 const expectedType = getType(type);
3105 if (isSimpleType(expectedType)) {
3106 const t = typeof value;
3107 valid = t === expectedType.toLowerCase();
3108 // for primitive wrapper objects
3109 if (!valid && t === 'object') {
3110 valid = value instanceof type;
3111 }
3112 }
3113 else if (expectedType === 'Object') {
3114 valid = isObject(value);
3115 }
3116 else if (expectedType === 'Array') {
3117 valid = isArray(value);
3118 }
3119 else {
3120 valid = value instanceof type;
3121 }
3122 return {
3123 valid,
3124 expectedType
3125 };
3126 }
3127 /**
3128 * dev only
3129 */
3130 function getInvalidTypeMessage(name, value, expectedTypes) {
3131 let message = `Invalid prop: type check failed for prop "${name}".` +
3132 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
3133 const expectedType = expectedTypes[0];
3134 const receivedType = toRawType(value);
3135 const expectedValue = styleValue(value, expectedType);
3136 const receivedValue = styleValue(value, receivedType);
3137 // check if we need to specify expected value
3138 if (expectedTypes.length === 1 &&
3139 isExplicable(expectedType) &&
3140 !isBoolean(expectedType, receivedType)) {
3141 message += ` with value ${expectedValue}`;
3142 }
3143 message += `, got ${receivedType} `;
3144 // check if we need to specify received value
3145 if (isExplicable(receivedType)) {
3146 message += `with value ${receivedValue}.`;
3147 }
3148 return message;
3149 }
3150 /**
3151 * dev only
3152 */
3153 function styleValue(value, type) {
3154 if (type === 'String') {
3155 return `"${value}"`;
3156 }
3157 else if (type === 'Number') {
3158 return `${Number(value)}`;
3159 }
3160 else {
3161 return `${value}`;
3162 }
3163 }
3164 /**
3165 * dev only
3166 */
3167 function isExplicable(type) {
3168 const explicitTypes = ['string', 'number', 'boolean'];
3169 return explicitTypes.some(elem => type.toLowerCase() === elem);
3170 }
3171 /**
3172 * dev only
3173 */
3174 function isBoolean(...args) {
3175 return args.some(elem => elem.toLowerCase() === 'boolean');
3176 }
3177
3178 function injectHook(type, hook, target = currentInstance, prepend = false) {
3179 if (target) {
3180 const hooks = target[type] || (target[type] = []);
3181 // cache the error handling wrapper for injected hooks so the same hook
3182 // can be properly deduped by the scheduler. "__weh" stands for "with error
3183 // handling".
3184 const wrappedHook = hook.__weh ||
3185 (hook.__weh = (...args) => {
3186 if (target.isUnmounted) {
3187 return;
3188 }
3189 // disable tracking inside all lifecycle hooks
3190 // since they can potentially be called inside effects.
3191 pauseTracking();
3192 // Set currentInstance during hook invocation.
3193 // This assumes the hook does not synchronously trigger other hooks, which
3194 // can only be false when the user does something really funky.
3195 setCurrentInstance(target);
3196 const res = callWithAsyncErrorHandling(hook, target, type, args);
3197 setCurrentInstance(null);
3198 resetTracking();
3199 return res;
3200 });
3201 if (prepend) {
3202 hooks.unshift(wrappedHook);
3203 }
3204 else {
3205 hooks.push(wrappedHook);
3206 }
3207 return wrappedHook;
3208 }
3209 else {
3210 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
3211 warn(`${apiName} is called when there is no active component instance to be ` +
3212 `associated with. ` +
3213 `Lifecycle injection APIs can only be used during execution of setup().` +
3214 (` If you are using async setup(), make sure to register lifecycle ` +
3215 `hooks before the first await statement.`
3216 ));
3217 }
3218 }
3219 const createHook = (lifecycle) => (hook, target = currentInstance) =>
3220 // post-create lifecycle registrations are noops during SSR
3221 !isInSSRComponentSetup && injectHook(lifecycle, hook, target);
3222 const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
3223 const onMounted = createHook("m" /* MOUNTED */);
3224 const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
3225 const onUpdated = createHook("u" /* UPDATED */);
3226 const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
3227 const onUnmounted = createHook("um" /* UNMOUNTED */);
3228 const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
3229 const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
3230 const onErrorCaptured = (hook, target = currentInstance) => {
3231 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
3232 };
3233
3234 // Simple effect.
3235 function watchEffect(effect, options) {
3236 return doWatch(effect, null, options);
3237 }
3238 // initial value for watchers to trigger on undefined initial values
3239 const INITIAL_WATCHER_VALUE = {};
3240 // implementation
3241 function watch(source, cb, options) {
3242 if (!isFunction(cb)) {
3243 warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3244 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3245 `supports \`watch(source, cb, options?) signature.`);
3246 }
3247 return doWatch(source, cb, options);
3248 }
3249 function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
3250 if (!cb) {
3251 if (immediate !== undefined) {
3252 warn(`watch() "immediate" option is only respected when using the ` +
3253 `watch(source, callback, options?) signature.`);
3254 }
3255 if (deep !== undefined) {
3256 warn(`watch() "deep" option is only respected when using the ` +
3257 `watch(source, callback, options?) signature.`);
3258 }
3259 }
3260 const warnInvalidSource = (s) => {
3261 warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3262 `a reactive object, or an array of these types.`);
3263 };
3264 let getter;
3265 let forceTrigger = false;
3266 if (isRef(source)) {
3267 getter = () => source.value;
3268 forceTrigger = !!source._shallow;
3269 }
3270 else if (isReactive(source)) {
3271 getter = () => source;
3272 deep = true;
3273 }
3274 else if (isArray(source)) {
3275 getter = () => source.map(s => {
3276 if (isRef(s)) {
3277 return s.value;
3278 }
3279 else if (isReactive(s)) {
3280 return traverse(s);
3281 }
3282 else if (isFunction(s)) {
3283 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */, [
3284 instance && instance.proxy
3285 ]);
3286 }
3287 else {
3288 warnInvalidSource(s);
3289 }
3290 });
3291 }
3292 else if (isFunction(source)) {
3293 if (cb) {
3294 // getter with cb
3295 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */, [
3296 instance && instance.proxy
3297 ]);
3298 }
3299 else {
3300 // no cb -> simple effect
3301 getter = () => {
3302 if (instance && instance.isUnmounted) {
3303 return;
3304 }
3305 if (cleanup) {
3306 cleanup();
3307 }
3308 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
3309 };
3310 }
3311 }
3312 else {
3313 getter = NOOP;
3314 warnInvalidSource(source);
3315 }
3316 if (cb && deep) {
3317 const baseGetter = getter;
3318 getter = () => traverse(baseGetter());
3319 }
3320 let cleanup;
3321 let onInvalidate = (fn) => {
3322 cleanup = runner.options.onStop = () => {
3323 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3324 };
3325 };
3326 let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE;
3327 const job = () => {
3328 if (!runner.active) {
3329 return;
3330 }
3331 if (cb) {
3332 // watch(source, cb)
3333 const newValue = runner();
3334 if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
3335 // cleanup before running cb again
3336 if (cleanup) {
3337 cleanup();
3338 }
3339 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3340 newValue,
3341 // pass undefined as the old value when it's changed for the first time
3342 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3343 onInvalidate
3344 ]);
3345 oldValue = newValue;
3346 }
3347 }
3348 else {
3349 // watchEffect
3350 runner();
3351 }
3352 };
3353 // important: mark the job as a watcher callback so that scheduler knows
3354 // it is allowed to self-trigger (#1727)
3355 job.allowRecurse = !!cb;
3356 let scheduler;
3357 if (flush === 'sync') {
3358 scheduler = job;
3359 }
3360 else if (flush === 'post') {
3361 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3362 }
3363 else {
3364 // default: 'pre'
3365 scheduler = () => {
3366 if (!instance || instance.isMounted) {
3367 queuePreFlushCb(job);
3368 }
3369 else {
3370 // with 'pre' option, the first call must happen before
3371 // the component is mounted so it is called synchronously.
3372 job();
3373 }
3374 };
3375 }
3376 const runner = effect(getter, {
3377 lazy: true,
3378 onTrack,
3379 onTrigger,
3380 scheduler
3381 });
3382 recordInstanceBoundEffect(runner, instance);
3383 // initial run
3384 if (cb) {
3385 if (immediate) {
3386 job();
3387 }
3388 else {
3389 oldValue = runner();
3390 }
3391 }
3392 else if (flush === 'post') {
3393 queuePostRenderEffect(runner, instance && instance.suspense);
3394 }
3395 else {
3396 runner();
3397 }
3398 return () => {
3399 stop(runner);
3400 if (instance) {
3401 remove(instance.effects, runner);
3402 }
3403 };
3404 }
3405 // this.$watch
3406 function instanceWatch(source, cb, options) {
3407 const publicThis = this.proxy;
3408 const getter = isString(source)
3409 ? () => publicThis[source]
3410 : source.bind(publicThis);
3411 return doWatch(getter, cb.bind(publicThis), options, this);
3412 }
3413 function traverse(value, seen = new Set()) {
3414 if (!isObject(value) || seen.has(value)) {
3415 return value;
3416 }
3417 seen.add(value);
3418 if (isRef(value)) {
3419 traverse(value.value, seen);
3420 }
3421 else if (isArray(value)) {
3422 for (let i = 0; i < value.length; i++) {
3423 traverse(value[i], seen);
3424 }
3425 }
3426 else if (isSet(value) || isMap(value)) {
3427 value.forEach((v) => {
3428 traverse(v, seen);
3429 });
3430 }
3431 else {
3432 for (const key in value) {
3433 traverse(value[key], seen);
3434 }
3435 }
3436 return value;
3437 }
3438
3439 function useTransitionState() {
3440 const state = {
3441 isMounted: false,
3442 isLeaving: false,
3443 isUnmounting: false,
3444 leavingVNodes: new Map()
3445 };
3446 onMounted(() => {
3447 state.isMounted = true;
3448 });
3449 onBeforeUnmount(() => {
3450 state.isUnmounting = true;
3451 });
3452 return state;
3453 }
3454 const TransitionHookValidator = [Function, Array];
3455 const BaseTransitionImpl = {
3456 name: `BaseTransition`,
3457 props: {
3458 mode: String,
3459 appear: Boolean,
3460 persisted: Boolean,
3461 // enter
3462 onBeforeEnter: TransitionHookValidator,
3463 onEnter: TransitionHookValidator,
3464 onAfterEnter: TransitionHookValidator,
3465 onEnterCancelled: TransitionHookValidator,
3466 // leave
3467 onBeforeLeave: TransitionHookValidator,
3468 onLeave: TransitionHookValidator,
3469 onAfterLeave: TransitionHookValidator,
3470 onLeaveCancelled: TransitionHookValidator,
3471 // appear
3472 onBeforeAppear: TransitionHookValidator,
3473 onAppear: TransitionHookValidator,
3474 onAfterAppear: TransitionHookValidator,
3475 onAppearCancelled: TransitionHookValidator
3476 },
3477 setup(props, { slots }) {
3478 const instance = getCurrentInstance();
3479 const state = useTransitionState();
3480 let prevTransitionKey;
3481 return () => {
3482 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3483 if (!children || !children.length) {
3484 return;
3485 }
3486 // warn multiple elements
3487 if (children.length > 1) {
3488 warn('<transition> can only be used on a single element or component. Use ' +
3489 '<transition-group> for lists.');
3490 }
3491 // there's no need to track reactivity for these props so use the raw
3492 // props for a bit better perf
3493 const rawProps = toRaw(props);
3494 const { mode } = rawProps;
3495 // check mode
3496 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3497 warn(`invalid <transition> mode: ${mode}`);
3498 }
3499 // at this point children has a guaranteed length of 1.
3500 const child = children[0];
3501 if (state.isLeaving) {
3502 return emptyPlaceholder(child);
3503 }
3504 // in the case of <transition><keep-alive/></transition>, we need to
3505 // compare the type of the kept-alive children.
3506 const innerChild = getKeepAliveChild(child);
3507 if (!innerChild) {
3508 return emptyPlaceholder(child);
3509 }
3510 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3511 setTransitionHooks(innerChild, enterHooks);
3512 const oldChild = instance.subTree;
3513 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3514 let transitionKeyChanged = false;
3515 const { getTransitionKey } = innerChild.type;
3516 if (getTransitionKey) {
3517 const key = getTransitionKey();
3518 if (prevTransitionKey === undefined) {
3519 prevTransitionKey = key;
3520 }
3521 else if (key !== prevTransitionKey) {
3522 prevTransitionKey = key;
3523 transitionKeyChanged = true;
3524 }
3525 }
3526 // handle mode
3527 if (oldInnerChild &&
3528 oldInnerChild.type !== Comment &&
3529 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3530 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3531 // update old tree's hooks in case of dynamic transition
3532 setTransitionHooks(oldInnerChild, leavingHooks);
3533 // switching between different views
3534 if (mode === 'out-in') {
3535 state.isLeaving = true;
3536 // return placeholder node and queue update when leave finishes
3537 leavingHooks.afterLeave = () => {
3538 state.isLeaving = false;
3539 instance.update();
3540 };
3541 return emptyPlaceholder(child);
3542 }
3543 else if (mode === 'in-out' && innerChild.type !== Comment) {
3544 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3545 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3546 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3547 // early removal callback
3548 el._leaveCb = () => {
3549 earlyRemove();
3550 el._leaveCb = undefined;
3551 delete enterHooks.delayedLeave;
3552 };
3553 enterHooks.delayedLeave = delayedLeave;
3554 };
3555 }
3556 }
3557 return child;
3558 };
3559 }
3560 };
3561 // export the public type for h/tsx inference
3562 // also to avoid inline import() in generated d.ts files
3563 const BaseTransition = BaseTransitionImpl;
3564 function getLeavingNodesForType(state, vnode) {
3565 const { leavingVNodes } = state;
3566 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3567 if (!leavingVNodesCache) {
3568 leavingVNodesCache = Object.create(null);
3569 leavingVNodes.set(vnode.type, leavingVNodesCache);
3570 }
3571 return leavingVNodesCache;
3572 }
3573 // The transition hooks are attached to the vnode as vnode.transition
3574 // and will be called at appropriate timing in the renderer.
3575 function resolveTransitionHooks(vnode, props, state, instance) {
3576 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3577 const key = String(vnode.key);
3578 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3579 const callHook = (hook, args) => {
3580 hook &&
3581 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3582 };
3583 const hooks = {
3584 mode,
3585 persisted,
3586 beforeEnter(el) {
3587 let hook = onBeforeEnter;
3588 if (!state.isMounted) {
3589 if (appear) {
3590 hook = onBeforeAppear || onBeforeEnter;
3591 }
3592 else {
3593 return;
3594 }
3595 }
3596 // for same element (v-show)
3597 if (el._leaveCb) {
3598 el._leaveCb(true /* cancelled */);
3599 }
3600 // for toggled element with same key (v-if)
3601 const leavingVNode = leavingVNodesCache[key];
3602 if (leavingVNode &&
3603 isSameVNodeType(vnode, leavingVNode) &&
3604 leavingVNode.el._leaveCb) {
3605 // force early removal (not cancelled)
3606 leavingVNode.el._leaveCb();
3607 }
3608 callHook(hook, [el]);
3609 },
3610 enter(el) {
3611 let hook = onEnter;
3612 let afterHook = onAfterEnter;
3613 let cancelHook = onEnterCancelled;
3614 if (!state.isMounted) {
3615 if (appear) {
3616 hook = onAppear || onEnter;
3617 afterHook = onAfterAppear || onAfterEnter;
3618 cancelHook = onAppearCancelled || onEnterCancelled;
3619 }
3620 else {
3621 return;
3622 }
3623 }
3624 let called = false;
3625 const done = (el._enterCb = (cancelled) => {
3626 if (called)
3627 return;
3628 called = true;
3629 if (cancelled) {
3630 callHook(cancelHook, [el]);
3631 }
3632 else {
3633 callHook(afterHook, [el]);
3634 }
3635 if (hooks.delayedLeave) {
3636 hooks.delayedLeave();
3637 }
3638 el._enterCb = undefined;
3639 });
3640 if (hook) {
3641 hook(el, done);
3642 if (hook.length <= 1) {
3643 done();
3644 }
3645 }
3646 else {
3647 done();
3648 }
3649 },
3650 leave(el, remove) {
3651 const key = String(vnode.key);
3652 if (el._enterCb) {
3653 el._enterCb(true /* cancelled */);
3654 }
3655 if (state.isUnmounting) {
3656 return remove();
3657 }
3658 callHook(onBeforeLeave, [el]);
3659 let called = false;
3660 const done = (el._leaveCb = (cancelled) => {
3661 if (called)
3662 return;
3663 called = true;
3664 remove();
3665 if (cancelled) {
3666 callHook(onLeaveCancelled, [el]);
3667 }
3668 else {
3669 callHook(onAfterLeave, [el]);
3670 }
3671 el._leaveCb = undefined;
3672 if (leavingVNodesCache[key] === vnode) {
3673 delete leavingVNodesCache[key];
3674 }
3675 });
3676 leavingVNodesCache[key] = vnode;
3677 if (onLeave) {
3678 onLeave(el, done);
3679 if (onLeave.length <= 1) {
3680 done();
3681 }
3682 }
3683 else {
3684 done();
3685 }
3686 },
3687 clone(vnode) {
3688 return resolveTransitionHooks(vnode, props, state, instance);
3689 }
3690 };
3691 return hooks;
3692 }
3693 // the placeholder really only handles one special case: KeepAlive
3694 // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3695 // placeholder with empty content to avoid the KeepAlive instance from being
3696 // unmounted.
3697 function emptyPlaceholder(vnode) {
3698 if (isKeepAlive(vnode)) {
3699 vnode = cloneVNode(vnode);
3700 vnode.children = null;
3701 return vnode;
3702 }
3703 }
3704 function getKeepAliveChild(vnode) {
3705 return isKeepAlive(vnode)
3706 ? vnode.children
3707 ? vnode.children[0]
3708 : undefined
3709 : vnode;
3710 }
3711 function setTransitionHooks(vnode, hooks) {
3712 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3713 setTransitionHooks(vnode.component.subTree, hooks);
3714 }
3715 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3716 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3717 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3718 }
3719 else {
3720 vnode.transition = hooks;
3721 }
3722 }
3723 function getTransitionRawChildren(children, keepComment = false) {
3724 let ret = [];
3725 let keyedFragmentCount = 0;
3726 for (let i = 0; i < children.length; i++) {
3727 const child = children[i];
3728 // handle fragment children case, e.g. v-for
3729 if (child.type === Fragment) {
3730 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3731 keyedFragmentCount++;
3732 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3733 }
3734 // comment placeholders should be skipped, e.g. v-if
3735 else if (keepComment || child.type !== Comment) {
3736 ret.push(child);
3737 }
3738 }
3739 // #1126 if a transition children list contains multiple sub fragments, these
3740 // fragments will be merged into a flat children array. Since each v-for
3741 // fragment may contain different static bindings inside, we need to de-op
3742 // these children to force full diffs to ensure correct behavior.
3743 if (keyedFragmentCount > 1) {
3744 for (let i = 0; i < ret.length; i++) {
3745 ret[i].patchFlag = -2 /* BAIL */;
3746 }
3747 }
3748 return ret;
3749 }
3750
3751 const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3752 const KeepAliveImpl = {
3753 name: `KeepAlive`,
3754 // Marker for special handling inside the renderer. We are not using a ===
3755 // check directly on KeepAlive in the renderer, because importing it directly
3756 // would prevent it from being tree-shaken.
3757 __isKeepAlive: true,
3758 props: {
3759 include: [String, RegExp, Array],
3760 exclude: [String, RegExp, Array],
3761 max: [String, Number]
3762 },
3763 setup(props, { slots }) {
3764 const instance = getCurrentInstance();
3765 // KeepAlive communicates with the instantiated renderer via the
3766 // ctx where the renderer passes in its internals,
3767 // and the KeepAlive instance exposes activate/deactivate implementations.
3768 // The whole point of this is to avoid importing KeepAlive directly in the
3769 // renderer to facilitate tree-shaking.
3770 const sharedContext = instance.ctx;
3771 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3772 // for KeepAlive, we just need to render its children
3773 if (!sharedContext.renderer) {
3774 return slots.default;
3775 }
3776 const cache = new Map();
3777 const keys = new Set();
3778 let current = null;
3779 const parentSuspense = instance.suspense;
3780 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3781 const storageContainer = createElement('div');
3782 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3783 const instance = vnode.component;
3784 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3785 // in case props have changed
3786 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3787 queuePostRenderEffect(() => {
3788 instance.isDeactivated = false;
3789 if (instance.a) {
3790 invokeArrayFns(instance.a);
3791 }
3792 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3793 if (vnodeHook) {
3794 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3795 }
3796 }, parentSuspense);
3797 };
3798 sharedContext.deactivate = (vnode) => {
3799 const instance = vnode.component;
3800 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3801 queuePostRenderEffect(() => {
3802 if (instance.da) {
3803 invokeArrayFns(instance.da);
3804 }
3805 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3806 if (vnodeHook) {
3807 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3808 }
3809 instance.isDeactivated = true;
3810 }, parentSuspense);
3811 };
3812 function unmount(vnode) {
3813 // reset the shapeFlag so it can be properly unmounted
3814 resetShapeFlag(vnode);
3815 _unmount(vnode, instance, parentSuspense);
3816 }
3817 function pruneCache(filter) {
3818 cache.forEach((vnode, key) => {
3819 const name = getComponentName(vnode.type);
3820 if (name && (!filter || !filter(name))) {
3821 pruneCacheEntry(key);
3822 }
3823 });
3824 }
3825 function pruneCacheEntry(key) {
3826 const cached = cache.get(key);
3827 if (!current || cached.type !== current.type) {
3828 unmount(cached);
3829 }
3830 else if (current) {
3831 // current active instance should no longer be kept-alive.
3832 // we can't unmount it now but it might be later, so reset its flag now.
3833 resetShapeFlag(current);
3834 }
3835 cache.delete(key);
3836 keys.delete(key);
3837 }
3838 // prune cache on include/exclude prop change
3839 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3840 include && pruneCache(name => matches(include, name));
3841 exclude && pruneCache(name => !matches(exclude, name));
3842 },
3843 // prune post-render after `current` has been updated
3844 { flush: 'post', deep: true });
3845 // cache sub tree after render
3846 let pendingCacheKey = null;
3847 const cacheSubtree = () => {
3848 // fix #1621, the pendingCacheKey could be 0
3849 if (pendingCacheKey != null) {
3850 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3851 }
3852 };
3853 onMounted(cacheSubtree);
3854 onUpdated(cacheSubtree);
3855 onBeforeUnmount(() => {
3856 cache.forEach(cached => {
3857 const { subTree, suspense } = instance;
3858 const vnode = getInnerChild(subTree);
3859 if (cached.type === vnode.type) {
3860 // current instance will be unmounted as part of keep-alive's unmount
3861 resetShapeFlag(vnode);
3862 // but invoke its deactivated hook here
3863 const da = vnode.component.da;
3864 da && queuePostRenderEffect(da, suspense);
3865 return;
3866 }
3867 unmount(cached);
3868 });
3869 });
3870 return () => {
3871 pendingCacheKey = null;
3872 if (!slots.default) {
3873 return null;
3874 }
3875 const children = slots.default();
3876 const rawVNode = children[0];
3877 if (children.length > 1) {
3878 {
3879 warn(`KeepAlive should contain exactly one component child.`);
3880 }
3881 current = null;
3882 return children;
3883 }
3884 else if (!isVNode(rawVNode) ||
3885 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3886 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3887 current = null;
3888 return rawVNode;
3889 }
3890 let vnode = getInnerChild(rawVNode);
3891 const comp = vnode.type;
3892 const name = getComponentName(comp);
3893 const { include, exclude, max } = props;
3894 if ((include && (!name || !matches(include, name))) ||
3895 (exclude && name && matches(exclude, name))) {
3896 current = vnode;
3897 return rawVNode;
3898 }
3899 const key = vnode.key == null ? comp : vnode.key;
3900 const cachedVNode = cache.get(key);
3901 // clone vnode if it's reused because we are going to mutate it
3902 if (vnode.el) {
3903 vnode = cloneVNode(vnode);
3904 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
3905 rawVNode.ssContent = vnode;
3906 }
3907 }
3908 // #1513 it's possible for the returned vnode to be cloned due to attr
3909 // fallthrough or scopeId, so the vnode here may not be the final vnode
3910 // that is mounted. Instead of caching it directly, we store the pending
3911 // key and cache `instance.subTree` (the normalized vnode) in
3912 // beforeMount/beforeUpdate hooks.
3913 pendingCacheKey = key;
3914 if (cachedVNode) {
3915 // copy over mounted state
3916 vnode.el = cachedVNode.el;
3917 vnode.component = cachedVNode.component;
3918 if (vnode.transition) {
3919 // recursively update transition hooks on subTree
3920 setTransitionHooks(vnode, vnode.transition);
3921 }
3922 // avoid vnode being mounted as fresh
3923 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
3924 // make this key the freshest
3925 keys.delete(key);
3926 keys.add(key);
3927 }
3928 else {
3929 keys.add(key);
3930 // prune oldest entry
3931 if (max && keys.size > parseInt(max, 10)) {
3932 pruneCacheEntry(keys.values().next().value);
3933 }
3934 }
3935 // avoid vnode being unmounted
3936 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3937 current = vnode;
3938 return rawVNode;
3939 };
3940 }
3941 };
3942 // export the public type for h/tsx inference
3943 // also to avoid inline import() in generated d.ts files
3944 const KeepAlive = KeepAliveImpl;
3945 function matches(pattern, name) {
3946 if (isArray(pattern)) {
3947 return pattern.some((p) => matches(p, name));
3948 }
3949 else if (isString(pattern)) {
3950 return pattern.split(',').indexOf(name) > -1;
3951 }
3952 else if (pattern.test) {
3953 return pattern.test(name);
3954 }
3955 /* istanbul ignore next */
3956 return false;
3957 }
3958 function onActivated(hook, target) {
3959 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
3960 }
3961 function onDeactivated(hook, target) {
3962 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
3963 }
3964 function registerKeepAliveHook(hook, type, target = currentInstance) {
3965 // cache the deactivate branch check wrapper for injected hooks so the same
3966 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
3967 // deactivation check".
3968 const wrappedHook = hook.__wdc ||
3969 (hook.__wdc = () => {
3970 // only fire the hook if the target instance is NOT in a deactivated branch.
3971 let current = target;
3972 while (current) {
3973 if (current.isDeactivated) {
3974 return;
3975 }
3976 current = current.parent;
3977 }
3978 hook();
3979 });
3980 injectHook(type, wrappedHook, target);
3981 // In addition to registering it on the target instance, we walk up the parent
3982 // chain and register it on all ancestor instances that are keep-alive roots.
3983 // This avoids the need to walk the entire component tree when invoking these
3984 // hooks, and more importantly, avoids the need to track child components in
3985 // arrays.
3986 if (target) {
3987 let current = target.parent;
3988 while (current && current.parent) {
3989 if (isKeepAlive(current.parent.vnode)) {
3990 injectToKeepAliveRoot(wrappedHook, type, target, current);
3991 }
3992 current = current.parent;
3993 }
3994 }
3995 }
3996 function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
3997 // injectHook wraps the original for error handling, so make sure to remove
3998 // the wrapped version.
3999 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4000 onUnmounted(() => {
4001 remove(keepAliveRoot[type], injected);
4002 }, target);
4003 }
4004 function resetShapeFlag(vnode) {
4005 let shapeFlag = vnode.shapeFlag;
4006 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4007 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4008 }
4009 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4010 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4011 }
4012 vnode.shapeFlag = shapeFlag;
4013 }
4014 function getInnerChild(vnode) {
4015 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4016 }
4017
4018 const isInternalKey = (key) => key[0] === '_' || key === '$stable';
4019 const normalizeSlotValue = (value) => isArray(value)
4020 ? value.map(normalizeVNode)
4021 : [normalizeVNode(value)];
4022 const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => {
4023 if (currentInstance) {
4024 warn(`Slot "${key}" invoked outside of the render function: ` +
4025 `this will not track dependencies used in the slot. ` +
4026 `Invoke the slot function inside the render function instead.`);
4027 }
4028 return normalizeSlotValue(rawSlot(props));
4029 }, ctx);
4030 const normalizeObjectSlots = (rawSlots, slots) => {
4031 const ctx = rawSlots._ctx;
4032 for (const key in rawSlots) {
4033 if (isInternalKey(key))
4034 continue;
4035 const value = rawSlots[key];
4036 if (isFunction(value)) {
4037 slots[key] = normalizeSlot(key, value, ctx);
4038 }
4039 else if (value != null) {
4040 {
4041 warn(`Non-function value encountered for slot "${key}". ` +
4042 `Prefer function slots for better performance.`);
4043 }
4044 const normalized = normalizeSlotValue(value);
4045 slots[key] = () => normalized;
4046 }
4047 }
4048 };
4049 const normalizeVNodeSlots = (instance, children) => {
4050 if (!isKeepAlive(instance.vnode)) {
4051 warn(`Non-function value encountered for default slot. ` +
4052 `Prefer function slots for better performance.`);
4053 }
4054 const normalized = normalizeSlotValue(children);
4055 instance.slots.default = () => normalized;
4056 };
4057 const initSlots = (instance, children) => {
4058 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4059 const type = children._;
4060 if (type) {
4061 instance.slots = children;
4062 // make compiler marker non-enumerable
4063 def(children, '_', type);
4064 }
4065 else {
4066 normalizeObjectSlots(children, (instance.slots = {}));
4067 }
4068 }
4069 else {
4070 instance.slots = {};
4071 if (children) {
4072 normalizeVNodeSlots(instance, children);
4073 }
4074 }
4075 def(instance.slots, InternalObjectKey, 1);
4076 };
4077 const updateSlots = (instance, children) => {
4078 const { vnode, slots } = instance;
4079 let needDeletionCheck = true;
4080 let deletionComparisonTarget = EMPTY_OBJ;
4081 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4082 const type = children._;
4083 if (type) {
4084 // compiled slots.
4085 if (isHmrUpdating) {
4086 // Parent was HMR updated so slot content may have changed.
4087 // force update slots and mark instance for hmr as well
4088 extend(slots, children);
4089 }
4090 else if (type === 1 /* STABLE */) {
4091 // compiled AND stable.
4092 // no need to update, and skip stale slots removal.
4093 needDeletionCheck = false;
4094 }
4095 else {
4096 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
4097 // normalization.
4098 extend(slots, children);
4099 }
4100 }
4101 else {
4102 needDeletionCheck = !children.$stable;
4103 normalizeObjectSlots(children, slots);
4104 }
4105 deletionComparisonTarget = children;
4106 }
4107 else if (children) {
4108 // non slot object children (direct value) passed to a component
4109 normalizeVNodeSlots(instance, children);
4110 deletionComparisonTarget = { default: 1 };
4111 }
4112 // delete stale slots
4113 if (needDeletionCheck) {
4114 for (const key in slots) {
4115 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
4116 delete slots[key];
4117 }
4118 }
4119 }
4120 };
4121
4122 /**
4123 Runtime helper for applying directives to a vnode. Example usage:
4124
4125 const comp = resolveComponent('comp')
4126 const foo = resolveDirective('foo')
4127 const bar = resolveDirective('bar')
4128
4129 return withDirectives(h(comp), [
4130 [foo, this.x],
4131 [bar, this.y]
4132 ])
4133 */
4134 const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
4135 function validateDirectiveName(name) {
4136 if (isBuiltInDirective(name)) {
4137 warn('Do not use built-in directive ids as custom directive id: ' + name);
4138 }
4139 }
4140 /**
4141 * Adds directives to a VNode.
4142 */
4143 function withDirectives(vnode, directives) {
4144 const internalInstance = currentRenderingInstance;
4145 if (internalInstance === null) {
4146 warn(`withDirectives can only be used inside render functions.`);
4147 return vnode;
4148 }
4149 const instance = internalInstance.proxy;
4150 const bindings = vnode.dirs || (vnode.dirs = []);
4151 for (let i = 0; i < directives.length; i++) {
4152 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4153 if (isFunction(dir)) {
4154 dir = {
4155 mounted: dir,
4156 updated: dir
4157 };
4158 }
4159 bindings.push({
4160 dir,
4161 instance,
4162 value,
4163 oldValue: void 0,
4164 arg,
4165 modifiers
4166 });
4167 }
4168 return vnode;
4169 }
4170 function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4171 const bindings = vnode.dirs;
4172 const oldBindings = prevVNode && prevVNode.dirs;
4173 for (let i = 0; i < bindings.length; i++) {
4174 const binding = bindings[i];
4175 if (oldBindings) {
4176 binding.oldValue = oldBindings[i].value;
4177 }
4178 const hook = binding.dir[name];
4179 if (hook) {
4180 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4181 vnode.el,
4182 binding,
4183 vnode,
4184 prevVNode
4185 ]);
4186 }
4187 }
4188 }
4189
4190 function createAppContext() {
4191 return {
4192 app: null,
4193 config: {
4194 isNativeTag: NO,
4195 performance: false,
4196 globalProperties: {},
4197 optionMergeStrategies: {},
4198 isCustomElement: NO,
4199 errorHandler: undefined,
4200 warnHandler: undefined
4201 },
4202 mixins: [],
4203 components: {},
4204 directives: {},
4205 provides: Object.create(null)
4206 };
4207 }
4208 let uid$1 = 0;
4209 function createAppAPI(render, hydrate) {
4210 return function createApp(rootComponent, rootProps = null) {
4211 if (rootProps != null && !isObject(rootProps)) {
4212 warn(`root props passed to app.mount() must be an object.`);
4213 rootProps = null;
4214 }
4215 const context = createAppContext();
4216 const installedPlugins = new Set();
4217 let isMounted = false;
4218 const app = (context.app = {
4219 _uid: uid$1++,
4220 _component: rootComponent,
4221 _props: rootProps,
4222 _container: null,
4223 _context: context,
4224 version,
4225 get config() {
4226 return context.config;
4227 },
4228 set config(v) {
4229 {
4230 warn(`app.config cannot be replaced. Modify individual options instead.`);
4231 }
4232 },
4233 use(plugin, ...options) {
4234 if (installedPlugins.has(plugin)) {
4235 warn(`Plugin has already been applied to target app.`);
4236 }
4237 else if (plugin && isFunction(plugin.install)) {
4238 installedPlugins.add(plugin);
4239 plugin.install(app, ...options);
4240 }
4241 else if (isFunction(plugin)) {
4242 installedPlugins.add(plugin);
4243 plugin(app, ...options);
4244 }
4245 else {
4246 warn(`A plugin must either be a function or an object with an "install" ` +
4247 `function.`);
4248 }
4249 return app;
4250 },
4251 mixin(mixin) {
4252 {
4253 if (!context.mixins.includes(mixin)) {
4254 context.mixins.push(mixin);
4255 // global mixin with props/emits de-optimizes props/emits
4256 // normalization caching.
4257 if (mixin.props || mixin.emits) {
4258 context.deopt = true;
4259 }
4260 }
4261 else {
4262 warn('Mixin has already been applied to target app' +
4263 (mixin.name ? `: ${mixin.name}` : ''));
4264 }
4265 }
4266 return app;
4267 },
4268 component(name, component) {
4269 {
4270 validateComponentName(name, context.config);
4271 }
4272 if (!component) {
4273 return context.components[name];
4274 }
4275 if (context.components[name]) {
4276 warn(`Component "${name}" has already been registered in target app.`);
4277 }
4278 context.components[name] = component;
4279 return app;
4280 },
4281 directive(name, directive) {
4282 {
4283 validateDirectiveName(name);
4284 }
4285 if (!directive) {
4286 return context.directives[name];
4287 }
4288 if (context.directives[name]) {
4289 warn(`Directive "${name}" has already been registered in target app.`);
4290 }
4291 context.directives[name] = directive;
4292 return app;
4293 },
4294 mount(rootContainer, isHydrate, isSVG) {
4295 if (!isMounted) {
4296 const vnode = createVNode(rootComponent, rootProps);
4297 // store app context on the root VNode.
4298 // this will be set on the root instance on initial mount.
4299 vnode.appContext = context;
4300 // HMR root reload
4301 {
4302 context.reload = () => {
4303 render(cloneVNode(vnode), rootContainer, isSVG);
4304 };
4305 }
4306 if (isHydrate && hydrate) {
4307 hydrate(vnode, rootContainer);
4308 }
4309 else {
4310 render(vnode, rootContainer, isSVG);
4311 }
4312 isMounted = true;
4313 app._container = rootContainer;
4314 rootContainer.__vue_app__ = app;
4315 {
4316 devtoolsInitApp(app, version);
4317 }
4318 return vnode.component.proxy;
4319 }
4320 else {
4321 warn(`App has already been mounted.\n` +
4322 `If you want to remount the same app, move your app creation logic ` +
4323 `into a factory function and create fresh app instances for each ` +
4324 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
4325 }
4326 },
4327 unmount() {
4328 if (isMounted) {
4329 render(null, app._container);
4330 {
4331 devtoolsUnmountApp(app);
4332 }
4333 delete app._container.__vue_app__;
4334 }
4335 else {
4336 warn(`Cannot unmount an app that is not mounted.`);
4337 }
4338 },
4339 provide(key, value) {
4340 if (key in context.provides) {
4341 warn(`App already provides property with key "${String(key)}". ` +
4342 `It will be overwritten with the new value.`);
4343 }
4344 // TypeScript doesn't allow symbols as index type
4345 // https://github.com/Microsoft/TypeScript/issues/24587
4346 context.provides[key] = value;
4347 return app;
4348 }
4349 });
4350 return app;
4351 };
4352 }
4353
4354 let hasMismatch = false;
4355 const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
4356 const isComment = (node) => node.nodeType === 8 /* COMMENT */;
4357 // Note: hydration is DOM-specific
4358 // But we have to place it in core due to tight coupling with core - splitting
4359 // it out creates a ton of unnecessary complexity.
4360 // Hydration also depends on some renderer internal logic which needs to be
4361 // passed in via arguments.
4362 function createHydrationFunctions(rendererInternals) {
4363 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
4364 const hydrate = (vnode, container) => {
4365 if (!container.hasChildNodes()) {
4366 warn(`Attempting to hydrate existing markup but container is empty. ` +
4367 `Performing full mount instead.`);
4368 patch(null, vnode, container);
4369 return;
4370 }
4371 hasMismatch = false;
4372 hydrateNode(container.firstChild, vnode, null, null, null);
4373 flushPostFlushCbs();
4374 if (hasMismatch && !false) {
4375 // this error should show up in production
4376 console.error(`Hydration completed but contains mismatches.`);
4377 }
4378 };
4379 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
4380 const isFragmentStart = isComment(node) && node.data === '[';
4381 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
4382 const { type, ref, shapeFlag } = vnode;
4383 const domType = node.nodeType;
4384 vnode.el = node;
4385 let nextNode = null;
4386 switch (type) {
4387 case Text:
4388 if (domType !== 3 /* TEXT */) {
4389 nextNode = onMismatch();
4390 }
4391 else {
4392 if (node.data !== vnode.children) {
4393 hasMismatch = true;
4394 warn(`Hydration text mismatch:` +
4395 `\n- Client: ${JSON.stringify(node.data)}` +
4396 `\n- Server: ${JSON.stringify(vnode.children)}`);
4397 node.data = vnode.children;
4398 }
4399 nextNode = nextSibling(node);
4400 }
4401 break;
4402 case Comment:
4403 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
4404 nextNode = onMismatch();
4405 }
4406 else {
4407 nextNode = nextSibling(node);
4408 }
4409 break;
4410 case Static:
4411 if (domType !== 1 /* ELEMENT */) {
4412 nextNode = onMismatch();
4413 }
4414 else {
4415 // determine anchor, adopt content
4416 nextNode = node;
4417 // if the static vnode has its content stripped during build,
4418 // adopt it from the server-rendered HTML.
4419 const needToAdoptContent = !vnode.children.length;
4420 for (let i = 0; i < vnode.staticCount; i++) {
4421 if (needToAdoptContent)
4422 vnode.children += nextNode.outerHTML;
4423 if (i === vnode.staticCount - 1) {
4424 vnode.anchor = nextNode;
4425 }
4426 nextNode = nextSibling(nextNode);
4427 }
4428 return nextNode;
4429 }
4430 break;
4431 case Fragment:
4432 if (!isFragmentStart) {
4433 nextNode = onMismatch();
4434 }
4435 else {
4436 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
4437 }
4438 break;
4439 default:
4440 if (shapeFlag & 1 /* ELEMENT */) {
4441 if (domType !== 1 /* ELEMENT */ ||
4442 vnode.type.toLowerCase() !==
4443 node.tagName.toLowerCase()) {
4444 nextNode = onMismatch();
4445 }
4446 else {
4447 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
4448 }
4449 }
4450 else if (shapeFlag & 6 /* COMPONENT */) {
4451 // when setting up the render effect, if the initial vnode already
4452 // has .el set, the component will perform hydration instead of mount
4453 // on its sub-tree.
4454 vnode.slotScopeIds = slotScopeIds;
4455 const container = parentNode(node);
4456 const hydrateComponent = () => {
4457 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
4458 };
4459 // async component
4460 const loadAsync = vnode.type.__asyncLoader;
4461 if (loadAsync) {
4462 loadAsync().then(hydrateComponent);
4463 }
4464 else {
4465 hydrateComponent();
4466 }
4467 // component may be async, so in the case of fragments we cannot rely
4468 // on component's rendered output to determine the end of the fragment
4469 // instead, we do a lookahead to find the end anchor node.
4470 nextNode = isFragmentStart
4471 ? locateClosingAsyncAnchor(node)
4472 : nextSibling(node);
4473 }
4474 else if (shapeFlag & 64 /* TELEPORT */) {
4475 if (domType !== 8 /* COMMENT */) {
4476 nextNode = onMismatch();
4477 }
4478 else {
4479 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
4480 }
4481 }
4482 else if (shapeFlag & 128 /* SUSPENSE */) {
4483 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
4484 }
4485 else {
4486 warn('Invalid HostVNode type:', type, `(${typeof type})`);
4487 }
4488 }
4489 if (ref != null) {
4490 setRef(ref, null, parentSuspense, vnode);
4491 }
4492 return nextNode;
4493 };
4494 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
4495 optimized = optimized || !!vnode.dynamicChildren;
4496 const { props, patchFlag, shapeFlag, dirs } = vnode;
4497 // skip props & children if this is hoisted static nodes
4498 if (patchFlag !== -1 /* HOISTED */) {
4499 if (dirs) {
4500 invokeDirectiveHook(vnode, null, parentComponent, 'created');
4501 }
4502 // props
4503 if (props) {
4504 if (!optimized ||
4505 (patchFlag & 16 /* FULL_PROPS */ ||
4506 patchFlag & 32 /* HYDRATE_EVENTS */)) {
4507 for (const key in props) {
4508 if (!isReservedProp(key) && isOn(key)) {
4509 patchProp(el, key, null, props[key]);
4510 }
4511 }
4512 }
4513 else if (props.onClick) {
4514 // Fast path for click listeners (which is most often) to avoid
4515 // iterating through props.
4516 patchProp(el, 'onClick', null, props.onClick);
4517 }
4518 }
4519 // vnode / directive hooks
4520 let vnodeHooks;
4521 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
4522 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
4523 }
4524 if (dirs) {
4525 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
4526 }
4527 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
4528 queueEffectWithSuspense(() => {
4529 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
4530 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
4531 }, parentSuspense);
4532 }
4533 // children
4534 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
4535 // skip if element has innerHTML / textContent
4536 !(props && (props.innerHTML || props.textContent))) {
4537 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
4538 let hasWarned = false;
4539 while (next) {
4540 hasMismatch = true;
4541 if (!hasWarned) {
4542 warn(`Hydration children mismatch in <${vnode.type}>: ` +
4543 `server rendered element contains more child nodes than client vdom.`);
4544 hasWarned = true;
4545 }
4546 // The SSRed DOM contains more nodes than it should. Remove them.
4547 const cur = next;
4548 next = next.nextSibling;
4549 remove(cur);
4550 }
4551 }
4552 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
4553 if (el.textContent !== vnode.children) {
4554 hasMismatch = true;
4555 warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
4556 `- Client: ${el.textContent}\n` +
4557 `- Server: ${vnode.children}`);
4558 el.textContent = vnode.children;
4559 }
4560 }
4561 }
4562 return el.nextSibling;
4563 };
4564 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
4565 optimized = optimized || !!parentVNode.dynamicChildren;
4566 const children = parentVNode.children;
4567 const l = children.length;
4568 let hasWarned = false;
4569 for (let i = 0; i < l; i++) {
4570 const vnode = optimized
4571 ? children[i]
4572 : (children[i] = normalizeVNode(children[i]));
4573 if (node) {
4574 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
4575 }
4576 else if (vnode.type === Text && !vnode.children) {
4577 continue;
4578 }
4579 else {
4580 hasMismatch = true;
4581 if (!hasWarned) {
4582 warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
4583 `server rendered element contains fewer child nodes than client vdom.`);
4584 hasWarned = true;
4585 }
4586 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
4587 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
4588 }
4589 }
4590 return node;
4591 };
4592 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
4593 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
4594 if (fragmentSlotScopeIds) {
4595 slotScopeIds = slotScopeIds
4596 ? slotScopeIds.concat(fragmentSlotScopeIds)
4597 : fragmentSlotScopeIds;
4598 }
4599 const container = parentNode(node);
4600 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
4601 if (next && isComment(next) && next.data === ']') {
4602 return nextSibling((vnode.anchor = next));
4603 }
4604 else {
4605 // fragment didn't hydrate successfully, since we didn't get a end anchor
4606 // back. This should have led to node/children mismatch warnings.
4607 hasMismatch = true;
4608 // since the anchor is missing, we need to create one and insert it
4609 insert((vnode.anchor = createComment(`]`)), container, next);
4610 return next;
4611 }
4612 };
4613 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
4614 hasMismatch = true;
4615 warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
4616 ? `(text)`
4617 : isComment(node) && node.data === '['
4618 ? `(start of fragment)`
4619 : ``);
4620 vnode.el = null;
4621 if (isFragment) {
4622 // remove excessive fragment nodes
4623 const end = locateClosingAsyncAnchor(node);
4624 while (true) {
4625 const next = nextSibling(node);
4626 if (next && next !== end) {
4627 remove(next);
4628 }
4629 else {
4630 break;
4631 }
4632 }
4633 }
4634 const next = nextSibling(node);
4635 const container = parentNode(node);
4636 remove(node);
4637 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
4638 return next;
4639 };
4640 const locateClosingAsyncAnchor = (node) => {
4641 let match = 0;
4642 while (node) {
4643 node = nextSibling(node);
4644 if (node && isComment(node)) {
4645 if (node.data === '[')
4646 match++;
4647 if (node.data === ']') {
4648 if (match === 0) {
4649 return nextSibling(node);
4650 }
4651 else {
4652 match--;
4653 }
4654 }
4655 }
4656 }
4657 return node;
4658 };
4659 return [hydrate, hydrateNode];
4660 }
4661
4662 let supported;
4663 let perf;
4664 function startMeasure(instance, type) {
4665 if (instance.appContext.config.performance && isSupported()) {
4666 perf.mark(`vue-${type}-${instance.uid}`);
4667 }
4668 }
4669 function endMeasure(instance, type) {
4670 if (instance.appContext.config.performance && isSupported()) {
4671 const startTag = `vue-${type}-${instance.uid}`;
4672 const endTag = startTag + `:end`;
4673 perf.mark(endTag);
4674 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
4675 perf.clearMarks(startTag);
4676 perf.clearMarks(endTag);
4677 }
4678 }
4679 function isSupported() {
4680 if (supported !== undefined) {
4681 return supported;
4682 }
4683 /* eslint-disable no-restricted-globals */
4684 if (typeof window !== 'undefined' && window.performance) {
4685 supported = true;
4686 perf = window.performance;
4687 }
4688 else {
4689 supported = false;
4690 }
4691 /* eslint-enable no-restricted-globals */
4692 return supported;
4693 }
4694
4695 // implementation, close to no-op
4696 function defineComponent(options) {
4697 return isFunction(options) ? { setup: options, name: options.name } : options;
4698 }
4699
4700 const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
4701 function defineAsyncComponent(source) {
4702 if (isFunction(source)) {
4703 source = { loader: source };
4704 }
4705 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
4706 suspensible = true, onError: userOnError } = source;
4707 let pendingRequest = null;
4708 let resolvedComp;
4709 let retries = 0;
4710 const retry = () => {
4711 retries++;
4712 pendingRequest = null;
4713 return load();
4714 };
4715 const load = () => {
4716 let thisRequest;
4717 return (pendingRequest ||
4718 (thisRequest = pendingRequest = loader()
4719 .catch(err => {
4720 err = err instanceof Error ? err : new Error(String(err));
4721 if (userOnError) {
4722 return new Promise((resolve, reject) => {
4723 const userRetry = () => resolve(retry());
4724 const userFail = () => reject(err);
4725 userOnError(err, userRetry, userFail, retries + 1);
4726 });
4727 }
4728 else {
4729 throw err;
4730 }
4731 })
4732 .then((comp) => {
4733 if (thisRequest !== pendingRequest && pendingRequest) {
4734 return pendingRequest;
4735 }
4736 if (!comp) {
4737 warn(`Async component loader resolved to undefined. ` +
4738 `If you are using retry(), make sure to return its return value.`);
4739 }
4740 // interop module default
4741 if (comp &&
4742 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
4743 comp = comp.default;
4744 }
4745 if (comp && !isObject(comp) && !isFunction(comp)) {
4746 throw new Error(`Invalid async component load result: ${comp}`);
4747 }
4748 resolvedComp = comp;
4749 return comp;
4750 })));
4751 };
4752 return defineComponent({
4753 __asyncLoader: load,
4754 name: 'AsyncComponentWrapper',
4755 setup() {
4756 const instance = currentInstance;
4757 // already resolved
4758 if (resolvedComp) {
4759 return () => createInnerComp(resolvedComp, instance);
4760 }
4761 const onError = (err) => {
4762 pendingRequest = null;
4763 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
4764 };
4765 // suspense-controlled or SSR.
4766 if ((suspensible && instance.suspense) ||
4767 (false )) {
4768 return load()
4769 .then(comp => {
4770 return () => createInnerComp(comp, instance);
4771 })
4772 .catch(err => {
4773 onError(err);
4774 return () => errorComponent
4775 ? createVNode(errorComponent, {
4776 error: err
4777 })
4778 : null;
4779 });
4780 }
4781 const loaded = ref(false);
4782 const error = ref();
4783 const delayed = ref(!!delay);
4784 if (delay) {
4785 setTimeout(() => {
4786 delayed.value = false;
4787 }, delay);
4788 }
4789 if (timeout != null) {
4790 setTimeout(() => {
4791 if (!loaded.value && !error.value) {
4792 const err = new Error(`Async component timed out after ${timeout}ms.`);
4793 onError(err);
4794 error.value = err;
4795 }
4796 }, timeout);
4797 }
4798 load()
4799 .then(() => {
4800 loaded.value = true;
4801 })
4802 .catch(err => {
4803 onError(err);
4804 error.value = err;
4805 });
4806 return () => {
4807 if (loaded.value && resolvedComp) {
4808 return createInnerComp(resolvedComp, instance);
4809 }
4810 else if (error.value && errorComponent) {
4811 return createVNode(errorComponent, {
4812 error: error.value
4813 });
4814 }
4815 else if (loadingComponent && !delayed.value) {
4816 return createVNode(loadingComponent);
4817 }
4818 };
4819 }
4820 });
4821 }
4822 function createInnerComp(comp, { vnode: { ref, props, children } }) {
4823 const vnode = createVNode(comp, props, children);
4824 // ensure inner component inherits the async wrapper's ref owner
4825 vnode.ref = ref;
4826 return vnode;
4827 }
4828
4829 function createDevEffectOptions(instance) {
4830 return {
4831 scheduler: queueJob,
4832 allowRecurse: true,
4833 onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
4834 onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
4835 };
4836 }
4837 const queuePostRenderEffect = queueEffectWithSuspense
4838 ;
4839 const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => {
4840 if (isArray(rawRef)) {
4841 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode));
4842 return;
4843 }
4844 let value;
4845 if (!vnode) {
4846 // means unmount
4847 value = null;
4848 }
4849 else if (isAsyncWrapper(vnode)) {
4850 // when mounting async components, nothing needs to be done,
4851 // because the template ref is forwarded to inner component
4852 return;
4853 }
4854 else if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
4855 value = vnode.component.exposed || vnode.component.proxy;
4856 }
4857 else {
4858 value = vnode.el;
4859 }
4860 const { i: owner, r: ref } = rawRef;
4861 if (!owner) {
4862 warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
4863 `A vnode with ref must be created inside the render function.`);
4864 return;
4865 }
4866 const oldRef = oldRawRef && oldRawRef.r;
4867 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
4868 const setupState = owner.setupState;
4869 // unset old ref
4870 if (oldRef != null && oldRef !== ref) {
4871 if (isString(oldRef)) {
4872 refs[oldRef] = null;
4873 if (hasOwn(setupState, oldRef)) {
4874 setupState[oldRef] = null;
4875 }
4876 }
4877 else if (isRef(oldRef)) {
4878 oldRef.value = null;
4879 }
4880 }
4881 if (isString(ref)) {
4882 const doSet = () => {
4883 refs[ref] = value;
4884 if (hasOwn(setupState, ref)) {
4885 setupState[ref] = value;
4886 }
4887 };
4888 // #1789: for non-null values, set them after render
4889 // null values means this is unmount and it should not overwrite another
4890 // ref with the same key
4891 if (value) {
4892 doSet.id = -1;
4893 queuePostRenderEffect(doSet, parentSuspense);
4894 }
4895 else {
4896 doSet();
4897 }
4898 }
4899 else if (isRef(ref)) {
4900 const doSet = () => {
4901 ref.value = value;
4902 };
4903 if (value) {
4904 doSet.id = -1;
4905 queuePostRenderEffect(doSet, parentSuspense);
4906 }
4907 else {
4908 doSet();
4909 }
4910 }
4911 else if (isFunction(ref)) {
4912 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
4913 }
4914 else {
4915 warn('Invalid template ref type:', value, `(${typeof value})`);
4916 }
4917 };
4918 /**
4919 * The createRenderer function accepts two generic arguments:
4920 * HostNode and HostElement, corresponding to Node and Element types in the
4921 * host environment. For example, for runtime-dom, HostNode would be the DOM
4922 * `Node` interface and HostElement would be the DOM `Element` interface.
4923 *
4924 * Custom renderers can pass in the platform specific types like this:
4925 *
4926 * ``` js
4927 * const { render, createApp } = createRenderer<Node, Element>({
4928 * patchProp,
4929 * ...nodeOps
4930 * })
4931 * ```
4932 */
4933 function createRenderer(options) {
4934 return baseCreateRenderer(options);
4935 }
4936 // Separate API for creating hydration-enabled renderer.
4937 // Hydration logic is only used when calling this function, making it
4938 // tree-shakable.
4939 function createHydrationRenderer(options) {
4940 return baseCreateRenderer(options, createHydrationFunctions);
4941 }
4942 // implementation
4943 function baseCreateRenderer(options, createHydrationFns) {
4944 {
4945 const target = getGlobalThis();
4946 target.__VUE__ = true;
4947 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
4948 }
4949 const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
4950 // Note: functions inside this closure should use `const xxx = () => {}`
4951 // style in order to prevent being inlined by minifiers.
4952 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = false) => {
4953 // patching & not same type, unmount old tree
4954 if (n1 && !isSameVNodeType(n1, n2)) {
4955 anchor = getNextHostNode(n1);
4956 unmount(n1, parentComponent, parentSuspense, true);
4957 n1 = null;
4958 }
4959 if (n2.patchFlag === -2 /* BAIL */) {
4960 optimized = false;
4961 n2.dynamicChildren = null;
4962 }
4963 const { type, ref, shapeFlag } = n2;
4964 switch (type) {
4965 case Text:
4966 processText(n1, n2, container, anchor);
4967 break;
4968 case Comment:
4969 processCommentNode(n1, n2, container, anchor);
4970 break;
4971 case Static:
4972 if (n1 == null) {
4973 mountStaticNode(n2, container, anchor, isSVG);
4974 }
4975 else {
4976 patchStaticNode(n1, n2, container, isSVG);
4977 }
4978 break;
4979 case Fragment:
4980 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
4981 break;
4982 default:
4983 if (shapeFlag & 1 /* ELEMENT */) {
4984 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
4985 }
4986 else if (shapeFlag & 6 /* COMPONENT */) {
4987 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
4988 }
4989 else if (shapeFlag & 64 /* TELEPORT */) {
4990 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
4991 }
4992 else if (shapeFlag & 128 /* SUSPENSE */) {
4993 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
4994 }
4995 else {
4996 warn('Invalid VNode type:', type, `(${typeof type})`);
4997 }
4998 }
4999 // set ref
5000 if (ref != null && parentComponent) {
5001 setRef(ref, n1 && n1.ref, parentSuspense, n2);
5002 }
5003 };
5004 const processText = (n1, n2, container, anchor) => {
5005 if (n1 == null) {
5006 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5007 }
5008 else {
5009 const el = (n2.el = n1.el);
5010 if (n2.children !== n1.children) {
5011 hostSetText(el, n2.children);
5012 }
5013 }
5014 };
5015 const processCommentNode = (n1, n2, container, anchor) => {
5016 if (n1 == null) {
5017 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5018 }
5019 else {
5020 // there's no support for dynamic comments
5021 n2.el = n1.el;
5022 }
5023 };
5024 const mountStaticNode = (n2, container, anchor, isSVG) => {
5025 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5026 };
5027 /**
5028 * Dev / HMR only
5029 */
5030 const patchStaticNode = (n1, n2, container, isSVG) => {
5031 // static nodes are only patched during dev for HMR
5032 if (n2.children !== n1.children) {
5033 const anchor = hostNextSibling(n1.anchor);
5034 // remove existing
5035 removeStaticNode(n1);
5036 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5037 }
5038 else {
5039 n2.el = n1.el;
5040 n2.anchor = n1.anchor;
5041 }
5042 };
5043 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5044 let next;
5045 while (el && el !== anchor) {
5046 next = hostNextSibling(el);
5047 hostInsert(el, container, nextSibling);
5048 el = next;
5049 }
5050 hostInsert(anchor, container, nextSibling);
5051 };
5052 const removeStaticNode = ({ el, anchor }) => {
5053 let next;
5054 while (el && el !== anchor) {
5055 next = hostNextSibling(el);
5056 hostRemove(el);
5057 el = next;
5058 }
5059 hostRemove(anchor);
5060 };
5061 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5062 isSVG = isSVG || n2.type === 'svg';
5063 if (n1 == null) {
5064 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5065 }
5066 else {
5067 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5068 }
5069 };
5070 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5071 let el;
5072 let vnodeHook;
5073 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
5074 {
5075 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
5076 // mount children first, since some props may rely on child content
5077 // being already rendered, e.g. `<select value>`
5078 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5079 hostSetElementText(el, vnode.children);
5080 }
5081 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5082 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized || !!vnode.dynamicChildren);
5083 }
5084 if (dirs) {
5085 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5086 }
5087 // props
5088 if (props) {
5089 for (const key in props) {
5090 if (!isReservedProp(key)) {
5091 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5092 }
5093 }
5094 if ((vnodeHook = props.onVnodeBeforeMount)) {
5095 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5096 }
5097 }
5098 // scopeId
5099 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
5100 }
5101 {
5102 Object.defineProperty(el, '__vnode', {
5103 value: vnode,
5104 enumerable: false
5105 });
5106 Object.defineProperty(el, '__vueParentComponent', {
5107 value: parentComponent,
5108 enumerable: false
5109 });
5110 }
5111 if (dirs) {
5112 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5113 }
5114 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5115 // #1689 For inside suspense + suspense resolved case, just call it
5116 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5117 transition &&
5118 !transition.persisted;
5119 if (needCallTransitionHooks) {
5120 transition.beforeEnter(el);
5121 }
5122 hostInsert(el, container, anchor);
5123 if ((vnodeHook = props && props.onVnodeMounted) ||
5124 needCallTransitionHooks ||
5125 dirs) {
5126 queuePostRenderEffect(() => {
5127 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5128 needCallTransitionHooks && transition.enter(el);
5129 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5130 }, parentSuspense);
5131 }
5132 };
5133 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
5134 if (scopeId) {
5135 hostSetScopeId(el, scopeId);
5136 }
5137 if (slotScopeIds) {
5138 for (let i = 0; i < slotScopeIds.length; i++) {
5139 hostSetScopeId(el, slotScopeIds[i]);
5140 }
5141 }
5142 if (parentComponent) {
5143 let subTree = parentComponent.subTree;
5144 if (subTree.patchFlag > 0 &&
5145 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
5146 subTree =
5147 filterSingleRoot(subTree.children) || subTree;
5148 }
5149 if (vnode === subTree) {
5150 const parentVNode = parentComponent.vnode;
5151 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
5152 }
5153 }
5154 };
5155 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, slotScopeIds, start = 0) => {
5156 for (let i = start; i < children.length; i++) {
5157 const child = (children[i] = optimized
5158 ? cloneIfMounted(children[i])
5159 : normalizeVNode(children[i]));
5160 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized, slotScopeIds);
5161 }
5162 };
5163 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5164 const el = (n2.el = n1.el);
5165 let { patchFlag, dynamicChildren, dirs } = n2;
5166 // #1426 take the old vnode's patch flag into account since user may clone a
5167 // compiler-generated vnode, which de-opts to FULL_PROPS
5168 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
5169 const oldProps = n1.props || EMPTY_OBJ;
5170 const newProps = n2.props || EMPTY_OBJ;
5171 let vnodeHook;
5172 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
5173 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5174 }
5175 if (dirs) {
5176 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
5177 }
5178 if (isHmrUpdating) {
5179 // HMR updated, force full diff
5180 patchFlag = 0;
5181 optimized = false;
5182 dynamicChildren = null;
5183 }
5184 if (patchFlag > 0) {
5185 // the presence of a patchFlag means this element's render code was
5186 // generated by the compiler and can take the fast path.
5187 // in this path old node and new node are guaranteed to have the same shape
5188 // (i.e. at the exact same position in the source template)
5189 if (patchFlag & 16 /* FULL_PROPS */) {
5190 // element props contain dynamic keys, full diff needed
5191 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5192 }
5193 else {
5194 // class
5195 // this flag is matched when the element has dynamic class bindings.
5196 if (patchFlag & 2 /* CLASS */) {
5197 if (oldProps.class !== newProps.class) {
5198 hostPatchProp(el, 'class', null, newProps.class, isSVG);
5199 }
5200 }
5201 // style
5202 // this flag is matched when the element has dynamic style bindings
5203 if (patchFlag & 4 /* STYLE */) {
5204 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
5205 }
5206 // props
5207 // This flag is matched when the element has dynamic prop/attr bindings
5208 // other than class and style. The keys of dynamic prop/attrs are saved for
5209 // faster iteration.
5210 // Note dynamic keys like :[foo]="bar" will cause this optimization to
5211 // bail out and go through a full diff because we need to unset the old key
5212 if (patchFlag & 8 /* PROPS */) {
5213 // if the flag is present then dynamicProps must be non-null
5214 const propsToUpdate = n2.dynamicProps;
5215 for (let i = 0; i < propsToUpdate.length; i++) {
5216 const key = propsToUpdate[i];
5217 const prev = oldProps[key];
5218 const next = newProps[key];
5219 if (next !== prev ||
5220 (hostForcePatchProp && hostForcePatchProp(el, key))) {
5221 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
5222 }
5223 }
5224 }
5225 }
5226 // text
5227 // This flag is matched when the element has only dynamic text children.
5228 if (patchFlag & 1 /* TEXT */) {
5229 if (n1.children !== n2.children) {
5230 hostSetElementText(el, n2.children);
5231 }
5232 }
5233 }
5234 else if (!optimized && dynamicChildren == null) {
5235 // unoptimized, full diff
5236 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5237 }
5238 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
5239 if (dynamicChildren) {
5240 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
5241 if (parentComponent && parentComponent.type.__hmrId) {
5242 traverseStaticChildren(n1, n2);
5243 }
5244 }
5245 else if (!optimized) {
5246 // full diff
5247 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
5248 }
5249 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
5250 queuePostRenderEffect(() => {
5251 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5252 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
5253 }, parentSuspense);
5254 }
5255 };
5256 // The fast path for blocks.
5257 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
5258 for (let i = 0; i < newChildren.length; i++) {
5259 const oldVNode = oldChildren[i];
5260 const newVNode = newChildren[i];
5261 // Determine the container (parent element) for the patch.
5262 const container =
5263 // - In the case of a Fragment, we need to provide the actual parent
5264 // of the Fragment itself so it can move its children.
5265 oldVNode.type === Fragment ||
5266 // - In the case of different nodes, there is going to be a replacement
5267 // which also requires the correct parent container
5268 !isSameVNodeType(oldVNode, newVNode) ||
5269 // - In the case of a component, it could contain anything.
5270 oldVNode.shapeFlag & 6 /* COMPONENT */ ||
5271 oldVNode.shapeFlag & 64 /* TELEPORT */
5272 ? hostParentNode(oldVNode.el)
5273 : // In other cases, the parent container is not actually used so we
5274 // just pass the block element here to avoid a DOM parentNode call.
5275 fallbackContainer;
5276 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
5277 }
5278 };
5279 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
5280 if (oldProps !== newProps) {
5281 for (const key in newProps) {
5282 // empty string is not valid prop
5283 if (isReservedProp(key))
5284 continue;
5285 const next = newProps[key];
5286 const prev = oldProps[key];
5287 if (next !== prev ||
5288 (hostForcePatchProp && hostForcePatchProp(el, key))) {
5289 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5290 }
5291 }
5292 if (oldProps !== EMPTY_OBJ) {
5293 for (const key in oldProps) {
5294 if (!isReservedProp(key) && !(key in newProps)) {
5295 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5296 }
5297 }
5298 }
5299 }
5300 };
5301 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5302 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
5303 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
5304 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
5305 if (patchFlag > 0) {
5306 optimized = true;
5307 }
5308 // check if this is a slot fragment with :slotted scope ids
5309 if (fragmentSlotScopeIds) {
5310 slotScopeIds = slotScopeIds
5311 ? slotScopeIds.concat(fragmentSlotScopeIds)
5312 : fragmentSlotScopeIds;
5313 }
5314 if (isHmrUpdating) {
5315 // HMR updated, force full diff
5316 patchFlag = 0;
5317 optimized = false;
5318 dynamicChildren = null;
5319 }
5320 if (n1 == null) {
5321 hostInsert(fragmentStartAnchor, container, anchor);
5322 hostInsert(fragmentEndAnchor, container, anchor);
5323 // a fragment can only have array children
5324 // since they are either generated by the compiler, or implicitly created
5325 // from arrays.
5326 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5327 }
5328 else {
5329 if (patchFlag > 0 &&
5330 patchFlag & 64 /* STABLE_FRAGMENT */ &&
5331 dynamicChildren &&
5332 // #2715 the previous fragment could've been a BAILed one as a result
5333 // of renderSlot() with no valid children
5334 n1.dynamicChildren) {
5335 // a stable fragment (template root or <template v-for>) doesn't need to
5336 // patch children order, but it may contain dynamicChildren.
5337 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
5338 if (parentComponent && parentComponent.type.__hmrId) {
5339 traverseStaticChildren(n1, n2);
5340 }
5341 else if (
5342 // #2080 if the stable fragment has a key, it's a <template v-for> that may
5343 // get moved around. Make sure all root level vnodes inherit el.
5344 // #2134 or if it's a component root, it may also get moved around
5345 // as the component is being moved.
5346 n2.key != null ||
5347 (parentComponent && n2 === parentComponent.subTree)) {
5348 traverseStaticChildren(n1, n2, true /* shallow */);
5349 }
5350 }
5351 else {
5352 // keyed / unkeyed, or manual fragments.
5353 // for keyed & unkeyed, since they are compiler generated from v-for,
5354 // each child is guaranteed to be a block so the fragment will never
5355 // have dynamicChildren.
5356 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5357 }
5358 }
5359 };
5360 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5361 n2.slotScopeIds = slotScopeIds;
5362 if (n1 == null) {
5363 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
5364 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
5365 }
5366 else {
5367 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5368 }
5369 }
5370 else {
5371 updateComponent(n1, n2, optimized);
5372 }
5373 };
5374 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5375 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
5376 if (instance.type.__hmrId) {
5377 registerHMR(instance);
5378 }
5379 {
5380 pushWarningContext(initialVNode);
5381 startMeasure(instance, `mount`);
5382 }
5383 // inject renderer internals for keepAlive
5384 if (isKeepAlive(initialVNode)) {
5385 instance.ctx.renderer = internals;
5386 }
5387 // resolve props and slots for setup context
5388 {
5389 startMeasure(instance, `init`);
5390 }
5391 setupComponent(instance);
5392 {
5393 endMeasure(instance, `init`);
5394 }
5395 // setup() is async. This component relies on async logic to be resolved
5396 // before proceeding
5397 if (instance.asyncDep) {
5398 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
5399 // Give it a placeholder if this is not hydration
5400 // TODO handle self-defined fallback
5401 if (!initialVNode.el) {
5402 const placeholder = (instance.subTree = createVNode(Comment));
5403 processCommentNode(null, placeholder, container, anchor);
5404 }
5405 return;
5406 }
5407 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
5408 {
5409 popWarningContext();
5410 endMeasure(instance, `mount`);
5411 }
5412 };
5413 const updateComponent = (n1, n2, optimized) => {
5414 const instance = (n2.component = n1.component);
5415 if (shouldUpdateComponent(n1, n2, optimized)) {
5416 if (instance.asyncDep &&
5417 !instance.asyncResolved) {
5418 // async & still pending - just update props and slots
5419 // since the component's reactive effect for render isn't set-up yet
5420 {
5421 pushWarningContext(n2);
5422 }
5423 updateComponentPreRender(instance, n2, optimized);
5424 {
5425 popWarningContext();
5426 }
5427 return;
5428 }
5429 else {
5430 // normal update
5431 instance.next = n2;
5432 // in case the child component is also queued, remove it to avoid
5433 // double updating the same child component in the same flush.
5434 invalidateJob(instance.update);
5435 // instance.update is the reactive effect runner.
5436 instance.update();
5437 }
5438 }
5439 else {
5440 // no update needed. just copy over properties
5441 n2.component = n1.component;
5442 n2.el = n1.el;
5443 instance.vnode = n2;
5444 }
5445 };
5446 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
5447 // create reactive effect for rendering
5448 instance.update = effect(function componentEffect() {
5449 if (!instance.isMounted) {
5450 let vnodeHook;
5451 const { el, props } = initialVNode;
5452 const { bm, m, parent } = instance;
5453 // beforeMount hook
5454 if (bm) {
5455 invokeArrayFns(bm);
5456 }
5457 // onVnodeBeforeMount
5458 if ((vnodeHook = props && props.onVnodeBeforeMount)) {
5459 invokeVNodeHook(vnodeHook, parent, initialVNode);
5460 }
5461 // render
5462 {
5463 startMeasure(instance, `render`);
5464 }
5465 const subTree = (instance.subTree = renderComponentRoot(instance));
5466 {
5467 endMeasure(instance, `render`);
5468 }
5469 if (el && hydrateNode) {
5470 {
5471 startMeasure(instance, `hydrate`);
5472 }
5473 // vnode has adopted host node - perform hydration instead of mount.
5474 hydrateNode(initialVNode.el, subTree, instance, parentSuspense, null);
5475 {
5476 endMeasure(instance, `hydrate`);
5477 }
5478 }
5479 else {
5480 {
5481 startMeasure(instance, `patch`);
5482 }
5483 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
5484 {
5485 endMeasure(instance, `patch`);
5486 }
5487 initialVNode.el = subTree.el;
5488 }
5489 // mounted hook
5490 if (m) {
5491 queuePostRenderEffect(m, parentSuspense);
5492 }
5493 // onVnodeMounted
5494 if ((vnodeHook = props && props.onVnodeMounted)) {
5495 const scopedInitialVNode = initialVNode;
5496 queuePostRenderEffect(() => {
5497 invokeVNodeHook(vnodeHook, parent, scopedInitialVNode);
5498 }, parentSuspense);
5499 }
5500 // activated hook for keep-alive roots.
5501 // #1742 activated hook must be accessed after first render
5502 // since the hook may be injected by a child keep-alive
5503 const { a } = instance;
5504 if (a &&
5505 initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5506 queuePostRenderEffect(a, parentSuspense);
5507 }
5508 instance.isMounted = true;
5509 {
5510 devtoolsComponentAdded(instance);
5511 }
5512 // #2458: deference mount-only object parameters to prevent memleaks
5513 initialVNode = container = anchor = null;
5514 }
5515 else {
5516 // updateComponent
5517 // This is triggered by mutation of component's own state (next: null)
5518 // OR parent calling processComponent (next: VNode)
5519 let { next, bu, u, parent, vnode } = instance;
5520 let originNext = next;
5521 let vnodeHook;
5522 {
5523 pushWarningContext(next || instance.vnode);
5524 }
5525 if (next) {
5526 next.el = vnode.el;
5527 updateComponentPreRender(instance, next, optimized);
5528 }
5529 else {
5530 next = vnode;
5531 }
5532 // beforeUpdate hook
5533 if (bu) {
5534 invokeArrayFns(bu);
5535 }
5536 // onVnodeBeforeUpdate
5537 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
5538 invokeVNodeHook(vnodeHook, parent, next, vnode);
5539 }
5540 // render
5541 {
5542 startMeasure(instance, `render`);
5543 }
5544 const nextTree = renderComponentRoot(instance);
5545 {
5546 endMeasure(instance, `render`);
5547 }
5548 const prevTree = instance.subTree;
5549 instance.subTree = nextTree;
5550 {
5551 startMeasure(instance, `patch`);
5552 }
5553 patch(prevTree, nextTree,
5554 // parent may have changed if it's in a teleport
5555 hostParentNode(prevTree.el),
5556 // anchor may have changed if it's in a fragment
5557 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
5558 {
5559 endMeasure(instance, `patch`);
5560 }
5561 next.el = nextTree.el;
5562 if (originNext === null) {
5563 // self-triggered update. In case of HOC, update parent component
5564 // vnode el. HOC is indicated by parent instance's subTree pointing
5565 // to child component's vnode
5566 updateHOCHostEl(instance, nextTree.el);
5567 }
5568 // updated hook
5569 if (u) {
5570 queuePostRenderEffect(u, parentSuspense);
5571 }
5572 // onVnodeUpdated
5573 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
5574 queuePostRenderEffect(() => {
5575 invokeVNodeHook(vnodeHook, parent, next, vnode);
5576 }, parentSuspense);
5577 }
5578 {
5579 devtoolsComponentUpdated(instance);
5580 }
5581 {
5582 popWarningContext();
5583 }
5584 }
5585 }, createDevEffectOptions(instance) );
5586 };
5587 const updateComponentPreRender = (instance, nextVNode, optimized) => {
5588 nextVNode.component = instance;
5589 const prevProps = instance.vnode.props;
5590 instance.vnode = nextVNode;
5591 instance.next = null;
5592 updateProps(instance, nextVNode.props, prevProps, optimized);
5593 updateSlots(instance, nextVNode.children);
5594 pauseTracking();
5595 // props update may have triggered pre-flush watchers.
5596 // flush them before the render update.
5597 flushPreFlushCbs(undefined, instance.update);
5598 resetTracking();
5599 };
5600 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
5601 const c1 = n1 && n1.children;
5602 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
5603 const c2 = n2.children;
5604 const { patchFlag, shapeFlag } = n2;
5605 // fast path
5606 if (patchFlag > 0) {
5607 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
5608 // this could be either fully-keyed or mixed (some keyed some not)
5609 // presence of patchFlag means children are guaranteed to be arrays
5610 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5611 return;
5612 }
5613 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
5614 // unkeyed
5615 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5616 return;
5617 }
5618 }
5619 // children has 3 possibilities: text, array or no children.
5620 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5621 // text children fast path
5622 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
5623 unmountChildren(c1, parentComponent, parentSuspense);
5624 }
5625 if (c2 !== c1) {
5626 hostSetElementText(container, c2);
5627 }
5628 }
5629 else {
5630 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
5631 // prev children was array
5632 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5633 // two arrays, cannot assume anything, do full diff
5634 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5635 }
5636 else {
5637 // no new children, just unmount old
5638 unmountChildren(c1, parentComponent, parentSuspense, true);
5639 }
5640 }
5641 else {
5642 // prev children was text OR null
5643 // new children is array OR null
5644 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
5645 hostSetElementText(container, '');
5646 }
5647 // mount new if array
5648 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5649 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5650 }
5651 }
5652 }
5653 };
5654 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5655 c1 = c1 || EMPTY_ARR;
5656 c2 = c2 || EMPTY_ARR;
5657 const oldLength = c1.length;
5658 const newLength = c2.length;
5659 const commonLength = Math.min(oldLength, newLength);
5660 let i;
5661 for (i = 0; i < commonLength; i++) {
5662 const nextChild = (c2[i] = optimized
5663 ? cloneIfMounted(c2[i])
5664 : normalizeVNode(c2[i]));
5665 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5666 }
5667 if (oldLength > newLength) {
5668 // remove old
5669 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
5670 }
5671 else {
5672 // mount new
5673 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
5674 }
5675 };
5676 // can be all-keyed or mixed
5677 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5678 let i = 0;
5679 const l2 = c2.length;
5680 let e1 = c1.length - 1; // prev ending index
5681 let e2 = l2 - 1; // next ending index
5682 // 1. sync from start
5683 // (a b) c
5684 // (a b) d e
5685 while (i <= e1 && i <= e2) {
5686 const n1 = c1[i];
5687 const n2 = (c2[i] = optimized
5688 ? cloneIfMounted(c2[i])
5689 : normalizeVNode(c2[i]));
5690 if (isSameVNodeType(n1, n2)) {
5691 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5692 }
5693 else {
5694 break;
5695 }
5696 i++;
5697 }
5698 // 2. sync from end
5699 // a (b c)
5700 // d e (b c)
5701 while (i <= e1 && i <= e2) {
5702 const n1 = c1[e1];
5703 const n2 = (c2[e2] = optimized
5704 ? cloneIfMounted(c2[e2])
5705 : normalizeVNode(c2[e2]));
5706 if (isSameVNodeType(n1, n2)) {
5707 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5708 }
5709 else {
5710 break;
5711 }
5712 e1--;
5713 e2--;
5714 }
5715 // 3. common sequence + mount
5716 // (a b)
5717 // (a b) c
5718 // i = 2, e1 = 1, e2 = 2
5719 // (a b)
5720 // c (a b)
5721 // i = 0, e1 = -1, e2 = 0
5722 if (i > e1) {
5723 if (i <= e2) {
5724 const nextPos = e2 + 1;
5725 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
5726 while (i <= e2) {
5727 patch(null, (c2[i] = optimized
5728 ? cloneIfMounted(c2[i])
5729 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5730 i++;
5731 }
5732 }
5733 }
5734 // 4. common sequence + unmount
5735 // (a b) c
5736 // (a b)
5737 // i = 2, e1 = 2, e2 = 1
5738 // a (b c)
5739 // (b c)
5740 // i = 0, e1 = 0, e2 = -1
5741 else if (i > e2) {
5742 while (i <= e1) {
5743 unmount(c1[i], parentComponent, parentSuspense, true);
5744 i++;
5745 }
5746 }
5747 // 5. unknown sequence
5748 // [i ... e1 + 1]: a b [c d e] f g
5749 // [i ... e2 + 1]: a b [e d c h] f g
5750 // i = 2, e1 = 4, e2 = 5
5751 else {
5752 const s1 = i; // prev starting index
5753 const s2 = i; // next starting index
5754 // 5.1 build key:index map for newChildren
5755 const keyToNewIndexMap = new Map();
5756 for (i = s2; i <= e2; i++) {
5757 const nextChild = (c2[i] = optimized
5758 ? cloneIfMounted(c2[i])
5759 : normalizeVNode(c2[i]));
5760 if (nextChild.key != null) {
5761 if (keyToNewIndexMap.has(nextChild.key)) {
5762 warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
5763 }
5764 keyToNewIndexMap.set(nextChild.key, i);
5765 }
5766 }
5767 // 5.2 loop through old children left to be patched and try to patch
5768 // matching nodes & remove nodes that are no longer present
5769 let j;
5770 let patched = 0;
5771 const toBePatched = e2 - s2 + 1;
5772 let moved = false;
5773 // used to track whether any node has moved
5774 let maxNewIndexSoFar = 0;
5775 // works as Map<newIndex, oldIndex>
5776 // Note that oldIndex is offset by +1
5777 // and oldIndex = 0 is a special value indicating the new node has
5778 // no corresponding old node.
5779 // used for determining longest stable subsequence
5780 const newIndexToOldIndexMap = new Array(toBePatched);
5781 for (i = 0; i < toBePatched; i++)
5782 newIndexToOldIndexMap[i] = 0;
5783 for (i = s1; i <= e1; i++) {
5784 const prevChild = c1[i];
5785 if (patched >= toBePatched) {
5786 // all new children have been patched so this can only be a removal
5787 unmount(prevChild, parentComponent, parentSuspense, true);
5788 continue;
5789 }
5790 let newIndex;
5791 if (prevChild.key != null) {
5792 newIndex = keyToNewIndexMap.get(prevChild.key);
5793 }
5794 else {
5795 // key-less node, try to locate a key-less node of the same type
5796 for (j = s2; j <= e2; j++) {
5797 if (newIndexToOldIndexMap[j - s2] === 0 &&
5798 isSameVNodeType(prevChild, c2[j])) {
5799 newIndex = j;
5800 break;
5801 }
5802 }
5803 }
5804 if (newIndex === undefined) {
5805 unmount(prevChild, parentComponent, parentSuspense, true);
5806 }
5807 else {
5808 newIndexToOldIndexMap[newIndex - s2] = i + 1;
5809 if (newIndex >= maxNewIndexSoFar) {
5810 maxNewIndexSoFar = newIndex;
5811 }
5812 else {
5813 moved = true;
5814 }
5815 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5816 patched++;
5817 }
5818 }
5819 // 5.3 move and mount
5820 // generate longest stable subsequence only when nodes have moved
5821 const increasingNewIndexSequence = moved
5822 ? getSequence(newIndexToOldIndexMap)
5823 : EMPTY_ARR;
5824 j = increasingNewIndexSequence.length - 1;
5825 // looping backwards so that we can use last patched node as anchor
5826 for (i = toBePatched - 1; i >= 0; i--) {
5827 const nextIndex = s2 + i;
5828 const nextChild = c2[nextIndex];
5829 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
5830 if (newIndexToOldIndexMap[i] === 0) {
5831 // mount new
5832 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5833 }
5834 else if (moved) {
5835 // move if:
5836 // There is no stable subsequence (e.g. a reverse)
5837 // OR current node is not among the stable sequence
5838 if (j < 0 || i !== increasingNewIndexSequence[j]) {
5839 move(nextChild, container, anchor, 2 /* REORDER */);
5840 }
5841 else {
5842 j--;
5843 }
5844 }
5845 }
5846 }
5847 };
5848 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
5849 const { el, type, transition, children, shapeFlag } = vnode;
5850 if (shapeFlag & 6 /* COMPONENT */) {
5851 move(vnode.component.subTree, container, anchor, moveType);
5852 return;
5853 }
5854 if (shapeFlag & 128 /* SUSPENSE */) {
5855 vnode.suspense.move(container, anchor, moveType);
5856 return;
5857 }
5858 if (shapeFlag & 64 /* TELEPORT */) {
5859 type.move(vnode, container, anchor, internals);
5860 return;
5861 }
5862 if (type === Fragment) {
5863 hostInsert(el, container, anchor);
5864 for (let i = 0; i < children.length; i++) {
5865 move(children[i], container, anchor, moveType);
5866 }
5867 hostInsert(vnode.anchor, container, anchor);
5868 return;
5869 }
5870 if (type === Static) {
5871 moveStaticNode(vnode, container, anchor);
5872 return;
5873 }
5874 // single nodes
5875 const needTransition = moveType !== 2 /* REORDER */ &&
5876 shapeFlag & 1 /* ELEMENT */ &&
5877 transition;
5878 if (needTransition) {
5879 if (moveType === 0 /* ENTER */) {
5880 transition.beforeEnter(el);
5881 hostInsert(el, container, anchor);
5882 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
5883 }
5884 else {
5885 const { leave, delayLeave, afterLeave } = transition;
5886 const remove = () => hostInsert(el, container, anchor);
5887 const performLeave = () => {
5888 leave(el, () => {
5889 remove();
5890 afterLeave && afterLeave();
5891 });
5892 };
5893 if (delayLeave) {
5894 delayLeave(el, remove, performLeave);
5895 }
5896 else {
5897 performLeave();
5898 }
5899 }
5900 }
5901 else {
5902 hostInsert(el, container, anchor);
5903 }
5904 };
5905 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
5906 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
5907 // unset ref
5908 if (ref != null) {
5909 setRef(ref, null, parentSuspense, null);
5910 }
5911 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5912 parentComponent.ctx.deactivate(vnode);
5913 return;
5914 }
5915 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
5916 let vnodeHook;
5917 if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
5918 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5919 }
5920 if (shapeFlag & 6 /* COMPONENT */) {
5921 unmountComponent(vnode.component, parentSuspense, doRemove);
5922 }
5923 else {
5924 if (shapeFlag & 128 /* SUSPENSE */) {
5925 vnode.suspense.unmount(parentSuspense, doRemove);
5926 return;
5927 }
5928 if (shouldInvokeDirs) {
5929 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
5930 }
5931 if (shapeFlag & 64 /* TELEPORT */) {
5932 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
5933 }
5934 else if (dynamicChildren &&
5935 // #1153: fast path should not be taken for non-stable (v-for) fragments
5936 (type !== Fragment ||
5937 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
5938 // fast path for block nodes: only need to unmount dynamic children.
5939 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
5940 }
5941 else if ((type === Fragment &&
5942 (patchFlag & 128 /* KEYED_FRAGMENT */ ||
5943 patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
5944 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
5945 unmountChildren(children, parentComponent, parentSuspense);
5946 }
5947 if (doRemove) {
5948 remove(vnode);
5949 }
5950 }
5951 if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
5952 queuePostRenderEffect(() => {
5953 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5954 shouldInvokeDirs &&
5955 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
5956 }, parentSuspense);
5957 }
5958 };
5959 const remove = vnode => {
5960 const { type, el, anchor, transition } = vnode;
5961 if (type === Fragment) {
5962 removeFragment(el, anchor);
5963 return;
5964 }
5965 if (type === Static) {
5966 removeStaticNode(vnode);
5967 return;
5968 }
5969 const performRemove = () => {
5970 hostRemove(el);
5971 if (transition && !transition.persisted && transition.afterLeave) {
5972 transition.afterLeave();
5973 }
5974 };
5975 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
5976 transition &&
5977 !transition.persisted) {
5978 const { leave, delayLeave } = transition;
5979 const performLeave = () => leave(el, performRemove);
5980 if (delayLeave) {
5981 delayLeave(vnode.el, performRemove, performLeave);
5982 }
5983 else {
5984 performLeave();
5985 }
5986 }
5987 else {
5988 performRemove();
5989 }
5990 };
5991 const removeFragment = (cur, end) => {
5992 // For fragments, directly remove all contained DOM nodes.
5993 // (fragment child nodes cannot have transition)
5994 let next;
5995 while (cur !== end) {
5996 next = hostNextSibling(cur);
5997 hostRemove(cur);
5998 cur = next;
5999 }
6000 hostRemove(end);
6001 };
6002 const unmountComponent = (instance, parentSuspense, doRemove) => {
6003 if (instance.type.__hmrId) {
6004 unregisterHMR(instance);
6005 }
6006 const { bum, effects, update, subTree, um } = instance;
6007 // beforeUnmount hook
6008 if (bum) {
6009 invokeArrayFns(bum);
6010 }
6011 if (effects) {
6012 for (let i = 0; i < effects.length; i++) {
6013 stop(effects[i]);
6014 }
6015 }
6016 // update may be null if a component is unmounted before its async
6017 // setup has resolved.
6018 if (update) {
6019 stop(update);
6020 unmount(subTree, instance, parentSuspense, doRemove);
6021 }
6022 // unmounted hook
6023 if (um) {
6024 queuePostRenderEffect(um, parentSuspense);
6025 }
6026 queuePostRenderEffect(() => {
6027 instance.isUnmounted = true;
6028 }, parentSuspense);
6029 // A component with async dep inside a pending suspense is unmounted before
6030 // its async dep resolves. This should remove the dep from the suspense, and
6031 // cause the suspense to resolve immediately if that was the last dep.
6032 if (parentSuspense &&
6033 parentSuspense.pendingBranch &&
6034 !parentSuspense.isUnmounted &&
6035 instance.asyncDep &&
6036 !instance.asyncResolved &&
6037 instance.suspenseId === parentSuspense.pendingId) {
6038 parentSuspense.deps--;
6039 if (parentSuspense.deps === 0) {
6040 parentSuspense.resolve();
6041 }
6042 }
6043 {
6044 devtoolsComponentRemoved(instance);
6045 }
6046 };
6047 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
6048 for (let i = start; i < children.length; i++) {
6049 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
6050 }
6051 };
6052 const getNextHostNode = vnode => {
6053 if (vnode.shapeFlag & 6 /* COMPONENT */) {
6054 return getNextHostNode(vnode.component.subTree);
6055 }
6056 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
6057 return vnode.suspense.next();
6058 }
6059 return hostNextSibling((vnode.anchor || vnode.el));
6060 };
6061 const render = (vnode, container, isSVG) => {
6062 if (vnode == null) {
6063 if (container._vnode) {
6064 unmount(container._vnode, null, null, true);
6065 }
6066 }
6067 else {
6068 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
6069 }
6070 flushPostFlushCbs();
6071 container._vnode = vnode;
6072 };
6073 const internals = {
6074 p: patch,
6075 um: unmount,
6076 m: move,
6077 r: remove,
6078 mt: mountComponent,
6079 mc: mountChildren,
6080 pc: patchChildren,
6081 pbc: patchBlockChildren,
6082 n: getNextHostNode,
6083 o: options
6084 };
6085 let hydrate;
6086 let hydrateNode;
6087 if (createHydrationFns) {
6088 [hydrate, hydrateNode] = createHydrationFns(internals);
6089 }
6090 return {
6091 render,
6092 hydrate,
6093 createApp: createAppAPI(render, hydrate)
6094 };
6095 }
6096 function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6097 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6098 vnode,
6099 prevVNode
6100 ]);
6101 }
6102 /**
6103 * #1156
6104 * When a component is HMR-enabled, we need to make sure that all static nodes
6105 * inside a block also inherit the DOM element from the previous tree so that
6106 * HMR updates (which are full updates) can retrieve the element for patching.
6107 *
6108 * #2080
6109 * Inside keyed `template` fragment static children, if a fragment is moved,
6110 * the children will always moved so that need inherit el form previous nodes
6111 * to ensure correct moved position.
6112 */
6113 function traverseStaticChildren(n1, n2, shallow = false) {
6114 const ch1 = n1.children;
6115 const ch2 = n2.children;
6116 if (isArray(ch1) && isArray(ch2)) {
6117 for (let i = 0; i < ch1.length; i++) {
6118 // this is only called in the optimized path so array children are
6119 // guaranteed to be vnodes
6120 const c1 = ch1[i];
6121 let c2 = ch2[i];
6122 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
6123 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
6124 c2 = ch2[i] = cloneIfMounted(ch2[i]);
6125 c2.el = c1.el;
6126 }
6127 if (!shallow)
6128 traverseStaticChildren(c1, c2);
6129 }
6130 // also inherit for comment nodes, but not placeholders (e.g. v-if which
6131 // would have received .el during block patch)
6132 if (c2.type === Comment && !c2.el) {
6133 c2.el = c1.el;
6134 }
6135 }
6136 }
6137 }
6138 // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
6139 function getSequence(arr) {
6140 const p = arr.slice();
6141 const result = [0];
6142 let i, j, u, v, c;
6143 const len = arr.length;
6144 for (i = 0; i < len; i++) {
6145 const arrI = arr[i];
6146 if (arrI !== 0) {
6147 j = result[result.length - 1];
6148 if (arr[j] < arrI) {
6149 p[i] = j;
6150 result.push(i);
6151 continue;
6152 }
6153 u = 0;
6154 v = result.length - 1;
6155 while (u < v) {
6156 c = ((u + v) / 2) | 0;
6157 if (arr[result[c]] < arrI) {
6158 u = c + 1;
6159 }
6160 else {
6161 v = c;
6162 }
6163 }
6164 if (arrI < arr[result[u]]) {
6165 if (u > 0) {
6166 p[i] = result[u - 1];
6167 }
6168 result[u] = i;
6169 }
6170 }
6171 }
6172 u = result.length;
6173 v = result[u - 1];
6174 while (u-- > 0) {
6175 result[u] = v;
6176 v = p[v];
6177 }
6178 return result;
6179 }
6180
6181 const isTeleport = (type) => type.__isTeleport;
6182 const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
6183 const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
6184 const resolveTarget = (props, select) => {
6185 const targetSelector = props && props.to;
6186 if (isString(targetSelector)) {
6187 if (!select) {
6188 warn(`Current renderer does not support string target for Teleports. ` +
6189 `(missing querySelector renderer option)`);
6190 return null;
6191 }
6192 else {
6193 const target = select(targetSelector);
6194 if (!target) {
6195 warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
6196 `Note the target element must exist before the component is mounted - ` +
6197 `i.e. the target cannot be rendered by the component itself, and ` +
6198 `ideally should be outside of the entire Vue component tree.`);
6199 }
6200 return target;
6201 }
6202 }
6203 else {
6204 if (!targetSelector && !isTeleportDisabled(props)) {
6205 warn(`Invalid Teleport target: ${targetSelector}`);
6206 }
6207 return targetSelector;
6208 }
6209 };
6210 const TeleportImpl = {
6211 __isTeleport: true,
6212 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
6213 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
6214 const disabled = isTeleportDisabled(n2.props);
6215 const { shapeFlag, children } = n2;
6216 // #3302
6217 // HMR updated, force full diff
6218 if (isHmrUpdating) {
6219 optimized = false;
6220 n2.dynamicChildren = null;
6221 }
6222 if (n1 == null) {
6223 // insert anchors in the main view
6224 const placeholder = (n2.el = createComment('teleport start')
6225 );
6226 const mainAnchor = (n2.anchor = createComment('teleport end')
6227 );
6228 insert(placeholder, container, anchor);
6229 insert(mainAnchor, container, anchor);
6230 const target = (n2.target = resolveTarget(n2.props, querySelector));
6231 const targetAnchor = (n2.targetAnchor = createText(''));
6232 if (target) {
6233 insert(targetAnchor, target);
6234 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
6235 isSVG = isSVG || isTargetSVG(target);
6236 }
6237 else if (!disabled) {
6238 warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
6239 }
6240 const mount = (container, anchor) => {
6241 // Teleport *always* has Array children. This is enforced in both the
6242 // compiler and vnode children normalization.
6243 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6244 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6245 }
6246 };
6247 if (disabled) {
6248 mount(container, mainAnchor);
6249 }
6250 else if (target) {
6251 mount(target, targetAnchor);
6252 }
6253 }
6254 else {
6255 // update content
6256 n2.el = n1.el;
6257 const mainAnchor = (n2.anchor = n1.anchor);
6258 const target = (n2.target = n1.target);
6259 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
6260 const wasDisabled = isTeleportDisabled(n1.props);
6261 const currentContainer = wasDisabled ? container : target;
6262 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
6263 isSVG = isSVG || isTargetSVG(target);
6264 if (n2.dynamicChildren) {
6265 // fast path when the teleport happens to be a block root
6266 patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
6267 // even in block tree mode we need to make sure all root-level nodes
6268 // in the teleport inherit previous DOM references so that they can
6269 // be moved in future patches.
6270 traverseStaticChildren(n1, n2, true);
6271 }
6272 else if (!optimized) {
6273 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
6274 }
6275 if (disabled) {
6276 if (!wasDisabled) {
6277 // enabled -> disabled
6278 // move into main container
6279 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
6280 }
6281 }
6282 else {
6283 // target changed
6284 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
6285 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
6286 if (nextTarget) {
6287 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
6288 }
6289 else {
6290 warn('Invalid Teleport target on update:', target, `(${typeof target})`);
6291 }
6292 }
6293 else if (wasDisabled) {
6294 // disabled -> enabled
6295 // move into teleport target
6296 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
6297 }
6298 }
6299 }
6300 },
6301 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
6302 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
6303 if (target) {
6304 hostRemove(targetAnchor);
6305 }
6306 // an unmounted teleport should always remove its children if not disabled
6307 if (doRemove || !isTeleportDisabled(props)) {
6308 hostRemove(anchor);
6309 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6310 for (let i = 0; i < children.length; i++) {
6311 unmount(children[i], parentComponent, parentSuspense, true, optimized);
6312 }
6313 }
6314 }
6315 },
6316 move: moveTeleport,
6317 hydrate: hydrateTeleport
6318 };
6319 function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
6320 // move target anchor if this is a target change.
6321 if (moveType === 0 /* TARGET_CHANGE */) {
6322 insert(vnode.targetAnchor, container, parentAnchor);
6323 }
6324 const { el, anchor, shapeFlag, children, props } = vnode;
6325 const isReorder = moveType === 2 /* REORDER */;
6326 // move main view anchor if this is a re-order.
6327 if (isReorder) {
6328 insert(el, container, parentAnchor);
6329 }
6330 // if this is a re-order and teleport is enabled (content is in target)
6331 // do not move children. So the opposite is: only move children if this
6332 // is not a reorder, or the teleport is disabled
6333 if (!isReorder || isTeleportDisabled(props)) {
6334 // Teleport has either Array children or no children.
6335 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6336 for (let i = 0; i < children.length; i++) {
6337 move(children[i], container, parentAnchor, 2 /* REORDER */);
6338 }
6339 }
6340 }
6341 // move main view anchor if this is a re-order.
6342 if (isReorder) {
6343 insert(anchor, container, parentAnchor);
6344 }
6345 }
6346 function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
6347 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
6348 if (target) {
6349 // if multiple teleports rendered to the same target element, we need to
6350 // pick up from where the last teleport finished instead of the first node
6351 const targetNode = target._lpa || target.firstChild;
6352 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
6353 if (isTeleportDisabled(vnode.props)) {
6354 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
6355 vnode.targetAnchor = targetNode;
6356 }
6357 else {
6358 vnode.anchor = nextSibling(node);
6359 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
6360 }
6361 target._lpa =
6362 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
6363 }
6364 }
6365 return vnode.anchor && nextSibling(vnode.anchor);
6366 }
6367 // Force-casted public typing for h and TSX props inference
6368 const Teleport = TeleportImpl;
6369
6370 const COMPONENTS = 'components';
6371 const DIRECTIVES = 'directives';
6372 /**
6373 * @private
6374 */
6375 function resolveComponent(name, maybeSelfReference) {
6376 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
6377 }
6378 const NULL_DYNAMIC_COMPONENT = Symbol();
6379 /**
6380 * @private
6381 */
6382 function resolveDynamicComponent(component) {
6383 if (isString(component)) {
6384 return resolveAsset(COMPONENTS, component, false) || component;
6385 }
6386 else {
6387 // invalid types will fallthrough to createVNode and raise warning
6388 return (component || NULL_DYNAMIC_COMPONENT);
6389 }
6390 }
6391 /**
6392 * @private
6393 */
6394 function resolveDirective(name) {
6395 return resolveAsset(DIRECTIVES, name);
6396 }
6397 // implementation
6398 function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
6399 const instance = currentRenderingInstance || currentInstance;
6400 if (instance) {
6401 const Component = instance.type;
6402 // explicit self name has highest priority
6403 if (type === COMPONENTS) {
6404 const selfName = getComponentName(Component);
6405 if (selfName &&
6406 (selfName === name ||
6407 selfName === camelize(name) ||
6408 selfName === capitalize(camelize(name)))) {
6409 return Component;
6410 }
6411 }
6412 const res =
6413 // local registration
6414 // check instance[type] first for components with mixin or extends.
6415 resolve(instance[type] || Component[type], name) ||
6416 // global registration
6417 resolve(instance.appContext[type], name);
6418 if (!res && maybeSelfReference) {
6419 // fallback to implicit self-reference
6420 return Component;
6421 }
6422 if (warnMissing && !res) {
6423 warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
6424 }
6425 return res;
6426 }
6427 else {
6428 warn(`resolve${capitalize(type.slice(0, -1))} ` +
6429 `can only be used in render() or setup().`);
6430 }
6431 }
6432 function resolve(registry, name) {
6433 return (registry &&
6434 (registry[name] ||
6435 registry[camelize(name)] ||
6436 registry[capitalize(camelize(name))]));
6437 }
6438
6439 const Fragment = Symbol('Fragment' );
6440 const Text = Symbol('Text' );
6441 const Comment = Symbol('Comment' );
6442 const Static = Symbol('Static' );
6443 // Since v-if and v-for are the two possible ways node structure can dynamically
6444 // change, once we consider v-if branches and each v-for fragment a block, we
6445 // can divide a template into nested blocks, and within each block the node
6446 // structure would be stable. This allows us to skip most children diffing
6447 // and only worry about the dynamic nodes (indicated by patch flags).
6448 const blockStack = [];
6449 let currentBlock = null;
6450 /**
6451 * Open a block.
6452 * This must be called before `createBlock`. It cannot be part of `createBlock`
6453 * because the children of the block are evaluated before `createBlock` itself
6454 * is called. The generated code typically looks like this:
6455 *
6456 * ```js
6457 * function render() {
6458 * return (openBlock(),createBlock('div', null, [...]))
6459 * }
6460 * ```
6461 * disableTracking is true when creating a v-for fragment block, since a v-for
6462 * fragment always diffs its children.
6463 *
6464 * @private
6465 */
6466 function openBlock(disableTracking = false) {
6467 blockStack.push((currentBlock = disableTracking ? null : []));
6468 }
6469 function closeBlock() {
6470 blockStack.pop();
6471 currentBlock = blockStack[blockStack.length - 1] || null;
6472 }
6473 // Whether we should be tracking dynamic child nodes inside a block.
6474 // Only tracks when this value is > 0
6475 // We are not using a simple boolean because this value may need to be
6476 // incremented/decremented by nested usage of v-once (see below)
6477 let shouldTrack$1 = 1;
6478 /**
6479 * Block tracking sometimes needs to be disabled, for example during the
6480 * creation of a tree that needs to be cached by v-once. The compiler generates
6481 * code like this:
6482 *
6483 * ``` js
6484 * _cache[1] || (
6485 * setBlockTracking(-1),
6486 * _cache[1] = createVNode(...),
6487 * setBlockTracking(1),
6488 * _cache[1]
6489 * )
6490 * ```
6491 *
6492 * @private
6493 */
6494 function setBlockTracking(value) {
6495 shouldTrack$1 += value;
6496 }
6497 /**
6498 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
6499 * A block root keeps track of dynamic nodes within the block in the
6500 * `dynamicChildren` array.
6501 *
6502 * @private
6503 */
6504 function createBlock(type, props, children, patchFlag, dynamicProps) {
6505 const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
6506 // save current block children on the block vnode
6507 vnode.dynamicChildren = currentBlock || EMPTY_ARR;
6508 // close block
6509 closeBlock();
6510 // a block is always going to be patched, so track it as a child of its
6511 // parent block
6512 if (shouldTrack$1 > 0 && currentBlock) {
6513 currentBlock.push(vnode);
6514 }
6515 return vnode;
6516 }
6517 function isVNode(value) {
6518 return value ? value.__v_isVNode === true : false;
6519 }
6520 function isSameVNodeType(n1, n2) {
6521 if (n2.shapeFlag & 6 /* COMPONENT */ &&
6522 hmrDirtyComponents.has(n2.type)) {
6523 // HMR only: if the component has been hot-updated, force a reload.
6524 return false;
6525 }
6526 return n1.type === n2.type && n1.key === n2.key;
6527 }
6528 let vnodeArgsTransformer;
6529 /**
6530 * Internal API for registering an arguments transform for createVNode
6531 * used for creating stubs in the test-utils
6532 * It is *internal* but needs to be exposed for test-utils to pick up proper
6533 * typings
6534 */
6535 function transformVNodeArgs(transformer) {
6536 vnodeArgsTransformer = transformer;
6537 }
6538 const createVNodeWithArgsTransform = (...args) => {
6539 return _createVNode(...(vnodeArgsTransformer
6540 ? vnodeArgsTransformer(args, currentRenderingInstance)
6541 : args));
6542 };
6543 const InternalObjectKey = `__vInternal`;
6544 const normalizeKey = ({ key }) => key != null ? key : null;
6545 const normalizeRef = ({ ref }) => {
6546 return (ref != null
6547 ? isString(ref) || isRef(ref) || isFunction(ref)
6548 ? { i: currentRenderingInstance, r: ref }
6549 : ref
6550 : null);
6551 };
6552 const createVNode = (createVNodeWithArgsTransform
6553 );
6554 function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
6555 if (!type || type === NULL_DYNAMIC_COMPONENT) {
6556 if (!type) {
6557 warn(`Invalid vnode type when creating vnode: ${type}.`);
6558 }
6559 type = Comment;
6560 }
6561 if (isVNode(type)) {
6562 // createVNode receiving an existing vnode. This happens in cases like
6563 // <component :is="vnode"/>
6564 // #2078 make sure to merge refs during the clone instead of overwriting it
6565 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
6566 if (children) {
6567 normalizeChildren(cloned, children);
6568 }
6569 return cloned;
6570 }
6571 // class component normalization.
6572 if (isClassComponent(type)) {
6573 type = type.__vccOpts;
6574 }
6575 // class & style normalization.
6576 if (props) {
6577 // for reactive or proxy objects, we need to clone it to enable mutation.
6578 if (isProxy(props) || InternalObjectKey in props) {
6579 props = extend({}, props);
6580 }
6581 let { class: klass, style } = props;
6582 if (klass && !isString(klass)) {
6583 props.class = normalizeClass(klass);
6584 }
6585 if (isObject(style)) {
6586 // reactive state objects need to be cloned since they are likely to be
6587 // mutated
6588 if (isProxy(style) && !isArray(style)) {
6589 style = extend({}, style);
6590 }
6591 props.style = normalizeStyle(style);
6592 }
6593 }
6594 // encode the vnode type information into a bitmap
6595 const shapeFlag = isString(type)
6596 ? 1 /* ELEMENT */
6597 : isSuspense(type)
6598 ? 128 /* SUSPENSE */
6599 : isTeleport(type)
6600 ? 64 /* TELEPORT */
6601 : isObject(type)
6602 ? 4 /* STATEFUL_COMPONENT */
6603 : isFunction(type)
6604 ? 2 /* FUNCTIONAL_COMPONENT */
6605 : 0;
6606 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
6607 type = toRaw(type);
6608 warn(`Vue received a Component which was made a reactive object. This can ` +
6609 `lead to unnecessary performance overhead, and should be avoided by ` +
6610 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
6611 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
6612 }
6613 const vnode = {
6614 __v_isVNode: true,
6615 ["__v_skip" /* SKIP */]: true,
6616 type,
6617 props,
6618 key: props && normalizeKey(props),
6619 ref: props && normalizeRef(props),
6620 scopeId: currentScopeId,
6621 slotScopeIds: null,
6622 children: null,
6623 component: null,
6624 suspense: null,
6625 ssContent: null,
6626 ssFallback: null,
6627 dirs: null,
6628 transition: null,
6629 el: null,
6630 anchor: null,
6631 target: null,
6632 targetAnchor: null,
6633 staticCount: 0,
6634 shapeFlag,
6635 patchFlag,
6636 dynamicProps,
6637 dynamicChildren: null,
6638 appContext: null
6639 };
6640 // validate key
6641 if (vnode.key !== vnode.key) {
6642 warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
6643 }
6644 normalizeChildren(vnode, children);
6645 // normalize suspense children
6646 if (shapeFlag & 128 /* SUSPENSE */) {
6647 const { content, fallback } = normalizeSuspenseChildren(vnode);
6648 vnode.ssContent = content;
6649 vnode.ssFallback = fallback;
6650 }
6651 if (shouldTrack$1 > 0 &&
6652 // avoid a block node from tracking itself
6653 !isBlockNode &&
6654 // has current parent block
6655 currentBlock &&
6656 // presence of a patch flag indicates this node needs patching on updates.
6657 // component nodes also should always be patched, because even if the
6658 // component doesn't need to update, it needs to persist the instance on to
6659 // the next vnode so that it can be properly unmounted later.
6660 (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
6661 // the EVENTS flag is only for hydration and if it is the only flag, the
6662 // vnode should not be considered dynamic due to handler caching.
6663 patchFlag !== 32 /* HYDRATE_EVENTS */) {
6664 currentBlock.push(vnode);
6665 }
6666 return vnode;
6667 }
6668 function cloneVNode(vnode, extraProps, mergeRef = false) {
6669 // This is intentionally NOT using spread or extend to avoid the runtime
6670 // key enumeration cost.
6671 const { props, ref, patchFlag, children } = vnode;
6672 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
6673 return {
6674 __v_isVNode: true,
6675 ["__v_skip" /* SKIP */]: true,
6676 type: vnode.type,
6677 props: mergedProps,
6678 key: mergedProps && normalizeKey(mergedProps),
6679 ref: extraProps && extraProps.ref
6680 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
6681 // if the vnode itself already has a ref, cloneVNode will need to merge
6682 // the refs so the single vnode can be set on multiple refs
6683 mergeRef && ref
6684 ? isArray(ref)
6685 ? ref.concat(normalizeRef(extraProps))
6686 : [ref, normalizeRef(extraProps)]
6687 : normalizeRef(extraProps)
6688 : ref,
6689 scopeId: vnode.scopeId,
6690 slotScopeIds: vnode.slotScopeIds,
6691 children: patchFlag === -1 /* HOISTED */ && isArray(children)
6692 ? children.map(deepCloneVNode)
6693 : children,
6694 target: vnode.target,
6695 targetAnchor: vnode.targetAnchor,
6696 staticCount: vnode.staticCount,
6697 shapeFlag: vnode.shapeFlag,
6698 // if the vnode is cloned with extra props, we can no longer assume its
6699 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
6700 // note: perserve flag for fragments since they use the flag for children
6701 // fast paths only.
6702 patchFlag: extraProps && vnode.type !== Fragment
6703 ? patchFlag === -1 // hoisted node
6704 ? 16 /* FULL_PROPS */
6705 : patchFlag | 16 /* FULL_PROPS */
6706 : patchFlag,
6707 dynamicProps: vnode.dynamicProps,
6708 dynamicChildren: vnode.dynamicChildren,
6709 appContext: vnode.appContext,
6710 dirs: vnode.dirs,
6711 transition: vnode.transition,
6712 // These should technically only be non-null on mounted VNodes. However,
6713 // they *should* be copied for kept-alive vnodes. So we just always copy
6714 // them since them being non-null during a mount doesn't affect the logic as
6715 // they will simply be overwritten.
6716 component: vnode.component,
6717 suspense: vnode.suspense,
6718 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
6719 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
6720 el: vnode.el,
6721 anchor: vnode.anchor
6722 };
6723 }
6724 /**
6725 * Dev only, for HMR of hoisted vnodes reused in v-for
6726 * https://github.com/vitejs/vite/issues/2022
6727 */
6728 function deepCloneVNode(vnode) {
6729 const cloned = cloneVNode(vnode);
6730 if (isArray(vnode.children)) {
6731 cloned.children = vnode.children.map(deepCloneVNode);
6732 }
6733 return cloned;
6734 }
6735 /**
6736 * @private
6737 */
6738 function createTextVNode(text = ' ', flag = 0) {
6739 return createVNode(Text, null, text, flag);
6740 }
6741 /**
6742 * @private
6743 */
6744 function createStaticVNode(content, numberOfNodes) {
6745 // A static vnode can contain multiple stringified elements, and the number
6746 // of elements is necessary for hydration.
6747 const vnode = createVNode(Static, null, content);
6748 vnode.staticCount = numberOfNodes;
6749 return vnode;
6750 }
6751 /**
6752 * @private
6753 */
6754 function createCommentVNode(text = '',
6755 // when used as the v-else branch, the comment node must be created as a
6756 // block to ensure correct updates.
6757 asBlock = false) {
6758 return asBlock
6759 ? (openBlock(), createBlock(Comment, null, text))
6760 : createVNode(Comment, null, text);
6761 }
6762 function normalizeVNode(child) {
6763 if (child == null || typeof child === 'boolean') {
6764 // empty placeholder
6765 return createVNode(Comment);
6766 }
6767 else if (isArray(child)) {
6768 // fragment
6769 return createVNode(Fragment, null, child);
6770 }
6771 else if (typeof child === 'object') {
6772 // already vnode, this should be the most common since compiled templates
6773 // always produce all-vnode children arrays
6774 return child.el === null ? child : cloneVNode(child);
6775 }
6776 else {
6777 // strings and numbers
6778 return createVNode(Text, null, String(child));
6779 }
6780 }
6781 // optimized normalization for template-compiled render fns
6782 function cloneIfMounted(child) {
6783 return child.el === null ? child : cloneVNode(child);
6784 }
6785 function normalizeChildren(vnode, children) {
6786 let type = 0;
6787 const { shapeFlag } = vnode;
6788 if (children == null) {
6789 children = null;
6790 }
6791 else if (isArray(children)) {
6792 type = 16 /* ARRAY_CHILDREN */;
6793 }
6794 else if (typeof children === 'object') {
6795 if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
6796 // Normalize slot to plain children for plain element and Teleport
6797 const slot = children.default;
6798 if (slot) {
6799 // _c marker is added by withCtx() indicating this is a compiled slot
6800 slot._c && setCompiledSlotRendering(1);
6801 normalizeChildren(vnode, slot());
6802 slot._c && setCompiledSlotRendering(-1);
6803 }
6804 return;
6805 }
6806 else {
6807 type = 32 /* SLOTS_CHILDREN */;
6808 const slotFlag = children._;
6809 if (!slotFlag && !(InternalObjectKey in children)) {
6810 children._ctx = currentRenderingInstance;
6811 }
6812 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
6813 // a child component receives forwarded slots from the parent.
6814 // its slot type is determined by its parent's slot type.
6815 if (currentRenderingInstance.vnode.patchFlag & 1024 /* DYNAMIC_SLOTS */) {
6816 children._ = 2 /* DYNAMIC */;
6817 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
6818 }
6819 else {
6820 children._ = 1 /* STABLE */;
6821 }
6822 }
6823 }
6824 }
6825 else if (isFunction(children)) {
6826 children = { default: children, _ctx: currentRenderingInstance };
6827 type = 32 /* SLOTS_CHILDREN */;
6828 }
6829 else {
6830 children = String(children);
6831 // force teleport children to array so it can be moved around
6832 if (shapeFlag & 64 /* TELEPORT */) {
6833 type = 16 /* ARRAY_CHILDREN */;
6834 children = [createTextVNode(children)];
6835 }
6836 else {
6837 type = 8 /* TEXT_CHILDREN */;
6838 }
6839 }
6840 vnode.children = children;
6841 vnode.shapeFlag |= type;
6842 }
6843 function mergeProps(...args) {
6844 const ret = extend({}, args[0]);
6845 for (let i = 1; i < args.length; i++) {
6846 const toMerge = args[i];
6847 for (const key in toMerge) {
6848 if (key === 'class') {
6849 if (ret.class !== toMerge.class) {
6850 ret.class = normalizeClass([ret.class, toMerge.class]);
6851 }
6852 }
6853 else if (key === 'style') {
6854 ret.style = normalizeStyle([ret.style, toMerge.style]);
6855 }
6856 else if (isOn(key)) {
6857 const existing = ret[key];
6858 const incoming = toMerge[key];
6859 if (existing !== incoming) {
6860 ret[key] = existing
6861 ? [].concat(existing, toMerge[key])
6862 : incoming;
6863 }
6864 }
6865 else if (key !== '') {
6866 ret[key] = toMerge[key];
6867 }
6868 }
6869 }
6870 return ret;
6871 }
6872
6873 function provide(key, value) {
6874 if (!currentInstance) {
6875 {
6876 warn(`provide() can only be used inside setup().`);
6877 }
6878 }
6879 else {
6880 let provides = currentInstance.provides;
6881 // by default an instance inherits its parent's provides object
6882 // but when it needs to provide values of its own, it creates its
6883 // own provides object using parent provides object as prototype.
6884 // this way in `inject` we can simply look up injections from direct
6885 // parent and let the prototype chain do the work.
6886 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
6887 if (parentProvides === provides) {
6888 provides = currentInstance.provides = Object.create(parentProvides);
6889 }
6890 // TS doesn't allow symbol as index type
6891 provides[key] = value;
6892 }
6893 }
6894 function inject(key, defaultValue, treatDefaultAsFactory = false) {
6895 // fallback to `currentRenderingInstance` so that this can be called in
6896 // a functional component
6897 const instance = currentInstance || currentRenderingInstance;
6898 if (instance) {
6899 // #2400
6900 // to support `app.use` plugins,
6901 // fallback to appContext's `provides` if the intance is at root
6902 const provides = instance.parent == null
6903 ? instance.vnode.appContext && instance.vnode.appContext.provides
6904 : instance.parent.provides;
6905 if (provides && key in provides) {
6906 // TS doesn't allow symbol as index type
6907 return provides[key];
6908 }
6909 else if (arguments.length > 1) {
6910 return treatDefaultAsFactory && isFunction(defaultValue)
6911 ? defaultValue()
6912 : defaultValue;
6913 }
6914 else {
6915 warn(`injection "${String(key)}" not found.`);
6916 }
6917 }
6918 else {
6919 warn(`inject() can only be used inside setup() or functional components.`);
6920 }
6921 }
6922
6923 function createDuplicateChecker() {
6924 const cache = Object.create(null);
6925 return (type, key) => {
6926 if (cache[key]) {
6927 warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
6928 }
6929 else {
6930 cache[key] = type;
6931 }
6932 };
6933 }
6934 let shouldCacheAccess = true;
6935 function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) {
6936 const {
6937 // composition
6938 mixins, extends: extendsOptions,
6939 // state
6940 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
6941 // assets
6942 components, directives,
6943 // lifecycle
6944 beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured,
6945 // public API
6946 expose } = options;
6947 const publicThis = instance.proxy;
6948 const ctx = instance.ctx;
6949 const globalMixins = instance.appContext.mixins;
6950 if (asMixin && render && instance.render === NOOP) {
6951 instance.render = render;
6952 }
6953 // applyOptions is called non-as-mixin once per instance
6954 if (!asMixin) {
6955 shouldCacheAccess = false;
6956 callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins);
6957 shouldCacheAccess = true;
6958 // global mixins are applied first
6959 applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide);
6960 }
6961 // extending a base component...
6962 if (extendsOptions) {
6963 applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true);
6964 }
6965 // local mixins
6966 if (mixins) {
6967 applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide);
6968 }
6969 const checkDuplicateProperties = createDuplicateChecker() ;
6970 {
6971 const [propsOptions] = instance.propsOptions;
6972 if (propsOptions) {
6973 for (const key in propsOptions) {
6974 checkDuplicateProperties("Props" /* PROPS */, key);
6975 }
6976 }
6977 }
6978 // options initialization order (to be consistent with Vue 2):
6979 // - props (already done outside of this function)
6980 // - inject
6981 // - methods
6982 // - data (deferred since it relies on `this` access)
6983 // - computed
6984 // - watch (deferred since it relies on `this` access)
6985 if (injectOptions) {
6986 if (isArray(injectOptions)) {
6987 for (let i = 0; i < injectOptions.length; i++) {
6988 const key = injectOptions[i];
6989 ctx[key] = inject(key);
6990 {
6991 checkDuplicateProperties("Inject" /* INJECT */, key);
6992 }
6993 }
6994 }
6995 else {
6996 for (const key in injectOptions) {
6997 const opt = injectOptions[key];
6998 if (isObject(opt)) {
6999 ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
7000 }
7001 else {
7002 ctx[key] = inject(opt);
7003 }
7004 {
7005 checkDuplicateProperties("Inject" /* INJECT */, key);
7006 }
7007 }
7008 }
7009 }
7010 if (methods) {
7011 for (const key in methods) {
7012 const methodHandler = methods[key];
7013 if (isFunction(methodHandler)) {
7014 // In dev mode, we use the `createRenderContext` function to define methods to the proxy target,
7015 // and those are read-only but reconfigurable, so it needs to be redefined here
7016 {
7017 Object.defineProperty(ctx, key, {
7018 value: methodHandler.bind(publicThis),
7019 configurable: true,
7020 enumerable: true,
7021 writable: true
7022 });
7023 }
7024 {
7025 checkDuplicateProperties("Methods" /* METHODS */, key);
7026 }
7027 }
7028 else {
7029 warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
7030 `Did you reference the function correctly?`);
7031 }
7032 }
7033 }
7034 if (!asMixin) {
7035 if (deferredData.length) {
7036 deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis));
7037 }
7038 if (dataOptions) {
7039 // @ts-ignore dataOptions is not fully type safe
7040 resolveData(instance, dataOptions, publicThis);
7041 }
7042 {
7043 const rawData = toRaw(instance.data);
7044 for (const key in rawData) {
7045 checkDuplicateProperties("Data" /* DATA */, key);
7046 // expose data on ctx during dev
7047 if (key[0] !== '$' && key[0] !== '_') {
7048 Object.defineProperty(ctx, key, {
7049 configurable: true,
7050 enumerable: true,
7051 get: () => rawData[key],
7052 set: NOOP
7053 });
7054 }
7055 }
7056 }
7057 }
7058 else if (dataOptions) {
7059 deferredData.push(dataOptions);
7060 }
7061 if (computedOptions) {
7062 for (const key in computedOptions) {
7063 const opt = computedOptions[key];
7064 const get = isFunction(opt)
7065 ? opt.bind(publicThis, publicThis)
7066 : isFunction(opt.get)
7067 ? opt.get.bind(publicThis, publicThis)
7068 : NOOP;
7069 if (get === NOOP) {
7070 warn(`Computed property "${key}" has no getter.`);
7071 }
7072 const set = !isFunction(opt) && isFunction(opt.set)
7073 ? opt.set.bind(publicThis)
7074 : () => {
7075 warn(`Write operation failed: computed property "${key}" is readonly.`);
7076 }
7077 ;
7078 const c = computed$1({
7079 get,
7080 set
7081 });
7082 Object.defineProperty(ctx, key, {
7083 enumerable: true,
7084 configurable: true,
7085 get: () => c.value,
7086 set: v => (c.value = v)
7087 });
7088 {
7089 checkDuplicateProperties("Computed" /* COMPUTED */, key);
7090 }
7091 }
7092 }
7093 if (watchOptions) {
7094 deferredWatch.push(watchOptions);
7095 }
7096 if (!asMixin && deferredWatch.length) {
7097 deferredWatch.forEach(watchOptions => {
7098 for (const key in watchOptions) {
7099 createWatcher(watchOptions[key], ctx, publicThis, key);
7100 }
7101 });
7102 }
7103 if (provideOptions) {
7104 deferredProvide.push(provideOptions);
7105 }
7106 if (!asMixin && deferredProvide.length) {
7107 deferredProvide.forEach(provideOptions => {
7108 const provides = isFunction(provideOptions)
7109 ? provideOptions.call(publicThis)
7110 : provideOptions;
7111 Reflect.ownKeys(provides).forEach(key => {
7112 provide(key, provides[key]);
7113 });
7114 });
7115 }
7116 // asset options.
7117 // To reduce memory usage, only components with mixins or extends will have
7118 // resolved asset registry attached to instance.
7119 if (asMixin) {
7120 if (components) {
7121 extend(instance.components ||
7122 (instance.components = extend({}, instance.type.components)), components);
7123 }
7124 if (directives) {
7125 extend(instance.directives ||
7126 (instance.directives = extend({}, instance.type.directives)), directives);
7127 }
7128 }
7129 // lifecycle options
7130 if (!asMixin) {
7131 callSyncHook('created', "c" /* CREATED */, options, instance, globalMixins);
7132 }
7133 if (beforeMount) {
7134 onBeforeMount(beforeMount.bind(publicThis));
7135 }
7136 if (mounted) {
7137 onMounted(mounted.bind(publicThis));
7138 }
7139 if (beforeUpdate) {
7140 onBeforeUpdate(beforeUpdate.bind(publicThis));
7141 }
7142 if (updated) {
7143 onUpdated(updated.bind(publicThis));
7144 }
7145 if (activated) {
7146 onActivated(activated.bind(publicThis));
7147 }
7148 if (deactivated) {
7149 onDeactivated(deactivated.bind(publicThis));
7150 }
7151 if (errorCaptured) {
7152 onErrorCaptured(errorCaptured.bind(publicThis));
7153 }
7154 if (renderTracked) {
7155 onRenderTracked(renderTracked.bind(publicThis));
7156 }
7157 if (renderTriggered) {
7158 onRenderTriggered(renderTriggered.bind(publicThis));
7159 }
7160 if (beforeDestroy) {
7161 warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`);
7162 }
7163 if (beforeUnmount) {
7164 onBeforeUnmount(beforeUnmount.bind(publicThis));
7165 }
7166 if (destroyed) {
7167 warn(`\`destroyed\` has been renamed to \`unmounted\`.`);
7168 }
7169 if (unmounted) {
7170 onUnmounted(unmounted.bind(publicThis));
7171 }
7172 if (isArray(expose)) {
7173 if (!asMixin) {
7174 if (expose.length) {
7175 const exposed = instance.exposed || (instance.exposed = proxyRefs({}));
7176 expose.forEach(key => {
7177 exposed[key] = toRef(publicThis, key);
7178 });
7179 }
7180 else if (!instance.exposed) {
7181 instance.exposed = EMPTY_OBJ;
7182 }
7183 }
7184 else {
7185 warn(`The \`expose\` option is ignored when used in mixins.`);
7186 }
7187 }
7188 }
7189 function callSyncHook(name, type, options, instance, globalMixins) {
7190 for (let i = 0; i < globalMixins.length; i++) {
7191 callHookWithMixinAndExtends(name, type, globalMixins[i], instance);
7192 }
7193 callHookWithMixinAndExtends(name, type, options, instance);
7194 }
7195 function callHookWithMixinAndExtends(name, type, options, instance) {
7196 const { extends: base, mixins } = options;
7197 const selfHook = options[name];
7198 if (base) {
7199 callHookWithMixinAndExtends(name, type, base, instance);
7200 }
7201 if (mixins) {
7202 for (let i = 0; i < mixins.length; i++) {
7203 callHookWithMixinAndExtends(name, type, mixins[i], instance);
7204 }
7205 }
7206 if (selfHook) {
7207 callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type);
7208 }
7209 }
7210 function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) {
7211 for (let i = 0; i < mixins.length; i++) {
7212 applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true);
7213 }
7214 }
7215 function resolveData(instance, dataFn, publicThis) {
7216 if (!isFunction(dataFn)) {
7217 warn(`The data option must be a function. ` +
7218 `Plain object usage is no longer supported.`);
7219 }
7220 shouldCacheAccess = false;
7221 const data = dataFn.call(publicThis, publicThis);
7222 shouldCacheAccess = true;
7223 if (isPromise(data)) {
7224 warn(`data() returned a Promise - note data() cannot be async; If you ` +
7225 `intend to perform data fetching before component renders, use ` +
7226 `async setup() + <Suspense>.`);
7227 }
7228 if (!isObject(data)) {
7229 warn(`data() should return an object.`);
7230 }
7231 else if (instance.data === EMPTY_OBJ) {
7232 instance.data = reactive(data);
7233 }
7234 else {
7235 // existing data: this is a mixin or extends.
7236 extend(instance.data, data);
7237 }
7238 }
7239 function createWatcher(raw, ctx, publicThis, key) {
7240 const getter = key.includes('.')
7241 ? createPathGetter(publicThis, key)
7242 : () => publicThis[key];
7243 if (isString(raw)) {
7244 const handler = ctx[raw];
7245 if (isFunction(handler)) {
7246 watch(getter, handler);
7247 }
7248 else {
7249 warn(`Invalid watch handler specified by key "${raw}"`, handler);
7250 }
7251 }
7252 else if (isFunction(raw)) {
7253 watch(getter, raw.bind(publicThis));
7254 }
7255 else if (isObject(raw)) {
7256 if (isArray(raw)) {
7257 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
7258 }
7259 else {
7260 const handler = isFunction(raw.handler)
7261 ? raw.handler.bind(publicThis)
7262 : ctx[raw.handler];
7263 if (isFunction(handler)) {
7264 watch(getter, handler, raw);
7265 }
7266 else {
7267 warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
7268 }
7269 }
7270 }
7271 else {
7272 warn(`Invalid watch option: "${key}"`, raw);
7273 }
7274 }
7275 function createPathGetter(ctx, path) {
7276 const segments = path.split('.');
7277 return () => {
7278 let cur = ctx;
7279 for (let i = 0; i < segments.length && cur; i++) {
7280 cur = cur[segments[i]];
7281 }
7282 return cur;
7283 };
7284 }
7285 function resolveMergedOptions(instance) {
7286 const raw = instance.type;
7287 const { __merged, mixins, extends: extendsOptions } = raw;
7288 if (__merged)
7289 return __merged;
7290 const globalMixins = instance.appContext.mixins;
7291 if (!globalMixins.length && !mixins && !extendsOptions)
7292 return raw;
7293 const options = {};
7294 globalMixins.forEach(m => mergeOptions(options, m, instance));
7295 mergeOptions(options, raw, instance);
7296 return (raw.__merged = options);
7297 }
7298 function mergeOptions(to, from, instance) {
7299 const strats = instance.appContext.config.optionMergeStrategies;
7300 const { mixins, extends: extendsOptions } = from;
7301 extendsOptions && mergeOptions(to, extendsOptions, instance);
7302 mixins &&
7303 mixins.forEach((m) => mergeOptions(to, m, instance));
7304 for (const key in from) {
7305 if (strats && hasOwn(strats, key)) {
7306 to[key] = strats[key](to[key], from[key], instance.proxy, key);
7307 }
7308 else {
7309 to[key] = from[key];
7310 }
7311 }
7312 }
7313
7314 /**
7315 * #2437 In Vue 3, functional components do not have a public instance proxy but
7316 * they exist in the internal parent chain. For code that relies on traversing
7317 * public $parent chains, skip functional ones and go to the parent instead.
7318 */
7319 const getPublicInstance = (i) => {
7320 if (!i)
7321 return null;
7322 if (isStatefulComponent(i))
7323 return i.exposed ? i.exposed : i.proxy;
7324 return getPublicInstance(i.parent);
7325 };
7326 const publicPropertiesMap = extend(Object.create(null), {
7327 $: i => i,
7328 $el: i => i.vnode.el,
7329 $data: i => i.data,
7330 $props: i => (shallowReadonly(i.props) ),
7331 $attrs: i => (shallowReadonly(i.attrs) ),
7332 $slots: i => (shallowReadonly(i.slots) ),
7333 $refs: i => (shallowReadonly(i.refs) ),
7334 $parent: i => getPublicInstance(i.parent),
7335 $root: i => getPublicInstance(i.root),
7336 $emit: i => i.emit,
7337 $options: i => (resolveMergedOptions(i) ),
7338 $forceUpdate: i => () => queueJob(i.update),
7339 $nextTick: i => nextTick.bind(i.proxy),
7340 $watch: i => (instanceWatch.bind(i) )
7341 });
7342 const PublicInstanceProxyHandlers = {
7343 get({ _: instance }, key) {
7344 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7345 // let @vue/reactivity know it should never observe Vue public instances.
7346 if (key === "__v_skip" /* SKIP */) {
7347 return true;
7348 }
7349 // for internal formatters to know that this is a Vue instance
7350 if (key === '__isVue') {
7351 return true;
7352 }
7353 // data / props / ctx
7354 // This getter gets called for every property access on the render context
7355 // during render and is a major hotspot. The most expensive part of this
7356 // is the multiple hasOwn() calls. It's much faster to do a simple property
7357 // access on a plain object, so we use an accessCache object (with null
7358 // prototype) to memoize what access type a key corresponds to.
7359 let normalizedProps;
7360 if (key[0] !== '$') {
7361 const n = accessCache[key];
7362 if (n !== undefined) {
7363 switch (n) {
7364 case 0 /* SETUP */:
7365 return setupState[key];
7366 case 1 /* DATA */:
7367 return data[key];
7368 case 3 /* CONTEXT */:
7369 return ctx[key];
7370 case 2 /* PROPS */:
7371 return props[key];
7372 // default: just fallthrough
7373 }
7374 }
7375 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7376 accessCache[key] = 0 /* SETUP */;
7377 return setupState[key];
7378 }
7379 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7380 accessCache[key] = 1 /* DATA */;
7381 return data[key];
7382 }
7383 else if (
7384 // only cache other properties when instance has declared (thus stable)
7385 // props
7386 (normalizedProps = instance.propsOptions[0]) &&
7387 hasOwn(normalizedProps, key)) {
7388 accessCache[key] = 2 /* PROPS */;
7389 return props[key];
7390 }
7391 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7392 accessCache[key] = 3 /* CONTEXT */;
7393 return ctx[key];
7394 }
7395 else if (shouldCacheAccess) {
7396 accessCache[key] = 4 /* OTHER */;
7397 }
7398 }
7399 const publicGetter = publicPropertiesMap[key];
7400 let cssModule, globalProperties;
7401 // public $xxx properties
7402 if (publicGetter) {
7403 if (key === '$attrs') {
7404 track(instance, "get" /* GET */, key);
7405 markAttrsAccessed();
7406 }
7407 return publicGetter(instance);
7408 }
7409 else if (
7410 // css module (injected by vue-loader)
7411 (cssModule = type.__cssModules) &&
7412 (cssModule = cssModule[key])) {
7413 return cssModule;
7414 }
7415 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7416 // user may set custom properties to `this` that start with `$`
7417 accessCache[key] = 3 /* CONTEXT */;
7418 return ctx[key];
7419 }
7420 else if (
7421 // global properties
7422 ((globalProperties = appContext.config.globalProperties),
7423 hasOwn(globalProperties, key))) {
7424 return globalProperties[key];
7425 }
7426 else if (currentRenderingInstance &&
7427 (!isString(key) ||
7428 // #1091 avoid internal isRef/isVNode checks on component instance leading
7429 // to infinite warning loop
7430 key.indexOf('__v') !== 0)) {
7431 if (data !== EMPTY_OBJ &&
7432 (key[0] === '$' || key[0] === '_') &&
7433 hasOwn(data, key)) {
7434 warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
7435 `character ("$" or "_") and is not proxied on the render context.`);
7436 }
7437 else if (instance === currentRenderingInstance) {
7438 warn(`Property ${JSON.stringify(key)} was accessed during render ` +
7439 `but is not defined on instance.`);
7440 }
7441 }
7442 },
7443 set({ _: instance }, key, value) {
7444 const { data, setupState, ctx } = instance;
7445 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7446 setupState[key] = value;
7447 }
7448 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7449 data[key] = value;
7450 }
7451 else if (hasOwn(instance.props, key)) {
7452 warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
7453 return false;
7454 }
7455 if (key[0] === '$' && key.slice(1) in instance) {
7456 warn(`Attempting to mutate public property "${key}". ` +
7457 `Properties starting with $ are reserved and readonly.`, instance);
7458 return false;
7459 }
7460 else {
7461 if (key in instance.appContext.config.globalProperties) {
7462 Object.defineProperty(ctx, key, {
7463 enumerable: true,
7464 configurable: true,
7465 value
7466 });
7467 }
7468 else {
7469 ctx[key] = value;
7470 }
7471 }
7472 return true;
7473 },
7474 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
7475 let normalizedProps;
7476 return (accessCache[key] !== undefined ||
7477 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
7478 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
7479 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
7480 hasOwn(ctx, key) ||
7481 hasOwn(publicPropertiesMap, key) ||
7482 hasOwn(appContext.config.globalProperties, key));
7483 }
7484 };
7485 {
7486 PublicInstanceProxyHandlers.ownKeys = (target) => {
7487 warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
7488 `The keys will be empty in production mode to avoid performance overhead.`);
7489 return Reflect.ownKeys(target);
7490 };
7491 }
7492 const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
7493 get(target, key) {
7494 // fast path for unscopables when using `with` block
7495 if (key === Symbol.unscopables) {
7496 return;
7497 }
7498 return PublicInstanceProxyHandlers.get(target, key, target);
7499 },
7500 has(_, key) {
7501 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
7502 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
7503 warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
7504 }
7505 return has;
7506 }
7507 });
7508 // In dev mode, the proxy target exposes the same properties as seen on `this`
7509 // for easier console inspection. In prod mode it will be an empty object so
7510 // these properties definitions can be skipped.
7511 function createRenderContext(instance) {
7512 const target = {};
7513 // expose internal instance for proxy handlers
7514 Object.defineProperty(target, `_`, {
7515 configurable: true,
7516 enumerable: false,
7517 get: () => instance
7518 });
7519 // expose public properties
7520 Object.keys(publicPropertiesMap).forEach(key => {
7521 Object.defineProperty(target, key, {
7522 configurable: true,
7523 enumerable: false,
7524 get: () => publicPropertiesMap[key](instance),
7525 // intercepted by the proxy so no need for implementation,
7526 // but needed to prevent set errors
7527 set: NOOP
7528 });
7529 });
7530 // expose global properties
7531 const { globalProperties } = instance.appContext.config;
7532 Object.keys(globalProperties).forEach(key => {
7533 Object.defineProperty(target, key, {
7534 configurable: true,
7535 enumerable: false,
7536 get: () => globalProperties[key],
7537 set: NOOP
7538 });
7539 });
7540 return target;
7541 }
7542 // dev only
7543 function exposePropsOnRenderContext(instance) {
7544 const { ctx, propsOptions: [propsOptions] } = instance;
7545 if (propsOptions) {
7546 Object.keys(propsOptions).forEach(key => {
7547 Object.defineProperty(ctx, key, {
7548 enumerable: true,
7549 configurable: true,
7550 get: () => instance.props[key],
7551 set: NOOP
7552 });
7553 });
7554 }
7555 }
7556 // dev only
7557 function exposeSetupStateOnRenderContext(instance) {
7558 const { ctx, setupState } = instance;
7559 Object.keys(toRaw(setupState)).forEach(key => {
7560 if (key[0] === '$' || key[0] === '_') {
7561 warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
7562 `which are reserved prefixes for Vue internals.`);
7563 return;
7564 }
7565 Object.defineProperty(ctx, key, {
7566 enumerable: true,
7567 configurable: true,
7568 get: () => setupState[key],
7569 set: NOOP
7570 });
7571 });
7572 }
7573
7574 const emptyAppContext = createAppContext();
7575 let uid$2 = 0;
7576 function createComponentInstance(vnode, parent, suspense) {
7577 const type = vnode.type;
7578 // inherit parent app context - or - if root, adopt from root vnode
7579 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
7580 const instance = {
7581 uid: uid$2++,
7582 vnode,
7583 type,
7584 parent,
7585 appContext,
7586 root: null,
7587 next: null,
7588 subTree: null,
7589 update: null,
7590 render: null,
7591 proxy: null,
7592 exposed: null,
7593 withProxy: null,
7594 effects: null,
7595 provides: parent ? parent.provides : Object.create(appContext.provides),
7596 accessCache: null,
7597 renderCache: [],
7598 // local resovled assets
7599 components: null,
7600 directives: null,
7601 // resolved props and emits options
7602 propsOptions: normalizePropsOptions(type, appContext),
7603 emitsOptions: normalizeEmitsOptions(type, appContext),
7604 // emit
7605 emit: null,
7606 emitted: null,
7607 // props default value
7608 propsDefaults: EMPTY_OBJ,
7609 // state
7610 ctx: EMPTY_OBJ,
7611 data: EMPTY_OBJ,
7612 props: EMPTY_OBJ,
7613 attrs: EMPTY_OBJ,
7614 slots: EMPTY_OBJ,
7615 refs: EMPTY_OBJ,
7616 setupState: EMPTY_OBJ,
7617 setupContext: null,
7618 // suspense related
7619 suspense,
7620 suspenseId: suspense ? suspense.pendingId : 0,
7621 asyncDep: null,
7622 asyncResolved: false,
7623 // lifecycle hooks
7624 // not using enums here because it results in computed properties
7625 isMounted: false,
7626 isUnmounted: false,
7627 isDeactivated: false,
7628 bc: null,
7629 c: null,
7630 bm: null,
7631 m: null,
7632 bu: null,
7633 u: null,
7634 um: null,
7635 bum: null,
7636 da: null,
7637 a: null,
7638 rtg: null,
7639 rtc: null,
7640 ec: null
7641 };
7642 {
7643 instance.ctx = createRenderContext(instance);
7644 }
7645 instance.root = parent ? parent.root : instance;
7646 instance.emit = emit.bind(null, instance);
7647 return instance;
7648 }
7649 let currentInstance = null;
7650 const getCurrentInstance = () => currentInstance || currentRenderingInstance;
7651 const setCurrentInstance = (instance) => {
7652 currentInstance = instance;
7653 };
7654 const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
7655 function validateComponentName(name, config) {
7656 const appIsNativeTag = config.isNativeTag || NO;
7657 if (isBuiltInTag(name) || appIsNativeTag(name)) {
7658 warn('Do not use built-in or reserved HTML elements as component id: ' + name);
7659 }
7660 }
7661 function isStatefulComponent(instance) {
7662 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
7663 }
7664 let isInSSRComponentSetup = false;
7665 function setupComponent(instance, isSSR = false) {
7666 isInSSRComponentSetup = isSSR;
7667 const { props, children } = instance.vnode;
7668 const isStateful = isStatefulComponent(instance);
7669 initProps(instance, props, isStateful, isSSR);
7670 initSlots(instance, children);
7671 const setupResult = isStateful
7672 ? setupStatefulComponent(instance, isSSR)
7673 : undefined;
7674 isInSSRComponentSetup = false;
7675 return setupResult;
7676 }
7677 function setupStatefulComponent(instance, isSSR) {
7678 const Component = instance.type;
7679 {
7680 if (Component.name) {
7681 validateComponentName(Component.name, instance.appContext.config);
7682 }
7683 if (Component.components) {
7684 const names = Object.keys(Component.components);
7685 for (let i = 0; i < names.length; i++) {
7686 validateComponentName(names[i], instance.appContext.config);
7687 }
7688 }
7689 if (Component.directives) {
7690 const names = Object.keys(Component.directives);
7691 for (let i = 0; i < names.length; i++) {
7692 validateDirectiveName(names[i]);
7693 }
7694 }
7695 }
7696 // 0. create render proxy property access cache
7697 instance.accessCache = Object.create(null);
7698 // 1. create public instance / render proxy
7699 // also mark it raw so it's never observed
7700 instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
7701 {
7702 exposePropsOnRenderContext(instance);
7703 }
7704 // 2. call setup()
7705 const { setup } = Component;
7706 if (setup) {
7707 const setupContext = (instance.setupContext =
7708 setup.length > 1 ? createSetupContext(instance) : null);
7709 currentInstance = instance;
7710 pauseTracking();
7711 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
7712 resetTracking();
7713 currentInstance = null;
7714 if (isPromise(setupResult)) {
7715 if (isSSR) {
7716 // return the promise so server-renderer can wait on it
7717 return setupResult
7718 .then((resolvedResult) => {
7719 handleSetupResult(instance, resolvedResult, isSSR);
7720 })
7721 .catch(e => {
7722 handleError(e, instance, 0 /* SETUP_FUNCTION */);
7723 });
7724 }
7725 else {
7726 // async setup returned Promise.
7727 // bail here and wait for re-entry.
7728 instance.asyncDep = setupResult;
7729 }
7730 }
7731 else {
7732 handleSetupResult(instance, setupResult, isSSR);
7733 }
7734 }
7735 else {
7736 finishComponentSetup(instance, isSSR);
7737 }
7738 }
7739 function handleSetupResult(instance, setupResult, isSSR) {
7740 if (isFunction(setupResult)) {
7741 // setup returned an inline render function
7742 {
7743 instance.render = setupResult;
7744 }
7745 }
7746 else if (isObject(setupResult)) {
7747 if (isVNode(setupResult)) {
7748 warn(`setup() should not return VNodes directly - ` +
7749 `return a render function instead.`);
7750 }
7751 // setup returned bindings.
7752 // assuming a render function compiled from template is present.
7753 {
7754 instance.devtoolsRawSetupState = setupResult;
7755 }
7756 instance.setupState = proxyRefs(setupResult);
7757 {
7758 exposeSetupStateOnRenderContext(instance);
7759 }
7760 }
7761 else if (setupResult !== undefined) {
7762 warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
7763 }
7764 finishComponentSetup(instance, isSSR);
7765 }
7766 let compile;
7767 // dev only
7768 const isRuntimeOnly = () => !compile;
7769 /**
7770 * For runtime-dom to register the compiler.
7771 * Note the exported method uses any to avoid d.ts relying on the compiler types.
7772 */
7773 function registerRuntimeCompiler(_compile) {
7774 compile = _compile;
7775 }
7776 function finishComponentSetup(instance, isSSR) {
7777 const Component = instance.type;
7778 // template / render function normalization
7779 if (!instance.render) {
7780 // could be set from setup()
7781 if (compile && Component.template && !Component.render) {
7782 {
7783 startMeasure(instance, `compile`);
7784 }
7785 Component.render = compile(Component.template, {
7786 isCustomElement: instance.appContext.config.isCustomElement,
7787 delimiters: Component.delimiters
7788 });
7789 {
7790 endMeasure(instance, `compile`);
7791 }
7792 }
7793 instance.render = (Component.render || NOOP);
7794 // for runtime-compiled render functions using `with` blocks, the render
7795 // proxy used needs a different `has` handler which is more performant and
7796 // also only allows a whitelist of globals to fallthrough.
7797 if (instance.render._rc) {
7798 instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
7799 }
7800 }
7801 // support for 2.x options
7802 {
7803 currentInstance = instance;
7804 pauseTracking();
7805 applyOptions(instance, Component);
7806 resetTracking();
7807 currentInstance = null;
7808 }
7809 // warn missing template/render
7810 // the runtime compilation of template in SSR is done by server-render
7811 if (!Component.render && instance.render === NOOP && !isSSR) {
7812 /* istanbul ignore if */
7813 if (!compile && Component.template) {
7814 warn(`Component provided template option but ` +
7815 `runtime compilation is not supported in this build of Vue.` +
7816 (` Use "vue.global.js" instead.`
7817 ) /* should not happen */);
7818 }
7819 else {
7820 warn(`Component is missing template or render function.`);
7821 }
7822 }
7823 }
7824 const attrHandlers = {
7825 get: (target, key) => {
7826 {
7827 markAttrsAccessed();
7828 }
7829 return target[key];
7830 },
7831 set: () => {
7832 warn(`setupContext.attrs is readonly.`);
7833 return false;
7834 },
7835 deleteProperty: () => {
7836 warn(`setupContext.attrs is readonly.`);
7837 return false;
7838 }
7839 };
7840 function createSetupContext(instance) {
7841 const expose = exposed => {
7842 if (instance.exposed) {
7843 warn(`expose() should be called only once per setup().`);
7844 }
7845 instance.exposed = proxyRefs(exposed);
7846 };
7847 {
7848 // We use getters in dev in case libs like test-utils overwrite instance
7849 // properties (overwrites should not be done in prod)
7850 return Object.freeze({
7851 get attrs() {
7852 return new Proxy(instance.attrs, attrHandlers);
7853 },
7854 get slots() {
7855 return shallowReadonly(instance.slots);
7856 },
7857 get emit() {
7858 return (event, ...args) => instance.emit(event, ...args);
7859 },
7860 expose
7861 });
7862 }
7863 }
7864 // record effects created during a component's setup() so that they can be
7865 // stopped when the component unmounts
7866 function recordInstanceBoundEffect(effect, instance = currentInstance) {
7867 if (instance) {
7868 (instance.effects || (instance.effects = [])).push(effect);
7869 }
7870 }
7871 const classifyRE = /(?:^|[-_])(\w)/g;
7872 const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
7873 function getComponentName(Component) {
7874 return isFunction(Component)
7875 ? Component.displayName || Component.name
7876 : Component.name;
7877 }
7878 /* istanbul ignore next */
7879 function formatComponentName(instance, Component, isRoot = false) {
7880 let name = getComponentName(Component);
7881 if (!name && Component.__file) {
7882 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
7883 if (match) {
7884 name = match[1];
7885 }
7886 }
7887 if (!name && instance && instance.parent) {
7888 // try to infer the name based on reverse resolution
7889 const inferFromRegistry = (registry) => {
7890 for (const key in registry) {
7891 if (registry[key] === Component) {
7892 return key;
7893 }
7894 }
7895 };
7896 name =
7897 inferFromRegistry(instance.components ||
7898 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
7899 }
7900 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
7901 }
7902 function isClassComponent(value) {
7903 return isFunction(value) && '__vccOpts' in value;
7904 }
7905
7906 function computed$1(getterOrOptions) {
7907 const c = computed(getterOrOptions);
7908 recordInstanceBoundEffect(c.effect);
7909 return c;
7910 }
7911
7912 // implementation
7913 function defineProps() {
7914 {
7915 warn(`defineProps() is a compiler-hint helper that is only usable inside ` +
7916 `<script setup> of a single file component. Its arguments should be ` +
7917 `compiled away and passing it at runtime has no effect.`);
7918 }
7919 return null;
7920 }
7921 // implementation
7922 function defineEmit() {
7923 {
7924 warn(`defineEmit() is a compiler-hint helper that is only usable inside ` +
7925 `<script setup> of a single file component. Its arguments should be ` +
7926 `compiled away and passing it at runtime has no effect.`);
7927 }
7928 return null;
7929 }
7930 function useContext() {
7931 const i = getCurrentInstance();
7932 if (!i) {
7933 warn(`useContext() called without active instance.`);
7934 }
7935 return i.setupContext || (i.setupContext = createSetupContext(i));
7936 }
7937
7938 // Actual implementation
7939 function h(type, propsOrChildren, children) {
7940 const l = arguments.length;
7941 if (l === 2) {
7942 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
7943 // single vnode without props
7944 if (isVNode(propsOrChildren)) {
7945 return createVNode(type, null, [propsOrChildren]);
7946 }
7947 // props without children
7948 return createVNode(type, propsOrChildren);
7949 }
7950 else {
7951 // omit props
7952 return createVNode(type, null, propsOrChildren);
7953 }
7954 }
7955 else {
7956 if (l > 3) {
7957 children = Array.prototype.slice.call(arguments, 2);
7958 }
7959 else if (l === 3 && isVNode(children)) {
7960 children = [children];
7961 }
7962 return createVNode(type, propsOrChildren, children);
7963 }
7964 }
7965
7966 const ssrContextKey = Symbol(`ssrContext` );
7967 const useSSRContext = () => {
7968 {
7969 warn(`useSSRContext() is not supported in the global build.`);
7970 }
7971 };
7972
7973 function initCustomFormatter() {
7974 /* eslint-disable no-restricted-globals */
7975 if (typeof window === 'undefined') {
7976 return;
7977 }
7978 const vueStyle = { style: 'color:#3ba776' };
7979 const numberStyle = { style: 'color:#0b1bc9' };
7980 const stringStyle = { style: 'color:#b62e24' };
7981 const keywordStyle = { style: 'color:#9d288c' };
7982 // custom formatter for Chrome
7983 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
7984 const formatter = {
7985 header(obj) {
7986 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
7987 if (!isObject(obj)) {
7988 return null;
7989 }
7990 if (obj.__isVue) {
7991 return ['div', vueStyle, `VueInstance`];
7992 }
7993 else if (isRef(obj)) {
7994 return [
7995 'div',
7996 {},
7997 ['span', vueStyle, genRefFlag(obj)],
7998 '<',
7999 formatValue(obj.value),
8000 `>`
8001 ];
8002 }
8003 else if (isReactive(obj)) {
8004 return [
8005 'div',
8006 {},
8007 ['span', vueStyle, 'Reactive'],
8008 '<',
8009 formatValue(obj),
8010 `>${isReadonly(obj) ? ` (readonly)` : ``}`
8011 ];
8012 }
8013 else if (isReadonly(obj)) {
8014 return [
8015 'div',
8016 {},
8017 ['span', vueStyle, 'Readonly'],
8018 '<',
8019 formatValue(obj),
8020 '>'
8021 ];
8022 }
8023 return null;
8024 },
8025 hasBody(obj) {
8026 return obj && obj.__isVue;
8027 },
8028 body(obj) {
8029 if (obj && obj.__isVue) {
8030 return [
8031 'div',
8032 {},
8033 ...formatInstance(obj.$)
8034 ];
8035 }
8036 }
8037 };
8038 function formatInstance(instance) {
8039 const blocks = [];
8040 if (instance.type.props && instance.props) {
8041 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
8042 }
8043 if (instance.setupState !== EMPTY_OBJ) {
8044 blocks.push(createInstanceBlock('setup', instance.setupState));
8045 }
8046 if (instance.data !== EMPTY_OBJ) {
8047 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
8048 }
8049 const computed = extractKeys(instance, 'computed');
8050 if (computed) {
8051 blocks.push(createInstanceBlock('computed', computed));
8052 }
8053 const injected = extractKeys(instance, 'inject');
8054 if (injected) {
8055 blocks.push(createInstanceBlock('injected', injected));
8056 }
8057 blocks.push([
8058 'div',
8059 {},
8060 [
8061 'span',
8062 {
8063 style: keywordStyle.style + ';opacity:0.66'
8064 },
8065 '$ (internal): '
8066 ],
8067 ['object', { object: instance }]
8068 ]);
8069 return blocks;
8070 }
8071 function createInstanceBlock(type, target) {
8072 target = extend({}, target);
8073 if (!Object.keys(target).length) {
8074 return ['span', {}];
8075 }
8076 return [
8077 'div',
8078 { style: 'line-height:1.25em;margin-bottom:0.6em' },
8079 [
8080 'div',
8081 {
8082 style: 'color:#476582'
8083 },
8084 type
8085 ],
8086 [
8087 'div',
8088 {
8089 style: 'padding-left:1.25em'
8090 },
8091 ...Object.keys(target).map(key => {
8092 return [
8093 'div',
8094 {},
8095 ['span', keywordStyle, key + ': '],
8096 formatValue(target[key], false)
8097 ];
8098 })
8099 ]
8100 ];
8101 }
8102 function formatValue(v, asRaw = true) {
8103 if (typeof v === 'number') {
8104 return ['span', numberStyle, v];
8105 }
8106 else if (typeof v === 'string') {
8107 return ['span', stringStyle, JSON.stringify(v)];
8108 }
8109 else if (typeof v === 'boolean') {
8110 return ['span', keywordStyle, v];
8111 }
8112 else if (isObject(v)) {
8113 return ['object', { object: asRaw ? toRaw(v) : v }];
8114 }
8115 else {
8116 return ['span', stringStyle, String(v)];
8117 }
8118 }
8119 function extractKeys(instance, type) {
8120 const Comp = instance.type;
8121 if (isFunction(Comp)) {
8122 return;
8123 }
8124 const extracted = {};
8125 for (const key in instance.ctx) {
8126 if (isKeyOfType(Comp, key, type)) {
8127 extracted[key] = instance.ctx[key];
8128 }
8129 }
8130 return extracted;
8131 }
8132 function isKeyOfType(Comp, key, type) {
8133 const opts = Comp[type];
8134 if ((isArray(opts) && opts.includes(key)) ||
8135 (isObject(opts) && key in opts)) {
8136 return true;
8137 }
8138 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
8139 return true;
8140 }
8141 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
8142 return true;
8143 }
8144 }
8145 function genRefFlag(v) {
8146 if (v._shallow) {
8147 return `ShallowRef`;
8148 }
8149 if (v.effect) {
8150 return `ComputedRef`;
8151 }
8152 return `Ref`;
8153 }
8154 if (window.devtoolsFormatters) {
8155 window.devtoolsFormatters.push(formatter);
8156 }
8157 else {
8158 window.devtoolsFormatters = [formatter];
8159 }
8160 }
8161
8162 /**
8163 * Actual implementation
8164 */
8165 function renderList(source, renderItem) {
8166 let ret;
8167 if (isArray(source) || isString(source)) {
8168 ret = new Array(source.length);
8169 for (let i = 0, l = source.length; i < l; i++) {
8170 ret[i] = renderItem(source[i], i);
8171 }
8172 }
8173 else if (typeof source === 'number') {
8174 if (!Number.isInteger(source)) {
8175 warn(`The v-for range expect an integer value but got ${source}.`);
8176 return [];
8177 }
8178 ret = new Array(source);
8179 for (let i = 0; i < source; i++) {
8180 ret[i] = renderItem(i + 1, i);
8181 }
8182 }
8183 else if (isObject(source)) {
8184 if (source[Symbol.iterator]) {
8185 ret = Array.from(source, renderItem);
8186 }
8187 else {
8188 const keys = Object.keys(source);
8189 ret = new Array(keys.length);
8190 for (let i = 0, l = keys.length; i < l; i++) {
8191 const key = keys[i];
8192 ret[i] = renderItem(source[key], key, i);
8193 }
8194 }
8195 }
8196 else {
8197 ret = [];
8198 }
8199 return ret;
8200 }
8201
8202 /**
8203 * For prefixing keys in v-on="obj" with "on"
8204 * @private
8205 */
8206 function toHandlers(obj) {
8207 const ret = {};
8208 if (!isObject(obj)) {
8209 warn(`v-on with no argument expects an object value.`);
8210 return ret;
8211 }
8212 for (const key in obj) {
8213 ret[toHandlerKey(key)] = obj[key];
8214 }
8215 return ret;
8216 }
8217
8218 /**
8219 * Compiler runtime helper for creating dynamic slots object
8220 * @private
8221 */
8222 function createSlots(slots, dynamicSlots) {
8223 for (let i = 0; i < dynamicSlots.length; i++) {
8224 const slot = dynamicSlots[i];
8225 // array of dynamic slot generated by <template v-for="..." #[...]>
8226 if (isArray(slot)) {
8227 for (let j = 0; j < slot.length; j++) {
8228 slots[slot[j].name] = slot[j].fn;
8229 }
8230 }
8231 else if (slot) {
8232 // conditional single slot generated by <template v-if="..." #foo>
8233 slots[slot.name] = slot.fn;
8234 }
8235 }
8236 return slots;
8237 }
8238
8239 // Core API ------------------------------------------------------------------
8240 const version = "3.0.10";
8241 /**
8242 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
8243 * @internal
8244 */
8245 const ssrUtils = (null);
8246
8247 const svgNS = 'http://www.w3.org/2000/svg';
8248 const doc = (typeof document !== 'undefined' ? document : null);
8249 let tempContainer;
8250 let tempSVGContainer;
8251 const nodeOps = {
8252 insert: (child, parent, anchor) => {
8253 parent.insertBefore(child, anchor || null);
8254 },
8255 remove: child => {
8256 const parent = child.parentNode;
8257 if (parent) {
8258 parent.removeChild(child);
8259 }
8260 },
8261 createElement: (tag, isSVG, is, props) => {
8262 const el = isSVG
8263 ? doc.createElementNS(svgNS, tag)
8264 : doc.createElement(tag, is ? { is } : undefined);
8265 if (tag === 'select' && props && props.multiple != null) {
8266 el.setAttribute('multiple', props.multiple);
8267 }
8268 return el;
8269 },
8270 createText: text => doc.createTextNode(text),
8271 createComment: text => doc.createComment(text),
8272 setText: (node, text) => {
8273 node.nodeValue = text;
8274 },
8275 setElementText: (el, text) => {
8276 el.textContent = text;
8277 },
8278 parentNode: node => node.parentNode,
8279 nextSibling: node => node.nextSibling,
8280 querySelector: selector => doc.querySelector(selector),
8281 setScopeId(el, id) {
8282 el.setAttribute(id, '');
8283 },
8284 cloneNode(el) {
8285 const cloned = el.cloneNode(true);
8286 // #3072
8287 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
8288 // - normally, elements using `:value` bindings will not be hoisted, but if
8289 // the bound value is a constant, e.g. `:value="true"` - they do get
8290 // hoisted.
8291 // - in production, hoisted nodes are cloned when subsequent inserts, but
8292 // cloneNode() does not copy the custom property we attached.
8293 // - This may need to account for other custom DOM properties we attach to
8294 // elements in addition to `_value` in the future.
8295 if (`_value` in el) {
8296 cloned._value = el._value;
8297 }
8298 return cloned;
8299 },
8300 // __UNSAFE__
8301 // Reason: innerHTML.
8302 // Static content here can only come from compiled templates.
8303 // As long as the user only uses trusted templates, this is safe.
8304 insertStaticContent(content, parent, anchor, isSVG) {
8305 const temp = isSVG
8306 ? tempSVGContainer ||
8307 (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
8308 : tempContainer || (tempContainer = doc.createElement('div'));
8309 temp.innerHTML = content;
8310 const first = temp.firstChild;
8311 let node = first;
8312 let last = node;
8313 while (node) {
8314 last = node;
8315 nodeOps.insert(node, parent, anchor);
8316 node = temp.firstChild;
8317 }
8318 return [first, last];
8319 }
8320 };
8321
8322 // compiler should normalize class + :class bindings on the same element
8323 // into a single binding ['staticClass', dynamic]
8324 function patchClass(el, value, isSVG) {
8325 if (value == null) {
8326 value = '';
8327 }
8328 if (isSVG) {
8329 el.setAttribute('class', value);
8330 }
8331 else {
8332 // directly setting className should be faster than setAttribute in theory
8333 // if this is an element during a transition, take the temporary transition
8334 // classes into account.
8335 const transitionClasses = el._vtc;
8336 if (transitionClasses) {
8337 value = (value
8338 ? [value, ...transitionClasses]
8339 : [...transitionClasses]).join(' ');
8340 }
8341 el.className = value;
8342 }
8343 }
8344
8345 function patchStyle(el, prev, next) {
8346 const style = el.style;
8347 if (!next) {
8348 el.removeAttribute('style');
8349 }
8350 else if (isString(next)) {
8351 if (prev !== next) {
8352 const current = style.display;
8353 style.cssText = next;
8354 // indicates that the `display` of the element is controlled by `v-show`,
8355 // so we always keep the current `display` value regardless of the `style` value,
8356 // thus handing over control to `v-show`.
8357 if ('_vod' in el) {
8358 style.display = current;
8359 }
8360 }
8361 }
8362 else {
8363 for (const key in next) {
8364 setStyle(style, key, next[key]);
8365 }
8366 if (prev && !isString(prev)) {
8367 for (const key in prev) {
8368 if (next[key] == null) {
8369 setStyle(style, key, '');
8370 }
8371 }
8372 }
8373 }
8374 }
8375 const importantRE = /\s*!important$/;
8376 function setStyle(style, name, val) {
8377 if (isArray(val)) {
8378 val.forEach(v => setStyle(style, name, v));
8379 }
8380 else {
8381 if (name.startsWith('--')) {
8382 // custom property definition
8383 style.setProperty(name, val);
8384 }
8385 else {
8386 const prefixed = autoPrefix(style, name);
8387 if (importantRE.test(val)) {
8388 // !important
8389 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
8390 }
8391 else {
8392 style[prefixed] = val;
8393 }
8394 }
8395 }
8396 }
8397 const prefixes = ['Webkit', 'Moz', 'ms'];
8398 const prefixCache = {};
8399 function autoPrefix(style, rawName) {
8400 const cached = prefixCache[rawName];
8401 if (cached) {
8402 return cached;
8403 }
8404 let name = camelize(rawName);
8405 if (name !== 'filter' && name in style) {
8406 return (prefixCache[rawName] = name);
8407 }
8408 name = capitalize(name);
8409 for (let i = 0; i < prefixes.length; i++) {
8410 const prefixed = prefixes[i] + name;
8411 if (prefixed in style) {
8412 return (prefixCache[rawName] = prefixed);
8413 }
8414 }
8415 return rawName;
8416 }
8417
8418 const xlinkNS = 'http://www.w3.org/1999/xlink';
8419 function patchAttr(el, key, value, isSVG) {
8420 if (isSVG && key.startsWith('xlink:')) {
8421 if (value == null) {
8422 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
8423 }
8424 else {
8425 el.setAttributeNS(xlinkNS, key, value);
8426 }
8427 }
8428 else {
8429 // note we are only checking boolean attributes that don't have a
8430 // corresponding dom prop of the same name here.
8431 const isBoolean = isSpecialBooleanAttr(key);
8432 if (value == null || (isBoolean && value === false)) {
8433 el.removeAttribute(key);
8434 }
8435 else {
8436 el.setAttribute(key, isBoolean ? '' : value);
8437 }
8438 }
8439 }
8440
8441 // __UNSAFE__
8442 // functions. The user is responsible for using them with only trusted content.
8443 function patchDOMProp(el, key, value,
8444 // the following args are passed only due to potential innerHTML/textContent
8445 // overriding existing VNodes, in which case the old tree must be properly
8446 // unmounted.
8447 prevChildren, parentComponent, parentSuspense, unmountChildren) {
8448 if (key === 'innerHTML' || key === 'textContent') {
8449 if (prevChildren) {
8450 unmountChildren(prevChildren, parentComponent, parentSuspense);
8451 }
8452 el[key] = value == null ? '' : value;
8453 return;
8454 }
8455 if (key === 'value' && el.tagName !== 'PROGRESS') {
8456 // store value as _value as well since
8457 // non-string values will be stringified.
8458 el._value = value;
8459 const newValue = value == null ? '' : value;
8460 if (el.value !== newValue) {
8461 el.value = newValue;
8462 }
8463 return;
8464 }
8465 if (value === '' || value == null) {
8466 const type = typeof el[key];
8467 if (value === '' && type === 'boolean') {
8468 // e.g. <select multiple> compiles to { multiple: '' }
8469 el[key] = true;
8470 return;
8471 }
8472 else if (value == null && type === 'string') {
8473 // e.g. <div :id="null">
8474 el[key] = '';
8475 el.removeAttribute(key);
8476 return;
8477 }
8478 else if (type === 'number') {
8479 // e.g. <img :width="null">
8480 el[key] = 0;
8481 el.removeAttribute(key);
8482 return;
8483 }
8484 }
8485 // some properties perform value validation and throw
8486 try {
8487 el[key] = value;
8488 }
8489 catch (e) {
8490 {
8491 warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
8492 `value ${value} is invalid.`, e);
8493 }
8494 }
8495 }
8496
8497 // Async edge case fix requires storing an event listener's attach timestamp.
8498 let _getNow = Date.now;
8499 let skipTimestampCheck = false;
8500 if (typeof window !== 'undefined') {
8501 // Determine what event timestamp the browser is using. Annoyingly, the
8502 // timestamp can either be hi-res (relative to page load) or low-res
8503 // (relative to UNIX epoch), so in order to compare time we have to use the
8504 // same timestamp type when saving the flush timestamp.
8505 if (_getNow() > document.createEvent('Event').timeStamp) {
8506 // if the low-res timestamp which is bigger than the event timestamp
8507 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
8508 // and we need to use the hi-res version for event listeners as well.
8509 _getNow = () => performance.now();
8510 }
8511 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
8512 // and does not fire microtasks in between event propagation, so safe to exclude.
8513 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
8514 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
8515 }
8516 // To avoid the overhead of repeatedly calling performance.now(), we cache
8517 // and use the same timestamp for all event listeners attached in the same tick.
8518 let cachedNow = 0;
8519 const p = Promise.resolve();
8520 const reset = () => {
8521 cachedNow = 0;
8522 };
8523 const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
8524 function addEventListener(el, event, handler, options) {
8525 el.addEventListener(event, handler, options);
8526 }
8527 function removeEventListener(el, event, handler, options) {
8528 el.removeEventListener(event, handler, options);
8529 }
8530 function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
8531 // vei = vue event invokers
8532 const invokers = el._vei || (el._vei = {});
8533 const existingInvoker = invokers[rawName];
8534 if (nextValue && existingInvoker) {
8535 // patch
8536 existingInvoker.value = nextValue;
8537 }
8538 else {
8539 const [name, options] = parseName(rawName);
8540 if (nextValue) {
8541 // add
8542 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
8543 addEventListener(el, name, invoker, options);
8544 }
8545 else if (existingInvoker) {
8546 // remove
8547 removeEventListener(el, name, existingInvoker, options);
8548 invokers[rawName] = undefined;
8549 }
8550 }
8551 }
8552 const optionsModifierRE = /(?:Once|Passive|Capture)$/;
8553 function parseName(name) {
8554 let options;
8555 if (optionsModifierRE.test(name)) {
8556 options = {};
8557 let m;
8558 while ((m = name.match(optionsModifierRE))) {
8559 name = name.slice(0, name.length - m[0].length);
8560 options[m[0].toLowerCase()] = true;
8561 }
8562 }
8563 return [hyphenate(name.slice(2)), options];
8564 }
8565 function createInvoker(initialValue, instance) {
8566 const invoker = (e) => {
8567 // async edge case #6566: inner click event triggers patch, event handler
8568 // attached to outer element during patch, and triggered again. This
8569 // happens because browsers fire microtask ticks between event propagation.
8570 // the solution is simple: we save the timestamp when a handler is attached,
8571 // and the handler would only fire if the event passed to it was fired
8572 // AFTER it was attached.
8573 const timeStamp = e.timeStamp || _getNow();
8574 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
8575 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
8576 }
8577 };
8578 invoker.value = initialValue;
8579 invoker.attached = getNow();
8580 return invoker;
8581 }
8582 function patchStopImmediatePropagation(e, value) {
8583 if (isArray(value)) {
8584 const originalStop = e.stopImmediatePropagation;
8585 e.stopImmediatePropagation = () => {
8586 originalStop.call(e);
8587 e._stopped = true;
8588 };
8589 return value.map(fn => (e) => !e._stopped && fn(e));
8590 }
8591 else {
8592 return value;
8593 }
8594 }
8595
8596 const nativeOnRE = /^on[a-z]/;
8597 const forcePatchProp = (_, key) => key === 'value';
8598 const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
8599 switch (key) {
8600 // special
8601 case 'class':
8602 patchClass(el, nextValue, isSVG);
8603 break;
8604 case 'style':
8605 patchStyle(el, prevValue, nextValue);
8606 break;
8607 default:
8608 if (isOn(key)) {
8609 // ignore v-model listeners
8610 if (!isModelListener(key)) {
8611 patchEvent(el, key, prevValue, nextValue, parentComponent);
8612 }
8613 }
8614 else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
8615 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
8616 }
8617 else {
8618 // special case for <input v-model type="checkbox"> with
8619 // :true-value & :false-value
8620 // store value as dom properties since non-string values will be
8621 // stringified.
8622 if (key === 'true-value') {
8623 el._trueValue = nextValue;
8624 }
8625 else if (key === 'false-value') {
8626 el._falseValue = nextValue;
8627 }
8628 patchAttr(el, key, nextValue, isSVG);
8629 }
8630 break;
8631 }
8632 };
8633 function shouldSetAsProp(el, key, value, isSVG) {
8634 if (isSVG) {
8635 // most keys must be set as attribute on svg elements to work
8636 // ...except innerHTML
8637 if (key === 'innerHTML') {
8638 return true;
8639 }
8640 // or native onclick with function values
8641 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
8642 return true;
8643 }
8644 return false;
8645 }
8646 // spellcheck and draggable are numerated attrs, however their
8647 // corresponding DOM properties are actually booleans - this leads to
8648 // setting it with a string "false" value leading it to be coerced to
8649 // `true`, so we need to always treat them as attributes.
8650 // Note that `contentEditable` doesn't have this problem: its DOM
8651 // property is also enumerated string values.
8652 if (key === 'spellcheck' || key === 'draggable') {
8653 return false;
8654 }
8655 // #1787, #2840 form property on form elements is readonly and must be set as
8656 // attribute.
8657 if (key === 'form') {
8658 return false;
8659 }
8660 // #1526 <input list> must be set as attribute
8661 if (key === 'list' && el.tagName === 'INPUT') {
8662 return false;
8663 }
8664 // #2766 <textarea type> must be set as attribute
8665 if (key === 'type' && el.tagName === 'TEXTAREA') {
8666 return false;
8667 }
8668 // native onclick with string value, must be set as attribute
8669 if (nativeOnRE.test(key) && isString(value)) {
8670 return false;
8671 }
8672 return key in el;
8673 }
8674
8675 function useCssModule(name = '$style') {
8676 /* istanbul ignore else */
8677 {
8678 {
8679 warn(`useCssModule() is not supported in the global build.`);
8680 }
8681 return EMPTY_OBJ;
8682 }
8683 }
8684
8685 /**
8686 * Runtime helper for SFC's CSS variable injection feature.
8687 * @private
8688 */
8689 function useCssVars(getter) {
8690 const instance = getCurrentInstance();
8691 /* istanbul ignore next */
8692 if (!instance) {
8693 warn(`useCssVars is called without current active component instance.`);
8694 return;
8695 }
8696 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
8697 onMounted(() => watchEffect(setVars, { flush: 'post' }));
8698 onUpdated(setVars);
8699 }
8700 function setVarsOnVNode(vnode, vars) {
8701 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
8702 const suspense = vnode.suspense;
8703 vnode = suspense.activeBranch;
8704 if (suspense.pendingBranch && !suspense.isHydrating) {
8705 suspense.effects.push(() => {
8706 setVarsOnVNode(suspense.activeBranch, vars);
8707 });
8708 }
8709 }
8710 // drill down HOCs until it's a non-component vnode
8711 while (vnode.component) {
8712 vnode = vnode.component.subTree;
8713 }
8714 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
8715 const style = vnode.el.style;
8716 for (const key in vars) {
8717 style.setProperty(`--${key}`, vars[key]);
8718 }
8719 }
8720 else if (vnode.type === Fragment) {
8721 vnode.children.forEach(c => setVarsOnVNode(c, vars));
8722 }
8723 }
8724
8725 const TRANSITION = 'transition';
8726 const ANIMATION = 'animation';
8727 // DOM Transition is a higher-order-component based on the platform-agnostic
8728 // base Transition component, with DOM-specific logic.
8729 const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
8730 Transition.displayName = 'Transition';
8731 const DOMTransitionPropsValidators = {
8732 name: String,
8733 type: String,
8734 css: {
8735 type: Boolean,
8736 default: true
8737 },
8738 duration: [String, Number, Object],
8739 enterFromClass: String,
8740 enterActiveClass: String,
8741 enterToClass: String,
8742 appearFromClass: String,
8743 appearActiveClass: String,
8744 appearToClass: String,
8745 leaveFromClass: String,
8746 leaveActiveClass: String,
8747 leaveToClass: String
8748 };
8749 const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
8750 function resolveTransitionProps(rawProps) {
8751 let { name = 'v', type, css = true, 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;
8752 const baseProps = {};
8753 for (const key in rawProps) {
8754 if (!(key in DOMTransitionPropsValidators)) {
8755 baseProps[key] = rawProps[key];
8756 }
8757 }
8758 if (!css) {
8759 return baseProps;
8760 }
8761 const durations = normalizeDuration(duration);
8762 const enterDuration = durations && durations[0];
8763 const leaveDuration = durations && durations[1];
8764 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
8765 const finishEnter = (el, isAppear, done) => {
8766 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
8767 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
8768 done && done();
8769 };
8770 const finishLeave = (el, done) => {
8771 removeTransitionClass(el, leaveToClass);
8772 removeTransitionClass(el, leaveActiveClass);
8773 done && done();
8774 };
8775 const makeEnterHook = (isAppear) => {
8776 return (el, done) => {
8777 const hook = isAppear ? onAppear : onEnter;
8778 const resolve = () => finishEnter(el, isAppear, done);
8779 hook && hook(el, resolve);
8780 nextFrame(() => {
8781 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
8782 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
8783 if (!(hook && hook.length > 1)) {
8784 whenTransitionEnds(el, type, enterDuration, resolve);
8785 }
8786 });
8787 };
8788 };
8789 return extend(baseProps, {
8790 onBeforeEnter(el) {
8791 onBeforeEnter && onBeforeEnter(el);
8792 addTransitionClass(el, enterFromClass);
8793 addTransitionClass(el, enterActiveClass);
8794 },
8795 onBeforeAppear(el) {
8796 onBeforeAppear && onBeforeAppear(el);
8797 addTransitionClass(el, appearFromClass);
8798 addTransitionClass(el, appearActiveClass);
8799 },
8800 onEnter: makeEnterHook(false),
8801 onAppear: makeEnterHook(true),
8802 onLeave(el, done) {
8803 const resolve = () => finishLeave(el, done);
8804 addTransitionClass(el, leaveFromClass);
8805 // force reflow so *-leave-from classes immediately take effect (#2593)
8806 forceReflow();
8807 addTransitionClass(el, leaveActiveClass);
8808 nextFrame(() => {
8809 removeTransitionClass(el, leaveFromClass);
8810 addTransitionClass(el, leaveToClass);
8811 if (!(onLeave && onLeave.length > 1)) {
8812 whenTransitionEnds(el, type, leaveDuration, resolve);
8813 }
8814 });
8815 onLeave && onLeave(el, resolve);
8816 },
8817 onEnterCancelled(el) {
8818 finishEnter(el, false);
8819 onEnterCancelled && onEnterCancelled(el);
8820 },
8821 onAppearCancelled(el) {
8822 finishEnter(el, true);
8823 onAppearCancelled && onAppearCancelled(el);
8824 },
8825 onLeaveCancelled(el) {
8826 finishLeave(el);
8827 onLeaveCancelled && onLeaveCancelled(el);
8828 }
8829 });
8830 }
8831 function normalizeDuration(duration) {
8832 if (duration == null) {
8833 return null;
8834 }
8835 else if (isObject(duration)) {
8836 return [NumberOf(duration.enter), NumberOf(duration.leave)];
8837 }
8838 else {
8839 const n = NumberOf(duration);
8840 return [n, n];
8841 }
8842 }
8843 function NumberOf(val) {
8844 const res = toNumber(val);
8845 validateDuration(res);
8846 return res;
8847 }
8848 function validateDuration(val) {
8849 if (typeof val !== 'number') {
8850 warn(`<transition> explicit duration is not a valid number - ` +
8851 `got ${JSON.stringify(val)}.`);
8852 }
8853 else if (isNaN(val)) {
8854 warn(`<transition> explicit duration is NaN - ` +
8855 'the duration expression might be incorrect.');
8856 }
8857 }
8858 function addTransitionClass(el, cls) {
8859 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
8860 (el._vtc ||
8861 (el._vtc = new Set())).add(cls);
8862 }
8863 function removeTransitionClass(el, cls) {
8864 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
8865 const { _vtc } = el;
8866 if (_vtc) {
8867 _vtc.delete(cls);
8868 if (!_vtc.size) {
8869 el._vtc = undefined;
8870 }
8871 }
8872 }
8873 function nextFrame(cb) {
8874 requestAnimationFrame(() => {
8875 requestAnimationFrame(cb);
8876 });
8877 }
8878 let endId = 0;
8879 function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
8880 const id = (el._endId = ++endId);
8881 const resolveIfNotStale = () => {
8882 if (id === el._endId) {
8883 resolve();
8884 }
8885 };
8886 if (explicitTimeout) {
8887 return setTimeout(resolveIfNotStale, explicitTimeout);
8888 }
8889 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
8890 if (!type) {
8891 return resolve();
8892 }
8893 const endEvent = type + 'end';
8894 let ended = 0;
8895 const end = () => {
8896 el.removeEventListener(endEvent, onEnd);
8897 resolveIfNotStale();
8898 };
8899 const onEnd = (e) => {
8900 if (e.target === el && ++ended >= propCount) {
8901 end();
8902 }
8903 };
8904 setTimeout(() => {
8905 if (ended < propCount) {
8906 end();
8907 }
8908 }, timeout + 1);
8909 el.addEventListener(endEvent, onEnd);
8910 }
8911 function getTransitionInfo(el, expectedType) {
8912 const styles = window.getComputedStyle(el);
8913 // JSDOM may return undefined for transition properties
8914 const getStyleProperties = (key) => (styles[key] || '').split(', ');
8915 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
8916 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
8917 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
8918 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
8919 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
8920 const animationTimeout = getTimeout(animationDelays, animationDurations);
8921 let type = null;
8922 let timeout = 0;
8923 let propCount = 0;
8924 /* istanbul ignore if */
8925 if (expectedType === TRANSITION) {
8926 if (transitionTimeout > 0) {
8927 type = TRANSITION;
8928 timeout = transitionTimeout;
8929 propCount = transitionDurations.length;
8930 }
8931 }
8932 else if (expectedType === ANIMATION) {
8933 if (animationTimeout > 0) {
8934 type = ANIMATION;
8935 timeout = animationTimeout;
8936 propCount = animationDurations.length;
8937 }
8938 }
8939 else {
8940 timeout = Math.max(transitionTimeout, animationTimeout);
8941 type =
8942 timeout > 0
8943 ? transitionTimeout > animationTimeout
8944 ? TRANSITION
8945 : ANIMATION
8946 : null;
8947 propCount = type
8948 ? type === TRANSITION
8949 ? transitionDurations.length
8950 : animationDurations.length
8951 : 0;
8952 }
8953 const hasTransform = type === TRANSITION &&
8954 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
8955 return {
8956 type,
8957 timeout,
8958 propCount,
8959 hasTransform
8960 };
8961 }
8962 function getTimeout(delays, durations) {
8963 while (delays.length < durations.length) {
8964 delays = delays.concat(delays);
8965 }
8966 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
8967 }
8968 // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
8969 // numbers in a locale-dependent way, using a comma instead of a dot.
8970 // If comma is not replaced with a dot, the input will be rounded down
8971 // (i.e. acting as a floor function) causing unexpected behaviors
8972 function toMs(s) {
8973 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
8974 }
8975 // synchronously force layout to put elements into a certain state
8976 function forceReflow() {
8977 return document.body.offsetHeight;
8978 }
8979
8980 const positionMap = new WeakMap();
8981 const newPositionMap = new WeakMap();
8982 const TransitionGroupImpl = {
8983 name: 'TransitionGroup',
8984 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
8985 tag: String,
8986 moveClass: String
8987 }),
8988 setup(props, { slots }) {
8989 const instance = getCurrentInstance();
8990 const state = useTransitionState();
8991 let prevChildren;
8992 let children;
8993 onUpdated(() => {
8994 // children is guaranteed to exist after initial render
8995 if (!prevChildren.length) {
8996 return;
8997 }
8998 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
8999 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
9000 return;
9001 }
9002 // we divide the work into three loops to avoid mixing DOM reads and writes
9003 // in each iteration - which helps prevent layout thrashing.
9004 prevChildren.forEach(callPendingCbs);
9005 prevChildren.forEach(recordPosition);
9006 const movedChildren = prevChildren.filter(applyTranslation);
9007 // force reflow to put everything in position
9008 forceReflow();
9009 movedChildren.forEach(c => {
9010 const el = c.el;
9011 const style = el.style;
9012 addTransitionClass(el, moveClass);
9013 style.transform = style.webkitTransform = style.transitionDuration = '';
9014 const cb = (el._moveCb = (e) => {
9015 if (e && e.target !== el) {
9016 return;
9017 }
9018 if (!e || /transform$/.test(e.propertyName)) {
9019 el.removeEventListener('transitionend', cb);
9020 el._moveCb = null;
9021 removeTransitionClass(el, moveClass);
9022 }
9023 });
9024 el.addEventListener('transitionend', cb);
9025 });
9026 });
9027 return () => {
9028 const rawProps = toRaw(props);
9029 const cssTransitionProps = resolveTransitionProps(rawProps);
9030 const tag = rawProps.tag || Fragment;
9031 prevChildren = children;
9032 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
9033 for (let i = 0; i < children.length; i++) {
9034 const child = children[i];
9035 if (child.key != null) {
9036 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
9037 }
9038 else {
9039 warn(`<TransitionGroup> children must be keyed.`);
9040 }
9041 }
9042 if (prevChildren) {
9043 for (let i = 0; i < prevChildren.length; i++) {
9044 const child = prevChildren[i];
9045 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
9046 positionMap.set(child, child.el.getBoundingClientRect());
9047 }
9048 }
9049 return createVNode(tag, null, children);
9050 };
9051 }
9052 };
9053 const TransitionGroup = TransitionGroupImpl;
9054 function callPendingCbs(c) {
9055 const el = c.el;
9056 if (el._moveCb) {
9057 el._moveCb();
9058 }
9059 if (el._enterCb) {
9060 el._enterCb();
9061 }
9062 }
9063 function recordPosition(c) {
9064 newPositionMap.set(c, c.el.getBoundingClientRect());
9065 }
9066 function applyTranslation(c) {
9067 const oldPos = positionMap.get(c);
9068 const newPos = newPositionMap.get(c);
9069 const dx = oldPos.left - newPos.left;
9070 const dy = oldPos.top - newPos.top;
9071 if (dx || dy) {
9072 const s = c.el.style;
9073 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
9074 s.transitionDuration = '0s';
9075 return c;
9076 }
9077 }
9078 function hasCSSTransform(el, root, moveClass) {
9079 // Detect whether an element with the move class applied has
9080 // CSS transitions. Since the element may be inside an entering
9081 // transition at this very moment, we make a clone of it and remove
9082 // all other transition classes applied to ensure only the move class
9083 // is applied.
9084 const clone = el.cloneNode();
9085 if (el._vtc) {
9086 el._vtc.forEach(cls => {
9087 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
9088 });
9089 }
9090 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
9091 clone.style.display = 'none';
9092 const container = (root.nodeType === 1
9093 ? root
9094 : root.parentNode);
9095 container.appendChild(clone);
9096 const { hasTransform } = getTransitionInfo(clone);
9097 container.removeChild(clone);
9098 return hasTransform;
9099 }
9100
9101 const getModelAssigner = (vnode) => {
9102 const fn = vnode.props['onUpdate:modelValue'];
9103 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
9104 };
9105 function onCompositionStart(e) {
9106 e.target.composing = true;
9107 }
9108 function onCompositionEnd(e) {
9109 const target = e.target;
9110 if (target.composing) {
9111 target.composing = false;
9112 trigger$1(target, 'input');
9113 }
9114 }
9115 function trigger$1(el, type) {
9116 const e = document.createEvent('HTMLEvents');
9117 e.initEvent(type, true, true);
9118 el.dispatchEvent(e);
9119 }
9120 // We are exporting the v-model runtime directly as vnode hooks so that it can
9121 // be tree-shaken in case v-model is never used.
9122 const vModelText = {
9123 created(el, { modifiers: { lazy, trim, number } }, vnode) {
9124 el._assign = getModelAssigner(vnode);
9125 const castToNumber = number || el.type === 'number';
9126 addEventListener(el, lazy ? 'change' : 'input', e => {
9127 if (e.target.composing)
9128 return;
9129 let domValue = el.value;
9130 if (trim) {
9131 domValue = domValue.trim();
9132 }
9133 else if (castToNumber) {
9134 domValue = toNumber(domValue);
9135 }
9136 el._assign(domValue);
9137 });
9138 if (trim) {
9139 addEventListener(el, 'change', () => {
9140 el.value = el.value.trim();
9141 });
9142 }
9143 if (!lazy) {
9144 addEventListener(el, 'compositionstart', onCompositionStart);
9145 addEventListener(el, 'compositionend', onCompositionEnd);
9146 // Safari < 10.2 & UIWebView doesn't fire compositionend when
9147 // switching focus before confirming composition choice
9148 // this also fixes the issue where some browsers e.g. iOS Chrome
9149 // fires "change" instead of "input" on autocomplete.
9150 addEventListener(el, 'change', onCompositionEnd);
9151 }
9152 },
9153 // set value on mounted so it's after min/max for type="range"
9154 mounted(el, { value }) {
9155 el.value = value == null ? '' : value;
9156 },
9157 beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
9158 el._assign = getModelAssigner(vnode);
9159 // avoid clearing unresolved text. #2302
9160 if (el.composing)
9161 return;
9162 if (document.activeElement === el) {
9163 if (trim && el.value.trim() === value) {
9164 return;
9165 }
9166 if ((number || el.type === 'number') && toNumber(el.value) === value) {
9167 return;
9168 }
9169 }
9170 const newValue = value == null ? '' : value;
9171 if (el.value !== newValue) {
9172 el.value = newValue;
9173 }
9174 }
9175 };
9176 const vModelCheckbox = {
9177 created(el, _, vnode) {
9178 el._assign = getModelAssigner(vnode);
9179 addEventListener(el, 'change', () => {
9180 const modelValue = el._modelValue;
9181 const elementValue = getValue(el);
9182 const checked = el.checked;
9183 const assign = el._assign;
9184 if (isArray(modelValue)) {
9185 const index = looseIndexOf(modelValue, elementValue);
9186 const found = index !== -1;
9187 if (checked && !found) {
9188 assign(modelValue.concat(elementValue));
9189 }
9190 else if (!checked && found) {
9191 const filtered = [...modelValue];
9192 filtered.splice(index, 1);
9193 assign(filtered);
9194 }
9195 }
9196 else if (isSet(modelValue)) {
9197 const cloned = new Set(modelValue);
9198 if (checked) {
9199 cloned.add(elementValue);
9200 }
9201 else {
9202 cloned.delete(elementValue);
9203 }
9204 assign(cloned);
9205 }
9206 else {
9207 assign(getCheckboxValue(el, checked));
9208 }
9209 });
9210 },
9211 // set initial checked on mount to wait for true-value/false-value
9212 mounted: setChecked,
9213 beforeUpdate(el, binding, vnode) {
9214 el._assign = getModelAssigner(vnode);
9215 setChecked(el, binding, vnode);
9216 }
9217 };
9218 function setChecked(el, { value, oldValue }, vnode) {
9219 el._modelValue = value;
9220 if (isArray(value)) {
9221 el.checked = looseIndexOf(value, vnode.props.value) > -1;
9222 }
9223 else if (isSet(value)) {
9224 el.checked = value.has(vnode.props.value);
9225 }
9226 else if (value !== oldValue) {
9227 el.checked = looseEqual(value, getCheckboxValue(el, true));
9228 }
9229 }
9230 const vModelRadio = {
9231 created(el, { value }, vnode) {
9232 el.checked = looseEqual(value, vnode.props.value);
9233 el._assign = getModelAssigner(vnode);
9234 addEventListener(el, 'change', () => {
9235 el._assign(getValue(el));
9236 });
9237 },
9238 beforeUpdate(el, { value, oldValue }, vnode) {
9239 el._assign = getModelAssigner(vnode);
9240 if (value !== oldValue) {
9241 el.checked = looseEqual(value, vnode.props.value);
9242 }
9243 }
9244 };
9245 const vModelSelect = {
9246 created(el, { value, modifiers: { number } }, vnode) {
9247 const isSetModel = isSet(value);
9248 addEventListener(el, 'change', () => {
9249 const selectedVal = Array.prototype.filter
9250 .call(el.options, (o) => o.selected)
9251 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
9252 el._assign(el.multiple
9253 ? isSetModel
9254 ? new Set(selectedVal)
9255 : selectedVal
9256 : selectedVal[0]);
9257 });
9258 el._assign = getModelAssigner(vnode);
9259 },
9260 // set value in mounted & updated because <select> relies on its children
9261 // <option>s.
9262 mounted(el, { value }) {
9263 setSelected(el, value);
9264 },
9265 beforeUpdate(el, _binding, vnode) {
9266 el._assign = getModelAssigner(vnode);
9267 },
9268 updated(el, { value }) {
9269 setSelected(el, value);
9270 }
9271 };
9272 function setSelected(el, value) {
9273 const isMultiple = el.multiple;
9274 if (isMultiple && !isArray(value) && !isSet(value)) {
9275 warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
9276 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
9277 return;
9278 }
9279 for (let i = 0, l = el.options.length; i < l; i++) {
9280 const option = el.options[i];
9281 const optionValue = getValue(option);
9282 if (isMultiple) {
9283 if (isArray(value)) {
9284 option.selected = looseIndexOf(value, optionValue) > -1;
9285 }
9286 else {
9287 option.selected = value.has(optionValue);
9288 }
9289 }
9290 else {
9291 if (looseEqual(getValue(option), value)) {
9292 el.selectedIndex = i;
9293 return;
9294 }
9295 }
9296 }
9297 if (!isMultiple) {
9298 el.selectedIndex = -1;
9299 }
9300 }
9301 // retrieve raw value set via :value bindings
9302 function getValue(el) {
9303 return '_value' in el ? el._value : el.value;
9304 }
9305 // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
9306 function getCheckboxValue(el, checked) {
9307 const key = checked ? '_trueValue' : '_falseValue';
9308 return key in el ? el[key] : checked;
9309 }
9310 const vModelDynamic = {
9311 created(el, binding, vnode) {
9312 callModelHook(el, binding, vnode, null, 'created');
9313 },
9314 mounted(el, binding, vnode) {
9315 callModelHook(el, binding, vnode, null, 'mounted');
9316 },
9317 beforeUpdate(el, binding, vnode, prevVNode) {
9318 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
9319 },
9320 updated(el, binding, vnode, prevVNode) {
9321 callModelHook(el, binding, vnode, prevVNode, 'updated');
9322 }
9323 };
9324 function callModelHook(el, binding, vnode, prevVNode, hook) {
9325 let modelToUse;
9326 switch (el.tagName) {
9327 case 'SELECT':
9328 modelToUse = vModelSelect;
9329 break;
9330 case 'TEXTAREA':
9331 modelToUse = vModelText;
9332 break;
9333 default:
9334 switch (vnode.props && vnode.props.type) {
9335 case 'checkbox':
9336 modelToUse = vModelCheckbox;
9337 break;
9338 case 'radio':
9339 modelToUse = vModelRadio;
9340 break;
9341 default:
9342 modelToUse = vModelText;
9343 }
9344 }
9345 const fn = modelToUse[hook];
9346 fn && fn(el, binding, vnode, prevVNode);
9347 }
9348
9349 const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
9350 const modifierGuards = {
9351 stop: e => e.stopPropagation(),
9352 prevent: e => e.preventDefault(),
9353 self: e => e.target !== e.currentTarget,
9354 ctrl: e => !e.ctrlKey,
9355 shift: e => !e.shiftKey,
9356 alt: e => !e.altKey,
9357 meta: e => !e.metaKey,
9358 left: e => 'button' in e && e.button !== 0,
9359 middle: e => 'button' in e && e.button !== 1,
9360 right: e => 'button' in e && e.button !== 2,
9361 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
9362 };
9363 /**
9364 * @private
9365 */
9366 const withModifiers = (fn, modifiers) => {
9367 return (event, ...args) => {
9368 for (let i = 0; i < modifiers.length; i++) {
9369 const guard = modifierGuards[modifiers[i]];
9370 if (guard && guard(event, modifiers))
9371 return;
9372 }
9373 return fn(event, ...args);
9374 };
9375 };
9376 // Kept for 2.x compat.
9377 // Note: IE11 compat for `spacebar` and `del` is removed for now.
9378 const keyNames = {
9379 esc: 'escape',
9380 space: ' ',
9381 up: 'arrow-up',
9382 left: 'arrow-left',
9383 right: 'arrow-right',
9384 down: 'arrow-down',
9385 delete: 'backspace'
9386 };
9387 /**
9388 * @private
9389 */
9390 const withKeys = (fn, modifiers) => {
9391 return (event) => {
9392 if (!('key' in event))
9393 return;
9394 const eventKey = hyphenate(event.key);
9395 if (
9396 // None of the provided key modifiers match the current event key
9397 !modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
9398 return;
9399 }
9400 return fn(event);
9401 };
9402 };
9403
9404 const vShow = {
9405 beforeMount(el, { value }, { transition }) {
9406 el._vod = el.style.display === 'none' ? '' : el.style.display;
9407 if (transition && value) {
9408 transition.beforeEnter(el);
9409 }
9410 else {
9411 setDisplay(el, value);
9412 }
9413 },
9414 mounted(el, { value }, { transition }) {
9415 if (transition && value) {
9416 transition.enter(el);
9417 }
9418 },
9419 updated(el, { value, oldValue }, { transition }) {
9420 if (!value === !oldValue)
9421 return;
9422 if (transition) {
9423 if (value) {
9424 transition.beforeEnter(el);
9425 setDisplay(el, true);
9426 transition.enter(el);
9427 }
9428 else {
9429 transition.leave(el, () => {
9430 setDisplay(el, false);
9431 });
9432 }
9433 }
9434 else {
9435 setDisplay(el, value);
9436 }
9437 },
9438 beforeUnmount(el, { value }) {
9439 setDisplay(el, value);
9440 }
9441 };
9442 function setDisplay(el, value) {
9443 el.style.display = value ? el._vod : 'none';
9444 }
9445
9446 const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
9447 // lazy create the renderer - this makes core renderer logic tree-shakable
9448 // in case the user only imports reactivity utilities from Vue.
9449 let renderer;
9450 let enabledHydration = false;
9451 function ensureRenderer() {
9452 return renderer || (renderer = createRenderer(rendererOptions));
9453 }
9454 function ensureHydrationRenderer() {
9455 renderer = enabledHydration
9456 ? renderer
9457 : createHydrationRenderer(rendererOptions);
9458 enabledHydration = true;
9459 return renderer;
9460 }
9461 // use explicit type casts here to avoid import() calls in rolled-up d.ts
9462 const render = ((...args) => {
9463 ensureRenderer().render(...args);
9464 });
9465 const hydrate = ((...args) => {
9466 ensureHydrationRenderer().hydrate(...args);
9467 });
9468 const createApp = ((...args) => {
9469 const app = ensureRenderer().createApp(...args);
9470 {
9471 injectNativeTagCheck(app);
9472 injectCustomElementCheck(app);
9473 }
9474 const { mount } = app;
9475 app.mount = (containerOrSelector) => {
9476 const container = normalizeContainer(containerOrSelector);
9477 if (!container)
9478 return;
9479 const component = app._component;
9480 if (!isFunction(component) && !component.render && !component.template) {
9481 component.template = container.innerHTML;
9482 }
9483 // clear content before mounting
9484 container.innerHTML = '';
9485 const proxy = mount(container, false, container instanceof SVGElement);
9486 if (container instanceof Element) {
9487 container.removeAttribute('v-cloak');
9488 container.setAttribute('data-v-app', '');
9489 }
9490 return proxy;
9491 };
9492 return app;
9493 });
9494 const createSSRApp = ((...args) => {
9495 const app = ensureHydrationRenderer().createApp(...args);
9496 {
9497 injectNativeTagCheck(app);
9498 injectCustomElementCheck(app);
9499 }
9500 const { mount } = app;
9501 app.mount = (containerOrSelector) => {
9502 const container = normalizeContainer(containerOrSelector);
9503 if (container) {
9504 return mount(container, true, container instanceof SVGElement);
9505 }
9506 };
9507 return app;
9508 });
9509 function injectNativeTagCheck(app) {
9510 // Inject `isNativeTag`
9511 // this is used for component name validation (dev only)
9512 Object.defineProperty(app.config, 'isNativeTag', {
9513 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
9514 writable: false
9515 });
9516 }
9517 // dev only
9518 function injectCustomElementCheck(app) {
9519 if (isRuntimeOnly()) {
9520 const value = app.config.isCustomElement;
9521 Object.defineProperty(app.config, 'isCustomElement', {
9522 get() {
9523 return value;
9524 },
9525 set() {
9526 warn(`The \`isCustomElement\` config option is only respected when using the runtime compiler.` +
9527 `If you are using the runtime-only build, \`isCustomElement\` must be passed to \`@vue/compiler-dom\` in the build setup instead` +
9528 `- for example, via the \`compilerOptions\` option in vue-loader: https://vue-loader.vuejs.org/options.html#compileroptions.`);
9529 }
9530 });
9531 }
9532 }
9533 function normalizeContainer(container) {
9534 if (isString(container)) {
9535 const res = document.querySelector(container);
9536 if (!res) {
9537 warn(`Failed to mount app: mount target selector "${container}" returned null.`);
9538 }
9539 return res;
9540 }
9541 if (container instanceof window.ShadowRoot &&
9542 container.mode === 'closed') {
9543 warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
9544 }
9545 return container;
9546 }
9547
9548 function initDev() {
9549 {
9550 {
9551 console.info(`You are running a development build of Vue.\n` +
9552 `Make sure to use the production build (*.prod.js) when deploying for production.`);
9553 }
9554 initCustomFormatter();
9555 }
9556 }
9557
9558 function defaultOnError(error) {
9559 throw error;
9560 }
9561 function createCompilerError(code, loc, messages, additionalMessage) {
9562 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
9563 ;
9564 const error = new SyntaxError(String(msg));
9565 error.code = code;
9566 error.loc = loc;
9567 return error;
9568 }
9569 const errorMessages = {
9570 // parse errors
9571 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
9572 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
9573 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
9574 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
9575 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
9576 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
9577 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
9578 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
9579 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
9580 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
9581 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
9582 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
9583 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
9584 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
9585 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
9586 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
9587 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
9588 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
9589 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
9590 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
9591 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
9592 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
9593 // Vue-specific parse errors
9594 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
9595 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
9596 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
9597 [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
9598 'Note that dynamic directive argument cannot contain spaces.',
9599 // transform errors
9600 [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
9601 [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
9602 [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
9603 [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
9604 [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
9605 [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
9606 [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
9607 [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
9608 [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
9609 [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
9610 `When there are multiple named slots, all slots should use <template> ` +
9611 `syntax to avoid scope ambiguity.`,
9612 [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
9613 [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
9614 `default slot. These children will be ignored.`,
9615 [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
9616 [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
9617 [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
9618 [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
9619 [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
9620 [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
9621 // generic errors
9622 [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
9623 [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
9624 [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
9625 [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
9626 };
9627
9628 const FRAGMENT = Symbol(`Fragment` );
9629 const TELEPORT = Symbol(`Teleport` );
9630 const SUSPENSE = Symbol(`Suspense` );
9631 const KEEP_ALIVE = Symbol(`KeepAlive` );
9632 const BASE_TRANSITION = Symbol(`BaseTransition` );
9633 const OPEN_BLOCK = Symbol(`openBlock` );
9634 const CREATE_BLOCK = Symbol(`createBlock` );
9635 const CREATE_VNODE = Symbol(`createVNode` );
9636 const CREATE_COMMENT = Symbol(`createCommentVNode` );
9637 const CREATE_TEXT = Symbol(`createTextVNode` );
9638 const CREATE_STATIC = Symbol(`createStaticVNode` );
9639 const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
9640 const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
9641 const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
9642 const WITH_DIRECTIVES = Symbol(`withDirectives` );
9643 const RENDER_LIST = Symbol(`renderList` );
9644 const RENDER_SLOT = Symbol(`renderSlot` );
9645 const CREATE_SLOTS = Symbol(`createSlots` );
9646 const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
9647 const MERGE_PROPS = Symbol(`mergeProps` );
9648 const TO_HANDLERS = Symbol(`toHandlers` );
9649 const CAMELIZE = Symbol(`camelize` );
9650 const CAPITALIZE = Symbol(`capitalize` );
9651 const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
9652 const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
9653 const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
9654 const POP_SCOPE_ID = Symbol(`popScopeId` );
9655 const WITH_SCOPE_ID = Symbol(`withScopeId` );
9656 const WITH_CTX = Symbol(`withCtx` );
9657 const UNREF = Symbol(`unref` );
9658 const IS_REF = Symbol(`isRef` );
9659 // Name mapping for runtime helpers that need to be imported from 'vue' in
9660 // generated code. Make sure these are correctly exported in the runtime!
9661 // Using `any` here because TS doesn't allow symbols as index type.
9662 const helperNameMap = {
9663 [FRAGMENT]: `Fragment`,
9664 [TELEPORT]: `Teleport`,
9665 [SUSPENSE]: `Suspense`,
9666 [KEEP_ALIVE]: `KeepAlive`,
9667 [BASE_TRANSITION]: `BaseTransition`,
9668 [OPEN_BLOCK]: `openBlock`,
9669 [CREATE_BLOCK]: `createBlock`,
9670 [CREATE_VNODE]: `createVNode`,
9671 [CREATE_COMMENT]: `createCommentVNode`,
9672 [CREATE_TEXT]: `createTextVNode`,
9673 [CREATE_STATIC]: `createStaticVNode`,
9674 [RESOLVE_COMPONENT]: `resolveComponent`,
9675 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
9676 [RESOLVE_DIRECTIVE]: `resolveDirective`,
9677 [WITH_DIRECTIVES]: `withDirectives`,
9678 [RENDER_LIST]: `renderList`,
9679 [RENDER_SLOT]: `renderSlot`,
9680 [CREATE_SLOTS]: `createSlots`,
9681 [TO_DISPLAY_STRING]: `toDisplayString`,
9682 [MERGE_PROPS]: `mergeProps`,
9683 [TO_HANDLERS]: `toHandlers`,
9684 [CAMELIZE]: `camelize`,
9685 [CAPITALIZE]: `capitalize`,
9686 [TO_HANDLER_KEY]: `toHandlerKey`,
9687 [SET_BLOCK_TRACKING]: `setBlockTracking`,
9688 [PUSH_SCOPE_ID]: `pushScopeId`,
9689 [POP_SCOPE_ID]: `popScopeId`,
9690 [WITH_SCOPE_ID]: `withScopeId`,
9691 [WITH_CTX]: `withCtx`,
9692 [UNREF]: `unref`,
9693 [IS_REF]: `isRef`
9694 };
9695 function registerRuntimeHelpers(helpers) {
9696 Object.getOwnPropertySymbols(helpers).forEach(s => {
9697 helperNameMap[s] = helpers[s];
9698 });
9699 }
9700
9701 // AST Utilities ---------------------------------------------------------------
9702 // Some expressions, e.g. sequence and conditional expressions, are never
9703 // associated with template nodes, so their source locations are just a stub.
9704 // Container types like CompoundExpression also don't need a real location.
9705 const locStub = {
9706 source: '',
9707 start: { line: 1, column: 1, offset: 0 },
9708 end: { line: 1, column: 1, offset: 0 }
9709 };
9710 function createRoot(children, loc = locStub) {
9711 return {
9712 type: 0 /* ROOT */,
9713 children,
9714 helpers: [],
9715 components: [],
9716 directives: [],
9717 hoists: [],
9718 imports: [],
9719 cached: 0,
9720 temps: 0,
9721 codegenNode: undefined,
9722 loc
9723 };
9724 }
9725 function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
9726 if (context) {
9727 if (isBlock) {
9728 context.helper(OPEN_BLOCK);
9729 context.helper(CREATE_BLOCK);
9730 }
9731 else {
9732 context.helper(CREATE_VNODE);
9733 }
9734 if (directives) {
9735 context.helper(WITH_DIRECTIVES);
9736 }
9737 }
9738 return {
9739 type: 13 /* VNODE_CALL */,
9740 tag,
9741 props,
9742 children,
9743 patchFlag,
9744 dynamicProps,
9745 directives,
9746 isBlock,
9747 disableTracking,
9748 loc
9749 };
9750 }
9751 function createArrayExpression(elements, loc = locStub) {
9752 return {
9753 type: 17 /* JS_ARRAY_EXPRESSION */,
9754 loc,
9755 elements
9756 };
9757 }
9758 function createObjectExpression(properties, loc = locStub) {
9759 return {
9760 type: 15 /* JS_OBJECT_EXPRESSION */,
9761 loc,
9762 properties
9763 };
9764 }
9765 function createObjectProperty(key, value) {
9766 return {
9767 type: 16 /* JS_PROPERTY */,
9768 loc: locStub,
9769 key: isString(key) ? createSimpleExpression(key, true) : key,
9770 value
9771 };
9772 }
9773 function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
9774 return {
9775 type: 4 /* SIMPLE_EXPRESSION */,
9776 loc,
9777 content,
9778 isStatic,
9779 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
9780 };
9781 }
9782 function createCompoundExpression(children, loc = locStub) {
9783 return {
9784 type: 8 /* COMPOUND_EXPRESSION */,
9785 loc,
9786 children
9787 };
9788 }
9789 function createCallExpression(callee, args = [], loc = locStub) {
9790 return {
9791 type: 14 /* JS_CALL_EXPRESSION */,
9792 loc,
9793 callee,
9794 arguments: args
9795 };
9796 }
9797 function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
9798 return {
9799 type: 18 /* JS_FUNCTION_EXPRESSION */,
9800 params,
9801 returns,
9802 newline,
9803 isSlot,
9804 loc
9805 };
9806 }
9807 function createConditionalExpression(test, consequent, alternate, newline = true) {
9808 return {
9809 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
9810 test,
9811 consequent,
9812 alternate,
9813 newline,
9814 loc: locStub
9815 };
9816 }
9817 function createCacheExpression(index, value, isVNode = false) {
9818 return {
9819 type: 20 /* JS_CACHE_EXPRESSION */,
9820 index,
9821 value,
9822 isVNode,
9823 loc: locStub
9824 };
9825 }
9826
9827 const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
9828 const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
9829 function isCoreComponent(tag) {
9830 if (isBuiltInType(tag, 'Teleport')) {
9831 return TELEPORT;
9832 }
9833 else if (isBuiltInType(tag, 'Suspense')) {
9834 return SUSPENSE;
9835 }
9836 else if (isBuiltInType(tag, 'KeepAlive')) {
9837 return KEEP_ALIVE;
9838 }
9839 else if (isBuiltInType(tag, 'BaseTransition')) {
9840 return BASE_TRANSITION;
9841 }
9842 }
9843 const nonIdentifierRE = /^\d|[^\$\w]/;
9844 const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
9845 const memberExpRE = /^[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*(?:\s*\.\s*[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*|\[[^\]]+\])*$/;
9846 const isMemberExpression = (path) => {
9847 if (!path)
9848 return false;
9849 return memberExpRE.test(path.trim());
9850 };
9851 function getInnerRange(loc, offset, length) {
9852 const source = loc.source.substr(offset, length);
9853 const newLoc = {
9854 source,
9855 start: advancePositionWithClone(loc.start, loc.source, offset),
9856 end: loc.end
9857 };
9858 if (length != null) {
9859 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
9860 }
9861 return newLoc;
9862 }
9863 function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
9864 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
9865 }
9866 // advance by mutation without cloning (for performance reasons), since this
9867 // gets called a lot in the parser
9868 function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
9869 let linesCount = 0;
9870 let lastNewLinePos = -1;
9871 for (let i = 0; i < numberOfCharacters; i++) {
9872 if (source.charCodeAt(i) === 10 /* newline char code */) {
9873 linesCount++;
9874 lastNewLinePos = i;
9875 }
9876 }
9877 pos.offset += numberOfCharacters;
9878 pos.line += linesCount;
9879 pos.column =
9880 lastNewLinePos === -1
9881 ? pos.column + numberOfCharacters
9882 : numberOfCharacters - lastNewLinePos;
9883 return pos;
9884 }
9885 function assert(condition, msg) {
9886 /* istanbul ignore if */
9887 if (!condition) {
9888 throw new Error(msg || `unexpected compiler condition`);
9889 }
9890 }
9891 function findDir(node, name, allowEmpty = false) {
9892 for (let i = 0; i < node.props.length; i++) {
9893 const p = node.props[i];
9894 if (p.type === 7 /* DIRECTIVE */ &&
9895 (allowEmpty || p.exp) &&
9896 (isString(name) ? p.name === name : name.test(p.name))) {
9897 return p;
9898 }
9899 }
9900 }
9901 function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
9902 for (let i = 0; i < node.props.length; i++) {
9903 const p = node.props[i];
9904 if (p.type === 6 /* ATTRIBUTE */) {
9905 if (dynamicOnly)
9906 continue;
9907 if (p.name === name && (p.value || allowEmpty)) {
9908 return p;
9909 }
9910 }
9911 else if (p.name === 'bind' &&
9912 (p.exp || allowEmpty) &&
9913 isBindKey(p.arg, name)) {
9914 return p;
9915 }
9916 }
9917 }
9918 function isBindKey(arg, name) {
9919 return !!(arg && isStaticExp(arg) && arg.content === name);
9920 }
9921 function hasDynamicKeyVBind(node) {
9922 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
9923 p.name === 'bind' &&
9924 (!p.arg || // v-bind="obj"
9925 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
9926 !p.arg.isStatic) // v-bind:[foo]
9927 );
9928 }
9929 function isText(node) {
9930 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
9931 }
9932 function isVSlot(p) {
9933 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
9934 }
9935 function isTemplateNode(node) {
9936 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
9937 }
9938 function isSlotOutlet(node) {
9939 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
9940 }
9941 function injectProp(node, prop, context) {
9942 let propsWithInjection;
9943 const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
9944 if (props == null || isString(props)) {
9945 propsWithInjection = createObjectExpression([prop]);
9946 }
9947 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
9948 // merged props... add ours
9949 // only inject key to object literal if it's the first argument so that
9950 // if doesn't override user provided keys
9951 const first = props.arguments[0];
9952 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
9953 first.properties.unshift(prop);
9954 }
9955 else {
9956 if (props.callee === TO_HANDLERS) {
9957 // #2366
9958 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
9959 createObjectExpression([prop]),
9960 props
9961 ]);
9962 }
9963 else {
9964 props.arguments.unshift(createObjectExpression([prop]));
9965 }
9966 }
9967 !propsWithInjection && (propsWithInjection = props);
9968 }
9969 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
9970 let alreadyExists = false;
9971 // check existing key to avoid overriding user provided keys
9972 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
9973 const propKeyName = prop.key.content;
9974 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
9975 p.key.content === propKeyName);
9976 }
9977 if (!alreadyExists) {
9978 props.properties.unshift(prop);
9979 }
9980 propsWithInjection = props;
9981 }
9982 else {
9983 // single v-bind with expression, return a merged replacement
9984 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
9985 createObjectExpression([prop]),
9986 props
9987 ]);
9988 }
9989 if (node.type === 13 /* VNODE_CALL */) {
9990 node.props = propsWithInjection;
9991 }
9992 else {
9993 node.arguments[2] = propsWithInjection;
9994 }
9995 }
9996 function toValidAssetId(name, type) {
9997 return `_${type}_${name.replace(/[^\w]/g, '_')}`;
9998 }
9999
10000 // The default decoder only provides escapes for characters reserved as part of
10001 // the template syntax, and is only used if the custom renderer did not provide
10002 // a platform-specific decoder.
10003 const decodeRE = /&(gt|lt|amp|apos|quot);/g;
10004 const decodeMap = {
10005 gt: '>',
10006 lt: '<',
10007 amp: '&',
10008 apos: "'",
10009 quot: '"'
10010 };
10011 const defaultParserOptions = {
10012 delimiters: [`{{`, `}}`],
10013 getNamespace: () => 0 /* HTML */,
10014 getTextMode: () => 0 /* DATA */,
10015 isVoidTag: NO,
10016 isPreTag: NO,
10017 isCustomElement: NO,
10018 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
10019 onError: defaultOnError,
10020 comments: false
10021 };
10022 function baseParse(content, options = {}) {
10023 const context = createParserContext(content, options);
10024 const start = getCursor(context);
10025 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
10026 }
10027 function createParserContext(content, rawOptions) {
10028 const options = extend({}, defaultParserOptions);
10029 for (const key in rawOptions) {
10030 // @ts-ignore
10031 options[key] = rawOptions[key] || defaultParserOptions[key];
10032 }
10033 return {
10034 options,
10035 column: 1,
10036 line: 1,
10037 offset: 0,
10038 originalSource: content,
10039 source: content,
10040 inPre: false,
10041 inVPre: false
10042 };
10043 }
10044 function parseChildren(context, mode, ancestors) {
10045 const parent = last(ancestors);
10046 const ns = parent ? parent.ns : 0 /* HTML */;
10047 const nodes = [];
10048 while (!isEnd(context, mode, ancestors)) {
10049 const s = context.source;
10050 let node = undefined;
10051 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
10052 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
10053 // '{{'
10054 node = parseInterpolation(context, mode);
10055 }
10056 else if (mode === 0 /* DATA */ && s[0] === '<') {
10057 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
10058 if (s.length === 1) {
10059 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
10060 }
10061 else if (s[1] === '!') {
10062 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
10063 if (startsWith(s, '<!--')) {
10064 node = parseComment(context);
10065 }
10066 else if (startsWith(s, '<!DOCTYPE')) {
10067 // Ignore DOCTYPE by a limitation.
10068 node = parseBogusComment(context);
10069 }
10070 else if (startsWith(s, '<![CDATA[')) {
10071 if (ns !== 0 /* HTML */) {
10072 node = parseCDATA(context, ancestors);
10073 }
10074 else {
10075 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
10076 node = parseBogusComment(context);
10077 }
10078 }
10079 else {
10080 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
10081 node = parseBogusComment(context);
10082 }
10083 }
10084 else if (s[1] === '/') {
10085 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
10086 if (s.length === 2) {
10087 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
10088 }
10089 else if (s[2] === '>') {
10090 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
10091 advanceBy(context, 3);
10092 continue;
10093 }
10094 else if (/[a-z]/i.test(s[2])) {
10095 emitError(context, 23 /* X_INVALID_END_TAG */);
10096 parseTag(context, 1 /* End */, parent);
10097 continue;
10098 }
10099 else {
10100 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
10101 node = parseBogusComment(context);
10102 }
10103 }
10104 else if (/[a-z]/i.test(s[1])) {
10105 node = parseElement(context, ancestors);
10106 }
10107 else if (s[1] === '?') {
10108 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
10109 node = parseBogusComment(context);
10110 }
10111 else {
10112 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
10113 }
10114 }
10115 }
10116 if (!node) {
10117 node = parseText(context, mode);
10118 }
10119 if (isArray(node)) {
10120 for (let i = 0; i < node.length; i++) {
10121 pushNode(nodes, node[i]);
10122 }
10123 }
10124 else {
10125 pushNode(nodes, node);
10126 }
10127 }
10128 // Whitespace management for more efficient output
10129 // (same as v2 whitespace: 'condense')
10130 let removedWhitespace = false;
10131 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
10132 for (let i = 0; i < nodes.length; i++) {
10133 const node = nodes[i];
10134 if (!context.inPre && node.type === 2 /* TEXT */) {
10135 if (!/[^\t\r\n\f ]/.test(node.content)) {
10136 const prev = nodes[i - 1];
10137 const next = nodes[i + 1];
10138 // If:
10139 // - the whitespace is the first or last node, or:
10140 // - the whitespace is adjacent to a comment, or:
10141 // - the whitespace is between two elements AND contains newline
10142 // Then the whitespace is ignored.
10143 if (!prev ||
10144 !next ||
10145 prev.type === 3 /* COMMENT */ ||
10146 next.type === 3 /* COMMENT */ ||
10147 (prev.type === 1 /* ELEMENT */ &&
10148 next.type === 1 /* ELEMENT */ &&
10149 /[\r\n]/.test(node.content))) {
10150 removedWhitespace = true;
10151 nodes[i] = null;
10152 }
10153 else {
10154 // Otherwise, condensed consecutive whitespace inside the text
10155 // down to a single space
10156 node.content = ' ';
10157 }
10158 }
10159 else {
10160 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
10161 }
10162 }
10163 }
10164 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
10165 // remove leading newline per html spec
10166 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
10167 const first = nodes[0];
10168 if (first && first.type === 2 /* TEXT */) {
10169 first.content = first.content.replace(/^\r?\n/, '');
10170 }
10171 }
10172 }
10173 return removedWhitespace ? nodes.filter(Boolean) : nodes;
10174 }
10175 function pushNode(nodes, node) {
10176 if (node.type === 2 /* TEXT */) {
10177 const prev = last(nodes);
10178 // Merge if both this and the previous node are text and those are
10179 // consecutive. This happens for cases like "a < b".
10180 if (prev &&
10181 prev.type === 2 /* TEXT */ &&
10182 prev.loc.end.offset === node.loc.start.offset) {
10183 prev.content += node.content;
10184 prev.loc.end = node.loc.end;
10185 prev.loc.source += node.loc.source;
10186 return;
10187 }
10188 }
10189 nodes.push(node);
10190 }
10191 function parseCDATA(context, ancestors) {
10192 advanceBy(context, 9);
10193 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
10194 if (context.source.length === 0) {
10195 emitError(context, 6 /* EOF_IN_CDATA */);
10196 }
10197 else {
10198 advanceBy(context, 3);
10199 }
10200 return nodes;
10201 }
10202 function parseComment(context) {
10203 const start = getCursor(context);
10204 let content;
10205 // Regular comment.
10206 const match = /--(\!)?>/.exec(context.source);
10207 if (!match) {
10208 content = context.source.slice(4);
10209 advanceBy(context, context.source.length);
10210 emitError(context, 7 /* EOF_IN_COMMENT */);
10211 }
10212 else {
10213 if (match.index <= 3) {
10214 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
10215 }
10216 if (match[1]) {
10217 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
10218 }
10219 content = context.source.slice(4, match.index);
10220 // Advancing with reporting nested comments.
10221 const s = context.source.slice(0, match.index);
10222 let prevIndex = 1, nestedIndex = 0;
10223 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
10224 advanceBy(context, nestedIndex - prevIndex + 1);
10225 if (nestedIndex + 4 < s.length) {
10226 emitError(context, 16 /* NESTED_COMMENT */);
10227 }
10228 prevIndex = nestedIndex + 1;
10229 }
10230 advanceBy(context, match.index + match[0].length - prevIndex + 1);
10231 }
10232 return {
10233 type: 3 /* COMMENT */,
10234 content,
10235 loc: getSelection(context, start)
10236 };
10237 }
10238 function parseBogusComment(context) {
10239 const start = getCursor(context);
10240 const contentStart = context.source[1] === '?' ? 1 : 2;
10241 let content;
10242 const closeIndex = context.source.indexOf('>');
10243 if (closeIndex === -1) {
10244 content = context.source.slice(contentStart);
10245 advanceBy(context, context.source.length);
10246 }
10247 else {
10248 content = context.source.slice(contentStart, closeIndex);
10249 advanceBy(context, closeIndex + 1);
10250 }
10251 return {
10252 type: 3 /* COMMENT */,
10253 content,
10254 loc: getSelection(context, start)
10255 };
10256 }
10257 function parseElement(context, ancestors) {
10258 // Start tag.
10259 const wasInPre = context.inPre;
10260 const wasInVPre = context.inVPre;
10261 const parent = last(ancestors);
10262 const element = parseTag(context, 0 /* Start */, parent);
10263 const isPreBoundary = context.inPre && !wasInPre;
10264 const isVPreBoundary = context.inVPre && !wasInVPre;
10265 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
10266 return element;
10267 }
10268 // Children.
10269 ancestors.push(element);
10270 const mode = context.options.getTextMode(element, parent);
10271 const children = parseChildren(context, mode, ancestors);
10272 ancestors.pop();
10273 element.children = children;
10274 // End tag.
10275 if (startsWithEndTagOpen(context.source, element.tag)) {
10276 parseTag(context, 1 /* End */, parent);
10277 }
10278 else {
10279 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
10280 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
10281 const first = children[0];
10282 if (first && startsWith(first.loc.source, '<!--')) {
10283 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
10284 }
10285 }
10286 }
10287 element.loc = getSelection(context, element.loc.start);
10288 if (isPreBoundary) {
10289 context.inPre = false;
10290 }
10291 if (isVPreBoundary) {
10292 context.inVPre = false;
10293 }
10294 return element;
10295 }
10296 const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
10297 /**
10298 * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
10299 */
10300 function parseTag(context, type, parent) {
10301 // Tag open.
10302 const start = getCursor(context);
10303 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
10304 const tag = match[1];
10305 const ns = context.options.getNamespace(tag, parent);
10306 advanceBy(context, match[0].length);
10307 advanceSpaces(context);
10308 // save current state in case we need to re-parse attributes with v-pre
10309 const cursor = getCursor(context);
10310 const currentSource = context.source;
10311 // Attributes.
10312 let props = parseAttributes(context, type);
10313 // check <pre> tag
10314 if (context.options.isPreTag(tag)) {
10315 context.inPre = true;
10316 }
10317 // check v-pre
10318 if (!context.inVPre &&
10319 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
10320 context.inVPre = true;
10321 // reset context
10322 extend(context, cursor);
10323 context.source = currentSource;
10324 // re-parse attrs and filter out v-pre itself
10325 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
10326 }
10327 // Tag close.
10328 let isSelfClosing = false;
10329 if (context.source.length === 0) {
10330 emitError(context, 9 /* EOF_IN_TAG */);
10331 }
10332 else {
10333 isSelfClosing = startsWith(context.source, '/>');
10334 if (type === 1 /* End */ && isSelfClosing) {
10335 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
10336 }
10337 advanceBy(context, isSelfClosing ? 2 : 1);
10338 }
10339 let tagType = 0 /* ELEMENT */;
10340 const options = context.options;
10341 if (!context.inVPre && !options.isCustomElement(tag)) {
10342 const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
10343 if (options.isNativeTag && !hasVIs) {
10344 if (!options.isNativeTag(tag))
10345 tagType = 1 /* COMPONENT */;
10346 }
10347 else if (hasVIs ||
10348 isCoreComponent(tag) ||
10349 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
10350 /^[A-Z]/.test(tag) ||
10351 tag === 'component') {
10352 tagType = 1 /* COMPONENT */;
10353 }
10354 if (tag === 'slot') {
10355 tagType = 2 /* SLOT */;
10356 }
10357 else if (tag === 'template' &&
10358 props.some(p => {
10359 return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
10360 })) {
10361 tagType = 3 /* TEMPLATE */;
10362 }
10363 }
10364 return {
10365 type: 1 /* ELEMENT */,
10366 ns,
10367 tag,
10368 tagType,
10369 props,
10370 isSelfClosing,
10371 children: [],
10372 loc: getSelection(context, start),
10373 codegenNode: undefined // to be created during transform phase
10374 };
10375 }
10376 function parseAttributes(context, type) {
10377 const props = [];
10378 const attributeNames = new Set();
10379 while (context.source.length > 0 &&
10380 !startsWith(context.source, '>') &&
10381 !startsWith(context.source, '/>')) {
10382 if (startsWith(context.source, '/')) {
10383 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
10384 advanceBy(context, 1);
10385 advanceSpaces(context);
10386 continue;
10387 }
10388 if (type === 1 /* End */) {
10389 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
10390 }
10391 const attr = parseAttribute(context, attributeNames);
10392 if (type === 0 /* Start */) {
10393 props.push(attr);
10394 }
10395 if (/^[^\t\r\n\f />]/.test(context.source)) {
10396 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
10397 }
10398 advanceSpaces(context);
10399 }
10400 return props;
10401 }
10402 function parseAttribute(context, nameSet) {
10403 // Name.
10404 const start = getCursor(context);
10405 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
10406 const name = match[0];
10407 if (nameSet.has(name)) {
10408 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
10409 }
10410 nameSet.add(name);
10411 if (name[0] === '=') {
10412 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
10413 }
10414 {
10415 const pattern = /["'<]/g;
10416 let m;
10417 while ((m = pattern.exec(name))) {
10418 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
10419 }
10420 }
10421 advanceBy(context, name.length);
10422 // Value
10423 let value = undefined;
10424 if (/^[\t\r\n\f ]*=/.test(context.source)) {
10425 advanceSpaces(context);
10426 advanceBy(context, 1);
10427 advanceSpaces(context);
10428 value = parseAttributeValue(context);
10429 if (!value) {
10430 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
10431 }
10432 }
10433 const loc = getSelection(context, start);
10434 if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
10435 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
10436 const dirName = match[1] ||
10437 (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
10438 let arg;
10439 if (match[2]) {
10440 const isSlot = dirName === 'slot';
10441 const startOffset = name.lastIndexOf(match[2]);
10442 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
10443 let content = match[2];
10444 let isStatic = true;
10445 if (content.startsWith('[')) {
10446 isStatic = false;
10447 if (!content.endsWith(']')) {
10448 emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
10449 }
10450 content = content.substr(1, content.length - 2);
10451 }
10452 else if (isSlot) {
10453 // #1241 special case for v-slot: vuetify relies extensively on slot
10454 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
10455 // supports such usage so we are keeping it consistent with 2.x.
10456 content += match[3] || '';
10457 }
10458 arg = {
10459 type: 4 /* SIMPLE_EXPRESSION */,
10460 content,
10461 isStatic,
10462 constType: isStatic
10463 ? 3 /* CAN_STRINGIFY */
10464 : 0 /* NOT_CONSTANT */,
10465 loc
10466 };
10467 }
10468 if (value && value.isQuoted) {
10469 const valueLoc = value.loc;
10470 valueLoc.start.offset++;
10471 valueLoc.start.column++;
10472 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
10473 valueLoc.source = valueLoc.source.slice(1, -1);
10474 }
10475 return {
10476 type: 7 /* DIRECTIVE */,
10477 name: dirName,
10478 exp: value && {
10479 type: 4 /* SIMPLE_EXPRESSION */,
10480 content: value.content,
10481 isStatic: false,
10482 // Treat as non-constant by default. This can be potentially set to
10483 // other values by `transformExpression` to make it eligible for hoisting.
10484 constType: 0 /* NOT_CONSTANT */,
10485 loc: value.loc
10486 },
10487 arg,
10488 modifiers: match[3] ? match[3].substr(1).split('.') : [],
10489 loc
10490 };
10491 }
10492 return {
10493 type: 6 /* ATTRIBUTE */,
10494 name,
10495 value: value && {
10496 type: 2 /* TEXT */,
10497 content: value.content,
10498 loc: value.loc
10499 },
10500 loc
10501 };
10502 }
10503 function parseAttributeValue(context) {
10504 const start = getCursor(context);
10505 let content;
10506 const quote = context.source[0];
10507 const isQuoted = quote === `"` || quote === `'`;
10508 if (isQuoted) {
10509 // Quoted value.
10510 advanceBy(context, 1);
10511 const endIndex = context.source.indexOf(quote);
10512 if (endIndex === -1) {
10513 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
10514 }
10515 else {
10516 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
10517 advanceBy(context, 1);
10518 }
10519 }
10520 else {
10521 // Unquoted
10522 const match = /^[^\t\r\n\f >]+/.exec(context.source);
10523 if (!match) {
10524 return undefined;
10525 }
10526 const unexpectedChars = /["'<=`]/g;
10527 let m;
10528 while ((m = unexpectedChars.exec(match[0]))) {
10529 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
10530 }
10531 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
10532 }
10533 return { content, isQuoted, loc: getSelection(context, start) };
10534 }
10535 function parseInterpolation(context, mode) {
10536 const [open, close] = context.options.delimiters;
10537 const closeIndex = context.source.indexOf(close, open.length);
10538 if (closeIndex === -1) {
10539 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
10540 return undefined;
10541 }
10542 const start = getCursor(context);
10543 advanceBy(context, open.length);
10544 const innerStart = getCursor(context);
10545 const innerEnd = getCursor(context);
10546 const rawContentLength = closeIndex - open.length;
10547 const rawContent = context.source.slice(0, rawContentLength);
10548 const preTrimContent = parseTextData(context, rawContentLength, mode);
10549 const content = preTrimContent.trim();
10550 const startOffset = preTrimContent.indexOf(content);
10551 if (startOffset > 0) {
10552 advancePositionWithMutation(innerStart, rawContent, startOffset);
10553 }
10554 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
10555 advancePositionWithMutation(innerEnd, rawContent, endOffset);
10556 advanceBy(context, close.length);
10557 return {
10558 type: 5 /* INTERPOLATION */,
10559 content: {
10560 type: 4 /* SIMPLE_EXPRESSION */,
10561 isStatic: false,
10562 // Set `isConstant` to false by default and will decide in transformExpression
10563 constType: 0 /* NOT_CONSTANT */,
10564 content,
10565 loc: getSelection(context, innerStart, innerEnd)
10566 },
10567 loc: getSelection(context, start)
10568 };
10569 }
10570 function parseText(context, mode) {
10571 const endTokens = ['<', context.options.delimiters[0]];
10572 if (mode === 3 /* CDATA */) {
10573 endTokens.push(']]>');
10574 }
10575 let endIndex = context.source.length;
10576 for (let i = 0; i < endTokens.length; i++) {
10577 const index = context.source.indexOf(endTokens[i], 1);
10578 if (index !== -1 && endIndex > index) {
10579 endIndex = index;
10580 }
10581 }
10582 const start = getCursor(context);
10583 const content = parseTextData(context, endIndex, mode);
10584 return {
10585 type: 2 /* TEXT */,
10586 content,
10587 loc: getSelection(context, start)
10588 };
10589 }
10590 /**
10591 * Get text data with a given length from the current location.
10592 * This translates HTML entities in the text data.
10593 */
10594 function parseTextData(context, length, mode) {
10595 const rawText = context.source.slice(0, length);
10596 advanceBy(context, length);
10597 if (mode === 2 /* RAWTEXT */ ||
10598 mode === 3 /* CDATA */ ||
10599 rawText.indexOf('&') === -1) {
10600 return rawText;
10601 }
10602 else {
10603 // DATA or RCDATA containing "&"". Entity decoding required.
10604 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
10605 }
10606 }
10607 function getCursor(context) {
10608 const { column, line, offset } = context;
10609 return { column, line, offset };
10610 }
10611 function getSelection(context, start, end) {
10612 end = end || getCursor(context);
10613 return {
10614 start,
10615 end,
10616 source: context.originalSource.slice(start.offset, end.offset)
10617 };
10618 }
10619 function last(xs) {
10620 return xs[xs.length - 1];
10621 }
10622 function startsWith(source, searchString) {
10623 return source.startsWith(searchString);
10624 }
10625 function advanceBy(context, numberOfCharacters) {
10626 const { source } = context;
10627 advancePositionWithMutation(context, source, numberOfCharacters);
10628 context.source = source.slice(numberOfCharacters);
10629 }
10630 function advanceSpaces(context) {
10631 const match = /^[\t\r\n\f ]+/.exec(context.source);
10632 if (match) {
10633 advanceBy(context, match[0].length);
10634 }
10635 }
10636 function getNewPosition(context, start, numberOfCharacters) {
10637 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
10638 }
10639 function emitError(context, code, offset, loc = getCursor(context)) {
10640 if (offset) {
10641 loc.offset += offset;
10642 loc.column += offset;
10643 }
10644 context.options.onError(createCompilerError(code, {
10645 start: loc,
10646 end: loc,
10647 source: ''
10648 }));
10649 }
10650 function isEnd(context, mode, ancestors) {
10651 const s = context.source;
10652 switch (mode) {
10653 case 0 /* DATA */:
10654 if (startsWith(s, '</')) {
10655 // TODO: probably bad performance
10656 for (let i = ancestors.length - 1; i >= 0; --i) {
10657 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
10658 return true;
10659 }
10660 }
10661 }
10662 break;
10663 case 1 /* RCDATA */:
10664 case 2 /* RAWTEXT */: {
10665 const parent = last(ancestors);
10666 if (parent && startsWithEndTagOpen(s, parent.tag)) {
10667 return true;
10668 }
10669 break;
10670 }
10671 case 3 /* CDATA */:
10672 if (startsWith(s, ']]>')) {
10673 return true;
10674 }
10675 break;
10676 }
10677 return !s;
10678 }
10679 function startsWithEndTagOpen(source, tag) {
10680 return (startsWith(source, '</') &&
10681 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
10682 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
10683 }
10684
10685 function hoistStatic(root, context) {
10686 walk(root, context,
10687 // Root node is unfortunately non-hoistable due to potential parent
10688 // fallthrough attributes.
10689 isSingleElementRoot(root, root.children[0]));
10690 }
10691 function isSingleElementRoot(root, child) {
10692 const { children } = root;
10693 return (children.length === 1 &&
10694 child.type === 1 /* ELEMENT */ &&
10695 !isSlotOutlet(child));
10696 }
10697 function walk(node, context, doNotHoistNode = false) {
10698 let hasHoistedNode = false;
10699 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
10700 // static bindings with expressions. These expressions are guaranteed to be
10701 // constant so they are still eligible for hoisting, but they are only
10702 // available at runtime and therefore cannot be evaluated ahead of time.
10703 // This is only a concern for pre-stringification (via transformHoist by
10704 // @vue/compiler-dom), but doing it here allows us to perform only one full
10705 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
10706 // stringficiation threshold is met.
10707 let canStringify = true;
10708 const { children } = node;
10709 for (let i = 0; i < children.length; i++) {
10710 const child = children[i];
10711 // only plain elements & text calls are eligible for hoisting.
10712 if (child.type === 1 /* ELEMENT */ &&
10713 child.tagType === 0 /* ELEMENT */) {
10714 const constantType = doNotHoistNode
10715 ? 0 /* NOT_CONSTANT */
10716 : getConstantType(child, context);
10717 if (constantType > 0 /* NOT_CONSTANT */) {
10718 if (constantType < 3 /* CAN_STRINGIFY */) {
10719 canStringify = false;
10720 }
10721 if (constantType >= 2 /* CAN_HOIST */) {
10722 child.codegenNode.patchFlag =
10723 -1 /* HOISTED */ + (` /* HOISTED */` );
10724 child.codegenNode = context.hoist(child.codegenNode);
10725 hasHoistedNode = true;
10726 continue;
10727 }
10728 }
10729 else {
10730 // node may contain dynamic children, but its props may be eligible for
10731 // hoisting.
10732 const codegenNode = child.codegenNode;
10733 if (codegenNode.type === 13 /* VNODE_CALL */) {
10734 const flag = getPatchFlag(codegenNode);
10735 if ((!flag ||
10736 flag === 512 /* NEED_PATCH */ ||
10737 flag === 1 /* TEXT */) &&
10738 getGeneratedPropsConstantType(child, context) >=
10739 2 /* CAN_HOIST */) {
10740 const props = getNodeProps(child);
10741 if (props) {
10742 codegenNode.props = context.hoist(props);
10743 }
10744 }
10745 }
10746 }
10747 }
10748 else if (child.type === 12 /* TEXT_CALL */) {
10749 const contentType = getConstantType(child.content, context);
10750 if (contentType > 0) {
10751 if (contentType < 3 /* CAN_STRINGIFY */) {
10752 canStringify = false;
10753 }
10754 if (contentType >= 2 /* CAN_HOIST */) {
10755 child.codegenNode = context.hoist(child.codegenNode);
10756 hasHoistedNode = true;
10757 }
10758 }
10759 }
10760 // walk further
10761 if (child.type === 1 /* ELEMENT */) {
10762 const isComponent = child.tagType === 1 /* COMPONENT */;
10763 if (isComponent) {
10764 context.scopes.vSlot++;
10765 }
10766 walk(child, context);
10767 if (isComponent) {
10768 context.scopes.vSlot--;
10769 }
10770 }
10771 else if (child.type === 11 /* FOR */) {
10772 // Do not hoist v-for single child because it has to be a block
10773 walk(child, context, child.children.length === 1);
10774 }
10775 else if (child.type === 9 /* IF */) {
10776 for (let i = 0; i < child.branches.length; i++) {
10777 // Do not hoist v-if single child because it has to be a block
10778 walk(child.branches[i], context, child.branches[i].children.length === 1);
10779 }
10780 }
10781 }
10782 if (canStringify && hasHoistedNode && context.transformHoist) {
10783 context.transformHoist(children, context, node);
10784 }
10785 }
10786 function getConstantType(node, context) {
10787 const { constantCache } = context;
10788 switch (node.type) {
10789 case 1 /* ELEMENT */:
10790 if (node.tagType !== 0 /* ELEMENT */) {
10791 return 0 /* NOT_CONSTANT */;
10792 }
10793 const cached = constantCache.get(node);
10794 if (cached !== undefined) {
10795 return cached;
10796 }
10797 const codegenNode = node.codegenNode;
10798 if (codegenNode.type !== 13 /* VNODE_CALL */) {
10799 return 0 /* NOT_CONSTANT */;
10800 }
10801 const flag = getPatchFlag(codegenNode);
10802 if (!flag) {
10803 let returnType = 3 /* CAN_STRINGIFY */;
10804 // Element itself has no patch flag. However we still need to check:
10805 // 1. Even for a node with no patch flag, it is possible for it to contain
10806 // non-hoistable expressions that refers to scope variables, e.g. compiler
10807 // injected keys or cached event handlers. Therefore we need to always
10808 // check the codegenNode's props to be sure.
10809 const generatedPropsType = getGeneratedPropsConstantType(node, context);
10810 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
10811 constantCache.set(node, 0 /* NOT_CONSTANT */);
10812 return 0 /* NOT_CONSTANT */;
10813 }
10814 if (generatedPropsType < returnType) {
10815 returnType = generatedPropsType;
10816 }
10817 // 2. its children.
10818 for (let i = 0; i < node.children.length; i++) {
10819 const childType = getConstantType(node.children[i], context);
10820 if (childType === 0 /* NOT_CONSTANT */) {
10821 constantCache.set(node, 0 /* NOT_CONSTANT */);
10822 return 0 /* NOT_CONSTANT */;
10823 }
10824 if (childType < returnType) {
10825 returnType = childType;
10826 }
10827 }
10828 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
10829 // type, check if any of the props can cause the type to be lowered
10830 // we can skip can_patch because it's guaranteed by the absence of a
10831 // patchFlag.
10832 if (returnType > 1 /* CAN_SKIP_PATCH */) {
10833 for (let i = 0; i < node.props.length; i++) {
10834 const p = node.props[i];
10835 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
10836 const expType = getConstantType(p.exp, context);
10837 if (expType === 0 /* NOT_CONSTANT */) {
10838 constantCache.set(node, 0 /* NOT_CONSTANT */);
10839 return 0 /* NOT_CONSTANT */;
10840 }
10841 if (expType < returnType) {
10842 returnType = expType;
10843 }
10844 }
10845 }
10846 }
10847 // only svg/foreignObject could be block here, however if they are
10848 // static then they don't need to be blocks since there will be no
10849 // nested updates.
10850 if (codegenNode.isBlock) {
10851 context.removeHelper(OPEN_BLOCK);
10852 context.removeHelper(CREATE_BLOCK);
10853 codegenNode.isBlock = false;
10854 context.helper(CREATE_VNODE);
10855 }
10856 constantCache.set(node, returnType);
10857 return returnType;
10858 }
10859 else {
10860 constantCache.set(node, 0 /* NOT_CONSTANT */);
10861 return 0 /* NOT_CONSTANT */;
10862 }
10863 case 2 /* TEXT */:
10864 case 3 /* COMMENT */:
10865 return 3 /* CAN_STRINGIFY */;
10866 case 9 /* IF */:
10867 case 11 /* FOR */:
10868 case 10 /* IF_BRANCH */:
10869 return 0 /* NOT_CONSTANT */;
10870 case 5 /* INTERPOLATION */:
10871 case 12 /* TEXT_CALL */:
10872 return getConstantType(node.content, context);
10873 case 4 /* SIMPLE_EXPRESSION */:
10874 return node.constType;
10875 case 8 /* COMPOUND_EXPRESSION */:
10876 let returnType = 3 /* CAN_STRINGIFY */;
10877 for (let i = 0; i < node.children.length; i++) {
10878 const child = node.children[i];
10879 if (isString(child) || isSymbol(child)) {
10880 continue;
10881 }
10882 const childType = getConstantType(child, context);
10883 if (childType === 0 /* NOT_CONSTANT */) {
10884 return 0 /* NOT_CONSTANT */;
10885 }
10886 else if (childType < returnType) {
10887 returnType = childType;
10888 }
10889 }
10890 return returnType;
10891 default:
10892 return 0 /* NOT_CONSTANT */;
10893 }
10894 }
10895 function getGeneratedPropsConstantType(node, context) {
10896 let returnType = 3 /* CAN_STRINGIFY */;
10897 const props = getNodeProps(node);
10898 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
10899 const { properties } = props;
10900 for (let i = 0; i < properties.length; i++) {
10901 const { key, value } = properties[i];
10902 const keyType = getConstantType(key, context);
10903 if (keyType === 0 /* NOT_CONSTANT */) {
10904 return keyType;
10905 }
10906 if (keyType < returnType) {
10907 returnType = keyType;
10908 }
10909 if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
10910 return 0 /* NOT_CONSTANT */;
10911 }
10912 const valueType = getConstantType(value, context);
10913 if (valueType === 0 /* NOT_CONSTANT */) {
10914 return valueType;
10915 }
10916 if (valueType < returnType) {
10917 returnType = valueType;
10918 }
10919 }
10920 }
10921 return returnType;
10922 }
10923 function getNodeProps(node) {
10924 const codegenNode = node.codegenNode;
10925 if (codegenNode.type === 13 /* VNODE_CALL */) {
10926 return codegenNode.props;
10927 }
10928 }
10929 function getPatchFlag(node) {
10930 const flag = node.patchFlag;
10931 return flag ? parseInt(flag, 10) : undefined;
10932 }
10933
10934 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, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
10935 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
10936 const context = {
10937 // options
10938 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
10939 prefixIdentifiers,
10940 hoistStatic,
10941 cacheHandlers,
10942 nodeTransforms,
10943 directiveTransforms,
10944 transformHoist,
10945 isBuiltInComponent,
10946 isCustomElement,
10947 expressionPlugins,
10948 scopeId,
10949 slotted,
10950 ssr,
10951 ssrCssVars,
10952 bindingMetadata,
10953 inline,
10954 isTS,
10955 onError,
10956 // state
10957 root,
10958 helpers: new Map(),
10959 components: new Set(),
10960 directives: new Set(),
10961 hoists: [],
10962 imports: [],
10963 constantCache: new Map(),
10964 temps: 0,
10965 cached: 0,
10966 identifiers: Object.create(null),
10967 scopes: {
10968 vFor: 0,
10969 vSlot: 0,
10970 vPre: 0,
10971 vOnce: 0
10972 },
10973 parent: null,
10974 currentNode: root,
10975 childIndex: 0,
10976 // methods
10977 helper(name) {
10978 const count = context.helpers.get(name) || 0;
10979 context.helpers.set(name, count + 1);
10980 return name;
10981 },
10982 removeHelper(name) {
10983 const count = context.helpers.get(name);
10984 if (count) {
10985 const currentCount = count - 1;
10986 if (!currentCount) {
10987 context.helpers.delete(name);
10988 }
10989 else {
10990 context.helpers.set(name, currentCount);
10991 }
10992 }
10993 },
10994 helperString(name) {
10995 return `_${helperNameMap[context.helper(name)]}`;
10996 },
10997 replaceNode(node) {
10998 /* istanbul ignore if */
10999 {
11000 if (!context.currentNode) {
11001 throw new Error(`Node being replaced is already removed.`);
11002 }
11003 if (!context.parent) {
11004 throw new Error(`Cannot replace root node.`);
11005 }
11006 }
11007 context.parent.children[context.childIndex] = context.currentNode = node;
11008 },
11009 removeNode(node) {
11010 if (!context.parent) {
11011 throw new Error(`Cannot remove root node.`);
11012 }
11013 const list = context.parent.children;
11014 const removalIndex = node
11015 ? list.indexOf(node)
11016 : context.currentNode
11017 ? context.childIndex
11018 : -1;
11019 /* istanbul ignore if */
11020 if (removalIndex < 0) {
11021 throw new Error(`node being removed is not a child of current parent`);
11022 }
11023 if (!node || node === context.currentNode) {
11024 // current node removed
11025 context.currentNode = null;
11026 context.onNodeRemoved();
11027 }
11028 else {
11029 // sibling node removed
11030 if (context.childIndex > removalIndex) {
11031 context.childIndex--;
11032 context.onNodeRemoved();
11033 }
11034 }
11035 context.parent.children.splice(removalIndex, 1);
11036 },
11037 onNodeRemoved: () => { },
11038 addIdentifiers(exp) {
11039 },
11040 removeIdentifiers(exp) {
11041 },
11042 hoist(exp) {
11043 context.hoists.push(exp);
11044 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
11045 identifier.hoisted = exp;
11046 return identifier;
11047 },
11048 cache(exp, isVNode = false) {
11049 return createCacheExpression(++context.cached, exp, isVNode);
11050 }
11051 };
11052 return context;
11053 }
11054 function transform(root, options) {
11055 const context = createTransformContext(root, options);
11056 traverseNode(root, context);
11057 if (options.hoistStatic) {
11058 hoistStatic(root, context);
11059 }
11060 if (!options.ssr) {
11061 createRootCodegen(root, context);
11062 }
11063 // finalize meta information
11064 root.helpers = [...context.helpers.keys()];
11065 root.components = [...context.components];
11066 root.directives = [...context.directives];
11067 root.imports = context.imports;
11068 root.hoists = context.hoists;
11069 root.temps = context.temps;
11070 root.cached = context.cached;
11071 }
11072 function createRootCodegen(root, context) {
11073 const { helper, removeHelper } = context;
11074 const { children } = root;
11075 if (children.length === 1) {
11076 const child = children[0];
11077 // if the single child is an element, turn it into a block.
11078 if (isSingleElementRoot(root, child) && child.codegenNode) {
11079 // single element root is never hoisted so codegenNode will never be
11080 // SimpleExpressionNode
11081 const codegenNode = child.codegenNode;
11082 if (codegenNode.type === 13 /* VNODE_CALL */) {
11083 if (!codegenNode.isBlock) {
11084 removeHelper(CREATE_VNODE);
11085 codegenNode.isBlock = true;
11086 helper(OPEN_BLOCK);
11087 helper(CREATE_BLOCK);
11088 }
11089 }
11090 root.codegenNode = codegenNode;
11091 }
11092 else {
11093 // - single <slot/>, IfNode, ForNode: already blocks.
11094 // - single text node: always patched.
11095 // root codegen falls through via genNode()
11096 root.codegenNode = child;
11097 }
11098 }
11099 else if (children.length > 1) {
11100 // root has multiple nodes - return a fragment block.
11101 let patchFlag = 64 /* STABLE_FRAGMENT */;
11102 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
11103 // check if the fragment actually contains a single valid child with
11104 // the rest being comments
11105 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
11106 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
11107 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
11108 }
11109 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
11110 }
11111 else ;
11112 }
11113 function traverseChildren(parent, context) {
11114 let i = 0;
11115 const nodeRemoved = () => {
11116 i--;
11117 };
11118 for (; i < parent.children.length; i++) {
11119 const child = parent.children[i];
11120 if (isString(child))
11121 continue;
11122 context.parent = parent;
11123 context.childIndex = i;
11124 context.onNodeRemoved = nodeRemoved;
11125 traverseNode(child, context);
11126 }
11127 }
11128 function traverseNode(node, context) {
11129 context.currentNode = node;
11130 // apply transform plugins
11131 const { nodeTransforms } = context;
11132 const exitFns = [];
11133 for (let i = 0; i < nodeTransforms.length; i++) {
11134 const onExit = nodeTransforms[i](node, context);
11135 if (onExit) {
11136 if (isArray(onExit)) {
11137 exitFns.push(...onExit);
11138 }
11139 else {
11140 exitFns.push(onExit);
11141 }
11142 }
11143 if (!context.currentNode) {
11144 // node was removed
11145 return;
11146 }
11147 else {
11148 // node may have been replaced
11149 node = context.currentNode;
11150 }
11151 }
11152 switch (node.type) {
11153 case 3 /* COMMENT */:
11154 if (!context.ssr) {
11155 // inject import for the Comment symbol, which is needed for creating
11156 // comment nodes with `createVNode`
11157 context.helper(CREATE_COMMENT);
11158 }
11159 break;
11160 case 5 /* INTERPOLATION */:
11161 // no need to traverse, but we need to inject toString helper
11162 if (!context.ssr) {
11163 context.helper(TO_DISPLAY_STRING);
11164 }
11165 break;
11166 // for container types, further traverse downwards
11167 case 9 /* IF */:
11168 for (let i = 0; i < node.branches.length; i++) {
11169 traverseNode(node.branches[i], context);
11170 }
11171 break;
11172 case 10 /* IF_BRANCH */:
11173 case 11 /* FOR */:
11174 case 1 /* ELEMENT */:
11175 case 0 /* ROOT */:
11176 traverseChildren(node, context);
11177 break;
11178 }
11179 // exit transforms
11180 context.currentNode = node;
11181 let i = exitFns.length;
11182 while (i--) {
11183 exitFns[i]();
11184 }
11185 }
11186 function createStructuralDirectiveTransform(name, fn) {
11187 const matches = isString(name)
11188 ? (n) => n === name
11189 : (n) => name.test(n);
11190 return (node, context) => {
11191 if (node.type === 1 /* ELEMENT */) {
11192 const { props } = node;
11193 // structural directive transforms are not concerned with slots
11194 // as they are handled separately in vSlot.ts
11195 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
11196 return;
11197 }
11198 const exitFns = [];
11199 for (let i = 0; i < props.length; i++) {
11200 const prop = props[i];
11201 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
11202 // structural directives are removed to avoid infinite recursion
11203 // also we remove them *before* applying so that it can further
11204 // traverse itself in case it moves the node around
11205 props.splice(i, 1);
11206 i--;
11207 const onExit = fn(node, prop, context);
11208 if (onExit)
11209 exitFns.push(onExit);
11210 }
11211 }
11212 return exitFns;
11213 }
11214 };
11215 }
11216
11217 const PURE_ANNOTATION = `/*#__PURE__*/`;
11218 function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
11219 const context = {
11220 mode,
11221 prefixIdentifiers,
11222 sourceMap,
11223 filename,
11224 scopeId,
11225 optimizeImports,
11226 runtimeGlobalName,
11227 runtimeModuleName,
11228 ssr,
11229 source: ast.loc.source,
11230 code: ``,
11231 column: 1,
11232 line: 1,
11233 offset: 0,
11234 indentLevel: 0,
11235 pure: false,
11236 map: undefined,
11237 helper(key) {
11238 return `_${helperNameMap[key]}`;
11239 },
11240 push(code, node) {
11241 context.code += code;
11242 },
11243 indent() {
11244 newline(++context.indentLevel);
11245 },
11246 deindent(withoutNewLine = false) {
11247 if (withoutNewLine) {
11248 --context.indentLevel;
11249 }
11250 else {
11251 newline(--context.indentLevel);
11252 }
11253 },
11254 newline() {
11255 newline(context.indentLevel);
11256 }
11257 };
11258 function newline(n) {
11259 context.push('\n' + ` `.repeat(n));
11260 }
11261 return context;
11262 }
11263 function generate(ast, options = {}) {
11264 const context = createCodegenContext(ast, options);
11265 if (options.onContextCreated)
11266 options.onContextCreated(context);
11267 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
11268 const hasHelpers = ast.helpers.length > 0;
11269 const useWithBlock = !prefixIdentifiers && mode !== 'module';
11270 // preambles
11271 // in setup() inline mode, the preamble is generated in a sub context
11272 // and returned separately.
11273 const preambleContext = context;
11274 {
11275 genFunctionPreamble(ast, preambleContext);
11276 }
11277 // enter render function
11278 const functionName = ssr ? `ssrRender` : `render`;
11279 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
11280 const signature = args.join(', ');
11281 {
11282 push(`function ${functionName}(${signature}) {`);
11283 }
11284 indent();
11285 if (useWithBlock) {
11286 push(`with (_ctx) {`);
11287 indent();
11288 // function mode const declarations should be inside with block
11289 // also they should be renamed to avoid collision with user properties
11290 if (hasHelpers) {
11291 push(`const { ${ast.helpers
11292 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
11293 .join(', ')} } = _Vue`);
11294 push(`\n`);
11295 newline();
11296 }
11297 }
11298 // generate asset resolution statements
11299 if (ast.components.length) {
11300 genAssets(ast.components, 'component', context);
11301 if (ast.directives.length || ast.temps > 0) {
11302 newline();
11303 }
11304 }
11305 if (ast.directives.length) {
11306 genAssets(ast.directives, 'directive', context);
11307 if (ast.temps > 0) {
11308 newline();
11309 }
11310 }
11311 if (ast.temps > 0) {
11312 push(`let `);
11313 for (let i = 0; i < ast.temps; i++) {
11314 push(`${i > 0 ? `, ` : ``}_temp${i}`);
11315 }
11316 }
11317 if (ast.components.length || ast.directives.length || ast.temps) {
11318 push(`\n`);
11319 newline();
11320 }
11321 // generate the VNode tree expression
11322 if (!ssr) {
11323 push(`return `);
11324 }
11325 if (ast.codegenNode) {
11326 genNode(ast.codegenNode, context);
11327 }
11328 else {
11329 push(`null`);
11330 }
11331 if (useWithBlock) {
11332 deindent();
11333 push(`}`);
11334 }
11335 deindent();
11336 push(`}`);
11337 return {
11338 ast,
11339 code: context.code,
11340 preamble: ``,
11341 // SourceMapGenerator does have toJSON() method but it's not in the types
11342 map: context.map ? context.map.toJSON() : undefined
11343 };
11344 }
11345 function genFunctionPreamble(ast, context) {
11346 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
11347 const VueBinding = runtimeGlobalName;
11348 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
11349 // Generate const declaration for helpers
11350 // In prefix mode, we place the const declaration at top so it's done
11351 // only once; But if we not prefixing, we place the declaration inside the
11352 // with block so it doesn't incur the `in` check cost for every helper access.
11353 if (ast.helpers.length > 0) {
11354 {
11355 // "with" mode.
11356 // save Vue in a separate variable to avoid collision
11357 push(`const _Vue = ${VueBinding}\n`);
11358 // in "with" mode, helpers are declared inside the with block to avoid
11359 // has check cost, but hoists are lifted out of the function - we need
11360 // to provide the helper here.
11361 if (ast.hoists.length) {
11362 const staticHelpers = [
11363 CREATE_VNODE,
11364 CREATE_COMMENT,
11365 CREATE_TEXT,
11366 CREATE_STATIC
11367 ]
11368 .filter(helper => ast.helpers.includes(helper))
11369 .map(aliasHelper)
11370 .join(', ');
11371 push(`const { ${staticHelpers} } = _Vue\n`);
11372 }
11373 }
11374 }
11375 genHoists(ast.hoists, context);
11376 newline();
11377 push(`return `);
11378 }
11379 function genAssets(assets, type, { helper, push, newline }) {
11380 const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
11381 for (let i = 0; i < assets.length; i++) {
11382 let id = assets[i];
11383 // potential component implicit self-reference inferred from SFC filename
11384 const maybeSelfReference = id.endsWith('__self');
11385 if (maybeSelfReference) {
11386 id = id.slice(0, -6);
11387 }
11388 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})`);
11389 if (i < assets.length - 1) {
11390 newline();
11391 }
11392 }
11393 }
11394 function genHoists(hoists, context) {
11395 if (!hoists.length) {
11396 return;
11397 }
11398 context.pure = true;
11399 const { push, newline, helper, scopeId, mode } = context;
11400 newline();
11401 hoists.forEach((exp, i) => {
11402 if (exp) {
11403 push(`const _hoisted_${i + 1} = `);
11404 genNode(exp, context);
11405 newline();
11406 }
11407 });
11408 context.pure = false;
11409 }
11410 function isText$1(n) {
11411 return (isString(n) ||
11412 n.type === 4 /* SIMPLE_EXPRESSION */ ||
11413 n.type === 2 /* TEXT */ ||
11414 n.type === 5 /* INTERPOLATION */ ||
11415 n.type === 8 /* COMPOUND_EXPRESSION */);
11416 }
11417 function genNodeListAsArray(nodes, context) {
11418 const multilines = nodes.length > 3 ||
11419 (nodes.some(n => isArray(n) || !isText$1(n)));
11420 context.push(`[`);
11421 multilines && context.indent();
11422 genNodeList(nodes, context, multilines);
11423 multilines && context.deindent();
11424 context.push(`]`);
11425 }
11426 function genNodeList(nodes, context, multilines = false, comma = true) {
11427 const { push, newline } = context;
11428 for (let i = 0; i < nodes.length; i++) {
11429 const node = nodes[i];
11430 if (isString(node)) {
11431 push(node);
11432 }
11433 else if (isArray(node)) {
11434 genNodeListAsArray(node, context);
11435 }
11436 else {
11437 genNode(node, context);
11438 }
11439 if (i < nodes.length - 1) {
11440 if (multilines) {
11441 comma && push(',');
11442 newline();
11443 }
11444 else {
11445 comma && push(', ');
11446 }
11447 }
11448 }
11449 }
11450 function genNode(node, context) {
11451 if (isString(node)) {
11452 context.push(node);
11453 return;
11454 }
11455 if (isSymbol(node)) {
11456 context.push(context.helper(node));
11457 return;
11458 }
11459 switch (node.type) {
11460 case 1 /* ELEMENT */:
11461 case 9 /* IF */:
11462 case 11 /* FOR */:
11463 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
11464 `Apply appropriate transforms first.`);
11465 genNode(node.codegenNode, context);
11466 break;
11467 case 2 /* TEXT */:
11468 genText(node, context);
11469 break;
11470 case 4 /* SIMPLE_EXPRESSION */:
11471 genExpression(node, context);
11472 break;
11473 case 5 /* INTERPOLATION */:
11474 genInterpolation(node, context);
11475 break;
11476 case 12 /* TEXT_CALL */:
11477 genNode(node.codegenNode, context);
11478 break;
11479 case 8 /* COMPOUND_EXPRESSION */:
11480 genCompoundExpression(node, context);
11481 break;
11482 case 3 /* COMMENT */:
11483 genComment(node, context);
11484 break;
11485 case 13 /* VNODE_CALL */:
11486 genVNodeCall(node, context);
11487 break;
11488 case 14 /* JS_CALL_EXPRESSION */:
11489 genCallExpression(node, context);
11490 break;
11491 case 15 /* JS_OBJECT_EXPRESSION */:
11492 genObjectExpression(node, context);
11493 break;
11494 case 17 /* JS_ARRAY_EXPRESSION */:
11495 genArrayExpression(node, context);
11496 break;
11497 case 18 /* JS_FUNCTION_EXPRESSION */:
11498 genFunctionExpression(node, context);
11499 break;
11500 case 19 /* JS_CONDITIONAL_EXPRESSION */:
11501 genConditionalExpression(node, context);
11502 break;
11503 case 20 /* JS_CACHE_EXPRESSION */:
11504 genCacheExpression(node, context);
11505 break;
11506 // SSR only types
11507 case 21 /* JS_BLOCK_STATEMENT */:
11508 break;
11509 case 22 /* JS_TEMPLATE_LITERAL */:
11510 break;
11511 case 23 /* JS_IF_STATEMENT */:
11512 break;
11513 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
11514 break;
11515 case 25 /* JS_SEQUENCE_EXPRESSION */:
11516 break;
11517 case 26 /* JS_RETURN_STATEMENT */:
11518 break;
11519 /* istanbul ignore next */
11520 case 10 /* IF_BRANCH */:
11521 // noop
11522 break;
11523 default:
11524 {
11525 assert(false, `unhandled codegen node type: ${node.type}`);
11526 // make sure we exhaust all possible types
11527 const exhaustiveCheck = node;
11528 return exhaustiveCheck;
11529 }
11530 }
11531 }
11532 function genText(node, context) {
11533 context.push(JSON.stringify(node.content), node);
11534 }
11535 function genExpression(node, context) {
11536 const { content, isStatic } = node;
11537 context.push(isStatic ? JSON.stringify(content) : content, node);
11538 }
11539 function genInterpolation(node, context) {
11540 const { push, helper, pure } = context;
11541 if (pure)
11542 push(PURE_ANNOTATION);
11543 push(`${helper(TO_DISPLAY_STRING)}(`);
11544 genNode(node.content, context);
11545 push(`)`);
11546 }
11547 function genCompoundExpression(node, context) {
11548 for (let i = 0; i < node.children.length; i++) {
11549 const child = node.children[i];
11550 if (isString(child)) {
11551 context.push(child);
11552 }
11553 else {
11554 genNode(child, context);
11555 }
11556 }
11557 }
11558 function genExpressionAsPropertyKey(node, context) {
11559 const { push } = context;
11560 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
11561 push(`[`);
11562 genCompoundExpression(node, context);
11563 push(`]`);
11564 }
11565 else if (node.isStatic) {
11566 // only quote keys if necessary
11567 const text = isSimpleIdentifier(node.content)
11568 ? node.content
11569 : JSON.stringify(node.content);
11570 push(text, node);
11571 }
11572 else {
11573 push(`[${node.content}]`, node);
11574 }
11575 }
11576 function genComment(node, context) {
11577 {
11578 const { push, helper, pure } = context;
11579 if (pure) {
11580 push(PURE_ANNOTATION);
11581 }
11582 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
11583 }
11584 }
11585 function genVNodeCall(node, context) {
11586 const { push, helper, pure } = context;
11587 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
11588 if (directives) {
11589 push(helper(WITH_DIRECTIVES) + `(`);
11590 }
11591 if (isBlock) {
11592 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
11593 }
11594 if (pure) {
11595 push(PURE_ANNOTATION);
11596 }
11597 push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
11598 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
11599 push(`)`);
11600 if (isBlock) {
11601 push(`)`);
11602 }
11603 if (directives) {
11604 push(`, `);
11605 genNode(directives, context);
11606 push(`)`);
11607 }
11608 }
11609 function genNullableArgs(args) {
11610 let i = args.length;
11611 while (i--) {
11612 if (args[i] != null)
11613 break;
11614 }
11615 return args.slice(0, i + 1).map(arg => arg || `null`);
11616 }
11617 // JavaScript
11618 function genCallExpression(node, context) {
11619 const { push, helper, pure } = context;
11620 const callee = isString(node.callee) ? node.callee : helper(node.callee);
11621 if (pure) {
11622 push(PURE_ANNOTATION);
11623 }
11624 push(callee + `(`, node);
11625 genNodeList(node.arguments, context);
11626 push(`)`);
11627 }
11628 function genObjectExpression(node, context) {
11629 const { push, indent, deindent, newline } = context;
11630 const { properties } = node;
11631 if (!properties.length) {
11632 push(`{}`, node);
11633 return;
11634 }
11635 const multilines = properties.length > 1 ||
11636 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
11637 push(multilines ? `{` : `{ `);
11638 multilines && indent();
11639 for (let i = 0; i < properties.length; i++) {
11640 const { key, value } = properties[i];
11641 // key
11642 genExpressionAsPropertyKey(key, context);
11643 push(`: `);
11644 // value
11645 genNode(value, context);
11646 if (i < properties.length - 1) {
11647 // will only reach this if it's multilines
11648 push(`,`);
11649 newline();
11650 }
11651 }
11652 multilines && deindent();
11653 push(multilines ? `}` : ` }`);
11654 }
11655 function genArrayExpression(node, context) {
11656 genNodeListAsArray(node.elements, context);
11657 }
11658 function genFunctionExpression(node, context) {
11659 const { push, indent, deindent, scopeId, mode } = context;
11660 const { params, returns, body, newline, isSlot } = node;
11661 if (isSlot) {
11662 // wrap slot functions with owner context
11663 push(`_${helperNameMap[WITH_CTX]}(`);
11664 }
11665 push(`(`, node);
11666 if (isArray(params)) {
11667 genNodeList(params, context);
11668 }
11669 else if (params) {
11670 genNode(params, context);
11671 }
11672 push(`) => `);
11673 if (newline || body) {
11674 push(`{`);
11675 indent();
11676 }
11677 if (returns) {
11678 if (newline) {
11679 push(`return `);
11680 }
11681 if (isArray(returns)) {
11682 genNodeListAsArray(returns, context);
11683 }
11684 else {
11685 genNode(returns, context);
11686 }
11687 }
11688 else if (body) {
11689 genNode(body, context);
11690 }
11691 if (newline || body) {
11692 deindent();
11693 push(`}`);
11694 }
11695 if (isSlot) {
11696 push(`)`);
11697 }
11698 }
11699 function genConditionalExpression(node, context) {
11700 const { test, consequent, alternate, newline: needNewline } = node;
11701 const { push, indent, deindent, newline } = context;
11702 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
11703 const needsParens = !isSimpleIdentifier(test.content);
11704 needsParens && push(`(`);
11705 genExpression(test, context);
11706 needsParens && push(`)`);
11707 }
11708 else {
11709 push(`(`);
11710 genNode(test, context);
11711 push(`)`);
11712 }
11713 needNewline && indent();
11714 context.indentLevel++;
11715 needNewline || push(` `);
11716 push(`? `);
11717 genNode(consequent, context);
11718 context.indentLevel--;
11719 needNewline && newline();
11720 needNewline || push(` `);
11721 push(`: `);
11722 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
11723 if (!isNested) {
11724 context.indentLevel++;
11725 }
11726 genNode(alternate, context);
11727 if (!isNested) {
11728 context.indentLevel--;
11729 }
11730 needNewline && deindent(true /* without newline */);
11731 }
11732 function genCacheExpression(node, context) {
11733 const { push, helper, indent, deindent, newline } = context;
11734 push(`_cache[${node.index}] || (`);
11735 if (node.isVNode) {
11736 indent();
11737 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
11738 newline();
11739 }
11740 push(`_cache[${node.index}] = `);
11741 genNode(node.value, context);
11742 if (node.isVNode) {
11743 push(`,`);
11744 newline();
11745 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
11746 newline();
11747 push(`_cache[${node.index}]`);
11748 deindent();
11749 }
11750 push(`)`);
11751 }
11752
11753 // these keywords should not appear inside expressions, but operators like
11754 // typeof, instanceof and in are allowed
11755 const prohibitedKeywordRE = new RegExp('\\b' +
11756 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
11757 'super,throw,while,yield,delete,export,import,return,switch,default,' +
11758 'extends,finally,continue,debugger,function,arguments,typeof,void')
11759 .split(',')
11760 .join('\\b|\\b') +
11761 '\\b');
11762 // strip strings in expressions
11763 const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
11764 /**
11765 * Validate a non-prefixed expression.
11766 * This is only called when using the in-browser runtime compiler since it
11767 * doesn't prefix expressions.
11768 */
11769 function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
11770 const exp = node.content;
11771 // empty expressions are validated per-directive since some directives
11772 // do allow empty expressions.
11773 if (!exp.trim()) {
11774 return;
11775 }
11776 try {
11777 new Function(asRawStatements
11778 ? ` ${exp} `
11779 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
11780 }
11781 catch (e) {
11782 let message = e.message;
11783 const keywordMatch = exp
11784 .replace(stripStringRE, '')
11785 .match(prohibitedKeywordRE);
11786 if (keywordMatch) {
11787 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
11788 }
11789 context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
11790 }
11791 }
11792
11793 const transformExpression = (node, context) => {
11794 if (node.type === 5 /* INTERPOLATION */) {
11795 node.content = processExpression(node.content, context);
11796 }
11797 else if (node.type === 1 /* ELEMENT */) {
11798 // handle directives on element
11799 for (let i = 0; i < node.props.length; i++) {
11800 const dir = node.props[i];
11801 // do not process for v-on & v-for since they are special handled
11802 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
11803 const exp = dir.exp;
11804 const arg = dir.arg;
11805 // do not process exp if this is v-on:arg - we need special handling
11806 // for wrapping inline statements.
11807 if (exp &&
11808 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
11809 !(dir.name === 'on' && arg)) {
11810 dir.exp = processExpression(exp, context,
11811 // slot args must be processed as function params
11812 dir.name === 'slot');
11813 }
11814 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
11815 dir.arg = processExpression(arg, context);
11816 }
11817 }
11818 }
11819 }
11820 };
11821 // Important: since this function uses Node.js only dependencies, it should
11822 // always be used with a leading !true check so that it can be
11823 // tree-shaken from the browser build.
11824 function processExpression(node, context,
11825 // some expressions like v-slot props & v-for aliases should be parsed as
11826 // function params
11827 asParams = false,
11828 // v-on handler values may contain multiple statements
11829 asRawStatements = false) {
11830 {
11831 {
11832 // simple in-browser validation (same logic in 2.x)
11833 validateBrowserExpression(node, context, asParams, asRawStatements);
11834 }
11835 return node;
11836 }
11837 }
11838
11839 const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
11840 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
11841 // #1587: We need to dynamically increment the key based on the current
11842 // node's sibling nodes, since chained v-if/else branches are
11843 // rendered at the same depth
11844 const siblings = context.parent.children;
11845 let i = siblings.indexOf(ifNode);
11846 let key = 0;
11847 while (i-- >= 0) {
11848 const sibling = siblings[i];
11849 if (sibling && sibling.type === 9 /* IF */) {
11850 key += sibling.branches.length;
11851 }
11852 }
11853 // Exit callback. Complete the codegenNode when all children have been
11854 // transformed.
11855 return () => {
11856 if (isRoot) {
11857 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
11858 }
11859 else {
11860 // attach this branch's codegen node to the v-if root.
11861 const parentCondition = getParentCondition(ifNode.codegenNode);
11862 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
11863 }
11864 };
11865 });
11866 });
11867 // target-agnostic transform used for both Client and SSR
11868 function processIf(node, dir, context, processCodegen) {
11869 if (dir.name !== 'else' &&
11870 (!dir.exp || !dir.exp.content.trim())) {
11871 const loc = dir.exp ? dir.exp.loc : node.loc;
11872 context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
11873 dir.exp = createSimpleExpression(`true`, false, loc);
11874 }
11875 if (dir.exp) {
11876 validateBrowserExpression(dir.exp, context);
11877 }
11878 if (dir.name === 'if') {
11879 const branch = createIfBranch(node, dir);
11880 const ifNode = {
11881 type: 9 /* IF */,
11882 loc: node.loc,
11883 branches: [branch]
11884 };
11885 context.replaceNode(ifNode);
11886 if (processCodegen) {
11887 return processCodegen(ifNode, branch, true);
11888 }
11889 }
11890 else {
11891 // locate the adjacent v-if
11892 const siblings = context.parent.children;
11893 const comments = [];
11894 let i = siblings.indexOf(node);
11895 while (i-- >= -1) {
11896 const sibling = siblings[i];
11897 if (sibling && sibling.type === 3 /* COMMENT */) {
11898 context.removeNode(sibling);
11899 comments.unshift(sibling);
11900 continue;
11901 }
11902 if (sibling &&
11903 sibling.type === 2 /* TEXT */ &&
11904 !sibling.content.trim().length) {
11905 context.removeNode(sibling);
11906 continue;
11907 }
11908 if (sibling && sibling.type === 9 /* IF */) {
11909 // move the node to the if node's branches
11910 context.removeNode();
11911 const branch = createIfBranch(node, dir);
11912 if (comments.length) {
11913 branch.children = [...comments, ...branch.children];
11914 }
11915 // check if user is forcing same key on different branches
11916 {
11917 const key = branch.userKey;
11918 if (key) {
11919 sibling.branches.forEach(({ userKey }) => {
11920 if (isSameKey(userKey, key)) {
11921 context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
11922 }
11923 });
11924 }
11925 }
11926 sibling.branches.push(branch);
11927 const onExit = processCodegen && processCodegen(sibling, branch, false);
11928 // since the branch was removed, it will not be traversed.
11929 // make sure to traverse here.
11930 traverseNode(branch, context);
11931 // call on exit
11932 if (onExit)
11933 onExit();
11934 // make sure to reset currentNode after traversal to indicate this
11935 // node has been removed.
11936 context.currentNode = null;
11937 }
11938 else {
11939 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
11940 }
11941 break;
11942 }
11943 }
11944 }
11945 function createIfBranch(node, dir) {
11946 return {
11947 type: 10 /* IF_BRANCH */,
11948 loc: node.loc,
11949 condition: dir.name === 'else' ? undefined : dir.exp,
11950 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
11951 ? node.children
11952 : [node],
11953 userKey: findProp(node, `key`)
11954 };
11955 }
11956 function createCodegenNodeForBranch(branch, keyIndex, context) {
11957 if (branch.condition) {
11958 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
11959 // make sure to pass in asBlock: true so that the comment node call
11960 // closes the current block.
11961 createCallExpression(context.helper(CREATE_COMMENT), [
11962 '"v-if"' ,
11963 'true'
11964 ]));
11965 }
11966 else {
11967 return createChildrenCodegenNode(branch, keyIndex, context);
11968 }
11969 }
11970 function createChildrenCodegenNode(branch, keyIndex, context) {
11971 const { helper, removeHelper } = context;
11972 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
11973 const { children } = branch;
11974 const firstChild = children[0];
11975 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
11976 if (needFragmentWrapper) {
11977 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
11978 // optimize away nested fragments when child is a ForNode
11979 const vnodeCall = firstChild.codegenNode;
11980 injectProp(vnodeCall, keyProperty, context);
11981 return vnodeCall;
11982 }
11983 else {
11984 let patchFlag = 64 /* STABLE_FRAGMENT */;
11985 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
11986 // check if the fragment actually contains a single valid child with
11987 // the rest being comments
11988 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
11989 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
11990 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
11991 }
11992 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, branch.loc);
11993 }
11994 }
11995 else {
11996 const vnodeCall = firstChild
11997 .codegenNode;
11998 // Change createVNode to createBlock.
11999 if (vnodeCall.type === 13 /* VNODE_CALL */ && !vnodeCall.isBlock) {
12000 removeHelper(CREATE_VNODE);
12001 vnodeCall.isBlock = true;
12002 helper(OPEN_BLOCK);
12003 helper(CREATE_BLOCK);
12004 }
12005 // inject branch key
12006 injectProp(vnodeCall, keyProperty, context);
12007 return vnodeCall;
12008 }
12009 }
12010 function isSameKey(a, b) {
12011 if (!a || a.type !== b.type) {
12012 return false;
12013 }
12014 if (a.type === 6 /* ATTRIBUTE */) {
12015 if (a.value.content !== b.value.content) {
12016 return false;
12017 }
12018 }
12019 else {
12020 // directive
12021 const exp = a.exp;
12022 const branchExp = b.exp;
12023 if (exp.type !== branchExp.type) {
12024 return false;
12025 }
12026 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
12027 (exp.isStatic !== branchExp.isStatic ||
12028 exp.content !== branchExp.content)) {
12029 return false;
12030 }
12031 }
12032 return true;
12033 }
12034 function getParentCondition(node) {
12035 while (true) {
12036 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12037 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12038 node = node.alternate;
12039 }
12040 else {
12041 return node;
12042 }
12043 }
12044 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
12045 node = node.value;
12046 }
12047 }
12048 }
12049
12050 const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
12051 const { helper, removeHelper } = context;
12052 return processFor(node, dir, context, forNode => {
12053 // create the loop render function expression now, and add the
12054 // iterator on exit after all children have been traversed
12055 const renderExp = createCallExpression(helper(RENDER_LIST), [
12056 forNode.source
12057 ]);
12058 const keyProp = findProp(node, `key`);
12059 const keyProperty = keyProp
12060 ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
12061 ? createSimpleExpression(keyProp.value.content, true)
12062 : keyProp.exp)
12063 : null;
12064 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
12065 forNode.source.constType > 0 /* NOT_CONSTANT */;
12066 const fragmentFlag = isStableFragment
12067 ? 64 /* STABLE_FRAGMENT */
12068 : keyProp
12069 ? 128 /* KEYED_FRAGMENT */
12070 : 256 /* UNKEYED_FRAGMENT */;
12071 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
12072 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
12073 return () => {
12074 // finish the codegen now that all children have been traversed
12075 let childBlock;
12076 const isTemplate = isTemplateNode(node);
12077 const { children } = forNode;
12078 // check <template v-for> key placement
12079 if (isTemplate) {
12080 node.children.some(c => {
12081 if (c.type === 1 /* ELEMENT */) {
12082 const key = findProp(c, 'key');
12083 if (key) {
12084 context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
12085 return true;
12086 }
12087 }
12088 });
12089 }
12090 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
12091 const slotOutlet = isSlotOutlet(node)
12092 ? node
12093 : isTemplate &&
12094 node.children.length === 1 &&
12095 isSlotOutlet(node.children[0])
12096 ? node.children[0] // api-extractor somehow fails to infer this
12097 : null;
12098 if (slotOutlet) {
12099 // <slot v-for="..."> or <template v-for="..."><slot/></template>
12100 childBlock = slotOutlet.codegenNode;
12101 if (isTemplate && keyProperty) {
12102 // <template v-for="..." :key="..."><slot/></template>
12103 // we need to inject the key to the renderSlot() call.
12104 // the props for renderSlot is passed as the 3rd argument.
12105 injectProp(childBlock, keyProperty, context);
12106 }
12107 }
12108 else if (needFragmentWrapper) {
12109 // <template v-for="..."> with text or multi-elements
12110 // should generate a fragment block for each loop
12111 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
12112 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
12113 ), undefined, undefined, true);
12114 }
12115 else {
12116 // Normal element v-for. Directly use the child's codegenNode
12117 // but mark it as a block.
12118 childBlock = children[0]
12119 .codegenNode;
12120 if (isTemplate && keyProperty) {
12121 injectProp(childBlock, keyProperty, context);
12122 }
12123 if (childBlock.isBlock !== !isStableFragment) {
12124 if (childBlock.isBlock) {
12125 // switch from block to vnode
12126 removeHelper(OPEN_BLOCK);
12127 removeHelper(CREATE_BLOCK);
12128 }
12129 else {
12130 // switch from vnode to block
12131 removeHelper(CREATE_VNODE);
12132 }
12133 }
12134 childBlock.isBlock = !isStableFragment;
12135 if (childBlock.isBlock) {
12136 helper(OPEN_BLOCK);
12137 helper(CREATE_BLOCK);
12138 }
12139 else {
12140 helper(CREATE_VNODE);
12141 }
12142 }
12143 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
12144 };
12145 });
12146 });
12147 // target-agnostic transform used for both Client and SSR
12148 function processFor(node, dir, context, processCodegen) {
12149 if (!dir.exp) {
12150 context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
12151 return;
12152 }
12153 const parseResult = parseForExpression(
12154 // can only be simple expression because vFor transform is applied
12155 // before expression transform.
12156 dir.exp, context);
12157 if (!parseResult) {
12158 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
12159 return;
12160 }
12161 const { addIdentifiers, removeIdentifiers, scopes } = context;
12162 const { source, value, key, index } = parseResult;
12163 const forNode = {
12164 type: 11 /* FOR */,
12165 loc: dir.loc,
12166 source,
12167 valueAlias: value,
12168 keyAlias: key,
12169 objectIndexAlias: index,
12170 parseResult,
12171 children: isTemplateNode(node) ? node.children : [node]
12172 };
12173 context.replaceNode(forNode);
12174 // bookkeeping
12175 scopes.vFor++;
12176 const onExit = processCodegen && processCodegen(forNode);
12177 return () => {
12178 scopes.vFor--;
12179 if (onExit)
12180 onExit();
12181 };
12182 }
12183 const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
12184 // This regex doesn't cover the case if key or index aliases have destructuring,
12185 // but those do not make sense in the first place, so this works in practice.
12186 const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
12187 const stripParensRE = /^\(|\)$/g;
12188 function parseForExpression(input, context) {
12189 const loc = input.loc;
12190 const exp = input.content;
12191 const inMatch = exp.match(forAliasRE);
12192 if (!inMatch)
12193 return;
12194 const [, LHS, RHS] = inMatch;
12195 const result = {
12196 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
12197 value: undefined,
12198 key: undefined,
12199 index: undefined
12200 };
12201 {
12202 validateBrowserExpression(result.source, context);
12203 }
12204 let valueContent = LHS.trim()
12205 .replace(stripParensRE, '')
12206 .trim();
12207 const trimmedOffset = LHS.indexOf(valueContent);
12208 const iteratorMatch = valueContent.match(forIteratorRE);
12209 if (iteratorMatch) {
12210 valueContent = valueContent.replace(forIteratorRE, '').trim();
12211 const keyContent = iteratorMatch[1].trim();
12212 let keyOffset;
12213 if (keyContent) {
12214 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
12215 result.key = createAliasExpression(loc, keyContent, keyOffset);
12216 {
12217 validateBrowserExpression(result.key, context, true);
12218 }
12219 }
12220 if (iteratorMatch[2]) {
12221 const indexContent = iteratorMatch[2].trim();
12222 if (indexContent) {
12223 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
12224 ? keyOffset + keyContent.length
12225 : trimmedOffset + valueContent.length));
12226 {
12227 validateBrowserExpression(result.index, context, true);
12228 }
12229 }
12230 }
12231 }
12232 if (valueContent) {
12233 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
12234 {
12235 validateBrowserExpression(result.value, context, true);
12236 }
12237 }
12238 return result;
12239 }
12240 function createAliasExpression(range, content, offset) {
12241 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
12242 }
12243 function createForLoopParams({ value, key, index }) {
12244 const params = [];
12245 if (value) {
12246 params.push(value);
12247 }
12248 if (key) {
12249 if (!value) {
12250 params.push(createSimpleExpression(`_`, false));
12251 }
12252 params.push(key);
12253 }
12254 if (index) {
12255 if (!key) {
12256 if (!value) {
12257 params.push(createSimpleExpression(`_`, false));
12258 }
12259 params.push(createSimpleExpression(`__`, false));
12260 }
12261 params.push(index);
12262 }
12263 return params;
12264 }
12265
12266 const defaultFallback = createSimpleExpression(`undefined`, false);
12267 // A NodeTransform that:
12268 // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
12269 // by transformExpression. This is only applied in non-browser builds with
12270 // { prefixIdentifiers: true }.
12271 // 2. Track v-slot depths so that we know a slot is inside another slot.
12272 // Note the exit callback is executed before buildSlots() on the same node,
12273 // so only nested slots see positive numbers.
12274 const trackSlotScopes = (node, context) => {
12275 if (node.type === 1 /* ELEMENT */ &&
12276 (node.tagType === 1 /* COMPONENT */ ||
12277 node.tagType === 3 /* TEMPLATE */)) {
12278 // We are only checking non-empty v-slot here
12279 // since we only care about slots that introduce scope variables.
12280 const vSlot = findDir(node, 'slot');
12281 if (vSlot) {
12282 vSlot.exp;
12283 context.scopes.vSlot++;
12284 return () => {
12285 context.scopes.vSlot--;
12286 };
12287 }
12288 }
12289 };
12290 const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
12291 // Instead of being a DirectiveTransform, v-slot processing is called during
12292 // transformElement to build the slots object for a component.
12293 function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
12294 context.helper(WITH_CTX);
12295 const { children, loc } = node;
12296 const slotsProperties = [];
12297 const dynamicSlots = [];
12298 const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
12299 // If the slot is inside a v-for or another v-slot, force it to be dynamic
12300 // since it likely uses a scope variable.
12301 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
12302 // 1. Check for slot with slotProps on component itself.
12303 // <Comp v-slot="{ prop }"/>
12304 const onComponentSlot = findDir(node, 'slot', true);
12305 if (onComponentSlot) {
12306 const { arg, exp } = onComponentSlot;
12307 if (arg && !isStaticExp(arg)) {
12308 hasDynamicSlots = true;
12309 }
12310 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
12311 }
12312 // 2. Iterate through children and check for template slots
12313 // <template v-slot:foo="{ prop }">
12314 let hasTemplateSlots = false;
12315 let hasNamedDefaultSlot = false;
12316 const implicitDefaultChildren = [];
12317 const seenSlotNames = new Set();
12318 for (let i = 0; i < children.length; i++) {
12319 const slotElement = children[i];
12320 let slotDir;
12321 if (!isTemplateNode(slotElement) ||
12322 !(slotDir = findDir(slotElement, 'slot', true))) {
12323 // not a <template v-slot>, skip.
12324 if (slotElement.type !== 3 /* COMMENT */) {
12325 implicitDefaultChildren.push(slotElement);
12326 }
12327 continue;
12328 }
12329 if (onComponentSlot) {
12330 // already has on-component slot - this is incorrect usage.
12331 context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
12332 break;
12333 }
12334 hasTemplateSlots = true;
12335 const { children: slotChildren, loc: slotLoc } = slotElement;
12336 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
12337 // check if name is dynamic.
12338 let staticSlotName;
12339 if (isStaticExp(slotName)) {
12340 staticSlotName = slotName ? slotName.content : `default`;
12341 }
12342 else {
12343 hasDynamicSlots = true;
12344 }
12345 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
12346 // check if this slot is conditional (v-if/v-for)
12347 let vIf;
12348 let vElse;
12349 let vFor;
12350 if ((vIf = findDir(slotElement, 'if'))) {
12351 hasDynamicSlots = true;
12352 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
12353 }
12354 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
12355 // find adjacent v-if
12356 let j = i;
12357 let prev;
12358 while (j--) {
12359 prev = children[j];
12360 if (prev.type !== 3 /* COMMENT */) {
12361 break;
12362 }
12363 }
12364 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
12365 // remove node
12366 children.splice(i, 1);
12367 i--;
12368 // attach this slot to previous conditional
12369 let conditional = dynamicSlots[dynamicSlots.length - 1];
12370 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12371 conditional = conditional.alternate;
12372 }
12373 conditional.alternate = vElse.exp
12374 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
12375 : buildDynamicSlot(slotName, slotFunction);
12376 }
12377 else {
12378 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
12379 }
12380 }
12381 else if ((vFor = findDir(slotElement, 'for'))) {
12382 hasDynamicSlots = true;
12383 const parseResult = vFor.parseResult ||
12384 parseForExpression(vFor.exp, context);
12385 if (parseResult) {
12386 // Render the dynamic slots as an array and add it to the createSlot()
12387 // args. The runtime knows how to handle it appropriately.
12388 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
12389 parseResult.source,
12390 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
12391 ]));
12392 }
12393 else {
12394 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
12395 }
12396 }
12397 else {
12398 // check duplicate static names
12399 if (staticSlotName) {
12400 if (seenSlotNames.has(staticSlotName)) {
12401 context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
12402 continue;
12403 }
12404 seenSlotNames.add(staticSlotName);
12405 if (staticSlotName === 'default') {
12406 hasNamedDefaultSlot = true;
12407 }
12408 }
12409 slotsProperties.push(createObjectProperty(slotName, slotFunction));
12410 }
12411 }
12412 if (!onComponentSlot) {
12413 if (!hasTemplateSlots) {
12414 // implicit default slot (on component)
12415 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
12416 }
12417 else if (implicitDefaultChildren.length) {
12418 // implicit default slot (mixed with named slots)
12419 if (hasNamedDefaultSlot) {
12420 context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
12421 }
12422 else {
12423 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
12424 }
12425 }
12426 }
12427 const slotFlag = hasDynamicSlots
12428 ? 2 /* DYNAMIC */
12429 : hasForwardedSlots(node.children)
12430 ? 3 /* FORWARDED */
12431 : 1 /* STABLE */;
12432 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
12433 // 2 = compiled but dynamic = can skip normalization, but must run diff
12434 // 1 = compiled and static = can skip normalization AND diff as optimized
12435 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
12436 if (dynamicSlots.length) {
12437 slots = createCallExpression(context.helper(CREATE_SLOTS), [
12438 slots,
12439 createArrayExpression(dynamicSlots)
12440 ]);
12441 }
12442 return {
12443 slots,
12444 hasDynamicSlots
12445 };
12446 }
12447 function buildDynamicSlot(name, fn) {
12448 return createObjectExpression([
12449 createObjectProperty(`name`, name),
12450 createObjectProperty(`fn`, fn)
12451 ]);
12452 }
12453 function hasForwardedSlots(children) {
12454 for (let i = 0; i < children.length; i++) {
12455 const child = children[i];
12456 switch (child.type) {
12457 case 1 /* ELEMENT */:
12458 if (child.tagType === 2 /* SLOT */ ||
12459 (child.tagType === 0 /* ELEMENT */ &&
12460 hasForwardedSlots(child.children))) {
12461 return true;
12462 }
12463 break;
12464 case 9 /* IF */:
12465 if (hasForwardedSlots(child.branches))
12466 return true;
12467 break;
12468 case 10 /* IF_BRANCH */:
12469 case 11 /* FOR */:
12470 if (hasForwardedSlots(child.children))
12471 return true;
12472 break;
12473 }
12474 }
12475 return false;
12476 }
12477
12478 // some directive transforms (e.g. v-model) may return a symbol for runtime
12479 // import, which should be used instead of a resolveDirective call.
12480 const directiveImportMap = new WeakMap();
12481 // generate a JavaScript AST for this element's codegen
12482 const transformElement = (node, context) => {
12483 // perform the work on exit, after all child expressions have been
12484 // processed and merged.
12485 return function postTransformElement() {
12486 node = context.currentNode;
12487 if (!(node.type === 1 /* ELEMENT */ &&
12488 (node.tagType === 0 /* ELEMENT */ ||
12489 node.tagType === 1 /* COMPONENT */))) {
12490 return;
12491 }
12492 const { tag, props } = node;
12493 const isComponent = node.tagType === 1 /* COMPONENT */;
12494 // The goal of the transform is to create a codegenNode implementing the
12495 // VNodeCall interface.
12496 const vnodeTag = isComponent
12497 ? resolveComponentType(node, context)
12498 : `"${tag}"`;
12499 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
12500 let vnodeProps;
12501 let vnodeChildren;
12502 let vnodePatchFlag;
12503 let patchFlag = 0;
12504 let vnodeDynamicProps;
12505 let dynamicPropNames;
12506 let vnodeDirectives;
12507 let shouldUseBlock =
12508 // dynamic component may resolve to plain elements
12509 isDynamicComponent ||
12510 vnodeTag === TELEPORT ||
12511 vnodeTag === SUSPENSE ||
12512 (!isComponent &&
12513 // <svg> and <foreignObject> must be forced into blocks so that block
12514 // updates inside get proper isSVG flag at runtime. (#639, #643)
12515 // This is technically web-specific, but splitting the logic out of core
12516 // leads to too much unnecessary complexity.
12517 (tag === 'svg' ||
12518 tag === 'foreignObject' ||
12519 // #938: elements with dynamic keys should be forced into blocks
12520 findProp(node, 'key', true)));
12521 // props
12522 if (props.length > 0) {
12523 const propsBuildResult = buildProps(node, context);
12524 vnodeProps = propsBuildResult.props;
12525 patchFlag = propsBuildResult.patchFlag;
12526 dynamicPropNames = propsBuildResult.dynamicPropNames;
12527 const directives = propsBuildResult.directives;
12528 vnodeDirectives =
12529 directives && directives.length
12530 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
12531 : undefined;
12532 }
12533 // children
12534 if (node.children.length > 0) {
12535 if (vnodeTag === KEEP_ALIVE) {
12536 // Although a built-in component, we compile KeepAlive with raw children
12537 // instead of slot functions so that it can be used inside Transition
12538 // or other Transition-wrapping HOCs.
12539 // To ensure correct updates with block optimizations, we need to:
12540 // 1. Force keep-alive into a block. This avoids its children being
12541 // collected by a parent block.
12542 shouldUseBlock = true;
12543 // 2. Force keep-alive to always be updated, since it uses raw children.
12544 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
12545 if (node.children.length > 1) {
12546 context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
12547 start: node.children[0].loc.start,
12548 end: node.children[node.children.length - 1].loc.end,
12549 source: ''
12550 }));
12551 }
12552 }
12553 const shouldBuildAsSlots = isComponent &&
12554 // Teleport is not a real component and has dedicated runtime handling
12555 vnodeTag !== TELEPORT &&
12556 // explained above.
12557 vnodeTag !== KEEP_ALIVE;
12558 if (shouldBuildAsSlots) {
12559 const { slots, hasDynamicSlots } = buildSlots(node, context);
12560 vnodeChildren = slots;
12561 if (hasDynamicSlots) {
12562 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
12563 }
12564 }
12565 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
12566 const child = node.children[0];
12567 const type = child.type;
12568 // check for dynamic text children
12569 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
12570 type === 8 /* COMPOUND_EXPRESSION */;
12571 if (hasDynamicTextChild &&
12572 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
12573 patchFlag |= 1 /* TEXT */;
12574 }
12575 // pass directly if the only child is a text node
12576 // (plain / interpolation / expression)
12577 if (hasDynamicTextChild || type === 2 /* TEXT */) {
12578 vnodeChildren = child;
12579 }
12580 else {
12581 vnodeChildren = node.children;
12582 }
12583 }
12584 else {
12585 vnodeChildren = node.children;
12586 }
12587 }
12588 // patchFlag & dynamicPropNames
12589 if (patchFlag !== 0) {
12590 {
12591 if (patchFlag < 0) {
12592 // special flags (negative and mutually exclusive)
12593 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
12594 }
12595 else {
12596 // bitwise flags
12597 const flagNames = Object.keys(PatchFlagNames)
12598 .map(Number)
12599 .filter(n => n > 0 && patchFlag & n)
12600 .map(n => PatchFlagNames[n])
12601 .join(`, `);
12602 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
12603 }
12604 }
12605 if (dynamicPropNames && dynamicPropNames.length) {
12606 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
12607 }
12608 }
12609 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
12610 };
12611 };
12612 function resolveComponentType(node, context, ssr = false) {
12613 const { tag } = node;
12614 // 1. dynamic component
12615 const isProp = isComponentTag(tag)
12616 ? findProp(node, 'is')
12617 : findDir(node, 'is');
12618 if (isProp) {
12619 const exp = isProp.type === 6 /* ATTRIBUTE */
12620 ? isProp.value && createSimpleExpression(isProp.value.content, true)
12621 : isProp.exp;
12622 if (exp) {
12623 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
12624 exp
12625 ]);
12626 }
12627 }
12628 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
12629 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
12630 if (builtIn) {
12631 // built-ins are simply fallthroughs / have special handling during ssr
12632 // so we don't need to import their runtime equivalents
12633 if (!ssr)
12634 context.helper(builtIn);
12635 return builtIn;
12636 }
12637 // 5. user component (resolve)
12638 context.helper(RESOLVE_COMPONENT);
12639 context.components.add(tag);
12640 return toValidAssetId(tag, `component`);
12641 }
12642 function buildProps(node, context, props = node.props, ssr = false) {
12643 const { tag, loc: elementLoc } = node;
12644 const isComponent = node.tagType === 1 /* COMPONENT */;
12645 let properties = [];
12646 const mergeArgs = [];
12647 const runtimeDirectives = [];
12648 // patchFlag analysis
12649 let patchFlag = 0;
12650 let hasRef = false;
12651 let hasClassBinding = false;
12652 let hasStyleBinding = false;
12653 let hasHydrationEventBinding = false;
12654 let hasDynamicKeys = false;
12655 let hasVnodeHook = false;
12656 const dynamicPropNames = [];
12657 const analyzePatchFlag = ({ key, value }) => {
12658 if (isStaticExp(key)) {
12659 const name = key.content;
12660 const isEventHandler = isOn(name);
12661 if (!isComponent &&
12662 isEventHandler &&
12663 // omit the flag for click handlers because hydration gives click
12664 // dedicated fast path.
12665 name.toLowerCase() !== 'onclick' &&
12666 // omit v-model handlers
12667 name !== 'onUpdate:modelValue' &&
12668 // omit onVnodeXXX hooks
12669 !isReservedProp(name)) {
12670 hasHydrationEventBinding = true;
12671 }
12672 if (isEventHandler && isReservedProp(name)) {
12673 hasVnodeHook = true;
12674 }
12675 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
12676 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
12677 value.type === 8 /* COMPOUND_EXPRESSION */) &&
12678 getConstantType(value, context) > 0)) {
12679 // skip if the prop is a cached handler or has constant value
12680 return;
12681 }
12682 if (name === 'ref') {
12683 hasRef = true;
12684 }
12685 else if (name === 'class' && !isComponent) {
12686 hasClassBinding = true;
12687 }
12688 else if (name === 'style' && !isComponent) {
12689 hasStyleBinding = true;
12690 }
12691 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
12692 dynamicPropNames.push(name);
12693 }
12694 }
12695 else {
12696 hasDynamicKeys = true;
12697 }
12698 };
12699 for (let i = 0; i < props.length; i++) {
12700 // static attribute
12701 const prop = props[i];
12702 if (prop.type === 6 /* ATTRIBUTE */) {
12703 const { loc, name, value } = prop;
12704 let isStatic = true;
12705 if (name === 'ref') {
12706 hasRef = true;
12707 }
12708 // skip :is on <component>
12709 if (name === 'is' && isComponentTag(tag)) {
12710 continue;
12711 }
12712 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
12713 }
12714 else {
12715 // directives
12716 const { name, arg, exp, loc } = prop;
12717 const isBind = name === 'bind';
12718 const isOn = name === 'on';
12719 // skip v-slot - it is handled by its dedicated transform.
12720 if (name === 'slot') {
12721 if (!isComponent) {
12722 context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
12723 }
12724 continue;
12725 }
12726 // skip v-once - it is handled by its dedicated transform.
12727 if (name === 'once') {
12728 continue;
12729 }
12730 // skip v-is and :is on <component>
12731 if (name === 'is' ||
12732 (isBind && isComponentTag(tag) && isBindKey(arg, 'is'))) {
12733 continue;
12734 }
12735 // skip v-on in SSR compilation
12736 if (isOn && ssr) {
12737 continue;
12738 }
12739 // special case for v-bind and v-on with no argument
12740 if (!arg && (isBind || isOn)) {
12741 hasDynamicKeys = true;
12742 if (exp) {
12743 if (properties.length) {
12744 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
12745 properties = [];
12746 }
12747 if (isBind) {
12748 mergeArgs.push(exp);
12749 }
12750 else {
12751 // v-on="obj" -> toHandlers(obj)
12752 mergeArgs.push({
12753 type: 14 /* JS_CALL_EXPRESSION */,
12754 loc,
12755 callee: context.helper(TO_HANDLERS),
12756 arguments: [exp]
12757 });
12758 }
12759 }
12760 else {
12761 context.onError(createCompilerError(isBind
12762 ? 33 /* X_V_BIND_NO_EXPRESSION */
12763 : 34 /* X_V_ON_NO_EXPRESSION */, loc));
12764 }
12765 continue;
12766 }
12767 const directiveTransform = context.directiveTransforms[name];
12768 if (directiveTransform) {
12769 // has built-in directive transform.
12770 const { props, needRuntime } = directiveTransform(prop, node, context);
12771 !ssr && props.forEach(analyzePatchFlag);
12772 properties.push(...props);
12773 if (needRuntime) {
12774 runtimeDirectives.push(prop);
12775 if (isSymbol(needRuntime)) {
12776 directiveImportMap.set(prop, needRuntime);
12777 }
12778 }
12779 }
12780 else {
12781 // no built-in transform, this is a user custom directive.
12782 runtimeDirectives.push(prop);
12783 }
12784 }
12785 }
12786 let propsExpression = undefined;
12787 // has v-bind="object" or v-on="object", wrap with mergeProps
12788 if (mergeArgs.length) {
12789 if (properties.length) {
12790 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
12791 }
12792 if (mergeArgs.length > 1) {
12793 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
12794 }
12795 else {
12796 // single v-bind with nothing else - no need for a mergeProps call
12797 propsExpression = mergeArgs[0];
12798 }
12799 }
12800 else if (properties.length) {
12801 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
12802 }
12803 // patchFlag analysis
12804 if (hasDynamicKeys) {
12805 patchFlag |= 16 /* FULL_PROPS */;
12806 }
12807 else {
12808 if (hasClassBinding) {
12809 patchFlag |= 2 /* CLASS */;
12810 }
12811 if (hasStyleBinding) {
12812 patchFlag |= 4 /* STYLE */;
12813 }
12814 if (dynamicPropNames.length) {
12815 patchFlag |= 8 /* PROPS */;
12816 }
12817 if (hasHydrationEventBinding) {
12818 patchFlag |= 32 /* HYDRATE_EVENTS */;
12819 }
12820 }
12821 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
12822 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
12823 patchFlag |= 512 /* NEED_PATCH */;
12824 }
12825 return {
12826 props: propsExpression,
12827 directives: runtimeDirectives,
12828 patchFlag,
12829 dynamicPropNames
12830 };
12831 }
12832 // Dedupe props in an object literal.
12833 // Literal duplicated attributes would have been warned during the parse phase,
12834 // however, it's possible to encounter duplicated `onXXX` handlers with different
12835 // modifiers. We also need to merge static and dynamic class / style attributes.
12836 // - onXXX handlers / style: merge into array
12837 // - class: merge into single expression with concatenation
12838 function dedupeProperties(properties) {
12839 const knownProps = new Map();
12840 const deduped = [];
12841 for (let i = 0; i < properties.length; i++) {
12842 const prop = properties[i];
12843 // dynamic keys are always allowed
12844 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
12845 deduped.push(prop);
12846 continue;
12847 }
12848 const name = prop.key.content;
12849 const existing = knownProps.get(name);
12850 if (existing) {
12851 if (name === 'style' || name === 'class' || name.startsWith('on')) {
12852 mergeAsArray(existing, prop);
12853 }
12854 // unexpected duplicate, should have emitted error during parse
12855 }
12856 else {
12857 knownProps.set(name, prop);
12858 deduped.push(prop);
12859 }
12860 }
12861 return deduped;
12862 }
12863 function mergeAsArray(existing, incoming) {
12864 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
12865 existing.value.elements.push(incoming.value);
12866 }
12867 else {
12868 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
12869 }
12870 }
12871 function buildDirectiveArgs(dir, context) {
12872 const dirArgs = [];
12873 const runtime = directiveImportMap.get(dir);
12874 if (runtime) {
12875 // built-in directive with runtime
12876 dirArgs.push(context.helperString(runtime));
12877 }
12878 else {
12879 {
12880 // inject statement for resolving directive
12881 context.helper(RESOLVE_DIRECTIVE);
12882 context.directives.add(dir.name);
12883 dirArgs.push(toValidAssetId(dir.name, `directive`));
12884 }
12885 }
12886 const { loc } = dir;
12887 if (dir.exp)
12888 dirArgs.push(dir.exp);
12889 if (dir.arg) {
12890 if (!dir.exp) {
12891 dirArgs.push(`void 0`);
12892 }
12893 dirArgs.push(dir.arg);
12894 }
12895 if (Object.keys(dir.modifiers).length) {
12896 if (!dir.arg) {
12897 if (!dir.exp) {
12898 dirArgs.push(`void 0`);
12899 }
12900 dirArgs.push(`void 0`);
12901 }
12902 const trueExpression = createSimpleExpression(`true`, false, loc);
12903 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
12904 }
12905 return createArrayExpression(dirArgs, dir.loc);
12906 }
12907 function stringifyDynamicPropNames(props) {
12908 let propsNamesString = `[`;
12909 for (let i = 0, l = props.length; i < l; i++) {
12910 propsNamesString += JSON.stringify(props[i]);
12911 if (i < l - 1)
12912 propsNamesString += ', ';
12913 }
12914 return propsNamesString + `]`;
12915 }
12916 function isComponentTag(tag) {
12917 return tag[0].toLowerCase() + tag.slice(1) === 'component';
12918 }
12919
12920 const transformSlotOutlet = (node, context) => {
12921 if (isSlotOutlet(node)) {
12922 const { children, loc } = node;
12923 const { slotName, slotProps } = processSlotOutlet(node, context);
12924 const slotArgs = [
12925 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
12926 slotName
12927 ];
12928 if (slotProps) {
12929 slotArgs.push(slotProps);
12930 }
12931 if (children.length) {
12932 if (!slotProps) {
12933 slotArgs.push(`{}`);
12934 }
12935 slotArgs.push(createFunctionExpression([], children, false, false, loc));
12936 }
12937 if (context.scopeId && !context.slotted) {
12938 if (!slotProps) {
12939 slotArgs.push(`{}`);
12940 }
12941 if (!children.length) {
12942 slotArgs.push(`undefined`);
12943 }
12944 slotArgs.push(`true`);
12945 }
12946 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
12947 }
12948 };
12949 function processSlotOutlet(node, context) {
12950 let slotName = `"default"`;
12951 let slotProps = undefined;
12952 const nonNameProps = [];
12953 for (let i = 0; i < node.props.length; i++) {
12954 const p = node.props[i];
12955 if (p.type === 6 /* ATTRIBUTE */) {
12956 if (p.value) {
12957 if (p.name === 'name') {
12958 slotName = JSON.stringify(p.value.content);
12959 }
12960 else {
12961 p.name = camelize(p.name);
12962 nonNameProps.push(p);
12963 }
12964 }
12965 }
12966 else {
12967 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
12968 if (p.exp)
12969 slotName = p.exp;
12970 }
12971 else {
12972 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
12973 p.arg.content = camelize(p.arg.content);
12974 }
12975 nonNameProps.push(p);
12976 }
12977 }
12978 }
12979 if (nonNameProps.length > 0) {
12980 const { props, directives } = buildProps(node, context, nonNameProps);
12981 slotProps = props;
12982 if (directives.length) {
12983 context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
12984 }
12985 }
12986 return {
12987 slotName,
12988 slotProps
12989 };
12990 }
12991
12992 const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
12993 const transformOn = (dir, node, context, augmentor) => {
12994 const { loc, modifiers, arg } = dir;
12995 if (!dir.exp && !modifiers.length) {
12996 context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
12997 }
12998 let eventName;
12999 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
13000 if (arg.isStatic) {
13001 const rawName = arg.content;
13002 // for all event listeners, auto convert it to camelCase. See issue #2249
13003 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
13004 }
13005 else {
13006 // #2388
13007 eventName = createCompoundExpression([
13008 `${context.helperString(TO_HANDLER_KEY)}(`,
13009 arg,
13010 `)`
13011 ]);
13012 }
13013 }
13014 else {
13015 // already a compound expression.
13016 eventName = arg;
13017 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
13018 eventName.children.push(`)`);
13019 }
13020 // handler processing
13021 let exp = dir.exp;
13022 if (exp && !exp.content.trim()) {
13023 exp = undefined;
13024 }
13025 let shouldCache = context.cacheHandlers && !exp;
13026 if (exp) {
13027 const isMemberExp = isMemberExpression(exp.content);
13028 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
13029 const hasMultipleStatements = exp.content.includes(`;`);
13030 {
13031 validateBrowserExpression(exp, context, false, hasMultipleStatements);
13032 }
13033 if (isInlineStatement || (shouldCache && isMemberExp)) {
13034 // wrap inline statement in a function expression
13035 exp = createCompoundExpression([
13036 `${isInlineStatement
13037 ? `$event`
13038 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
13039 exp,
13040 hasMultipleStatements ? `}` : `)`
13041 ]);
13042 }
13043 }
13044 let ret = {
13045 props: [
13046 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
13047 ]
13048 };
13049 // apply extended compiler augmentor
13050 if (augmentor) {
13051 ret = augmentor(ret);
13052 }
13053 if (shouldCache) {
13054 // cache handlers so that it's always the same handler being passed down.
13055 // this avoids unnecessary re-renders when users use inline handlers on
13056 // components.
13057 ret.props[0].value = context.cache(ret.props[0].value);
13058 }
13059 return ret;
13060 };
13061
13062 // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
13063 // codegen for the entire props object. This transform here is only for v-bind
13064 // *with* args.
13065 const transformBind = (dir, node, context) => {
13066 const { exp, modifiers, loc } = dir;
13067 const arg = dir.arg;
13068 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
13069 arg.children.unshift(`(`);
13070 arg.children.push(`) || ""`);
13071 }
13072 else if (!arg.isStatic) {
13073 arg.content = `${arg.content} || ""`;
13074 }
13075 // .prop is no longer necessary due to new patch behavior
13076 // .sync is replaced by v-model:arg
13077 if (modifiers.includes('camel')) {
13078 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
13079 if (arg.isStatic) {
13080 arg.content = camelize(arg.content);
13081 }
13082 else {
13083 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
13084 }
13085 }
13086 else {
13087 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
13088 arg.children.push(`)`);
13089 }
13090 }
13091 if (!exp ||
13092 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
13093 context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
13094 return {
13095 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
13096 };
13097 }
13098 return {
13099 props: [createObjectProperty(arg, exp)]
13100 };
13101 };
13102
13103 // Merge adjacent text nodes and expressions into a single expression
13104 // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
13105 const transformText = (node, context) => {
13106 if (node.type === 0 /* ROOT */ ||
13107 node.type === 1 /* ELEMENT */ ||
13108 node.type === 11 /* FOR */ ||
13109 node.type === 10 /* IF_BRANCH */) {
13110 // perform the transform on node exit so that all expressions have already
13111 // been processed.
13112 return () => {
13113 const children = node.children;
13114 let currentContainer = undefined;
13115 let hasText = false;
13116 for (let i = 0; i < children.length; i++) {
13117 const child = children[i];
13118 if (isText(child)) {
13119 hasText = true;
13120 for (let j = i + 1; j < children.length; j++) {
13121 const next = children[j];
13122 if (isText(next)) {
13123 if (!currentContainer) {
13124 currentContainer = children[i] = {
13125 type: 8 /* COMPOUND_EXPRESSION */,
13126 loc: child.loc,
13127 children: [child]
13128 };
13129 }
13130 // merge adjacent text node into current
13131 currentContainer.children.push(` + `, next);
13132 children.splice(j, 1);
13133 j--;
13134 }
13135 else {
13136 currentContainer = undefined;
13137 break;
13138 }
13139 }
13140 }
13141 }
13142 if (!hasText ||
13143 // if this is a plain element with a single text child, leave it
13144 // as-is since the runtime has dedicated fast path for this by directly
13145 // setting textContent of the element.
13146 // for component root it's always normalized anyway.
13147 (children.length === 1 &&
13148 (node.type === 0 /* ROOT */ ||
13149 (node.type === 1 /* ELEMENT */ &&
13150 node.tagType === 0 /* ELEMENT */)))) {
13151 return;
13152 }
13153 // pre-convert text nodes into createTextVNode(text) calls to avoid
13154 // runtime normalization.
13155 for (let i = 0; i < children.length; i++) {
13156 const child = children[i];
13157 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
13158 const callArgs = [];
13159 // createTextVNode defaults to single whitespace, so if it is a
13160 // single space the code could be an empty call to save bytes.
13161 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
13162 callArgs.push(child);
13163 }
13164 // mark dynamic text with flag so it gets patched inside a block
13165 if (!context.ssr &&
13166 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
13167 callArgs.push(1 /* TEXT */ +
13168 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
13169 }
13170 children[i] = {
13171 type: 12 /* TEXT_CALL */,
13172 content: child,
13173 loc: child.loc,
13174 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
13175 };
13176 }
13177 }
13178 };
13179 }
13180 };
13181
13182 const seen = new WeakSet();
13183 const transformOnce = (node, context) => {
13184 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
13185 if (seen.has(node)) {
13186 return;
13187 }
13188 seen.add(node);
13189 context.helper(SET_BLOCK_TRACKING);
13190 return () => {
13191 const cur = context.currentNode;
13192 if (cur.codegenNode) {
13193 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
13194 }
13195 };
13196 }
13197 };
13198
13199 const transformModel = (dir, node, context) => {
13200 const { exp, arg } = dir;
13201 if (!exp) {
13202 context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
13203 return createTransformProps();
13204 }
13205 const rawExp = exp.loc.source;
13206 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
13207 // im SFC <script setup> inline mode, the exp may have been transformed into
13208 // _unref(exp)
13209 context.bindingMetadata[rawExp];
13210 const maybeRef = !true /* SETUP_CONST */;
13211 if (!isMemberExpression(expString) && !maybeRef) {
13212 context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
13213 return createTransformProps();
13214 }
13215 const propName = arg ? arg : createSimpleExpression('modelValue', true);
13216 const eventName = arg
13217 ? isStaticExp(arg)
13218 ? `onUpdate:${arg.content}`
13219 : createCompoundExpression(['"onUpdate:" + ', arg])
13220 : `onUpdate:modelValue`;
13221 let assignmentExp;
13222 const eventArg = context.isTS ? `($event: any)` : `$event`;
13223 {
13224 assignmentExp = createCompoundExpression([
13225 `${eventArg} => (`,
13226 exp,
13227 ` = $event)`
13228 ]);
13229 }
13230 const props = [
13231 // modelValue: foo
13232 createObjectProperty(propName, dir.exp),
13233 // "onUpdate:modelValue": $event => (foo = $event)
13234 createObjectProperty(eventName, assignmentExp)
13235 ];
13236 // modelModifiers: { foo: true, "bar-baz": true }
13237 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
13238 const modifiers = dir.modifiers
13239 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
13240 .join(`, `);
13241 const modifiersKey = arg
13242 ? isStaticExp(arg)
13243 ? `${arg.content}Modifiers`
13244 : createCompoundExpression([arg, ' + "Modifiers"'])
13245 : `modelModifiers`;
13246 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
13247 }
13248 return createTransformProps(props);
13249 };
13250 function createTransformProps(props = []) {
13251 return { props };
13252 }
13253
13254 function getBaseTransformPreset(prefixIdentifiers) {
13255 return [
13256 [
13257 transformOnce,
13258 transformIf,
13259 transformFor,
13260 ...([transformExpression]
13261 ),
13262 transformSlotOutlet,
13263 transformElement,
13264 trackSlotScopes,
13265 transformText
13266 ],
13267 {
13268 on: transformOn,
13269 bind: transformBind,
13270 model: transformModel
13271 }
13272 ];
13273 }
13274 // we name it `baseCompile` so that higher order compilers like
13275 // @vue/compiler-dom can export `compile` while re-exporting everything else.
13276 function baseCompile(template, options = {}) {
13277 const onError = options.onError || defaultOnError;
13278 const isModuleMode = options.mode === 'module';
13279 /* istanbul ignore if */
13280 {
13281 if (options.prefixIdentifiers === true) {
13282 onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
13283 }
13284 else if (isModuleMode) {
13285 onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
13286 }
13287 }
13288 const prefixIdentifiers = !true ;
13289 if (options.cacheHandlers) {
13290 onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
13291 }
13292 if (options.scopeId && !isModuleMode) {
13293 onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
13294 }
13295 const ast = isString(template) ? baseParse(template, options) : template;
13296 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
13297 transform(ast, extend({}, options, {
13298 prefixIdentifiers,
13299 nodeTransforms: [
13300 ...nodeTransforms,
13301 ...(options.nodeTransforms || []) // user transforms
13302 ],
13303 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
13304 )
13305 }));
13306 return generate(ast, extend({}, options, {
13307 prefixIdentifiers
13308 }));
13309 }
13310
13311 const noopDirectiveTransform = () => ({ props: [] });
13312
13313 const V_MODEL_RADIO = Symbol(`vModelRadio` );
13314 const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
13315 const V_MODEL_TEXT = Symbol(`vModelText` );
13316 const V_MODEL_SELECT = Symbol(`vModelSelect` );
13317 const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
13318 const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
13319 const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
13320 const V_SHOW = Symbol(`vShow` );
13321 const TRANSITION$1 = Symbol(`Transition` );
13322 const TRANSITION_GROUP = Symbol(`TransitionGroup` );
13323 registerRuntimeHelpers({
13324 [V_MODEL_RADIO]: `vModelRadio`,
13325 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
13326 [V_MODEL_TEXT]: `vModelText`,
13327 [V_MODEL_SELECT]: `vModelSelect`,
13328 [V_MODEL_DYNAMIC]: `vModelDynamic`,
13329 [V_ON_WITH_MODIFIERS]: `withModifiers`,
13330 [V_ON_WITH_KEYS]: `withKeys`,
13331 [V_SHOW]: `vShow`,
13332 [TRANSITION$1]: `Transition`,
13333 [TRANSITION_GROUP]: `TransitionGroup`
13334 });
13335
13336 /* eslint-disable no-restricted-globals */
13337 let decoder;
13338 function decodeHtmlBrowser(raw) {
13339 (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
13340 return decoder.textContent;
13341 }
13342
13343 const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
13344 const parserOptions = {
13345 isVoidTag,
13346 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
13347 isPreTag: tag => tag === 'pre',
13348 decodeEntities: decodeHtmlBrowser ,
13349 isBuiltInComponent: (tag) => {
13350 if (isBuiltInType(tag, `Transition`)) {
13351 return TRANSITION$1;
13352 }
13353 else if (isBuiltInType(tag, `TransitionGroup`)) {
13354 return TRANSITION_GROUP;
13355 }
13356 },
13357 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
13358 getNamespace(tag, parent) {
13359 let ns = parent ? parent.ns : 0 /* HTML */;
13360 if (parent && ns === 2 /* MATH_ML */) {
13361 if (parent.tag === 'annotation-xml') {
13362 if (tag === 'svg') {
13363 return 1 /* SVG */;
13364 }
13365 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
13366 a.name === 'encoding' &&
13367 a.value != null &&
13368 (a.value.content === 'text/html' ||
13369 a.value.content === 'application/xhtml+xml'))) {
13370 ns = 0 /* HTML */;
13371 }
13372 }
13373 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
13374 tag !== 'mglyph' &&
13375 tag !== 'malignmark') {
13376 ns = 0 /* HTML */;
13377 }
13378 }
13379 else if (parent && ns === 1 /* SVG */) {
13380 if (parent.tag === 'foreignObject' ||
13381 parent.tag === 'desc' ||
13382 parent.tag === 'title') {
13383 ns = 0 /* HTML */;
13384 }
13385 }
13386 if (ns === 0 /* HTML */) {
13387 if (tag === 'svg') {
13388 return 1 /* SVG */;
13389 }
13390 if (tag === 'math') {
13391 return 2 /* MATH_ML */;
13392 }
13393 }
13394 return ns;
13395 },
13396 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
13397 getTextMode({ tag, ns }) {
13398 if (ns === 0 /* HTML */) {
13399 if (tag === 'textarea' || tag === 'title') {
13400 return 1 /* RCDATA */;
13401 }
13402 if (isRawTextContainer(tag)) {
13403 return 2 /* RAWTEXT */;
13404 }
13405 }
13406 return 0 /* DATA */;
13407 }
13408 };
13409
13410 // Parse inline CSS strings for static style attributes into an object.
13411 // This is a NodeTransform since it works on the static `style` attribute and
13412 // converts it into a dynamic equivalent:
13413 // style="color: red" -> :style='{ "color": "red" }'
13414 // It is then processed by `transformElement` and included in the generated
13415 // props.
13416 const transformStyle = node => {
13417 if (node.type === 1 /* ELEMENT */) {
13418 node.props.forEach((p, i) => {
13419 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
13420 // replace p with an expression node
13421 node.props[i] = {
13422 type: 7 /* DIRECTIVE */,
13423 name: `bind`,
13424 arg: createSimpleExpression(`style`, true, p.loc),
13425 exp: parseInlineCSS(p.value.content, p.loc),
13426 modifiers: [],
13427 loc: p.loc
13428 };
13429 }
13430 });
13431 }
13432 };
13433 const parseInlineCSS = (cssText, loc) => {
13434 const normalized = parseStringStyle(cssText);
13435 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
13436 };
13437
13438 function createDOMCompilerError(code, loc) {
13439 return createCompilerError(code, loc, DOMErrorMessages );
13440 }
13441 const DOMErrorMessages = {
13442 [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
13443 [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
13444 [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
13445 [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
13446 [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
13447 [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
13448 [55 /* 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.`,
13449 [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
13450 [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
13451 [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
13452 [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
13453 };
13454
13455 const transformVHtml = (dir, node, context) => {
13456 const { exp, loc } = dir;
13457 if (!exp) {
13458 context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
13459 }
13460 if (node.children.length) {
13461 context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
13462 node.children.length = 0;
13463 }
13464 return {
13465 props: [
13466 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
13467 ]
13468 };
13469 };
13470
13471 const transformVText = (dir, node, context) => {
13472 const { exp, loc } = dir;
13473 if (!exp) {
13474 context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
13475 }
13476 if (node.children.length) {
13477 context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
13478 node.children.length = 0;
13479 }
13480 return {
13481 props: [
13482 createObjectProperty(createSimpleExpression(`textContent`, true), exp
13483 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
13484 : createSimpleExpression('', true))
13485 ]
13486 };
13487 };
13488
13489 const transformModel$1 = (dir, node, context) => {
13490 const baseResult = transformModel(dir, node, context);
13491 // base transform has errors OR component v-model (only need props)
13492 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
13493 return baseResult;
13494 }
13495 if (dir.arg) {
13496 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
13497 }
13498 function checkDuplicatedValue() {
13499 const value = findProp(node, 'value');
13500 if (value) {
13501 context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
13502 }
13503 }
13504 const { tag } = node;
13505 const isCustomElement = context.isCustomElement(tag);
13506 if (tag === 'input' ||
13507 tag === 'textarea' ||
13508 tag === 'select' ||
13509 isCustomElement) {
13510 let directiveToUse = V_MODEL_TEXT;
13511 let isInvalidType = false;
13512 if (tag === 'input' || isCustomElement) {
13513 const type = findProp(node, `type`);
13514 if (type) {
13515 if (type.type === 7 /* DIRECTIVE */) {
13516 // :type="foo"
13517 directiveToUse = V_MODEL_DYNAMIC;
13518 }
13519 else if (type.value) {
13520 switch (type.value.content) {
13521 case 'radio':
13522 directiveToUse = V_MODEL_RADIO;
13523 break;
13524 case 'checkbox':
13525 directiveToUse = V_MODEL_CHECKBOX;
13526 break;
13527 case 'file':
13528 isInvalidType = true;
13529 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
13530 break;
13531 default:
13532 // text type
13533 checkDuplicatedValue();
13534 break;
13535 }
13536 }
13537 }
13538 else if (hasDynamicKeyVBind(node)) {
13539 // element has bindings with dynamic keys, which can possibly contain
13540 // "type".
13541 directiveToUse = V_MODEL_DYNAMIC;
13542 }
13543 else {
13544 // text type
13545 checkDuplicatedValue();
13546 }
13547 }
13548 else if (tag === 'select') {
13549 directiveToUse = V_MODEL_SELECT;
13550 }
13551 else {
13552 // textarea
13553 checkDuplicatedValue();
13554 }
13555 // inject runtime directive
13556 // by returning the helper symbol via needRuntime
13557 // the import will replaced a resolveDirective call.
13558 if (!isInvalidType) {
13559 baseResult.needRuntime = context.helper(directiveToUse);
13560 }
13561 }
13562 else {
13563 context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
13564 }
13565 // native vmodel doesn't need the `modelValue` props since they are also
13566 // passed to the runtime as `binding.value`. removing it reduces code size.
13567 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
13568 p.key.content === 'modelValue'));
13569 return baseResult;
13570 };
13571
13572 const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
13573 const isNonKeyModifier = /*#__PURE__*/ makeMap(
13574 // event propagation management
13575`stop,prevent,self,` +
13576 // system modifiers + exact
13577 `ctrl,shift,alt,meta,exact,` +
13578 // mouse
13579 `middle`);
13580 // left & right could be mouse or key modifiers based on event type
13581 const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
13582 const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
13583 const resolveModifiers = (key, modifiers) => {
13584 const keyModifiers = [];
13585 const nonKeyModifiers = [];
13586 const eventOptionModifiers = [];
13587 for (let i = 0; i < modifiers.length; i++) {
13588 const modifier = modifiers[i];
13589 if (isEventOptionModifier(modifier)) {
13590 // eventOptionModifiers: modifiers for addEventListener() options,
13591 // e.g. .passive & .capture
13592 eventOptionModifiers.push(modifier);
13593 }
13594 else {
13595 // runtimeModifiers: modifiers that needs runtime guards
13596 if (maybeKeyModifier(modifier)) {
13597 if (isStaticExp(key)) {
13598 if (isKeyboardEvent(key.content)) {
13599 keyModifiers.push(modifier);
13600 }
13601 else {
13602 nonKeyModifiers.push(modifier);
13603 }
13604 }
13605 else {
13606 keyModifiers.push(modifier);
13607 nonKeyModifiers.push(modifier);
13608 }
13609 }
13610 else {
13611 if (isNonKeyModifier(modifier)) {
13612 nonKeyModifiers.push(modifier);
13613 }
13614 else {
13615 keyModifiers.push(modifier);
13616 }
13617 }
13618 }
13619 }
13620 return {
13621 keyModifiers,
13622 nonKeyModifiers,
13623 eventOptionModifiers
13624 };
13625 };
13626 const transformClick = (key, event) => {
13627 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
13628 return isStaticClick
13629 ? createSimpleExpression(event, true)
13630 : key.type !== 4 /* SIMPLE_EXPRESSION */
13631 ? createCompoundExpression([
13632 `(`,
13633 key,
13634 `) === "onClick" ? "${event}" : (`,
13635 key,
13636 `)`
13637 ])
13638 : key;
13639 };
13640 const transformOn$1 = (dir, node, context) => {
13641 return transformOn(dir, node, context, baseResult => {
13642 const { modifiers } = dir;
13643 if (!modifiers.length)
13644 return baseResult;
13645 let { key, value: handlerExp } = baseResult.props[0];
13646 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
13647 // normalize click.right and click.middle since they don't actually fire
13648 if (nonKeyModifiers.includes('right')) {
13649 key = transformClick(key, `onContextmenu`);
13650 }
13651 if (nonKeyModifiers.includes('middle')) {
13652 key = transformClick(key, `onMouseup`);
13653 }
13654 if (nonKeyModifiers.length) {
13655 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
13656 handlerExp,
13657 JSON.stringify(nonKeyModifiers)
13658 ]);
13659 }
13660 if (keyModifiers.length &&
13661 // if event name is dynamic, always wrap with keys guard
13662 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
13663 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
13664 handlerExp,
13665 JSON.stringify(keyModifiers)
13666 ]);
13667 }
13668 if (eventOptionModifiers.length) {
13669 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
13670 key = isStaticExp(key)
13671 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
13672 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
13673 }
13674 return {
13675 props: [createObjectProperty(key, handlerExp)]
13676 };
13677 });
13678 };
13679
13680 const transformShow = (dir, node, context) => {
13681 const { exp, loc } = dir;
13682 if (!exp) {
13683 context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
13684 }
13685 return {
13686 props: [],
13687 needRuntime: context.helper(V_SHOW)
13688 };
13689 };
13690
13691 const warnTransitionChildren = (node, context) => {
13692 if (node.type === 1 /* ELEMENT */ &&
13693 node.tagType === 1 /* COMPONENT */) {
13694 const component = context.isBuiltInComponent(node.tag);
13695 if (component === TRANSITION$1) {
13696 return () => {
13697 if (node.children.length && hasMultipleChildren(node)) {
13698 context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
13699 start: node.children[0].loc.start,
13700 end: node.children[node.children.length - 1].loc.end,
13701 source: ''
13702 }));
13703 }
13704 };
13705 }
13706 }
13707 };
13708 function hasMultipleChildren(node) {
13709 // #1352 filter out potential comment nodes.
13710 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
13711 const child = children[0];
13712 return (children.length !== 1 ||
13713 child.type === 11 /* FOR */ ||
13714 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
13715 }
13716
13717 const ignoreSideEffectTags = (node, context) => {
13718 if (node.type === 1 /* ELEMENT */ &&
13719 node.tagType === 0 /* ELEMENT */ &&
13720 (node.tag === 'script' || node.tag === 'style')) {
13721 context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
13722 context.removeNode();
13723 }
13724 };
13725
13726 const DOMNodeTransforms = [
13727 transformStyle,
13728 ...([warnTransitionChildren] )
13729 ];
13730 const DOMDirectiveTransforms = {
13731 cloak: noopDirectiveTransform,
13732 html: transformVHtml,
13733 text: transformVText,
13734 model: transformModel$1,
13735 on: transformOn$1,
13736 show: transformShow
13737 };
13738 function compile$1(template, options = {}) {
13739 return baseCompile(template, extend({}, parserOptions, options, {
13740 nodeTransforms: [
13741 // ignore <script> and <tag>
13742 // this is not put inside DOMNodeTransforms because that list is used
13743 // by compiler-ssr to generate vnode fallback branches
13744 ignoreSideEffectTags,
13745 ...DOMNodeTransforms,
13746 ...(options.nodeTransforms || [])
13747 ],
13748 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
13749 transformHoist: null
13750 }));
13751 }
13752
13753 // This entry is the "full-build" that includes both the runtime
13754 {
13755 initDev();
13756 }
13757 const compileCache = Object.create(null);
13758 function compileToFunction(template, options) {
13759 if (!isString(template)) {
13760 if (template.nodeType) {
13761 template = template.innerHTML;
13762 }
13763 else {
13764 warn(`invalid template option: `, template);
13765 return NOOP;
13766 }
13767 }
13768 const key = template;
13769 const cached = compileCache[key];
13770 if (cached) {
13771 return cached;
13772 }
13773 if (template[0] === '#') {
13774 const el = document.querySelector(template);
13775 if (!el) {
13776 warn(`Template element not found or is empty: ${template}`);
13777 }
13778 // __UNSAFE__
13779 // Reason: potential execution of JS expressions in in-DOM template.
13780 // The user must make sure the in-DOM template is trusted. If it's rendered
13781 // by the server, the template should not contain any user data.
13782 template = el ? el.innerHTML : ``;
13783 }
13784 const { code } = compile$1(template, extend({
13785 hoistStatic: true,
13786 onError(err) {
13787 {
13788 const message = `Template compilation error: ${err.message}`;
13789 const codeFrame = err.loc &&
13790 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
13791 warn(codeFrame ? `${message}\n${codeFrame}` : message);
13792 }
13793 }
13794 }, options));
13795 // The wildcard import results in a huge object with every export
13796 // with keys that cannot be mangled, and can be quite heavy size-wise.
13797 // In the global build we know `Vue` is available globally so we can avoid
13798 // the wildcard object.
13799 const render = (new Function(code)()
13800 );
13801 render._rc = true;
13802 return (compileCache[key] = render);
13803 }
13804 registerRuntimeCompiler(compileToFunction);
13805
13806 exports.BaseTransition = BaseTransition;
13807 exports.Comment = Comment;
13808 exports.Fragment = Fragment;
13809 exports.KeepAlive = KeepAlive;
13810 exports.Static = Static;
13811 exports.Suspense = Suspense;
13812 exports.Teleport = Teleport;
13813 exports.Text = Text;
13814 exports.Transition = Transition;
13815 exports.TransitionGroup = TransitionGroup;
13816 exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
13817 exports.callWithErrorHandling = callWithErrorHandling;
13818 exports.camelize = camelize;
13819 exports.capitalize = capitalize;
13820 exports.cloneVNode = cloneVNode;
13821 exports.compile = compileToFunction;
13822 exports.computed = computed$1;
13823 exports.createApp = createApp;
13824 exports.createBlock = createBlock;
13825 exports.createCommentVNode = createCommentVNode;
13826 exports.createHydrationRenderer = createHydrationRenderer;
13827 exports.createRenderer = createRenderer;
13828 exports.createSSRApp = createSSRApp;
13829 exports.createSlots = createSlots;
13830 exports.createStaticVNode = createStaticVNode;
13831 exports.createTextVNode = createTextVNode;
13832 exports.createVNode = createVNode;
13833 exports.customRef = customRef;
13834 exports.defineAsyncComponent = defineAsyncComponent;
13835 exports.defineComponent = defineComponent;
13836 exports.defineEmit = defineEmit;
13837 exports.defineProps = defineProps;
13838 exports.getCurrentInstance = getCurrentInstance;
13839 exports.getTransitionRawChildren = getTransitionRawChildren;
13840 exports.h = h;
13841 exports.handleError = handleError;
13842 exports.hydrate = hydrate;
13843 exports.initCustomFormatter = initCustomFormatter;
13844 exports.inject = inject;
13845 exports.isProxy = isProxy;
13846 exports.isReactive = isReactive;
13847 exports.isReadonly = isReadonly;
13848 exports.isRef = isRef;
13849 exports.isRuntimeOnly = isRuntimeOnly;
13850 exports.isVNode = isVNode;
13851 exports.markRaw = markRaw;
13852 exports.mergeProps = mergeProps;
13853 exports.nextTick = nextTick;
13854 exports.onActivated = onActivated;
13855 exports.onBeforeMount = onBeforeMount;
13856 exports.onBeforeUnmount = onBeforeUnmount;
13857 exports.onBeforeUpdate = onBeforeUpdate;
13858 exports.onDeactivated = onDeactivated;
13859 exports.onErrorCaptured = onErrorCaptured;
13860 exports.onMounted = onMounted;
13861 exports.onRenderTracked = onRenderTracked;
13862 exports.onRenderTriggered = onRenderTriggered;
13863 exports.onUnmounted = onUnmounted;
13864 exports.onUpdated = onUpdated;
13865 exports.openBlock = openBlock;
13866 exports.popScopeId = popScopeId;
13867 exports.provide = provide;
13868 exports.proxyRefs = proxyRefs;
13869 exports.pushScopeId = pushScopeId;
13870 exports.queuePostFlushCb = queuePostFlushCb;
13871 exports.reactive = reactive;
13872 exports.readonly = readonly;
13873 exports.ref = ref;
13874 exports.registerRuntimeCompiler = registerRuntimeCompiler;
13875 exports.render = render;
13876 exports.renderList = renderList;
13877 exports.renderSlot = renderSlot;
13878 exports.resolveComponent = resolveComponent;
13879 exports.resolveDirective = resolveDirective;
13880 exports.resolveDynamicComponent = resolveDynamicComponent;
13881 exports.resolveTransitionHooks = resolveTransitionHooks;
13882 exports.setBlockTracking = setBlockTracking;
13883 exports.setDevtoolsHook = setDevtoolsHook;
13884 exports.setTransitionHooks = setTransitionHooks;
13885 exports.shallowReactive = shallowReactive;
13886 exports.shallowReadonly = shallowReadonly;
13887 exports.shallowRef = shallowRef;
13888 exports.ssrContextKey = ssrContextKey;
13889 exports.ssrUtils = ssrUtils;
13890 exports.toDisplayString = toDisplayString;
13891 exports.toHandlerKey = toHandlerKey;
13892 exports.toHandlers = toHandlers;
13893 exports.toRaw = toRaw;
13894 exports.toRef = toRef;
13895 exports.toRefs = toRefs;
13896 exports.transformVNodeArgs = transformVNodeArgs;
13897 exports.triggerRef = triggerRef;
13898 exports.unref = unref;
13899 exports.useContext = useContext;
13900 exports.useCssModule = useCssModule;
13901 exports.useCssVars = useCssVars;
13902 exports.useSSRContext = useSSRContext;
13903 exports.useTransitionState = useTransitionState;
13904 exports.vModelCheckbox = vModelCheckbox;
13905 exports.vModelDynamic = vModelDynamic;
13906 exports.vModelRadio = vModelRadio;
13907 exports.vModelSelect = vModelSelect;
13908 exports.vModelText = vModelText;
13909 exports.vShow = vShow;
13910 exports.version = version;
13911 exports.warn = warn;
13912 exports.watch = watch;
13913 exports.watchEffect = watchEffect;
13914 exports.withCtx = withCtx;
13915 exports.withDirectives = withDirectives;
13916 exports.withKeys = withKeys;
13917 exports.withModifiers = withModifiers;
13918 exports.withScopeId = withScopeId;
13919
13920 Object.defineProperty(exports, '__esModule', { value: true });
13921
13922 return exports;
13923
13924}({}));