-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
nuxt.ts
491 lines (421 loc) · 15.5 KB
/
nuxt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/* eslint-disable no-use-before-define */
import { effectScope, getCurrentInstance, hasInjectionContext, reactive } from 'vue'
import type { App, EffectScope, Ref, VNode, onErrorCaptured } from 'vue'
import type { RouteLocationNormalizedLoaded } from '#vue-router'
import type { HookCallback, Hookable } from 'hookable'
import { createHooks } from 'hookable'
import { getContext } from 'unctx'
import type { SSRContext, createRenderer } from 'vue-bundle-renderer/runtime'
import type { EventHandlerRequest, H3Event } from 'h3'
import type { AppConfig, AppConfigInput, RuntimeConfig } from 'nuxt/schema'
import type { RenderResponse } from 'nitropack'
import type { LogObject } from 'consola'
import type { MergeHead, VueHeadClient } from '@unhead/vue'
import type { NuxtIslandContext } from '../app/types'
import type { RouteMiddleware } from '../app/composables/router'
import type { NuxtError } from '../app/composables/error'
import type { AsyncDataRequestStatus } from '../app/composables/asyncData'
import type { NuxtAppManifestMeta } from '../app/composables/manifest'
import type { LoadingIndicator } from '../app/composables/loading-indicator'
import type { ViewTransition } from './plugins/view-transitions.client'
import type { NuxtAppLiterals } from '#app'
const nuxtAppCtx = /* @__PURE__ */ getContext<NuxtApp>('nuxt-app', {
asyncContext: !!__NUXT_ASYNC_CONTEXT__ && import.meta.server
})
type HookResult = Promise<void> | void
type AppRenderedContext = { ssrContext: NuxtApp['ssrContext'], renderResult: null | Awaited<ReturnType<ReturnType<typeof createRenderer>['renderToString']>> }
export interface RuntimeNuxtHooks {
'app:created': (app: App<Element>) => HookResult
'app:beforeMount': (app: App<Element>) => HookResult
'app:mounted': (app: App<Element>) => HookResult
'app:rendered': (ctx: AppRenderedContext) => HookResult
'app:redirected': () => HookResult
'app:suspense:resolve': (Component?: VNode) => HookResult
'app:error': (err: any) => HookResult
'app:error:cleared': (options: { redirect?: string }) => HookResult
'app:chunkError': (options: { error: any }) => HookResult
'app:data:refresh': (keys?: string[]) => HookResult
'app:manifest:update': (meta?: NuxtAppManifestMeta) => HookResult
'dev:ssr-logs': (logs: LogObject[]) => void | Promise<void>
'link:prefetch': (link: string) => HookResult
'page:start': (Component?: VNode) => HookResult
'page:finish': (Component?: VNode) => HookResult
'page:transition:start': () => HookResult
'page:transition:finish': (Component?: VNode) => HookResult
'page:view-transition:start': (transition: ViewTransition) => HookResult
'page:loading:start': () => HookResult
'page:loading:end': () => HookResult
'vue:setup': () => void
'vue:error': (...args: Parameters<Parameters<typeof onErrorCaptured>[0]>) => HookResult
}
export interface NuxtSSRContext extends SSRContext {
url: string
event: H3Event
runtimeConfig: RuntimeConfig
noSSR: boolean
/** whether we are rendering an SSR error */
error?: boolean
nuxt: _NuxtApp
payload: NuxtPayload
head: VueHeadClient<MergeHead>
/** This is used solely to render runtime config with SPA renderer. */
config?: Pick<RuntimeConfig, 'public' | 'app'>
teleports?: Record<string, string>
islandContext?: NuxtIslandContext
/** @internal */
_renderResponse?: Partial<RenderResponse>
/** @internal */
_payloadReducers: Record<string, (data: any) => any>
/** @internal */
_sharedPrerenderCache?: {
get<T = unknown> (key: string): Promise<T> | undefined
set<T> (key: string, value: Promise<T>): Promise<void>
}
}
export interface NuxtPayload {
path?: string
serverRendered?: boolean
prerenderedAt?: number
data: Record<string, any>
state: Record<string, any>
once: Set<string>
config?: Pick<RuntimeConfig, 'public' | 'app'>
error?: NuxtError | null
_errors: Record<string, NuxtError | null>
[key: string]: unknown
}
interface _NuxtApp {
vueApp: App<Element>
globalName: string
versions: Record<string, string>
hooks: Hookable<RuntimeNuxtHooks>
hook: _NuxtApp['hooks']['hook']
callHook: _NuxtApp['hooks']['callHook']
runWithContext: <T extends () => any>(fn: T) => ReturnType<T> | Promise<Awaited<ReturnType<T>>>
[key: string]: unknown
/** @internal */
_id?: number
/** @internal */
_scope: EffectScope
/** @internal */
_asyncDataPromises: Record<string, Promise<any> | undefined>
/** @internal */
_asyncData: Record<string, {
data: Ref<any>
pending: Ref<boolean>
error: Ref<Error | null>
status: Ref<AsyncDataRequestStatus>
} | undefined>
/** @internal */
_loadingIndicator?: LoadingIndicator
/** @internal */
_loadingIndicatorDeps?: number
/** @internal */
_middleware: {
global: RouteMiddleware[]
named: Record<string, RouteMiddleware>
}
/** @internal */
_once: {
[key: string]: Promise<any>
}
/** @internal */
_observer?: { observe: (element: Element, callback: () => void) => () => void }
/** @internal */
_payloadCache?: Record<string, Promise<Record<string, any>> | Record<string, any> | null>
/** @internal */
_appConfig: AppConfig
/** @internal */
_route: RouteLocationNormalizedLoaded
/** @internal */
_islandPromises?: Record<string, Promise<any>>
/** @internal */
_payloadRevivers: Record<string, (data: any) => any>
// Nuxt injections
$config: RuntimeConfig
isHydrating?: boolean
deferHydration: () => () => void | Promise<void>
ssrContext?: NuxtSSRContext
payload: NuxtPayload
static: {
data: Record<string, any>
}
provide: (name: string, value: any) => void
}
export interface NuxtApp extends _NuxtApp {}
export const NuxtPluginIndicator = '__nuxt_plugin'
export interface PluginMeta {
name?: string
enforce?: 'pre' | 'default' | 'post'
/**
* Await for other named plugins to finish before running this plugin.
*/
dependsOn?: NuxtAppLiterals['pluginName'][]
/**
* This allows more granular control over plugin order and should only be used by advanced users.
* It overrides the value of `enforce` and is used to sort plugins.
*/
order?: number
}
export interface PluginEnvContext {
/**
* This enable the plugin for islands components.
* Require `experimental.componentsIslands`.
* @default true
*/
islands?: boolean
}
export interface ResolvedPluginMeta {
name?: string
parallel?: boolean
}
export interface Plugin<Injections extends Record<string, unknown> = Record<string, unknown>> {
(nuxt: _NuxtApp): Promise<void> | Promise<{ provide?: Injections }> | void | { provide?: Injections }
[NuxtPluginIndicator]?: true
meta?: ResolvedPluginMeta
}
export interface ObjectPlugin<Injections extends Record<string, unknown> = Record<string, unknown>> extends PluginMeta {
hooks?: Partial<RuntimeNuxtHooks>
setup?: Plugin<Injections>
env?: PluginEnvContext
/**
* Execute plugin in parallel with other parallel plugins.
* @default false
*/
parallel?: boolean
/**
* @internal
*/
_name?: string
}
/** @deprecated Use `ObjectPlugin` */
export type ObjectPluginInput<Injections extends Record<string, unknown> = Record<string, unknown>> = ObjectPlugin<Injections>
export interface CreateOptions {
vueApp: NuxtApp['vueApp']
ssrContext?: NuxtApp['ssrContext']
globalName?: NuxtApp['globalName']
}
export function createNuxtApp (options: CreateOptions) {
let hydratingCount = 0
const nuxtApp: NuxtApp = {
_scope: effectScope(),
provide: undefined,
globalName: 'nuxt',
versions: {
get nuxt () { return __NUXT_VERSION__ },
get vue () { return nuxtApp.vueApp.version }
},
payload: reactive({
data: {},
state: {},
once: new Set<string>(),
_errors: {},
...(import.meta.client ? window.__NUXT__ ?? {} : { serverRendered: true })
}),
static: {
data: {}
},
runWithContext: (fn: any) => nuxtApp._scope.run(() => callWithNuxt(nuxtApp, fn)),
isHydrating: import.meta.client,
deferHydration () {
if (!nuxtApp.isHydrating) { return () => {} }
hydratingCount++
let called = false
return () => {
if (called) { return }
called = true
hydratingCount--
if (hydratingCount === 0) {
nuxtApp.isHydrating = false
return nuxtApp.callHook('app:suspense:resolve')
}
}
},
_asyncDataPromises: {},
_asyncData: {},
_payloadRevivers: {},
...options
} as any as NuxtApp
nuxtApp.hooks = createHooks<RuntimeNuxtHooks>()
nuxtApp.hook = nuxtApp.hooks.hook
if (import.meta.server) {
const contextCaller = async function (hooks: HookCallback[], args: any[]) {
for (const hook of hooks) {
await nuxtApp.runWithContext(() => hook(...args))
}
}
// Patch callHook to preserve NuxtApp context on server
// TODO: Refactor after https://github.com/unjs/hookable/issues/74
nuxtApp.hooks.callHook = (name: any, ...args: any[]) => nuxtApp.hooks.callHookWith(contextCaller, name, ...args)
}
nuxtApp.callHook = nuxtApp.hooks.callHook
nuxtApp.provide = (name: string, value: any) => {
const $name = '$' + name
defineGetter(nuxtApp, $name, value)
defineGetter(nuxtApp.vueApp.config.globalProperties, $name, value)
}
// Inject $nuxt
defineGetter(nuxtApp.vueApp, '$nuxt', nuxtApp)
defineGetter(nuxtApp.vueApp.config.globalProperties, '$nuxt', nuxtApp)
if (import.meta.server) {
if (nuxtApp.ssrContext) {
// Expose nuxt to the renderContext
nuxtApp.ssrContext.nuxt = nuxtApp
// Expose payload types
nuxtApp.ssrContext._payloadReducers = {}
// Expose current path
nuxtApp.payload.path = nuxtApp.ssrContext.url
}
// Expose to server renderer to create payload
nuxtApp.ssrContext = nuxtApp.ssrContext || {} as any
if (nuxtApp.ssrContext!.payload) {
Object.assign(nuxtApp.payload, nuxtApp.ssrContext!.payload)
}
nuxtApp.ssrContext!.payload = nuxtApp.payload
// Expose client runtime-config to the payload
nuxtApp.ssrContext!.config = {
public: options.ssrContext!.runtimeConfig.public,
app: options.ssrContext!.runtimeConfig.app
}
}
// Listen to chunk load errors
if (import.meta.client) {
window.addEventListener('nuxt.preloadError', (event) => {
nuxtApp.callHook('app:chunkError', { error: (event as Event & { payload: Error }).payload })
})
window.useNuxtApp = window.useNuxtApp || useNuxtApp
// Log errors captured when running plugins, in the `app:created` and `app:beforeMount` hooks
// as well as when mounting the app.
const unreg = nuxtApp.hook('app:error', (...args) => { console.error('[nuxt] error caught during app initialization', ...args) })
nuxtApp.hook('app:mounted', unreg)
}
// Expose runtime config
const runtimeConfig = import.meta.server ? options.ssrContext!.runtimeConfig : reactive(nuxtApp.payload.config!)
nuxtApp.provide('config', runtimeConfig)
return nuxtApp
}
export async function applyPlugin (nuxtApp: NuxtApp, plugin: Plugin & ObjectPlugin<any>) {
if (plugin.hooks) {
nuxtApp.hooks.addHooks(plugin.hooks)
}
if (typeof plugin === 'function') {
const { provide } = await nuxtApp.runWithContext(() => plugin(nuxtApp)) || {}
if (provide && typeof provide === 'object') {
for (const key in provide) {
nuxtApp.provide(key, provide[key])
}
}
}
}
export async function applyPlugins (nuxtApp: NuxtApp, plugins: Array<Plugin & ObjectPlugin<any>>) {
const resolvedPlugins: string[] = []
const unresolvedPlugins: [Set<string>, Plugin & ObjectPlugin<any>][] = []
const parallels: Promise<any>[] = []
const errors: Error[] = []
let promiseDepth = 0
async function executePlugin (plugin: Plugin & ObjectPlugin<any>) {
const unresolvedPluginsForThisPlugin = plugin.dependsOn?.filter(name => plugins.some(p => p._name === name) && !resolvedPlugins.includes(name)) ?? []
if (unresolvedPluginsForThisPlugin.length > 0) {
unresolvedPlugins.push([new Set(unresolvedPluginsForThisPlugin), plugin])
} else {
const promise = applyPlugin(nuxtApp, plugin).then(async () => {
if (plugin._name) {
resolvedPlugins.push(plugin._name)
await Promise.all(unresolvedPlugins.map(async ([dependsOn, unexecutedPlugin]) => {
if (dependsOn.has(plugin._name!)) {
dependsOn.delete(plugin._name!)
if (dependsOn.size === 0) {
promiseDepth++
await executePlugin(unexecutedPlugin)
}
}
}))
}
})
if (plugin.parallel) {
parallels.push(promise.catch(e => errors.push(e)))
} else {
await promise
}
}
}
for (const plugin of plugins) {
if (import.meta.server && nuxtApp.ssrContext?.islandContext && plugin.env?.islands === false) { continue }
await executePlugin(plugin)
}
await Promise.all(parallels)
if (promiseDepth) {
for (let i = 0; i < promiseDepth; i++) {
await Promise.all(parallels)
}
}
if (errors.length) { throw errors[0] }
}
/* @__NO_SIDE_EFFECTS__ */
export function defineNuxtPlugin<T extends Record<string, unknown>> (plugin: Plugin<T> | ObjectPlugin<T>): Plugin<T> & ObjectPlugin<T> {
if (typeof plugin === 'function') { return plugin }
const _name = plugin._name || plugin.name
delete plugin.name
return Object.assign(plugin.setup || (() => {}), plugin, { [NuxtPluginIndicator]: true, _name } as const)
}
/* @__NO_SIDE_EFFECTS__ */
export const definePayloadPlugin = defineNuxtPlugin
export function isNuxtPlugin (plugin: unknown) {
return typeof plugin === 'function' && NuxtPluginIndicator in plugin
}
/**
* Ensures that the setup function passed in has access to the Nuxt instance via `useNuxt`.
* @param nuxt A Nuxt instance
* @param setup The function to call
*/
export function callWithNuxt<T extends (...args: any[]) => any> (nuxt: NuxtApp | _NuxtApp, setup: T, args?: Parameters<T>) {
const fn: () => ReturnType<T> = () => args ? setup(...args as Parameters<T>) : setup()
if (import.meta.server) {
return nuxt.vueApp.runWithContext(() => nuxtAppCtx.callAsync(nuxt as NuxtApp, fn))
} else {
// In client side we could assume nuxt app is singleton
nuxtAppCtx.set(nuxt as NuxtApp)
return nuxt.vueApp.runWithContext(fn)
}
}
/* @__NO_SIDE_EFFECTS__ */
/**
* Returns the current Nuxt instance.
*
* Returns `null` if Nuxt instance is unavailable.
*/
export function tryUseNuxtApp (): NuxtApp | null {
let nuxtAppInstance
if (hasInjectionContext()) {
nuxtAppInstance = getCurrentInstance()?.appContext.app.$nuxt
}
nuxtAppInstance = nuxtAppInstance || nuxtAppCtx.tryUse()
return nuxtAppInstance || null
}
/* @__NO_SIDE_EFFECTS__ */
/**
* Returns the current Nuxt instance.
*
* Throws an error if Nuxt instance is unavailable.
*/
export function useNuxtApp (): NuxtApp {
const nuxtAppInstance = tryUseNuxtApp()
if (!nuxtAppInstance) {
if (import.meta.dev) {
throw new Error('[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at `https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables`.')
} else {
throw new Error('[nuxt] instance unavailable')
}
}
return nuxtAppInstance
}
/* @__NO_SIDE_EFFECTS__ */
export function useRuntimeConfig (_event?: H3Event<EventHandlerRequest>): RuntimeConfig {
return useNuxtApp().$config
}
function defineGetter<K extends string | number | symbol, V> (obj: Record<K, V>, key: K, val: V) {
Object.defineProperty(obj, key, { get: () => val })
}
export function defineAppConfig<C extends AppConfigInput> (config: C): C {
return config
}