@sugardarius/anzen 2.2.1 → 2.3.1

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.
@@ -1,10 +1,10 @@
1
- import { i as StandardSchemaDictionary, g as Awaitable, j as StandardSchemaV1, A as AuthContext, U as UnwrapReadonlyObject, E as EmptyObjectType } from '../types-D-blrRCr.cjs';
1
+ import { A as AuthContext, S as StandardSchemaDictionary, b as Awaitable, a as StandardSchemaV1, U as UnwrapReadonlyObject, E as EmptyObjectType } from '../standard-schema-BHEkWkzf.cjs';
2
2
 
3
3
  type ArrayToUnion<T extends readonly (string | number)[]> = T[number];
4
4
  type TSegmentsDict = StandardSchemaDictionary;
5
5
  type TSearchParamsDict = StandardSchemaDictionary;
6
6
  type OnValidationError = (issues: readonly StandardSchemaV1.Issue[]) => Awaitable<never>;
7
- type BaseOptions<TSegments extends TSegmentsDict | undefined> = {
7
+ type ServerComponentBaseOptions<TSegments extends TSegmentsDict | undefined> = {
8
8
  /**
9
9
  * ID for the server component.
10
10
  * Used when logging in development or when `debug` is enabled.
@@ -18,7 +18,7 @@ type BaseOptions<TSegments extends TSegmentsDict | undefined> = {
18
18
  * band use error boundaries. The error is logged into the console.
19
19
  *
20
20
  * Use it if you want to manage unexpected errors properly
21
- * to log, trace or define behaviors like using `notFound` or `redirect`.
21
+ * to log, trace or define navigation behaviors like using `notFound` or `redirect`.
22
22
  */
23
23
  onError?: (err: unknown) => Awaitable<never>;
24
24
  /**
@@ -71,7 +71,7 @@ type LayoutAuthFunctionParams<TSegments extends TSegmentsDict | undefined> = {
71
71
  } : EmptyObjectType);
72
72
  type PageAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = (params: PageAuthFunctionParams<TSegments, TSearchParams>) => Awaitable<AC | never>;
73
73
  type LayoutAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = (params: LayoutAuthFunctionParams<TSegments>) => Awaitable<AC | never>;
74
- type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = BaseOptions<TSegments> & {
74
+ type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = ServerComponentBaseOptions<TSegments> & {
75
75
  /**
76
76
  * Search params used in the route.
77
77
  *
@@ -92,7 +92,7 @@ type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TS
92
92
  */
93
93
  authorize?: PageAuthFunction<AC, TSegments, TSearchParams>;
94
94
  };
95
- type CreateSafeLayoutServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSlots extends readonly string[] | undefined> = BaseOptions<TSegments> & {
95
+ type CreateSafeLayoutServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSlots extends readonly string[] | undefined> = ServerComponentBaseOptions<TSegments> & {
96
96
  /**
97
97
  * Function to use to authorize the server component.
98
98
  * By default it always authorize the server component.
@@ -220,4 +220,4 @@ declare function createSafePageServerComponent<AC extends AuthContext | undefine
220
220
  */
221
221
  declare function createSafeLayoutServerComponent<AC extends AuthContext | undefined = undefined, TSegments extends TSegmentsDict | undefined = undefined, TSlots extends readonly string[] | undefined = undefined>(options: CreateSafeLayoutServerComponentOptions<AC, TSegments, TSlots>, layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments, TSlots>): CreateSafeLayoutServerComponentReturnType<TSlots>;
222
222
 
223
- export { type BaseOptions, type CreateSafeLayoutServerComponentOptions, type CreateSafeLayoutServerComponentReturnType, type CreateSafePageServerComponentOptions, type CreateSafePageServerComponentReturnType, type LayoutAuthFunction, type LayoutAuthFunctionParams, type OnValidationError, type PageAuthFunction, type PageAuthFunctionParams, type SafeLayoutServerComponent, type SafeLayoutServerComponentContext, type SafePageServerComponent, type SafePageServerComponentContext, type TSearchParamsDict, type TSegmentsDict, createSafeLayoutServerComponent, createSafePageServerComponent };
223
+ export { type CreateSafeLayoutServerComponentOptions, type CreateSafeLayoutServerComponentReturnType, type CreateSafePageServerComponentOptions, type CreateSafePageServerComponentReturnType, type LayoutAuthFunction, type LayoutAuthFunctionParams, type OnValidationError, type PageAuthFunction, type PageAuthFunctionParams, type SafeLayoutServerComponent, type SafeLayoutServerComponentContext, type SafePageServerComponent, type SafePageServerComponentContext, type ServerComponentBaseOptions, type TSearchParamsDict, type TSegmentsDict, createSafeLayoutServerComponent, createSafePageServerComponent };
@@ -1,10 +1,10 @@
1
- import { i as StandardSchemaDictionary, g as Awaitable, j as StandardSchemaV1, A as AuthContext, U as UnwrapReadonlyObject, E as EmptyObjectType } from '../types-D-blrRCr.js';
1
+ import { A as AuthContext, S as StandardSchemaDictionary, b as Awaitable, a as StandardSchemaV1, U as UnwrapReadonlyObject, E as EmptyObjectType } from '../standard-schema-BHEkWkzf.js';
2
2
 
3
3
  type ArrayToUnion<T extends readonly (string | number)[]> = T[number];
4
4
  type TSegmentsDict = StandardSchemaDictionary;
5
5
  type TSearchParamsDict = StandardSchemaDictionary;
6
6
  type OnValidationError = (issues: readonly StandardSchemaV1.Issue[]) => Awaitable<never>;
7
- type BaseOptions<TSegments extends TSegmentsDict | undefined> = {
7
+ type ServerComponentBaseOptions<TSegments extends TSegmentsDict | undefined> = {
8
8
  /**
9
9
  * ID for the server component.
10
10
  * Used when logging in development or when `debug` is enabled.
@@ -18,7 +18,7 @@ type BaseOptions<TSegments extends TSegmentsDict | undefined> = {
18
18
  * band use error boundaries. The error is logged into the console.
19
19
  *
20
20
  * Use it if you want to manage unexpected errors properly
21
- * to log, trace or define behaviors like using `notFound` or `redirect`.
21
+ * to log, trace or define navigation behaviors like using `notFound` or `redirect`.
22
22
  */
23
23
  onError?: (err: unknown) => Awaitable<never>;
24
24
  /**
@@ -71,7 +71,7 @@ type LayoutAuthFunctionParams<TSegments extends TSegmentsDict | undefined> = {
71
71
  } : EmptyObjectType);
72
72
  type PageAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = (params: PageAuthFunctionParams<TSegments, TSearchParams>) => Awaitable<AC | never>;
73
73
  type LayoutAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = (params: LayoutAuthFunctionParams<TSegments>) => Awaitable<AC | never>;
74
- type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = BaseOptions<TSegments> & {
74
+ type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = ServerComponentBaseOptions<TSegments> & {
75
75
  /**
76
76
  * Search params used in the route.
77
77
  *
@@ -92,7 +92,7 @@ type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TS
92
92
  */
93
93
  authorize?: PageAuthFunction<AC, TSegments, TSearchParams>;
94
94
  };
95
- type CreateSafeLayoutServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSlots extends readonly string[] | undefined> = BaseOptions<TSegments> & {
95
+ type CreateSafeLayoutServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSlots extends readonly string[] | undefined> = ServerComponentBaseOptions<TSegments> & {
96
96
  /**
97
97
  * Function to use to authorize the server component.
98
98
  * By default it always authorize the server component.
@@ -220,4 +220,4 @@ declare function createSafePageServerComponent<AC extends AuthContext | undefine
220
220
  */
221
221
  declare function createSafeLayoutServerComponent<AC extends AuthContext | undefined = undefined, TSegments extends TSegmentsDict | undefined = undefined, TSlots extends readonly string[] | undefined = undefined>(options: CreateSafeLayoutServerComponentOptions<AC, TSegments, TSlots>, layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments, TSlots>): CreateSafeLayoutServerComponentReturnType<TSlots>;
222
222
 
223
- export { type BaseOptions, type CreateSafeLayoutServerComponentOptions, type CreateSafeLayoutServerComponentReturnType, type CreateSafePageServerComponentOptions, type CreateSafePageServerComponentReturnType, type LayoutAuthFunction, type LayoutAuthFunctionParams, type OnValidationError, type PageAuthFunction, type PageAuthFunctionParams, type SafeLayoutServerComponent, type SafeLayoutServerComponentContext, type SafePageServerComponent, type SafePageServerComponentContext, type TSearchParamsDict, type TSegmentsDict, createSafeLayoutServerComponent, createSafePageServerComponent };
223
+ export { type CreateSafeLayoutServerComponentOptions, type CreateSafeLayoutServerComponentReturnType, type CreateSafePageServerComponentOptions, type CreateSafePageServerComponentReturnType, type LayoutAuthFunction, type LayoutAuthFunctionParams, type OnValidationError, type PageAuthFunction, type PageAuthFunctionParams, type SafeLayoutServerComponent, type SafeLayoutServerComponentContext, type SafePageServerComponent, type SafePageServerComponentContext, type ServerComponentBaseOptions, type TSearchParamsDict, type TSegmentsDict, createSafeLayoutServerComponent, createSafePageServerComponent };
@@ -1,2 +1,2 @@
1
- import{a as x,b as w,c as T,e as v}from"../chunk-WEUMYDOP.js";var p=class extends Error{constructor(o,t,e){super(`${o==="searchParams"?"Search params":"Segments"} validation error for ${e} server component '${t}`),this.name="ValidationError"}},g=class extends Error{constructor(o,t){super(`No segments provided for ${t} server component '${o}'`),this.name="NoSegmentsProvidedError"}},h=class extends Error{constructor(o,t){super(`No search params provided for ${t} server component '${o}'`),this.name="NoSearchParamsProvidedError"}},P=class extends Error{constructor(o,t){let e=t.map(f=>`'${f}'`).join(", ");super(`Missing slots [${e}] for layout server component '${o}'`),this.name="MissingLayoutSlotsError"}};var A="[unknown:page:server:component]";function $(r,o){let t=x(r.debug),e=r.id??A,f=r.onError??(c=>{throw t.error(`\u{1F6D1} Unexpected error in page server component '${e}'`,c),c}),C=r.onSegmentsValidationError??(c=>{throw t.error(`\u{1F6D1} Invalid segments for page server component '${e}'`,c),new p("segments",e,"page")}),y=r.onSearchParamsValidationError??(c=>{throw t.error(`\u{1F6D1} Invalid search params for server component '${e}'`,c),new p("searchParams",e,"page")}),d=r.authorize??(async()=>{});return async function(l){let m=w();m.start(),t.info(`\u{1F504} Running page server component'${e}'`);let s;if(r.segments){let a=await l.params;if(a===void 0)throw new g(e,"page");let n=v(r.segments,a);n.issues?await C(n.issues):s=n.value}let i;if(r.searchParams){let a=await l.searchParams;if(a===void 0)throw new h(e,"page");let n=v(r.searchParams,a);n.issues?await y(n.issues):i=n.value}let S;try{let a={id:e,...s?{segments:s}:{},...i?{searchParams:i}:{}};S=await d(a)}catch(a){throw t.error(`\u{1F6D1} Page server component '${e}' not authorized`),a}try{let a={id:e,...S?{auth:S}:{},...s?{segments:s}:{},...i?{searchParams:i}:{}},n=await o(a);return m.stop(),t.info(`\u2705 Page server component '${e}' executed successfully in ${m.get()}`),n}catch(a){if(m.stop(),T(a))throw t.info("\u2139\uFE0F Ignoring native Next.js error"),a;return t.error(`\u{1F6D1} Page server component '${e}' failed to execute after ${m.get()}`),await f(a)}}}var E="[unknown:layout:server:component]";function D(r,o){let t=x(r.debug),e=r.id??E,f=r.onError??(d=>{throw t.error(`\u{1F6D1} Unexpected error in layout server component '${e}'`,d),d}),C=r.onSegmentsValidationError??(d=>{throw t.error(`\u{1F6D1} Invalid segments for layout server component '${e}'`,d),new p("segments",e,"page")}),y=r.authorize??(async()=>{});return async function({params:c,children:l,...m}){let s=w();s.start(),t.info(`\u{1F504} Running layout server component'${e}'`);let i;if(r.segments){let n=await c;if(n===void 0)throw new g(e,"page");let u=v(r.segments,n);u.issues?await C(u.issues):i=u.value}let S;if(r.experimental_slots){let n=r.experimental_slots,u=[];for(let L of n)L in m||u.push(L);if(u.length>0)throw new P(e,u);S=m}let a;try{let n={id:e,...i?{segments:i}:{}};a=await y(n)}catch(n){throw t.error(`\u{1F6D1} Layout server component '${e}' not authorized`),n}try{let n={id:e,...a?{auth:a}:{},...i?{segments:i}:{},children:l,...S?{experimental_slots:S}:{}},u=await o(n);return s.stop(),t.info(`\u2705 Layout server component '${e}' executed successfully in ${s.get()}`),u}catch(n){if(s.stop(),T(n))throw t.info("\u2139\uFE0F Ignoring native Next.js error"),n;return t.error(`\u{1F6D1} Layout server component '${e}' failed to execute after ${s.get()}`),await f(n)}}}export{D as createSafeLayoutServerComponent,$ as createSafePageServerComponent};
1
+ import{a as x,b as w,c as T,g as v}from"../chunk-A7I43FHB.js";var S=class extends Error{constructor(s,t,e){super(`${s==="searchParams"?"Search params":"Segments"} validation error for ${e} server component '${t}`),this.name="ValidationError"}},g=class extends Error{constructor(s,t){super(`No segments provided for ${t} server component '${s}'`),this.name="NoSegmentsProvidedError"}},h=class extends Error{constructor(s,t){super(`No search params provided for ${t} server component '${s}'`),this.name="NoSearchParamsProvidedError"}},C=class extends Error{constructor(s,t){let e=t.map(f=>`'${f}'`).join(", ");super(`Missing slots [${e}] for layout server component '${s}'`),this.name="MissingLayoutSlotsError"}};var L="[unknown:page:server:component]";function A(r,s){let t=x(r.debug),e=r.id??L,f=r.onError??(u=>{throw t.error(`\u{1F6D1} Unexpected error in page server component '${e}'`,u),u}),P=r.onSegmentsValidationError??(u=>{throw t.error(`\u{1F6D1} Invalid segments for page server component '${e}'`,u),new S("segments",e,"page")}),y=r.onSearchParamsValidationError??(u=>{throw t.error(`\u{1F6D1} Invalid search params for server component '${e}'`,u),new S("searchParams",e,"page")}),p=r.authorize??(async()=>{});return async function(l){let i=w();i.start(),t.info(`\u{1F504} Running page server component'${e}'`);let a;if(r.segments){let o=await l.params;if(o===void 0)throw new g(e,"page");let n=v(r.segments,o);n.issues?await P(n.issues):a=n.value}let c;if(r.searchParams){let o=await l.searchParams;if(o===void 0)throw new h(e,"page");let n=v(r.searchParams,o);n.issues?await y(n.issues):c=n.value}let d;try{let o={id:e,...a?{segments:a}:{},...c?{searchParams:c}:{}};d=await p(o)}catch(o){throw i.stop(),t.error(`\u{1F6D1} Page server component '${e}' not authorized after ${i.get()}`),o}try{let o={id:e,...d?{auth:d}:{},...a?{segments:a}:{},...c?{searchParams:c}:{}},n=await s(o);return i.stop(),t.info(`\u2705 Page server component '${e}' executed successfully in ${i.get()}`),n}catch(o){if(i.stop(),T(o))throw t.info(`\u2139\uFE0F Ignoring native Next.js error while executing page server component '${e}' after ${i.get()}`),o;return t.error(`\u{1F6D1} Page server component '${e}' failed to execute after ${i.get()}`),await f(o)}}}var E="[unknown:layout:server:component]";function D(r,s){let t=x(r.debug),e=r.id??E,f=r.onError??(p=>{throw t.error(`\u{1F6D1} Unexpected error in layout server component '${e}'`,p),p}),P=r.onSegmentsValidationError??(p=>{throw t.error(`\u{1F6D1} Invalid segments for layout server component '${e}'`,p),new S("segments",e,"page")}),y=r.authorize??(async()=>{});return async function({params:u,children:l,...i}){let a=w();a.start(),t.info(`\u{1F504} Running layout server component'${e}'`);let c;if(r.segments){let n=await u;if(n===void 0)throw new g(e,"page");let m=v(r.segments,n);m.issues?await P(m.issues):c=m.value}let d;if(r.experimental_slots){let n=r.experimental_slots,m=[];for(let $ of n)$ in i||m.push($);if(m.length>0)throw new C(e,m);d=i}let o;try{let n={id:e,...c?{segments:c}:{}};o=await y(n)}catch(n){throw a.stop(),t.error(`\u{1F6D1} Layout server component '${e}' not authorized after ${a.get()}`),n}try{let n={id:e,...o?{auth:o}:{},...c?{segments:c}:{},children:l,...d?{experimental_slots:d}:{}},m=await s(n);return a.stop(),t.info(`\u2705 Layout server component '${e}' executed successfully in ${a.get()}`),m}catch(n){if(a.stop(),T(n))throw t.info(`\u2139\uFE0F Ignoring native Next.js error while executing layout server component '${e}' after ${a.get()}`),n;return t.error(`\u{1F6D1} Layout server component '${e}' failed to execute after ${a.get()}`),await f(n)}}}export{D as createSafeLayoutServerComponent,A as createSafePageServerComponent};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-components/errors.ts","../../src/server-components/create-safe-server-component.ts"],"sourcesContent":["/**\n * Validation error for server components.\n */\nexport class ValidationError extends Error {\n constructor(\n validationType: 'segments' | 'searchParams',\n id: string,\n serverComponentType: 'page' | 'layout'\n ) {\n super(\n `${validationType === 'searchParams' ? 'Search params' : 'Segments'} validation error for ${serverComponentType} server component '${id}`\n )\n this.name = 'ValidationError'\n }\n}\n\n/**\n * No segments provided error for server components.\n */\nexport class NoSegmentsProvidedError extends Error {\n constructor(id: string, serverComponentType: 'page' | 'layout') {\n super(\n `No segments provided for ${serverComponentType} server component '${id}'`\n )\n this.name = 'NoSegmentsProvidedError'\n }\n}\n\n/**\n * No search params provided error for server components.\n */\nexport class NoSearchParamsProvidedError extends Error {\n constructor(id: string, serverComponentType: 'page' | 'layout') {\n super(\n `No search params provided for ${serverComponentType} server component '${id}'`\n )\n this.name = 'NoSearchParamsProvidedError'\n }\n}\n\n/**\n * Missing slots error for layout server components.\n */\nexport class MissingLayoutSlotsError extends Error {\n constructor(id: string, missingSlots: readonly string[]) {\n const slotsList = missingSlots.map((s) => `'${s}'`).join(', ')\n super(`Missing slots [${slotsList}] for layout server component '${id}'`)\n this.name = 'MissingLayoutSlotsError'\n }\n}\n","import { createExecutionClock, createLogger, isNextNativeError } from '../utils'\nimport { parseWithDictionary, type StandardSchemaV1 } from '../standard-schema'\nimport type { Awaitable, AuthContext } from '../types'\nimport type {\n TSegmentsDict,\n TSearchParamsDict,\n PageAuthFunctionParams,\n PageProvidedProps,\n SafePageServerComponentContext,\n CreateSafePageServerComponentOptions,\n CreateSafePageServerComponentReturnType,\n SafePageServerComponent,\n CreateSafeLayoutServerComponentOptions,\n SafeLayoutServerComponent,\n CreateSafeLayoutServerComponentReturnType,\n LayoutProvidedProps,\n LayoutAuthFunctionParams,\n SafeLayoutServerComponentContext,\n} from './types'\nimport {\n ValidationError,\n NoSegmentsProvidedError,\n NoSearchParamsProvidedError,\n MissingLayoutSlotsError,\n} from './errors'\n\n/** @internal exported for testing only */\nexport const DEFAULT_PAGE_ID = '[unknown:page:server:component]'\n\n/**\n * Creates a safe page server component with data validation and error handling\n * for Next.js (>= 14) page server components.\n *\n * @param options - Options to configure the pageserver component.\n * @param pageServerComponentFn - The page server component function.\n *\n * @returns A Next.js page server component.\n */\nexport function createSafePageServerComponent<\n AC extends AuthContext | undefined = undefined,\n TSegments extends TSegmentsDict | undefined = undefined,\n TSearchParams extends TSearchParamsDict | undefined = undefined,\n>(\n options: CreateSafePageServerComponentOptions<AC, TSegments, TSearchParams>,\n pageServerComponentFn: SafePageServerComponent<AC, TSegments, TSearchParams>\n): CreateSafePageServerComponentReturnType {\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_PAGE_ID\n\n const onError =\n options.onError ??\n ((err: unknown): Awaitable<never> => {\n log.error(`🛑 Unexpected error in page server component '${id}'`, err)\n throw err\n })\n\n const onSegmentsValidationError =\n options.onSegmentsValidationError ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<never> => {\n log.error(`🛑 Invalid segments for page server component '${id}'`, issues)\n throw new ValidationError('segments', id, 'page')\n })\n\n const onSearchParamsValidationError =\n options.onSearchParamsValidationError ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<never> => {\n log.error(`🛑 Invalid search params for server component '${id}'`, issues)\n throw new ValidationError('searchParams', id, 'page')\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js page server component\n return async function SafePageServerComponent(\n props: PageProvidedProps\n ): Promise<React.ReactElement | never> {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running page server component'${id}'`)\n\n let segments = undefined\n if (options.segments) {\n const params_unsafe = await props.params\n if (params_unsafe === undefined) {\n throw new NoSegmentsProvidedError(id, 'page')\n }\n\n const parsedSegments = parseWithDictionary(\n options.segments,\n params_unsafe\n )\n if (parsedSegments.issues) {\n await onSegmentsValidationError(parsedSegments.issues)\n } else {\n segments = parsedSegments.value\n }\n }\n\n let searchParams = undefined\n if (options.searchParams) {\n const searchParams_unsafe = await props.searchParams\n if (searchParams_unsafe === undefined) {\n throw new NoSearchParamsProvidedError(id, 'page')\n }\n\n const parsedSearchParams = parseWithDictionary(\n options.searchParams,\n searchParams_unsafe\n )\n if (parsedSearchParams.issues) {\n await onSearchParamsValidationError(parsedSearchParams.issues)\n } else {\n searchParams = parsedSearchParams.value\n }\n }\n\n // Authorize the server component\n let auth = undefined\n try {\n // Build page auth function params\n const authParams = {\n id,\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n } as PageAuthFunctionParams<TSegments, TSearchParams>\n\n auth = await authorize(authParams)\n } catch (err: unknown) {\n log.error(`🛑 Page server component '${id}' not authorized`)\n throw err\n }\n\n try {\n // Build safe page server component context\n const ctx = {\n id,\n ...(auth ? { auth } : {}),\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n } as SafePageServerComponentContext<AC, TSegments, TSearchParams>\n\n // Execute the page server component\n const PageServerComponent = await pageServerComponentFn(ctx)\n\n // Stop the execution clock\n executionClock.stop()\n log.info(\n `✅ Page server component '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return PageServerComponent\n } catch (err: unknown) {\n executionClock.stop()\n\n if (!isNextNativeError(err)) {\n log.error(\n `🛑 Page server component '${id}' failed to execute after ${executionClock.get()}`\n )\n return await onError(err)\n } else {\n log.info('ℹ️ Ignoring native Next.js error')\n throw err\n }\n }\n }\n}\n\n/** @internal exported for testing only */\nexport const DEFAULT_LAYOUT_ID = '[unknown:layout:server:component]'\n\n/**\n * Creates a safe layout server component with data validation and error handling\n * for Next.js (>= 14) layout server components.\n *\n * @param options - Options to configure the pageserver component.\n * @param layoutServerComponentFn - The layout server component function.\n *\n * @returns A Next.js layout server component.\n */\nexport function createSafeLayoutServerComponent<\n AC extends AuthContext | undefined = undefined,\n TSegments extends TSegmentsDict | undefined = undefined,\n TSlots extends readonly string[] | undefined = undefined,\n>(\n options: CreateSafeLayoutServerComponentOptions<AC, TSegments, TSlots>,\n layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments, TSlots>\n): CreateSafeLayoutServerComponentReturnType<TSlots> {\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_LAYOUT_ID\n\n const onError =\n options.onError ??\n ((err: unknown): Awaitable<never> => {\n log.error(`🛑 Unexpected error in layout server component '${id}'`, err)\n throw err\n })\n\n const onSegmentsValidationError =\n options.onSegmentsValidationError ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<never> => {\n log.error(\n `🛑 Invalid segments for layout server component '${id}'`,\n issues\n )\n throw new ValidationError('segments', id, 'page')\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js layout server component\n return async function SafeLayoutServerComponent({\n params,\n children,\n ...layoutSlots\n }: LayoutProvidedProps<TSlots>) {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running layout server component'${id}'`)\n\n let segments = undefined\n if (options.segments) {\n const params_unsafe = await params\n if (params_unsafe === undefined) {\n throw new NoSegmentsProvidedError(id, 'page')\n }\n\n const parsedSegments = parseWithDictionary(\n options.segments,\n params_unsafe\n )\n if (parsedSegments.issues) {\n await onSegmentsValidationError(parsedSegments.issues)\n } else {\n segments = parsedSegments.value\n }\n }\n\n let experimental_slots = undefined\n if (options.experimental_slots) {\n // Validate that all expected slots exist in `layoutSlots`\n // We don't want to let pass unexpected slots to the layout server component\n // when using parallel routes and when they are not explicitly defined in the `experimental_slots` option.\n // It ensures data integrity and prevents potential security issues.\n const expectedSlots = options.experimental_slots\n const missingSlots: string[] = []\n\n for (const slotName of expectedSlots) {\n if (!(slotName in layoutSlots)) {\n missingSlots.push(slotName)\n }\n }\n\n if (missingSlots.length > 0) {\n throw new MissingLayoutSlotsError(id, missingSlots)\n }\n\n experimental_slots = layoutSlots\n }\n\n // Authorize the server component\n let auth = undefined\n try {\n // Build layout auth function params\n const authParams = {\n id,\n ...(segments ? { segments } : {}),\n } as LayoutAuthFunctionParams<TSegments>\n\n auth = await authorize(authParams)\n } catch (err: unknown) {\n log.error(`🛑 Layout server component '${id}' not authorized`)\n throw err\n }\n\n try {\n // Build safe layout server component context\n const ctx = {\n id,\n ...(auth ? { auth } : {}),\n ...(segments ? { segments } : {}),\n children,\n ...(experimental_slots ? { experimental_slots } : {}),\n } as SafeLayoutServerComponentContext<AC, TSegments, TSlots>\n\n // Execute the layout server component\n const LayoutServerComponent = await layoutServerComponentFn(ctx)\n\n // Stop the execution clock\n executionClock.stop()\n log.info(\n `✅ Layout server component '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return LayoutServerComponent\n } catch (err: unknown) {\n executionClock.stop()\n\n if (!isNextNativeError(err)) {\n log.error(\n `🛑 Layout server component '${id}' failed to execute after ${executionClock.get()}`\n )\n return await onError(err)\n } else {\n log.info('ℹ️ Ignoring native Next.js error')\n throw err\n }\n }\n }\n}\n"],"mappings":"8DAGO,IAAMA,EAAN,cAA8B,KAAM,CACzC,YACEC,EACAC,EACAC,EACA,CACA,MACE,GAAGF,IAAmB,eAAiB,gBAAkB,UAAU,yBAAyBE,CAAmB,sBAAsBD,CAAE,EACzI,EACA,KAAK,KAAO,iBACd,CACF,EAKaE,EAAN,cAAsC,KAAM,CACjD,YAAYF,EAAYC,EAAwC,CAC9D,MACE,4BAA4BA,CAAmB,sBAAsBD,CAAE,GACzE,EACA,KAAK,KAAO,yBACd,CACF,EAKaG,EAAN,cAA0C,KAAM,CACrD,YAAYH,EAAYC,EAAwC,CAC9D,MACE,iCAAiCA,CAAmB,sBAAsBD,CAAE,GAC9E,EACA,KAAK,KAAO,6BACd,CACF,EAKaI,EAAN,cAAsC,KAAM,CACjD,YAAYJ,EAAYK,EAAiC,CACvD,IAAMC,EAAYD,EAAa,IAAKE,GAAM,IAAIA,CAAC,GAAG,EAAE,KAAK,IAAI,EAC7D,MAAM,kBAAkBD,CAAS,kCAAkCN,CAAE,GAAG,EACxE,KAAK,KAAO,yBACd,CACF,ECtBO,IAAMQ,EAAkB,kCAWxB,SAASC,EAKdC,EACAC,EACyC,CACzC,IAAMC,EAAMC,EAAaH,EAAQ,KAAK,EAChCI,EAAKJ,EAAQ,IAAMF,EAEnBO,EACJL,EAAQ,UACNM,GAAmC,CACnC,MAAAJ,EAAI,MAAM,w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MAAMR,EAAQC,CAAG,CAK5B,CACF,CACF","names":["ValidationError","validationType","id","serverComponentType","NoSegmentsProvidedError","NoSearchParamsProvidedError","MissingLayoutSlotsError","missingSlots","slotsList","s","DEFAULT_PAGE_ID","createSafePageServerComponent","options","pageServerComponentFn","log","createLogger","id","onError","err","onSegmentsValidationError","issues","ValidationError","onSearchParamsValidationError","authorize","props","executionClock","createExecutionClock","segments","params_unsafe","NoSegmentsProvidedError","parsedSegments","parseWithDictionary","searchParams","searchParams_unsafe","NoSearchParamsProvidedError","parsedSearchParams","auth","authParams","ctx","PageServerComponent","isNextNativeError","DEFAULT_LAYOUT_ID","createSafeLayoutServerComponent","layoutServerComponentFn","params","children","layoutSlots","experimental_slots","expectedSlots","missingSlots","slotName","MissingLayoutSlotsError","LayoutServerComponent"]}
1
+ {"version":3,"sources":["../../src/server-components/errors.ts","../../src/server-components/create-safe-server-component.ts"],"sourcesContent":["/**\n * Validation error for server components.\n */\nexport class ValidationError extends Error {\n constructor(\n validationType: 'segments' | 'searchParams',\n id: string,\n serverComponentType: 'page' | 'layout'\n ) {\n super(\n `${validationType === 'searchParams' ? 'Search params' : 'Segments'} validation error for ${serverComponentType} server component '${id}`\n )\n this.name = 'ValidationError'\n }\n}\n\n/**\n * No segments provided error for server components.\n */\nexport class NoSegmentsProvidedError extends Error {\n constructor(id: string, serverComponentType: 'page' | 'layout') {\n super(\n `No segments provided for ${serverComponentType} server component '${id}'`\n )\n this.name = 'NoSegmentsProvidedError'\n }\n}\n\n/**\n * No search params provided error for server components.\n */\nexport class NoSearchParamsProvidedError extends Error {\n constructor(id: string, serverComponentType: 'page' | 'layout') {\n super(\n `No search params provided for ${serverComponentType} server component '${id}'`\n )\n this.name = 'NoSearchParamsProvidedError'\n }\n}\n\n/**\n * Missing slots error for layout server components.\n */\nexport class MissingLayoutSlotsError extends Error {\n constructor(id: string, missingSlots: readonly string[]) {\n const slotsList = missingSlots.map((s) => `'${s}'`).join(', ')\n super(`Missing slots [${slotsList}] for layout server component '${id}'`)\n this.name = 'MissingLayoutSlotsError'\n }\n}\n","import { createExecutionClock, createLogger, isNextNativeError } from '../utils'\nimport { parseWithDictionary, type StandardSchemaV1 } from '../standard-schema'\nimport type { Awaitable, AuthContext } from '../types'\nimport type {\n TSegmentsDict,\n TSearchParamsDict,\n PageAuthFunctionParams,\n PageProvidedProps,\n SafePageServerComponentContext,\n CreateSafePageServerComponentOptions,\n CreateSafePageServerComponentReturnType,\n SafePageServerComponent,\n CreateSafeLayoutServerComponentOptions,\n SafeLayoutServerComponent,\n CreateSafeLayoutServerComponentReturnType,\n LayoutProvidedProps,\n LayoutAuthFunctionParams,\n SafeLayoutServerComponentContext,\n} from './types'\nimport {\n ValidationError,\n NoSegmentsProvidedError,\n NoSearchParamsProvidedError,\n MissingLayoutSlotsError,\n} from './errors'\n\n/** @internal exported for testing only */\nexport const DEFAULT_PAGE_ID = '[unknown:page:server:component]'\n\n/**\n * Creates a safe page server component with data validation and error handling\n * for Next.js (>= 14) page server components.\n *\n * @param options - Options to configure the pageserver component.\n * @param pageServerComponentFn - The page server component function.\n *\n * @returns A Next.js page server component.\n */\nexport function createSafePageServerComponent<\n AC extends AuthContext | undefined = undefined,\n TSegments extends TSegmentsDict | undefined = undefined,\n TSearchParams extends TSearchParamsDict | undefined = undefined,\n>(\n options: CreateSafePageServerComponentOptions<AC, TSegments, TSearchParams>,\n pageServerComponentFn: SafePageServerComponent<AC, TSegments, TSearchParams>\n): CreateSafePageServerComponentReturnType {\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_PAGE_ID\n\n const onError =\n options.onError ??\n ((err: unknown): Awaitable<never> => {\n log.error(`🛑 Unexpected error in page server component '${id}'`, err)\n throw err\n })\n\n const onSegmentsValidationError =\n options.onSegmentsValidationError ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<never> => {\n log.error(`🛑 Invalid segments for page server component '${id}'`, issues)\n throw new ValidationError('segments', id, 'page')\n })\n\n const onSearchParamsValidationError =\n options.onSearchParamsValidationError ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<never> => {\n log.error(`🛑 Invalid search params for server component '${id}'`, issues)\n throw new ValidationError('searchParams', id, 'page')\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js page server component\n return async function SafePageServerComponent(\n props: PageProvidedProps\n ): Promise<React.ReactElement | never> {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running page server component'${id}'`)\n\n let segments = undefined\n if (options.segments) {\n const params_unsafe = await props.params\n if (params_unsafe === undefined) {\n throw new NoSegmentsProvidedError(id, 'page')\n }\n\n const parsedSegments = parseWithDictionary(\n options.segments,\n params_unsafe\n )\n if (parsedSegments.issues) {\n await onSegmentsValidationError(parsedSegments.issues)\n } else {\n segments = parsedSegments.value\n }\n }\n\n let searchParams = undefined\n if (options.searchParams) {\n const searchParams_unsafe = await props.searchParams\n if (searchParams_unsafe === undefined) {\n throw new NoSearchParamsProvidedError(id, 'page')\n }\n\n const parsedSearchParams = parseWithDictionary(\n options.searchParams,\n searchParams_unsafe\n )\n if (parsedSearchParams.issues) {\n await onSearchParamsValidationError(parsedSearchParams.issues)\n } else {\n searchParams = parsedSearchParams.value\n }\n }\n\n // Authorize the server component\n let auth = undefined\n try {\n // Build page auth function params\n const authParams = {\n id,\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n } as PageAuthFunctionParams<TSegments, TSearchParams>\n\n auth = await authorize(authParams)\n } catch (err: unknown) {\n executionClock.stop()\n log.error(\n `🛑 Page server component '${id}' not authorized after ${executionClock.get()}`\n )\n\n throw err\n }\n\n try {\n // Build safe page server component context\n const ctx = {\n id,\n ...(auth ? { auth } : {}),\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n } as SafePageServerComponentContext<AC, TSegments, TSearchParams>\n\n // Execute the page server component\n const PageServerComponent = await pageServerComponentFn(ctx)\n\n // Stop the execution clock\n executionClock.stop()\n log.info(\n `✅ Page server component '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return PageServerComponent\n } catch (err: unknown) {\n executionClock.stop()\n\n if (isNextNativeError(err)) {\n log.info(\n `ℹ️ Ignoring native Next.js error while executing page server component '${id}' after ${executionClock.get()}`\n )\n throw err\n }\n\n log.error(\n `🛑 Page server component '${id}' failed to execute after ${executionClock.get()}`\n )\n return await onError(err)\n }\n }\n}\n\n/** @internal exported for testing only */\nexport const DEFAULT_LAYOUT_ID = '[unknown:layout:server:component]'\n\n/**\n * Creates a safe layout server component with data validation and error handling\n * for Next.js (>= 14) layout server components.\n *\n * @param options - Options to configure the pageserver component.\n * @param layoutServerComponentFn - The layout server component function.\n *\n * @returns A Next.js layout server component.\n */\nexport function createSafeLayoutServerComponent<\n AC extends AuthContext | undefined = undefined,\n TSegments extends TSegmentsDict | undefined = undefined,\n TSlots extends readonly string[] | undefined = undefined,\n>(\n options: CreateSafeLayoutServerComponentOptions<AC, TSegments, TSlots>,\n layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments, TSlots>\n): CreateSafeLayoutServerComponentReturnType<TSlots> {\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_LAYOUT_ID\n\n const onError =\n options.onError ??\n ((err: unknown): Awaitable<never> => {\n log.error(`🛑 Unexpected error in layout server component '${id}'`, err)\n throw err\n })\n\n const onSegmentsValidationError =\n options.onSegmentsValidationError ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<never> => {\n log.error(\n `🛑 Invalid segments for layout server component '${id}'`,\n issues\n )\n throw new ValidationError('segments', id, 'page')\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js layout server component\n return async function SafeLayoutServerComponent({\n params,\n children,\n ...layoutSlots\n }: LayoutProvidedProps<TSlots>) {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running layout server component'${id}'`)\n\n let segments = undefined\n if (options.segments) {\n const params_unsafe = await params\n if (params_unsafe === undefined) {\n throw new NoSegmentsProvidedError(id, 'page')\n }\n\n const parsedSegments = parseWithDictionary(\n options.segments,\n params_unsafe\n )\n if (parsedSegments.issues) {\n await onSegmentsValidationError(parsedSegments.issues)\n } else {\n segments = parsedSegments.value\n }\n }\n\n let experimental_slots = undefined\n if (options.experimental_slots) {\n // Validate that all expected slots exist in `layoutSlots`\n // We don't want to let pass unexpected slots to the layout server component\n // when using parallel routes and when they are not explicitly defined in the `experimental_slots` option.\n // It ensures data integrity and prevents potential security issues.\n const expectedSlots = options.experimental_slots\n const missingSlots: string[] = []\n\n for (const slotName of expectedSlots) {\n if (!(slotName in layoutSlots)) {\n missingSlots.push(slotName)\n }\n }\n\n if (missingSlots.length > 0) {\n throw new MissingLayoutSlotsError(id, missingSlots)\n }\n\n experimental_slots = layoutSlots\n }\n\n // Authorize the server component\n let auth = undefined\n try {\n // Build layout auth function params\n const authParams = {\n id,\n ...(segments ? { segments } : {}),\n } as LayoutAuthFunctionParams<TSegments>\n\n auth = await authorize(authParams)\n } catch (err: unknown) {\n executionClock.stop()\n log.error(\n `🛑 Layout server component '${id}' not authorized after ${executionClock.get()}`\n )\n throw err\n }\n\n try {\n // Build safe layout server component context\n const ctx = {\n id,\n ...(auth ? { auth } : {}),\n ...(segments ? { segments } : {}),\n children,\n ...(experimental_slots ? { experimental_slots } : {}),\n } as SafeLayoutServerComponentContext<AC, TSegments, TSlots>\n\n // Execute the layout server component\n const LayoutServerComponent = await layoutServerComponentFn(ctx)\n\n // Stop the execution clock\n executionClock.stop()\n log.info(\n `✅ Layout server component '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return LayoutServerComponent\n } catch (err: unknown) {\n executionClock.stop()\n\n if (isNextNativeError(err)) {\n log.info(\n `ℹ️ Ignoring native Next.js error while executing layout server component '${id}' after ${executionClock.get()}`\n )\n throw err\n }\n\n log.error(\n `🛑 Layout server component '${id}' failed to execute after ${executionClock.get()}`\n )\n return await onError(err)\n }\n }\n}\n"],"mappings":"8DAGO,IAAMA,EAAN,cAA8B,KAAM,CACzC,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,KAAKC,CAAQ,EAI9B,GAAID,EAAa,OAAS,EACxB,MAAM,IAAIE,EAAwBnC,EAAIiC,CAAY,EAGpDF,EAAqBD,CACvB,CAGA,IAAIV,EACJ,GAAI,CAEF,IAAMC,EAAa,CACjB,GAAArB,EACA,GAAIW,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,CACjC,EAEAS,EAAO,MAAMb,EAAUc,CAAU,CACnC,OAASnB,EAAc,CACrB,MAAAO,EAAe,KAAK,EACpBX,EAAI,MACF,sCAA+BE,CAAE,0BAA0BS,EAAe,IAAI,CAAC,EACjF,EACMP,CACR,CAEA,GAAI,CAEF,IAAMoB,EAAM,CACV,GAAAtB,EACA,GAAIoB,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,EACvB,GAAIT,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,EAC/B,SAAAkB,EACA,GAAIE,EAAqB,CAAE,mBAAAA,CAAmB,EAAI,CAAC,CACrD,EAGMK,EAAwB,MAAMT,EAAwBL,CAAG,EAG/D,OAAAb,EAAe,KAAK,EACpBX,EAAI,KACF,mCAA8BE,CAAE,8BAA8BS,EAAe,IAAI,CAAC,EACpF,EAEO2B,CACT,OAASlC,EAAc,CAGrB,GAFAO,EAAe,KAAK,EAEhBe,EAAkBtB,CAAG,EACvB,MAAAJ,EAAI,KACF,uFAA6EE,CAAE,WAAWS,EAAe,IAAI,CAAC,EAChH,EACMP,EAGR,OAAAJ,EAAI,MACF,sCAA+BE,CAAE,6BAA6BS,EAAe,IAAI,CAAC,EACpF,EACO,MAAMR,EAAQC,CAAG,CAC1B,CACF,CACF","names":["ValidationError","validationType","id","serverComponentType","NoSegmentsProvidedError","NoSearchParamsProvidedError","MissingLayoutSlotsError","missingSlots","slotsList","s","DEFAULT_PAGE_ID","createSafePageServerComponent","options","pageServerComponentFn","log","createLogger","id","onError","err","onSegmentsValidationError","issues","ValidationError","onSearchParamsValidationError","authorize","props","executionClock","createExecutionClock","segments","params_unsafe","NoSegmentsProvidedError","parsedSegments","parseWithDictionary","searchParams","searchParams_unsafe","NoSearchParamsProvidedError","parsedSearchParams","auth","authParams","ctx","PageServerComponent","isNextNativeError","DEFAULT_LAYOUT_ID","createSafeLayoutServerComponent","layoutServerComponentFn","params","children","layoutSlots","experimental_slots","expectedSlots","missingSlots","slotName","MissingLayoutSlotsError","LayoutServerComponent"]}
@@ -0,0 +1,73 @@
1
+ type EmptyObjectType = {};
2
+ type UnwrapReadonlyObject<T> = T extends Readonly<infer U> ? U : T;
3
+ type Awaitable<T> = T | PromiseLike<T>;
4
+ type AuthContext = Record<string, unknown>;
5
+
6
+ /** The Standard Schema interface. */
7
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
8
+ /** The Standard Schema properties. */
9
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
10
+ }
11
+ declare namespace StandardSchemaV1 {
12
+ /** The Standard Schema properties interface. */
13
+ interface Props<Input = unknown, Output = Input> {
14
+ /** The version number of the standard. */
15
+ readonly version: 1;
16
+ /** The vendor name of the schema library. */
17
+ readonly vendor: string;
18
+ /** Validates unknown input values. */
19
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
20
+ /** Inferred types associated with the schema. */
21
+ readonly types?: Types<Input, Output> | undefined;
22
+ }
23
+ /** The result interface of the validate function. */
24
+ type Result<Output> = SuccessResult<Output> | FailureResult;
25
+ /** The result interface if validation succeeds. */
26
+ interface SuccessResult<Output> {
27
+ /** The typed output value. */
28
+ readonly value: Output;
29
+ /** The non-existent issues. */
30
+ readonly issues?: undefined;
31
+ }
32
+ /** The result interface if validation fails. */
33
+ interface FailureResult {
34
+ /** The issues of failed validation. */
35
+ readonly issues: ReadonlyArray<Issue>;
36
+ }
37
+ /** The issue interface of the failure output. */
38
+ interface Issue {
39
+ /** The error message of the issue. */
40
+ readonly message: string;
41
+ /** The path of the issue, if any. */
42
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
43
+ }
44
+ /** The path segment interface of the issue. */
45
+ interface PathSegment {
46
+ /** The key representing a path segment. */
47
+ readonly key: PropertyKey;
48
+ }
49
+ /** The Standard Schema types interface. */
50
+ interface Types<Input = unknown, Output = Input> {
51
+ /** The input type of the schema. */
52
+ readonly input: Input;
53
+ /** The output type of the schema. */
54
+ readonly output: Output;
55
+ }
56
+ /** Infers the input type of a Standard Schema. */
57
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
58
+ /** Infers the output type of a Standard Schema. */
59
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
60
+ }
61
+ type StandardSchemaDictionary<Input = Record<string, unknown>, Output extends Record<keyof Input, unknown> = Input> = {
62
+ [K in keyof Input]-?: StandardSchemaV1<Input[K], Output[K]>;
63
+ };
64
+ declare namespace StandardSchemaDictionary {
65
+ type InferInput<T extends StandardSchemaDictionary> = {
66
+ [K in keyof T]: StandardSchemaV1.InferInput<T[K]>;
67
+ };
68
+ type InferOutput<T extends StandardSchemaDictionary> = {
69
+ [K in keyof T]: StandardSchemaV1.InferOutput<T[K]>;
70
+ };
71
+ }
72
+
73
+ export { type AuthContext as A, type EmptyObjectType as E, StandardSchemaDictionary as S, type UnwrapReadonlyObject as U, StandardSchemaV1 as a, type Awaitable as b };
@@ -0,0 +1,73 @@
1
+ type EmptyObjectType = {};
2
+ type UnwrapReadonlyObject<T> = T extends Readonly<infer U> ? U : T;
3
+ type Awaitable<T> = T | PromiseLike<T>;
4
+ type AuthContext = Record<string, unknown>;
5
+
6
+ /** The Standard Schema interface. */
7
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
8
+ /** The Standard Schema properties. */
9
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
10
+ }
11
+ declare namespace StandardSchemaV1 {
12
+ /** The Standard Schema properties interface. */
13
+ interface Props<Input = unknown, Output = Input> {
14
+ /** The version number of the standard. */
15
+ readonly version: 1;
16
+ /** The vendor name of the schema library. */
17
+ readonly vendor: string;
18
+ /** Validates unknown input values. */
19
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
20
+ /** Inferred types associated with the schema. */
21
+ readonly types?: Types<Input, Output> | undefined;
22
+ }
23
+ /** The result interface of the validate function. */
24
+ type Result<Output> = SuccessResult<Output> | FailureResult;
25
+ /** The result interface if validation succeeds. */
26
+ interface SuccessResult<Output> {
27
+ /** The typed output value. */
28
+ readonly value: Output;
29
+ /** The non-existent issues. */
30
+ readonly issues?: undefined;
31
+ }
32
+ /** The result interface if validation fails. */
33
+ interface FailureResult {
34
+ /** The issues of failed validation. */
35
+ readonly issues: ReadonlyArray<Issue>;
36
+ }
37
+ /** The issue interface of the failure output. */
38
+ interface Issue {
39
+ /** The error message of the issue. */
40
+ readonly message: string;
41
+ /** The path of the issue, if any. */
42
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
43
+ }
44
+ /** The path segment interface of the issue. */
45
+ interface PathSegment {
46
+ /** The key representing a path segment. */
47
+ readonly key: PropertyKey;
48
+ }
49
+ /** The Standard Schema types interface. */
50
+ interface Types<Input = unknown, Output = Input> {
51
+ /** The input type of the schema. */
52
+ readonly input: Input;
53
+ /** The output type of the schema. */
54
+ readonly output: Output;
55
+ }
56
+ /** Infers the input type of a Standard Schema. */
57
+ type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
58
+ /** Infers the output type of a Standard Schema. */
59
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
60
+ }
61
+ type StandardSchemaDictionary<Input = Record<string, unknown>, Output extends Record<keyof Input, unknown> = Input> = {
62
+ [K in keyof Input]-?: StandardSchemaV1<Input[K], Output[K]>;
63
+ };
64
+ declare namespace StandardSchemaDictionary {
65
+ type InferInput<T extends StandardSchemaDictionary> = {
66
+ [K in keyof T]: StandardSchemaV1.InferInput<T[K]>;
67
+ };
68
+ type InferOutput<T extends StandardSchemaDictionary> = {
69
+ [K in keyof T]: StandardSchemaV1.InferOutput<T[K]>;
70
+ };
71
+ }
72
+
73
+ export { type AuthContext as A, type EmptyObjectType as E, StandardSchemaDictionary as S, type UnwrapReadonlyObject as U, StandardSchemaV1 as a, type Awaitable as b };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sugardarius/anzen",
3
- "version": "2.2.1",
4
- "description": "Fast, flexible, framework validation agnostic, type‑safe factories for creating route handlers, page and layout Server Component files in Next.js.",
3
+ "version": "2.3.1",
4
+ "description": "Fast, flexible, framework validation agnostic, type‑safe factories for creating server actions, route handlers, page and layout Server Component files in Next.js.",
5
5
  "license": "MIT",
6
6
  "packageManager": "npm@11.8.0",
7
7
  "workspaces": [
@@ -54,6 +54,7 @@
54
54
  },
55
55
  "keywords": [
56
56
  "nextjs",
57
+ "safe server actions",
57
58
  "safe route handlers",
58
59
  "safe page server components",
59
60
  "safe layout server components",
@@ -82,21 +83,21 @@
82
83
  },
83
84
  "devDependencies": {
84
85
  "@arethetypeswrong/cli": "^0.18.2",
85
- "@eslint/eslintrc": "^3.3.4",
86
- "@eslint/js": "^9.39.3",
86
+ "@eslint/eslintrc": "^3.3.5",
87
+ "@eslint/js": "^9.39.4",
87
88
  "@release-it/keep-a-changelog": "^7.0.1",
88
- "@types/node": "^25.3.0",
89
+ "@types/node": "^25.6.0",
89
90
  "@types/react": "^19.2.14",
90
- "decoders": "^2.8.0",
91
- "eslint": "^9.39.3",
92
- "prettier": "^3.8.1",
93
- "publint": "^0.3.17",
91
+ "decoders": "^2.9.3",
92
+ "eslint": "^9.39.4",
93
+ "prettier": "^3.8.3",
94
+ "publint": "^0.3.18",
94
95
  "release-it": "^19.2.4",
95
96
  "tsup": "^8.5.1",
96
97
  "turbo": "^2.5.6",
97
- "typescript": "^5.9.3",
98
- "typescript-eslint": "^8.56.1",
99
- "vitest": "^4.0.18",
98
+ "typescript": "^6.0.2",
99
+ "typescript-eslint": "^8.58.2",
100
+ "vitest": "^4.1.4",
100
101
  "zod": "^4.3.6"
101
102
  }
102
103
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts"],"names":["hasDictKey","obj","key","isPromise","value","assertsSyncOperation","message","createLogger","debug","shouldLog","rest","createExecutionClock","startTime","endTime"],"mappings":"AACO,sLAASA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACwC,CACxC,OAAOA,EAAAA,GAAOD,CAChB,CAGO,SAASE,CAAAA,CACdC,CAAAA,CACsC,CACtC,OACEA,CAAAA,GAAU,IAAA,EAAA,CACT,OAAOA,CAAAA,EAAU,QAAA,EAAY,OAAOA,CAAAA,EAAU,UAAA,CAAA,EAE/C,OAAQA,CAAAA,CAAc,IAAA,EAAS,UAEnC,CAGO,SAASC,CAAAA,CACdD,CAAAA,CACAE,CAAAA,CACoB,CACpB,EAAA,CAAIH,CAAAA,CAAaC,CAAK,CAAA,CACpB,MAAM,IAAI,KAAA,CAAME,CAAO,CAE3B,CAGO,SAASC,CAAAA,CAAaC,CAAAA,CAAiB,CAAA,CAAA,CAAO,CACnD,IAAMC,CAAAA,CAAYD,CAAAA,EAAS,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,YAAA,CACpD,MAAO,CACL,IAAA,CAAM,CAACF,CAAAA,CAAAA,GAAoBI,CAAAA,CAAAA,EAA0B,CAC/CD,CAAAA,EACF,OAAA,CAAQ,GAAA,CAAIH,CAAAA,CAAS,GAAGI,CAAI,CAEhC,CAAA,CACA,KAAA,CAAO,CAACJ,CAAAA,CAAAA,GAAoBI,CAAAA,CAAAA,EAA0B,CAChDD,CAAAA,EACF,OAAA,CAAQ,KAAA,CAAMH,CAAAA,CAAS,GAAGI,CAAI,CAElC,CAAA,CACA,IAAA,CAAM,CAACJ,CAAAA,CAAAA,GAAoBI,CAAAA,CAAAA,EAA0B,CAC/CD,CAAAA,EACF,OAAA,CAAQ,IAAA,CAAKH,CAAAA,CAAS,GAAGI,CAAI,CAEjC,CACF,CACF,CAGO,SAASC,CAAAA,CAAAA,CAAuB,CACrC,IAAIC,CAAAA,CAA2B,IAAA,CAC3BC,CAAAA,CAAyB,IAAA,CAE7B,MAAO,CACL,KAAA,CAAO,CAAA,CAAA,EAAY,CACjBD,CAAAA,CAAY,WAAA,CAAY,GAAA,CAAI,CAC9B,CAAA,CACA,IAAA,CAAM,CAAA,CAAA,EAAY,CAChB,EAAA,CAAIA,CAAAA,GAAc,IAAA,CAChB,MAAM,IAAI,KAAA,CAAM,kCAAkC,CAAA,CAEpDC,CAAAA,CAAU,WAAA,CAAY,GAAA,CAAI,CAC5B,CAAA,CACA,GAAA,CAAK,CAAA,CAAA,EAAc,CACjB,EAAA,CAAI,CAACD,CAAAA,EAAa,CAACC,CAAAA,CACjB,MAAM,IAAI,KAAA,CAAM,kDAAkD,CAAA,CAIpE,MAAO,CAAA,EAAA","file":"/home/runner/work/anzen/anzen/dist/chunk-LYFK3PWU.cjs","sourcesContent":["/** @internal */\nexport function hasDictKey<T extends object, K extends PropertyKey>(\n obj: T,\n key: K\n): obj is T & Record<typeof key, unknown> {\n return key in obj\n}\n\n/** @internal */\nexport function isPromise<T>(\n value: unknown\n): value is Promise<T> | PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any).then === 'function'\n )\n}\n\n/** @internal */\nexport function assertsSyncOperation<T>(\n value: T | Promise<T> | PromiseLike<T>,\n message: string\n): asserts value is T {\n if (isPromise<T>(value)) {\n throw new Error(message)\n }\n}\n\n/** @internal */\nexport function createLogger(debug: boolean = false) {\n const shouldLog = debug || process.env.NODE_ENV !== 'production'\n return {\n info: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.log(message, ...rest)\n }\n },\n error: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.error(message, ...rest)\n }\n },\n warn: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.warn(message, ...rest)\n }\n },\n }\n}\n\n/** @internal */\nexport function createExecutionClock() {\n let startTime: number | null = null\n let endTime: number | null = null\n\n return {\n start: (): void => {\n startTime = performance.now()\n },\n stop: (): void => {\n if (startTime === null) {\n throw new Error('Execution clock was not started.')\n }\n endTime = performance.now()\n },\n get: (): string => {\n if (!startTime || !endTime) {\n throw new Error('Execution clock has not been started or stopped.')\n }\n\n const duration = endTime - startTime\n return `${duration.toFixed(2)}ms`\n },\n }\n}\n\n/**\n * @internal\n * Checks if an error is a Next.js redirect error.\n */\nconst isNextRedirectError = (error: unknown): boolean => {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n return error.digest.startsWith('NEXT_REDIRECT;')\n}\n\n/**\n * @internal\n * Checks if an error is a Next.js HTTP error (notFound, forbidden, unauthorized).\n */\nconst isNextHttpError = (error: unknown): boolean => {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const digest = error.digest\n // Check for notFound (;404), forbidden (;403), or unauthorized (;401)\n return (\n digest.endsWith(';404') ||\n digest.endsWith(';403') ||\n digest.endsWith(';401')\n )\n}\n\n/**\n * @internal\n * Checks if an error is a Next.js native error that should not be logged.\n */\nexport function isNextNativeError(error: unknown): boolean {\n return isNextRedirectError(error) || isNextHttpError(error)\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts","../src/standard-schema.ts"],"sourcesContent":["/** @internal */\nexport function hasDictKey<T extends object, K extends PropertyKey>(\n obj: T,\n key: K\n): obj is T & Record<typeof key, unknown> {\n return key in obj\n}\n\n/** @internal */\nexport function isPromise<T>(\n value: unknown\n): value is Promise<T> | PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any).then === 'function'\n )\n}\n\n/** @internal */\nexport function assertsSyncOperation<T>(\n value: T | Promise<T> | PromiseLike<T>,\n message: string\n): asserts value is T {\n if (isPromise<T>(value)) {\n throw new Error(message)\n }\n}\n\n/** @internal */\nexport function createLogger(debug: boolean = false) {\n const shouldLog = debug || process.env.NODE_ENV !== 'production'\n return {\n info: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.log(message, ...rest)\n }\n },\n error: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.error(message, ...rest)\n }\n },\n warn: (message: string, ...rest: unknown[]): void => {\n if (shouldLog) {\n console.warn(message, ...rest)\n }\n },\n }\n}\n\n/** @internal */\nexport function createExecutionClock() {\n let startTime: number | null = null\n let endTime: number | null = null\n\n return {\n start: (): void => {\n startTime = performance.now()\n },\n stop: (): void => {\n if (startTime === null) {\n throw new Error('Execution clock was not started.')\n }\n endTime = performance.now()\n },\n get: (): string => {\n if (!startTime || !endTime) {\n throw new Error('Execution clock has not been started or stopped.')\n }\n\n const duration = endTime - startTime\n return `${duration.toFixed(2)}ms`\n },\n }\n}\n\n/**\n * @internal\n * Checks if an error is a Next.js redirect error.\n */\nconst isNextRedirectError = (error: unknown): boolean => {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n return error.digest.startsWith('NEXT_REDIRECT;')\n}\n\n/**\n * @internal\n * Checks if an error is a Next.js HTTP error (notFound, forbidden, unauthorized).\n */\nconst isNextHttpError = (error: unknown): boolean => {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const digest = error.digest\n // Check for notFound (;404), forbidden (;403), or unauthorized (;401)\n return (\n digest.endsWith(';404') ||\n digest.endsWith(';403') ||\n digest.endsWith(';401')\n )\n}\n\n/**\n * @internal\n * Checks if an error is a Next.js native error that should not be logged.\n */\nexport function isNextNativeError(error: unknown): boolean {\n return isNextRedirectError(error) || isNextHttpError(error)\n}\n","import { assertsSyncOperation, hasDictKey } from './utils'\n\n/** The Standard Schema interface. */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>\n}\n\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1\n /** The vendor name of the schema library. */\n readonly vendor: string\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output\n /** The non-existent issues. */\n readonly issues?: undefined\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input\n /** The output type of the schema. */\n readonly output: Output\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input']\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output']\n}\n\nexport function validateWithSchema<TSchema extends StandardSchemaV1>(\n schema: TSchema,\n value: unknown,\n errSyncMsg = 'Validation must be synchronous but schema returned a Promise.'\n): StandardSchemaV1.Result<StandardSchemaV1.InferOutput<TSchema>> {\n const result = schema['~standard'].validate(value)\n assertsSyncOperation(result, errSyncMsg)\n\n return result\n}\n\n// Thanks to `@t3-env/core` (👉🏻 https://github.com/t3-oss/t3-env/blob/main/packages/core/src/standard.ts)\n// for this awesome dictionary schema.\nexport type StandardSchemaDictionary<\n Input = Record<string, unknown>,\n Output extends Record<keyof Input, unknown> = Input,\n> = {\n [K in keyof Input]-?: StandardSchemaV1<Input[K], Output[K]>\n}\n\nexport namespace StandardSchemaDictionary {\n export type InferInput<T extends StandardSchemaDictionary> = {\n [K in keyof T]: StandardSchemaV1.InferInput<T[K]>\n }\n export type InferOutput<T extends StandardSchemaDictionary> = {\n [K in keyof T]: StandardSchemaV1.InferOutput<T[K]>\n }\n}\n\nexport function parseWithDictionary<TDict extends StandardSchemaDictionary>(\n dictionary: TDict,\n value: Record<string, unknown>\n): StandardSchemaV1.Result<StandardSchemaDictionary.InferOutput<TDict>> {\n const result: Record<string, unknown> = {}\n const issues: StandardSchemaV1.Issue[] = []\n\n for (const key in dictionary) {\n if (!hasDictKey(dictionary, key)) {\n continue\n }\n // NOTE: safe to assert as we're ensuring just before key isn't undefined\n const propResult = dictionary[key]!['~standard'].validate(value[key])\n\n assertsSyncOperation(\n propResult,\n `Validation must be synchronous, but ${key} returned a Promise.`\n )\n\n if (propResult.issues) {\n issues.push(\n ...propResult.issues.map((issue) => ({\n ...issue,\n path: [key, ...(issue.path ?? [])],\n }))\n )\n continue\n }\n result[key] = propResult.value\n }\n\n if (issues.length > 0) {\n return { issues }\n }\n\n return { value: result as never }\n}\n"],"mappings":"AACO,SAASA,EACdC,EACAC,EACwC,CACxC,OAAOA,KAAOD,CAChB,CAGO,SAASE,EACdC,EACsC,CACtC,OACEA,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAE/C,OAAQA,EAAc,MAAS,UAEnC,CAGO,SAASC,EACdD,EACAE,EACoB,CACpB,GAAIH,EAAaC,CAAK,EACpB,MAAM,IAAI,MAAME,CAAO,CAE3B,CAGO,SAASC,EAAaC,EAAiB,GAAO,CACnD,IAAMC,EAAYD,GAAS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EAAQD,CAAU,EAEhCC,CACT,CAoBO,SAASE,EACdC,EACAL,EACsE,CACtE,IAAME,EAAkC,CAAC,EACnCI,EAAmC,CAAC,EAE1C,QAAWC,KAAOF,EAAY,CAC5B,GAAI,CAACG,EAAWH,EAAYE,CAAG,EAC7B,SAGF,IAAME,EAAaJ,EAAWE,CAAG,EAAG,WAAW,EAAE,SAASP,EAAMO,CAAG,CAAC,EAOpE,GALAJ,EACEM,EACA,uCAAuCF,CAAG,sBAC5C,EAEIE,EAAW,OAAQ,CACrBH,EAAO,KACL,GAAGG,EAAW,OAAO,IAAKC,IAAW,CACnC,GAAGA,EACH,KAAM,CAACH,EAAK,GAAIG,EAAM,MAAQ,CAAC,CAAE,CACnC,EAAE,CACJ,EACA,QACF,CACAR,EAAOK,CAAG,EAAIE,EAAW,KAC3B,CAEA,OAAIH,EAAO,OAAS,EACX,CAAE,OAAAA,CAAO,EAGX,CAAE,MAAOJ,CAAgB,CAClC","names":["hasDictKey","obj","key","isPromise","value","assertsSyncOperation","message","createLogger","debug","shouldLog","rest","createExecutionClock","startTime","endTime","isNextRedirectError","error","isNextHttpError","digest","isNextNativeError","validateWithSchema","schema","value","errSyncMsg","result","assertsSyncOperation","parseWithDictionary","dictionary","issues","key","hasDictKey","propResult","issue"]}