@emeryld/rrroutes-contract 2.3.2 → 2.3.3

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.
@@ -115,24 +115,9 @@ export type MethodCfgLowProfile = Omit<MethodCfg, 'bodySchema' | 'querySchema' |
115
115
  outputSchema?: RouteSchema;
116
116
  };
117
117
  export type AnyLeafLowProfile = LeafLowProfile<HttpMethod, string, MethodCfgLowProfile>;
118
- export declare function buildLowProfileLeaf<T extends AnyLeaf>(leaf: T): T & {
119
- cfg: {
120
- bodySchema: RouteSchema<z.infer<typeof leaf.cfg.bodySchema>>;
121
- querySchema: RouteSchema<z.infer<typeof leaf.cfg.querySchema>>;
122
- paramsSchema: RouteSchema<z.infer<typeof leaf.cfg.paramsSchema>>;
123
- outputSchema: RouteSchema<z.infer<typeof leaf.cfg.outputSchema>>;
124
- bodyFiles?: FileField[];
125
- feed?: boolean;
126
- description?: string;
127
- summary?: string;
128
- docsGroup?: string;
129
- tags?: string[];
130
- deprecated?: boolean;
131
- stability?: "experimental" | "beta" | "stable" | "deprecated";
132
- docsHidden?: boolean;
133
- docsMeta?: Record<string, unknown>;
134
- };
135
- };
118
+ export declare function buildLowProfileLeaf<L extends AnyLeaf>(leaf: L): LeafLowProfile<L['method'], L['path'], {
119
+ [K in keyof L['cfg']]: K extends 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema' ? RouteSchema<z.infer<L['cfg'][K]>> : L['cfg'][K];
120
+ }>;
136
121
  export type LeafLowProfile<M extends HttpMethod, P extends string, C extends MethodCfgLowProfile> = {
137
122
  /** Lowercase HTTP method (get/post/...). */
138
123
  readonly method: M;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts"],"sourcesContent":["export * from './core/routesV3.builder'\nexport * from './core/routesV3.core'\nexport * from './core/routesV3.finalize'\nexport * from './crud/routesV3.crud'\nexport * from './sockets/socket.index'\n","import { z } from 'zod'\nimport {\n AnyLeaf,\n AnyLeafLowProfile,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n RouteSchema,\n} from './routesV3.core'\n\nconst paginationQueryShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nconst defaultFeedQuerySchema = z.object(paginationQueryShape)\ntype PaginationShape = typeof paginationQueryShape\n\ntype ZodTypeAny = z.ZodTypeAny\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{\n [K in Name]: S\n}>\ntype ZodArrayAny = z.ZodArray<ZodTypeAny>\ntype ZodObjectAny = z.ZodObject<any>\ntype AnyZodObject = z.ZodObject<any>\ntype MergedParamsResult<\n PS,\n Name extends string,\n P extends ZodTypeAny,\n> = PS extends ZodTypeAny\n ? z.ZodIntersection<PS, ParamZod<Name, P>>\n : ParamZod<Name, P>\n\nfunction getZodShape(schema: ZodObjectAny) {\n const shapeOrGetter = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n if (!shapeOrGetter) return {}\n return typeof shapeOrGetter === 'function'\n ? shapeOrGetter.call(schema)\n : shapeOrGetter\n}\n\nfunction collectNestedFieldSuggestions(\n shape: Record<string, ZodTypeAny> | undefined,\n prefix: string[] = [],\n): string[] {\n if (!shape) return []\n const suggestions: string[] = []\n for (const [key, value] of Object.entries(shape)) {\n if (value instanceof z.ZodObject) {\n const nestedShape = getZodShape(value as ZodObjectAny)\n const nestedSuggestions = collectNestedFieldSuggestions(nestedShape, [\n ...prefix,\n key,\n ])\n suggestions.push(\n ...(nestedSuggestions.length\n ? nestedSuggestions\n : [[...prefix, key].join('_')]),\n )\n } else if (prefix.length > 0) {\n suggestions.push([...prefix, key].join('_'))\n }\n }\n return suggestions\n}\n\nconst defaultFeedOutputSchema = z.object({\n items: z.array(z.unknown()),\n nextCursor: z.string().optional(),\n})\n\nfunction augmentFeedQuerySchema<Q extends ZodTypeAny | undefined>(schema: Q) {\n if (schema && !(schema instanceof z.ZodObject)) {\n console.warn(\n 'Feed queries must be a ZodObject; default pagination applied.',\n )\n return defaultFeedQuerySchema\n }\n\n const base = (schema as ZodObjectAny) ?? z.object({})\n const shape = getZodShape(base)\n const nestedSuggestions = collectNestedFieldSuggestions(shape)\n if (nestedSuggestions.length) {\n console.warn(\n `Feed query schemas should avoid nested objects; consider flattening fields like: ${nestedSuggestions.join(\n ', ',\n )}`,\n )\n }\n return base.extend(paginationQueryShape)\n}\n\nfunction augmentFeedOutputSchema<O extends ZodTypeAny | undefined>(schema: O) {\n if (!schema) return defaultFeedOutputSchema\n if (schema instanceof z.ZodArray) {\n return z.object({\n items: schema,\n nextCursor: z.string().optional(),\n })\n }\n if (schema instanceof z.ZodObject) {\n const shape = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n const hasItems = Boolean(shape?.items)\n if (hasItems) {\n return schema.extend({ nextCursor: z.string().optional() })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n}\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny, B extends ZodTypeAny>(\n a: A,\n b: B,\n): ZodTypeAny\nfunction mergeSchemas<A extends ZodTypeAny>(a: A, b: undefined): A\nfunction mergeSchemas<B extends ZodTypeAny>(a: undefined, b: B): B\nfunction mergeSchemas(\n a: ZodTypeAny | undefined,\n b: ZodTypeAny | undefined,\n): ZodTypeAny | undefined\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined) {\n if (a && b) return z.intersection(a as any, b as any)\n return (a ?? b) as ZodTypeAny | undefined\n}\n\ntype FeedQuerySchema<C extends MethodCfg> = z.ZodObject<any>\n\ntype FeedOutputSchema<C extends MethodCfg> =\n C['outputSchema'] extends ZodArrayAny\n ? z.ZodObject<{\n items: C['outputSchema']\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : C['outputSchema'] extends ZodTypeAny\n ? z.ZodObject<{\n items: z.ZodArray<C['outputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : typeof defaultFeedOutputSchema\n\ntype BaseMethodCfg<C extends MethodCfg> = Merge<\n Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>,\n Omit<C, 'querySchema' | 'outputSchema' | 'feed'>\n>\n\ntype FeedField<C extends MethodCfg> = C['feed'] extends true\n ? { feed: true }\n : { feed?: boolean }\n\ntype AddPaginationToQuery<Q extends AnyZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & PaginationShape>\n : z.ZodObject<PaginationShape>\n\ntype FeedQueryField<C extends MethodCfg> = {\n querySchema: AddPaginationToQuery<\n C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined\n >\n}\n\ntype NonFeedQueryField<C extends MethodCfg> =\n C['querySchema'] extends ZodTypeAny\n ? { querySchema: C['querySchema'] }\n : { querySchema?: undefined }\n\ntype FeedOutputField<C extends MethodCfg> = {\n outputSchema: FeedOutputSchema<C>\n}\n\ntype NonFeedOutputField<C extends MethodCfg> =\n C['outputSchema'] extends ZodTypeAny\n ? { outputSchema: C['outputSchema'] }\n : { outputSchema?: undefined }\n\ntype ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny\n ? { paramsSchema: C['paramsSchema'] }\n : { paramsSchema: PS }\n\ntype EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true\n ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS>\n : FeedField<C> &\n NonFeedQueryField<C> &\n NonFeedOutputField<C> &\n ParamsField<C, PS>\n\ntype EffectiveCfg<C extends MethodCfg, PS> = Prettify<\n Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>\n>\n\ntype ToRouteSchema<S> = S extends ZodTypeAny ? RouteSchema<z.output<S>> : S\n\ntype LowProfileCfg<Cfg extends MethodCfg> = Prettify<\n Omit<Cfg, 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'> & {\n bodySchema: ToRouteSchema<Cfg['bodySchema']>\n querySchema: ToRouteSchema<Cfg['querySchema']>\n paramsSchema: ToRouteSchema<Cfg['paramsSchema']>\n outputSchema: ToRouteSchema<Cfg['outputSchema']>\n }\n>\n\ntype BuiltLeaf<\n M extends HttpMethod,\n Base extends string,\n I extends NodeCfg,\n C extends MethodCfg,\n PS,\n> = Leaf<M, Base, Merge<I, LowProfileCfg<EffectiveCfg<C, PS>>>>\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>\n\n sub<\n Name extends string,\n J extends NodeCfg | undefined,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n cfg: J,\n builder: (\n r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>,\n ) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>\n\n sub<Name extends string, R extends readonly AnyLeafLowProfile[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n MergedParamsResult<PS, Name, P>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends MethodCfg>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>,\n I,\n PS\n >\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'post', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'put', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'patch', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'delete', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) }\n\n function makeBranch<\n Base2 extends string,\n I2 extends NodeCfg,\n PS2 extends ZodTypeAny | undefined,\n >(base2: Base2, inherited2: I2, mergedParamsSchema?: PS2) {\n const stack: AnyLeaf[] = []\n let currentBase: string = base2\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) }\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ??\n currentParamsSchema) as PS2 | undefined\n const effectiveQuerySchema =\n cfg.feed === true\n ? augmentFeedQuerySchema(cfg.querySchema)\n : cfg.querySchema\n const effectiveOutputSchema =\n cfg.feed === true\n ? augmentFeedOutputSchema(cfg.outputSchema)\n : cfg.outputSchema\n\n const fullCfg = (\n effectiveParamsSchema\n ? {\n ...inheritedCfg,\n ...cfg,\n paramsSchema: effectiveParamsSchema,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n : {\n ...inheritedCfg,\n ...cfg,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n ) as any\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const\n\n stack.push(leaf as unknown as AnyLeaf)\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<\n Base2,\n Append<readonly [], typeof leaf>,\n I2,\n PS2\n >\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeafLowProfile[]),\n maybeBuilder?: (r: any) => readonly AnyLeafLowProfile[],\n ) {\n let cfg: NodeCfg | undefined\n let builder: ((r: any) => readonly AnyLeafLowProfile[]) | undefined\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined\n builder = maybeBuilder\n }\n\n const childBase = `${currentBase}/${name}` as const\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<\n I2,\n NonNullable<J>\n >\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(\n childBase,\n childInherited,\n currentParamsSchema,\n )\n const leaves = builder(child) //as readonly AnyLeafLowProfile[]\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >\n } else {\n currentBase = childBase\n inheritedCfg = childInherited\n return api as Branch<\n `${Base2}/${Name}`,\n readonly [],\n typeof childInherited,\n PS2\n >\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n MergedParamsResult<PS2, Name, P>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({\n [name]: paramsSchema,\n } as Record<Name, P>)\n const childParams = (\n currentParamsSchema\n ? mergeSchemas(currentParamsSchema, paramObj)\n : paramObj\n ) as MergedParamsResult<PS2, Name, P>\n const child = makeBranch(childBase, inheritedCfg as I2, childParams)\n const leaves = builder(child)\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n MergedParamsResult<PS2, Name, P>\n >\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg }\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg)\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false })\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false })\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false })\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false })\n },\n\n done() {\n return stack\n },\n }\n\n return api as Branch<Base2, readonly [], I2, PS2>\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined)\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S]\n}\n","import { z, ZodType } from 'zod'\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string\n /** Maximum number of files accepted for this field. */\n maxCount: number\n}\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean\n}\n\nexport type RouteSchema<Output = unknown> = ZodType & {\n __out: Output\n}\n\nexport type RouteSchemaOutput<Schema extends ZodType> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport const lowProfileParse = <T extends RouteSchema>(\n schema: T,\n data: unknown,\n): RouteSchemaOutput<T> => {\n return schema.parse(data) as RouteSchemaOutput<T>\n}\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodType\n /** Zod schema describing the query string. */\n querySchema?: ZodType\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodType\n /** Zod schema describing the response payload. */\n outputSchema?: ZodType\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[]\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean\n\n /** Optional human-readable description for docs/debugging. */\n description?: string\n /**\n * Short one-line summary for docs list views.\n * Shown in navigation / tables instead of the full description.\n */\n summary?: string\n /**\n * Group name used for navigation sections in docs UIs.\n * e.g. \"Users\", \"Billing\", \"Auth\".\n */\n docsGroup?: string\n /**\n * Tags that can be used to filter / facet in interactive docs.\n * e.g. [\"users\", \"admin\", \"internal\"].\n */\n tags?: string[]\n /**\n * Mark the route as deprecated in docs.\n * Renderers can badge this and/or hide by default.\n */\n deprecated?: boolean\n /**\n * Optional stability information for the route.\n * Renderers can surface this prominently.\n */\n stability?: 'experimental' | 'beta' | 'stable' | 'deprecated'\n /**\n * Hide this route from public docs while keeping it usable in code.\n */\n docsHidden?: boolean\n /**\n * Arbitrary extra metadata for docs renderers.\n * Can be used for auth requirements, rate limits, feature flags, etc.\n */\n docsMeta?: Record<string, unknown>\n}\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfg,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X]\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<\n A extends readonly unknown[],\n B extends readonly unknown[],\n> = [...A, ...B]\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S]\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never\n ? never\n : Record<ExtractParamNames<Path>, string | number>\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(\n path: Path,\n params: ExtractParamsFromPath<Path>,\n) {\n if (!params) return path\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k]\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`)\n return String(v)\n })\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P]\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L\n params?: ExtractParamsFromPath<L['path']>\n query?: InferQuery<L>\n}) {\n let p = args.leaf.path\n if (args.params) {\n p = compilePath<L['path']>(p, args.params)\n }\n return [\n args.leaf.method,\n ...(p.split('/').filter(Boolean) as SplitPath<typeof p>),\n args.query ?? {},\n ] as const\n}\n\n/** Definition-time method config (for clarity). */\nexport type MethodCfgDef = MethodCfg\n\n/** Low-profile method config where schemas carry a phantom __out like SocketSchema. */\nexport type MethodCfgLowProfile = Omit<\n MethodCfg,\n 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'\n> & {\n bodySchema?: RouteSchema\n querySchema?: RouteSchema\n paramsSchema?: RouteSchema\n outputSchema?: RouteSchema\n}\nexport type AnyLeafLowProfile = LeafLowProfile<\n HttpMethod,\n string,\n MethodCfgLowProfile\n>\n\nexport function buildLowProfileLeaf<T extends AnyLeaf>(leaf: T) {\n return {\n ...leaf,\n cfg: {\n ...leaf.cfg,\n bodySchema: leaf.cfg.bodySchema as RouteSchema<\n z.infer<typeof leaf.cfg.bodySchema>\n >,\n querySchema: leaf.cfg.querySchema as RouteSchema<\n z.infer<typeof leaf.cfg.querySchema>\n >,\n paramsSchema: leaf.cfg.paramsSchema as RouteSchema<\n z.infer<typeof leaf.cfg.paramsSchema>\n >,\n outputSchema: leaf.cfg.outputSchema as RouteSchema<\n z.infer<typeof leaf.cfg.outputSchema>\n >,\n },\n }\n}\n\nexport type LeafLowProfile<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfgLowProfile,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeafLowProfile> =\n L['cfg']['paramsSchema'] extends RouteSchema<infer P> ? P : undefined\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> =\n L['cfg']['querySchema'] extends RouteSchema<infer Q> ? Q : undefined\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> =\n L['cfg']['bodySchema'] extends RouteSchema<infer B> ? B : undefined\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> =\n L['cfg']['outputSchema'] extends RouteSchema<infer O> ? O : undefined\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {}\n","// TODO:\n// * use this as a transform that infers the types from Zod, to only pass the types around instead of the full schemas -> make converters that go both ways (data to schema, schema to data)\n// * consider moving to core package\n// * update server and client side to use this type instead of raw zod schemas\nimport { AnyLeafLowProfile, HttpMethod, Prettify } from './routesV3.core'\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeafLowProfile> = L extends AnyLeafLowProfile\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeafLowProfile[]> = KeyOf<Leaves[number]>\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}`\n ? Lowercase<M>\n : never\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}`\n ? P\n : never\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<\n Leaves extends readonly AnyLeafLowProfile[],\n K extends string,\n> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeafLowProfile[]>(\n leaves: L,\n) {\n type Keys = KeysOf<L>\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> }\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:')\n ;(Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k]\n logger.system(`- ${k}`)\n })\n }\n\n return { all: leaves, byKey, log }\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R\n\ntype FilterRoute<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n Acc extends readonly AnyLeafLowProfile[] = [],\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S\n\ntype Routes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = FilterRoute<T, F>\ntype ByKey<\n T extends readonly AnyLeafLowProfile[],\n Acc extends Record<string, AnyLeafLowProfile> = {},\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? ByKey<\n Rest,\n Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }\n >\n : Acc\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = {\n byKey: ByKey<Routes<T, F>>\n all: Routes<T, F>\n}\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod'\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder'\nimport {\n AnyLeafLowProfile,\n MethodCfg,\n NodeCfg,\n RouteSchema, // ← add\n RouteSchemaOutput,\n type AnyLeaf,\n type Leaf,\n} from '../core/routesV3.core'\n\n/** Convert a raw ZodType to a low-profile RouteSchema. */\ntype ToRouteSchema<S> = S extends ZodType\n ? RouteSchema<RouteSchemaOutput<S>>\n : S\n\n/**\n * Map over a cfg object and turn any schema fields into RouteSchema.\n * We only touch the standard schema keys.\n */\ntype WithRouteSchemas<Cfg extends MethodCfg> = {\n [K in keyof Cfg]: K extends\n | 'bodySchema'\n | 'querySchema'\n | 'paramsSchema'\n | 'outputSchema'\n ? ToRouteSchema<Cfg[K]>\n : Cfg[K]\n}\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nconst crudPaginationShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nexport const CrudDefaultPagination = z.object(crudPaginationShape)\ntype CrudPaginationShape = typeof crudPaginationShape\ntype AnyCrudZodObject = z.ZodObject<any>\ntype AddCrudPagination<Q extends AnyCrudZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & CrudPaginationShape>\n : z.ZodObject<CrudPaginationShape>\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<\n A extends ZodType | undefined,\n B extends ZodType | undefined,\n>(\n a: A,\n b: B,\n): A extends ZodType\n ? B extends ZodType\n ? ReturnType<typeof z.intersection<A, B>>\n : A\n : B {\n if (a && b) return z.intersection(a as any, b as any) as any\n return (a ?? b) as any\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S\n}>\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType\n ? Omit<I, 'paramsSchema'> & { paramsSchema: P }\n : I\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean\n /** GET /collection/:id. Defaults to true. */ read?: boolean\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean\n}\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType\n /** Optional description string. */\n description?: string\n}\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable\n\n /** GET /collection configuration. */ list?: CrudListCfg\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg\n /** GET /collection/:id configuration. */ read?: CrudReadCfg\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg\n}\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n feed: true\n querySchema: C['list'] extends CrudListCfg\n ? AddCrudPagination<\n C['list']['querySchema'] extends AnyCrudZodObject\n ? C['list']['querySchema']\n : undefined\n >\n : AddCrudPagination<undefined>\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['create']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema']\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['update']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n ]\n : never\n : never\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras]\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<\n typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>\n >\n >\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any\n if (typeof b.crud === 'function') return branch\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n this: any,\n name: Name,\n cfg: C,\n extras?: (ctx: { collection: any; item: any }) => Extras,\n ) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function'\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey]\n ? ((s as any).shape()[idKey] as ZodType)\n : (s as ZodType)\n\n const itemOut = cfg.itemOutputSchema\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n })\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n })\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n })\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(\n idKey as any,\n paramValueSchema as any,\n (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n })\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n })\n }\n if (want.remove) {\n item.delete({\n outputSchema:\n cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n })\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras)\n extras({ collection: withCrud(collection), item: withCrud(item) })\n\n return item.done()\n },\n )\n\n return collection.done()\n })\n }\n\n return branch\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited))\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource }\n","// socket.index.ts (shared client/server)\n\nimport { z } from 'zod'\n\nexport type SocketSchema<Output = unknown> = z.ZodType & {\n __out: Output\n}\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out\n}\n\nexport type EventMap = Record<string, SocketEvent<any>>\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName =\n | 'sys:connect'\n | 'sys:disconnect'\n | 'sys:reconnect'\n | 'sys:connect_error'\n | 'sys:ping'\n | 'sys:pong'\n | 'sys:room_join'\n | 'sys:room_leave'\nexport function defineSocketEvents<\n const C extends SocketConnectionConfig,\n const Schemas extends Record<\n string,\n {\n message: z.ZodTypeAny\n }\n >,\n>(\n config: C,\n events: Schemas,\n): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>\n }\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>\n }\n}\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events }\n}\n\nexport type Payload<\n T extends EventMap,\n K extends keyof T,\n> = T[K] extends SocketEvent<infer Out> ? Out : never\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny\n leaveMetaMessage: z.ZodTypeAny\n pingPayload: z.ZodTypeAny\n pongPayload: z.ZodTypeAny\n}\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>\n leaveMetaMessage: SocketSchema<any>\n pingPayload: SocketSchema<any>\n pongPayload: SocketSchema<any>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAelB,IAAM,uBAAuB;AAAA,EAC3B,mBAAmB,aAAE,OAAO,EAAE,SAAS;AAAA,EACvC,kBAAkB,aAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAChE;AAEA,IAAM,yBAAyB,aAAE,OAAO,oBAAoB;AAkB5D,SAAS,YAAY,QAAsB;AACzC,QAAM,gBAAiB,OAAe,QACjC,OAAe,QACf,OAAe,MAAM,QAAQ;AAClC,MAAI,CAAC,cAAe,QAAO,CAAC;AAC5B,SAAO,OAAO,kBAAkB,aAC5B,cAAc,KAAK,MAAM,IACzB;AACN;AAEA,SAAS,8BACP,OACA,SAAmB,CAAC,GACV;AACV,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,QAAM,cAAwB,CAAC;AAC/B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,iBAAiB,aAAE,WAAW;AAChC,YAAM,cAAc,YAAY,KAAqB;AACrD,YAAM,oBAAoB,8BAA8B,aAAa;AAAA,QACnE,GAAG;AAAA,QACH;AAAA,MACF,CAAC;AACD,kBAAY;AAAA,QACV,GAAI,kBAAkB,SAClB,oBACA,CAAC,CAAC,GAAG,QAAQ,GAAG,EAAE,KAAK,GAAG,CAAC;AAAA,MACjC;AAAA,IACF,WAAW,OAAO,SAAS,GAAG;AAC5B,kBAAY,KAAK,CAAC,GAA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Q,eAAe;AAAA,YAC1C,CAAC;AAAA,UACH;AAGA,cAAI;AACF,mBAAO,EAAE,YAAY,SAAS,UAAU,GAAG,MAAM,SAAS,IAAI,EAAE,CAAC;AAEnE,iBAAO,KAAK,KAAK;AAAA,QACnB;AAAA,MACF;AAEA,aAAO,WAAW,KAAK;AAAA,IACzB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAaO,SAAS,iBACd,MACA,WACA;AACA,SAAO,SAAS,SAAa,MAAM,SAAS,CAAC;AAC/C;;;AC1fO,SAAS,mBAAmB,QAAa,QAAa;AAC3D,SAAO,EAAE,QAAQ,OAAO;AAC1B;","names":["mergeSchemas","import_zod","mergeSchemas"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts"],"sourcesContent":["export * from './core/routesV3.builder'\nexport * from './core/routesV3.core'\nexport * from './core/routesV3.finalize'\nexport * from './crud/routesV3.crud'\nexport * from './sockets/socket.index'\n","import { z } from 'zod'\nimport {\n AnyLeaf,\n AnyLeafLowProfile,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n RouteSchema,\n} from './routesV3.core'\n\nconst paginationQueryShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nconst defaultFeedQuerySchema = z.object(paginationQueryShape)\ntype PaginationShape = typeof paginationQueryShape\n\ntype ZodTypeAny = z.ZodTypeAny\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{\n [K in Name]: S\n}>\ntype ZodArrayAny = z.ZodArray<ZodTypeAny>\ntype ZodObjectAny = z.ZodObject<any>\ntype AnyZodObject = z.ZodObject<any>\ntype MergedParamsResult<\n PS,\n Name extends string,\n P extends ZodTypeAny,\n> = PS extends ZodTypeAny\n ? z.ZodIntersection<PS, ParamZod<Name, P>>\n : ParamZod<Name, P>\n\nfunction getZodShape(schema: ZodObjectAny) {\n const shapeOrGetter = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n if (!shapeOrGetter) return {}\n return typeof shapeOrGetter === 'function'\n ? shapeOrGetter.call(schema)\n : shapeOrGetter\n}\n\nfunction collectNestedFieldSuggestions(\n shape: Record<string, ZodTypeAny> | undefined,\n prefix: string[] = [],\n): string[] {\n if (!shape) return []\n const suggestions: string[] = []\n for (const [key, value] of Object.entries(shape)) {\n if (value instanceof z.ZodObject) {\n const nestedShape = getZodShape(value as ZodObjectAny)\n const nestedSuggestions = collectNestedFieldSuggestions(nestedShape, [\n ...prefix,\n key,\n ])\n suggestions.push(\n ...(nestedSuggestions.length\n ? nestedSuggestions\n : [[...prefix, key].join('_')]),\n )\n } else if (prefix.length > 0) {\n suggestions.push([...prefix, key].join('_'))\n }\n }\n return suggestions\n}\n\nconst defaultFeedOutputSchema = z.object({\n items: z.array(z.unknown()),\n nextCursor: z.string().optional(),\n})\n\nfunction augmentFeedQuerySchema<Q extends ZodTypeAny | undefined>(schema: Q) {\n if (schema && !(schema instanceof z.ZodObject)) {\n console.warn(\n 'Feed queries must be a ZodObject; default pagination applied.',\n )\n return defaultFeedQuerySchema\n }\n\n const base = (schema as ZodObjectAny) ?? z.object({})\n const shape = getZodShape(base)\n const nestedSuggestions = collectNestedFieldSuggestions(shape)\n if (nestedSuggestions.length) {\n console.warn(\n `Feed query schemas should avoid nested objects; consider flattening fields like: ${nestedSuggestions.join(\n ', ',\n )}`,\n )\n }\n return base.extend(paginationQueryShape)\n}\n\nfunction augmentFeedOutputSchema<O extends ZodTypeAny | undefined>(schema: O) {\n if (!schema) return defaultFeedOutputSchema\n if (schema instanceof z.ZodArray) {\n return z.object({\n items: schema,\n nextCursor: z.string().optional(),\n })\n }\n if (schema instanceof z.ZodObject) {\n const shape = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n const hasItems = Boolean(shape?.items)\n if (hasItems) {\n return schema.extend({ nextCursor: z.string().optional() })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n}\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny, B extends ZodTypeAny>(\n a: A,\n b: B,\n): ZodTypeAny\nfunction mergeSchemas<A extends ZodTypeAny>(a: A, b: undefined): A\nfunction mergeSchemas<B extends ZodTypeAny>(a: undefined, b: B): B\nfunction mergeSchemas(\n a: ZodTypeAny | undefined,\n b: ZodTypeAny | undefined,\n): ZodTypeAny | undefined\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined) {\n if (a && b) return z.intersection(a as any, b as any)\n return (a ?? b) as ZodTypeAny | undefined\n}\n\ntype FeedQuerySchema<C extends MethodCfg> = z.ZodObject<any>\n\ntype FeedOutputSchema<C extends MethodCfg> =\n C['outputSchema'] extends ZodArrayAny\n ? z.ZodObject<{\n items: C['outputSchema']\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : C['outputSchema'] extends ZodTypeAny\n ? z.ZodObject<{\n items: z.ZodArray<C['outputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : typeof defaultFeedOutputSchema\n\ntype BaseMethodCfg<C extends MethodCfg> = Merge<\n Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>,\n Omit<C, 'querySchema' | 'outputSchema' | 'feed'>\n>\n\ntype FeedField<C extends MethodCfg> = C['feed'] extends true\n ? { feed: true }\n : { feed?: boolean }\n\ntype AddPaginationToQuery<Q extends AnyZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & PaginationShape>\n : z.ZodObject<PaginationShape>\n\ntype FeedQueryField<C extends MethodCfg> = {\n querySchema: AddPaginationToQuery<\n C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined\n >\n}\n\ntype NonFeedQueryField<C extends MethodCfg> =\n C['querySchema'] extends ZodTypeAny\n ? { querySchema: C['querySchema'] }\n : { querySchema?: undefined }\n\ntype FeedOutputField<C extends MethodCfg> = {\n outputSchema: FeedOutputSchema<C>\n}\n\ntype NonFeedOutputField<C extends MethodCfg> =\n C['outputSchema'] extends ZodTypeAny\n ? { outputSchema: C['outputSchema'] }\n : { outputSchema?: undefined }\n\ntype ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny\n ? { paramsSchema: C['paramsSchema'] }\n : { paramsSchema: PS }\n\ntype EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true\n ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS>\n : FeedField<C> &\n NonFeedQueryField<C> &\n NonFeedOutputField<C> &\n ParamsField<C, PS>\n\ntype EffectiveCfg<C extends MethodCfg, PS> = Prettify<\n Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>\n>\n\ntype ToRouteSchema<S> = S extends ZodTypeAny ? RouteSchema<z.output<S>> : S\n\ntype LowProfileCfg<Cfg extends MethodCfg> = Prettify<\n Omit<Cfg, 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'> & {\n bodySchema: ToRouteSchema<Cfg['bodySchema']>\n querySchema: ToRouteSchema<Cfg['querySchema']>\n paramsSchema: ToRouteSchema<Cfg['paramsSchema']>\n outputSchema: ToRouteSchema<Cfg['outputSchema']>\n }\n>\n\ntype BuiltLeaf<\n M extends HttpMethod,\n Base extends string,\n I extends NodeCfg,\n C extends MethodCfg,\n PS,\n> = Leaf<M, Base, Merge<I, LowProfileCfg<EffectiveCfg<C, PS>>>>\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>\n\n sub<\n Name extends string,\n J extends NodeCfg | undefined,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n cfg: J,\n builder: (\n r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>,\n ) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>\n\n sub<Name extends string, R extends readonly AnyLeafLowProfile[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n MergedParamsResult<PS, Name, P>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends MethodCfg>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>,\n I,\n PS\n >\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'post', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'put', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'patch', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'delete', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) }\n\n function makeBranch<\n Base2 extends string,\n I2 extends NodeCfg,\n PS2 extends ZodTypeAny | undefined,\n >(base2: Base2, inherited2: I2, mergedParamsSchema?: PS2) {\n const stack: AnyLeaf[] = []\n let currentBase: string = base2\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) }\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ??\n currentParamsSchema) as PS2 | undefined\n const effectiveQuerySchema =\n cfg.feed === true\n ? augmentFeedQuerySchema(cfg.querySchema)\n : cfg.querySchema\n const effectiveOutputSchema =\n cfg.feed === true\n ? augmentFeedOutputSchema(cfg.outputSchema)\n : cfg.outputSchema\n\n const fullCfg = (\n effectiveParamsSchema\n ? {\n ...inheritedCfg,\n ...cfg,\n paramsSchema: effectiveParamsSchema,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n : {\n ...inheritedCfg,\n ...cfg,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n ) as any\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const\n\n stack.push(leaf as unknown as AnyLeaf)\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<\n Base2,\n Append<readonly [], typeof leaf>,\n I2,\n PS2\n >\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeafLowProfile[]),\n maybeBuilder?: (r: any) => readonly AnyLeafLowProfile[],\n ) {\n let cfg: NodeCfg | undefined\n let builder: ((r: any) => readonly AnyLeafLowProfile[]) | undefined\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined\n builder = maybeBuilder\n }\n\n const childBase = `${currentBase}/${name}` as const\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<\n I2,\n NonNullable<J>\n >\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(\n childBase,\n childInherited,\n currentParamsSchema,\n )\n const leaves = builder(child) //as readonly AnyLeafLowProfile[]\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >\n } else {\n currentBase = childBase\n inheritedCfg = childInherited\n return api as Branch<\n `${Base2}/${Name}`,\n readonly [],\n typeof childInherited,\n PS2\n >\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n MergedParamsResult<PS2, Name, P>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({\n [name]: paramsSchema,\n } as Record<Name, P>)\n const childParams = (\n currentParamsSchema\n ? mergeSchemas(currentParamsSchema, paramObj)\n : paramObj\n ) as MergedParamsResult<PS2, Name, P>\n const child = makeBranch(childBase, inheritedCfg as I2, childParams)\n const leaves = builder(child)\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n MergedParamsResult<PS2, Name, P>\n >\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg }\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg)\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false })\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false })\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false })\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false })\n },\n\n done() {\n return stack\n },\n }\n\n return api as Branch<Base2, readonly [], I2, PS2>\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined)\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S]\n}\n","import { z, ZodType } from 'zod'\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string\n /** Maximum number of files accepted for this field. */\n maxCount: number\n}\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean\n}\n\nexport type RouteSchema<Output = unknown> = ZodType & {\n __out: Output\n}\n\nexport type RouteSchemaOutput<Schema extends ZodType> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport const lowProfileParse = <T extends RouteSchema>(\n schema: T,\n data: unknown,\n): RouteSchemaOutput<T> => {\n return schema.parse(data) as RouteSchemaOutput<T>\n}\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodType\n /** Zod schema describing the query string. */\n querySchema?: ZodType\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodType\n /** Zod schema describing the response payload. */\n outputSchema?: ZodType\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[]\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean\n\n /** Optional human-readable description for docs/debugging. */\n description?: string\n /**\n * Short one-line summary for docs list views.\n * Shown in navigation / tables instead of the full description.\n */\n summary?: string\n /**\n * Group name used for navigation sections in docs UIs.\n * e.g. \"Users\", \"Billing\", \"Auth\".\n */\n docsGroup?: string\n /**\n * Tags that can be used to filter / facet in interactive docs.\n * e.g. [\"users\", \"admin\", \"internal\"].\n */\n tags?: string[]\n /**\n * Mark the route as deprecated in docs.\n * Renderers can badge this and/or hide by default.\n */\n deprecated?: boolean\n /**\n * Optional stability information for the route.\n * Renderers can surface this prominently.\n */\n stability?: 'experimental' | 'beta' | 'stable' | 'deprecated'\n /**\n * Hide this route from public docs while keeping it usable in code.\n */\n docsHidden?: boolean\n /**\n * Arbitrary extra metadata for docs renderers.\n * Can be used for auth requirements, rate limits, feature flags, etc.\n */\n docsMeta?: Record<string, unknown>\n}\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfg,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X]\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<\n A extends readonly unknown[],\n B extends readonly unknown[],\n> = [...A, ...B]\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S]\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never\n ? never\n : Record<ExtractParamNames<Path>, string | number>\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(\n path: Path,\n params: ExtractParamsFromPath<Path>,\n) {\n if (!params) return path\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k]\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`)\n return String(v)\n })\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P]\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L\n params?: ExtractParamsFromPath<L['path']>\n query?: InferQuery<L>\n}) {\n let p = args.leaf.path\n if (args.params) {\n p = compilePath<L['path']>(p, args.params)\n }\n return [\n args.leaf.method,\n ...(p.split('/').filter(Boolean) as SplitPath<typeof p>),\n args.query ?? {},\n ] as const\n}\n\n/** Definition-time method config (for clarity). */\nexport type MethodCfgDef = MethodCfg\n\n/** Low-profile method config where schemas carry a phantom __out like SocketSchema. */\nexport type MethodCfgLowProfile = Omit<\n MethodCfg,\n 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'\n> & {\n bodySchema?: RouteSchema\n querySchema?: RouteSchema\n paramsSchema?: RouteSchema\n outputSchema?: RouteSchema\n}\nexport type AnyLeafLowProfile = LeafLowProfile<\n HttpMethod,\n string,\n MethodCfgLowProfile\n>\n\nexport function buildLowProfileLeaf<L extends AnyLeaf>(\n leaf: L,\n): LeafLowProfile<\n L['method'],\n L['path'],\n {\n [K in keyof L['cfg']]: K extends\n | 'bodySchema'\n | 'querySchema'\n | 'paramsSchema'\n | 'outputSchema'\n ? RouteSchema<z.infer<L['cfg'][K]>>\n : L['cfg'][K]\n }\n>\nexport function buildLowProfileLeaf(leaf: any): any {\n return {\n ...leaf,\n cfg: {\n ...leaf.cfg,\n bodySchema: leaf.cfg.bodySchema as RouteSchema<\n z.infer<typeof leaf.cfg.bodySchema>\n >,\n querySchema: leaf.cfg.querySchema as RouteSchema<\n z.infer<typeof leaf.cfg.querySchema>\n >,\n paramsSchema: leaf.cfg.paramsSchema as RouteSchema<\n z.infer<typeof leaf.cfg.paramsSchema>\n >,\n outputSchema: leaf.cfg.outputSchema as RouteSchema<\n z.infer<typeof leaf.cfg.outputSchema>\n >,\n },\n }\n}\n\nexport type LeafLowProfile<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfgLowProfile,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeafLowProfile> =\n L['cfg']['paramsSchema'] extends RouteSchema<infer P> ? P : undefined\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> =\n L['cfg']['querySchema'] extends RouteSchema<infer Q> ? Q : undefined\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> =\n L['cfg']['bodySchema'] extends RouteSchema<infer B> ? B : undefined\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> =\n L['cfg']['outputSchema'] extends RouteSchema<infer O> ? O : undefined\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {}\n","// TODO:\n// * use this as a transform that infers the types from Zod, to only pass the types around instead of the full schemas -> make converters that go both ways (data to schema, schema to data)\n// * consider moving to core package\n// * update server and client side to use this type instead of raw zod schemas\nimport { AnyLeafLowProfile, HttpMethod, Prettify } from './routesV3.core'\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeafLowProfile> = L extends AnyLeafLowProfile\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeafLowProfile[]> = KeyOf<Leaves[number]>\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}`\n ? Lowercase<M>\n : never\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}`\n ? P\n : never\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<\n Leaves extends readonly AnyLeafLowProfile[],\n K extends string,\n> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeafLowProfile[]>(\n leaves: L,\n) {\n type Keys = KeysOf<L>\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> }\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:')\n ;(Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k]\n logger.system(`- ${k}`)\n })\n }\n\n return { all: leaves, byKey, log }\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R\n\ntype FilterRoute<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n Acc extends readonly AnyLeafLowProfile[] = [],\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S\n\ntype Routes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = FilterRoute<T, F>\ntype ByKey<\n T extends readonly AnyLeafLowProfile[],\n Acc extends Record<string, AnyLeafLowProfile> = {},\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? ByKey<\n Rest,\n Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }\n >\n : Acc\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = {\n byKey: ByKey<Routes<T, F>>\n all: Routes<T, F>\n}\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod'\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder'\nimport {\n AnyLeafLowProfile,\n MethodCfg,\n NodeCfg,\n RouteSchema, // ← add\n RouteSchemaOutput,\n type AnyLeaf,\n type Leaf,\n} from '../core/routesV3.core'\n\n/** Convert a raw ZodType to a low-profile RouteSchema. */\ntype ToRouteSchema<S> = S extends ZodType\n ? RouteSchema<RouteSchemaOutput<S>>\n : S\n\n/**\n * Map over a cfg object and turn any schema fields into RouteSchema.\n * We only touch the standard schema keys.\n */\ntype WithRouteSchemas<Cfg extends MethodCfg> = {\n [K in keyof Cfg]: K extends\n | 'bodySchema'\n | 'querySchema'\n | 'paramsSchema'\n | 'outputSchema'\n ? ToRouteSchema<Cfg[K]>\n : Cfg[K]\n}\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nconst crudPaginationShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nexport const CrudDefaultPagination = z.object(crudPaginationShape)\ntype CrudPaginationShape = typeof crudPaginationShape\ntype AnyCrudZodObject = z.ZodObject<any>\ntype AddCrudPagination<Q extends AnyCrudZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & CrudPaginationShape>\n : z.ZodObject<CrudPaginationShape>\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<\n A extends ZodType | undefined,\n B extends ZodType | undefined,\n>(\n a: A,\n b: B,\n): A extends ZodType\n ? B extends ZodType\n ? ReturnType<typeof z.intersection<A, B>>\n : A\n : B {\n if (a && b) return z.intersection(a as any, b as any) as any\n return (a ?? b) as any\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S\n}>\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType\n ? Omit<I, 'paramsSchema'> & { paramsSchema: P }\n : I\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean\n /** GET /collection/:id. Defaults to true. */ read?: boolean\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean\n}\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType\n /** Optional description string. */\n description?: string\n}\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable\n\n /** GET /collection configuration. */ list?: CrudListCfg\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg\n /** GET /collection/:id configuration. */ read?: CrudReadCfg\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg\n}\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n feed: true\n querySchema: C['list'] extends CrudListCfg\n ? AddCrudPagination<\n C['list']['querySchema'] extends AnyCrudZodObject\n ? C['list']['querySchema']\n : undefined\n >\n : AddCrudPagination<undefined>\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['create']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema']\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['update']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n ]\n : never\n : never\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras]\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<\n typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>\n >\n >\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any\n if (typeof b.crud === 'function') return branch\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n this: any,\n name: Name,\n cfg: C,\n extras?: (ctx: { collection: any; item: any }) => Extras,\n ) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function'\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey]\n ? ((s as any).shape()[idKey] as ZodType)\n : (s as ZodType)\n\n const itemOut = cfg.itemOutputSchema\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n })\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n })\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n })\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(\n idKey as any,\n paramValueSchema as any,\n (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n })\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n })\n }\n if (want.remove) {\n item.delete({\n outputSchema:\n cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n })\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras)\n extras({ collection: withCrud(collection), item: withCrud(item) })\n\n return item.done()\n },\n )\n\n return collection.done()\n })\n }\n\n return branch\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited))\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource }\n","// socket.index.ts (shared client/server)\n\nimport { z } from 'zod'\n\nexport type SocketSchema<Output = unknown> = z.ZodType & {\n __out: Output\n}\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out\n}\n\nexport type EventMap = Record<string, SocketEvent<any>>\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName =\n | 'sys:connect'\n | 'sys:disconnect'\n | 'sys:reconnect'\n | 'sys:connect_error'\n | 'sys:ping'\n | 'sys:pong'\n | 'sys:room_join'\n | 'sys:room_leave'\nexport function defineSocketEvents<\n const C extends SocketConnectionConfig,\n const Schemas extends Record<\n string,\n {\n message: z.ZodTypeAny\n }\n >,\n>(\n config: C,\n events: Schemas,\n): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>\n }\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>\n }\n}\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events }\n}\n\nexport type Payload<\n T extends EventMap,\n K extends keyof T,\n> = T[K] extends SocketEvent<infer Out> ? Out : never\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny\n leaveMetaMessage: z.ZodTypeAny\n pingPayload: z.ZodTypeAny\n pongPayload: z.ZodTypeAny\n}\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>\n leaveMetaMessage: SocketSchema<any>\n pingPayload: SocketSchema<any>\n pongPayload: SocketSchema<any>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAelB,IAAM,uBAAuB;AAAA,EAC3B,mBAAmB,aAAE,OAAO,EAAE,SAAS;AAAA,EACv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emas"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n AnyLeaf,\n AnyLeafLowProfile,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n RouteSchema,\n} from './routesV3.core'\n\nconst paginationQueryShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nconst defaultFeedQuerySchema = z.object(paginationQueryShape)\ntype PaginationShape = typeof paginationQueryShape\n\ntype ZodTypeAny = z.ZodTypeAny\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{\n [K in Name]: S\n}>\ntype ZodArrayAny = z.ZodArray<ZodTypeAny>\ntype ZodObjectAny = z.ZodObject<any>\ntype AnyZodObject = z.ZodObject<any>\ntype MergedParamsResult<\n PS,\n Name extends string,\n P extends ZodTypeAny,\n> = PS extends ZodTypeAny\n ? z.ZodIntersection<PS, ParamZod<Name, P>>\n : ParamZod<Name, P>\n\nfunction getZodShape(schema: ZodObjectAny) {\n const shapeOrGetter = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n if (!shapeOrGetter) return {}\n return typeof shapeOrGetter === 'function'\n ? shapeOrGetter.call(schema)\n : shapeOrGetter\n}\n\nfunction collectNestedFieldSuggestions(\n shape: Record<string, ZodTypeAny> | undefined,\n prefix: string[] = [],\n): string[] {\n if (!shape) return []\n const suggestions: string[] = []\n for (const [key, value] of Object.entries(shape)) {\n if (value instanceof z.ZodObject) {\n const nestedShape = getZodShape(value as ZodObjectAny)\n const nestedSuggestions = collectNestedFieldSuggestions(nestedShape, [\n ...prefix,\n key,\n ])\n suggestions.push(\n ...(nestedSuggestions.length\n ? nestedSuggestions\n : [[...prefix, key].join('_')]),\n )\n } else if (prefix.length > 0) {\n suggestions.push([...prefix, key].join('_'))\n }\n }\n return suggestions\n}\n\nconst defaultFeedOutputSchema = z.object({\n items: z.array(z.unknown()),\n nextCursor: z.string().optional(),\n})\n\nfunction augmentFeedQuerySchema<Q extends ZodTypeAny | undefined>(schema: Q) {\n if (schema && !(schema instanceof z.ZodObject)) {\n console.warn(\n 'Feed queries must be a ZodObject; default pagination applied.',\n )\n return defaultFeedQuerySchema\n }\n\n const base = (schema as ZodObjectAny) ?? z.object({})\n const shape = getZodShape(base)\n const nestedSuggestions = collectNestedFieldSuggestions(shape)\n if (nestedSuggestions.length) {\n console.warn(\n `Feed query schemas should avoid nested objects; consider flattening fields like: ${nestedSuggestions.join(\n ', ',\n )}`,\n )\n }\n return base.extend(paginationQueryShape)\n}\n\nfunction augmentFeedOutputSchema<O extends ZodTypeAny | undefined>(schema: O) {\n if (!schema) return defaultFeedOutputSchema\n if (schema instanceof z.ZodArray) {\n return z.object({\n items: schema,\n nextCursor: z.string().optional(),\n })\n }\n if (schema instanceof z.ZodObject) {\n const shape = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n const hasItems = Boolean(shape?.items)\n if (hasItems) {\n return schema.extend({ nextCursor: z.string().optional() })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n}\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny, B extends ZodTypeAny>(\n a: A,\n b: B,\n): ZodTypeAny\nfunction mergeSchemas<A extends ZodTypeAny>(a: A, b: undefined): A\nfunction mergeSchemas<B extends ZodTypeAny>(a: undefined, b: B): B\nfunction mergeSchemas(\n a: ZodTypeAny | undefined,\n b: ZodTypeAny | undefined,\n): ZodTypeAny | undefined\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined) {\n if (a && b) return z.intersection(a as any, b as any)\n return (a ?? b) as ZodTypeAny | undefined\n}\n\ntype FeedQuerySchema<C extends MethodCfg> = z.ZodObject<any>\n\ntype FeedOutputSchema<C extends MethodCfg> =\n C['outputSchema'] extends ZodArrayAny\n ? z.ZodObject<{\n items: C['outputSchema']\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : C['outputSchema'] extends ZodTypeAny\n ? z.ZodObject<{\n items: z.ZodArray<C['outputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : typeof defaultFeedOutputSchema\n\ntype BaseMethodCfg<C extends MethodCfg> = Merge<\n Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>,\n Omit<C, 'querySchema' | 'outputSchema' | 'feed'>\n>\n\ntype FeedField<C extends MethodCfg> = C['feed'] extends true\n ? { feed: true }\n : { feed?: boolean }\n\ntype AddPaginationToQuery<Q extends AnyZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & PaginationShape>\n : z.ZodObject<PaginationShape>\n\ntype FeedQueryField<C extends MethodCfg> = {\n querySchema: AddPaginationToQuery<\n C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined\n >\n}\n\ntype NonFeedQueryField<C extends MethodCfg> =\n C['querySchema'] extends ZodTypeAny\n ? { querySchema: C['querySchema'] }\n : { querySchema?: undefined }\n\ntype FeedOutputField<C extends MethodCfg> = {\n outputSchema: FeedOutputSchema<C>\n}\n\ntype NonFeedOutputField<C extends MethodCfg> =\n C['outputSchema'] extends ZodTypeAny\n ? { outputSchema: C['outputSchema'] }\n : { outputSchema?: undefined }\n\ntype ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny\n ? { paramsSchema: C['paramsSchema'] }\n : { paramsSchema: PS }\n\ntype EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true\n ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS>\n : FeedField<C> &\n NonFeedQueryField<C> &\n NonFeedOutputField<C> &\n ParamsField<C, PS>\n\ntype EffectiveCfg<C extends MethodCfg, PS> = Prettify<\n Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>\n>\n\ntype ToRouteSchema<S> = S extends ZodTypeAny ? RouteSchema<z.output<S>> : S\n\ntype LowProfileCfg<Cfg extends MethodCfg> = Prettify<\n Omit<Cfg, 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'> & {\n bodySchema: ToRouteSchema<Cfg['bodySchema']>\n querySchema: ToRouteSchema<Cfg['querySchema']>\n paramsSchema: ToRouteSchema<Cfg['paramsSchema']>\n outputSchema: ToRouteSchema<Cfg['outputSchema']>\n }\n>\n\ntype BuiltLeaf<\n M extends HttpMethod,\n Base extends string,\n I extends NodeCfg,\n C extends MethodCfg,\n PS,\n> = Leaf<M, Base, Merge<I, LowProfileCfg<EffectiveCfg<C, PS>>>>\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>\n\n sub<\n Name extends string,\n J extends NodeCfg | undefined,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n cfg: J,\n builder: (\n r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>,\n ) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>\n\n sub<Name extends string, R extends readonly AnyLeafLowProfile[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n MergedParamsResult<PS, Name, P>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends MethodCfg>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>,\n I,\n PS\n >\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'post', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'put', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'patch', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'delete', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) }\n\n function makeBranch<\n Base2 extends string,\n I2 extends NodeCfg,\n PS2 extends ZodTypeAny | undefined,\n >(base2: Base2, inherited2: I2, mergedParamsSchema?: PS2) {\n const stack: AnyLeaf[] = []\n let currentBase: string = base2\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) }\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ??\n currentParamsSchema) as PS2 | undefined\n const effectiveQuerySchema =\n cfg.feed === true\n ? augmentFeedQuerySchema(cfg.querySchema)\n : cfg.querySchema\n const effectiveOutputSchema =\n cfg.feed === true\n ? augmentFeedOutputSchema(cfg.outputSchema)\n : cfg.outputSchema\n\n const fullCfg = (\n effectiveParamsSchema\n ? {\n ...inheritedCfg,\n ...cfg,\n paramsSchema: effectiveParamsSchema,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n : {\n ...inheritedCfg,\n ...cfg,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n ) as any\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const\n\n stack.push(leaf as unknown as AnyLeaf)\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<\n Base2,\n Append<readonly [], typeof leaf>,\n I2,\n PS2\n >\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeafLowProfile[]),\n maybeBuilder?: (r: any) => readonly AnyLeafLowProfile[],\n ) {\n let cfg: NodeCfg | undefined\n let builder: ((r: any) => readonly AnyLeafLowProfile[]) | undefined\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined\n builder = maybeBuilder\n }\n\n const childBase = `${currentBase}/${name}` as const\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<\n I2,\n NonNullable<J>\n >\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(\n childBase,\n childInherited,\n currentParamsSchema,\n )\n const leaves = builder(child) //as readonly AnyLeafLowProfile[]\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >\n } else {\n currentBase = childBase\n inheritedCfg = childInherited\n return api as Branch<\n `${Base2}/${Name}`,\n readonly [],\n typeof childInherited,\n PS2\n >\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n MergedParamsResult<PS2, Name, P>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({\n [name]: paramsSchema,\n } as Record<Name, P>)\n const childParams = (\n currentParamsSchema\n ? mergeSchemas(currentParamsSchema, paramObj)\n : paramObj\n ) as MergedParamsResult<PS2, Name, P>\n const child = makeBranch(childBase, inheritedCfg as I2, childParams)\n const leaves = builder(child)\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n MergedParamsResult<PS2, Name, P>\n >\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg }\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg)\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false })\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false })\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false })\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false })\n },\n\n done() {\n return stack\n },\n }\n\n return api as Branch<Base2, readonly [], I2, PS2>\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined)\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S]\n}\n","import { z, ZodType } from 'zod'\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string\n /** Maximum number of files accepted for this field. */\n maxCount: number\n}\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean\n}\n\nexport type RouteSchema<Output = unknown> = ZodType & {\n __out: Output\n}\n\nexport type RouteSchemaOutput<Schema extends ZodType> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport const lowProfileParse = <T extends RouteSchema>(\n schema: T,\n data: unknown,\n): RouteSchemaOutput<T> => {\n return schema.parse(data) as RouteSchemaOutput<T>\n}\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodType\n /** Zod schema describing the query string. */\n querySchema?: ZodType\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodType\n /** Zod schema describing the response payload. */\n outputSchema?: ZodType\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[]\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean\n\n /** Optional human-readable description for docs/debugging. */\n description?: string\n /**\n * Short one-line summary for docs list views.\n * Shown in navigation / tables instead of the full description.\n */\n summary?: string\n /**\n * Group name used for navigation sections in docs UIs.\n * e.g. \"Users\", \"Billing\", \"Auth\".\n */\n docsGroup?: string\n /**\n * Tags that can be used to filter / facet in interactive docs.\n * e.g. [\"users\", \"admin\", \"internal\"].\n */\n tags?: string[]\n /**\n * Mark the route as deprecated in docs.\n * Renderers can badge this and/or hide by default.\n */\n deprecated?: boolean\n /**\n * Optional stability information for the route.\n * Renderers can surface this prominently.\n */\n stability?: 'experimental' | 'beta' | 'stable' | 'deprecated'\n /**\n * Hide this route from public docs while keeping it usable in code.\n */\n docsHidden?: boolean\n /**\n * Arbitrary extra metadata for docs renderers.\n * Can be used for auth requirements, rate limits, feature flags, etc.\n */\n docsMeta?: Record<string, unknown>\n}\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfg,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X]\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<\n A extends readonly unknown[],\n B extends readonly unknown[],\n> = [...A, ...B]\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S]\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never\n ? never\n : Record<ExtractParamNames<Path>, string | number>\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(\n path: Path,\n params: ExtractParamsFromPath<Path>,\n) {\n if (!params) return path\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k]\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`)\n return String(v)\n })\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P]\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L\n params?: ExtractParamsFromPath<L['path']>\n query?: InferQuery<L>\n}) {\n let p = args.leaf.path\n if (args.params) {\n p = compilePath<L['path']>(p, args.params)\n }\n return [\n args.leaf.method,\n ...(p.split('/').filter(Boolean) as SplitPath<typeof p>),\n args.query ?? {},\n ] as const\n}\n\n/** Definition-time method config (for clarity). */\nexport type MethodCfgDef = MethodCfg\n\n/** Low-profile method config where schemas carry a phantom __out like SocketSchema. */\nexport type MethodCfgLowProfile = Omit<\n MethodCfg,\n 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'\n> & {\n bodySchema?: RouteSchema\n querySchema?: RouteSchema\n paramsSchema?: RouteSchema\n outputSchema?: RouteSchema\n}\nexport type AnyLeafLowProfile = LeafLowProfile<\n HttpMethod,\n string,\n MethodCfgLowProfile\n>\n\nexport function buildLowProfileLeaf<T extends AnyLeaf>(leaf: T) {\n return {\n ...leaf,\n cfg: {\n ...leaf.cfg,\n bodySchema: leaf.cfg.bodySchema as RouteSchema<\n z.infer<typeof leaf.cfg.bodySchema>\n >,\n querySchema: leaf.cfg.querySchema as RouteSchema<\n z.infer<typeof leaf.cfg.querySchema>\n >,\n paramsSchema: leaf.cfg.paramsSchema as RouteSchema<\n z.infer<typeof leaf.cfg.paramsSchema>\n >,\n outputSchema: leaf.cfg.outputSchema as RouteSchema<\n z.infer<typeof leaf.cfg.outputSchema>\n >,\n },\n }\n}\n\nexport type LeafLowProfile<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfgLowProfile,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeafLowProfile> =\n L['cfg']['paramsSchema'] extends RouteSchema<infer P> ? P : undefined\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> =\n L['cfg']['querySchema'] extends RouteSchema<infer Q> ? Q : undefined\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> =\n L['cfg']['bodySchema'] extends RouteSchema<infer B> ? B : undefined\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> =\n L['cfg']['outputSchema'] extends RouteSchema<infer O> ? O : undefined\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {}\n","// TODO:\n// * use this as a transform that infers the types from Zod, to only pass the types around instead of the full schemas -> make converters that go both ways (data to schema, schema to data)\n// * consider moving to core package\n// * update server and client side to use this type instead of raw zod schemas\nimport { AnyLeafLowProfile, HttpMethod, Prettify } from './routesV3.core'\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeafLowProfile> = L extends AnyLeafLowProfile\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeafLowProfile[]> = KeyOf<Leaves[number]>\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}`\n ? Lowercase<M>\n : never\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}`\n ? P\n : never\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<\n Leaves extends readonly AnyLeafLowProfile[],\n K extends string,\n> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeafLowProfile[]>(\n leaves: L,\n) {\n type Keys = KeysOf<L>\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> }\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:')\n ;(Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k]\n logger.system(`- ${k}`)\n })\n }\n\n return { all: leaves, byKey, log }\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R\n\ntype FilterRoute<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n Acc extends readonly AnyLeafLowProfile[] = [],\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S\n\ntype Routes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = FilterRoute<T, F>\ntype ByKey<\n T extends readonly AnyLeafLowProfile[],\n Acc extends Record<string, AnyLeafLowProfile> = {},\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? ByKey<\n Rest,\n Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }\n >\n : Acc\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = {\n byKey: ByKey<Routes<T, F>>\n all: Routes<T, F>\n}\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod'\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder'\nimport {\n AnyLeafLowProfile,\n MethodCfg,\n NodeCfg,\n RouteSchema, // ← add\n RouteSchemaOutput,\n type AnyLeaf,\n type Leaf,\n} from '../core/routesV3.core'\n\n/** Convert a raw ZodType to a low-profile RouteSchema. */\ntype ToRouteSchema<S> = S extends ZodType\n ? RouteSchema<RouteSchemaOutput<S>>\n : S\n\n/**\n * Map over a cfg object and turn any schema fields into RouteSchema.\n * We only touch the standard schema keys.\n */\ntype WithRouteSchemas<Cfg extends MethodCfg> = {\n [K in keyof Cfg]: K extends\n | 'bodySchema'\n | 'querySchema'\n | 'paramsSchema'\n | 'outputSchema'\n ? ToRouteSchema<Cfg[K]>\n : Cfg[K]\n}\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nconst crudPaginationShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nexport const CrudDefaultPagination = z.object(crudPaginationShape)\ntype CrudPaginationShape = typeof crudPaginationShape\ntype AnyCrudZodObject = z.ZodObject<any>\ntype AddCrudPagination<Q extends AnyCrudZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & CrudPaginationShape>\n : z.ZodObject<CrudPaginationShape>\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<\n A extends ZodType | undefined,\n B extends ZodType | undefined,\n>(\n a: A,\n b: B,\n): A extends ZodType\n ? B extends ZodType\n ? ReturnType<typeof z.intersection<A, B>>\n : A\n : B {\n if (a && b) return z.intersection(a as any, b as any) as any\n return (a ?? b) as any\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S\n}>\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType\n ? Omit<I, 'paramsSchema'> & { paramsSchema: P }\n : I\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean\n /** GET /collection/:id. Defaults to true. */ read?: boolean\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean\n}\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType\n /** Optional description string. */\n description?: string\n}\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable\n\n /** GET /collection configuration. */ list?: CrudListCfg\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg\n /** GET /collection/:id configuration. */ read?: CrudReadCfg\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg\n}\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n feed: true\n querySchema: C['list'] extends CrudListCfg\n ? AddCrudPagination<\n C['list']['querySchema'] extends AnyCrudZodObject\n ? C['list']['querySchema']\n : undefined\n >\n : AddCrudPagination<undefined>\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['create']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema']\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['update']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n ]\n : never\n : never\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras]\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<\n typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>\n >\n >\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any\n if (typeof b.crud === 'function') return branch\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n this: any,\n name: Name,\n cfg: C,\n extras?: (ctx: { collection: any; item: any }) => Extras,\n ) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function'\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey]\n ? ((s as any).shape()[idKey] as ZodType)\n : (s as ZodType)\n\n const itemOut = cfg.itemOutputSchema\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n })\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n })\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n })\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(\n idKey as any,\n paramValueSchema as any,\n (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n })\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n })\n }\n if (want.remove) {\n item.delete({\n outputSchema:\n cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n })\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras)\n extras({ collection: withCrud(collection), item: withCrud(item) })\n\n return item.done()\n },\n )\n\n return collection.done()\n })\n }\n\n return branch\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited))\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource }\n","// socket.index.ts (shared client/server)\n\nimport { z } from 'zod'\n\nexport type SocketSchema<Output = unknown> = z.ZodType & {\n __out: Output\n}\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out\n}\n\nexport type EventMap = Record<string, SocketEvent<any>>\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName =\n | 'sys:connect'\n | 'sys:disconnect'\n | 'sys:reconnect'\n | 'sys:connect_error'\n | 'sys:ping'\n | 'sys:pong'\n | 'sys:room_join'\n | 'sys:room_leave'\nexport function defineSocketEvents<\n const C extends SocketConnectionConfig,\n const Schemas extends Record<\n string,\n {\n message: z.ZodTypeAny\n }\n >,\n>(\n config: C,\n events: Schemas,\n): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>\n }\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>\n }\n}\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events }\n}\n\nexport type Payload<\n T extends EventMap,\n K extends keyof T,\n> = T[K] extends SocketEvent<infer Out> ? Out : never\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny\n leaveMetaMessage: z.ZodTypeAny\n pingPayload: z.ZodTypeAny\n pongPayload: z.ZodTypeAny\n}\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>\n leaveMetaMessage: SocketSchema<any>\n pingPayload: SocketSchema<any>\n pongPayload: SocketSchema<any>\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAelB,IAAM,uBAAuB;AAAA,EAC3B,mBAAmB,EAAE,OAAO,EAAE,SAAS;AAAA,EACvC,kBAAkB,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAChE;AAEA,IAAM,yBAAyB,EAAE,OAAO,oBAAoB;AAkB5D,SAAS,YAAY,QAAsB;AACzC,QAAM,gBAAiB,OAAe,QACjC,OAAe,QACf,OAAe,MAAM,QAAQ;AAClC,MAAI,CAAC,cAAe,QAAO,CAAC;AAC5B,SAAO,OAAO,kBAAkB,aAC5B,cAAc,KAAK,MAAM,IACzB;AACN;AAEA,SAAS,8BACP,OACA,SAAmB,CAAC,GACV;AACV,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,QAAM,cAAwB,CAAC;AAC/B,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,GAAG;AAChD,QAAI,iBAAiB,EAAE,WAAW;AAChC,YAAM,cAAc,YAAY,KAAqB;AACrD,YAAM,oBAAoB,8BAA8B,aAAa;AAAA,QACnE,GAAG;AAAA,QACH;AAAA,MACF,CAAC;AACD,kBAAY;AAAA,QACV,GAAI,kBAAkB,SAClB,oBACA,CAAC,CAAC,GAAG,QAAQ,GAAG,EAAE,KAAK,GAAG,CAAC;AAAA,MACjC;AAAA,IACF,WAAW,OAAO,SAAS,GAAG;AAC5B,kBAAY,KAAK,CAAC,GAAG,QAAQ,GAAG,EAAE,KAAK,GAAG,CAA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C,CAAC;AAAA,UACH;AAGA,cAAI;AACF,mBAAO,EAAE,YAAY,SAAS,UAAU,GAAG,MAAM,SAAS,IAAI,EAAE,CAAC;AAEnE,iBAAO,KAAK,KAAK;AAAA,QACnB;AAAA,MACF;AAEA,aAAO,WAAW,KAAK;AAAA,IACzB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAaO,SAAS,iBACd,MACA,WACA;AACA,SAAO,SAAS,SAAa,MAAM,SAAS,CAAC;AAC/C;;;AC1fO,SAAS,mBAAmB,QAAa,QAAa;AAC3D,SAAO,EAAE,QAAQ,OAAO;AAC1B;","names":["z","z","mergeSchemas"]}
1
+ {"version":3,"sources":["../src/core/routesV3.builder.ts","../src/core/routesV3.core.ts","../src/core/routesV3.finalize.ts","../src/crud/routesV3.crud.ts","../src/sockets/socket.index.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n AnyLeaf,\n AnyLeafLowProfile,\n Append,\n HttpMethod,\n Leaf,\n Merge,\n MergeArray,\n MethodCfg,\n NodeCfg,\n Prettify,\n RouteSchema,\n} from './routesV3.core'\n\nconst paginationQueryShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nconst defaultFeedQuerySchema = z.object(paginationQueryShape)\ntype PaginationShape = typeof paginationQueryShape\n\ntype ZodTypeAny = z.ZodTypeAny\ntype ParamZod<Name extends string, S extends ZodTypeAny> = z.ZodObject<{\n [K in Name]: S\n}>\ntype ZodArrayAny = z.ZodArray<ZodTypeAny>\ntype ZodObjectAny = z.ZodObject<any>\ntype AnyZodObject = z.ZodObject<any>\ntype MergedParamsResult<\n PS,\n Name extends string,\n P extends ZodTypeAny,\n> = PS extends ZodTypeAny\n ? z.ZodIntersection<PS, ParamZod<Name, P>>\n : ParamZod<Name, P>\n\nfunction getZodShape(schema: ZodObjectAny) {\n const shapeOrGetter = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n if (!shapeOrGetter) return {}\n return typeof shapeOrGetter === 'function'\n ? shapeOrGetter.call(schema)\n : shapeOrGetter\n}\n\nfunction collectNestedFieldSuggestions(\n shape: Record<string, ZodTypeAny> | undefined,\n prefix: string[] = [],\n): string[] {\n if (!shape) return []\n const suggestions: string[] = []\n for (const [key, value] of Object.entries(shape)) {\n if (value instanceof z.ZodObject) {\n const nestedShape = getZodShape(value as ZodObjectAny)\n const nestedSuggestions = collectNestedFieldSuggestions(nestedShape, [\n ...prefix,\n key,\n ])\n suggestions.push(\n ...(nestedSuggestions.length\n ? nestedSuggestions\n : [[...prefix, key].join('_')]),\n )\n } else if (prefix.length > 0) {\n suggestions.push([...prefix, key].join('_'))\n }\n }\n return suggestions\n}\n\nconst defaultFeedOutputSchema = z.object({\n items: z.array(z.unknown()),\n nextCursor: z.string().optional(),\n})\n\nfunction augmentFeedQuerySchema<Q extends ZodTypeAny | undefined>(schema: Q) {\n if (schema && !(schema instanceof z.ZodObject)) {\n console.warn(\n 'Feed queries must be a ZodObject; default pagination applied.',\n )\n return defaultFeedQuerySchema\n }\n\n const base = (schema as ZodObjectAny) ?? z.object({})\n const shape = getZodShape(base)\n const nestedSuggestions = collectNestedFieldSuggestions(shape)\n if (nestedSuggestions.length) {\n console.warn(\n `Feed query schemas should avoid nested objects; consider flattening fields like: ${nestedSuggestions.join(\n ', ',\n )}`,\n )\n }\n return base.extend(paginationQueryShape)\n}\n\nfunction augmentFeedOutputSchema<O extends ZodTypeAny | undefined>(schema: O) {\n if (!schema) return defaultFeedOutputSchema\n if (schema instanceof z.ZodArray) {\n return z.object({\n items: schema,\n nextCursor: z.string().optional(),\n })\n }\n if (schema instanceof z.ZodObject) {\n const shape = (schema as any).shape\n ? (schema as any).shape\n : (schema as any)._def?.shape?.()\n const hasItems = Boolean(shape?.items)\n if (hasItems) {\n return schema.extend({ nextCursor: z.string().optional() })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n }\n return z.object({\n items: z.array(schema as ZodTypeAny),\n nextCursor: z.string().optional(),\n })\n}\n\n/**\n * Runtime helper that mirrors the typed merge used by the builder.\n * @param a Previously merged params schema inherited from parent segments.\n * @param b Newly introduced params schema.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nfunction mergeSchemas<A extends ZodTypeAny, B extends ZodTypeAny>(\n a: A,\n b: B,\n): ZodTypeAny\nfunction mergeSchemas<A extends ZodTypeAny>(a: A, b: undefined): A\nfunction mergeSchemas<B extends ZodTypeAny>(a: undefined, b: B): B\nfunction mergeSchemas(\n a: ZodTypeAny | undefined,\n b: ZodTypeAny | undefined,\n): ZodTypeAny | undefined\nfunction mergeSchemas(a: ZodTypeAny | undefined, b: ZodTypeAny | undefined) {\n if (a && b) return z.intersection(a as any, b as any)\n return (a ?? b) as ZodTypeAny | undefined\n}\n\ntype FeedQuerySchema<C extends MethodCfg> = z.ZodObject<any>\n\ntype FeedOutputSchema<C extends MethodCfg> =\n C['outputSchema'] extends ZodArrayAny\n ? z.ZodObject<{\n items: C['outputSchema']\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : C['outputSchema'] extends ZodTypeAny\n ? z.ZodObject<{\n items: z.ZodArray<C['outputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : typeof defaultFeedOutputSchema\n\ntype BaseMethodCfg<C extends MethodCfg> = Merge<\n Omit<MethodCfg, 'querySchema' | 'outputSchema' | 'feed'>,\n Omit<C, 'querySchema' | 'outputSchema' | 'feed'>\n>\n\ntype FeedField<C extends MethodCfg> = C['feed'] extends true\n ? { feed: true }\n : { feed?: boolean }\n\ntype AddPaginationToQuery<Q extends AnyZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & PaginationShape>\n : z.ZodObject<PaginationShape>\n\ntype FeedQueryField<C extends MethodCfg> = {\n querySchema: AddPaginationToQuery<\n C['querySchema'] extends AnyZodObject ? C['querySchema'] : undefined\n >\n}\n\ntype NonFeedQueryField<C extends MethodCfg> =\n C['querySchema'] extends ZodTypeAny\n ? { querySchema: C['querySchema'] }\n : { querySchema?: undefined }\n\ntype FeedOutputField<C extends MethodCfg> = {\n outputSchema: FeedOutputSchema<C>\n}\n\ntype NonFeedOutputField<C extends MethodCfg> =\n C['outputSchema'] extends ZodTypeAny\n ? { outputSchema: C['outputSchema'] }\n : { outputSchema?: undefined }\n\ntype ParamsField<C extends MethodCfg, PS> = C['paramsSchema'] extends ZodTypeAny\n ? { paramsSchema: C['paramsSchema'] }\n : { paramsSchema: PS }\n\ntype EffectiveFeedFields<C extends MethodCfg, PS> = C['feed'] extends true\n ? FeedField<C> & FeedQueryField<C> & FeedOutputField<C> & ParamsField<C, PS>\n : FeedField<C> &\n NonFeedQueryField<C> &\n NonFeedOutputField<C> &\n ParamsField<C, PS>\n\ntype EffectiveCfg<C extends MethodCfg, PS> = Prettify<\n Merge<MethodCfg, BaseMethodCfg<C> & EffectiveFeedFields<C, PS>>\n>\n\ntype ToRouteSchema<S> = S extends ZodTypeAny ? RouteSchema<z.output<S>> : S\n\ntype LowProfileCfg<Cfg extends MethodCfg> = Prettify<\n Omit<Cfg, 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'> & {\n bodySchema: ToRouteSchema<Cfg['bodySchema']>\n querySchema: ToRouteSchema<Cfg['querySchema']>\n paramsSchema: ToRouteSchema<Cfg['paramsSchema']>\n outputSchema: ToRouteSchema<Cfg['outputSchema']>\n }\n>\n\ntype BuiltLeaf<\n M extends HttpMethod,\n Base extends string,\n I extends NodeCfg,\n C extends MethodCfg,\n PS,\n> = Leaf<M, Base, Merge<I, LowProfileCfg<EffectiveCfg<C, PS>>>>\n\n/** Builder surface used by `resource(...)` to accumulate leaves. */\nexport interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodTypeAny | undefined,\n> {\n // --- structure ---\n /**\n * Enter or define a static child segment.\n * Optionally accepts extra config and/or a builder to populate nested routes.\n * @param name Child segment literal (no leading slash).\n * @param cfg Optional node configuration to merge for descendants.\n * @param builder Callback to produce leaves for the child branch.\n */\n sub<Name extends string, J extends NodeCfg>(\n name: Name,\n cfg?: J,\n ): Branch<`${Base}/${Name}`, Acc, Merge<I, NonNullable<J>>, PS>\n\n sub<\n Name extends string,\n J extends NodeCfg | undefined,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n cfg: J,\n builder: (\n r: Branch<`${Base}/${Name}`, readonly [], Merge<I, NonNullable<J>>, PS>,\n ) => R,\n ): Branch<Base, Append<Acc, R[number]>, Merge<I, NonNullable<J>>, PS>\n\n sub<Name extends string, R extends readonly AnyLeafLowProfile[]>(\n name: Name,\n builder: (r: Branch<`${Base}/${Name}`, readonly [], I, PS>) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, PS>\n\n // --- parameterized segment (single signature) ---\n /**\n * Introduce a `:param` segment and merge its schema into downstream leaves.\n * @param name Parameter key (without leading colon).\n * @param paramsSchema Zod schema for the parameter value.\n * @param builder Callback that produces leaves beneath the parameterized segment.\n */\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base}/:${Name}`,\n readonly [],\n I,\n MergedParamsResult<PS, Name, P>\n >,\n ) => R,\n ): Branch<Base, MergeArray<Acc, R>, I, MergedParamsResult<PS, Name, P>>\n\n // --- flags inheritance ---\n /**\n * Merge additional node configuration that subsequent leaves will inherit.\n * @param cfg Partial node configuration.\n */\n with<J extends NodeCfg>(cfg: J): Branch<Base, Acc, Merge<I, J>, PS>\n\n // --- methods (return Branch to keep chaining) ---\n /**\n * Register a GET leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n get<C extends MethodCfg>(\n cfg: C,\n ): Branch<\n Base,\n Append<Acc, Prettify<BuiltLeaf<'get', Base, I, C, PS>>>,\n I,\n PS\n >\n\n /**\n * Register a POST leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n post<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'post', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PUT leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n put<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'put', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a PATCH leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n patch<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'patch', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n /**\n * Register a DELETE leaf at the current path.\n * @param cfg Method configuration (schemas, flags, descriptions, etc).\n */\n delete<C extends Omit<MethodCfg, 'feed'>>(\n cfg: C,\n ): Branch<\n Base,\n Append<\n Acc,\n Prettify<BuiltLeaf<'delete', Base, I, Merge<C, { feed: false }>, PS>>\n >,\n I,\n PS\n >\n\n // --- finalize this subtree ---\n /**\n * Finish the branch and return the collected leaves.\n * @returns Readonly tuple of accumulated leaves.\n */\n done(): Readonly<Acc>\n}\n\n/**\n * Start building a resource at the given base path.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Optional node configuration applied to all descendants.\n * @returns Root `Branch` instance used to compose the route tree.\n */\nexport function resource<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited?: I,\n): Branch<Base, readonly [], I, undefined> {\n const rootBase = base\n const rootInherited: NodeCfg = { ...(inherited as NodeCfg) }\n\n function makeBranch<\n Base2 extends string,\n I2 extends NodeCfg,\n PS2 extends ZodTypeAny | undefined,\n >(base2: Base2, inherited2: I2, mergedParamsSchema?: PS2) {\n const stack: AnyLeaf[] = []\n let currentBase: string = base2\n let inheritedCfg: NodeCfg = { ...(inherited2 as NodeCfg) }\n let currentParamsSchema: PS2 = mergedParamsSchema as PS2\n\n function add<M extends HttpMethod, C extends MethodCfg>(method: M, cfg: C) {\n // If the method didn’t provide a paramsSchema, inject the active merged one.\n const effectiveParamsSchema = (cfg.paramsSchema ??\n currentParamsSchema) as PS2 | undefined\n const effectiveQuerySchema =\n cfg.feed === true\n ? augmentFeedQuerySchema(cfg.querySchema)\n : cfg.querySchema\n const effectiveOutputSchema =\n cfg.feed === true\n ? augmentFeedOutputSchema(cfg.outputSchema)\n : cfg.outputSchema\n\n const fullCfg = (\n effectiveParamsSchema\n ? {\n ...inheritedCfg,\n ...cfg,\n paramsSchema: effectiveParamsSchema,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n : {\n ...inheritedCfg,\n ...cfg,\n ...(effectiveQuerySchema\n ? { querySchema: effectiveQuerySchema }\n : {}),\n ...(effectiveOutputSchema\n ? { outputSchema: effectiveOutputSchema }\n : {}),\n }\n ) as any\n\n const leaf = {\n method,\n path: currentBase as Base2,\n cfg: fullCfg,\n } as const\n\n stack.push(leaf as unknown as AnyLeaf)\n\n // Return same runtime obj, but with Acc including this new leaf\n return api as unknown as Branch<\n Base2,\n Append<readonly [], typeof leaf>,\n I2,\n PS2\n >\n }\n\n const api: any = {\n // compose a plain subpath (optional cfg) with optional builder\n sub<Name extends string, J extends NodeCfg | undefined = undefined>(\n name: Name,\n cfgOrBuilder?: J | ((r: any) => readonly AnyLeafLowProfile[]),\n maybeBuilder?: (r: any) => readonly AnyLeafLowProfile[],\n ) {\n let cfg: NodeCfg | undefined\n let builder: ((r: any) => readonly AnyLeafLowProfile[]) | undefined\n\n if (typeof cfgOrBuilder === 'function') {\n builder = cfgOrBuilder as any\n } else {\n cfg = cfgOrBuilder as NodeCfg | undefined\n builder = maybeBuilder\n }\n\n const childBase = `${currentBase}/${name}` as const\n const childInherited = { ...inheritedCfg, ...(cfg ?? {}) } as Merge<\n I2,\n NonNullable<J>\n >\n\n if (builder) {\n // params schema PS2 flows through unchanged on plain sub\n const child = makeBranch(\n childBase,\n childInherited,\n currentParamsSchema,\n )\n const leaves = builder(child) //as readonly AnyLeafLowProfile[]\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n typeof childInherited,\n PS2\n >\n } else {\n currentBase = childBase\n inheritedCfg = childInherited\n return api as Branch<\n `${Base2}/${Name}`,\n readonly [],\n typeof childInherited,\n PS2\n >\n }\n },\n\n // the single param function: name + schema + builder\n routeParameter<\n Name extends string,\n P extends ZodTypeAny,\n R extends readonly AnyLeafLowProfile[],\n >(\n name: Name,\n paramsSchema: P,\n builder: (\n r: Branch<\n `${Base2}/:${Name}`,\n readonly [],\n I2,\n MergedParamsResult<PS2, Name, P>\n >,\n ) => R,\n ) {\n const childBase = `${currentBase}/:${name}` as const\n // Wrap the value schema under the param name before merging with inherited params schema\n const paramObj: ParamZod<Name, P> = z.object({\n [name]: paramsSchema,\n } as Record<Name, P>)\n const childParams = (\n currentParamsSchema\n ? mergeSchemas(currentParamsSchema, paramObj)\n : paramObj\n ) as MergedParamsResult<PS2, Name, P>\n const child = makeBranch(childBase, inheritedCfg as I2, childParams)\n const leaves = builder(child)\n for (const l of leaves) stack.push(l)\n return api as Branch<\n Base2,\n Append<readonly [], (typeof leaves)[number]>,\n I2,\n MergedParamsResult<PS2, Name, P>\n >\n },\n\n with<J extends NodeCfg>(cfg: J) {\n inheritedCfg = { ...inheritedCfg, ...cfg }\n return api as Branch<Base2, readonly [], Merge<I2, J>, PS2>\n },\n\n // methods (inject current params schema if missing)\n get<C extends MethodCfg>(cfg: C) {\n return add('get', cfg)\n },\n post<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('post', { ...cfg, feed: false })\n },\n put<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('put', { ...cfg, feed: false })\n },\n patch<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('patch', { ...cfg, feed: false })\n },\n delete<C extends Omit<MethodCfg, 'feed'>>(cfg: C) {\n return add('delete', { ...cfg, feed: false })\n },\n\n done() {\n return stack\n },\n }\n\n return api as Branch<Base2, readonly [], I2, PS2>\n }\n\n // Root branch starts with no params schema (PS = undefined)\n return makeBranch(rootBase, rootInherited, undefined)\n}\n\n/**\n * Merge two readonly tuples (preserves literal tuple information).\n * @param arr1 First tuple.\n * @param arr2 Second tuple.\n * @returns New tuple containing values from both inputs.\n */\nexport const mergeArrays = <T extends readonly any[], S extends readonly any[]>(\n arr1: T,\n arr2: S,\n) => {\n return [...arr1, ...arr2] as [...T, ...S]\n}\n","import { z, ZodType } from 'zod'\n\n/** Supported HTTP verbs for the routes DSL. */\nexport type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'\n\n/** Declarative description of a multipart upload field. */\nexport type FileField = {\n /** Form field name used for uploads. */\n name: string\n /** Maximum number of files accepted for this field. */\n maxCount: number\n}\n\n/** Configuration that applies to an entire branch of the route tree. */\nexport type NodeCfg = {\n /** @deprecated. Does nothing. */\n authenticated?: boolean\n}\n\nexport type RouteSchema<Output = unknown> = ZodType & {\n __out: Output\n}\n\nexport type RouteSchemaOutput<Schema extends ZodType> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport const lowProfileParse = <T extends RouteSchema>(\n schema: T,\n data: unknown,\n): RouteSchemaOutput<T> => {\n return schema.parse(data) as RouteSchemaOutput<T>\n}\n\n/** Per-method configuration merged with inherited node config. */\nexport type MethodCfg = {\n /** Zod schema describing the request body. */\n bodySchema?: ZodType\n /** Zod schema describing the query string. */\n querySchema?: ZodType\n /** Zod schema describing path params (overrides inferred params). */\n paramsSchema?: ZodType\n /** Zod schema describing the response payload. */\n outputSchema?: ZodType\n /** Multipart upload definitions for the route. */\n bodyFiles?: FileField[]\n /** Marks the route as an infinite feed (enables cursor helpers). */\n feed?: boolean\n\n /** Optional human-readable description for docs/debugging. */\n description?: string\n /**\n * Short one-line summary for docs list views.\n * Shown in navigation / tables instead of the full description.\n */\n summary?: string\n /**\n * Group name used for navigation sections in docs UIs.\n * e.g. \"Users\", \"Billing\", \"Auth\".\n */\n docsGroup?: string\n /**\n * Tags that can be used to filter / facet in interactive docs.\n * e.g. [\"users\", \"admin\", \"internal\"].\n */\n tags?: string[]\n /**\n * Mark the route as deprecated in docs.\n * Renderers can badge this and/or hide by default.\n */\n deprecated?: boolean\n /**\n * Optional stability information for the route.\n * Renderers can surface this prominently.\n */\n stability?: 'experimental' | 'beta' | 'stable' | 'deprecated'\n /**\n * Hide this route from public docs while keeping it usable in code.\n */\n docsHidden?: boolean\n /**\n * Arbitrary extra metadata for docs renderers.\n * Can be used for auth requirements, rate limits, feature flags, etc.\n */\n docsMeta?: Record<string, unknown>\n}\n\n/** Immutable representation of a single HTTP route in the tree. */\nexport type Leaf<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfg,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n\n/** Convenience union covering all generated leaves. */\nexport type AnyLeaf = Leaf<HttpMethod, string, MethodCfg>\n\n/** Merge two object types while keeping nice IntelliSense output. */\nexport type Merge<A, B> = Prettify<Omit<A, keyof B> & B>\n\n/** Append a new element to a readonly tuple type. */\nexport type Append<T extends readonly unknown[], X> = [...T, X]\n\n/** Concatenate two readonly tuple types. */\nexport type MergeArray<\n A extends readonly unknown[],\n B extends readonly unknown[],\n> = [...A, ...B]\n\n// helpers (optional)\ntype SegmentParams<S extends string> = S extends `:${infer P}` ? P : never\ntype Split<S extends string> = S extends ''\n ? []\n : S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S]\ntype ExtractParamNames<Path extends string> = SegmentParams<Split<Path>[number]>\n\n/** Derive a params object type from a literal route string. */\nexport type ExtractParamsFromPath<Path extends string> =\n ExtractParamNames<Path> extends never\n ? never\n : Record<ExtractParamNames<Path>, string | number>\n\n/**\n * Interpolate `:params` in a path using the given values.\n * @param path Literal route string containing `:param` segments.\n * @param params Object of parameter values to interpolate.\n * @returns Path string with parameters substituted.\n */\nexport function compilePath<Path extends string>(\n path: Path,\n params: ExtractParamsFromPath<Path>,\n) {\n if (!params) return path\n return path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {\n const v = (params as any)[k]\n if (v === undefined || v === null) throw new Error(`Missing param :${k}`)\n return String(v)\n })\n}\n\n/**\n * Build a deterministic cache key for the given leaf.\n * The key matches the shape consumed by React Query helpers.\n * @param args.leaf Leaf describing the endpoint.\n * @param args.params Optional params used to build the path.\n * @param args.query Optional query payload.\n * @returns Tuple suitable for React Query cache keys.\n */\ntype SplitPath<P extends string> = P extends ''\n ? []\n : P extends `${infer A}/${infer B}`\n ? [A, ...SplitPath<B>]\n : [P]\nexport function buildCacheKey<L extends AnyLeaf>(args: {\n leaf: L\n params?: ExtractParamsFromPath<L['path']>\n query?: InferQuery<L>\n}) {\n let p = args.leaf.path\n if (args.params) {\n p = compilePath<L['path']>(p, args.params)\n }\n return [\n args.leaf.method,\n ...(p.split('/').filter(Boolean) as SplitPath<typeof p>),\n args.query ?? {},\n ] as const\n}\n\n/** Definition-time method config (for clarity). */\nexport type MethodCfgDef = MethodCfg\n\n/** Low-profile method config where schemas carry a phantom __out like SocketSchema. */\nexport type MethodCfgLowProfile = Omit<\n MethodCfg,\n 'bodySchema' | 'querySchema' | 'paramsSchema' | 'outputSchema'\n> & {\n bodySchema?: RouteSchema\n querySchema?: RouteSchema\n paramsSchema?: RouteSchema\n outputSchema?: RouteSchema\n}\nexport type AnyLeafLowProfile = LeafLowProfile<\n HttpMethod,\n string,\n MethodCfgLowProfile\n>\n\nexport function buildLowProfileLeaf<L extends AnyLeaf>(\n leaf: L,\n): LeafLowProfile<\n L['method'],\n L['path'],\n {\n [K in keyof L['cfg']]: K extends\n | 'bodySchema'\n | 'querySchema'\n | 'paramsSchema'\n | 'outputSchema'\n ? RouteSchema<z.infer<L['cfg'][K]>>\n : L['cfg'][K]\n }\n>\nexport function buildLowProfileLeaf(leaf: any): any {\n return {\n ...leaf,\n cfg: {\n ...leaf.cfg,\n bodySchema: leaf.cfg.bodySchema as RouteSchema<\n z.infer<typeof leaf.cfg.bodySchema>\n >,\n querySchema: leaf.cfg.querySchema as RouteSchema<\n z.infer<typeof leaf.cfg.querySchema>\n >,\n paramsSchema: leaf.cfg.paramsSchema as RouteSchema<\n z.infer<typeof leaf.cfg.paramsSchema>\n >,\n outputSchema: leaf.cfg.outputSchema as RouteSchema<\n z.infer<typeof leaf.cfg.outputSchema>\n >,\n },\n }\n}\n\nexport type LeafLowProfile<\n M extends HttpMethod,\n P extends string,\n C extends MethodCfgLowProfile,\n> = {\n /** Lowercase HTTP method (get/post/...). */\n readonly method: M\n /** Concrete path for the route (e.g. `/v1/users/:userId`). */\n readonly path: P\n /** Readonly snapshot of route configuration. */\n readonly cfg: Readonly<C>\n}\n/** Infer params either from the explicit params schema or from the path literal. */\nexport type InferParams<L extends AnyLeafLowProfile> =\n L['cfg']['paramsSchema'] extends RouteSchema<infer P> ? P : undefined\n\n/** Infer query shape from a Zod schema when present. */\nexport type InferQuery<L extends AnyLeaf> =\n L['cfg']['querySchema'] extends RouteSchema<infer Q> ? Q : undefined\n\n/** Infer request body shape from a Zod schema when present. */\nexport type InferBody<L extends AnyLeaf> =\n L['cfg']['bodySchema'] extends RouteSchema<infer B> ? B : undefined\n\n/** Infer handler output shape from a Zod schema. Defaults to unknown. */\nexport type InferOutput<L extends AnyLeaf> =\n L['cfg']['outputSchema'] extends RouteSchema<infer O> ? O : undefined\n\n/** Render a type as if it were a simple object literal. */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {}\n","// TODO:\n// * use this as a transform that infers the types from Zod, to only pass the types around instead of the full schemas -> make converters that go both ways (data to schema, schema to data)\n// * consider moving to core package\n// * update server and client side to use this type instead of raw zod schemas\nimport { AnyLeafLowProfile, HttpMethod, Prettify } from './routesV3.core'\n\n/** Build the key type for a leaf — distributive so method/path stay paired. */\nexport type KeyOf<L extends AnyLeafLowProfile> = L extends AnyLeafLowProfile\n ? `${Uppercase<L['method']>} ${L['path']}`\n : never\n\n// From a tuple of leaves, get the union of keys (pairwise, no cartesian blow-up)\ntype KeysOf<Leaves extends readonly AnyLeafLowProfile[]> = KeyOf<Leaves[number]>\n\n// Parse method & path out of a key\ntype MethodFromKey<K extends string> = K extends `${infer M} ${string}`\n ? Lowercase<M>\n : never\ntype PathFromKey<K extends string> = K extends `${string} ${infer P}`\n ? P\n : never\n\n// Given Leaves and a Key, pick the exact leaf that matches method+path\ntype LeafForKey<\n Leaves extends readonly AnyLeafLowProfile[],\n K extends string,\n> = Extract<\n Leaves[number],\n { method: MethodFromKey<K> & HttpMethod; path: PathFromKey<K> }\n>\n\n/**\n * Freeze a leaf tuple into a registry with typed key lookups.\n * @param leaves Readonly tuple of leaves produced by the builder DSL.\n * @returns Registry containing the leaves array and a `byKey` lookup map.\n */\nexport function finalize<const L extends readonly AnyLeafLowProfile[]>(\n leaves: L,\n) {\n type Keys = KeysOf<L>\n type MapByKey = { [K in Keys]: Prettify<LeafForKey<L, K>> }\n\n const byKey = Object.fromEntries(\n leaves.map((l) => [`${l.method.toUpperCase()} ${l.path}`, l] as const),\n ) as unknown as MapByKey\n\n const log = (logger: { system: (...args: unknown[]) => void }) => {\n logger.system('Finalized routes:')\n ;(Object.keys(byKey) as Keys[]).forEach((k) => {\n const leaf = byKey[k]\n logger.system(`- ${k}`)\n })\n }\n\n return { all: leaves, byKey, log }\n}\n\n/** Nominal type alias for a finalized registry. */\nexport type Registry<R extends ReturnType<typeof finalize>> = R\n\ntype FilterRoute<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n Acc extends readonly AnyLeafLowProfile[] = [],\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? First extends { path: `${string}${F}${string}` }\n ? FilterRoute<Rest, F, [...Acc, First]>\n : FilterRoute<Rest, F, Acc>\n : Acc\n\ntype UpperCase<S extends string> = S extends `${infer First}${infer Rest}`\n ? `${Uppercase<First>}${UpperCase<Rest>}`\n : S\n\ntype Routes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = FilterRoute<T, F>\ntype ByKey<\n T extends readonly AnyLeafLowProfile[],\n Acc extends Record<string, AnyLeafLowProfile> = {},\n> = T extends readonly [\n infer First extends AnyLeafLowProfile,\n ...infer Rest extends AnyLeafLowProfile[],\n]\n ? ByKey<\n Rest,\n Acc & { [K in `${UpperCase<First['method']>} ${First['path']}`]: First }\n >\n : Acc\n\n/**\n * Convenience helper for extracting a subset of routes by path fragment.\n * @param T Tuple of leaves produced by the DSL.\n * @param F String fragment to match against the route path.\n */\nexport type SubsetRoutes<\n T extends readonly AnyLeafLowProfile[],\n F extends string,\n> = {\n byKey: ByKey<Routes<T, F>>\n all: Routes<T, F>\n}\n","// routesV3.crud.ts\n// -----------------------------------------------------------------------------\n// Add a first-class .crud() helper to the routesV3 DSL, without touching the\n// core builder. This file:\n// 1) Declares types + module augmentation to extend Branch<...> with .crud\n// 2) Provides a runtime decorator `withCrud(...)` that installs the method\n// 3) Exports a convenience `resourceWithCrud(...)` wrapper (optional)\n// -----------------------------------------------------------------------------\n\nimport { z, ZodType } from 'zod'\nimport {\n resource as baseResource,\n type Branch as _Branch, // import type so we can augment it\n} from '../core/routesV3.builder'\nimport {\n AnyLeafLowProfile,\n MethodCfg,\n NodeCfg,\n RouteSchema, // ← add\n RouteSchemaOutput,\n type AnyLeaf,\n type Leaf,\n} from '../core/routesV3.core'\n\n/** Convert a raw ZodType to a low-profile RouteSchema. */\ntype ToRouteSchema<S> = S extends ZodType\n ? RouteSchema<RouteSchemaOutput<S>>\n : S\n\n/**\n * Map over a cfg object and turn any schema fields into RouteSchema.\n * We only touch the standard schema keys.\n */\ntype WithRouteSchemas<Cfg extends MethodCfg> = {\n [K in keyof Cfg]: K extends\n | 'bodySchema'\n | 'querySchema'\n | 'paramsSchema'\n | 'outputSchema'\n ? ToRouteSchema<Cfg[K]>\n : Cfg[K]\n}\n\n// -----------------------------------------------------------------------------\n// Small utilities (runtime + types)\n// -----------------------------------------------------------------------------\n/** Default cursor pagination used by list (GET collection). */\nconst crudPaginationShape = {\n pagination_cursor: z.string().optional(),\n pagination_limit: z.coerce.number().min(1).max(100).default(20),\n}\n\nexport const CrudDefaultPagination = z.object(crudPaginationShape)\ntype CrudPaginationShape = typeof crudPaginationShape\ntype AnyCrudZodObject = z.ZodObject<any>\ntype AddCrudPagination<Q extends AnyCrudZodObject | undefined> =\n Q extends z.ZodObject<infer Shape>\n ? z.ZodObject<Shape & CrudPaginationShape>\n : z.ZodObject<CrudPaginationShape>\n\n/**\n * Merge two Zod schemas at runtime; matches the typing pattern used in builder.\n * @param a Existing params schema inherited from parent branches.\n * @param b Schema introduced at the current branch.\n * @returns Intersection of schemas when both exist, otherwise whichever is defined.\n */\nexport function mergeSchemas<\n A extends ZodType | undefined,\n B extends ZodType | undefined,\n>(\n a: A,\n b: B,\n): A extends ZodType\n ? B extends ZodType\n ? ReturnType<typeof z.intersection<A, B>>\n : A\n : B {\n if (a && b) return z.intersection(a as any, b as any) as any\n return (a ?? b) as any\n}\n\n/** Build { [Name]: S } Zod object at the type-level. */\nexport type ParamSchema<Name extends string, S extends ZodType> = z.ZodObject<{\n [K in Name]: S\n}>\n\n/** Inject active params schema into a leaf cfg (to match your Leaf typing). */\ntype WithParams<I, P> = P extends ZodType\n ? Omit<I, 'paramsSchema'> & { paramsSchema: P }\n : I\n\n/** Resolve boolean flag: default D unless explicitly false. */\ntype Flag<E, D extends boolean> = E extends false ? false : D\n\n// -----------------------------------------------------------------------------\n// CRUD config (few knobs, with DX comments)\n// -----------------------------------------------------------------------------\n\n/** Toggle individual CRUD methods; defaults enable all (create/update require body). */\nexport type CrudEnable = {\n /** GET /collection (feed). Defaults to true. */ list?: boolean\n /** POST /collection. Defaults to true if `create` provided. */ create?: boolean\n /** GET /collection/:id. Defaults to true. */ read?: boolean\n /** PATCH /collection/:id. Defaults to true if `update` provided. */ update?: boolean\n /** DELETE /collection/:id. Defaults to true. */ remove?: boolean\n}\n\n/** Collection GET config. */\nexport type CrudListCfg = {\n /** Query schema (defaults to cursor pagination). */\n querySchema?: ZodType\n /** Output schema (defaults to { items: Item[], nextCursor? }). */\n outputSchema?: ZodType\n /** Optional description string. */\n description?: string\n}\n\n/** Collection POST config. */\nexport type CrudCreateCfg = {\n /** Body schema for creating an item. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item GET config. */\nexport type CrudReadCfg = {\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item PATCH config. */\nexport type CrudUpdateCfg = {\n /** Body schema for partial updates. */\n bodySchema: ZodType\n /** Output schema (defaults to itemOutputSchema). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/** Item DELETE config. */\nexport type CrudRemoveCfg = {\n /** Output schema (defaults to { ok: true }). */\n outputSchema?: ZodType\n /** Optional description. */\n description?: string\n}\n\n/**\n * CRUD config for `.crud(\"resource\", cfg, extras?)`.\n *\n * It synthesizes `:[resourceName]Id` as the param key and uses `paramSchema` for the value.\n * Prefer passing a **value schema** (e.g. `z.string().uuid()`).\n * As a convenience, a ZodObject of shape `{ [resourceName]Id: schema }` is accepted at runtime too.\n */\nexport type CrudCfg<Name extends string = string> = {\n /**\n * Zod schema for the ID *value* (e.g. `z.string().uuid()`).\n * The parameter key is always `:${name}Id`.\n * (If you pass `z.object({ [name]Id: ... })`, it's accepted at runtime.)\n */\n paramSchema: ZodType\n\n /**\n * The single-item output shape used by read/create/update by default.\n * List defaults to `{ items: z.array(itemOutputSchema), nextCursor? }`.\n */\n itemOutputSchema: ZodType\n\n /** Per-method toggles (all enabled by default; create/update require bodies). */\n enable?: CrudEnable\n\n /** GET /collection configuration. */ list?: CrudListCfg\n /** POST /collection configuration (enables create). */ create?: CrudCreateCfg\n /** GET /collection/:id configuration. */ read?: CrudReadCfg\n /** PATCH /collection/:id configuration (enables update). */ update?: CrudUpdateCfg\n /** DELETE /collection/:id configuration. */ remove?: CrudRemoveCfg\n}\n\n// -----------------------------------------------------------------------------\n// Type plumbing to expose generated leaves (so finalize().byKey sees them)\n// -----------------------------------------------------------------------------\n\ntype CrudLeavesTuple<\n Base extends string,\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n> = `${Name}Id` extends infer IdName extends string\n ? ParamSchema<IdName, C['paramSchema']> extends infer IdParamZ extends ZodType\n ? [\n // GET /collection\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['list'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n feed: true\n querySchema: C['list'] extends CrudListCfg\n ? AddCrudPagination<\n C['list']['querySchema'] extends AnyCrudZodObject\n ? C['list']['querySchema']\n : undefined\n >\n : AddCrudPagination<undefined>\n outputSchema: C['list'] extends CrudListCfg\n ? C['list']['outputSchema'] extends ZodType\n ? C['list']['outputSchema']\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n : z.ZodObject<{\n items: z.ZodArray<C['itemOutputSchema']>\n nextCursor: z.ZodOptional<z.ZodString>\n }>\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []),\n\n // POST /collection\n ...((C['create'] extends CrudCreateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['create']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'post',\n `${Base}/${Name}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['create'] extends CrudCreateCfg\n ? C['create']['bodySchema']\n : never\n outputSchema: C['create'] extends CrudCreateCfg\n ? C['create']['outputSchema'] extends ZodType\n ? C['create']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n PS\n >\n >\n >,\n ]\n : []\n : []),\n\n // GET /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['read'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'get',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['read'] extends CrudReadCfg\n ? C['read']['outputSchema'] extends ZodType\n ? C['read']['outputSchema']\n : C['itemOutputSchema']\n : C['itemOutputSchema']\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n\n // PATCH /collection/:id\n ...((C['update'] extends CrudUpdateCfg ? true : false) extends true\n ? Flag<\n C['enable'] extends CrudEnable\n ? C['enable']['update']\n : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'patch',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n bodySchema: C['update'] extends CrudUpdateCfg\n ? C['update']['bodySchema']\n : never\n outputSchema: C['update'] extends CrudUpdateCfg\n ? C['update']['outputSchema'] extends ZodType\n ? C['update']['outputSchema']\n : C['itemOutputSchema']\n : never\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []\n : []),\n\n // DELETE /collection/:id\n ...(Flag<\n C['enable'] extends CrudEnable ? C['enable']['remove'] : undefined,\n true\n > extends true\n ? [\n Leaf<\n 'delete',\n `${Base}/${Name}/:${IdName}`,\n WithRouteSchemas<\n // ← wrap cfg\n WithParams<\n Omit<I, never> & {\n outputSchema: C['remove'] extends CrudRemoveCfg\n ? C['remove']['outputSchema'] extends ZodType\n ? C['remove']['outputSchema']\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n : z.ZodObject<{ ok: z.ZodLiteral<true> }>\n description?: string\n },\n ReturnType<typeof mergeSchemas<PS, IdParamZ>>\n >\n >\n >,\n ]\n : []),\n ]\n : never\n : never\n\n/** Merge generated leaves + extras into the branch accumulator. */\ntype CrudResultAcc<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[],\n> = [...Acc, ...CrudLeavesTuple<Base, I, PS, Name, C>, ...Extras]\n\n// -----------------------------------------------------------------------------\n// Module augmentation: add the typed `.crud(...)` to Branch<...>\n// -----------------------------------------------------------------------------\n\ndeclare module './../core/routesV3.builder' {\n interface Branch<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n > {\n /**\n * Generate opinionated CRUD endpoints for a collection at `/.../<name>`\n * with an item at `/.../<name>/:<name>Id`.\n *\n * Creates (subject to `enable` + presence of create/update bodies):\n * - GET /<name> (feed list)\n * - POST /<name> (create)\n * - GET /<name>/:<name>Id (read item)\n * - PATCH /<name>/:<name>Id (update item)\n * - DELETE /<name>/:<name>Id (remove item)\n *\n * The `extras` callback receives live builders at both collection and item\n * levels so you can add custom subroutes; their leaves are included in the\n * returned Branch type.\n */\n crud<\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeafLowProfile[] = readonly [],\n >(\n name: Name,\n cfg: C,\n extras?: (ctx: {\n /** Builder at `/.../<name>` (collection scope). */\n collection: _Branch<`${Base}/${Name}`, readonly [], I, PS>\n /** Builder at `/.../<name>/:<name>Id` (item scope). */\n item: _Branch<\n `${Base}/${Name}/:${`${Name}Id`}`,\n readonly [],\n I,\n ReturnType<\n typeof mergeSchemas<PS, ParamSchema<`${Name}Id`, C['paramSchema']>>\n >\n >\n }) => Extras,\n ): _Branch<Base, CrudResultAcc<Base, Acc, I, PS, Name, C, Extras>, I, PS>\n }\n}\n\n// -----------------------------------------------------------------------------\n// Runtime: install .crud on any Branch via decorator\n// -----------------------------------------------------------------------------\n\n/**\n * Decorate a Branch instance so `.crud(...)` is available at runtime.\n * Tip: wrap the root: `withCrud(resource('/v1'))`.\n * @param branch Branch returned by `resource(...)`.\n * @returns Same branch with `.crud(...)` installed.\n */\nexport function withCrud<\n Base extends string,\n Acc extends readonly AnyLeafLowProfile[],\n I extends NodeCfg,\n PS extends ZodType | undefined,\n>(branch: _Branch<Base, Acc, I, PS>): _Branch<Base, Acc, I, PS> {\n const b = branch as any\n if (typeof b.crud === 'function') return branch\n\n b.crud = function <\n Name extends string,\n C extends CrudCfg<Name>,\n Extras extends readonly AnyLeaf[] = readonly [],\n >(\n this: any,\n name: Name,\n cfg: C,\n extras?: (ctx: { collection: any; item: any }) => Extras,\n ) {\n // Build inside a sub-branch at `/.../<name>` and harvest its leaves.\n return this.sub(name, (collection: any) => {\n const idKey = `${name}Id`\n\n // Accept a value schema (preferred); but if a z.object({[name]Id: ...}) is provided, use it.\n const s = cfg.paramSchema\n const isObj =\n s &&\n typeof (s as any)._def === 'object' &&\n (s as any)._def.typeName === 'ZodObject' &&\n typeof (s as any).shape === 'function'\n\n const paramValueSchema =\n isObj && (s as any).shape()[idKey]\n ? ((s as any).shape()[idKey] as ZodType)\n : (s as ZodType)\n\n const itemOut = cfg.itemOutputSchema\n const listOut =\n cfg.list?.outputSchema ??\n z.object({\n items: z.array(itemOut),\n nextCursor: z.string().optional(),\n })\n\n const want = {\n list: cfg.enable?.list !== false,\n create: cfg.enable?.create !== false && !!cfg.create?.bodySchema,\n read: cfg.enable?.read !== false,\n update: cfg.enable?.update !== false && !!cfg.update?.bodySchema,\n remove: cfg.enable?.remove !== false,\n } as const\n\n // Collection routes\n if (want.list) {\n collection.get({\n feed: true,\n querySchema: cfg.list?.querySchema ?? CrudDefaultPagination,\n outputSchema: listOut,\n description: cfg.list?.description ?? 'List',\n })\n }\n\n if (want.create) {\n collection.post({\n bodySchema: cfg.create!.bodySchema,\n outputSchema: cfg.create?.outputSchema ?? itemOut,\n description: cfg.create?.description ?? 'Create',\n })\n }\n\n // Item routes via :<name>Id\n collection.routeParameter(\n idKey as any,\n paramValueSchema as any,\n (item: any) => {\n if (want.read) {\n item.get({\n outputSchema: cfg.read?.outputSchema ?? itemOut,\n description: cfg.read?.description ?? 'Read',\n })\n }\n if (want.update) {\n item.patch({\n bodySchema: cfg.update!.bodySchema,\n outputSchema: cfg.update?.outputSchema ?? itemOut,\n description: cfg.update?.description ?? 'Update',\n })\n }\n if (want.remove) {\n item.delete({\n outputSchema:\n cfg.remove?.outputSchema ?? z.object({ ok: z.literal(true) }),\n description: cfg.remove?.description ?? 'Delete',\n })\n }\n\n // Give extras fully-capable builders (decorate so extras can call .crud again)\n if (extras)\n extras({ collection: withCrud(collection), item: withCrud(item) })\n\n return item.done()\n },\n )\n\n return collection.done()\n })\n }\n\n return branch\n}\n\n// -----------------------------------------------------------------------------\n// Optional convenience: re-export a resource() that already has .crud installed\n// -----------------------------------------------------------------------------\n\n/**\n * Drop-in replacement for `resource(...)` that returns a Branch with `.crud()` installed.\n * You can either use this or call `withCrud(resource(...))`.\n * @param base Root path for the resource (e.g. `/v1`).\n * @param inherited Node configuration merged into every leaf.\n * @returns Branch builder that already includes the CRUD helper.\n */\nexport function resourceWithCrud<Base extends string, I extends NodeCfg = {}>(\n base: Base,\n inherited: I,\n) {\n return withCrud(baseResource(base, inherited))\n}\n\n// Re-export the original in case you want both styles from this module\nexport { baseResource as resource }\n","// socket.index.ts (shared client/server)\n\nimport { z } from 'zod'\n\nexport type SocketSchema<Output = unknown> = z.ZodType & {\n __out: Output\n}\n\nexport type SocketSchemaOutput<Schema extends z.ZodTypeAny> = Schema extends {\n __out: infer Out\n}\n ? Out\n : z.output<Schema>\n\nexport type SocketEvent<Out = unknown> = {\n message: z.ZodTypeAny\n /** phantom field, only for typing; not meant to be used at runtime */\n __out: Out\n}\n\nexport type EventMap = Record<string, SocketEvent<any>>\n\n/**\n * System event names – shared so server and client\n * don't drift on naming.\n */\nexport type SysEventName =\n | 'sys:connect'\n | 'sys:disconnect'\n | 'sys:reconnect'\n | 'sys:connect_error'\n | 'sys:ping'\n | 'sys:pong'\n | 'sys:room_join'\n | 'sys:room_leave'\nexport function defineSocketEvents<\n const C extends SocketConnectionConfig,\n const Schemas extends Record<\n string,\n {\n message: z.ZodTypeAny\n }\n >,\n>(\n config: C,\n events: Schemas,\n): {\n config: {\n [K in keyof C]: SocketSchema<z.output<C[K]>>\n }\n events: {\n [K in keyof Schemas]: SocketEvent<z.output<Schemas[K]['message']>>\n }\n}\n\nexport function defineSocketEvents(config: any, events: any) {\n return { config, events }\n}\n\nexport type Payload<\n T extends EventMap,\n K extends keyof T,\n> = T[K] extends SocketEvent<infer Out> ? Out : never\nexport type SocketConnectionConfig = {\n joinMetaMessage: z.ZodTypeAny\n leaveMetaMessage: z.ZodTypeAny\n pingPayload: z.ZodTypeAny\n pongPayload: z.ZodTypeAny\n}\n\nexport type SocketConnectionConfigOutput = {\n joinMetaMessage: SocketSchema<any>\n leaveMetaMessage: SocketSchema<any>\n pingPayload: SocketSchema<any>\n pongPayload: SocketSchema<any>\n}\n"],"mappings":";AAAA,SAAS,SAAS;AAelB,IAAM,uBAAuB;AAAA,EAC3B,mBAAmB,EAAE,OAAO,EAAE,SAAS;AAAA,EACvC,kBAAkB,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAChE;AAEA,IAAM,yBAAyB,EAAE,OAAO,oBAAoB;AAkB5D,SAAS,YAAY,QAAsB;AACzC,QAAM,gBAAiB,OAAe,QACjC,OAAe,QACf,OAAe,MAAM,QAAQ;AAClC,MAAI,CAAC,cAAe,QAAO,CAAC;AAC5B,SAAO,OAAO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MACH;AAGA,iBAAW;AAAA,QACT;AAAA,QACA;AAAA,QACA,CAAC,SAAc;AACb,cAAI,KAAK,MAAM;AACb,iBAAK,IAAI;AAAA,cACP,cAAc,IAAI,MAAM,gBAAgB;AAAA,cACxC,aAAa,IAAI,MAAM,eAAe;AAAA,YACxC,CAAC;AAAA,UACH;AACA,cAAI,KAAK,QAAQ;AACf,iBAAK,MAAM;AAAA,cACT,YAAY,IAAI,OAAQ;AAAA,cACxB,cAAc,IAAI,QAAQ,gBAAgB;AAAA,cAC1C,aAAa,IAAI,QAAQ,eAAe;AAAA,YAC1C,CAAC;AAAA,UACH;AACA,cAAI,KAAK,QAAQ;AACf,iBAAK,OAAO;AAAA,cACV,cACE,IAAI,QAAQ,gBAAgBA,GAAE,OAAO,EAAE,IAAIA,GAAE,QAAQ,IAAI,EAAE,CAAC;AAAA,cAC9D,aAAa,IAAI,QAAQ,eAAe;AAAA,YAC1C,CAAC;AAAA,UACH;AAGA,cAAI;AACF,mBAAO,EAAE,YAAY,SAAS,UAAU,GAAG,MAAM,SAAS,IAAI,EAAE,CAAC;AAEnE,iBAAO,KAAK,KAAK;AAAA,QACnB;AAAA,MACF;AAEA,aAAO,WAAW,KAAK;AAAA,IACzB,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAaO,SAAS,iBACd,MACA,WACA;AACA,SAAO,SAAS,SAAa,MAAM,SAAS,CAAC;AAC/C;;;AC1fO,SAAS,mBAAmB,QAAa,QAAa;AAC3D,SAAO,EAAE,QAAQ,OAAO;AAC1B;","names":["z","z","mergeSchemas"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@emeryld/rrroutes-contract",
3
3
  "description": "TypeScript contract definitions for RRRoutes",
4
- "version": "2.3.2",
4
+ "version": "2.3.3",
5
5
  "private": false,
6
6
  "type": "module",
7
7
  "main": "dist/index.cjs",