@lpdjs/firestore-repo-service 2.6.32 → 2.6.34

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.
Files changed (40) hide show
  1. package/README.md +14 -373
  2. package/dist/{create-servers-nXXPnlJt.d.ts → create-servers-DDHHOqOW.d.ts} +3 -3
  3. package/dist/{create-servers-BoJrRNI2.d.cts → create-servers-DmQNkgM_.d.cts} +3 -3
  4. package/dist/{index-DZnXSClM.d.cts → index-bkOZzCvS.d.cts} +1 -1
  5. package/dist/{index-BE-Iuye5.d.ts → index-qSs2G4CW.d.ts} +1 -1
  6. package/dist/index.cjs +94 -94
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +7 -5
  9. package/dist/index.d.ts +7 -5
  10. package/dist/index.js +94 -94
  11. package/dist/index.js.map +1 -1
  12. package/dist/llms-full.txt +43 -21
  13. package/dist/llms.txt +1 -1
  14. package/dist/{openapi-BHW1HViI.d.cts → openapi-B_2O8iJW.d.cts} +1 -1
  15. package/dist/{openapi-BupSdudk.d.ts → openapi-DBi6hg2V.d.ts} +1 -1
  16. package/dist/servers/admin/index.d.cts +4 -2
  17. package/dist/servers/admin/index.d.ts +4 -2
  18. package/dist/servers/crud/index.cjs +7 -7
  19. package/dist/servers/crud/index.cjs.map +1 -1
  20. package/dist/servers/crud/index.d.cts +7 -171
  21. package/dist/servers/crud/index.d.ts +7 -171
  22. package/dist/servers/crud/index.js +7 -7
  23. package/dist/servers/crud/index.js.map +1 -1
  24. package/dist/servers/hono/index.d.cts +5 -858
  25. package/dist/servers/hono/index.d.ts +5 -858
  26. package/dist/servers/index.cjs +98 -98
  27. package/dist/servers/index.cjs.map +1 -1
  28. package/dist/servers/index.d.cts +7 -5
  29. package/dist/servers/index.d.ts +7 -5
  30. package/dist/servers/index.js +98 -98
  31. package/dist/servers/index.js.map +1 -1
  32. package/dist/sync/index.cjs +7 -7
  33. package/dist/sync/index.cjs.map +1 -1
  34. package/dist/sync/index.js +7 -7
  35. package/dist/sync/index.js.map +1 -1
  36. package/dist/types-B4dMmfet.d.cts +860 -0
  37. package/dist/{types-CpkQQn4b.d.cts → types-BRS75oO7.d.cts} +10 -38
  38. package/dist/{types-BcT92G9B.d.ts → types-DnycnK_G.d.ts} +10 -38
  39. package/dist/types-DyKJJ9UQ.d.ts +860 -0
  40. package/package.json +1 -1
@@ -1,863 +1,10 @@
1
- import { Env, Context, MiddlewareHandler, Hono } from 'hono';
1
+ import { Env, Hono } from 'hono';
2
2
  import { IncomingMessage, ServerResponse } from 'node:http';
3
3
  import { HttpsOptions } from 'firebase-functions/v2/https';
4
+ import { H as HonoServerOptions, A as AnyServicesContainer, a as HttpMethod, P as PayloadSource, R as RouteDef, E as ErrorHandler, L as Logger, b as RouteHandler, c as AnyRouteDef, O as OpenAPIConfig, I as InterceptorConfig, d as ErrorHandlerContext } from '../../types-DyKJJ9UQ.js';
5
+ export { t as ApiKeySecurityScheme, B as BasicAuthOptions, D as DecodedBearerToken, k as DocsAuthExtension, l as DocsAuthRoute, h as FirebaseBearerAuthLike, F as FirebaseBearerAuthOptions, j as FirebaseDocsAuthOptions, u as HttpSecurityScheme, v as InterceptorErrorResponse, x as InterceptorOption, y as InterceptorOutput, M as MutualTlsSecurityScheme, z as OAuth2SecurityScheme, C as OAuthFlowObject, G as OAuthFlowsObject, J as OpenAPIInfo, K as OpenIdConnectSecurityScheme, p as RequestContext, N as RouteInput, Q as RouteInterceptor, T as RouteModuleDefault, U as RouteOutput, W as RoutesUnion, X as SecurityRequirement, Y as SecurityScheme, Z as SecuritySchemeBase, q as ServiceProvider, r as ServiceProviderMap, s as ServicesContainer, S as ServicesOf, V as ValidationError, e as basicAuth, o as createRequestContextMiddleware, n as createServices, m as defineRoutes, f as firebaseBearerAuth, g as firebaseDocsAuth, i as isDocsAuthExtension, w as withRequestContext } from '../../types-DyKJJ9UQ.js';
4
6
  import { z, ZodError } from 'zod';
