@hypequery/serve 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +201 -0
  2. package/package.json +10 -10
  3. package/dist/adapters/fetch.d.ts +0 -3
  4. package/dist/adapters/fetch.d.ts.map +0 -1
  5. package/dist/adapters/fetch.js +0 -26
  6. package/dist/adapters/node.d.ts +0 -8
  7. package/dist/adapters/node.d.ts.map +0 -1
  8. package/dist/adapters/node.js +0 -105
  9. package/dist/adapters/utils.d.ts +0 -39
  10. package/dist/adapters/utils.d.ts.map +0 -1
  11. package/dist/adapters/utils.js +0 -114
  12. package/dist/adapters/vercel.d.ts +0 -7
  13. package/dist/adapters/vercel.d.ts.map +0 -1
  14. package/dist/adapters/vercel.js +0 -13
  15. package/dist/auth.d.ts +0 -14
  16. package/dist/auth.d.ts.map +0 -1
  17. package/dist/auth.js +0 -37
  18. package/dist/client-config.d.ts +0 -44
  19. package/dist/client-config.d.ts.map +0 -1
  20. package/dist/client-config.js +0 -53
  21. package/dist/dev.d.ts +0 -9
  22. package/dist/dev.d.ts.map +0 -1
  23. package/dist/dev.js +0 -24
  24. package/dist/docs-ui.d.ts +0 -3
  25. package/dist/docs-ui.d.ts.map +0 -1
  26. package/dist/docs-ui.js +0 -34
  27. package/dist/endpoint.d.ts +0 -5
  28. package/dist/endpoint.d.ts.map +0 -1
  29. package/dist/endpoint.js +0 -59
  30. package/dist/index.d.ts +0 -13
  31. package/dist/index.d.ts.map +0 -1
  32. package/dist/index.js +0 -12
  33. package/dist/openapi.d.ts +0 -3
  34. package/dist/openapi.d.ts.map +0 -1
  35. package/dist/openapi.js +0 -189
  36. package/dist/queries.d.ts +0 -3
  37. package/dist/queries.d.ts.map +0 -1
  38. package/dist/queries.js +0 -1
  39. package/dist/query.d.ts +0 -4
  40. package/dist/query.d.ts.map +0 -1
  41. package/dist/query.js +0 -1
  42. package/dist/router.d.ts +0 -13
  43. package/dist/router.d.ts.map +0 -1
  44. package/dist/router.js +0 -56
  45. package/dist/sdk-generator.d.ts +0 -7
  46. package/dist/sdk-generator.d.ts.map +0 -1
  47. package/dist/sdk-generator.js +0 -143
  48. package/dist/server.d.ts +0 -9
  49. package/dist/server.d.ts.map +0 -1
  50. package/dist/server.js +0 -584
  51. package/dist/tenant.d.ts +0 -35
  52. package/dist/tenant.d.ts.map +0 -1
  53. package/dist/tenant.js +0 -49
  54. package/dist/type-tests/builder.test-d.d.ts +0 -13
  55. package/dist/type-tests/builder.test-d.d.ts.map +0 -1
  56. package/dist/type-tests/builder.test-d.js +0 -20
  57. package/dist/types.d.ts +0 -373
  58. package/dist/types.d.ts.map +0 -1
  59. package/dist/types.js +0 -1
