utils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. import Vue from 'vue'
  2. import { isSamePath as _isSamePath, joinURL, normalizeURL, withQuery, withoutTrailingSlash } from 'ufo'
  3. // window.{{globals.loadedCallback}} hook
  4. // Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading)
  5. if (process.client) {
  6. window.onNuxtReadyCbs = []
  7. window.onNuxtReady = (cb) => {
  8. window.onNuxtReadyCbs.push(cb)
  9. }
  10. }
  11. export function createGetCounter (counterObject, defaultKey = '') {
  12. return function getCounter (id = defaultKey) {
  13. if (counterObject[id] === undefined) {
  14. counterObject[id] = 0
  15. }
  16. return counterObject[id]++
  17. }
  18. }
  19. export function empty () {}
  20. export function globalHandleError (error) {
  21. if (Vue.config.errorHandler) {
  22. Vue.config.errorHandler(error)
  23. }
  24. }
  25. export function interopDefault (promise) {
  26. return promise.then(m => m.default || m)
  27. }
  28. export function hasFetch(vm) {
  29. return vm.$options && typeof vm.$options.fetch === 'function' && !vm.$options.fetch.length
  30. }
  31. export function purifyData(data) {
  32. if (process.env.NODE_ENV === 'production') {
  33. return data
  34. }
  35. return Object.entries(data).filter(
  36. ([key, value]) => {
  37. const valid = !(value instanceof Function) && !(value instanceof Promise)
  38. if (!valid) {
  39. console.warn(`${key} is not able to be stringified. This will break in a production environment.`)
  40. }
  41. return valid
  42. }
  43. ).reduce((obj, [key, value]) => {
  44. obj[key] = value
  45. return obj
  46. }, {})
  47. }
  48. export function getChildrenComponentInstancesUsingFetch(vm, instances = []) {
  49. const children = vm.$children || []
  50. for (const child of children) {
  51. if (child.$fetch) {
  52. instances.push(child)
  53. continue; // Don't get the children since it will reload the template
  54. }
  55. if (child.$children) {
  56. getChildrenComponentInstancesUsingFetch(child, instances)
  57. }
  58. }
  59. return instances
  60. }
  61. export function applyAsyncData (Component, asyncData) {
  62. if (
  63. // For SSR, we once all this function without second param to just apply asyncData
  64. // Prevent doing this for each SSR request
  65. !asyncData && Component.options.__hasNuxtData
  66. ) {
  67. return
  68. }
  69. const ComponentData = Component.options._originDataFn || Component.options.data || function () { return {} }
  70. Component.options._originDataFn = ComponentData
  71. Component.options.data = function () {
  72. const data = ComponentData.call(this, this)
  73. if (this.$ssrContext) {
  74. asyncData = this.$ssrContext.asyncData[Component.cid]
  75. }
  76. return { ...data, ...asyncData }
  77. }
  78. Component.options.__hasNuxtData = true
  79. if (Component._Ctor && Component._Ctor.options) {
  80. Component._Ctor.options.data = Component.options.data
  81. }
  82. }
  83. export function sanitizeComponent (Component) {
  84. // If Component already sanitized
  85. if (Component.options && Component._Ctor === Component) {
  86. return Component
  87. }
  88. if (!Component.options) {
  89. Component = Vue.extend(Component) // fix issue #6
  90. Component._Ctor = Component
  91. } else {
  92. Component._Ctor = Component
  93. Component.extendOptions = Component.options
  94. }
  95. // If no component name defined, set file path as name, (also fixes #5703)
  96. if (!Component.options.name && Component.options.__file) {
  97. Component.options.name = Component.options.__file
  98. }
  99. return Component
  100. }
  101. export function getMatchedComponents (route, matches = false, prop = 'components') {
  102. return Array.prototype.concat.apply([], route.matched.map((m, index) => {
  103. return Object.keys(m[prop]).map((key) => {
  104. matches && matches.push(index)
  105. return m[prop][key]
  106. })
  107. }))
  108. }
  109. export function getMatchedComponentsInstances (route, matches = false) {
  110. return getMatchedComponents(route, matches, 'instances')
  111. }
  112. export function flatMapComponents (route, fn) {
  113. return Array.prototype.concat.apply([], route.matched.map((m, index) => {
  114. return Object.keys(m.components).reduce((promises, key) => {
  115. if (m.components[key]) {
  116. promises.push(fn(m.components[key], m.instances[key], m, key, index))
  117. } else {
  118. delete m.components[key]
  119. }
  120. return promises
  121. }, [])
  122. }))
  123. }
  124. export function resolveRouteComponents (route, fn) {
  125. return Promise.all(
  126. flatMapComponents(route, async (Component, instance, match, key) => {
  127. // If component is a function, resolve it
  128. if (typeof Component === 'function' && !Component.options) {
  129. try {
  130. Component = await Component()
  131. } catch (error) {
  132. // Handle webpack chunk loading errors
  133. // This may be due to a new deployment or a network problem
  134. if (
  135. error &&
  136. error.name === 'ChunkLoadError' &&
  137. typeof window !== 'undefined' &&
  138. window.sessionStorage
  139. ) {
  140. const timeNow = Date.now()
  141. const previousReloadTime = parseInt(window.sessionStorage.getItem('nuxt-reload'))
  142. // check for previous reload time not to reload infinitely
  143. if (!previousReloadTime || previousReloadTime + 60000 < timeNow) {
  144. window.sessionStorage.setItem('nuxt-reload', timeNow)
  145. window.location.reload(true /* skip cache */)
  146. }
  147. }
  148. throw error
  149. }
  150. }
  151. match.components[key] = Component = sanitizeComponent(Component)
  152. return typeof fn === 'function' ? fn(Component, instance, match, key) : Component
  153. })
  154. )
  155. }
  156. export async function getRouteData (route) {
  157. if (!route) {
  158. return
  159. }
  160. // Make sure the components are resolved (code-splitting)
  161. await resolveRouteComponents(route)
  162. // Send back a copy of route with meta based on Component definition
  163. return {
  164. ...route,
  165. meta: getMatchedComponents(route).map((Component, index) => {
  166. return { ...Component.options.meta, ...(route.matched[index] || {}).meta }
  167. })
  168. }
  169. }
  170. export async function setContext (app, context) {
  171. // If context not defined, create it
  172. if (!app.context) {
  173. app.context = {
  174. isStatic: process.static,
  175. isDev: true,
  176. isHMR: false,
  177. app,
  178. payload: context.payload,
  179. error: context.error,
  180. base: app.router.options.base,
  181. env: {"BASE_URL":"localhost:8090/website/","NODE_ENV":"development"}
  182. }
  183. // Only set once
  184. if (context.req) {
  185. app.context.req = context.req
  186. }
  187. if (context.res) {
  188. app.context.res = context.res
  189. }
  190. if (context.ssrContext) {
  191. app.context.ssrContext = context.ssrContext
  192. }
  193. app.context.redirect = (status, path, query) => {
  194. if (!status) {
  195. return
  196. }
  197. app.context._redirected = true
  198. // if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' })
  199. let pathType = typeof path
  200. if (typeof status !== 'number' && (pathType === 'undefined' || pathType === 'object')) {
  201. query = path || {}
  202. path = status
  203. pathType = typeof path
  204. status = 302
  205. }
  206. if (pathType === 'object') {
  207. path = app.router.resolve(path).route.fullPath
  208. }
  209. // "/absolute/route", "./relative/route" or "../relative/route"
  210. if (/(^[.]{1,2}\/)|(^\/(?!\/))/.test(path)) {
  211. app.context.next({
  212. path,
  213. query,
  214. status
  215. })
  216. } else {
  217. path = withQuery(path, query)
  218. if (process.server) {
  219. app.context.next({
  220. path,
  221. status
  222. })
  223. }
  224. if (process.client) {
  225. // https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
  226. window.location.replace(path)
  227. // Throw a redirect error
  228. throw new Error('ERR_REDIRECT')
  229. }
  230. }
  231. }
  232. if (process.server) {
  233. app.context.beforeNuxtRender = fn => context.beforeRenderFns.push(fn)
  234. }
  235. if (process.client) {
  236. app.context.nuxtState = window.__NUXT__
  237. }
  238. }
  239. // Dynamic keys
  240. const [currentRouteData, fromRouteData] = await Promise.all([
  241. getRouteData(context.route),
  242. getRouteData(context.from)
  243. ])
  244. if (context.route) {
  245. app.context.route = currentRouteData
  246. }
  247. if (context.from) {
  248. app.context.from = fromRouteData
  249. }
  250. app.context.next = context.next
  251. app.context._redirected = false
  252. app.context._errored = false
  253. app.context.isHMR = Boolean(context.isHMR)
  254. app.context.params = app.context.route.params || {}
  255. app.context.query = app.context.route.query || {}
  256. }
  257. export function middlewareSeries (promises, appContext) {
  258. if (!promises.length || appContext._redirected || appContext._errored) {
  259. return Promise.resolve()
  260. }
  261. return promisify(promises[0], appContext)
  262. .then(() => {
  263. return middlewareSeries(promises.slice(1), appContext)
  264. })
  265. }
  266. export function promisify (fn, context) {
  267. let promise
  268. if (fn.length === 2) {
  269. console.warn('Callback-based asyncData, fetch or middleware calls are deprecated. ' +
  270. 'Please switch to promises or async/await syntax')
  271. // fn(context, callback)
  272. promise = new Promise((resolve) => {
  273. fn(context, function (err, data) {
  274. if (err) {
  275. context.error(err)
  276. }
  277. data = data || {}
  278. resolve(data)
  279. })
  280. })
  281. } else {
  282. promise = fn(context)
  283. }
  284. if (promise && promise instanceof Promise && typeof promise.then === 'function') {
  285. return promise
  286. }
  287. return Promise.resolve(promise)
  288. }
  289. // Imported from vue-router
  290. export function getLocation (base, mode) {
  291. if (mode === 'hash') {
  292. return window.location.hash.replace(/^#\//, '')
  293. }
  294. base = decodeURI(base).slice(0, -1) // consideration is base is normalized with trailing slash
  295. let path = decodeURI(window.location.pathname)
  296. if (base && path.startsWith(base)) {
  297. path = path.slice(base.length)
  298. }
  299. const fullPath = (path || '/') + window.location.search + window.location.hash
  300. return normalizeURL(fullPath)
  301. }
  302. // Imported from path-to-regexp
  303. /**
  304. * Compile a string to a template function for the path.
  305. *
  306. * @param {string} str
  307. * @param {Object=} options
  308. * @return {!function(Object=, Object=)}
  309. */
  310. export function compile (str, options) {
  311. return tokensToFunction(parse(str, options), options)
  312. }
  313. export function getQueryDiff (toQuery, fromQuery) {
  314. const diff = {}
  315. const queries = { ...toQuery, ...fromQuery }
  316. for (const k in queries) {
  317. if (String(toQuery[k]) !== String(fromQuery[k])) {
  318. diff[k] = true
  319. }
  320. }
  321. return diff
  322. }
  323. export function normalizeError (err) {
  324. let message
  325. if (!(err.message || typeof err === 'string')) {
  326. try {
  327. message = JSON.stringify(err, null, 2)
  328. } catch (e) {
  329. message = `[${err.constructor.name}]`
  330. }
  331. } else {
  332. message = err.message || err
  333. }
  334. return {
  335. ...err,
  336. message,
  337. statusCode: (err.statusCode || err.status || (err.response && err.response.status) || 500)
  338. }
  339. }
  340. /**
  341. * The main path matching regexp utility.
  342. *
  343. * @type {RegExp}
  344. */
  345. const PATH_REGEXP = new RegExp([
  346. // Match escaped characters that would otherwise appear in future matches.
  347. // This allows the user to escape special characters that won't transform.
  348. '(\\\\.)',
  349. // Match Express-style parameters and un-named parameters with a prefix
  350. // and optional suffixes. Matches appear as:
  351. //
  352. // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  353. // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
  354. // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
  355. '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  356. ].join('|'), 'g')
  357. /**
  358. * Parse a string for the raw tokens.
  359. *
  360. * @param {string} str
  361. * @param {Object=} options
  362. * @return {!Array}
  363. */
  364. function parse (str, options) {
  365. const tokens = []
  366. let key = 0
  367. let index = 0
  368. let path = ''
  369. const defaultDelimiter = (options && options.delimiter) || '/'
  370. let res
  371. while ((res = PATH_REGEXP.exec(str)) != null) {
  372. const m = res[0]
  373. const escaped = res[1]
  374. const offset = res.index
  375. path += str.slice(index, offset)
  376. index = offset + m.length
  377. // Ignore already escaped sequences.
  378. if (escaped) {
  379. path += escaped[1]
  380. continue
  381. }
  382. const next = str[index]
  383. const prefix = res[2]
  384. const name = res[3]
  385. const capture = res[4]
  386. const group = res[5]
  387. const modifier = res[6]
  388. const asterisk = res[7]
  389. // Push the current path onto the tokens.
  390. if (path) {
  391. tokens.push(path)
  392. path = ''
  393. }
  394. const partial = prefix != null && next != null && next !== prefix
  395. const repeat = modifier === '+' || modifier === '*'
  396. const optional = modifier === '?' || modifier === '*'
  397. const delimiter = res[2] || defaultDelimiter
  398. const pattern = capture || group
  399. tokens.push({
  400. name: name || key++,
  401. prefix: prefix || '',
  402. delimiter,
  403. optional,
  404. repeat,
  405. partial,
  406. asterisk: Boolean(asterisk),
  407. pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
  408. })
  409. }
  410. // Match any characters still remaining.
  411. if (index < str.length) {
  412. path += str.substr(index)
  413. }
  414. // If the path exists, push it onto the end.
  415. if (path) {
  416. tokens.push(path)
  417. }
  418. return tokens
  419. }
  420. /**
  421. * Prettier encoding of URI path segments.
  422. *
  423. * @param {string}
  424. * @return {string}
  425. */
  426. function encodeURIComponentPretty (str, slashAllowed) {
  427. const re = slashAllowed ? /[?#]/g : /[/?#]/g
  428. return encodeURI(str).replace(re, (c) => {
  429. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  430. })
  431. }
  432. /**
  433. * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
  434. *
  435. * @param {string}
  436. * @return {string}
  437. */
  438. function encodeAsterisk (str) {
  439. return encodeURIComponentPretty(str, true)
  440. }
  441. /**
  442. * Escape a regular expression string.
  443. *
  444. * @param {string} str
  445. * @return {string}
  446. */
  447. function escapeString (str) {
  448. return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
  449. }
  450. /**
  451. * Escape the capturing group by escaping special characters and meaning.
  452. *
  453. * @param {string} group
  454. * @return {string}
  455. */
  456. function escapeGroup (group) {
  457. return group.replace(/([=!:$/()])/g, '\\$1')
  458. }
  459. /**
  460. * Expose a method for transforming tokens into the path function.
  461. */
  462. function tokensToFunction (tokens, options) {
  463. // Compile all the tokens into regexps.
  464. const matches = new Array(tokens.length)
  465. // Compile all the patterns before compilation.
  466. for (let i = 0; i < tokens.length; i++) {
  467. if (typeof tokens[i] === 'object') {
  468. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options))
  469. }
  470. }
  471. return function (obj, opts) {
  472. let path = ''
  473. const data = obj || {}
  474. const options = opts || {}
  475. const encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent
  476. for (let i = 0; i < tokens.length; i++) {
  477. const token = tokens[i]
  478. if (typeof token === 'string') {
  479. path += token
  480. continue
  481. }
  482. const value = data[token.name || 'pathMatch']
  483. let segment
  484. if (value == null) {
  485. if (token.optional) {
  486. // Prepend partial segment prefixes.
  487. if (token.partial) {
  488. path += token.prefix
  489. }
  490. continue
  491. } else {
  492. throw new TypeError('Expected "' + token.name + '" to be defined')
  493. }
  494. }
  495. if (Array.isArray(value)) {
  496. if (!token.repeat) {
  497. throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
  498. }
  499. if (value.length === 0) {
  500. if (token.optional) {
  501. continue
  502. } else {
  503. throw new TypeError('Expected "' + token.name + '" to not be empty')
  504. }
  505. }
  506. for (let j = 0; j < value.length; j++) {
  507. segment = encode(value[j])
  508. if (!matches[i].test(segment)) {
  509. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
  510. }
  511. path += (j === 0 ? token.prefix : token.delimiter) + segment
  512. }
  513. continue
  514. }
  515. segment = token.asterisk ? encodeAsterisk(value) : encode(value)
  516. if (!matches[i].test(segment)) {
  517. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
  518. }
  519. path += token.prefix + segment
  520. }
  521. return path
  522. }
  523. }
  524. /**
  525. * Get the flags for a regexp from the options.
  526. *
  527. * @param {Object} options
  528. * @return {string}
  529. */
  530. function flags (options) {
  531. return options && options.sensitive ? '' : 'i'
  532. }
  533. export function addLifecycleHook(vm, hook, fn) {
  534. if (!vm.$options[hook]) {
  535. vm.$options[hook] = []
  536. }
  537. if (!vm.$options[hook].includes(fn)) {
  538. vm.$options[hook].push(fn)
  539. }
  540. }
  541. export const urlJoin = joinURL
  542. export const stripTrailingSlash = withoutTrailingSlash
  543. export const isSamePath = _isSamePath
  544. export function setScrollRestoration (newVal) {
  545. try {
  546. window.history.scrollRestoration = newVal;
  547. } catch(e) {}
  548. }