utils.js 15 KB

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