@sugardarius/anzen 1.1.3 → 2.0.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.
- package/README.md +121 -379
- package/dist/chunk-DT3TEL5X.js +2 -0
- package/dist/chunk-DT3TEL5X.js.map +1 -0
- package/dist/chunk-UDCVGQMH.cjs +2 -0
- package/dist/chunk-UDCVGQMH.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -240
- package/dist/index.d.ts +3 -240
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/server-components/index.cjs +2 -0
- package/dist/server-components/index.cjs.map +1 -0
- package/dist/server-components/index.d.cts +208 -0
- package/dist/server-components/index.d.ts +208 -0
- package/dist/server-components/index.js +2 -0
- package/dist/server-components/index.js.map +1 -0
- package/dist/types-LPIIICMI.d.cts +266 -0
- package/dist/types-LPIIICMI.d.ts +266 -0
- package/package.json +26 -10
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/standard-schema.ts","../src/create-safe-route-handler.ts"],"sourcesContent":["export 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\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\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\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","import { assertsSyncOperation } 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\nconst 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\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","import { createLogger, createExecutionClock } from './utils'\nimport {\n parseWithDictionary,\n validateWithSchema,\n type StandardSchemaV1,\n} from './standard-schema'\nimport type {\n Awaitable,\n AuthContext,\n TSegmentsDict,\n TSearchParamsDict,\n TBodySchema,\n TFormDataDict,\n RequestExtras,\n CreateSafeRouteHandlerOptions,\n CreateSafeRouteHandlerReturnType,\n SafeRouteHandler,\n SafeRouteHandlerContext,\n} from './types'\n\n/** @internal exported for testing only */\nexport const DEFAULT_ID = '[unknown:route:handler]'\n\n/**\n * @internal\n *\n * Reads the request body as JSON.\n * If it fails, it calls the `onErrorResponse` callback.\n */\nconst readRequestBodyAsJson = async <TReq extends Request>(\n req: TReq\n): Promise<unknown> => {\n const contentType = req.headers.get('content-type')\n if (contentType?.startsWith('application/json')) {\n return await req.json()\n }\n\n const text = await req.text()\n return JSON.parse(text)\n}\n\n/**\n * Creates a safe route handler with data validation and error handling\n * for Next.js (>= 14) API route handlers.\n *\n * @param options - Options to configure the route handler.\n * @param handlerFn - The route handler function.\n *\n * @returns A Next.js API route handler function.\n *\n * @example\n * ```ts\n * import { string } from 'decoders'\n *import { createSafeRouteHandler } from '@sugardarius/anzen'\n * import { auth } from '~/lib/auth'\n *\n * export const GET = createSafeRouteHandler(\n * {\n * id: 'my-safe-route-handler',\n * authorize: async ({ req }) => {\n * const session = await auth.getSession(req)\n * if (!session) {\n * return new Response(null, { status: 401 })\n * }\n *\n * return { user: session.user }\n * },\n * segments: {\n * id: string,\n * },\n * },\n * async ({ auth, segments, }, req): Promise<Response> => {\n * return Response.json({ user: auth.user, segments }, { status: 200 })\n * }\n *)\n * ```\n */\nexport function createSafeRouteHandler<\n AC extends AuthContext | undefined = undefined,\n TRouteDynamicSegments extends TSegmentsDict | undefined = undefined,\n TSearchParams extends TSearchParamsDict | undefined = undefined,\n TBody extends TBodySchema | undefined = undefined,\n TFormData extends TFormDataDict | undefined = undefined,\n TReq extends Request = Request,\n>(\n options: CreateSafeRouteHandlerOptions<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >,\n handlerFn: SafeRouteHandler<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData,\n TReq\n >\n): CreateSafeRouteHandlerReturnType<TReq> {\n // NOTE: `body` and `formData` options are mutually exclusive 🎭\n if (options.body && options.formData) {\n throw new Error(\n 'You cannot use both `body` and `formData` in the same route handler. They are both mutually exclusive.'\n )\n }\n\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_ID\n\n const onErrorResponse =\n options.onErrorResponse ??\n ((err: unknown): Awaitable<Response> => {\n log.error(`🛑 Unexpected error in route handler '${id}'`, err)\n return new Response('Internal server error', {\n status: 500,\n })\n })\n\n const onSegmentsValidationErrorResponse =\n options.onSegmentsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid segments for route handler '${id}':`, issues)\n return new Response('Invalid segments', {\n status: 400,\n })\n })\n\n const onSearchParamsValidationErrorResponse =\n options.onSearchParamsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid search params for route handler '${id}':`, issues)\n return new Response('Invalid search params', {\n status: 400,\n })\n })\n\n const onBodyValidationErrorResponse =\n options.onBodyValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid body for route handler '${id}':`, issues)\n return new Response('Invalid body', {\n status: 400,\n })\n })\n\n const onFormDataValidationErrorResponse =\n options.onFormDataValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid form data for route handler '${id}':`, issues)\n return new Response('Invalid form data', {\n status: 400,\n })\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js API Route handler declaration\n return async function (req: TReq, extras: RequestExtras): Promise<Response> {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running route handler '${id}'`)\n log.info(`👉🏻 Request ${req.method} ${req.url}`)\n\n const url = new URL(req.url)\n\n // Do not mutate / consume the original request\n // Due to `NextRequest` limitations as the req is cloned it's always a Request\n const clonedReq_forAuth = req.clone() as TReq\n const authOrResponse = await authorize({ url, req: clonedReq_forAuth })\n if (authOrResponse instanceof Response) {\n log.error(`🛑 Request not authorized for route handler '${id}'`)\n return authOrResponse\n }\n\n let segments = undefined\n if (options.segments) {\n const params = await extras.params\n if (params === undefined) {\n return new Response('No segments provided', { status: 400 })\n }\n\n const parsedSegments = parseWithDictionary(options.segments, params)\n if (parsedSegments.issues) {\n return await onSegmentsValidationErrorResponse(parsedSegments.issues)\n }\n\n segments = parsedSegments.value\n }\n\n let searchParams = undefined\n if (options.searchParams) {\n const queryParams_unsafe = [...url.searchParams.keys()].map((k) => {\n const values = url.searchParams.getAll(k)\n return [k, values.length > 1 ? values : values[0]]\n })\n\n const parsedSearchParams = parseWithDictionary(\n options.searchParams,\n Object.fromEntries(queryParams_unsafe)\n )\n\n if (parsedSearchParams.issues) {\n return await onSearchParamsValidationErrorResponse(\n parsedSearchParams.issues\n )\n }\n\n searchParams = parsedSearchParams.value\n }\n\n // Do not mutate / consume the original request\n const clonedReq_forBody = req.clone() as TReq\n\n let body = undefined\n if (options.body) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request body', {\n status: 405,\n })\n }\n\n let body_unsafe: unknown\n try {\n body_unsafe = await readRequestBodyAsJson(clonedReq_forBody)\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedBody = validateWithSchema(\n options.body,\n body_unsafe,\n 'Request body validation must be synchronous'\n )\n\n if (parsedBody.issues) {\n return await onBodyValidationErrorResponse(parsedBody.issues)\n }\n\n body = parsedBody.value\n }\n\n let formData = undefined\n if (options.formData) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request form data', {\n status: 405,\n })\n }\n\n const contentType = req.headers.get('content-type')\n if (\n !contentType?.startsWith('multipart/form-data') &&\n !contentType?.startsWith('application/x-www-form-urlencoded')\n ) {\n return new Response('Invalid content type for request form data', {\n status: 415,\n })\n }\n\n let formData_unsafe: FormData\n try {\n // NOTE: 🤔 maybe find a better way to counter the deprecation warning?\n formData_unsafe = await clonedReq_forBody.formData()\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedFormData = parseWithDictionary(\n options.formData,\n Object.fromEntries(formData_unsafe.entries())\n )\n\n if (parsedFormData.issues) {\n return await onFormDataValidationErrorResponse(parsedFormData.issues)\n }\n\n formData = parsedFormData.value\n }\n\n // Build safe route handler context\n const ctx = {\n id,\n url,\n ...(authOrResponse ? { auth: authOrResponse } : {}),\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n ...(body ? { body } : {}),\n ...(formData ? { formData } : {}),\n } as SafeRouteHandlerContext<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >\n\n // Let's catch any error that might happen in the handler\n try {\n const response = await handlerFn(ctx, req)\n\n executionClock.stop()\n log.info(\n `✅ Route handler '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return response\n } catch (err) {\n executionClock.stop()\n log.error(\n `🛑 Route handler '${id} failed to execute after ${executionClock.get()}'`\n )\n\n return await onErrorResponse(err)\n }\n }\n}\n"],"mappings":"AAAO,SAASA,EACdC,EACsC,CACtC,OACEA,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAE/C,OAAQA,EAAc,MAAS,UAEnC,CAEO,SAASC,EACdD,EACAE,EACoB,CACpB,GAAIH,EAAaC,CAAK,EACpB,MAAM,IAAI,MAAME,CAAO,CAE3B,CAEO,SAASC,EAAaC,EAAiB,GAAO,CACnD,IAAMC,EAAYD,GAAS,QAAQ,IAAI,WAAa,aACpD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II,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,CACjC,EASA,GAAI,CACF,IAAMK,EAAW,MAAMrC,EAAUoC,EAAKxC,CAAG,EAEzC,OAAAiB,EAAe,KAAK,EACpBZ,EAAI,KACF,yBAAoBE,CAAE,8BAA8BU,EAAe,IAAI,CAAC,EAC1E,EAEOwB,CACT,OAAShC,EAAK,CACZ,OAAAQ,EAAe,KAAK,EACpBZ,EAAI,MACF,4BAAqBE,CAAE,4BAA4BU,EAAe,IAAI,CAAC,GACzE,EAEO,MAAMT,EAAgBC,CAAG,CAClC,CACF,CACF","names":["isPromise","value","assertsSyncOperation","message","createLogger","debug","shouldLog","rest","createExecutionClock","startTime","endTime","validateWithSchema","schema","value","errSyncMsg","result","assertsSyncOperation","hasDictKey","obj","key","parseWithDictionary","dictionary","issues","propResult","issue","DEFAULT_ID","readRequestBodyAsJson","req","text","createSafeRouteHandler","options","handlerFn","log","createLogger","id","onErrorResponse","err","onSegmentsValidationErrorResponse","issues","onSearchParamsValidationErrorResponse","onBodyValidationErrorResponse","onFormDataValidationErrorResponse","authorize","extras","executionClock","createExecutionClock","url","clonedReq_forAuth","authOrResponse","segments","params","parsedSegments","parseWithDictionary","searchParams","queryParams_unsafe","k","values","parsedSearchParams","clonedReq_forBody","body","body_unsafe","parsedBody","validateWithSchema","formData","contentType","formData_unsafe","parsedFormData","ctx","response"]}
|
|
1
|
+
{"version":3,"sources":["../src/create-safe-route-handler.ts"],"sourcesContent":["import { createLogger, createExecutionClock } from './utils'\nimport {\n parseWithDictionary,\n validateWithSchema,\n type StandardSchemaV1,\n} from './standard-schema'\nimport type {\n Awaitable,\n AuthContext,\n TSegmentsDict,\n TSearchParamsDict,\n TBodySchema,\n TFormDataDict,\n ProvidedRouteContext,\n CreateSafeRouteHandlerOptions,\n CreateSafeRouteHandlerReturnType,\n SafeRouteHandler,\n SafeRouteHandlerContext,\n AuthFunctionParams,\n} from './types'\n\n/** @internal exported for testing only */\nexport const DEFAULT_ID = '[unknown:route:handler]'\n\n/**\n * @internal\n *\n * Reads the request body as JSON.\n * If it fails, it calls the `onErrorResponse` callback.\n */\nconst readRequestBodyAsJson = async <TReq extends Request>(\n req: TReq\n): Promise<unknown> => {\n const contentType = req.headers.get('content-type')\n if (contentType?.startsWith('application/json')) {\n return await req.json()\n }\n\n const text = await req.text()\n return JSON.parse(text)\n}\n\n/**\n * Creates a safe route handler with data validation and error handling\n * for Next.js (>= 14) API route handlers.\n *\n * @param options - Options to configure the route handler.\n * @param handlerFn - The route handler function.\n *\n * @returns A Next.js API route handler function.\n *\n * @example\n * ```ts\n * import { string } from 'decoders'\n *import { createSafeRouteHandler } from '@sugardarius/anzen'\n * import { auth } from '~/lib/auth'\n *\n * export const GET = createSafeRouteHandler(\n * {\n * id: 'my-safe-route-handler',\n * authorize: async ({ req }) => {\n * const session = await auth.getSession(req)\n * if (!session) {\n * return new Response(null, { status: 401 })\n * }\n *\n * return { user: session.user }\n * },\n * segments: {\n * id: string,\n * },\n * },\n * async ({ auth, segments, }, req): Promise<Response> => {\n * return Response.json({ user: auth.user, segments }, { status: 200 })\n * }\n *)\n * ```\n */\nexport function createSafeRouteHandler<\n AC extends AuthContext | undefined = undefined,\n TRouteDynamicSegments extends TSegmentsDict | undefined = undefined,\n TSearchParams extends TSearchParamsDict | undefined = undefined,\n TBody extends TBodySchema | undefined = undefined,\n TFormData extends TFormDataDict | undefined = undefined,\n TReq extends Request = Request,\n>(\n options: CreateSafeRouteHandlerOptions<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >,\n handlerFn: SafeRouteHandler<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData,\n TReq\n >\n): CreateSafeRouteHandlerReturnType<TReq> {\n // NOTE: `body` and `formData` options are mutually exclusive 🎭\n if (options.body && options.formData) {\n throw new Error(\n 'You cannot use both `body` and `formData` in the same route handler. They are both mutually exclusive.'\n )\n }\n\n const log = createLogger(options.debug)\n const id = options.id ?? DEFAULT_ID\n\n const onErrorResponse =\n options.onErrorResponse ??\n ((err: unknown): Awaitable<Response> => {\n log.error(`🛑 Unexpected error in route handler '${id}'`, err)\n return new Response('Internal server error', {\n status: 500,\n })\n })\n\n const onSegmentsValidationErrorResponse =\n options.onSegmentsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid segments for route handler '${id}':`, issues)\n return new Response('Invalid segments', {\n status: 400,\n })\n })\n\n const onSearchParamsValidationErrorResponse =\n options.onSearchParamsValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid search params for route handler '${id}':`, issues)\n return new Response('Invalid search params', {\n status: 400,\n })\n })\n\n const onBodyValidationErrorResponse =\n options.onBodyValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid body for route handler '${id}':`, issues)\n return new Response('Invalid body', {\n status: 400,\n })\n })\n\n const onFormDataValidationErrorResponse =\n options.onFormDataValidationErrorResponse ??\n ((issues: readonly StandardSchemaV1.Issue[]): Awaitable<Response> => {\n log.error(`🛑 Invalid form data for route handler '${id}':`, issues)\n return new Response('Invalid form data', {\n status: 400,\n })\n })\n\n const authorize = options.authorize ?? (async () => undefined)\n\n // Next.js API Route handler declaration\n return async function (\n req: TReq,\n providedContext: ProvidedRouteContext\n ): Promise<Response> {\n const executionClock = createExecutionClock()\n executionClock.start()\n\n log.info(`🔄 Running route handler '${id}'`)\n log.info(`👉🏻 Request ${req.method} ${req.url}`)\n\n const url = new URL(req.url)\n\n let segments = undefined\n if (options.segments) {\n const params = await providedContext.params\n if (params === undefined) {\n return new Response('No segments provided', { status: 400 })\n }\n\n const parsedSegments = parseWithDictionary(options.segments, params)\n if (parsedSegments.issues) {\n return await onSegmentsValidationErrorResponse(parsedSegments.issues)\n }\n\n segments = parsedSegments.value\n }\n\n let searchParams = undefined\n if (options.searchParams) {\n const queryParams_unsafe = [...url.searchParams.keys()].map((k) => {\n const values = url.searchParams.getAll(k)\n return [k, values.length > 1 ? values : values[0]]\n })\n\n const parsedSearchParams = parseWithDictionary(\n options.searchParams,\n Object.fromEntries(queryParams_unsafe)\n )\n\n if (parsedSearchParams.issues) {\n return await onSearchParamsValidationErrorResponse(\n parsedSearchParams.issues\n )\n }\n\n searchParams = parsedSearchParams.value\n }\n\n // Do not mutate / consume the original request\n const clonedReq_forBody = req.clone() as TReq\n\n let body = undefined\n if (options.body) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request body', {\n status: 405,\n })\n }\n\n let body_unsafe: unknown\n try {\n body_unsafe = await readRequestBodyAsJson(clonedReq_forBody)\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedBody = validateWithSchema(\n options.body,\n body_unsafe,\n 'Request body validation must be synchronous'\n )\n\n if (parsedBody.issues) {\n return await onBodyValidationErrorResponse(parsedBody.issues)\n }\n\n body = parsedBody.value\n }\n\n let formData = undefined\n if (options.formData) {\n if (!['POST', 'PUT', 'PATCH'].includes(req.method)) {\n return new Response('Invalid method for request form data', {\n status: 405,\n })\n }\n\n const contentType = req.headers.get('content-type')\n if (\n !contentType?.startsWith('multipart/form-data') &&\n !contentType?.startsWith('application/x-www-form-urlencoded')\n ) {\n return new Response('Invalid content type for request form data', {\n status: 415,\n })\n }\n\n let formData_unsafe: FormData\n try {\n // NOTE: 🤔 maybe find a better way to counter the deprecation warning?\n formData_unsafe = await clonedReq_forBody.formData()\n } catch (err) {\n return await onErrorResponse(err)\n }\n\n const parsedFormData = parseWithDictionary(\n options.formData,\n Object.fromEntries(formData_unsafe.entries())\n )\n\n if (parsedFormData.issues) {\n return await onFormDataValidationErrorResponse(parsedFormData.issues)\n }\n\n formData = parsedFormData.value\n }\n\n // Do not mutate / consume the original request\n // Due to `NextRequest` limitations as the req is cloned it's always a Request\n const clonedReq_forAuth = req.clone()\n const authParams = {\n id,\n url,\n req: clonedReq_forAuth,\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n ...(body ? { body } : {}),\n ...(formData ? { formData } : {}),\n } as AuthFunctionParams<\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >\n const authOrResponse = await authorize(authParams)\n if (authOrResponse instanceof Response) {\n log.error(`🛑 Request not authorized for route handler '${id}'`)\n return authOrResponse\n }\n\n // Build safe route handler context\n const ctx = {\n id,\n url,\n ...(authOrResponse ? { auth: authOrResponse } : {}),\n ...(segments ? { segments } : {}),\n ...(searchParams ? { searchParams } : {}),\n ...(body ? { body } : {}),\n ...(formData ? { formData } : {}),\n } as SafeRouteHandlerContext<\n AC,\n TRouteDynamicSegments,\n TSearchParams,\n TBody,\n TFormData\n >\n\n // Let's catch any error that might happen in the handler\n try {\n const response = await handlerFn(ctx, req)\n\n executionClock.stop()\n log.info(\n `✅ Route handler '${id}' executed successfully in ${executionClock.get()}`\n )\n\n return response\n } catch (err) {\n executionClock.stop()\n log.error(\n `🛑 Route handler '${id} failed to execute after ${executionClock.get()}'`\n )\n\n return await onErrorResponse(err)\n }\n }\n}\n"],"mappings":"6DAsBO,IAAMA,EAAa,0BAQpBC,EAAwB,MAC5BC,GACqB,CAErB,GADoBA,EAAI,QAAQ,IAAI,cAAc,GACjC,WAAW,kBAAkB,EAC5C,OAAO,MAAMA,EAAI,KAAK,EAGxB,IAAMC,EAAO,MAAMD,EAAI,KAAK,EAC5B,OAAO,KAAK,MAAMC,CAAI,CACxB,EAsCO,SAASC,EAQdC,EAOAC,EAQwC,CAExC,GAAID,EAAQ,MAAQA,EAAQ,SAC1B,MAAM,IAAI,MACR,wGACF,EAGF,IAAME,EAAMC,EAAaH,EAAQ,KAAK,EAChCI,EAAKJ,EAAQ,IAAML,EAEnBU,EACJL,EAAQ,kBACNM,IACAJ,EAAI,MAAM,gDAAyCE,CAAE,IAAKE,CAAG,EACtD,IAAI,SAAS,wBAAyB,CAC3C,OAAQ,GACV,CAAC,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AAQ,CAAC,CAC9C,EAEA,GAAIC,EAAe,OACjB,OAAO,MAAMvB,EAAkCuB,EAAe,MAAM,EAGtEH,EAAWG,EAAe,KAC5B,CAIA,IAAMC,EAAoBtC,EAAI,MAAM,EAC9BuC,EAAa,CACjB,GAAAhC,EACA,IAAAY,EACA,IAAKmB,EACL,GAAIlB,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,EAC/B,GAAII,EAAe,CAAE,aAAAA,CAAa,EAAI,CAAC,EACvC,GAAIM,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,EACvB,GAAII,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,CACjC,EAMMM,EAAiB,MAAMzB,EAAUwB,CAAU,EACjD,GAAIC,aAA0B,SAC5B,OAAAnC,EAAI,MAAM,uDAAgDE,CAAE,GAAG,EACxDiC,EAIT,IAAMC,EAAM,CACV,GAAAlC,EACA,IAAAY,EACA,GAAIqB,EAAiB,CAAE,KAAMA,CAAe,EAAI,CAAC,EACjD,GAAIpB,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,EAC/B,GAAII,EAAe,CAAE,aAAAA,CAAa,EAAI,CAAC,EACvC,GAAIM,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,EACvB,GAAII,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,CACjC,EASA,GAAI,CACF,IAAMQ,EAAW,MAAMtC,EAAUqC,EAAKzC,CAAG,EAEzC,OAAAiB,EAAe,KAAK,EACpBZ,EAAI,KACF,yBAAoBE,CAAE,8BAA8BU,EAAe,IAAI,CAAC,EAC1E,EAEOyB,CACT,OAASjC,EAAK,CACZ,OAAAQ,EAAe,KAAK,EACpBZ,EAAI,MACF,4BAAqBE,CAAE,4BAA4BU,EAAe,IAAI,CAAC,GACzE,EAEO,MAAMT,EAAgBC,CAAG,CAClC,CACF,CACF","names":["DEFAULT_ID","readRequestBodyAsJson","req","text","createSafeRouteHandler","options","handlerFn","log","createLogger","id","onErrorResponse","err","onSegmentsValidationErrorResponse","issues","onSearchParamsValidationErrorResponse","onBodyValidationErrorResponse","onFormDataValidationErrorResponse","authorize","providedContext","executionClock","createExecutionClock","url","segments","params","parsedSegments","parseWithDictionary","searchParams","queryParams_unsafe","k","values","parsedSearchParams","clonedReq_forBody","body","body_unsafe","parsedBody","validateWithSchema","formData","contentType","formData_unsafe","parsedFormData","clonedReq_forAuth","authParams","authOrResponse","ctx","response"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkUDCVGQMHcjs = require('../chunk-UDCVGQMH.cjs');var p=class extends Error{constructor(c,n,e){super(`${c==="searchParams"?"Search params":"Segments"} validation error for ${e} server component '${n}`),this.name="ValidationError"}},f=class extends Error{constructor(c,n){super(`No segments provided for ${n} server component '${c}'`),this.name="NoSegmentsProvidedError"}},v=class extends Error{constructor(c,n){super(`No search params provided for ${n} server component '${c}'`),this.name="NoSearchParamsProvidedError"}};var w="[unknown:page:server:component]";function x(r,c){let n=_chunkUDCVGQMHcjs.a.call(void 0, r.debug),e=_nullishCoalesce(r.id, () => (w)),h=_nullishCoalesce(r.onError, () => ((s=>{throw n.error(`\u{1F6D1} Unexpected error in page server component '${e}'`,s),s}))),P=_nullishCoalesce(r.onSegmentsValidationError, () => ((s=>{throw n.error(`\u{1F6D1} Invalid segments for page server component '${e}'`,s),new p("segments",e,"page")}))),C=_nullishCoalesce(r.onSearchParamsValidationError, () => ((s=>{throw n.error(`\u{1F6D1} Invalid search params for server component '${e}'`,s),new p("searchParams",e,"page")}))),S=_nullishCoalesce(r.authorize, () => ((async()=>{})));return async function(d){let o=_chunkUDCVGQMHcjs.b.call(void 0, );o.start(),n.info(`\u{1F504} Running page server component'${e}'`);let u;if(r.segments){let a=await d.params;if(a===void 0)throw new f(e,"page");let i=_chunkUDCVGQMHcjs.d.call(void 0, r.segments,a);i.issues?await P(i.issues):u=i.value}let t;if(r.searchParams){let a=await d.searchParams;if(a===void 0)throw new v(e,"page");let i=_chunkUDCVGQMHcjs.d.call(void 0, r.searchParams,a);i.issues?await C(i.issues):t=i.value}let m;try{let a={id:e,...u?{segments:u}:{},...t?{searchParams:t}:{}};m=await S(a)}catch(a){throw n.error(`Page server component '${e}' not authorized`),a}try{let a={id:e,...m?{auth:m}:{},...u?{segments:u}:{},...t?{searchParams:t}:{}},i=await c(a);return o.stop(),n.info(`\u2705 Page server component '${e}' executed successfully in ${o.get()}`),i}catch(a){return o.stop(),n.error(`\u{1F6D1} Page server component '${e}' failed to execute after ${o.get()}`,a),await h(a)}}}var T="[unknown:layout:server:component]";function A(r,c){let n=_chunkUDCVGQMHcjs.a.call(void 0, r.debug),e=_nullishCoalesce(r.id, () => (T)),h=_nullishCoalesce(r.onError, () => ((S=>{throw n.error(`\u{1F6D1} Unexpected error in layout server component '${e}'`,S),S}))),P=_nullishCoalesce(r.onSegmentsValidationError, () => ((S=>{throw n.error(`\u{1F6D1} Invalid segments for layout server component '${e}'`,S),new p("segments",e,"page")}))),C=_nullishCoalesce(r.authorize, () => ((async()=>{})));return async function(s){let d=_chunkUDCVGQMHcjs.b.call(void 0, );d.start(),n.info(`\u{1F504} Running layout server component'${e}'`);let o;if(r.segments){let t=await s.params;if(t===void 0)throw new f(e,"page");let m=_chunkUDCVGQMHcjs.d.call(void 0, r.segments,t);m.issues?await P(m.issues):o=m.value}let u;try{let t={id:e,...o?{segments:o}:{}};u=await C(t)}catch(t){throw n.error(`Layout server component '${e}' not authorized`),t}try{let t={id:e,...u?{auth:u}:{},...o?{segments:o}:{},children:s.children},m=await c(t);return d.stop(),n.info(`\u2705 Layout server component '${e}' executed successfully in ${d.get()}`),m}catch(t){return d.stop(),n.error(`\u{1F6D1} Layout server component '${e}' failed to execute after ${d.get()}`,t),await h(t)}}}exports.createSafeLayoutServerComponent = A; exports.createSafePageServerComponent = x;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/anzen/anzen/dist/server-components/index.cjs","../../src/server-components/errors.ts"],"names":["ValidationError","validationType","id","serverComponentType"],"mappings":"AAAA,sOAAuD,ICG1CA,CAAAA,CAAN,MAAA,QAA8B,KAAM,CACzC,WAAA,CACEC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACA,CACA,KAAA,CACE,CAAA,EAAA","file":"/home/runner/work/anzen/anzen/dist/server-components/index.cjs","sourcesContent":[null,"/**\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"]}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { i as StandardSchemaDictionary, j as StandardSchemaV1, e as Awaitable, U as UnwrapReadonlyObject, E as EmptyObjectType, A as AuthContext } from '../types-LPIIICMI.cjs';
|
|
2
|
+
|
|
3
|
+
type TSegmentsDict = StandardSchemaDictionary;
|
|
4
|
+
type TSearchParamsDict = StandardSchemaDictionary;
|
|
5
|
+
type OnValidationError = (issues: readonly StandardSchemaV1.Issue[]) => Awaitable<never>;
|
|
6
|
+
type BaseOptions<TSegments extends TSegmentsDict | undefined> = {
|
|
7
|
+
/**
|
|
8
|
+
* ID for the server component.
|
|
9
|
+
* Used when logging in development or when `debug` is enabled.
|
|
10
|
+
*
|
|
11
|
+
* You can also use it to add extra logging or monitoring.
|
|
12
|
+
*/
|
|
13
|
+
id?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Callback triggered when the server component throws an unhandled error..
|
|
16
|
+
* By default it rethrows as service hatch to Next.js do its job
|
|
17
|
+
* band use error boundaries. The error is logged into the console.
|
|
18
|
+
*
|
|
19
|
+
* Use it if you want to manage unexpected errors properly
|
|
20
|
+
* to log, trace or define behaviors like using `notFound` or `redirect`.
|
|
21
|
+
*/
|
|
22
|
+
onError?: (err: unknown) => Awaitable<never>;
|
|
23
|
+
/**
|
|
24
|
+
* Use this options to enable debug mode.
|
|
25
|
+
* It will add logs in the handler to help you debug server component..
|
|
26
|
+
*
|
|
27
|
+
* By default it's set to `false` for production builds.
|
|
28
|
+
* In development builds, it will be `true` if `NODE_ENV` is not set to `production`.
|
|
29
|
+
*/
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Dynamic route segments used for the server component route path.
|
|
33
|
+
* By design it will handle if the segments are a `Promise` or not.
|
|
34
|
+
*
|
|
35
|
+
* Please note the expected input is a `StandardSchemaDictionary`.
|
|
36
|
+
*/
|
|
37
|
+
segments?: TSegments;
|
|
38
|
+
/**
|
|
39
|
+
* Callback triggered when dynamic segments validations returned issues.
|
|
40
|
+
* By default it throws a Validation error and issues are logged into the console.
|
|
41
|
+
*/
|
|
42
|
+
onSegmentsValidationError?: OnValidationError;
|
|
43
|
+
};
|
|
44
|
+
type PageAuthFunctionParams<TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = {
|
|
45
|
+
/**
|
|
46
|
+
* Server component ID
|
|
47
|
+
*/
|
|
48
|
+
readonly id: string;
|
|
49
|
+
} & (TSegments extends TSegmentsDict ? {
|
|
50
|
+
/**
|
|
51
|
+
* Validated route dynamic segments
|
|
52
|
+
*/
|
|
53
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
54
|
+
} : EmptyObjectType) & (TSearchParams extends TSearchParamsDict ? {
|
|
55
|
+
/**
|
|
56
|
+
* Validated search params
|
|
57
|
+
*/
|
|
58
|
+
readonly searchParams: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSearchParams>>;
|
|
59
|
+
} : EmptyObjectType);
|
|
60
|
+
type LayoutAuthFunctionParams<TSegments extends TSegmentsDict | undefined> = {
|
|
61
|
+
/**
|
|
62
|
+
* Server component ID
|
|
63
|
+
*/
|
|
64
|
+
readonly id: string;
|
|
65
|
+
} & (TSegments extends TSegmentsDict ? {
|
|
66
|
+
/**
|
|
67
|
+
* Validated route dynamic segments
|
|
68
|
+
*/
|
|
69
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
70
|
+
} : EmptyObjectType);
|
|
71
|
+
type PageAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = (params: PageAuthFunctionParams<TSegments, TSearchParams>) => Awaitable<AC | never>;
|
|
72
|
+
type LayoutAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = (params: LayoutAuthFunctionParams<TSegments>) => Awaitable<AC | never>;
|
|
73
|
+
type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = BaseOptions<TSegments> & {
|
|
74
|
+
/**
|
|
75
|
+
* Search params used in the route.
|
|
76
|
+
*
|
|
77
|
+
* Please note the expected input is a `StandardSchemaDictionary`.
|
|
78
|
+
*/
|
|
79
|
+
searchParams?: TSearchParams;
|
|
80
|
+
/**
|
|
81
|
+
* Callback triggered when search params validations returned issues.
|
|
82
|
+
* By default it throws a Validation error and issues are logged into the console.
|
|
83
|
+
*/
|
|
84
|
+
onSearchParamsValidationError?: OnValidationError;
|
|
85
|
+
/**
|
|
86
|
+
* Function to use to authorize the server component.
|
|
87
|
+
* By default it always authorize the server component.
|
|
88
|
+
*
|
|
89
|
+
* Return never (throws an error, `notFound`, `forbidden`, `unauthorized`, or `redirect`)
|
|
90
|
+
* when the request to the server component is not authorized.
|
|
91
|
+
*/
|
|
92
|
+
authorize?: PageAuthFunction<AC, TSegments, TSearchParams>;
|
|
93
|
+
};
|
|
94
|
+
type CreateSafeLayoutServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = BaseOptions<TSegments> & {
|
|
95
|
+
/**
|
|
96
|
+
* Function to use to authorize the server component.
|
|
97
|
+
* By default it always authorize the server component.
|
|
98
|
+
*
|
|
99
|
+
* Return never (throws an error, `notFound`, `forbidden`, `unauthorized`, or `redirect`)
|
|
100
|
+
* when the request to the server component is not authorized.
|
|
101
|
+
*/
|
|
102
|
+
authorize?: LayoutAuthFunction<AC, TSegments>;
|
|
103
|
+
};
|
|
104
|
+
type PageProvidedProps = {
|
|
105
|
+
/**
|
|
106
|
+
* Route dynamic segments as params
|
|
107
|
+
*/
|
|
108
|
+
params: Awaitable<any> | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Search params
|
|
111
|
+
*/
|
|
112
|
+
searchParams: Awaitable<any> | undefined;
|
|
113
|
+
};
|
|
114
|
+
type LayoutProvidedProps = {
|
|
115
|
+
/**
|
|
116
|
+
* Route dynamic segments as params
|
|
117
|
+
*/
|
|
118
|
+
params: Awaitable<any> | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* Incoming children when `createSafeServerComponent` is used for `layout.js` file.
|
|
121
|
+
*/
|
|
122
|
+
children: React.ReactNode;
|
|
123
|
+
};
|
|
124
|
+
type CreateSafePageServerComponentReturnType = (
|
|
125
|
+
/**
|
|
126
|
+
* Provided props added by Next.js itself
|
|
127
|
+
*/
|
|
128
|
+
props: PageProvidedProps) => Promise<React.ReactElement | never>;
|
|
129
|
+
type CreateSafeLayoutServerComponentReturnType = (
|
|
130
|
+
/**
|
|
131
|
+
* Provided props added by Next.js itself
|
|
132
|
+
*/
|
|
133
|
+
props: LayoutProvidedProps) => Promise<React.ReactElement | never>;
|
|
134
|
+
type SafePageServerComponentContext<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = {
|
|
135
|
+
/**
|
|
136
|
+
* Server component ID
|
|
137
|
+
*/
|
|
138
|
+
readonly id: string;
|
|
139
|
+
} & (AC extends AuthContext ? {
|
|
140
|
+
/**
|
|
141
|
+
* Auth context
|
|
142
|
+
*/
|
|
143
|
+
readonly auth: AC;
|
|
144
|
+
} : EmptyObjectType) & (TSegments extends TSegmentsDict ? {
|
|
145
|
+
/**
|
|
146
|
+
* Validated route dynamic segments
|
|
147
|
+
*/
|
|
148
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
149
|
+
} : EmptyObjectType) & (TSearchParams extends TSearchParamsDict ? {
|
|
150
|
+
/**
|
|
151
|
+
* Validated search params
|
|
152
|
+
*/
|
|
153
|
+
readonly searchParams: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSearchParams>>;
|
|
154
|
+
} : EmptyObjectType);
|
|
155
|
+
type SafeLayoutServerComponentContext<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = {
|
|
156
|
+
/**
|
|
157
|
+
* Server component ID
|
|
158
|
+
*/
|
|
159
|
+
readonly id: string;
|
|
160
|
+
/**
|
|
161
|
+
* Incoming children when `createSafeServerComponent` is used for `layout.js` file.
|
|
162
|
+
* They are set to a fragment when they don't exists in a `page.js` file.
|
|
163
|
+
*/
|
|
164
|
+
readonly children: React.ReactNode;
|
|
165
|
+
} & (AC extends AuthContext ? {
|
|
166
|
+
/**
|
|
167
|
+
* Auth context
|
|
168
|
+
*/
|
|
169
|
+
readonly auth: AC;
|
|
170
|
+
} : EmptyObjectType) & (TSegments extends TSegmentsDict ? {
|
|
171
|
+
/**
|
|
172
|
+
* Validated route dynamic segments
|
|
173
|
+
*/
|
|
174
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
175
|
+
} : EmptyObjectType);
|
|
176
|
+
type SafePageServerComponent<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = (
|
|
177
|
+
/**
|
|
178
|
+
* Safe page server component context
|
|
179
|
+
*/
|
|
180
|
+
ctx: SafePageServerComponentContext<AC, TSegments, TSearchParams>) => Promise<React.ReactElement | never>;
|
|
181
|
+
type SafeLayoutServerComponent<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = (
|
|
182
|
+
/**
|
|
183
|
+
* Safe layout server component context
|
|
184
|
+
*/
|
|
185
|
+
ctx: SafeLayoutServerComponentContext<AC, TSegments>) => Promise<React.ReactElement | never>;
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Creates a safe page server component with data validation and error handling
|
|
189
|
+
* for Next.js (>= 14) page server components.
|
|
190
|
+
*
|
|
191
|
+
* @param options - Options to configure the pageserver component.
|
|
192
|
+
* @param pageServerComponentFn - The page server component function.
|
|
193
|
+
*
|
|
194
|
+
* @returns A Next.js page server component.
|
|
195
|
+
*/
|
|
196
|
+
declare function createSafePageServerComponent<AC extends AuthContext | undefined = undefined, TSegments extends TSegmentsDict | undefined = undefined, TSearchParams extends TSearchParamsDict | undefined = undefined>(options: CreateSafePageServerComponentOptions<AC, TSegments, TSearchParams>, pageServerComponentFn: SafePageServerComponent<AC, TSegments, TSearchParams>): CreateSafePageServerComponentReturnType;
|
|
197
|
+
/**
|
|
198
|
+
* Creates a safe layout server component with data validation and error handling
|
|
199
|
+
* for Next.js (>= 14) layout server components.
|
|
200
|
+
*
|
|
201
|
+
* @param options - Options to configure the pageserver component.
|
|
202
|
+
* @param layoutServerComponentFn - The layout server component function.
|
|
203
|
+
*
|
|
204
|
+
* @returns A Next.js layout server component.
|
|
205
|
+
*/
|
|
206
|
+
declare function createSafeLayoutServerComponent<AC extends AuthContext | undefined = undefined, TSegments extends TSegmentsDict | undefined = undefined>(options: CreateSafeLayoutServerComponentOptions<AC, TSegments>, layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments>): CreateSafeLayoutServerComponentReturnType;
|
|
207
|
+
|
|
208
|
+
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 };
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { i as StandardSchemaDictionary, j as StandardSchemaV1, e as Awaitable, U as UnwrapReadonlyObject, E as EmptyObjectType, A as AuthContext } from '../types-LPIIICMI.js';
|
|
2
|
+
|
|
3
|
+
type TSegmentsDict = StandardSchemaDictionary;
|
|
4
|
+
type TSearchParamsDict = StandardSchemaDictionary;
|
|
5
|
+
type OnValidationError = (issues: readonly StandardSchemaV1.Issue[]) => Awaitable<never>;
|
|
6
|
+
type BaseOptions<TSegments extends TSegmentsDict | undefined> = {
|
|
7
|
+
/**
|
|
8
|
+
* ID for the server component.
|
|
9
|
+
* Used when logging in development or when `debug` is enabled.
|
|
10
|
+
*
|
|
11
|
+
* You can also use it to add extra logging or monitoring.
|
|
12
|
+
*/
|
|
13
|
+
id?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Callback triggered when the server component throws an unhandled error..
|
|
16
|
+
* By default it rethrows as service hatch to Next.js do its job
|
|
17
|
+
* band use error boundaries. The error is logged into the console.
|
|
18
|
+
*
|
|
19
|
+
* Use it if you want to manage unexpected errors properly
|
|
20
|
+
* to log, trace or define behaviors like using `notFound` or `redirect`.
|
|
21
|
+
*/
|
|
22
|
+
onError?: (err: unknown) => Awaitable<never>;
|
|
23
|
+
/**
|
|
24
|
+
* Use this options to enable debug mode.
|
|
25
|
+
* It will add logs in the handler to help you debug server component..
|
|
26
|
+
*
|
|
27
|
+
* By default it's set to `false` for production builds.
|
|
28
|
+
* In development builds, it will be `true` if `NODE_ENV` is not set to `production`.
|
|
29
|
+
*/
|
|
30
|
+
debug?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Dynamic route segments used for the server component route path.
|
|
33
|
+
* By design it will handle if the segments are a `Promise` or not.
|
|
34
|
+
*
|
|
35
|
+
* Please note the expected input is a `StandardSchemaDictionary`.
|
|
36
|
+
*/
|
|
37
|
+
segments?: TSegments;
|
|
38
|
+
/**
|
|
39
|
+
* Callback triggered when dynamic segments validations returned issues.
|
|
40
|
+
* By default it throws a Validation error and issues are logged into the console.
|
|
41
|
+
*/
|
|
42
|
+
onSegmentsValidationError?: OnValidationError;
|
|
43
|
+
};
|
|
44
|
+
type PageAuthFunctionParams<TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = {
|
|
45
|
+
/**
|
|
46
|
+
* Server component ID
|
|
47
|
+
*/
|
|
48
|
+
readonly id: string;
|
|
49
|
+
} & (TSegments extends TSegmentsDict ? {
|
|
50
|
+
/**
|
|
51
|
+
* Validated route dynamic segments
|
|
52
|
+
*/
|
|
53
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
54
|
+
} : EmptyObjectType) & (TSearchParams extends TSearchParamsDict ? {
|
|
55
|
+
/**
|
|
56
|
+
* Validated search params
|
|
57
|
+
*/
|
|
58
|
+
readonly searchParams: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSearchParams>>;
|
|
59
|
+
} : EmptyObjectType);
|
|
60
|
+
type LayoutAuthFunctionParams<TSegments extends TSegmentsDict | undefined> = {
|
|
61
|
+
/**
|
|
62
|
+
* Server component ID
|
|
63
|
+
*/
|
|
64
|
+
readonly id: string;
|
|
65
|
+
} & (TSegments extends TSegmentsDict ? {
|
|
66
|
+
/**
|
|
67
|
+
* Validated route dynamic segments
|
|
68
|
+
*/
|
|
69
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
70
|
+
} : EmptyObjectType);
|
|
71
|
+
type PageAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = (params: PageAuthFunctionParams<TSegments, TSearchParams>) => Awaitable<AC | never>;
|
|
72
|
+
type LayoutAuthFunction<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = (params: LayoutAuthFunctionParams<TSegments>) => Awaitable<AC | never>;
|
|
73
|
+
type CreateSafePageServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = BaseOptions<TSegments> & {
|
|
74
|
+
/**
|
|
75
|
+
* Search params used in the route.
|
|
76
|
+
*
|
|
77
|
+
* Please note the expected input is a `StandardSchemaDictionary`.
|
|
78
|
+
*/
|
|
79
|
+
searchParams?: TSearchParams;
|
|
80
|
+
/**
|
|
81
|
+
* Callback triggered when search params validations returned issues.
|
|
82
|
+
* By default it throws a Validation error and issues are logged into the console.
|
|
83
|
+
*/
|
|
84
|
+
onSearchParamsValidationError?: OnValidationError;
|
|
85
|
+
/**
|
|
86
|
+
* Function to use to authorize the server component.
|
|
87
|
+
* By default it always authorize the server component.
|
|
88
|
+
*
|
|
89
|
+
* Return never (throws an error, `notFound`, `forbidden`, `unauthorized`, or `redirect`)
|
|
90
|
+
* when the request to the server component is not authorized.
|
|
91
|
+
*/
|
|
92
|
+
authorize?: PageAuthFunction<AC, TSegments, TSearchParams>;
|
|
93
|
+
};
|
|
94
|
+
type CreateSafeLayoutServerComponentOptions<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = BaseOptions<TSegments> & {
|
|
95
|
+
/**
|
|
96
|
+
* Function to use to authorize the server component.
|
|
97
|
+
* By default it always authorize the server component.
|
|
98
|
+
*
|
|
99
|
+
* Return never (throws an error, `notFound`, `forbidden`, `unauthorized`, or `redirect`)
|
|
100
|
+
* when the request to the server component is not authorized.
|
|
101
|
+
*/
|
|
102
|
+
authorize?: LayoutAuthFunction<AC, TSegments>;
|
|
103
|
+
};
|
|
104
|
+
type PageProvidedProps = {
|
|
105
|
+
/**
|
|
106
|
+
* Route dynamic segments as params
|
|
107
|
+
*/
|
|
108
|
+
params: Awaitable<any> | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Search params
|
|
111
|
+
*/
|
|
112
|
+
searchParams: Awaitable<any> | undefined;
|
|
113
|
+
};
|
|
114
|
+
type LayoutProvidedProps = {
|
|
115
|
+
/**
|
|
116
|
+
* Route dynamic segments as params
|
|
117
|
+
*/
|
|
118
|
+
params: Awaitable<any> | undefined;
|
|
119
|
+
/**
|
|
120
|
+
* Incoming children when `createSafeServerComponent` is used for `layout.js` file.
|
|
121
|
+
*/
|
|
122
|
+
children: React.ReactNode;
|
|
123
|
+
};
|
|
124
|
+
type CreateSafePageServerComponentReturnType = (
|
|
125
|
+
/**
|
|
126
|
+
* Provided props added by Next.js itself
|
|
127
|
+
*/
|
|
128
|
+
props: PageProvidedProps) => Promise<React.ReactElement | never>;
|
|
129
|
+
type CreateSafeLayoutServerComponentReturnType = (
|
|
130
|
+
/**
|
|
131
|
+
* Provided props added by Next.js itself
|
|
132
|
+
*/
|
|
133
|
+
props: LayoutProvidedProps) => Promise<React.ReactElement | never>;
|
|
134
|
+
type SafePageServerComponentContext<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = {
|
|
135
|
+
/**
|
|
136
|
+
* Server component ID
|
|
137
|
+
*/
|
|
138
|
+
readonly id: string;
|
|
139
|
+
} & (AC extends AuthContext ? {
|
|
140
|
+
/**
|
|
141
|
+
* Auth context
|
|
142
|
+
*/
|
|
143
|
+
readonly auth: AC;
|
|
144
|
+
} : EmptyObjectType) & (TSegments extends TSegmentsDict ? {
|
|
145
|
+
/**
|
|
146
|
+
* Validated route dynamic segments
|
|
147
|
+
*/
|
|
148
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
149
|
+
} : EmptyObjectType) & (TSearchParams extends TSearchParamsDict ? {
|
|
150
|
+
/**
|
|
151
|
+
* Validated search params
|
|
152
|
+
*/
|
|
153
|
+
readonly searchParams: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSearchParams>>;
|
|
154
|
+
} : EmptyObjectType);
|
|
155
|
+
type SafeLayoutServerComponentContext<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = {
|
|
156
|
+
/**
|
|
157
|
+
* Server component ID
|
|
158
|
+
*/
|
|
159
|
+
readonly id: string;
|
|
160
|
+
/**
|
|
161
|
+
* Incoming children when `createSafeServerComponent` is used for `layout.js` file.
|
|
162
|
+
* They are set to a fragment when they don't exists in a `page.js` file.
|
|
163
|
+
*/
|
|
164
|
+
readonly children: React.ReactNode;
|
|
165
|
+
} & (AC extends AuthContext ? {
|
|
166
|
+
/**
|
|
167
|
+
* Auth context
|
|
168
|
+
*/
|
|
169
|
+
readonly auth: AC;
|
|
170
|
+
} : EmptyObjectType) & (TSegments extends TSegmentsDict ? {
|
|
171
|
+
/**
|
|
172
|
+
* Validated route dynamic segments
|
|
173
|
+
*/
|
|
174
|
+
readonly segments: UnwrapReadonlyObject<StandardSchemaDictionary.InferOutput<TSegments>>;
|
|
175
|
+
} : EmptyObjectType);
|
|
176
|
+
type SafePageServerComponent<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined, TSearchParams extends TSearchParamsDict | undefined> = (
|
|
177
|
+
/**
|
|
178
|
+
* Safe page server component context
|
|
179
|
+
*/
|
|
180
|
+
ctx: SafePageServerComponentContext<AC, TSegments, TSearchParams>) => Promise<React.ReactElement | never>;
|
|
181
|
+
type SafeLayoutServerComponent<AC extends AuthContext | undefined, TSegments extends TSegmentsDict | undefined> = (
|
|
182
|
+
/**
|
|
183
|
+
* Safe layout server component context
|
|
184
|
+
*/
|
|
185
|
+
ctx: SafeLayoutServerComponentContext<AC, TSegments>) => Promise<React.ReactElement | never>;
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Creates a safe page server component with data validation and error handling
|
|
189
|
+
* for Next.js (>= 14) page server components.
|
|
190
|
+
*
|
|
191
|
+
* @param options - Options to configure the pageserver component.
|
|
192
|
+
* @param pageServerComponentFn - The page server component function.
|
|
193
|
+
*
|
|
194
|
+
* @returns A Next.js page server component.
|
|
195
|
+
*/
|
|
196
|
+
declare function createSafePageServerComponent<AC extends AuthContext | undefined = undefined, TSegments extends TSegmentsDict | undefined = undefined, TSearchParams extends TSearchParamsDict | undefined = undefined>(options: CreateSafePageServerComponentOptions<AC, TSegments, TSearchParams>, pageServerComponentFn: SafePageServerComponent<AC, TSegments, TSearchParams>): CreateSafePageServerComponentReturnType;
|
|
197
|
+
/**
|
|
198
|
+
* Creates a safe layout server component with data validation and error handling
|
|
199
|
+
* for Next.js (>= 14) layout server components.
|
|
200
|
+
*
|
|
201
|
+
* @param options - Options to configure the pageserver component.
|
|
202
|
+
* @param layoutServerComponentFn - The layout server component function.
|
|
203
|
+
*
|
|
204
|
+
* @returns A Next.js layout server component.
|
|
205
|
+
*/
|
|
206
|
+
declare function createSafeLayoutServerComponent<AC extends AuthContext | undefined = undefined, TSegments extends TSegmentsDict | undefined = undefined>(options: CreateSafeLayoutServerComponentOptions<AC, TSegments>, layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments>): CreateSafeLayoutServerComponentReturnType;
|
|
207
|
+
|
|
208
|
+
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 };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as y,b as l,d as g}from"../chunk-DT3TEL5X.js";var p=class extends Error{constructor(c,n,e){super(`${c==="searchParams"?"Search params":"Segments"} validation error for ${e} server component '${n}`),this.name="ValidationError"}},f=class extends Error{constructor(c,n){super(`No segments provided for ${n} server component '${c}'`),this.name="NoSegmentsProvidedError"}},v=class extends Error{constructor(c,n){super(`No search params provided for ${n} server component '${c}'`),this.name="NoSearchParamsProvidedError"}};var w="[unknown:page:server:component]";function x(r,c){let n=y(r.debug),e=r.id??w,h=r.onError??(s=>{throw n.error(`\u{1F6D1} Unexpected error in page server component '${e}'`,s),s}),P=r.onSegmentsValidationError??(s=>{throw n.error(`\u{1F6D1} Invalid segments for page server component '${e}'`,s),new p("segments",e,"page")}),C=r.onSearchParamsValidationError??(s=>{throw n.error(`\u{1F6D1} Invalid search params for server component '${e}'`,s),new p("searchParams",e,"page")}),S=r.authorize??(async()=>{});return async function(d){let o=l();o.start(),n.info(`\u{1F504} Running page server component'${e}'`);let u;if(r.segments){let a=await d.params;if(a===void 0)throw new f(e,"page");let i=g(r.segments,a);i.issues?await P(i.issues):u=i.value}let t;if(r.searchParams){let a=await d.searchParams;if(a===void 0)throw new v(e,"page");let i=g(r.searchParams,a);i.issues?await C(i.issues):t=i.value}let m;try{let a={id:e,...u?{segments:u}:{},...t?{searchParams:t}:{}};m=await S(a)}catch(a){throw n.error(`Page server component '${e}' not authorized`),a}try{let a={id:e,...m?{auth:m}:{},...u?{segments:u}:{},...t?{searchParams:t}:{}},i=await c(a);return o.stop(),n.info(`\u2705 Page server component '${e}' executed successfully in ${o.get()}`),i}catch(a){return o.stop(),n.error(`\u{1F6D1} Page server component '${e}' failed to execute after ${o.get()}`,a),await h(a)}}}var T="[unknown:layout:server:component]";function A(r,c){let n=y(r.debug),e=r.id??T,h=r.onError??(S=>{throw n.error(`\u{1F6D1} Unexpected error in layout server component '${e}'`,S),S}),P=r.onSegmentsValidationError??(S=>{throw n.error(`\u{1F6D1} Invalid segments for layout server component '${e}'`,S),new p("segments",e,"page")}),C=r.authorize??(async()=>{});return async function(s){let d=l();d.start(),n.info(`\u{1F504} Running layout server component'${e}'`);let o;if(r.segments){let t=await s.params;if(t===void 0)throw new f(e,"page");let m=g(r.segments,t);m.issues?await P(m.issues):o=m.value}let u;try{let t={id:e,...o?{segments:o}:{}};u=await C(t)}catch(t){throw n.error(`Layout server component '${e}' not authorized`),t}try{let t={id:e,...u?{auth:u}:{},...o?{segments:o}:{},children:s.children},m=await c(t);return d.stop(),n.info(`\u2705 Layout server component '${e}' executed successfully in ${d.get()}`),m}catch(t){return d.stop(),n.error(`\u{1F6D1} Layout server component '${e}' failed to execute after ${d.get()}`,t),await h(t)}}}export{A as createSafeLayoutServerComponent,x as createSafePageServerComponent};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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","import { createExecutionClock, createLogger } 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} 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 log.error(\n `🛑 Page server component '${id}' failed to execute after ${executionClock.get()}`,\n err\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>(\n options: CreateSafeLayoutServerComponentOptions<AC, TSegments>,\n layoutServerComponentFn: SafeLayoutServerComponent<AC, TSegments>\n): CreateSafeLayoutServerComponentReturnType {\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(props: LayoutProvidedProps) {\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 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 // 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: props.children,\n } as SafeLayoutServerComponentContext<AC, TSegments>\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 log.error(\n `🛑 Layout server component '${id}' failed to execute after ${executionClock.get()}`,\n err\n )\n return await onError(err)\n }\n }\n}\n"],"mappings":"uDAGO,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,ECZO,IAAMI,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,wDAAiDE,CAAE,IAAKE,CAAG,EAC/DA,CACR,GAEIC,EACJP,EAAQ,4BACNQ,GAAgE,CAChE,MAAAN,EAAI,MAAM,yDAAkDE,CAAE,IAAKI,CAAM,EACnE,IAAIC,E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AArB,EACA,GAAIW,EAAW,CAAE,SAAAA,CAAS,EAAI,CAAC,CACjC,EAEAS,EAAO,MAAMb,EAAUc,CAAU,CACnC,OAASnB,EAAc,CACrB,MAAAJ,EAAI,MAAM,4BAA4BE,CAAE,kBAAkB,EACpDE,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,SAAUH,EAAM,QAClB,EAGMmB,EAAwB,MAAMD,EAAwBJ,CAAG,EAG/D,OAAAb,EAAe,KAAK,EACpBX,EAAI,KACF,mCAA8BE,CAAE,8BAA8BS,EAAe,IAAI,CAAC,EACpF,EAEOkB,CACT,OAASzB,EAAc,CACrB,OAAAO,EAAe,KAAK,EACpBX,EAAI,MACF,sCAA+BE,CAAE,6BAA6BS,EAAe,IAAI,CAAC,GAClFP,CACF,EACO,MAAMD,EAAQC,CAAG,CAC1B,CACF,CACF","names":["ValidationError","validationType","id","serverComponentType","NoSegmentsProvidedError","NoSearchParamsProvidedError","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","DEFAULT_LAYOUT_ID","createSafeLayoutServerComponent","layoutServerComponentFn","LayoutServerComponent"]}
|