shared.esm-bundler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* TEXT */]: `TEXT`,
  21. [2 /* CLASS */]: `CLASS`,
  22. [4 /* STYLE */]: `STYLE`,
  23. [8 /* PROPS */]: `PROPS`,
  24. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* HOISTED */]: `HOISTED`,
  33. [-2 /* BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* STABLE */]: 'STABLE',
  40. [2 /* DYNAMIC */]: 'DYNAMIC',
  41. [3 /* FORWARDED */]: 'FORWARDED'
  42. };
  43. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  44. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  45. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  46. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  47. const range = 2;
  48. function generateCodeFrame(source, start = 0, end = source.length) {
  49. const lines = source.split(/\r?\n/);
  50. let count = 0;
  51. const res = [];
  52. for (let i = 0; i < lines.length; i++) {
  53. count += lines[i].length + 1;
  54. if (count >= start) {
  55. for (let j = i - range; j <= i + range || end > count; j++) {
  56. if (j < 0 || j >= lines.length)
  57. continue;
  58. const line = j + 1;
  59. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  60. const lineLength = lines[j].length;
  61. if (j === i) {
  62. // push underline
  63. const pad = start - (count - lineLength) + 1;
  64. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  65. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  66. }
  67. else if (j > i) {
  68. if (end > count) {
  69. const length = Math.max(Math.min(end - count, lineLength), 1);
  70. res.push(` | ` + '^'.repeat(length));
  71. }
  72. count += lineLength + 1;
  73. }
  74. }
  75. break;
  76. }
  77. }
  78. return res.join('\n');
  79. }
  80. /**
  81. * On the client we only need to offer special cases for boolean attributes that
  82. * have different names from their corresponding dom properties:
  83. * - itemscope -> N/A
  84. * - allowfullscreen -> allowFullscreen
  85. * - formnovalidate -> formNoValidate
  86. * - ismap -> isMap
  87. * - nomodule -> noModule
  88. * - novalidate -> noValidate
  89. * - readonly -> readOnly
  90. */
  91. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  92. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  93. /**
  94. * The full list is needed during SSR to produce the correct initial markup.
  95. */
  96. const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
  97. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  98. `loop,open,required,reversed,scoped,seamless,` +
  99. `checked,muted,multiple,selected`);
  100. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  101. const attrValidationCache = {};
  102. function isSSRSafeAttrName(name) {
  103. if (attrValidationCache.hasOwnProperty(name)) {
  104. return attrValidationCache[name];
  105. }
  106. const isUnsafe = unsafeAttrCharRE.test(name);
  107. if (isUnsafe) {
  108. console.error(`unsafe attribute name: ${name}`);
  109. }
  110. return (attrValidationCache[name] = !isUnsafe);
  111. }
  112. const propsToAttrMap = {
  113. acceptCharset: 'accept-charset',
  114. className: 'class',
  115. htmlFor: 'for',
  116. httpEquiv: 'http-equiv'
  117. };
  118. /**
  119. * CSS properties that accept plain numbers
  120. */
  121. const isNoUnitNumericStyleProp = /*#__PURE__*/ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,` +
  122. `border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,` +
  123. `columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,` +
  124. `grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,` +
  125. `grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,` +
  126. `line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,` +
  127. // SVG
  128. `fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,` +
  129. `stroke-miterlimit,stroke-opacity,stroke-width`);
  130. /**
  131. * Known attributes, this is used for stringification of runtime static nodes
  132. * so that we don't stringify bindings that cannot be set from HTML.
  133. * Don't also forget to allow `data-*` and `aria-*`!
  134. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  135. */
  136. const isKnownAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  137. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  138. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  139. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  140. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  141. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  142. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  143. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
  144. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  145. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  146. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  147. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  148. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  149. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  150. `value,width,wrap`);
  151. function normalizeStyle(value) {
  152. if (isArray(value)) {
  153. const res = {};
  154. for (let i = 0; i < value.length; i++) {
  155. const item = value[i];
  156. const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
  157. if (normalized) {
  158. for (const key in normalized) {
  159. res[key] = normalized[key];
  160. }
  161. }
  162. }
  163. return res;
  164. }
  165. else if (isObject(value)) {
  166. return value;
  167. }
  168. }
  169. const listDelimiterRE = /;(?![^(]*\))/g;
  170. const propertyDelimiterRE = /:(.+)/;
  171. function parseStringStyle(cssText) {
  172. const ret = {};
  173. cssText.split(listDelimiterRE).forEach(item => {
  174. if (item) {
  175. const tmp = item.split(propertyDelimiterRE);
  176. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  177. }
  178. });
  179. return ret;
  180. }
  181. function stringifyStyle(styles) {
  182. let ret = '';
  183. if (!styles) {
  184. return ret;
  185. }
  186. for (const key in styles) {
  187. const value = styles[key];
  188. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  189. if (isString(value) ||
  190. (typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))) {
  191. // only render valid values
  192. ret += `${normalizedKey}:${value};`;
  193. }
  194. }
  195. return ret;
  196. }
  197. function normalizeClass(value) {
  198. let res = '';
  199. if (isString(value)) {
  200. res = value;
  201. }
  202. else if (isArray(value)) {
  203. for (let i = 0; i < value.length; i++) {
  204. const normalized = normalizeClass(value[i]);
  205. if (normalized) {
  206. res += normalized + ' ';
  207. }
  208. }
  209. }
  210. else if (isObject(value)) {
  211. for (const name in value) {
  212. if (value[name]) {
  213. res += name + ' ';
  214. }
  215. }
  216. }
  217. return res.trim();
  218. }
  219. // These tag configs are shared between compiler-dom and runtime-dom, so they
  220. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  221. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  222. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  223. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  224. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  225. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  226. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  227. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  228. 'option,output,progress,select,textarea,details,dialog,menu,' +
  229. 'summary,template,blockquote,iframe,tfoot';
  230. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  231. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  232. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  233. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  234. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  235. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  236. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  237. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  238. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  239. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  240. 'text,textPath,title,tspan,unknown,use,view';
  241. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  242. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  243. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  244. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  245. const escapeRE = /["'&<>]/;
  246. function escapeHtml(string) {
  247. const str = '' + string;
  248. const match = escapeRE.exec(str);
  249. if (!match) {
  250. return str;
  251. }
  252. let html = '';
  253. let escaped;
  254. let index;
  255. let lastIndex = 0;
  256. for (index = match.index; index < str.length; index++) {
  257. switch (str.charCodeAt(index)) {
  258. case 34: // "
  259. escaped = '&quot;';
  260. break;
  261. case 38: // &
  262. escaped = '&amp;';
  263. break;
  264. case 39: // '
  265. escaped = '&#39;';
  266. break;
  267. case 60: // <
  268. escaped = '&lt;';
  269. break;
  270. case 62: // >
  271. escaped = '&gt;';
  272. break;
  273. default:
  274. continue;
  275. }
  276. if (lastIndex !== index) {
  277. html += str.substring(lastIndex, index);
  278. }
  279. lastIndex = index + 1;
  280. html += escaped;
  281. }
  282. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  283. }
  284. // https://www.w3.org/TR/html52/syntax.html#comments
  285. const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;
  286. function escapeHtmlComment(src) {
  287. return src.replace(commentStripRE, '');
  288. }
  289. function looseCompareArrays(a, b) {
  290. if (a.length !== b.length)
  291. return false;
  292. let equal = true;
  293. for (let i = 0; equal && i < a.length; i++) {
  294. equal = looseEqual(a[i], b[i]);
  295. }
  296. return equal;
  297. }
  298. function looseEqual(a, b) {
  299. if (a === b)
  300. return true;
  301. let aValidType = isDate(a);
  302. let bValidType = isDate(b);
  303. if (aValidType || bValidType) {
  304. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  305. }
  306. aValidType = isArray(a);
  307. bValidType = isArray(b);
  308. if (aValidType || bValidType) {
  309. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  310. }
  311. aValidType = isObject(a);
  312. bValidType = isObject(b);
  313. if (aValidType || bValidType) {
  314. /* istanbul ignore if: this if will probably never be called */
  315. if (!aValidType || !bValidType) {
  316. return false;
  317. }
  318. const aKeysCount = Object.keys(a).length;
  319. const bKeysCount = Object.keys(b).length;
  320. if (aKeysCount !== bKeysCount) {
  321. return false;
  322. }
  323. for (const key in a) {
  324. const aHasKey = a.hasOwnProperty(key);
  325. const bHasKey = b.hasOwnProperty(key);
  326. if ((aHasKey && !bHasKey) ||
  327. (!aHasKey && bHasKey) ||
  328. !looseEqual(a[key], b[key])) {
  329. return false;
  330. }
  331. }
  332. }
  333. return String(a) === String(b);
  334. }
  335. function looseIndexOf(arr, val) {
  336. return arr.findIndex(item => looseEqual(item, val));
  337. }
  338. /**
  339. * For converting {{ interpolation }} values to displayed strings.
  340. * @private
  341. */
  342. const toDisplayString = (val) => {
  343. return val == null
  344. ? ''
  345. : isObject(val)
  346. ? JSON.stringify(val, replacer, 2)
  347. : String(val);
  348. };
  349. const replacer = (_key, val) => {
  350. if (isMap(val)) {
  351. return {
  352. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  353. entries[`${key} =>`] = val;
  354. return entries;
  355. }, {})
  356. };
  357. }
  358. else if (isSet(val)) {
  359. return {
  360. [`Set(${val.size})`]: [...val.values()]
  361. };
  362. }
  363. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  364. return String(val);
  365. }
  366. return val;
  367. };
  368. /**
  369. * List of @babel/parser plugins that are used for template expression
  370. * transforms and SFC script transforms. By default we enable proposals slated
  371. * for ES2020. This will need to be updated as the spec moves forward.
  372. * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
  373. */
  374. const babelParserDefaultPlugins = [
  375. 'bigInt',
  376. 'optionalChaining',
  377. 'nullishCoalescingOperator'
  378. ];
  379. const EMPTY_OBJ = (process.env.NODE_ENV !== 'production')
  380. ? Object.freeze({})
  381. : {};
  382. const EMPTY_ARR = (process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
  383. const NOOP = () => { };
  384. /**
  385. * Always return false.
  386. */
  387. const NO = () => false;
  388. const onRE = /^on[^a-z]/;
  389. const isOn = (key) => onRE.test(key);
  390. const isModelListener = (key) => key.startsWith('onUpdate:');
  391. const extend = Object.assign;
  392. const remove = (arr, el) => {
  393. const i = arr.indexOf(el);
  394. if (i > -1) {
  395. arr.splice(i, 1);
  396. }
  397. };
  398. const hasOwnProperty = Object.prototype.hasOwnProperty;
  399. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  400. const isArray = Array.isArray;
  401. const isMap = (val) => toTypeString(val) === '[object Map]';
  402. const isSet = (val) => toTypeString(val) === '[object Set]';
  403. const isDate = (val) => val instanceof Date;
  404. const isFunction = (val) => typeof val === 'function';
  405. const isString = (val) => typeof val === 'string';
  406. const isSymbol = (val) => typeof val === 'symbol';
  407. const isObject = (val) => val !== null && typeof val === 'object';
  408. const isPromise = (val) => {
  409. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  410. };
  411. const objectToString = Object.prototype.toString;
  412. const toTypeString = (value) => objectToString.call(value);
  413. const toRawType = (value) => {
  414. // extract "RawType" from strings like "[object RawType]"
  415. return toTypeString(value).slice(8, -1);
  416. };
  417. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  418. const isIntegerKey = (key) => isString(key) &&
  419. key !== 'NaN' &&
  420. key[0] !== '-' &&
  421. '' + parseInt(key, 10) === key;
  422. const isReservedProp = /*#__PURE__*/ makeMap(
  423. // the leading comma is intentional so empty string "" is also included
  424. ',key,ref,' +
  425. 'onVnodeBeforeMount,onVnodeMounted,' +
  426. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  427. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  428. const cacheStringFunction = (fn) => {
  429. const cache = Object.create(null);
  430. return ((str) => {
  431. const hit = cache[str];
  432. return hit || (cache[str] = fn(str));
  433. });
  434. };
  435. const camelizeRE = /-(\w)/g;
  436. /**
  437. * @private
  438. */
  439. const camelize = cacheStringFunction((str) => {
  440. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  441. });
  442. const hyphenateRE = /\B([A-Z])/g;
  443. /**
  444. * @private
  445. */
  446. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  447. /**
  448. * @private
  449. */
  450. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  451. /**
  452. * @private
  453. */
  454. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  455. // compare whether a value has changed, accounting for NaN.
  456. const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
  457. const invokeArrayFns = (fns, arg) => {
  458. for (let i = 0; i < fns.length; i++) {
  459. fns[i](arg);
  460. }
  461. };
  462. const def = (obj, key, value) => {
  463. Object.defineProperty(obj, key, {
  464. configurable: true,
  465. enumerable: false,
  466. value
  467. });
  468. };
  469. const toNumber = (val) => {
  470. const n = parseFloat(val);
  471. return isNaN(n) ? val : n;
  472. };
  473. let _globalThis;
  474. const getGlobalThis = () => {
  475. return (_globalThis ||
  476. (_globalThis =
  477. typeof globalThis !== 'undefined'
  478. ? globalThis
  479. : typeof self !== 'undefined'
  480. ? self
  481. : typeof window !== 'undefined'
  482. ? window
  483. : typeof global !== 'undefined'
  484. ? global
  485. : {}));
  486. };
  487. export { EMPTY_ARR, EMPTY_OBJ, NO, NOOP, PatchFlagNames, babelParserDefaultPlugins, camelize, capitalize, def, escapeHtml, escapeHtmlComment, extend, generateCodeFrame, getGlobalThis, hasChanged, hasOwn, hyphenate, invokeArrayFns, isArray, isBooleanAttr, isDate, isFunction, isGloballyWhitelisted, isHTMLTag, isIntegerKey, isKnownAttr, isMap, isModelListener, isNoUnitNumericStyleProp, isObject, isOn, isPlainObject, isPromise, isReservedProp, isSSRSafeAttrName, isSVGTag, isSet, isSpecialBooleanAttr, isString, isSymbol, isVoidTag, looseEqual, looseIndexOf, makeMap, normalizeClass, normalizeStyle, objectToString, parseStringStyle, propsToAttrMap, remove, slotFlagsText, stringifyStyle, toDisplayString, toHandlerKey, toNumber, toRawType, toTypeString };