Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 | 3258x 3258x 3258x 3258x 3258x 2050x 751x 537x 3224x 3258x 3054x 204x 180x 24x 3258x 222x 473x 457x 228x 228x 228x 228x 228x 28x 19x 19x 33x 33x 1x 32x 32x 30x 2x 1x 1x 28x 28x 2x 2x 2x 2x 2x 2x 200x 55x 200x 292x 155x 154x 10x 1x 200x 189x 82x 9x 9x 228x 59x 228x 222x 3458x 3458x 3458x 980x 1883x 200x 1683x 1683x 1x 1683x 1x 1682x 1682x 1252x 1148x 104x 430x 393x 393x 1x 392x 14x 379x 358x 358x 3458x 667x 667x 667x 286x 286x 3458x 324x 324x 316x 316x 73x 73x 6x 6x 2x 4x 4x 4x 67x 73x 12x 316x 213x 116x 97x 11x 324x 94x 3355x 3355x 3355x 299x 3056x 3056x 3056x 3056x 3056x 2839x 96x 5x 96x 96x 96x 96x 2839x 16x 2839x 20x 2839x 45x 3056x 2645x 2465x 2645x 411x 184x 192x 192x 192x 192x 227x 163x 163x 1046x 1046x 1043x 1043x 1043x 1043x 1043x 1043x 555x 1158x 1158x 1158x 1x 1x 1157x 72x 488x 1043x 1043x 1043x 165x 411x 411x 387x 411x 1238x 1235x 3x 3x 3x 975x 1x 974x 974x 3446x 3446x 3446x 3446x 2347x 2347x 2347x 2347x 2347x 3x 3x 2344x 1056x 1288x 947x 947x 947x 947x 975x 975x 975x 947x 11x 11x 1277x 94x 975x 975x 1x 974x 928x 928x 928x 16x 46x 18x 28x 12x 16x 975x 11x 1x 10x 10x 10x 10x 10x 10x 2x 10x 10x 7x 10x 20x 2x 18x 6x 12x 2x 10x 20x 44x 5x 8x 8x | import {
TriggerOpTypes,
shallowReactive,
shallowReadonly,
toRaw,
trigger,
} from '@vue/reactivity'
import {
EMPTY_ARR,
EMPTY_OBJ,
type IfAny,
PatchFlags,
camelize,
capitalize,
extend,
hasOwn,
hyphenate,
isArray,
isFunction,
isObject,
isOn,
isReservedProp,
isString,
isSymbol,
makeMap,
toRawType,
} from '@vue/shared'
import { warn } from './warning'
import {
type ComponentInternalInstance,
type ComponentOptions,
type ConcreteComponent,
type Data,
setCurrentInstance,
} from './component'
import { isEmitListener } from './componentEmits'
import type { AppContext } from './apiCreateApp'
import { createPropsDefaultThis } from './compat/props'
import { isCompatEnabled, softAssertCompatEnabled } from './compat/compatConfig'
import { DeprecationTypes } from './compat/compatConfig'
import { shouldSkipAttr } from './compat/attrsFallthrough'
import { createInternalObject } from './internalObject'
export type ComponentPropsOptions<P = Data> =
ComponentObjectPropsOptions<P> | string[]
export type ComponentObjectPropsOptions<P = Data> = {
[K in keyof P]: Prop<P[K]> | null
}
export type Prop<T, D = T> = PropOptions<T, D> | PropType<T>
type DefaultFactory<T> = (props: Data) => T | null | undefined
export interface PropOptions<T = any, D = T> {
type?: PropType<T> | true | null
required?: boolean
default?: D | DefaultFactory<D> | null | undefined | object
validator?(value: unknown, props: Data): boolean
/**
* @internal
*/
skipCheck?: boolean
/**
* @internal
*/
skipFactory?: boolean
}
export type PropType<T> = PropConstructor<T> | (PropConstructor<T> | null)[]
type PropConstructor<T = any> =
{ new (...args: any[]): T & {} } | { (): T } | PropMethod<T>
// Function-like constructor so that `Function as PropType<() => void>`
// type-checks. Intentionally not conditional on `T`: a conditional type here
// makes `PropType<T>` a deferred (generic) type whenever `T` is a type
// parameter, which in turn defers `RequiredKeys` / `OptionalKeys` and drops
// every non-required prop from `ExtractPropTypes` (#9546).
type PropMethod<T, TConstructor = any> = {
new (): TConstructor
(): T
readonly prototype: TConstructor
}
type RequiredKeys<T> = {
[K in keyof T]: T[K] extends
| { required: true }
| { default: any }
// don't mark Boolean props as undefined
| BooleanConstructor
| { type: BooleanConstructor }
? T[K] extends { default: undefined | (() => undefined) }
? never
: K
: never
}[keyof T]
type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>
type DefaultKeys<T> = {
[K in keyof T]: T[K] extends
| { default: any }
// Boolean implicitly defaults to false
| BooleanConstructor
| { type: BooleanConstructor }
? T[K] extends { type: BooleanConstructor; required: true } // not default if Boolean is marked as required
? never
: K
: never
}[keyof T]
type InferPropType<T, NullAsAny = true> = [T] extends [null]
? NullAsAny extends true
? any
: null
: [T] extends [{ type: null | true }]
? any // As TS issue https://github.com/Microsoft/TypeScript/issues/14829 // somehow `ObjectConstructor` when inferred from { (): T } becomes `any` // `BooleanConstructor` when inferred from PropConstructor(with PropMethod) becomes `Boolean`
: [T] extends [ObjectConstructor | { type: ObjectConstructor }]
? Record<string, any>
: [T] extends [BooleanConstructor | { type: BooleanConstructor }]
? boolean
: [T] extends [DateConstructor | { type: DateConstructor }]
? Date
: [T] extends [(infer U)[] | { type: (infer U)[] }]
? U extends DateConstructor
? Date | InferPropType<U, false>
: InferPropType<U, false>
: [T] extends [Prop<infer V, infer D>]
? unknown extends V
? keyof V extends never
? // `D` is only meaningful when a default is present; falling
// back to `V` keeps the deferred type assignable to `V`
// when `V` is a type parameter (#9546)
IfAny<V, V, unknown extends D ? V : D>
: V
: V
: T
/**
* Extract prop types from a runtime props options object.
* The extracted types are **internal** - i.e. the resolved props received by
* the component.
* - Boolean props are always present
* - Props with default values are always present
*
* To extract accepted props from the parent, use {@link ExtractPublicPropTypes}.
*/
export type ExtractPropTypes<O> = {
// use `keyof Pick<O, RequiredKeys<O>>` instead of `RequiredKeys<O>` to
// support IDE features
[K in keyof Pick<O, RequiredKeys<O>>]: O[K] extends { default: any }
? Exclude<InferPropType<O[K]>, undefined>
: InferPropType<O[K]>
} & {
// use `keyof Pick<O, OptionalKeys<O>>` instead of `OptionalKeys<O>` to
// support IDE features
[K in keyof Pick<O, OptionalKeys<O>>]?: InferPropType<O[K]>
}
type PublicRequiredKeys<T> = {
[K in keyof T]: T[K] extends { required: true } ? K : never
}[keyof T]
type PublicOptionalKeys<T> = Exclude<keyof T, PublicRequiredKeys<T>>
/**
* Extract prop types from a runtime props options object.
* The extracted types are **public** - i.e. the expected props that can be
* passed to component.
*/
export type ExtractPublicPropTypes<O> = {
[K in keyof Pick<O, PublicRequiredKeys<O>>]: InferPropType<O[K]>
} & {
[K in keyof Pick<O, PublicOptionalKeys<O>>]?: InferPropType<O[K]>
}
enum BooleanFlags {
shouldCast,
shouldCastTrue,
}
// extract props which defined with default from prop options
export type ExtractDefaultPropTypes<O> = O extends object
? // use `keyof Pick<O, DefaultKeys<O>>` instead of `DefaultKeys<O>` to support IDE features
{ [K in keyof Pick<O, DefaultKeys<O>>]: InferPropType<O[K]> }
: {}
type NormalizedProp = PropOptions & {
[BooleanFlags.shouldCast]?: boolean
[BooleanFlags.shouldCastTrue]?: boolean
}
// normalized value is a tuple of the actual normalized options
// and an array of prop keys that need value casting (booleans and defaults)
export type NormalizedProps = Record<string, NormalizedProp>
export type NormalizedPropsOptions = [NormalizedProps, string[]] | []
export function initProps(
instance: ComponentInternalInstance,
rawProps: Data | null,
isStateful: number, // result of bitwise flag comparison
isSSR = false,
): void {
const props: Data = {}
const attrs: Data = createInternalObject()
instance.propsDefaults = Object.create(null)
setFullProps(instance, rawProps, props, attrs)
// ensure all declared prop keys are present
for (const key in instance.propsOptions[0]) {
if (!(key in props)) {
props[key] = undefined
}
}
// validation
if (__DEV__) {
validateProps(rawProps || {}, props, instance)
}
if (isStateful) {
// stateful
instance.props = isSSR ? props : shallowReactive(props)
} else {
if (!instance.type.props) {
// functional w/ optional props, props === attrs
instance.props = attrs
} else {
// functional w/ declared props
instance.props = props
}
}
instance.attrs = attrs
}
function isInHmrContext(instance: ComponentInternalInstance | null) {
while (instance) {
if (instance.type.__hmrId) return true
instance = instance.parent
}
}
export function updateProps(
instance: ComponentInternalInstance,
rawProps: Data | null,
rawPrevProps: Data | null,
optimized: boolean,
): void {
const {
props,
attrs,
vnode: { patchFlag },
} = instance
const rawCurrentProps = toRaw(props)
const [options] = instance.propsOptions
let hasAttrsChanged = false
if (
// always force full diff in dev
// - #1942 if hmr is enabled with sfc component
// - vite#872 non-sfc component used by sfc component
!(__DEV__ && isInHmrContext(instance)) &&
(optimized || patchFlag > 0) &&
!(patchFlag & PatchFlags.FULL_PROPS)
) {
if (patchFlag & PatchFlags.PROPS) {
// Compiler-generated props & no keys change, just set the updated
// the props.
const propsToUpdate = instance.vnode.dynamicProps!
for (let i = 0; i < propsToUpdate.length; i++) {
let key = propsToUpdate[i]
// skip if the prop key is a declared emit event listener
if (isEmitListener(instance.emitsOptions, key)) {
continue
}
// PROPS flag guarantees rawProps to be non-null
const value = rawProps![key]
if (options) {
// attr / props separation was done on init and will be consistent
// in this code path, so just check if attrs have it.
if (hasOwn(attrs, key)) {
if (value !== attrs[key]) {
attrs[key] = value
hasAttrsChanged = true
}
} else {
const camelizedKey = camelize(key)
props[camelizedKey] = resolvePropValue(
options,
rawCurrentProps,
camelizedKey,
value,
instance,
false /* isAbsent */,
)
}
} else {
Eif (__COMPAT__) {
Iif (isOn(key) && key.endsWith('Native')) {
key = key.slice(0, -6) // remove Native postfix
} else Iif (shouldSkipAttr(key, instance)) {
continue
}
}
Eif (value !== attrs[key]) {
attrs[key] = value
hasAttrsChanged = true
}
}
}
}
} else {
// full props update.
if (setFullProps(instance, rawProps, props, attrs)) {
hasAttrsChanged = true
}
// in case of dynamic props, check if we need to delete keys from
// the props object
let kebabKey: string
for (const key in rawCurrentProps) {
if (
!rawProps ||
// for camelCase
(!hasOwn(rawProps, key) &&
// it's possible the original props was passed in as kebab-case
// and converted to camelCase (#955)
((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))
) {
if (options) {
if (
rawPrevProps &&
// for camelCase
(rawPrevProps[key] !== undefined ||
// for kebab-case
rawPrevProps[kebabKey!] !== undefined)
) {
props[key] = resolvePropValue(
options,
rawCurrentProps,
key,
undefined,
instance,
true /* isAbsent */,
)
}
} else {
delete props[key]
}
}
}
// in the case of functional component w/o props declaration, props and
// attrs point to the same object so it should already have been updated.
if (attrs !== rawCurrentProps) {
for (const key in attrs) {
if (
!rawProps ||
(!hasOwn(rawProps, key) &&
(!__COMPAT__ || !hasOwn(rawProps, key + 'Native')))
) {
delete attrs[key]
hasAttrsChanged = true
}
}
}
}
// trigger updates for $attrs in case it's used in component slots
if (hasAttrsChanged) {
trigger(instance.attrs, TriggerOpTypes.SET, '')
}
if (__DEV__) {
validateProps(rawProps || {}, props, instance)
}
}
function setFullProps(
instance: ComponentInternalInstance,
rawProps: Data | null,
props: Data,
attrs: Data,
) {
const [options, needCastKeys] = instance.propsOptions
let hasAttrsChanged = false
let rawCastValues: Data | undefined
if (rawProps) {
for (let key in rawProps) {
// key, ref are reserved and never passed down
if (isReservedProp(key)) {
continue
}
Eif (__COMPAT__) {
if (key.startsWith('onHook:')) {
softAssertCompatEnabled(
DeprecationTypes.INSTANCE_EVENT_HOOKS,
instance,
key.slice(2).toLowerCase(),
)
}
if (key === 'inline-template') {
continue
}
}
const value = rawProps[key]
// prop option names are camelized during normalization, so to support
// kebab -> camel conversion here we need to camelize the key.
let camelKey
if (options && hasOwn(options, (camelKey = camelize(key)))) {
if (!needCastKeys || !needCastKeys.includes(camelKey)) {
props[camelKey] = value
} else {
;(rawCastValues || (rawCastValues = {}))[camelKey] = value
}
} else if (!isEmitListener(instance.emitsOptions, key)) {
// Any non-declared (either as a prop or an emitted event) props are put
// into a separate `attrs` object for spreading. Make sure to preserve
// original key casing
Eif (__COMPAT__) {
if (isOn(key) && key.endsWith('Native')) {
key = key.slice(0, -6) // remove Native postfix
} else if (shouldSkipAttr(key, instance)) {
continue
}
}
if (!(key in attrs) || value !== attrs[key]) {
attrs[key] = value
hasAttrsChanged = true
}
}
}
}
if (needCastKeys) {
const rawCurrentProps = toRaw(props)
const castValues = rawCastValues || EMPTY_OBJ
for (let i = 0; i < needCastKeys.length; i++) {
const key = needCastKeys[i]
props[key] = resolvePropValue(
options!,
rawCurrentProps,
key,
castValues[key],
instance,
!hasOwn(castValues, key),
)
}
}
return hasAttrsChanged
}
function resolvePropValue(
options: NormalizedProps,
props: Data,
key: string,
value: unknown,
instance: ComponentInternalInstance,
isAbsent: boolean,
) {
const opt = options[key]
if (opt != null) {
const hasDefault = hasOwn(opt, 'default')
// default values
if (hasDefault && value === undefined) {
const defaultValue = opt.default
if (
opt.type !== Function &&
!opt.skipFactory &&
isFunction(defaultValue)
) {
const { propsDefaults } = instance
if (key in propsDefaults) {
value = propsDefaults[key]
} else {
const reset = setCurrentInstance(instance)
value = propsDefaults[key] = defaultValue.call(
__COMPAT__ &&
isCompatEnabled(DeprecationTypes.PROPS_DEFAULT_THIS, instance)
? createPropsDefaultThis(instance, props, key)
: null,
props,
)
reset()
}
} else {
value = defaultValue
}
// #9006 reflect default value on custom element
if (instance.ce) {
instance.ce._setProp(key, value)
}
}
// boolean casting
if (opt[BooleanFlags.shouldCast]) {
if (isAbsent && !hasDefault) {
value = false
} else if (
opt[BooleanFlags.shouldCastTrue] &&
(value === '' || value === hyphenate(key))
) {
value = true
}
}
}
return value
}
const mixinPropsCache = new WeakMap<ConcreteComponent, NormalizedPropsOptions>()
export function normalizePropsOptions(
comp: ConcreteComponent,
appContext: AppContext,
asMixin = false,
): NormalizedPropsOptions {
const cache =
__FEATURE_OPTIONS_API__ && asMixin ? mixinPropsCache : appContext.propsCache
const cached = cache.get(comp)
if (cached) {
return cached
}
const raw = comp.props
const normalized: NormalizedPropsOptions[0] = {}
const needCastKeys: NormalizedPropsOptions[1] = []
// apply mixin/extends props
let hasExtends = false
if (__FEATURE_OPTIONS_API__ && !isFunction(comp)) {
const extendProps = (raw: ComponentOptions) => {
if (__COMPAT__ && isFunction(raw)) {
raw = raw.options
}
hasExtends = true
const [props, keys] = normalizePropsOptions(raw, appContext, true)
extend(normalized, props)
if (keys) needCastKeys.push(...keys)
}
if (!asMixin && appContext.mixins.length) {
appContext.mixins.forEach(extendProps)
}
if (comp.extends) {
extendProps(comp.extends)
}
if (comp.mixins) {
comp.mixins.forEach(extendProps)
}
}
if (!raw && !hasExtends) {
if (isObject(comp)) {
cache.set(comp, EMPTY_ARR as any)
}
return EMPTY_ARR as any
}
if (isArray(raw)) {
for (let i = 0; i < raw.length; i++) {
Iif (__DEV__ && !isString(raw[i])) {
warn(`props must be strings when using array syntax.`, raw[i])
}
const normalizedKey = camelize(raw[i])
Eif (validatePropName(normalizedKey)) {
normalized[normalizedKey] = EMPTY_OBJ
}
}
} else if (raw) {
Iif (__DEV__ && !isObject(raw)) {
warn(`invalid props options`, raw)
}
for (const key in raw) {
const normalizedKey = camelize(key)
if (validatePropName(normalizedKey)) {
const opt = raw[key]
const prop: NormalizedProp = (normalized[normalizedKey] =
isArray(opt) || isFunction(opt) ? { type: opt } : extend({}, opt))
const propType = prop.type
let shouldCast = false
let shouldCastTrue = true
if (isArray(propType)) {
for (let index = 0; index < propType.length; ++index) {
const type = propType[index]
const typeName = isFunction(type) && type.name
if (typeName === 'Boolean') {
shouldCast = true
break
} else if (typeName === 'String') {
// If we find `String` before `Boolean`, e.g. `[String, Boolean]`,
// we need to handle the casting slightly differently. Props
// passed as `<Comp checked="">` or `<Comp checked="checked">`
// will either be treated as strings or converted to a boolean
// `true`, depending on the order of the types.
shouldCastTrue = false
}
}
} else {
shouldCast = isFunction(propType) && propType.name === 'Boolean'
}
prop[BooleanFlags.shouldCast] = shouldCast
prop[BooleanFlags.shouldCastTrue] = shouldCastTrue
// if the prop needs boolean casting or default value
if (shouldCast || hasOwn(prop, 'default')) {
needCastKeys.push(normalizedKey)
}
}
}
}
const res: NormalizedPropsOptions = [normalized, needCastKeys]
if (isObject(comp)) {
cache.set(comp, res)
}
return res
}
function validatePropName(key: string) {
if (key[0] !== '$' && !isReservedProp(key)) {
return true
} else Eif (__DEV__) {
warn(`Invalid prop name: "${key}" is a reserved property.`)
}
return false
}
// dev only
// use function string name to check type constructors
// so that it works across vms / iframes.
function getType(ctor: Prop<any> | null): string {
// Early return for null to avoid unnecessary computations
if (ctor === null) {
return 'null'
}
// Avoid using regex for common cases by checking the type directly
if (typeof ctor === 'function') {
// Using name property to avoid converting function to string
return ctor.name || ''
} else Eif (typeof ctor === 'object') {
// Attempting to directly access constructor name if possible
const name = ctor.constructor && ctor.constructor.name
return name || ''
}
// Fallback for other types (though they're less likely to have meaningful names here)
return ''
}
/**
* dev only
*/
function validateProps(
rawProps: Data,
props: Data,
instance: ComponentInternalInstance,
) {
const resolvedValues = toRaw(props)
const options = instance.propsOptions[0]
const camelizePropsKey = Object.keys(rawProps).map(key => camelize(key))
for (const key in options) {
let opt = options[key]
Iif (opt == null) continue
validateProp(
key,
resolvedValues[key],
opt,
__DEV__ ? shallowReadonly(resolvedValues) : resolvedValues,
!camelizePropsKey.includes(key),
)
}
}
/**
* dev only
*/
function validateProp(
name: string,
value: unknown,
prop: PropOptions,
props: Data,
isAbsent: boolean,
) {
const { type, required, validator, skipCheck } = prop
// required!
if (required && isAbsent) {
warn('Missing required prop: "' + name + '"')
return
}
// missing but optional
if (value == null && !required) {
return
}
// type check
if (type != null && type !== true && !skipCheck) {
let isValid = false
const types = isArray(type) ? type : [type]
const expectedTypes = []
// value is valid as long as one of the specified types match
for (let i = 0; i < types.length && !isValid; i++) {
const { valid, expectedType } = assertType(value, types[i])
expectedTypes.push(expectedType || '')
isValid = valid
}
if (!isValid) {
warn(getInvalidTypeMessage(name, value, expectedTypes))
return
}
}
// custom validator
Iif (validator && !validator(value, props)) {
warn('Invalid prop: custom validator check failed for prop "' + name + '".')
}
}
const isSimpleType = /*@__PURE__*/ makeMap(
'String,Number,Boolean,Function,Symbol,BigInt',
)
type AssertionResult = {
valid: boolean
expectedType: string
}
/**
* dev only
*/
function assertType(
value: unknown,
type: PropConstructor | null,
): AssertionResult {
let valid
const expectedType = getType(type)
if (expectedType === 'null') {
valid = value === null
} else if (isSimpleType(expectedType)) {
const t = typeof value
valid = t === expectedType.toLowerCase()
// for primitive wrapper objects
if (!valid && t === 'object') {
valid = value instanceof (type as PropConstructor)
}
} else if (expectedType === 'Object') {
valid = isObject(value)
} else if (expectedType === 'Array') {
valid = isArray(value)
} else {
valid = value instanceof (type as PropConstructor)
}
return {
valid,
expectedType,
}
}
/**
* dev only
*/
function getInvalidTypeMessage(
name: string,
value: unknown,
expectedTypes: string[],
): string {
if (expectedTypes.length === 0) {
return (
`Prop type [] for prop "${name}" won't match anything.` +
` Did you mean to use type Array instead?`
)
}
let message =
`Invalid prop: type check failed for prop "${name}".` +
` Expected ${expectedTypes.map(capitalize).join(' | ')}`
const expectedType = expectedTypes[0]
const receivedType = toRawType(value)
const expectedValue = styleValue(value, expectedType)
const receivedValue = styleValue(value, receivedType)
// check if we need to specify expected value
if (
expectedTypes.length === 1 &&
isExplicable(expectedType) &&
isCoercible(expectedType, receivedType)
) {
message += ` with value ${expectedValue}`
}
message += `, got ${receivedType} `
// check if we need to specify received value
if (isExplicable(receivedType)) {
message += `with value ${receivedValue}.`
}
return message
}
/**
* dev only
*/
function styleValue(value: unknown, type: string): string {
if (isSymbol(value)) {
return value.toString()
} else if (type === 'String') {
return `"${value}"`
} else if (type === 'Number') {
return `${Number(value)}`
} else {
return `${value}`
}
}
/**
* dev only
*/
function isExplicable(type: string): boolean {
const explicitTypes = ['string', 'number', 'boolean']
return explicitTypes.some(elem => type.toLowerCase() === elem)
}
/**
* dev only
*/
function isCoercible(...args: string[]): boolean {
return args.every(elem => {
const value = elem.toLowerCase()
return value !== 'boolean' && value !== 'symbol'
})
}
|