kitcn 0.33.10 → 0.33.11

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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # kitcn
2
2
 
3
+ ## 0.33.11
4
+
5
+ ### Patch Changes
6
+
7
+ - [#485](https://github.com/udecode/kitcn/pull/485) [`1aea19e`](https://github.com/udecode/kitcn/commit/1aea19e9a2d6afe909fa7fe3e31238a15809eb74) Thanks [@EfficiencyCorp](https://github.com/EfficiencyCorp)! - ## Patches
8
+
9
+ - Fix Better Auth 1.7.6+ HTTP auth routes failing with `Unexpected field 'modelKey'`: the auth adapters no longer forward Better Auth's `modelKey` into Convex function arguments.
10
+
11
+ - [#481](https://github.com/udecode/kitcn/pull/481) [`88140a0`](https://github.com/udecode/kitcn/commit/88140a045795e0fe4234dca44180d37ee3bcfa55) Thanks [@EfficiencyCorp](https://github.com/EfficiencyCorp)! - ## Patches
12
+
13
+ - Fix Better Auth `findMany` calls with `select` failing with `Unexpected field select` in the generated auth `findMany` query.
14
+
15
+ - [#483](https://github.com/udecode/kitcn/pull/483) [`64d84a2`](https://github.com/udecode/kitcn/commit/64d84a28e629e0201ac0bbb768462d71f618c75d) Thanks [@EfficiencyCorp](https://github.com/EfficiencyCorp)! - ## Patches
16
+
17
+ - Fix `kitcn codegen` and `kitcn dev` making a running `convex dev` redeploy
18
+ when nothing changed.
19
+
3
20
  ## 0.33.10
4
21
 
5
22
  ### Patch Changes
@@ -1,2 +1,2 @@
1
- import { C as GenericAuthTriggerHandlers, S as GenericAuthTriggerChange, T as defineAuth, b as GenericAuthBeforeResult, i as getGeneratedAuthDisabledReason, n as GeneratedAuthDisabledReasonKind, r as createDisabledAuthRuntime, t as AuthRuntime, w as GenericAuthTriggers, x as GenericAuthDefinition, y as BetterAuthOptionsWithoutDatabase } from "../../generated-contract-disabled-PdNGvNYP.js";
1
+ import { C as GenericAuthTriggerHandlers, S as GenericAuthTriggerChange, T as defineAuth, b as GenericAuthBeforeResult, i as getGeneratedAuthDisabledReason, n as GeneratedAuthDisabledReasonKind, r as createDisabledAuthRuntime, t as AuthRuntime, w as GenericAuthTriggers, x as GenericAuthDefinition, y as BetterAuthOptionsWithoutDatabase } from "../../generated-contract-disabled-DcgLIEHK.js";
2
2
  export { type AuthRuntime, BetterAuthOptionsWithoutDatabase, type GeneratedAuthDisabledReasonKind, GenericAuthBeforeResult, GenericAuthDefinition, GenericAuthTriggerChange, GenericAuthTriggerHandlers, GenericAuthTriggers, createDisabledAuthRuntime, defineAuth, getGeneratedAuthDisabledReason };
@@ -1,7 +1,7 @@
1
1
  import { a as QueryCtxWithPreferredOrmQueryTable, n as LookupByIdResultByCtx, t as DocByCtx } from "../query-context-BkNjkDCk.js";
2
2
  import { t as GetAuth } from "../types-ex0-J-SC.js";
3
3
  import { t as GenericCtx } from "../context-utils-Cbv4r0AA.js";
4
- import { C as GenericAuthTriggerHandlers, S as GenericAuthTriggerChange, T as defineAuth, _ as updateManyHandler, a as AuthFunctions, b as GenericAuthBeforeResult, c as consumeOneHandler, d as createHandler, f as deleteManyHandler, g as incrementOneHandler, h as findOneHandler, i as getGeneratedAuthDisabledReason, l as countHandler, m as findManyHandler, n as GeneratedAuthDisabledReasonKind, o as Triggers, p as deleteOneHandler, r as createDisabledAuthRuntime, s as createClient, t as AuthRuntime, u as createApi, v as updateOneHandler, w as GenericAuthTriggers, x as GenericAuthDefinition, y as BetterAuthOptionsWithoutDatabase } from "../generated-contract-disabled-PdNGvNYP.js";
4
+ import { C as GenericAuthTriggerHandlers, S as GenericAuthTriggerChange, T as defineAuth, _ as updateManyHandler, a as AuthFunctions, b as GenericAuthBeforeResult, c as consumeOneHandler, d as createHandler, f as deleteManyHandler, g as incrementOneHandler, h as findOneHandler, i as getGeneratedAuthDisabledReason, l as countHandler, m as findManyHandler, n as GeneratedAuthDisabledReasonKind, o as Triggers, p as deleteOneHandler, r as createDisabledAuthRuntime, s as createClient, t as AuthRuntime, u as createApi, v as updateOneHandler, w as GenericAuthTriggers, x as GenericAuthDefinition, y as BetterAuthOptionsWithoutDatabase } from "../generated-contract-disabled-DcgLIEHK.js";
5
5
  import * as convex_values0 from "convex/values";
6
6
  import { Infer } from "convex/values";
7
7
  import { AuthConfig, DocumentByName, GenericDataModel, GenericMutationCtx, GenericQueryCtx, GenericSchema, PaginationOptions, PaginationResult, SchemaDefinition, TableNamesInDataModel } from "convex/server";
@@ -932,6 +932,7 @@ const createApi = (schema, getAuth, options) => {
932
932
  model: modelValidator,
933
933
  offset: v.optional(v.number()),
934
934
  paginationOpts: paginationOptsValidator,
935
+ select: v.optional(v.array(v.string())),
935
936
  sortBy: v.optional(v.object({
936
937
  direction: v.union(v.literal("asc"), v.literal("desc")),
937
938
  field: v.string()
@@ -1072,6 +1073,10 @@ const parseWhere = (where) => {
1072
1073
  return w;
1073
1074
  });
1074
1075
  };
1076
+ const omitModelKey = (args) => {
1077
+ const { modelKey: _modelKey, ...rest } = args;
1078
+ return rest;
1079
+ };
1075
1080
  const getDocId = (doc) => {
1076
1081
  if (doc?._id !== void 0 && doc?._id !== null) return String(doc._id);
1077
1082
  if (doc?.id !== void 0 && doc?.id !== null) return String(doc.id);
@@ -1156,7 +1161,8 @@ const httpAdapter = (ctx, { authFunctions, debugLogs, schema }) => {
1156
1161
  return {
1157
1162
  id: "convex",
1158
1163
  options: { isRunMutationCtx: isRunMutationCtx(ctx) },
1159
- count: async (data) => {
1164
+ count: async (args) => {
1165
+ const data = omitModelKey(args);
1160
1166
  assertSupportedOrWhere(data.where, "count");
1161
1167
  if (hasOrWhere(data.where)) return dedupeDocsById((await asyncMap(data.where, async (w) => handlePagination(async ({ paginationOpts }) => await ctx.runQuery(authFunctions.findMany, {
1162
1168
  ...data,
@@ -1203,7 +1209,8 @@ const httpAdapter = (ctx, { authFunctions, debugLogs, schema }) => {
1203
1209
  where: parseWhere(data.where)
1204
1210
  } });
1205
1211
  },
1206
- deleteMany: async (data) => {
1212
+ deleteMany: async (args) => {
1213
+ const data = omitModelKey(args);
1207
1214
  if (!("runMutation" in ctx)) throw new Error("ctx is not a mutation ctx");
1208
1215
  assertSupportedOrWhere(data.where, "deleteMany");
1209
1216
  if (hasOrWhere(data.where)) {
@@ -1231,7 +1238,8 @@ const httpAdapter = (ctx, { authFunctions, debugLogs, schema }) => {
1231
1238
  paginationOpts
1232
1239
  }))).count;
1233
1240
  },
1234
- findMany: async (data) => {
1241
+ findMany: async (args) => {
1242
+ const data = omitModelKey(args);
1235
1243
  if (data.offset) throw new Error("offset not supported");
1236
1244
  assertSupportedOrWhere(data.where, "findMany");
1237
1245
  if (hasOrWhere(data.where)) {
@@ -1251,7 +1259,8 @@ const httpAdapter = (ctx, { authFunctions, debugLogs, schema }) => {
1251
1259
  where: parseWhere(data.where)
1252
1260
  }), { limit: data.limit })).docs;
1253
1261
  },
1254
- findOne: async (data) => {
1262
+ findOne: async (args) => {
1263
+ const data = omitModelKey(args);
1255
1264
  const parsedWhere = parseWhere(data.where);
1256
1265
  if (data.where?.every((w) => w.connector === "OR")) for (const w of data.where) {
1257
1266
  const result = await ctx.runQuery(authFunctions.findOne, {
@@ -1265,7 +1274,8 @@ const httpAdapter = (ctx, { authFunctions, debugLogs, schema }) => {
1265
1274
  where: parsedWhere
1266
1275
  });
1267
1276
  },
1268
- incrementOne: async (data) => {
1277
+ incrementOne: async (args) => {
1278
+ const data = omitModelKey(args);
1269
1279
  if (!("runMutation" in ctx)) throw new Error("ctx is not a mutation ctx");
1270
1280
  const { set, ...input } = data;
1271
1281
  return await ctx.runMutation(authFunctions.incrementOne, { input: {
@@ -1284,7 +1294,8 @@ const httpAdapter = (ctx, { authFunctions, debugLogs, schema }) => {
1284
1294
  } });
1285
1295
  throw new Error("where clause not supported");
1286
1296
  },
1287
- updateMany: async (data) => {
1297
+ updateMany: async (args) => {
1298
+ const data = omitModelKey(args);
1288
1299
  if (!("runMutation" in ctx)) throw new Error("ctx is not a mutation ctx");
1289
1300
  assertSupportedOrWhere(data.where, "updateMany");
1290
1301
  if (hasOrWhere(data.where)) {
@@ -1337,7 +1348,8 @@ const dbAdapter = (ctx, { authFunctions, debugLogs, getBetterAuthSchema, schema
1337
1348
  return {
1338
1349
  id: "convex",
1339
1350
  options: { isRunMutationCtx: isRunMutationCtx(ctx) },
1340
- count: async (data) => {
1351
+ count: async (args) => {
1352
+ const data = omitModelKey(args);
1341
1353
  assertSupportedOrWhere(data.where, "count");
1342
1354
  if (hasOrWhere(data.where)) return dedupeDocsById((await asyncMap(data.where, async (w) => handlePagination(async ({ paginationOpts }) => await findManyHandler(ctx, {
1343
1355
  ...data,
@@ -1384,7 +1396,8 @@ const dbAdapter = (ctx, { authFunctions, debugLogs, getBetterAuthSchema, schema
1384
1396
  where: parseWhere(data.where)
1385
1397
  } });
1386
1398
  },
1387
- deleteMany: async (data) => {
1399
+ deleteMany: async (args) => {
1400
+ const data = omitModelKey(args);
1388
1401
  if (!("runMutation" in ctx)) throw new Error("ctx is not a mutation ctx");
1389
1402
  assertSupportedOrWhere(data.where, "deleteMany");
1390
1403
  if (hasOrWhere(data.where)) {
@@ -1412,7 +1425,8 @@ const dbAdapter = (ctx, { authFunctions, debugLogs, getBetterAuthSchema, schema
1412
1425
  paginationOpts
1413
1426
  }))).count;
1414
1427
  },
1415
- findMany: async (data) => {
1428
+ findMany: async (args) => {
1429
+ const data = omitModelKey(args);
1416
1430
  if (data.offset) throw new Error("offset not supported");
1417
1431
  assertSupportedOrWhere(data.where, "findMany");
1418
1432
  if (hasOrWhere(data.where)) {
@@ -1432,7 +1446,8 @@ const dbAdapter = (ctx, { authFunctions, debugLogs, getBetterAuthSchema, schema
1432
1446
  where: parseWhere(data.where)
1433
1447
  }, schema, betterAuthSchema), { limit: data.limit })).docs;
1434
1448
  },
1435
- findOne: async (data) => {
1449
+ findOne: async (args) => {
1450
+ const data = omitModelKey(args);
1436
1451
  if (data.where?.every((w) => w.connector === "OR")) for (const w of data.where) {
1437
1452
  const result = await findOneHandler(ctx, {
1438
1453
  ...data,
@@ -1445,7 +1460,8 @@ const dbAdapter = (ctx, { authFunctions, debugLogs, getBetterAuthSchema, schema
1445
1460
  where: parseWhere(data.where)
1446
1461
  }, schema, betterAuthSchema);
1447
1462
  },
1448
- incrementOne: async (data) => {
1463
+ incrementOne: async (args) => {
1464
+ const data = omitModelKey(args);
1449
1465
  if (!("runMutation" in ctx)) throw new Error("ctx is not a mutation ctx");
1450
1466
  const { set, ...input } = data;
1451
1467
  return await ctx.runMutation(authFunctions.incrementOne, { input: {
@@ -1466,7 +1482,8 @@ const dbAdapter = (ctx, { authFunctions, debugLogs, getBetterAuthSchema, schema
1466
1482
  }
1467
1483
  throw new Error("where clause not supported");
1468
1484
  },
1469
- updateMany: async (data) => {
1485
+ updateMany: async (args) => {
1486
+ const data = omitModelKey(args);
1470
1487
  if (!("runMutation" in ctx)) throw new Error("ctx is not a mutation ctx");
1471
1488
  assertSupportedOrWhere(data.where, "updateMany");
1472
1489
  if (hasOrWhere(data.where)) {
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { C as Columns, D as TableName, E as RlsPolicies, O as createSystemFields, S as getRankIndexes, T as OrmSchemaExtensions, _ as loadEsbuild, a as generateMeta, b as getAggregateIndexes, c as resolveSchemaDefaultExport, f as createProjectJiti, g as loadDotenv, h as loadClackPrompts, i as resolveConfiguredBackend, l as schemaDeclaresAggregateIndexes, m as loadBabelParser, n as withLocalCodegenEnv, o as getConvexConfig, p as CRPC_BUILDER_STUB_SOURCE, r as loadCliConfig, s as collectSchemaTables, t as getLocalBackendEnvVars, u as logger, v as highlighter, w as EnableRLS, x as getIndexes, y as isColorEnabled } from "./local-env-CaFwt5Bw.mjs";
2
+ import { C as Columns, D as TableName, E as RlsPolicies, O as createSystemFields, S as getRankIndexes, T as OrmSchemaExtensions, _ as loadEsbuild, a as generateMeta, b as getAggregateIndexes, c as resolveSchemaDefaultExport, f as createProjectJiti, g as loadDotenv, h as loadClackPrompts, i as resolveConfiguredBackend, l as schemaDeclaresAggregateIndexes, m as loadBabelParser, n as withLocalCodegenEnv, o as getConvexConfig, p as CRPC_BUILDER_STUB_SOURCE, r as loadCliConfig, s as collectSchemaTables, t as getLocalBackendEnvVars, u as logger, v as highlighter, w as EnableRLS, x as getIndexes, y as isColorEnabled } from "./local-env-tM3bdL1l.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import fs, { existsSync, readFileSync } from "node:fs";
5
5
  import path, { basename, delimiter, dirname, extname, isAbsolute, join, posix, relative, resolve } from "node:path";
@@ -116,6 +116,7 @@ declare const findManyHandler: (ctx: any, args: {
116
116
  paginationOpts: any;
117
117
  limit?: number;
118
118
  offset?: number;
119
+ select?: string[];
119
120
  sortBy?: {
120
121
  direction: "asc" | "desc";
121
122
  field: string;
@@ -288,6 +289,7 @@ declare const createApi: <Schema extends SchemaDefinition<any, any>, DataModel e
288
289
  }[] | undefined;
289
290
  limit?: number | undefined;
290
291
  offset?: number | undefined;
292
+ select?: string[] | undefined;
291
293
  sortBy?: {
292
294
  field: string;
293
295
  direction: "asc" | "desc";
@@ -2,9 +2,12 @@
2
2
  import { createRequire } from "node:module";
3
3
  import fs from "node:fs";
4
4
  import path, { join } from "node:path";
5
- import { createHash } from "node:crypto";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createHash, randomUUID } from "node:crypto";
6
7
  import { v } from "convex/values";
8
+ import { tmpdir } from "node:os";
7
9
  import { createColors } from "picocolors";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
8
11
  import "convex/server";
9
12
 
10
13
  //#region src/orm/builders/column-builder.ts
@@ -636,19 +639,217 @@ const buildTsconfigPathAliases = (cwd) => {
636
639
  }
637
640
  return aliases;
638
641
  };
642
+ const DECLARATION_FILE_RE = /\.d\.[cm]?ts$/;
643
+ const PATH_SEPARATOR_RE = /[\\/]/;
644
+ const isPackageLookupDir = (dir) => {
645
+ const segments = dir.split(PATH_SEPARATOR_RE);
646
+ const index = segments.lastIndexOf("node_modules");
647
+ const depth = segments.length - 1 - index;
648
+ return index !== -1 && (depth <= 1 || depth === 2 && segments[index + 1]?.startsWith("@"));
649
+ };
650
+ const getRuntimeConditions = () => {
651
+ if (process.versions.bun) return ["bun"];
652
+ const conditions = process.execArgv.includes("--no-addons") ? [] : ["node-addons"];
653
+ if (process.features.require_module) conditions.push("module-sync");
654
+ return conditions;
655
+ };
656
+ /**
657
+ * Selects the file a bare request maps to (package `imports`, `exports`,
658
+ * self-references, workspace packages) whether or not it exists. Package
659
+ * discovery stays on disk; declaration files never match, since the runtime
660
+ * ignores `types`. TypeScript loads on first use.
661
+ */
662
+ const createMissingModuleResolver = (loadTypeScriptModule = loadTypeScript) => {
663
+ let resolve;
664
+ const init = () => {
665
+ const typescript = loadTypeScriptModule();
666
+ if (!typescript) return null;
667
+ const { sys } = typescript;
668
+ const currentDirectory = process.cwd();
669
+ const options = {
670
+ customConditions: getRuntimeConditions(),
671
+ module: typescript.ModuleKind.NodeNext,
672
+ moduleResolution: typescript.ModuleResolutionKind.NodeNext
673
+ };
674
+ const host = {
675
+ directoryExists: (dir) => !isPackageLookupDir(dir) || sys.directoryExists(dir),
676
+ fileExists: (fileName) => path.basename(fileName) === "package.json" ? sys.fileExists(fileName) : !DECLARATION_FILE_RE.test(fileName),
677
+ getCurrentDirectory: () => currentDirectory,
678
+ readFile: sys.readFile,
679
+ realpath: sys.realpath
680
+ };
681
+ const cache = typescript.createModuleResolutionCache(currentDirectory, (fileName) => sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(), options);
682
+ return (request, parentFile) => typescript.resolveModuleName(request, parentFile, options, host, cache, void 0, typescript.ModuleKind.CommonJS).resolvedModule?.resolvedFileName;
683
+ };
684
+ return (request, parentFile) => {
685
+ try {
686
+ if (resolve === void 0) {
687
+ resolve = null;
688
+ resolve = init();
689
+ }
690
+ return resolve?.(request, parentFile);
691
+ } catch {
692
+ return;
693
+ }
694
+ };
695
+ };
696
+ const missingModuleFallbacks = /* @__PURE__ */ new Set();
697
+ const MISSING_MODULE_BRIDGE_KEY = `kitcn.project-jiti.${import.meta.url}`;
698
+ const missingModuleBridge = Symbol.for(MISSING_MODULE_BRIDGE_KEY);
699
+ const projectImportGraph = new AsyncLocalStorage();
700
+ const PROJECT_SOURCE_EXTENSION_RE = /\.[cm]?[jt]sx?$/;
701
+ const JAVASCRIPT_SOURCE_EXTENSION_RE = /\.[cm]?jsx?$/;
702
+ const isProjectSource = (filename) => path.isAbsolute(filename) && !filename.split(path.sep).includes("node_modules") && PROJECT_SOURCE_EXTENSION_RE.test(filename);
703
+ const isMissingModuleError = (error) => error !== null && typeof error === "object" && "code" in error && (error.code === "MODULE_NOT_FOUND" || error.code === "ERR_MODULE_NOT_FOUND");
704
+ const resolveRequestAlias = (request, aliases) => {
705
+ const entries = Object.entries(aliases).sort(([left], [right]) => right.length - left.length);
706
+ for (const [alias, target] of entries) {
707
+ const prefix = alias.endsWith("/") ? alias.slice(0, -1) : alias;
708
+ if (request === prefix || request.startsWith(`${prefix}/`)) return `${target}${request.slice(prefix.length)}`;
709
+ }
710
+ return request.startsWith("file:") ? fileURLToPath(request) : request;
711
+ };
712
+ const loadWithMissingModuleFallback = (load, resolve, args, parentFile, aliases, operation) => {
713
+ let resolved;
714
+ let loadArgs = args;
715
+ try {
716
+ resolved = resolve(...args);
717
+ } catch (error) {
718
+ const [request, ...rest] = args;
719
+ if (typeof request !== "string" || !isMissingModuleError(error)) throw error;
720
+ const normalizedRequest = resolveRequestAlias(request, aliases);
721
+ for (const fallback of missingModuleFallbacks) {
722
+ const target = fallback(normalizedRequest, parentFile);
723
+ if (target) {
724
+ loadArgs = [target, ...rest];
725
+ resolved = resolve(...loadArgs);
726
+ break;
727
+ }
728
+ }
729
+ if (!resolved) throw error;
730
+ }
731
+ if (operation === "resolve" || !resolved) return load(...loadArgs);
732
+ const filename = resolved.startsWith("file:") ? fileURLToPath(resolved) : resolved;
733
+ const graph = projectImportGraph.getStore();
734
+ if (graph && isProjectSource(filename) && JAVASCRIPT_SOURCE_EXTENSION_RE.test(filename) && !graph.cache[filename]) return graph.jiti.evalModule(fs.readFileSync(filename, "utf8"), {
735
+ filename,
736
+ async: operation === "import",
737
+ forceTranspile: true,
738
+ cache: graph.cache
739
+ });
740
+ return load(...loadArgs);
741
+ };
742
+ const importProjectGraph = (jiti, load, resolve, args, operation) => {
743
+ if (missingModuleFallbacks.size === 0) return load(...args);
744
+ const cache = Object.create(null);
745
+ return projectImportGraph.run({
746
+ jiti,
747
+ cache
748
+ }, () => {
749
+ const resolved = resolve(...args);
750
+ const filename = resolved?.startsWith("file:") ? fileURLToPath(resolved) : resolved;
751
+ if (!filename || !isProjectSource(filename)) return load(...args);
752
+ return jiti.evalModule(fs.readFileSync(filename, "utf8"), {
753
+ filename,
754
+ async: operation === "import",
755
+ forceTranspile: true,
756
+ cache
757
+ });
758
+ });
759
+ };
760
+ /**
761
+ * Transformed imports consult fallbacks only after normal resolution fails.
762
+ * A live callback also covers computed specifiers and release; patching
763
+ * Node's global resolver loses createRequire's parent under Bun.
764
+ */
765
+ const registerMissingModuleFallback = (fallback) => {
766
+ missingModuleFallbacks.add(fallback);
767
+ Object.defineProperty(globalThis, missingModuleBridge, {
768
+ configurable: true,
769
+ value: loadWithMissingModuleFallback
770
+ });
771
+ return () => {
772
+ missingModuleFallbacks.delete(fallback);
773
+ if (missingModuleFallbacks.size === 0) Reflect.deleteProperty(globalThis, missingModuleBridge);
774
+ };
775
+ };
639
776
  const getProjectServerParserShimPath = (cwd = process.cwd()) => ensureServerParserShim(cwd);
640
- const createProjectJiti = (cwd = process.cwd()) => loadJiti().createJiti(cwd, {
641
- interopDefault: true,
642
- jsx: { runtime: "automatic" },
643
- moduleCache: false,
644
- tryNative: false,
645
- alias: {
646
- ...buildTsconfigPathAliases(cwd),
647
- ...buildLocalPackageExportAliases(cwd, "kitcn"),
648
- ...buildLocalPackageExportAliases(cwd, "convex"),
649
- "kitcn/server": getProjectServerParserShimPath(cwd)
650
- }
651
- });
777
+ const missingModuleTransform = (options, transform) => (input) => ({ code: transform({
778
+ ...input,
779
+ babel: {
780
+ ...input.babel,
781
+ plugins: [...input.babel?.plugins ?? [], () => ({ visitor: { Program: { exit(program) {
782
+ program.traverse({ CallExpression({ node, scope }) {
783
+ const callee = node.callee;
784
+ if (callee.type !== "Identifier" && callee.type !== "MemberExpression") return;
785
+ let name;
786
+ if (callee.type === "Identifier") name = callee.name;
787
+ else if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.object.name === "require" && callee.property.type === "Identifier" && callee.property.name === "resolve") name = "require";
788
+ if (!name || ![
789
+ "require",
790
+ "jitiImport",
791
+ "jitiESMResolve"
792
+ ].includes(name) || scope.getBinding(name)) return;
793
+ const args = node.arguments.filter((argument) => argument.type !== "ArgumentPlaceholder");
794
+ if (args.length !== node.arguments.length) return;
795
+ for (const globalName of ["Symbol", "globalThis"]) if (scope.getBinding(globalName)) scope.rename(globalName);
796
+ let operation = "require";
797
+ if (name === "jitiImport") operation = "import";
798
+ else if (callee.type === "MemberExpression" || name === "jitiESMResolve") operation = "resolve";
799
+ const resolver = operation === "import" || name === "jitiESMResolve" ? "jitiESMResolve" : "require.resolve";
800
+ node.callee = loadBabelParser().parseExpression(`
801
+ (function(load, args, resolve) {
802
+ const bridge = globalThis[Symbol.for(${JSON.stringify(MISSING_MODULE_BRIDGE_KEY)})];
803
+ return typeof bridge === 'function'
804
+ ? bridge(load, resolve, args, ${JSON.stringify(input.filename)}, ${JSON.stringify(options.alias ?? {})}, ${JSON.stringify(operation)})
805
+ : load(...args);
806
+ })
807
+ `);
808
+ node.arguments = [
809
+ callee,
810
+ {
811
+ type: "ArrayExpression",
812
+ elements: args
813
+ },
814
+ loadBabelParser().parseExpression(resolver)
815
+ ];
816
+ } });
817
+ } } } })]
818
+ }
819
+ }) });
820
+ const createProjectJiti = (cwd = process.cwd()) => {
821
+ const options = {
822
+ interopDefault: true,
823
+ jsx: { runtime: "automatic" },
824
+ moduleCache: false,
825
+ fsCache: false,
826
+ tryNative: false,
827
+ alias: {
828
+ ...buildTsconfigPathAliases(cwd),
829
+ ...buildLocalPackageExportAliases(cwd, "kitcn"),
830
+ ...buildLocalPackageExportAliases(cwd, "convex"),
831
+ "kitcn/server": getProjectServerParserShimPath(cwd)
832
+ }
833
+ };
834
+ const transformer = loadJiti().createJiti(cwd, options);
835
+ const transformNamespace = createHash("sha256").update(JSON.stringify([
836
+ missingModuleTransform.toString(),
837
+ MISSING_MODULE_BRIDGE_KEY,
838
+ options.alias
839
+ ])).digest("hex");
840
+ const jiti = loadJiti().createJiti(cwd, {
841
+ ...options,
842
+ fsCache: path.join(tmpdir(), "kitcn-project-jiti", transformNamespace),
843
+ transform: missingModuleTransform(options, (input) => transformer.transform(input))
844
+ });
845
+ return Object.assign((id) => importProjectGraph(jiti, jiti, (request) => jiti.resolve(request), [id], "require"), jiti, { async import(...args) {
846
+ const result = await importProjectGraph(jiti, (request, requestOptions) => jiti.import(request, {
847
+ ...requestOptions,
848
+ default: void 0
849
+ }), (...requests) => jiti.esmResolve(...requests), args, "import");
850
+ return args[1]?.default && result !== null && (typeof result === "object" || typeof result === "function") && "default" in result ? result.default ?? result : result;
851
+ } });
852
+ };
652
853
 
653
854
  //#endregion
654
855
  //#region src/orm/builders/convex-column-builder.ts
@@ -3313,17 +3514,66 @@ export function ${handlerExportName}(_ctx: unknown) {
3313
3514
  }
3314
3515
  `;
3315
3516
  }
3316
- function ensureGeneratedRuntimePlaceholders(fileCache, functionsDir, moduleNames, runtimeExportNames) {
3317
- const createdPlaceholderFiles = [];
3318
- for (const moduleName of moduleNames) {
3319
- const runtimeOutputFile = getGeneratedRuntimeOutputFile(functionsDir, moduleName);
3320
- if (fileCache.read(runtimeOutputFile) !== null) continue;
3321
- const exportNames = runtimeExportNames.get(moduleName) ?? getModuleRuntimeExportNames(moduleName);
3322
- fs.mkdirSync(path.dirname(runtimeOutputFile), { recursive: true });
3323
- fileCache.write(runtimeOutputFile, emitGeneratedRuntimePlaceholderFile(exportNames));
3324
- createdPlaceholderFiles.push(runtimeOutputFile);
3517
+ const RUNTIME_IMPORT_EXTENSION_RE = /\.[cm]?[jt]sx?$/;
3518
+ const RUNTIME_SOURCE_EXTENSIONS = [
3519
+ ".ts",
3520
+ ".tsx",
3521
+ ".mts",
3522
+ ".cts",
3523
+ ".js",
3524
+ ".mjs",
3525
+ ".cjs"
3526
+ ];
3527
+ function isCaseInsensitiveDir(dir) {
3528
+ const name = path.basename(dir);
3529
+ const flipped = [...name].map((char) => char === char.toLowerCase() ? char.toUpperCase() : char.toLowerCase()).join("");
3530
+ return flipped !== name && fs.existsSync(path.join(path.dirname(dir), flipped));
3531
+ }
3532
+ function toCanonicalPath(filePath) {
3533
+ const missingSegments = [];
3534
+ let existing = filePath;
3535
+ while (!fs.existsSync(existing)) {
3536
+ const parent = path.dirname(existing);
3537
+ if (parent === existing) return filePath;
3538
+ missingSegments.unshift(path.basename(existing));
3539
+ existing = parent;
3540
+ }
3541
+ return path.join(fs.realpathSync(existing), ...missingSegments);
3542
+ }
3543
+ function writeRuntimePlaceholder(placeholdersDir, content) {
3544
+ const placeholderFile = path.join(placeholdersDir, `${createHash("sha256").update(content).digest("hex").slice(0, 16)}.ts`);
3545
+ if (fs.existsSync(placeholderFile)) return placeholderFile;
3546
+ fs.mkdirSync(placeholdersDir, { recursive: true });
3547
+ const tempFile = `${placeholderFile}.${process.pid}-${randomUUID()}.tmp`;
3548
+ fs.writeFileSync(tempFile, content);
3549
+ try {
3550
+ fs.renameSync(tempFile, placeholderFile);
3551
+ } catch (error) {
3552
+ fs.rmSync(tempFile, { force: true });
3553
+ if (!fs.existsSync(placeholderFile)) throw error;
3325
3554
  }
3326
- return createdPlaceholderFiles;
3555
+ return placeholderFile;
3556
+ }
3557
+ /**
3558
+ * Missing runtimes resolve to content-addressed placeholders under
3559
+ * `node_modules/.kitcn`, never inside the functions dir, where a co-running
3560
+ * `convex dev` would redeploy.
3561
+ */
3562
+ function registerRuntimePlaceholders(functionsDir, moduleNames, runtimeExportNames) {
3563
+ const placeholdersDir = path.join(process.cwd(), "node_modules", ".kitcn", "runtime-placeholders");
3564
+ const canonicalFunctionsDir = fs.realpathSync(functionsDir);
3565
+ const foldCase = isCaseInsensitiveDir(canonicalFunctionsDir) ? (filePath) => filePath.toLowerCase() : (filePath) => filePath;
3566
+ const moduleNameByRuntimeFile = new Map(moduleNames.map((moduleName) => [foldCase(getGeneratedRuntimeOutputFile(canonicalFunctionsDir, moduleName).replace(TS_EXTENSION_RE, "")), moduleName]));
3567
+ const resolveBareRequest = createMissingModuleResolver();
3568
+ return registerMissingModuleFallback((request, parentFile) => {
3569
+ const parent = parentFile ?? path.join(process.cwd(), "index.ts");
3570
+ const target = request.startsWith(".") || path.isAbsolute(request) ? path.resolve(path.dirname(parent), request) : resolveBareRequest(request, parent);
3571
+ if (!target) return;
3572
+ const runtimeFile = toCanonicalPath(target).replace(RUNTIME_IMPORT_EXTENSION_RE, "");
3573
+ const moduleName = moduleNameByRuntimeFile.get(foldCase(runtimeFile));
3574
+ if (moduleName === void 0 || RUNTIME_SOURCE_EXTENSIONS.some((extension) => fs.existsSync(`${runtimeFile}${extension}`))) return;
3575
+ return writeRuntimePlaceholder(placeholdersDir, emitGeneratedRuntimePlaceholderFile(runtimeExportNames.get(moduleName) ?? getModuleRuntimeExportNames(moduleName)));
3576
+ });
3327
3577
  }
3328
3578
  function listGeneratedRuntimeFiles(functionsDir) {
3329
3579
  const generatedDir = path.join(functionsDir, "generated");
@@ -4017,7 +4267,6 @@ async function generateMeta(sharedDir, options) {
4017
4267
  const procedureEntries = [];
4018
4268
  const procedureNameLookup = {};
4019
4269
  const fatalParseFailures = [];
4020
- let createdRuntimePlaceholders = [];
4021
4270
  let supportPlaceholderState = {
4022
4271
  createdFiles: [],
4023
4272
  replacedFiles: []
@@ -4036,12 +4285,12 @@ async function generateMeta(sharedDir, options) {
4036
4285
  const getSharedJitiInstance = () => sharedJitiInstance ??= createProjectJiti();
4037
4286
  const convexModuleFiles = listFilesRecursive(functionsDir).filter((file) => file.endsWith(".ts") && isValidConvexFile(file));
4038
4287
  const schemaRuntimeModules = convexModuleFiles.map((file) => file.replace(TS_EXTENSION_RE, ""));
4039
- const schemaRuntimePlaceholders = ensureGeneratedRuntimePlaceholders(fileCache, functionsDir, schemaRuntimeModules, resolveModuleRuntimeExportNames(schemaRuntimeModules, normalizedTrimSegments));
4288
+ const releaseSchemaRuntimePlaceholders = registerRuntimePlaceholders(functionsDir, schemaRuntimeModules, resolveModuleRuntimeExportNames(schemaRuntimeModules, normalizedTrimSegments));
4040
4289
  const schemaMetadata = await (async () => {
4041
4290
  try {
4042
4291
  return await withCodegenParseSentinel(() => resolveSchemaMetadataForCodegen(functionsDir, debug, getSharedJitiInstance));
4043
4292
  } finally {
4044
- for (const schemaRuntimePlaceholder of schemaRuntimePlaceholders) fileCache.remove(schemaRuntimePlaceholder);
4293
+ releaseSchemaRuntimePlaceholders();
4045
4294
  }
4046
4295
  })();
4047
4296
  const hasOrmSchemaMetadata = schemaMetadata.hasOrmSchema;
@@ -4063,6 +4312,7 @@ async function generateMeta(sharedDir, options) {
4063
4312
  if (convexGeneratedServerFile) emitServerFile();
4064
4313
  if (generateApi) {
4065
4314
  globalThis.__KITCN_CODEGEN__ = true;
4315
+ let releaseRuntimePlaceholders = () => {};
4066
4316
  try {
4067
4317
  const jitiInstance = getSharedJitiInstance();
4068
4318
  const serverShimSpecifier = normalizeImportPath(getProjectServerParserShimPath());
@@ -4074,7 +4324,7 @@ async function generateMeta(sharedDir, options) {
4074
4324
  ...hasOrmSchema ? ["generated/aggregate"] : [],
4075
4325
  ...generateAuth ? [generatedAuthModuleName] : []
4076
4326
  ])];
4077
- createdRuntimePlaceholders = ensureGeneratedRuntimePlaceholders(fileCache, functionsDir, runtimePlaceholderModules, resolveModuleRuntimeExportNames(runtimePlaceholderModules, normalizedTrimSegments));
4327
+ releaseRuntimePlaceholders = registerRuntimePlaceholders(functionsDir, runtimePlaceholderModules, resolveModuleRuntimeExportNames(runtimePlaceholderModules, normalizedTrimSegments));
4078
4328
  for (const file of parseCandidateFiles) {
4079
4329
  const filePath = path.join(functionsDir, file);
4080
4330
  const moduleName = file.replace(TS_EXTENSION_RE, "");
@@ -4116,11 +4366,11 @@ async function generateMeta(sharedDir, options) {
4116
4366
  }
4117
4367
  }
4118
4368
  } finally {
4369
+ releaseRuntimePlaceholders();
4119
4370
  delete globalThis.__KITCN_CODEGEN__;
4120
4371
  }
4121
4372
  }
4122
4373
  if (fatalParseFailures.length > 0) {
4123
- for (const createdRuntimePlaceholder of createdRuntimePlaceholders) fileCache.remove(createdRuntimePlaceholder);
4124
4374
  for (const createdSupportPlaceholder of supportPlaceholderState.createdFiles) fileCache.remove(createdSupportPlaceholder);
4125
4375
  for (const replacedSupportFile of supportPlaceholderState.replacedFiles) fileCache.write(replacedSupportFile.filePath, replacedSupportFile.content);
4126
4376
  const failureSummary = fatalParseFailures.map(({ file, error }) => `- ${file}: ${error instanceof Error ? error.message : String(error)}`).join("\n");
@@ -4233,10 +4483,6 @@ ${optionalTypeExports}
4233
4483
  if (runtimeOutputFileSet.has(existingRuntimeFile) || runtimeFilesPreservedFromParseFailures.has(existingRuntimeFile)) continue;
4234
4484
  fileCache.remove(existingRuntimeFile);
4235
4485
  }
4236
- for (const createdRuntimePlaceholder of createdRuntimePlaceholders) {
4237
- if (runtimeOutputFileSet.has(createdRuntimePlaceholder) || runtimeFilesPreservedFromParseFailures.has(createdRuntimePlaceholder)) continue;
4238
- fileCache.remove(createdRuntimePlaceholder);
4239
- }
4240
4486
  const elapsed = ((Date.now() - startTime) / 1e3).toFixed(2);
4241
4487
  const time = (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
4242
4488
  hour12: false,
package/dist/watcher.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as generateMeta, d as PARSE_SNAPSHOT_SUFFIX, i as resolveConfiguredBackend, n as withLocalCodegenEnv, o as getConvexConfig, r as loadCliConfig, u as logger } from "./local-env-CaFwt5Bw.mjs";
2
+ import { a as generateMeta, d as PARSE_SNAPSHOT_SUFFIX, i as resolveConfiguredBackend, n as withLocalCodegenEnv, o as getConvexConfig, r as loadCliConfig, u as logger } from "./local-env-tM3bdL1l.mjs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kitcn",
3
- "version": "0.33.10",
3
+ "version": "0.33.11",
4
4
  "description": "kitcn - React Query integration and CLI tools for Convex",
5
5
  "keywords": [
6
6
  "convex",