kitcn 0.0.1 → 0.12.1

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 (93) hide show
  1. package/bin/intent.js +3 -0
  2. package/dist/aggregate/index.d.ts +388 -0
  3. package/dist/aggregate/index.js +37 -0
  4. package/dist/api-entry-BckXqaLb.js +66 -0
  5. package/dist/auth/client/index.d.ts +37 -0
  6. package/dist/auth/client/index.js +217 -0
  7. package/dist/auth/config/index.d.ts +45 -0
  8. package/dist/auth/config/index.js +24 -0
  9. package/dist/auth/generated/index.d.ts +2 -0
  10. package/dist/auth/generated/index.js +3 -0
  11. package/dist/auth/http/index.d.ts +64 -0
  12. package/dist/auth/http/index.js +461 -0
  13. package/dist/auth/index.d.ts +221 -0
  14. package/dist/auth/index.js +1398 -0
  15. package/dist/auth/nextjs/index.d.ts +50 -0
  16. package/dist/auth/nextjs/index.js +81 -0
  17. package/dist/auth-store-Cljlmdmi.js +197 -0
  18. package/dist/builder-CBdG5W6A.js +1974 -0
  19. package/dist/caller-factory-cTXNvYdz.js +216 -0
  20. package/dist/cli.mjs +13264 -0
  21. package/dist/codegen-lF80HSWu.mjs +3416 -0
  22. package/dist/context-utils-HPC5nXzx.d.ts +17 -0
  23. package/dist/create-schema-odyF4kCy.js +156 -0
  24. package/dist/create-schema-orm-DOyiNDCx.js +246 -0
  25. package/dist/crpc/index.d.ts +105 -0
  26. package/dist/crpc/index.js +169 -0
  27. package/dist/customFunctions-C0voKmtx.js +144 -0
  28. package/dist/error-BZEnI7Sq.js +41 -0
  29. package/dist/generated-contract-disabled-Cih4eITO.js +50 -0
  30. package/dist/generated-contract-disabled-D-sOFy92.d.ts +354 -0
  31. package/dist/http-types-DqJubRPJ.d.ts +292 -0
  32. package/dist/meta-utils-0Pu0Nrap.js +117 -0
  33. package/dist/middleware-BUybuv9n.d.ts +34 -0
  34. package/dist/middleware-C2qTZ3V7.js +84 -0
  35. package/dist/orm/index.d.ts +17 -0
  36. package/dist/orm/index.js +10713 -0
  37. package/dist/plugins/index.d.ts +2 -0
  38. package/dist/plugins/index.js +3 -0
  39. package/dist/procedure-caller-DtxLmGwA.d.ts +1467 -0
  40. package/dist/procedure-caller-MWcxhQDv.js +349 -0
  41. package/dist/query-context-B8o6-8kC.js +1518 -0
  42. package/dist/query-context-CFZqIvD7.d.ts +42 -0
  43. package/dist/query-options-Dw7cOyXl.js +121 -0
  44. package/dist/ratelimit/index.d.ts +269 -0
  45. package/dist/ratelimit/index.js +856 -0
  46. package/dist/ratelimit/react/index.d.ts +76 -0
  47. package/dist/ratelimit/react/index.js +183 -0
  48. package/dist/react/index.d.ts +1284 -0
  49. package/dist/react/index.js +2526 -0
  50. package/dist/rsc/index.d.ts +276 -0
  51. package/dist/rsc/index.js +233 -0
  52. package/dist/runtime-CtvJPkur.js +2453 -0
  53. package/dist/server/index.d.ts +5 -0
  54. package/dist/server/index.js +6 -0
  55. package/dist/solid/index.d.ts +1221 -0
  56. package/dist/solid/index.js +2940 -0
  57. package/dist/transformer-DtDhR3Lc.js +194 -0
  58. package/dist/types-BTb_4BaU.d.ts +42 -0
  59. package/dist/types-BiJE7qxR.d.ts +4 -0
  60. package/dist/types-DEJpkIhw.d.ts +88 -0
  61. package/dist/types-HhO_R6pd.d.ts +213 -0
  62. package/dist/validators-B7oIJCAp.js +279 -0
  63. package/dist/validators-vzRKjBJC.d.ts +88 -0
  64. package/dist/watcher.mjs +96 -0
  65. package/dist/where-clause-compiler-DdjN63Io.d.ts +4756 -0
  66. package/package.json +107 -34
  67. package/skills/convex/SKILL.md +486 -0
  68. package/skills/convex/references/features/aggregates.md +353 -0
  69. package/skills/convex/references/features/auth-admin.md +446 -0
  70. package/skills/convex/references/features/auth-organizations.md +1141 -0
  71. package/skills/convex/references/features/auth-polar.md +579 -0
  72. package/skills/convex/references/features/auth.md +470 -0
  73. package/skills/convex/references/features/create-plugins.md +153 -0
  74. package/skills/convex/references/features/http.md +676 -0
  75. package/skills/convex/references/features/migrations.md +162 -0
  76. package/skills/convex/references/features/orm.md +1166 -0
  77. package/skills/convex/references/features/react.md +657 -0
  78. package/skills/convex/references/features/scheduling.md +267 -0
  79. package/skills/convex/references/features/testing.md +209 -0
  80. package/skills/convex/references/setup/auth.md +501 -0
  81. package/skills/convex/references/setup/biome.md +190 -0
  82. package/skills/convex/references/setup/doc-guidelines.md +145 -0
  83. package/skills/convex/references/setup/index.md +761 -0
  84. package/skills/convex/references/setup/next.md +116 -0
  85. package/skills/convex/references/setup/react.md +175 -0
  86. package/skills/convex/references/setup/server.md +473 -0
  87. package/skills/convex/references/setup/start.md +67 -0
  88. package/LICENSE +0 -21
  89. package/README.md +0 -0
  90. package/dist/index.d.mts +0 -5
  91. package/dist/index.d.mts.map +0 -1
  92. package/dist/index.mjs +0 -6
  93. package/dist/index.mjs.map +0 -1