package/dist/server.js DELETED
@@ -1,584 +0,0 @@
1
- import { z } from "zod";
2
- import { zodToJsonSchema } from "zod-to-json-schema";
3
- import { startNodeServer } from "./adapters/node.js";
4
- import { createEndpoint } from "./endpoint.js";
5
- import { buildOpenApiDocument } from "./openapi.js";
6
- import { applyBasePath, normalizeRoutePath, ServeRouter } from "./router.js";
7
- import { buildDocsHtml } from "./docs-ui.js";
8
- import { createTenantScope, warnTenantMisconfiguration } from "./tenant.js";
9
- const ensureArray = (value) => {
10
- if (!value) {
11
- return [];
12
- }
13
- return Array.isArray(value) ? value : [value];
14
- };
15
- const generateRequestId = () => {
16
- return `req_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
17
- };
18
- const createProcedureBuilder = () => {
19
- const build = (state) => {
20
- return {
21
- input: (schema) => build({ ...state, inputSchema: schema }),
22
- output: (schema) => build({ ...state, outputSchema: schema }),
23
- describe: (description) => build({ ...state, description }),
24
- name: (name) => build({ ...state, name }),
25
- summary: (summary) => build({ ...state, summary }),
26
- tag: (tag) => build({
27
- ...state,
28
- tags: Array.from(new Set([...state.tags, tag])),
29
- }),
30
- tags: (tags) => build({
31
- ...state,
32
- tags: Array.from(new Set([...state.tags, ...(tags ?? [])])),
33
- }),
34
- method: (method) => build({ ...state, method }),
35
- cache: (ttlMs) => build({ ...state, cacheTtlMs: ttlMs }),
36
- auth: (strategy) => build({ ...state, auth: strategy }),
37
- tenant: (config) => build({ ...state, tenant: config }),
38
- custom: (custom) => build({
39
- ...state,
40
- custom: { ...(state.custom ?? {}), ...custom },
41
- }),
42
- use: (...middlewares) => build({
43
- ...state,
44
- middlewares: [...state.middlewares, ...middlewares],
45
- }),
46
- query: (executable) => {
47
- const base = {
48
- description: state.description,
49
- name: state.name,
50
- summary: state.summary,
51
- tags: state.tags,
52
- method: state.method,
53
- inputSchema: state.inputSchema,
54
- outputSchema: state.outputSchema,
55
- cacheTtlMs: state.cacheTtlMs,
56
- auth: typeof state.auth === "undefined" ? null : state.auth,
57
- tenant: state.tenant,
58
- custom: state.custom,
59
- middlewares: state.middlewares,
60
- query: executable,
61
- };
62
- return base;
63
- },
64
- };
65
- };
66
- return build({ tags: [], middlewares: [] });
67
- };
68
- const getRequestId = (request) => {
69
- return (request.headers["x-request-id"] ??
70
- request.headers["x-trace-id"] ??
71
- generateRequestId());
72
- };
73
- const safeInvokeHook = async (name, hook, payload) => {
74
- if (!hook) {
75
- return;
76
- }
77
- try {
78
- await hook(payload);
79
- }
80
- catch (error) {
81
- console.error(`[hypequery/serve] ${name} hook failed`, error);
82
- }
83
- };
84
- const mergeTags = (existing, next) => {
85
- const merged = [...existing, ...(next ?? [])];
86
- return Array.from(new Set(merged.filter(Boolean)));
87
- };
88
- const createErrorResponse = (status, type, message, details) => {
89
- return {
90
- status,
91
- body: {
92
- error: {
93
- type,
94
- message,
95
- ...(details ? { details } : {}),
96
- },
97
- },
98
- };
99
- };
100
- const buildContextInput = (request) => {
101
- if (request.body !== undefined && request.body !== null) {
102
- return request.body;
103
- }
104
- if (request.query && Object.keys(request.query).length > 0) {
105
- return request.query;
106
- }
107
- return {};
108
- };
109
- const runMiddlewares = async (middlewares, ctx, handler) => {
110
- let index = middlewares.length - 1;
111
- let next = handler;
112
- while (index >= 0) {
113
- const middleware = middlewares[index];
114
- const downstream = next;
115
- next = () => middleware(ctx, downstream);
116
- index -= 1;
117
- }
118
- return next();
119
- };
120
- const authenticateRequest = async (strategies, request, metadata) => {
121
- for (const strategy of strategies) {
122
- const result = await strategy({
123
- request,
124
- endpoint: metadata,
125
- });
126
- if (result) {
127
- return result;
128
- }
129
- }
130
- return null;
131
- };
132
- const gatherAuthStrategies = (endpointStrategy, globalStrategies) => {
133
- const strategies = [];
134
- if (endpointStrategy) {
135
- strategies.push(endpointStrategy);
136
- }
137
- return [...strategies, ...globalStrategies];
138
- };
139
- const computeRequiresAuth = (metadata, endpointStrategy, globalStrategies) => {
140
- if (typeof metadata.requiresAuth === "boolean") {
141
- return metadata.requiresAuth;
142
- }
143
- if (endpointStrategy) {
144
- return true;
145
- }
146
- return globalStrategies.length > 0;
147
- };
148
- const validateInput = (schema, payload) => {
149
- if (!schema) {
150
- return { success: true, data: payload };
151
- }
152
- const result = schema.safeParse(payload);
153
- return result.success
154
- ? { success: true, data: result.data }
155
- : { success: false, error: result.error };
156
- };
157
- const createOpenApiEndpoint = (path, getEndpoints, openapiOptions) => {
158
- // Cache the OpenAPI document to avoid rebuilding on every request
159
- let cachedDocument = null;
160
- return {
161
- key: "__hypequery_openapi__",
162
- method: "GET",
163
- inputSchema: undefined,
164
- outputSchema: z.any(),
165
- handler: async () => {
166
- if (!cachedDocument) {
167
- cachedDocument = buildOpenApiDocument(getEndpoints(), openapiOptions);
168
- }
169
- return cachedDocument;
170
- },
171
- query: undefined,
172
- middlewares: [],
173
- auth: null,
174
- metadata: {
175
- path,
176
- method: "GET",
177
- name: "OpenAPI schema",
178
- summary: "OpenAPI schema",
179
- description: "Generated OpenAPI specification for the registered endpoints",
180
- tags: ["docs"],
181
- requiresAuth: false,
182
- deprecated: false,
183
- visibility: "internal",
184
- },
185
- cacheTtlMs: null,
186
- };
187
- };
188
- const createDocsEndpoint = (path, openapiPath, options) => ({
189
- key: "__hypequery_docs__",
190
- method: "GET",
191
- inputSchema: undefined,
192
- outputSchema: z.string(),
193
- handler: async () => buildDocsHtml(openapiPath, options),
194
- query: undefined,
195
- middlewares: [],
196
- auth: null,
197
- metadata: {
198
- path,
199
- method: "GET",
200
- name: "Docs",
201
- summary: "API documentation",
202
- description: "Auto-generated documentation for your hypequery endpoints",
203
- tags: ["docs"],
204
- requiresAuth: false,
205
- deprecated: false,
206
- visibility: "internal",
207
- },
208
- cacheTtlMs: null,
209
- defaultHeaders: {
210
- "content-type": "text/html; charset=utf-8",
211
- },
212
- });
213
- const cloneContext = (ctx) => (ctx ? { ...ctx } : {});
214
- const resolveContext = async (factory, request, auth) => {
215
- if (!factory) {
216
- return {};
217
- }
218
- if (typeof factory === "function") {
219
- const value = await factory({ request, auth });
220
- return cloneContext(value);
221
- }
222
- return cloneContext(factory);
223
- };
224
- const executeEndpoint = async (options) => {
225
- const { endpoint, request, requestId, authStrategies, contextFactory, globalMiddlewares, globalTenantConfig, hooks, additionalContext, } = options;
226
- const locals = {};
227
- let cacheTtlMs = endpoint.cacheTtlMs ?? null;
228
- const setCacheTtl = (ttl) => {
229
- cacheTtlMs = ttl;
230
- };
231
- const context = {
232
- request,
233
- input: buildContextInput(request),
234
- auth: null,
235
- metadata: endpoint.metadata,
236
- locals,
237
- setCacheTtl,
238
- };
239
- const startedAt = Date.now();
240
- await safeInvokeHook("onRequestStart", hooks.onRequestStart, {
241
- requestId,
242
- queryKey: endpoint.key,
243
- metadata: endpoint.metadata,
244
- request,
245
- auth: context.auth,
246
- });
247
- try {
248
- const endpointAuth = endpoint.auth ?? null;
249
- const strategies = gatherAuthStrategies(endpointAuth, authStrategies);
250
- const requiresAuth = computeRequiresAuth(endpoint.metadata, endpointAuth, authStrategies);
251
- const metadataWithAuth = {
252
- ...endpoint.metadata,
253
- requiresAuth,
254
- };
255
- context.metadata = metadataWithAuth;
256
- const authContext = await authenticateRequest(strategies, request, metadataWithAuth);
257
- if (!authContext && requiresAuth) {
258
- await safeInvokeHook("onAuthFailure", hooks.onAuthFailure, {
259
- requestId,
260
- queryKey: endpoint.key,
261
- metadata: metadataWithAuth,
262
- request,
263
- auth: context.auth,
264
- reason: "MISSING",
265
- });
266
- return createErrorResponse(401, "UNAUTHORIZED", "Authentication required", {
267
- reason: "missing_credentials",
268
- strategies_attempted: strategies.length,
269
- endpoint: endpoint.metadata.path,
270
- });
271
- }
272
- // After the auth check above, if requiresAuth is true, authContext is guaranteed to be non-null
273
- context.auth = authContext;
274
- const hydratedContext = await resolveContext(contextFactory, request, authContext);
275
- Object.assign(context, hydratedContext, additionalContext);
276
- // Tenant isolation: Extract and validate tenant ID if configured
277
- // Use endpoint-specific config, or fall back to global config
278
- const tenantConfig = endpoint.tenant ?? globalTenantConfig;
279
- if (tenantConfig) {
280
- const tenantRequired = tenantConfig.required !== false; // Default to true
281
- const tenantId = authContext ? tenantConfig.extract(authContext) : null;
282
- if (!tenantId && tenantRequired) {
283
- const errorMessage = tenantConfig.errorMessage ??
284
- "Tenant context is required but could not be determined from authentication";
285
- await safeInvokeHook("onError", hooks.onError, {
286
- requestId,
287
- queryKey: endpoint.key,
288
- metadata: metadataWithAuth,
289
- request,
290
- auth: context.auth,
291
- durationMs: Date.now() - startedAt,
292
- error: new Error(errorMessage),
293
- });
294
- return createErrorResponse(403, "UNAUTHORIZED", errorMessage, {
295
- reason: "missing_tenant_context",
296
- tenant_required: true,
297
- });
298
- }
299
- if (tenantId) {
300
- context.tenantId = tenantId;
301
- // Auto-inject tenant filtering if configured
302
- const mode = tenantConfig.mode ?? 'manual'; // Default to manual for backward compatibility
303
- const column = tenantConfig.column;
304
- if (mode === 'auto-inject' && column) {
305
- // Wrap all query builders in the context to auto-inject tenant filters
306
- const contextValues = context;
307
- for (const key of Object.keys(contextValues)) {
308
- const value = contextValues[key];
309
- // Check if it looks like a query builder (has a table method)
310
- if (value && typeof value === 'object' && 'table' in value && typeof value.table === 'function') {
311
- contextValues[key] = createTenantScope(value, { tenantId, column });
312
- }
313
- }
314
- }
315
- else if (mode === 'manual') {
316
- // Warn developers in manual mode to ensure they manually filter
317
- warnTenantMisconfiguration({
318
- queryKey: endpoint.key,
319
- hasTenantConfig: true,
320
- hasTenantId: true,
321
- mode: 'manual',
322
- });
323
- }
324
- }
325
- else if (tenantConfig && !tenantRequired) {
326
- // Optional tenant mode - warn if no tenant config when accessing user data
327
- warnTenantMisconfiguration({
328
- queryKey: endpoint.key,
329
- hasTenantConfig: true,
330
- hasTenantId: false,
331
- mode: tenantConfig.mode,
332
- });
333
- }
334
- }
335
- const validationResult = validateInput(endpoint.inputSchema, context.input);
336
- if (!validationResult.success) {
337
- await safeInvokeHook("onError", hooks.onError, {
338
- requestId,
339
- queryKey: endpoint.key,
340
- metadata: metadataWithAuth,
341
- request,
342
- auth: context.auth,
343
- durationMs: Date.now() - startedAt,
344
- error: validationResult.error,
345
- });
346
- return createErrorResponse(400, "VALIDATION_ERROR", "Request validation failed", {
347
- issues: validationResult.error.issues,
348
- });
349
- }
350
- context.input = validationResult.data;
351
- const pipeline = [
352
- ...globalMiddlewares,
353
- ...endpoint.middlewares,
354
- ];
355
- const result = await runMiddlewares(pipeline, context, () => endpoint.handler(context));
356
- const headers = { ...(endpoint.defaultHeaders ?? {}) };
357
- if (typeof cacheTtlMs === "number") {
358
- headers["cache-control"] = cacheTtlMs > 0 ? `public, max-age=${Math.floor(cacheTtlMs / 1000)}` : "no-store";
359
- }
360
- const durationMs = Date.now() - startedAt;
361
- await safeInvokeHook("onRequestEnd", hooks.onRequestEnd, {
362
- requestId,
363
- queryKey: endpoint.key,
364
- metadata: metadataWithAuth,
365
- request,
366
- auth: context.auth,
367
- durationMs,
368
- result,
369
- });
370
- return {
371
- status: 200,
372
- headers,
373
- body: result,
374
- };
375
- }
376
- catch (error) {
377
- await safeInvokeHook("onError", hooks.onError, {
378
- requestId,
379
- queryKey: endpoint.key,
380
- metadata: context.metadata,
381
- request,
382
- auth: context.auth,
383
- durationMs: Date.now() - startedAt,
384
- error,
385
- });
386
- const message = error instanceof Error ? error.message : "Unexpected error";
387
- return createErrorResponse(500, "INTERNAL_SERVER_ERROR", message);
388
- }
389
- };
390
- export const defineServe = (config) => {
391
- const basePath = config.basePath ?? "";
392
- const router = new ServeRouter(basePath);
393
- const globalMiddlewares = [
394
- ...(config.middlewares ?? []),
395
- ];
396
- const authStrategies = ensureArray(config.auth);
397
- const globalTenantConfig = config.tenant;
398
- const contextFactory = config.context;
399
- const hooks = (config.hooks ?? {});
400
- const openapiConfig = {
401
- enabled: config.openapi?.enabled ?? true,
402
- path: config.openapi?.path ?? "/openapi.json",
403
- };
404
- const docsConfig = {
405
- enabled: config.docs?.enabled ?? true,
406
- path: config.docs?.path ?? "/docs",
407
- };
408
- const openapiPublicPath = applyBasePath(basePath, openapiConfig.path);
409
- const configuredQueries = config.queries ?? {};
410
- const queryEntries = {};
411
- const registerQuery = (key, definition) => {
412
- queryEntries[key] = createEndpoint(String(key), definition);
413
- };
414
- for (const key of Object.keys(configuredQueries)) {
415
- registerQuery(key, configuredQueries[key]);
416
- }
417
- const handler = async (request) => {
418
- const requestId = getRequestId(request);
419
- const endpoint = router.match(request.method, request.path);
420
- if (!endpoint) {
421
- return createErrorResponse(404, "NOT_FOUND", `No endpoint registered for ${request.method} ${request.path}`);
422
- }
423
- return executeEndpoint({
424
- endpoint,
425
- request,
426
- requestId,
427
- authStrategies,
428
- contextFactory,
429
- globalMiddlewares,
430
- globalTenantConfig,
431
- hooks,
432
- });
433
- };
434
- // Track route configuration for client config extraction
435
- const routeConfig = {};
436
- const executeQuery = async (key, options) => {
437
- const endpoint = queryEntries[key];
438
- if (!endpoint) {
439
- throw new Error(`No query registered for key ${String(key)}`);
440
- }
441
- const request = {
442
- method: endpoint.method,
443
- path: options?.request?.path ?? endpoint.metadata.path ?? `/__execute/${String(key)}`,
444
- query: options?.request?.query ?? {},
445
- headers: options?.request?.headers ?? {},
446
- body: options?.input ?? options?.request?.body,
447
- raw: options?.request?.raw,
448
- };
449
- const requestId = getRequestId(request);
450
- const response = await executeEndpoint({
451
- endpoint,
452
- request,
453
- requestId,
454
- authStrategies,
455
- contextFactory,
456
- globalMiddlewares,
457
- globalTenantConfig,
458
- hooks,
459
- additionalContext: options?.context,
460
- });
461
- if (response.status !== 200) {
462
- const errorBody = response.body;
463
- const error = new Error(errorBody.error.message);
464
- error.type = errorBody.error.type;
465
- if (errorBody.error.details) {
466
- error.details = errorBody.error.details;
467
- }
468
- throw error;
469
- }
470
- return response.body;
471
- };
472
- const builder = {
473
- queries: queryEntries,
474
- _routeConfig: routeConfig,
475
- route: (path, endpoint, options) => {
476
- if (!endpoint) {
477
- throw new Error("Endpoint definition is required when registering a route");
478
- }
479
- const method = options?.method ?? endpoint.method;
480
- // Find the query key for this endpoint
481
- const queryKey = Object.entries(queryEntries).find(([_, e]) => e === endpoint)?.[0];
482
- if (queryKey) {
483
- routeConfig[queryKey] = { method };
484
- }
485
- const normalizedPath = normalizeRoutePath(path);
486
- const fallbackRequiresAuth = endpoint.auth
487
- ? true
488
- : authStrategies.length > 0
489
- ? true
490
- : undefined;
491
- const requiresAuth = options?.requiresAuth ?? endpoint.metadata.requiresAuth ?? fallbackRequiresAuth;
492
- const visibility = options?.visibility ?? endpoint.metadata.visibility ?? "public";
493
- const metadata = {
494
- ...endpoint.metadata,
495
- path: normalizedPath,
496
- method,
497
- name: options?.name ?? endpoint.metadata.name ?? endpoint.key,
498
- summary: options?.summary ?? endpoint.metadata.summary,
499
- description: options?.description ?? endpoint.metadata.description,
500
- tags: mergeTags(endpoint.metadata.tags, options?.tags),
501
- requiresAuth,
502
- visibility,
503
- };
504
- const middlewares = [...endpoint.middlewares, ...(options?.middlewares ?? [])];
505
- const registeredEndpoint = {
506
- ...endpoint,
507
- method,
508
- metadata,
509
- middlewares,
510
- };
511
- router.register(registeredEndpoint);
512
- return builder;
513
- },
514
- use: (middleware) => {
515
- globalMiddlewares.push(middleware);
516
- return builder;
517
- },
518
- useAuth: (strategy) => {
519
- authStrategies.push(strategy);
520
- router.markRoutesRequireAuth();
521
- return builder;
522
- },
523
- execute: executeQuery,
524
- run: executeQuery,
525
- describe: () => {
526
- const description = {
527
- basePath: basePath || undefined,
528
- queries: router.list().map(mapEndpointToToolkit),
529
- };
530
- return description;
531
- },
532
- handler,
533
- start: async (options) => startNodeServer(handler, options),
534
- };
535
- if (openapiConfig.enabled) {
536
- const openapiEndpoint = createOpenApiEndpoint(openapiConfig.path, () => router.list(), config.openapi);
537
- router.register(openapiEndpoint);
538
- }
539
- if (docsConfig.enabled) {
540
- const docsEndpoint = createDocsEndpoint(docsConfig.path, openapiPublicPath, config.docs);
541
- router.register(docsEndpoint);
542
- }
543
- return builder;
544
- };
545
- const mapEndpointToToolkit = (endpoint) => {
546
- // Use type assertion to avoid deep type instantiation issues with zodToJsonSchema
547
- const inputSchema = endpoint.inputSchema
548
- ? zodToJsonSchema(endpoint.inputSchema, { target: "openApi3" })
549
- : undefined;
550
- const outputSchema = endpoint.outputSchema
551
- ? zodToJsonSchema(endpoint.outputSchema, { target: "openApi3" })
552
- : undefined;
553
- return {
554
- key: endpoint.key,
555
- path: endpoint.metadata.path,
556
- method: endpoint.method,
557
- name: endpoint.metadata.name ?? endpoint.key,
558
- summary: endpoint.metadata.summary,
559
- description: endpoint.metadata.description,
560
- tags: endpoint.metadata.tags,
561
- visibility: endpoint.metadata.visibility,
562
- requiresAuth: Boolean(endpoint.metadata.requiresAuth),
563
- requiresTenant: endpoint.tenant ? (endpoint.tenant.required !== false) : undefined,
564
- inputSchema,
565
- outputSchema,
566
- custom: endpoint.metadata.custom,
567
- };
568
- };
569
- export const initServe = (options) => {
570
- const { context, ...staticOptions } = options;
571
- const procedure = createProcedureBuilder();
572
- return {
573
- procedure,
574
- query: procedure,
575
- queries: (definitions) => definitions,
576
- define: (config) => {
577
- return defineServe({
578
- ...staticOptions,
579
- ...config,
580
- context: (context ?? {}),
581
- });
582
- },
583
- };
584
- };
package/dist/tenant.d.ts DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * Utilities for multi-tenant query isolation
3
- */
4
- /**
5
- * Creates a tenant-scoped query builder wrapper that automatically
6
- * adds WHERE clauses to filter by tenant.
7
- *
8
- * @example
9
- * ```typescript
10
- * const api = defineServe({
11
- * context: ({ auth }) => ({
12
- * db: createTenantScope(myDb, {
13
- * tenantId: auth?.tenantId,
14
- * column: 'organization_id',
15
- * }),
16
- * }),
17
- * });
18
- * ```
19
- */
20
- export declare function createTenantScope<TDb extends {
21
- table: (name: string) => any;
22
- }>(db: TDb, options: {
23
- tenantId: string | null | undefined;
24
- column: string;
25
- }): TDb;
26
- /**
27
- * Runtime warning when tenant isolation might be misconfigured
28
- */
29
- export declare function warnTenantMisconfiguration(options: {
30
- queryKey: string;
31
- hasTenantConfig: boolean;
32
- hasTenantId: boolean;
33
- mode?: string;
34
- }): void;
35
- //# sourceMappingURL=tenant.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tenant.d.ts","sourceRoot":"","sources":["../src/tenant.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,SAAS;IAAE,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,GAAG,CAAA;CAAE,EAC5E,EAAE,EAAE,GAAG,EACP,OAAO,EAAE;IACP,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACpC,MAAM,EAAE,MAAM,CAAC;CAChB,GACA,GAAG,CAoBL;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,OAAO,CAAC;IACzB,WAAW,EAAE,OAAO,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,QAYA"}
package/dist/tenant.js DELETED
@@ -1,49 +0,0 @@
1
- /**
2
- * Utilities for multi-tenant query isolation
3
- */
4
- /**
5
- * Creates a tenant-scoped query builder wrapper that automatically
6
- * adds WHERE clauses to filter by tenant.
7
- *
8
- * @example
9
- * ```typescript
10
- * const api = defineServe({
11
- * context: ({ auth }) => ({
12
- * db: createTenantScope(myDb, {
13
- * tenantId: auth?.tenantId,
14
- * column: 'organization_id',
15
- * }),
16
- * }),
17
- * });
18
- * ```
19
- */
20
- export function createTenantScope(db, options) {
21
- if (!options.tenantId) {
22
- return db;
23
- }
24
- const originalTable = db.table.bind(db);
25
- return {
26
- ...db,
27
- table: (name) => {
28
- const query = originalTable(name);
29
- // Auto-inject tenant filter
30
- if (query && typeof query.where === 'function') {
31
- return query.where(options.column, 'eq', options.tenantId);
32
- }
33
- return query;
34
- },
35
- };
36
- }
37
- /**
38
- * Runtime warning when tenant isolation might be misconfigured
39
- */
40
- export function warnTenantMisconfiguration(options) {
41
- if (!options.hasTenantConfig) {
42
- console.warn(`[hypequery/serve] Query "${options.queryKey}" accesses user data but has no tenant configuration. ` +
43
- `This may lead to data leaks. Add tenant config to defineServe or the query definition.`);
44
- }
45
- else if (options.hasTenantId && options.mode === 'manual') {
46
- console.warn(`[hypequery/serve] Query "${options.queryKey}" uses manual tenant mode. ` +
47
- `Ensure you manually filter queries by tenantId to prevent data leaks.`);
48
- }
49
- }
@@ -1,13 +0,0 @@
1
- import { z } from 'zod';
2
- export declare const api: import("../types.js").ServeBuilder<import("../types.js").ServeEndpointMap<{
3
- typedQuery: import("../types.js").ServeQueryConfig<z.ZodObject<{
4
- plan: z.ZodOptional<z.ZodString>;
5
- }, "strip", z.ZodTypeAny, {
6
- plan?: string | undefined;
7
- }, {
8
- plan?: string | undefined;
9
- }>, z.ZodTypeAny, {}, import("../types.js").AuthContext, {
10
- plan: string;
11
- }[]>;
12
- }, {}, import("../types.js").AuthContext>, {}, import("../types.js").AuthContext>;
13
- //# sourceMappingURL=builder.test-d.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"builder.test-d.d.ts","sourceRoot":"","sources":["../../src/type-tests/builder.test-d.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAUxB,eAAO,MAAM,GAAG;;;;;;;;;;iFAUd,CAAC"}