utils.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. /*!
  2. * @nuxt/utils v2.15.8 (c) 2016-2021
  3. * Released under the MIT License
  4. * Repository: https://github.com/nuxt/nuxt.js
  5. * Website: https://nuxtjs.org
  6. */
  7. 'use strict';
  8. Object.defineProperty(exports, '__esModule', { value: true });
  9. const ufo = require('ufo');
  10. const path = require('path');
  11. const consola = require('consola');
  12. const hash = require('hash-sum');
  13. const fs = require('fs-extra');
  14. const properlock = require('proper-lockfile');
  15. const onExit = require('signal-exit');
  16. const lodash = require('lodash');
  17. const serialize = require('serialize-javascript');
  18. const _createRequire = require('create-require');
  19. const jiti = require('jiti');
  20. const UAParser = require('ua-parser-js');
  21. const semver = require('semver');
  22. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  23. const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  24. const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
  25. const hash__default = /*#__PURE__*/_interopDefaultLegacy(hash);
  26. const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
  27. const properlock__default = /*#__PURE__*/_interopDefaultLegacy(properlock);
  28. const onExit__default = /*#__PURE__*/_interopDefaultLegacy(onExit);
  29. const serialize__default = /*#__PURE__*/_interopDefaultLegacy(serialize);
  30. const _createRequire__default = /*#__PURE__*/_interopDefaultLegacy(_createRequire);
  31. const jiti__default = /*#__PURE__*/_interopDefaultLegacy(jiti);
  32. const UAParser__default = /*#__PURE__*/_interopDefaultLegacy(UAParser);
  33. const semver__default = /*#__PURE__*/_interopDefaultLegacy(semver);
  34. const TARGETS = {
  35. server: 'server',
  36. static: 'static'
  37. };
  38. const MODES = {
  39. universal: 'universal',
  40. spa: 'spa'
  41. };
  42. const getContext = function getContext (req, res) {
  43. return { req, res }
  44. };
  45. const determineGlobals = function determineGlobals (globalName, globals) {
  46. const _globals = {};
  47. for (const global in globals) {
  48. if (typeof globals[global] === 'function') {
  49. _globals[global] = globals[global](globalName);
  50. } else {
  51. _globals[global] = globals[global];
  52. }
  53. }
  54. return _globals
  55. };
  56. const isFullStatic = function (options) {
  57. return !options.dev && !options._legacyGenerate && options.target === TARGETS.static && options.render.ssr
  58. };
  59. const encodeHtml = function encodeHtml (str) {
  60. return str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
  61. };
  62. const isString = obj => typeof obj === 'string' || obj instanceof String;
  63. const isNonEmptyString = obj => Boolean(obj && isString(obj));
  64. const isPureObject = obj => !Array.isArray(obj) && typeof obj === 'object';
  65. const isUrl = function isUrl (url) {
  66. return ufo.hasProtocol(url, true)
  67. };
  68. const urlJoin = ufo.joinURL;
  69. /**
  70. * Wraps value in array if it is not already an array
  71. *
  72. * @param {any} value
  73. * @return {array}
  74. */
  75. const wrapArray = value => Array.isArray(value) ? value : [value];
  76. const WHITESPACE_REPLACEMENTS = [
  77. [/[ \t\f\r]+\n/g, '\n'], // strip empty indents
  78. [/{\n{2,}/g, '{\n'], // strip start padding from blocks
  79. [/\n{2,}([ \t\f\r]*})/g, '\n$1'], // strip end padding from blocks
  80. [/\n{3,}/g, '\n\n'], // strip multiple blank lines (1 allowed)
  81. [/\n{2,}$/g, '\n'] // strip blank lines EOF (0 allowed)
  82. ];
  83. const stripWhitespace = function stripWhitespace (string) {
  84. WHITESPACE_REPLACEMENTS.forEach(([regex, newSubstr]) => {
  85. string = string.replace(regex, newSubstr);
  86. });
  87. return string
  88. };
  89. const lockPaths = new Set();
  90. const defaultLockOptions = {
  91. stale: 30000,
  92. onCompromised: err => consola__default['default'].warn(err)
  93. };
  94. function getLockOptions (options) {
  95. return Object.assign({}, defaultLockOptions, options)
  96. }
  97. function createLockPath ({ id = 'nuxt', dir, root }) {
  98. const sum = hash__default['default'](`${root}-${dir}`);
  99. return path__default['default'].resolve(root, 'node_modules/.cache/nuxt', `${id}-lock-${sum}`)
  100. }
  101. async function getLockPath (config) {
  102. const lockPath = createLockPath(config);
  103. // the lock is created for the lockPath as ${lockPath}.lock
  104. // so the (temporary) lockPath needs to exist
  105. await fs__default['default'].ensureDir(lockPath);
  106. return lockPath
  107. }
  108. async function lock ({ id, dir, root, options }) {
  109. const lockPath = await getLockPath({ id, dir, root });
  110. try {
  111. const locked = await properlock__default['default'].check(lockPath);
  112. if (locked) {
  113. consola__default['default'].fatal(`A lock with id '${id}' already exists on ${dir}`);
  114. }
  115. } catch (e) {
  116. consola__default['default'].debug(`Check for an existing lock with id '${id}' on ${dir} failed`, e);
  117. }
  118. let lockWasCompromised = false;
  119. let release;
  120. try {
  121. options = getLockOptions(options);
  122. const onCompromised = options.onCompromised;
  123. options.onCompromised = (err) => {
  124. onCompromised(err);
  125. lockWasCompromised = true;
  126. };
  127. release = await properlock__default['default'].lock(lockPath, options);
  128. } catch (e) {}
  129. if (!release) {
  130. consola__default['default'].warn(`Unable to get a lock with id '${id}' on ${dir} (but will continue)`);
  131. return false
  132. }
  133. if (!lockPaths.size) {
  134. // make sure to always cleanup our temporary lockPaths
  135. onExit__default['default'](() => {
  136. for (const lockPath of lockPaths) {
  137. fs__default['default'].removeSync(lockPath);
  138. }
  139. });
  140. }
  141. lockPaths.add(lockPath);
  142. return async function lockRelease () {
  143. try {
  144. await fs__default['default'].remove(lockPath);
  145. lockPaths.delete(lockPath);
  146. // release as last so the lockPath is still removed
  147. // when it fails on a compromised lock
  148. await release();
  149. } catch (e) {
  150. if (!lockWasCompromised || !e.message.includes('already released')) {
  151. consola__default['default'].debug(e);
  152. return
  153. }
  154. // proper-lockfile doesnt remove lockDir when lock is compromised
  155. // removing it here could cause the 'other' process to throw an error
  156. // as well, but in our case its much more likely the lock was
  157. // compromised due to mtime update timeouts
  158. const lockDir = `${lockPath}.lock`;
  159. if (await fs__default['default'].exists(lockDir)) {
  160. await fs__default['default'].remove(lockDir);
  161. }
  162. }
  163. }
  164. }
  165. const startsWithAlias = aliasArray => str => aliasArray.some(c => str.startsWith(c));
  166. const startsWithSrcAlias = startsWithAlias(['@', '~']);
  167. const startsWithRootAlias = startsWithAlias(['@@', '~~']);
  168. const isWindows = process.platform.startsWith('win');
  169. const wp = function wp (p = '') {
  170. if (isWindows) {
  171. return p.replace(/\\/g, '\\\\')
  172. }
  173. return p
  174. };
  175. // Kept for backward compat (modules may use it from template context)
  176. const wChunk = function wChunk (p = '') {
  177. return p
  178. };
  179. const reqSep = /\//g;
  180. const sysSep = lodash.escapeRegExp(path__default['default'].sep);
  181. const normalize = string => string.replace(reqSep, sysSep);
  182. const r = function r (...args) {
  183. const lastArg = args[args.length - 1];
  184. if (startsWithSrcAlias(lastArg)) {
  185. return wp(lastArg)
  186. }
  187. return wp(path__default['default'].resolve(...args.map(normalize)))
  188. };
  189. const relativeTo = function relativeTo (...args) {
  190. const dir = args.shift();
  191. // Keep webpack inline loader intact
  192. if (args[0].includes('!')) {
  193. const loaders = args.shift().split('!');
  194. return loaders.concat(relativeTo(dir, loaders.pop(), ...args)).join('!')
  195. }
  196. // Resolve path
  197. const resolvedPath = r(...args);
  198. // Check if path is an alias
  199. if (startsWithSrcAlias(resolvedPath)) {
  200. return resolvedPath
  201. }
  202. // Make correct relative path
  203. let rp = path__default['default'].relative(dir, resolvedPath);
  204. if (rp[0] !== '.') {
  205. rp = '.' + path__default['default'].sep + rp;
  206. }
  207. return wp(rp)
  208. };
  209. function defineAlias (src, target, prop, opts = {}) {
  210. const { bind = true, warn = false } = opts;
  211. if (Array.isArray(prop)) {
  212. for (const p of prop) {
  213. defineAlias(src, target, p, opts);
  214. }
  215. return
  216. }
  217. let targetVal = target[prop];
  218. if (bind && typeof targetVal === 'function') {
  219. targetVal = targetVal.bind(target);
  220. }
  221. let warned = false;
  222. Object.defineProperty(src, prop, {
  223. get: () => {
  224. if (warn && !warned) {
  225. warned = true;
  226. consola__default['default'].warn({
  227. message: `'${prop}' is deprecated'`,
  228. // eslint-disable-next-line unicorn/error-message
  229. additional: new Error().stack.split('\n').splice(2).join('\n')
  230. });
  231. }
  232. return targetVal
  233. }
  234. });
  235. }
  236. const isIndex = s => /(.*)\/index\.[^/]+$/.test(s);
  237. function isIndexFileAndFolder (pluginFiles) {
  238. // Return early in case the matching file count exceeds 2 (index.js + folder)
  239. if (pluginFiles.length !== 2) {
  240. return false
  241. }
  242. return pluginFiles.some(isIndex)
  243. }
  244. const getMainModule = () => {
  245. return (require && require.main) || (module && module.main) || module
  246. };
  247. const routeChildren = function (route) {
  248. const hasChildWithEmptyPath = route.children.some(child => child.path === '');
  249. if (hasChildWithEmptyPath) {
  250. return route.children
  251. }
  252. return [
  253. // Add default child to render parent page
  254. {
  255. ...route,
  256. children: undefined
  257. },
  258. ...route.children
  259. ]
  260. };
  261. const flatRoutes = function flatRoutes (router, fileName = '', routes = []) {
  262. router.forEach((r) => {
  263. if ([':', '*'].some(c => r.path.includes(c))) {
  264. return
  265. }
  266. const route = `${fileName}${r.path}/`.replace(/\/+/g, '/');
  267. if (r.children) {
  268. return flatRoutes(routeChildren(r), route, routes)
  269. }
  270. // if child path is already absolute, do not make any concatenations
  271. if (r.path && r.path.startsWith('/')) {
  272. routes.push(r.path);
  273. } else if (route !== '/' && route[route.length - 1] === '/') {
  274. routes.push(route.slice(0, -1));
  275. } else {
  276. routes.push(route);
  277. }
  278. });
  279. return routes
  280. };
  281. // eslint-disable-next-line default-param-last
  282. function cleanChildrenRoutes (routes, isChild = false, routeNameSplitter = '-', trailingSlash, parentRouteName) {
  283. const regExpIndex = new RegExp(`${routeNameSplitter}index$`);
  284. const regExpParentRouteName = new RegExp(`^${parentRouteName}${routeNameSplitter}`);
  285. const routesIndex = [];
  286. routes.forEach((route) => {
  287. if (regExpIndex.test(route.name) || route.name === 'index') {
  288. const res = route.name.replace(regExpParentRouteName, '').split(routeNameSplitter);
  289. routesIndex.push(res);
  290. }
  291. });
  292. routes.forEach((route) => {
  293. route.path = isChild ? route.path.replace('/', '') : route.path;
  294. if (route.path.includes('?')) {
  295. if (route.name.endsWith(`${routeNameSplitter}index`)) {
  296. route.path = route.path.replace(/\?$/, '');
  297. }
  298. const names = route.name.replace(regExpParentRouteName, '').split(routeNameSplitter);
  299. const paths = route.path.split('/');
  300. if (!isChild) {
  301. paths.shift();
  302. } // clean first / for parents
  303. routesIndex.forEach((r) => {
  304. const i = r.indexOf('index');
  305. if (i < paths.length) {
  306. for (let a = 0; a <= i; a++) {
  307. if (a === i) {
  308. paths[a] = paths[a].replace('?', '');
  309. }
  310. if (a < i && names[a] !== r[a]) {
  311. break
  312. }
  313. }
  314. }
  315. });
  316. route.path = (isChild ? '' : '/') + paths.join('/');
  317. }
  318. route.name = route.name.replace(regExpIndex, '');
  319. if (route.children) {
  320. const defaultChildRoute = route.children.find(child => child.path === '/' || child.path === '');
  321. const routeName = route.name;
  322. if (defaultChildRoute) {
  323. route.children.forEach((child) => {
  324. if (child.path !== defaultChildRoute.path) {
  325. const parts = child.path.split('/');
  326. parts[1] = parts[1].endsWith('?') ? parts[1].substr(0, parts[1].length - 1) : parts[1];
  327. child.path = parts.join('/');
  328. }
  329. });
  330. delete route.name;
  331. }
  332. route.children = cleanChildrenRoutes(route.children, true, routeNameSplitter, trailingSlash, routeName);
  333. }
  334. });
  335. return routes
  336. }
  337. const DYNAMIC_ROUTE_REGEX = /^\/([:*])/;
  338. const sortRoutes = function sortRoutes (routes) {
  339. routes.sort((a, b) => {
  340. if (!a.path.length) {
  341. return -1
  342. }
  343. if (!b.path.length) {
  344. return 1
  345. }
  346. // Order: /static, /index, /:dynamic
  347. // Match exact route before index: /login before /index/_slug
  348. if (a.path === '/') {
  349. return DYNAMIC_ROUTE_REGEX.test(b.path) ? -1 : 1
  350. }
  351. if (b.path === '/') {
  352. return DYNAMIC_ROUTE_REGEX.test(a.path) ? 1 : -1
  353. }
  354. let i;
  355. let res = 0;
  356. let y = 0;
  357. let z = 0;
  358. const _a = a.path.split('/');
  359. const _b = b.path.split('/');
  360. for (i = 0; i < _a.length; i++) {
  361. if (res !== 0) {
  362. break
  363. }
  364. y = _a[i] === '*' ? 2 : _a[i].includes(':') ? 1 : 0;
  365. z = _b[i] === '*' ? 2 : _b[i].includes(':') ? 1 : 0;
  366. res = y - z;
  367. // If a.length >= b.length
  368. if (i === _b.length - 1 && res === 0) {
  369. // unless * found sort by level, then alphabetically
  370. res = _a[i] === '*'
  371. ? -1
  372. : (
  373. _a.length === _b.length ? a.path.localeCompare(b.path) : (_a.length - _b.length)
  374. );
  375. }
  376. }
  377. if (res === 0) {
  378. // unless * found sort by level, then alphabetically
  379. res = _a[i - 1] === '*' && _b[i]
  380. ? 1
  381. : (
  382. _a.length === _b.length ? a.path.localeCompare(b.path) : (_a.length - _b.length)
  383. );
  384. }
  385. return res
  386. });
  387. routes.forEach((route) => {
  388. if (route.children) {
  389. sortRoutes(route.children);
  390. }
  391. });
  392. return routes
  393. };
  394. const createRoutes = function createRoutes ({
  395. files,
  396. srcDir,
  397. pagesDir = '',
  398. routeNameSplitter = '-',
  399. supportedExtensions = ['vue', 'js'],
  400. trailingSlash
  401. }) {
  402. const routes = [];
  403. files.forEach((file) => {
  404. const keys = file
  405. .replace(new RegExp(`^${pagesDir}`), '')
  406. .replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '')
  407. .replace(/\/{2,}/g, '/')
  408. .split('/')
  409. .slice(1);
  410. const route = { name: '', path: '', component: r(srcDir, file) };
  411. let parent = routes;
  412. keys.forEach((key, i) => {
  413. // remove underscore only, if its the prefix
  414. const sanitizedKey = key.startsWith('_') ? key.substr(1) : key;
  415. route.name = route.name
  416. ? route.name + routeNameSplitter + sanitizedKey
  417. : sanitizedKey;
  418. route.name += key === '_' ? 'all' : '';
  419. route.chunkName = file.replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '');
  420. const child = parent.find(parentRoute => parentRoute.name === route.name);
  421. if (child) {
  422. child.children = child.children || [];
  423. parent = child.children;
  424. route.path = '';
  425. } else if (key === 'index' && i + 1 === keys.length) {
  426. route.path += i > 0 ? '' : '/';
  427. } else {
  428. route.path += '/' + ufo.normalizeURL(getRoutePathExtension(key));
  429. if (key.startsWith('_') && key.length > 1) {
  430. route.path += '?';
  431. }
  432. }
  433. });
  434. if (trailingSlash !== undefined) {
  435. route.pathToRegexpOptions = { ...route.pathToRegexpOptions, strict: true };
  436. if (trailingSlash && !route.path.endsWith('*')) {
  437. route.path = ufo.withTrailingSlash(route.path);
  438. } else {
  439. route.path = ufo.withoutTrailingSlash(route.path);
  440. }
  441. }
  442. parent.push(route);
  443. });
  444. sortRoutes(routes);
  445. return cleanChildrenRoutes(routes, false, routeNameSplitter, trailingSlash)
  446. };
  447. // Guard dir1 from dir2 which can be indiscriminately removed
  448. const guardDir = function guardDir (options, key1, key2) {
  449. const dir1 = lodash.get(options, key1, false);
  450. const dir2 = lodash.get(options, key2, false);
  451. if (
  452. dir1 &&
  453. dir2 &&
  454. (
  455. dir1 === dir2 ||
  456. (
  457. dir1.startsWith(dir2) &&
  458. !path__default['default'].basename(dir1).startsWith(path__default['default'].basename(dir2))
  459. )
  460. )
  461. ) {
  462. const errorMessage = `options.${key2} cannot be a parent of or same as ${key1}`;
  463. consola__default['default'].fatal(errorMessage);
  464. throw new Error(errorMessage)
  465. }
  466. };
  467. const getRoutePathExtension = (key) => {
  468. if (key === '_') {
  469. return '*'
  470. }
  471. if (key.startsWith('_')) {
  472. return `:${key.substr(1)}`
  473. }
  474. return key
  475. };
  476. const promisifyRoute = function promisifyRoute (fn, ...args) {
  477. // If routes is an array
  478. if (Array.isArray(fn)) {
  479. return Promise.resolve(fn)
  480. }
  481. // If routes is a function expecting a callback
  482. if (fn.length === arguments.length) {
  483. return new Promise((resolve, reject) => {
  484. fn((err, routeParams) => {
  485. if (err) {
  486. reject(err);
  487. }
  488. resolve(routeParams);
  489. }, ...args);
  490. })
  491. }
  492. let promise = fn(...args);
  493. if (
  494. !promise ||
  495. (!(promise instanceof Promise) && typeof promise.then !== 'function')
  496. ) {
  497. promise = Promise.resolve(promise);
  498. }
  499. return promise
  500. };
  501. function normalizeFunctions (obj) {
  502. if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) {
  503. return obj
  504. }
  505. for (const key in obj) {
  506. if (key === '__proto__' || key === 'constructor') {
  507. continue
  508. }
  509. const val = obj[key];
  510. if (val !== null && typeof val === 'object' && !Array.isArray(obj)) {
  511. obj[key] = normalizeFunctions(val);
  512. }
  513. if (typeof obj[key] === 'function') {
  514. const asString = obj[key].toString();
  515. const match = asString.match(/^([^{(]+)=>\s*([\0-\uFFFF]*)/);
  516. if (match) {
  517. const fullFunctionBody = match[2].match(/^{?(\s*return\s+)?([\0-\uFFFF]*?)}?$/);
  518. let functionBody = fullFunctionBody[2].trim();
  519. if (fullFunctionBody[1] || !match[2].trim().match(/^\s*{/)) {
  520. functionBody = `return ${functionBody}`;
  521. }
  522. // eslint-disable-next-line no-new-func
  523. obj[key] = new Function(...match[1].split(',').map(arg => arg.trim()), functionBody);
  524. }
  525. }
  526. }
  527. return obj
  528. }
  529. function serializeFunction (func) {
  530. let open = false;
  531. func = normalizeFunctions(func);
  532. return serialize__default['default'](func)
  533. .replace(serializeFunction.assignmentRE, (_, spaces) => {
  534. return `${spaces}: function (`
  535. })
  536. .replace(serializeFunction.internalFunctionRE, (_, spaces, name, args) => {
  537. if (open) {
  538. return `${spaces}${name}: function (${args}) {`
  539. } else {
  540. open = true;
  541. return _
  542. }
  543. })
  544. .replace(new RegExp(`${(func.name || 'function').replace('$', '\\$')}\\s*\\(`), 'function(')
  545. .replace('function function', 'function')
  546. }
  547. serializeFunction.internalFunctionRE = /^(\s*)(?!(?:if)|(?:for)|(?:while)|(?:switch)|(?:catch))(\w+)\s*\((.*?)\)\s*\{/gm;
  548. serializeFunction.assignmentRE = /^(\s*):(\w+)\(/gm;
  549. const sequence = function sequence (tasks, fn) {
  550. return tasks.reduce(
  551. (promise, task) => promise.then(() => fn(task)),
  552. Promise.resolve()
  553. )
  554. };
  555. const parallel = function parallel (tasks, fn) {
  556. return Promise.all(tasks.map(fn))
  557. };
  558. const chainFn = function chainFn (base, fn) {
  559. if (typeof fn !== 'function') {
  560. return base
  561. }
  562. if (typeof base !== 'function') {
  563. return fn
  564. }
  565. return function (arg0, ...args) {
  566. const next = (previous = arg0) => {
  567. const fnResult = fn.call(this, previous, ...args);
  568. if (fnResult && typeof fnResult.then === 'function') {
  569. return fnResult.then(res => res || previous)
  570. }
  571. return fnResult || previous
  572. };
  573. const baseResult = base.call(this, arg0, ...args);
  574. if (baseResult && typeof baseResult.then === 'function') {
  575. return baseResult.then(res => next(res))
  576. }
  577. return next(baseResult)
  578. }
  579. };
  580. async function promiseFinally (fn, finalFn) {
  581. let result;
  582. try {
  583. if (typeof fn === 'function') {
  584. result = await fn();
  585. } else {
  586. result = await fn;
  587. }
  588. } finally {
  589. finalFn();
  590. }
  591. return result
  592. }
  593. const timeout = function timeout (fn, ms, msg) {
  594. let timerId;
  595. const warpPromise = promiseFinally(fn, () => clearTimeout(timerId));
  596. const timerPromise = new Promise((resolve, reject) => {
  597. timerId = setTimeout(() => reject(new Error(msg)), ms);
  598. });
  599. return Promise.race([warpPromise, timerPromise])
  600. };
  601. const waitFor = function waitFor (ms) {
  602. return new Promise(resolve => setTimeout(resolve, ms || 0))
  603. };
  604. class Timer {
  605. constructor () {
  606. this._times = new Map();
  607. }
  608. start (name, description) {
  609. const time = {
  610. name,
  611. description,
  612. start: this.hrtime()
  613. };
  614. this._times.set(name, time);
  615. return time
  616. }
  617. end (name) {
  618. if (this._times.has(name)) {
  619. const time = this._times.get(name);
  620. time.duration = this.hrtime(time.start);
  621. this._times.delete(name);
  622. return time
  623. }
  624. }
  625. hrtime (start) {
  626. const useBigInt = typeof process.hrtime.bigint === 'function';
  627. if (start) {
  628. const end = useBigInt ? process.hrtime.bigint() : process.hrtime(start);
  629. return useBigInt
  630. ? (end - start) / BigInt(1000000)
  631. : (end[0] * 1e3) + (end[1] * 1e-6)
  632. }
  633. return useBigInt ? process.hrtime.bigint() : process.hrtime()
  634. }
  635. clear () {
  636. this._times.clear();
  637. }
  638. }
  639. const createRequire = (filename, useJiti = global.__NUXT_DEV__) => {
  640. if (useJiti && typeof jest === 'undefined') {
  641. return jiti__default['default'](filename)
  642. }
  643. return _createRequire__default['default'](filename)
  644. };
  645. const _require = createRequire();
  646. function isHMRCompatible (id) {
  647. return !/[/\\]mongoose[/\\/]/.test(id)
  648. }
  649. function isExternalDependency (id) {
  650. return /[/\\]node_modules[/\\]/.test(id)
  651. }
  652. function clearRequireCache (id) {
  653. if (isExternalDependency(id) && isHMRCompatible(id)) {
  654. return
  655. }
  656. const entry = getRequireCacheItem(id);
  657. if (!entry) {
  658. delete _require.cache[id];
  659. return
  660. }
  661. if (entry.parent) {
  662. entry.parent.children = entry.parent.children.filter(e => e.id !== id);
  663. }
  664. // Needs to be cleared before children, to protect against circular deps (#7966)
  665. delete _require.cache[id];
  666. for (const child of entry.children) {
  667. clearRequireCache(child.id);
  668. }
  669. }
  670. function scanRequireTree (id, files = new Set()) {
  671. if (isExternalDependency(id) || files.has(id)) {
  672. return files
  673. }
  674. const entry = getRequireCacheItem(id);
  675. if (!entry) {
  676. files.add(id);
  677. return files
  678. }
  679. files.add(entry.id);
  680. for (const child of entry.children) {
  681. scanRequireTree(child.id, files);
  682. }
  683. return files
  684. }
  685. function getRequireCacheItem (id) {
  686. try {
  687. return _require.cache[id]
  688. } catch (e) {
  689. }
  690. }
  691. function resolveModule (id, paths) {
  692. if (typeof paths === 'string') {
  693. paths = [paths];
  694. }
  695. return _require.resolve(id, {
  696. paths: [].concat(...(global.__NUXT_PREPATHS__ || []), paths || [], global.__NUXT_PATHS__ || [], process.cwd())
  697. })
  698. }
  699. function requireModule (id, paths) {
  700. return _require(resolveModule(id, paths))
  701. }
  702. function tryRequire (id, paths) {
  703. try { return requireModule(id, paths) } catch (e) { }
  704. }
  705. function tryResolve (id, paths) {
  706. try { return resolveModule(id, paths) } catch (e) { }
  707. }
  708. function getPKG (id, paths) {
  709. return tryRequire(path.join(id, 'package.json'), paths)
  710. }
  711. const ModernBrowsers = {
  712. Edge: '16',
  713. Firefox: '60',
  714. Chrome: '61',
  715. 'Chrome Headless': '61',
  716. Chromium: '61',
  717. Iron: '61',
  718. Safari: '10.1',
  719. Opera: '48',
  720. Yandex: '18',
  721. Vivaldi: '1.14',
  722. 'Mobile Safari': '10.3'
  723. };
  724. let __modernBrowsers;
  725. const getModernBrowsers = () => {
  726. if (__modernBrowsers) {
  727. return __modernBrowsers
  728. }
  729. __modernBrowsers = Object.keys(ModernBrowsers)
  730. .reduce((allBrowsers, browser) => {
  731. allBrowsers[browser] = semver__default['default'].coerce(ModernBrowsers[browser]);
  732. return allBrowsers
  733. }, {});
  734. return __modernBrowsers
  735. };
  736. const isModernBrowser = (ua) => {
  737. if (!ua) {
  738. return false
  739. }
  740. const { browser } = UAParser__default['default'](ua);
  741. const browserVersion = semver__default['default'].coerce(browser.version);
  742. if (!browserVersion) {
  743. return false
  744. }
  745. const modernBrowsers = getModernBrowsers();
  746. return Boolean(modernBrowsers[browser.name] && semver__default['default'].gte(browserVersion, modernBrowsers[browser.name]))
  747. };
  748. const isModernRequest = (req, modernMode = false) => {
  749. if (modernMode === false) {
  750. return false
  751. }
  752. const { socket = {}, headers } = req;
  753. if (socket._modern === undefined) {
  754. const ua = headers && headers['user-agent'];
  755. socket._modern = isModernBrowser(ua);
  756. }
  757. return socket._modern
  758. };
  759. // https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
  760. const safariNoModuleFix = '!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();';
  761. exports.MODES = MODES;
  762. exports.ModernBrowsers = ModernBrowsers;
  763. exports.TARGETS = TARGETS;
  764. exports.Timer = Timer;
  765. exports.chainFn = chainFn;
  766. exports.clearRequireCache = clearRequireCache;
  767. exports.createLockPath = createLockPath;
  768. exports.createRequire = createRequire;
  769. exports.createRoutes = createRoutes;
  770. exports.defaultLockOptions = defaultLockOptions;
  771. exports.defineAlias = defineAlias;
  772. exports.determineGlobals = determineGlobals;
  773. exports.encodeHtml = encodeHtml;
  774. exports.flatRoutes = flatRoutes;
  775. exports.getContext = getContext;
  776. exports.getLockOptions = getLockOptions;
  777. exports.getLockPath = getLockPath;
  778. exports.getMainModule = getMainModule;
  779. exports.getPKG = getPKG;
  780. exports.getRequireCacheItem = getRequireCacheItem;
  781. exports.guardDir = guardDir;
  782. exports.isExternalDependency = isExternalDependency;
  783. exports.isFullStatic = isFullStatic;
  784. exports.isHMRCompatible = isHMRCompatible;
  785. exports.isIndexFileAndFolder = isIndexFileAndFolder;
  786. exports.isModernBrowser = isModernBrowser;
  787. exports.isModernRequest = isModernRequest;
  788. exports.isNonEmptyString = isNonEmptyString;
  789. exports.isPureObject = isPureObject;
  790. exports.isString = isString;
  791. exports.isUrl = isUrl;
  792. exports.isWindows = isWindows;
  793. exports.lock = lock;
  794. exports.lockPaths = lockPaths;
  795. exports.normalizeFunctions = normalizeFunctions;
  796. exports.parallel = parallel;
  797. exports.promisifyRoute = promisifyRoute;
  798. exports.r = r;
  799. exports.relativeTo = relativeTo;
  800. exports.requireModule = requireModule;
  801. exports.resolveModule = resolveModule;
  802. exports.safariNoModuleFix = safariNoModuleFix;
  803. exports.scanRequireTree = scanRequireTree;
  804. exports.sequence = sequence;
  805. exports.serializeFunction = serializeFunction;
  806. exports.sortRoutes = sortRoutes;
  807. exports.startsWithAlias = startsWithAlias;
  808. exports.startsWithRootAlias = startsWithRootAlias;
  809. exports.startsWithSrcAlias = startsWithSrcAlias;
  810. exports.stripWhitespace = stripWhitespace;
  811. exports.timeout = timeout;
  812. exports.tryRequire = tryRequire;
  813. exports.tryResolve = tryResolve;
  814. exports.urlJoin = urlJoin;
  815. exports.wChunk = wChunk;
  816. exports.waitFor = waitFor;
  817. exports.wp = wp;
  818. exports.wrapArray = wrapArray;