@@ -0,0 +1,461 @@
1
+ import { ROUTABLE_HTTP_METHODS, httpActionGeneric, httpRouter } from "convex/server";
2
+
3
+ //#region src/auth/error-response.ts
4
+ const isApiErrorLike = (error) => !!error && typeof error === "object" && (error.name === "APIError" && "statusCode" in error || typeof error.statusCode === "number");
5
+ const toResponseInit = (error) => {
6
+ const init = {
7
+ headers: new Headers(error.headers ?? {}),
8
+ status: typeof error.statusCode === "number" ? error.statusCode : 500
9
+ };
10
+ if (typeof error.status === "string") init.statusText = error.status;
11
+ return init;
12
+ };
13
+ const toAuthErrorResponse = (error) => {
14
+ if (!isApiErrorLike(error)) return null;
15
+ const init = toResponseInit(error);
16
+ const { body } = error;
17
+ if (body === void 0) return new Response(null, init);
18
+ if (typeof body === "string") {
19
+ if (init.headers instanceof Headers && !init.headers.has("content-type")) init.headers.set("content-type", "text/plain");
20
+ return new Response(body, init);
21
+ }
22
+ return Response.json(body, init);
23
+ };
24
+
25
+ //#endregion
26
+ //#region src/auth/middleware.ts
27
+ /**
28
+ * Create auth middleware that handles auth routes and OpenID well-known redirect.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { Hono } from 'hono';
33
+ * import { cors } from 'hono/cors';
34
+ * import { authMiddleware } from 'kitcn/auth/http';
35
+ * import { createHttpRouter } from 'kitcn/server';
36
+ *
37
+ * const app = new Hono();
38
+ * app.use('/api/*', cors({ origin: process.env.SITE_URL, credentials: true }));
39
+ * app.use(authMiddleware(getAuth));
40
+ *
41
+ * export default createHttpRouter(app, httpRouter);
42
+ * ```
43
+ */
44
+ function authMiddleware(getAuth, opts = {}) {
45
+ const basePath = opts.basePath ?? "/api/auth";
46
+ return async (c, next) => {
47
+ if (c.req.path === "/.well-known/openid-configuration") return c.redirect(`${process.env.CONVEX_SITE_URL}${basePath}/convex/.well-known/openid-configuration`);
48
+ if (c.req.path.startsWith(basePath)) {
49
+ if (opts.verbose) console.log("request headers", c.req.raw.headers);
50
+ const auth = getAuth(c.env);
51
+ let response;
52
+ try {
53
+ response = await auth.handler(c.req.raw);
54
+ } catch (error) {
55
+ const errorResponse = toAuthErrorResponse(error);
56
+ if (errorResponse) return errorResponse;
57
+ throw error;
58
+ }
59
+ if (opts.verbose) console.log("response headers", response.headers);
60
+ return response;
61
+ }
62
+ return next();
63
+ };
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/internal/upstream/server/cors.ts
68
+ /** biome-ignore-all lint: vendored upstream helper source */
69
+ /**
70
+ * Vendored from upstream helper repository at commit c5e52c8.
71
+ * Source path: packages/convex_helpers/server/cors.ts
72
+ */
73
+ /**
74
+ * This file defines a CorsHttpRouter class that extends Convex's HttpRouter.
75
+ * It provides CORS (Cross-Origin Resource Sharing) support for HTTP routes.
76
+ *
77
+ * The CorsHttpRouter:
78
+ * 1. Allows specifying allowed origins for CORS.
79
+ * 2. Overrides the route method to add CORS headers to all non-OPTIONS requests.
80
+ * 3. Automatically adds an OPTIONS route to handle CORS preflight requests.
81
+ * 4. Uses the handleCors helper function to apply CORS headers consistently.
82
+ *
83
+ * This router simplifies the process of making Convex HTTP endpoints
84
+ * accessible to web applications hosted on different domains while
85
+ * maintaining proper CORS configuration.
86
+ */
87
+ const DEFAULT_EXPOSED_HEADERS = ["Content-Range", "Accept-Ranges"];
88
+ /**
89
+ * Factory function to create a router that adds CORS support to routes.
90
+ * @param allowedOrigins An array of allowed origins for CORS.
91
+ * @returns A function to use instead of http.route when you want CORS.
92
+ */
93
+ const corsRouter = (http, corsConfig) => {
94
+ const allowedExactMethodsByPath = /* @__PURE__ */ new Map();
95
+ const allowedPrefixMethodsByPath = /* @__PURE__ */ new Map();
96
+ return {
97
+ http,
98
+ route: (routeSpec) => {
99
+ const tempRouter = httpRouter();
100
+ tempRouter.exactRoutes = http.exactRoutes;
101
+ tempRouter.prefixRoutes = http.prefixRoutes;
102
+ const config = {
103
+ ...corsConfig,
104
+ ...routeSpec
105
+ };
106
+ const httpCorsHandler = handleCors({
107
+ originalHandler: routeSpec.handler,
108
+ allowedMethods: [routeSpec.method],
109
+ ...config
110
+ });
111
+ /**
112
+ * Figure out what kind of route we're adding: exact or prefix and handle
113
+ * accordingly.
114
+ */
115
+ if ("path" in routeSpec) {
116
+ let methods = allowedExactMethodsByPath.get(routeSpec.path);
117
+ if (!methods) {
118
+ methods = /* @__PURE__ */ new Set();
119
+ allowedExactMethodsByPath.set(routeSpec.path, methods);
120
+ }
121
+ methods.add(routeSpec.method);
122
+ tempRouter.route({
123
+ path: routeSpec.path,
124
+ method: routeSpec.method,
125
+ handler: httpCorsHandler
126
+ });
127
+ handleExactRoute(tempRouter, routeSpec, config, Array.from(methods));
128
+ } else {
129
+ let methods = allowedPrefixMethodsByPath.get(routeSpec.pathPrefix);
130
+ if (!methods) {
131
+ methods = /* @__PURE__ */ new Set();
132
+ allowedPrefixMethodsByPath.set(routeSpec.pathPrefix, methods);
133
+ }
134
+ methods.add(routeSpec.method);
135
+ tempRouter.route({
136
+ pathPrefix: routeSpec.pathPrefix,
137
+ method: routeSpec.method,
138
+ handler: httpCorsHandler
139
+ });
140
+ handlePrefixRoute(tempRouter, routeSpec, config, Array.from(methods));
141
+ }
142
+ /**
143
+ * Copy the routes from the temporary router to the main router.
144
+ */
145
+ http.exactRoutes = new Map(tempRouter.exactRoutes);
146
+ http.prefixRoutes = new Map(tempRouter.prefixRoutes);
147
+ }
148
+ };
149
+ };
150
+ /**
151
+ * Handles exact route matching and adds OPTIONS handler.
152
+ * @param tempRouter Temporary router instance.
153
+ * @param routeSpec Route specification for exact matching.
154
+ */
155
+ function handleExactRoute(tempRouter, routeSpec, config, allowedMethods) {
156
+ const currentMethodsForPath = tempRouter.exactRoutes.get(routeSpec.path);
157
+ /**
158
+ * Add the OPTIONS handler for the given path
159
+ */
160
+ const optionsHandler = createOptionsHandlerForMethods(allowedMethods, config);
161
+ currentMethodsForPath?.set("OPTIONS", optionsHandler);
162
+ tempRouter.exactRoutes.set(routeSpec.path, new Map(currentMethodsForPath));
163
+ }
164
+ /**
165
+ * Handles prefix route matching and adds OPTIONS handler.
166
+ * @param tempRouter Temporary router instance.
167
+ * @param routeSpec Route specification for prefix matching.
168
+ */
169
+ function handlePrefixRoute(tempRouter, routeSpec, config, allowedMethods) {
170
+ /**
171
+ * prefixRoutes is structured differently than exactRoutes. It's defined as
172
+ * a Map<string, Map<string, PublicHttpAction>> where the KEY is the
173
+ * METHOD and the VALUE is a map of paths and handlers.
174
+ */
175
+ const optionsHandler = createOptionsHandlerForMethods(allowedMethods, config);
176
+ const optionsPrefixes = tempRouter.prefixRoutes.get("OPTIONS") || /* @__PURE__ */ new Map();
177
+ optionsPrefixes.set(routeSpec.pathPrefix, optionsHandler);
178
+ tempRouter.prefixRoutes.set("OPTIONS", optionsPrefixes);
179
+ }
180
+ /**
181
+ * Creates an OPTIONS handler for the given HTTP methods.
182
+ * @param methods Array of HTTP methods to be allowed.
183
+ * @returns A CORS-enabled OPTIONS handler.
184
+ */
185
+ function createOptionsHandlerForMethods(methods, config) {
186
+ return handleCors({
187
+ ...config,
188
+ allowedMethods: methods
189
+ });
190
+ }
191
+ /**
192
+ * handleCors() is a higher-order function that wraps a Convex HTTP action handler to add CORS support.
193
+ * It allows for customization of allowed HTTP methods and origins for cross-origin requests.
194
+ *
195
+ * The function:
196
+ * 1. Validates and normalizes the allowed HTTP methods.
197
+ * 2. Generates appropriate CORS headers based on the provided configuration.
198
+ * 3. Handles preflight OPTIONS requests automatically.
199
+ * 4. Wraps the original handler to add CORS headers to its response.
200
+ *
201
+ * This helper simplifies the process of making Convex HTTP actions accessible
202
+ * to web applications hosted on different domains.
203
+ */
204
+ const SECONDS_IN_A_DAY = 3600 * 24;
205
+ /**
206
+ * Example CORS origins:
207
+ * - "*" (allow all origins)
208
+ * - "https://example.com" (allow a specific domain)
209
+ * - "https://*.example.com" (allow all subdomains of example.com)
210
+ * - "https://example1.com, https://example2.com" (allow multiple specific domains)
211
+ * - "null" (allow requests from data URLs or local files)
212
+ */
213
+ const handleCors = ({ originalHandler, allowedMethods = ["OPTIONS"], allowedOrigins = ["*"], allowedHeaders = ["Content-Type"], exposedHeaders = DEFAULT_EXPOSED_HEADERS, allowCredentials = false, browserCacheMaxAge = SECONDS_IN_A_DAY, enforceAllowOrigins = false, debug = false }) => {
214
+ const filteredMethods = Array.from(new Set(allowedMethods.map((method) => method.toUpperCase()))).filter((method) => ROUTABLE_HTTP_METHODS.includes(method));
215
+ if (filteredMethods.length === 0) throw new Error("No valid HTTP methods provided");
216
+ /**
217
+ * Ensure OPTIONS is not duplicated if it was passed in
218
+ * E.g. if allowedMethods = ["GET", "OPTIONS"]
219
+ */
220
+ const allowMethods = filteredMethods.includes("OPTIONS") ? filteredMethods.join(", ") : [...filteredMethods].join(", ");
221
+ /**
222
+ * Build up the set of CORS headers
223
+ */
224
+ const commonHeaders = { Vary: "Origin" };
225
+ if (allowCredentials) commonHeaders["Access-Control-Allow-Credentials"] = "true";
226
+ if (exposedHeaders.length > 0) commonHeaders["Access-Control-Expose-Headers"] = exposedHeaders.join(", ");
227
+ async function parseAllowedOrigins(request) {
228
+ return Array.isArray(allowedOrigins) ? allowedOrigins : await allowedOrigins(request);
229
+ }
230
+ async function isAllowedOrigin(request) {
231
+ const requestOrigin = request.headers.get("origin");
232
+ if (!requestOrigin) return false;
233
+ return (await parseAllowedOrigins(request)).some((allowed) => {
234
+ if (allowed === "*") return true;
235
+ if (allowed === requestOrigin) return true;
236
+ if (allowed.startsWith("*.")) {
237
+ const wildcardDomain = allowed.slice(1);
238
+ const rootDomain = allowed.slice(2);
239
+ try {
240
+ const url = new URL(requestOrigin);
241
+ return url.protocol === "https:" && (url.hostname.endsWith(wildcardDomain) || url.hostname === rootDomain);
242
+ } catch {
243
+ return false;
244
+ }
245
+ }
246
+ return false;
247
+ });
248
+ }
249
+ /**
250
+ * Return our modified HTTP action
251
+ */
252
+ return httpActionGeneric(async (ctx, request) => {
253
+ if (debug) console.log("CORS request", {
254
+ path: request.url,
255
+ origin: request.headers.get("origin"),
256
+ headers: request.headers,
257
+ method: request.method,
258
+ body: request.body
259
+ });
260
+ const requestOrigin = request.headers.get("origin");
261
+ const parsedAllowedOrigins = await parseAllowedOrigins(request);
262
+ if (debug) console.log("allowed origins", parsedAllowedOrigins);
263
+ let allowOrigins = null;
264
+ if (parsedAllowedOrigins.includes("*") && requestOrigin && !allowCredentials) allowOrigins = requestOrigin;
265
+ else if (requestOrigin) {
266
+ if (await isAllowedOrigin(request)) allowOrigins = requestOrigin;
267
+ }
268
+ if (enforceAllowOrigins && !allowOrigins) {
269
+ console.error(`Request from origin ${requestOrigin} blocked, missing from allowed origins: ${parsedAllowedOrigins.join()}`);
270
+ return new Response(null, { status: 403 });
271
+ }
272
+ /**
273
+ * OPTIONS has no handler and just returns headers
274
+ */
275
+ if (request.method === "OPTIONS") {
276
+ const responseHeaders = new Headers({
277
+ ...commonHeaders,
278
+ ...allowOrigins ? { "Access-Control-Allow-Origin": allowOrigins } : {},
279
+ "Access-Control-Allow-Methods": allowMethods,
280
+ "Access-Control-Allow-Headers": allowedHeaders.join(", "),
281
+ "Access-Control-Max-Age": browserCacheMaxAge.toString()
282
+ });
283
+ if (debug) console.log("CORS OPTIONS response headers", responseHeaders);
284
+ return new Response(null, {
285
+ status: 204,
286
+ headers: responseHeaders
287
+ });
288
+ }
289
+ /**
290
+ * If the method is not OPTIONS, it must pass a handler
291
+ */
292
+ if (!originalHandler) throw new Error("No PublicHttpAction provider to CORS handler");
293
+ const originalResponse = await ("_handler" in originalHandler ? originalHandler["_handler"] : originalHandler)(ctx, request);
294
+ /**
295
+ * Second, get a copy of the original response's headers and add the
296
+ * allow origin header if it's allowed
297
+ */
298
+ const newHeaders = new Headers(originalResponse.headers);
299
+ if (allowOrigins) newHeaders.set("Access-Control-Allow-Origin", allowOrigins);
300
+ /**
301
+ * Third, add or update our other CORS headers
302
+ */
303
+ Object.entries(commonHeaders).forEach(([key, value]) => {
304
+ newHeaders.set(key, value);
305
+ });
306
+ if (debug) console.log("CORS response headers", newHeaders);
307
+ /**
308
+ * Fourth, return the modified Response.
309
+ * A Response object is immutable, so we create a new one to return here.
310
+ */
311
+ return new Response(originalResponse.body, {
312
+ status: originalResponse.status,
313
+ statusText: originalResponse.statusText,
314
+ headers: newHeaders
315
+ });
316
+ });
317
+ };
318
+
319
+ //#endregion
320
+ //#region src/auth/registerRoutes.ts
321
+ /** biome-ignore-all lint/suspicious/noConsole: lib */
322
+ const LOCAL_AUTH_HOSTS = new Set([
323
+ "127.0.0.1",
324
+ "::1",
325
+ "localhost"
326
+ ]);
327
+ const LOCAL_CONVEX_AUTH_IP_PATHS = new Set([
328
+ "/convex/.well-known/openid-configuration",
329
+ "/convex/jwks",
330
+ "/convex/token"
331
+ ]);
332
+ const withLocalConvexAuthIp = (request, basePath) => {
333
+ if (request.headers.get("x-forwarded-for")) return request;
334
+ let url;
335
+ try {
336
+ url = new URL(request.url);
337
+ } catch {
338
+ return request;
339
+ }
340
+ if (!LOCAL_AUTH_HOSTS.has(url.hostname)) return request;
341
+ if (request.method !== "GET") return request;
342
+ const normalizedBasePath = basePath.length > 1 && basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
343
+ const normalizedPath = normalizedBasePath === "/" ? url.pathname : url.pathname.startsWith(normalizedBasePath) ? url.pathname.slice(normalizedBasePath.length) || "/" : url.pathname;
344
+ if (!LOCAL_CONVEX_AUTH_IP_PATHS.has(normalizedPath)) return request;
345
+ const headers = new Headers(request.headers);
346
+ headers.set("x-forwarded-for", "127.0.0.1");
347
+ return new Request(url.toString(), {
348
+ headers,
349
+ method: request.method
350
+ });
351
+ };
352
+ const registerRoutes = (http, getAuth, opts = {}) => {
353
+ const staticAuth = getAuth({});
354
+ const path = staticAuth.options.basePath ?? "/api/auth";
355
+ const authRequestHandler = httpActionGeneric(async (ctx, request) => {
356
+ if (opts?.verbose) {
357
+ console.log("options.baseURL", staticAuth.options.baseURL);
358
+ console.log("request headers", request.headers);
359
+ }
360
+ const auth = getAuth(ctx);
361
+ const authRequest = withLocalConvexAuthIp(request, path);
362
+ let response;
363
+ try {
364
+ response = await auth.handler(authRequest);
365
+ } catch (error) {
366
+ const errorResponse = toAuthErrorResponse(error);
367
+ if (errorResponse) return errorResponse;
368
+ throw error;
369
+ }
370
+ if (opts?.verbose) console.log("response headers", response.headers);
371
+ return response;
372
+ });
373
+ if (!http.lookup("/.well-known/openid-configuration", "GET")) http.route({
374
+ handler: httpActionGeneric(async () => {
375
+ const url = `${process.env.CONVEX_SITE_URL}${path}/convex/.well-known/openid-configuration`;
376
+ return Response.redirect(url);
377
+ }),
378
+ method: "GET",
379
+ path: "/.well-known/openid-configuration"
380
+ });
381
+ if (!opts.cors) {
382
+ http.route({
383
+ handler: authRequestHandler,
384
+ method: "GET",
385
+ pathPrefix: `${path}/`
386
+ });
387
+ http.route({
388
+ handler: authRequestHandler,
389
+ method: "POST",
390
+ pathPrefix: `${path}/`
391
+ });
392
+ return;
393
+ }
394
+ const corsOpts = typeof opts.cors === "boolean" ? {
395
+ allowedHeaders: [],
396
+ allowedOrigins: [],
397
+ exposedHeaders: []
398
+ } : opts.cors;
399
+ let trustedOriginsOption;
400
+ const cors = corsRouter(http, {
401
+ allowCredentials: true,
402
+ allowedHeaders: [
403
+ "Content-Type",
404
+ "Better-Auth-Cookie",
405
+ "Authorization"
406
+ ].concat(corsOpts.allowedHeaders ?? []),
407
+ debug: opts?.verbose,
408
+ enforceAllowOrigins: false,
409
+ exposedHeaders: ["Set-Better-Auth-Cookie"].concat(corsOpts.exposedHeaders ?? []),
410
+ allowedOrigins: async (request) => {
411
+ const resolvedTrustedOrigins = trustedOriginsOption ?? (await staticAuth.$context).options.trustedOrigins ?? [];
412
+ trustedOriginsOption = resolvedTrustedOrigins;
413
+ return (Array.isArray(resolvedTrustedOrigins) ? resolvedTrustedOrigins : await resolvedTrustedOrigins(request) ?? []).filter((origin) => typeof origin === "string").map((origin) => origin.endsWith("*") && origin.length > 1 ? origin.slice(0, -1) : origin).concat(corsOpts.allowedOrigins ?? []);
414
+ }
415
+ });
416
+ cors.route({
417
+ handler: authRequestHandler,
418
+ method: "GET",
419
+ pathPrefix: `${path}/`
420
+ });
421
+ cors.route({
422
+ handler: authRequestHandler,
423
+ method: "POST",
424
+ pathPrefix: `${path}/`
425
+ });
426
+ };
427
+
428
+ //#endregion
429
+ //#region src/auth-http/index.ts
430
+ /**
431
+ * Install Convex-safe polyfills required by Better Auth's HTTP handling.
432
+ * This runs automatically when importing `kitcn/auth/http`.
433
+ */
434
+ function installAuthHttpPolyfills() {
435
+ if (typeof MessageChannel !== "undefined") return;
436
+ class MockMessagePort {
437
+ onmessage;
438
+ onmessageerror;
439
+ addEventListener() {}
440
+ close() {}
441
+ dispatchEvent(_event) {
442
+ return false;
443
+ }
444
+ postMessage(_message, _transfer = []) {}
445
+ removeEventListener() {}
446
+ start() {}
447
+ }
448
+ class MockMessageChannel {
449
+ port1;
450
+ port2;
451
+ constructor() {
452
+ this.port1 = new MockMessagePort();
453
+ this.port2 = new MockMessagePort();
454
+ }
455
+ }
456
+ globalThis.MessageChannel = MockMessageChannel;
457
+ }
458
+ installAuthHttpPolyfills();
459
+
460
+ //#endregion
461
+ export { authMiddleware, installAuthHttpPolyfills, registerRoutes };
@@ -0,0 +1,221 @@
1
+ import { a as QueryCtxWithPreferredOrmQueryTable, n as LookupByIdResultByCtx, t as DocByCtx } from "../query-context-CFZqIvD7.js";
2
+ import { t as GetAuth } from "../types-BiJE7qxR.js";
3
+ import { t as GenericCtx } from "../context-utils-HPC5nXzx.js";
4
+ import { S as defineAuth, _ as GenericAuthBeforeResult, a as AuthFunctions, b as GenericAuthTriggerHandlers, c as createApi, d as deleteOneHandler, f as findManyHandler, g as BetterAuthOptionsWithoutDatabase, h as updateOneHandler, i as getGeneratedAuthDisabledReason, l as createHandler, m as updateManyHandler, n as GeneratedAuthDisabledReasonKind, o as Triggers, p as findOneHandler, r as createDisabledAuthRuntime, s as createClient, t as AuthRuntime, u as deleteManyHandler, v as GenericAuthDefinition, x as GenericAuthTriggers, y as GenericAuthTriggerChange } from "../generated-contract-disabled-D-sOFy92.js";
5
+ import * as convex_values0 from "convex/values";
6
+ import { Infer } from "convex/values";
7
+ import { DocumentByName, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericSchema, PaginationOptions, PaginationResult, SchemaDefinition, TableNamesInDataModel } from "convex/server";
8
+ import { convex } from "@convex-dev/better-auth/plugins";
9
+ import * as better_auth_adapters0 from "better-auth/adapters";
10
+ import { DBAdapterDebugLogOption } from "better-auth/adapters";
11
+ import { BetterAuthDBSchema } from "better-auth/db";
12
+ import { BetterAuthOptions } from "better-auth/minimal";
13
+ import * as better_auth0 from "better-auth";
14
+ import { Where } from "better-auth/types";
15
+ import { SetOptional } from "type-fest";
16
+
17
+ //#region src/auth/adapter.d.ts
18
+ declare const handlePagination: (next: ({
19
+ paginationOpts
20
+ }: {
21
+ paginationOpts: PaginationOptions;
22
+ }) => Promise<SetOptional<PaginationResult<any>, "page"> & {
23
+ count?: number;
24
+ }>, {
25
+ limit,
26
+ numItems
27
+ }?: {
28
+ limit?: number;
29
+ numItems?: number;
30
+ }) => Promise<{
31
+ count: number;
32
+ cursor: string | null;
33
+ docs: any[];
34
+ isDone: boolean;
35
+ }>;
36
+ type ConvexCleanedWhere = Where & {
37
+ value: number[] | string[] | boolean | number | string | null;
38
+ };
39
+ declare const adapterConfig: {
40
+ adapterId: string;
41
+ adapterName: string;
42
+ debugLogs: false;
43
+ disableIdGeneration: true;
44
+ mapKeysTransformInput: {
45
+ id: string;
46
+ };
47
+ mapKeysTransformOutput: {
48
+ _id: string;
49
+ };
50
+ supportsJSON: false;
51
+ supportsNumericIds: false;
52
+ supportsDates: false;
53
+ supportsArrays: true;
54
+ transaction: false;
55
+ usePlural: false;
56
+ customTransformInput: ({
57
+ data,
58
+ fieldAttributes
59
+ }: {
60
+ data: any;
61
+ fieldAttributes: better_auth0.DBFieldAttribute;
62
+ field: string;
63
+ action: "create" | "update" | "findOne" | "findMany" | "updateMany" | "delete" | "deleteMany" | "count";
64
+ model: string;
65
+ schema: BetterAuthDBSchema;
66
+ options: BetterAuthOptions;
67
+ }) => any;
68
+ customTransformOutput: ({
69
+ data,
70
+ fieldAttributes
71
+ }: {
72
+ data: any;
73
+ fieldAttributes: better_auth0.DBFieldAttribute;
74
+ field: string;
75
+ select: string[];
76
+ model: string;
77
+ schema: BetterAuthDBSchema;
78
+ options: BetterAuthOptions;
79
+ }) => any;
80
+ };
81
+ declare const httpAdapter: <DataModel extends GenericDataModel, Schema extends SchemaDefinition<any, any>>(ctx: GenericCtx<DataModel>, {
82
+ authFunctions,
83
+ debugLogs,
84
+ schema
85
+ }: {
86
+ authFunctions: AuthFunctions;
87
+ debugLogs?: DBAdapterDebugLogOption;
88
+ schema?: Schema;
89
+ }) => better_auth_adapters0.AdapterFactory<BetterAuthOptions>;
90
+ declare const dbAdapter: <DataModel extends GenericDataModel, Schema extends SchemaDefinition<any, any>>(ctx: GenericCtx<DataModel>, getAuthOptions: (ctx: any) => BetterAuthOptions, {
91
+ authFunctions,
92
+ debugLogs,
93
+ schema
94
+ }: {
95
+ authFunctions: AuthFunctions;
96
+ schema: Schema;
97
+ debugLogs?: DBAdapterDebugLogOption;
98
+ }) => better_auth_adapters0.AdapterFactory<BetterAuthOptions>;
99
+ //#endregion
100
+ //#region src/auth/adapter-utils.d.ts
101
+ type AdapterPaginationOptions = PaginationOptions & {
102
+ endCursor?: string | null;
103
+ maximumRowsRead?: number;
104
+ };
105
+ declare const adapterWhereValidator: convex_values0.VObject<{
106
+ connector?: "AND" | "OR" | undefined;
107
+ operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
108
+ value: string | number | boolean | string[] | number[] | null;
109
+ field: string;
110
+ }, {
111
+ connector: convex_values0.VUnion<"AND" | "OR" | undefined, [convex_values0.VLiteral<"AND", "required">, convex_values0.VLiteral<"OR", "required">], "optional", never>;
112
+ field: convex_values0.VString<string, "required">;
113
+ operator: convex_values0.VUnion<"lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined, [convex_values0.VLiteral<"lt", "required">, convex_values0.VLiteral<"lte", "required">, convex_values0.VLiteral<"gt", "required">, convex_values0.VLiteral<"gte", "required">, convex_values0.VLiteral<"eq", "required">, convex_values0.VLiteral<"in", "required">, convex_values0.VLiteral<"not_in", "required">, convex_values0.VLiteral<"ne", "required">, convex_values0.VLiteral<"contains", "required">, convex_values0.VLiteral<"starts_with", "required">, convex_values0.VLiteral<"ends_with", "required">], "optional", never>;
114
+ value: convex_values0.VUnion<string | number | boolean | string[] | number[] | null, [convex_values0.VString<string, "required">, convex_values0.VFloat64<number, "required">, convex_values0.VBoolean<boolean, "required">, convex_values0.VArray<string[], convex_values0.VString<string, "required">, "required">, convex_values0.VArray<number[], convex_values0.VFloat64<number, "required">, "required">, convex_values0.VNull<null, "required">], "required", never>;
115
+ }, "required", "value" | "connector" | "field" | "operator">;
116
+ declare const adapterArgsValidator: convex_values0.VObject<{
117
+ select?: string[] | undefined;
118
+ where?: {
119
+ connector?: "AND" | "OR" | undefined;
120
+ operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
121
+ value: string | number | boolean | string[] | number[] | null;
122
+ field: string;
123
+ }[] | undefined;
124
+ limit?: number | undefined;
125
+ offset?: number | undefined;
126
+ sortBy?: {
127
+ field: string;
128
+ direction: "asc" | "desc";
129
+ } | undefined;
130
+ model: string;
131
+ }, {
132
+ limit: convex_values0.VFloat64<number | undefined, "optional">;
133
+ model: convex_values0.VString<string, "required">;
134
+ offset: convex_values0.VFloat64<number | undefined, "optional">;
135
+ select: convex_values0.VArray<string[] | undefined, convex_values0.VString<string, "required">, "optional">;
136
+ sortBy: convex_values0.VObject<{
137
+ field: string;
138
+ direction: "asc" | "desc";
139
+ } | undefined, {
140
+ direction: convex_values0.VUnion<"asc" | "desc", [convex_values0.VLiteral<"asc", "required">, convex_values0.VLiteral<"desc", "required">], "required", never>;
141
+ field: convex_values0.VString<string, "required">;
142
+ }, "optional", "field" | "direction">;
143
+ where: convex_values0.VArray<{
144
+ connector?: "AND" | "OR" | undefined;
145
+ operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
146
+ value: string | number | boolean | string[] | number[] | null;
147
+ field: string;
148
+ }[] | undefined, convex_values0.VObject<{
149
+ connector?: "AND" | "OR" | undefined;
150
+ operator?: "lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined;
151
+ value: string | number | boolean | string[] | number[] | null;
152
+ field: string;
153
+ }, {
154
+ connector: convex_values0.VUnion<"AND" | "OR" | undefined, [convex_values0.VLiteral<"AND", "required">, convex_values0.VLiteral<"OR", "required">], "optional", never>;
155
+ field: convex_values0.VString<string, "required">;
156
+ operator: convex_values0.VUnion<"lt" | "lte" | "gt" | "gte" | "eq" | "in" | "not_in" | "ne" | "contains" | "starts_with" | "ends_with" | undefined, [convex_values0.VLiteral<"lt", "required">, convex_values0.VLiteral<"lte", "required">, convex_values0.VLiteral<"gt", "required">, convex_values0.VLiteral<"gte", "required">, convex_values0.VLiteral<"eq", "required">, convex_values0.VLiteral<"in", "required">, convex_values0.VLiteral<"not_in", "required">, convex_values0.VLiteral<"ne", "required">, convex_values0.VLiteral<"contains", "required">, convex_values0.VLiteral<"starts_with", "required">, convex_values0.VLiteral<"ends_with", "required">], "optional", never>;
157
+ value: convex_values0.VUnion<string | number | boolean | string[] | number[] | null, [convex_values0.VString<string, "required">, convex_values0.VFloat64<number, "required">, convex_values0.VBoolean<boolean, "required">, convex_values0.VArray<string[], convex_values0.VString<string, "required">, "required">, convex_values0.VArray<number[], convex_values0.VFloat64<number, "required">, "required">, convex_values0.VNull<null, "required">], "required", never>;
158
+ }, "required", "value" | "connector" | "field" | "operator">, "optional">;
159
+ }, "required", "model" | "select" | "where" | "limit" | "offset" | "sortBy" | "sortBy.field" | "sortBy.direction">;
160
+ declare const hasUniqueFields: (betterAuthSchema: BetterAuthDBSchema, model: string, input: Record<string, any>) => boolean;
161
+ declare const checkUniqueFields: <Schema extends SchemaDefinition<any, any>>(ctx: GenericQueryCtx<GenericDataModel>, schema: Schema, betterAuthSchema: BetterAuthDBSchema, table: string, input: Record<string, any>, doc?: Record<string, any>) => Promise<void>;
162
+ declare const selectFields: <T extends TableNamesInDataModel<GenericDataModel>, D extends DocumentByName<GenericDataModel, T>>(doc: D | null, select?: string[]) => D | null;
163
+ declare const paginate: <Doc extends DocumentByName<GenericDataModel, T>, T extends TableNamesInDataModel<GenericDataModel>>(ctx: GenericQueryCtx<GenericDataModel>, schema: SchemaDefinition<any, any>, betterAuthSchema: BetterAuthDBSchema, args: Infer<typeof adapterArgsValidator> & {
164
+ paginationOpts: AdapterPaginationOptions;
165
+ }) => Promise<PaginationResult<Doc>>;
166
+ declare const listOne: <Doc extends DocumentByName<GenericDataModel, T>, T extends TableNamesInDataModel<GenericDataModel>>(ctx: GenericQueryCtx<GenericDataModel>, schema: SchemaDefinition<any, any>, betterAuthSchema: BetterAuthDBSchema, args: Infer<typeof adapterArgsValidator>) => Promise<Doc | null>;
167
+ //#endregion
168
+ //#region src/auth/generated-contract.d.ts
169
+ type UnknownFn = (...args: never[]) => unknown;
170
+ declare const getInvalidAuthDefinitionExportReason: (authDefinitionPath?: string) => string;
171
+ type AuthDefinitionModule<GenericCtx, DataModel extends GenericDataModel, Schema extends SchemaDefinition<GenericSchema, true>, AuthOptions extends BetterAuthOptionsWithoutDatabase> = {
172
+ default: GenericAuthDefinition<GenericCtx, DataModel, Schema, AuthOptions>;
173
+ };
174
+ type AuthDefinitionInput<GenericCtx, DataModel extends GenericDataModel, Schema extends SchemaDefinition<GenericSchema, true>, AuthOptions extends BetterAuthOptionsWithoutDatabase> = GenericAuthDefinition<GenericCtx, DataModel, Schema, AuthOptions> | AuthDefinitionModule<GenericCtx, DataModel, Schema, AuthOptions>;
175
+ declare const resolveGeneratedAuthDefinition: <Definition extends UnknownFn>(input: unknown, reason: string) => Definition;
176
+ declare const createAuthRuntime: <DataModel extends GenericDataModel, Schema extends SchemaDefinition<GenericSchema, true>, TriggerCtx extends GenericMutationCtx<DataModel> = GenericMutationCtx<DataModel>, GenericCtx = GenericMutationCtx<DataModel>, AuthOptions extends BetterAuthOptionsWithoutDatabase = BetterAuthOptionsWithoutDatabase>(config: {
177
+ internal: unknown;
178
+ moduleName: string;
179
+ schema: Schema;
180
+ auth: AuthDefinitionInput<GenericCtx, DataModel, Schema, AuthOptions>;
181
+ context?: (ctx: GenericMutationCtx<DataModel>) => TriggerCtx | Promise<TriggerCtx>;
182
+ }) => AuthRuntime<DataModel, Schema, TriggerCtx, GenericCtx, AuthOptions>;
183
+ //#endregion
184
+ //#region src/auth/helpers.d.ts
185
+ type SessionDoc<TCtx extends GenericQueryCtx<any>> = DocByCtx<TCtx, 'session'>;
186
+ type SessionResult<TCtx extends GenericQueryCtx<any>> = LookupByIdResultByCtx<TCtx, 'session'>;
187
+ type SessionLookupCtx<TCtx extends GenericQueryCtx<any>> = QueryCtxWithPreferredOrmQueryTable<TCtx, 'session'>;
188
+ type SessionClientSignals = {
189
+ ip?: string;
190
+ userAgent?: string;
191
+ };
192
+ declare const getAuthUserIdentity: <DataModel extends GenericDataModel>(ctx: GenericQueryCtx<DataModel>) => Promise<{
193
+ sessionId: DocumentByName<DataModel, "session">["_id"];
194
+ userId: DocumentByName<DataModel, "user">["_id"];
195
+ tokenIdentifier: string;
196
+ subject: string;
197
+ issuer: string;
198
+ name?: string;
199
+ givenName?: string;
200
+ familyName?: string;
201
+ nickname?: string;
202
+ preferredUsername?: string;
203
+ profileUrl?: string;
204
+ pictureUrl?: string;
205
+ email?: string;
206
+ emailVerified?: boolean;
207
+ gender?: string;
208
+ birthday?: string;
209
+ timezone?: string;
210
+ language?: string;
211
+ phoneNumber?: string;
212
+ phoneNumberVerified?: boolean;
213
+ address?: string;
214
+ updatedAt?: string;
215
+ } | null>;
216
+ declare const getAuthUserId: <DataModel extends GenericDataModel>(ctx: GenericQueryCtx<DataModel>) => Promise<string | null>;
217
+ declare function getSession<TCtx extends GenericQueryCtx<any>>(ctx: TCtx & SessionLookupCtx<TCtx>, _sessionId?: SessionDoc<TCtx>['_id']): Promise<SessionResult<TCtx>>;
218
+ declare const getSessionNetworkSignals: <TCtx extends GenericQueryCtx<any>>(ctx: TCtx & QueryCtxWithPreferredOrmQueryTable<TCtx, "session">, session?: SessionResult<TCtx> | null) => Promise<SessionClientSignals>;
219
+ declare const getHeaders: <TCtx extends GenericQueryCtx<any>>(ctx: TCtx & QueryCtxWithPreferredOrmQueryTable<TCtx, "session">, session?: SessionResult<TCtx> | null) => Promise<Headers>;
220
+ //#endregion
221
+ export { type AuthFunctions, type AuthRuntime, BetterAuthOptionsWithoutDatabase, ConvexCleanedWhere, type GeneratedAuthDisabledReasonKind, GenericAuthBeforeResult, GenericAuthDefinition, GenericAuthTriggerChange, GenericAuthTriggerHandlers, GenericAuthTriggers, GetAuth, SessionClientSignals, type Triggers, adapterArgsValidator, adapterConfig, adapterWhereValidator, checkUniqueFields, convex, createApi, createAuthRuntime, createClient, createDisabledAuthRuntime, createHandler, dbAdapter, defineAuth, deleteManyHandler, deleteOneHandler, findManyHandler, findOneHandler, getAuthUserId, getAuthUserIdentity, getGeneratedAuthDisabledReason, getHeaders, getInvalidAuthDefinitionExportReason, getSession, getSessionNetworkSignals, handlePagination, hasUniqueFields, httpAdapter, listOne, paginate, resolveGeneratedAuthDefinition, selectFields, updateManyHandler, updateOneHandler };