@analogjs/router 2.7.5 → 2.8.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/fesm2022/analogjs-router-i18n.mjs +9 -0
- package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
- package/fesm2022/analogjs-router-server-actions.mjs +470 -1
- package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
- package/fesm2022/analogjs-router-server.mjs +6 -1
- package/fesm2022/analogjs-router-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query-server.mjs +90 -0
- package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -0
- package/fesm2022/analogjs-router-tanstack-query.mjs +142 -0
- package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -0
- package/fesm2022/analogjs-router.mjs +371 -17
- package/fesm2022/analogjs-router.mjs.map +1 -1
- package/package.json +17 -3
- package/types/analogjs-router-server-actions.d.ts +265 -2
- package/types/analogjs-router-tanstack-query-server.d.ts +70 -0
- package/types/analogjs-router-tanstack-query.d.ts +33 -0
- package/types/analogjs-router.d.ts +197 -17
|
@@ -61,6 +61,15 @@ function provideI18n(config) {
|
|
|
61
61
|
{ provide: I18N_CONFIG, useValue: resolved },
|
|
62
62
|
...localeProviders,
|
|
63
63
|
provideAppInitializer(async () => {
|
|
64
|
+
if (typeof window === 'undefined' &&
|
|
65
|
+
typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&
|
|
66
|
+
ANALOG_I18N_FIXED_LOCALE) {
|
|
67
|
+
// The worker entry loads translations before importing the application.
|
|
68
|
+
if (!resolved.locales.includes(ANALOG_I18N_FIXED_LOCALE)) {
|
|
69
|
+
throw new Error('The i18n worker locale must be included in provideI18n().');
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
64
73
|
const locale = resolveActiveLocale(resolved);
|
|
65
74
|
await initI18n(resolved, locale);
|
|
66
75
|
}),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analogjs-router-i18n.mjs","sources":["../../../../packages/router/i18n/src/provide-i18n.ts","../../../../packages/router/i18n/src/analogjs-router-i18n.ts"],"sourcesContent":["import {\n EnvironmentProviders,\n InjectionToken,\n assertInInjectionContext,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { LOCALE, REQUEST, ServerRequest } from '@analogjs/router/tokens';\n\ndeclare const ANALOG_I18N_DEFAULT_LOCALE: string;\ndeclare const ANALOG_I18N_LOCALES: string[];\n\n/**\n * Configuration for runtime i18n support.\n *\n * `defaultLocale` and `locales` are optional when the platform plugin\n * is configured with `i18n` in `vite.config.ts` — the values are\n * injected as build-time globals automatically.\n */\nexport interface I18nConfig {\n /**\n * The default locale to use when no locale is detected.\n * If omitted, reads from the platform plugin's `i18n.defaultLocale`.\n */\n defaultLocale?: string;\n\n /**\n * List of supported locale identifiers.\n * If omitted, reads from the platform plugin's `i18n.locales`.\n */\n locales?: string[];\n\n /**\n * A function that returns translations for a given locale.\n * The returned record maps message IDs to translated strings.\n */\n loader: (\n locale: string,\n ) => Promise<Record<string, string>> | Record<string, string>;\n}\n\n/**\n * Fully resolved i18n config with all required fields.\n */\nexport type ResolvedI18nConfig = Required<I18nConfig>;\n\n/**\n * Injection token for the resolved i18n configuration.\n * Provided by `provideI18n()` and consumed by `injectSwitchLocale()`.\n * @internal\n */\nconst I18N_CONFIG = new InjectionToken<ResolvedI18nConfig>(\n '@analogjs/router I18n Config',\n);\n\n/**\n * Resolves the full i18n config by merging explicit values with\n * build-time globals injected by the platform plugin.\n */\nexport function resolveI18nConfig(config: I18nConfig): Required<I18nConfig> {\n const defaultLocale =\n config.defaultLocale ??\n (typeof ANALOG_I18N_DEFAULT_LOCALE !== 'undefined'\n ? ANALOG_I18N_DEFAULT_LOCALE\n : undefined);\n\n const locales =\n config.locales ??\n (typeof ANALOG_I18N_LOCALES !== 'undefined'\n ? ANALOG_I18N_LOCALES\n : undefined);\n\n if (!defaultLocale || !locales) {\n throw new Error(\n '[@analogjs/router] provideI18n() requires defaultLocale and locales. ' +\n 'Either pass them explicitly or configure i18n in the analog() plugin in vite.config.ts.',\n );\n }\n\n return { defaultLocale, locales, loader: config.loader };\n}\n\n/**\n * Provides runtime i18n support using Angular's $localize.\n *\n * This provider:\n * 1. Detects the active locale from the URL or falls back to the default.\n * 2. Makes the current locale available via the LOCALE injection token.\n * 3. Loads translations for the active locale at startup using $localize.\n *\n * Works in both SSR and client-only modes. On the client, locale is detected\n * from `window.location.pathname`. On the server, locale is detected from\n * the request in `provideServerContext()` and provided at the platform level;\n * this function does not shadow it.\n *\n * When the platform plugin is configured with `i18n` in `vite.config.ts`,\n * `defaultLocale` and `locales` are injected automatically — only\n * `loader` is required:\n *\n * ```typescript\n * provideI18n({\n * loader: (locale) => import(`./i18n/${locale}.json`),\n * })\n * ```\n */\nexport function provideI18n(config: I18nConfig): EnvironmentProviders {\n const resolved = resolveI18nConfig(config);\n\n // Only provide LOCALE at the environment level on the client. On the\n // server, the platform-level LOCALE set by `provideServerContext()` is\n // authoritative and must not be shadowed by an environment-level provider.\n const localeProviders =\n typeof window !== 'undefined'\n ? [{ provide: LOCALE, useValue: detectClientLocale(resolved) }]\n : [];\n\n return makeEnvironmentProviders([\n { provide: I18N_CONFIG, useValue: resolved },\n ...localeProviders,\n provideAppInitializer(async () => {\n const locale = resolveActiveLocale(resolved);\n await initI18n(resolved, locale);\n }),\n ]);\n}\n\n/**\n * Resolves the active locale, preferring the injected `LOCALE` token\n * (which on the server reads from the platform-level provider set by\n * `provideServerContext()`) and falling back to the request URL,\n * `window.location.pathname`, or `defaultLocale`.\n */\nfunction resolveActiveLocale(config: ResolvedI18nConfig): string {\n const injected = inject(LOCALE, { optional: true });\n if (injected && config.locales.includes(injected)) {\n return injected;\n }\n\n // Fallback: read the path directly from the request on the server or\n // from the browser URL on the client. This covers cases where a locale\n // prefix is present in the URL but no token provider set it explicitly.\n const req = inject(REQUEST, { optional: true }) as ServerRequest | null;\n const pathname =\n req?.originalUrl ??\n req?.url ??\n (typeof window !== 'undefined' ? window.location.pathname : '/');\n const first = pathname.split('?')[0].split('/').filter(Boolean)[0];\n if (first && config.locales.includes(first)) {\n return first;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Detects the locale on the client from the URL path prefix.\n * Returns the default locale on the server or when no match is found.\n */\nexport function detectClientLocale(config: ResolvedI18nConfig): string {\n if (typeof window === 'undefined') {\n return config.defaultLocale;\n }\n\n const pathname = window.location.pathname;\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && config.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Loads translations for the given locale and registers them with $localize.\n *\n * Always clears any previously loaded translations first so that switching\n * between locales in a single SSR process does not mix translation maps.\n */\nexport async function initI18n(\n config: ResolvedI18nConfig,\n locale?: string,\n): Promise<void> {\n const activeLocale = locale ?? config.defaultLocale;\n await clearTranslationsRuntime();\n\n // The source locale (first entry in `locales`) has its messages baked\n // directly into the template source, so there is nothing to load.\n if (activeLocale === config.locales[0]) {\n return;\n }\n\n const translations = await config.loader(activeLocale);\n if (translations && Object.keys(translations).length > 0) {\n await loadTranslationsRuntime(translations);\n }\n}\n\n/**\n * Loads translations into the global $localize translation map.\n *\n * Uses `@angular/localize`'s `loadTranslations` when available so that\n * each translation string is parsed into the `{text, messageParts,\n * placeholderNames}` shape that `$localize.translate` expects. Falls back\n * to writing raw strings only as a last resort (in which case lookups\n * will not succeed — the fallback exists to keep error messages useful\n * for users who have not installed `@angular/localize`).\n *\n * Requires `@angular/localize/init` to be imported in the application\n * entry point so that `globalThis.$localize` is defined.\n */\nexport async function loadTranslationsRuntime(\n translations: Record<string, string>,\n): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n console.warn(\n '[@analogjs/router] $localize is not available. ' +\n 'Make sure to import @angular/localize/init in your application entry point.',\n );\n return;\n }\n\n try {\n const { loadTranslations } = (await import('@angular/localize')) as {\n loadTranslations: (t: Record<string, string>) => void;\n };\n loadTranslations(translations);\n } catch {\n console.warn(\n '[@analogjs/router] Unable to import @angular/localize. ' +\n 'Install it as a dependency to enable runtime translation loading.',\n );\n $localize.TRANSLATIONS ??= {};\n for (const [id, message] of Object.entries(translations)) {\n $localize.TRANSLATIONS[id] = message;\n }\n }\n}\n\n/**\n * Clears any previously loaded translations from `$localize` so that the\n * next render falls through to the source messages until new translations\n * are loaded. Uses `@angular/localize`'s `clearTranslations` when present.\n */\n/** @internal — exported for tests; not re-exported from the package entry. */\nexport async function clearTranslationsRuntime(): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n return;\n }\n try {\n const { clearTranslations } = (await import('@angular/localize')) as {\n clearTranslations: () => void;\n };\n clearTranslations();\n } catch {\n $localize.translate = undefined;\n $localize.TRANSLATIONS = {};\n }\n}\n\n/**\n * Returns an injectable function that switches the application locale.\n * Reads the configured locales from the I18N_CONFIG token provided\n * by `provideI18n()`.\n *\n * Triggers a full page navigation to the new locale URL so that\n * all $localize templates re-evaluate with the correct translations.\n *\n * Usage:\n * ```typescript\n * const switchLang = injectSwitchLocale();\n * switchLang('fr'); // navigates to /fr/current-path\n * ```\n */\nexport function injectSwitchLocale(): (targetLocale: string) => void {\n assertInInjectionContext(injectSwitchLocale);\n const config = inject(I18N_CONFIG);\n\n return (targetLocale: string) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const { pathname, search, hash } = window.location;\n const newPath = replaceLocaleInPath(pathname, targetLocale, config.locales);\n window.location.href = `${newPath}${search}${hash}`;\n };\n}\n\n/**\n * Replaces or inserts the locale prefix in a URL path.\n *\n * - If the path starts with a known locale, it is swapped.\n * - If no locale prefix exists, the target locale is prepended.\n */\nexport function replaceLocaleInPath(\n pathname: string,\n targetLocale: string,\n locales: string[],\n): string {\n const segments = pathname.split('/').filter(Boolean);\n\n if (segments.length > 0 && locales.includes(segments[0])) {\n segments[0] = targetLocale;\n } else {\n segments.unshift(targetLocale);\n }\n\n return '/' + segments.join('/');\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;AA+CA;;;;AAIG;AACH,MAAM,WAAW,GAAG,IAAI,cAAc,CACpC,8BAA8B,CAC/B;AAED;;;AAGG;AACG,SAAU,iBAAiB,CAAC,MAAkB,EAAA;AAClD,IAAA,MAAM,aAAa,GACjB,MAAM,CAAC,aAAa;SACnB,OAAO,0BAA0B,KAAK;AACrC,cAAE;cACA,SAAS,CAAC;AAEhB,IAAA,MAAM,OAAO,GACX,MAAM,CAAC,OAAO;SACb,OAAO,mBAAmB,KAAK;AAC9B,cAAE;cACA,SAAS,CAAC;AAEhB,IAAA,IAAI,CAAC,aAAa,IAAI,CAAC,OAAO,EAAE;QAC9B,MAAM,IAAI,KAAK,CACb,uEAAuE;AACrE,YAAA,yFAAyF,CAC5F;IACH;IAEA,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;AAC1D;AAEA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AACG,SAAU,WAAW,CAAC,MAAkB,EAAA;AAC5C,IAAA,MAAM,QAAQ,GAAG,iBAAiB,CAAC,MAAM,CAAC;;;;AAK1C,IAAA,MAAM,eAAe,GACnB,OAAO,MAAM,KAAK;AAChB,UAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE;UAC5D,EAAE;AAER,IAAA,OAAO,wBAAwB,CAAC;AAC9B,QAAA,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE;AAC5C,QAAA,GAAG,eAAe;QAClB,qBAAqB,CAAC,YAAW;AAC/B,YAAA,MAAM,MAAM,GAAG,mBAAmB,CAAC,QAAQ,CAAC;AAC5C,YAAA,MAAM,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;AAClC,QAAA,CA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,CAAC,CAAC,CAAC,GAAG,YAAY;IAC5B;SAAO;AACL,QAAA,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC;IAChC;IAEA,OAAO,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;AACjC;;ACzTA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"analogjs-router-i18n.mjs","sources":["../../../../packages/router/i18n/src/provide-i18n.ts","../../../../packages/router/i18n/src/analogjs-router-i18n.ts"],"sourcesContent":["import {\n EnvironmentProviders,\n InjectionToken,\n assertInInjectionContext,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { LOCALE, REQUEST, ServerRequest } from '@analogjs/router/tokens';\n\ndeclare const ANALOG_I18N_DEFAULT_LOCALE: string;\ndeclare const ANALOG_I18N_LOCALES: string[];\ndeclare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\n/**\n * Configuration for runtime i18n support.\n *\n * `defaultLocale` and `locales` are optional when the platform plugin\n * is configured with `i18n` in `vite.config.ts` — the values are\n * injected as build-time globals automatically.\n */\nexport interface I18nConfig {\n /**\n * The default locale to use when no locale is detected.\n * If omitted, reads from the platform plugin's `i18n.defaultLocale`.\n */\n defaultLocale?: string;\n\n /**\n * List of supported locale identifiers.\n * If omitted, reads from the platform plugin's `i18n.locales`.\n */\n locales?: string[];\n\n /**\n * A function that returns translations for a given locale.\n * The returned record maps message IDs to translated strings.\n */\n loader: (\n locale: string,\n ) => Promise<Record<string, string>> | Record<string, string>;\n}\n\n/**\n * Fully resolved i18n config with all required fields.\n */\nexport type ResolvedI18nConfig = Required<I18nConfig>;\n\n/**\n * Injection token for the resolved i18n configuration.\n * Provided by `provideI18n()` and consumed by `injectSwitchLocale()`.\n * @internal\n */\nconst I18N_CONFIG = new InjectionToken<ResolvedI18nConfig>(\n '@analogjs/router I18n Config',\n);\n\n/**\n * Resolves the full i18n config by merging explicit values with\n * build-time globals injected by the platform plugin.\n */\nexport function resolveI18nConfig(config: I18nConfig): Required<I18nConfig> {\n const defaultLocale =\n config.defaultLocale ??\n (typeof ANALOG_I18N_DEFAULT_LOCALE !== 'undefined'\n ? ANALOG_I18N_DEFAULT_LOCALE\n : undefined);\n\n const locales =\n config.locales ??\n (typeof ANALOG_I18N_LOCALES !== 'undefined'\n ? ANALOG_I18N_LOCALES\n : undefined);\n\n if (!defaultLocale || !locales) {\n throw new Error(\n '[@analogjs/router] provideI18n() requires defaultLocale and locales. ' +\n 'Either pass them explicitly or configure i18n in the analog() plugin in vite.config.ts.',\n );\n }\n\n return { defaultLocale, locales, loader: config.loader };\n}\n\n/**\n * Provides runtime i18n support using Angular's $localize.\n *\n * This provider:\n * 1. Detects the active locale from the URL or falls back to the default.\n * 2. Makes the current locale available via the LOCALE injection token.\n * 3. Loads translations for the active locale at startup using $localize.\n *\n * Works in both SSR and client-only modes. On the client, locale is detected\n * from `window.location.pathname`. On the server, locale is detected from\n * the request in `provideServerContext()` and provided at the platform level;\n * this function does not shadow it.\n *\n * When the platform plugin is configured with `i18n` in `vite.config.ts`,\n * `defaultLocale` and `locales` are injected automatically — only\n * `loader` is required:\n *\n * ```typescript\n * provideI18n({\n * loader: (locale) => import(`./i18n/${locale}.json`),\n * })\n * ```\n */\nexport function provideI18n(config: I18nConfig): EnvironmentProviders {\n const resolved = resolveI18nConfig(config);\n\n // Only provide LOCALE at the environment level on the client. On the\n // server, the platform-level LOCALE set by `provideServerContext()` is\n // authoritative and must not be shadowed by an environment-level provider.\n const localeProviders =\n typeof window !== 'undefined'\n ? [{ provide: LOCALE, useValue: detectClientLocale(resolved) }]\n : [];\n\n return makeEnvironmentProviders([\n { provide: I18N_CONFIG, useValue: resolved },\n ...localeProviders,\n provideAppInitializer(async () => {\n if (\n typeof window === 'undefined' &&\n typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE\n ) {\n // The worker entry loads translations before importing the application.\n if (!resolved.locales.includes(ANALOG_I18N_FIXED_LOCALE)) {\n throw new Error(\n 'The i18n worker locale must be included in provideI18n().',\n );\n }\n return;\n }\n const locale = resolveActiveLocale(resolved);\n await initI18n(resolved, locale);\n }),\n ]);\n}\n\n/**\n * Resolves the active locale, preferring the injected `LOCALE` token\n * (which on the server reads from the platform-level provider set by\n * `provideServerContext()`) and falling back to the request URL,\n * `window.location.pathname`, or `defaultLocale`.\n */\nfunction resolveActiveLocale(config: ResolvedI18nConfig): string {\n const injected = inject(LOCALE, { optional: true });\n if (injected && config.locales.includes(injected)) {\n return injected;\n }\n\n // Fallback: read the path directly from the request on the server or\n // from the browser URL on the client. This covers cases where a locale\n // prefix is present in the URL but no token provider set it explicitly.\n const req = inject(REQUEST, { optional: true }) as ServerRequest | null;\n const pathname =\n req?.originalUrl ??\n req?.url ??\n (typeof window !== 'undefined' ? window.location.pathname : '/');\n const first = pathname.split('?')[0].split('/').filter(Boolean)[0];\n if (first && config.locales.includes(first)) {\n return first;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Detects the locale on the client from the URL path prefix.\n * Returns the default locale on the server or when no match is found.\n */\nexport function detectClientLocale(config: ResolvedI18nConfig): string {\n if (typeof window === 'undefined') {\n return config.defaultLocale;\n }\n\n const pathname = window.location.pathname;\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && config.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Loads translations for the given locale and registers them with $localize.\n *\n * Always clears any previously loaded translations first so that switching\n * between locales in a single SSR process does not mix translation maps.\n */\nexport async function initI18n(\n config: ResolvedI18nConfig,\n locale?: string,\n): Promise<void> {\n const activeLocale = locale ?? config.defaultLocale;\n await clearTranslationsRuntime();\n\n // The source locale (first entry in `locales`) has its messages baked\n // directly into the template source, so there is nothing to load.\n if (activeLocale === config.locales[0]) {\n return;\n }\n\n const translations = await config.loader(activeLocale);\n if (translations && Object.keys(translations).length > 0) {\n await loadTranslationsRuntime(translations);\n }\n}\n\n/**\n * Loads translations into the global $localize translation map.\n *\n * Uses `@angular/localize`'s `loadTranslations` when available so that\n * each translation string is parsed into the `{text, messageParts,\n * placeholderNames}` shape that `$localize.translate` expects. Falls back\n * to writing raw strings only as a last resort (in which case lookups\n * will not succeed — the fallback exists to keep error messages useful\n * for users who have not installed `@angular/localize`).\n *\n * Requires `@angular/localize/init` to be imported in the application\n * entry point so that `globalThis.$localize` is defined.\n */\nexport async function loadTranslationsRuntime(\n translations: Record<string, string>,\n): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n console.warn(\n '[@analogjs/router] $localize is not available. ' +\n 'Make sure to import @angular/localize/init in your application entry point.',\n );\n return;\n }\n\n try {\n const { loadTranslations } = (await import('@angular/localize')) as {\n loadTranslations: (t: Record<string, string>) => void;\n };\n loadTranslations(translations);\n } catch {\n console.warn(\n '[@analogjs/router] Unable to import @angular/localize. ' +\n 'Install it as a dependency to enable runtime translation loading.',\n );\n $localize.TRANSLATIONS ??= {};\n for (const [id, message] of Object.entries(translations)) {\n $localize.TRANSLATIONS[id] = message;\n }\n }\n}\n\n/**\n * Clears any previously loaded translations from `$localize` so that the\n * next render falls through to the source messages until new translations\n * are loaded. Uses `@angular/localize`'s `clearTranslations` when present.\n */\n/** @internal — exported for tests; not re-exported from the package entry. */\nexport async function clearTranslationsRuntime(): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n return;\n }\n try {\n const { clearTranslations } = (await import('@angular/localize')) as {\n clearTranslations: () => void;\n };\n clearTranslations();\n } catch {\n $localize.translate = undefined;\n $localize.TRANSLATIONS = {};\n }\n}\n\n/**\n * Returns an injectable function that switches the application locale.\n * Reads the configured locales from the I18N_CONFIG token provided\n * by `provideI18n()`.\n *\n * Triggers a full page navigation to the new locale URL so that\n * all $localize templates re-evaluate with the correct translations.\n *\n * Usage:\n * ```typescript\n * const switchLang = injectSwitchLocale();\n * switchLang('fr'); // navigates to /fr/current-path\n * ```\n */\nexport function injectSwitchLocale(): (targetLocale: string) => void {\n assertInInjectionContext(injectSwitchLocale);\n const config = inject(I18N_CONFIG);\n\n return (targetLocale: string) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const { pathname, search, hash } = window.location;\n const newPath = replaceLocaleInPath(pathname, targetLocale, config.locales);\n window.location.href = `${newPath}${search}${hash}`;\n };\n}\n\n/**\n * Replaces or inserts the locale prefix in a URL path.\n *\n * - If the path starts with a known locale, it is swapped.\n * - If no locale prefix exists, the target locale is prepended.\n */\nexport function replaceLocaleInPath(\n pathname: string,\n targetLocale: string,\n locales: string[],\n): string {\n const segments = pathname.split('/').filter(Boolean);\n\n if (segments.length > 0 && locales.includes(segments[0])) {\n segments[0] = targetLocale;\n } else {\n segments.unshift(targetLocale);\n }\n\n return '/' + segments.join('/');\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;AAgDA;;;;AAIG;AACH,MAAM,WAAW,GAAG,IAAI,cAAc,CACpC,8BAA8B,CAC/B;AAED;;;AAGG;AACG,SAAU,iBAAiB,CAAC,MAAkB,EAAA;AAClD,IAAA,MAAM,aAAa,GACjB,MAAM,CAAC,aAAa;SACnB,OAAO,0BAA0B,KAAK;AACrC,cAAE;cACA,SAAS,CAAC;AAEhB,IAAA,MAAM,OAAO,GACX,MAAM,CAAC,OAAO;SACb,OAAO,mBAAmB,KAAK;AAC9B,cAAE;cACA,SAAS,CAAC;AAEhB,IAAA,IAAI,CAAC,aAAa,IAAI,CAAC,OAAO,EAAE;QAC9B,MAAM,IAAI,KAAK,CACb,uEAAuE;AACrE,YAAA,yFAAyF,CAC5F;IACH;IAEA,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;AAC1D;AAEA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AACG,SAAU,WAAW,CAAC,MAAkB,EAAA;AAC5C,IAAA,MAAM,QAAQ,GAAG,iBAAiB,CAAC,MAAM,CA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B,KAAI;AAC9B,QAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;YACjC;QACF;QAEA,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,QAAQ;AAClD,QAAA,MAAM,OAAO,GAAG,mBAAmB,CAAC,QAAQ,EAAE,YAAY,EAAE,MAAM,CAAC,OAAO,CAAC;AAC3E,QAAA,MAAM,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAA,EAAG,OAAO,CAAA,EAAG,MAAM,CAAA,EAAG,IAAI,CAAA,CAAE;AACrD,IAAA,CAAC;AACH;AAEA;;;;;AAKG;SACa,mBAAmB,CACjC,QAAgB,EAChB,YAAoB,EACpB,OAAiB,EAAA;AAEjB,IAAA,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;AAEpD,IAAA,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;AACxD,QAAA,QAAQ,CAAC,CAAC,CAAC,GAAG,YAAY;IAC5B;SAAO;AACL,QAAA,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC;IAChC;IAEA,OAAO,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;AACjC;;ACvUA;;AAEG;;;;"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { toWebRequest, getRequestURL, readBody, readFormData } from 'h3';
|
|
2
|
+
|
|
1
3
|
function fail(status, errors) {
|
|
2
4
|
return new Response(JSON.stringify(errors), {
|
|
3
5
|
status,
|
|
@@ -31,9 +33,476 @@ function redirect(url, config = 302) {
|
|
|
31
33
|
});
|
|
32
34
|
}
|
|
33
35
|
|
|
36
|
+
function appendEntry(target, key, value) {
|
|
37
|
+
const existingValue = target[key];
|
|
38
|
+
if (existingValue === undefined) {
|
|
39
|
+
target[key] = value;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (Array.isArray(existingValue)) {
|
|
43
|
+
existingValue.push(value);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
target[key] = [existingValue, value];
|
|
47
|
+
}
|
|
48
|
+
function getRequest(event) {
|
|
49
|
+
return event.web?.request ?? toWebRequest(event);
|
|
50
|
+
}
|
|
51
|
+
function getRequestUrl(event) {
|
|
52
|
+
return event.web?.request?.url ?? getRequestURL(event).href;
|
|
53
|
+
}
|
|
54
|
+
function getContentType(event) {
|
|
55
|
+
return (event.web?.request?.headers.get('content-type') ??
|
|
56
|
+
event.headers.get('content-type') ??
|
|
57
|
+
'');
|
|
58
|
+
}
|
|
59
|
+
function isJsonContentType(contentType) {
|
|
60
|
+
const mimeType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
|
61
|
+
return mimeType === 'application/json' || mimeType.endsWith('+json');
|
|
62
|
+
}
|
|
63
|
+
function isFormContentType(contentType) {
|
|
64
|
+
return (contentType.includes('multipart/form-data') ||
|
|
65
|
+
contentType.includes('application/x-www-form-urlencoded'));
|
|
66
|
+
}
|
|
67
|
+
function parseSearchParams(searchParams) {
|
|
68
|
+
const result = Object.create(null);
|
|
69
|
+
searchParams.forEach((value, key) => {
|
|
70
|
+
appendEntry(result, key, value);
|
|
71
|
+
});
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
function parseFormData(formData) {
|
|
75
|
+
const result = Object.create(null);
|
|
76
|
+
formData.forEach((value, key) => {
|
|
77
|
+
appendEntry(result, key, value);
|
|
78
|
+
});
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
async function parseRequestData(event) {
|
|
82
|
+
const method = event.method.toUpperCase();
|
|
83
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
84
|
+
const url = new URL(getRequestUrl(event), 'http://localhost');
|
|
85
|
+
return parseSearchParams(url.searchParams);
|
|
86
|
+
}
|
|
87
|
+
const contentType = getContentType(event);
|
|
88
|
+
if (isJsonContentType(contentType)) {
|
|
89
|
+
try {
|
|
90
|
+
return (await readBody(event)) ?? {};
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
try {
|
|
94
|
+
return await getRequest(event).json();
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return {};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (isFormContentType(contentType)) {
|
|
102
|
+
try {
|
|
103
|
+
return parseFormData(await readFormData(event));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
const request = getRequest(event);
|
|
107
|
+
if (typeof request.formData === 'function') {
|
|
108
|
+
try {
|
|
109
|
+
return parseFormData(await request.formData());
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return {};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return {};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
return (await readBody(event)) ?? {};
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
try {
|
|
123
|
+
return await getRequest(event).json();
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return {};
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Validates unknown input against a Standard Schema.
|
|
133
|
+
*
|
|
134
|
+
* Handles both sync and async `validate` implementations — the Standard
|
|
135
|
+
* Schema spec allows either return shape.
|
|
136
|
+
*/
|
|
137
|
+
async function validateWithSchema(schema, data) {
|
|
138
|
+
return schema['~standard'].validate(data);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function isDevEnvironment$1() {
|
|
142
|
+
return (typeof process !== 'undefined' &&
|
|
143
|
+
(process.env['NODE_ENV'] === 'development' ||
|
|
144
|
+
process.env['NODE_ENV'] === 'test'));
|
|
145
|
+
}
|
|
146
|
+
function warnOnOutputIssues$1(issues) {
|
|
147
|
+
console.warn(`[analog] Server route output validation failed:\n` +
|
|
148
|
+
issues
|
|
149
|
+
.map((i) => {
|
|
150
|
+
const path = i.path
|
|
151
|
+
? ` at "${i.path.map((p) => (typeof p === 'object' ? p.key : p)).join('.')}"`
|
|
152
|
+
: '';
|
|
153
|
+
return ` - ${i.message}${path}`;
|
|
154
|
+
})
|
|
155
|
+
.join('\n'));
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Creates an h3-compatible event handler with Standard Schema validation.
|
|
159
|
+
*
|
|
160
|
+
* - `input` schema validates the request body (POST/PUT/PATCH) or query
|
|
161
|
+
* params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.
|
|
162
|
+
* - `output` schema validates the response in development only (stripped
|
|
163
|
+
* in production for zero overhead). Logs a warning on mismatch.
|
|
164
|
+
* - Plain return values are serialized with `json(...)`; raw `Response`
|
|
165
|
+
* objects are returned unchanged.
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```typescript
|
|
169
|
+
* import { defineServerRoute } from '@analogjs/router/server/actions';
|
|
170
|
+
* import * as v from 'valibot';
|
|
171
|
+
*
|
|
172
|
+
* const Input = v.object({
|
|
173
|
+
* name: v.pipe(v.string(), v.minLength(1)),
|
|
174
|
+
* email: v.pipe(v.string(), v.email()),
|
|
175
|
+
* });
|
|
176
|
+
* const Output = v.object({
|
|
177
|
+
* id: v.string(),
|
|
178
|
+
* name: v.string(),
|
|
179
|
+
* });
|
|
180
|
+
*
|
|
181
|
+
* export default defineServerRoute({
|
|
182
|
+
* input: Input,
|
|
183
|
+
* output: Output,
|
|
184
|
+
* handler: async ({ data }) => {
|
|
185
|
+
* const user = await db.users.create(data);
|
|
186
|
+
* return user;
|
|
187
|
+
* },
|
|
188
|
+
* });
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
function defineServerRoute(options) {
|
|
192
|
+
return (async (event) => {
|
|
193
|
+
const method = event.method.toUpperCase();
|
|
194
|
+
let data;
|
|
195
|
+
let query;
|
|
196
|
+
let body;
|
|
197
|
+
let params = event.context?.params ?? {};
|
|
198
|
+
if (options.params) {
|
|
199
|
+
const paramsResult = await validateWithSchema(options.params, params);
|
|
200
|
+
if (paramsResult.issues) {
|
|
201
|
+
return fail(422, paramsResult.issues);
|
|
202
|
+
}
|
|
203
|
+
params = paramsResult.value;
|
|
204
|
+
}
|
|
205
|
+
const hasBody = method !== 'GET' && method !== 'HEAD';
|
|
206
|
+
const requestData = options.input || (options.body && hasBody)
|
|
207
|
+
? await parseRequestData(event)
|
|
208
|
+
: undefined;
|
|
209
|
+
if (options.input) {
|
|
210
|
+
const inputResult = await validateWithSchema(options.input, requestData);
|
|
211
|
+
if (inputResult.issues) {
|
|
212
|
+
return fail(422, inputResult.issues);
|
|
213
|
+
}
|
|
214
|
+
data = inputResult.value;
|
|
215
|
+
}
|
|
216
|
+
if (options.query) {
|
|
217
|
+
const url = new URL(getRequestUrl(event), 'http://localhost');
|
|
218
|
+
const queryResult = await validateWithSchema(options.query, parseSearchParams(url.searchParams));
|
|
219
|
+
if (queryResult.issues) {
|
|
220
|
+
return fail(422, queryResult.issues);
|
|
221
|
+
}
|
|
222
|
+
query = queryResult.value;
|
|
223
|
+
}
|
|
224
|
+
if (options.body && hasBody) {
|
|
225
|
+
const bodyResult = await validateWithSchema(options.body, requestData);
|
|
226
|
+
if (bodyResult.issues) {
|
|
227
|
+
return fail(422, bodyResult.issues);
|
|
228
|
+
}
|
|
229
|
+
body = bodyResult.value;
|
|
230
|
+
}
|
|
231
|
+
if (!options.input) {
|
|
232
|
+
if (!hasBody) {
|
|
233
|
+
data = query;
|
|
234
|
+
}
|
|
235
|
+
else if (body !== undefined) {
|
|
236
|
+
data = body;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
data = query;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const result = await options.handler({
|
|
243
|
+
data: data,
|
|
244
|
+
query: query,
|
|
245
|
+
body: body,
|
|
246
|
+
params: params,
|
|
247
|
+
event,
|
|
248
|
+
});
|
|
249
|
+
if (result instanceof Response) {
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
if (options.output && isDevEnvironment$1()) {
|
|
253
|
+
const outputResult = await validateWithSchema(options.output, result);
|
|
254
|
+
if (outputResult.issues) {
|
|
255
|
+
warnOnOutputIssues$1(outputResult.issues);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return json(result);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Creates a typed page server load function with optional
|
|
264
|
+
* Standard Schema validation for route params and query.
|
|
265
|
+
*
|
|
266
|
+
* Follows the same validation pattern as `defineServerRoute`:
|
|
267
|
+
* validates before invoking the handler and returns
|
|
268
|
+
* `fail(422, issues)` on validation failure.
|
|
269
|
+
*
|
|
270
|
+
* @example
|
|
271
|
+
* ```typescript
|
|
272
|
+
* // src/app/pages/users/[id].server.ts
|
|
273
|
+
* import { definePageLoad } from '@analogjs/router/server/actions';
|
|
274
|
+
* import * as v from 'valibot';
|
|
275
|
+
*
|
|
276
|
+
* export const routeParamsSchema = v.object({
|
|
277
|
+
* id: v.pipe(v.string(), v.regex(/^\d+$/)),
|
|
278
|
+
* });
|
|
279
|
+
*
|
|
280
|
+
* export const load = definePageLoad({
|
|
281
|
+
* params: routeParamsSchema,
|
|
282
|
+
* handler: async ({ params, fetch }) => {
|
|
283
|
+
* // params.id is typed as string (validated)
|
|
284
|
+
* const user = await fetch(`/api/users/${params.id}`);
|
|
285
|
+
* return user;
|
|
286
|
+
* },
|
|
287
|
+
* });
|
|
288
|
+
* ```
|
|
289
|
+
*/
|
|
290
|
+
function definePageLoad(options) {
|
|
291
|
+
return async (ctx) => {
|
|
292
|
+
let params = ctx.params ?? {};
|
|
293
|
+
const url = new URL(getRequestUrl(ctx.event), 'http://localhost');
|
|
294
|
+
let query = parseSearchParams(url.searchParams);
|
|
295
|
+
// Validate params
|
|
296
|
+
if (options.params) {
|
|
297
|
+
const result = await validateWithSchema(options.params, params);
|
|
298
|
+
if (result.issues) {
|
|
299
|
+
return fail(422, result.issues);
|
|
300
|
+
}
|
|
301
|
+
params = result.value;
|
|
302
|
+
}
|
|
303
|
+
// Validate query
|
|
304
|
+
if (options.query) {
|
|
305
|
+
const result = await validateWithSchema(options.query, query);
|
|
306
|
+
if (result.issues) {
|
|
307
|
+
return fail(422, result.issues);
|
|
308
|
+
}
|
|
309
|
+
query = result.value;
|
|
310
|
+
}
|
|
311
|
+
return options.handler({
|
|
312
|
+
params: params,
|
|
313
|
+
query: query,
|
|
314
|
+
req: ctx.req,
|
|
315
|
+
res: ctx.res,
|
|
316
|
+
fetch: ctx.fetch,
|
|
317
|
+
event: ctx.event,
|
|
318
|
+
});
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Creates a server action handler with Standard Schema input validation.
|
|
324
|
+
*
|
|
325
|
+
* Parses the request body (JSON or FormData) and validates it against the
|
|
326
|
+
* provided schema before invoking the handler. On validation failure,
|
|
327
|
+
* returns `fail(422, issues)` with `StandardSchemaV1.Issue[]`.
|
|
328
|
+
* Repeated form fields are preserved as arrays instead of being collapsed
|
|
329
|
+
* to the last value.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* ```typescript
|
|
333
|
+
* import { defineAction, json } from '@analogjs/router/server/actions';
|
|
334
|
+
* import * as v from 'valibot';
|
|
335
|
+
*
|
|
336
|
+
* const Schema = v.object({
|
|
337
|
+
* email: v.pipe(v.string(), v.email()),
|
|
338
|
+
* });
|
|
339
|
+
*
|
|
340
|
+
* export const action = defineAction({
|
|
341
|
+
* schema: Schema,
|
|
342
|
+
* handler: async ({ data }) => {
|
|
343
|
+
* // data is typed as { email: string }
|
|
344
|
+
* return json({ ok: true });
|
|
345
|
+
* },
|
|
346
|
+
* });
|
|
347
|
+
* ```
|
|
348
|
+
*/
|
|
349
|
+
function defineAction(options) {
|
|
350
|
+
function getParams(params) {
|
|
351
|
+
return (params ?? {});
|
|
352
|
+
}
|
|
353
|
+
return async (ctx) => {
|
|
354
|
+
const rawParams = getParams(ctx.params);
|
|
355
|
+
if (options.params) {
|
|
356
|
+
const paramsResult = await validateWithSchema(options.params, rawParams);
|
|
357
|
+
if (paramsResult.issues) {
|
|
358
|
+
return fail(422, paramsResult.issues);
|
|
359
|
+
}
|
|
360
|
+
return handleValidatedRequest(ctx, options, paramsResult.value);
|
|
361
|
+
}
|
|
362
|
+
return handleValidatedRequest(ctx, options, rawParams);
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
async function handleValidatedRequest(ctx, options, params) {
|
|
366
|
+
const body = await parseRequestData(ctx.event);
|
|
367
|
+
let data = body;
|
|
368
|
+
if (options.schema) {
|
|
369
|
+
const result = await validateWithSchema(options.schema, body);
|
|
370
|
+
if (result.issues) {
|
|
371
|
+
return fail(422, result.issues);
|
|
372
|
+
}
|
|
373
|
+
data = result.value;
|
|
374
|
+
}
|
|
375
|
+
return options.handler({
|
|
376
|
+
data: data,
|
|
377
|
+
params,
|
|
378
|
+
req: ctx.req,
|
|
379
|
+
res: ctx.res,
|
|
380
|
+
fetch: ctx.fetch,
|
|
381
|
+
event: ctx.event,
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function isDevEnvironment() {
|
|
386
|
+
return (typeof process !== 'undefined' &&
|
|
387
|
+
(process.env['NODE_ENV'] === 'development' ||
|
|
388
|
+
process.env['NODE_ENV'] === 'test'));
|
|
389
|
+
}
|
|
390
|
+
function warnOnOutputIssues(issues) {
|
|
391
|
+
console.warn(`[analog] API route output validation failed:\n` +
|
|
392
|
+
issues
|
|
393
|
+
.map((i) => {
|
|
394
|
+
const path = i.path
|
|
395
|
+
? ` at "${i.path.map((p) => (typeof p === 'object' ? p.key : p)).join('.')}"`
|
|
396
|
+
: '';
|
|
397
|
+
return ` - ${i.message}${path}`;
|
|
398
|
+
})
|
|
399
|
+
.join('\n'));
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Creates an h3-compatible event handler with Standard Schema validation.
|
|
403
|
+
*
|
|
404
|
+
* - `input` schema validates the request body (POST/PUT/PATCH) or query
|
|
405
|
+
* params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.
|
|
406
|
+
* - `output` schema validates the response in development and tests only. Logs a warning on mismatch.
|
|
407
|
+
* - Plain return values are serialized with `json(...)`; raw `Response`
|
|
408
|
+
* objects are returned unchanged.
|
|
409
|
+
*
|
|
410
|
+
* @example
|
|
411
|
+
* ```typescript
|
|
412
|
+
* import { defineApiRoute } from '@analogjs/router/server/actions';
|
|
413
|
+
* import * as v from 'valibot';
|
|
414
|
+
*
|
|
415
|
+
* const Input = v.object({
|
|
416
|
+
* name: v.pipe(v.string(), v.minLength(1)),
|
|
417
|
+
* email: v.pipe(v.string(), v.email()),
|
|
418
|
+
* });
|
|
419
|
+
* const Output = v.object({
|
|
420
|
+
* id: v.string(),
|
|
421
|
+
* name: v.string(),
|
|
422
|
+
* });
|
|
423
|
+
*
|
|
424
|
+
* export default defineApiRoute({
|
|
425
|
+
* input: Input,
|
|
426
|
+
* output: Output,
|
|
427
|
+
* handler: async ({ data }) => {
|
|
428
|
+
* const user = await db.users.create(data);
|
|
429
|
+
* return user;
|
|
430
|
+
* },
|
|
431
|
+
* });
|
|
432
|
+
* ```
|
|
433
|
+
*/
|
|
434
|
+
function defineApiRoute(options) {
|
|
435
|
+
return async (event) => {
|
|
436
|
+
const method = event.method.toUpperCase();
|
|
437
|
+
let data;
|
|
438
|
+
let query;
|
|
439
|
+
let body;
|
|
440
|
+
let params = event.context?.params ?? {};
|
|
441
|
+
if (options.params) {
|
|
442
|
+
const paramsResult = await validateWithSchema(options.params, params);
|
|
443
|
+
if (paramsResult.issues) {
|
|
444
|
+
return fail(422, paramsResult.issues);
|
|
445
|
+
}
|
|
446
|
+
params = paramsResult.value;
|
|
447
|
+
}
|
|
448
|
+
const requestData = options.input || (options.body && method !== 'GET' && method !== 'HEAD')
|
|
449
|
+
? await parseRequestData(event)
|
|
450
|
+
: undefined;
|
|
451
|
+
if (options.input) {
|
|
452
|
+
data = requestData;
|
|
453
|
+
const inputResult = await validateWithSchema(options.input, data);
|
|
454
|
+
if (inputResult.issues) {
|
|
455
|
+
return fail(422, inputResult.issues);
|
|
456
|
+
}
|
|
457
|
+
data = inputResult.value;
|
|
458
|
+
}
|
|
459
|
+
if (options.query) {
|
|
460
|
+
const url = new URL(getRequestUrl(event), 'http://localhost');
|
|
461
|
+
const queryResult = await validateWithSchema(options.query, parseSearchParams(url.searchParams));
|
|
462
|
+
if (queryResult.issues) {
|
|
463
|
+
return fail(422, queryResult.issues);
|
|
464
|
+
}
|
|
465
|
+
query = queryResult.value;
|
|
466
|
+
}
|
|
467
|
+
if (options.body && method !== 'GET' && method !== 'HEAD') {
|
|
468
|
+
body = requestData;
|
|
469
|
+
const bodyResult = await validateWithSchema(options.body, body);
|
|
470
|
+
if (bodyResult.issues) {
|
|
471
|
+
return fail(422, bodyResult.issues);
|
|
472
|
+
}
|
|
473
|
+
body = bodyResult.value;
|
|
474
|
+
}
|
|
475
|
+
if (!options.input) {
|
|
476
|
+
data =
|
|
477
|
+
method === 'GET' || method === 'HEAD'
|
|
478
|
+
? query
|
|
479
|
+
: body !== undefined
|
|
480
|
+
? body
|
|
481
|
+
: query;
|
|
482
|
+
}
|
|
483
|
+
const result = await options.handler({
|
|
484
|
+
data: data,
|
|
485
|
+
query: query,
|
|
486
|
+
body: body,
|
|
487
|
+
params: params,
|
|
488
|
+
event,
|
|
489
|
+
});
|
|
490
|
+
if (result instanceof Response) {
|
|
491
|
+
return result;
|
|
492
|
+
}
|
|
493
|
+
if (options.output && isDevEnvironment()) {
|
|
494
|
+
const outputResult = await validateWithSchema(options.output, result);
|
|
495
|
+
if (outputResult.issues) {
|
|
496
|
+
warnOnOutputIssues(outputResult.issues);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return json(result);
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
34
503
|
/**
|
|
35
504
|
* Generated bundle index. Do not edit.
|
|
36
505
|
*/
|
|
37
506
|
|
|
38
|
-
export { fail, json, redirect };
|
|
507
|
+
export { defineAction, defineApiRoute, definePageLoad, defineServerRoute, fail, json, redirect, validateWithSchema };
|
|
39
508
|
//# sourceMappingURL=analogjs-router-server-actions.mjs.map
|