5
- import { F as FirebaseAdminAuthLike, D as DecodedIdTokenLike } from '../../firebase-auth-DZ8lb2Ec.js';
6
-
7
- /**
8
- * Global DI services container for the Hono server.
9
- *
10
- * Lets you declare all your singletons (repositories, SDK clients, useCases,
11
- * loggers…) **once**, then inject them anywhere — routes, interceptors,
12
- * cron jobs, Firestore triggers, tests.
13
- *
14
- * ## How it works
15
- *
16
- * - Each service is constructed **lazily** on first access and cached for
17
- * the process lifetime (perfect for Cloud Functions cold-start).
18
- * - Providers may be **classes** (auto-injected: `new Class(services)`)
19
- * or **factories** (`(services) => instance`). Mix both freely.
20
- * - Inter-service dependencies are inferred either by destructuring the
21
- * factory argument (`postRepo: ({ db }) => new PostRepo(db)`) or by
22
- * reading `this.services.*` inside a class.
23
- * - A built-in `ctx` service exposes the **current request's** Hono
24
- * `Context` via `AsyncLocalStorage`. UseCases access
25
- * `this.services.ctx.c.get("user")` without any plumbing.
26
- * - Cycles are detected at first access with a clear error.
27
- *
28
- * @example
29
- * ```ts
30
- * // src/services.ts — infrastructure singletons only (no useCases here)
31
- * import { createServices } from "@lpdjs/firestore-repo-service/servers/hono";
32
- * import { PostRepo } from "./domains/posts/PostRepo.js";
33
- * import { Mailer } from "./services/Mailer.js";
34
- *
35
- * export const services = createServices({
36
- * postRepo: PostRepo, // class form (auto-injected)
37
- * mailer: ({ ctx }) => new Mailer(ctx), // factory form
38
- * });
39
- *
40
- * export type Services = typeof services;
41
- * ```
42
- *
43
- * @example
44
- * ```ts
45
- * // src/apis.ts
46
- * import { services } from "./services.js";
47
- * export const apis = createApiRegistry(
48
- * { v1: { basePath: "/v1", ... } },
49
- * { services },
50
- * );
51
- * ```
52
- *
53
- * @example
54
- * ```ts
55
- * // Inside a useCase — extends the UseCase base, owns its Zod schemas
56
- * import { z } from "zod";
57
- * import { UseCase } from "@lpdjs/firestore-repo-service/servers/hono";
58
- * import type { Services } from "../../services.js";
59
- *
60
- * const input = z.object({ title: z.string() });
61
- * const output = z.object({ id: z.string() });
62
- *
63
- * export class CreatePostUseCase extends UseCase<typeof input, typeof output, Services> {
64
- * static readonly input = input;
65
- * static readonly output = output;
66
- *
67
- * async execute(payload: z.infer<typeof input>): Promise<z.infer<typeof output>> {
68
- * const user = this.services.ctx.c.get("user");
69
- * return this.services.postRepo.create({ ...payload, authorId: user.id });
70
- * }
71
- * }
72
- * ```
73
- */
74
-
75
- /**
76
- * Per-request context exposed to every service / useCase.
77
- * The instance is a **stable singleton** but its `c` getter resolves to the
78
- * Hono `Context` of the currently-handled request via `AsyncLocalStorage`.
79
- *
80
- * Outside of a request (cron, manual scripts, tests), wrap your call in
81
- * {@link withRequestContext} to supply a context, otherwise accessing `c`
82
- * will throw.
83
- */
84
- interface RequestContext<TEnv extends Env = Env> {
85
- /** Hono `Context` of the currently-handled request. */
86
- readonly c: Context<TEnv>;
87
- /**
88
- * Same as `c` but returns `undefined` instead of throwing when called
89
- * outside a request scope. Useful for opportunistic logging.
90
- */
91
- readonly maybeC: Context<TEnv> | undefined;
92
- }
93
- /**
94
- * Hono middleware installed automatically by `HonoServer` when a `services`
95
- * container is provided. Populates the AsyncLocalStorage so the built-in
96
- * `ctx` service resolves to the current request.
97
- *
98
- * Exported for advanced cases (custom server / non-Hono adapter); you do not
99
- * need to call this manually in the standard flow.
100
- */
101
- declare function createRequestContextMiddleware(): MiddlewareHandler;
102
- /**
103
- * Run `fn` with a synthetic request context — required when invoking
104
- * services outside an HTTP handler (cron jobs, Firestore triggers, scripts,
105
- * unit tests). Inside `fn`, `services.ctx.c` resolves to the supplied `c`.
106
- *
107
- * @example
108
- * ```ts
109
- * // A cron that reuses a useCase
110
- * export const dailyTask = onSchedule("every 24 hours", async () => {
111
- * await withRequestContext({ c: fakeContext() }, async () => {
112
- * await services.createPostUseCase.execute({ ... });
113
- * });
114
- * });
115
- * ```
116
- */
117
- declare function withRequestContext<T>(ctx: {
118
- c: Context;
119
- }, fn: () => Promise<T> | T): Promise<T>;
120
- /**
121
- * Reserved service name — the built-in request context. User factories
122
- * cannot override it.
123
- */
124
- declare const CTX_KEY: "ctx";
125
- /**
126
- * Helper that derives the public services type from an output map.
127
- * Each entry in `TMap` is the instance type returned by its provider.
128
- * The built-in `ctx` is always present.
129
- */
130
- type ServicesOf<TMap> = {
131
- readonly ctx: RequestContext;
132
- } & {
133
- readonly [K in keyof TMap]: TMap[K];
134
- };
135
- /**
136
- * A single provider entry — either a factory `(deps) => R` or a class
137
- * `new (deps) => R`. `deps` is the *complete* services proxy
138
- * (siblings + built-in `ctx`).
139
- */
140
- type ServiceProvider<TMap, R> = ((deps: ServicesOf<TMap>) => R) | (new (deps: ServicesOf<TMap>) => R);
141
- /**
142
- * A provider map — each value is either a factory or a class constructor.
143
- */
144
- type ServiceProviderMap<TMap> = {
145
- [K in keyof TMap]: K extends typeof CTX_KEY ? never : ServiceProvider<TMap, TMap[K]>;
146
- };
147
- /**
148
- * Extract the instance/return type from a single provider value.
149
- */
150
- type ProviderReturn<P> = P extends new (...args: any) => infer R ? R : P extends (...args: any) => infer R ? R : never;
151
- /**
152
- * Compute the output service map from an inferred provider map.
153
- */
154
- type MapFromProviders<P> = {
155
- [K in keyof P]: ProviderReturn<P[K]>;
156
- };
157
- /**
158
- * Container returned by {@link createServices}. Behaves like a plain object
159
- * keyed by service name — accessing a key triggers lazy instantiation.
160
- * Use `type Services = typeof services` to derive the public type.
161
- */
162
- type ServicesContainer<TMap> = TMap;
163
- /**
164
- * Build a lazy singleton DI container.
165
- *
166
- * @param providers A map of service name → factory function **or** class
167
- * constructor. The single argument (factory deps / first
168
- * ctor param) receives a deps proxy typed as the full
169
- * services map (siblings + the built-in `ctx`).
170
- *
171
- * @example Factory form
172
- * ```ts
173
- * db: () => getFirestore(),
174
- * postRepo: ({ db }) => new PostRepo(db),
175
- * ```
176
- *
177
- * @example Class form (zero-boilerplate auto-injection)
178
- * ```ts
179
- * class RepositoryService {
180
- * constructor(private readonly services: Services) {}
181
- * get posts() { return this.services.db.posts; }
182
- * }
183
- *
184
- * createServices({
185
- * db: () => getFirestore(), // ← factory
186
- * repository: RepositoryService, // ← bare class (deps auto-injected)
187
- * });
188
- * ```
189
- */
190
- declare function createServices<P extends Record<string, ((deps: any) => unknown) | (new (deps: any) => unknown)>>(providers: P): ServicesContainer<ServicesOf<MapFromProviders<P>>>;
191
- /**
192
- * Opaque container type used by registry / server signatures that don't
193
- * need to know the concrete services map.
194
- */
195
- type AnyServicesContainer = ServicesContainer<Record<string, any>>;
196
-
197
- /**
198
- * Hono-native auth guards for the OpenAPI docs / spec endpoints.
199
- *
200
- * These return plain Hono `MiddlewareHandler`s, so they slot into
201
- * `OpenAPIConfig.docsAuth` (which protects only `/docs` + `/openapi.json`,
202
- * never the API routes). For a fully custom flow, pass your own middleware
203
- * instead of these helpers.
204
- */
205
-
206
- /** Decoded token shape — kept minimal to avoid a hard firebase-admin import. */
207
- interface DecodedBearerToken {
208
- uid: string;
209
- email?: string;
210
- [claim: string]: any;
211
- }
212
- /** Minimal Firebase Admin Auth surface used by {@link firebaseBearerAuth}. */
213
- interface FirebaseBearerAuthLike {
214
- verifyIdToken(idToken: string, checkRevoked?: boolean): Promise<DecodedBearerToken>;
215
- }
216
- /** Options for {@link firebaseBearerAuth}. */
217
- interface FirebaseBearerAuthOptions {
218
- /**
219
- * Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called
220
- * lazily on each request so `initializeApp()` runs first.
221
- */
222
- getAuth: () => FirebaseBearerAuthLike;
223
- /**
224
- * Authorization policy. Return `false` (or throw) to reject the request,
225
- * any truthy value to allow. Defaults to allowing any verified token.
226
- */
227
- allow?: (token: DecodedBearerToken) => boolean | Promise<boolean>;
228
- /** Revoke check passed to `verifyIdToken`. Default: `false`. */
229
- checkRevoked?: boolean;
230
- /**
231
- * Context key under which the decoded token is stored (`c.set(key, token)`)
232
- * for downstream handlers. Default: `"docsUser"`.
233
- */
234
- contextKey?: string;
235
- }
236
- /**
237
- * Guard the docs / spec endpoints with a Firebase ID token (Bearer scheme).
238
- *
239
- * @example
240
- * ```ts
241
- * import { getAuth } from "firebase-admin/auth";
242
- * import { firebaseBearerAuth } from "@lpdjs/firestore-repo-service/servers/hono";
243
- *
244
- * openapi: {
245
- * info,
246
- * docsAuth: firebaseBearerAuth({
247
- * getAuth: () => getAuth(),
248
- * allow: (t) => t.admin === true,
249
- * }),
250
- * }
251
- * ```
252
- */
253
- declare function firebaseBearerAuth(options: FirebaseBearerAuthOptions): MiddlewareHandler;
254
- /** Options for {@link basicAuth}. */
255
- interface BasicAuthOptions {
256
- username: string;
257
- password: string;
258
- /** Realm advertised in the `WWW-Authenticate` header. Default: `"Docs"`. */
259
- realm?: string;
260
- }
261
- /**
262
- * Guard the docs / spec endpoints with HTTP Basic Auth.
263
- *
264
- * @example
265
- * ```ts
266
- * openapi: { info, docsAuth: basicAuth({ username: "admin", password: "secret" }) }
267
- * ```
268
- */
269
- declare function basicAuth(options: BasicAuthOptions): MiddlewareHandler;
270
- /** A bare auxiliary route name (relative to the docs directory). */
271
- interface DocsAuthRoute {
272
- method: "GET" | "POST";
273
- /** Bare path segment relative to the docs directory, e.g. `"__login"`. */
274
- name: string;
275
- handler: MiddlewareHandler;
276
- }
277
- /**
278
- * Richer `docsAuth` value (vs. a bare `MiddlewareHandler`): a guard middleware
279
- * **plus** auxiliary routes (login page, session exchange, logout) that the
280
- * {@link HonoServer} mounts next to the docs/spec endpoints. Mirrors the admin
281
- * server's `AuthExtension`. Produced by {@link firebaseDocsAuth}.
282
- */
283
- interface DocsAuthExtension {
284
- readonly __docsAuthExtension: true;
285
- /** Guard applied to the docs UI + JSON spec endpoints. */
286
- middleware: MiddlewareHandler;
287
- /** Auxiliary routes mounted (unguarded) in the docs directory. */
288
- routes: DocsAuthRoute[];
289
- /** Bare login route name, used to redirect unauthenticated browsers. */
290
- loginName: string;
291
- }
292
- /** Type guard distinguishing a {@link DocsAuthExtension} from a raw middleware. */
293
- declare function isDocsAuthExtension(value: unknown): value is DocsAuthExtension;
294
- /** Options for {@link firebaseDocsAuth}. */
295
- interface FirebaseDocsAuthOptions {
296
- /**
297
- * Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called
298
- * lazily on each request so `initializeApp()` runs first. Must expose
299
- * `verifyIdToken`, `verifySessionCookie`, `createSessionCookie`,
300
- * `revokeRefreshTokens`.
301
- */
302
- getAuth: () => FirebaseAdminAuthLike;
303
- /** Firebase Web API key — required by the JS SDK on the login page. */
304
- apiKey: string;
305
- /** Firebase Auth domain (e.g. `my-project.firebaseapp.com`). */
306
- authDomain: string;
307
- /**
308
- * Transport mode. `"cookie"` (default) gates the docs behind the bundled
309
- * login form + a server-side session cookie. `"both"` additionally accepts a
310
- * `Bearer` ID token (handy to embed the docs in an authenticated iframe).
311
- */
312
- mode?: "cookie" | "both";
313
- /**
314
- * Authorization policy. Return `false` (or throw) to reject, any truthy value
315
- * to allow. Defaults to allowing any verified user. Receives the decoded
316
- * ID-token / session-cookie claims.
317
- */
318
- allow?: (token: DecodedIdTokenLike) => boolean | Promise<boolean>;
319
- /** Providers shown on the login page. Default: `["password", "google"]`. */
320
- providers?: ("password" | "google")[];
321
- /** Login page title. Default: `"Docs sign-in"`. */
322
- title?: string;
323
- /** Session cookie name. Default: `"__docs_session"`. */
324
- cookieName?: string;
325
- /** Session cookie TTL in days. Default: `5` (Firebase max is 14). */
326
- sessionTtlDays?: number;
327
- /** Cookie `Secure` flag. Default: `true` (set `false` only for local HTTP). */
328
- secureCookie?: boolean;
329
- /** Cookie `SameSite`. Default: `"Lax"`. */
330
- sameSite?: "Strict" | "Lax" | "None";
331
- /**
332
- * Context key under which the decoded token is stored (`c.set(key, token)`)
333
- * for downstream handlers. Default: `"docsUser"`.
334
- */
335
- contextKey?: string;
336
- /**
337
- * Behaviour when authentication fails. `"redirect"` (default) sends browser
338
- * `GET`s to the login page; `"401"` always returns a JSON 401.
339
- */
340
- onUnauthenticated?: "redirect" | "401";
341
- /**
342
- * Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login
343
- * page's client SDK targets the emulator via `connectAuthEmulator`, matching
344
- * the Admin SDK (which already routes to the emulator when
345
- * `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var; pass `""`
346
- * to force it off.
347
- */
348
- authEmulatorHost?: string;
349
- }
350
- /**
351
- * Guard the docs / spec endpoints with a Firebase **login form + session
352
- * cookie**, the same flow as the admin server — instead of forcing callers to
353
- * craft a `Bearer` token by hand.
354
- *
355
- * Returns a {@link DocsAuthExtension}: pass it straight to
356
- * `OpenAPIConfig.docsAuth`. The {@link HonoServer} mounts the bundled
357
- * `__login` / `__session` / `__logout` routes next to the docs and applies the
358
- * guard. Unauthenticated browsers are redirected to the login page; once signed
359
- * in, an HttpOnly session cookie keeps them authenticated.
360
- *
361
- * @example
362
- * ```ts
363
- * import { getAuth } from "firebase-admin/auth";
364
- * import { firebaseDocsAuth } from "@lpdjs/firestore-repo-service/servers/hono";
365
- *
366
- * openapi: {
367
- * info,
368
- * docsAuth: firebaseDocsAuth({
369
- * getAuth: () => getAuth(),
370
- * apiKey: process.env.FIREBASE_API_KEY!,
371
- * authDomain: process.env.FIREBASE_AUTH_DOMAIN!,
372
- * allow: (t) => t.admin === true, // optional policy
373
- * }),
374
- * }
375
- * ```
376
- */
377
- declare function firebaseDocsAuth(options: FirebaseDocsAuthOptions): DocsAuthExtension;
378
-
379
- /**
380
- * Public types for the Hono file-based API server.
381
- *
382
- * Designed to be:
383
- * - **fully typed** end-to-end (Zod input/output → handler payload type),
384
- * - **runtime-safe** via Zod parsing on every request,
385
- * - **bundle-friendly** for Firebase Cloud Functions v2 cold-start (codegen
386
- * emits static imports — no `fs`/`import()` at runtime).
387
- */
388
-
389
- type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
390
- /** Where the validated payload comes from. */
391
- type PayloadSource = "json" | "query" | "form" | "param";
392
- /**
393
- * Structured logger injected into every handler / interceptor / error-handler
394
- * context. Implement it, or extend the package's `BaseLogger` and override its
395
- * `write` hook to route to your sink (Firebase logger, pino, …).
396
- *
397
- * `error()` returns a correlation id so the same value can be both logged and
398
- * returned to the client.
399
- */
400
- interface Logger {
401
- info(message: string, meta?: unknown): void;
402
- warn(message: string, meta?: unknown): void;
403
- /** @returns a correlation id (e.g. to include in the HTTP error response). */
404
- error(error: unknown, meta?: unknown): string;
405
- debug(message: string, meta?: unknown): void;
406
- }
407
- /** Context passed to {@link ErrorHandler.handle}. */
408
- interface ErrorHandlerContext<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> {
409
- /** The thrown value (an `AppError`, a Zod {@link ValidationError}, …). */
410
- error: unknown;
411
- /** Hono request context — set status, read headers, build the response. */
412
- c: Context<TEnv>;
413
- /** Route metadata (read-only). */
414
- route: AnyRouteDef;
415
- /** Global DI services container. */
416
- services: TServices;
417
- /** Injected {@link Logger} when one was passed to the API, else `undefined`. */
418
- logger?: Logger;
419
- }
420
- /**
421
- * Cross-cutting error strategy — a class (or object) you pass to the API and
422
- * that the server injects everywhere **and** applies automatically.
423
- *
424
- * Implement {@link ErrorHandler.handle} to map any thrown value to an HTTP
425
- * `Response` (e.g. your `AppError` → status + localized body, plus structured
426
- * logging with a correlation id). Return `null` to decline the error and let
427
- * the built-in fallback (`ValidationError` envelope) / `onError` take over.
428
- *
429
- * Prefer extending the package's {@link BaseErrorHandler} (it already maps the
430
- * built-in errors) and overriding its `mapError` / `logError` hooks. Pass it
431
- * **per API** via `ApiConfig.errorHandler`, or once via the registry
432
- * (`{ services, errorHandler }`); it is then available in every handler /
433
- * interceptor context as `errorHandler` and auto-applied on any uncaught error.
434
- */
435
- interface ErrorHandler<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> {
436
- handle(ctx: ErrorHandlerContext<TEnv, TServices>): Response | null | Promise<Response | null>;
437
- }
438
- /** Handler signature — receives a single typed context object. */
439
- type RouteHandler<TIn, TOut, TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> = (ctx: {
440
- /** Validated (and typed) request payload. `void` when no `input` schema is defined. */
441
- input: TIn;
442
- /** Raw Hono `Context` for headers, set status, redirect, etc. */
443
- c: Context<TEnv>;
444
- /**
445
- * Global DI services container — same instance shared by every handler.
446
- * Empty `ServicesContainer` when the server was started without a
447
- * `services` option.
448
- */
449
- services: TServices;
450
- /**
451
- * Injected {@link ErrorHandler} when one was passed to the API, else
452
- * `undefined`. Usually you just `throw` and let it apply automatically.
453
- */
454
- errorHandler?: ErrorHandler<TEnv, TServices>;
455
- /** Injected {@link Logger} when one was passed to the API, else `undefined`. */
456
- logger?: Logger;
457
- }) => Promise<TOut | Response> | TOut | Response;
458
- /**
459
- * One route declaration. Default-exported by every `routes.ts` file inside the
460
- * domain tree. Use {@link defineRoute} for full type inference.
461
- */
462
- interface RouteDef<TIn extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined, TOut extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined, TEnv extends Env = Env> {
463
- /**
464
- * Logical API tag — routes sharing the same `api` are mounted on the same
465
- * `HonoServer` (typically one Cloud Function per `api`).
466
- *
467
- * To expose the **same logic** under several APIs with different
468
- * inputs/outputs, export multiple `defineRoute({...})` from the same file
469
- * (default + named exports are both picked up by the codegen).
470
- */
471
- api: string;
472
- /** HTTP method. */
473
- method: HttpMethod;
474
- /**
475
- * URL path appended to the server `basePath`. If omitted, the codegen will
476
- * derive it from the file location (e.g. `domains/activities/useCases/createCustom/routes.ts`
477
- * → `/activities/createCustom`).
478
- */
479
- path?: string;
480
- /**
481
- * Where the request payload comes from.
482
- * Default: `"json"` for body methods (POST/PUT/PATCH/DELETE), `"query"` for GET.
483
- */
484
- source?: PayloadSource;
485
- /** Zod schema validating the payload. Failures yield a 400 response. */
486
- input?: TIn;
487
- /**
488
- * Zod schema for the success response. Used to populate the OpenAPI spec
489
- * and (when `validateOutput` is enabled on the server) to assert the
490
- * runtime payload returned by the handler.
491
- */
492
- output?: TOut;
493
- /** Status code for the success response. Default: 200. */
494
- status?: number;
495
- /** Hono middlewares applied to this route only (after global middlewares). */
496
- middlewares?: MiddlewareHandler<TEnv>[];
497
- summary?: string;
498
- description?: string;
499
- tags?: string[];
500
- /** Mark the operation as deprecated in the generated spec. */
501
- deprecated?: boolean;
502
- /** Security requirements (operationId-level override). */
503
- security?: SecurityRequirement[];
504
- /** The request handler. */
505
- handler: RouteHandler<TIn extends z.ZodTypeAny ? z.infer<TIn> : void, TOut extends z.ZodTypeAny ? z.infer<TOut> : unknown, TEnv>;
506
- }
507
- /** Erased `RouteDef` used by registry/codegen — handler signature is opaque. */
508
- type AnyRouteDef = RouteDef<any, any>;
509
- /**
510
- * What `routes.ts` can default-export:
511
- * - a single {@link RouteDef} (most common case),
512
- * - or an array of {@link RouteDef} (e.g. expose the same useCase on
513
- * multiple `api` tags or under multiple paths). `readonly` arrays are
514
- * accepted so that tuple-preserving helpers like {@link defineRoutes} (or a
515
- * plain `as const` array) can be default-exported directly.
516
- */
517
- type RouteModuleDefault = AnyRouteDef | readonly AnyRouteDef[];
518
- /**
519
- * Identity helper that **preserves the tuple type** of a `routes.ts` default
520
- * export. A plain array literal (`export default [a, b]`) collapses every
521
- * element to a single common type, which would lose each route's individual
522
- * schema. Wrapping the array with `defineRoutes([...])` keeps the per-route
523
- * types intact so {@link RouteInput} / {@link RouteOutput} can aggregate them
524
- * into a union.
525
- *
526
- * @example
527
- * export default defineRoutes([
528
- * defineRoute({ ... }),
529
- * defineRoute({ ... }),
530
- * ]);
531
- */
532
- declare function defineRoutes<const T extends readonly AnyRouteDef[]>(routes: T): T;
533
- /**
534
- * Normalizes a `routes.ts` default export — a single {@link RouteDef} or an
535
- * array of them — to a *union* of its individual route members.
536
- */
537
- type RoutesUnion<T> = T extends readonly (infer R)[] ? R : T;
538
- type InferRouteInput<R> = R extends {
539
- input?: infer I;
540
- } ? I extends z.ZodTypeAny ? z.infer<I> : void : void;
541
- type InferRouteOutput<R> = R extends {
542
- output?: infer O;
543
- } ? O extends z.ZodTypeAny ? z.infer<O> : unknown : unknown;
544
- /**
545
- * Union of validated request payloads across every route in a `routes.ts`
546
- * module. Use it to type a useCase input without duplicating the Zod schema:
547
- *
548
- * @example
549
- * type Routes = typeof import("./routes.js").default;
550
- * export type CreatePostUseCaseInput = RouteInput<Routes>;
551
- */
552
- type RouteInput<T> = InferRouteInput<RoutesUnion<T>>;
553
- /**
554
- * Union of success-response payloads across every route in a `routes.ts`
555
- * module. Mirror of {@link RouteInput} for the useCase output type.
556
- */
557
- type RouteOutput<T> = InferRouteOutput<RoutesUnion<T>>;
558
- /**
559
- * Thrown by the server when the incoming request fails Zod validation.
560
- * Caught by the {@link RouteInterceptor} (if any) so users can shape the
561
- * response envelope however they like; otherwise yields a default 400.
562
- */
563
- declare class ValidationError extends Error {
564
- /** Original Zod error — `error.issues` to enumerate field-level problems. */
565
- readonly zodError: ZodError;
566
- /** Where the offending payload came from. */
567
- readonly source: PayloadSource;
568
- readonly statusCode: 400;
569
- constructor(
570
- /** Original Zod error — `error.issues` to enumerate field-level problems. */
571
- zodError: ZodError,
572
- /** Where the offending payload came from. */
573
- source: PayloadSource);
574
- }
575
- /**
576
- * Cross-cutting interceptor applied around every handler.
577
- * Use it for response envelopes, business-error → HTTP mapping, structured
578
- * logging, tracing spans, etc.
579
- *
580
- * Wrap `next()` in `try/catch` to intercept BOTH Zod {@link ValidationError}s
581
- * (thrown before the handler runs) AND business errors thrown by the handler.
582
- *
583
- * @example
584
- * ```ts
585
- * interceptor: async ({ next, route, c }) => {
586
- * try {
587
- * const data = await next();
588
- * return c.json({ success: true, data, error: null });
589
- * } catch (err) {
590
- * if (err instanceof ValidationError) {
591
- * return c.json({ success: false, error: "validation", issues: err.zodError.issues }, 400);
592
- * }
593
- * if (err instanceof DomainError) {
594
- * return c.json({ success: false, error: err.code }, err.statusCode);
595
- * }
596
- * throw err; // → falls back to onError or Hono's default 500
597
- * }
598
- * }
599
- * ```
600
- */
601
- type RouteInterceptor<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> = (ctx: {
602
- /**
603
- * Calls validation + handler and returns the raw value.
604
- * Throws {@link ValidationError} on Zod failure or any error thrown by the handler.
605
- */
606
- next: () => Promise<unknown>;
607
- /** Route metadata (read-only). */
608
- route: AnyRouteDef;
609
- /** Hono request context. */
610
- c: Context<TEnv>;
611
- /** Global DI services container. See {@link RouteHandler}. */
612
- services: TServices;
613
- /**
614
- * Injected {@link ErrorHandler} when one was passed to the API. Call
615
- * `errorHandler?.handle({ error, c, route, services })` in your `catch` to
616
- * reuse the shared mapping, or simply rethrow to let it apply automatically.
617
- */
618
- errorHandler?: ErrorHandler<TEnv, TServices>;
619
- /** Injected {@link Logger} when one was passed to the API, else `undefined`. */
620
- logger?: Logger;
621
- }) => Promise<Response | unknown> | Response | unknown;
622
- /**
623
- * Success-envelope schema declared alongside an interceptor so the generated
624
- * OpenAPI spec documents what the **wrapper actually returns** (not the raw
625
- * handler output).
626
- *
627
- * - a **static** Zod schema → same envelope for every route (e.g.
628
- * `z.object({ data: z.any(), intercepted: z.boolean() })`);
629
- * - a **factory** `(routeOutput) => schema` → wraps each route's own `output`,
630
- * so `data` is typed per endpoint in the docs.
631
- */
632
- type InterceptorOutput = z.ZodTypeAny | ((routeOutput: z.ZodTypeAny | undefined) => z.ZodTypeAny);
633
- /** A single declared error response for the OpenAPI spec. */
634
- type InterceptorErrorResponse = z.ZodTypeAny | {
635
- description?: string;
636
- schema?: z.ZodTypeAny;
637
- };
638
- /**
639
- * Structured interceptor — pairs the cross-cutting {@link RouteInterceptor}
640
- * `handler` with the OpenAPI metadata describing what it returns, so the docs
641
- * reflect the real wrapped responses (success envelope + error shapes).
642
- *
643
- * @example
644
- * ```ts
645
- * interceptor: {
646
- * // factory: `data` reflects each route's own output schema
647
- * output: (routeOutput) =>
648
- * z.object({ data: routeOutput ?? z.unknown(), intercepted: z.boolean() }),
649
- * errors: {
650
- * 400: ValidationErrorSchema,
651
- * 500: { description: "Internal", schema: ErrorSchema },
652
- * },
653
- * handler: async ({ c, next }) => {
654
- * const data = await next();
655
- * return c.json({ data, intercepted: true });
656
- * },
657
- * }
658
- * ```
659
- */
660
- interface InterceptorConfig<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> {
661
- /** Success-envelope schema (static) or per-route factory. */
662
- output?: InterceptorOutput;
663
- /**
664
- * Error responses applied to **every** operation, keyed by HTTP status. Pass
665
- * a bare Zod schema or `{ description, schema }`.
666
- */
667
- errors?: Record<number, InterceptorErrorResponse>;
668
- /** The interceptor function. See {@link RouteInterceptor}. */
669
- handler: RouteInterceptor<TEnv, TServices>;
670
- }
671
- /**
672
- * Interceptor option accepted by the server / registry — either a bare
673
- * {@link RouteInterceptor} function (legacy) or a structured
674
- * {@link InterceptorConfig} carrying OpenAPI metadata.
675
- */
676
- type InterceptorOption<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> = RouteInterceptor<TEnv, TServices> | InterceptorConfig<TEnv, TServices>;
677
- /** OpenAPI document info (subset of the spec used by the helper). */
678
- interface OpenAPIInfo {
679
- title: string;
680
- version: string;
681
- description?: string;
682
- }
683
- /** Fields shared by every security scheme. */
684
- interface SecuritySchemeBase {
685
- /** Human-readable description (CommonMark). */
686
- description?: string;
687
- }
688
- /** API key carried in a header, query param or cookie. */
689
- interface ApiKeySecurityScheme extends SecuritySchemeBase {
690
- type: "apiKey";
691
- /** Name of the header, query parameter or cookie. */
692
- name: string;
693
- /** Location of the API key. */
694
- in: "query" | "header" | "cookie";
695
- }
696
- /**
697
- * HTTP authentication (RFC 7235), e.g. `bearer` (Firebase ID tokens) or
698
- * `basic`.
699
- */
700
- interface HttpSecurityScheme extends SecuritySchemeBase {
701
- type: "http";
702
- /** Auth scheme name — `"bearer"`, `"basic"`, `"digest"`, … */
703
- scheme: "bearer" | "basic" | "digest" | (string & {});
704
- /** Hint for the bearer token format, e.g. `"JWT"` / `"Firebase JWT"`. */
705
- bearerFormat?: string;
706
- }
707
- /** Mutual TLS authentication. */
708
- interface MutualTlsSecurityScheme extends SecuritySchemeBase {
709
- type: "mutualTLS";
710
- }
711
- /** A single OAuth2 flow. */
712
- interface OAuthFlowObject {
713
- authorizationUrl?: string;
714
- tokenUrl?: string;
715
- refreshUrl?: string;
716
- /** Available scopes → description. */
717
- scopes: Record<string, string>;
718
- }
719
- /** The OAuth2 flows supported by an {@link OAuth2SecurityScheme}. */
720
- interface OAuthFlowsObject {
721
- implicit?: OAuthFlowObject;
722
- password?: OAuthFlowObject;
723
- clientCredentials?: OAuthFlowObject;
724
- authorizationCode?: OAuthFlowObject;
725
- }
726
- /** OAuth2 authentication. */
727
- interface OAuth2SecurityScheme extends SecuritySchemeBase {
728
- type: "oauth2";
729
- flows: OAuthFlowsObject;
730
- }
731
- /** OpenID Connect Discovery. */
732
- interface OpenIdConnectSecurityScheme extends SecuritySchemeBase {
733
- type: "openIdConnect";
734
- openIdConnectUrl: string;
735
- }
736
- /** OpenAPI 3.1 Security Scheme Object (discriminated on `type`). */
737
- type SecurityScheme = ApiKeySecurityScheme | HttpSecurityScheme | MutualTlsSecurityScheme | OAuth2SecurityScheme | OpenIdConnectSecurityScheme;
738
- /**
739
- * A single Security Requirement Object: maps a scheme name (a key of
740
- * {@link OpenAPIConfig.securitySchemes}) to the list of required scopes
741
- * (empty `[]` for `http` / `apiKey`).
742
- */
743
- type SecurityRequirement = Record<string, string[]>;
744
- /** OpenAPI configuration on the server. */
745
- interface OpenAPIConfig {
746
- /** Path served by the JSON spec (e.g. `/openapi.json`). Default: `/openapi.json`. */
747
- path?: string;
748
- /** Path serving the documentation UI. Set to `false` to disable. Default: `/docs`. */
749
- docsPath?: string | false;
750
- /** OpenAPI document info. */
751
- info: OpenAPIInfo;
752
- /** Optional servers list for the spec. */
753
- servers?: {
754
- url: string;
755
- description?: string;
756
- }[];
757
- /**
758
- * Reusable security schemes, keyed by name. The keys are referenced from
759
- * {@link OpenAPIConfig.security} / per-route `security`.
760
- *
761
- * @example
762
- * ```ts
763
- * securitySchemes: {
764
- * bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "Firebase JWT" },
765
- * }
766
- * ```
767
- */
768
- securitySchemes?: Record<string, SecurityScheme>;
769
- /**
770
- * Default security requirement applied to every operation. Each entry maps a
771
- * scheme name (a key of {@link OpenAPIConfig.securitySchemes}) to its scopes.
772
- *
773
- * @example `security: [{ bearerAuth: [] }]`
774
- */
775
- security?: SecurityRequirement[];
776
- /**
777
- * Hono middleware(s) guarding **only** the docs UI and JSON spec endpoints
778
- * (not the API routes). Use a raw middleware for a custom flow, or the
779
- * built-in {@link firebaseBearerAuth} / {@link basicAuth} helpers.
780
- *
781
- * @example
782
- * ```ts
783
- * import { firebaseBearerAuth } from "@lpdjs/firestore-repo-service/servers/hono";
784
- * openapi: { info, docsAuth: firebaseBearerAuth({ getAuth }) }
785
- * ```
786
- *
787
- * For a full login form + session cookie (like the admin server), pass the
788
- * {@link DocsAuthExtension} returned by `firebaseDocsAuth({ ... })` instead.
789
- */
790
- docsAuth?: MiddlewareHandler | MiddlewareHandler[] | DocsAuthExtension;
791
- }
792
- /** Options consumed by the {@link HonoServer} constructor. */
793
- interface HonoServerOptions<TEnv extends Env = Env> {
794
- /**
795
- * API tag — only routes whose `api` matches this value are mounted.
796
- * If omitted, every route in the registry is mounted.
797
- */
798
- api?: string;
799
- /** Pre-resolved route registry (typically the codegen output). */
800
- routes: AnyRouteDef[];
801
- /** URL prefix mounted before every route path. Default: `""`. */
802
- basePath?: string;
803
- /** Hono middlewares applied to every route (after the built-ins). */
804
- middlewares?: MiddlewareHandler<TEnv>[];
805
- /**
806
- * Alias for `middlewares` — global middlewares applied to every route.
807
- * If both are provided, `globalMiddlewares` is appended after `middlewares`.
808
- */
809
- globalMiddlewares?: MiddlewareHandler<TEnv>[];
810
- /**
811
- * If `true`, the server validates the value returned by every handler
812
- * against the route's `output` schema and rejects mismatches with a 500
813
- * response. Useful in dev / staging. Default: `false`.
814
- */
815
- validateOutput?: boolean;
816
- /** Enable verbose logging of mounted routes at startup. Default: `false`. */
817
- verbose?: boolean;
818
- /** OpenAPI configuration. Omit to disable. */
819
- openapi?: OpenAPIConfig;
820
- /** Custom 404 handler. */
821
- notFound?: (c: Context<TEnv>) => Response | Promise<Response>;
822
- /** Custom error handler. */
823
- onError?: (err: unknown, c: Context<TEnv>) => Response | Promise<Response>;
824
- /**
825
- * Cross-cutting interceptor wrapping every handler call.
826
- * Ideal for response envelopes, business-error mapping, tracing.
827
- *
828
- * Pass a bare {@link RouteInterceptor} function, or an
829
- * {@link InterceptorConfig} (`{ output?, errors?, handler }`) so the
830
- * generated OpenAPI spec documents the wrapped responses.
831
- */
832
- interceptor?: InterceptorOption<TEnv>;
833
- /**
834
- * Cross-cutting error strategy applied to every uncaught error and injected
835
- * into every handler / interceptor context. See {@link ErrorHandler}.
836
- *
837
- * Typically shared across APIs — pass it once to `createApiRegistry` via
838
- * `{ services, errorHandler }`; this per-API field overrides it.
839
- */
840
- errorHandler?: ErrorHandler<TEnv>;
841
- /**
842
- * Structured {@link Logger} injected into every handler / interceptor /
843
- * error-handler context. Extend the package's `BaseLogger` to route to your
844
- * sink. Typically shared via `createApiRegistry({ services, logger })`; this
845
- * per-API field overrides it.
846
- */
847
- logger?: Logger;
848
- /**
849
- * Global DI services container (see {@link createServices}).
850
- *
851
- * When provided:
852
- * - a middleware is installed automatically so the built-in `ctx`
853
- * service resolves to the current request via `AsyncLocalStorage`;
854
- * - `services` is passed into every handler and the interceptor.
855
- *
856
- * The same container instance should be shared across every API of your
857
- * project — declare it once and pass it to {@link createApiRegistry}.
858
- */
859
- services?: AnyServicesContainer;
860
- }
7
+ import '../../firebase-auth-DZ8lb2Ec.js';
861
8
 
