@forinda/kickjs 9.0.3 → 9.1.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.
- package/dist/{application-DPLzamTb.mjs → application-nDj-76EX.mjs} +3 -3
- package/dist/{application-DPLzamTb.mjs.map → application-nDj-76EX.mjs.map} +1 -1
- package/dist/{bootstrap-DUNvDJ1a.mjs → bootstrap-BqcT1h9H.mjs} +3 -3
- package/dist/{bootstrap-DUNvDJ1a.mjs.map → bootstrap-BqcT1h9H.mjs.map} +1 -1
- package/dist/{client-ip-CTr33Gtu.mjs → client-ip-DMKc-Trg.mjs} +2 -2
- package/dist/{client-ip-CTr33Gtu.mjs.map → client-ip-DMKc-Trg.mjs.map} +1 -1
- package/dist/config/index.mjs +2 -2
- package/dist/{config-C-sAHakM.mjs → config-DrgIbebd.mjs} +3 -3
- package/dist/{config-C-sAHakM.mjs.map → config-DrgIbebd.mjs.map} +1 -1
- package/dist/{container-ByH0uCpG.mjs → container-ZnfelY_a.mjs} +3 -3
- package/dist/{container-ByH0uCpG.mjs.map → container-ZnfelY_a.mjs.map} +1 -1
- package/dist/{context-fth87C3G.mjs → context-BGPof8bs.mjs} +3 -3
- package/dist/{context-fth87C3G.mjs.map → context-BGPof8bs.mjs.map} +1 -1
- package/dist/{context-errors-VjQBtxEc.mjs → context-errors-Cgtrrqfs.mjs} +2 -2
- package/dist/{context-errors-VjQBtxEc.mjs.map → context-errors-Cgtrrqfs.mjs.map} +1 -1
- package/dist/{contributor-runner-BEjgGaoG.mjs → contributor-runner-BSpshfPN.mjs} +3 -3
- package/dist/{contributor-runner-BEjgGaoG.mjs.map → contributor-runner-BSpshfPN.mjs.map} +1 -1
- package/dist/core/adapter.mjs +1 -1
- package/dist/core/app-module.mjs +1 -1
- package/dist/core/cache.mjs +1 -1
- package/dist/core/container.mjs +2 -2
- package/dist/core/cron.mjs +2 -2
- package/dist/core/decorators.mjs +2 -2
- package/dist/core/errors.mjs +1 -1
- package/dist/core/interfaces.mjs +1 -1
- package/dist/core/logger.d.mts +2 -2
- package/dist/core/logger.mjs +2 -2
- package/dist/core/logger.mjs.map +1 -1
- package/dist/core/path.mjs +1 -1
- package/dist/core/plugin.mjs +1 -1
- package/dist/core/reactivity.mjs +1 -1
- package/dist/{core-DrjVUTxG.mjs → core-_WNyghl_.mjs} +3 -3
- package/dist/{core-DrjVUTxG.mjs.map → core-_WNyghl_.mjs.map} +1 -1
- package/dist/{csrf-CbFJiyKW.mjs → csrf-BcxqzCZW.mjs} +3 -3
- package/dist/{csrf-CbFJiyKW.mjs.map → csrf-BcxqzCZW.mjs.map} +1 -1
- package/dist/{decorate-hW_esogS.mjs → decorate-BBwu7--P.mjs} +1 -1
- package/dist/{define-adapter-B4Iu_TcU.mjs → define-adapter-CajLeMzM.mjs} +2 -2
- package/dist/{define-adapter-B4Iu_TcU.mjs.map → define-adapter-CajLeMzM.mjs.map} +1 -1
- package/dist/{disposables-CgCLyCoP.mjs → disposables-DIXt8ze-.mjs} +2 -2
- package/dist/{disposables-CgCLyCoP.mjs.map → disposables-DIXt8ze-.mjs.map} +1 -1
- package/dist/{env-w27RDkCQ.mjs → env-DtJ-6gyL.mjs} +3 -3
- package/dist/{env-w27RDkCQ.mjs.map → env-DtJ-6gyL.mjs.map} +1 -1
- package/dist/{handler-eguNTfCv.mjs → handler-2OebsoPr.mjs} +3 -3
- package/dist/{handler-eguNTfCv.mjs.map → handler-2OebsoPr.mjs.map} +1 -1
- package/dist/http/application.mjs +2 -2
- package/dist/http/bootstrap.mjs +2 -2
- package/dist/http/context.mjs +2 -2
- package/dist/http/middleware/cors.mjs +1 -1
- package/dist/http/middleware/csrf.mjs +2 -2
- package/dist/http/middleware/error-handler.mjs +2 -2
- package/dist/http/middleware/helmet.mjs +1 -1
- package/dist/http/middleware/rate-limit.mjs +2 -2
- package/dist/http/middleware/request-id.mjs +1 -1
- package/dist/http/middleware/request-logger.mjs +2 -2
- package/dist/http/middleware/request-logger.mjs.map +1 -1
- package/dist/http/middleware/session.mjs +2 -2
- package/dist/http/middleware/spa.mjs +2 -2
- package/dist/http/middleware/upload.mjs +2 -2
- package/dist/http/middleware/validate.mjs +1 -1
- package/dist/http/middleware/views.mjs +2 -2
- package/dist/http/query/index.mjs +2 -2
- package/dist/http/router-builder.mjs +2 -2
- package/dist/http/runtimes/fastify.mjs +2 -2
- package/dist/http/runtimes/h3-web.mjs +2 -2
- package/dist/http/runtimes/h3.mjs +2 -2
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{jobs-CeP4aLYR.mjs → jobs-dx-MTUUb.mjs} +3 -3
- package/dist/{jobs-CeP4aLYR.mjs.map → jobs-dx-MTUUb.mjs.map} +1 -1
- package/dist/{kv-stores-5ocdxfdh.mjs → kv-stores-Ba5_rcz-.mjs} +3 -3
- package/dist/{kv-stores-5ocdxfdh.mjs.map → kv-stores-Ba5_rcz-.mjs.map} +1 -1
- package/dist/{logger-DA43DvNY.d.mts → logger-xE9qI_FS.d.mts} +45 -5
- package/dist/logger-xE9qI_FS.d.mts.map +1 -0
- package/dist/{metadata-CIXErBTj.mjs → metadata-CW4I35nN.mjs} +2 -2
- package/dist/{metadata-CIXErBTj.mjs.map → metadata-CW4I35nN.mjs.map} +1 -1
- package/dist/{module-registry-IO8RfVjX.mjs → module-registry-kqozOSo0.mjs} +2 -2
- package/dist/{module-registry-IO8RfVjX.mjs.map → module-registry-kqozOSo0.mjs.map} +1 -1
- package/dist/{observers-BtXkP5km.mjs → observers-CC3sO1BM.mjs} +2 -2
- package/dist/{observers-BtXkP5km.mjs.map → observers-CC3sO1BM.mjs.map} +1 -1
- package/dist/{query-CNa0mxSK.mjs → query-DPlkWOw6.mjs} +2 -2
- package/dist/{query-CNa0mxSK.mjs.map → query-DPlkWOw6.mjs.map} +1 -1
- package/dist/{respond-C4Vt5r46.mjs → respond-DjxNwGnN.mjs} +2 -2
- package/dist/{respond-C4Vt5r46.mjs.map → respond-DjxNwGnN.mjs.map} +1 -1
- package/dist/{route-flag-CpTa8y1n.mjs → route-flag-sIYXay3q.mjs} +3 -3
- package/dist/{route-flag-CpTa8y1n.mjs.map → route-flag-sIYXay3q.mjs.map} +1 -1
- package/dist/{route-policy-DPTLfer-.mjs → route-policy-B6_toGJW.mjs} +2 -2
- package/dist/{route-policy-DPTLfer-.mjs.map → route-policy-B6_toGJW.mjs.map} +1 -1
- package/dist/{router-builder-BxXKP8Wy.mjs → router-builder-CzVjPs5y.mjs} +3 -3
- package/dist/{router-builder-BxXKP8Wy.mjs.map → router-builder-CzVjPs5y.mjs.map} +1 -1
- package/dist/{runtime-B4NQGN66.mjs → runtime-CDz5ayBt.mjs} +3 -3
- package/dist/{runtime-B4NQGN66.mjs.map → runtime-CDz5ayBt.mjs.map} +1 -1
- package/dist/{upload-config-BmpmZZVK.mjs → upload-config-d0pisVsK.mjs} +2 -2
- package/dist/{upload-config-BmpmZZVK.mjs.map → upload-config-d0pisVsK.mjs.map} +1 -1
- package/dist/web.mjs +2 -2
- package/package.json +2 -2
- package/dist/logger-DA43DvNY.d.mts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kv-stores-5ocdxfdh.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/** Timer-free in-memory store: sweeps expired entries when the map grows. */\nclass LazyMemoryStore implements RateLimitStore {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n\n constructor(private readonly windowMs: number) {}\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n // ponytail: sweep-on-growth instead of a cleanup interval — no timer to\n // dispose, edge-safe. Bound is 10k live keys before a full sweep.\n if (this.hits.size > 10_000) {\n for (const [k, e] of this.hits) if (e.reset <= now) this.hits.delete(k)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.hits.get(key)\n if (entry && entry.hits > 0) entry.hits--\n }\n\n async reset(key: string): Promise<void> {\n this.hits.delete(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;gFAuEA,IAAM,gBAAN,KAAgD,CAGjB,SAF7B,KAAwB,IAAI,IAE5B,YAAY,SAAmC,CAAlB,KAAA,SAAA,QAAmB,CAEhD,MAAM,UAAU,IAA8D,CAC5E,IAAM,IAAM,KAAK,IAAI,EACf,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC/B,GAAI,OAAS,MAAM,MAAQ,IAEzB,MADA,OAAM,OACC,CAAE,UAAW,MAAM,KAAM,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,EAInE,GAAI,KAAK,KAAK,KAAO,IACd,IAAA,GAAM,CAAC,EAAG,KAAM,KAAK,KAAU,EAAE,OAAS,KAAK,KAAK,KAAK,OAAO,CAAC,EAExE,IAAM,MAAQ,CAAE,KAAM,EAAG,MAAO,IAAM,KAAK,QAAS,EAEpD,OADA,KAAK,KAAK,IAAI,IAAK,KAAK,EACjB,CAAE,UAAW,EAA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AG,CAC1D,cAAe,aAAa,KAAK,IAAI,MAAM,MAAQ,KAAK,IAAI,EAAG,GAAI,CAAC,CACtE,CAAC,CACH,CACF,EAiBa,eAAb,KAAoD,CAI/B,GAHnB,OAEA,YACE,GACA,QAAiC,CAAC,EAClC,CAFiB,KAAA,GAAA,GAGjB,KAAK,OAAS,QAAQ,QAAU,OAClC,CAEA,MAAM,IAAI,IAA0C,CAClD,IAAM,IAAM,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,GAAG,EAC/C,GAAI,MAAQ,KAAM,OAAO,KACzB,GAAI,CACF,OAAO,KAAK,MAAM,GAAG,CACvB,MAAQ,CACN,OAAO,IACT,CACF,CAEA,MAAM,IAAI,IAAa,KAAmB,OAA+B,CACvE,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,IAAI,EAAG,CACzD,cAAe,aAAa,MAAM,CACpC,CAAC,CACH,CAEA,MAAM,QAAQ,IAA4B,CACxC,MAAM,KAAK,GAAG,OAAO,KAAK,OAAS,GAAG,CACxC,CAEA,MAAM,MAAM,IAAa,OAA+B,CACtD,IAAM,KAAO,MAAM,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,MAAM,KAAK,IAAI,IAAK,KAAM,MAAM,CACrD,CACF"}
|
|
1
|
+
{"version":3,"file":"kv-stores-Ba5_rcz-.mjs","names":[],"sources":["../src/http/middleware/rate-limit-guard.ts","../src/http/middleware/kv-stores.ts"],"sourcesContent":["// Ctx-style rate limiter — runs on BOTH pipelines: the node runtimes (via\n// `@Middleware()` / class middleware) and the `@forinda/kickjs/web` fetch\n// entry (via `@Middleware()` or `createWebApp({ middleware })`), unlike the\n// connect-style `rateLimit()` which is node-only. Zero runtime imports —\n// part of the edge purity graph.\nimport { assertFlagTest, matchesFlagTest, type RouteFlagTest } from '../../core/route-flag'\nimport type { MiddlewareHandler } from '../../core/decorators'\nimport type { RequestContext } from '../context'\nimport type { RateLimitStore } from './rate-limit'\n\nexport interface RateLimitGuardOptions {\n /** Maximum number of requests per window (default: 100). */\n max?: number\n /** Time window in milliseconds (default: 60_000). */\n windowMs?: number\n /** Response message when the limit is exceeded (default: 'Too Many Requests'). */\n message?: string\n /** HTTP status code when the limit is exceeded (default: 429). */\n statusCode?: number\n /**\n * Rate-limit key per request. Defaults to `ctx.ip`, falling back to\n * `'global'`. Return a user/tenant id here for authenticated quotas.\n *\n * ::: warning Behind a proxy, configure `trustProxy` or every client shares\n * one bucket\n * On a node runtime `ctx.ip` is the runtime's vetted client address —\n * Express derives it from `trust proxy`, Fastify from `trustProxy`. Without\n * that setting it is the SOCKET address, which behind a load balancer or\n * Cloudflare is the proxy's, so every caller lands in the same bucket and one\n * noisy client exhausts the allowance for everyone.\n *\n * `bootstrap({ trustProxy: true })` is the fix. Forwarded headers are\n * deliberately not consulted here: `x-forwarded-for` is client-controllable\n * unless a proxy overwrites it, so trusting it unconditionally would let a\n * direct caller mint a fresh allowance per request by varying the header —\n * evading the limit rather than enforcing it. The header chain\n * (`cf-connecting-ip` → `x-forwarded-for` → `x-real-ip`) applies only on the\n * `@forinda/kickjs/web` edge entry, where there is no socket and the platform\n * has already terminated the connection.\n * :::\n */\n keyGenerator?: (ctx: RequestContext) => string\n /** Send `X-RateLimit-*` / `Retry-After` headers (default: true). */\n headers?: boolean\n /**\n * Counter backend. Defaults to a per-isolate in-memory map — fine for a\n * single node process, useless on edge where isolates recycle: pass a\n * `KvRateLimitStore` (or Redis-backed store) there.\n */\n store?: RateLimitStore\n /** Skip limiting for a request (health checks, allowlists). */\n skip?: (ctx: RequestContext) => boolean\n /**\n * Skip limiting on routes carrying a route flag — a name, a list of names\n * (any-of), or a predicate. Declared on the route rather than restated as a\n * path here, so it cannot drift when `apiPrefix` or a module's `version`\n * changes:\n *\n * ```ts\n * const Public = defineRouteFlag('auth.public')\n * rateLimitGuard({ max: 60, exemptWhen: 'auth.public' })\n * ```\n *\n * Only meaningful where a route has been matched — as `@Middleware()` on a\n * class or method, or in `createWebApp({ middleware })`. Mounted app-wide\n * ahead of routing there is no route to read, and nothing is exempted.\n */\n exemptWhen?: RouteFlagTest\n}\n\n/** Timer-free in-memory store: sweeps expired entries when the map grows. */\nclass LazyMemoryStore implements RateLimitStore {\n private readonly hits = new Map<string, { hits: number; reset: number }>()\n\n constructor(private readonly windowMs: number) {}\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = this.hits.get(key)\n if (entry && entry.reset > now) {\n entry.hits++\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n // ponytail: sweep-on-growth instead of a cleanup interval — no timer to\n // dispose, edge-safe. Bound is 10k live keys before a full sweep.\n if (this.hits.size > 10_000) {\n for (const [k, e] of this.hits) if (e.reset <= now) this.hits.delete(k)\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n this.hits.set(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = this.hits.get(key)\n if (entry && entry.hits > 0) entry.hits--\n }\n\n async reset(key: string): Promise<void> {\n this.hits.delete(key)\n }\n}\n\nfunction defaultKey(ctx: RequestContext): string {\n // `ctx.ip` carries the resolution that used to live here: prefer the\n // runtime-computed address (Express derives it from `trust proxy`), fall\n // back to forwarded headers only for runtimes that compute none.\n return ctx.ip ?? 'global'\n}\n\n/**\n * Rate limiting as a `(ctx, next)` middleware.\n *\n * ```ts\n * // Edge (Cloudflare Workers) — app-wide:\n * const app = createWebApp({\n * h3, modules,\n * middlewares: [rateLimitGuard({ max: 60, windowMs: 60_000, store: new KvRateLimitStore(env.KV, { windowMs: 60_000 }) })],\n * })\n *\n * // Any runtime — per controller/route:\n * @Middleware(rateLimitGuard({ max: 10 }))\n * @Post('/login')\n * ```\n */\nexport function rateLimitGuard(options: RateLimitGuardOptions = {}): MiddlewareHandler {\n const max = options.max ?? 100\n const windowMs = options.windowMs ?? 60_000\n const message = options.message ?? 'Too Many Requests'\n const statusCode = options.statusCode ?? 429\n const keyGenerator = options.keyGenerator ?? defaultKey\n const sendHeaders = options.headers ?? true\n const store = options.store ?? new LazyMemoryStore(windowMs)\n\n const exemptWhen = options.exemptWhen\n if (exemptWhen !== undefined) assertFlagTest(exemptWhen, 'rateLimitGuard({ exemptWhen })')\n\n return async (ctx: RequestContext, next: () => void): Promise<void> => {\n if (options.skip?.(ctx)) return next()\n if (exemptWhen !== undefined && matchesFlagTest(exemptWhen, ctx.route?.flags, ctx.route)) {\n return next()\n }\n\n const { totalHits, resetTime } = await store.increment(keyGenerator(ctx))\n const remaining = Math.max(0, max - totalHits)\n\n if (sendHeaders) {\n ctx.setHeader('X-RateLimit-Limit', String(max))\n ctx.setHeader('X-RateLimit-Remaining', String(remaining))\n ctx.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)))\n }\n\n if (totalHits > max) {\n const retryAfter = Math.max(1, Math.ceil((resetTime.getTime() - Date.now()) / 1000))\n if (sendHeaders) ctx.setHeader('Retry-After', String(retryAfter))\n ctx.json({ message }, statusCode)\n return\n }\n\n next()\n }\n}\n","// Edge-safe store adapters over a minimal KV surface. Zero runtime imports —\n// this file must stay importable from the `@forinda/kickjs/web` purity graph.\nimport type { RateLimitStore } from './rate-limit'\nimport type { SessionData, SessionStore } from './session'\n\n/**\n * The minimal async KV surface both stores need. Structurally compatible\n * with a Cloudflare Workers `KVNamespace` binding — pass it straight in:\n *\n * ```ts\n * export default {\n * fetch(req: Request, env: Env) {\n * const store = new KvRateLimitStore(env.MY_KV, { windowMs: 60_000 })\n * // ...\n * },\n * }\n * ```\n *\n * Anything with the same shape works too (Deno KV wrapper, Upstash Redis\n * REST client adapter, a Map-backed fake in tests).\n */\nexport interface KvLike {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n delete(key: string): Promise<void>\n}\n\n/** Cloudflare KV rejects TTLs under 60 seconds — clamp up, never down. */\nfunction kvTtlSeconds(ms: number): number {\n return Math.max(60, Math.ceil(ms / 1000))\n}\n\nexport interface KvRateLimitStoreOptions {\n /** Window length in ms — must match the `windowMs` given to the limiter. */\n windowMs: number\n /** Key prefix in the KV namespace (default `'rl:'`). */\n prefix?: string\n}\n\n/**\n * {@link RateLimitStore} over a {@link KvLike} namespace, for edge deployments\n * where in-memory counters reset on every isolate.\n *\n * KV is eventually consistent and this is a read-modify-write counter, so\n * limiting is **approximate** under concurrency — bursts racing across\n * isolates can each read the same count. That is the accepted trade-off for\n * abuse throttling; use a Durable Object / Redis store when you need an\n * exact ceiling (billing quotas, strict per-key locks).\n */\nexport class KvRateLimitStore implements RateLimitStore {\n private readonly prefix: string\n private readonly windowMs: number\n\n constructor(\n private readonly kv: KvLike,\n options: KvRateLimitStoreOptions,\n ) {\n this.windowMs = options.windowMs\n this.prefix = options.prefix ?? 'rl:'\n }\n\n async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {\n const now = Date.now()\n const entry = await this.read(key)\n if (entry && entry.reset > now) {\n entry.hits++\n await this.write(key, entry)\n return { totalHits: entry.hits, resetTime: new Date(entry.reset) }\n }\n const fresh = { hits: 1, reset: now + this.windowMs }\n await this.write(key, fresh)\n return { totalHits: 1, resetTime: new Date(fresh.reset) }\n }\n\n async decrement(key: string): Promise<void> {\n const entry = await this.read(key)\n if (entry && entry.hits > 0) {\n entry.hits--\n await this.write(key, entry)\n }\n }\n\n async reset(key: string): Promise<void> {\n await this.kv.delete(this.prefix + key)\n }\n\n private async read(key: string): Promise<{ hits: number; reset: number } | null> {\n const raw = await this.kv.get(this.prefix + key)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as { hits: number; reset: number }\n } catch {\n return null\n }\n }\n\n private async write(key: string, entry: { hits: number; reset: number }): Promise<void> {\n await this.kv.put(this.prefix + key, JSON.stringify(entry), {\n expirationTtl: kvTtlSeconds(Math.max(entry.reset - Date.now(), 1000)),\n })\n }\n}\n\nexport interface KvSessionStoreOptions {\n /** Key prefix in the KV namespace (default `'sess:'`). */\n prefix?: string\n}\n\n/**\n * {@link SessionStore} over a {@link KvLike} namespace. Plug into the node\n * `session()` middleware today (e.g. backed by Upstash/Cloudflare KV via\n * REST) so sessions survive restarts and horizontal scaling; TTL expiry is\n * delegated to the KV layer via `expirationTtl`.\n *\n * Cost note: `touch()` is a get + put round-trip (KvLike has no TTL-only\n * refresh), so `session({ rolling: true })` doubles KV operations per\n * request — per-operation-billed platforms may prefer `rolling: false`.\n */\nexport class KvSessionStore implements SessionStore {\n private readonly prefix: string\n\n constructor(\n private readonly kv: KvLike,\n options: KvSessionStoreOptions = {},\n ) {\n this.prefix = options.prefix ?? 'sess:'\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const raw = await this.kv.get(this.prefix + sid)\n if (raw === null) return null\n try {\n return JSON.parse(raw) as SessionData\n } catch {\n return null\n }\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n await this.kv.put(this.prefix + sid, JSON.stringify(data), {\n expirationTtl: kvTtlSeconds(maxAge),\n })\n }\n\n async destroy(sid: string): Promise<void> {\n await this.kv.delete(this.prefix + sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const data = await this.get(sid)\n if (data !== null) await this.set(sid, data, maxAge)\n }\n}\n"],"mappings":";;;;;;;;;;gFAuEA,IAAM,gBAAN,KAAgD,CAGjB,SAF7B,KAAwB,IAAI,IAE5B,YAAY,SAAmC,CAAlB,KAAA,SAAA,QAAmB,CAEhD,MAAM,UAAU,IAA8D,CAC5E,IAAM,IAAM,KAAK,IAAI,EACf,MAAQ,KAAK,KAAK,IAAI,GAAG,EAC/B,GAAI,OAAS,MAAM,MAAQ,IAEzB,MADA,OAAM,OACC,CAAE,UAAW,MAAM,KAAM,UAAW,IAAI,KAAK,MAAM,KAAK,CAAE,EAInE,GAAI,KAAK,KAAK,KAAO,IACd,IAAA,GAAM,CAAC,EAAG,KAAM,KAAK,KAAU,EAAE,OAAS,KAAK,KAAK,KAAK,OAAO,CAAC,EAExE,IAAM,MAAQ,CAAE,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CAEA,MAAc,MAAM,IAAa,MAAuD,CACtF,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,KAAK,EAAG,CAC1D,cAAe,aAAa,KAAK,IAAI,MAAM,MAAQ,KAAK,IAAI,EAAG,GAAI,CAAC,CACtE,CAAC,CACH,CACF,EAiBa,eAAb,KAAoD,CAI/B,GAHnB,OAEA,YACE,GACA,QAAiC,CAAC,EAClC,CAFiB,KAAA,GAAA,GAGjB,KAAK,OAAS,QAAQ,QAAU,OAClC,CAEA,MAAM,IAAI,IAA0C,CAClD,IAAM,IAAM,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,GAAG,EAC/C,GAAI,MAAQ,KAAM,OAAO,KACzB,GAAI,CACF,OAAO,KAAK,MAAM,GAAG,CACvB,MAAQ,CACN,OAAO,IACT,CACF,CAEA,MAAM,IAAI,IAAa,KAAmB,OAA+B,CACvE,MAAM,KAAK,GAAG,IAAI,KAAK,OAAS,IAAK,KAAK,UAAU,IAAI,EAAG,CACzD,cAAe,aAAa,MAAM,CACpC,CAAC,CACH,CAEA,MAAM,QAAQ,IAA4B,CACxC,MAAM,KAAK,GAAG,OAAO,KAAK,OAAS,GAAG,CACxC,CAEA,MAAM,MAAM,IAAa,OAA+B,CACtD,IAAM,KAAO,MAAM,KAAK,IAAI,GAAG,EAC3B,OAAS,MAAM,MAAM,KAAK,IAAI,IAAK,KAAM,MAAM,CACrD,CACF"}
|
|
@@ -36,11 +36,31 @@ interface LoggerProvider {
|
|
|
36
36
|
debug(msg: string, ...args: any[]): void;
|
|
37
37
|
trace?(msg: string, ...args: any[]): void;
|
|
38
38
|
fatal?(msg: string, ...args: any[]): void;
|
|
39
|
-
/**
|
|
39
|
+
/**
|
|
40
|
+
* Return a child provider scoped to the given component name. `bindings`
|
|
41
|
+
* may also carry fields from `logger.child({ ... })` (a request id, a job
|
|
42
|
+
* name) — a provider that ignores them keeps working as before.
|
|
43
|
+
*/
|
|
40
44
|
child(bindings: {
|
|
41
45
|
component: string;
|
|
46
|
+
[field: string]: unknown;
|
|
42
47
|
}): LoggerProvider;
|
|
43
48
|
}
|
|
49
|
+
/** Severity ordering — a message prints only when its rank ≥ the threshold. */
|
|
50
|
+
declare const LEVEL_RANK: Record<string, number>;
|
|
51
|
+
/**
|
|
52
|
+
* An error as a JSON field — `type`, `message`, `stack`, own enumerable
|
|
53
|
+
* properties (a driver's `code`), and its `cause` chain, depth-capped and
|
|
54
|
+
* cycle-guarded like {@link describeError}.
|
|
55
|
+
*/
|
|
56
|
+
declare function serializeError(err: unknown, depth?: number, seen?: Set<unknown>): unknown;
|
|
57
|
+
/**
|
|
58
|
+
* One JSON log line, field-compatible with pino (`level` 10–60, `time` in
|
|
59
|
+
* epoch ms, `msg`) so `pino-pretty` and log shippers read it as-is. Trailing
|
|
60
|
+
* plain objects become fields, an `Error` becomes `err`, and anything else
|
|
61
|
+
* fills the message's placeholders or is appended to it.
|
|
62
|
+
*/
|
|
63
|
+
declare function jsonLine(level: keyof typeof LEVEL_RANK, component: string, bindings: Record<string, unknown>, msg: string, args: unknown[]): string;
|
|
44
64
|
/**
|
|
45
65
|
* Default provider — emits through `console.*` methods. Zero deps.
|
|
46
66
|
*
|
|
@@ -50,6 +70,12 @@ interface LoggerProvider {
|
|
|
50
70
|
* appears with `LOG_LEVEL=debug`. `error`/`fatal` always print unless
|
|
51
71
|
* `LOG_LEVEL=silent`.
|
|
52
72
|
*
|
|
73
|
+
* `LOG_FORMAT=json` writes one pino-compatible JSON object per line instead
|
|
74
|
+
* (all levels through `console.log`, so one stream carries them): fields
|
|
75
|
+
* from `logger.child({ ... })` and from trailing plain-object arguments, and
|
|
76
|
+
* an `Error` argument as `err` with its stack and `cause` chain. The default
|
|
77
|
+
* text output is unchanged.
|
|
78
|
+
*
|
|
53
79
|
* Swap it for pino, winston, bunyan, or anything else by implementing
|
|
54
80
|
* the `LoggerProvider` interface and calling `Logger.setProvider()`
|
|
55
81
|
* before `bootstrap()`.
|
|
@@ -57,7 +83,11 @@ interface LoggerProvider {
|
|
|
57
83
|
declare class ConsoleLoggerProvider implements LoggerProvider {
|
|
58
84
|
private prefix;
|
|
59
85
|
private useColor;
|
|
60
|
-
|
|
86
|
+
/** Fields from `logger.child({ ... })` — written on JSON lines. */
|
|
87
|
+
private bindings;
|
|
88
|
+
constructor(prefix?: string, bindings?: Record<string, unknown>);
|
|
89
|
+
/** Write `msg` as a JSON line when `LOG_FORMAT=json`; returns whether it did. */
|
|
90
|
+
private json;
|
|
61
91
|
private fmt;
|
|
62
92
|
/** Should a message at `rank` print under the current `LOG_LEVEL`? */
|
|
63
93
|
private enabled;
|
|
@@ -69,6 +99,7 @@ declare class ConsoleLoggerProvider implements LoggerProvider {
|
|
|
69
99
|
fatal(msg: string, ...args: any[]): void;
|
|
70
100
|
child(bindings: {
|
|
71
101
|
component: string;
|
|
102
|
+
[field: string]: unknown;
|
|
72
103
|
}): LoggerProvider;
|
|
73
104
|
}
|
|
74
105
|
/**
|
|
@@ -99,9 +130,12 @@ declare class Logger {
|
|
|
99
130
|
private _provider;
|
|
100
131
|
private _providerVersion;
|
|
101
132
|
private _name?;
|
|
133
|
+
private _fields?;
|
|
102
134
|
/** Incremented on every setProvider/resetProvider so instances know to refresh */
|
|
103
135
|
private static _providerVersion;
|
|
104
|
-
constructor(name?: string);
|
|
136
|
+
constructor(name?: string, fields?: Record<string, unknown>);
|
|
137
|
+
/** The active provider's child for this logger's name and fields. */
|
|
138
|
+
private derive;
|
|
105
139
|
/** Re-derive the provider if setProvider() was called since construction/last access */
|
|
106
140
|
private get provider();
|
|
107
141
|
/**
|
|
@@ -126,6 +160,12 @@ declare class Logger {
|
|
|
126
160
|
static for(name: string): Logger;
|
|
127
161
|
/** Create a child logger with a sub-component name */
|
|
128
162
|
child(name: string): Logger;
|
|
163
|
+
/**
|
|
164
|
+
* Create a child logger carrying `fields` on every line it writes — a
|
|
165
|
+
* request id, a job name. Keeps this logger's name and fields. Written as
|
|
166
|
+
* JSON fields under `LOG_FORMAT=json`; the default text output is unchanged.
|
|
167
|
+
*/
|
|
168
|
+
child(fields: Record<string, unknown>): Logger;
|
|
129
169
|
info(msg: string, ...args: any[]): void;
|
|
130
170
|
warn(msg: string, ...args: any[]): void;
|
|
131
171
|
/** Pino-style error-first form — `log.error(err, 'what failed')`. */
|
|
@@ -151,5 +191,5 @@ declare function describeError(err: unknown, maxDepth?: number): string;
|
|
|
151
191
|
/** Shorthand for Logger.for(name) */
|
|
152
192
|
declare function createLogger(name: string): Logger;
|
|
153
193
|
//#endregion
|
|
154
|
-
export { describeError as a, createLogger as i, Logger as n, LoggerProvider as r, ConsoleLoggerProvider as t };
|
|
155
|
-
//# sourceMappingURL=logger-
|
|
194
|
+
export { describeError as a, createLogger as i, Logger as n, jsonLine as o, LoggerProvider as r, serializeError as s, ConsoleLoggerProvider as t };
|
|
195
|
+
//# sourceMappingURL=logger-xE9qI_FS.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger-xE9qI_FS.d.mts","names":[],"sources":["../src/core/logger.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA+BiB;EACf,KAAK,gBAAgB;EACrB,KAAK,gBAAgB;EACrB,MAAM,gBAAgB;EACtB,MAAM,gBAAgB;EACtB,OAAO,gBAAgB;EACvB,OAAO,gBAAgB;;;;;;EAMvB,MAAM;IAAY;KAAoB;MAA4B;;;cAM9D,YAAY;;;;;;iBA8CF,eAAe,cAAc,gBAAW,OAAI;;;;;;;iBAwC5C,SACd,oBAAoB,YACpB,mBACA,UAAU,yBACV,aACA;;;;;;;;;;;;;;;;;;;;cA+EW,iCAAiC;UACpC;UACA;;UAEA;EAER,YAAY,iBAAiB,WAAU;;UAQ/B;UAMA;;UASA;EAIR,KAAK,gBAAgB;EAIrB,KAAK,gBAAgB;EAIrB,MAAM,gBAAgB;EAItB,MAAM,gBAAgB;EAItB,MAAM,gBAAgB;EAItB,MAAM,gBAAgB;EAItB,MAAM;IAAY;KAAoB;MAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCvD;UACH;UACA;UACA;UACA;;iBAGO;EAEf,YAAY,eAAe,SAAS;;UAQ5B;;cAMI;;;;;;;;;;;SAkBL,YAAY,UAAU;;SAOtB,eAAe;;;;;SAQf;;SAOA,IAAI,eAAe;;EAU1B,MAAM,eAAe;;;;;;EAMrB,MAAM,QAAQ,0BAA0B;EAMxC,KAAK,gBAAgB;EAIrB,KAAK,gBAAgB;;EAKrB,MAAM,cAAc,gBAAgB;;EAEpC,MAAM,gBAAgB;;EAEtB,MAAM;EA8BN,MAAM,gBAAgB;EAItB,MAAM,gBAAgB;EAKtB,MAAM,gBAAgB;;;;;;;;;;;iBAeR,cAAc,cAAc;;iBA+B5B,aAAa,eAAe"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.0
|
|
2
|
+
* @forinda/kickjs v9.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import"reflect-metadata";function setClassMeta(key,value,target){Reflect.defineMetadata(key,value,target)}function setMethodMeta(key,value,target,method){Reflect.defineMetadata(key,value,target,method)}function getClassMeta(key,target,fallback){return Reflect.getMetadata(key,target)??fallback}function getMethodMeta(key,target,method,fallback){return Reflect.getMetadata(key,target,method)??fallback}function hasClassMeta(key,target){return Reflect.hasMetadata(key,target)}function getClassMetaOrUndefined(key,target){return Reflect.getMetadata(key,target)}function getMethodMetaOrUndefined(key,target,method){return Reflect.getMetadata(key,target,method)}function pushClassMeta(key,target,...items){let existing=Reflect.getOwnMetadata(key,target)??[];Reflect.defineMetadata(key,[...existing,...items],target)}function pushMethodMeta(key,target,method,...items){let existing=Reflect.getOwnMetadata(key,target,method)??[];Reflect.defineMetadata(key,[...existing,...items],target,method)}function setInMetaMap(key,target,mapKey,mapValue){let inherited=Reflect.getOwnMetadata(key,target),map=inherited?new Map(inherited):new Map;map.set(mapKey,mapValue),Reflect.defineMetadata(key,map,target)}function getMetaMap(key,target){return Reflect.getMetadata(key,target)??new Map}function setInMetaRecord(key,target,recKey,recValue){let inherited=Reflect.getOwnMetadata(key,target),rec=inherited?{...inherited}:{};rec[recKey]=recValue,Reflect.defineMetadata(key,rec,target)}function getMetaRecord(key,target){return Reflect.getMetadata(key,target)??{}}export{getMethodMeta as a,pushClassMeta as c,setInMetaMap as d,setInMetaRecord as f,getMetaRecord as i,pushMethodMeta as l,getClassMetaOrUndefined as n,getMethodMetaOrUndefined as o,setMethodMeta as p,getMetaMap as r,hasClassMeta as s,getClassMeta as t,setClassMeta as u};
|
|
12
|
-
//# sourceMappingURL=metadata-
|
|
12
|
+
//# sourceMappingURL=metadata-CW4I35nN.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata-
|
|
1
|
+
{"version":3,"file":"metadata-CW4I35nN.mjs","names":[],"sources":["../src/core/metadata.ts"],"sourcesContent":["import 'reflect-metadata'\nimport type { InjectionToken } from './token'\n\n/**\n * Typed utilities for reflect-metadata operations.\n *\n * Replaces scattered Reflect.defineMetadata/getMetadata calls with a single\n * source of truth. If we later move to Stage 3 decorators or a WeakMap-based\n * store, only this file changes — all 24+ consumer files stay untouched.\n *\n * Keys may be symbols, strings, or `InjectionToken<T>` objects produced by\n * `createToken()`. Using `createToken` is the preferred pattern because the\n * token's phantom type flows through the helpers, enabling type-safe reads.\n */\n\ntype MetaKey = symbol | string | InjectionToken<unknown>\n\n// ── Setters ─────────────────────────────────────────────────────\n\n/** Set metadata on a class (or prototype for property decorators) */\nexport function setClassMeta<T>(key: MetaKey, value: T, target: object): void {\n Reflect.defineMetadata(key, value, target)\n}\n\n/** Set metadata on a specific method */\nexport function setMethodMeta<T>(key: MetaKey, value: T, target: object, method: string): void {\n Reflect.defineMetadata(key, value, target, method)\n}\n\n// ── Getters ─────────────────────────────────────────────────────\n\n/** Get metadata from a class, returning `fallback` if not set */\nexport function getClassMeta<T>(key: MetaKey, target: object, fallback: T): T {\n return (Reflect.getMetadata(key, target) as T) ?? fallback\n}\n\n/** Get metadata from a specific method, returning `fallback` if not set */\nexport function getMethodMeta<T>(key: MetaKey, target: object, method: string, fallback: T): T {\n return (Reflect.getMetadata(key, target, method) as T) ?? fallback\n}\n\n/** Check if metadata exists on a class */\nexport function hasClassMeta(key: MetaKey, target: object): boolean {\n return Reflect.hasMetadata(key, target)\n}\n\n/** Get metadata from a class with no default (returns undefined if absent) */\nexport function getClassMetaOrUndefined<T>(key: MetaKey, target: object): T | undefined {\n return Reflect.getMetadata(key, target) as T | undefined\n}\n\n/** Get metadata from a method with no default (returns undefined if absent) */\nexport function getMethodMetaOrUndefined<T>(\n key: MetaKey,\n target: object,\n method: string,\n): T | undefined {\n return Reflect.getMetadata(key, target, method) as T | undefined\n}\n\n// ── Accumulate: Arrays ──────────────────────────────────────────\n\n/** Append items to an array stored in class metadata */\nexport function pushClassMeta<T>(key: MetaKey, target: object, ...items: T[]): void {\n const existing: T[] = Reflect.getOwnMetadata(key, target) ?? []\n Reflect.defineMetadata(key, [...existing, ...items], target)\n}\n\n/** Append items to an array stored in method metadata */\nexport function pushMethodMeta<T>(\n key: MetaKey,\n target: object,\n method: string,\n ...items: T[]\n): void {\n const existing: T[] = Reflect.getOwnMetadata(key, target, method) ?? []\n Reflect.defineMetadata(key, [...existing, ...items], target, method)\n}\n\n// ── Accumulate: Maps ────────────────────────────────────────────\n\n/** Set a key/value in a Map stored in class metadata */\nexport function setInMetaMap<K, V>(key: MetaKey, target: object, mapKey: K, mapValue: V): void {\n const inherited: Map<K, V> | undefined = Reflect.getOwnMetadata(key, target)\n const map = inherited ? new Map(inherited) : new Map<K, V>()\n map.set(mapKey, mapValue)\n Reflect.defineMetadata(key, map, target)\n}\n\n/** Get a Map from class metadata (returns empty Map if absent) */\nexport function getMetaMap<K, V>(key: MetaKey, target: object): Map<K, V> {\n return Reflect.getMetadata(key, target) ?? new Map()\n}\n\n// ── Accumulate: Records ─────────────────────────────────────────\n\n/** Set a key/value in a Record stored in class metadata */\nexport function setInMetaRecord<V>(\n key: MetaKey,\n target: object,\n recKey: string | number,\n recValue: V,\n): void {\n const inherited: Record<string | number, V> | undefined = Reflect.getOwnMetadata(key, target)\n const rec = inherited ? { ...inherited } : {}\n rec[recKey] = recValue\n Reflect.defineMetadata(key, rec, target)\n}\n\n/** Get a Record from class metadata (returns empty object if absent) */\nexport function getMetaRecord<V>(key: MetaKey, target: object): Record<string | number, V> {\n return Reflect.getMetadata(key, target) ?? {}\n}\n"],"mappings":";;;;;;;;;;yBAoBA,SAAgB,aAAgB,IAAc,MAAU,OAAsB,CAC5E,QAAQ,eAAe,IAAK,MAAO,MAAM,CAC3C,CAGA,SAAgB,cAAiB,IAAc,MAAU,OAAgB,OAAsB,CAC7F,QAAQ,eAAe,IAAK,MAAO,OAAQ,MAAM,CACnD,CAKA,SAAgB,aAAgB,IAAc,OAAgB,SAAgB,CAC5E,OAAQ,QAAQ,YAAY,IAAK,MAAM,GAAW,QACpD,CAGA,SAAgB,cAAiB,IAAc,OAAgB,OAAgB,SAAgB,CAC7F,OAAQ,QAAQ,YAAY,IAAK,OAAQ,MAAM,GAAW,QAC5D,CAGA,SAAgB,aAAa,IAAc,OAAyB,CAClE,OAAO,QAAQ,YAAY,IAAK,MAAM,CACxC,CAGA,SAAgB,wBAA2B,IAAc,OAA+B,CACtF,OAAO,QAAQ,YAAY,IAAK,MAAM,CACxC,CAGA,SAAgB,yBACd,IACA,OACA,OACe,CACf,OAAO,QAAQ,YAAY,IAAK,OAAQ,MAAM,CAChD,CAKA,SAAgB,cAAiB,IAAc,OAAgB,GAAG,MAAkB,CAClF,IAAM,SAAgB,QAAQ,eAAe,IAAK,MAAM,GAAK,CAAC,EAC9D,QAAQ,eAAe,IAAK,CAAC,GAAG,SAAU,GAAG,KAAK,EAAG,MAAM,CAC7D,CAGA,SAAgB,eACd,IACA,OACA,OACA,GAAG,MACG,CACN,IAAM,SAAgB,QAAQ,eAAe,IAAK,OAAQ,MAAM,GAAK,CAAC,EACtE,QAAQ,eAAe,IAAK,CAAC,GAAG,SAAU,GAAG,KAAK,EAAG,OAAQ,MAAM,CACrE,CAKA,SAAgB,aAAmB,IAAc,OAAgB,OAAW,SAAmB,CAC7F,IAAM,UAAmC,QAAQ,eAAe,IAAK,MAAM,EACrE,IAAM,UAAY,IAAI,IAAI,SAAS,EAAI,IAAI,IACjD,IAAI,IAAI,OAAQ,QAAQ,EACxB,QAAQ,eAAe,IAAK,IAAK,MAAM,CACzC,CAGA,SAAgB,WAAiB,IAAc,OAA2B,CACxE,OAAO,QAAQ,YAAY,IAAK,MAAM,GAAK,IAAI,GACjD,CAKA,SAAgB,gBACd,IACA,OACA,OACA,SACM,CACN,IAAM,UAAoD,QAAQ,eAAe,IAAK,MAAM,EACtF,IAAM,UAAY,CAAE,GAAG,SAAU,EAAI,CAAC,EAC5C,IAAI,QAAU,SACd,QAAQ,eAAe,IAAK,IAAK,MAAM,CACzC,CAGA,SAAgB,cAAiB,IAAc,OAA4C,CACzF,OAAO,QAAQ,YAAY,IAAK,MAAM,GAAK,CAAC,CAC9C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.0
|
|
2
|
+
* @forinda/kickjs v9.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
var MutableModuleRegistry=class{entries=[];mount(module){this.entries.push(module)}};export{MutableModuleRegistry as t};
|
|
12
|
-
//# sourceMappingURL=module-registry-
|
|
12
|
+
//# sourceMappingURL=module-registry-kqozOSo0.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module-registry-
|
|
1
|
+
{"version":3,"file":"module-registry-kqozOSo0.mjs","names":[],"sources":["../src/core/module-registry.ts"],"sourcesContent":["import type { AppModuleEntry } from './app-module'\n\n/**\n * Imperative receiver passed to {@link KickPlugin.setup} and the\n * top-level `bootstrap({ setup })` callback so adopters can register\n * modules conditionally — based on env flags, runtime config,\n * tenant lists, etc. — instead of being limited to the static\n * `modules: [...]` array.\n *\n * @example\n * ```ts\n * bootstrap({\n * modules: [HelloModule()], // static — always mounted\n * setup(registry) {\n * if (env.ENABLE_ADMIN) registry.mount(AdminModule())\n * for (const tenant of env.TENANTS) {\n * registry.mount(TenantModule.scoped(tenant.id, { id: tenant.id }))\n * }\n * },\n * })\n * ```\n *\n * **Currently exposes only `.mount(module)` — the HTTP-feature path.**\n * A future `.use(module)` for non-HTTP modules (queues, cron, workers,\n * DI-only seeds) is planned but not yet implemented; existing non-HTTP\n * modules continue returning `null` from `routes()` and registering\n * via `.mount()`.\n *\n * Same dispatch rules as the static `modules: [...]` array — class\n * entries get `new`-ed at boot, `defineModule` factory output is used\n * directly. The registry doesn't validate the entry shape itself; the\n * Application loader does the typeof discrimination at mount time.\n */\nexport interface ModuleRegistry {\n /**\n * Register a module for the full HTTP lifecycle: `register()` runs,\n * `import.meta.glob` decorator side-effects fire, `routes()` is\n * called and its result mounted, `contributors()` are merged at\n * `'module'` precedence and applied to the mounted routes.\n *\n * Modules are mounted in registration order (first call → first\n * mount). Order across sources is: plugin static modules → plugin\n * `setup()` calls → user static modules → user `setup()` callback.\n */\n mount(module: AppModuleEntry): void\n}\n\n/**\n * Internal collector implementing {@link ModuleRegistry}. Application\n * passes one of these to every `setup()` callback during bootstrap;\n * the collected `entries` array is then run through the same\n * class-vs-instance dispatch as the static `modules: [...]` array.\n *\n * Not exported from the public surface — adopters interact only\n * through the {@link ModuleRegistry} interface.\n */\nexport class MutableModuleRegistry implements ModuleRegistry {\n readonly entries: AppModuleEntry[] = []\n\n mount(module: AppModuleEntry): void {\n this.entries.push(module)\n }\n}\n"],"mappings":";;;;;;;;;;AAwDA,IAAa,sBAAb,KAA6D,CAC3D,QAAqC,CAAC,EAEtC,MAAM,OAA8B,CAClC,KAAK,QAAQ,KAAK,MAAM,CAC1B,CACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.0
|
|
2
|
+
* @forinda/kickjs v9.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
import{createLogger}from"./core/logger.mjs";const log=createLogger(`Observers`);let observers=[],publisher,publisherWantsResponses=()=>!1;function setObservers(list){return observers=list.filter(o=>o.onError||o.onResponse),observers}function releaseObservers(installed){observers===installed&&(observers=[])}function setObserverPublisher(next,wantsResponses=()=>!1){publisher=next,publisherWantsResponses=wantsResponses}function hasResponseObservers(){return observers.some(o=>o.onResponse)||publisherWantsResponses()}function notify(pick,what){for(let observer of publisher?[...observers,publisher]:observers)try{let result=pick(observer);result&&typeof result.catch==`function`&&result.catch(err=>failed(observer,what,err))}catch(err){failed(observer,what,err)}}function failed(observer,what,err){try{log.error({err},`${observer.name??`observer`}.${what} threw — skipped`)}catch{}}function reportError(error,info){notify(o=>o.onError?.(error,info),`onError`)}function reportResponse(info){notify(o=>o.onResponse?.(info),`onResponse`)}export{setObserverPublisher as a,reportResponse as i,releaseObservers as n,setObservers as o,reportError as r,hasResponseObservers as t};
|
|
12
|
-
//# sourceMappingURL=observers-
|
|
12
|
+
//# sourceMappingURL=observers-CC3sO1BM.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"observers-
|
|
1
|
+
{"version":3,"file":"observers-CC3sO1BM.mjs","names":[],"sources":["../src/core/observers.ts"],"sourcesContent":["/**\n * One place every error and every response is reported to — so an error\n * tracker, a metrics exporter, or an APM integration hooks in once instead of\n * replacing the error handler and patching each source.\n *\n * Observers are adapters and plugins with `onError` / `onResponse`, plus\n * whatever the Node server's tracing channels publish (see `http/tracing.ts`).\n * Observe-only: they cannot change the response, and one that throws is\n * logged and skipped — it never breaks a request or another observer.\n *\n * Free of `node:` imports: `waitUntil` (shared with the web entry) reports\n * through here.\n *\n * @module @forinda/kickjs/core/observers\n */\nimport { createLogger } from './logger'\n\nconst log = createLogger('Observers')\n\n/** Where an error came from. Integrations may report their own sources. */\nexport type ErrorSource =\n | 'request'\n | 'uncaught'\n | 'unhandled-rejection'\n | 'background'\n | 'job'\n | (string & {})\n\nexport interface ErrorInfo {\n source: ErrorSource\n requestId?: string\n method?: string\n /** The request URL path, as received. */\n path?: string\n /** The matched route pattern, e.g. `/api/v1/users/:id`, when one matched. */\n route?: string\n /** The status the error was answered with, for request errors. */\n status?: number\n /** Anything else the reporter knows — a queue and job name, a cron schedule. */\n context?: Record<string, unknown>\n}\n\nexport interface ResponseInfo {\n method: string\n path: string\n /** The matched route pattern, or undefined when no route matched (404s). */\n route?: string\n status: number\n durationMs: number\n requestId?: string\n}\n\nexport interface Observer {\n name?: string\n onError?(error: unknown, info: ErrorInfo): void | Promise<void>\n onResponse?(info: ResponseInfo): void | Promise<void>\n}\n\nlet observers: readonly Observer[] = []\nlet publisher: Observer | undefined\nlet publisherWantsResponses: () => boolean = () => false\n\n/**\n * Replace the observer set — called by the Application from its adapters and\n * plugins. Returns the installed set, so its owner can later release exactly\n * that set (see {@link releaseObservers}).\n */\nexport function setObservers(list: readonly Observer[]): readonly Observer[] {\n observers = list.filter((o) => o.onError || o.onResponse)\n return observers\n}\n\n/**\n * Clear the observer set — but only if it is still the one `installed`. The\n * set is process-wide: a newer Application may have replaced it, and an older\n * one shutting down must not clear the newer one's observers.\n */\nexport function releaseObservers(installed: readonly Observer[]): void {\n if (observers === installed) observers = []\n}\n\n/**\n * The Node server's tracing channels, fed from the same reports. `wantsResponses`\n * is checked per request: a channel can gain a subscriber at any time.\n */\nexport function setObserverPublisher(\n next: Observer | undefined,\n wantsResponses: () => boolean = () => false,\n): void {\n publisher = next\n publisherWantsResponses = wantsResponses\n}\n\n/** Whether anything is listening for responses — lets the server skip timing work. */\nexport function hasResponseObservers(): boolean {\n return observers.some((o) => o.onResponse) || publisherWantsResponses()\n}\n\nfunction notify(pick: (o: Observer) => void | Promise<void> | undefined, what: string): void {\n for (const observer of publisher ? [...observers, publisher] : observers) {\n try {\n const result = pick(observer)\n if (result && typeof (result as Promise<void>).catch === 'function') {\n ;(result as Promise<void>).catch((err: unknown) => failed(observer, what, err))\n }\n } catch (err) {\n failed(observer, what, err)\n }\n }\n}\n\nfunction failed(observer: Observer, what: string, err: unknown): void {\n // Logged directly, never re-reported: an observer failing inside onError\n // must not loop back into onError. Guarded too: a custom LoggerProvider that\n // throws would otherwise escape reportError() — or, from an async\n // observer, become an unhandled rejection that bootstrap reports right back\n // here.\n try {\n log.error({ err }, `${observer.name ?? 'observer'}.${what} threw — skipped`)\n } catch {\n // Nothing left to tell; reportError's \"never throws\" contract wins.\n }\n}\n\n/**\n * Report an error to every observer. The framework calls this for request\n * errors, uncaught exceptions, unhandled rejections, `waitUntil` failures and\n * queue job failures; call it from your own integrations too (a cron runner,\n * a message consumer). Never throws.\n */\nexport function reportError(error: unknown, info: ErrorInfo): void {\n notify((o) => o.onError?.(error, info), 'onError')\n}\n\n/** Report a finished response to every observer. Never throws. */\nexport function reportResponse(info: ResponseInfo): void {\n notify((o) => o.onResponse?.(info), 'onResponse')\n}\n"],"mappings":";;;;;;;;;;4CAiBA,MAAM,IAAM,aAAa,WAAW,EAyCpC,IAAI,UAAiC,CAAC,EAClC,UACA,4BAA+C,GAOnD,SAAgB,aAAa,KAAgD,CAE3E,MADA,WAAY,KAAK,OAAQ,GAAM,EAAE,SAAW,EAAE,UAAU,EACjD,SACT,CAOA,SAAgB,iBAAiB,UAAsC,CACjE,YAAc,YAAW,UAAY,CAAC,EAC5C,CAMA,SAAgB,qBACd,KACA,mBAAsC,GAChC,CACN,UAAY,KACZ,wBAA0B,cAC5B,CAGA,SAAgB,sBAAgC,CAC9C,OAAO,UAAU,KAAM,GAAM,EAAE,UAAU,GAAK,wBAAwB,CACxE,CAEA,SAAS,OAAO,KAAyD,KAAoB,CAC3F,IAAK,IAAM,YAAY,UAAY,CAAC,GAAG,UAAW,SAAS,EAAI,UAC7D,GAAI,CACF,IAAM,OAAS,KAAK,QAAQ,EACxB,QAAU,OAAQ,OAAyB,OAAU,YACtD,OAA0B,MAAO,KAAiB,OAAO,SAAU,KAAM,GAAG,CAAC,CAElF,OAAS,IAAK,CACZ,OAAO,SAAU,KAAM,GAAG,CAC5B,CAEJ,CAEA,SAAS,OAAO,SAAoB,KAAc,IAAoB,CAMpE,GAAI,CACF,IAAI,MAAM,CAAE,GAAI,EAAG,GAAG,SAAS,MAAQ,WAAW,GAAG,KAAK,iBAAiB,CAC7E,MAAQ,CAER,CACF,CAQA,SAAgB,YAAY,MAAgB,KAAuB,CACjE,OAAQ,GAAM,EAAE,UAAU,MAAO,IAAI,EAAG,SAAS,CACnD,CAGA,SAAgB,eAAe,KAA0B,CACvD,OAAQ,GAAM,EAAE,aAAa,IAAI,EAAG,YAAY,CAClD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.0
|
|
2
|
+
* @forinda/kickjs v9.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
const FILTER_OPERATORS=new Set([`eq`,`neq`,`gt`,`gte`,`lt`,`lte`,`between`,`in`,`contains`,`starts`,`ends`]),BUILTIN_DEFAULTS={maxLimit:100,defaultLimit:20,maxSearchLength:200,defaultPage:1},defaults={...BUILTIN_DEFAULTS};function setQueryParsingDefaults(partial){partial.maxLimit!==void 0&&(defaults.maxLimit=partial.maxLimit),partial.defaultLimit!==void 0&&(defaults.defaultLimit=partial.defaultLimit),partial.maxSearchLength!==void 0&&(defaults.maxSearchLength=partial.maxSearchLength)}function getQueryParsingDefaults(){return{...defaults}}function resetQueryParsingDefaults(){Object.assign(defaults,BUILTIN_DEFAULTS)}function parseFilters(filterParam,allowedFields,options){if(!filterParam)return[];let items=Array.isArray(filterParam)?filterParam:[filterParam],results=[],allowed=allowedFields?new Set(allowedFields):null,onReject=options?.onReject;for(let item of items){let firstColon=item.indexOf(`:`);if(firstColon===-1)continue;let secondColon=item.indexOf(`:`,firstColon+1);if(secondColon===-1)continue;let field=item.slice(0,firstColon),operator=item.slice(firstColon+1,secondColon),value=item.slice(secondColon+1);if(field&&value){if(!FILTER_OPERATORS.has(operator)){onReject?.({kind:`filter`,field,reason:`unknown-operator`});continue}if(allowed&&!allowed.has(field)){onReject?.({kind:`filter`,field,reason:`field-not-allowed`});continue}results.push({field,operator,value})}}return results}function parseSort(sortParam,allowedFields,options){if(!sortParam)return[];let items=Array.isArray(sortParam)?sortParam:[sortParam],results=[],allowed=allowedFields?new Set(allowedFields):null,onReject=options?.onReject;for(let item of items){let lastColon=item.lastIndexOf(`:`);if(lastColon===-1)continue;let field=item.slice(0,lastColon),dir=item.slice(lastColon+1).toLowerCase();if(field&&(dir===`asc`||dir===`desc`)){if(allowed&&!allowed.has(field)){onReject?.({kind:`sort`,field,reason:`field-not-allowed`});continue}results.push({field,direction:dir})}}return results}function parsePagination(params,options){let defaultLimit=options?.defaultLimit??defaults.defaultLimit,maxLimit=options?.maxLimit??defaults.maxLimit,page=typeof params.page==`string`?Number.parseInt(params.page,10):params.page??defaults.defaultPage,limit=typeof params.limit==`string`?Number.parseInt(params.limit,10):params.limit??defaultLimit;return(Number.isNaN(page)||page<1)&&(page=defaults.defaultPage),(Number.isNaN(limit)||limit<1)&&(limit=defaultLimit),limit>maxLimit&&(limit=maxLimit),{page,limit,offset:(page-1)*limit}}function parseSearchQuery(q,options){if(!q)return``;let maxLen=options?.maxSearchLength??defaults.maxSearchLength,trimmed=q.trim();return trimmed.length>maxLen?(options?.onReject?.({kind:`search`,field:`q`,reason:`truncated`}),trimmed.slice(0,maxLen)):trimmed}function normalizeFieldConfig(config){if(config)return`columns`in config&&config.columns&&typeof config.columns==`object`?{filterable:Object.keys(config.columns),sortable:config.sortable?Object.keys(config.sortable):void 0,searchable:void 0}:config}function parseQuery(query,fieldConfig,options){let normalized=normalizeFieldConfig(fieldConfig),rejectOpts=options?.onReject?{onReject:options.onReject}:void 0;return{filters:parseFilters(query.filter,normalized?.filterable,rejectOpts),sort:parseSort(query.sort,normalized?.sortable,rejectOpts),pagination:parsePagination({page:query.page,limit:query.limit},options),search:parseSearchQuery(query.q,options)}}function buildQueryParams(parsed){let params={};return parsed.filters?.length&&(params.filter=parsed.filters.map(f=>`${f.field}:${f.operator}:${f.value}`)),parsed.sort?.length&&(params.sort=parsed.sort.map(s=>`${s.field}:${s.direction}`)),parsed.pagination&&(params.page=parsed.pagination.page,params.limit=parsed.pagination.limit),parsed.search&&(params.q=parsed.search),params}export{parseQuery as a,resetQueryParsingDefaults as c,parsePagination as i,setQueryParsingDefaults as l,getQueryParsingDefaults as n,parseSearchQuery as o,parseFilters as r,parseSort as s,buildQueryParams as t,FILTER_OPERATORS as u};
|
|
12
|
-
//# sourceMappingURL=query-
|
|
12
|
+
//# sourceMappingURL=query-DPlkWOw6.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-CNa0mxSK.mjs","names":[],"sources":["../src/http/query/types.ts","../src/http/query/parse-query.ts"],"sourcesContent":["/** Supported filter operators for query string parsing */\nexport type FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'in'\n | 'contains'\n | 'starts'\n | 'ends'\n\nexport const FILTER_OPERATORS = new Set<string>([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'between',\n 'in',\n 'contains',\n 'starts',\n 'ends',\n])\n\nexport interface FilterItem {\n field: string\n operator: FilterOperator\n value: string\n}\n\nexport interface SortItem {\n field: string\n direction: 'asc' | 'desc'\n}\n\nexport interface PaginationParams {\n page: number\n limit: number\n offset: number\n}\n\n/**\n * The result of parsing a query string. ORM-agnostic — pass this to\n * a query builder adapter (Drizzle, Prisma, Sequelize, etc.) to produce\n * database-specific query objects.\n */\nexport interface ParsedQuery {\n filters: FilterItem[]\n sort: SortItem[]\n pagination: PaginationParams\n search: string\n}\n\n/**\n * Helper that extracts the literal field union from a `QueryFieldConfig`\n * key. When the user passes `{ filterable: ['status', 'category'] } as const`,\n * `FieldsOf<typeof config, 'filterable'>` resolves to `'status' | 'category'`.\n *\n * Without `as const`, the arrays widen to `string[]` and the union falls\n * back to `string`. This is the documented escape hatch.\n */\nexport type FieldsOf<\n TConfig extends QueryFieldConfig | undefined,\n K extends 'filterable' | 'sortable' | 'searchable',\n> = TConfig extends { readonly [P in K]: readonly (infer F)[] }\n ? F extends string\n ? F\n : string\n : TConfig extends { columns: infer C }\n ? K extends 'filterable'\n ? keyof C & string\n : string\n : string\n\n/**\n * Narrowed `ParsedQuery` whose `filters[].field` and `sort[].field`\n * unions are constrained to the literal whitelist passed to\n * `ctx.qs()` / `parseQuery()`. Extends `ParsedQuery`, so any function\n * accepting `ParsedQuery` accepts a `TypedParsedQuery<X>` automatically\n * (subtype assignment, no codegen, backward compatible).\n *\n * @example\n * ```ts\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt'],\n * } as const)\n * parsed.filters[0]?.field // 'status' | 'priority'\n * parsed.sort[0]?.field // 'createdAt'\n * ```\n */\nexport interface TypedParsedQuery<\n TConfig extends QueryFieldConfig | undefined,\n> extends ParsedQuery {\n filters: Array<FilterItem & { field: FieldsOf<TConfig, 'filterable'> }>\n sort: Array<SortItem & { field: FieldsOf<TConfig, 'sortable'> }>\n}\n\n/**\n * Restrict which fields can be filtered, sorted, or searched.\n * Fields not in the allow-list are silently ignored.\n *\n * Accepts two forms:\n * 1. **String arrays** (standard): `{ filterable: ['name', 'status'], sortable: ['createdAt'] }`\n * 2. **Column-object maps** (Drizzle-style): `{ columns: { name: col, status: col }, sortable: { createdAt: col } }`\n *\n * When column-object maps are provided, `Object.keys()` is used to derive the field names.\n */\nexport type QueryFieldConfig = StringQueryFieldConfig | ColumnQueryFieldConfig\n\nexport interface StringQueryFieldConfig {\n filterable?: string[]\n sortable?: string[]\n searchable?: string[]\n}\n\n/**\n * Column-object-based field config (e.g., from DrizzleQueryParamsConfig).\n * Keys are the field names used in query strings; values are ORM column references.\n */\nexport interface ColumnQueryFieldConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/** Standardized paginated response shape */\nexport interface PaginatedResponse<T = any> {\n data: T[]\n meta: {\n page: number\n limit: number\n total: number\n totalPages: number\n hasNext: boolean\n hasPrev: boolean\n }\n}\n\n/**\n * Interface for ORM-specific query builder adapters.\n * Implement this to translate a `ParsedQuery` into your ORM's query format.\n *\n * @example\n * ```ts\n * // Drizzle adapter\n * class DrizzleQueryAdapter implements QueryBuilderAdapter<DrizzleQueryResult> {\n * build(parsed: ParsedQuery, config: DrizzleConfig): DrizzleQueryResult {\n * // Convert filters → Drizzle SQL conditions\n * // Convert sort → Drizzle orderBy\n * return { where, orderBy, limit, offset }\n * }\n * }\n *\n * // Prisma adapter\n * class PrismaQueryAdapter implements QueryBuilderAdapter<PrismaQueryResult> {\n * build(parsed: ParsedQuery, config: PrismaConfig): PrismaQueryResult {\n * return { where, orderBy, skip, take }\n * }\n * }\n * ```\n */\nexport interface QueryBuilderAdapter<TResult = any, TConfig = any> {\n /** Human-readable name for debugging */\n readonly name: string\n\n /**\n * Convert a ParsedQuery into an ORM-specific query object.\n * @param parsed - The ORM-agnostic parsed query\n * @param config - ORM-specific configuration (column maps, search columns, etc.)\n */\n build(parsed: ParsedQuery, config: TConfig): TResult\n}\n","import {\n FILTER_OPERATORS,\n type FilterItem,\n type FilterOperator,\n type SortItem,\n type PaginationParams,\n type ParsedQuery,\n type QueryFieldConfig,\n type StringQueryFieldConfig,\n type TypedParsedQuery,\n} from './types'\n\n// ── Configurable defaults ───────────────────────────────────────────────\n\n/**\n * Why a rejected field/value was dropped. Surfaced through\n * {@link ParseQueryOptions.onReject} so a caller can warn, count, or\n * return a 400 instead of the historical silent drop.\n */\nexport type QueryRejectReason = 'field-not-allowed' | 'unknown-operator' | 'truncated'\n\nexport interface QueryRejection {\n kind: 'filter' | 'sort' | 'search'\n field: string\n reason: QueryRejectReason\n}\n\nexport interface ParseQueryOptions {\n /** Hard cap on `limit`. Default: global (100, override via {@link setQueryParsingDefaults}). */\n maxLimit?: number\n /** `limit` when the query omits one. Default: global (20). */\n defaultLimit?: number\n /** Max `q` length before truncation. Default: global (200). */\n maxSearchLength?: number\n /**\n * Called once per dropped filter/sort field or truncated search.\n * The historical behaviour is a silent drop; wire this to a logger or\n * a 400 to make over-broad / typo'd queries visible.\n */\n onReject?: (rejection: QueryRejection) => void\n}\n\ninterface QueryParsingDefaults {\n maxLimit: number\n defaultLimit: number\n maxSearchLength: number\n defaultPage: number\n}\n\nconst BUILTIN_DEFAULTS: QueryParsingDefaults = {\n maxLimit: 100,\n defaultLimit: 20,\n maxSearchLength: 200,\n defaultPage: 1,\n}\n\nconst defaults: QueryParsingDefaults = { ...BUILTIN_DEFAULTS }\n\n/**\n * Globally override the query-parsing limits — call once at bootstrap.\n * Per-call {@link ParseQueryOptions} still take precedence over these.\n */\nexport function setQueryParsingDefaults(\n partial: Partial<Omit<QueryParsingDefaults, 'defaultPage'>>,\n): void {\n if (partial.maxLimit !== undefined) defaults.maxLimit = partial.maxLimit\n if (partial.defaultLimit !== undefined) defaults.defaultLimit = partial.defaultLimit\n if (partial.maxSearchLength !== undefined) defaults.maxSearchLength = partial.maxSearchLength\n}\n\n/** Read the current global query-parsing defaults (a copy). */\nexport function getQueryParsingDefaults(): Readonly<QueryParsingDefaults> {\n return { ...defaults }\n}\n\n/**\n * Restore the built-in query-parsing defaults (maxLimit 100, defaultLimit\n * 20, maxSearchLength 200). Useful in test teardown after a\n * {@link setQueryParsingDefaults} override so global state can't leak\n * between tests.\n */\nexport function resetQueryParsingDefaults(): void {\n Object.assign(defaults, BUILTIN_DEFAULTS)\n}\n\n// ── Individual parsers ──────────────────────────────────────────────────\n\n/** Parse filter strings like \"status:eq:active\" into structured objects */\nexport function parseFilters(\n filterParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): FilterItem[] {\n if (!filterParam) return []\n\n const items = Array.isArray(filterParam) ? filterParam : [filterParam]\n const results: FilterItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on first two colons only — value may contain colons (e.g. timestamps)\n const firstColon = item.indexOf(':')\n if (firstColon === -1) continue\n\n const secondColon = item.indexOf(':', firstColon + 1)\n if (secondColon === -1) continue\n\n const field = item.slice(0, firstColon)\n const operator = item.slice(firstColon + 1, secondColon)\n const value = item.slice(secondColon + 1)\n\n if (!field || !value) continue\n if (!FILTER_OPERATORS.has(operator)) {\n onReject?.({ kind: 'filter', field, reason: 'unknown-operator' })\n continue\n }\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'filter', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, operator: operator as FilterOperator, value })\n }\n\n return results\n}\n\n/** Parse sort strings like \"firstName:asc\" into structured objects */\nexport function parseSort(\n sortParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): SortItem[] {\n if (!sortParam) return []\n\n const items = Array.isArray(sortParam) ? sortParam : [sortParam]\n const results: SortItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on last colon so field names with colons work\n const lastColon = item.lastIndexOf(':')\n if (lastColon === -1) continue\n\n const field = item.slice(0, lastColon)\n const dir = item.slice(lastColon + 1).toLowerCase()\n\n if (!field) continue\n if (dir !== 'asc' && dir !== 'desc') continue\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'sort', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, direction: dir })\n }\n\n return results\n}\n\n/** Parse page/limit into pagination with computed offset */\nexport function parsePagination(\n params: {\n page?: string | number\n limit?: string | number\n },\n options?: Pick<ParseQueryOptions, 'maxLimit' | 'defaultLimit'>,\n): PaginationParams {\n const defaultLimit = options?.defaultLimit ?? defaults.defaultLimit\n const maxLimit = options?.maxLimit ?? defaults.maxLimit\n\n let page =\n typeof params.page === 'string'\n ? Number.parseInt(params.page, 10)\n : (params.page ?? defaults.defaultPage)\n let limit =\n typeof params.limit === 'string'\n ? Number.parseInt(params.limit, 10)\n : (params.limit ?? defaultLimit)\n\n if (Number.isNaN(page) || page < 1) page = defaults.defaultPage\n if (Number.isNaN(limit) || limit < 1) limit = defaultLimit\n if (limit > maxLimit) limit = maxLimit\n\n return { page, limit, offset: (page - 1) * limit }\n}\n\n/** Sanitize and truncate search query */\nexport function parseSearchQuery(\n q: string | undefined,\n options?: Pick<ParseQueryOptions, 'maxSearchLength' | 'onReject'>,\n): string {\n if (!q) return ''\n const maxLen = options?.maxSearchLength ?? defaults.maxSearchLength\n const trimmed = q.trim()\n if (trimmed.length > maxLen) {\n options?.onReject?.({ kind: 'search', field: 'q', reason: 'truncated' })\n return trimmed.slice(0, maxLen)\n }\n return trimmed\n}\n\n// ── Config normalizer ───────────────────────────────────────────────────\n\n/**\n * Normalize a QueryFieldConfig into the string-based form.\n * Detects column-object-based configs (DrizzleQueryParamsConfig) by checking\n * for a `columns` property and extracts `Object.keys()`.\n */\nfunction normalizeFieldConfig(config?: QueryFieldConfig): StringQueryFieldConfig | undefined {\n if (!config) return undefined\n\n // Column-object-based config (e.g., DrizzleQueryParamsConfig)\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: undefined, // searchColumns are Column objects, not used for string filtering\n }\n }\n\n // Already string-based\n return config as StringQueryFieldConfig\n}\n\n// ── Combined parser ─────────────────────────────────────────────────────\n\n/**\n * Parse a raw Express query object into a structured, ORM-agnostic ParsedQuery.\n *\n * @param query - Raw query string object from `req.query` or Zod-validated object\n * @param fieldConfig - Optional field restrictions (whitelist filterable/sortable/searchable).\n * Accepts both string-based configs (`{ filterable, sortable, searchable }`) and\n * column-object configs (`{ columns, sortable, searchColumns }`).\n * @param options - Limits + an `onReject` hook for dropped/truncated input.\n *\n * @example\n * ```ts\n * // String-based config\n * const parsed = parseQuery(ctx.query, {\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * })\n *\n * // Column-object config (DrizzleQueryParamsConfig)\n * const parsed = parseQuery(ctx.query, TASK_QUERY_CONFIG)\n * ```\n *\n * Query string format:\n * - Filters: `?filter=field:operator:value` (repeatable)\n * - Sort: `?sort=field:asc|desc` (repeatable)\n * - Pagination: `?page=1&limit=20`\n * - Search: `?q=search+term`\n *\n * Filter operators: eq, neq, gt, gte, lt, lte, between, in, contains, starts, ends\n */\nexport function parseQuery<TConfig extends QueryFieldConfig | undefined = undefined>(\n query: Record<string, any>,\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n): TypedParsedQuery<TConfig> {\n const normalized = normalizeFieldConfig(fieldConfig)\n const rejectOpts = options?.onReject ? { onReject: options.onReject } : undefined\n return {\n filters: parseFilters(query.filter, normalized?.filterable, rejectOpts),\n sort: parseSort(query.sort, normalized?.sortable, rejectOpts),\n pagination: parsePagination({ page: query.page, limit: query.limit }, options),\n search: parseSearchQuery(query.q, options),\n } as TypedParsedQuery<TConfig>\n}\n\n// ── Query URL builder (for client-side or testing) ──────────────────────\n\n/** Convert ParsedQuery back into query string parameters */\nexport function buildQueryParams(\n parsed: Partial<ParsedQuery>,\n): Record<string, string | string[] | number> {\n const params: Record<string, string | string[] | number> = {}\n\n if (parsed.filters?.length) {\n params.filter = parsed.filters.map((f) => `${f.field}:${f.operator}:${f.value}`)\n }\n\n if (parsed.sort?.length) {\n params.sort = parsed.sort.map((s) => `${s.field}:${s.direction}`)\n }\n\n if (parsed.pagination) {\n params.page = parsed.pagination.page\n params.limit = parsed.pagination.limit\n }\n\n if (parsed.search) {\n params.q = parsed.search\n }\n\n return params\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAa,iBAAmB,IAAI,IAAY,CAC9C,KACA,MACA,KACA,MACA,KACA,MACA,UACA,KACA,WACA,SACA,MACF,CAAC,ECuBK,iBAAyC,CAC7C,SAAU,IACV,aAAc,GACd,gBAAiB,IACjB,YAAa,CACf,EAEM,SAAiC,CAAE,GAAG,gBAAiB,EAM7D,SAAgB,wBACd,QACM,CACF,QAAQ,WAAa,IAAA,KAAW,SAAS,SAAW,QAAQ,UAC5D,QAAQ,eAAiB,IAAA,KAAW,SAAS,aAAe,QAAQ,cACpE,QAAQ,kBAAoB,IAAA,KAAW,SAAS,gBAAkB,QAAQ,gBAChF,CAGA,SAAgB,yBAA0D,CACxE,MAAO,CAAE,GAAG,QAAS,CACvB,CAQA,SAAgB,2BAAkC,CAChD,OAAO,OAAO,SAAU,gBAAgB,CAC1C,CAKA,SAAgB,aACd,YACA,cACA,QACc,CACd,GAAI,CAAC,YAAa,MAAO,CAAC,EAE1B,IAAM,MAAQ,MAAM,QAAQ,WAAW,EAAI,YAAc,CAAC,WAAW,EAC/D,QAAwB,CAAC,EACzB,QAAU,cAAgB,IAAI,IAAI,aAAa,EAAI,KACnD,SAAW,SAAS,SAE1B,IAAK,IAAM,QAAQ,MAAO,CAExB,IAAM,WAAa,KAAK,QAAQ,GAAG,EACnC,GAAI,aAAe,GAAI,SAEvB,IAAM,YAAc,KAAK,QAAQ,IAAK,WAAa,CAAC,EACpD,GAAI,cAAgB,GAAI,SAExB,IAAM,MAAQ,KAAK,MAAM,EAAG,UAAU,EAChC,SAAW,KAAK,MAAM,WAAa,EAAG,WAAW,EACjD,MAAQ,KAAK,MAAM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,GAAG,EAAE,OAAO,GAG7E,OAAO,MAAM,SACf,OAAO,KAAO,OAAO,KAAK,IAAK,GAAM,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,GAG9D,OAAO,aACT,OAAO,KAAO,OAAO,WAAW,KAChC,OAAO,MAAQ,OAAO,WAAW,OAG/B,OAAO,SACT,OAAO,EAAI,OAAO,QAGb,MACT"}
|
|
1
|
+
{"version":3,"file":"query-DPlkWOw6.mjs","names":[],"sources":["../src/http/query/types.ts","../src/http/query/parse-query.ts"],"sourcesContent":["/** Supported filter operators for query string parsing */\nexport type FilterOperator =\n | 'eq'\n | 'neq'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'in'\n | 'contains'\n | 'starts'\n | 'ends'\n\nexport const FILTER_OPERATORS = new Set<string>([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'between',\n 'in',\n 'contains',\n 'starts',\n 'ends',\n])\n\nexport interface FilterItem {\n field: string\n operator: FilterOperator\n value: string\n}\n\nexport interface SortItem {\n field: string\n direction: 'asc' | 'desc'\n}\n\nexport interface PaginationParams {\n page: number\n limit: number\n offset: number\n}\n\n/**\n * The result of parsing a query string. ORM-agnostic — pass this to\n * a query builder adapter (Drizzle, Prisma, Sequelize, etc.) to produce\n * database-specific query objects.\n */\nexport interface ParsedQuery {\n filters: FilterItem[]\n sort: SortItem[]\n pagination: PaginationParams\n search: string\n}\n\n/**\n * Helper that extracts the literal field union from a `QueryFieldConfig`\n * key. When the user passes `{ filterable: ['status', 'category'] } as const`,\n * `FieldsOf<typeof config, 'filterable'>` resolves to `'status' | 'category'`.\n *\n * Without `as const`, the arrays widen to `string[]` and the union falls\n * back to `string`. This is the documented escape hatch.\n */\nexport type FieldsOf<\n TConfig extends QueryFieldConfig | undefined,\n K extends 'filterable' | 'sortable' | 'searchable',\n> = TConfig extends { readonly [P in K]: readonly (infer F)[] }\n ? F extends string\n ? F\n : string\n : TConfig extends { columns: infer C }\n ? K extends 'filterable'\n ? keyof C & string\n : string\n : string\n\n/**\n * Narrowed `ParsedQuery` whose `filters[].field` and `sort[].field`\n * unions are constrained to the literal whitelist passed to\n * `ctx.qs()` / `parseQuery()`. Extends `ParsedQuery`, so any function\n * accepting `ParsedQuery` accepts a `TypedParsedQuery<X>` automatically\n * (subtype assignment, no codegen, backward compatible).\n *\n * @example\n * ```ts\n * const parsed = ctx.qs({\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt'],\n * } as const)\n * parsed.filters[0]?.field // 'status' | 'priority'\n * parsed.sort[0]?.field // 'createdAt'\n * ```\n */\nexport interface TypedParsedQuery<\n TConfig extends QueryFieldConfig | undefined,\n> extends ParsedQuery {\n filters: Array<FilterItem & { field: FieldsOf<TConfig, 'filterable'> }>\n sort: Array<SortItem & { field: FieldsOf<TConfig, 'sortable'> }>\n}\n\n/**\n * Restrict which fields can be filtered, sorted, or searched.\n * Fields not in the allow-list are silently ignored.\n *\n * Accepts two forms:\n * 1. **String arrays** (standard): `{ filterable: ['name', 'status'], sortable: ['createdAt'] }`\n * 2. **Column-object maps** (Drizzle-style): `{ columns: { name: col, status: col }, sortable: { createdAt: col } }`\n *\n * When column-object maps are provided, `Object.keys()` is used to derive the field names.\n */\nexport type QueryFieldConfig = StringQueryFieldConfig | ColumnQueryFieldConfig\n\nexport interface StringQueryFieldConfig {\n filterable?: string[]\n sortable?: string[]\n searchable?: string[]\n}\n\n/**\n * Column-object-based field config (e.g., from DrizzleQueryParamsConfig).\n * Keys are the field names used in query strings; values are ORM column references.\n */\nexport interface ColumnQueryFieldConfig {\n columns: Record<string, any>\n sortable?: Record<string, any>\n searchColumns?: any[]\n [key: string]: any\n}\n\n/** Standardized paginated response shape */\nexport interface PaginatedResponse<T = any> {\n data: T[]\n meta: {\n page: number\n limit: number\n total: number\n totalPages: number\n hasNext: boolean\n hasPrev: boolean\n }\n}\n\n/**\n * Interface for ORM-specific query builder adapters.\n * Implement this to translate a `ParsedQuery` into your ORM's query format.\n *\n * @example\n * ```ts\n * // Drizzle adapter\n * class DrizzleQueryAdapter implements QueryBuilderAdapter<DrizzleQueryResult> {\n * build(parsed: ParsedQuery, config: DrizzleConfig): DrizzleQueryResult {\n * // Convert filters → Drizzle SQL conditions\n * // Convert sort → Drizzle orderBy\n * return { where, orderBy, limit, offset }\n * }\n * }\n *\n * // Prisma adapter\n * class PrismaQueryAdapter implements QueryBuilderAdapter<PrismaQueryResult> {\n * build(parsed: ParsedQuery, config: PrismaConfig): PrismaQueryResult {\n * return { where, orderBy, skip, take }\n * }\n * }\n * ```\n */\nexport interface QueryBuilderAdapter<TResult = any, TConfig = any> {\n /** Human-readable name for debugging */\n readonly name: string\n\n /**\n * Convert a ParsedQuery into an ORM-specific query object.\n * @param parsed - The ORM-agnostic parsed query\n * @param config - ORM-specific configuration (column maps, search columns, etc.)\n */\n build(parsed: ParsedQuery, config: TConfig): TResult\n}\n","import {\n FILTER_OPERATORS,\n type FilterItem,\n type FilterOperator,\n type SortItem,\n type PaginationParams,\n type ParsedQuery,\n type QueryFieldConfig,\n type StringQueryFieldConfig,\n type TypedParsedQuery,\n} from './types'\n\n// ── Configurable defaults ───────────────────────────────────────────────\n\n/**\n * Why a rejected field/value was dropped. Surfaced through\n * {@link ParseQueryOptions.onReject} so a caller can warn, count, or\n * return a 400 instead of the historical silent drop.\n */\nexport type QueryRejectReason = 'field-not-allowed' | 'unknown-operator' | 'truncated'\n\nexport interface QueryRejection {\n kind: 'filter' | 'sort' | 'search'\n field: string\n reason: QueryRejectReason\n}\n\nexport interface ParseQueryOptions {\n /** Hard cap on `limit`. Default: global (100, override via {@link setQueryParsingDefaults}). */\n maxLimit?: number\n /** `limit` when the query omits one. Default: global (20). */\n defaultLimit?: number\n /** Max `q` length before truncation. Default: global (200). */\n maxSearchLength?: number\n /**\n * Called once per dropped filter/sort field or truncated search.\n * The historical behaviour is a silent drop; wire this to a logger or\n * a 400 to make over-broad / typo'd queries visible.\n */\n onReject?: (rejection: QueryRejection) => void\n}\n\ninterface QueryParsingDefaults {\n maxLimit: number\n defaultLimit: number\n maxSearchLength: number\n defaultPage: number\n}\n\nconst BUILTIN_DEFAULTS: QueryParsingDefaults = {\n maxLimit: 100,\n defaultLimit: 20,\n maxSearchLength: 200,\n defaultPage: 1,\n}\n\nconst defaults: QueryParsingDefaults = { ...BUILTIN_DEFAULTS }\n\n/**\n * Globally override the query-parsing limits — call once at bootstrap.\n * Per-call {@link ParseQueryOptions} still take precedence over these.\n */\nexport function setQueryParsingDefaults(\n partial: Partial<Omit<QueryParsingDefaults, 'defaultPage'>>,\n): void {\n if (partial.maxLimit !== undefined) defaults.maxLimit = partial.maxLimit\n if (partial.defaultLimit !== undefined) defaults.defaultLimit = partial.defaultLimit\n if (partial.maxSearchLength !== undefined) defaults.maxSearchLength = partial.maxSearchLength\n}\n\n/** Read the current global query-parsing defaults (a copy). */\nexport function getQueryParsingDefaults(): Readonly<QueryParsingDefaults> {\n return { ...defaults }\n}\n\n/**\n * Restore the built-in query-parsing defaults (maxLimit 100, defaultLimit\n * 20, maxSearchLength 200). Useful in test teardown after a\n * {@link setQueryParsingDefaults} override so global state can't leak\n * between tests.\n */\nexport function resetQueryParsingDefaults(): void {\n Object.assign(defaults, BUILTIN_DEFAULTS)\n}\n\n// ── Individual parsers ──────────────────────────────────────────────────\n\n/** Parse filter strings like \"status:eq:active\" into structured objects */\nexport function parseFilters(\n filterParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): FilterItem[] {\n if (!filterParam) return []\n\n const items = Array.isArray(filterParam) ? filterParam : [filterParam]\n const results: FilterItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on first two colons only — value may contain colons (e.g. timestamps)\n const firstColon = item.indexOf(':')\n if (firstColon === -1) continue\n\n const secondColon = item.indexOf(':', firstColon + 1)\n if (secondColon === -1) continue\n\n const field = item.slice(0, firstColon)\n const operator = item.slice(firstColon + 1, secondColon)\n const value = item.slice(secondColon + 1)\n\n if (!field || !value) continue\n if (!FILTER_OPERATORS.has(operator)) {\n onReject?.({ kind: 'filter', field, reason: 'unknown-operator' })\n continue\n }\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'filter', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, operator: operator as FilterOperator, value })\n }\n\n return results\n}\n\n/** Parse sort strings like \"firstName:asc\" into structured objects */\nexport function parseSort(\n sortParam: string | string[] | undefined,\n allowedFields?: string[],\n options?: Pick<ParseQueryOptions, 'onReject'>,\n): SortItem[] {\n if (!sortParam) return []\n\n const items = Array.isArray(sortParam) ? sortParam : [sortParam]\n const results: SortItem[] = []\n const allowed = allowedFields ? new Set(allowedFields) : null\n const onReject = options?.onReject\n\n for (const item of items) {\n // Split on last colon so field names with colons work\n const lastColon = item.lastIndexOf(':')\n if (lastColon === -1) continue\n\n const field = item.slice(0, lastColon)\n const dir = item.slice(lastColon + 1).toLowerCase()\n\n if (!field) continue\n if (dir !== 'asc' && dir !== 'desc') continue\n if (allowed && !allowed.has(field)) {\n onReject?.({ kind: 'sort', field, reason: 'field-not-allowed' })\n continue\n }\n\n results.push({ field, direction: dir })\n }\n\n return results\n}\n\n/** Parse page/limit into pagination with computed offset */\nexport function parsePagination(\n params: {\n page?: string | number\n limit?: string | number\n },\n options?: Pick<ParseQueryOptions, 'maxLimit' | 'defaultLimit'>,\n): PaginationParams {\n const defaultLimit = options?.defaultLimit ?? defaults.defaultLimit\n const maxLimit = options?.maxLimit ?? defaults.maxLimit\n\n let page =\n typeof params.page === 'string'\n ? Number.parseInt(params.page, 10)\n : (params.page ?? defaults.defaultPage)\n let limit =\n typeof params.limit === 'string'\n ? Number.parseInt(params.limit, 10)\n : (params.limit ?? defaultLimit)\n\n if (Number.isNaN(page) || page < 1) page = defaults.defaultPage\n if (Number.isNaN(limit) || limit < 1) limit = defaultLimit\n if (limit > maxLimit) limit = maxLimit\n\n return { page, limit, offset: (page - 1) * limit }\n}\n\n/** Sanitize and truncate search query */\nexport function parseSearchQuery(\n q: string | undefined,\n options?: Pick<ParseQueryOptions, 'maxSearchLength' | 'onReject'>,\n): string {\n if (!q) return ''\n const maxLen = options?.maxSearchLength ?? defaults.maxSearchLength\n const trimmed = q.trim()\n if (trimmed.length > maxLen) {\n options?.onReject?.({ kind: 'search', field: 'q', reason: 'truncated' })\n return trimmed.slice(0, maxLen)\n }\n return trimmed\n}\n\n// ── Config normalizer ───────────────────────────────────────────────────\n\n/**\n * Normalize a QueryFieldConfig into the string-based form.\n * Detects column-object-based configs (DrizzleQueryParamsConfig) by checking\n * for a `columns` property and extracts `Object.keys()`.\n */\nfunction normalizeFieldConfig(config?: QueryFieldConfig): StringQueryFieldConfig | undefined {\n if (!config) return undefined\n\n // Column-object-based config (e.g., DrizzleQueryParamsConfig)\n if ('columns' in config && config.columns && typeof config.columns === 'object') {\n return {\n filterable: Object.keys(config.columns),\n sortable: config.sortable ? Object.keys(config.sortable) : undefined,\n searchable: undefined, // searchColumns are Column objects, not used for string filtering\n }\n }\n\n // Already string-based\n return config as StringQueryFieldConfig\n}\n\n// ── Combined parser ─────────────────────────────────────────────────────\n\n/**\n * Parse a raw Express query object into a structured, ORM-agnostic ParsedQuery.\n *\n * @param query - Raw query string object from `req.query` or Zod-validated object\n * @param fieldConfig - Optional field restrictions (whitelist filterable/sortable/searchable).\n * Accepts both string-based configs (`{ filterable, sortable, searchable }`) and\n * column-object configs (`{ columns, sortable, searchColumns }`).\n * @param options - Limits + an `onReject` hook for dropped/truncated input.\n *\n * @example\n * ```ts\n * // String-based config\n * const parsed = parseQuery(ctx.query, {\n * filterable: ['status', 'priority'],\n * sortable: ['createdAt', 'title'],\n * })\n *\n * // Column-object config (DrizzleQueryParamsConfig)\n * const parsed = parseQuery(ctx.query, TASK_QUERY_CONFIG)\n * ```\n *\n * Query string format:\n * - Filters: `?filter=field:operator:value` (repeatable)\n * - Sort: `?sort=field:asc|desc` (repeatable)\n * - Pagination: `?page=1&limit=20`\n * - Search: `?q=search+term`\n *\n * Filter operators: eq, neq, gt, gte, lt, lte, between, in, contains, starts, ends\n */\nexport function parseQuery<TConfig extends QueryFieldConfig | undefined = undefined>(\n query: Record<string, any>,\n fieldConfig?: TConfig,\n options?: ParseQueryOptions,\n): TypedParsedQuery<TConfig> {\n const normalized = normalizeFieldConfig(fieldConfig)\n const rejectOpts = options?.onReject ? { onReject: options.onReject } : undefined\n return {\n filters: parseFilters(query.filter, normalized?.filterable, rejectOpts),\n sort: parseSort(query.sort, normalized?.sortable, rejectOpts),\n pagination: parsePagination({ page: query.page, limit: query.limit }, options),\n search: parseSearchQuery(query.q, options),\n } as TypedParsedQuery<TConfig>\n}\n\n// ── Query URL builder (for client-side or testing) ──────────────────────\n\n/** Convert ParsedQuery back into query string parameters */\nexport function buildQueryParams(\n parsed: Partial<ParsedQuery>,\n): Record<string, string | string[] | number> {\n const params: Record<string, string | string[] | number> = {}\n\n if (parsed.filters?.length) {\n params.filter = parsed.filters.map((f) => `${f.field}:${f.operator}:${f.value}`)\n }\n\n if (parsed.sort?.length) {\n params.sort = parsed.sort.map((s) => `${s.field}:${s.direction}`)\n }\n\n if (parsed.pagination) {\n params.page = parsed.pagination.page\n params.limit = parsed.pagination.limit\n }\n\n if (parsed.search) {\n params.q = parsed.search\n }\n\n return params\n}\n"],"mappings":";;;;;;;;;;AAcA,MAAa,iBAAmB,IAAI,IAAY,CAC9C,KACA,MACA,KACA,MACA,KACA,MACA,UACA,KACA,WACA,SACA,MACF,CAAC,ECuBK,iBAAyC,CAC7C,SAAU,IACV,aAAc,GACd,gBAAiB,IACjB,YAAa,CACf,EAEM,SAAiC,CAAE,GAAG,gBAAiB,EAM7D,SAAgB,wBACd,QACM,CACF,QAAQ,WAAa,IAAA,KAAW,SAAS,SAAW,QAAQ,UAC5D,QAAQ,eAAiB,IAAA,KAAW,SAAS,aAAe,QAAQ,cACpE,QAAQ,kBAAoB,IAAA,KAAW,SAAS,gBA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OAAO,EACtC,SAAU,OAAO,SAAW,OAAO,KAAK,OAAO,QAAQ,EAAI,IAAA,GAC3D,WAAY,IAAA,EACd,EAIK,MACT,CAiCA,SAAgB,WACd,MACA,YACA,QAC2B,CAC3B,IAAM,WAAa,qBAAqB,WAAW,EAC7C,WAAa,SAAS,SAAW,CAAE,SAAU,QAAQ,QAAS,EAAI,IAAA,GACxE,MAAO,CACL,QAAS,aAAa,MAAM,OAAQ,YAAY,WAAY,UAAU,EACtE,KAAM,UAAU,MAAM,KAAM,YAAY,SAAU,UAAU,EAC5D,WAAY,gBAAgB,CAAE,KAAM,MAAM,KAAM,MAAO,MAAM,KAAM,EAAG,OAAO,EAC7E,OAAQ,iBAAiB,MAAM,EAAG,OAAO,CAC3C,CACF,CAKA,SAAgB,iBACd,OAC4C,CAC5C,IAAM,OAAqD,CAAC,EAmB5D,OAjBI,OAAO,SAAS,SAClB,OAAO,OAAS,OAAO,QAAQ,IAAK,GAAM,GAAG,EAAE,MAAM,GAAG,EAAE,SAAS,GAAG,EAAE,OAAO,GAG7E,OAAO,MAAM,SACf,OAAO,KAAO,OAAO,KAAK,IAAK,GAAM,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,GAG9D,OAAO,aACT,OAAO,KAAO,OAAO,WAAW,KAChC,OAAO,MAAQ,OAAO,WAAW,OAG/B,OAAO,SACT,OAAO,EAAI,OAAO,QAGb,MACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.0
|
|
2
|
+
* @forinda/kickjs v9.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
11
|
function readCookies(req){let source=req;if(source.cookies)return source.cookies;let header=source.headers?.cookie;return typeof header==`string`?parseCookieHeader(header):{}}function parseCookieHeader(header){let out={};for(let pair of header.split(`;`)){let eq=pair.indexOf(`=`);if(eq===-1)continue;let key=pair.slice(0,eq).trim();if(!key)continue;let value=pair.slice(eq+1).trim();value.startsWith(`"`)&&value.endsWith(`"`)&&(value=value.slice(1,-1));try{out[key]=decodeURIComponent(value)}catch{out[key]=value}}return out}function serializeCookie(name,value,options){let parts=[`${name}=${encodeURIComponent(value)}`];if(options.maxAge!==void 0&&parts.push(`Max-Age=${Math.floor(options.maxAge/1e3)}`),options.expires&&parts.push(`Expires=${options.expires.toUTCString()}`),options.domain&&parts.push(`Domain=${options.domain}`),parts.push(`Path=${options.path??`/`}`),options.httpOnly&&parts.push(`HttpOnly`),options.secure&&parts.push(`Secure`),options.sameSite){let value=options.sameSite===!0?`Strict`:options.sameSite;parts.push(`SameSite=${value.charAt(0).toUpperCase()}${value.slice(1)}`)}return parts.join(`; `)}function setCookie(res,name,value,options={}){let target=res;if(typeof target.cookie==`function`){target.cookie(name,value,options);return}let cookie=serializeCookie(name,value,options),prior=target.getHeader?.(`Set-Cookie`),all=prior===void 0?[cookie]:[...Array.isArray(prior)?prior:[prior],cookie];target.setHeader?.(`Set-Cookie`,all)}function sendJson(res,status,body){let target=res;if(typeof target.status==`function`){let chained=target.status(status);if(typeof chained?.json==`function`){chained.json(body);return}}target.statusCode=status,target.getHeader?.(`content-type`)||target.setHeader?.(`content-type`,`application/json; charset=utf-8`),target.end?.(JSON.stringify(body))}export{setCookie as i,readCookies as n,sendJson as r,parseCookieHeader as t};
|
|
12
|
-
//# sourceMappingURL=respond-
|
|
12
|
+
//# sourceMappingURL=respond-DjxNwGnN.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"respond-
|
|
1
|
+
{"version":3,"file":"respond-DjxNwGnN.mjs","names":[],"sources":["../src/http/middleware/respond.ts"],"sourcesContent":["/**\n * Response helpers that work on every runtime.\n *\n * Connect middleware receives an Express response under Express and a raw\n * `ServerResponse` under Fastify and h3. `res.cookie()` and `res.status().json()`\n * are Express conveniences that do not exist on the raw object, so a shipped\n * middleware reaching for them works on one engine and throws on the other two:\n *\n * csrf → `res.cookie()` threw before any check ran, so EVERY request\n * became a 500 — including safe methods the middleware is\n * supposed to wave through\n * rateLimit → `res.status()` threw only once the limit was hit, and the\n * throw left the request hanging rather than answering 429\n * session → `res.cookie()` threw on every response that issued a session\n *\n * These take the Express path when it is there — so behaviour under Express is\n * byte-identical to before — and fall back to the Node primitives otherwise.\n *\n * @module @forinda/kickjs/http/middleware/respond\n */\n\n/**\n * Cookies on the request, whoever parsed them.\n *\n * `req.cookies` exists only when an upstream cookie parser populated it —\n * `cookie-parser` under Express, nothing at all under Fastify and h3, which\n * pass a raw node request. A middleware that reads only `req.cookies` therefore\n * sees no cookies on those runtimes, and none under Express either unless the\n * app happens to mount a parser.\n *\n * For `csrf` that broke the double-submit flow outright: with no cookie visible\n * it minted a fresh token on every request and compared the submitted header\n * against that new value, so a client could never complete a protected request.\n */\nexport function readCookies(req: unknown): Record<string, string> {\n const source = req as { cookies?: Record<string, string>; headers?: Record<string, unknown> }\n if (source.cookies) return source.cookies\n const header = source.headers?.cookie\n return typeof header === 'string' ? parseCookieHeader(header) : {}\n}\n\n/** `a=1; b=2` → `{ a: '1', b: '2' }`. */\nexport function parseCookieHeader(header: string): Record<string, string> {\n const out: Record<string, string> = {}\n for (const pair of header.split(';')) {\n const eq = pair.indexOf('=')\n if (eq === -1) continue\n const key = pair.slice(0, eq).trim()\n if (!key) continue\n let value = pair.slice(eq + 1).trim()\n if (value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1)\n }\n try {\n out[key] = decodeURIComponent(value)\n } catch {\n // A malformed escape is not a reason to lose the whole cookie jar.\n out[key] = value\n }\n }\n return out\n}\n\n/** Cookie attributes, matching the subset of Express's `res.cookie` we use. */\nexport interface CookieOptions {\n maxAge?: number\n expires?: Date\n domain?: string\n path?: string\n httpOnly?: boolean\n secure?: boolean\n sameSite?: boolean | 'lax' | 'strict' | 'none'\n}\n\ninterface AnyResponse {\n cookie?: (name: string, value: string, options?: CookieOptions) => unknown\n status?: (code: number) => { json?: (body: unknown) => unknown }\n statusCode?: number\n getHeader?: (name: string) => unknown\n setHeader?: (name: string, value: unknown) => unknown\n end?: (chunk?: unknown) => unknown\n}\n\n/** `Set-Cookie` value for one cookie, per RFC 6265 §4.1. */\nfunction serializeCookie(name: string, value: string, options: CookieOptions): string {\n const parts = [`${name}=${encodeURIComponent(value)}`]\n // Express takes `maxAge` in milliseconds; `Max-Age` is seconds.\n if (options.maxAge !== undefined) parts.push(`Max-Age=${Math.floor(options.maxAge / 1000)}`)\n if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`)\n if (options.domain) parts.push(`Domain=${options.domain}`)\n parts.push(`Path=${options.path ?? '/'}`)\n if (options.httpOnly) parts.push('HttpOnly')\n if (options.secure) parts.push('Secure')\n if (options.sameSite) {\n // `true` means Strict, matching Express.\n const value = options.sameSite === true ? 'Strict' : options.sameSite\n parts.push(`SameSite=${value.charAt(0).toUpperCase()}${value.slice(1)}`)\n }\n return parts.join('; ')\n}\n\n/** Set a cookie without assuming Express. Appends, never replaces. */\nexport function setCookie(\n res: unknown,\n name: string,\n value: string,\n options: CookieOptions = {},\n): void {\n const target = res as AnyResponse\n if (typeof target.cookie === 'function') {\n target.cookie(name, value, options)\n return\n }\n const cookie = serializeCookie(name, value, options)\n const prior = target.getHeader?.('Set-Cookie')\n const all = prior === undefined ? [cookie] : [...(Array.isArray(prior) ? prior : [prior]), cookie]\n target.setHeader?.('Set-Cookie', all)\n}\n\n/** Send a JSON body with a status, without assuming Express. */\nexport function sendJson(res: unknown, status: number, body: unknown): void {\n const target = res as AnyResponse\n if (typeof target.status === 'function') {\n const chained = target.status(status)\n if (typeof chained?.json === 'function') {\n chained.json(body)\n return\n }\n }\n target.statusCode = status\n if (!target.getHeader?.('content-type')) {\n target.setHeader?.('content-type', 'application/json; charset=utf-8')\n }\n target.end?.(JSON.stringify(body))\n}\n"],"mappings":";;;;;;;;;;AAkCA,SAAgB,YAAY,I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MAAM,CAAC,GAAG,CACzE,CACA,OAAO,MAAM,KAAK,IAAI,CACxB,CAGA,SAAgB,UACd,IACA,KACA,MACA,QAAyB,CAAC,EACpB,CACN,IAAM,OAAS,IACf,GAAI,OAAO,OAAO,QAAW,WAAY,CACvC,OAAO,OAAO,KAAM,MAAO,OAAO,EAClC,MACF,CACA,IAAM,OAAS,gBAAgB,KAAM,MAAO,OAAO,EAC7C,MAAQ,OAAO,YAAY,YAAY,EACvC,IAAM,QAAU,IAAA,GAAY,CAAC,MAAM,EAAI,CAAC,GAAI,MAAM,QAAQ,KAAK,EAAI,MAAQ,CAAC,KAAK,EAAI,MAAM,EACjG,OAAO,YAAY,aAAc,GAAG,CACtC,CAGA,SAAgB,SAAS,IAAc,OAAgB,KAAqB,CAC1E,IAAM,OAAS,IACf,GAAI,OAAO,OAAO,QAAW,WAAY,CACvC,IAAM,QAAU,OAAO,OAAO,MAAM,EACpC,GAAI,OAAO,SAAS,MAAS,WAAY,CACvC,QAAQ,KAAK,IAAI,EACjB,MACF,CACF,CACA,OAAO,WAAa,OACf,OAAO,YAAY,cAAc,GACpC,OAAO,YAAY,eAAgB,iCAAiC,EAEtE,OAAO,MAAM,KAAK,UAAU,IAAI,CAAC,CACnC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs v9.0
|
|
2
|
+
* @forinda/kickjs v9.1.0
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,5 +8,5 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import{METADATA}from"./core/interfaces.mjs";import{a as getMethodMeta,c as pushClassMeta,l as pushMethodMeta,t as getClassMeta}from"./metadata-
|
|
12
|
-
//# sourceMappingURL=route-flag-
|
|
11
|
+
import{METADATA}from"./core/interfaces.mjs";import{a as getMethodMeta,c as pushClassMeta,l as pushMethodMeta,t as getClassMeta}from"./metadata-CW4I35nN.mjs";const FLAG_UNSET=Symbol(`kick.flagUnset`);function isDecoratorApplication(args){let[target,propertyKey]=args;return typeof propertyKey==`string`||typeof propertyKey==`symbol`||args.length===1&&typeof target==`function`}function defineRouteFlag(name){if(name.startsWith(`!`))throw Error(`defineRouteFlag('${name}'): a flag name cannot start with '!' — that prefix is reserved for negated tests ('!${name.slice(1)}' means "does not carry ${name.slice(1)}"). Rename the flag.`);function apply(value,target,propertyKey){let declaration={name,value};if(propertyKey===void 0){pushClassMeta(METADATA.CLASS_FLAGS,target,declaration);return}pushMethodMeta(METADATA.METHOD_FLAGS,target.constructor,String(propertyKey),declaration)}let flag=(...args)=>{if(isDecoratorApplication(args)){apply(!0,args[0],args[1]);return}let value=args[0];return(target,propertyKey)=>{apply(value,target,propertyKey)}};return Object.defineProperty(flag,"flagName",{value:name,enumerable:!0}),Object.defineProperty(flag,"off",{value:(target,propertyKey)=>{apply(FLAG_UNSET,target,propertyKey)},enumerable:!0}),flag}function resolveRouteFlags(classDeclarations,methodDeclarations,mountDeclarations=[]){let resolved=new Map;for(let{name,value}of[...mountDeclarations,...classDeclarations,...methodDeclarations]){if(value===FLAG_UNSET){resolved.delete(name);continue}resolved.set(name,value)}return resolved}function matchesFlagTest(test,flags,route){let resolved=flags??EMPTY_FLAGS;if(typeof test==`function`)return test({flags:resolved,route});if(typeof test==`string`)return isNegated(test)?!resolved.has(stripNegation(test)):resolved.has(test);if(test.length===0)return!1;let negated=isNegated(test[0]);if(test.some(name=>isNegated(name)!==negated))throw Error(`Route flag test mixes polarities: [${test.map(n=>`'${n}'`).join(`, `)}]. A list is either all names ("carries any of these") or all negated ("carries none of these") — for anything else, pass a predicate.`);return negated?test.every(name=>!resolved.has(stripNegation(name))):test.some(name=>resolved.has(name))}function assertFlagTest(test,site){if(typeof test==`function`||typeof test==`string`||test.length===0)return;let negated=isNegated(test[0]);if(test.some(name=>isNegated(name)!==negated))throw Error(`${site}: route flag test mixes polarities: [${test.map(n=>`'${n}'`).join(`, `)}]. A list is either all names ("carries any of these") or all negated ("carries none of these") — for anything else, pass a predicate.`)}const isNegated=name=>name.startsWith(`!`),stripNegation=name=>name.slice(1),EMPTY_FLAGS=new Map,ROUTE_SLOT=Symbol.for(`kick.route`);function getRouteFlags(controllerClass,handlerName){return resolveRouteFlags(getClassFlagDeclarations(controllerClass),getMethodFlagDeclarations(controllerClass,handlerName),getMountFlagDeclarations(controllerClass))}function getClassFlagDeclarations(controllerClass){return getClassMeta(METADATA.CLASS_FLAGS,controllerClass,[])}function getMethodFlagDeclarations(controllerClass,handlerName){return getMethodMeta(METADATA.METHOD_FLAGS,controllerClass,handlerName,[])}function toFlagDeclarations(flags,site){return flags?(Array.isArray(flags)?flags.map(name=>[name,!0]):Object.entries(flags)).map(([name,value])=>{if(name.startsWith(`!`))throw Error(`${site}: a flag name cannot start with '!' — that prefix is reserved for negated tests, and a declaration has no negative form. Remove the flag instead of declaring '${name}'.`);return{name,value}}):[]}const MOUNT_FLAGS=new WeakMap;function registerMountFlags(controllerClass,declarations){if(declarations.length===0){MOUNT_FLAGS.delete(controllerClass);return}MOUNT_FLAGS.set(controllerClass,[...declarations])}function getMountFlagDeclarations(controllerClass){return MOUNT_FLAGS.get(controllerClass)??[]}export{getMethodFlagDeclarations as a,registerMountFlags as c,getClassFlagDeclarations as i,resolveRouteFlags as l,assertFlagTest as n,getRouteFlags as o,defineRouteFlag as r,matchesFlagTest as s,ROUTE_SLOT as t,toFlagDeclarations as u};
|
|
12
|
+
//# sourceMappingURL=route-flag-sIYXay3q.mjs.map
|