express-file-cluster 0.9.6 → 0.10.2
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/auth/index.cjs +7 -6
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +5 -5
- package/dist/chunk-3SWI46YK.js +74 -0
- package/dist/chunk-3SWI46YK.js.map +1 -0
- package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
- package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
- package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
- package/dist/chunk-74BSJXWD.cjs +220 -0
- package/dist/chunk-74BSJXWD.cjs.map +1 -0
- package/dist/{chunk-6KHBJOLB.cjs → chunk-7BC3AN7R.cjs} +14 -14
- package/dist/{chunk-6KHBJOLB.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
- package/dist/chunk-AGOYTFRO.cjs +42 -0
- package/dist/chunk-AGOYTFRO.cjs.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-B6MB6HEG.js} +5 -1
- package/dist/chunk-B6MB6HEG.js.map +1 -0
- package/dist/{chunk-OFA7OGN5.js → chunk-BG4A7Z32.js} +176 -7
- package/dist/chunk-BG4A7Z32.js.map +1 -0
- package/dist/{chunk-45BWAR6P.js → chunk-C2FOZ7ME.js} +4 -4
- package/dist/chunk-CGY7JU4Y.cjs +8 -0
- package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
- package/dist/{chunk-BBSZLGZW.js → chunk-DN4TCGYB.js} +43 -14
- package/dist/chunk-DN4TCGYB.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-H2PVWCWC.cjs} +6 -2
- package/dist/chunk-H2PVWCWC.cjs.map +1 -0
- package/dist/{chunk-TYCYYLLM.cjs → chunk-IUZ6A7PB.cjs} +20 -53
- package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
- package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
- package/dist/chunk-JP36TLL4.cjs.map +1 -0
- package/dist/chunk-KLWL7XSC.js +220 -0
- package/dist/chunk-KLWL7XSC.js.map +1 -0
- package/dist/{chunk-QL6EWT4B.cjs → chunk-M53GODCX.cjs} +44 -15
- package/dist/chunk-M53GODCX.cjs.map +1 -0
- package/dist/{chunk-7ZESZG3J.js → chunk-MUVO7MGS.js} +4 -4
- package/dist/{chunk-VWSUQKCJ.cjs → chunk-R2K7AFIB.cjs} +286 -117
- package/dist/chunk-R2K7AFIB.cjs.map +1 -0
- package/dist/{chunk-ULWNHN6P.js → chunk-RETV3GKE.js} +9 -42
- package/dist/chunk-RETV3GKE.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-RPL2IFWK.cjs} +46 -7
- package/dist/chunk-RPL2IFWK.cjs.map +1 -0
- package/dist/{chunk-FMA76PRH.cjs → chunk-TBIVIR6L.cjs} +15 -15
- package/dist/{chunk-FMA76PRH.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
- package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
- package/dist/chunk-V73R76I4.js.map +1 -0
- package/dist/chunk-XPY5TQDK.js +42 -0
- package/dist/chunk-XPY5TQDK.js.map +1 -0
- package/dist/{chunk-RGT4ZVHL.cjs → chunk-Y4NKIXUL.cjs} +110 -55
- package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
- package/dist/{chunk-2SETEVMO.js → chunk-Y75V5FCU.js} +100 -45
- package/dist/chunk-Y75V5FCU.js.map +1 -0
- package/dist/cli/db-runner.cjs +2059 -126
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +2034 -102
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +50 -29
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +39 -21
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +23 -0
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/compose.md +1 -1
- package/dist/docs/api-reference/db.md +8 -0
- package/dist/docs/api-reference/ignite.md +13 -1
- package/dist/docs/api-reference/testing.md +26 -0
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/core-concepts/file-based-routing.md +2 -0
- package/dist/docs/core-concepts/middleware.md +2 -2
- package/dist/docs/getting-started/index.md +6 -1
- package/dist/docs/guides/authentication.md +33 -0
- package/dist/docs/guides/caching.md +34 -1
- package/dist/docs/guides/database.md +17 -0
- package/dist/docs/guides/environment-variables.md +6 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/generated-portals.md +3 -1
- package/dist/docs/guides/logging.md +17 -0
- package/dist/docs/guides/migrations.md +26 -3
- package/dist/docs/guides/testing.md +31 -0
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +5 -1
- package/dist/docs/skills/api-surface.md +25 -4
- package/dist/docs/skills/auth-internals.md +14 -1
- package/dist/docs/skills/pre-flight.md +6 -0
- package/dist/docs/skills/routing-rules.md +1 -1
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +13 -4
- package/dist/docs/versioning.md +1 -1
- package/dist/index.cjs +135 -255
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +228 -3
- package/dist/index.d.ts +228 -3
- package/dist/index.js +96 -217
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-4X2YT4RB.js +14 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
- package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
- package/dist/registry/index.json +39 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +5 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/testing-cjs.cjs +5 -0
- package/dist/testing.cjs +59 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +27 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.js +58 -0
- package/dist/testing.js.map +1 -0
- package/dist/thread-runner.cjs +9 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-DAsBKVM-.d.ts → types-CPMFTVXm.d.cts} +15 -1
- package/dist/{types-DAsBKVM-.d.cts → types-CPMFTVXm.d.ts} +15 -1
- package/package.json +6 -1
- package/dist/chunk-2SETEVMO.js.map +0 -1
- package/dist/chunk-73XJUT2S.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-DUADUR6R.cjs.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-OFA7OGN5.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RGT4ZVHL.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYCYYLLM.cjs.map +0 -1
- package/dist/chunk-ULWNHN6P.js.map +0 -1
- package/dist/chunk-VWSUQKCJ.cjs.map +0 -1
- package/dist/pgboss-backend-DSO3QTNK.cjs +0 -14
- package/dist/pgboss-backend-DSO3QTNK.cjs.map +0 -1
- package/dist/pgboss-backend-I6DFUNRM.js +0 -14
- /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
- /package/dist/{chunk-45BWAR6P.js.map → chunk-C2FOZ7ME.js.map} +0 -0
- /package/dist/{chunk-7ZESZG3J.js.map → chunk-MUVO7MGS.js.map} +0 -0
- /package/dist/{pgboss-backend-I6DFUNRM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
-
import { S as Simplify, I as InferSchema, b as InferCreateInput, M as ModelSchema, c as ModelOptions, d as InferredModel, e as TableSchema, f as TableOptions, g as SortDirection, C as CollectionSchema, R as RouteEntry, E as EFCConfig } from './types-
|
|
3
|
-
export { A as AuthStrategy,
|
|
2
|
+
import { S as Simplify, I as InferSchema, b as InferCreateInput, M as ModelSchema, c as ModelOptions, d as InferredModel, e as TableSchema, f as TableOptions, g as SortDirection, h as InferRecord, C as CollectionSchema, R as RouteEntry, E as EFCConfig } from './types-CPMFTVXm.js';
|
|
3
|
+
export { A as AuthStrategy, i as CacheConfig, j as CollectionFieldDefinition, k as CorsConfig, D as DatabaseEngine, l as DatabasePoolConfig, m as DefaultOperator, F as FieldDefinition, n as Filter, o as FilterOperators, p as FindOptions, G as GeoPoint, q as IndexDefinition, r as InferCreate, L as LoggingConfig, s as MigrationContext, t as ModelCRUD, u as ModelQueryOptions, v as ModelRecord, Q as QueryLogConfig, w as RequestSchema, x as RouteMeta, y as RouteMethodMeta, z as RouteSchema, B as ScalarKeys, H as SchemaField, J as TableFieldDefinition, K as TableRelation, N as TableSchemaField, a as TaskDefinition, T as TaskOptions, U as Update, V as ValidationIssue, O as Validator } from './types-CPMFTVXm.js';
|
|
4
4
|
import { Logger } from 'pino';
|
|
5
5
|
import { Request, RequestHandler } from 'express';
|
|
6
6
|
export { listTasks } from './tasks/index.js';
|
|
@@ -653,6 +653,30 @@ declare module 'express-serve-static-core' {
|
|
|
653
653
|
}
|
|
654
654
|
}
|
|
655
655
|
|
|
656
|
+
/** Aggregated per-process model operation statistics; never contains SQL/parameter values. */
|
|
657
|
+
interface QueryMetric {
|
|
658
|
+
model: string;
|
|
659
|
+
op: string;
|
|
660
|
+
calls: number;
|
|
661
|
+
errors: number;
|
|
662
|
+
statements: number;
|
|
663
|
+
totalMs: number;
|
|
664
|
+
minMs: number;
|
|
665
|
+
maxMs: number;
|
|
666
|
+
meanMs: number;
|
|
667
|
+
slow: number;
|
|
668
|
+
}
|
|
669
|
+
interface QueryMetricsSnapshot {
|
|
670
|
+
enabled: boolean;
|
|
671
|
+
since: number;
|
|
672
|
+
dropped: number;
|
|
673
|
+
entries: ReadonlyArray<QueryMetric>;
|
|
674
|
+
}
|
|
675
|
+
/** Returns detached, deterministically ordered counters; no logs or SQL are exposed. */
|
|
676
|
+
declare function getQueryMetrics(): QueryMetricsSnapshot;
|
|
677
|
+
/** Clears this process's counters/window; does not disable collection. */
|
|
678
|
+
declare function resetQueryMetrics(): void;
|
|
679
|
+
|
|
656
680
|
interface CacheSetOptions {
|
|
657
681
|
/** Seconds until the entry expires. Omit for no expiry. */
|
|
658
682
|
ttl?: number;
|
|
@@ -672,9 +696,54 @@ interface Cache {
|
|
|
672
696
|
wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>): Promise<T>;
|
|
673
697
|
/** Deletes every key starting with `keyPrefix` (all of this app's keys when omitted). */
|
|
674
698
|
clear(keyPrefix?: string): Promise<number>;
|
|
699
|
+
/**
|
|
700
|
+
* Atomically adds 1 and returns the new count — across workers and instances (Redis) or
|
|
701
|
+
* this machine's workers (memory). `ttl` applies when the key is created (a fixed
|
|
702
|
+
* window). Resolves `undefined` when the backend is unreachable: a count can't be made up.
|
|
703
|
+
*/
|
|
704
|
+
incr(key: string, options?: CacheSetOptions): Promise<number | undefined>;
|
|
675
705
|
}
|
|
676
706
|
declare const cache: Cache;
|
|
677
707
|
|
|
708
|
+
interface RateLimitOptions {
|
|
709
|
+
/** Window length: seconds, or `'30s'`, `'15m'`, `'1h'`, `'1d'`. */
|
|
710
|
+
window: number | string;
|
|
711
|
+
/** Requests allowed per window and key. */
|
|
712
|
+
max: number;
|
|
713
|
+
/**
|
|
714
|
+
* Who a request counts against. Default: the client IP (`req.ip`) — behind a proxy or load
|
|
715
|
+
* balancer set `trustProxy` in ignite(), or every client shares the proxy's IP. Return
|
|
716
|
+
* `undefined` to not limit this request.
|
|
717
|
+
*/
|
|
718
|
+
key?: (req: Request) => string | undefined;
|
|
719
|
+
/**
|
|
720
|
+
* Which counter: requests to routes with the same name share a limit. Default: the route
|
|
721
|
+
* pattern (`/users/:id`), so each route file has its own — or the path, for middleware
|
|
722
|
+
* that isn't on a route.
|
|
723
|
+
*/
|
|
724
|
+
name?: string;
|
|
725
|
+
/** Body of the 429 response. Default: `'Too many requests, try again later'`. */
|
|
726
|
+
message?: string;
|
|
727
|
+
/**
|
|
728
|
+
* The cache can't be reached: `'allow'` (default) lets requests through — a limiter
|
|
729
|
+
* shouldn't take the API down with it; `'reject'` answers 503.
|
|
730
|
+
*/
|
|
731
|
+
onCacheError?: 'allow' | 'reject';
|
|
732
|
+
/** Send `RateLimit-Limit/Remaining/Reset` (and `Retry-After` on 429). Default: true. */
|
|
733
|
+
headers?: boolean;
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Limits requests per key (default: client IP) to `max` per `window`, counted in the cache
|
|
737
|
+
* so the limit holds across every worker and instance:
|
|
738
|
+
*
|
|
739
|
+
* ```ts
|
|
740
|
+
* export const middlewares = [rateLimit({ window: '15m', max: 10 })];
|
|
741
|
+
* ```
|
|
742
|
+
*
|
|
743
|
+
* Needs `cache` in ignite() — use the Redis backend when you run more than one instance.
|
|
744
|
+
*/
|
|
745
|
+
declare function rateLimit(options: RateLimitOptions): RequestHandler;
|
|
746
|
+
|
|
678
747
|
interface CacheResponseOptions {
|
|
679
748
|
/** Seconds to keep a response. */
|
|
680
749
|
ttl: number;
|
|
@@ -722,6 +791,152 @@ declare function defineModel<T extends object = never, const S extends ModelSche
|
|
|
722
791
|
*/
|
|
723
792
|
declare function defineTable<const S extends TableSchema, const O extends TableOptions = object>(name: string, schema: S, options?: O): TableModel<S, O>;
|
|
724
793
|
|
|
794
|
+
type AnyRecord$1 = Record<string, unknown>;
|
|
795
|
+
type Elem$1<V> = V extends readonly (infer E)[] ? E : never;
|
|
796
|
+
type Keys<T> = keyof T & string;
|
|
797
|
+
/** Values that are objects with fields of their own (not arrays, dates, buffers). */
|
|
798
|
+
type Nested<V> = V extends readonly unknown[] | Date | Uint8Array | bigint ? never : V extends object ? V : never;
|
|
799
|
+
/** A field, or one level into an embedded object: `'name'`, `'address.city'`. */
|
|
800
|
+
type Path<T> = Keys<T> | {
|
|
801
|
+
[K in Keys<T>]: `${K}.${Keys<Nested<NonNullable<T[K]>>>}`;
|
|
802
|
+
}[Keys<T>];
|
|
803
|
+
/** `'$field'` / `'$embedded.field'` — a reference to the current record's values. */
|
|
804
|
+
type FieldRef<T> = `$${Path<T>}`;
|
|
805
|
+
/** The value a `'$field'` reference (or a literal) resolves to. */
|
|
806
|
+
type Ref<T, P> = P extends `$${infer K}.${infer R}` ? K extends keyof T ? R extends keyof Nested<NonNullable<T[K]>> ? Nested<NonNullable<T[K]>>[R] : unknown : unknown : P extends `$${infer K}` ? K extends keyof T ? T[K] : unknown : P;
|
|
807
|
+
/** `$sum` / `$avg` over a decimal field stay exact strings; numbers stay numbers. */
|
|
808
|
+
type Numeric<V> = [NonNullable<V>] extends [string] ? string : number;
|
|
809
|
+
type Accumulator<T> = {
|
|
810
|
+
$sum: FieldRef<T> | number;
|
|
811
|
+
} | {
|
|
812
|
+
$avg: FieldRef<T>;
|
|
813
|
+
} | {
|
|
814
|
+
$min: FieldRef<T>;
|
|
815
|
+
} | {
|
|
816
|
+
$max: FieldRef<T>;
|
|
817
|
+
} | {
|
|
818
|
+
$first: FieldRef<T>;
|
|
819
|
+
} | {
|
|
820
|
+
$last: FieldRef<T>;
|
|
821
|
+
} | {
|
|
822
|
+
$push: FieldRef<T>;
|
|
823
|
+
} | {
|
|
824
|
+
$addToSet: FieldRef<T>;
|
|
825
|
+
} | {
|
|
826
|
+
$count: Record<string, never>;
|
|
827
|
+
};
|
|
828
|
+
type AccResult<T, A> = A extends {
|
|
829
|
+
$sum: infer F;
|
|
830
|
+
} ? F extends number ? number : Numeric<Ref<T, F>> : A extends {
|
|
831
|
+
$avg: infer F;
|
|
832
|
+
} ? Numeric<Ref<T, F>> | null : A extends {
|
|
833
|
+
$count: unknown;
|
|
834
|
+
} ? number : A extends {
|
|
835
|
+
$min: infer F;
|
|
836
|
+
} | {
|
|
837
|
+
$max: infer F;
|
|
838
|
+
} | {
|
|
839
|
+
$first: infer F;
|
|
840
|
+
} | {
|
|
841
|
+
$last: infer F;
|
|
842
|
+
} ? Ref<T, F> : A extends {
|
|
843
|
+
$push: infer F;
|
|
844
|
+
} | {
|
|
845
|
+
$addToSet: infer F;
|
|
846
|
+
} ? NonNullable<Ref<T, F>>[] : unknown;
|
|
847
|
+
type GroupKey<T> = FieldRef<T> | null | {
|
|
848
|
+
[k: string]: FieldRef<T>;
|
|
849
|
+
};
|
|
850
|
+
type GroupId<T, I> = I extends null ? null : I extends string ? Ref<T, I> : {
|
|
851
|
+
-readonly [K in keyof I]: Ref<T, I[K]>;
|
|
852
|
+
};
|
|
853
|
+
/** `$group` output: `_id` (plus `id`, its string form) and one field per accumulator. */
|
|
854
|
+
type GroupResult<T, G> = Simplify<{
|
|
855
|
+
_id: GroupId<T, G extends {
|
|
856
|
+
_id: infer I;
|
|
857
|
+
} ? I : null>;
|
|
858
|
+
id: string;
|
|
859
|
+
} & {
|
|
860
|
+
[K in Exclude<keyof G, '_id'>]: AccResult<T, G[K]>;
|
|
861
|
+
}>;
|
|
862
|
+
/** Fields whose values are arrays. */
|
|
863
|
+
type ArrayKeys<T> = {
|
|
864
|
+
[K in Keys<T>]: NonNullable<T[K]> extends readonly unknown[] ? K : never;
|
|
865
|
+
}[Keys<T>];
|
|
866
|
+
/** `T` with ref field `K` replaced by the `M` record(s) it points to. */
|
|
867
|
+
type LookedUp<T, K extends keyof T, M> = Simplify<Omit<T, K> & {
|
|
868
|
+
[P in K]-?: NonNullable<T[K]> extends readonly unknown[] ? InferRecord<M>[] : InferRecord<M> | null;
|
|
869
|
+
}>;
|
|
870
|
+
/** A model `lookup` can join: anything with inferred record types and a mongoose `raw()`. */
|
|
871
|
+
interface LookupTarget {
|
|
872
|
+
readonly name: string;
|
|
873
|
+
readonly $types?: {
|
|
874
|
+
record: unknown;
|
|
875
|
+
};
|
|
876
|
+
raw(): Promise<unknown>;
|
|
877
|
+
}
|
|
878
|
+
type Stage = AnyRecord$1 | (() => Promise<AnyRecord$1[]>);
|
|
879
|
+
declare class Pipeline<T> implements PromiseLike<T[]> {
|
|
880
|
+
private readonly run;
|
|
881
|
+
private readonly stages;
|
|
882
|
+
/** @internal */
|
|
883
|
+
constructor(run: (stages: AnyRecord$1[]) => Promise<unknown[]>, stages?: Stage[]);
|
|
884
|
+
private next;
|
|
885
|
+
/** `$match` — same filter vocabulary as `find`. */
|
|
886
|
+
match(filter: AnyRecord$1): Pipeline<T>;
|
|
887
|
+
sort(spec: Partial<Record<Keys<T>, SortDirection>> & Record<string, SortDirection>): Pipeline<T>;
|
|
888
|
+
skip(n: number): Pipeline<T>;
|
|
889
|
+
limit(n: number): Pipeline<T>;
|
|
890
|
+
/** `$sample` — `n` random records. */
|
|
891
|
+
sample(n: number): Pipeline<T>;
|
|
892
|
+
/** `$project` with an inclusion spec: the result has only those fields (and `id`). */
|
|
893
|
+
project<const P extends Partial<Record<Keys<T>, 1 | true>>>(spec: P): Pipeline<Simplify<Pick<T, Extract<keyof P, keyof T>> & {
|
|
894
|
+
id: string;
|
|
895
|
+
}>>;
|
|
896
|
+
/**
|
|
897
|
+
* `$unwind` an array field: one result per element, the field holding that element.
|
|
898
|
+
* `preserveNullAndEmptyArrays` keeps records without elements (the field is then null).
|
|
899
|
+
*/
|
|
900
|
+
unwind<K extends ArrayKeys<T>, const Keep extends boolean = false>(path: `$${K}`, options?: {
|
|
901
|
+
preserveNullAndEmptyArrays?: Keep;
|
|
902
|
+
}): Pipeline<Simplify<Omit<T, K> & {
|
|
903
|
+
[P in K]-?: Keep extends true ? Elem$1<NonNullable<T[K]>> | null : Elem$1<NonNullable<T[K]>>;
|
|
904
|
+
}>>;
|
|
905
|
+
/** `$group` — `_id` is `'$field'`, `null` or `{ key: '$field' }`; accumulators are typed. */
|
|
906
|
+
group<const G extends {
|
|
907
|
+
_id: GroupKey<T>;
|
|
908
|
+
} & Record<string, unknown>>(spec: G & {
|
|
909
|
+
[K in Exclude<keyof G, '_id'>]: Accumulator<T>;
|
|
910
|
+
}): Pipeline<GroupResult<T, G>>;
|
|
911
|
+
/** `$count` — a single `{ [field]: n }` (no result at all when nothing matched). */
|
|
912
|
+
count<const F extends string>(field: F): Pipeline<{
|
|
913
|
+
[P in F]: number;
|
|
914
|
+
}>;
|
|
915
|
+
/** `$addFields` / `$set` — say what the new fields are: `addFields<{ total: number }>({ … })`. */
|
|
916
|
+
addFields<A extends AnyRecord$1>(spec: Record<keyof A, unknown>): Pipeline<Simplify<Omit<T, keyof A> & A>>;
|
|
917
|
+
/**
|
|
918
|
+
* `$lookup`. With a field that has a `ref` and its model — `lookup('author', User)` — the
|
|
919
|
+
* field is replaced by the referenced record (or `null`; an array of refs becomes an array
|
|
920
|
+
* of records). Or the full form: `lookup({ from: Review, localField: 'id', foreignField:
|
|
921
|
+
* 'place', as: 'reviews' })` adds `reviews: Review[]`. `id` means `_id` on either side.
|
|
922
|
+
*/
|
|
923
|
+
lookup<K extends Keys<T>, M extends LookupTarget>(field: K, from: M): Pipeline<LookedUp<T, K, M>>;
|
|
924
|
+
lookup<M extends LookupTarget, const As extends string>(spec: {
|
|
925
|
+
from: M;
|
|
926
|
+
localField: Keys<T> | `${string}.${string}`;
|
|
927
|
+
foreignField: string;
|
|
928
|
+
as: As;
|
|
929
|
+
}): Pipeline<Simplify<Omit<T, As> & {
|
|
930
|
+
[P in As]: InferRecord<M>[];
|
|
931
|
+
}>>;
|
|
932
|
+
/** Any other stage, with its output type spelled out: `stage<{ … }>({ $facet: … })`. */
|
|
933
|
+
stage<U = T>(stage: AnyRecord$1): Pipeline<U>;
|
|
934
|
+
/** The stages as plain objects (lookups resolved to collection names). */
|
|
935
|
+
toArray(): Promise<AnyRecord$1[]>;
|
|
936
|
+
exec(): Promise<T[]>;
|
|
937
|
+
then<A = T[], B = never>(onfulfilled?: ((value: T[]) => A | PromiseLike<A>) | null, onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<A | B>;
|
|
938
|
+
}
|
|
939
|
+
|
|
725
940
|
type AnyRecord = Record<string, unknown>;
|
|
726
941
|
interface CollectionOptions extends ModelOptions {
|
|
727
942
|
/** Default collation for this collection's queries, e.g. `{ locale: 'en', strength: 2 }`. */
|
|
@@ -895,6 +1110,16 @@ interface CollectionModel<S, O = object, R = Rec<S, O>, C = InferCreateInput<S>>
|
|
|
895
1110
|
deleteMany(filter?: CollectionFilter<R>): Promise<{
|
|
896
1111
|
deletedCount: number;
|
|
897
1112
|
}>;
|
|
1113
|
+
/**
|
|
1114
|
+
* A typed aggregation pipeline: `Order.pipeline().match({ … }).group({ _id: '$customer',
|
|
1115
|
+
* total: { $sum: '$amount' } })` — each stage's output type is inferred. Await it (or `.exec()`).
|
|
1116
|
+
*/
|
|
1117
|
+
pipeline(): Pipeline<R>;
|
|
1118
|
+
/**
|
|
1119
|
+
* `$lookup` for a ref field: `Post.lookup('author', User)` → posts whose `author` is the User
|
|
1120
|
+
* record (or null); an array of refs becomes an array of records. Optional filter first.
|
|
1121
|
+
*/
|
|
1122
|
+
lookup<K extends keyof R & string, M extends LookupTarget>(field: K, from: M, filter?: CollectionFilter<R>): Promise<LookedUp<R, K, M>[]>;
|
|
898
1123
|
/** An aggregation pipeline; type the output with the generic: `aggregate<{ _id: string; n: number }>(…)`. */
|
|
899
1124
|
aggregate<T = Record<string, unknown>>(pipeline: Record<string, unknown>[]): Promise<T[]>;
|
|
900
1125
|
bulkWrite(ops: CollectionBulkOp<R, C>[], options?: {
|
|
@@ -965,4 +1190,4 @@ declare function workerCount(): number;
|
|
|
965
1190
|
declare function ignite(config: EFCConfig): Promise<http.Server | undefined>;
|
|
966
1191
|
declare function gracefulShutdown(server: http.Server | undefined, timeoutMs?: number): void;
|
|
967
1192
|
|
|
968
|
-
export { type CollectionBulkOp, type CollectionBulkResult, type CollectionChange, type CollectionChangeStream, type CollectionFilter, type CollectionFindOptions, type CollectionModel, type CollectionOptions, CollectionSchema, type CollectionUpdate, type CollectionWriteResult, EFCConfig, HttpError, InferCreateInput, InferSchema, type InferTableRecord, type JsonFilter, type ListFilter, ModelOptions, ModelSchema, ModelValidationError, RouteEntry, type ScalarFilter, SortDirection, type StringFilter, type TableAggregateArgs, type TableAggregateResult, type TableCreateData, type TableCreateInput, type TableFindManyArgs, type TableGroupByArgs, type TableInclude, type TableModel, TableOptions, type TableOrderBy, type TableRecord, type TableResult, TableSchema, type TableSelect, type TableUpdateData, type TableUpdateInput, type TableWhere, type TableWhereUnique, type Tables, cache, cacheResponse, compose, db, defineCollection, defineModel, defineTable, getDbClient, getLogger, gracefulShutdown, ignite, isHttpError, logger, scanDir, setDbClient, transaction, workerCount };
|
|
1193
|
+
export { type Accumulator, type CollectionBulkOp, type CollectionBulkResult, type CollectionChange, type CollectionChangeStream, type CollectionFilter, type CollectionFindOptions, type CollectionModel, type CollectionOptions, CollectionSchema, type CollectionUpdate, type CollectionWriteResult, EFCConfig, type FieldRef, type GroupResult, HttpError, InferCreateInput, InferRecord, InferSchema, type InferTableRecord, type JsonFilter, type ListFilter, type LookedUp, type LookupTarget, ModelOptions, ModelSchema, ModelValidationError, Pipeline, type QueryMetric, type QueryMetricsSnapshot, type RateLimitOptions, RouteEntry, type ScalarFilter, SortDirection, type StringFilter, type TableAggregateArgs, type TableAggregateResult, type TableCreateData, type TableCreateInput, type TableFindManyArgs, type TableGroupByArgs, type TableInclude, type TableModel, TableOptions, type TableOrderBy, type TableRecord, type TableResult, TableSchema, type TableSelect, type TableUpdateData, type TableUpdateInput, type TableWhere, type TableWhereUnique, type Tables, cache, cacheResponse, compose, db, defineCollection, defineModel, defineTable, getDbClient, getLogger, getQueryMetrics, gracefulShutdown, ignite, isHttpError, logger, rateLimit, resetQueryMetrics, scanDir, setDbClient, transaction, workerCount };
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,24 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createHttpApp,
|
|
3
|
+
mountErrorHandler,
|
|
4
|
+
mountRoutes
|
|
5
|
+
} from "./chunk-KLWL7XSC.js";
|
|
1
6
|
import {
|
|
2
7
|
cache,
|
|
3
8
|
closeCache,
|
|
4
9
|
configureAuth,
|
|
5
10
|
configureCache,
|
|
11
|
+
isCacheConfigured,
|
|
12
|
+
rawIncr,
|
|
6
13
|
servePrimaryCache
|
|
7
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-Y75V5FCU.js";
|
|
8
15
|
import {
|
|
9
16
|
scanDir
|
|
10
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-5LPRKZPB.js";
|
|
11
18
|
import {
|
|
12
19
|
closeBullMQ,
|
|
13
20
|
initBullMQ
|
|
14
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-C2FOZ7ME.js";
|
|
15
22
|
import {
|
|
16
23
|
connectMongo,
|
|
17
24
|
db,
|
|
@@ -21,23 +28,25 @@ import {
|
|
|
21
28
|
getDbClient,
|
|
22
29
|
setDbClient,
|
|
23
30
|
transaction
|
|
24
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-BG4A7Z32.js";
|
|
25
32
|
import {
|
|
26
|
-
HttpError,
|
|
27
33
|
ModelValidationError,
|
|
28
|
-
isHttpError,
|
|
29
34
|
setAutoSync,
|
|
30
35
|
setDbEngine
|
|
31
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-RETV3GKE.js";
|
|
37
|
+
import {
|
|
38
|
+
HttpError,
|
|
39
|
+
isHttpError
|
|
40
|
+
} from "./chunk-XPY5TQDK.js";
|
|
32
41
|
import {
|
|
33
42
|
closePgBoss,
|
|
34
43
|
initPgBoss
|
|
35
|
-
} from "./chunk-
|
|
36
|
-
import "./chunk-
|
|
44
|
+
} from "./chunk-MUVO7MGS.js";
|
|
45
|
+
import "./chunk-3SWI46YK.js";
|
|
37
46
|
import {
|
|
38
47
|
listTasks,
|
|
39
48
|
registerTask
|
|
40
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-B6MB6HEG.js";
|
|
41
50
|
import {
|
|
42
51
|
checkConnectionBudget,
|
|
43
52
|
configureLogger,
|
|
@@ -45,153 +54,18 @@ import {
|
|
|
45
54
|
connectPostgres,
|
|
46
55
|
getCurrentUser,
|
|
47
56
|
getLogger,
|
|
57
|
+
getQueryMetrics,
|
|
48
58
|
logger,
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
} from "./chunk-73XJUT2S.js";
|
|
59
|
+
resetQueryMetrics
|
|
60
|
+
} from "./chunk-V73R76I4.js";
|
|
52
61
|
|
|
53
62
|
// src/index.ts
|
|
54
63
|
import fs2 from "fs";
|
|
55
64
|
import express from "express";
|
|
56
|
-
import cors from "cors";
|
|
57
|
-
import cookieParser from "cookie-parser";
|
|
58
65
|
import cluster2 from "cluster";
|
|
59
66
|
import os from "os";
|
|
60
67
|
import path2 from "path";
|
|
61
68
|
|
|
62
|
-
// src/router/validate.ts
|
|
63
|
-
var LOCATIONS = ["params", "query", "body"];
|
|
64
|
-
function isRequestSchema(value) {
|
|
65
|
-
return value != null && typeof value === "object" && LOCATIONS.some((loc) => loc in value);
|
|
66
|
-
}
|
|
67
|
-
function schemaFor(schema, method) {
|
|
68
|
-
if (!schema) return void 0;
|
|
69
|
-
const byMethod = schema[method];
|
|
70
|
-
if (isRequestSchema(byMethod)) return byMethod;
|
|
71
|
-
return isRequestSchema(schema) ? schema : void 0;
|
|
72
|
-
}
|
|
73
|
-
function pathToString(path3) {
|
|
74
|
-
if (!path3) return "";
|
|
75
|
-
return path3.map((p) => typeof p === "object" && p !== null && "key" in p ? p.key : p).map(String).join(".");
|
|
76
|
-
}
|
|
77
|
-
async function run(validator, input) {
|
|
78
|
-
const std = validator["~standard"];
|
|
79
|
-
if (std && typeof std.validate === "function") {
|
|
80
|
-
return await std.validate(input);
|
|
81
|
-
}
|
|
82
|
-
const v = validator;
|
|
83
|
-
const parse = v.safeParseAsync ?? v.safeParse;
|
|
84
|
-
if (typeof parse !== "function") {
|
|
85
|
-
throw new Error("[EFC] Route schema entries must be Standard Schema validators (e.g. zod)");
|
|
86
|
-
}
|
|
87
|
-
const r = await parse.call(validator, input);
|
|
88
|
-
return r.success ? { value: r.data } : { issues: r.error?.issues ?? [{ message: "Invalid" }] };
|
|
89
|
-
}
|
|
90
|
-
function validateRequest(schema) {
|
|
91
|
-
return (req, res, next) => {
|
|
92
|
-
void (async () => {
|
|
93
|
-
const issues = [];
|
|
94
|
-
const parsed = {};
|
|
95
|
-
for (const location of LOCATIONS) {
|
|
96
|
-
const validator = schema[location];
|
|
97
|
-
if (!validator) continue;
|
|
98
|
-
const result = await run(validator, req[location]);
|
|
99
|
-
if (result.issues) {
|
|
100
|
-
for (const issue of result.issues) {
|
|
101
|
-
issues.push({ location, path: pathToString(issue.path), message: issue.message });
|
|
102
|
-
}
|
|
103
|
-
} else {
|
|
104
|
-
parsed[location] = result.value;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
if (issues.length > 0) {
|
|
108
|
-
res.status(400).json({ error: "Validation failed", statusCode: 400, issues });
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
for (const location of LOCATIONS) {
|
|
112
|
-
if (location in parsed) {
|
|
113
|
-
Object.defineProperty(req, location, {
|
|
114
|
-
value: parsed[location],
|
|
115
|
-
writable: true,
|
|
116
|
-
configurable: true,
|
|
117
|
-
enumerable: true
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
next();
|
|
122
|
-
})().catch(next);
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// src/router/mount.ts
|
|
127
|
-
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
128
|
-
function asyncWrap(handler) {
|
|
129
|
-
return (req, res, next) => {
|
|
130
|
-
Promise.resolve(handler(req, res, next)).catch(next);
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
function namedParams(route) {
|
|
134
|
-
const catchAlls = new Set([...route.urlPath.matchAll(/:([A-Za-z0-9_$]+)\*/g)].map((m) => m[1]));
|
|
135
|
-
return (req, _res, next) => {
|
|
136
|
-
const positional = req.params;
|
|
137
|
-
const named = {};
|
|
138
|
-
route.params.forEach((name, i) => {
|
|
139
|
-
const value = positional[String(i)];
|
|
140
|
-
if (value === void 0 || value === "") {
|
|
141
|
-
named[name] = catchAlls.has(name) ? [] : void 0;
|
|
142
|
-
} else if (catchAlls.has(name)) {
|
|
143
|
-
named[name] = value.split("/").filter(Boolean).map(decodeURIComponent);
|
|
144
|
-
} else {
|
|
145
|
-
named[name] = decodeURIComponent(value);
|
|
146
|
-
}
|
|
147
|
-
});
|
|
148
|
-
req.params = named;
|
|
149
|
-
next();
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
async function mountRoutes(app, routes) {
|
|
153
|
-
const mounted = [];
|
|
154
|
-
for (const route of routes) {
|
|
155
|
-
const mod = await import(route.filePath);
|
|
156
|
-
const routeMiddlewares = Array.isArray(mod["middlewares"]) ? mod["middlewares"] : [];
|
|
157
|
-
const raw = mod["meta"];
|
|
158
|
-
const meta = raw != null && typeof raw === "object" && !Array.isArray(raw) ? raw : void 0;
|
|
159
|
-
const schema = mod["schema"] != null && typeof mod["schema"] === "object" ? mod["schema"] : void 0;
|
|
160
|
-
const routePath = route.pattern ?? route.urlPath;
|
|
161
|
-
const paramMapper = route.pattern ? [namedParams(route)] : [];
|
|
162
|
-
const implemented = [];
|
|
163
|
-
const unimplemented = [];
|
|
164
|
-
for (const method of HTTP_METHODS) {
|
|
165
|
-
if (typeof mod[method] === "function") {
|
|
166
|
-
implemented.push(method);
|
|
167
|
-
const methodSchema = schemaFor(schema, method);
|
|
168
|
-
const validation = methodSchema ? [validateRequest(methodSchema)] : [];
|
|
169
|
-
app[method.toLowerCase()](
|
|
170
|
-
routePath,
|
|
171
|
-
...paramMapper,
|
|
172
|
-
...routeMiddlewares,
|
|
173
|
-
...validation,
|
|
174
|
-
asyncWrap(mod[method])
|
|
175
|
-
);
|
|
176
|
-
} else {
|
|
177
|
-
unimplemented.push(method);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
if (implemented.length > 0 && unimplemented.length > 0) {
|
|
181
|
-
const allowHeader = implemented.join(", ");
|
|
182
|
-
app.all(routePath, (req, res, next) => {
|
|
183
|
-
if (unimplemented.includes(req.method)) {
|
|
184
|
-
res.set("Allow", allowHeader).status(405).json({ error: "Method Not Allowed" });
|
|
185
|
-
} else {
|
|
186
|
-
next();
|
|
187
|
-
}
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
mounted.push({ ...route, methods: implemented, ...meta !== void 0 && { meta } });
|
|
191
|
-
}
|
|
192
|
-
return mounted;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
69
|
// src/cluster/index.ts
|
|
196
70
|
import cluster from "cluster";
|
|
197
71
|
var isShuttingDown = false;
|
|
@@ -853,6 +727,71 @@ function generateDashboard(routes, basePath, port, projectName, projectVersion)
|
|
|
853
727
|
</html>`;
|
|
854
728
|
}
|
|
855
729
|
|
|
730
|
+
// src/rate-limit.ts
|
|
731
|
+
var UNITS = { s: 1, m: 60, h: 3600, d: 86400 };
|
|
732
|
+
function parseWindow(window) {
|
|
733
|
+
if (typeof window === "number") {
|
|
734
|
+
if (window > 0) return window;
|
|
735
|
+
} else {
|
|
736
|
+
const m = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)$/.exec(window.trim());
|
|
737
|
+
if (m) return Number(m[1]) * UNITS[m[2]];
|
|
738
|
+
}
|
|
739
|
+
throw new Error(`[EFC] rateLimit: window must be seconds or like '15m' \u2014 got ${String(window)}`);
|
|
740
|
+
}
|
|
741
|
+
var lastCacheError = 0;
|
|
742
|
+
function rateLimit(options) {
|
|
743
|
+
const windowSeconds = parseWindow(options.window);
|
|
744
|
+
if (!Number.isInteger(options.max) || options.max < 1) {
|
|
745
|
+
throw new Error("[EFC] rateLimit: max must be a positive integer");
|
|
746
|
+
}
|
|
747
|
+
const keyOf = options.key ?? ((req) => req.ip ?? req.socket.remoteAddress);
|
|
748
|
+
const message = options.message ?? "Too many requests, try again later";
|
|
749
|
+
const headers = options.headers ?? true;
|
|
750
|
+
return (req, res, next) => {
|
|
751
|
+
void (async () => {
|
|
752
|
+
const who = keyOf(req);
|
|
753
|
+
if (who === void 0) return next();
|
|
754
|
+
if (!isCacheConfigured()) {
|
|
755
|
+
throw new Error("[EFC] rateLimit needs a cache \u2014 pass cache: { backend } to ignite()");
|
|
756
|
+
}
|
|
757
|
+
const bucket = options.name ?? req.baseUrl + (req.route?.path ?? req.path);
|
|
758
|
+
const windowMs = windowSeconds * 1e3;
|
|
759
|
+
const now = Date.now();
|
|
760
|
+
const slot = Math.floor(now / windowMs);
|
|
761
|
+
const resetMs = (slot + 1) * windowMs - now;
|
|
762
|
+
let count;
|
|
763
|
+
try {
|
|
764
|
+
count = (await rawIncr(`rl:${bucket}:${who}:${slot}`, Math.ceil(resetMs / 1e3) + 1)).value;
|
|
765
|
+
} catch (err) {
|
|
766
|
+
if (Date.now() - lastCacheError > 3e4) {
|
|
767
|
+
lastCacheError = Date.now();
|
|
768
|
+
getLogger().error(
|
|
769
|
+
{ err },
|
|
770
|
+
`rateLimit: cache unavailable \u2014 ${options.onCacheError === "reject" ? "rejecting with 503" : "allowing requests"}`
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
if (options.onCacheError === "reject") {
|
|
774
|
+
res.status(503).json({ error: "Service Unavailable", statusCode: 503 });
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
return next();
|
|
778
|
+
}
|
|
779
|
+
const resetSeconds = Math.max(1, Math.ceil(resetMs / 1e3));
|
|
780
|
+
if (headers) {
|
|
781
|
+
res.setHeader("RateLimit-Limit", String(options.max));
|
|
782
|
+
res.setHeader("RateLimit-Remaining", String(Math.max(0, options.max - count)));
|
|
783
|
+
res.setHeader("RateLimit-Reset", String(resetSeconds));
|
|
784
|
+
}
|
|
785
|
+
if (count > options.max) {
|
|
786
|
+
if (headers) res.setHeader("Retry-After", String(resetSeconds));
|
|
787
|
+
res.status(429).json({ error: message, statusCode: 429 });
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
next();
|
|
791
|
+
})().catch(next);
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
|
|
856
795
|
// src/cache/response.ts
|
|
857
796
|
var RESPONSE_PREFIX = "res:";
|
|
858
797
|
function cacheResponse(options) {
|
|
@@ -899,7 +838,9 @@ function compose(...handlers) {
|
|
|
899
838
|
return;
|
|
900
839
|
}
|
|
901
840
|
try {
|
|
902
|
-
Promise.resolve(
|
|
841
|
+
Promise.resolve(
|
|
842
|
+
handler(req, res, (err) => err ? next(err) : dispatch(i + 1))
|
|
843
|
+
).catch(next);
|
|
903
844
|
} catch (err) {
|
|
904
845
|
next(err);
|
|
905
846
|
}
|
|
@@ -916,14 +857,7 @@ function detectDatabase(url) {
|
|
|
916
857
|
return void 0;
|
|
917
858
|
}
|
|
918
859
|
async function ignite(config) {
|
|
919
|
-
const {
|
|
920
|
-
port: _port,
|
|
921
|
-
workers,
|
|
922
|
-
globalMiddlewares = [],
|
|
923
|
-
onWorkerReady,
|
|
924
|
-
onWorkerCrash,
|
|
925
|
-
onError
|
|
926
|
-
} = config;
|
|
860
|
+
const { port: _port, workers, onWorkerReady, onWorkerCrash, onError } = config;
|
|
927
861
|
function resolveConventionDir(name) {
|
|
928
862
|
const candidates = [
|
|
929
863
|
...process.argv[1] ? [path2.join(path2.dirname(process.argv[1]), name)] : [],
|
|
@@ -974,39 +908,7 @@ async function ignite(config) {
|
|
|
974
908
|
});
|
|
975
909
|
return;
|
|
976
910
|
}
|
|
977
|
-
const app =
|
|
978
|
-
app.set(
|
|
979
|
-
"json replacer",
|
|
980
|
-
(_key, value) => typeof value === "bigint" ? value.toString() : value
|
|
981
|
-
);
|
|
982
|
-
app.use((_req, _res, next) => {
|
|
983
|
-
runWithContext({}, next);
|
|
984
|
-
});
|
|
985
|
-
app.use(requestLogger());
|
|
986
|
-
if (config.requestTimeout) {
|
|
987
|
-
const ms = config.requestTimeout;
|
|
988
|
-
app.use((_req, res, next) => {
|
|
989
|
-
const timer = setTimeout(() => {
|
|
990
|
-
if (!res.headersSent) res.status(408).json({ error: "Request Timeout", statusCode: 408 });
|
|
991
|
-
}, ms);
|
|
992
|
-
const clear = () => clearTimeout(timer);
|
|
993
|
-
res.once("finish", clear);
|
|
994
|
-
res.once("close", clear);
|
|
995
|
-
next();
|
|
996
|
-
});
|
|
997
|
-
}
|
|
998
|
-
const corsOption = config.cors ?? true;
|
|
999
|
-
if (corsOption !== false) {
|
|
1000
|
-
const origin = typeof corsOption === "object" && corsOption.origin !== void 0 ? corsOption.origin : true;
|
|
1001
|
-
const corsOpts = typeof corsOption === "object" ? { ...corsOption, origin } : { origin };
|
|
1002
|
-
app.use(cors(corsOpts));
|
|
1003
|
-
}
|
|
1004
|
-
app.use(express.json());
|
|
1005
|
-
app.use(express.urlencoded({ extended: true }));
|
|
1006
|
-
app.use(cookieParser());
|
|
1007
|
-
for (const mw of globalMiddlewares) {
|
|
1008
|
-
app.use(mw);
|
|
1009
|
-
}
|
|
911
|
+
const app = createHttpApp(config);
|
|
1010
912
|
if (database) setDbEngine(database);
|
|
1011
913
|
setAutoSync(config.autoSync ?? true);
|
|
1012
914
|
const poolWorkers = clusterEnabled ? workers ?? os.cpus().length : 1;
|
|
@@ -1079,33 +981,7 @@ async function ignite(config) {
|
|
|
1079
981
|
res.send(generateDashboard(mounted, basePath, port, name, version));
|
|
1080
982
|
});
|
|
1081
983
|
}
|
|
1082
|
-
|
|
1083
|
-
app.use(onError);
|
|
1084
|
-
} else {
|
|
1085
|
-
app.use(
|
|
1086
|
-
(err, _req, res, _next) => {
|
|
1087
|
-
if (res.headersSent) {
|
|
1088
|
-
getLogger().warn({ err }, "Error after the response was sent");
|
|
1089
|
-
return;
|
|
1090
|
-
}
|
|
1091
|
-
const status = err?.statusCode;
|
|
1092
|
-
const duckTyped = err instanceof Error && typeof status === "number" && status >= 400 && status < 500 ? err : null;
|
|
1093
|
-
if (isHttpError(err)) {
|
|
1094
|
-
const issues = err.issues;
|
|
1095
|
-
res.status(err.statusCode).json({
|
|
1096
|
-
error: err.message,
|
|
1097
|
-
statusCode: err.statusCode,
|
|
1098
|
-
...issues !== void 0 && { issues }
|
|
1099
|
-
});
|
|
1100
|
-
} else if (duckTyped) {
|
|
1101
|
-
res.status(duckTyped.statusCode).json({ error: duckTyped.message, statusCode: duckTyped.statusCode });
|
|
1102
|
-
} else {
|
|
1103
|
-
getLogger().error({ err }, "Unhandled error");
|
|
1104
|
-
res.status(500).json({ error: "Internal Server Error", statusCode: 500 });
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
);
|
|
1108
|
-
}
|
|
984
|
+
mountErrorHandler(app, onError);
|
|
1109
985
|
return new Promise((resolve, reject) => {
|
|
1110
986
|
const server = app.listen(port);
|
|
1111
987
|
server.once("listening", () => {
|
|
@@ -1156,11 +1032,14 @@ export {
|
|
|
1156
1032
|
defineTable,
|
|
1157
1033
|
getDbClient,
|
|
1158
1034
|
getLogger,
|
|
1035
|
+
getQueryMetrics,
|
|
1159
1036
|
gracefulShutdown,
|
|
1160
1037
|
ignite,
|
|
1161
1038
|
isHttpError,
|
|
1162
1039
|
listTasks,
|
|
1163
1040
|
logger,
|
|
1041
|
+
rateLimit,
|
|
1042
|
+
resetQueryMetrics,
|
|
1164
1043
|
scanDir,
|
|
1165
1044
|
setDbClient,
|
|
1166
1045
|
transaction,
|