862
9
  /**
863
10
  * `HonoServer` — high-performance, fully-typed file-based API server for
@@ -1497,4 +644,4 @@ declare function generateRoutesManifest(routes: ScannedRoute[], opts: GeneratorO
1497
644
  /** Convenience helper used by the CLI — combines scan + generate in one call. */
1498
645
  declare function generateFromRoot(rootAbs: string, outFileRel: string, derive: PathDeriveOptions, importExtension: string, scan: (root: string) => ScannedRoute[]): GenerationResult;
1499
646
 
1500
- export { type AnyRouteDef, type AnyServicesContainer, type ApiConfig, type ApiConfigMap, type ApiKeySecurityScheme, type ApiRegistry, type ApiRegistryOptions, BadRequestError, BaseErrorHandler, type BaseErrorHandlerOptions, BaseLogger, type BasicAuthOptions, DEFAULT_DERIVE, DEFAULT_GENERATOR_BANNER, DEFAULT_SCANNER, type DecodedBearerToken, type DocsAuthExtension, type DocsAuthRoute, type ErrorHandler, type ErrorHandlerContext, type FirebaseBearerAuthLike, type FirebaseBearerAuthOptions, type FirebaseDocsAuthOptions, type GcpLogsLinkOptions, type GenerationResult, type GeneratorOptions, HonoServer, type HonoServerOptions, type HttpMethod, type HttpSecurityScheme, type InterceptorConfig, type InterceptorErrorResponse, type InterceptorOption, type InterceptorOutput, type LogSeverity, type Logger, type MutualTlsSecurityScheme, type OAuth2SecurityScheme, type OAuthFlowObject, type OAuthFlowsObject, type OpenAPIConfig, type OpenAPIInfo, type OpenIdConnectSecurityScheme, OutputValidationError, type PathDeriveOptions, type PayloadSource, type RequestContext, type RouteDef, type RouteHandler, type RouteInput, type RouteInterceptor, type RouteModuleDefault, type RouteOutput, type RoutesUnion, type ScannedRoute, type ScannerOptions, type SecurityRequirement, type SecurityScheme, type SecuritySchemeBase, type ServiceProvider, type ServiceProviderMap, type ServicesContainer, type ServicesOf, UseCase, type UseCaseClass, type UseCaseRouteMeta, ValidationError, basicAuth, buildOpenApiDocument, createApiRegistry, createRequestContextMiddleware, createServices, defaultErrorResponse, defineRoutes, derivePath, firebaseBearerAuth, firebaseDocsAuth, gcpLogsUrl, generateFromRoot, generateRoutesManifest, isDocsAuthExtension, renderDocsHtml, resolveGcpProjectId, scanRoutes, toImportSpecifier, useCaseRoute, withRequestContext };
647
+ export { AnyRouteDef, AnyServicesContainer, type ApiConfig, type ApiConfigMap, type ApiRegistry, type ApiRegistryOptions, BadRequestError, BaseErrorHandler, type BaseErrorHandlerOptions, BaseLogger, DEFAULT_DERIVE, DEFAULT_GENERATOR_BANNER, DEFAULT_SCANNER, ErrorHandler, ErrorHandlerContext, type GcpLogsLinkOptions, type GenerationResult, type GeneratorOptions, HonoServer, HonoServerOptions, HttpMethod, InterceptorConfig, type LogSeverity, Logger, OpenAPIConfig, OutputValidationError, type PathDeriveOptions, PayloadSource, RouteDef, RouteHandler, type ScannedRoute, type ScannerOptions, UseCase, type UseCaseClass, type UseCaseRouteMeta, buildOpenApiDocument, createApiRegistry, defaultErrorResponse, derivePath, gcpLogsUrl, generateFromRoot, generateRoutesManifest, renderDocsHtml, resolveGcpProjectId, scanRoutes, toImportSpecifier, useCaseRoute };