shared.esm-bundler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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';
  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. res += normalizeClass(value[i]) + ' ';
  205. }
  206. }
  207. else if (isObject(value)) {
  208. for (const name in value) {
  209. if (value[name]) {
  210. res += name + ' ';
  211. }
  212. }
  213. }
  214. return res.trim();
  215. }
  216. // These tag configs are shared between compiler-dom and runtime-dom, so they
  217. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  218. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  219. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  220. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  221. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  222. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  223. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  224. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  225. 'option,output,progress,select,textarea,details,dialog,menu,' +
  226. 'summary,template,blockquote,iframe,tfoot';
  227. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  228. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  229. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  230. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  231. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  232. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  233. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  234. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  235. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  236. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  237. 'text,textPath,title,tspan,unknown,use,view';
  238. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  239. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  240. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  241. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  242. const escapeRE = /["'&<>]/;
  243. function escapeHtml(string) {
  244. const str = '' + string;
  245. const match = escapeRE.exec(str);
  246. if (!match) {
  247. return str;
  248. }
  249. let html = '';
  250. let escaped;
  251. let index;
  252. let lastIndex = 0;
  253. for (index = match.index; index < str.length; index++) {
  254. switch (str.charCodeAt(index)) {
  255. case 34: // "
  256. escaped = '&quot;';
  257. break;
  258. case 38: // &
  259. escaped = '&amp;';
  260. break;
  261. case 39: // '
  262. escaped = '&#39;';
  263. break;
  264. case 60: // <
  265. escaped = '&lt;';
  266. break;
  267. case 62: // >
  268. escaped = '&gt;';
  269. break;
  270. default:
  271. continue;
  272. }
  273. if (lastIndex !== index) {
  274. html += str.substring(lastIndex, index);
  275. }
  276. lastIndex = index + 1;
  277. html += escaped;
  278. }
  279. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  280. }
  281. // https://www.w3.org/TR/html52/syntax.html#comments
  282. const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;
  283. function escapeHtmlComment(src) {
  284. return src.replace(commentStripRE, '');
  285. }
  286. function looseCompareArrays(a, b) {
  287. if (a.length !== b.length)
  288. return false;
  289. let equal = true;
  290. for (let i = 0; equal && i < a.length; i++) {
  291. equal = looseEqual(a[i], b[i]);
  292. }
  293. return equal;
  294. }
  295. function looseEqual(a, b) {
  296. if (a === b)
  297. return true;
  298. let aValidType = isDate(a);
  299. let bValidType = isDate(b);
  300. if (aValidType || bValidType) {
  301. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  302. }
  303. aValidType = isArray(a);
  304. bValidType = isArray(b);
  305. if (aValidType || bValidType) {
  306. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  307. }
  308. aValidType = isObject(a);
  309. bValidType = isObject(b);
  310. if (aValidType || bValidType) {
  311. /* istanbul ignore if: this if will probably never be called */
  312. if (!aValidType || !bValidType) {
  313. return false;
  314. }
  315. const aKeysCount = Object.keys(a).length;
  316. const bKeysCount = Object.keys(b).length;
  317. if (aKeysCount !== bKeysCount) {
  318. return false;
  319. }
  320. for (const key in a) {
  321. const aHasKey = a.hasOwnProperty(key);
  322. const bHasKey = b.hasOwnProperty(key);
  323. if ((aHasKey && !bHasKey) ||
  324. (!aHasKey && bHasKey) ||
  325. !looseEqual(a[key], b[key])) {
  326. return false;
  327. }
  328. }
  329. }
  330. return String(a) === String(b);
  331. }
  332. function looseIndexOf(arr, val) {
  333. return arr.findIndex(item => looseEqual(item, val));
  334. }
  335. /**
  336. * For converting {{ interpolation }} values to displayed strings.
  337. * @private
  338. */
  339. const toDisplayString = (val) => {
  340. return val == null
  341. ? ''
  342. : isObject(val)
  343. ? JSON.stringify(val, replacer, 2)
  344. : String(val);
  345. };
  346. const replacer = (_key, val) => {
  347. if (isMap(val)) {
  348. return {
  349. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  350. entries[`${key} =>`] = val;
  351. return entries;
  352. }, {})
  353. };
  354. }
  355. else if (isSet(val)) {
  356. return {
  357. [`Set(${val.size})`]: [...val.values()]
  358. };
  359. }
  360. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  361. return String(val);
  362. }
  363. return val;
  364. };
  365. /**
  366. * List of @babel/parser plugins that are used for template expression
  367. * transforms and SFC script transforms. By default we enable proposals slated
  368. * for ES2020. This will need to be updated as the spec moves forward.
  369. * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
  370. */
  371. const babelParserDefaultPlugins = [
  372. 'bigInt',
  373. 'optionalChaining',
  374. 'nullishCoalescingOperator'
  375. ];
  376. const EMPTY_OBJ = (process.env.NODE_ENV !== 'production')
  377. ? Object.freeze({})
  378. : {};
  379. const EMPTY_ARR = (process.env.NODE_ENV !== 'production') ? Object.freeze([]) : [];
  380. const NOOP = () => { };
  381. /**
  382. * Always return false.
  383. */
  384. const NO = () => false;
  385. const onRE = /^on[^a-z]/;
  386. const isOn = (key) => onRE.test(key);
  387. const isModelListener = (key) => key.startsWith('onUpdate:');
  388. const extend = Object.assign;
  389. const remove = (arr, el) => {
  390. const i = arr.indexOf(el);
  391. if (i > -1) {
  392. arr.splice(i, 1);
  393. }
  394. };
  395. const hasOwnProperty = Object.prototype.hasOwnProperty;
  396. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  397. const isArray = Array.isArray;
  398. const isMap = (val) => toTypeString(val) === '[object Map]';
  399. const isSet = (val) => toTypeString(val) === '[object Set]';
  400. const isDate = (val) => val instanceof Date;
  401. const isFunction = (val) => typeof val === 'function';
  402. const isString = (val) => typeof val === 'string';
  403. const isSymbol = (val) => typeof val === 'symbol';
  404. const isObject = (val) => val !== null && typeof val === 'object';
  405. const isPromise = (val) => {
  406. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  407. };
  408. const objectToString = Object.prototype.toString;
  409. const toTypeString = (value) => objectToString.call(value);
  410. const toRawType = (value) => {
  411. // extract "RawType" from strings like "[object RawType]"
  412. return toTypeString(value).slice(8, -1);
  413. };
  414. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  415. const isIntegerKey = (key) => isString(key) &&
  416. key !== 'NaN' &&
  417. key[0] !== '-' &&
  418. '' + parseInt(key, 10) === key;
  419. const isReservedProp = /*#__PURE__*/ makeMap(
  420. // the leading comma is intentional so empty string "" is also included
  421. ',key,ref,' +
  422. 'onVnodeBeforeMount,onVnodeMounted,' +
  423. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  424. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  425. const cacheStringFunction = (fn) => {
  426. const cache = Object.create(null);
  427. return ((str) => {
  428. const hit = cache[str];
  429. return hit || (cache[str] = fn(str));
  430. });
  431. };
  432. const camelizeRE = /-(\w)/g;
  433. /**
  434. * @private
  435. */
  436. const camelize = cacheStringFunction((str) => {
  437. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  438. });
  439. const hyphenateRE = /\B([A-Z])/g;
  440. /**
  441. * @private
  442. */
  443. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  444. /**
  445. * @private
  446. */
  447. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  448. /**
  449. * @private
  450. */
  451. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  452. // compare whether a value has changed, accounting for NaN.
  453. const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
  454. const invokeArrayFns = (fns, arg) => {
  455. for (let i = 0; i < fns.length; i++) {
  456. fns[i](arg);
  457. }
  458. };
  459. const def = (obj, key, value) => {
  460. Object.defineProperty(obj, key, {
  461. configurable: true,
  462. enumerable: false,
  463. value
  464. });
  465. };
  466. const toNumber = (val) => {
  467. const n = parseFloat(val);
  468. return isNaN(n) ? val : n;
  469. };
  470. let _globalThis;
  471. const getGlobalThis = () => {
  472. return (_globalThis ||
  473. (_globalThis =
  474. typeof globalThis !== 'undefined'
  475. ? globalThis
  476. : typeof self !== 'undefined'
  477. ? self
  478. : typeof window !== 'undefined'
  479. ? window
  480. : typeof global !== 'undefined'
  481. ? global
  482. : {}));
  483. };
  484. 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 };