@guren/server 2.7.0 → 2.8.0

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.
@@ -6,7 +6,7 @@ import standard from "figlet/importable-fonts/Standard.js";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@guren/server",
9
- version: "2.7.0",
9
+ version: "2.8.0",
10
10
  type: "module",
11
11
  license: "MIT",
12
12
  repository: {
@@ -119,7 +119,7 @@ var package_default = {
119
119
  test: "bun test"
120
120
  },
121
121
  dependencies: {
122
- "@guren/orm": "^2.4.0",
122
+ "@guren/orm": "^2.5.0",
123
123
  "@modelcontextprotocol/sdk": "^1.30.0",
124
124
  chalk: "^5.3.0",
125
125
  consola: "^3.4.2",
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { parseRequestPayload, formatValidationErrors } from './http/request.js';
4
4
  export { Controller } from './mvc/Controller.js';
5
5
  export type { InertiaResponse, InferInertiaProps, ControllerInertiaProps, AuthPayload } from './mvc/Controller.js';
6
6
  export { Router } from './mvc/Router.js';
7
- export type { RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
7
+ export type { BindableModel, RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteModelBinding, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
8
8
  export { ViewEngine } from './mvc/ViewEngine.js';
9
9
  export { inertia, setInertiaSsrRenderer, setInertiaDocument } from './mvc/inertia/InertiaEngine.js';
10
10
  export { setInertiaSharedProps, getInertiaSharedPropsResolver, shareInertiaProps } from './mvc/inertia/shared.js';
package/dist/index.js CHANGED
@@ -5,17 +5,7 @@ import {
5
5
  logDevServerBanner,
6
6
  parseImportMap,
7
7
  startViteDevServer
8
- } from "./chunk-AOPXIURJ.js";
9
- import {
10
- LocalDriver,
11
- MemoryDriver as MemoryDriver3,
12
- S3Driver,
13
- StorageManager,
14
- createStorageManager
15
- } from "./chunk-JTNRAWQR.js";
16
- import {
17
- trimSlashes
18
- } from "./chunk-AZOYI43J.js";
8
+ } from "./chunk-4BUZXYGV.js";
19
9
  import {
20
10
  PendingSchedule,
21
11
  Schedule,
@@ -30,6 +20,16 @@ import {
30
20
  parseCron,
31
21
  toTimezone
32
22
  } from "./chunk-EI5GYMAT.js";
23
+ import {
24
+ LocalDriver,
25
+ MemoryDriver as MemoryDriver3,
26
+ S3Driver,
27
+ StorageManager,
28
+ createStorageManager
29
+ } from "./chunk-JTNRAWQR.js";
30
+ import {
31
+ trimSlashes
32
+ } from "./chunk-AZOYI43J.js";
33
33
  import {
34
34
  isDocsViewerEnabled
35
35
  } from "./chunk-A5JJ7XTH.js";
@@ -408,6 +408,16 @@ function capabilitiesOf(handler) {
408
408
  }
409
409
 
410
410
  // src/mvc/Router.ts
411
+ function normalizeModelBinding(binding) {
412
+ if (Array.isArray(binding)) {
413
+ const [model, key] = binding;
414
+ return { model, key };
415
+ }
416
+ return { model: binding };
417
+ }
418
+ async function resolveModelBinding({ model, key }, value) {
419
+ return key === void 0 ? model.findOrFail(value) : model.findOrFail(value, key);
420
+ }
411
421
  function assertSyncGroupCallback(result, method) {
412
422
  if (typeof result?.then !== "function") return;
413
423
  throw new Error(
@@ -440,8 +450,6 @@ var Router = class {
440
450
  middlewareAliases = /* @__PURE__ */ new Map();
441
451
  middlewareGroups = /* @__PURE__ */ new Map();
442
452
  modelBindings = /* @__PURE__ */ new Map();
443
- /** Model class names for router-level bind(param, Model) calls — resolver-only binds carry no name. */
444
- modelBindingNames = /* @__PURE__ */ new Map();
445
453
  aliasMiddleware(name, handler) {
446
454
  this.middlewareAliases.set(name, handler);
447
455
  return this;
@@ -457,21 +465,30 @@ var Router = class {
457
465
  middleware(...items) {
458
466
  return new RouterMiddlewareGroupBuilder(this, items);
459
467
  }
468
+ /**
469
+ * Bind a route parameter for every route on this router whose path names
470
+ * it. A model (class or `[Model, column]`) resolves through `findOrFail`
471
+ * and reaches the controller both via `this.model(Model)` and as a
472
+ * positional argument after the context; a custom resolver's value only
473
+ * arrives positionally, in path-parameter order:
474
+ *
475
+ * ```ts
476
+ * router.bind('post', async (slug) => Post.where('slug', slug).firstOrFail())
477
+ * router.get('/posts/:post', [PostController, 'show'])
478
+ *
479
+ * async show(_ctx: Context, post: PostRecord) { ... }
480
+ * ```
481
+ */
460
482
  bind(param, modelOrResolver) {
461
- if (typeof modelOrResolver === "function" && "findOrFail" in modelOrResolver) {
462
- const model = modelOrResolver;
463
- if (model.name) this.modelBindingNames.set(param, model.name);
464
- this.modelBindings.set(param, async (value) => {
465
- return model.findOrFail(value);
466
- });
467
- } else if (typeof modelOrResolver === "function") {
468
- this.modelBindings.set(param, modelOrResolver);
469
- } else {
470
- const model = modelOrResolver;
471
- this.modelBindings.set(param, async (value) => {
472
- return model.findOrFail(value);
473
- });
483
+ if (typeof modelOrResolver === "function" && !("findOrFail" in modelOrResolver)) {
484
+ this.modelBindings.set(param, { resolve: modelOrResolver });
485
+ return this;
474
486
  }
487
+ const binding = normalizeModelBinding(modelOrResolver);
488
+ this.modelBindings.set(param, {
489
+ model: binding.model,
490
+ resolve: (value) => resolveModelBinding(binding, value)
491
+ });
475
492
  return this;
476
493
  }
477
494
  on(method, path, handlerOrOptions, ...rest) {
@@ -549,7 +566,6 @@ var Router = class {
549
566
  this.middlewareAliases.clear();
550
567
  this.middlewareGroups.clear();
551
568
  this.modelBindings.clear();
552
- this.modelBindingNames.clear();
553
569
  }
554
570
  definitions() {
555
571
  return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings }) => ({
@@ -565,7 +581,7 @@ var Router = class {
565
581
  hasInlineMiddleware: middlewares.length > 0,
566
582
  capabilities: this.aggregateCapabilities(routeMiddlewareNames, [...scopedMiddlewares, ...middlewares]),
567
583
  controller: isControllerAction(handler) ? { name: handler[0].name, action: String(handler[1]) } : void 0,
568
- bindings: serializeBindings(path, bindings, this.modelBindingNames),
584
+ bindings: serializeBindings(path, bindings, this.modelBindings),
569
585
  ...openapi
570
586
  }));
571
587
  }
@@ -685,7 +701,9 @@ function applyRouteContract(route, options) {
685
701
  deprecated: options.deprecated
686
702
  };
687
703
  if (options.bind) {
688
- route.bindings = new Map(Object.entries(options.bind));
704
+ route.bindings = new Map(
705
+ Object.entries(options.bind).map(([param, binding]) => [param, normalizeModelBinding(binding)])
706
+ );
689
707
  }
690
708
  }
691
709
  var RouterMiddlewareGroupBuilder = class {
@@ -891,13 +909,14 @@ function resolveHandler(action, modelBindings, container, routeBindings, path) {
891
909
  if (container) {
892
910
  controller.setContainer(container);
893
911
  }
912
+ const routeBoundModels = /* @__PURE__ */ new Set();
894
913
  if (routeBindings && routeBindings.size > 0) {
895
914
  const params = c.req.param();
896
- for (const [paramName, model] of routeBindings) {
915
+ for (const [paramName, binding] of routeBindings) {
897
916
  const value = params[paramName];
898
917
  if (value !== void 0) {
899
- const resolved = await model.findOrFail(value);
900
- controller.setResolvedModel(model, resolved);
918
+ controller.setResolvedModel(binding.model, await resolveModelBinding(binding, value));
919
+ routeBoundModels.add(binding.model);
901
920
  }
902
921
  }
903
922
  }
@@ -906,7 +925,11 @@ function resolveHandler(action, modelBindings, container, routeBindings, path) {
906
925
  throw new Error(`Controller method ${String(methodName)} is not defined on ${ControllerClass.name}.`);
907
926
  }
908
927
  const resolvedBindings = modelBindings.size > 0 ? await resolveModelBindings(c, modelBindings, path) : [];
909
- const args = resolvedBindings.length > 0 ? [c, ...resolvedBindings] : [c];
928
+ const args = [c];
929
+ for (const { model, value } of resolvedBindings) {
930
+ if (model && !routeBoundModels.has(model)) controller.setResolvedModel(model, value);
931
+ args.push(value);
932
+ }
910
933
  const result = await method.apply(controller, args);
911
934
  return ensureResponse(result, c);
912
935
  };
@@ -927,12 +950,11 @@ async function resolveModelBindings(c, modelBindings, path) {
927
950
  const params = c.req.param();
928
951
  const pathParams = path ? extractPathParamNames(path) : [];
929
952
  for (const param of pathParams) {
930
- const resolver = modelBindings.get(param);
931
- if (!resolver) continue;
953
+ const binding = modelBindings.get(param);
954
+ if (!binding) continue;
932
955
  const value = params[param];
933
956
  if (value !== void 0) {
934
- const model = await resolver(value);
935
- resolved.push(model);
957
+ resolved.push({ model: binding.model, value: await binding.resolve(value) });
936
958
  }
937
959
  }
938
960
  return resolved;
@@ -963,13 +985,13 @@ function buildResponse(result) {
963
985
  }
964
986
  return new Response(String(result));
965
987
  }
966
- function serializeBindings(path, routeBindings, routerBindingNames) {
988
+ function serializeBindings(path, routeBindings, routerBindings) {
967
989
  const entries = /* @__PURE__ */ new Map();
968
990
  for (const param of extractPathParamNames(path)) {
969
- const name = routerBindingNames.get(param);
991
+ const name = routerBindings.get(param)?.model?.name;
970
992
  if (name) entries.set(param, name);
971
993
  }
972
- for (const [param, model] of routeBindings ?? []) {
994
+ for (const [param, { model }] of routeBindings ?? []) {
973
995
  if (model.name) entries.set(param, model.name);
974
996
  }
975
997
  return entries.size > 0 ? Object.fromEntries(entries) : void 0;
@@ -2928,6 +2950,7 @@ var Application = class {
2928
2950
  if (!hasUserProviderOf(InertiaServiceProvider)) {
2929
2951
  this.providerManager.register(InertiaServiceProvider);
2930
2952
  }
2953
+ setContainer(this.container);
2931
2954
  }
2932
2955
  options;
2933
2956
  hono;
@@ -3365,12 +3388,16 @@ var Controller = class {
3365
3388
  this.resolvedModels.set(modelClass, instance);
3366
3389
  }
3367
3390
  /**
3368
- * Retrieve a model instance resolved via route model binding.
3391
+ * Retrieve a model instance resolved via route model binding — a per-route
3392
+ * `bind` option or a router-level `router.bind(param, Model)`. Look up by
3393
+ * primary key with the class alone, or by another column with a
3394
+ * `[Model, column]` tuple.
3369
3395
  *
3370
3396
  * @example
3371
3397
  * ```typescript
3372
3398
  * // routes/web.ts
3373
3399
  * posts.get('/:id', { bind: { id: Post }, name: 'posts.show' }, [PostController, 'show'])
3400
+ * posts.get('/by-slug/:slug', { bind: { slug: [Post, 'slug'] } }, [PostController, 'show'])
3374
3401
  *
3375
3402
  * // PostController.ts
3376
3403
  * async show() {
@@ -3383,7 +3410,7 @@ var Controller = class {
3383
3410
  const instance = this.resolvedModels?.get(modelClass);
3384
3411
  if (instance === void 0) {
3385
3412
  throw new Error(
3386
- `No model binding found for ${modelClass.name ?? "unknown"}. Ensure the route has a matching bind option in RouteContractOptions.`
3413
+ `No model binding found for ${modelClass.name ?? "unknown"}. Ensure the route has a matching bind option in RouteContractOptions, or the router a bind(param, Model) call.`
3387
3414
  );
3388
3415
  }
3389
3416
  return instance;
@@ -33,6 +33,22 @@ export type SafeValidationResult<T> = {
33
33
  success: false;
34
34
  errors: Record<string, string>;
35
35
  };
36
+ /**
37
+ * The record `Controller.model()` returns for a bound model class. ORM models
38
+ * carry their row type as a `recordType` marker (set by `defineModel()`);
39
+ * `findOrFail`'s own return type cannot be read off the class because the
40
+ * method is generic in `this`, and `ReturnType` widens it to the base row.
41
+ * Anything without a usable marker — a class extending `Model` directly
42
+ * without redeclaring it, or a plain `{ findOrFail }` adapter — falls back to
43
+ * whatever its `findOrFail` resolves to. The marker is only trusted when it
44
+ * names an object type: `Model`'s own is `unknown`, and an unrelated
45
+ * `recordType` on some adapter (a string tag, say) describes no record.
46
+ */
47
+ export type BoundModelRecord<T extends {
48
+ findOrFail(...args: any[]): Promise<any>;
49
+ }> = T extends {
50
+ readonly recordType: infer R;
51
+ } ? unknown extends R ? Awaited<ReturnType<T['findOrFail']>> : R extends object ? R : Awaited<ReturnType<T['findOrFail']>> : Awaited<ReturnType<T['findOrFail']>>;
36
52
  type DefaultInertiaProps = Record<string, unknown>;
37
53
  export type AuthPayload = Record<string, unknown> & {
38
54
  user: unknown;
@@ -106,12 +122,16 @@ export declare class Controller {
106
122
  */
107
123
  setResolvedModel(modelClass: unknown, instance: unknown): void;
108
124
  /**
109
- * Retrieve a model instance resolved via route model binding.
125
+ * Retrieve a model instance resolved via route model binding — a per-route
126
+ * `bind` option or a router-level `router.bind(param, Model)`. Look up by
127
+ * primary key with the class alone, or by another column with a
128
+ * `[Model, column]` tuple.
110
129
  *
111
130
  * @example
112
131
  * ```typescript
113
132
  * // routes/web.ts
114
133
  * posts.get('/:id', { bind: { id: Post }, name: 'posts.show' }, [PostController, 'show'])
134
+ * posts.get('/by-slug/:slug', { bind: { slug: [Post, 'slug'] } }, [PostController, 'show'])
115
135
  *
116
136
  * // PostController.ts
117
137
  * async show() {
@@ -122,7 +142,7 @@ export declare class Controller {
122
142
  */
123
143
  protected model<T extends {
124
144
  findOrFail(...args: any[]): Promise<any>;
125
- }>(modelClass: T): Awaited<ReturnType<T['findOrFail']>>;
145
+ }>(modelClass: T): BoundModelRecord<T>;
126
146
  protected get ctx(): Context;
127
147
  protected get request(): import("hono").HonoRequest<any, unknown>;
128
148
  /**
@@ -29,11 +29,19 @@ type ModelBindingResolver = (value: string) => Promise<unknown>;
29
29
  /**
30
30
  * Model class with findOrFail static method.
31
31
  */
32
- interface BindableModel {
32
+ export interface BindableModel {
33
33
  findOrFail(id: unknown, key?: string): Promise<unknown>;
34
34
  /** Bound values are model classes at runtime; the constructor name is the introspection payload. */
35
35
  readonly name?: string;
36
36
  }
37
+ /**
38
+ * A model bound to a route parameter: the model class alone looks the value
39
+ * up by primary key (`Model.findOrFail(value)`); a `[Model, column]` tuple
40
+ * looks it up by that column (`Model.findOrFail(value, column)`), e.g.
41
+ * `bind: { slug: [Post, 'slug'] }`. Either way the controller reads the
42
+ * resolved record with `this.model(Model)`.
43
+ */
44
+ export type RouteModelBinding = BindableModel | readonly [BindableModel, string];
37
45
  /**
38
46
  * A Resource class accepted as a response hint. Only the constructor name is
39
47
  * introspected — the router never instantiates it, so any class whose
@@ -94,7 +102,13 @@ export interface RouteContractOptions<TParamsSchema extends SchemaLike<unknown>
94
102
  * it is the one actually enforced.
95
103
  */
96
104
  resource?: ResourceResponseHint;
97
- bind?: Record<string, BindableModel>;
105
+ /**
106
+ * Route model bindings: param name → model (see {@link RouteModelBinding}).
107
+ * `{ id: Post }` resolves by primary key, `{ slug: [Post, 'slug'] }` by
108
+ * that column; both throw the model's not-found exception (404) on a miss
109
+ * and expose the record to the controller via `this.model(Post)`.
110
+ */
111
+ bind?: Record<string, RouteModelBinding>;
98
112
  }
99
113
  export interface RouteOpenApiMetadata {
100
114
  summary?: string;
@@ -207,8 +221,6 @@ export declare class Router<M extends string = never> {
207
221
  private readonly middlewareAliases;
208
222
  private readonly middlewareGroups;
209
223
  private readonly modelBindings;
210
- /** Model class names for router-level bind(param, Model) calls — resolver-only binds carry no name. */
211
- private readonly modelBindingNames;
212
224
  aliasMiddleware<N extends string>(name: N, handler: MiddlewareHandler): Router<M | N>;
213
225
  groupMiddleware<N extends string>(name: N, middlewareNames: M[]): Router<M | N>;
214
226
  /**
@@ -216,7 +228,21 @@ export declare class Router<M extends string = never> {
216
228
  * builder. See {@link RouteMiddlewareInput}.
217
229
  */
218
230
  middleware(...items: RouteMiddlewareInput<M>[]): RouterMiddlewareGroupBuilder<M>;
219
- bind(param: string, modelOrResolver: BindableModel | ModelBindingResolver): this;
231
+ /**
232
+ * Bind a route parameter for every route on this router whose path names
233
+ * it. A model (class or `[Model, column]`) resolves through `findOrFail`
234
+ * and reaches the controller both via `this.model(Model)` and as a
235
+ * positional argument after the context; a custom resolver's value only
236
+ * arrives positionally, in path-parameter order:
237
+ *
238
+ * ```ts
239
+ * router.bind('post', async (slug) => Post.where('slug', slug).firstOrFail())
240
+ * router.get('/posts/:post', [PostController, 'show'])
241
+ *
242
+ * async show(_ctx: Context, post: PostRecord) { ... }
243
+ * ```
244
+ */
245
+ bind(param: string, modelOrResolver: RouteModelBinding | ModelBindingResolver): this;
220
246
  on<C extends ControllerConstructor>(method: string, path: string, handler: RouteHandler<C>, ...middlewares: MiddlewareHandler[]): RouteBuilder<M>;
221
247
  on<TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(method: string, path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: TypedRouteHandler<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>): RouteBuilder<M>;
222
248
  on<C extends ControllerConstructor, TParamsSchema extends SchemaLike<unknown>, TQuerySchema extends SchemaLike<unknown>, TBodySchema extends SchemaLike<unknown>, TOutputSchema extends SchemaLike<unknown>>(method: string, path: string, options: RouteContractOptions<TParamsSchema, TQuerySchema, TBodySchema, TOutputSchema>, handler: ControllerAction<C>): RouteBuilder<M>;
@@ -4,7 +4,7 @@ import {
4
4
  logDevServerBanner,
5
5
  parseImportMap,
6
6
  startViteDevServer
7
- } from "../chunk-AOPXIURJ.js";
7
+ } from "../chunk-4BUZXYGV.js";
8
8
  import {
9
9
  trimTrailingSlashes
10
10
  } from "../chunk-AZOYI43J.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -113,7 +113,7 @@
113
113
  "test": "bun test"
114
114
  },
115
115
  "dependencies": {
116
- "@guren/orm": "^2.4.0",
116
+ "@guren/orm": "^2.5.0",
117
117
  "@modelcontextprotocol/sdk": "^1.30.0",
118
118
  "chalk": "^5.3.0",
119
119
  "consola": "^3.4.2",