@hypequery/serve 0.2.0 → 0.3.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/README.md +138 -879
- package/dist/adapters/node.d.ts.map +1 -1
- package/dist/adapters/node.js +3 -5
- package/dist/adapters/standalone.d.ts +41 -0
- package/dist/adapters/standalone.d.ts.map +1 -0
- package/dist/adapters/standalone.js +46 -0
- package/dist/auth.d.ts +59 -83
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +136 -102
- package/dist/client-config.d.ts +3 -2
- package/dist/client-config.d.ts.map +1 -1
- package/dist/client-config.js +4 -2
- package/dist/errors.js +3 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/openapi.js +1 -2
- package/dist/pipeline.d.ts.map +1 -1
- package/dist/pipeline.js +10 -22
- package/dist/query-logger.js +1 -3
- package/dist/rate-limit.js +4 -3
- package/dist/router.js +2 -1
- package/dist/semantic/datasets/dataset-endpoint.d.ts +85 -0
- package/dist/semantic/datasets/dataset-endpoint.d.ts.map +1 -0
- package/dist/semantic/datasets/dataset-endpoint.js +121 -0
- package/dist/semantic/datasets/index.d.ts +6 -0
- package/dist/semantic/datasets/index.d.ts.map +1 -0
- package/dist/semantic/datasets/index.js +5 -0
- package/dist/semantic/datasets/metric-endpoint.d.ts +82 -0
- package/dist/semantic/datasets/metric-endpoint.d.ts.map +1 -0
- package/dist/semantic/datasets/metric-endpoint.js +159 -0
- package/dist/semantic/datasets/utils/dataset-entry.d.ts +24 -0
- package/dist/semantic/datasets/utils/dataset-entry.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/dataset-entry.js +15 -0
- package/dist/semantic/datasets/utils/dataset-query-metadata.d.ts +3 -0
- package/dist/semantic/datasets/utils/dataset-query-metadata.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/dataset-query-metadata.js +12 -0
- package/dist/semantic/datasets/utils/semantic-input-schema.d.ts +107 -0
- package/dist/semantic/datasets/utils/semantic-input-schema.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/semantic-input-schema.js +87 -0
- package/dist/semantic/index.d.ts +2 -0
- package/dist/semantic/index.d.ts.map +1 -0
- package/dist/semantic/index.js +1 -0
- package/dist/semantic/query-builder-context.d.ts +20 -0
- package/dist/semantic/query-builder-context.d.ts.map +1 -0
- package/dist/semantic/query-builder-context.js +66 -0
- package/dist/semantic/utils/tenant-runtime.d.ts +11 -0
- package/dist/semantic/utils/tenant-runtime.d.ts.map +1 -0
- package/dist/semantic/utils/tenant-runtime.js +48 -0
- package/dist/serve.d.ts +2 -2
- package/dist/serve.d.ts.map +1 -1
- package/dist/server/api-builder.d.ts +5 -0
- package/dist/server/api-builder.d.ts.map +1 -0
- package/dist/server/api-builder.js +76 -0
- package/dist/server/builder.d.ts.map +1 -1
- package/dist/server/builder.js +11 -1
- package/dist/server/create-api.d.ts +32 -0
- package/dist/server/create-api.d.ts.map +1 -0
- package/dist/server/create-api.js +211 -0
- package/dist/server/define-serve.d.ts +21 -2
- package/dist/server/define-serve.d.ts.map +1 -1
- package/dist/server/define-serve.js +53 -84
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +2 -0
- package/dist/server/init-serve.d.ts +1 -1
- package/dist/server/init-serve.d.ts.map +1 -1
- package/dist/server/init-serve.js +7 -2
- package/dist/type-tests/builder.test-d.d.ts +4 -0
- package/dist/type-tests/builder.test-d.d.ts.map +1 -1
- package/dist/type-tests/builder.test-d.js +16 -1
- package/dist/type-tests/semantic.test-d.d.ts +2 -0
- package/dist/type-tests/semantic.test-d.d.ts.map +1 -0
- package/dist/type-tests/semantic.test-d.js +59 -0
- package/dist/types.d.ts +227 -6
- package/dist/types.d.ts.map +1 -1
- package/package.json +6 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/adapters/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,MAAM,CAAC;AAG/E,OAAO,KAAK,EAEV,YAAY,EAGZ,kBAAkB,EACnB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/adapters/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,MAAM,CAAC;AAG/E,OAAO,KAAK,EAEV,YAAY,EAGZ,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAmHrB,eAAO,MAAM,iBAAiB,GAC5B,SAAS,YAAY,EACrB,UAAS,kBAAuB,MAKlB,KAAK,eAAe,EAAE,KAAK,cAAc,kBAmCxD,CAAC;AAEF,eAAO,MAAM,eAAe,GAC1B,SAAS,YAAY,EACrB,UAAS,kBAAuB;;gBA0BP,OAAO,CAAC,IAAI,CAAC;EAiEvC,CAAC"}
|
package/dist/adapters/node.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createServer } from "http";
|
|
2
2
|
import { once } from "node:events";
|
|
3
3
|
import { normalizeHeaders, parseQueryParams, parseRequestBody, serializeResponseBody, } from "./utils.js";
|
|
4
|
-
const DEFAULT_REQUEST_TIMEOUT =
|
|
5
|
-
const DEFAULT_BODY_LIMIT =
|
|
6
|
-
const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT =
|
|
4
|
+
const DEFAULT_REQUEST_TIMEOUT = 30_000; // 30 seconds
|
|
5
|
+
const DEFAULT_BODY_LIMIT = 1_048_576; // 1 MB
|
|
6
|
+
const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT = 10_000; // 10 seconds
|
|
7
7
|
const readRequestBody = async (req, bodyLimit) => {
|
|
8
8
|
const chunks = [];
|
|
9
9
|
let totalLength = 0;
|
|
@@ -11,8 +11,6 @@ const readRequestBody = async (req, bodyLimit) => {
|
|
|
11
11
|
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
12
12
|
totalLength += buf.length;
|
|
13
13
|
if (bodyLimit > 0 && totalLength > bodyLimit) {
|
|
14
|
-
// Destroy the stream to stop reading
|
|
15
|
-
req.destroy();
|
|
16
14
|
const error = new Error("Request body too large");
|
|
17
15
|
error.code = "PAYLOAD_TOO_LARGE";
|
|
18
16
|
throw error;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { FetchHandler, HypeQueryAPI, ServeHandler, StartServerOptions, ServeStartResult } from "../types.js";
|
|
2
|
+
type HandlerSource = HypeQueryAPI<any, any, any> | {
|
|
3
|
+
handler: ServeHandler;
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* Start a standalone HTTP server from a HypeQueryAPI.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const api = createAPI({ queries: { ... } });
|
|
11
|
+
* const { stop } = await startServer(api, { port: 3000 });
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare const startServer: (api: HandlerSource, options?: StartServerOptions) => Promise<ServeStartResult>;
|
|
15
|
+
/**
|
|
16
|
+
* @deprecated Use startServer(api, options) instead.
|
|
17
|
+
*/
|
|
18
|
+
export declare const serve: (api: HandlerSource, options?: StartServerOptions) => Promise<ServeStartResult>;
|
|
19
|
+
/**
|
|
20
|
+
* Create a Node.js HTTP handler (req, res) from a HypeQueryAPI.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* const api = createAPI({ queries: { ... } });
|
|
25
|
+
* app.use('/analytics', toNodeHandler(api));
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare const toNodeHandler: (api: HandlerSource) => (req: import("http").IncomingMessage, res: import("http").ServerResponse) => Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Create a Fetch API handler from a HypeQueryAPI.
|
|
31
|
+
* Works with Cloudflare Workers, Deno, Bun, Vercel Edge, etc.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* const api = createAPI({ queries: { ... } });
|
|
36
|
+
* export default toFetchHandler(api);
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare const toFetchHandler: (api: HandlerSource) => FetchHandler;
|
|
40
|
+
export {};
|
|
41
|
+
//# sourceMappingURL=standalone.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standalone.d.ts","sourceRoot":"","sources":["../../src/adapters/standalone.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAIrB,KAAK,aAAa,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG;IAAE,OAAO,EAAE,YAAY,CAAA;CAAE,CAAC;AAM7E;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,GACtB,KAAK,aAAa,EAClB,UAAU,kBAAkB,KAC3B,OAAO,CAAC,gBAAgB,CAE1B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,KAAK,QATX,aAAa,YACR,kBAAkB,KAC3B,OAAO,CAAC,gBAAgB,CAOK,CAAC;AAEjC;;;;;;;;GAQG;AACH,eAAO,MAAM,aAAa,GAAI,KAAK,aAAa,+FAE/C,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,KAAK,aAAa,KAAG,YAEnD,CAAC"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createNodeHandler, startNodeServer } from "./node.js";
|
|
2
|
+
import { createFetchHandler } from "./fetch.js";
|
|
3
|
+
const extractHandler = (source) => {
|
|
4
|
+
return source.handler;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Start a standalone HTTP server from a HypeQueryAPI.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* const api = createAPI({ queries: { ... } });
|
|
12
|
+
* const { stop } = await startServer(api, { port: 3000 });
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export const startServer = async (api, options) => {
|
|
16
|
+
return startNodeServer(extractHandler(api), options);
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* @deprecated Use startServer(api, options) instead.
|
|
20
|
+
*/
|
|
21
|
+
export const serve = startServer;
|
|
22
|
+
/**
|
|
23
|
+
* Create a Node.js HTTP handler (req, res) from a HypeQueryAPI.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const api = createAPI({ queries: { ... } });
|
|
28
|
+
* app.use('/analytics', toNodeHandler(api));
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export const toNodeHandler = (api) => {
|
|
32
|
+
return createNodeHandler(extractHandler(api));
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Create a Fetch API handler from a HypeQueryAPI.
|
|
36
|
+
* Works with Cloudflare Workers, Deno, Bun, Vercel Edge, etc.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* const api = createAPI({ queries: { ... } });
|
|
41
|
+
* export default toFetchHandler(api);
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export const toFetchHandler = (api) => {
|
|
45
|
+
return createFetchHandler(extractHandler(api));
|
|
46
|
+
};
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { AuthContext, AuthContextWithRoles, AuthContextWithScopes, AuthStrategy,
|
|
1
|
+
import type { AuthContext, AuthContextWithRoles, AuthContextWithScopes, AuthStrategy, AuthStrategyContext, AuthErrorInfo, ServeRequest } from "./types.js";
|
|
2
|
+
import { type JWTPayload } from "jose";
|
|
2
3
|
/**
|
|
3
4
|
* Safely read a header from a ServeRequest with case-insensitive
|
|
4
5
|
* and array-safe normalization.
|
|
@@ -30,6 +31,54 @@ export interface BearerTokenStrategyOptions<TAuth extends AuthContext = AuthCont
|
|
|
30
31
|
validate: (token: string, request: ServeRequest) => Promise<TAuth | null> | TAuth | null;
|
|
31
32
|
}
|
|
32
33
|
export declare const createBearerTokenStrategy: <TAuth extends AuthContext = AuthContext>(options: BearerTokenStrategyOptions<TAuth>) => AuthStrategy<TAuth>;
|
|
34
|
+
export declare const fromContext: <TAuth extends AuthContext = AuthContext>(extract: (context: AuthStrategyContext) => Promise<TAuth | null> | TAuth | null) => AuthStrategy<TAuth>;
|
|
35
|
+
interface BaseJwtStrategyOptions<TAuth extends AuthContext = AuthContext> {
|
|
36
|
+
/** Expected token issuer(s). */
|
|
37
|
+
issuer?: string | string[];
|
|
38
|
+
/** Expected audience(s). */
|
|
39
|
+
audience?: string | string[];
|
|
40
|
+
/** Allowed signature algorithms. Defaults to `['HS256']` for secrets and `['RS256']` for JWKS. */
|
|
41
|
+
algorithms?: string[];
|
|
42
|
+
/** Header carrying the token. @default "authorization" */
|
|
43
|
+
header?: string;
|
|
44
|
+
/** Token prefix. @default "Bearer " */
|
|
45
|
+
prefix?: string;
|
|
46
|
+
/** When true, a missing token resolves to `null` instead of throwing. */
|
|
47
|
+
optional?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Maps verified JWT claims to your auth context. Defaults to mapping
|
|
50
|
+
* `sub`→`userId`, `org_id`→`tenantId`, `roles`→`roles`, and
|
|
51
|
+
* `scope`/`scopes`→`scopes`.
|
|
52
|
+
*/
|
|
53
|
+
mapClaims?: (payload: JWTPayload, request: ServeRequest) => TAuth | null | Promise<TAuth | null>;
|
|
54
|
+
}
|
|
55
|
+
export interface SecretJwtStrategyOptions<TAuth extends AuthContext = AuthContext> extends BaseJwtStrategyOptions<TAuth> {
|
|
56
|
+
/** Shared secret for symmetric JWT verification. Defaults algorithms to `['HS256']`. */
|
|
57
|
+
secret: string | Uint8Array;
|
|
58
|
+
jwksUri?: never;
|
|
59
|
+
}
|
|
60
|
+
export interface JwksJwtStrategyOptions<TAuth extends AuthContext = AuthContext> extends BaseJwtStrategyOptions<TAuth> {
|
|
61
|
+
/** Remote JWKS endpoint for asymmetric JWT verification. Defaults algorithms to `['RS256']`. */
|
|
62
|
+
jwksUri: string;
|
|
63
|
+
secret?: never;
|
|
64
|
+
}
|
|
65
|
+
export type JwtStrategyOptions<TAuth extends AuthContext = AuthContext> = SecretJwtStrategyOptions<TAuth> | JwksJwtStrategyOptions<TAuth>;
|
|
66
|
+
type JwtStrategyOptionsWithMapper<TAuth extends AuthContext> = JwtStrategyOptions<TAuth> & {
|
|
67
|
+
mapClaims: (payload: JWTPayload, request: ServeRequest) => TAuth | null | Promise<TAuth | null>;
|
|
68
|
+
};
|
|
69
|
+
export declare function createJwtStrategy(options: JwtStrategyOptions<AuthContext>): AuthStrategy<AuthContext>;
|
|
70
|
+
export declare function createJwtStrategy<TAuth extends AuthContext>(options: JwtStrategyOptionsWithMapper<TAuth>): AuthStrategy<TAuth>;
|
|
71
|
+
export interface AnalyticsTokenIssuerOptions {
|
|
72
|
+
secret: string | Uint8Array;
|
|
73
|
+
expiresIn?: string;
|
|
74
|
+
issuer?: string;
|
|
75
|
+
audience?: string;
|
|
76
|
+
algorithm?: "HS256" | "HS384" | "HS512";
|
|
77
|
+
}
|
|
78
|
+
export type AnalyticsTokenClaims = Pick<AuthContext, "tenantId" | "roles"> & {
|
|
79
|
+
userId: string;
|
|
80
|
+
};
|
|
81
|
+
export declare const createAnalyticsTokenIssuer: (options: AnalyticsTokenIssuerOptions) => (claims: AnalyticsTokenClaims) => Promise<string>;
|
|
33
82
|
/**
|
|
34
83
|
* Result of an authorization check.
|
|
35
84
|
* Returns { ok: true } if authorization succeeds, or { ok: false, missing } with details.
|
|
@@ -73,42 +122,6 @@ export declare const checkRoleAuthorization: (auth: AuthContext | null, required
|
|
|
73
122
|
* ```
|
|
74
123
|
*/
|
|
75
124
|
export declare const checkScopeAuthorization: (auth: AuthContext | null, requiredScopes: string[]) => AuthorizationResult;
|
|
76
|
-
/**
|
|
77
|
-
* Middleware that requires the user to be authenticated.
|
|
78
|
-
* Returns 401 if no auth context is present.
|
|
79
|
-
*
|
|
80
|
-
* @deprecated Use `query.requireAuth()` instead for per-endpoint authentication.
|
|
81
|
-
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
82
|
-
* See: https://hypequery.com/docs/authentication#middleware-helpers
|
|
83
|
-
*
|
|
84
|
-
* Use this as a global middleware via `api.use(requireAuthMiddleware())`.
|
|
85
|
-
* For per-query guards, prefer `query.requireAuth()`.
|
|
86
|
-
*/
|
|
87
|
-
export declare const requireAuthMiddleware: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext>() => ServeMiddleware<any, any, TContext, TAuth>;
|
|
88
|
-
/**
|
|
89
|
-
* Middleware that requires the user to have at least one of the specified roles.
|
|
90
|
-
* Returns 403 if the user lacks the required role.
|
|
91
|
-
*
|
|
92
|
-
* @deprecated Use `query.requireRole(...)` instead for per-endpoint authorization.
|
|
93
|
-
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
94
|
-
* See: https://hypequery.com/docs/authentication#middleware-helpers
|
|
95
|
-
*
|
|
96
|
-
* Use this as a global or per-query middleware via `api.use(requireRoleMiddleware('admin'))`.
|
|
97
|
-
* For per-query guards, prefer `query.requireRole('admin')`.
|
|
98
|
-
*/
|
|
99
|
-
export declare const requireRoleMiddleware: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext>(...roles: string[]) => ServeMiddleware<any, any, TContext, TAuth>;
|
|
100
|
-
/**
|
|
101
|
-
* Middleware that requires the user to have all of the specified scopes.
|
|
102
|
-
* Returns 403 if the user lacks a required scope.
|
|
103
|
-
*
|
|
104
|
-
* @deprecated Use `query.requireScope(...)` instead for per-endpoint authorization.
|
|
105
|
-
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
106
|
-
* See: https://hypequery.com/docs/authentication#middleware-helpers
|
|
107
|
-
*
|
|
108
|
-
* Use this as a global or per-query middleware via `api.use(requireScopeMiddleware('read:metrics'))`.
|
|
109
|
-
* For per-query guards, prefer `query.requireScope('read:metrics')`.
|
|
110
|
-
*/
|
|
111
|
-
export declare const requireScopeMiddleware: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext>(...scopes: string[]) => ServeMiddleware<any, any, TContext, TAuth>;
|
|
112
125
|
/**
|
|
113
126
|
* Configuration options for creating a typed auth system.
|
|
114
127
|
* Enables compile-time safety for roles and scopes.
|
|
@@ -139,6 +152,12 @@ export type TypedAuthContext<TRoles extends string, TScopes extends string> = Au
|
|
|
139
152
|
/**
|
|
140
153
|
* Creates a typed auth system with compile-time role and scope safety.
|
|
141
154
|
*
|
|
155
|
+
* @deprecated Prefer typing your auth context directly and passing it to
|
|
156
|
+
* `initServe<TContext, TAuth>(...)`. Define roles/scopes as a
|
|
157
|
+
* union on your auth type and use `query.requireRole(...)` /
|
|
158
|
+
* `query.requireScope(...)` guards. This helper is kept for
|
|
159
|
+
* backwards compatibility and will be removed in a future release.
|
|
160
|
+
*
|
|
142
161
|
* This helper provides:
|
|
143
162
|
* - Type-safe auth context (combines AuthContextWithRoles and AuthContextWithScopes)
|
|
144
163
|
* - A `useAuth` wrapper for auth strategies
|
|
@@ -155,67 +174,24 @@ export type TypedAuthContext<TRoles extends string, TScopes extends string> = Au
|
|
|
155
174
|
* });
|
|
156
175
|
*
|
|
157
176
|
* // Extract the typed auth type for use with initServe
|
|
158
|
-
* type AppAuth = TypedAuth;
|
|
177
|
+
* type AppAuth = typeof TypedAuth;
|
|
159
178
|
*
|
|
160
179
|
* const { query, serve } = initServe<Record<string, never>, AppAuth>({
|
|
161
180
|
* auth: useAuth(jwtStrategy),
|
|
162
181
|
* });
|
|
163
|
-
*
|
|
164
|
-
* const adminOnly = query({
|
|
165
|
-
* requiredRoles: ['admin'],
|
|
166
|
-
* query: async () => {
|
|
167
|
-
* // ✅ TypeScript autocomplete for 'admin'
|
|
168
|
-
* // ❌ Compile error on typo like 'admn'
|
|
169
|
-
* return { secret: true };
|
|
170
|
-
* },
|
|
171
|
-
* });
|
|
172
|
-
*
|
|
173
|
-
* const writeData = query({
|
|
174
|
-
* requiredScopes: ['write:metrics'],
|
|
175
|
-
* query: async () => {
|
|
176
|
-
* // ✅ TypeScript autocomplete for 'write:metrics'
|
|
177
|
-
* return { success: true };
|
|
178
|
-
* },
|
|
179
|
-
* });
|
|
180
|
-
*
|
|
181
|
-
* const api = serve({
|
|
182
|
-
* queries: { adminOnly, writeData },
|
|
183
|
-
* });
|
|
184
182
|
* ```
|
|
185
183
|
*/
|
|
186
184
|
export declare const createAuthSystem: <TRoles extends string = string, TScopes extends string = string>() => {
|
|
187
185
|
/**
|
|
188
186
|
* Type-safe wrapper for auth strategies.
|
|
189
187
|
* Ensures the strategy returns auth context with the correct role/scope types.
|
|
190
|
-
*
|
|
191
|
-
* @example
|
|
192
|
-
* ```ts
|
|
193
|
-
* const jwtStrategy: AuthStrategy<AppAuth> = async ({ request }) => {
|
|
194
|
-
* const token = request.headers.authorization?.slice(7);
|
|
195
|
-
* const payload = await verifyJwt(token);
|
|
196
|
-
* return {
|
|
197
|
-
* userId: payload.sub,
|
|
198
|
-
* roles: payload.roles, // ✅ Type-checked against ['admin', 'editor', 'viewer']
|
|
199
|
-
* scopes: payload.scopes, // ✅ Type-checked against ['read:metrics', 'write:metrics']
|
|
200
|
-
* };
|
|
201
|
-
* };
|
|
202
|
-
*
|
|
203
|
-
* const api = defineServe<AppAuth>({
|
|
204
|
-
* auth: useAuth(jwtStrategy),
|
|
205
|
-
* // ...
|
|
206
|
-
* });
|
|
207
|
-
* ```
|
|
208
188
|
*/
|
|
209
189
|
useAuth: <TAuth extends AuthContext>(strategy: AuthStrategy<TAuth>) => AuthStrategy<TAuth>;
|
|
210
190
|
/**
|
|
211
191
|
* The combined typed auth context type.
|
|
212
|
-
* Use this to type your
|
|
213
|
-
*
|
|
214
|
-
* @example
|
|
215
|
-
* ```ts
|
|
216
|
-
* type AppAuth = typeof TypedAuth;
|
|
217
|
-
* ```
|
|
192
|
+
* Use this to type your initServe generic parameter.
|
|
218
193
|
*/
|
|
219
194
|
TypedAuth: TypedAuthContext<TRoles, TScopes>;
|
|
220
195
|
};
|
|
196
|
+
export {};
|
|
221
197
|
//# sourceMappingURL=auth.d.ts.map
|
package/dist/auth.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,oBAAoB,EACpB,qBAAqB,EACrB,YAAY,EACZ,aAAa,EACb,
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,oBAAoB,EACpB,qBAAqB,EACrB,YAAY,EACZ,mBAAmB,EACnB,aAAa,EACb,YAAY,EACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAIL,KAAK,UAAU,EAChB,MAAM,MAAM,CAAC;AAWd;;;GAGG;AACH,eAAO,MAAM,SAAS,GAAI,SAAS,YAAY,EAAE,MAAM,MAAM,KAAG,MAAM,GAAG,SAexE,CAAC;AAEF,qBAAa,SAAU,SAAQ,KAAM,YAAW,aAAa;IAC3D,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;gBAEtB,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;CAMhG;AAED,MAAM,WAAW,iBAAiB,CAAC,KAAK,SAAS,WAAW,GAAG,WAAW;IACxE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAA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Ae,MAAM,EAAE,KACtB,mBAWF,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,uBAAuB,GAClC,MAAM,WAAW,GAAG,IAAI,EACxB,gBAAgB,MAAM,EAAE,KACvB,mBAWF,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,uBAAuB,CACtC,MAAM,SAAS,MAAM,GAAG,MAAM,EAC9B,OAAO,SAAS,MAAM,GAAG,MAAM;IAE/B;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAE1B;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,MAAM,gBAAgB,CAC1B,MAAM,SAAS,MAAM,EACrB,OAAO,SAAS,MAAM,IACpB,oBAAoB,CAAC,MAAM,CAAC,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,eAAO,MAAM,gBAAgB,GAC3B,MAAM,SAAS,MAAM,GAAG,MAAM,EAC9B,OAAO,SAAS,MAAM,GAAG,MAAM;IAG7B;;;OAGG;cACO,KAAK,SAAS,WAAW,YACvB,YAAY,CAAC,KAAK,CAAC,KAC5B,YAAY,CAAC,KAAK,CAAC;IAEtB;;;OAGG;eAC2B,gBAAgB,CAAC,MAAM,EAAE,OAAO,CAAC;CAElE,CAAC"}
|
package/dist/auth.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { SignJWT, createRemoteJWKSet, jwtVerify, } from "jose";
|
|
1
2
|
const resolveHeaderValue = (value) => {
|
|
2
3
|
if (Array.isArray(value)) {
|
|
3
4
|
const first = value.find((item) => typeof item === "string");
|
|
@@ -28,6 +29,8 @@ export const getHeader = (request, name) => {
|
|
|
28
29
|
return trimmed.length > 0 ? trimmed : undefined;
|
|
29
30
|
};
|
|
30
31
|
export class AuthError extends Error {
|
|
32
|
+
reason;
|
|
33
|
+
details;
|
|
31
34
|
constructor(reason, message, details) {
|
|
32
35
|
super(message);
|
|
33
36
|
this.name = "AuthError";
|
|
@@ -92,6 +95,131 @@ export const createBearerTokenStrategy = (options) => {
|
|
|
92
95
|
return options.validate(token, request);
|
|
93
96
|
};
|
|
94
97
|
};
|
|
98
|
+
export const fromContext = (extract) => async (context) => extract(context);
|
|
99
|
+
const defaultJwtClaimMapper = (payload) => {
|
|
100
|
+
const scopeClaim = payload.scope ?? payload.scopes;
|
|
101
|
+
const scopes = typeof scopeClaim === "string"
|
|
102
|
+
? scopeClaim.split(" ").filter(Boolean)
|
|
103
|
+
: Array.isArray(scopeClaim)
|
|
104
|
+
? scopeClaim.filter((scope) => typeof scope === "string")
|
|
105
|
+
: undefined;
|
|
106
|
+
const roles = Array.isArray(payload.roles)
|
|
107
|
+
? payload.roles.filter((role) => typeof role === "string")
|
|
108
|
+
: undefined;
|
|
109
|
+
return {
|
|
110
|
+
userId: typeof payload.sub === "string" ? payload.sub : undefined,
|
|
111
|
+
tenantId: typeof payload.org_id === "string" ? payload.org_id : undefined,
|
|
112
|
+
roles,
|
|
113
|
+
scopes,
|
|
114
|
+
metadata: payload,
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* Verifies JWT bearer tokens with either a shared secret (HS256 by default) or
|
|
119
|
+
* a remote JWKS (RS256 by default). Use shared secrets when you mint the token
|
|
120
|
+
* yourself, and JWKS when a provider such as Auth0, Clerk, or Cognito mints it.
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* ```ts
|
|
124
|
+
* const api = createAPI({
|
|
125
|
+
* auth: createJwtStrategy({
|
|
126
|
+
* jwksUri: 'https://example.auth0.com/.well-known/jwks.json',
|
|
127
|
+
* issuer: 'https://example.auth0.com/',
|
|
128
|
+
* audience: 'https://api.example.com',
|
|
129
|
+
* }),
|
|
130
|
+
* queries: { ... },
|
|
131
|
+
* });
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
const resolveSecretKey = (secret, helperName) => {
|
|
135
|
+
if (typeof secret === "string") {
|
|
136
|
+
if (secret.length === 0) {
|
|
137
|
+
throw new Error(`${helperName}: \`secret\` must not be empty.`);
|
|
138
|
+
}
|
|
139
|
+
return new TextEncoder().encode(secret);
|
|
140
|
+
}
|
|
141
|
+
if (secret.byteLength === 0) {
|
|
142
|
+
throw new Error(`${helperName}: \`secret\` must not be empty.`);
|
|
143
|
+
}
|
|
144
|
+
return secret;
|
|
145
|
+
};
|
|
146
|
+
const isSecretJwtOptions = (options) => "secret" in options && options.secret != null;
|
|
147
|
+
const isJwksJwtOptions = (options) => "jwksUri" in options && options.jwksUri != null;
|
|
148
|
+
export function createJwtStrategy(options) {
|
|
149
|
+
const hasSecret = isSecretJwtOptions(options);
|
|
150
|
+
const hasJwksUri = isJwksJwtOptions(options);
|
|
151
|
+
if (hasSecret === hasJwksUri) {
|
|
152
|
+
throw new Error("createJwtStrategy: provide exactly one of `secret` or `jwksUri`.");
|
|
153
|
+
}
|
|
154
|
+
const headerName = options.header ?? "authorization";
|
|
155
|
+
const prefix = options.prefix ?? "Bearer ";
|
|
156
|
+
const mapClaims = options.mapClaims
|
|
157
|
+
?? defaultJwtClaimMapper;
|
|
158
|
+
let verify;
|
|
159
|
+
if (hasSecret) {
|
|
160
|
+
const key = resolveSecretKey(options.secret, "createJwtStrategy");
|
|
161
|
+
verify = (token) => jwtVerify(token, key, {
|
|
162
|
+
issuer: options.issuer,
|
|
163
|
+
audience: options.audience,
|
|
164
|
+
algorithms: options.algorithms ?? ["HS256"],
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
if (options.jwksUri.trim().length === 0) {
|
|
169
|
+
throw new Error("createJwtStrategy: `jwksUri` must not be empty.");
|
|
170
|
+
}
|
|
171
|
+
const jwks = createRemoteJWKSet(new URL(options.jwksUri));
|
|
172
|
+
verify = (token) => jwtVerify(token, jwks, {
|
|
173
|
+
issuer: options.issuer,
|
|
174
|
+
audience: options.audience,
|
|
175
|
+
algorithms: options.algorithms ?? ["RS256"],
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
return async ({ request }) => {
|
|
179
|
+
const raw = getHeader(request, headerName);
|
|
180
|
+
if (typeof raw !== "string" || !raw.startsWith(prefix)) {
|
|
181
|
+
if (options.optional)
|
|
182
|
+
return null;
|
|
183
|
+
throw new AuthError("MISSING", `Missing bearer token in "${headerName}" header`, { header: headerName });
|
|
184
|
+
}
|
|
185
|
+
const token = raw.slice(prefix.length).trim();
|
|
186
|
+
if (!token) {
|
|
187
|
+
if (options.optional)
|
|
188
|
+
return null;
|
|
189
|
+
throw new AuthError("MISSING", `Empty bearer token in "${headerName}" header`, { header: headerName });
|
|
190
|
+
}
|
|
191
|
+
let payload;
|
|
192
|
+
try {
|
|
193
|
+
const verified = await verify(token);
|
|
194
|
+
payload = verified.payload;
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
throw new AuthError("INVALID", "JWT verification failed", {
|
|
198
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return mapClaims(payload, request);
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
export const createAnalyticsTokenIssuer = (options) => {
|
|
205
|
+
const key = resolveSecretKey(options.secret, "createAnalyticsTokenIssuer");
|
|
206
|
+
const algorithm = options.algorithm ?? "HS256";
|
|
207
|
+
return async (claims) => {
|
|
208
|
+
let jwt = new SignJWT({
|
|
209
|
+
...(claims.tenantId ? { org_id: claims.tenantId } : {}),
|
|
210
|
+
...(claims.roles ? { roles: claims.roles } : {}),
|
|
211
|
+
})
|
|
212
|
+
.setProtectedHeader({ alg: algorithm })
|
|
213
|
+
.setSubject(claims.userId)
|
|
214
|
+
.setIssuedAt()
|
|
215
|
+
.setExpirationTime(options.expiresIn ?? "15m");
|
|
216
|
+
if (options.issuer)
|
|
217
|
+
jwt = jwt.setIssuer(options.issuer);
|
|
218
|
+
if (options.audience)
|
|
219
|
+
jwt = jwt.setAudience(options.audience);
|
|
220
|
+
return jwt.sign(key);
|
|
221
|
+
};
|
|
222
|
+
};
|
|
95
223
|
/**
|
|
96
224
|
* Check if the authenticated user has at least one of the required roles (OR semantics).
|
|
97
225
|
*
|
|
@@ -146,65 +274,15 @@ export const checkScopeAuthorization = (auth, requiredScopes) => {
|
|
|
146
274
|
? { ok: true }
|
|
147
275
|
: { ok: false, missing: requiredScopes, reason: 'MISSING_SCOPE' };
|
|
148
276
|
};
|
|
149
|
-
/**
|
|
150
|
-
* Middleware that requires the user to be authenticated.
|
|
151
|
-
* Returns 401 if no auth context is present.
|
|
152
|
-
*
|
|
153
|
-
* @deprecated Use `query.requireAuth()` instead for per-endpoint authentication.
|
|
154
|
-
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
155
|
-
* See: https://hypequery.com/docs/authentication#middleware-helpers
|
|
156
|
-
*
|
|
157
|
-
* Use this as a global middleware via `api.use(requireAuthMiddleware())`.
|
|
158
|
-
* For per-query guards, prefer `query.requireAuth()`.
|
|
159
|
-
*/
|
|
160
|
-
export const requireAuthMiddleware = () => async (ctx, next) => {
|
|
161
|
-
if (!ctx.auth) {
|
|
162
|
-
throw Object.assign(new Error("Authentication required"), {
|
|
163
|
-
status: 401,
|
|
164
|
-
type: "UNAUTHORIZED",
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
return next();
|
|
168
|
-
};
|
|
169
|
-
/**
|
|
170
|
-
* Middleware that requires the user to have at least one of the specified roles.
|
|
171
|
-
* Returns 403 if the user lacks the required role.
|
|
172
|
-
*
|
|
173
|
-
* @deprecated Use `query.requireRole(...)` instead for per-endpoint authorization.
|
|
174
|
-
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
175
|
-
* See: https://hypequery.com/docs/authentication#middleware-helpers
|
|
176
|
-
*
|
|
177
|
-
* Use this as a global or per-query middleware via `api.use(requireRoleMiddleware('admin'))`.
|
|
178
|
-
* For per-query guards, prefer `query.requireRole('admin')`.
|
|
179
|
-
*/
|
|
180
|
-
export const requireRoleMiddleware = (...roles) => async (ctx, next) => {
|
|
181
|
-
const result = checkRoleAuthorization(ctx.auth, roles);
|
|
182
|
-
if (!result.ok) {
|
|
183
|
-
throw Object.assign(new Error(`Missing required role. Required one of: ${roles.join(", ")}`), { status: 403, type: "FORBIDDEN" });
|
|
184
|
-
}
|
|
185
|
-
return next();
|
|
186
|
-
};
|
|
187
|
-
/**
|
|
188
|
-
* Middleware that requires the user to have all of the specified scopes.
|
|
189
|
-
* Returns 403 if the user lacks a required scope.
|
|
190
|
-
*
|
|
191
|
-
* @deprecated Use `query.requireScope(...)` instead for per-endpoint authorization.
|
|
192
|
-
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
193
|
-
* See: https://hypequery.com/docs/authentication#middleware-helpers
|
|
194
|
-
*
|
|
195
|
-
* Use this as a global or per-query middleware via `api.use(requireScopeMiddleware('read:metrics'))`.
|
|
196
|
-
* For per-query guards, prefer `query.requireScope('read:metrics')`.
|
|
197
|
-
*/
|
|
198
|
-
export const requireScopeMiddleware = (...scopes) => async (ctx, next) => {
|
|
199
|
-
const result = checkScopeAuthorization(ctx.auth, scopes);
|
|
200
|
-
if (!result.ok) {
|
|
201
|
-
throw Object.assign(new Error(`Missing required scopes: ${result.missing.join(", ")}`), { status: 403, type: "FORBIDDEN" });
|
|
202
|
-
}
|
|
203
|
-
return next();
|
|
204
|
-
};
|
|
205
277
|
/**
|
|
206
278
|
* Creates a typed auth system with compile-time role and scope safety.
|
|
207
279
|
*
|
|
280
|
+
* @deprecated Prefer typing your auth context directly and passing it to
|
|
281
|
+
* `initServe<TContext, TAuth>(...)`. Define roles/scopes as a
|
|
282
|
+
* union on your auth type and use `query.requireRole(...)` /
|
|
283
|
+
* `query.requireScope(...)` guards. This helper is kept for
|
|
284
|
+
* backwards compatibility and will be removed in a future release.
|
|
285
|
+
*
|
|
208
286
|
* This helper provides:
|
|
209
287
|
* - Type-safe auth context (combines AuthContextWithRoles and AuthContextWithScopes)
|
|
210
288
|
* - A `useAuth` wrapper for auth strategies
|
|
@@ -221,32 +299,11 @@ export const requireScopeMiddleware = (...scopes) => async (ctx, next) => {
|
|
|
221
299
|
* });
|
|
222
300
|
*
|
|
223
301
|
* // Extract the typed auth type for use with initServe
|
|
224
|
-
* type AppAuth = TypedAuth;
|
|
302
|
+
* type AppAuth = typeof TypedAuth;
|
|
225
303
|
*
|
|
226
304
|
* const { query, serve } = initServe<Record<string, never>, AppAuth>({
|
|
227
305
|
* auth: useAuth(jwtStrategy),
|
|
228
306
|
* });
|
|
229
|
-
*
|
|
230
|
-
* const adminOnly = query({
|
|
231
|
-
* requiredRoles: ['admin'],
|
|
232
|
-
* query: async () => {
|
|
233
|
-
* // ✅ TypeScript autocomplete for 'admin'
|
|
234
|
-
* // ❌ Compile error on typo like 'admn'
|
|
235
|
-
* return { secret: true };
|
|
236
|
-
* },
|
|
237
|
-
* });
|
|
238
|
-
*
|
|
239
|
-
* const writeData = query({
|
|
240
|
-
* requiredScopes: ['write:metrics'],
|
|
241
|
-
* query: async () => {
|
|
242
|
-
* // ✅ TypeScript autocomplete for 'write:metrics'
|
|
243
|
-
* return { success: true };
|
|
244
|
-
* },
|
|
245
|
-
* });
|
|
246
|
-
*
|
|
247
|
-
* const api = serve({
|
|
248
|
-
* queries: { adminOnly, writeData },
|
|
249
|
-
* });
|
|
250
307
|
* ```
|
|
251
308
|
*/
|
|
252
309
|
export const createAuthSystem = () => {
|
|
@@ -254,34 +311,11 @@ export const createAuthSystem = () => {
|
|
|
254
311
|
/**
|
|
255
312
|
* Type-safe wrapper for auth strategies.
|
|
256
313
|
* Ensures the strategy returns auth context with the correct role/scope types.
|
|
257
|
-
*
|
|
258
|
-
* @example
|
|
259
|
-
* ```ts
|
|
260
|
-
* const jwtStrategy: AuthStrategy<AppAuth> = async ({ request }) => {
|
|
261
|
-
* const token = request.headers.authorization?.slice(7);
|
|
262
|
-
* const payload = await verifyJwt(token);
|
|
263
|
-
* return {
|
|
264
|
-
* userId: payload.sub,
|
|
265
|
-
* roles: payload.roles, // ✅ Type-checked against ['admin', 'editor', 'viewer']
|
|
266
|
-
* scopes: payload.scopes, // ✅ Type-checked against ['read:metrics', 'write:metrics']
|
|
267
|
-
* };
|
|
268
|
-
* };
|
|
269
|
-
*
|
|
270
|
-
* const api = defineServe<AppAuth>({
|
|
271
|
-
* auth: useAuth(jwtStrategy),
|
|
272
|
-
* // ...
|
|
273
|
-
* });
|
|
274
|
-
* ```
|
|
275
314
|
*/
|
|
276
315
|
useAuth: (strategy) => strategy,
|
|
277
316
|
/**
|
|
278
317
|
* The combined typed auth context type.
|
|
279
|
-
* Use this to type your
|
|
280
|
-
*
|
|
281
|
-
* @example
|
|
282
|
-
* ```ts
|
|
283
|
-
* type AppAuth = typeof TypedAuth;
|
|
284
|
-
* ```
|
|
318
|
+
* Use this to type your initServe generic parameter.
|
|
285
319
|
*/
|
|
286
320
|
TypedAuth: null,
|
|
287
321
|
};
|
package/dist/client-config.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { ServeBuilder, HttpMethod, AuthContext } from "./types.js";
|
|
|
4
4
|
*/
|
|
5
5
|
export interface QueryClientConfig {
|
|
6
6
|
method: HttpMethod;
|
|
7
|
+
path?: string;
|
|
7
8
|
}
|
|
8
9
|
/**
|
|
9
10
|
* Map of query names to their client configurations
|
|
@@ -36,8 +37,8 @@ export declare function extractClientConfig<TQueries extends Record<string, any>
|
|
|
36
37
|
*
|
|
37
38
|
* @example
|
|
38
39
|
* const config = defineClientConfig({
|
|
39
|
-
* hello: { method: 'GET' },
|
|
40
|
-
* createUser: { method: 'POST' },
|
|
40
|
+
* hello: { method: 'GET', path: '/api/analytics/queries/hello' },
|
|
41
|
+
* createUser: { method: 'POST', path: '/api/analytics/queries/createUser' },
|
|
41
42
|
* });
|
|
42
43
|
*/
|
|
43
44
|
export declare function defineClientConfig<T extends ApiClientConfig>(config: T): T;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-config.d.ts","sourceRoot":"","sources":["../src/client-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAExE;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"client-config.d.ts","sourceRoot":"","sources":["../src/client-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAExE;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,UAAU,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;AAEhE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACpC,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACxC,KAAK,SAAS,WAAW,EACzB,GAAG,EAAE,YAAY,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,GAAG,eAAe,CAsB/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,eAAe,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,CAE1E"}
|