index.mjs 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483
  1. import { promises, existsSync, readFileSync, lstatSync } from 'node:fs';
  2. import { performance } from 'node:perf_hooks';
  3. import defu$1, { defu } from 'defu';
  4. import { applyDefaults } from 'untyped';
  5. import { dirname, relative, join, resolve, normalize, isAbsolute, basename, parse } from 'pathe';
  6. import { consola } from 'consola';
  7. import { AsyncLocalStorage } from 'node:async_hooks';
  8. import { getContext, createContext } from 'unctx';
  9. import satisfies from 'semver/functions/satisfies.js';
  10. import { readPackageJSON, resolvePackageJSON } from 'pkg-types';
  11. import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork';
  12. import { pathToFileURL, fileURLToPath } from 'node:url';
  13. import { createJiti } from 'jiti';
  14. import { interopDefault, parseNodeModulePath, resolveModuleExportNames } from 'mlly';
  15. import { resolveModulePath, resolveModuleURL } from 'exsolve';
  16. import { isRelative, withTrailingSlash } from 'ufo';
  17. import { glob } from 'tinyglobby';
  18. import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
  19. import ignore from 'ignore';
  20. import { loadConfig } from 'c12';
  21. import process$1 from 'node:process';
  22. import destr from 'destr';
  23. import { snakeCase, pascalCase, kebabCase } from 'scule';
  24. import { klona } from 'klona';
  25. import { hash } from 'ohash';
  26. import { gte } from 'semver';
  27. import { captureStackTrace } from 'errx';
  28. import { isAbsolute as isAbsolute$1 } from 'node:path';
  29. const logger = consola;
  30. function useLogger(tag, options = {}) {
  31. return tag ? logger.create(options).withTag(tag) : logger;
  32. }
  33. const nuxtCtx = getContext("nuxt");
  34. const asyncNuxtStorage = createContext({
  35. asyncContext: true,
  36. AsyncLocalStorage
  37. });
  38. const getNuxtCtx = () => asyncNuxtStorage.tryUse();
  39. function useNuxt() {
  40. const instance = asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
  41. if (!instance) {
  42. throw new Error("Nuxt instance is unavailable!");
  43. }
  44. return instance;
  45. }
  46. function tryUseNuxt() {
  47. return asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
  48. }
  49. function runWithNuxtContext(nuxt, fn) {
  50. return asyncNuxtStorage.call(nuxt, fn);
  51. }
  52. const SEMANTIC_VERSION_RE = /-\d+\.[0-9a-f]+/;
  53. function normalizeSemanticVersion(version) {
  54. return version.replace(SEMANTIC_VERSION_RE, "");
  55. }
  56. const builderMap = {
  57. "@nuxt/rspack-builder": "rspack",
  58. "@nuxt/vite-builder": "vite",
  59. "@nuxt/webpack-builder": "webpack"
  60. };
  61. function checkNuxtVersion(version, nuxt = useNuxt()) {
  62. const nuxtVersion = getNuxtVersion(nuxt);
  63. return satisfies(normalizeSemanticVersion(nuxtVersion), version, { includePrerelease: true });
  64. }
  65. async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
  66. const issues = [];
  67. if (constraints.nuxt) {
  68. const nuxtVersion = getNuxtVersion(nuxt);
  69. if (!checkNuxtVersion(constraints.nuxt, nuxt)) {
  70. issues.push({
  71. name: "nuxt",
  72. message: `Nuxt version \`${constraints.nuxt}\` is required but currently using \`${nuxtVersion}\``
  73. });
  74. }
  75. }
  76. if (isNuxt2(nuxt)) {
  77. const bridgeRequirement = constraints.bridge;
  78. const hasBridge = !!nuxt.options.bridge;
  79. if (bridgeRequirement === true && !hasBridge) {
  80. issues.push({
  81. name: "bridge",
  82. message: "Nuxt bridge is required"
  83. });
  84. } else if (bridgeRequirement === false && hasBridge) {
  85. issues.push({
  86. name: "bridge",
  87. message: "Nuxt bridge is not supported"
  88. });
  89. }
  90. }
  91. if (constraints.builder && typeof nuxt.options.builder === "string") {
  92. const currentBuilder = builderMap[nuxt.options.builder] || nuxt.options.builder;
  93. if (currentBuilder in constraints.builder) {
  94. const constraint = constraints.builder[currentBuilder];
  95. if (constraint === false) {
  96. issues.push({
  97. name: "builder",
  98. message: `Not compatible with \`${nuxt.options.builder}\`.`
  99. });
  100. } else {
  101. for (const parent of [nuxt.options.rootDir, nuxt.options.workspaceDir, import.meta.url]) {
  102. const builderVersion = await readPackageJSON(nuxt.options.builder, { parent }).then((r) => r.version).catch(() => void 0);
  103. if (builderVersion) {
  104. if (!satisfies(normalizeSemanticVersion(builderVersion), constraint, { includePrerelease: true })) {
  105. issues.push({
  106. name: "builder",
  107. message: `Not compatible with \`${builderVersion}\` of \`${currentBuilder}\`. This module requires \`${constraint}\`.`
  108. });
  109. }
  110. break;
  111. }
  112. }
  113. }
  114. }
  115. }
  116. await nuxt.callHook("kit:compatibility", constraints, issues);
  117. issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
  118. return issues;
  119. }
  120. async function assertNuxtCompatibility(constraints, nuxt = useNuxt()) {
  121. const issues = await checkNuxtCompatibility(constraints, nuxt);
  122. if (issues.length) {
  123. throw new Error("Nuxt compatibility issues found:\n" + issues.toString());
  124. }
  125. return true;
  126. }
  127. async function hasNuxtCompatibility(constraints, nuxt = useNuxt()) {
  128. const issues = await checkNuxtCompatibility(constraints, nuxt);
  129. return !issues.length;
  130. }
  131. function isNuxtMajorVersion(majorVersion, nuxt = useNuxt()) {
  132. const version = getNuxtVersion(nuxt);
  133. return version[0] === majorVersion.toString() && version[1] === ".";
  134. }
  135. function isNuxt2(nuxt = useNuxt()) {
  136. return isNuxtMajorVersion(2, nuxt);
  137. }
  138. function isNuxt3(nuxt = useNuxt()) {
  139. return isNuxtMajorVersion(3, nuxt);
  140. }
  141. const NUXT_VERSION_RE = /^v/g;
  142. function getNuxtVersion(nuxt = useNuxt()) {
  143. const rawVersion = nuxt?._version || nuxt?.version || nuxt?.constructor?.version;
  144. if (typeof rawVersion !== "string") {
  145. throw new TypeError("Cannot determine nuxt version! Is current instance passed?");
  146. }
  147. return rawVersion.replace(NUXT_VERSION_RE, "");
  148. }
  149. /** Detect free variable `global` from Node.js. */
  150. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  151. /** Detect free variable `self`. */
  152. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  153. /** Used as a reference to the global object. */
  154. var root = freeGlobal || freeSelf || Function('return this')();
  155. /** Built-in value references. */
  156. var Symbol$1 = root.Symbol;
  157. /** Used for built-in method references. */
  158. var objectProto$b = Object.prototype;
  159. /** Used to check objects for own properties. */
  160. var hasOwnProperty$9 = objectProto$b.hasOwnProperty;
  161. /**
  162. * Used to resolve the
  163. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  164. * of values.
  165. */
  166. var nativeObjectToString$1 = objectProto$b.toString;
  167. /** Built-in value references. */
  168. var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
  169. /**
  170. * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
  171. *
  172. * @private
  173. * @param {*} value The value to query.
  174. * @returns {string} Returns the raw `toStringTag`.
  175. */
  176. function getRawTag(value) {
  177. var isOwn = hasOwnProperty$9.call(value, symToStringTag$1),
  178. tag = value[symToStringTag$1];
  179. try {
  180. value[symToStringTag$1] = undefined;
  181. var unmasked = true;
  182. } catch (e) {}
  183. var result = nativeObjectToString$1.call(value);
  184. if (unmasked) {
  185. if (isOwn) {
  186. value[symToStringTag$1] = tag;
  187. } else {
  188. delete value[symToStringTag$1];
  189. }
  190. }
  191. return result;
  192. }
  193. /** Used for built-in method references. */
  194. var objectProto$a = Object.prototype;
  195. /**
  196. * Used to resolve the
  197. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  198. * of values.
  199. */
  200. var nativeObjectToString = objectProto$a.toString;
  201. /**
  202. * Converts `value` to a string using `Object.prototype.toString`.
  203. *
  204. * @private
  205. * @param {*} value The value to convert.
  206. * @returns {string} Returns the converted string.
  207. */
  208. function objectToString(value) {
  209. return nativeObjectToString.call(value);
  210. }
  211. /** `Object#toString` result references. */
  212. var nullTag = '[object Null]',
  213. undefinedTag = '[object Undefined]';
  214. /** Built-in value references. */
  215. var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
  216. /**
  217. * The base implementation of `getTag` without fallbacks for buggy environments.
  218. *
  219. * @private
  220. * @param {*} value The value to query.
  221. * @returns {string} Returns the `toStringTag`.
  222. */
  223. function baseGetTag(value) {
  224. if (value == null) {
  225. return value === undefined ? undefinedTag : nullTag;
  226. }
  227. return (symToStringTag && symToStringTag in Object(value))
  228. ? getRawTag(value)
  229. : objectToString(value);
  230. }
  231. /**
  232. * Checks if `value` is object-like. A value is object-like if it's not `null`
  233. * and has a `typeof` result of "object".
  234. *
  235. * @static
  236. * @memberOf _
  237. * @since 4.0.0
  238. * @category Lang
  239. * @param {*} value The value to check.
  240. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  241. * @example
  242. *
  243. * _.isObjectLike({});
  244. * // => true
  245. *
  246. * _.isObjectLike([1, 2, 3]);
  247. * // => true
  248. *
  249. * _.isObjectLike(_.noop);
  250. * // => false
  251. *
  252. * _.isObjectLike(null);
  253. * // => false
  254. */
  255. function isObjectLike(value) {
  256. return value != null && typeof value == 'object';
  257. }
  258. /** `Object#toString` result references. */
  259. var symbolTag = '[object Symbol]';
  260. /**
  261. * Checks if `value` is classified as a `Symbol` primitive or object.
  262. *
  263. * @static
  264. * @memberOf _
  265. * @since 4.0.0
  266. * @category Lang
  267. * @param {*} value The value to check.
  268. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
  269. * @example
  270. *
  271. * _.isSymbol(Symbol.iterator);
  272. * // => true
  273. *
  274. * _.isSymbol('abc');
  275. * // => false
  276. */
  277. function isSymbol(value) {
  278. return typeof value == 'symbol' ||
  279. (isObjectLike(value) && baseGetTag(value) == symbolTag);
  280. }
  281. /**
  282. * A specialized version of `_.map` for arrays without support for iteratee
  283. * shorthands.
  284. *
  285. * @private
  286. * @param {Array} [array] The array to iterate over.
  287. * @param {Function} iteratee The function invoked per iteration.
  288. * @returns {Array} Returns the new mapped array.
  289. */
  290. function arrayMap(array, iteratee) {
  291. var index = -1,
  292. length = array == null ? 0 : array.length,
  293. result = Array(length);
  294. while (++index < length) {
  295. result[index] = iteratee(array[index], index, array);
  296. }
  297. return result;
  298. }
  299. /**
  300. * Checks if `value` is classified as an `Array` object.
  301. *
  302. * @static
  303. * @memberOf _
  304. * @since 0.1.0
  305. * @category Lang
  306. * @param {*} value The value to check.
  307. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  308. * @example
  309. *
  310. * _.isArray([1, 2, 3]);
  311. * // => true
  312. *
  313. * _.isArray(document.body.children);
  314. * // => false
  315. *
  316. * _.isArray('abc');
  317. * // => false
  318. *
  319. * _.isArray(_.noop);
  320. * // => false
  321. */
  322. var isArray = Array.isArray;
  323. /** Used to convert symbols to primitives and strings. */
  324. var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
  325. symbolToString = symbolProto ? symbolProto.toString : undefined;
  326. /**
  327. * The base implementation of `_.toString` which doesn't convert nullish
  328. * values to empty strings.
  329. *
  330. * @private
  331. * @param {*} value The value to process.
  332. * @returns {string} Returns the string.
  333. */
  334. function baseToString(value) {
  335. // Exit early for strings to avoid a performance hit in some environments.
  336. if (typeof value == 'string') {
  337. return value;
  338. }
  339. if (isArray(value)) {
  340. // Recursively convert values (susceptible to call stack limits).
  341. return arrayMap(value, baseToString) + '';
  342. }
  343. if (isSymbol(value)) {
  344. return symbolToString ? symbolToString.call(value) : '';
  345. }
  346. var result = (value + '');
  347. return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
  348. }
  349. /**
  350. * Checks if `value` is the
  351. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  352. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  353. *
  354. * @static
  355. * @memberOf _
  356. * @since 0.1.0
  357. * @category Lang
  358. * @param {*} value The value to check.
  359. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  360. * @example
  361. *
  362. * _.isObject({});
  363. * // => true
  364. *
  365. * _.isObject([1, 2, 3]);
  366. * // => true
  367. *
  368. * _.isObject(_.noop);
  369. * // => true
  370. *
  371. * _.isObject(null);
  372. * // => false
  373. */
  374. function isObject(value) {
  375. var type = typeof value;
  376. return value != null && (type == 'object' || type == 'function');
  377. }
  378. /**
  379. * This method returns the first argument it receives.
  380. *
  381. * @static
  382. * @since 0.1.0
  383. * @memberOf _
  384. * @category Util
  385. * @param {*} value Any value.
  386. * @returns {*} Returns `value`.
  387. * @example
  388. *
  389. * var object = { 'a': 1 };
  390. *
  391. * console.log(_.identity(object) === object);
  392. * // => true
  393. */
  394. function identity(value) {
  395. return value;
  396. }
  397. /** `Object#toString` result references. */
  398. var asyncTag = '[object AsyncFunction]',
  399. funcTag$1 = '[object Function]',
  400. genTag = '[object GeneratorFunction]',
  401. proxyTag = '[object Proxy]';
  402. /**
  403. * Checks if `value` is classified as a `Function` object.
  404. *
  405. * @static
  406. * @memberOf _
  407. * @since 0.1.0
  408. * @category Lang
  409. * @param {*} value The value to check.
  410. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  411. * @example
  412. *
  413. * _.isFunction(_);
  414. * // => true
  415. *
  416. * _.isFunction(/abc/);
  417. * // => false
  418. */
  419. function isFunction(value) {
  420. if (!isObject(value)) {
  421. return false;
  422. }
  423. // The use of `Object#toString` avoids issues with the `typeof` operator
  424. // in Safari 9 which returns 'object' for typed arrays and other constructors.
  425. var tag = baseGetTag(value);
  426. return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
  427. }
  428. /** Used to detect overreaching core-js shims. */
  429. var coreJsData = root['__core-js_shared__'];
  430. /** Used to detect methods masquerading as native. */
  431. var maskSrcKey = (function() {
  432. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  433. return uid ? ('Symbol(src)_1.' + uid) : '';
  434. }());
  435. /**
  436. * Checks if `func` has its source masked.
  437. *
  438. * @private
  439. * @param {Function} func The function to check.
  440. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  441. */
  442. function isMasked(func) {
  443. return !!maskSrcKey && (maskSrcKey in func);
  444. }
  445. /** Used for built-in method references. */
  446. var funcProto$2 = Function.prototype;
  447. /** Used to resolve the decompiled source of functions. */
  448. var funcToString$2 = funcProto$2.toString;
  449. /**
  450. * Converts `func` to its source code.
  451. *
  452. * @private
  453. * @param {Function} func The function to convert.
  454. * @returns {string} Returns the source code.
  455. */
  456. function toSource(func) {
  457. if (func != null) {
  458. try {
  459. return funcToString$2.call(func);
  460. } catch (e) {}
  461. try {
  462. return (func + '');
  463. } catch (e) {}
  464. }
  465. return '';
  466. }
  467. /**
  468. * Used to match `RegExp`
  469. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  470. */
  471. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  472. /** Used to detect host constructors (Safari). */
  473. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  474. /** Used for built-in method references. */
  475. var funcProto$1 = Function.prototype,
  476. objectProto$9 = Object.prototype;
  477. /** Used to resolve the decompiled source of functions. */
  478. var funcToString$1 = funcProto$1.toString;
  479. /** Used to check objects for own properties. */
  480. var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
  481. /** Used to detect if a method is native. */
  482. var reIsNative = RegExp('^' +
  483. funcToString$1.call(hasOwnProperty$8).replace(reRegExpChar, '\\$&')
  484. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  485. );
  486. /**
  487. * The base implementation of `_.isNative` without bad shim checks.
  488. *
  489. * @private
  490. * @param {*} value The value to check.
  491. * @returns {boolean} Returns `true` if `value` is a native function,
  492. * else `false`.
  493. */
  494. function baseIsNative(value) {
  495. if (!isObject(value) || isMasked(value)) {
  496. return false;
  497. }
  498. var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
  499. return pattern.test(toSource(value));
  500. }
  501. /**
  502. * Gets the value at `key` of `object`.
  503. *
  504. * @private
  505. * @param {Object} [object] The object to query.
  506. * @param {string} key The key of the property to get.
  507. * @returns {*} Returns the property value.
  508. */
  509. function getValue(object, key) {
  510. return object == null ? undefined : object[key];
  511. }
  512. /**
  513. * Gets the native function at `key` of `object`.
  514. *
  515. * @private
  516. * @param {Object} object The object to query.
  517. * @param {string} key The key of the method to get.
  518. * @returns {*} Returns the function if it's native, else `undefined`.
  519. */
  520. function getNative(object, key) {
  521. var value = getValue(object, key);
  522. return baseIsNative(value) ? value : undefined;
  523. }
  524. /**
  525. * A faster alternative to `Function#apply`, this function invokes `func`
  526. * with the `this` binding of `thisArg` and the arguments of `args`.
  527. *
  528. * @private
  529. * @param {Function} func The function to invoke.
  530. * @param {*} thisArg The `this` binding of `func`.
  531. * @param {Array} args The arguments to invoke `func` with.
  532. * @returns {*} Returns the result of `func`.
  533. */
  534. function apply(func, thisArg, args) {
  535. switch (args.length) {
  536. case 0: return func.call(thisArg);
  537. case 1: return func.call(thisArg, args[0]);
  538. case 2: return func.call(thisArg, args[0], args[1]);
  539. case 3: return func.call(thisArg, args[0], args[1], args[2]);
  540. }
  541. return func.apply(thisArg, args);
  542. }
  543. /** Used to detect hot functions by number of calls within a span of milliseconds. */
  544. var HOT_COUNT = 800,
  545. HOT_SPAN = 16;
  546. /* Built-in method references for those with the same name as other `lodash` methods. */
  547. var nativeNow = Date.now;
  548. /**
  549. * Creates a function that'll short out and invoke `identity` instead
  550. * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
  551. * milliseconds.
  552. *
  553. * @private
  554. * @param {Function} func The function to restrict.
  555. * @returns {Function} Returns the new shortable function.
  556. */
  557. function shortOut(func) {
  558. var count = 0,
  559. lastCalled = 0;
  560. return function() {
  561. var stamp = nativeNow(),
  562. remaining = HOT_SPAN - (stamp - lastCalled);
  563. lastCalled = stamp;
  564. if (remaining > 0) {
  565. if (++count >= HOT_COUNT) {
  566. return arguments[0];
  567. }
  568. } else {
  569. count = 0;
  570. }
  571. return func.apply(undefined, arguments);
  572. };
  573. }
  574. /**
  575. * Creates a function that returns `value`.
  576. *
  577. * @static
  578. * @memberOf _
  579. * @since 2.4.0
  580. * @category Util
  581. * @param {*} value The value to return from the new function.
  582. * @returns {Function} Returns the new constant function.
  583. * @example
  584. *
  585. * var objects = _.times(2, _.constant({ 'a': 1 }));
  586. *
  587. * console.log(objects);
  588. * // => [{ 'a': 1 }, { 'a': 1 }]
  589. *
  590. * console.log(objects[0] === objects[1]);
  591. * // => true
  592. */
  593. function constant(value) {
  594. return function() {
  595. return value;
  596. };
  597. }
  598. var defineProperty = (function() {
  599. try {
  600. var func = getNative(Object, 'defineProperty');
  601. func({}, '', {});
  602. return func;
  603. } catch (e) {}
  604. }());
  605. /**
  606. * The base implementation of `setToString` without support for hot loop shorting.
  607. *
  608. * @private
  609. * @param {Function} func The function to modify.
  610. * @param {Function} string The `toString` result.
  611. * @returns {Function} Returns `func`.
  612. */
  613. var baseSetToString = !defineProperty ? identity : function(func, string) {
  614. return defineProperty(func, 'toString', {
  615. 'configurable': true,
  616. 'enumerable': false,
  617. 'value': constant(string),
  618. 'writable': true
  619. });
  620. };
  621. /**
  622. * Sets the `toString` method of `func` to return `string`.
  623. *
  624. * @private
  625. * @param {Function} func The function to modify.
  626. * @param {Function} string The `toString` result.
  627. * @returns {Function} Returns `func`.
  628. */
  629. var setToString = shortOut(baseSetToString);
  630. /** Used as references for various `Number` constants. */
  631. var MAX_SAFE_INTEGER$1 = 9007199254740991;
  632. /** Used to detect unsigned integer values. */
  633. var reIsUint = /^(?:0|[1-9]\d*)$/;
  634. /**
  635. * Checks if `value` is a valid array-like index.
  636. *
  637. * @private
  638. * @param {*} value The value to check.
  639. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  640. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  641. */
  642. function isIndex(value, length) {
  643. var type = typeof value;
  644. length = length == null ? MAX_SAFE_INTEGER$1 : length;
  645. return !!length &&
  646. (type == 'number' ||
  647. (type != 'symbol' && reIsUint.test(value))) &&
  648. (value > -1 && value % 1 == 0 && value < length);
  649. }
  650. /**
  651. * The base implementation of `assignValue` and `assignMergeValue` without
  652. * value checks.
  653. *
  654. * @private
  655. * @param {Object} object The object to modify.
  656. * @param {string} key The key of the property to assign.
  657. * @param {*} value The value to assign.
  658. */
  659. function baseAssignValue(object, key, value) {
  660. if (key == '__proto__' && defineProperty) {
  661. defineProperty(object, key, {
  662. 'configurable': true,
  663. 'enumerable': true,
  664. 'value': value,
  665. 'writable': true
  666. });
  667. } else {
  668. object[key] = value;
  669. }
  670. }
  671. /**
  672. * Performs a
  673. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  674. * comparison between two values to determine if they are equivalent.
  675. *
  676. * @static
  677. * @memberOf _
  678. * @since 4.0.0
  679. * @category Lang
  680. * @param {*} value The value to compare.
  681. * @param {*} other The other value to compare.
  682. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  683. * @example
  684. *
  685. * var object = { 'a': 1 };
  686. * var other = { 'a': 1 };
  687. *
  688. * _.eq(object, object);
  689. * // => true
  690. *
  691. * _.eq(object, other);
  692. * // => false
  693. *
  694. * _.eq('a', 'a');
  695. * // => true
  696. *
  697. * _.eq('a', Object('a'));
  698. * // => false
  699. *
  700. * _.eq(NaN, NaN);
  701. * // => true
  702. */
  703. function eq(value, other) {
  704. return value === other || (value !== value && other !== other);
  705. }
  706. /** Used for built-in method references. */
  707. var objectProto$8 = Object.prototype;
  708. /** Used to check objects for own properties. */
  709. var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
  710. /**
  711. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  712. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  713. * for equality comparisons.
  714. *
  715. * @private
  716. * @param {Object} object The object to modify.
  717. * @param {string} key The key of the property to assign.
  718. * @param {*} value The value to assign.
  719. */
  720. function assignValue(object, key, value) {
  721. var objValue = object[key];
  722. if (!(hasOwnProperty$7.call(object, key) && eq(objValue, value)) ||
  723. (value === undefined && !(key in object))) {
  724. baseAssignValue(object, key, value);
  725. }
  726. }
  727. /**
  728. * Copies properties of `source` to `object`.
  729. *
  730. * @private
  731. * @param {Object} source The object to copy properties from.
  732. * @param {Array} props The property identifiers to copy.
  733. * @param {Object} [object={}] The object to copy properties to.
  734. * @param {Function} [customizer] The function to customize copied values.
  735. * @returns {Object} Returns `object`.
  736. */
  737. function copyObject(source, props, object, customizer) {
  738. var isNew = !object;
  739. object || (object = {});
  740. var index = -1,
  741. length = props.length;
  742. while (++index < length) {
  743. var key = props[index];
  744. var newValue = customizer
  745. ? customizer(object[key], source[key], key, object, source)
  746. : undefined;
  747. if (newValue === undefined) {
  748. newValue = source[key];
  749. }
  750. if (isNew) {
  751. baseAssignValue(object, key, newValue);
  752. } else {
  753. assignValue(object, key, newValue);
  754. }
  755. }
  756. return object;
  757. }
  758. /* Built-in method references for those with the same name as other `lodash` methods. */
  759. var nativeMax = Math.max;
  760. /**
  761. * A specialized version of `baseRest` which transforms the rest array.
  762. *
  763. * @private
  764. * @param {Function} func The function to apply a rest parameter to.
  765. * @param {number} [start=func.length-1] The start position of the rest parameter.
  766. * @param {Function} transform The rest array transform.
  767. * @returns {Function} Returns the new function.
  768. */
  769. function overRest(func, start, transform) {
  770. start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
  771. return function() {
  772. var args = arguments,
  773. index = -1,
  774. length = nativeMax(args.length - start, 0),
  775. array = Array(length);
  776. while (++index < length) {
  777. array[index] = args[start + index];
  778. }
  779. index = -1;
  780. var otherArgs = Array(start + 1);
  781. while (++index < start) {
  782. otherArgs[index] = args[index];
  783. }
  784. otherArgs[start] = transform(array);
  785. return apply(func, this, otherArgs);
  786. };
  787. }
  788. /**
  789. * The base implementation of `_.rest` which doesn't validate or coerce arguments.
  790. *
  791. * @private
  792. * @param {Function} func The function to apply a rest parameter to.
  793. * @param {number} [start=func.length-1] The start position of the rest parameter.
  794. * @returns {Function} Returns the new function.
  795. */
  796. function baseRest(func, start) {
  797. return setToString(overRest(func, start, identity), func + '');
  798. }
  799. /** Used as references for various `Number` constants. */
  800. var MAX_SAFE_INTEGER = 9007199254740991;
  801. /**
  802. * Checks if `value` is a valid array-like length.
  803. *
  804. * **Note:** This method is loosely based on
  805. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  806. *
  807. * @static
  808. * @memberOf _
  809. * @since 4.0.0
  810. * @category Lang
  811. * @param {*} value The value to check.
  812. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  813. * @example
  814. *
  815. * _.isLength(3);
  816. * // => true
  817. *
  818. * _.isLength(Number.MIN_VALUE);
  819. * // => false
  820. *
  821. * _.isLength(Infinity);
  822. * // => false
  823. *
  824. * _.isLength('3');
  825. * // => false
  826. */
  827. function isLength(value) {
  828. return typeof value == 'number' &&
  829. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  830. }
  831. /**
  832. * Checks if `value` is array-like. A value is considered array-like if it's
  833. * not a function and has a `value.length` that's an integer greater than or
  834. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  835. *
  836. * @static
  837. * @memberOf _
  838. * @since 4.0.0
  839. * @category Lang
  840. * @param {*} value The value to check.
  841. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  842. * @example
  843. *
  844. * _.isArrayLike([1, 2, 3]);
  845. * // => true
  846. *
  847. * _.isArrayLike(document.body.children);
  848. * // => true
  849. *
  850. * _.isArrayLike('abc');
  851. * // => true
  852. *
  853. * _.isArrayLike(_.noop);
  854. * // => false
  855. */
  856. function isArrayLike(value) {
  857. return value != null && isLength(value.length) && !isFunction(value);
  858. }
  859. /**
  860. * Checks if the given arguments are from an iteratee call.
  861. *
  862. * @private
  863. * @param {*} value The potential iteratee value argument.
  864. * @param {*} index The potential iteratee index or key argument.
  865. * @param {*} object The potential iteratee object argument.
  866. * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
  867. * else `false`.
  868. */
  869. function isIterateeCall(value, index, object) {
  870. if (!isObject(object)) {
  871. return false;
  872. }
  873. var type = typeof index;
  874. if (type == 'number'
  875. ? (isArrayLike(object) && isIndex(index, object.length))
  876. : (type == 'string' && index in object)
  877. ) {
  878. return eq(object[index], value);
  879. }
  880. return false;
  881. }
  882. /**
  883. * Creates a function like `_.assign`.
  884. *
  885. * @private
  886. * @param {Function} assigner The function to assign values.
  887. * @returns {Function} Returns the new assigner function.
  888. */
  889. function createAssigner(assigner) {
  890. return baseRest(function(object, sources) {
  891. var index = -1,
  892. length = sources.length,
  893. customizer = length > 1 ? sources[length - 1] : undefined,
  894. guard = length > 2 ? sources[2] : undefined;
  895. customizer = (assigner.length > 3 && typeof customizer == 'function')
  896. ? (length--, customizer)
  897. : undefined;
  898. if (guard && isIterateeCall(sources[0], sources[1], guard)) {
  899. customizer = length < 3 ? undefined : customizer;
  900. length = 1;
  901. }
  902. object = Object(object);
  903. while (++index < length) {
  904. var source = sources[index];
  905. if (source) {
  906. assigner(object, source, index, customizer);
  907. }
  908. }
  909. return object;
  910. });
  911. }
  912. /** Used for built-in method references. */
  913. var objectProto$7 = Object.prototype;
  914. /**
  915. * Checks if `value` is likely a prototype object.
  916. *
  917. * @private
  918. * @param {*} value The value to check.
  919. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  920. */
  921. function isPrototype(value) {
  922. var Ctor = value && value.constructor,
  923. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$7;
  924. return value === proto;
  925. }
  926. /**
  927. * The base implementation of `_.times` without support for iteratee shorthands
  928. * or max array length checks.
  929. *
  930. * @private
  931. * @param {number} n The number of times to invoke `iteratee`.
  932. * @param {Function} iteratee The function invoked per iteration.
  933. * @returns {Array} Returns the array of results.
  934. */
  935. function baseTimes(n, iteratee) {
  936. var index = -1,
  937. result = Array(n);
  938. while (++index < n) {
  939. result[index] = iteratee(index);
  940. }
  941. return result;
  942. }
  943. /** `Object#toString` result references. */
  944. var argsTag$1 = '[object Arguments]';
  945. /**
  946. * The base implementation of `_.isArguments`.
  947. *
  948. * @private
  949. * @param {*} value The value to check.
  950. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  951. */
  952. function baseIsArguments(value) {
  953. return isObjectLike(value) && baseGetTag(value) == argsTag$1;
  954. }
  955. /** Used for built-in method references. */
  956. var objectProto$6 = Object.prototype;
  957. /** Used to check objects for own properties. */
  958. var hasOwnProperty$6 = objectProto$6.hasOwnProperty;
  959. /** Built-in value references. */
  960. var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
  961. /**
  962. * Checks if `value` is likely an `arguments` object.
  963. *
  964. * @static
  965. * @memberOf _
  966. * @since 0.1.0
  967. * @category Lang
  968. * @param {*} value The value to check.
  969. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  970. * else `false`.
  971. * @example
  972. *
  973. * _.isArguments(function() { return arguments; }());
  974. * // => true
  975. *
  976. * _.isArguments([1, 2, 3]);
  977. * // => false
  978. */
  979. var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
  980. return isObjectLike(value) && hasOwnProperty$6.call(value, 'callee') &&
  981. !propertyIsEnumerable.call(value, 'callee');
  982. };
  983. /**
  984. * This method returns `false`.
  985. *
  986. * @static
  987. * @memberOf _
  988. * @since 4.13.0
  989. * @category Util
  990. * @returns {boolean} Returns `false`.
  991. * @example
  992. *
  993. * _.times(2, _.stubFalse);
  994. * // => [false, false]
  995. */
  996. function stubFalse() {
  997. return false;
  998. }
  999. /** Detect free variable `exports`. */
  1000. var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports;
  1001. /** Detect free variable `module`. */
  1002. var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module;
  1003. /** Detect the popular CommonJS extension `module.exports`. */
  1004. var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
  1005. /** Built-in value references. */
  1006. var Buffer = moduleExports$1 ? root.Buffer : undefined;
  1007. /* Built-in method references for those with the same name as other `lodash` methods. */
  1008. var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
  1009. /**
  1010. * Checks if `value` is a buffer.
  1011. *
  1012. * @static
  1013. * @memberOf _
  1014. * @since 4.3.0
  1015. * @category Lang
  1016. * @param {*} value The value to check.
  1017. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  1018. * @example
  1019. *
  1020. * _.isBuffer(new Buffer(2));
  1021. * // => true
  1022. *
  1023. * _.isBuffer(new Uint8Array(2));
  1024. * // => false
  1025. */
  1026. var isBuffer = nativeIsBuffer || stubFalse;
  1027. /** `Object#toString` result references. */
  1028. var argsTag = '[object Arguments]',
  1029. arrayTag = '[object Array]',
  1030. boolTag = '[object Boolean]',
  1031. dateTag = '[object Date]',
  1032. errorTag$1 = '[object Error]',
  1033. funcTag = '[object Function]',
  1034. mapTag = '[object Map]',
  1035. numberTag = '[object Number]',
  1036. objectTag$1 = '[object Object]',
  1037. regexpTag = '[object RegExp]',
  1038. setTag = '[object Set]',
  1039. stringTag = '[object String]',
  1040. weakMapTag = '[object WeakMap]';
  1041. var arrayBufferTag = '[object ArrayBuffer]',
  1042. dataViewTag = '[object DataView]',
  1043. float32Tag = '[object Float32Array]',
  1044. float64Tag = '[object Float64Array]',
  1045. int8Tag = '[object Int8Array]',
  1046. int16Tag = '[object Int16Array]',
  1047. int32Tag = '[object Int32Array]',
  1048. uint8Tag = '[object Uint8Array]',
  1049. uint8ClampedTag = '[object Uint8ClampedArray]',
  1050. uint16Tag = '[object Uint16Array]',
  1051. uint32Tag = '[object Uint32Array]';
  1052. /** Used to identify `toStringTag` values of typed arrays. */
  1053. var typedArrayTags = {};
  1054. typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
  1055. typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
  1056. typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
  1057. typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
  1058. typedArrayTags[uint32Tag] = true;
  1059. typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
  1060. typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
  1061. typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
  1062. typedArrayTags[errorTag$1] = typedArrayTags[funcTag] =
  1063. typedArrayTags[mapTag] = typedArrayTags[numberTag] =
  1064. typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] =
  1065. typedArrayTags[setTag] = typedArrayTags[stringTag] =
  1066. typedArrayTags[weakMapTag] = false;
  1067. /**
  1068. * The base implementation of `_.isTypedArray` without Node.js optimizations.
  1069. *
  1070. * @private
  1071. * @param {*} value The value to check.
  1072. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  1073. */
  1074. function baseIsTypedArray(value) {
  1075. return isObjectLike(value) &&
  1076. isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
  1077. }
  1078. /**
  1079. * The base implementation of `_.unary` without support for storing metadata.
  1080. *
  1081. * @private
  1082. * @param {Function} func The function to cap arguments for.
  1083. * @returns {Function} Returns the new capped function.
  1084. */
  1085. function baseUnary(func) {
  1086. return function(value) {
  1087. return func(value);
  1088. };
  1089. }
  1090. /** Detect free variable `exports`. */
  1091. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  1092. /** Detect free variable `module`. */
  1093. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  1094. /** Detect the popular CommonJS extension `module.exports`. */
  1095. var moduleExports = freeModule && freeModule.exports === freeExports;
  1096. /** Detect free variable `process` from Node.js. */
  1097. var freeProcess = moduleExports && freeGlobal.process;
  1098. /** Used to access faster Node.js helpers. */
  1099. var nodeUtil = (function() {
  1100. try {
  1101. // Use `util.types` for Node.js 10+.
  1102. var types = freeModule && freeModule.require && freeModule.require('util').types;
  1103. if (types) {
  1104. return types;
  1105. }
  1106. // Legacy `process.binding('util')` for Node.js < 10.
  1107. return freeProcess && freeProcess.binding && freeProcess.binding('util');
  1108. } catch (e) {}
  1109. }());
  1110. /* Node.js helper references. */
  1111. var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
  1112. /**
  1113. * Checks if `value` is classified as a typed array.
  1114. *
  1115. * @static
  1116. * @memberOf _
  1117. * @since 3.0.0
  1118. * @category Lang
  1119. * @param {*} value The value to check.
  1120. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
  1121. * @example
  1122. *
  1123. * _.isTypedArray(new Uint8Array);
  1124. * // => true
  1125. *
  1126. * _.isTypedArray([]);
  1127. * // => false
  1128. */
  1129. var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
  1130. /** Used for built-in method references. */
  1131. var objectProto$5 = Object.prototype;
  1132. /** Used to check objects for own properties. */
  1133. var hasOwnProperty$5 = objectProto$5.hasOwnProperty;
  1134. /**
  1135. * Creates an array of the enumerable property names of the array-like `value`.
  1136. *
  1137. * @private
  1138. * @param {*} value The value to query.
  1139. * @param {boolean} inherited Specify returning inherited property names.
  1140. * @returns {Array} Returns the array of property names.
  1141. */
  1142. function arrayLikeKeys(value, inherited) {
  1143. var isArr = isArray(value),
  1144. isArg = !isArr && isArguments(value),
  1145. isBuff = !isArr && !isArg && isBuffer(value),
  1146. isType = !isArr && !isArg && !isBuff && isTypedArray(value),
  1147. skipIndexes = isArr || isArg || isBuff || isType,
  1148. result = skipIndexes ? baseTimes(value.length, String) : [],
  1149. length = result.length;
  1150. for (var key in value) {
  1151. if ((inherited || hasOwnProperty$5.call(value, key)) &&
  1152. !(skipIndexes && (
  1153. // Safari 9 has enumerable `arguments.length` in strict mode.
  1154. key == 'length' ||
  1155. // Node.js 0.10 has enumerable non-index properties on buffers.
  1156. (isBuff && (key == 'offset' || key == 'parent')) ||
  1157. // PhantomJS 2 has enumerable non-index properties on typed arrays.
  1158. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
  1159. // Skip index properties.
  1160. isIndex(key, length)
  1161. ))) {
  1162. result.push(key);
  1163. }
  1164. }
  1165. return result;
  1166. }
  1167. /**
  1168. * Creates a unary function that invokes `func` with its argument transformed.
  1169. *
  1170. * @private
  1171. * @param {Function} func The function to wrap.
  1172. * @param {Function} transform The argument transform.
  1173. * @returns {Function} Returns the new function.
  1174. */
  1175. function overArg(func, transform) {
  1176. return function(arg) {
  1177. return func(transform(arg));
  1178. };
  1179. }
  1180. /* Built-in method references for those with the same name as other `lodash` methods. */
  1181. var nativeKeys = overArg(Object.keys, Object);
  1182. /** Used for built-in method references. */
  1183. var objectProto$4 = Object.prototype;
  1184. /** Used to check objects for own properties. */
  1185. var hasOwnProperty$4 = objectProto$4.hasOwnProperty;
  1186. /**
  1187. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  1188. *
  1189. * @private
  1190. * @param {Object} object The object to query.
  1191. * @returns {Array} Returns the array of property names.
  1192. */
  1193. function baseKeys(object) {
  1194. if (!isPrototype(object)) {
  1195. return nativeKeys(object);
  1196. }
  1197. var result = [];
  1198. for (var key in Object(object)) {
  1199. if (hasOwnProperty$4.call(object, key) && key != 'constructor') {
  1200. result.push(key);
  1201. }
  1202. }
  1203. return result;
  1204. }
  1205. /**
  1206. * Creates an array of the own enumerable property names of `object`.
  1207. *
  1208. * **Note:** Non-object values are coerced to objects. See the
  1209. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  1210. * for more details.
  1211. *
  1212. * @static
  1213. * @since 0.1.0
  1214. * @memberOf _
  1215. * @category Object
  1216. * @param {Object} object The object to query.
  1217. * @returns {Array} Returns the array of property names.
  1218. * @example
  1219. *
  1220. * function Foo() {
  1221. * this.a = 1;
  1222. * this.b = 2;
  1223. * }
  1224. *
  1225. * Foo.prototype.c = 3;
  1226. *
  1227. * _.keys(new Foo);
  1228. * // => ['a', 'b'] (iteration order is not guaranteed)
  1229. *
  1230. * _.keys('hi');
  1231. * // => ['0', '1']
  1232. */
  1233. function keys(object) {
  1234. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  1235. }
  1236. /**
  1237. * This function is like
  1238. * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  1239. * except that it includes inherited enumerable properties.
  1240. *
  1241. * @private
  1242. * @param {Object} object The object to query.
  1243. * @returns {Array} Returns the array of property names.
  1244. */
  1245. function nativeKeysIn(object) {
  1246. var result = [];
  1247. if (object != null) {
  1248. for (var key in Object(object)) {
  1249. result.push(key);
  1250. }
  1251. }
  1252. return result;
  1253. }
  1254. /** Used for built-in method references. */
  1255. var objectProto$3 = Object.prototype;
  1256. /** Used to check objects for own properties. */
  1257. var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
  1258. /**
  1259. * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
  1260. *
  1261. * @private
  1262. * @param {Object} object The object to query.
  1263. * @returns {Array} Returns the array of property names.
  1264. */
  1265. function baseKeysIn(object) {
  1266. if (!isObject(object)) {
  1267. return nativeKeysIn(object);
  1268. }
  1269. var isProto = isPrototype(object),
  1270. result = [];
  1271. for (var key in object) {
  1272. if (!(key == 'constructor' && (isProto || !hasOwnProperty$3.call(object, key)))) {
  1273. result.push(key);
  1274. }
  1275. }
  1276. return result;
  1277. }
  1278. /**
  1279. * Creates an array of the own and inherited enumerable property names of `object`.
  1280. *
  1281. * **Note:** Non-object values are coerced to objects.
  1282. *
  1283. * @static
  1284. * @memberOf _
  1285. * @since 3.0.0
  1286. * @category Object
  1287. * @param {Object} object The object to query.
  1288. * @returns {Array} Returns the array of property names.
  1289. * @example
  1290. *
  1291. * function Foo() {
  1292. * this.a = 1;
  1293. * this.b = 2;
  1294. * }
  1295. *
  1296. * Foo.prototype.c = 3;
  1297. *
  1298. * _.keysIn(new Foo);
  1299. * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
  1300. */
  1301. function keysIn(object) {
  1302. return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
  1303. }
  1304. /**
  1305. * This method is like `_.assignIn` except that it accepts `customizer`
  1306. * which is invoked to produce the assigned values. If `customizer` returns
  1307. * `undefined`, assignment is handled by the method instead. The `customizer`
  1308. * is invoked with five arguments: (objValue, srcValue, key, object, source).
  1309. *
  1310. * **Note:** This method mutates `object`.
  1311. *
  1312. * @static
  1313. * @memberOf _
  1314. * @since 4.0.0
  1315. * @alias extendWith
  1316. * @category Object
  1317. * @param {Object} object The destination object.
  1318. * @param {...Object} sources The source objects.
  1319. * @param {Function} [customizer] The function to customize assigned values.
  1320. * @returns {Object} Returns `object`.
  1321. * @see _.assignWith
  1322. * @example
  1323. *
  1324. * function customizer(objValue, srcValue) {
  1325. * return _.isUndefined(objValue) ? srcValue : objValue;
  1326. * }
  1327. *
  1328. * var defaults = _.partialRight(_.assignInWith, customizer);
  1329. *
  1330. * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
  1331. * // => { 'a': 1, 'b': 2 }
  1332. */
  1333. var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
  1334. copyObject(source, keysIn(source), object, customizer);
  1335. });
  1336. /**
  1337. * Converts `value` to a string. An empty string is returned for `null`
  1338. * and `undefined` values. The sign of `-0` is preserved.
  1339. *
  1340. * @static
  1341. * @memberOf _
  1342. * @since 4.0.0
  1343. * @category Lang
  1344. * @param {*} value The value to convert.
  1345. * @returns {string} Returns the converted string.
  1346. * @example
  1347. *
  1348. * _.toString(null);
  1349. * // => ''
  1350. *
  1351. * _.toString(-0);
  1352. * // => '-0'
  1353. *
  1354. * _.toString([1, 2, 3]);
  1355. * // => '1,2,3'
  1356. */
  1357. function toString(value) {
  1358. return value == null ? '' : baseToString(value);
  1359. }
  1360. /** Built-in value references. */
  1361. var getPrototype = overArg(Object.getPrototypeOf, Object);
  1362. /** `Object#toString` result references. */
  1363. var objectTag = '[object Object]';
  1364. /** Used for built-in method references. */
  1365. var funcProto = Function.prototype,
  1366. objectProto$2 = Object.prototype;
  1367. /** Used to resolve the decompiled source of functions. */
  1368. var funcToString = funcProto.toString;
  1369. /** Used to check objects for own properties. */
  1370. var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
  1371. /** Used to infer the `Object` constructor. */
  1372. var objectCtorString = funcToString.call(Object);
  1373. /**
  1374. * Checks if `value` is a plain object, that is, an object created by the
  1375. * `Object` constructor or one with a `[[Prototype]]` of `null`.
  1376. *
  1377. * @static
  1378. * @memberOf _
  1379. * @since 0.8.0
  1380. * @category Lang
  1381. * @param {*} value The value to check.
  1382. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
  1383. * @example
  1384. *
  1385. * function Foo() {
  1386. * this.a = 1;
  1387. * }
  1388. *
  1389. * _.isPlainObject(new Foo);
  1390. * // => false
  1391. *
  1392. * _.isPlainObject([1, 2, 3]);
  1393. * // => false
  1394. *
  1395. * _.isPlainObject({ 'x': 0, 'y': 0 });
  1396. * // => true
  1397. *
  1398. * _.isPlainObject(Object.create(null));
  1399. * // => true
  1400. */
  1401. function isPlainObject(value) {
  1402. if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
  1403. return false;
  1404. }
  1405. var proto = getPrototype(value);
  1406. if (proto === null) {
  1407. return true;
  1408. }
  1409. var Ctor = hasOwnProperty$2.call(proto, 'constructor') && proto.constructor;
  1410. return typeof Ctor == 'function' && Ctor instanceof Ctor &&
  1411. funcToString.call(Ctor) == objectCtorString;
  1412. }
  1413. /** `Object#toString` result references. */
  1414. var domExcTag = '[object DOMException]',
  1415. errorTag = '[object Error]';
  1416. /**
  1417. * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
  1418. * `SyntaxError`, `TypeError`, or `URIError` object.
  1419. *
  1420. * @static
  1421. * @memberOf _
  1422. * @since 3.0.0
  1423. * @category Lang
  1424. * @param {*} value The value to check.
  1425. * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
  1426. * @example
  1427. *
  1428. * _.isError(new Error);
  1429. * // => true
  1430. *
  1431. * _.isError(Error);
  1432. * // => false
  1433. */
  1434. function isError(value) {
  1435. if (!isObjectLike(value)) {
  1436. return false;
  1437. }
  1438. var tag = baseGetTag(value);
  1439. return tag == errorTag || tag == domExcTag ||
  1440. (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
  1441. }
  1442. /**
  1443. * Attempts to invoke `func`, returning either the result or the caught error
  1444. * object. Any additional arguments are provided to `func` when it's invoked.
  1445. *
  1446. * @static
  1447. * @memberOf _
  1448. * @since 3.0.0
  1449. * @category Util
  1450. * @param {Function} func The function to attempt.
  1451. * @param {...*} [args] The arguments to invoke `func` with.
  1452. * @returns {*} Returns the `func` result or error object.
  1453. * @example
  1454. *
  1455. * // Avoid throwing errors for invalid selectors.
  1456. * var elements = _.attempt(function(selector) {
  1457. * return document.querySelectorAll(selector);
  1458. * }, '>_>');
  1459. *
  1460. * if (_.isError(elements)) {
  1461. * elements = [];
  1462. * }
  1463. */
  1464. var attempt = baseRest(function(func, args) {
  1465. try {
  1466. return apply(func, undefined, args);
  1467. } catch (e) {
  1468. return isError(e) ? e : new Error(e);
  1469. }
  1470. });
  1471. /**
  1472. * The base implementation of `_.propertyOf` without support for deep paths.
  1473. *
  1474. * @private
  1475. * @param {Object} object The object to query.
  1476. * @returns {Function} Returns the new accessor function.
  1477. */
  1478. function basePropertyOf(object) {
  1479. return function(key) {
  1480. return object == null ? undefined : object[key];
  1481. };
  1482. }
  1483. /** Used to map characters to HTML entities. */
  1484. var htmlEscapes = {
  1485. '&': '&amp;',
  1486. '<': '&lt;',
  1487. '>': '&gt;',
  1488. '"': '&quot;',
  1489. "'": '&#39;'
  1490. };
  1491. /**
  1492. * Used by `_.escape` to convert characters to HTML entities.
  1493. *
  1494. * @private
  1495. * @param {string} chr The matched character to escape.
  1496. * @returns {string} Returns the escaped character.
  1497. */
  1498. var escapeHtmlChar = basePropertyOf(htmlEscapes);
  1499. /** Used to match HTML entities and HTML characters. */
  1500. var reUnescapedHtml = /[&<>"']/g,
  1501. reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
  1502. /**
  1503. * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
  1504. * corresponding HTML entities.
  1505. *
  1506. * **Note:** No other characters are escaped. To escape additional
  1507. * characters use a third-party library like [_he_](https://mths.be/he).
  1508. *
  1509. * Though the ">" character is escaped for symmetry, characters like
  1510. * ">" and "/" don't need escaping in HTML and have no special meaning
  1511. * unless they're part of a tag or unquoted attribute value. See
  1512. * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
  1513. * (under "semi-related fun fact") for more details.
  1514. *
  1515. * When working with HTML you should always
  1516. * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
  1517. * XSS vectors.
  1518. *
  1519. * @static
  1520. * @since 0.1.0
  1521. * @memberOf _
  1522. * @category String
  1523. * @param {string} [string=''] The string to escape.
  1524. * @returns {string} Returns the escaped string.
  1525. * @example
  1526. *
  1527. * _.escape('fred, barney, & pebbles');
  1528. * // => 'fred, barney, &amp; pebbles'
  1529. */
  1530. function escape(string) {
  1531. string = toString(string);
  1532. return (string && reHasUnescapedHtml.test(string))
  1533. ? string.replace(reUnescapedHtml, escapeHtmlChar)
  1534. : string;
  1535. }
  1536. /**
  1537. * The base implementation of `_.values` and `_.valuesIn` which creates an
  1538. * array of `object` property values corresponding to the property names
  1539. * of `props`.
  1540. *
  1541. * @private
  1542. * @param {Object} object The object to query.
  1543. * @param {Array} props The property names to get values for.
  1544. * @returns {Object} Returns the array of property values.
  1545. */
  1546. function baseValues(object, props) {
  1547. return arrayMap(props, function(key) {
  1548. return object[key];
  1549. });
  1550. }
  1551. /** Used for built-in method references. */
  1552. var objectProto$1 = Object.prototype;
  1553. /** Used to check objects for own properties. */
  1554. var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
  1555. /**
  1556. * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
  1557. * of source objects to the destination object for all destination properties
  1558. * that resolve to `undefined`.
  1559. *
  1560. * @private
  1561. * @param {*} objValue The destination value.
  1562. * @param {*} srcValue The source value.
  1563. * @param {string} key The key of the property to assign.
  1564. * @param {Object} object The parent object of `objValue`.
  1565. * @returns {*} Returns the value to assign.
  1566. */
  1567. function customDefaultsAssignIn(objValue, srcValue, key, object) {
  1568. if (objValue === undefined ||
  1569. (eq(objValue, objectProto$1[key]) && !hasOwnProperty$1.call(object, key))) {
  1570. return srcValue;
  1571. }
  1572. return objValue;
  1573. }
  1574. /** Used to escape characters for inclusion in compiled string literals. */
  1575. var stringEscapes = {
  1576. '\\': '\\',
  1577. "'": "'",
  1578. '\n': 'n',
  1579. '\r': 'r',
  1580. '\u2028': 'u2028',
  1581. '\u2029': 'u2029'
  1582. };
  1583. /**
  1584. * Used by `_.template` to escape characters for inclusion in compiled string literals.
  1585. *
  1586. * @private
  1587. * @param {string} chr The matched character to escape.
  1588. * @returns {string} Returns the escaped character.
  1589. */
  1590. function escapeStringChar(chr) {
  1591. return '\\' + stringEscapes[chr];
  1592. }
  1593. /** Used to match template delimiters. */
  1594. var reInterpolate = /<%=([\s\S]+?)%>/g;
  1595. /** Used to match template delimiters. */
  1596. var reEscape = /<%-([\s\S]+?)%>/g;
  1597. /** Used to match template delimiters. */
  1598. var reEvaluate = /<%([\s\S]+?)%>/g;
  1599. /**
  1600. * By default, the template delimiters used by lodash are like those in
  1601. * embedded Ruby (ERB) as well as ES2015 template strings. Change the
  1602. * following template settings to use alternative delimiters.
  1603. *
  1604. * @static
  1605. * @memberOf _
  1606. * @type {Object}
  1607. */
  1608. var templateSettings = {
  1609. /**
  1610. * Used to detect `data` property values to be HTML-escaped.
  1611. *
  1612. * @memberOf _.templateSettings
  1613. * @type {RegExp}
  1614. */
  1615. 'escape': reEscape,
  1616. /**
  1617. * Used to detect code to be evaluated.
  1618. *
  1619. * @memberOf _.templateSettings
  1620. * @type {RegExp}
  1621. */
  1622. 'evaluate': reEvaluate,
  1623. /**
  1624. * Used to detect `data` property values to inject.
  1625. *
  1626. * @memberOf _.templateSettings
  1627. * @type {RegExp}
  1628. */
  1629. 'interpolate': reInterpolate,
  1630. /**
  1631. * Used to reference the data object in the template text.
  1632. *
  1633. * @memberOf _.templateSettings
  1634. * @type {string}
  1635. */
  1636. 'variable': '',
  1637. /**
  1638. * Used to import variables into the compiled template.
  1639. *
  1640. * @memberOf _.templateSettings
  1641. * @type {Object}
  1642. */
  1643. 'imports': {
  1644. /**
  1645. * A reference to the `lodash` function.
  1646. *
  1647. * @memberOf _.templateSettings.imports
  1648. * @type {Function}
  1649. */
  1650. '_': { 'escape': escape }
  1651. }
  1652. };
  1653. /** Error message constants. */
  1654. var INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
  1655. /** Used to match empty string literals in compiled template source. */
  1656. var reEmptyStringLeading = /\b__p \+= '';/g,
  1657. reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
  1658. reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
  1659. /**
  1660. * Used to validate the `validate` option in `_.template` variable.
  1661. *
  1662. * Forbids characters which could potentially change the meaning of the function argument definition:
  1663. * - "()," (modification of function parameters)
  1664. * - "=" (default value)
  1665. * - "[]{}" (destructuring of function parameters)
  1666. * - "/" (beginning of a comment)
  1667. * - whitespace
  1668. */
  1669. var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
  1670. /**
  1671. * Used to match
  1672. * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
  1673. */
  1674. var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
  1675. /** Used to ensure capturing order of template delimiters. */
  1676. var reNoMatch = /($^)/;
  1677. /** Used to match unescaped characters in compiled string literals. */
  1678. var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
  1679. /** Used for built-in method references. */
  1680. var objectProto = Object.prototype;
  1681. /** Used to check objects for own properties. */
  1682. var hasOwnProperty = objectProto.hasOwnProperty;
  1683. /**
  1684. * Creates a compiled template function that can interpolate data properties
  1685. * in "interpolate" delimiters, HTML-escape interpolated data properties in
  1686. * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
  1687. * properties may be accessed as free variables in the template. If a setting
  1688. * object is given, it takes precedence over `_.templateSettings` values.
  1689. *
  1690. * **Note:** In the development build `_.template` utilizes
  1691. * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
  1692. * for easier debugging.
  1693. *
  1694. * For more information on precompiling templates see
  1695. * [lodash's custom builds documentation](https://lodash.com/custom-builds).
  1696. *
  1697. * For more information on Chrome extension sandboxes see
  1698. * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
  1699. *
  1700. * @static
  1701. * @since 0.1.0
  1702. * @memberOf _
  1703. * @category String
  1704. * @param {string} [string=''] The template string.
  1705. * @param {Object} [options={}] The options object.
  1706. * @param {RegExp} [options.escape=_.templateSettings.escape]
  1707. * The HTML "escape" delimiter.
  1708. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
  1709. * The "evaluate" delimiter.
  1710. * @param {Object} [options.imports=_.templateSettings.imports]
  1711. * An object to import into the template as free variables.
  1712. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
  1713. * The "interpolate" delimiter.
  1714. * @param {string} [options.sourceURL='templateSources[n]']
  1715. * The sourceURL of the compiled template.
  1716. * @param {string} [options.variable='obj']
  1717. * The data object variable name.
  1718. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
  1719. * @returns {Function} Returns the compiled template function.
  1720. * @example
  1721. *
  1722. * // Use the "interpolate" delimiter to create a compiled template.
  1723. * var compiled = _.template('hello <%= user %>!');
  1724. * compiled({ 'user': 'fred' });
  1725. * // => 'hello fred!'
  1726. *
  1727. * // Use the HTML "escape" delimiter to escape data property values.
  1728. * var compiled = _.template('<b><%- value %></b>');
  1729. * compiled({ 'value': '<script>' });
  1730. * // => '<b>&lt;script&gt;</b>'
  1731. *
  1732. * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
  1733. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
  1734. * compiled({ 'users': ['fred', 'barney'] });
  1735. * // => '<li>fred</li><li>barney</li>'
  1736. *
  1737. * // Use the internal `print` function in "evaluate" delimiters.
  1738. * var compiled = _.template('<% print("hello " + user); %>!');
  1739. * compiled({ 'user': 'barney' });
  1740. * // => 'hello barney!'
  1741. *
  1742. * // Use the ES template literal delimiter as an "interpolate" delimiter.
  1743. * // Disable support by replacing the "interpolate" delimiter.
  1744. * var compiled = _.template('hello ${ user }!');
  1745. * compiled({ 'user': 'pebbles' });
  1746. * // => 'hello pebbles!'
  1747. *
  1748. * // Use backslashes to treat delimiters as plain text.
  1749. * var compiled = _.template('<%= "\\<%- value %\\>" %>');
  1750. * compiled({ 'value': 'ignored' });
  1751. * // => '<%- value %>'
  1752. *
  1753. * // Use the `imports` option to import `jQuery` as `jq`.
  1754. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
  1755. * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
  1756. * compiled({ 'users': ['fred', 'barney'] });
  1757. * // => '<li>fred</li><li>barney</li>'
  1758. *
  1759. * // Use the `sourceURL` option to specify a custom sourceURL for the template.
  1760. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
  1761. * compiled(data);
  1762. * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
  1763. *
  1764. * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
  1765. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
  1766. * compiled.source;
  1767. * // => function(data) {
  1768. * // var __t, __p = '';
  1769. * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
  1770. * // return __p;
  1771. * // }
  1772. *
  1773. * // Use custom template delimiters.
  1774. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
  1775. * var compiled = _.template('hello {{ user }}!');
  1776. * compiled({ 'user': 'mustache' });
  1777. * // => 'hello mustache!'
  1778. *
  1779. * // Use the `source` property to inline compiled templates for meaningful
  1780. * // line numbers in error messages and stack traces.
  1781. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
  1782. * var JST = {\
  1783. * "main": ' + _.template(mainText).source + '\
  1784. * };\
  1785. * ');
  1786. */
  1787. function template(string, options, guard) {
  1788. // Based on John Resig's `tmpl` implementation
  1789. // (http://ejohn.org/blog/javascript-micro-templating/)
  1790. // and Laura Doktorova's doT.js (https://github.com/olado/doT).
  1791. var settings = templateSettings.imports._.templateSettings || templateSettings;
  1792. string = toString(string);
  1793. options = assignInWith({}, options, settings, customDefaultsAssignIn);
  1794. var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
  1795. importsKeys = keys(imports),
  1796. importsValues = baseValues(imports, importsKeys);
  1797. var isEscaping,
  1798. isEvaluating,
  1799. index = 0,
  1800. interpolate = options.interpolate || reNoMatch,
  1801. source = "__p += '";
  1802. // Compile the regexp to match each delimiter.
  1803. var reDelimiters = RegExp(
  1804. (options.escape || reNoMatch).source + '|' +
  1805. interpolate.source + '|' +
  1806. (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
  1807. (options.evaluate || reNoMatch).source + '|$'
  1808. , 'g');
  1809. // Use a sourceURL for easier debugging.
  1810. // The sourceURL gets injected into the source that's eval-ed, so be careful
  1811. // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
  1812. // and escape the comment, thus injecting code that gets evaled.
  1813. var sourceURL = hasOwnProperty.call(options, 'sourceURL')
  1814. ? ('//# sourceURL=' +
  1815. (options.sourceURL + '').replace(/\s/g, ' ') +
  1816. '\n')
  1817. : '';
  1818. string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
  1819. interpolateValue || (interpolateValue = esTemplateValue);
  1820. // Escape characters that can't be included in string literals.
  1821. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
  1822. // Replace delimiters with snippets.
  1823. if (escapeValue) {
  1824. isEscaping = true;
  1825. source += "' +\n__e(" + escapeValue + ") +\n'";
  1826. }
  1827. if (evaluateValue) {
  1828. isEvaluating = true;
  1829. source += "';\n" + evaluateValue + ";\n__p += '";
  1830. }
  1831. if (interpolateValue) {
  1832. source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
  1833. }
  1834. index = offset + match.length;
  1835. // The JS engine embedded in Adobe products needs `match` returned in
  1836. // order to produce the correct `offset` value.
  1837. return match;
  1838. });
  1839. source += "';\n";
  1840. // If `variable` is not specified wrap a with-statement around the generated
  1841. // code to add the data object to the top of the scope chain.
  1842. var variable = hasOwnProperty.call(options, 'variable') && options.variable;
  1843. if (!variable) {
  1844. source = 'with (obj) {\n' + source + '\n}\n';
  1845. }
  1846. // Throw an error if a forbidden character was found in `variable`, to prevent
  1847. // potential command injection attacks.
  1848. else if (reForbiddenIdentifierChars.test(variable)) {
  1849. throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
  1850. }
  1851. // Cleanup code by stripping empty strings.
  1852. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
  1853. .replace(reEmptyStringMiddle, '$1')
  1854. .replace(reEmptyStringTrailing, '$1;');
  1855. // Frame code as the function body.
  1856. source = 'function(' + (variable || 'obj') + ') {\n' +
  1857. (variable
  1858. ? ''
  1859. : 'obj || (obj = {});\n'
  1860. ) +
  1861. "var __t, __p = ''" +
  1862. (isEscaping
  1863. ? ', __e = _.escape'
  1864. : ''
  1865. ) +
  1866. (isEvaluating
  1867. ? ', __j = Array.prototype.join;\n' +
  1868. "function print() { __p += __j.call(arguments, '') }\n"
  1869. : ';\n'
  1870. ) +
  1871. source +
  1872. 'return __p\n}';
  1873. var result = attempt(function() {
  1874. return Function(importsKeys, sourceURL + 'return ' + source)
  1875. .apply(undefined, importsValues);
  1876. });
  1877. // Provide the compiled function's source by its `toString` method or
  1878. // the `source` property as a convenience for inlining compiled templates.
  1879. result.source = source;
  1880. if (isError(result)) {
  1881. throw result;
  1882. }
  1883. return result;
  1884. }
  1885. function toArray(value) {
  1886. return Array.isArray(value) ? value : [value];
  1887. }
  1888. function filterInPlace(array, predicate) {
  1889. for (let i = array.length; i--; i >= 0) {
  1890. if (!predicate(array[i], i, array)) {
  1891. array.splice(i, 1);
  1892. }
  1893. }
  1894. return array;
  1895. }
  1896. const MODE_RE = /\.(server|client)(\.\w+)*$/;
  1897. const distDirURL = new URL(".", import.meta.url);
  1898. async function compileTemplate(template$1, ctx) {
  1899. const data = { ...ctx, options: template$1.options };
  1900. if (template$1.src) {
  1901. try {
  1902. const srcContents = await promises.readFile(template$1.src, "utf-8");
  1903. return template(srcContents, {})(data);
  1904. } catch (err) {
  1905. logger.error("Error compiling template: ", template$1);
  1906. throw err;
  1907. }
  1908. }
  1909. if (template$1.getContents) {
  1910. return template$1.getContents(data);
  1911. }
  1912. throw new Error("Invalid template: " + JSON.stringify(template$1));
  1913. }
  1914. const serialize = (data) => JSON.stringify(data, null, 2).replace(/"\{(.+)\}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^\{(.*)\}$/, "$1"));
  1915. const importSources = (sources, { lazy = false } = {}) => {
  1916. return toArray(sources).map((src) => {
  1917. const safeVariableName = genSafeVariableName(src);
  1918. if (lazy) {
  1919. return `const ${safeVariableName} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
  1920. }
  1921. return genImport(src, safeVariableName);
  1922. }).join("\n");
  1923. };
  1924. const importName = genSafeVariableName;
  1925. const templateUtils = { serialize, importName, importSources };
  1926. function defineNuxtModule(definition) {
  1927. if (definition) {
  1928. return _defineNuxtModule(definition);
  1929. }
  1930. return {
  1931. with: (definition2) => _defineNuxtModule(definition2)
  1932. };
  1933. }
  1934. function _defineNuxtModule(definition) {
  1935. if (typeof definition === "function") {
  1936. return _defineNuxtModule({ setup: definition });
  1937. }
  1938. const module = defu(definition, { meta: {} });
  1939. module.meta.configKey ||= module.meta.name;
  1940. async function getOptions(inlineOptions, nuxt = useNuxt()) {
  1941. const nuxtConfigOptionsKey = module.meta.configKey || module.meta.name;
  1942. const nuxtConfigOptions = nuxtConfigOptionsKey && nuxtConfigOptionsKey in nuxt.options ? nuxt.options[nuxtConfigOptionsKey] : {};
  1943. const optionsDefaults = module.defaults instanceof Function ? await module.defaults(nuxt) : module.defaults ?? {};
  1944. let options = defu(inlineOptions, nuxtConfigOptions, optionsDefaults);
  1945. if (module.schema) {
  1946. options = await applyDefaults(module.schema, options);
  1947. }
  1948. return Promise.resolve(options);
  1949. }
  1950. async function normalizedModule(inlineOptions, nuxt) {
  1951. nuxt ||= tryUseNuxt() || this.nuxt;
  1952. const uniqueKey = module.meta.name || module.meta.configKey;
  1953. if (uniqueKey) {
  1954. nuxt.options._requiredModules ||= {};
  1955. if (nuxt.options._requiredModules[uniqueKey]) {
  1956. return false;
  1957. }
  1958. nuxt.options._requiredModules[uniqueKey] = true;
  1959. }
  1960. if (module.meta.compatibility) {
  1961. const issues = await checkNuxtCompatibility(module.meta.compatibility, nuxt);
  1962. if (issues.length) {
  1963. const errorMessage = `Module \`${module.meta.name}\` is disabled due to incompatibility issues:
  1964. ${issues.toString()}`;
  1965. if (nuxt.options.experimental.enforceModuleCompatibility) {
  1966. const error = new Error(errorMessage);
  1967. error.name = "ModuleCompatibilityError";
  1968. throw error;
  1969. }
  1970. logger.warn(errorMessage);
  1971. return;
  1972. }
  1973. }
  1974. nuxt2Shims(nuxt);
  1975. const _options = await getOptions(inlineOptions, nuxt);
  1976. if (module.hooks) {
  1977. nuxt.hooks.addHooks(module.hooks);
  1978. }
  1979. const start = performance.now();
  1980. const res = await module.setup?.call(null, _options, nuxt) ?? {};
  1981. const perf = performance.now() - start;
  1982. const setupTime = Math.round(perf * 100) / 100;
  1983. if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") {
  1984. logger.warn(`Slow module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
  1985. } else if (nuxt.options.debug && nuxt.options.debug.modules) {
  1986. logger.info(`Module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
  1987. }
  1988. if (res === false) {
  1989. return false;
  1990. }
  1991. return defu(res, {
  1992. timings: {
  1993. setup: setupTime
  1994. }
  1995. });
  1996. }
  1997. normalizedModule.getMeta = () => Promise.resolve(module.meta);
  1998. normalizedModule.getOptions = getOptions;
  1999. return normalizedModule;
  2000. }
  2001. const NUXT2_SHIMS_KEY = "__nuxt2_shims_key__";
  2002. function nuxt2Shims(nuxt) {
  2003. if (!isNuxt2(nuxt) || nuxt[NUXT2_SHIMS_KEY]) {
  2004. return;
  2005. }
  2006. nuxt[NUXT2_SHIMS_KEY] = true;
  2007. nuxt.hooks = nuxt;
  2008. if (!nuxtCtx.tryUse()) {
  2009. nuxtCtx.set(nuxt);
  2010. nuxt.hook("close", () => nuxtCtx.unset());
  2011. }
  2012. let virtualTemplates;
  2013. nuxt.hook("builder:prepared", (_builder, buildOptions) => {
  2014. virtualTemplates = buildOptions.templates.filter((t) => t.getContents);
  2015. for (const template of virtualTemplates) {
  2016. buildOptions.templates.splice(buildOptions.templates.indexOf(template), 1);
  2017. }
  2018. });
  2019. nuxt.hook("build:templates", async (templates) => {
  2020. const context = {
  2021. nuxt,
  2022. utils: templateUtils,
  2023. app: {
  2024. dir: nuxt.options.srcDir,
  2025. extensions: nuxt.options.extensions,
  2026. plugins: nuxt.options.plugins,
  2027. templates: [
  2028. ...templates.templatesFiles,
  2029. ...virtualTemplates
  2030. ],
  2031. templateVars: templates.templateVars
  2032. }
  2033. };
  2034. for await (const template of virtualTemplates) {
  2035. const contents = await compileTemplate({ ...template, src: "" }, context);
  2036. await promises.mkdir(dirname(template.dst), { recursive: true });
  2037. await promises.writeFile(template.dst, contents);
  2038. }
  2039. });
  2040. }
  2041. function directoryToURL(dir) {
  2042. return pathToFileURL(dir + "/");
  2043. }
  2044. function tryResolveModule(id, url = import.meta.url) {
  2045. return Promise.resolve(resolveModulePath(id, {
  2046. from: url,
  2047. suffixes: ["", "index"],
  2048. try: true
  2049. }));
  2050. }
  2051. function resolveModule(id, options) {
  2052. return resolveModulePath(id, {
  2053. from: options?.url ?? options?.paths ?? [import.meta.url],
  2054. extensions: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
  2055. });
  2056. }
  2057. async function importModule(id, opts) {
  2058. const resolvedPath = resolveModule(id, opts);
  2059. return await import(pathToFileURL(resolvedPath).href).then((r) => opts?.interopDefault !== false ? interopDefault(r) : r);
  2060. }
  2061. function tryImportModule(id, opts) {
  2062. try {
  2063. return importModule(id, opts).catch(() => void 0);
  2064. } catch {
  2065. }
  2066. }
  2067. const warnings = /* @__PURE__ */ new Set();
  2068. function requireModule(id, opts) {
  2069. if (!warnings.has(id)) {
  2070. console.warn("[@nuxt/kit] `requireModule` is deprecated. Please use `importModule` instead.");
  2071. warnings.add(id);
  2072. }
  2073. const resolvedPath = resolveModule(id, opts);
  2074. const jiti = createJiti(import.meta.url, {
  2075. interopDefault: opts?.interopDefault !== false
  2076. });
  2077. return jiti(pathToFileURL(resolvedPath).href);
  2078. }
  2079. function tryRequireModule(id, opts) {
  2080. try {
  2081. return requireModule(id, opts);
  2082. } catch {
  2083. }
  2084. }
  2085. function createIsIgnored(nuxt = tryUseNuxt()) {
  2086. return (pathname, stats) => isIgnored(pathname, stats, nuxt);
  2087. }
  2088. function isIgnored(pathname, _stats, nuxt = tryUseNuxt()) {
  2089. if (!nuxt) {
  2090. return false;
  2091. }
  2092. if (!nuxt._ignore) {
  2093. nuxt._ignore = ignore(nuxt.options.ignoreOptions);
  2094. nuxt._ignore.add(resolveIgnorePatterns());
  2095. }
  2096. const cwds = nuxt.options._layers?.map((layer2) => layer2.cwd).sort((a, b) => b.length - a.length);
  2097. const layer = cwds?.find((cwd) => pathname.startsWith(cwd));
  2098. const relativePath = relative(layer ?? nuxt.options.rootDir, pathname);
  2099. if (relativePath[0] === "." && relativePath[1] === ".") {
  2100. return false;
  2101. }
  2102. return !!(relativePath && nuxt._ignore.ignores(relativePath));
  2103. }
  2104. const NEGATION_RE = /^(!?)(.*)$/;
  2105. function resolveIgnorePatterns(relativePath) {
  2106. const nuxt = tryUseNuxt();
  2107. if (!nuxt) {
  2108. return [];
  2109. }
  2110. const ignorePatterns = nuxt.options.ignore.flatMap((s) => resolveGroupSyntax(s));
  2111. const nuxtignoreFile = join(nuxt.options.rootDir, ".nuxtignore");
  2112. if (existsSync(nuxtignoreFile)) {
  2113. const contents = readFileSync(nuxtignoreFile, "utf-8");
  2114. ignorePatterns.push(...contents.trim().split(/\r?\n/));
  2115. }
  2116. if (relativePath) {
  2117. return ignorePatterns.map((p) => {
  2118. const [_, negation = "", pattern] = p.match(NEGATION_RE) || [];
  2119. if (pattern && pattern[0] === "*") {
  2120. return p;
  2121. }
  2122. return negation + relative(relativePath, resolve(nuxt.options.rootDir, pattern || p));
  2123. });
  2124. }
  2125. return ignorePatterns;
  2126. }
  2127. function resolveGroupSyntax(group) {
  2128. let groups = [group];
  2129. while (groups.some((group2) => group2.includes("{"))) {
  2130. groups = groups.flatMap((group2) => {
  2131. const [head, ...tail] = group2.split("{");
  2132. if (tail.length) {
  2133. const [body = "", ...rest] = tail.join("{").split("}");
  2134. return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
  2135. }
  2136. return group2;
  2137. });
  2138. }
  2139. return groups;
  2140. }
  2141. async function resolvePath(path, opts = {}) {
  2142. const res = await _resolvePathGranularly(path, opts);
  2143. if (res.type === "file") {
  2144. return res.path;
  2145. }
  2146. return opts.fallbackToOriginal ? path : res.path;
  2147. }
  2148. async function findPath(paths, opts, pathType = "file") {
  2149. for (const path of toArray(paths)) {
  2150. const res = await _resolvePathGranularly(path, opts);
  2151. if (!res.type || pathType && res.type !== pathType) {
  2152. continue;
  2153. }
  2154. if (res.virtual || await existsSensitive(res.path)) {
  2155. return res.path;
  2156. }
  2157. }
  2158. return null;
  2159. }
  2160. function resolveAlias(path, alias) {
  2161. alias ||= tryUseNuxt()?.options.alias || {};
  2162. return resolveAlias$1(path, alias);
  2163. }
  2164. function createResolver(base) {
  2165. if (!base) {
  2166. throw new Error("`base` argument is missing for createResolver(base)!");
  2167. }
  2168. base = base.toString();
  2169. if (base.startsWith("file://")) {
  2170. base = dirname(fileURLToPath(base));
  2171. }
  2172. return {
  2173. resolve: (...path) => resolve(base, ...path),
  2174. resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
  2175. };
  2176. }
  2177. async function resolveNuxtModule(base, paths) {
  2178. const resolved = [];
  2179. const resolver = createResolver(base);
  2180. for (const path of paths) {
  2181. if (path.startsWith(base)) {
  2182. resolved.push(path.split("/index.ts")[0]);
  2183. } else {
  2184. const resolvedPath = await resolver.resolvePath(path);
  2185. resolved.push(resolvedPath.slice(0, resolvedPath.lastIndexOf(path) + path.length));
  2186. }
  2187. }
  2188. return resolved;
  2189. }
  2190. async function _resolvePathType(path, opts = {}, skipFs = false) {
  2191. if (opts?.virtual && existsInVFS(path)) {
  2192. return {
  2193. path,
  2194. type: "file",
  2195. virtual: true
  2196. };
  2197. }
  2198. if (skipFs) {
  2199. return;
  2200. }
  2201. const fd = await promises.open(path, "r").catch(() => null);
  2202. try {
  2203. const stats = await fd?.stat();
  2204. if (stats) {
  2205. return {
  2206. path,
  2207. type: stats.isFile() ? "file" : "dir",
  2208. virtual: false
  2209. };
  2210. }
  2211. } finally {
  2212. fd?.close();
  2213. }
  2214. }
  2215. async function _resolvePathGranularly(path, opts = {}) {
  2216. const _path = path;
  2217. path = normalize(path);
  2218. if (isAbsolute(path)) {
  2219. const res2 = await _resolvePathType(path, opts);
  2220. if (res2 && res2.type === "file") {
  2221. return res2;
  2222. }
  2223. }
  2224. const nuxt = tryUseNuxt();
  2225. const cwd = opts.cwd || (nuxt ? nuxt.options.rootDir : process.cwd());
  2226. const extensions = opts.extensions || (nuxt ? nuxt.options.extensions : [".ts", ".mjs", ".cjs", ".json"]);
  2227. const modulesDir = nuxt ? nuxt.options.modulesDir : [];
  2228. path = resolveAlias$1(path, opts.alias ?? nuxt?.options.alias ?? {});
  2229. if (!isAbsolute(path)) {
  2230. path = resolve(cwd, path);
  2231. }
  2232. const res = await _resolvePathType(path, opts);
  2233. if (res && res.type === "file") {
  2234. return res;
  2235. }
  2236. for (const ext of extensions) {
  2237. const extPath = await _resolvePathType(path + ext, opts);
  2238. if (extPath && extPath.type === "file") {
  2239. return extPath;
  2240. }
  2241. const indexPath = await _resolvePathType(
  2242. join(path, "index" + ext),
  2243. opts,
  2244. res?.type !== "dir"
  2245. /* skip checking if parent is not a directory */
  2246. );
  2247. if (indexPath && indexPath.type === "file") {
  2248. return indexPath;
  2249. }
  2250. }
  2251. const resolvedModulePath = resolveModulePath(_path, {
  2252. try: true,
  2253. suffixes: ["", "index"],
  2254. from: [cwd, ...modulesDir].map((d) => directoryToURL(d))
  2255. });
  2256. if (resolvedModulePath) {
  2257. return {
  2258. path: resolvedModulePath,
  2259. type: "file",
  2260. virtual: false
  2261. };
  2262. }
  2263. return {
  2264. path
  2265. };
  2266. }
  2267. async function existsSensitive(path) {
  2268. const dirFiles = new Set(await promises.readdir(dirname(path)).catch(() => []));
  2269. return dirFiles.has(basename(path));
  2270. }
  2271. function existsInVFS(path, nuxt = tryUseNuxt()) {
  2272. if (!nuxt) {
  2273. return false;
  2274. }
  2275. if (path in nuxt.vfs) {
  2276. return true;
  2277. }
  2278. const templates = nuxt.apps.default?.templates ?? nuxt.options.build.templates;
  2279. return templates.some((template) => template.dst === path);
  2280. }
  2281. async function resolveFiles(path, pattern, opts = {}) {
  2282. const files = [];
  2283. for (const file of await glob(pattern, { cwd: path, followSymbolicLinks: opts.followSymbolicLinks ?? true })) {
  2284. const p = resolve(path, file);
  2285. if (!isIgnored(p)) {
  2286. files.push(p);
  2287. }
  2288. }
  2289. return files.sort();
  2290. }
  2291. const NODE_MODULES_RE = /[/\\]node_modules[/\\]/;
  2292. async function installModule(moduleToInstall, inlineOptions, nuxt = useNuxt()) {
  2293. const { nuxtModule, buildTimeModuleMeta, resolvedModulePath } = await loadNuxtModuleInstance(moduleToInstall, nuxt);
  2294. const localLayerModuleDirs = [];
  2295. for (const l of nuxt.options._layers) {
  2296. const srcDir = l.config.srcDir || l.cwd;
  2297. if (!NODE_MODULES_RE.test(srcDir)) {
  2298. localLayerModuleDirs.push(resolve(srcDir, l.config?.dir?.modules || "modules").replace(/\/?$/, "/"));
  2299. }
  2300. }
  2301. const res = (isNuxt2() ? await nuxtModule.call(nuxt.moduleContainer, inlineOptions, nuxt) : nuxt.options.experimental?.debugModuleMutation && nuxt._asyncLocalStorageModule ? await nuxt._asyncLocalStorageModule.run(nuxtModule, () => nuxtModule(inlineOptions || {}, nuxt)) : await nuxtModule(inlineOptions || {}, nuxt)) ?? {};
  2302. if (res === false) {
  2303. return;
  2304. }
  2305. const modulePath = resolvedModulePath || moduleToInstall;
  2306. if (typeof modulePath === "string") {
  2307. const parsed = parseNodeModulePath(modulePath);
  2308. const moduleRoot = parsed.dir ? parsed.dir + parsed.name : await resolvePackageJSON(modulePath, { try: true }).then((r) => r ? dirname(r) : modulePath);
  2309. nuxt.options.build.transpile.push(normalizeModuleTranspilePath(moduleRoot));
  2310. const directory = moduleRoot.replace(/\/?$/, "/");
  2311. if (moduleRoot !== moduleToInstall && !localLayerModuleDirs.some((dir) => directory.startsWith(dir))) {
  2312. nuxt.options.modulesDir.push(join(moduleRoot, "node_modules"));
  2313. }
  2314. }
  2315. nuxt.options._installedModules ||= [];
  2316. const entryPath = typeof moduleToInstall === "string" ? resolveAlias(moduleToInstall) : void 0;
  2317. if (typeof moduleToInstall === "string" && entryPath !== moduleToInstall) {
  2318. buildTimeModuleMeta.rawPath = moduleToInstall;
  2319. }
  2320. nuxt.options._installedModules.push({
  2321. meta: defu(await nuxtModule.getMeta?.(), buildTimeModuleMeta),
  2322. module: nuxtModule,
  2323. timings: res.timings,
  2324. entryPath
  2325. });
  2326. }
  2327. function getDirectory(p) {
  2328. try {
  2329. return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
  2330. } catch {
  2331. }
  2332. return p;
  2333. }
  2334. const normalizeModuleTranspilePath = (p) => {
  2335. return getDirectory(p).split("node_modules/").pop();
  2336. };
  2337. const MissingModuleMatcher = /Cannot find module\s+['"]?([^'")\s]+)['"]?/i;
  2338. async function loadNuxtModuleInstance(nuxtModule, nuxt = useNuxt()) {
  2339. let buildTimeModuleMeta = {};
  2340. if (typeof nuxtModule === "function") {
  2341. return {
  2342. nuxtModule,
  2343. buildTimeModuleMeta
  2344. };
  2345. }
  2346. if (typeof nuxtModule !== "string") {
  2347. throw new TypeError(`Nuxt module should be a function or a string to import. Received: ${nuxtModule}.`);
  2348. }
  2349. const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
  2350. nuxtModule = resolveAlias(nuxtModule, nuxt.options.alias);
  2351. if (isRelative(nuxtModule)) {
  2352. nuxtModule = resolve(nuxt.options.rootDir, nuxtModule);
  2353. }
  2354. try {
  2355. const src = resolveModuleURL(nuxtModule, {
  2356. from: nuxt.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
  2357. suffixes: ["nuxt", "nuxt/index", "module", "module/index", "", "index"],
  2358. extensions: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
  2359. });
  2360. const resolvedModulePath = fileURLToPath(src);
  2361. const resolvedNuxtModule = await jiti.import(src, { default: true });
  2362. if (typeof resolvedNuxtModule !== "function") {
  2363. throw new TypeError(`Nuxt module should be a function: ${nuxtModule}.`);
  2364. }
  2365. const moduleMetadataPath = new URL("module.json", src);
  2366. if (existsSync(moduleMetadataPath)) {
  2367. buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
  2368. }
  2369. return { nuxtModule: resolvedNuxtModule, buildTimeModuleMeta, resolvedModulePath };
  2370. } catch (error) {
  2371. const code = error.code;
  2372. if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
  2373. throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
  2374. }
  2375. if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
  2376. const module = MissingModuleMatcher.exec(error.message)?.[1];
  2377. if (module && !module.includes(nuxtModule)) {
  2378. throw new TypeError(`Error while importing module \`${nuxtModule}\`: ${error}`);
  2379. }
  2380. }
  2381. }
  2382. throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
  2383. }
  2384. function resolveNuxtModuleEntryName(m) {
  2385. if (typeof m === "object" && !Array.isArray(m)) {
  2386. return m.name;
  2387. }
  2388. if (Array.isArray(m)) {
  2389. return resolveNuxtModuleEntryName(m[0]);
  2390. }
  2391. return m || false;
  2392. }
  2393. function hasNuxtModule(moduleName, nuxt = useNuxt()) {
  2394. return nuxt.options._installedModules.some(({ meta }) => meta.name === moduleName) || // check modules to be installed
  2395. nuxt.options.modules.some((m) => moduleName === resolveNuxtModuleEntryName(m));
  2396. }
  2397. async function hasNuxtModuleCompatibility(module, semverVersion, nuxt = useNuxt()) {
  2398. const version = await getNuxtModuleVersion(module, nuxt);
  2399. if (!version) {
  2400. return false;
  2401. }
  2402. return satisfies(normalizeSemanticVersion(version), semverVersion, {
  2403. includePrerelease: true
  2404. });
  2405. }
  2406. async function getNuxtModuleVersion(module, nuxt = useNuxt()) {
  2407. const moduleMeta = (typeof module === "string" ? { name: module } : await module.getMeta?.()) || {};
  2408. if (moduleMeta.version) {
  2409. return moduleMeta.version;
  2410. }
  2411. if (!moduleMeta.name) {
  2412. return false;
  2413. }
  2414. for (const m of nuxt.options._installedModules) {
  2415. if (m.meta.name === moduleMeta.name && m.meta.version) {
  2416. return m.meta.version;
  2417. }
  2418. }
  2419. if (hasNuxtModule(moduleMeta.name)) {
  2420. const { nuxtModule, buildTimeModuleMeta } = await loadNuxtModuleInstance(moduleMeta.name, nuxt);
  2421. return buildTimeModuleMeta.version || await nuxtModule.getMeta?.().then((r) => r.version) || false;
  2422. }
  2423. return false;
  2424. }
  2425. async function loadNuxtConfig(opts) {
  2426. const localLayers = (await glob("layers/*", { onlyDirectories: true, cwd: opts.cwd || process.cwd() })).map((d) => d.endsWith("/") ? d.substring(0, d.length - 1) : d);
  2427. opts.overrides = defu$1(opts.overrides, { _extends: localLayers });
  2428. globalThis.defineNuxtConfig = (c) => c;
  2429. const { configFile, layers = [], cwd, config: nuxtConfig, meta } = await loadConfig({
  2430. name: "nuxt",
  2431. configFile: "nuxt.config",
  2432. rcFile: ".nuxtrc",
  2433. extend: { extendKey: ["theme", "extends", "_extends"] },
  2434. dotenv: true,
  2435. globalRc: true,
  2436. ...opts
  2437. });
  2438. delete globalThis.defineNuxtConfig;
  2439. nuxtConfig.rootDir ||= cwd;
  2440. nuxtConfig._nuxtConfigFile = configFile;
  2441. nuxtConfig._nuxtConfigFiles = [configFile];
  2442. nuxtConfig._loadOptions = opts;
  2443. nuxtConfig.alias ||= {};
  2444. if (meta?.name) {
  2445. const alias = `#layers/${meta.name}`;
  2446. nuxtConfig.alias[alias] ||= nuxtConfig.rootDir;
  2447. }
  2448. const defaultBuildDir = join(nuxtConfig.rootDir, ".nuxt");
  2449. if (!opts.overrides?._prepare && !nuxtConfig.dev && !nuxtConfig.buildDir && nuxtConfig.future?.compatibilityVersion === 4 && existsSync(defaultBuildDir)) {
  2450. nuxtConfig.buildDir = join(nuxtConfig.rootDir, "node_modules/.cache/nuxt/.nuxt");
  2451. }
  2452. const NuxtConfigSchema = await loadNuxtSchema(nuxtConfig.rootDir || cwd || process.cwd());
  2453. const layerSchemaKeys = ["future", "srcDir", "rootDir", "serverDir", "dir"];
  2454. const layerSchema = /* @__PURE__ */ Object.create(null);
  2455. for (const key of layerSchemaKeys) {
  2456. if (key in NuxtConfigSchema) {
  2457. layerSchema[key] = NuxtConfigSchema[key];
  2458. }
  2459. }
  2460. const _layers = [];
  2461. const processedLayers = /* @__PURE__ */ new Set();
  2462. const localRelativePaths = new Set(localLayers);
  2463. for (const layer of layers) {
  2464. layer.config ||= {};
  2465. layer.config.rootDir ??= layer.cwd;
  2466. if (processedLayers.has(layer.config.rootDir)) {
  2467. continue;
  2468. }
  2469. processedLayers.add(layer.config.rootDir);
  2470. layer.config = await applyDefaults(layerSchema, layer.config);
  2471. if (!layer.configFile || layer.configFile.endsWith(".nuxtrc")) {
  2472. continue;
  2473. }
  2474. if (layer.cwd && cwd && localRelativePaths.has(relative(cwd, layer.cwd))) {
  2475. layer.meta ||= {};
  2476. layer.meta.name ||= basename(layer.cwd);
  2477. }
  2478. if (layer.meta?.name) {
  2479. const alias = `#layers/${layer.meta.name}`;
  2480. nuxtConfig.alias[alias] ||= layer.config.rootDir || layer.cwd;
  2481. }
  2482. _layers.push(layer);
  2483. }
  2484. nuxtConfig._layers = _layers;
  2485. if (!_layers.length) {
  2486. _layers.push({
  2487. cwd,
  2488. config: {
  2489. rootDir: cwd,
  2490. srcDir: cwd
  2491. }
  2492. });
  2493. }
  2494. return await applyDefaults(NuxtConfigSchema, nuxtConfig);
  2495. }
  2496. async function loadNuxtSchema(cwd) {
  2497. const url = directoryToURL(cwd);
  2498. const urls = [url];
  2499. const nuxtPath = resolveModuleURL("nuxt", { try: true, from: url }) ?? resolveModuleURL("nuxt-nightly", { try: true, from: url });
  2500. if (nuxtPath) {
  2501. urls.unshift(pathToFileURL(nuxtPath));
  2502. }
  2503. const schemaPath = resolveModuleURL("@nuxt/schema", { try: true, from: urls }) ?? "@nuxt/schema";
  2504. return await import(schemaPath).then((r) => r.NuxtConfigSchema);
  2505. }
  2506. function extendNuxtSchema(def) {
  2507. const nuxt = useNuxt();
  2508. nuxt.hook("schema:extend", (schemas) => {
  2509. schemas.push(typeof def === "function" ? def() : def);
  2510. });
  2511. }
  2512. async function loadNuxt(opts) {
  2513. opts.cwd ||= opts.rootDir;
  2514. opts.overrides ||= opts.config || {};
  2515. opts.overrides.dev = !!opts.dev;
  2516. const resolvedPath = ["nuxt-nightly", "nuxt3", "nuxt", "nuxt-edge"].map((pkg2) => resolveModulePath(pkg2, { try: true, from: [directoryToURL(opts.cwd)] })).filter((p) => !!p).sort((a, b) => b.length - a.length)[0];
  2517. if (!resolvedPath) {
  2518. throw new Error(`Cannot find any nuxt version from ${opts.cwd}`);
  2519. }
  2520. const pkg = await readPackageJSON(resolvedPath);
  2521. const majorVersion = pkg.version ? Number.parseInt(pkg.version.split(".")[0]) : "";
  2522. if (majorVersion && majorVersion >= 3) {
  2523. const { loadNuxt: loadNuxt3 } = await import(pathToFileURL(resolvedPath).href).then((r) => interopDefault(r));
  2524. const nuxt2 = await loadNuxt3(opts);
  2525. return nuxt2;
  2526. }
  2527. const rootURL = directoryToURL(opts.cwd);
  2528. const { loadNuxt: loadNuxt2 } = await tryImportModule("nuxt-edge", { url: rootURL }) || await importModule("nuxt", { url: rootURL });
  2529. const nuxt = await loadNuxt2({
  2530. rootDir: opts.cwd,
  2531. for: opts.dev ? "dev" : "build",
  2532. configOverrides: opts.overrides,
  2533. ready: opts.ready,
  2534. envConfig: opts.dotenv
  2535. // TODO: Backward format conversion
  2536. });
  2537. nuxt.removeHook ||= nuxt.clearHook.bind(nuxt);
  2538. nuxt.removeAllHooks ||= nuxt.clearHooks.bind(nuxt);
  2539. nuxt.hookOnce ||= (name, fn, ...hookArgs) => {
  2540. const unsub = nuxt.hook(name, (...args) => {
  2541. unsub();
  2542. return fn(...args);
  2543. }, ...hookArgs);
  2544. return unsub;
  2545. };
  2546. nuxt.hooks ||= nuxt;
  2547. return nuxt;
  2548. }
  2549. async function buildNuxt(nuxt) {
  2550. const rootURL = directoryToURL(nuxt.options.rootDir);
  2551. if (nuxt.options._majorVersion === 3) {
  2552. const { build: build2 } = await tryImportModule("nuxt-nightly", { url: rootURL }) || await tryImportModule("nuxt3", { url: rootURL }) || await importModule("nuxt", { url: rootURL });
  2553. return runWithNuxtContext(nuxt, () => build2(nuxt));
  2554. }
  2555. const { build } = await tryImportModule("nuxt-edge", { url: rootURL }) || await importModule("nuxt", { url: rootURL });
  2556. return runWithNuxtContext(nuxt, () => build(nuxt));
  2557. }
  2558. function addImports(imports) {
  2559. assertNuxtCompatibility({ bridge: true });
  2560. useNuxt().hook("imports:extend", (_imports) => {
  2561. _imports.push(...toArray(imports));
  2562. });
  2563. }
  2564. function addImportsDir(dirs, opts = {}) {
  2565. assertNuxtCompatibility({ bridge: true });
  2566. useNuxt().hook("imports:dirs", (_dirs) => {
  2567. for (const dir of toArray(dirs)) {
  2568. _dirs[opts.prepend ? "unshift" : "push"](dir);
  2569. }
  2570. });
  2571. }
  2572. function addImportsSources(presets) {
  2573. assertNuxtCompatibility({ bridge: true });
  2574. useNuxt().hook("imports:sources", (_presets) => {
  2575. for (const preset of toArray(presets)) {
  2576. _presets.push(preset);
  2577. }
  2578. });
  2579. }
  2580. const HANDLER_METHOD_RE = /\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/;
  2581. function normalizeHandlerMethod(handler) {
  2582. const [, method = void 0] = handler.handler.match(HANDLER_METHOD_RE) || [];
  2583. return {
  2584. method,
  2585. ...handler,
  2586. handler: normalize(handler.handler)
  2587. };
  2588. }
  2589. function addServerHandler(handler) {
  2590. useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
  2591. }
  2592. function addDevServerHandler(handler) {
  2593. useNuxt().options.devServerHandlers.push(handler);
  2594. }
  2595. function addServerPlugin(plugin) {
  2596. const nuxt = useNuxt();
  2597. nuxt.options.nitro.plugins ||= [];
  2598. nuxt.options.nitro.plugins.push(normalize(plugin));
  2599. }
  2600. function addPrerenderRoutes(routes) {
  2601. const nuxt = useNuxt();
  2602. routes = toArray(routes).filter(Boolean);
  2603. if (!routes.length) {
  2604. return;
  2605. }
  2606. nuxt.hook("prerender:routes", (ctx) => {
  2607. for (const route of routes) {
  2608. ctx.routes.add(route);
  2609. }
  2610. });
  2611. }
  2612. function useNitro() {
  2613. const nuxt = useNuxt();
  2614. if (!nuxt._nitro) {
  2615. throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
  2616. }
  2617. return nuxt._nitro;
  2618. }
  2619. function addServerImports(imports) {
  2620. const nuxt = useNuxt();
  2621. nuxt.hook("nitro:config", (config) => {
  2622. config.imports ||= {};
  2623. config.imports.imports ||= [];
  2624. config.imports.imports.push(...imports);
  2625. });
  2626. }
  2627. function addServerImportsDir(dirs, opts = {}) {
  2628. const nuxt = useNuxt();
  2629. const _dirs = toArray(dirs);
  2630. nuxt.hook("nitro:config", (config) => {
  2631. config.imports ||= {};
  2632. config.imports.dirs ||= [];
  2633. config.imports.dirs[opts.prepend ? "unshift" : "push"](..._dirs);
  2634. });
  2635. }
  2636. function addServerScanDir(dirs, opts = {}) {
  2637. const nuxt = useNuxt();
  2638. nuxt.hook("nitro:config", (config) => {
  2639. config.scanDirs ||= [];
  2640. for (const dir of toArray(dirs)) {
  2641. config.scanDirs[opts.prepend ? "unshift" : "push"](dir);
  2642. }
  2643. });
  2644. }
  2645. function useRuntimeConfig() {
  2646. const nuxt = useNuxt();
  2647. return applyEnv(klona(nuxt.options.nitro.runtimeConfig), {
  2648. prefix: "NITRO_",
  2649. altPrefix: "NUXT_",
  2650. envExpansion: nuxt.options.nitro.experimental?.envExpansion ?? !!process$1.env.NITRO_ENV_EXPANSION
  2651. });
  2652. }
  2653. function updateRuntimeConfig(runtimeConfig) {
  2654. const nuxt = useNuxt();
  2655. Object.assign(nuxt.options.nitro.runtimeConfig, defu$1(runtimeConfig, nuxt.options.nitro.runtimeConfig));
  2656. try {
  2657. return useNitro().updateConfig({ runtimeConfig });
  2658. } catch {
  2659. }
  2660. }
  2661. function getEnv(key, opts, env = process$1.env) {
  2662. const envKey = snakeCase(key).toUpperCase();
  2663. return destr(
  2664. env[opts.prefix + envKey] ?? env[opts.altPrefix + envKey]
  2665. );
  2666. }
  2667. function _isObject(input) {
  2668. return typeof input === "object" && !Array.isArray(input);
  2669. }
  2670. function applyEnv(obj, opts, parentKey = "") {
  2671. for (const key in obj) {
  2672. const subKey = parentKey ? `${parentKey}_${key}` : key;
  2673. const envValue = getEnv(subKey, opts);
  2674. if (_isObject(obj[key])) {
  2675. if (_isObject(envValue)) {
  2676. obj[key] = { ...obj[key], ...envValue };
  2677. applyEnv(obj[key], opts, subKey);
  2678. } else if (envValue === void 0) {
  2679. applyEnv(obj[key], opts, subKey);
  2680. } else {
  2681. obj[key] = envValue ?? obj[key];
  2682. }
  2683. } else {
  2684. obj[key] = envValue ?? obj[key];
  2685. }
  2686. if (opts.envExpansion && typeof obj[key] === "string") {
  2687. obj[key] = _expandFromEnv(obj[key]);
  2688. }
  2689. }
  2690. return obj;
  2691. }
  2692. const envExpandRx = /\{\{(.*?)\}\}/g;
  2693. function _expandFromEnv(value, env = process$1.env) {
  2694. return value.replace(envExpandRx, (match, key) => {
  2695. return env[key] || match;
  2696. });
  2697. }
  2698. const extendWebpackCompatibleConfig = (builder) => (fn, options = {}) => {
  2699. const nuxt = useNuxt();
  2700. if (options.dev === false && nuxt.options.dev) {
  2701. return;
  2702. }
  2703. if (options.build === false && nuxt.options.build) {
  2704. return;
  2705. }
  2706. nuxt.hook(`${builder}:config`, (configs) => {
  2707. if (options.server !== false) {
  2708. const config = configs.find((i) => i.name === "server");
  2709. if (config) {
  2710. fn(config);
  2711. }
  2712. }
  2713. if (options.client !== false) {
  2714. const config = configs.find((i) => i.name === "client");
  2715. if (config) {
  2716. fn(config);
  2717. }
  2718. }
  2719. });
  2720. };
  2721. const extendWebpackConfig = extendWebpackCompatibleConfig("webpack");
  2722. const extendRspackConfig = extendWebpackCompatibleConfig("rspack");
  2723. function extendViteConfig(fn, options = {}) {
  2724. const nuxt = useNuxt();
  2725. if (options.dev === false && nuxt.options.dev) {
  2726. return;
  2727. }
  2728. if (options.build === false && nuxt.options.build) {
  2729. return;
  2730. }
  2731. if (options.server !== false && options.client !== false) {
  2732. return nuxt.hook("vite:extend", ({ config }) => fn(config));
  2733. }
  2734. nuxt.hook("vite:extendConfig", (config, { isClient, isServer }) => {
  2735. if (options.server !== false && isServer) {
  2736. return fn(config);
  2737. }
  2738. if (options.client !== false && isClient) {
  2739. return fn(config);
  2740. }
  2741. });
  2742. }
  2743. function addWebpackPlugin(pluginOrGetter, options) {
  2744. extendWebpackConfig((config) => {
  2745. const method = options?.prepend ? "unshift" : "push";
  2746. const plugin = typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter;
  2747. config.plugins ||= [];
  2748. config.plugins[method](...toArray(plugin));
  2749. }, options);
  2750. }
  2751. function addRspackPlugin(pluginOrGetter, options) {
  2752. extendRspackConfig((config) => {
  2753. const method = options?.prepend ? "unshift" : "push";
  2754. const plugin = typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter;
  2755. config.plugins ||= [];
  2756. config.plugins[method](...toArray(plugin));
  2757. }, options);
  2758. }
  2759. function addVitePlugin(pluginOrGetter, options) {
  2760. extendViteConfig((config) => {
  2761. const method = options?.prepend ? "unshift" : "push";
  2762. const plugin = typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter;
  2763. config.plugins ||= [];
  2764. config.plugins[method](...toArray(plugin));
  2765. }, options);
  2766. }
  2767. function addBuildPlugin(pluginFactory, options) {
  2768. if (pluginFactory.vite) {
  2769. addVitePlugin(pluginFactory.vite, options);
  2770. }
  2771. if (pluginFactory.webpack) {
  2772. addWebpackPlugin(pluginFactory.webpack, options);
  2773. }
  2774. if (pluginFactory.rspack) {
  2775. addRspackPlugin(pluginFactory.rspack, options);
  2776. }
  2777. }
  2778. function addComponentsDir(dir, opts = {}) {
  2779. const nuxt = useNuxt();
  2780. if (!checkNuxtVersion(">=2.13", nuxt)) {
  2781. throw new Error(`\`addComponentsDir\` requires Nuxt 2.13 or higher.`);
  2782. }
  2783. nuxt.options.components ||= [];
  2784. dir.priority ||= 0;
  2785. nuxt.hook("components:dirs", (dirs) => {
  2786. dirs[opts.prepend ? "unshift" : "push"](dir);
  2787. });
  2788. }
  2789. function addComponentExports(opts) {
  2790. const nuxt = useNuxt();
  2791. const components = [];
  2792. nuxt.hook("components:dirs", async () => {
  2793. const filePath = await resolvePath(opts.filePath);
  2794. const names = await resolveModuleExportNames(filePath, { extensions: nuxt.options.extensions });
  2795. components.length = 0;
  2796. for (const name of names) {
  2797. components.push(normalizeComponent({ name: pascalCase([opts.prefix || "", name === "default" ? "" : name]), export: name, ...opts }));
  2798. }
  2799. });
  2800. addComponents(components);
  2801. }
  2802. function addComponent(opts) {
  2803. const component = normalizeComponent(opts);
  2804. addComponents([component]);
  2805. }
  2806. function addComponents(addedComponents) {
  2807. const nuxt = useNuxt();
  2808. if (!checkNuxtVersion(">=2.13", nuxt)) {
  2809. throw new Error(`\`addComponent\` requires Nuxt 2.13 or higher.`);
  2810. }
  2811. nuxt.options.components ||= [];
  2812. nuxt.hook("components:extend", (components) => {
  2813. for (const component of addedComponents) {
  2814. const existingComponentIndex = components.findIndex((c) => (c.pascalName === component.pascalName || c.kebabName === component.kebabName) && c.mode === component.mode);
  2815. if (existingComponentIndex !== -1) {
  2816. const existingComponent = components[existingComponentIndex];
  2817. const existingPriority = existingComponent.priority ?? 0;
  2818. const newPriority = component.priority ?? 0;
  2819. if (newPriority < existingPriority) {
  2820. return;
  2821. }
  2822. if (newPriority === existingPriority) {
  2823. const name = existingComponent.pascalName || existingComponent.kebabName;
  2824. logger.warn(`Overriding ${name} component. You can specify a \`priority\` option when calling \`addComponent\` to avoid this warning.`);
  2825. }
  2826. components.splice(existingComponentIndex, 1, component);
  2827. } else {
  2828. components.push(component);
  2829. }
  2830. }
  2831. });
  2832. }
  2833. function normalizeComponent(opts) {
  2834. if (!opts.mode) {
  2835. const [, mode = "all"] = opts.filePath.match(MODE_RE) || [];
  2836. opts.mode = mode;
  2837. }
  2838. const component = {
  2839. export: opts.export || "default",
  2840. chunkName: "components/" + kebabCase(opts.name),
  2841. global: opts.global ?? false,
  2842. kebabName: kebabCase(opts.name || ""),
  2843. pascalName: pascalCase(opts.name || ""),
  2844. prefetch: false,
  2845. preload: false,
  2846. mode: "all",
  2847. shortPath: opts.filePath,
  2848. priority: 0,
  2849. meta: {},
  2850. ...opts
  2851. };
  2852. return component;
  2853. }
  2854. function addTemplate(_template) {
  2855. const nuxt = useNuxt();
  2856. const template = normalizeTemplate(_template);
  2857. filterInPlace(nuxt.options.build.templates, (p) => normalizeTemplate(p).dst !== template.dst);
  2858. try {
  2859. const distDir = distDirURL.toString();
  2860. const { source } = captureStackTrace().find((e) => e.source && !e.source.startsWith(distDir)) ?? {};
  2861. if (source) {
  2862. const path = normalize(fileURLToPath(source));
  2863. if (existsSync(path)) {
  2864. template._path = path;
  2865. }
  2866. }
  2867. } catch {
  2868. }
  2869. nuxt.options.build.templates.push(template);
  2870. return template;
  2871. }
  2872. function addServerTemplate(template) {
  2873. const nuxt = useNuxt();
  2874. nuxt.options.nitro.virtual ||= {};
  2875. nuxt.options.nitro.virtual[template.filename] = template.getContents;
  2876. return template;
  2877. }
  2878. function addTypeTemplate(_template, context) {
  2879. const nuxt = useNuxt();
  2880. const template = addTemplate(_template);
  2881. if (!template.filename.endsWith(".d.ts")) {
  2882. throw new Error(`Invalid type template. Filename must end with .d.ts : "${template.filename}"`);
  2883. }
  2884. if (!context || context.nuxt) {
  2885. nuxt.hook("prepare:types", ({ references }) => {
  2886. references.push({ path: template.dst });
  2887. });
  2888. }
  2889. if (context?.nitro) {
  2890. nuxt.hook("nitro:prepare:types", ({ references }) => {
  2891. references.push({ path: template.dst });
  2892. });
  2893. }
  2894. return template;
  2895. }
  2896. function normalizeTemplate(template, buildDir) {
  2897. if (!template) {
  2898. throw new Error("Invalid template: " + JSON.stringify(template));
  2899. }
  2900. if (typeof template === "string") {
  2901. template = { src: template };
  2902. } else {
  2903. template = { ...template };
  2904. }
  2905. if (template.src) {
  2906. if (!existsSync(template.src)) {
  2907. throw new Error("Template not found: " + template.src);
  2908. }
  2909. if (!template.filename) {
  2910. const srcPath = parse(template.src);
  2911. template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src).replace(/-/g, "_")}${srcPath.ext}`;
  2912. }
  2913. }
  2914. if (!template.src && !template.getContents) {
  2915. throw new Error("Invalid template. Either `getContents` or `src` should be provided: " + JSON.stringify(template));
  2916. }
  2917. if (!template.filename) {
  2918. throw new Error("Invalid template. `filename` must be provided: " + JSON.stringify(template));
  2919. }
  2920. if (template.filename.endsWith(".d.ts")) {
  2921. template.write = true;
  2922. }
  2923. template.dst ||= resolve(buildDir ?? useNuxt().options.buildDir, template.filename);
  2924. return template;
  2925. }
  2926. async function updateTemplates(options) {
  2927. return await tryUseNuxt()?.hooks.callHook("builder:generateApp", options);
  2928. }
  2929. const EXTENSION_RE = /\b(?:\.d\.[cm]?ts|\.\w+)$/g;
  2930. const excludedAlias = [/^@vue\/.*$/, /^#internal\/nuxt/];
  2931. async function _generateTypes(nuxt) {
  2932. const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
  2933. const relativeRootDir = relativeWithDot(nuxt.options.buildDir, nuxt.options.rootDir);
  2934. const include = /* @__PURE__ */ new Set([
  2935. join(relativeRootDir, "**/*"),
  2936. join(relativeRootDir, ".config/nuxt.*"),
  2937. "./nuxt.d.ts"
  2938. ]);
  2939. if (nuxt.options.srcDir !== nuxt.options.rootDir) {
  2940. include.add(join(relative(nuxt.options.buildDir, nuxt.options.srcDir), "**/*"));
  2941. }
  2942. if (nuxt.options.typescript.includeWorkspace && nuxt.options.workspaceDir !== nuxt.options.rootDir) {
  2943. include.add(join(relative(nuxt.options.buildDir, nuxt.options.workspaceDir), "**/*"));
  2944. }
  2945. for (const layer of nuxt.options._layers) {
  2946. const srcOrCwd = layer.config.srcDir ?? layer.cwd;
  2947. if (!srcOrCwd.startsWith(rootDirWithSlash) || srcOrCwd.includes("node_modules")) {
  2948. include.add(join(relative(nuxt.options.buildDir, srcOrCwd), "**/*"));
  2949. }
  2950. }
  2951. const exclude = /* @__PURE__ */ new Set([
  2952. // nitro generate output: https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/core/nitro.ts#L186
  2953. relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, "dist")),
  2954. // nitro generate .data in development when kv storage is used
  2955. relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, ".data"))
  2956. ]);
  2957. for (const dir of nuxt.options.modulesDir) {
  2958. exclude.add(relativeWithDot(nuxt.options.buildDir, dir));
  2959. }
  2960. const moduleEntryPaths = [];
  2961. for (const m of nuxt.options._installedModules) {
  2962. if (m.entryPath) {
  2963. moduleEntryPaths.push(getDirectory(m.entryPath));
  2964. }
  2965. }
  2966. const modulePaths = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
  2967. for (const path of modulePaths) {
  2968. const relative2 = relativeWithDot(nuxt.options.buildDir, path);
  2969. include.add(join(relative2, "runtime"));
  2970. exclude.add(join(relative2, "runtime/server"));
  2971. include.add(join(relative2, "dist/runtime"));
  2972. exclude.add(join(relative2, "dist/runtime/server"));
  2973. }
  2974. const isV4 = nuxt.options.future?.compatibilityVersion === 4;
  2975. const nestedModulesDirs = [];
  2976. for (const dir of [...nuxt.options.modulesDir].sort()) {
  2977. const withSlash = withTrailingSlash(dir);
  2978. if (nestedModulesDirs.every((d) => !d.startsWith(withSlash))) {
  2979. nestedModulesDirs.push(withSlash);
  2980. }
  2981. }
  2982. let hasTypescriptVersionWithModulePreserve;
  2983. for (const parent of nestedModulesDirs) {
  2984. hasTypescriptVersionWithModulePreserve ??= await readPackageJSON("typescript", { parent }).then((r) => r?.version && gte(r.version, "5.4.0")).catch(() => void 0);
  2985. }
  2986. hasTypescriptVersionWithModulePreserve ??= isV4;
  2987. const useDecorators = Boolean(nuxt.options.experimental?.decorators);
  2988. const tsConfig = defu(nuxt.options.typescript?.tsConfig, {
  2989. compilerOptions: {
  2990. /* Base options: */
  2991. esModuleInterop: true,
  2992. skipLibCheck: true,
  2993. target: "ESNext",
  2994. allowJs: true,
  2995. resolveJsonModule: true,
  2996. moduleDetection: "force",
  2997. isolatedModules: true,
  2998. verbatimModuleSyntax: true,
  2999. /* Strictness */
  3000. strict: nuxt.options.typescript?.strict ?? true,
  3001. noUncheckedIndexedAccess: isV4,
  3002. forceConsistentCasingInFileNames: true,
  3003. noImplicitOverride: true,
  3004. /* Decorator support */
  3005. ...useDecorators ? {
  3006. experimentalDecorators: false
  3007. } : {},
  3008. /* If NOT transpiling with TypeScript: */
  3009. module: hasTypescriptVersionWithModulePreserve ? "preserve" : "ESNext",
  3010. noEmit: true,
  3011. /* If your code runs in the DOM: */
  3012. lib: [
  3013. "ESNext",
  3014. ...useDecorators ? ["esnext.decorators"] : [],
  3015. "dom",
  3016. "dom.iterable",
  3017. "webworker"
  3018. ],
  3019. /* JSX support for Vue */
  3020. jsx: "preserve",
  3021. jsxImportSource: "vue",
  3022. /* remove auto-scanning for types */
  3023. types: [],
  3024. /* add paths object for filling-in later */
  3025. paths: {},
  3026. /* Possibly consider removing the following in future */
  3027. moduleResolution: nuxt.options.future?.typescriptBundlerResolution || nuxt.options.experimental?.typescriptBundlerResolution ? "Bundler" : "Node",
  3028. /* implied by module: preserve */
  3029. useDefineForClassFields: true,
  3030. /* implied by target: es2022+ */
  3031. noImplicitThis: true,
  3032. /* enabled with `strict` */
  3033. allowSyntheticDefaultImports: true
  3034. },
  3035. include: [...include],
  3036. exclude: [...exclude]
  3037. });
  3038. const aliases = nuxt.options.alias;
  3039. const basePath = tsConfig.compilerOptions.baseUrl ? resolve(nuxt.options.buildDir, tsConfig.compilerOptions.baseUrl) : nuxt.options.buildDir;
  3040. tsConfig.compilerOptions ||= {};
  3041. tsConfig.compilerOptions.paths ||= {};
  3042. tsConfig.include ||= [];
  3043. const importPaths = nuxt.options.modulesDir.map((d) => directoryToURL(d));
  3044. for (const alias in aliases) {
  3045. if (excludedAlias.some((re) => re.test(alias))) {
  3046. continue;
  3047. }
  3048. let absolutePath = resolve(basePath, aliases[alias]);
  3049. let stats = await promises.stat(absolutePath).catch(
  3050. () => null
  3051. /* file does not exist */
  3052. );
  3053. if (!stats) {
  3054. const resolvedModule = resolveModulePath(aliases[alias], {
  3055. try: true,
  3056. from: importPaths,
  3057. extensions: [...nuxt.options.extensions, ".d.ts", ".d.mts", ".d.cts"]
  3058. });
  3059. if (resolvedModule) {
  3060. absolutePath = resolvedModule;
  3061. stats = await promises.stat(resolvedModule).catch(() => null);
  3062. }
  3063. }
  3064. const relativePath = relativeWithDot(nuxt.options.buildDir, absolutePath);
  3065. if (stats?.isDirectory()) {
  3066. tsConfig.compilerOptions.paths[alias] = [relativePath];
  3067. tsConfig.compilerOptions.paths[`${alias}/*`] = [`${relativePath}/*`];
  3068. if (!absolutePath.startsWith(rootDirWithSlash)) {
  3069. tsConfig.include.push(relativePath);
  3070. }
  3071. } else {
  3072. const path = stats?.isFile() ? relativePath.replace(EXTENSION_RE, "") : aliases[alias];
  3073. tsConfig.compilerOptions.paths[alias] = [path];
  3074. if (!absolutePath.startsWith(rootDirWithSlash)) {
  3075. tsConfig.include.push(path);
  3076. }
  3077. }
  3078. }
  3079. const references = [];
  3080. await Promise.all([...nuxt.options.modules, ...nuxt.options._modules].map(async (id) => {
  3081. if (typeof id !== "string") {
  3082. return;
  3083. }
  3084. for (const parent of nestedModulesDirs) {
  3085. const pkg = await readPackageJSON(id, { parent }).catch(() => null);
  3086. if (pkg) {
  3087. references.push({ types: pkg.name ?? id });
  3088. return;
  3089. }
  3090. }
  3091. references.push({ types: id });
  3092. }));
  3093. const declarations = [];
  3094. await nuxt.callHook("prepare:types", { references, declarations, tsConfig });
  3095. for (const alias in tsConfig.compilerOptions.paths) {
  3096. const paths = tsConfig.compilerOptions.paths[alias];
  3097. tsConfig.compilerOptions.paths[alias] = await Promise.all(paths.map(async (path) => {
  3098. if (!isAbsolute(path)) {
  3099. return path;
  3100. }
  3101. const stats = await promises.stat(path).catch(
  3102. () => null
  3103. /* file does not exist */
  3104. );
  3105. return relativeWithDot(nuxt.options.buildDir, stats?.isFile() ? path.replace(EXTENSION_RE, "") : path);
  3106. }));
  3107. }
  3108. sortTsPaths(tsConfig.compilerOptions.paths);
  3109. tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
  3110. tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
  3111. const declaration = [
  3112. ...references.map((ref) => {
  3113. if ("path" in ref && isAbsolute(ref.path)) {
  3114. ref.path = relative(nuxt.options.buildDir, ref.path);
  3115. }
  3116. return `/// <reference ${renderAttrs(ref)} />`;
  3117. }),
  3118. ...declarations,
  3119. "",
  3120. "export {}",
  3121. ""
  3122. ].join("\n");
  3123. return {
  3124. declaration,
  3125. tsConfig
  3126. };
  3127. }
  3128. async function writeTypes(nuxt) {
  3129. const { tsConfig, declaration } = await _generateTypes(nuxt);
  3130. async function writeFile() {
  3131. const tsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.json");
  3132. await promises.mkdir(nuxt.options.buildDir, { recursive: true });
  3133. await promises.writeFile(tsConfigPath, JSON.stringify(tsConfig, null, 2));
  3134. const declarationPath = resolve(nuxt.options.buildDir, "nuxt.d.ts");
  3135. await promises.writeFile(declarationPath, declaration);
  3136. }
  3137. nuxt.hook("builder:prepared", writeFile);
  3138. await writeFile();
  3139. }
  3140. function sortTsPaths(paths) {
  3141. for (const pathKey in paths) {
  3142. if (pathKey.startsWith("#build")) {
  3143. const pathValue = paths[pathKey];
  3144. delete paths[pathKey];
  3145. paths[pathKey] = pathValue;
  3146. }
  3147. }
  3148. }
  3149. function renderAttrs(obj) {
  3150. const attrs = [];
  3151. for (const key in obj) {
  3152. attrs.push(renderAttr(key, obj[key]));
  3153. }
  3154. return attrs.join(" ");
  3155. }
  3156. function renderAttr(key, value) {
  3157. return value ? `${key}="${value}"` : "";
  3158. }
  3159. const RELATIVE_WITH_DOT_RE = /^([^.])/;
  3160. function relativeWithDot(from, to) {
  3161. return relative(from, to).replace(RELATIVE_WITH_DOT_RE, "./$1") || ".";
  3162. }
  3163. const LAYOUT_RE = /["']/g;
  3164. function addLayout(template, name) {
  3165. const nuxt = useNuxt();
  3166. const { filename, src } = addTemplate(template);
  3167. const layoutName = kebabCase(name || parse(filename).name).replace(LAYOUT_RE, "");
  3168. if (isNuxt2(nuxt)) {
  3169. const layout = nuxt.options.layouts[layoutName];
  3170. if (layout) {
  3171. return logger.warn(
  3172. `Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
  3173. );
  3174. }
  3175. nuxt.options.layouts[layoutName] = `./${filename}`;
  3176. if (name === "error") {
  3177. this.addErrorLayout(filename);
  3178. }
  3179. return;
  3180. }
  3181. nuxt.hook("app:templates", (app) => {
  3182. if (layoutName in app.layouts) {
  3183. const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName].file);
  3184. return logger.warn(
  3185. `Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
  3186. );
  3187. }
  3188. app.layouts[layoutName] = {
  3189. file: join("#build", filename),
  3190. name: layoutName
  3191. };
  3192. });
  3193. }
  3194. function extendPages(cb) {
  3195. const nuxt = useNuxt();
  3196. if (isNuxt2(nuxt)) {
  3197. nuxt.hook("build:extendRoutes", cb);
  3198. } else {
  3199. nuxt.hook("pages:extend", cb);
  3200. }
  3201. }
  3202. function extendRouteRules(route, rule, options = {}) {
  3203. const nuxt = useNuxt();
  3204. for (const opts of [nuxt.options, nuxt.options.nitro]) {
  3205. opts.routeRules ||= {};
  3206. opts.routeRules[route] = options.override ? defu(rule, opts.routeRules[route]) : defu(opts.routeRules[route], rule);
  3207. }
  3208. }
  3209. function addRouteMiddleware(input, options = {}) {
  3210. const nuxt = useNuxt();
  3211. const middlewares = toArray(input);
  3212. nuxt.hook("app:resolve", (app) => {
  3213. for (const middleware of middlewares) {
  3214. const find = app.middleware.findIndex((item) => item.name === middleware.name);
  3215. if (find >= 0) {
  3216. const foundPath = app.middleware[find].path;
  3217. if (foundPath === middleware.path) {
  3218. continue;
  3219. }
  3220. if (options.override === true) {
  3221. app.middleware[find] = { ...middleware };
  3222. } else {
  3223. logger.warn(`'${middleware.name}' middleware already exists at '${foundPath}'. You can set \`override: true\` to replace it.`);
  3224. }
  3225. } else if (options.prepend === true) {
  3226. app.middleware.unshift({ ...middleware });
  3227. } else {
  3228. app.middleware.push({ ...middleware });
  3229. }
  3230. }
  3231. });
  3232. }
  3233. const pluginSymbol = Symbol.for("nuxt plugin");
  3234. function normalizePlugin(plugin) {
  3235. if (typeof plugin === "string") {
  3236. plugin = { src: plugin };
  3237. } else {
  3238. plugin = { ...plugin };
  3239. }
  3240. if (pluginSymbol in plugin) {
  3241. return plugin;
  3242. }
  3243. if (!plugin.src) {
  3244. throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
  3245. }
  3246. plugin.src = normalize(resolveAlias(plugin.src));
  3247. if (!existsSync(plugin.src) && isAbsolute$1(plugin.src)) {
  3248. try {
  3249. plugin.src = resolveModulePath(plugin.src, {
  3250. extensions: tryUseNuxt()?.options.extensions ?? [".js", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"]
  3251. });
  3252. } catch {
  3253. }
  3254. }
  3255. if (plugin.ssr) {
  3256. plugin.mode = "server";
  3257. }
  3258. if (!plugin.mode) {
  3259. const [, mode = "all"] = plugin.src.match(MODE_RE) || [];
  3260. plugin.mode = mode;
  3261. }
  3262. plugin[pluginSymbol] = true;
  3263. return plugin;
  3264. }
  3265. function addPlugin(_plugin, opts = {}) {
  3266. const nuxt = useNuxt();
  3267. const plugin = normalizePlugin(_plugin);
  3268. filterInPlace(nuxt.options.plugins, (p) => normalizePlugin(p).src !== plugin.src);
  3269. nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
  3270. return plugin;
  3271. }
  3272. function addPluginTemplate(plugin, opts = {}) {
  3273. const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
  3274. return addPlugin(normalizedPlugin, opts);
  3275. }
  3276. export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, compileTemplate, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, importModule, installModule, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, requireModule, resolveAlias, resolveFiles, resolveIgnorePatterns, resolveModule, resolveNuxtModule, resolvePath, runWithNuxtContext, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };