feat: init
This commit is contained in:
2
node_modules/nuxt/dist/app/composables/asyncContext.d.ts
generated
vendored
Normal file
2
node_modules/nuxt/dist/app/composables/asyncContext.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/** @since 3.8.0 */
|
||||
export declare function withAsyncContext(fn: () => PromiseLike<unknown>): any;
|
||||
7
node_modules/nuxt/dist/app/composables/asyncContext.js
generated
vendored
Normal file
7
node_modules/nuxt/dist/app/composables/asyncContext.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import { getCurrentInstance, withAsyncContext as withVueAsyncContext } from "vue";
|
||||
export function withAsyncContext(fn) {
|
||||
return withVueAsyncContext(() => {
|
||||
const nuxtApp = getCurrentInstance()?.appContext.app.$nuxt;
|
||||
return nuxtApp ? nuxtApp.runWithContext(fn) : fn();
|
||||
});
|
||||
}
|
||||
151
node_modules/nuxt/dist/app/composables/asyncData.d.ts
generated
vendored
Normal file
151
node_modules/nuxt/dist/app/composables/asyncData.d.ts
generated
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
import type { MaybeRefOrGetter, MultiWatchSources, Ref } from 'vue';
|
||||
import type { NuxtApp } from '../nuxt.js';
|
||||
import type { NuxtError } from './error.js';
|
||||
export type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error';
|
||||
export type _Transform<Input = any, Output = any> = (input: Input) => Output | Promise<Output>;
|
||||
export type AsyncDataHandler<ResT> = (nuxtApp: NuxtApp, options: {
|
||||
signal: AbortSignal;
|
||||
}) => Promise<ResT>;
|
||||
export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? keyof T extends K[number] ? T : K[number] extends never ? T : Pick<T, K[number]> : T;
|
||||
export type KeysOf<T> = Array<T extends T ? keyof T extends string ? keyof T : never : never>;
|
||||
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>;
|
||||
export type { MultiWatchSources };
|
||||
export type NoInfer<T> = [T][T extends any ? 0 : never];
|
||||
export type AsyncDataRefreshCause = 'initial' | 'refresh:hook' | 'refresh:manual' | 'watch';
|
||||
export interface AsyncDataOptions<ResT, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined> {
|
||||
/**
|
||||
* Whether to fetch on the server side.
|
||||
* @default true
|
||||
*/
|
||||
server?: boolean;
|
||||
/**
|
||||
* Whether to resolve the async function after loading the route, instead of blocking client-side navigation
|
||||
* @default false
|
||||
*/
|
||||
lazy?: boolean;
|
||||
/**
|
||||
* a factory function to set the default value of the data, before the async function resolves - useful with the `lazy: true` or `immediate: false` options
|
||||
*/
|
||||
default?: () => DefaultT | Ref<DefaultT>;
|
||||
/**
|
||||
* Provide a function which returns cached data.
|
||||
* An `undefined` return value will trigger a fetch.
|
||||
* Default is `key => nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key]` which only caches data when payloadExtraction is enabled.
|
||||
*/
|
||||
getCachedData?: (key: string, nuxtApp: NuxtApp, context: {
|
||||
cause: AsyncDataRefreshCause;
|
||||
}) => NoInfer<DataT> | undefined;
|
||||
/**
|
||||
* A function that can be used to alter handler function result after resolving.
|
||||
* Do not use it along with the `pick` option.
|
||||
*/
|
||||
transform?: _Transform<ResT, DataT>;
|
||||
/**
|
||||
* Only pick specified keys in this array from the handler function result.
|
||||
* Do not use it along with the `transform` option.
|
||||
*/
|
||||
pick?: PickKeys;
|
||||
/**
|
||||
* Watch reactive sources to auto-refresh when changed
|
||||
*/
|
||||
watch?: MultiWatchSources;
|
||||
/**
|
||||
* When set to false, will prevent the request from firing immediately
|
||||
* @default true
|
||||
*/
|
||||
immediate?: boolean;
|
||||
/**
|
||||
* Return data in a deep ref object (it is false by default). It can be set to false to return data in a shallow ref object, which can improve performance if your data does not need to be deeply reactive.
|
||||
*/
|
||||
deep?: boolean;
|
||||
/**
|
||||
* Avoid fetching the same key more than once at a time
|
||||
* @default 'cancel'
|
||||
*/
|
||||
dedupe?: 'cancel' | 'defer';
|
||||
/**
|
||||
* A timeout in milliseconds after which the request will be aborted if it has not resolved yet.
|
||||
*/
|
||||
timeout?: number;
|
||||
}
|
||||
export interface AsyncDataExecuteOptions {
|
||||
/**
|
||||
* Force a refresh, even if there is already a pending request. Previous requests will
|
||||
* not be cancelled, but their result will not affect the data/pending state - and any
|
||||
* previously awaited promises will not resolve until this new request resolves.
|
||||
*/
|
||||
dedupe?: 'cancel' | 'defer';
|
||||
cause?: AsyncDataRefreshCause;
|
||||
/** @internal */
|
||||
cachedData?: any;
|
||||
signal?: AbortSignal;
|
||||
timeout?: number;
|
||||
}
|
||||
export interface _AsyncData<DataT, ErrorT> {
|
||||
data: Ref<DataT>;
|
||||
pending: Ref<boolean>;
|
||||
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>;
|
||||
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>;
|
||||
clear: () => void;
|
||||
error: Ref<ErrorT | undefined>;
|
||||
status: Ref<AsyncDataRequestStatus>;
|
||||
}
|
||||
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>;
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/4.x/api/composables/use-async-data}
|
||||
* @since 3.0.0
|
||||
* @param handler An asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side.
|
||||
* @param options customize the behavior of useAsyncData
|
||||
*/
|
||||
export declare function useAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(handler: AsyncDataHandler<ResT>, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
export declare function useAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(handler: AsyncDataHandler<ResT>, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/4.x/api/composables/use-async-data}
|
||||
* @param key A unique key to ensure that data fetching can be properly de-duplicated across requests.
|
||||
* @param handler An asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side.
|
||||
* @param options customize the behavior of useAsyncData
|
||||
*/
|
||||
export declare function useAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(key: MaybeRefOrGetter<string>, handler: AsyncDataHandler<ResT>, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
export declare function useAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(key: MaybeRefOrGetter<string>, handler: AsyncDataHandler<ResT>, options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/4.x/api/composables/use-lazy-async-data}
|
||||
* @since 3.0.0
|
||||
* @param handler An asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side.
|
||||
* @param options customize the behavior of useLazyAsyncData
|
||||
*/
|
||||
export declare function useLazyAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(handler: AsyncDataHandler<ResT>, options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
export declare function useLazyAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(handler: AsyncDataHandler<ResT>, options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/4.x/api/composables/use-lazy-async-data}
|
||||
* @param key A unique key to ensure that data fetching can be properly de-duplicated across requests.
|
||||
* @param handler An asynchronous function that must return a truthy value (for example, it should not be `undefined` or `null`) or the request may be duplicated on the client side.
|
||||
* @param options customize the behavior of useLazyAsyncData
|
||||
*/
|
||||
export declare function useLazyAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(key: MaybeRefOrGetter<string>, handler: AsyncDataHandler<ResT>, options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
export declare function useLazyAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(key: MaybeRefOrGetter<string>, handler: AsyncDataHandler<ResT>, options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>;
|
||||
/** @since 3.1.0 */
|
||||
export declare function useNuxtData<DataT = any>(key: string): {
|
||||
data: Ref<DataT | undefined>;
|
||||
};
|
||||
/** @since 3.0.0 */
|
||||
export declare function refreshNuxtData(keys?: string | string[]): Promise<void>;
|
||||
/** @since 3.0.0 */
|
||||
export declare function clearNuxtData(keys?: string | string[] | ((key: string) => boolean)): void;
|
||||
export type DebouncedReturn<ArgumentsT extends unknown[], ReturnT> = ((...args: ArgumentsT) => Promise<ReturnT>) & {
|
||||
cancel: () => void;
|
||||
flush: () => Promise<ReturnT> | undefined;
|
||||
isPending: () => boolean;
|
||||
};
|
||||
export type CreatedAsyncData<ResT, NuxtErrorDataT = unknown, DataT = ResT, DefaultT = undefined> = Omit<_AsyncData<DataT | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>)>, 'clear' | 'refresh'> & {
|
||||
_off: () => void;
|
||||
_hash?: Record<string, string | undefined>;
|
||||
_default: () => unknown;
|
||||
_init: boolean;
|
||||
_deps: number;
|
||||
_execute: DebouncedReturn<[opts?: AsyncDataExecuteOptions | undefined], void>;
|
||||
_abortController?: AbortController;
|
||||
};
|
||||
496
node_modules/nuxt/dist/app/composables/asyncData.js
generated
vendored
Normal file
496
node_modules/nuxt/dist/app/composables/asyncData.js
generated
vendored
Normal file
@@ -0,0 +1,496 @@
|
||||
import { computed, getCurrentInstance, getCurrentScope, inject, isShallow, nextTick, onBeforeMount, onScopeDispose, onServerPrefetch, onUnmounted, queuePostFlushCb, ref, shallowRef, toRef, toValue, unref, watch } from "vue";
|
||||
import { debounce } from "perfect-debounce";
|
||||
import { hash } from "ohash";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { getUserCaller, toArray } from "../utils.js";
|
||||
import { clientOnlySymbol } from "../components/client-only.js";
|
||||
import { createError } from "./error.js";
|
||||
import { onNuxtReady } from "./ready.js";
|
||||
import { asyncDataDefaults, granularCachedData, pendingWhenIdle, purgeCachedData } from "#build/nuxt.config.mjs";
|
||||
export function useAsyncData(...args) {
|
||||
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
|
||||
if (_isAutoKeyNeeded(args[0], args[1])) {
|
||||
args.unshift(autoKey);
|
||||
}
|
||||
let [_key, _handler, options = {}] = args;
|
||||
let keyChanging = false;
|
||||
const key = computed(() => toValue(_key));
|
||||
if (typeof key.value !== "string") {
|
||||
throw new TypeError("[nuxt] [useAsyncData] key must be a string.");
|
||||
}
|
||||
if (typeof _handler !== "function") {
|
||||
throw new TypeError("[nuxt] [useAsyncData] handler must be a function.");
|
||||
}
|
||||
const nuxtApp = useNuxtApp();
|
||||
options.server ??= true;
|
||||
options.default ??= getDefault;
|
||||
options.getCachedData ??= getDefaultCachedData;
|
||||
options.lazy ??= false;
|
||||
options.immediate ??= true;
|
||||
options.deep ??= asyncDataDefaults.deep;
|
||||
options.dedupe ??= "cancel";
|
||||
const functionName = options._functionName || "useAsyncData";
|
||||
const currentData = nuxtApp._asyncData[key.value];
|
||||
if (import.meta.dev && currentData) {
|
||||
const warnings = [];
|
||||
const values = createHash(_handler, options);
|
||||
if (values.handler !== currentData._hash?.handler) {
|
||||
warnings.push(`different handler`);
|
||||
}
|
||||
for (const opt of ["transform", "pick", "getCachedData"]) {
|
||||
if (values[opt] !== currentData._hash[opt]) {
|
||||
warnings.push(`different \`${opt}\` option`);
|
||||
}
|
||||
}
|
||||
if (currentData._default.toString() !== options.default.toString()) {
|
||||
warnings.push(`different \`default\` value`);
|
||||
}
|
||||
if (options.deep && isShallow(currentData.data)) {
|
||||
warnings.push(`mismatching \`deep\` option`);
|
||||
}
|
||||
if (warnings.length) {
|
||||
const caller = getUserCaller();
|
||||
const explanation = caller ? ` (used at ${caller.source}:${caller.line}:${caller.column})` : "";
|
||||
console.warn(`[nuxt] [${functionName}] Incompatible options detected for "${key.value}"${explanation}:
|
||||
${warnings.map((w) => `- ${w}`).join("\n")}
|
||||
You can use a different key or move the call to a composable to ensure the options are shared across calls.`);
|
||||
}
|
||||
}
|
||||
function createInitialFetch() {
|
||||
const initialFetchOptions = { cause: "initial", dedupe: options.dedupe };
|
||||
if (!nuxtApp._asyncData[key.value]?._init) {
|
||||
initialFetchOptions.cachedData = options.getCachedData(key.value, nuxtApp, { cause: "initial" });
|
||||
nuxtApp._asyncData[key.value] = createAsyncData(nuxtApp, key.value, _handler, options, initialFetchOptions.cachedData);
|
||||
}
|
||||
return () => nuxtApp._asyncData[key.value].execute(initialFetchOptions);
|
||||
}
|
||||
const initialFetch = createInitialFetch();
|
||||
const asyncData = nuxtApp._asyncData[key.value];
|
||||
asyncData._deps++;
|
||||
const fetchOnServer = options.server !== false && nuxtApp.payload.serverRendered;
|
||||
if (import.meta.server && fetchOnServer && options.immediate) {
|
||||
const promise = initialFetch();
|
||||
if (getCurrentInstance()) {
|
||||
onServerPrefetch(() => promise);
|
||||
} else {
|
||||
nuxtApp.hook("app:created", async () => {
|
||||
await promise;
|
||||
});
|
||||
}
|
||||
}
|
||||
if (import.meta.client) {
|
||||
let unregister = function(key2) {
|
||||
const data = nuxtApp._asyncData[key2];
|
||||
if (data?._deps) {
|
||||
data._deps--;
|
||||
if (data._deps === 0) {
|
||||
data?._off();
|
||||
}
|
||||
}
|
||||
};
|
||||
const instance = getCurrentInstance();
|
||||
if (instance && fetchOnServer && options.immediate && !instance.sp) {
|
||||
instance.sp = [];
|
||||
}
|
||||
if (import.meta.dev && !nuxtApp.isHydrating && !nuxtApp._processingMiddleware && (!instance || instance?.isMounted)) {
|
||||
console.warn(`[nuxt] [${functionName}] Component is already mounted, please use $fetch instead. See https://nuxt.com/docs/4.x/getting-started/data-fetching`);
|
||||
}
|
||||
if (instance && !instance._nuxtOnBeforeMountCbs) {
|
||||
instance._nuxtOnBeforeMountCbs = [];
|
||||
const cbs = instance._nuxtOnBeforeMountCbs;
|
||||
onBeforeMount(() => {
|
||||
cbs.forEach((cb) => {
|
||||
cb();
|
||||
});
|
||||
cbs.splice(0, cbs.length);
|
||||
});
|
||||
onUnmounted(() => cbs.splice(0, cbs.length));
|
||||
}
|
||||
const isWithinClientOnly = instance && (instance._nuxtClientOnly || inject(clientOnlySymbol, false));
|
||||
if (fetchOnServer && nuxtApp.isHydrating && (asyncData.error.value || asyncData.data.value !== void 0)) {
|
||||
if (pendingWhenIdle) {
|
||||
asyncData.pending.value = false;
|
||||
}
|
||||
asyncData.status.value = asyncData.error.value ? "error" : "success";
|
||||
} else if (instance && (!isWithinClientOnly && nuxtApp.payload.serverRendered && nuxtApp.isHydrating || options.lazy) && options.immediate) {
|
||||
instance._nuxtOnBeforeMountCbs.push(initialFetch);
|
||||
} else if (options.immediate && asyncData.status.value !== "success") {
|
||||
initialFetch();
|
||||
}
|
||||
const hasScope = getCurrentScope();
|
||||
const unsubKeyWatcher = watch(key, (newKey, oldKey) => {
|
||||
if ((newKey || oldKey) && newKey !== oldKey) {
|
||||
keyChanging = true;
|
||||
const hadData = nuxtApp._asyncData[oldKey]?.data.value !== void 0;
|
||||
const wasRunning = nuxtApp._asyncDataPromises[oldKey] !== void 0;
|
||||
const initialFetchOptions = { cause: "initial", dedupe: options.dedupe };
|
||||
if (!nuxtApp._asyncData[newKey]?._init) {
|
||||
let initialValue;
|
||||
if (oldKey && hadData) {
|
||||
initialValue = nuxtApp._asyncData[oldKey].data.value;
|
||||
} else {
|
||||
initialValue = options.getCachedData(newKey, nuxtApp, { cause: "initial" });
|
||||
initialFetchOptions.cachedData = initialValue;
|
||||
}
|
||||
nuxtApp._asyncData[newKey] = createAsyncData(nuxtApp, newKey, _handler, options, initialValue);
|
||||
}
|
||||
nuxtApp._asyncData[newKey]._deps++;
|
||||
if (oldKey) {
|
||||
unregister(oldKey);
|
||||
}
|
||||
if (options.immediate || hadData || wasRunning) {
|
||||
nuxtApp._asyncData[newKey].execute(initialFetchOptions);
|
||||
}
|
||||
queuePostFlushCb(() => {
|
||||
keyChanging = false;
|
||||
});
|
||||
}
|
||||
}, { flush: "sync" });
|
||||
const unsubParamsWatcher = options.watch ? watch(options.watch, () => {
|
||||
if (keyChanging) {
|
||||
return;
|
||||
}
|
||||
if (nuxtApp._asyncData[key.value]?._execute.isPending()) {
|
||||
queuePostFlushCb(() => {
|
||||
nuxtApp._asyncData[key.value]?._execute.flush();
|
||||
});
|
||||
}
|
||||
nuxtApp._asyncData[key.value]?._execute({ cause: "watch", dedupe: options.dedupe });
|
||||
}) : () => {
|
||||
};
|
||||
if (hasScope) {
|
||||
onScopeDispose(() => {
|
||||
unsubKeyWatcher();
|
||||
unsubParamsWatcher();
|
||||
unregister(key.value);
|
||||
});
|
||||
}
|
||||
}
|
||||
const asyncReturn = {
|
||||
data: writableComputedRef(() => nuxtApp._asyncData[key.value]?.data),
|
||||
pending: writableComputedRef(() => nuxtApp._asyncData[key.value]?.pending),
|
||||
status: writableComputedRef(() => nuxtApp._asyncData[key.value]?.status),
|
||||
error: writableComputedRef(() => nuxtApp._asyncData[key.value]?.error),
|
||||
refresh: (...args2) => {
|
||||
if (!nuxtApp._asyncData[key.value]?._init) {
|
||||
const initialFetch2 = createInitialFetch();
|
||||
return initialFetch2();
|
||||
}
|
||||
return nuxtApp._asyncData[key.value].execute(...args2);
|
||||
},
|
||||
execute: (...args2) => asyncReturn.refresh(...args2),
|
||||
clear: () => {
|
||||
const entry = nuxtApp._asyncData[key.value];
|
||||
if (entry?._abortController) {
|
||||
try {
|
||||
entry._abortController.abort(new DOMException("AsyncData aborted by user.", "AbortError"));
|
||||
} finally {
|
||||
entry._abortController = void 0;
|
||||
}
|
||||
}
|
||||
clearNuxtDataByKey(nuxtApp, key.value);
|
||||
}
|
||||
};
|
||||
const asyncDataPromise = Promise.resolve(nuxtApp._asyncDataPromises[key.value]).then(() => asyncReturn);
|
||||
Object.assign(asyncDataPromise, asyncReturn);
|
||||
return asyncDataPromise;
|
||||
}
|
||||
function writableComputedRef(getter) {
|
||||
return computed({
|
||||
get() {
|
||||
return getter()?.value;
|
||||
},
|
||||
set(value) {
|
||||
const ref2 = getter();
|
||||
if (ref2) {
|
||||
ref2.value = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
export function useLazyAsyncData(...args) {
|
||||
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
|
||||
if (_isAutoKeyNeeded(args[0], args[1])) {
|
||||
args.unshift(autoKey);
|
||||
}
|
||||
const [key, handler, options = {}] = args;
|
||||
if (import.meta.dev) {
|
||||
options._functionName ||= "useLazyAsyncData";
|
||||
}
|
||||
return useAsyncData(key, handler, { ...options, lazy: true }, null);
|
||||
}
|
||||
function _isAutoKeyNeeded(keyOrFetcher, fetcher) {
|
||||
if (typeof keyOrFetcher === "string") {
|
||||
return false;
|
||||
}
|
||||
if (typeof keyOrFetcher === "object" && keyOrFetcher !== null) {
|
||||
return false;
|
||||
}
|
||||
if (typeof keyOrFetcher === "function" && typeof fetcher === "function") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export function useNuxtData(key) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
if (!(key in nuxtApp.payload.data)) {
|
||||
nuxtApp.payload.data[key] = void 0;
|
||||
}
|
||||
if (nuxtApp._asyncData[key]) {
|
||||
const data = nuxtApp._asyncData[key];
|
||||
data._deps++;
|
||||
if (getCurrentScope()) {
|
||||
onScopeDispose(() => {
|
||||
data._deps--;
|
||||
if (data._deps === 0) {
|
||||
data?._off();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
data: computed({
|
||||
get() {
|
||||
return nuxtApp._asyncData[key]?.data.value ?? nuxtApp.payload.data[key];
|
||||
},
|
||||
set(value) {
|
||||
if (nuxtApp._asyncData[key]) {
|
||||
nuxtApp._asyncData[key].data.value = value;
|
||||
} else {
|
||||
nuxtApp.payload.data[key] = value;
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
export async function refreshNuxtData(keys) {
|
||||
if (import.meta.server) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
await new Promise((resolve) => onNuxtReady(resolve));
|
||||
const _keys = keys ? toArray(keys) : void 0;
|
||||
await useNuxtApp().hooks.callHookParallel("app:data:refresh", _keys);
|
||||
}
|
||||
export function clearNuxtData(keys) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const _allKeys = Object.keys(nuxtApp.payload.data);
|
||||
const _keys = !keys ? _allKeys : typeof keys === "function" ? _allKeys.filter(keys) : toArray(keys);
|
||||
for (const key of _keys) {
|
||||
clearNuxtDataByKey(nuxtApp, key);
|
||||
}
|
||||
}
|
||||
function clearNuxtDataByKey(nuxtApp, key) {
|
||||
if (key in nuxtApp.payload.data) {
|
||||
nuxtApp.payload.data[key] = void 0;
|
||||
}
|
||||
if (key in nuxtApp.payload._errors) {
|
||||
nuxtApp.payload._errors[key] = void 0;
|
||||
}
|
||||
if (nuxtApp._asyncData[key]) {
|
||||
nuxtApp._asyncData[key].data.value = unref(nuxtApp._asyncData[key]._default());
|
||||
nuxtApp._asyncData[key].error.value = void 0;
|
||||
if (pendingWhenIdle) {
|
||||
nuxtApp._asyncData[key].pending.value = false;
|
||||
}
|
||||
nuxtApp._asyncData[key].status.value = "idle";
|
||||
}
|
||||
if (key in nuxtApp._asyncDataPromises) {
|
||||
nuxtApp._asyncDataPromises[key] = void 0;
|
||||
}
|
||||
}
|
||||
function pick(obj, keys) {
|
||||
const newObj = {};
|
||||
for (const key of keys) {
|
||||
newObj[key] = obj[key];
|
||||
}
|
||||
return newObj;
|
||||
}
|
||||
function createAsyncData(nuxtApp, key, _handler, options, initialCachedData) {
|
||||
nuxtApp.payload._errors[key] ??= void 0;
|
||||
const hasCustomGetCachedData = options.getCachedData !== getDefaultCachedData;
|
||||
const handler = import.meta.client || !import.meta.prerender || !nuxtApp.ssrContext?.["~sharedPrerenderCache"] ? _handler : (nuxtApp2, options2) => {
|
||||
const value = nuxtApp2.ssrContext["~sharedPrerenderCache"].get(key);
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
const promise = Promise.resolve().then(() => nuxtApp2.runWithContext(() => _handler(nuxtApp2, options2)));
|
||||
nuxtApp2.ssrContext["~sharedPrerenderCache"].set(key, promise);
|
||||
return promise;
|
||||
};
|
||||
const _ref = options.deep ? ref : shallowRef;
|
||||
const hasCachedData = initialCachedData !== void 0;
|
||||
const unsubRefreshAsyncData = nuxtApp.hook("app:data:refresh", async (keys) => {
|
||||
if (!keys || keys.includes(key)) {
|
||||
await asyncData.execute({ cause: "refresh:hook" });
|
||||
}
|
||||
});
|
||||
const asyncData = {
|
||||
data: _ref(hasCachedData ? initialCachedData : options.default()),
|
||||
pending: pendingWhenIdle ? shallowRef(!hasCachedData) : computed(() => asyncData.status.value === "pending"),
|
||||
error: toRef(nuxtApp.payload._errors, key),
|
||||
status: shallowRef("idle"),
|
||||
execute: (...args) => {
|
||||
const [_opts, newValue = void 0] = args;
|
||||
const opts = _opts && newValue === void 0 && typeof _opts === "object" ? _opts : {};
|
||||
if (import.meta.dev && newValue !== void 0 && (!_opts || typeof _opts !== "object")) {
|
||||
console.warn(`[nuxt] [${options._functionName}] Do not pass \`execute\` directly to \`watch\`. Instead, use an inline function, such as \`watch(q, () => execute())\`.`);
|
||||
}
|
||||
if (nuxtApp._asyncDataPromises[key]) {
|
||||
if ((opts.dedupe ?? options.dedupe) === "defer") {
|
||||
return nuxtApp._asyncDataPromises[key];
|
||||
}
|
||||
}
|
||||
if (granularCachedData || opts.cause === "initial" || nuxtApp.isHydrating) {
|
||||
const cachedData = "cachedData" in opts ? opts.cachedData : options.getCachedData(key, nuxtApp, { cause: opts.cause ?? "refresh:manual" });
|
||||
if (cachedData !== void 0) {
|
||||
nuxtApp.payload.data[key] = asyncData.data.value = cachedData;
|
||||
asyncData.error.value = void 0;
|
||||
asyncData.status.value = "success";
|
||||
return Promise.resolve(cachedData);
|
||||
}
|
||||
}
|
||||
if (pendingWhenIdle) {
|
||||
asyncData.pending.value = true;
|
||||
}
|
||||
if (asyncData._abortController) {
|
||||
asyncData._abortController.abort(new DOMException("AsyncData request cancelled by deduplication", "AbortError"));
|
||||
}
|
||||
asyncData._abortController = new AbortController();
|
||||
asyncData.status.value = "pending";
|
||||
const cleanupController = new AbortController();
|
||||
const promise = new Promise(
|
||||
(resolve, reject) => {
|
||||
try {
|
||||
const timeout = opts.timeout ?? options.timeout;
|
||||
const mergedSignal = mergeAbortSignals([asyncData._abortController?.signal, opts?.signal], cleanupController.signal, timeout);
|
||||
if (mergedSignal.aborted) {
|
||||
const reason = mergedSignal.reason;
|
||||
reject(reason instanceof Error ? reason : new DOMException(String(reason ?? "Aborted"), "AbortError"));
|
||||
return;
|
||||
}
|
||||
mergedSignal.addEventListener("abort", () => {
|
||||
const reason = mergedSignal.reason;
|
||||
reject(reason instanceof Error ? reason : new DOMException(String(reason ?? "Aborted"), "AbortError"));
|
||||
}, { once: true, signal: cleanupController.signal });
|
||||
return Promise.resolve(handler(nuxtApp, { signal: mergedSignal })).then(resolve, reject);
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
}
|
||||
).then(async (_result) => {
|
||||
let result = _result;
|
||||
if (options.transform) {
|
||||
result = await options.transform(_result);
|
||||
}
|
||||
if (options.pick) {
|
||||
result = pick(result, options.pick);
|
||||
}
|
||||
if (import.meta.dev && import.meta.server && typeof result === "undefined") {
|
||||
const caller = getUserCaller();
|
||||
const explanation = caller ? ` (used at ${caller.source}:${caller.line}:${caller.column})` : "";
|
||||
console.warn(`[nuxt] \`${options._functionName || "useAsyncData"}${explanation}\` must return a value (it should not be \`undefined\`) or the request may be duplicated on the client side.`);
|
||||
}
|
||||
nuxtApp.payload.data[key] = result;
|
||||
asyncData.data.value = result;
|
||||
asyncData.error.value = void 0;
|
||||
asyncData.status.value = "success";
|
||||
}).catch((error) => {
|
||||
if (nuxtApp._asyncDataPromises[key] && nuxtApp._asyncDataPromises[key] !== promise) {
|
||||
return nuxtApp._asyncDataPromises[key];
|
||||
}
|
||||
if (asyncData._abortController?.signal.aborted) {
|
||||
return nuxtApp._asyncDataPromises[key];
|
||||
}
|
||||
if (typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError") {
|
||||
asyncData.status.value = "idle";
|
||||
return nuxtApp._asyncDataPromises[key];
|
||||
}
|
||||
asyncData.error.value = createError(error);
|
||||
asyncData.data.value = unref(options.default());
|
||||
asyncData.status.value = "error";
|
||||
}).finally(() => {
|
||||
if (pendingWhenIdle) {
|
||||
asyncData.pending.value = false;
|
||||
}
|
||||
cleanupController.abort();
|
||||
delete nuxtApp._asyncDataPromises[key];
|
||||
});
|
||||
nuxtApp._asyncDataPromises[key] = promise;
|
||||
return nuxtApp._asyncDataPromises[key];
|
||||
},
|
||||
_execute: debounce((...args) => asyncData.execute(...args), 0, { leading: true }),
|
||||
_default: options.default,
|
||||
_deps: 0,
|
||||
_init: true,
|
||||
_hash: import.meta.dev ? createHash(_handler, options) : void 0,
|
||||
_off: () => {
|
||||
unsubRefreshAsyncData();
|
||||
if (nuxtApp._asyncData[key]?._init) {
|
||||
nuxtApp._asyncData[key]._init = false;
|
||||
}
|
||||
if (purgeCachedData && !hasCustomGetCachedData) {
|
||||
nextTick(() => {
|
||||
if (!nuxtApp._asyncData[key]?._init) {
|
||||
clearNuxtDataByKey(nuxtApp, key);
|
||||
asyncData.execute = () => Promise.resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
return asyncData;
|
||||
}
|
||||
const getDefault = () => void 0;
|
||||
const getDefaultCachedData = (key, nuxtApp, ctx) => {
|
||||
if (nuxtApp.isHydrating) {
|
||||
return nuxtApp.payload.data[key];
|
||||
}
|
||||
if (ctx.cause !== "refresh:manual" && ctx.cause !== "refresh:hook") {
|
||||
return nuxtApp.static.data[key];
|
||||
}
|
||||
};
|
||||
function createHash(_handler, options) {
|
||||
return {
|
||||
handler: hash(_handler),
|
||||
transform: options.transform ? hash(options.transform) : void 0,
|
||||
pick: options.pick ? hash(options.pick) : void 0,
|
||||
getCachedData: options.getCachedData ? hash(options.getCachedData) : void 0
|
||||
};
|
||||
}
|
||||
function mergeAbortSignals(signals, cleanupSignal, timeout) {
|
||||
const list = signals.filter((s) => !!s);
|
||||
if (typeof timeout === "number" && timeout >= 0) {
|
||||
const timeoutSignal = AbortSignal.timeout?.(timeout);
|
||||
if (timeoutSignal) {
|
||||
list.push(timeoutSignal);
|
||||
}
|
||||
}
|
||||
if (AbortSignal.any) {
|
||||
return AbortSignal.any(list);
|
||||
}
|
||||
const controller = new AbortController();
|
||||
for (const sig of list) {
|
||||
if (sig.aborted) {
|
||||
const reason = sig.reason ?? new DOMException("Aborted", "AbortError");
|
||||
try {
|
||||
controller.abort(reason);
|
||||
} catch {
|
||||
controller.abort();
|
||||
}
|
||||
return controller.signal;
|
||||
}
|
||||
}
|
||||
const onAbort = () => {
|
||||
const abortedSignal = list.find((s) => s.aborted);
|
||||
const reason = abortedSignal?.reason ?? new DOMException("Aborted", "AbortError");
|
||||
try {
|
||||
controller.abort(reason);
|
||||
} catch {
|
||||
controller.abort();
|
||||
}
|
||||
};
|
||||
for (const sig of list) {
|
||||
sig.addEventListener?.("abort", onAbort, { once: true, signal: cleanupSignal });
|
||||
}
|
||||
return controller.signal;
|
||||
}
|
||||
25
node_modules/nuxt/dist/app/composables/chunk.d.ts
generated
vendored
Normal file
25
node_modules/nuxt/dist/app/composables/chunk.d.ts
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
export interface ReloadNuxtAppOptions {
|
||||
/**
|
||||
* Number of milliseconds in which to ignore future reload requests
|
||||
* @default {10000}
|
||||
*/
|
||||
ttl?: number;
|
||||
/**
|
||||
* Force a reload even if one has occurred within the previously specified TTL.
|
||||
* @default {false}
|
||||
*/
|
||||
force?: boolean;
|
||||
/**
|
||||
* Whether to dump the current Nuxt state to sessionStorage (as `nuxt:reload:state`).
|
||||
* @default {false}
|
||||
*/
|
||||
persistState?: boolean;
|
||||
/**
|
||||
* The path to reload. If this is different from the current window location it will
|
||||
* trigger a navigation and add an entry in the browser history.
|
||||
* @default {window.location.pathname}
|
||||
*/
|
||||
path?: string;
|
||||
}
|
||||
/** @since 3.3.0 */
|
||||
export declare function reloadNuxtApp(options?: ReloadNuxtAppOptions): void;
|
||||
30
node_modules/nuxt/dist/app/composables/chunk.js
generated
vendored
Normal file
30
node_modules/nuxt/dist/app/composables/chunk.js
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
import destr from "destr";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
export function reloadNuxtApp(options = {}) {
|
||||
if (import.meta.server) {
|
||||
return;
|
||||
}
|
||||
const path = options.path || window.location.pathname;
|
||||
let handledPath = {};
|
||||
try {
|
||||
handledPath = destr(sessionStorage.getItem("nuxt:reload") || "{}");
|
||||
} catch {
|
||||
}
|
||||
if (options.force || handledPath?.path !== path || handledPath?.expires < Date.now()) {
|
||||
try {
|
||||
sessionStorage.setItem("nuxt:reload", JSON.stringify({ path, expires: Date.now() + (options.ttl ?? 1e4) }));
|
||||
} catch {
|
||||
}
|
||||
if (options.persistState) {
|
||||
try {
|
||||
sessionStorage.setItem("nuxt:reload:state", JSON.stringify({ state: useNuxtApp().payload.state }));
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
if (window.location.pathname !== path) {
|
||||
window.location.href = path;
|
||||
} else {
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
}
|
||||
4
node_modules/nuxt/dist/app/composables/component.d.ts
generated
vendored
Normal file
4
node_modules/nuxt/dist/app/composables/component.d.ts
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
import type { defineComponent } from 'vue';
|
||||
export declare const NuxtComponentIndicator = "__nuxt_component";
|
||||
/** @since 3.0.0 */
|
||||
export declare const defineNuxtComponent: typeof defineComponent;
|
||||
81
node_modules/nuxt/dist/app/composables/component.js
generated
vendored
Normal file
81
node_modules/nuxt/dist/app/composables/component.js
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
import { computed, getCurrentInstance } from "vue";
|
||||
import { hash } from "ohash";
|
||||
import { getNuxtAppCtx, useNuxtApp } from "../nuxt.js";
|
||||
import { useHead } from "./head.js";
|
||||
import { useAsyncData } from "./asyncData.js";
|
||||
import { useRoute } from "./router.js";
|
||||
import { createError } from "./error.js";
|
||||
export const NuxtComponentIndicator = "__nuxt_component";
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
function getFetchKey() {
|
||||
const vm = getCurrentInstance();
|
||||
const route = useRoute();
|
||||
const { _fetchKeyBase } = vm.proxy.$options;
|
||||
return hash([
|
||||
_fetchKeyBase,
|
||||
route.path,
|
||||
route.query,
|
||||
route.matched.findIndex((r) => Object.values(r.components || {}).includes(vm.type))
|
||||
]);
|
||||
}
|
||||
async function runLegacyAsyncData(res, fn) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const { fetchKey } = getCurrentInstance().proxy.$options;
|
||||
const key = (typeof fetchKey === "function" ? fetchKey(() => "") : fetchKey) || /* @__PURE__ */ getFetchKey();
|
||||
const { data, error } = await useAsyncData(`options:asyncdata:${key}`, () => import.meta.server ? nuxtApp.runWithContext(() => fn(nuxtApp)) : fn(nuxtApp));
|
||||
if (error.value) {
|
||||
throw createError(error.value);
|
||||
}
|
||||
if (data.value && typeof data.value === "object") {
|
||||
const _res = await res;
|
||||
for (const key2 in data.value) {
|
||||
_res[key2] = computed({
|
||||
get: () => data.value?.[key2],
|
||||
set(v) {
|
||||
data.value = data.value ? { ...data.value, [key2]: v } : { [key2]: v };
|
||||
}
|
||||
});
|
||||
}
|
||||
} else if (import.meta.dev) {
|
||||
console.warn("[nuxt] asyncData should return an object", data);
|
||||
}
|
||||
}
|
||||
export const defineNuxtComponent = /* @__NO_SIDE_EFFECTS__ */ function defineNuxtComponent2(...args) {
|
||||
const [options, key] = args;
|
||||
const { setup } = options;
|
||||
if (!setup && !options.asyncData && !options.head) {
|
||||
return {
|
||||
[NuxtComponentIndicator]: true,
|
||||
...options
|
||||
};
|
||||
}
|
||||
return {
|
||||
[NuxtComponentIndicator]: true,
|
||||
_fetchKeyBase: key,
|
||||
...options,
|
||||
setup(props, ctx) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
let res = {};
|
||||
if (setup) {
|
||||
const fn = () => Promise.resolve(setup(props, ctx)).then((r) => r || {});
|
||||
const nuxtAppCtx = getNuxtAppCtx(nuxtApp._id);
|
||||
if (import.meta.server) {
|
||||
res = nuxtAppCtx.callAsync(nuxtApp, fn);
|
||||
} else {
|
||||
nuxtAppCtx.set(nuxtApp);
|
||||
res = fn();
|
||||
}
|
||||
}
|
||||
const promises = [];
|
||||
if (options.asyncData) {
|
||||
promises.push(runLegacyAsyncData(res, options.asyncData));
|
||||
}
|
||||
if (options.head) {
|
||||
useHead(typeof options.head === "function" ? () => options.head(nuxtApp) : options.head);
|
||||
}
|
||||
return Promise.resolve(res).then(() => Promise.all(promises)).then(() => res).finally(() => {
|
||||
promises.length = 0;
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
22
node_modules/nuxt/dist/app/composables/cookie.d.ts
generated
vendored
Normal file
22
node_modules/nuxt/dist/app/composables/cookie.d.ts
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
import type { Ref } from 'vue';
|
||||
import type { CookieParseOptions, CookieSerializeOptions } from 'cookie-es';
|
||||
type _CookieOptions = Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'>;
|
||||
export interface CookieOptions<T = any> extends _CookieOptions {
|
||||
decode?(value: string): T;
|
||||
encode?(value: T): string;
|
||||
default?: () => T | Ref<T>;
|
||||
watch?: boolean | 'shallow';
|
||||
readonly?: boolean;
|
||||
}
|
||||
export interface CookieRef<T> extends Ref<T> {
|
||||
}
|
||||
/** @since 3.0.0 */
|
||||
export declare function useCookie<T = string | null | undefined>(name: string, _opts?: CookieOptions<T> & {
|
||||
readonly?: false;
|
||||
}): CookieRef<T>;
|
||||
export declare function useCookie<T = string | null | undefined>(name: string, _opts: CookieOptions<T> & {
|
||||
readonly: true;
|
||||
}): Readonly<CookieRef<T>>;
|
||||
/** @since 3.10.0 */
|
||||
export declare function refreshCookie(name: string): void;
|
||||
export {};
|
||||
212
node_modules/nuxt/dist/app/composables/cookie.js
generated
vendored
Normal file
212
node_modules/nuxt/dist/app/composables/cookie.js
generated
vendored
Normal file
@@ -0,0 +1,212 @@
|
||||
import { customRef, getCurrentScope, nextTick, onScopeDispose, ref, watch } from "vue";
|
||||
import { parse, serialize } from "cookie-es";
|
||||
import { deleteCookie, getCookie, getRequestHeader, setCookie } from "h3";
|
||||
import destr from "destr";
|
||||
import { isEqual } from "ohash";
|
||||
import { klona } from "klona";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { useRequestEvent } from "./ssr.js";
|
||||
import { cookieStore } from "#build/nuxt.config.mjs";
|
||||
const CookieDefaults = {
|
||||
path: "/",
|
||||
watch: true,
|
||||
decode: (val) => {
|
||||
const decoded = decodeURIComponent(val);
|
||||
const parsed = destr(decoded);
|
||||
if (typeof parsed === "number" && (!Number.isFinite(parsed) || String(parsed) !== decoded)) {
|
||||
return decoded;
|
||||
}
|
||||
return parsed;
|
||||
},
|
||||
encode: (val) => encodeURIComponent(typeof val === "string" ? val : JSON.stringify(val))
|
||||
};
|
||||
const store = import.meta.client && cookieStore ? globalThis.cookieStore : void 0;
|
||||
export function useCookie(name, _opts) {
|
||||
const opts = { ...CookieDefaults, ..._opts };
|
||||
opts.filter ??= (key) => key === name;
|
||||
const cookies = readRawCookies(opts) || {};
|
||||
let delay;
|
||||
if (opts.maxAge !== void 0) {
|
||||
delay = opts.maxAge * 1e3;
|
||||
} else if (opts.expires) {
|
||||
delay = opts.expires.getTime() - Date.now();
|
||||
}
|
||||
const hasExpired = delay !== void 0 && delay <= 0;
|
||||
const shouldSetInitialClientCookie = import.meta.client && (hasExpired || cookies[name] === void 0 || cookies[name] === null);
|
||||
const cookieValue = klona(hasExpired ? void 0 : cookies[name] ?? opts.default?.());
|
||||
const cookie = import.meta.client && delay && !hasExpired ? cookieRef(cookieValue, delay, opts.watch && opts.watch !== "shallow") : ref(cookieValue);
|
||||
if (import.meta.dev && hasExpired) {
|
||||
console.warn(`[nuxt] not setting cookie \`${name}\` as it has already expired.`);
|
||||
}
|
||||
if (import.meta.client) {
|
||||
let channel = null;
|
||||
try {
|
||||
if (!store && typeof BroadcastChannel !== "undefined") {
|
||||
channel = new BroadcastChannel(`nuxt:cookies:${name}`);
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
const callback = (force = false) => {
|
||||
if (!force) {
|
||||
if (opts.readonly || isEqual(cookie.value, cookies[name])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
writeClientCookie(name, cookie.value, opts);
|
||||
cookies[name] = klona(cookie.value);
|
||||
channel?.postMessage({ value: opts.encode(cookie.value) });
|
||||
};
|
||||
const handleChange = (data) => {
|
||||
const value = data.refresh ? readRawCookies(opts)?.[name] : opts.decode(data.value);
|
||||
watchPaused = true;
|
||||
cookie.value = value;
|
||||
cookies[name] = klona(value);
|
||||
nextTick(() => {
|
||||
watchPaused = false;
|
||||
});
|
||||
};
|
||||
let watchPaused = false;
|
||||
const hasScope = !!getCurrentScope();
|
||||
if (hasScope) {
|
||||
onScopeDispose(() => {
|
||||
watchPaused = true;
|
||||
callback();
|
||||
channel?.close();
|
||||
});
|
||||
}
|
||||
if (store) {
|
||||
const changeHandler = (event) => {
|
||||
const changedCookie = event.changed.find((c) => c.name === name);
|
||||
const removedCookie = event.deleted.find((c) => c.name === name);
|
||||
if (changedCookie) {
|
||||
handleChange({ value: changedCookie.value });
|
||||
}
|
||||
if (removedCookie) {
|
||||
handleChange({ value: null });
|
||||
}
|
||||
};
|
||||
store.addEventListener("change", changeHandler);
|
||||
if (hasScope) {
|
||||
onScopeDispose(() => store.removeEventListener("change", changeHandler));
|
||||
}
|
||||
} else if (channel) {
|
||||
channel.onmessage = ({ data }) => handleChange(data);
|
||||
}
|
||||
if (opts.watch) {
|
||||
watch(
|
||||
cookie,
|
||||
() => {
|
||||
if (watchPaused) {
|
||||
return;
|
||||
}
|
||||
callback();
|
||||
},
|
||||
{ deep: opts.watch !== "shallow" }
|
||||
);
|
||||
}
|
||||
if (shouldSetInitialClientCookie) {
|
||||
callback(shouldSetInitialClientCookie);
|
||||
}
|
||||
} else if (import.meta.server) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const writeFinalCookieValue = () => {
|
||||
if (opts.readonly || isEqual(cookie.value, cookies[name])) {
|
||||
return;
|
||||
}
|
||||
nuxtApp._cookies ||= {};
|
||||
if (name in nuxtApp._cookies) {
|
||||
if (isEqual(cookie.value, nuxtApp._cookies[name])) {
|
||||
return;
|
||||
}
|
||||
if (import.meta.dev) {
|
||||
console.warn(`[nuxt] cookie \`${name}\` was previously set to \`${opts.encode(nuxtApp._cookies[name])}\` and is being overridden to \`${opts.encode(cookie.value)}\`. This may cause unexpected issues.`);
|
||||
}
|
||||
}
|
||||
nuxtApp._cookies[name] = cookie.value;
|
||||
writeServerCookie(useRequestEvent(nuxtApp), name, cookie.value, opts);
|
||||
};
|
||||
const unhook = nuxtApp.hooks.hookOnce("app:rendered", writeFinalCookieValue);
|
||||
nuxtApp.hooks.hookOnce("app:error", () => {
|
||||
unhook();
|
||||
return writeFinalCookieValue();
|
||||
});
|
||||
}
|
||||
return cookie;
|
||||
}
|
||||
export function refreshCookie(name) {
|
||||
if (import.meta.server || store || typeof BroadcastChannel === "undefined") {
|
||||
return;
|
||||
}
|
||||
new BroadcastChannel(`nuxt:cookies:${name}`)?.postMessage({ refresh: true });
|
||||
}
|
||||
function readRawCookies(opts = {}) {
|
||||
if (import.meta.server) {
|
||||
return parse(getRequestHeader(useRequestEvent(), "cookie") || "", opts);
|
||||
} else if (import.meta.client) {
|
||||
return parse(document.cookie, opts);
|
||||
}
|
||||
}
|
||||
function serializeCookie(name, value, opts = {}) {
|
||||
if (value === null || value === void 0) {
|
||||
return serialize(name, value, { ...opts, maxAge: -1 });
|
||||
}
|
||||
return serialize(name, value, opts);
|
||||
}
|
||||
function writeClientCookie(name, value, opts = {}) {
|
||||
if (import.meta.client) {
|
||||
document.cookie = serializeCookie(name, value, opts);
|
||||
}
|
||||
}
|
||||
function writeServerCookie(event, name, value, opts = {}) {
|
||||
if (event) {
|
||||
if (value !== null && value !== void 0) {
|
||||
return setCookie(event, name, value, opts);
|
||||
}
|
||||
if (getCookie(event, name) !== void 0) {
|
||||
return deleteCookie(event, name, opts);
|
||||
}
|
||||
}
|
||||
}
|
||||
const MAX_TIMEOUT_DELAY = 2147483647;
|
||||
function cookieRef(value, delay, shouldWatch) {
|
||||
let timeout;
|
||||
let unsubscribe;
|
||||
let elapsed = 0;
|
||||
const internalRef = shouldWatch ? ref(value) : { value };
|
||||
if (getCurrentScope()) {
|
||||
onScopeDispose(() => {
|
||||
unsubscribe?.();
|
||||
clearTimeout(timeout);
|
||||
});
|
||||
}
|
||||
return customRef((track, trigger) => {
|
||||
if (shouldWatch) {
|
||||
unsubscribe = watch(internalRef, trigger);
|
||||
}
|
||||
function createExpirationTimeout() {
|
||||
elapsed = 0;
|
||||
clearTimeout(timeout);
|
||||
const timeRemaining = delay - elapsed;
|
||||
const timeoutLength = timeRemaining < MAX_TIMEOUT_DELAY ? timeRemaining : MAX_TIMEOUT_DELAY;
|
||||
timeout = setTimeout(() => {
|
||||
elapsed += timeoutLength;
|
||||
if (elapsed < delay) {
|
||||
return createExpirationTimeout();
|
||||
}
|
||||
internalRef.value = void 0;
|
||||
trigger();
|
||||
}, timeoutLength);
|
||||
}
|
||||
return {
|
||||
get() {
|
||||
track();
|
||||
return internalRef.value;
|
||||
},
|
||||
set(newValue) {
|
||||
createExpirationTimeout();
|
||||
internalRef.value = newValue;
|
||||
trigger();
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
28
node_modules/nuxt/dist/app/composables/error.d.ts
generated
vendored
Normal file
28
node_modules/nuxt/dist/app/composables/error.d.ts
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { H3Error } from 'h3';
|
||||
import type { Ref } from 'vue';
|
||||
import type { NuxtPayload } from '../nuxt.js';
|
||||
export declare const NUXT_ERROR_SIGNATURE = "__nuxt_error";
|
||||
/** @since 3.0.0 */
|
||||
export declare const useError: () => Ref<NuxtPayload["error"]>;
|
||||
export interface NuxtError<DataT = unknown> extends Omit<H3Error<DataT>, 'statusCode' | 'statusMessage'>, Error {
|
||||
error?: true;
|
||||
status?: number;
|
||||
statusText?: string;
|
||||
/** @deprecated Use `status` */
|
||||
statusCode?: H3Error<DataT>['statusCode'];
|
||||
/** @deprecated Use `statusText` */
|
||||
statusMessage?: H3Error<DataT>['statusMessage'];
|
||||
}
|
||||
/** @since 3.0.0 */
|
||||
export declare const showError: <DataT = unknown>(error: string | Error | (Partial<NuxtError<DataT>> & {
|
||||
status?: number;
|
||||
statusText?: string;
|
||||
})) => NuxtError<DataT>;
|
||||
/** @since 3.0.0 */
|
||||
export declare const clearError: (options?: {
|
||||
redirect?: string;
|
||||
}) => Promise<void>;
|
||||
/** @since 3.0.0 */
|
||||
export declare const isNuxtError: <DataT = unknown>(error: unknown) => error is NuxtError<DataT>;
|
||||
/** @since 3.0.0 */
|
||||
export declare const createError: <DataT = unknown>(error: string | Error | Partial<NuxtError<DataT>>) => NuxtError<DataT>;
|
||||
52
node_modules/nuxt/dist/app/composables/error.js
generated
vendored
Normal file
52
node_modules/nuxt/dist/app/composables/error.js
generated
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
import { createError as createH3Error } from "h3";
|
||||
import { toRef } from "vue";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { useRouter } from "./router.js";
|
||||
export const NUXT_ERROR_SIGNATURE = "__nuxt_error";
|
||||
export const useError = /* @__NO_SIDE_EFFECTS__ */ () => toRef(useNuxtApp().payload, "error");
|
||||
export const showError = (error) => {
|
||||
const nuxtError = createError(error);
|
||||
try {
|
||||
const error2 = /* @__PURE__ */ useError();
|
||||
if (import.meta.client) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
nuxtApp.hooks.callHook("app:error", nuxtError);
|
||||
}
|
||||
error2.value ||= nuxtError;
|
||||
} catch {
|
||||
throw nuxtError;
|
||||
}
|
||||
return nuxtError;
|
||||
};
|
||||
export const clearError = async (options = {}) => {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const error = /* @__PURE__ */ useError();
|
||||
nuxtApp.callHook("app:error:cleared", options);
|
||||
if (options.redirect) {
|
||||
await useRouter().replace(options.redirect);
|
||||
}
|
||||
error.value = void 0;
|
||||
};
|
||||
export const isNuxtError = (error) => !!error && typeof error === "object" && NUXT_ERROR_SIGNATURE in error;
|
||||
export const createError = (error) => {
|
||||
if (typeof error !== "string" && error.statusText) {
|
||||
error.message ??= error.statusText;
|
||||
}
|
||||
const nuxtError = createH3Error(error);
|
||||
Object.defineProperty(nuxtError, NUXT_ERROR_SIGNATURE, {
|
||||
value: true,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
Object.defineProperty(nuxtError, "status", {
|
||||
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
||||
get: () => nuxtError.statusCode,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(nuxtError, "statusText", {
|
||||
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
||||
get: () => nuxtError.statusMessage,
|
||||
configurable: true
|
||||
});
|
||||
return nuxtError;
|
||||
};
|
||||
37
node_modules/nuxt/dist/app/composables/fetch.d.ts
generated
vendored
Normal file
37
node_modules/nuxt/dist/app/composables/fetch.d.ts
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { FetchError, FetchOptions, ResponseType as _ResponseType } from 'ofetch';
|
||||
import type { NitroFetchRequest, TypedInternalResponse, AvailableRouterMethod as _AvailableRouterMethod } from 'nitropack/types';
|
||||
import type { MaybeRefOrGetter, Ref } from 'vue';
|
||||
import type { AsyncData, AsyncDataOptions, KeysOf, MultiWatchSources, PickFrom } from './asyncData.js';
|
||||
type AvailableRouterMethod<R extends NitroFetchRequest> = _AvailableRouterMethod<R> | Uppercase<_AvailableRouterMethod<R>>;
|
||||
export type FetchResult<ReqT extends NitroFetchRequest, M extends AvailableRouterMethod<ReqT>> = TypedInternalResponse<ReqT, unknown, Lowercase<M>>;
|
||||
type ComputedOptions<T extends Record<string, any>> = {
|
||||
[K in keyof T]: T[K] extends Function ? T[K] : ComputedOptions<T[K]> | Ref<T[K]> | T[K];
|
||||
};
|
||||
interface NitroFetchOptions<R extends NitroFetchRequest, M extends AvailableRouterMethod<R> = AvailableRouterMethod<R>, DataT = any> extends FetchOptions<_ResponseType, DataT> {
|
||||
method?: M;
|
||||
}
|
||||
type ComputedFetchOptions<R extends NitroFetchRequest, M extends AvailableRouterMethod<R>, DataT = any> = ComputedOptions<NitroFetchOptions<R, M, DataT>>;
|
||||
export interface UseFetchOptions<ResT, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined, R extends NitroFetchRequest = string & {}, M extends AvailableRouterMethod<R> = AvailableRouterMethod<R>> extends Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'watch'>, Omit<ComputedFetchOptions<R, M, DataT>, 'timeout'> {
|
||||
key?: MaybeRefOrGetter<string>;
|
||||
$fetch?: typeof globalThis.$fetch;
|
||||
watch?: MultiWatchSources | false;
|
||||
}
|
||||
/**
|
||||
* Fetch data from an API endpoint with an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/4.x/api/composables/use-fetch}
|
||||
* @since 3.0.0
|
||||
* @param request The URL to fetch
|
||||
* @param opts extends $fetch options and useAsyncData options
|
||||
*/
|
||||
export declare function useFetch<ResT = void, ErrorT = FetchError, ReqT extends NitroFetchRequest = NitroFetchRequest, Method extends AvailableRouterMethod<ReqT> = ResT extends void ? 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT> : AvailableRouterMethod<ReqT>, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, DataT = _ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(request: Ref<ReqT> | ReqT | (() => ReqT), opts?: UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>;
|
||||
export declare function useFetch<ResT = void, ErrorT = FetchError, ReqT extends NitroFetchRequest = NitroFetchRequest, Method extends AvailableRouterMethod<ReqT> = ResT extends void ? 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT> : AvailableRouterMethod<ReqT>, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, DataT = _ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(request: Ref<ReqT> | ReqT | (() => ReqT), opts?: UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>;
|
||||
/**
|
||||
* Fetch data from an API endpoint with an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/4.x/api/composables/use-lazy-fetch}
|
||||
* @since 3.0.0
|
||||
* @param request The URL to fetch
|
||||
* @param opts extends $fetch options and useAsyncData options
|
||||
*/
|
||||
export declare function useLazyFetch<ResT = void, ErrorT = FetchError, ReqT extends NitroFetchRequest = NitroFetchRequest, Method extends AvailableRouterMethod<ReqT> = ResT extends void ? 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT> : AvailableRouterMethod<ReqT>, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, DataT = _ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = undefined>(request: Ref<ReqT> | ReqT | (() => ReqT), opts?: Omit<UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>, 'lazy'>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>;
|
||||
export declare function useLazyFetch<ResT = void, ErrorT = FetchError, ReqT extends NitroFetchRequest = NitroFetchRequest, Method extends AvailableRouterMethod<ReqT> = ResT extends void ? 'get' extends AvailableRouterMethod<ReqT> ? 'get' : AvailableRouterMethod<ReqT> : AvailableRouterMethod<ReqT>, _ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT, DataT = _ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DataT>(request: Ref<ReqT> | ReqT | (() => ReqT), opts?: Omit<UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>, 'lazy'>): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>;
|
||||
export {};
|
||||
123
node_modules/nuxt/dist/app/composables/fetch.js
generated
vendored
Normal file
123
node_modules/nuxt/dist/app/composables/fetch.js
generated
vendored
Normal file
@@ -0,0 +1,123 @@
|
||||
import { computed, reactive, toValue, watch } from "vue";
|
||||
import { hash } from "ohash";
|
||||
import { isPlainObject } from "@vue/shared";
|
||||
import { useRequestFetch } from "./ssr.js";
|
||||
import { useAsyncData } from "./asyncData.js";
|
||||
import { alwaysRunFetchOnKeyChange, fetchDefaults } from "#build/nuxt.config.mjs";
|
||||
export function useFetch(request, arg1, arg2) {
|
||||
const [opts = {}, autoKey] = typeof arg1 === "string" ? [{}, arg1] : [arg1, arg2];
|
||||
const _request = computed(() => toValue(request));
|
||||
const key = computed(() => toValue(opts.key) || "$f" + hash([autoKey, typeof _request.value === "string" ? _request.value : "", ...generateOptionSegments(opts)]));
|
||||
if (!opts.baseURL && typeof _request.value === "string" && (_request.value[0] === "/" && _request.value[1] === "/")) {
|
||||
throw new Error('[nuxt] [useFetch] the request URL must not start with "//".');
|
||||
}
|
||||
const {
|
||||
server,
|
||||
lazy,
|
||||
default: defaultFn,
|
||||
transform,
|
||||
pick,
|
||||
watch: watchSources,
|
||||
immediate,
|
||||
getCachedData,
|
||||
deep,
|
||||
dedupe,
|
||||
timeout,
|
||||
...fetchOptions
|
||||
} = opts;
|
||||
const _fetchOptions = reactive({
|
||||
...fetchDefaults,
|
||||
...fetchOptions,
|
||||
cache: typeof opts.cache === "boolean" ? void 0 : opts.cache
|
||||
});
|
||||
const _asyncDataOptions = {
|
||||
server,
|
||||
lazy,
|
||||
default: defaultFn,
|
||||
transform,
|
||||
pick,
|
||||
immediate,
|
||||
getCachedData,
|
||||
deep,
|
||||
dedupe,
|
||||
timeout,
|
||||
watch: watchSources === false ? [] : [...watchSources || [], _fetchOptions]
|
||||
};
|
||||
if (import.meta.dev) {
|
||||
_asyncDataOptions._functionName ||= "useFetch";
|
||||
}
|
||||
if (alwaysRunFetchOnKeyChange && !immediate) {
|
||||
let setImmediate = function() {
|
||||
_asyncDataOptions.immediate = true;
|
||||
};
|
||||
watch(key, setImmediate, { flush: "sync", once: true });
|
||||
watch([...watchSources || [], _fetchOptions], setImmediate, { flush: "sync", once: true });
|
||||
}
|
||||
const asyncData = useAsyncData(watchSources === false ? key.value : key, (_, { signal }) => {
|
||||
let _$fetch = opts.$fetch || globalThis.$fetch;
|
||||
if (import.meta.server && !opts.$fetch) {
|
||||
const isLocalFetch = typeof _request.value === "string" && _request.value[0] === "/" && (!toValue(opts.baseURL) || toValue(opts.baseURL)[0] === "/");
|
||||
if (isLocalFetch) {
|
||||
_$fetch = useRequestFetch();
|
||||
}
|
||||
}
|
||||
return _$fetch(_request.value, { signal, ..._fetchOptions });
|
||||
}, _asyncDataOptions);
|
||||
return asyncData;
|
||||
}
|
||||
export function useLazyFetch(request, arg1, arg2) {
|
||||
const [opts = {}, autoKey] = typeof arg1 === "string" ? [{}, arg1] : [arg1, arg2];
|
||||
if (import.meta.dev) {
|
||||
opts._functionName ||= "useLazyFetch";
|
||||
}
|
||||
return useFetch(
|
||||
request,
|
||||
{
|
||||
...opts,
|
||||
lazy: true
|
||||
},
|
||||
// @ts-expect-error we pass an extra argument with the resolved auto-key to prevent another from being injected
|
||||
autoKey
|
||||
);
|
||||
}
|
||||
function generateOptionSegments(opts) {
|
||||
const segments = [
|
||||
toValue(opts.method)?.toUpperCase() || "GET",
|
||||
toValue(opts.baseURL)
|
||||
];
|
||||
for (const _obj of [opts.query || opts.params]) {
|
||||
const obj = toValue(_obj);
|
||||
if (!obj) {
|
||||
continue;
|
||||
}
|
||||
const unwrapped = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
unwrapped[toValue(key)] = toValue(value);
|
||||
}
|
||||
segments.push(unwrapped);
|
||||
}
|
||||
if (opts.body) {
|
||||
const value = toValue(opts.body);
|
||||
if (!value) {
|
||||
segments.push(hash(value));
|
||||
} else if (value instanceof ArrayBuffer) {
|
||||
segments.push(hash(Object.fromEntries([...new Uint8Array(value).entries()].map(([k, v]) => [k, v.toString()]))));
|
||||
} else if (value instanceof FormData) {
|
||||
const obj = {};
|
||||
for (const entry of value.entries()) {
|
||||
const [key, val] = entry;
|
||||
obj[key] = val instanceof File ? val.name : val;
|
||||
}
|
||||
segments.push(hash(obj));
|
||||
} else if (isPlainObject(value)) {
|
||||
segments.push(hash(reactive(value)));
|
||||
} else {
|
||||
try {
|
||||
segments.push(hash(value));
|
||||
} catch {
|
||||
console.warn("[useFetch] Failed to hash body", value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
1
node_modules/nuxt/dist/app/composables/head.d.ts
generated
vendored
Normal file
1
node_modules/nuxt/dist/app/composables/head.d.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export { injectHead, useHead, useServerHead, useSeoMeta, useServerSeoMeta, useHeadSafe, useServerHeadSafe } from '#unhead/composables';
|
||||
1
node_modules/nuxt/dist/app/composables/head.js
generated
vendored
Normal file
1
node_modules/nuxt/dist/app/composables/head.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export { injectHead, useHead, useServerHead, useSeoMeta, useServerSeoMeta, useHeadSafe, useServerHeadSafe } from "#unhead/composables";
|
||||
9
node_modules/nuxt/dist/app/composables/hydrate.d.ts
generated
vendored
Normal file
9
node_modules/nuxt/dist/app/composables/hydrate.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { NuxtPayload } from '../nuxt.js';
|
||||
/**
|
||||
* Allows full control of the hydration cycle to set and receive data from the server.
|
||||
* @param key a unique key to identify the data in the Nuxt payload
|
||||
* @param get a function that returns the value to set the initial data
|
||||
* @param set a function that will receive the data on the client-side
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export declare const useHydration: <K extends keyof NuxtPayload, T = NuxtPayload[K]>(key: K, get: () => T, set: (value: T) => void) => void;
|
||||
14
node_modules/nuxt/dist/app/composables/hydrate.js
generated
vendored
Normal file
14
node_modules/nuxt/dist/app/composables/hydrate.js
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
export const useHydration = (key, get, set) => {
|
||||
const nuxtApp = useNuxtApp();
|
||||
if (import.meta.server) {
|
||||
nuxtApp.hooks.hook("app:rendered", () => {
|
||||
nuxtApp.payload[key] = get();
|
||||
});
|
||||
}
|
||||
if (import.meta.client) {
|
||||
nuxtApp.hooks.hook("app:created", () => {
|
||||
set(nuxtApp.payload[key]);
|
||||
});
|
||||
}
|
||||
};
|
||||
3
node_modules/nuxt/dist/app/composables/id.d.ts
generated
vendored
Normal file
3
node_modules/nuxt/dist/app/composables/id.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import { useId as _useId } from 'vue';
|
||||
/** @deprecated Use `useId` from `vue` */
|
||||
export declare const useId: typeof _useId;
|
||||
2
node_modules/nuxt/dist/app/composables/id.js
generated
vendored
Normal file
2
node_modules/nuxt/dist/app/composables/id.js
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import { useId as _useId } from "vue";
|
||||
export const useId = _useId;
|
||||
29
node_modules/nuxt/dist/app/composables/index.d.ts
generated
vendored
Normal file
29
node_modules/nuxt/dist/app/composables/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
export { defineNuxtComponent } from './component.js';
|
||||
export { useAsyncData, useLazyAsyncData, useNuxtData, refreshNuxtData, clearNuxtData } from './asyncData.js';
|
||||
export type { AsyncDataOptions, AsyncData, AsyncDataRequestStatus } from './asyncData.js';
|
||||
export { useHydration } from './hydrate.js';
|
||||
export { callOnce } from './once.js';
|
||||
export { useState, clearNuxtState } from './state.js';
|
||||
export { clearError, createError, isNuxtError, showError, useError } from './error.js';
|
||||
export type { NuxtError } from './error.js';
|
||||
export { useFetch, useLazyFetch } from './fetch.js';
|
||||
export type { FetchResult, UseFetchOptions } from './fetch.js';
|
||||
export { useCookie, refreshCookie } from './cookie.js';
|
||||
export type { CookieOptions, CookieRef } from './cookie.js';
|
||||
export { onPrehydrate, prerenderRoutes, useRequestHeaders, useRequestEvent, useRequestFetch, setResponseStatus, useResponseHeader } from './ssr.js';
|
||||
export { onNuxtReady } from './ready.js';
|
||||
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from './router.js';
|
||||
export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router.js';
|
||||
export { preloadComponents, prefetchComponents, preloadRouteComponents } from './preload.js';
|
||||
export { isPrerendered, loadPayload, preloadPayload, definePayloadReducer, definePayloadReviver } from './payload.js';
|
||||
export { getAppManifest, getRouteRules } from './manifest.js';
|
||||
export type { NuxtAppManifest, NuxtAppManifestMeta } from './manifest.js';
|
||||
export type { ReloadNuxtAppOptions } from './chunk.js';
|
||||
export { reloadNuxtApp } from './chunk.js';
|
||||
export { useRequestURL } from './url.js';
|
||||
export { usePreviewMode } from './preview.js';
|
||||
export { useId } from './id.js';
|
||||
export { useRouteAnnouncer } from './route-announcer.js';
|
||||
export type { Politeness } from './route-announcer.js';
|
||||
export { useRuntimeHook } from './runtime-hook.js';
|
||||
export { injectHead, useHead, useHeadSafe, useSeoMeta, useServerHead, useServerHeadSafe, useServerSeoMeta } from './head.js';
|
||||
21
node_modules/nuxt/dist/app/composables/index.js
generated
vendored
Normal file
21
node_modules/nuxt/dist/app/composables/index.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
export { defineNuxtComponent } from "./component.js";
|
||||
export { useAsyncData, useLazyAsyncData, useNuxtData, refreshNuxtData, clearNuxtData } from "./asyncData.js";
|
||||
export { useHydration } from "./hydrate.js";
|
||||
export { callOnce } from "./once.js";
|
||||
export { useState, clearNuxtState } from "./state.js";
|
||||
export { clearError, createError, isNuxtError, showError, useError } from "./error.js";
|
||||
export { useFetch, useLazyFetch } from "./fetch.js";
|
||||
export { useCookie, refreshCookie } from "./cookie.js";
|
||||
export { onPrehydrate, prerenderRoutes, useRequestHeaders, useRequestEvent, useRequestFetch, setResponseStatus, useResponseHeader } from "./ssr.js";
|
||||
export { onNuxtReady } from "./ready.js";
|
||||
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from "./router.js";
|
||||
export { preloadComponents, prefetchComponents, preloadRouteComponents } from "./preload.js";
|
||||
export { isPrerendered, loadPayload, preloadPayload, definePayloadReducer, definePayloadReviver } from "./payload.js";
|
||||
export { getAppManifest, getRouteRules } from "./manifest.js";
|
||||
export { reloadNuxtApp } from "./chunk.js";
|
||||
export { useRequestURL } from "./url.js";
|
||||
export { usePreviewMode } from "./preview.js";
|
||||
export { useId } from "./id.js";
|
||||
export { useRouteAnnouncer } from "./route-announcer.js";
|
||||
export { useRuntimeHook } from "./runtime-hook.js";
|
||||
export { injectHead, useHead, useHeadSafe, useSeoMeta, useServerHead, useServerHeadSafe, useServerSeoMeta } from "./head.js";
|
||||
40
node_modules/nuxt/dist/app/composables/lazy-hydration.d.ts
generated
vendored
Normal file
40
node_modules/nuxt/dist/app/composables/lazy-hydration.d.ts
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
import type { AsyncComponentLoader, Component, ComponentPublicInstance, DefineComponent } from 'vue';
|
||||
type LazyHydrationComponent<T extends Component, Props> = T & DefineComponent<Props, {}, {}, {}, {}, {}, {}, {
|
||||
hydrated: () => void;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'visible', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateOnVisible?: IntersectionObserverInit | true;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'idle', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateOnIdle?: number | true;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'interaction', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateOnInteraction?: keyof HTMLElementEventMap | Array<keyof HTMLElementEventMap>;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'mediaQuery', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateOnMediaQuery: string;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'if', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateWhen: boolean;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'time', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateAfter: number | true;
|
||||
}>;
|
||||
export declare function defineLazyHydrationComponent<T extends Component = {
|
||||
new (): ComponentPublicInstance;
|
||||
}>(strategy: 'never', source: AsyncComponentLoader<T>): LazyHydrationComponent<T, {
|
||||
hydrateNever?: true;
|
||||
}>;
|
||||
export {};
|
||||
2
node_modules/nuxt/dist/app/composables/lazy-hydration.js
generated
vendored
Normal file
2
node_modules/nuxt/dist/app/composables/lazy-hydration.js
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
export function defineLazyHydrationComponent(_strategy, _source) {
|
||||
}
|
||||
39
node_modules/nuxt/dist/app/composables/loading-indicator.d.ts
generated
vendored
Normal file
39
node_modules/nuxt/dist/app/composables/loading-indicator.d.ts
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { Ref } from 'vue';
|
||||
export type LoadingIndicatorOpts = {
|
||||
/** @default 2000 */
|
||||
duration: number;
|
||||
/** @default 200 */
|
||||
throttle: number;
|
||||
/** @default 500 */
|
||||
hideDelay: number;
|
||||
/** @default 400 */
|
||||
resetDelay: number;
|
||||
/**
|
||||
* You can provide a custom function to customize the progress estimation,
|
||||
* which is a function that receives the duration of the loading bar (above)
|
||||
* and the elapsed time. It should return a value between 0 and 100.
|
||||
*/
|
||||
estimatedProgress?: (duration: number, elapsed: number) => number;
|
||||
};
|
||||
export type LoadingIndicator = {
|
||||
_cleanup: () => void;
|
||||
progress: Ref<number>;
|
||||
isLoading: Ref<boolean>;
|
||||
error: Ref<boolean>;
|
||||
start: (opts?: {
|
||||
force?: boolean;
|
||||
}) => void;
|
||||
set: (value: number, opts?: {
|
||||
force?: boolean;
|
||||
}) => void;
|
||||
finish: (opts?: {
|
||||
force?: boolean;
|
||||
error?: boolean;
|
||||
}) => void;
|
||||
clear: () => void;
|
||||
};
|
||||
/**
|
||||
* composable to handle the loading state of the page
|
||||
* @since 3.9.0
|
||||
*/
|
||||
export declare function useLoadingIndicator(opts?: Partial<LoadingIndicatorOpts>): Omit<LoadingIndicator, '_cleanup'>;
|
||||
142
node_modules/nuxt/dist/app/composables/loading-indicator.js
generated
vendored
Normal file
142
node_modules/nuxt/dist/app/composables/loading-indicator.js
generated
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
import { computed, getCurrentScope, onScopeDispose, shallowRef } from "vue";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
function defaultEstimatedProgress(duration, elapsed) {
|
||||
const completionPercentage = elapsed / duration * 100;
|
||||
return 2 / Math.PI * 100 * Math.atan(completionPercentage / 50);
|
||||
}
|
||||
function createLoadingIndicator(opts = {}) {
|
||||
const { duration = 2e3, throttle = 200, hideDelay = 500, resetDelay = 400 } = opts;
|
||||
const getProgress = opts.estimatedProgress || defaultEstimatedProgress;
|
||||
const nuxtApp = useNuxtApp();
|
||||
const progress = shallowRef(0);
|
||||
const isLoading = shallowRef(false);
|
||||
const error = shallowRef(false);
|
||||
let done = false;
|
||||
let rafId;
|
||||
let throttleTimeout;
|
||||
let hideTimeout;
|
||||
let resetTimeout;
|
||||
const start = (opts2 = {}) => {
|
||||
_clearTimeouts();
|
||||
error.value = false;
|
||||
set(0, opts2);
|
||||
};
|
||||
function set(at = 0, opts2 = {}) {
|
||||
if (nuxtApp.isHydrating) {
|
||||
return;
|
||||
}
|
||||
if (at >= 100) {
|
||||
return finish({ force: opts2.force });
|
||||
}
|
||||
clear();
|
||||
progress.value = at < 0 ? 0 : at;
|
||||
const throttleTime = opts2.force ? 0 : throttle;
|
||||
if (throttleTime && import.meta.client) {
|
||||
throttleTimeout = setTimeout(() => {
|
||||
isLoading.value = true;
|
||||
_startProgress();
|
||||
}, throttleTime);
|
||||
} else {
|
||||
isLoading.value = true;
|
||||
_startProgress();
|
||||
}
|
||||
}
|
||||
function _hide() {
|
||||
if (import.meta.client) {
|
||||
hideTimeout = setTimeout(() => {
|
||||
isLoading.value = false;
|
||||
resetTimeout = setTimeout(() => {
|
||||
progress.value = 0;
|
||||
}, resetDelay);
|
||||
}, hideDelay);
|
||||
}
|
||||
}
|
||||
function finish(opts2 = {}) {
|
||||
progress.value = 100;
|
||||
done = true;
|
||||
clear();
|
||||
_clearTimeouts();
|
||||
if (opts2.error) {
|
||||
error.value = true;
|
||||
}
|
||||
if (opts2.force) {
|
||||
progress.value = 0;
|
||||
isLoading.value = false;
|
||||
} else {
|
||||
_hide();
|
||||
}
|
||||
}
|
||||
function _clearTimeouts() {
|
||||
if (import.meta.client) {
|
||||
clearTimeout(hideTimeout);
|
||||
clearTimeout(resetTimeout);
|
||||
}
|
||||
}
|
||||
function clear() {
|
||||
if (import.meta.client) {
|
||||
clearTimeout(throttleTimeout);
|
||||
cancelAnimationFrame(rafId);
|
||||
}
|
||||
}
|
||||
function _startProgress() {
|
||||
done = false;
|
||||
let startTimeStamp;
|
||||
function step(timeStamp) {
|
||||
if (done) {
|
||||
return;
|
||||
}
|
||||
startTimeStamp ??= timeStamp;
|
||||
const elapsed = timeStamp - startTimeStamp;
|
||||
progress.value = Math.max(0, Math.min(100, getProgress(duration, elapsed)));
|
||||
if (import.meta.client) {
|
||||
rafId = requestAnimationFrame(step);
|
||||
}
|
||||
}
|
||||
if (import.meta.client) {
|
||||
rafId = requestAnimationFrame(step);
|
||||
}
|
||||
}
|
||||
let _cleanup = () => {
|
||||
};
|
||||
if (import.meta.client) {
|
||||
const unsubLoadingStartHook = nuxtApp.hook("page:loading:start", () => {
|
||||
start();
|
||||
});
|
||||
const unsubLoadingFinishHook = nuxtApp.hook("page:loading:end", () => {
|
||||
finish();
|
||||
});
|
||||
const unsubError = nuxtApp.hook("vue:error", () => finish());
|
||||
_cleanup = () => {
|
||||
unsubError();
|
||||
unsubLoadingStartHook();
|
||||
unsubLoadingFinishHook();
|
||||
clear();
|
||||
};
|
||||
}
|
||||
return {
|
||||
_cleanup,
|
||||
progress: computed(() => progress.value),
|
||||
isLoading: computed(() => isLoading.value),
|
||||
error: computed(() => error.value),
|
||||
start,
|
||||
set,
|
||||
finish,
|
||||
clear
|
||||
};
|
||||
}
|
||||
export function useLoadingIndicator(opts = {}) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const indicator = nuxtApp._loadingIndicator ||= createLoadingIndicator(opts);
|
||||
if (import.meta.client && getCurrentScope()) {
|
||||
nuxtApp._loadingIndicatorDeps ||= 0;
|
||||
nuxtApp._loadingIndicatorDeps++;
|
||||
onScopeDispose(() => {
|
||||
nuxtApp._loadingIndicatorDeps--;
|
||||
if (nuxtApp._loadingIndicatorDeps === 0) {
|
||||
indicator._cleanup();
|
||||
delete nuxtApp._loadingIndicator;
|
||||
}
|
||||
});
|
||||
}
|
||||
return indicator;
|
||||
}
|
||||
18
node_modules/nuxt/dist/app/composables/manifest.d.ts
generated
vendored
Normal file
18
node_modules/nuxt/dist/app/composables/manifest.d.ts
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { H3Event } from 'h3';
|
||||
import type { NitroRouteRules } from 'nitropack/types';
|
||||
export interface NuxtAppManifestMeta {
|
||||
id: string;
|
||||
timestamp: number;
|
||||
}
|
||||
export interface NuxtAppManifest extends NuxtAppManifestMeta {
|
||||
prerendered: string[];
|
||||
}
|
||||
/** @since 3.7.4 */
|
||||
export declare function getAppManifest(): Promise<NuxtAppManifest>;
|
||||
/** @since 3.7.4 */
|
||||
export declare function getRouteRules(event: H3Event): NitroRouteRules;
|
||||
export declare function getRouteRules(options: {
|
||||
path: string;
|
||||
}): Record<string, any>;
|
||||
/** @deprecated use `getRouteRules({ path })` instead */
|
||||
export declare function getRouteRules(url: string): Record<string, any>;
|
||||
44
node_modules/nuxt/dist/app/composables/manifest.js
generated
vendored
Normal file
44
node_modules/nuxt/dist/app/composables/manifest.js
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useNuxtApp, useRuntimeConfig } from "../nuxt.js";
|
||||
import { appManifest as isAppManifestEnabled } from "#build/nuxt.config.mjs";
|
||||
import { buildAssetsURL } from "#internal/nuxt/paths";
|
||||
import _routeRulesMatcher from "#build/route-rules.mjs";
|
||||
const routeRulesMatcher = _routeRulesMatcher;
|
||||
let manifest;
|
||||
function fetchManifest() {
|
||||
if (!isAppManifestEnabled) {
|
||||
throw new Error("[nuxt] app manifest should be enabled with `experimental.appManifest`");
|
||||
}
|
||||
if (import.meta.server) {
|
||||
manifest = import(
|
||||
/* webpackIgnore: true */
|
||||
/* @vite-ignore */
|
||||
"#app-manifest"
|
||||
);
|
||||
} else {
|
||||
manifest = $fetch(buildAssetsURL(`builds/meta/${useRuntimeConfig().app.buildId}.json`), {
|
||||
responseType: "json"
|
||||
});
|
||||
}
|
||||
manifest.catch((e) => {
|
||||
console.error("[nuxt] Error fetching app manifest.", e);
|
||||
});
|
||||
return manifest;
|
||||
}
|
||||
export function getAppManifest() {
|
||||
if (!isAppManifestEnabled) {
|
||||
throw new Error("[nuxt] app manifest should be enabled with `experimental.appManifest`");
|
||||
}
|
||||
if (import.meta.server) {
|
||||
useNuxtApp().ssrContext["~preloadManifest"] = true;
|
||||
}
|
||||
return manifest || fetchManifest();
|
||||
}
|
||||
export function getRouteRules(arg) {
|
||||
const path = typeof arg === "string" ? arg : arg.path;
|
||||
try {
|
||||
return routeRulesMatcher(path);
|
||||
} catch (e) {
|
||||
console.error("[nuxt] Error matching route rules.", e);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
14
node_modules/nuxt/dist/app/composables/once.d.ts
generated
vendored
Normal file
14
node_modules/nuxt/dist/app/composables/once.d.ts
generated
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
type CallOnceOptions = {
|
||||
mode?: 'navigation' | 'render';
|
||||
};
|
||||
/**
|
||||
* An SSR-friendly utility to call a method once
|
||||
* @param key a unique key ensuring the function can be properly de-duplicated across requests
|
||||
* @param fn a function to call
|
||||
* @param options Setup the mode, e.g. to re-execute on navigation
|
||||
* @see https://nuxt.com/docs/4.x/api/utils/call-once
|
||||
* @since 3.9.0
|
||||
*/
|
||||
export declare function callOnce(key?: string, fn?: (() => any | Promise<any>), options?: CallOnceOptions): Promise<void>;
|
||||
export declare function callOnce(fn?: (() => any | Promise<any>), options?: CallOnceOptions): Promise<void>;
|
||||
export {};
|
||||
49
node_modules/nuxt/dist/app/composables/once.js
generated
vendored
Normal file
49
node_modules/nuxt/dist/app/composables/once.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useRouter } from "./router.js";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
let _isHmrUpdating = false;
|
||||
export async function callOnce(...args) {
|
||||
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
|
||||
if (typeof args[0] !== "string") {
|
||||
args.unshift(autoKey);
|
||||
}
|
||||
const [_key, fn, options] = args;
|
||||
if (!_key || typeof _key !== "string") {
|
||||
throw new TypeError("[nuxt] [callOnce] key must be a string: " + _key);
|
||||
}
|
||||
if (fn !== void 0 && typeof fn !== "function") {
|
||||
throw new Error("[nuxt] [callOnce] fn must be a function: " + fn);
|
||||
}
|
||||
const nuxtApp = useNuxtApp();
|
||||
if (options?.mode === "navigation") {
|
||||
let callback = function() {
|
||||
nuxtApp.payload.once.delete(_key);
|
||||
for (const cleanup of cleanups) {
|
||||
cleanup();
|
||||
}
|
||||
};
|
||||
const cleanups = [];
|
||||
cleanups.push(nuxtApp.hooks.hook("page:start", callback), useRouter().beforeResolve(callback));
|
||||
}
|
||||
if (nuxtApp.payload.once.has(_key)) {
|
||||
if (!import.meta.dev || !_isHmrUpdating) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
nuxtApp._once ||= {};
|
||||
nuxtApp._once[_key] ||= fn() || true;
|
||||
await nuxtApp._once[_key];
|
||||
nuxtApp.payload.once.add(_key);
|
||||
delete nuxtApp._once[_key];
|
||||
}
|
||||
if (import.meta.hot) {
|
||||
import.meta.hot.on("vite:beforeUpdate", (payload) => {
|
||||
if (payload.updates.some((u) => u.type === "js-update")) {
|
||||
_isHmrUpdating = true;
|
||||
}
|
||||
});
|
||||
import.meta.hot.on("vite:afterUpdate", (payload) => {
|
||||
if (payload.updates.some((u) => u.type === "js-update")) {
|
||||
_isHmrUpdating = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
31
node_modules/nuxt/dist/app/composables/payload.d.ts
generated
vendored
Normal file
31
node_modules/nuxt/dist/app/composables/payload.d.ts
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { NuxtPayload } from '../nuxt.js';
|
||||
interface LoadPayloadOptions {
|
||||
fresh?: boolean;
|
||||
hash?: string;
|
||||
}
|
||||
/** @since 3.0.0 */
|
||||
export declare function loadPayload(url: string, opts?: LoadPayloadOptions): Promise<Record<string, any> | null>;
|
||||
/** @since 3.0.0 */
|
||||
export declare function preloadPayload(url: string, opts?: LoadPayloadOptions): Promise<void>;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export declare function shouldLoadPayload(url?: string): Promise<boolean>;
|
||||
/** @since 3.0.0 */
|
||||
export declare function isPrerendered(url?: string): Promise<boolean>;
|
||||
/** @since 3.4.0 */
|
||||
export declare function getNuxtClientPayload(): Promise<Partial<NuxtPayload> | null>;
|
||||
export declare function parsePayload(payload: string): Promise<any>;
|
||||
/**
|
||||
* This is an experimental function for configuring passing rich data from server -> client.
|
||||
* @since 3.4.0
|
||||
*/
|
||||
export declare function definePayloadReducer(name: string, reduce: (data: any) => any): void;
|
||||
/**
|
||||
* This is an experimental function for configuring passing rich data from server -> client.
|
||||
*
|
||||
* This function _must_ be called in a Nuxt plugin that is `unshift`ed to the beginning of the Nuxt plugins array.
|
||||
* @since 3.4.0
|
||||
*/
|
||||
export declare function definePayloadReviver(name: string, revive: (data: any) => any | undefined): void;
|
||||
export {};
|
||||
155
node_modules/nuxt/dist/app/composables/payload.js
generated
vendored
Normal file
155
node_modules/nuxt/dist/app/composables/payload.js
generated
vendored
Normal file
@@ -0,0 +1,155 @@
|
||||
import { hasProtocol, joinURL } from "ufo";
|
||||
import { parse } from "devalue";
|
||||
import { getCurrentInstance, onServerPrefetch, reactive } from "vue";
|
||||
import { useNuxtApp, useRuntimeConfig } from "../nuxt.js";
|
||||
import { useHead } from "./head.js";
|
||||
import { useRoute } from "./router.js";
|
||||
import { getAppManifest, getRouteRules } from "./manifest.js";
|
||||
import { appId, appManifest, multiApp, payloadExtraction, renderJsonPayloads } from "#build/nuxt.config.mjs";
|
||||
export async function loadPayload(url, opts = {}) {
|
||||
if (import.meta.server || !payloadExtraction) {
|
||||
return null;
|
||||
}
|
||||
if (await shouldLoadPayload(url)) {
|
||||
const payloadURL = await _getPayloadURL(url, opts);
|
||||
return await _importPayload(payloadURL) || null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
let linkRelType;
|
||||
function detectLinkRelType() {
|
||||
if (import.meta.server) {
|
||||
return "preload";
|
||||
}
|
||||
if (linkRelType) {
|
||||
return linkRelType;
|
||||
}
|
||||
const relList = document.createElement("link").relList;
|
||||
linkRelType = relList && relList.supports && relList.supports("prefetch") ? "prefetch" : "preload";
|
||||
return linkRelType;
|
||||
}
|
||||
export function preloadPayload(url, opts = {}) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const promise = _getPayloadURL(url, opts).then((payloadURL) => {
|
||||
const link = renderJsonPayloads ? { rel: detectLinkRelType(), as: "fetch", crossorigin: "anonymous", href: payloadURL } : { rel: "modulepreload", crossorigin: "", href: payloadURL };
|
||||
if (import.meta.server) {
|
||||
nuxtApp.runWithContext(() => useHead({ link: [link] }));
|
||||
} else {
|
||||
const linkEl = document.createElement("link");
|
||||
for (const key of Object.keys(link)) {
|
||||
linkEl[key === "crossorigin" ? "crossOrigin" : key] = link[key];
|
||||
}
|
||||
document.head.appendChild(linkEl);
|
||||
return new Promise((resolve, reject) => {
|
||||
linkEl.addEventListener("load", () => resolve());
|
||||
linkEl.addEventListener("error", () => reject());
|
||||
});
|
||||
}
|
||||
});
|
||||
if (import.meta.server) {
|
||||
onServerPrefetch(() => promise);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
const filename = renderJsonPayloads ? "_payload.json" : "_payload.js";
|
||||
async function _getPayloadURL(url, opts = {}) {
|
||||
const u = new URL(url, "http://localhost");
|
||||
if (u.host !== "localhost" || hasProtocol(u.pathname, { acceptRelative: true })) {
|
||||
throw new Error("Payload URL must not include hostname: " + url);
|
||||
}
|
||||
const config = useRuntimeConfig();
|
||||
const hash = opts.hash || (opts.fresh ? Date.now() : config.app.buildId);
|
||||
const cdnURL = config.app.cdnURL;
|
||||
const baseOrCdnURL = cdnURL && await isPrerendered(url) ? cdnURL : config.app.baseURL;
|
||||
return joinURL(baseOrCdnURL, u.pathname, filename + (hash ? `?${hash}` : ""));
|
||||
}
|
||||
async function _importPayload(payloadURL) {
|
||||
if (import.meta.server || !payloadExtraction) {
|
||||
return null;
|
||||
}
|
||||
const payloadPromise = renderJsonPayloads ? fetch(payloadURL, { cache: "force-cache" }).then((res) => res.text().then(parsePayload)) : import(
|
||||
/* webpackIgnore: true */
|
||||
/* @vite-ignore */
|
||||
payloadURL
|
||||
).then((r) => r.default || r);
|
||||
try {
|
||||
return await payloadPromise;
|
||||
} catch (err) {
|
||||
console.warn("[nuxt] Cannot load payload ", payloadURL, err);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function _shouldLoadPrerenderedPayload(rules) {
|
||||
if (rules.redirect) {
|
||||
return false;
|
||||
}
|
||||
if (rules.prerender) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
async function _isPrerenderedInManifest(url) {
|
||||
if (!appManifest) {
|
||||
return false;
|
||||
}
|
||||
url = url === "/" ? url : url.replace(/\/$/, "");
|
||||
const manifest = await getAppManifest();
|
||||
return manifest.prerendered.includes(url);
|
||||
}
|
||||
export async function shouldLoadPayload(url = useRoute().path) {
|
||||
const rules = getRouteRules({ path: url });
|
||||
const res = _shouldLoadPrerenderedPayload(rules);
|
||||
if (res !== void 0) {
|
||||
return res;
|
||||
}
|
||||
if (rules.payload) {
|
||||
return true;
|
||||
}
|
||||
return await _isPrerenderedInManifest(url);
|
||||
}
|
||||
export async function isPrerendered(url = useRoute().path) {
|
||||
const res = _shouldLoadPrerenderedPayload(getRouteRules({ path: url }));
|
||||
if (res !== void 0) {
|
||||
return res;
|
||||
}
|
||||
return await _isPrerenderedInManifest(url);
|
||||
}
|
||||
let payloadCache = null;
|
||||
export async function getNuxtClientPayload() {
|
||||
if (import.meta.server) {
|
||||
return null;
|
||||
}
|
||||
if (payloadCache) {
|
||||
return payloadCache;
|
||||
}
|
||||
const el = multiApp ? document.querySelector(`[data-nuxt-data="${appId}"]`) : document.getElementById("__NUXT_DATA__");
|
||||
if (!el) {
|
||||
return {};
|
||||
}
|
||||
const inlineData = await parsePayload(el.textContent || "");
|
||||
const externalData = el.dataset.src ? await _importPayload(el.dataset.src) : void 0;
|
||||
payloadCache = {
|
||||
...inlineData,
|
||||
...externalData,
|
||||
...multiApp ? window.__NUXT__?.[appId] : window.__NUXT__
|
||||
};
|
||||
if (payloadCache.config?.public) {
|
||||
payloadCache.config.public = reactive(payloadCache.config.public);
|
||||
}
|
||||
return payloadCache;
|
||||
}
|
||||
export async function parsePayload(payload) {
|
||||
return await parse(payload, useNuxtApp()._payloadRevivers);
|
||||
}
|
||||
export function definePayloadReducer(name, reduce) {
|
||||
if (import.meta.server) {
|
||||
useNuxtApp().ssrContext["~payloadReducers"][name] = reduce;
|
||||
}
|
||||
}
|
||||
export function definePayloadReviver(name, revive) {
|
||||
if (import.meta.dev && getCurrentInstance()) {
|
||||
console.warn("[nuxt] [definePayloadReviver] This function must be called in a Nuxt plugin that is `unshift`ed to the beginning of the Nuxt plugins array.");
|
||||
}
|
||||
if (import.meta.client) {
|
||||
useNuxtApp()._payloadRevivers[name] = revive;
|
||||
}
|
||||
}
|
||||
20
node_modules/nuxt/dist/app/composables/preload.d.ts
generated
vendored
Normal file
20
node_modules/nuxt/dist/app/composables/preload.d.ts
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
import type { Component } from 'vue';
|
||||
import type { RouteLocationRaw, Router } from 'vue-router';
|
||||
/**
|
||||
* Preload a component or components that have been globally registered.
|
||||
* @param components Pascal-cased name or names of components to prefetch
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export declare const preloadComponents: (components: string | string[]) => Promise<void>;
|
||||
/**
|
||||
* Prefetch a component or components that have been globally registered.
|
||||
* @param components Pascal-cased name or names of components to prefetch
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export declare const prefetchComponents: (components: string | string[]) => Promise<void> | undefined;
|
||||
export declare function _loadAsyncComponent(component: Component): any;
|
||||
/** @since 3.0.0 */
|
||||
export declare function preloadRouteComponents(to: RouteLocationRaw, router?: Router & {
|
||||
_routePreloaded?: Set<string>;
|
||||
_preloadPromises?: Array<Promise<unknown>>;
|
||||
}): Promise<void>;
|
||||
55
node_modules/nuxt/dist/app/composables/preload.js
generated
vendored
Normal file
55
node_modules/nuxt/dist/app/composables/preload.js
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { toArray } from "../utils.js";
|
||||
import { useRouter } from "./router.js";
|
||||
export const preloadComponents = async (components) => {
|
||||
if (import.meta.server) {
|
||||
return;
|
||||
}
|
||||
const nuxtApp = useNuxtApp();
|
||||
components = toArray(components);
|
||||
await Promise.all(components.map((name) => {
|
||||
const component = nuxtApp.vueApp._context.components[name];
|
||||
if (component) {
|
||||
return _loadAsyncComponent(component);
|
||||
}
|
||||
}));
|
||||
};
|
||||
export const prefetchComponents = (components) => {
|
||||
if (import.meta.server) {
|
||||
return;
|
||||
}
|
||||
return preloadComponents(components);
|
||||
};
|
||||
export function _loadAsyncComponent(component) {
|
||||
if (component?.__asyncLoader && !component.__asyncResolved) {
|
||||
return component.__asyncLoader();
|
||||
}
|
||||
}
|
||||
export async function preloadRouteComponents(to, router = useRouter()) {
|
||||
if (import.meta.server) {
|
||||
return;
|
||||
}
|
||||
const { path, matched } = router.resolve(to);
|
||||
if (!matched.length) {
|
||||
return;
|
||||
}
|
||||
router._routePreloaded ||= /* @__PURE__ */ new Set();
|
||||
if (router._routePreloaded.has(path)) {
|
||||
return;
|
||||
}
|
||||
const promises = router._preloadPromises ||= [];
|
||||
if (promises.length > 4) {
|
||||
return Promise.all(promises).then(() => preloadRouteComponents(to, router));
|
||||
}
|
||||
router._routePreloaded.add(path);
|
||||
for (const route of matched) {
|
||||
const component = route.components?.default;
|
||||
if (typeof component !== "function") {
|
||||
continue;
|
||||
}
|
||||
const promise = Promise.resolve(component()).catch(() => {
|
||||
}).finally(() => promises.splice(promises.indexOf(promise)));
|
||||
promises.push(promise);
|
||||
}
|
||||
await Promise.all(promises);
|
||||
}
|
||||
38
node_modules/nuxt/dist/app/composables/preview.d.ts
generated
vendored
Normal file
38
node_modules/nuxt/dist/app/composables/preview.d.ts
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
interface Preview {
|
||||
enabled: boolean;
|
||||
state: Record<any, unknown>;
|
||||
_initialized?: boolean;
|
||||
}
|
||||
/**
|
||||
* Options for configuring preview mode.
|
||||
*/
|
||||
interface PreviewModeOptions<S> {
|
||||
/**
|
||||
* A function that determines whether preview mode should be enabled based on the current state.
|
||||
* @param {Record<any, unknown>} state - The state of the preview.
|
||||
* @returns {boolean} A boolean indicating whether the preview mode is enabled.
|
||||
*/
|
||||
shouldEnable?: (state: Preview['state']) => boolean;
|
||||
/**
|
||||
* A function that retrieves the current state.
|
||||
* The `getState` function will append returned values to current state, so be careful not to accidentally overwrite important state.
|
||||
* @param {Record<any, unknown>} state - The preview state.
|
||||
* @returns {Record<any, unknown>} The preview state.
|
||||
*/
|
||||
getState?: (state: Preview['state']) => S;
|
||||
/**
|
||||
* A function to be called when the preview mode is enabled.
|
||||
*/
|
||||
onEnable?: () => void;
|
||||
/**
|
||||
* A function to be called when the preview mode is disabled.
|
||||
*/
|
||||
onDisable?: () => void;
|
||||
}
|
||||
type EnteredState = Record<any, unknown> | null | undefined | void;
|
||||
/** @since 3.11.0 */
|
||||
export declare function usePreviewMode<S extends EnteredState>(options?: PreviewModeOptions<S>): {
|
||||
enabled: import("vue").Ref<boolean, boolean>;
|
||||
state: S extends void ? Preview["state"] : (NonNullable<S> & Preview["state"]);
|
||||
};
|
||||
export {};
|
||||
61
node_modules/nuxt/dist/app/composables/preview.js
generated
vendored
Normal file
61
node_modules/nuxt/dist/app/composables/preview.js
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
import { toRef, watch } from "vue";
|
||||
import { useState } from "./state.js";
|
||||
import { refreshNuxtData } from "./asyncData.js";
|
||||
import { useRoute, useRouter } from "./router.js";
|
||||
let unregisterRefreshHook;
|
||||
export function usePreviewMode(options = {}) {
|
||||
const preview = useState("_preview-state", () => ({
|
||||
enabled: false,
|
||||
state: {}
|
||||
}));
|
||||
if (preview.value._initialized) {
|
||||
return {
|
||||
enabled: toRef(preview.value, "enabled"),
|
||||
state: preview.value.state
|
||||
};
|
||||
}
|
||||
if (import.meta.client) {
|
||||
preview.value._initialized = true;
|
||||
}
|
||||
if (!preview.value.enabled) {
|
||||
const shouldEnable = options.shouldEnable ?? defaultShouldEnable;
|
||||
const result = shouldEnable(preview.value.state);
|
||||
if (typeof result === "boolean") {
|
||||
preview.value.enabled = result;
|
||||
}
|
||||
}
|
||||
watch(() => preview.value.enabled, (value) => {
|
||||
if (value) {
|
||||
const getState = options.getState ?? getDefaultState;
|
||||
const newState = getState(preview.value.state);
|
||||
if (newState !== preview.value.state) {
|
||||
Object.assign(preview.value.state, newState);
|
||||
}
|
||||
if (import.meta.client && !unregisterRefreshHook) {
|
||||
const onEnable = options.onEnable ?? refreshNuxtData;
|
||||
onEnable();
|
||||
unregisterRefreshHook = options.onDisable ?? useRouter().afterEach(() => refreshNuxtData());
|
||||
}
|
||||
} else if (unregisterRefreshHook) {
|
||||
unregisterRefreshHook();
|
||||
unregisterRefreshHook = void 0;
|
||||
}
|
||||
}, { immediate: true, flush: "sync" });
|
||||
return {
|
||||
enabled: toRef(preview.value, "enabled"),
|
||||
state: preview.value.state
|
||||
};
|
||||
}
|
||||
function defaultShouldEnable() {
|
||||
const route = useRoute();
|
||||
const previewQueryName = "preview";
|
||||
return route.query[previewQueryName] === "true";
|
||||
}
|
||||
function getDefaultState(state) {
|
||||
if (state.token !== void 0) {
|
||||
return state;
|
||||
}
|
||||
const route = useRoute();
|
||||
state.token = Array.isArray(route.query.token) ? route.query.token[0] : route.query.token;
|
||||
return state;
|
||||
}
|
||||
2
node_modules/nuxt/dist/app/composables/ready.d.ts
generated
vendored
Normal file
2
node_modules/nuxt/dist/app/composables/ready.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/** @since 3.1.0 */
|
||||
export declare const onNuxtReady: (callback: () => any) => void;
|
||||
15
node_modules/nuxt/dist/app/composables/ready.js
generated
vendored
Normal file
15
node_modules/nuxt/dist/app/composables/ready.js
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { requestIdleCallback } from "../compat/idle-callback.js";
|
||||
export const onNuxtReady = (callback) => {
|
||||
if (import.meta.server) {
|
||||
return;
|
||||
}
|
||||
const nuxtApp = useNuxtApp();
|
||||
if (nuxtApp.isHydrating) {
|
||||
nuxtApp.hooks.hookOnce("app:suspense:resolve", () => {
|
||||
requestIdleCallback(() => callback());
|
||||
});
|
||||
} else {
|
||||
requestIdleCallback(() => callback());
|
||||
}
|
||||
};
|
||||
19
node_modules/nuxt/dist/app/composables/route-announcer.d.ts
generated
vendored
Normal file
19
node_modules/nuxt/dist/app/composables/route-announcer.d.ts
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Ref } from 'vue';
|
||||
export type Politeness = 'assertive' | 'polite' | 'off';
|
||||
export type NuxtRouteAnnouncerOpts = {
|
||||
/** @default 'polite' */
|
||||
politeness?: Politeness;
|
||||
};
|
||||
export type RouteAnnouncer = {
|
||||
message: Ref<string>;
|
||||
politeness: Ref<Politeness>;
|
||||
set: (message: string, politeness: Politeness) => void;
|
||||
polite: (message: string) => void;
|
||||
assertive: (message: string) => void;
|
||||
_cleanup: () => void;
|
||||
};
|
||||
/**
|
||||
* composable to handle the route announcer
|
||||
* @since 3.12.0
|
||||
*/
|
||||
export declare function useRouteAnnouncer(opts?: Partial<NuxtRouteAnnouncerOpts>): Omit<RouteAnnouncer, '_cleanup'>;
|
||||
55
node_modules/nuxt/dist/app/composables/route-announcer.js
generated
vendored
Normal file
55
node_modules/nuxt/dist/app/composables/route-announcer.js
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
||||
import { getCurrentScope, onScopeDispose, shallowRef } from "vue";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { injectHead } from "./head.js";
|
||||
function createRouteAnnouncer(opts = {}) {
|
||||
const message = shallowRef("");
|
||||
const politeness = shallowRef(opts.politeness || "polite");
|
||||
const activeHead = injectHead();
|
||||
function set(messageValue = "", politenessSetting = "polite") {
|
||||
message.value = messageValue;
|
||||
politeness.value = politenessSetting;
|
||||
}
|
||||
function polite(message2) {
|
||||
return set(message2, "polite");
|
||||
}
|
||||
function assertive(message2) {
|
||||
return set(message2, "assertive");
|
||||
}
|
||||
function _updateMessageWithPageHeading() {
|
||||
set(document?.title?.trim(), politeness.value);
|
||||
}
|
||||
function _cleanup() {
|
||||
activeHead?.hooks?.removeHook("dom:rendered", _updateMessageWithPageHeading);
|
||||
}
|
||||
_updateMessageWithPageHeading();
|
||||
activeHead?.hooks?.hook("dom:rendered", () => {
|
||||
_updateMessageWithPageHeading();
|
||||
});
|
||||
return {
|
||||
_cleanup,
|
||||
message,
|
||||
politeness,
|
||||
set,
|
||||
polite,
|
||||
assertive
|
||||
};
|
||||
}
|
||||
export function useRouteAnnouncer(opts = {}) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const announcer = nuxtApp._routeAnnouncer ||= createRouteAnnouncer(opts);
|
||||
if (opts.politeness !== announcer.politeness.value) {
|
||||
announcer.politeness.value = opts.politeness || "polite";
|
||||
}
|
||||
if (import.meta.client && getCurrentScope()) {
|
||||
nuxtApp._routeAnnouncerDeps ||= 0;
|
||||
nuxtApp._routeAnnouncerDeps++;
|
||||
onScopeDispose(() => {
|
||||
nuxtApp._routeAnnouncerDeps--;
|
||||
if (nuxtApp._routeAnnouncerDeps === 0) {
|
||||
announcer._cleanup();
|
||||
delete nuxtApp._routeAnnouncer;
|
||||
}
|
||||
});
|
||||
}
|
||||
return announcer;
|
||||
}
|
||||
107
node_modules/nuxt/dist/app/composables/router.d.ts
generated
vendored
Normal file
107
node_modules/nuxt/dist/app/composables/router.d.ts
generated
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
import type { NavigationFailure, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, useRoute as _useRoute, useRouter as _useRouter } from 'vue-router';
|
||||
import type { NuxtLayouts } from '../../pages/runtime/composables.js';
|
||||
import type { NuxtError } from './error.js';
|
||||
import type { MakeSerializableObject } from '../../pages/runtime/utils.js';
|
||||
/** @since 3.0.0 */
|
||||
export declare const useRouter: typeof _useRouter;
|
||||
/** @since 3.0.0 */
|
||||
export declare const useRoute: typeof _useRoute;
|
||||
/** @since 3.0.0 */
|
||||
export declare const onBeforeRouteLeave: (guard: NavigationGuard) => void;
|
||||
/** @since 3.0.0 */
|
||||
export declare const onBeforeRouteUpdate: (guard: NavigationGuard) => void;
|
||||
export interface RouteMiddleware {
|
||||
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>;
|
||||
}
|
||||
/** @since 3.0.0 */
|
||||
export declare function defineNuxtRouteMiddleware(middleware: RouteMiddleware): RouteMiddleware;
|
||||
export interface AddRouteMiddlewareOptions {
|
||||
global?: boolean;
|
||||
}
|
||||
interface AddRouteMiddleware {
|
||||
(name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void;
|
||||
(middleware: RouteMiddleware): void;
|
||||
}
|
||||
/** @since 3.0.0 */
|
||||
export declare const addRouteMiddleware: AddRouteMiddleware;
|
||||
type Without<T, U> = {
|
||||
[P in Exclude<keyof T, keyof U>]?: never;
|
||||
};
|
||||
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
|
||||
export type OpenWindowFeatures = {
|
||||
popup?: boolean;
|
||||
noopener?: boolean;
|
||||
noreferrer?: boolean;
|
||||
} & XOR<{
|
||||
width?: number;
|
||||
}, {
|
||||
innerWidth?: number;
|
||||
}> & XOR<{
|
||||
height?: number;
|
||||
}, {
|
||||
innerHeight?: number;
|
||||
}> & XOR<{
|
||||
left?: number;
|
||||
}, {
|
||||
screenX?: number;
|
||||
}> & XOR<{
|
||||
top?: number;
|
||||
}, {
|
||||
screenY?: number;
|
||||
}>;
|
||||
export type OpenOptions = {
|
||||
target: '_blank' | '_parent' | '_self' | '_top' | (string & {});
|
||||
windowFeatures?: OpenWindowFeatures;
|
||||
};
|
||||
export interface NavigateToOptions {
|
||||
/**
|
||||
* Whether or not the given route should replace the current route in the navigation history, rather than push it.
|
||||
*/
|
||||
replace?: boolean;
|
||||
/**
|
||||
* The status code to emit with the navigation. Defaults to `302 Found` when used on server side redirects.
|
||||
*/
|
||||
redirectCode?: number;
|
||||
/**
|
||||
* Whether or not the given route is a website/resource from a different origin. By default, navigating to external resources without setting `external: true` would result in an error.
|
||||
*/
|
||||
external?: boolean;
|
||||
open?: OpenOptions;
|
||||
}
|
||||
/**
|
||||
* A helper that aids in programmatic navigation within your Nuxt application.
|
||||
*
|
||||
* Can be called on the server and on the client, within pages, route middleware, plugins, and more.
|
||||
* @param {RouteLocationRaw | undefined | null} [to] - The route to navigate to. Accepts a route object, string path, `undefined`, or `null`. Defaults to '/'.
|
||||
* @param {NavigateToOptions} [options] - Optional customization for controlling the behavior of the navigation.
|
||||
* @returns {Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw} The navigation result, which varies depending on context and options.
|
||||
* @see https://nuxt.com/docs/4.x/api/utils/navigate-to
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export declare const navigateTo: (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions) => Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw;
|
||||
/**
|
||||
* This will abort navigation within a Nuxt route middleware handler.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export declare const abortNavigation: (err?: string | Partial<NuxtError>) => boolean;
|
||||
/**
|
||||
* Sets the layout for the current page.
|
||||
* @since 3.0.0
|
||||
*/
|
||||
export declare const setPageLayout: <Layout extends keyof NuxtLayouts>(layout: unknown extends Layout ? string : Layout, props?: typeof layout extends Layout ? MakeSerializableObject<NuxtLayouts[Layout]> : never) => void;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export declare function resolveRouteObject(to: Exclude<RouteLocationRaw, string>): string;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
export declare function encodeURL(location: string, isExternalHost?: boolean): string;
|
||||
/**
|
||||
* Encode the pathname of a route location string. Ensures decoded paths like
|
||||
* `/café` are percent-encoded to match vue-router's encoded route records.
|
||||
* Already-encoded paths are not double-encoded.
|
||||
* @internal
|
||||
*/
|
||||
export declare function encodeRoutePath(url: string): string;
|
||||
export {};
|
||||
206
node_modules/nuxt/dist/app/composables/router.js
generated
vendored
Normal file
206
node_modules/nuxt/dist/app/composables/router.js
generated
vendored
Normal file
@@ -0,0 +1,206 @@
|
||||
import { getCurrentInstance, hasInjectionContext, inject, onScopeDispose } from "vue";
|
||||
import { sanitizeStatusCode } from "h3";
|
||||
import { decodePath, encodePath, hasProtocol, isScriptProtocol, joinURL, parseQuery, parseURL, withQuery } from "ufo";
|
||||
import { useNuxtApp, useRuntimeConfig } from "../nuxt.js";
|
||||
import { PageRouteSymbol } from "../components/injections.js";
|
||||
import { createError, showError } from "./error.js";
|
||||
import { getUserTrace } from "../utils.js";
|
||||
export const useRouter = () => {
|
||||
return useNuxtApp()?.$router;
|
||||
};
|
||||
export const useRoute = () => {
|
||||
if (import.meta.dev && !getCurrentInstance() && isProcessingMiddleware()) {
|
||||
const middleware = useNuxtApp()._processingMiddleware;
|
||||
const trace = getUserTrace().map(({ source, line, column }) => `at ${source}:${line}:${column}`).join("\n");
|
||||
console.warn(`[nuxt] \`useRoute\` was called within middleware${typeof middleware === "string" ? ` (\`${middleware}\`)` : ""}. This may lead to misleading results. Instead, use the (to, from) arguments passed to the middleware to access the new and old routes. Learn more: https://nuxt.com/docs/4.x/directory-structure/app/middleware#accessing-route-in-middleware` + ("\n" + trace));
|
||||
}
|
||||
if (hasInjectionContext()) {
|
||||
return inject(PageRouteSymbol, useNuxtApp()._route);
|
||||
}
|
||||
return useNuxtApp()._route;
|
||||
};
|
||||
export const onBeforeRouteLeave = (guard) => {
|
||||
const unsubscribe = useRouter().beforeEach((to, from, next) => {
|
||||
if (to === from) {
|
||||
return;
|
||||
}
|
||||
return guard(to, from, next);
|
||||
});
|
||||
onScopeDispose(unsubscribe);
|
||||
};
|
||||
export const onBeforeRouteUpdate = (guard) => {
|
||||
const unsubscribe = useRouter().beforeEach(guard);
|
||||
onScopeDispose(unsubscribe);
|
||||
};
|
||||
// @__NO_SIDE_EFFECTS__
|
||||
export function defineNuxtRouteMiddleware(middleware) {
|
||||
return middleware;
|
||||
}
|
||||
export const addRouteMiddleware = (name, middleware, options = {}) => {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const global = options.global || typeof name !== "string";
|
||||
const mw = typeof name !== "string" ? name : middleware;
|
||||
if (!mw) {
|
||||
console.warn("[nuxt] No route middleware passed to `addRouteMiddleware`.", name);
|
||||
return;
|
||||
}
|
||||
if (global) {
|
||||
nuxtApp._middleware.global.push(mw);
|
||||
} else {
|
||||
nuxtApp._middleware.named[name] = mw;
|
||||
}
|
||||
};
|
||||
const isProcessingMiddleware = () => {
|
||||
try {
|
||||
if (useNuxtApp()._processingMiddleware) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const URL_QUOTE_RE = /"/g;
|
||||
export const navigateTo = (to, options) => {
|
||||
to ||= "/";
|
||||
const toPath = typeof to === "string" ? to : "path" in to ? resolveRouteObject(to) : useRouter().resolve(to).href;
|
||||
if (import.meta.client && options?.open) {
|
||||
const { target = "_blank", windowFeatures = {} } = options.open;
|
||||
const features = [];
|
||||
for (const [feature, value] of Object.entries(windowFeatures)) {
|
||||
if (value !== void 0) {
|
||||
features.push(`${feature.toLowerCase()}=${value}`);
|
||||
}
|
||||
}
|
||||
open(toPath, target, features.join(", "));
|
||||
return Promise.resolve();
|
||||
}
|
||||
const isExternalHost = hasProtocol(toPath, { acceptRelative: true });
|
||||
const isExternal = options?.external || isExternalHost;
|
||||
if (isExternal) {
|
||||
if (!options?.external) {
|
||||
throw new Error("Navigating to an external URL is not allowed by default. Use `navigateTo(url, { external: true })`.");
|
||||
}
|
||||
const { protocol } = new URL(toPath, import.meta.client ? window.location.href : "http://localhost");
|
||||
if (protocol && isScriptProtocol(protocol)) {
|
||||
throw new Error(`Cannot navigate to a URL with '${protocol}' protocol.`);
|
||||
}
|
||||
}
|
||||
const inMiddleware = isProcessingMiddleware();
|
||||
if (import.meta.client && !isExternal && inMiddleware) {
|
||||
if (options?.replace) {
|
||||
if (typeof to === "string") {
|
||||
const { pathname, search, hash } = parseURL(to);
|
||||
return {
|
||||
path: pathname,
|
||||
...search && { query: parseQuery(search) },
|
||||
...hash && { hash },
|
||||
replace: true
|
||||
};
|
||||
}
|
||||
return { ...to, replace: true };
|
||||
}
|
||||
return to;
|
||||
}
|
||||
const router = useRouter();
|
||||
const nuxtApp = useNuxtApp();
|
||||
if (import.meta.server) {
|
||||
if (nuxtApp.ssrContext) {
|
||||
const fullPath = typeof to === "string" || isExternal ? toPath : router.resolve(to).fullPath || "/";
|
||||
const location2 = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, fullPath);
|
||||
const redirect = async function(response) {
|
||||
await nuxtApp.callHook("app:redirected");
|
||||
const encodedLoc = location2.replace(URL_QUOTE_RE, "%22");
|
||||
const encodedHeader = encodeURL(location2, isExternalHost);
|
||||
nuxtApp.ssrContext["~renderResponse"] = {
|
||||
statusCode: sanitizeStatusCode(options?.redirectCode || 302, 302),
|
||||
body: `<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=${encodedLoc}"></head></html>`,
|
||||
headers: { location: encodedHeader }
|
||||
};
|
||||
return response;
|
||||
};
|
||||
if (!isExternal && inMiddleware) {
|
||||
router.afterEach((final) => final.fullPath === fullPath ? redirect(false) : void 0);
|
||||
return to;
|
||||
}
|
||||
return redirect(!inMiddleware ? void 0 : (
|
||||
/* abort route navigation */
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
if (isExternal) {
|
||||
nuxtApp._scope.stop();
|
||||
if (options?.replace) {
|
||||
location.replace(toPath);
|
||||
} else {
|
||||
location.href = toPath;
|
||||
}
|
||||
if (inMiddleware) {
|
||||
if (!nuxtApp.isHydrating) {
|
||||
return false;
|
||||
}
|
||||
return new Promise(() => {
|
||||
});
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
const encodedTo = typeof to === "string" ? encodeRoutePath(to) : to;
|
||||
return options?.replace ? router.replace(encodedTo) : router.push(encodedTo);
|
||||
};
|
||||
export const abortNavigation = (err) => {
|
||||
if (import.meta.dev && !isProcessingMiddleware()) {
|
||||
throw new Error("abortNavigation() is only usable inside a route middleware handler.");
|
||||
}
|
||||
if (!err) {
|
||||
return false;
|
||||
}
|
||||
err = createError(err);
|
||||
if (err.fatal) {
|
||||
useNuxtApp().runWithContext(() => showError(err));
|
||||
}
|
||||
throw err;
|
||||
};
|
||||
export const setPageLayout = (layout, props) => {
|
||||
const nuxtApp = useNuxtApp();
|
||||
if (import.meta.server) {
|
||||
if (import.meta.dev && getCurrentInstance() && nuxtApp.payload.state._layout !== layout) {
|
||||
console.warn("[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.");
|
||||
}
|
||||
nuxtApp.payload.state._layout = layout;
|
||||
nuxtApp.payload.state._layoutProps = props;
|
||||
}
|
||||
if (import.meta.dev && nuxtApp.isHydrating && nuxtApp.payload.serverRendered && nuxtApp.payload.state._layout !== layout) {
|
||||
console.warn("[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.");
|
||||
}
|
||||
const inMiddleware = isProcessingMiddleware();
|
||||
if (inMiddleware || import.meta.server || nuxtApp.isHydrating) {
|
||||
const unsubscribe = useRouter().beforeResolve((to) => {
|
||||
to.meta.layout = layout;
|
||||
to.meta.layoutProps = props;
|
||||
unsubscribe();
|
||||
});
|
||||
}
|
||||
if (!inMiddleware) {
|
||||
const route = useRoute();
|
||||
route.meta.layout = layout;
|
||||
route.meta.layoutProps = props;
|
||||
}
|
||||
};
|
||||
export function resolveRouteObject(to) {
|
||||
return withQuery(to.path || "", to.query || {}) + (to.hash || "");
|
||||
}
|
||||
export function encodeURL(location2, isExternalHost = false) {
|
||||
const url = new URL(location2, "http://localhost");
|
||||
if (!isExternalHost) {
|
||||
return url.pathname + url.search + url.hash;
|
||||
}
|
||||
if (location2.startsWith("//")) {
|
||||
return url.toString().replace(url.protocol, "");
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
export function encodeRoutePath(url) {
|
||||
const parsed = parseURL(url);
|
||||
return encodePath(decodePath(parsed.pathname)) + parsed.search + parsed.hash;
|
||||
}
|
||||
9
node_modules/nuxt/dist/app/composables/runtime-hook.d.ts
generated
vendored
Normal file
9
node_modules/nuxt/dist/app/composables/runtime-hook.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { HookCallback } from 'hookable';
|
||||
import type { RuntimeNuxtHooks } from '../nuxt.js';
|
||||
/**
|
||||
* Registers a runtime hook in a Nuxt application and ensures it is properly disposed of when the scope is destroyed.
|
||||
* @param name - The name of the hook to register.
|
||||
* @param fn - The callback function to be executed when the hook is triggered.
|
||||
* @since 3.14.0
|
||||
*/
|
||||
export declare function useRuntimeHook<THookName extends keyof RuntimeNuxtHooks>(name: THookName, fn: RuntimeNuxtHooks[THookName] extends HookCallback ? RuntimeNuxtHooks[THookName] : never): void;
|
||||
7
node_modules/nuxt/dist/app/composables/runtime-hook.js
generated
vendored
Normal file
7
node_modules/nuxt/dist/app/composables/runtime-hook.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
import { onScopeDispose } from "vue";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
export function useRuntimeHook(name, fn) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const unregister = nuxtApp.hook(name, fn);
|
||||
onScopeDispose(unregister);
|
||||
}
|
||||
32
node_modules/nuxt/dist/app/composables/script-stubs.d.ts
generated
vendored
Normal file
32
node_modules/nuxt/dist/app/composables/script-stubs.d.ts
generated
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { UseScriptInput } from '@unhead/vue/scripts';
|
||||
export declare function useScript<T extends Record<string | symbol, any>>(input: UseScriptInput, options?: Record<string, unknown>): void;
|
||||
export declare function useScriptTriggerElement(...args: unknown[]): void;
|
||||
export declare function useScriptTriggerConsent(...args: unknown[]): void;
|
||||
export declare function useScriptEventPage(...args: unknown[]): void;
|
||||
export declare function useScriptGoogleAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptPlausibleAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptCloudflareWebAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptCrisp(...args: unknown[]): void;
|
||||
export declare function useScriptFathomAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptMatomoAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptGoogleTagManager(...args: unknown[]): void;
|
||||
export declare function useScriptSegment(...args: unknown[]): void;
|
||||
export declare function useScriptClarity(...args: unknown[]): void;
|
||||
export declare function useScriptMetaPixel(...args: unknown[]): void;
|
||||
export declare function useScriptXPixel(...args: unknown[]): void;
|
||||
export declare function useScriptIntercom(...args: unknown[]): void;
|
||||
export declare function useScriptHotjar(...args: unknown[]): void;
|
||||
export declare function useScriptStripe(...args: unknown[]): void;
|
||||
export declare function useScriptLemonSqueezy(...args: unknown[]): void;
|
||||
export declare function useScriptVimeoPlayer(...args: unknown[]): void;
|
||||
export declare function useScriptYouTubeIframe(...args: unknown[]): void;
|
||||
export declare function useScriptGoogleMaps(...args: unknown[]): void;
|
||||
export declare function useScriptNpm(...args: unknown[]): void;
|
||||
export declare function useScriptGoogleAdsense(...args: unknown[]): void;
|
||||
export declare function useScriptYouTubePlayer(...args: unknown[]): void;
|
||||
export declare function useScriptUmamiAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptSnapchatPixel(...args: unknown[]): void;
|
||||
export declare function useScriptRybbitAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptDatabuddyAnalytics(...args: unknown[]): void;
|
||||
export declare function useScriptRedditPixel(...args: unknown[]): void;
|
||||
export declare function useScriptPayPal(...args: unknown[]): void;
|
||||
104
node_modules/nuxt/dist/app/composables/script-stubs.js
generated
vendored
Normal file
104
node_modules/nuxt/dist/app/composables/script-stubs.js
generated
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
import { createError } from "./error.js";
|
||||
function renderStubMessage(name) {
|
||||
const message = `\`${name}\` is provided by @nuxt/scripts. Check your console to install it or run 'npx nuxt module add @nuxt/scripts' to install it.`;
|
||||
if (import.meta.client) {
|
||||
throw createError({
|
||||
fatal: true,
|
||||
status: 500,
|
||||
statusText: message
|
||||
});
|
||||
}
|
||||
}
|
||||
export function useScript(input, options) {
|
||||
renderStubMessage("useScript");
|
||||
}
|
||||
export function useScriptTriggerElement(...args) {
|
||||
renderStubMessage("useScriptTriggerElement");
|
||||
}
|
||||
export function useScriptTriggerConsent(...args) {
|
||||
renderStubMessage("useScriptTriggerConsent");
|
||||
}
|
||||
export function useScriptEventPage(...args) {
|
||||
renderStubMessage("useScriptEventPage");
|
||||
}
|
||||
export function useScriptGoogleAnalytics(...args) {
|
||||
renderStubMessage("useScriptGoogleAnalytics");
|
||||
}
|
||||
export function useScriptPlausibleAnalytics(...args) {
|
||||
renderStubMessage("useScriptPlausibleAnalytics");
|
||||
}
|
||||
export function useScriptCloudflareWebAnalytics(...args) {
|
||||
renderStubMessage("useScriptCloudflareWebAnalytics");
|
||||
}
|
||||
export function useScriptCrisp(...args) {
|
||||
renderStubMessage("useScriptCrisp");
|
||||
}
|
||||
export function useScriptFathomAnalytics(...args) {
|
||||
renderStubMessage("useScriptFathomAnalytics");
|
||||
}
|
||||
export function useScriptMatomoAnalytics(...args) {
|
||||
renderStubMessage("useScriptMatomoAnalytics");
|
||||
}
|
||||
export function useScriptGoogleTagManager(...args) {
|
||||
renderStubMessage("useScriptGoogleTagManager");
|
||||
}
|
||||
export function useScriptSegment(...args) {
|
||||
renderStubMessage("useScriptSegment");
|
||||
}
|
||||
export function useScriptClarity(...args) {
|
||||
renderStubMessage("useScriptClarity");
|
||||
}
|
||||
export function useScriptMetaPixel(...args) {
|
||||
renderStubMessage("useScriptMetaPixel");
|
||||
}
|
||||
export function useScriptXPixel(...args) {
|
||||
renderStubMessage("useScriptXPixel");
|
||||
}
|
||||
export function useScriptIntercom(...args) {
|
||||
renderStubMessage("useScriptIntercom");
|
||||
}
|
||||
export function useScriptHotjar(...args) {
|
||||
renderStubMessage("useScriptHotjar");
|
||||
}
|
||||
export function useScriptStripe(...args) {
|
||||
renderStubMessage("useScriptStripe");
|
||||
}
|
||||
export function useScriptLemonSqueezy(...args) {
|
||||
renderStubMessage("useScriptLemonSqueezy");
|
||||
}
|
||||
export function useScriptVimeoPlayer(...args) {
|
||||
renderStubMessage("useScriptVimeoPlayer");
|
||||
}
|
||||
export function useScriptYouTubeIframe(...args) {
|
||||
renderStubMessage("useScriptYouTubeIframe");
|
||||
}
|
||||
export function useScriptGoogleMaps(...args) {
|
||||
renderStubMessage("useScriptGoogleMaps");
|
||||
}
|
||||
export function useScriptNpm(...args) {
|
||||
renderStubMessage("useScriptNpm");
|
||||
}
|
||||
export function useScriptGoogleAdsense(...args) {
|
||||
renderStubMessage("useScriptGoogleAdsense");
|
||||
}
|
||||
export function useScriptYouTubePlayer(...args) {
|
||||
renderStubMessage("useScriptYouTubePlayer");
|
||||
}
|
||||
export function useScriptUmamiAnalytics(...args) {
|
||||
renderStubMessage("useScriptUmamiAnalytics");
|
||||
}
|
||||
export function useScriptSnapchatPixel(...args) {
|
||||
renderStubMessage("useScriptSnapchatPixel");
|
||||
}
|
||||
export function useScriptRybbitAnalytics(...args) {
|
||||
renderStubMessage("useScriptRybbitAnalytics");
|
||||
}
|
||||
export function useScriptDatabuddyAnalytics(...args) {
|
||||
renderStubMessage("useScriptDatabuddyAnalytics");
|
||||
}
|
||||
export function useScriptRedditPixel(...args) {
|
||||
renderStubMessage("useScriptRedditPixel");
|
||||
}
|
||||
export function useScriptPayPal(...args) {
|
||||
renderStubMessage("useScriptPayPal");
|
||||
}
|
||||
33
node_modules/nuxt/dist/app/composables/ssr.d.ts
generated
vendored
Normal file
33
node_modules/nuxt/dist/app/composables/ssr.d.ts
generated
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
import type { H3Event } from 'h3';
|
||||
import type { H3Event$Fetch } from 'nitropack/types';
|
||||
import type { NuxtApp } from '../nuxt.js';
|
||||
/** @since 3.0.0 */
|
||||
export declare function useRequestEvent(nuxtApp?: NuxtApp): H3Event<import("h3").EventHandlerRequest> | undefined;
|
||||
/** @since 3.0.0 */
|
||||
export declare function useRequestHeaders<K extends string = string>(include: K[]): {
|
||||
[key in Lowercase<K>]?: string;
|
||||
};
|
||||
export declare function useRequestHeaders(): Readonly<Record<string, string>>;
|
||||
/** @since 3.9.0 */
|
||||
export declare function useRequestHeader(header: string): string | undefined;
|
||||
/** @since 3.2.0 */
|
||||
export declare function useRequestFetch(): H3Event$Fetch | typeof globalThis.$fetch;
|
||||
/** @since 3.0.0 */
|
||||
export declare function setResponseStatus(event: H3Event, code?: number, message?: string): void;
|
||||
/** @deprecated Pass `event` as first option. */
|
||||
export declare function setResponseStatus(code: number, message?: string): void;
|
||||
/** @since 3.14.0 */
|
||||
export declare function useResponseHeader(header: string): import("vue").Ref<any, any>;
|
||||
/** @since 3.8.0 */
|
||||
export declare function prerenderRoutes(path: string | string[]): void;
|
||||
/**
|
||||
* `onPrehydrate` is a composable lifecycle hook that allows you to run a callback on the client immediately before
|
||||
* Nuxt hydrates the page. This is an advanced feature.
|
||||
*
|
||||
* The callback will be stringified and inlined in the HTML so it should not have any external
|
||||
* dependencies (such as auto-imports) or refer to variables defined outside the callback.
|
||||
*
|
||||
* The callback will run before Nuxt runtime initializes so it should not rely on the Nuxt or Vue context.
|
||||
* @since 3.12.0
|
||||
*/
|
||||
export declare function onPrehydrate(callback: (el: HTMLElement) => void): void;
|
||||
113
node_modules/nuxt/dist/app/composables/ssr.js
generated
vendored
Normal file
113
node_modules/nuxt/dist/app/composables/ssr.js
generated
vendored
Normal file
@@ -0,0 +1,113 @@
|
||||
import { setResponseStatus as _setResponseStatus, appendHeader, getRequestHeader, getRequestHeaders, getResponseHeader, removeResponseHeader, setResponseHeader } from "h3";
|
||||
import { computed, getCurrentInstance, ref } from "vue";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { toArray } from "../utils.js";
|
||||
import { useHead } from "./head.js";
|
||||
export function useRequestEvent(nuxtApp) {
|
||||
if (import.meta.client) {
|
||||
return;
|
||||
}
|
||||
nuxtApp ||= useNuxtApp();
|
||||
return nuxtApp.ssrContext?.event;
|
||||
}
|
||||
export function useRequestHeaders(include) {
|
||||
if (import.meta.client) {
|
||||
return {};
|
||||
}
|
||||
const event = useRequestEvent();
|
||||
const _headers = event ? getRequestHeaders(event) : {};
|
||||
if (!include || !event) {
|
||||
return _headers;
|
||||
}
|
||||
const headers = /* @__PURE__ */ Object.create(null);
|
||||
for (const _key of include) {
|
||||
const key = _key.toLowerCase();
|
||||
const header = _headers[key];
|
||||
if (header) {
|
||||
headers[key] = header;
|
||||
}
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
export function useRequestHeader(header) {
|
||||
if (import.meta.client) {
|
||||
return void 0;
|
||||
}
|
||||
const event = useRequestEvent();
|
||||
return event ? getRequestHeader(event, header) : void 0;
|
||||
}
|
||||
export function useRequestFetch() {
|
||||
if (import.meta.client) {
|
||||
return globalThis.$fetch;
|
||||
}
|
||||
return useRequestEvent()?.$fetch || globalThis.$fetch;
|
||||
}
|
||||
export function setResponseStatus(arg1, arg2, arg3) {
|
||||
if (import.meta.client) {
|
||||
return;
|
||||
}
|
||||
if (arg1 && typeof arg1 !== "number") {
|
||||
return _setResponseStatus(arg1, arg2, arg3);
|
||||
}
|
||||
const event = useRequestEvent();
|
||||
if (event) {
|
||||
return _setResponseStatus(event, arg1, arg2);
|
||||
}
|
||||
}
|
||||
export function useResponseHeader(header) {
|
||||
if (import.meta.client) {
|
||||
if (import.meta.dev) {
|
||||
return computed({
|
||||
get: () => void 0,
|
||||
set: () => console.warn("[nuxt] Setting response headers is not supported in the browser.")
|
||||
});
|
||||
}
|
||||
return ref();
|
||||
}
|
||||
const event = useRequestEvent();
|
||||
return computed({
|
||||
get() {
|
||||
return getResponseHeader(event, header);
|
||||
},
|
||||
set(newValue) {
|
||||
if (!newValue) {
|
||||
return removeResponseHeader(event, header);
|
||||
}
|
||||
return setResponseHeader(event, header, newValue);
|
||||
}
|
||||
});
|
||||
}
|
||||
export function prerenderRoutes(path) {
|
||||
if (!import.meta.server || !import.meta.prerender) {
|
||||
return;
|
||||
}
|
||||
const paths = toArray(path);
|
||||
appendHeader(useRequestEvent(), "x-nitro-prerender", paths.map((p) => encodeURIComponent(p)).join(", "));
|
||||
}
|
||||
const PREHYDRATE_ATTR_KEY = "data-prehydrate-id";
|
||||
export function onPrehydrate(callback, key) {
|
||||
if (import.meta.client) {
|
||||
return;
|
||||
}
|
||||
if (typeof callback !== "string") {
|
||||
throw new TypeError("[nuxt] To transform a callback into a string, `onPrehydrate` must be processed by the Nuxt build pipeline. If it is called in a third-party library, make sure to add the library to `build.transpile`.");
|
||||
}
|
||||
const vm = getCurrentInstance();
|
||||
if (vm && key) {
|
||||
vm.attrs[PREHYDRATE_ATTR_KEY] ||= "";
|
||||
key = ":" + key + ":";
|
||||
if (!vm.attrs[PREHYDRATE_ATTR_KEY].includes(key)) {
|
||||
vm.attrs[PREHYDRATE_ATTR_KEY] += key;
|
||||
}
|
||||
}
|
||||
const code = vm && key ? `document.querySelectorAll('[${PREHYDRATE_ATTR_KEY}*=${JSON.stringify(key)}]').forEach` + callback : callback + "()";
|
||||
useHead({
|
||||
script: [{
|
||||
key: vm && key ? key : void 0,
|
||||
tagPosition: "bodyClose",
|
||||
tagPriority: "critical",
|
||||
innerHTML: code
|
||||
}]
|
||||
});
|
||||
return vm && key ? vm.attrs[PREHYDRATE_ATTR_KEY] : void 0;
|
||||
}
|
||||
11
node_modules/nuxt/dist/app/composables/state.d.ts
generated
vendored
Normal file
11
node_modules/nuxt/dist/app/composables/state.d.ts
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
import type { Ref } from 'vue';
|
||||
/**
|
||||
* Create a global reactive ref that will be hydrated but not shared across ssr requests
|
||||
* @since 3.0.0
|
||||
* @param key a unique key ensuring that data fetching can be properly de-duplicated across requests
|
||||
* @param init a function that provides initial value for the state when it's not initiated
|
||||
*/
|
||||
export declare function useState<T>(key?: string, init?: (() => T | Ref<T>)): Ref<T>;
|
||||
export declare function useState<T>(init?: (() => T | Ref<T>)): Ref<T>;
|
||||
/** @since 3.6.0 */
|
||||
export declare function clearNuxtState(keys?: string | string[] | ((key: string) => boolean)): void;
|
||||
40
node_modules/nuxt/dist/app/composables/state.js
generated
vendored
Normal file
40
node_modules/nuxt/dist/app/composables/state.js
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
import { isRef, toRef } from "vue";
|
||||
import { useNuxtApp } from "../nuxt.js";
|
||||
import { toArray } from "../utils.js";
|
||||
const useStateKeyPrefix = "$s";
|
||||
export function useState(...args) {
|
||||
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
|
||||
if (typeof args[0] !== "string") {
|
||||
args.unshift(autoKey);
|
||||
}
|
||||
const [_key, init] = args;
|
||||
if (!_key || typeof _key !== "string") {
|
||||
throw new TypeError("[nuxt] [useState] key must be a string: " + _key);
|
||||
}
|
||||
if (init !== void 0 && typeof init !== "function") {
|
||||
throw new Error("[nuxt] [useState] init must be a function: " + init);
|
||||
}
|
||||
const key = useStateKeyPrefix + _key;
|
||||
const nuxtApp = useNuxtApp();
|
||||
const state = toRef(nuxtApp.payload.state, key);
|
||||
if (state.value === void 0 && init) {
|
||||
const initialValue = init();
|
||||
if (isRef(initialValue)) {
|
||||
nuxtApp.payload.state[key] = initialValue;
|
||||
return initialValue;
|
||||
}
|
||||
state.value = initialValue;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
export function clearNuxtState(keys) {
|
||||
const nuxtApp = useNuxtApp();
|
||||
const _allKeys = Object.keys(nuxtApp.payload.state).map((key) => key.substring(useStateKeyPrefix.length));
|
||||
const _keys = !keys ? _allKeys : typeof keys === "function" ? _allKeys.filter(keys) : toArray(keys);
|
||||
for (const _key of _keys) {
|
||||
const key = useStateKeyPrefix + _key;
|
||||
if (key in nuxtApp.payload.state) {
|
||||
nuxtApp.payload.state[key] = void 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
3
node_modules/nuxt/dist/app/composables/url.d.ts
generated
vendored
Normal file
3
node_modules/nuxt/dist/app/composables/url.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
import { getRequestURL } from 'h3';
|
||||
/** @since 3.5.0 */
|
||||
export declare function useRequestURL(opts?: Parameters<typeof getRequestURL>[1]): URL;
|
||||
8
node_modules/nuxt/dist/app/composables/url.js
generated
vendored
Normal file
8
node_modules/nuxt/dist/app/composables/url.js
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
import { getRequestURL } from "h3";
|
||||
import { useRequestEvent } from "./ssr.js";
|
||||
export function useRequestURL(opts) {
|
||||
if (import.meta.server) {
|
||||
return getRequestURL(useRequestEvent(), opts);
|
||||
}
|
||||
return new URL(globalThis.location.href);
|
||||
}
|
||||
Reference in New Issue
Block a user