@concavejs/docstore-better-sqlite3 0.0.1-alpha.10 → 0.0.1-alpha.12

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 (2) hide show
  1. package/dist/index.js +1072 -491
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- import { createRequire } from "node:module";
2
1
  var __defProp = Object.defineProperty;
3
2
  var __returnValue = (v) => v;
4
3
  function __exportSetter(name, newValue) {
@@ -14,7 +13,6 @@ var __export = (target, all) => {
14
13
  });
15
14
  };
16
15
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
18
16
 
19
17
  // ../../node_modules/convex/dist/esm/values/base64.js
20
18
  function getLens(b64) {
@@ -802,6 +800,237 @@ var init_values = __esm(() => {
802
800
  init_errors();
803
801
  });
804
802
 
803
+ // ../core/dist/id-codec/base32.js
804
+ function base32Encode(data) {
805
+ if (data.length === 0)
806
+ return "";
807
+ let result = "";
808
+ let buffer = 0;
809
+ let bitsLeft = 0;
810
+ for (const byte of data) {
811
+ buffer = buffer << 8 | byte;
812
+ bitsLeft += 8;
813
+ while (bitsLeft >= 5) {
814
+ bitsLeft -= 5;
815
+ const index = buffer >> bitsLeft & 31;
816
+ result += ALPHABET[index];
817
+ }
818
+ }
819
+ if (bitsLeft > 0) {
820
+ const index = buffer << 5 - bitsLeft & 31;
821
+ result += ALPHABET[index];
822
+ }
823
+ return result;
824
+ }
825
+ function base32Decode(str) {
826
+ if (str.length === 0)
827
+ return new Uint8Array(0);
828
+ const outputLength = Math.floor(str.length * 5 / 8);
829
+ const result = new Uint8Array(outputLength);
830
+ let buffer = 0;
831
+ let bitsLeft = 0;
832
+ let outputIndex = 0;
833
+ for (const char of str) {
834
+ const value = ALPHABET_MAP.get(char);
835
+ if (value === undefined) {
836
+ throw new Error(`Invalid base32 character: ${char}`);
837
+ }
838
+ buffer = buffer << 5 | value;
839
+ bitsLeft += 5;
840
+ if (bitsLeft >= 8) {
841
+ bitsLeft -= 8;
842
+ result[outputIndex++] = buffer >> bitsLeft & 255;
843
+ }
844
+ }
845
+ return result;
846
+ }
847
+ function isValidBase32(str) {
848
+ for (const char of str) {
849
+ if (!ALPHABET_MAP.has(char)) {
850
+ return false;
851
+ }
852
+ }
853
+ return true;
854
+ }
855
+ var ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz", ALPHABET_MAP;
856
+ var init_base32 = __esm(() => {
857
+ ALPHABET_MAP = new Map;
858
+ for (let i2 = 0;i2 < ALPHABET.length; i2++) {
859
+ ALPHABET_MAP.set(ALPHABET[i2], i2);
860
+ ALPHABET_MAP.set(ALPHABET[i2].toUpperCase(), i2);
861
+ }
862
+ ALPHABET_MAP.set("i", 1);
863
+ ALPHABET_MAP.set("I", 1);
864
+ ALPHABET_MAP.set("l", 1);
865
+ ALPHABET_MAP.set("L", 1);
866
+ ALPHABET_MAP.set("o", 0);
867
+ ALPHABET_MAP.set("O", 0);
868
+ });
869
+
870
+ // ../core/dist/id-codec/vint.js
871
+ function vintEncode(value) {
872
+ if (value < 0) {
873
+ throw new Error("VInt cannot encode negative numbers");
874
+ }
875
+ if (value > 4294967295) {
876
+ throw new Error("VInt cannot encode values larger than 2^32-1");
877
+ }
878
+ value = value >>> 0;
879
+ if (value < 128) {
880
+ return new Uint8Array([value]);
881
+ }
882
+ if (value < 16512) {
883
+ const adjusted2 = value - 128;
884
+ return new Uint8Array([128 | adjusted2 >> 8 & 63, adjusted2 & 255]);
885
+ }
886
+ if (value < 2113664) {
887
+ const adjusted2 = value - 16512;
888
+ return new Uint8Array([192 | adjusted2 >> 16 & 31, adjusted2 >> 8 & 255, adjusted2 & 255]);
889
+ }
890
+ if (value < 270549120) {
891
+ const adjusted2 = value - 2113664;
892
+ return new Uint8Array([
893
+ 224 | adjusted2 >> 24 & 15,
894
+ adjusted2 >> 16 & 255,
895
+ adjusted2 >> 8 & 255,
896
+ adjusted2 & 255
897
+ ]);
898
+ }
899
+ const adjusted = value - 270549120;
900
+ return new Uint8Array([
901
+ 240 | adjusted >> 32 & 7,
902
+ adjusted >> 24 & 255,
903
+ adjusted >> 16 & 255,
904
+ adjusted >> 8 & 255,
905
+ adjusted & 255
906
+ ]);
907
+ }
908
+ function vintDecode(data, offset = 0) {
909
+ if (offset >= data.length) {
910
+ throw new Error("VInt decode: unexpected end of data");
911
+ }
912
+ const first = data[offset];
913
+ if ((first & 128) === 0) {
914
+ return { value: first, bytesRead: 1 };
915
+ }
916
+ if ((first & 192) === 128) {
917
+ if (offset + 1 >= data.length) {
918
+ throw new Error("VInt decode: truncated 2-byte encoding");
919
+ }
920
+ const value = 128 + ((first & 63) << 8 | data[offset + 1]);
921
+ return { value, bytesRead: 2 };
922
+ }
923
+ if ((first & 224) === 192) {
924
+ if (offset + 2 >= data.length) {
925
+ throw new Error("VInt decode: truncated 3-byte encoding");
926
+ }
927
+ const value = 16512 + ((first & 31) << 16 | data[offset + 1] << 8 | data[offset + 2]);
928
+ return { value, bytesRead: 3 };
929
+ }
930
+ if ((first & 240) === 224) {
931
+ if (offset + 3 >= data.length) {
932
+ throw new Error("VInt decode: truncated 4-byte encoding");
933
+ }
934
+ const value = 2113664 + ((first & 15) << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]);
935
+ return { value: value >>> 0, bytesRead: 4 };
936
+ }
937
+ if ((first & 248) === 240) {
938
+ if (offset + 4 >= data.length) {
939
+ throw new Error("VInt decode: truncated 5-byte encoding");
940
+ }
941
+ const high = first & 7;
942
+ const low = (data[offset + 1] << 24 | data[offset + 2] << 16 | data[offset + 3] << 8 | data[offset + 4]) >>> 0;
943
+ const value = 270549120 + high * 4294967296 + low;
944
+ return { value: value >>> 0, bytesRead: 5 };
945
+ }
946
+ throw new Error("VInt decode: invalid prefix");
947
+ }
948
+
949
+ // ../core/dist/id-codec/fletcher16.js
950
+ function fletcher16(data) {
951
+ let sum1 = 0;
952
+ let sum2 = 0;
953
+ for (const byte of data) {
954
+ sum1 = (sum1 + byte) % 255;
955
+ sum2 = (sum2 + sum1) % 255;
956
+ }
957
+ return new Uint8Array([sum1, sum2]);
958
+ }
959
+ function verifyFletcher16(data, checksum) {
960
+ if (checksum.length !== 2)
961
+ return false;
962
+ const computed = fletcher16(data);
963
+ return computed[0] === checksum[0] && computed[1] === checksum[1];
964
+ }
965
+
966
+ // ../core/dist/utils/crypto.js
967
+ var weakRandomState;
968
+ var init_crypto = __esm(() => {
969
+ weakRandomState = (Date.now() ^ 2654435769) >>> 0;
970
+ });
971
+
972
+ // ../core/dist/id-codec/document-id.js
973
+ function encodeDocumentId(tableNumber, internalId) {
974
+ if (internalId.length !== INTERNAL_ID_LENGTH) {
975
+ throw new Error(`Internal ID must be exactly ${INTERNAL_ID_LENGTH} bytes, got ${internalId.length}`);
976
+ }
977
+ if (tableNumber < 1 || tableNumber > 4294967295) {
978
+ throw new Error(`Table number must be between 1 and 2^32-1, got ${tableNumber}`);
979
+ }
980
+ const tableBytes = vintEncode(tableNumber);
981
+ const payload = new Uint8Array(tableBytes.length + INTERNAL_ID_LENGTH);
982
+ payload.set(tableBytes, 0);
983
+ payload.set(internalId, tableBytes.length);
984
+ const checksum = fletcher16(payload);
985
+ const final = new Uint8Array(payload.length + 2);
986
+ final.set(payload, 0);
987
+ final.set(checksum, payload.length);
988
+ return base32Encode(final);
989
+ }
990
+ function decodeDocumentId(encoded) {
991
+ if (encoded.length < MIN_ENCODED_LENGTH || encoded.length > MAX_ENCODED_LENGTH) {
992
+ throw new Error(`Invalid document ID length: ${encoded.length} (expected ${MIN_ENCODED_LENGTH}-${MAX_ENCODED_LENGTH})`);
993
+ }
994
+ if (!isValidBase32(encoded)) {
995
+ throw new Error("Invalid document ID: contains invalid base32 characters");
996
+ }
997
+ const bytes = base32Decode(encoded);
998
+ if (bytes.length < 19) {
999
+ throw new Error(`Invalid document ID: decoded to ${bytes.length} bytes (minimum 19)`);
1000
+ }
1001
+ const checksum = bytes.slice(bytes.length - 2);
1002
+ const payload = bytes.slice(0, bytes.length - 2);
1003
+ if (!verifyFletcher16(payload, checksum)) {
1004
+ throw new Error("Invalid document ID: checksum verification failed");
1005
+ }
1006
+ const { value: tableNumber, bytesRead } = vintDecode(payload, 0);
1007
+ const internalId = payload.slice(bytesRead, bytesRead + INTERNAL_ID_LENGTH);
1008
+ if (internalId.length !== INTERNAL_ID_LENGTH) {
1009
+ throw new Error(`Invalid document ID: internal ID is ${internalId.length} bytes (expected ${INTERNAL_ID_LENGTH})`);
1010
+ }
1011
+ return { tableNumber, internalId };
1012
+ }
1013
+ function isValidDocumentId(encoded) {
1014
+ try {
1015
+ decodeDocumentId(encoded);
1016
+ return true;
1017
+ } catch {
1018
+ return false;
1019
+ }
1020
+ }
1021
+ function internalIdToHex(internalId) {
1022
+ let hex = "";
1023
+ for (let i2 = 0;i2 < internalId.length; i2++) {
1024
+ hex += internalId[i2].toString(16).padStart(2, "0");
1025
+ }
1026
+ return hex;
1027
+ }
1028
+ var INTERNAL_ID_LENGTH = 16, MIN_ENCODED_LENGTH = 31, MAX_ENCODED_LENGTH = 37;
1029
+ var init_document_id = __esm(() => {
1030
+ init_base32();
1031
+ init_crypto();
1032
+ });
1033
+
805
1034
  // ../core/dist/utils/utils.js
806
1035
  function hexToArrayBuffer(hex) {
807
1036
  if (hex === "") {
@@ -840,9 +1069,15 @@ function deserializeDeveloperId(developerId) {
840
1069
  return null;
841
1070
  }
842
1071
  var DOC_ID_SEPARATOR = ":", LEGACY_DOC_ID_SEPARATOR = ";";
1072
+ var init_utils = __esm(() => {
1073
+ init_document_id();
1074
+ });
843
1075
 
844
1076
  // ../core/dist/tables/interface.js
845
1077
  function getFullTableName(tableName, componentPath) {
1078
+ if (isSystemTable(tableName)) {
1079
+ return tableName;
1080
+ }
846
1081
  if (!componentPath || componentPath === "") {
847
1082
  return tableName;
848
1083
  }
@@ -859,23 +1094,28 @@ function parseFullTableName(fullName) {
859
1094
  };
860
1095
  }
861
1096
  function isSystemTable(tableName) {
862
- return tableName.startsWith("_");
1097
+ return Object.hasOwn(SYSTEM_TABLE_NUMBERS, tableName);
863
1098
  }
864
- var SYSTEM_TABLE_NUMBERS, FIRST_USER_TABLE_NUMBER = 100;
1099
+ var SYSTEM_TABLE_NUMBERS, FIRST_USER_TABLE_NUMBER = 10001;
865
1100
  var init_interface = __esm(() => {
866
1101
  SYSTEM_TABLE_NUMBERS = {
867
1102
  _tables: 1,
868
1103
  _scheduled_functions: 2,
869
1104
  _storage: 3,
870
- _crons: 4
1105
+ _crons: 4,
1106
+ _indexes: 5,
1107
+ _schemas: 6,
1108
+ _components: 7,
1109
+ _component_definitions: 8,
1110
+ _schema_validation_progress: 9
871
1111
  };
872
1112
  });
873
1113
 
874
1114
  // ../core/dist/kernel/context-storage.js
875
- function resolveFromRequire(req) {
1115
+ function resolveFromModuleResolver(resolveModule) {
876
1116
  for (const specifier of ["node:async_hooks", "async_hooks"]) {
877
1117
  try {
878
- const mod = req(specifier);
1118
+ const mod = resolveModule(specifier);
879
1119
  if (mod?.AsyncLocalStorage) {
880
1120
  return mod.AsyncLocalStorage;
881
1121
  }
@@ -918,16 +1158,16 @@ var resolveAsyncLocalStorage = () => {
918
1158
  if (globalCtor) {
919
1159
  return globalCtor;
920
1160
  }
921
- const runtimeRequire = __require;
922
- if (runtimeRequire) {
923
- const ctor = resolveFromRequire(runtimeRequire);
1161
+ const getBuiltinModule = globalThis?.process?.getBuiltinModule;
1162
+ if (typeof getBuiltinModule === "function") {
1163
+ const ctor = resolveFromModuleResolver((specifier) => getBuiltinModule(specifier));
924
1164
  if (ctor) {
925
1165
  return ctor;
926
1166
  }
927
1167
  }
928
1168
  const globalRequire = globalThis?.require;
929
1169
  if (typeof globalRequire === "function") {
930
- return resolveFromRequire(globalRequire);
1170
+ return resolveFromModuleResolver(globalRequire);
931
1171
  }
932
1172
  return;
933
1173
  }, AsyncLocalStorageCtor;
@@ -2212,7 +2452,7 @@ async function listSystemFunctions(options = {}) {
2212
2452
  }
2213
2453
  for (const route of httpRoutes) {
2214
2454
  const method = route.route.method;
2215
- const routePath = route.route.path;
2455
+ const routePath = mountHttpRoutePath(route.route.path, owningComponent);
2216
2456
  results.push({
2217
2457
  name: `${method} ${routePath}`,
2218
2458
  module: listing.path,
@@ -2274,6 +2514,16 @@ async function loadAndAnalyzeModule(listing, componentPath) {
2274
2514
  function makeCacheKey(componentPath, modulePath) {
2275
2515
  return `${componentPath ?? ""}::${modulePath}`;
2276
2516
  }
2517
+ function mountHttpRoutePath(routePath, componentPath) {
2518
+ if (!componentPath) {
2519
+ return routePath;
2520
+ }
2521
+ const prefix = `/${componentPath}`;
2522
+ if (routePath === "/") {
2523
+ return prefix;
2524
+ }
2525
+ return `${prefix}${routePath}`;
2526
+ }
2277
2527
  function buildFallbackSourcePath(modulePath) {
2278
2528
  const trimmed = modulePath.replace(/\\/g, "/").replace(/^\//, "");
2279
2529
  const withConvex = trimmed.startsWith("convex/") ? trimmed : `convex/${trimmed}`;
@@ -3960,6 +4210,7 @@ var init_remote = __esm(() => {
3960
4210
  // ../../node_modules/jose/dist/webapi/index.js
3961
4211
  var init_webapi = __esm(() => {
3962
4212
  init_verify4();
4213
+ init_local();
3963
4214
  init_remote();
3964
4215
  init_errors2();
3965
4216
  });
@@ -4164,7 +4415,7 @@ function getRemoteJwks(jwksUrl, config) {
4164
4415
  if (cached) {
4165
4416
  JWKS_CACHE.delete(jwksUrl);
4166
4417
  }
4167
- const jwks = createRemoteJWKSet(new URL(jwksUrl));
4418
+ const jwks = jwksUrl.startsWith("data:") ? createLocalJWKSet(parseDataUriJson(jwksUrl)) : createRemoteJWKSet(new URL(jwksUrl));
4168
4419
  const configuredTtl = config?.jwksCacheTtlMs;
4169
4420
  const ttlMs = resolveJwksCacheTtlMs(configuredTtl);
4170
4421
  JWKS_CACHE.set(jwksUrl, {
@@ -4173,6 +4424,24 @@ function getRemoteJwks(jwksUrl, config) {
4173
4424
  });
4174
4425
  return jwks;
4175
4426
  }
4427
+ function parseDataUriJson(dataUri) {
4428
+ const match = /^data:([^;,]+)?(?:;charset=[^;,]+)?(;base64)?,(.*)$/i.exec(dataUri);
4429
+ if (!match) {
4430
+ throw new JWTValidationError("INVALID_TOKEN", "Invalid JWKS data URI");
4431
+ }
4432
+ const [, , isBase64, payload] = match;
4433
+ const jsonText = isBase64 ? decodeBase642(payload) : decodeURIComponent(payload);
4434
+ return JSON.parse(jsonText);
4435
+ }
4436
+ function decodeBase642(value) {
4437
+ if (typeof Buffer !== "undefined") {
4438
+ return Buffer.from(value, "base64").toString("utf8");
4439
+ }
4440
+ if (typeof atob === "function") {
4441
+ return new TextDecoder().decode(Uint8Array.from(atob(value), (char) => char.charCodeAt(0)));
4442
+ }
4443
+ throw new JWTValidationError("INVALID_TOKEN", "Base64 decoding is unavailable");
4444
+ }
4176
4445
  function resolveJwksCacheTtlMs(configuredTtl) {
4177
4446
  if (configuredTtl === undefined) {
4178
4447
  return DEFAULT_JWKS_CACHE_TTL_MS;
@@ -4207,6 +4476,7 @@ async function verifyJwt(token, config) {
4207
4476
  const options = {
4208
4477
  issuer: effectiveConfig.issuer,
4209
4478
  audience: effectiveConfig.audience,
4479
+ algorithms: effectiveConfig.algorithms,
4210
4480
  clockTolerance: effectiveConfig.clockTolerance ?? DEFAULT_CLOCK_TOLERANCE_SECONDS
4211
4481
  };
4212
4482
  let payload;
@@ -4276,11 +4546,20 @@ var init_jwt = __esm(() => {
4276
4546
  function getPrincipal() {
4277
4547
  return principalContext.getStore();
4278
4548
  }
4279
- var authContext, principalContext;
4549
+ var AUTH_CONTEXT_SYMBOL, PRINCIPAL_CONTEXT_SYMBOL, globalAuthContext, authContext, principalContext;
4280
4550
  var init_auth_context = __esm(() => {
4281
4551
  init_context_storage();
4282
- authContext = new ContextStorage;
4283
- principalContext = new ContextStorage;
4552
+ AUTH_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/auth-context");
4553
+ PRINCIPAL_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/principal-context");
4554
+ globalAuthContext = globalThis;
4555
+ authContext = globalAuthContext[AUTH_CONTEXT_SYMBOL] ?? new ContextStorage;
4556
+ principalContext = globalAuthContext[PRINCIPAL_CONTEXT_SYMBOL] ?? new ContextStorage;
4557
+ if (!globalAuthContext[AUTH_CONTEXT_SYMBOL]) {
4558
+ globalAuthContext[AUTH_CONTEXT_SYMBOL] = authContext;
4559
+ }
4560
+ if (!globalAuthContext[PRINCIPAL_CONTEXT_SYMBOL]) {
4561
+ globalAuthContext[PRINCIPAL_CONTEXT_SYMBOL] = principalContext;
4562
+ }
4284
4563
  });
4285
4564
 
4286
4565
  // ../core/dist/auth/principal.js
@@ -4755,47 +5034,231 @@ var init_auth = __esm(() => {
4755
5034
  init_auth_config_service();
4756
5035
  });
4757
5036
 
4758
- // ../core/dist/system/internal.js
4759
- function requireSystemCapability(capability) {
4760
- const principal2 = getPrincipal();
4761
- if (!principal2) {
4762
- throw new Error("System functions require authentication context");
4763
- }
4764
- requireAuthorization(principal2, { kind: "management_operation", capability });
4765
- }
4766
- function createSystemFunctions(deps) {
4767
- const { query, mutation } = deps;
5037
+ // ../core/dist/components/manifest.js
5038
+ var COMPONENT_MANIFEST_SYMBOL;
5039
+ var init_manifest = __esm(() => {
5040
+ COMPONENT_MANIFEST_SYMBOL = Symbol.for("concave.componentManifest");
5041
+ });
5042
+
5043
+ // ../core/dist/id-codec/index.js
5044
+ var init_id_codec = __esm(() => {
5045
+ init_base32();
5046
+ init_document_id();
5047
+ });
5048
+
5049
+ // ../core/dist/system/system-tables.js
5050
+ function getSystemTableDefinition(name) {
5051
+ return SYSTEM_TABLE_DEFINITIONS.find((definition) => definition.name === name) ?? null;
5052
+ }
5053
+ function isPublicSystemTable(name) {
5054
+ return getSystemTableDefinition(name)?.visibility === "public";
5055
+ }
5056
+ function createTableInfo(name, tableNumber, componentPath = "", options = {}) {
5057
+ const fullName = getFullTableName(name, componentPath);
5058
+ return {
5059
+ tableNumber,
5060
+ name,
5061
+ componentPath: isSystemTableName(name) ? "" : componentPath,
5062
+ fullName,
5063
+ isSystem: options.isSystem ?? isSystemTableName(name),
5064
+ visibility: options.visibility ?? (isPublicSystemTable(name) ? "public" : "private"),
5065
+ state: "active",
5066
+ createdAt: options.createdAt ?? Date.now()
5067
+ };
5068
+ }
5069
+ function getReservedSystemTables() {
5070
+ return SYSTEM_TABLE_DEFINITIONS.map((definition) => createTableInfo(definition.name, SYSTEM_TABLE_NUMBERS[definition.name], "", {
5071
+ isSystem: true,
5072
+ visibility: definition.visibility
5073
+ }));
5074
+ }
5075
+ function tableInfoFromStoredDocument(value) {
5076
+ if (!value) {
5077
+ return null;
5078
+ }
5079
+ const name = typeof value.name === "string" ? value.name : null;
5080
+ const tableNumber = typeof value.tableNumber === "number" ? value.tableNumber : null;
5081
+ if (!name || !tableNumber) {
5082
+ return null;
5083
+ }
5084
+ const componentPath = typeof value.componentPath === "string" ? value.componentPath : "";
5085
+ const fullName = typeof value.fullName === "string" ? value.fullName : getFullTableName(name, componentPath);
5086
+ return {
5087
+ tableNumber,
5088
+ name,
5089
+ componentPath,
5090
+ fullName,
5091
+ isSystem: value.isSystem === true,
5092
+ visibility: value.visibility === "private" ? "private" : "public",
5093
+ state: "active",
5094
+ createdAt: typeof value.createdAt === "number" ? value.createdAt : Date.now()
5095
+ };
5096
+ }
5097
+ function nextUserTableNumber(tables) {
5098
+ let next = FIRST_USER_TABLE_NUMBER;
5099
+ for (const table of tables) {
5100
+ if (table.tableNumber >= next) {
5101
+ next = table.tableNumber + 1;
5102
+ }
5103
+ }
5104
+ return next;
5105
+ }
5106
+ function createSystemMetadata(partial) {
5107
+ const now = partial?.updatedAt ?? Date.now();
5108
+ return {
5109
+ version: 1,
5110
+ bootstrapped: true,
5111
+ tableIdStrategy: "registry_u32",
5112
+ developerIdCodec: "convex_base32",
5113
+ nextUserTableNumber: partial?.nextUserTableNumber ?? FIRST_USER_TABLE_NUMBER,
5114
+ registryVersion: partial?.registryVersion ?? now,
5115
+ runtimeMetadataVersion: partial?.runtimeMetadataVersion,
5116
+ bootstrappedAt: partial?.bootstrappedAt ?? now,
5117
+ updatedAt: now
5118
+ };
5119
+ }
5120
+ async function readSystemMetadata(docstore) {
5121
+ const metadata = await docstore.getGlobal(SYSTEM_METADATA_GLOBAL_KEY);
5122
+ if (!metadata || metadata.bootstrapped !== true || metadata.version !== 1) {
5123
+ return null;
5124
+ }
5125
+ return createSystemMetadata({
5126
+ nextUserTableNumber: metadata.nextUserTableNumber,
5127
+ registryVersion: metadata.registryVersion ?? metadata.updatedAt,
5128
+ runtimeMetadataVersion: metadata.runtimeMetadataVersion,
5129
+ bootstrappedAt: metadata.bootstrappedAt,
5130
+ updatedAt: metadata.updatedAt
5131
+ });
5132
+ }
5133
+ function createTableNumberReservationKey(tableNumber) {
5134
+ return `${TABLE_NUMBER_RESERVATION_GLOBAL_PREFIX}${tableNumber}`;
5135
+ }
5136
+ async function ensureSystemTablesBootstrapped(docstore) {
5137
+ const existingMetadata = await readSystemMetadata(docstore);
5138
+ if (existingMetadata?.version === 1 && existingMetadata.bootstrapped) {
5139
+ return;
5140
+ }
5141
+ const now = Date.now();
5142
+ const tableInfos = getReservedSystemTables();
5143
+ const existingEntries = await docstore.scan(stringToHex("_tables"));
5144
+ const existingByName = new Map;
5145
+ for (const entry of existingEntries) {
5146
+ const info = tableInfoFromStoredDocument(entry.value.value);
5147
+ if (info) {
5148
+ existingByName.set(info.fullName, info);
5149
+ }
5150
+ }
5151
+ const docs = [];
5152
+ const oracle = docstore.timestampOracle;
5153
+ const allocateTimestamp = oracle?.allocateTimestamp?.bind(oracle) ?? (() => BigInt(Date.now()));
5154
+ for (const table of tableInfos) {
5155
+ const existing = existingByName.get(table.fullName);
5156
+ const createdAt = existing?.createdAt ?? now;
5157
+ docs.push(createTableMetadataEntry(table, allocateTimestamp(), createdAt));
5158
+ }
5159
+ if (docs.length > 0) {
5160
+ await docstore.write(docs, new Set, "Overwrite");
5161
+ }
5162
+ const metadata = createSystemMetadata({
5163
+ nextUserTableNumber: nextUserTableNumber([...tableInfos, ...existingByName.values()]),
5164
+ registryVersion: now,
5165
+ bootstrappedAt: existingMetadata?.bootstrappedAt ?? now,
5166
+ updatedAt: now
5167
+ });
5168
+ await docstore.writeGlobal(SYSTEM_METADATA_GLOBAL_KEY, metadata);
5169
+ }
5170
+ function createTableMetadataEntryForUserTable(table, timestamp2) {
5171
+ return createTableMetadataEntry(table, timestamp2, table.createdAt);
5172
+ }
5173
+ function createTableMetadataEntry(table, timestamp2, createdAt) {
5174
+ const docId = createTableMetadataDocumentId(table.fullName);
5175
+ const developerId = encodeDocumentId(SYSTEM_TABLE_NUMBERS._tables, stableMetadataInternalIdBytes(table.fullName));
5176
+ const storedTable = {
5177
+ _id: developerId,
5178
+ _creationTime: Number(timestamp2),
5179
+ name: table.name,
5180
+ componentPath: table.componentPath,
5181
+ fullName: table.fullName,
5182
+ tableNumber: table.tableNumber,
5183
+ isSystem: table.isSystem,
5184
+ visibility: table.visibility,
5185
+ state: table.state,
5186
+ createdAt
5187
+ };
5188
+ return {
5189
+ ts: timestamp2,
5190
+ id: docId,
5191
+ value: {
5192
+ id: docId,
5193
+ value: storedTable
5194
+ },
5195
+ prev_ts: null
5196
+ };
5197
+ }
5198
+ function createTableMetadataDocumentId(fullTableName) {
5199
+ const internalIdBytes = stableMetadataInternalIdBytes(fullTableName);
5200
+ return {
5201
+ table: stringToHex("_tables"),
5202
+ internalId: internalIdToHex(internalIdBytes),
5203
+ tableNumber: SYSTEM_TABLE_NUMBERS._tables
5204
+ };
5205
+ }
5206
+ function stableMetadataInternalIdBytes(fullTableName) {
5207
+ const bytes = new Uint8Array(16);
5208
+ const input = new TextEncoder().encode(`table:${fullTableName}`);
5209
+ for (let i2 = 0;i2 < input.length; i2 += 1) {
5210
+ const target = i2 % 16;
5211
+ bytes[target] = bytes[target] * 33 + input[i2] & 255;
5212
+ }
5213
+ return bytes;
5214
+ }
5215
+ function isSystemTableName(name) {
5216
+ return Object.hasOwn(SYSTEM_TABLE_NUMBERS, name);
5217
+ }
5218
+ var SYSTEM_METADATA_GLOBAL_KEY = "concave:system_metadata:v1", TABLE_NUMBER_RESERVATION_GLOBAL_PREFIX = "concave:table_number:", SYSTEM_TABLE_DEFINITIONS;
5219
+ var init_system_tables = __esm(() => {
5220
+ init_manifest();
5221
+ init_id_codec();
5222
+ init_interface();
5223
+ init_utils();
5224
+ init_module_loader();
5225
+ SYSTEM_TABLE_DEFINITIONS = [
5226
+ { name: "_tables", visibility: "public" },
5227
+ { name: "_scheduled_functions", visibility: "public" },
5228
+ { name: "_storage", visibility: "public" },
5229
+ { name: "_crons", visibility: "public" },
5230
+ { name: "_indexes", visibility: "private" },
5231
+ { name: "_schemas", visibility: "private" },
5232
+ { name: "_components", visibility: "private" },
5233
+ { name: "_component_definitions", visibility: "private" },
5234
+ { name: "_schema_validation_progress", visibility: "private" }
5235
+ ];
5236
+ });
5237
+
5238
+ // ../core/dist/system/internal.js
5239
+ function requireSystemCapability(capability) {
5240
+ const principal2 = getPrincipal();
5241
+ if (!principal2) {
5242
+ throw new Error("System functions require authentication context");
5243
+ }
5244
+ requireAuthorization(principal2, { kind: "management_operation", capability });
5245
+ }
5246
+ function createSystemFunctions(deps) {
5247
+ const { query, mutation } = deps;
4768
5248
  return {
4769
5249
  systemListComponents: query({
4770
5250
  args: {},
4771
- handler: async (_ctx) => {
5251
+ handler: async (ctx) => {
4772
5252
  requireSystemCapability("components:read");
4773
- const modules = await listRegisteredModules();
4774
- const componentPaths = new Set;
4775
- componentPaths.add("");
4776
- for (const module of modules) {
4777
- if (module.componentPath) {
4778
- componentPaths.add(module.componentPath);
4779
- }
4780
- }
4781
- const components = [];
4782
- for (const path of componentPaths) {
4783
- const componentModules = modules.filter((m) => path === "" ? !m.componentPath || m.componentPath === "" : m.componentPath === path);
4784
- const functions = await listSystemFunctions({ componentPath: path || undefined });
4785
- components.push({
4786
- path: path || "(root)",
4787
- isRoot: path === "",
4788
- moduleCount: componentModules.length,
5253
+ const components = await loadComponentRows(ctx);
5254
+ const withFunctionCounts = await Promise.all(components.map(async (component) => {
5255
+ const functions = await listSystemFunctions({ componentPath: component.componentPath || undefined });
5256
+ return {
5257
+ ...component,
4789
5258
  functionCount: functions.length
4790
- });
4791
- }
4792
- return components.sort((a, b) => {
4793
- if (a.isRoot)
4794
- return -1;
4795
- if (b.isRoot)
4796
- return 1;
4797
- return a.path.localeCompare(b.path);
4798
- });
5259
+ };
5260
+ }));
5261
+ return sortComponentRows(withFunctionCounts);
4799
5262
  }
4800
5263
  }),
4801
5264
  systemListTables: query({
@@ -4804,25 +5267,40 @@ function createSystemFunctions(deps) {
4804
5267
  requireSystemCapability("tables:read");
4805
5268
  const targetComponent = componentPath ?? "";
4806
5269
  const schema2 = await loadSchemaDefinition(targetComponent);
4807
- let tableEntries = [];
5270
+ const schemaTables = new Map;
4808
5271
  if (schema2?.tables) {
4809
- tableEntries = extractTablesFromSchema(schema2);
4810
- } else {
4811
- try {
4812
- const systemTables = await ctx.db.system.query("_tables").collect();
4813
- tableEntries = systemTables.map((table) => ({
4814
- name: table.name,
4815
- exported: {
4816
- indexes: table.indexes || [],
4817
- searchIndexes: table.searchIndexes || [],
4818
- vectorIndexes: table.vectorIndexes || [],
4819
- documentType: null
4820
- }
4821
- }));
4822
- } catch {
4823
- tableEntries = [];
5272
+ for (const table of extractTablesFromSchema(schema2)) {
5273
+ schemaTables.set(table.name, table);
4824
5274
  }
4825
5275
  }
5276
+ const discoveredTables = new Map;
5277
+ for (const name of schemaTables.keys()) {
5278
+ discoveredTables.set(name, {
5279
+ name,
5280
+ isSystem: isSystemTable(name),
5281
+ visibility: getDefaultSystemTableVisibility(name)
5282
+ });
5283
+ }
5284
+ try {
5285
+ const systemTables = await ctx.db.system.query("_tables").collect();
5286
+ discoveredTables.clear();
5287
+ for (const table of systemTables.filter((entry) => (entry.componentPath ?? "") === targetComponent)) {
5288
+ discoveredTables.set(table.name, {
5289
+ name: table.name,
5290
+ isSystem: table.isSystem === true || isSystemTable(table.name),
5291
+ visibility: table.visibility === "private" ? "private" : "public"
5292
+ });
5293
+ }
5294
+ } catch {}
5295
+ const tableEntries = Array.from(discoveredTables.values()).map((metadata) => ({
5296
+ ...metadata,
5297
+ exported: schemaTables.get(metadata.name)?.exported ?? {
5298
+ indexes: [],
5299
+ searchIndexes: [],
5300
+ vectorIndexes: [],
5301
+ documentType: null
5302
+ }
5303
+ }));
4826
5304
  const tableInfo = await Promise.all(tableEntries.map(async (table) => {
4827
5305
  const fullName = getFullTableName(table.name, targetComponent);
4828
5306
  const documentCount = await countDocuments(ctx, fullName);
@@ -4833,6 +5311,8 @@ function createSystemFunctions(deps) {
4833
5311
  name: table.name,
4834
5312
  fullName,
4835
5313
  componentPath: targetComponent || undefined,
5314
+ isSystem: table.isSystem,
5315
+ visibility: table.visibility,
4836
5316
  documentCount,
4837
5317
  indexes: buildIndexList(exported?.indexes),
4838
5318
  searchIndexes: searchIndexes.map((idx) => typeof idx === "string" ? idx : idx.indexDescriptor),
@@ -4866,7 +5346,7 @@ function createSystemFunctions(deps) {
4866
5346
  }
4867
5347
  try {
4868
5348
  const fullName = getFullTableName(tableName, targetComponent);
4869
- const sampleDoc = await ctx.db.query(fullName).first();
5349
+ const sampleDoc = await getTableQuery(ctx, fullName).first();
4870
5350
  const fields = sampleDoc ? Object.keys(sampleDoc).map((key) => ({
4871
5351
  name: key,
4872
5352
  type: typeof sampleDoc[key],
@@ -4901,7 +5381,7 @@ function createSystemFunctions(deps) {
4901
5381
  handler: async (ctx, args) => {
4902
5382
  requireSystemCapability("documents:read");
4903
5383
  const fullName = getFullTableName(args.tableName, args.componentPath ?? "");
4904
- let query2 = ctx.db.query(fullName);
5384
+ let query2 = getTableQuery(ctx, fullName);
4905
5385
  if (args.orderBy && args.orderBy !== "_creationTime") {
4906
5386
  const allDocs2 = await query2.collect();
4907
5387
  const sorted = allDocs2.sort((a, b) => {
@@ -4952,7 +5432,7 @@ function createSystemFunctions(deps) {
4952
5432
  handler: async (ctx, args) => {
4953
5433
  requireSystemCapability("documents:write");
4954
5434
  const fullName = getFullTableName(args.tableName, args.componentPath ?? "");
4955
- const docs = await ctx.db.query(fullName).collect();
5435
+ const docs = await getTableQuery(ctx, fullName).collect();
4956
5436
  for (const doc of docs) {
4957
5437
  await ctx.db.delete(doc._id);
4958
5438
  }
@@ -5248,6 +5728,83 @@ function resolveFunctionReference(functionPath, componentPath) {
5248
5728
  }
5249
5729
  return functionPath;
5250
5730
  }
5731
+ async function loadComponentRows(ctx) {
5732
+ try {
5733
+ const rows = await ctx.db.system.query("_components").collect();
5734
+ if (rows.length > 0) {
5735
+ return rows.map((row) => normalizeStoredComponentRow(row));
5736
+ }
5737
+ } catch {}
5738
+ const modules = await listRegisteredModules();
5739
+ const moduleCountByComponent = new Map;
5740
+ const hasHttpByComponent = new Map;
5741
+ const componentPaths = new Set([""]);
5742
+ for (const module of modules) {
5743
+ const componentPath = module.componentPath ?? "";
5744
+ componentPaths.add(componentPath);
5745
+ moduleCountByComponent.set(componentPath, (moduleCountByComponent.get(componentPath) ?? 0) + 1);
5746
+ if (module.path === "http") {
5747
+ hasHttpByComponent.set(componentPath, true);
5748
+ }
5749
+ }
5750
+ return Array.from(componentPaths).map((componentPath) => ({
5751
+ componentPath,
5752
+ path: componentPath || "(root)",
5753
+ isRoot: componentPath === "",
5754
+ parentPath: componentPath === "" ? null : componentPath.includes("/") ? componentPath.split("/").slice(0, -1).join("/") : "",
5755
+ depth: componentPath === "" ? 0 : componentPath.split("/").length,
5756
+ moduleCount: moduleCountByComponent.get(componentPath) ?? 0,
5757
+ childCount: 0,
5758
+ functionCount: 0,
5759
+ sourceType: "local",
5760
+ hasHttp: hasHttpByComponent.get(componentPath) === true
5761
+ }));
5762
+ }
5763
+ function normalizeStoredComponentRow(row) {
5764
+ const componentPath = typeof row.componentPath === "string" ? row.componentPath : "";
5765
+ return {
5766
+ componentPath,
5767
+ path: typeof row.displayPath === "string" ? row.displayPath : typeof row.path === "string" && row.path.length > 0 ? row.path : componentPath || "(root)",
5768
+ isRoot: row.isRoot === true || componentPath === "",
5769
+ parentPath: row.parentPath === null ? null : typeof row.parentPath === "string" ? row.parentPath : componentPath === "" ? null : "",
5770
+ depth: typeof row.depth === "number" ? row.depth : componentPath === "" ? 0 : componentPath.split("/").length,
5771
+ moduleCount: typeof row.moduleCount === "number" ? row.moduleCount : 0,
5772
+ childCount: typeof row.childCount === "number" ? row.childCount : 0,
5773
+ functionCount: 0,
5774
+ sourceType: row.sourceType === "npm" ? "npm" : row.sourceType === "local" ? "local" : undefined,
5775
+ sourcePath: typeof row.sourcePath === "string" ? row.sourcePath : undefined,
5776
+ packageName: typeof row.packageName === "string" ? row.packageName : undefined,
5777
+ packageVersion: typeof row.packageVersion === "string" ? row.packageVersion : undefined,
5778
+ hasHttp: row.hasHttp === true
5779
+ };
5780
+ }
5781
+ function sortComponentRows(rows) {
5782
+ const childrenByParent = new Map;
5783
+ for (const row of rows) {
5784
+ const parentKey = row.parentPath ?? null;
5785
+ const siblings = childrenByParent.get(parentKey) ?? [];
5786
+ siblings.push(row);
5787
+ childrenByParent.set(parentKey, siblings);
5788
+ }
5789
+ for (const siblings of childrenByParent.values()) {
5790
+ siblings.sort((a, b) => {
5791
+ if (a.isRoot)
5792
+ return -1;
5793
+ if (b.isRoot)
5794
+ return 1;
5795
+ return a.componentPath.localeCompare(b.componentPath);
5796
+ });
5797
+ }
5798
+ const ordered = [];
5799
+ const visit = (parentPath) => {
5800
+ for (const row of childrenByParent.get(parentPath) ?? []) {
5801
+ ordered.push(row);
5802
+ visit(row.componentPath);
5803
+ }
5804
+ };
5805
+ visit(null);
5806
+ return ordered;
5807
+ }
5251
5808
  async function loadSchemaDefinition(componentPath) {
5252
5809
  try {
5253
5810
  const module = await loadConvexModule("schema", {
@@ -5281,13 +5838,26 @@ function extractTableMetadata(schema2, tableName) {
5281
5838
  }
5282
5839
  async function countDocuments(ctx, tableName) {
5283
5840
  try {
5284
- const documents = await ctx.db.query(tableName).collect();
5841
+ const documents = await getTableQuery(ctx, tableName).collect();
5285
5842
  return documents.length;
5286
5843
  } catch (error) {
5287
5844
  console.warn(`Failed to count documents for table ${tableName}:`, error);
5288
5845
  return 0;
5289
5846
  }
5290
5847
  }
5848
+ function getTableQuery(ctx, fullTableName) {
5849
+ const { tableName } = parseFullTableName(fullTableName);
5850
+ if (isSystemTable(tableName)) {
5851
+ return ctx.db.system.query(tableName);
5852
+ }
5853
+ return ctx.db.query(fullTableName);
5854
+ }
5855
+ function getDefaultSystemTableVisibility(tableName) {
5856
+ if (!isSystemTable(tableName)) {
5857
+ return "public";
5858
+ }
5859
+ return isPublicSystemTable(tableName) ? "public" : "private";
5860
+ }
5291
5861
  function buildIndexList(indexes) {
5292
5862
  const base = ["by_id", "by_creation_time"];
5293
5863
  if (!indexes || indexes.length === 0) {
@@ -5389,6 +5959,7 @@ var init_internal = __esm(() => {
5389
5959
  init_interface();
5390
5960
  init_execution_log();
5391
5961
  init_auth();
5962
+ init_system_tables();
5392
5963
  });
5393
5964
 
5394
5965
  // ../core/dist/system/system-functions-module.js
@@ -5546,8 +6117,9 @@ class ModuleRegistry {
5546
6117
  const normalized = normalizeModuleListing(listing);
5547
6118
  if (!normalized)
5548
6119
  continue;
5549
- if (!results.has(normalized.path)) {
5550
- results.set(normalized.path, {
6120
+ const resultKey = `${normalized.componentPath ?? scope ?? ""}:${normalized.path}`;
6121
+ if (!results.has(resultKey)) {
6122
+ results.set(resultKey, {
5551
6123
  ...normalized,
5552
6124
  scope: scope || undefined,
5553
6125
  componentPath: normalized.componentPath ?? (scope || undefined)
@@ -5866,8 +6438,10 @@ var init_module_loader = __esm(() => {
5866
6438
  class SchemaValidator {
5867
6439
  schemaCache = new Map;
5868
6440
  componentPath;
5869
- constructor(componentPath) {
6441
+ tableRegistry;
6442
+ constructor(componentPath, tableRegistry) {
5870
6443
  this.componentPath = componentPath;
6444
+ this.tableRegistry = tableRegistry;
5871
6445
  }
5872
6446
  async loadTableSchema(tableName) {
5873
6447
  if (this.schemaCache.has(tableName)) {
@@ -5910,8 +6484,11 @@ class SchemaValidator {
5910
6484
  return;
5911
6485
  }
5912
6486
  try {
6487
+ const tableNumberToName = this.tableRegistry ? new Map((await this.tableRegistry.listTables()).map((table) => [table.tableNumber, table.fullName])) : undefined;
5913
6488
  validateValidator(tableSchema, omit(document, ["_id", "_creationTime"]), "", {
5914
- componentPath: this.componentPath ?? ""
6489
+ componentPath: this.componentPath ?? "",
6490
+ tableRegistry: this.tableRegistry,
6491
+ tableNumberToName
5915
6492
  });
5916
6493
  } catch (error) {
5917
6494
  throw new ValidatorError(`Failed to insert or update a document in table "${tableName}" because it does not match the schema: ${error.message}`);
@@ -6009,6 +6586,16 @@ Path: ${formatPath(path)}
6009
6586
  Value: ${formatValue(value)}
6010
6587
  Validator: v.id("${validator2.tableName}")`);
6011
6588
  }
6589
+ if (isValidDocumentId(value)) {
6590
+ const tableName2 = tableNameFromConvexId(value, options);
6591
+ if (!tableName2 || !isMatchingValidatorTable(tableName2, validator2.tableName, options.componentPath)) {
6592
+ throw new Error(`Value does not match validator.
6593
+ Path: ${formatPath(path)}
6594
+ Value: ${formatValue(value)}
6595
+ Validator: v.id("${validator2.tableName}")`);
6596
+ }
6597
+ return;
6598
+ }
6012
6599
  const tableName = tableNameFromId(value);
6013
6600
  if (!tableName || !isMatchingValidatorTable(tableName, validator2.tableName, options.componentPath)) {
6014
6601
  throw new Error(`Value does not match validator.
@@ -6070,289 +6657,72 @@ Validator: v.object({...})`);
6070
6657
  }
6071
6658
  } else {
6072
6659
  const fieldPath = path ? `${path}.${k}` : `.${k}`;
6073
- validateValidator(fieldType, value[k], fieldPath, options);
6074
- }
6075
- }
6076
- for (const k of Object.keys(value)) {
6077
- if (validator2.value[k] === undefined) {
6078
- throw new Error(`Object contains extra field \`${k}\` that is not in the validator.
6079
-
6080
- Object: ${JSON.stringify(value)}
6081
- Validator: v.object({...})`);
6082
- }
6083
- }
6084
- return;
6085
- }
6086
- }
6087
- }
6088
- function tableNameFromId(id) {
6089
- const parts = deserializeDeveloperId(id);
6090
- if (!parts) {
6091
- return null;
6092
- }
6093
- return hexToString(parts.table);
6094
- }
6095
- function isMatchingValidatorTable(idTableName, validatorTableName, componentPath) {
6096
- if (idTableName === validatorTableName) {
6097
- return true;
6098
- }
6099
- const { tableName: validatorBareName } = parseFullTableName(validatorTableName);
6100
- const { tableName: idBareName } = parseFullTableName(idTableName);
6101
- if (componentPath !== undefined) {
6102
- const expectedFullName = getFullTableName(validatorBareName, componentPath);
6103
- return idTableName === expectedFullName;
6104
- }
6105
- return idBareName === validatorBareName;
6106
- }
6107
- function isSimpleObject2(value) {
6108
- const isObject2 = typeof value === "object";
6109
- const prototype = Object.getPrototypeOf(value);
6110
- const isSimple = prototype === null || prototype === Object.prototype || prototype?.constructor?.name === "Object";
6111
- return isObject2 && isSimple;
6112
- }
6113
- var ValidatorError;
6114
- var init_validator2 = __esm(() => {
6115
- init_interface();
6116
- init_module_loader();
6117
- ValidatorError = class ValidatorError extends Error {
6118
- path;
6119
- constructor(message2, path = "") {
6120
- super(message2);
6121
- this.path = path;
6122
- this.name = "ValidatorError";
6123
- }
6124
- };
6125
- });
6126
-
6127
- // ../core/dist/id-codec/base32.js
6128
- function base32Encode(data) {
6129
- if (data.length === 0)
6130
- return "";
6131
- let result = "";
6132
- let buffer = 0;
6133
- let bitsLeft = 0;
6134
- for (const byte of data) {
6135
- buffer = buffer << 8 | byte;
6136
- bitsLeft += 8;
6137
- while (bitsLeft >= 5) {
6138
- bitsLeft -= 5;
6139
- const index = buffer >> bitsLeft & 31;
6140
- result += ALPHABET[index];
6141
- }
6142
- }
6143
- if (bitsLeft > 0) {
6144
- const index = buffer << 5 - bitsLeft & 31;
6145
- result += ALPHABET[index];
6146
- }
6147
- return result;
6148
- }
6149
- function base32Decode(str) {
6150
- if (str.length === 0)
6151
- return new Uint8Array(0);
6152
- const outputLength = Math.floor(str.length * 5 / 8);
6153
- const result = new Uint8Array(outputLength);
6154
- let buffer = 0;
6155
- let bitsLeft = 0;
6156
- let outputIndex = 0;
6157
- for (const char of str) {
6158
- const value = ALPHABET_MAP.get(char);
6159
- if (value === undefined) {
6160
- throw new Error(`Invalid base32 character: ${char}`);
6161
- }
6162
- buffer = buffer << 5 | value;
6163
- bitsLeft += 5;
6164
- if (bitsLeft >= 8) {
6165
- bitsLeft -= 8;
6166
- result[outputIndex++] = buffer >> bitsLeft & 255;
6167
- }
6168
- }
6169
- return result;
6170
- }
6171
- function isValidBase32(str) {
6172
- for (const char of str) {
6173
- if (!ALPHABET_MAP.has(char)) {
6174
- return false;
6175
- }
6176
- }
6177
- return true;
6178
- }
6179
- var ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz", ALPHABET_MAP;
6180
- var init_base32 = __esm(() => {
6181
- ALPHABET_MAP = new Map;
6182
- for (let i2 = 0;i2 < ALPHABET.length; i2++) {
6183
- ALPHABET_MAP.set(ALPHABET[i2], i2);
6184
- ALPHABET_MAP.set(ALPHABET[i2].toUpperCase(), i2);
6185
- }
6186
- ALPHABET_MAP.set("i", 1);
6187
- ALPHABET_MAP.set("I", 1);
6188
- ALPHABET_MAP.set("l", 1);
6189
- ALPHABET_MAP.set("L", 1);
6190
- ALPHABET_MAP.set("o", 0);
6191
- ALPHABET_MAP.set("O", 0);
6192
- });
6193
-
6194
- // ../core/dist/id-codec/vint.js
6195
- function vintEncode(value) {
6196
- if (value < 0) {
6197
- throw new Error("VInt cannot encode negative numbers");
6198
- }
6199
- if (value > 4294967295) {
6200
- throw new Error("VInt cannot encode values larger than 2^32-1");
6201
- }
6202
- value = value >>> 0;
6203
- if (value < 128) {
6204
- return new Uint8Array([value]);
6205
- }
6206
- if (value < 16512) {
6207
- const adjusted2 = value - 128;
6208
- return new Uint8Array([128 | adjusted2 >> 8 & 63, adjusted2 & 255]);
6209
- }
6210
- if (value < 2113664) {
6211
- const adjusted2 = value - 16512;
6212
- return new Uint8Array([192 | adjusted2 >> 16 & 31, adjusted2 >> 8 & 255, adjusted2 & 255]);
6213
- }
6214
- if (value < 270549120) {
6215
- const adjusted2 = value - 2113664;
6216
- return new Uint8Array([
6217
- 224 | adjusted2 >> 24 & 15,
6218
- adjusted2 >> 16 & 255,
6219
- adjusted2 >> 8 & 255,
6220
- adjusted2 & 255
6221
- ]);
6222
- }
6223
- const adjusted = value - 270549120;
6224
- return new Uint8Array([
6225
- 240 | adjusted >> 32 & 7,
6226
- adjusted >> 24 & 255,
6227
- adjusted >> 16 & 255,
6228
- adjusted >> 8 & 255,
6229
- adjusted & 255
6230
- ]);
6231
- }
6232
- function vintDecode(data, offset = 0) {
6233
- if (offset >= data.length) {
6234
- throw new Error("VInt decode: unexpected end of data");
6235
- }
6236
- const first = data[offset];
6237
- if ((first & 128) === 0) {
6238
- return { value: first, bytesRead: 1 };
6239
- }
6240
- if ((first & 192) === 128) {
6241
- if (offset + 1 >= data.length) {
6242
- throw new Error("VInt decode: truncated 2-byte encoding");
6243
- }
6244
- const value = 128 + ((first & 63) << 8 | data[offset + 1]);
6245
- return { value, bytesRead: 2 };
6246
- }
6247
- if ((first & 224) === 192) {
6248
- if (offset + 2 >= data.length) {
6249
- throw new Error("VInt decode: truncated 3-byte encoding");
6250
- }
6251
- const value = 16512 + ((first & 31) << 16 | data[offset + 1] << 8 | data[offset + 2]);
6252
- return { value, bytesRead: 3 };
6253
- }
6254
- if ((first & 240) === 224) {
6255
- if (offset + 3 >= data.length) {
6256
- throw new Error("VInt decode: truncated 4-byte encoding");
6257
- }
6258
- const value = 2113664 + ((first & 15) << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]);
6259
- return { value: value >>> 0, bytesRead: 4 };
6260
- }
6261
- if ((first & 248) === 240) {
6262
- if (offset + 4 >= data.length) {
6263
- throw new Error("VInt decode: truncated 5-byte encoding");
6264
- }
6265
- const high = first & 7;
6266
- const low = (data[offset + 1] << 24 | data[offset + 2] << 16 | data[offset + 3] << 8 | data[offset + 4]) >>> 0;
6267
- const value = 270549120 + high * 4294967296 + low;
6268
- return { value: value >>> 0, bytesRead: 5 };
6269
- }
6270
- throw new Error("VInt decode: invalid prefix");
6271
- }
6272
-
6273
- // ../core/dist/id-codec/fletcher16.js
6274
- function fletcher16(data) {
6275
- let sum1 = 0;
6276
- let sum2 = 0;
6277
- for (const byte of data) {
6278
- sum1 = (sum1 + byte) % 255;
6279
- sum2 = (sum2 + sum1) % 255;
6280
- }
6281
- return new Uint8Array([sum1, sum2]);
6282
- }
6283
- function verifyFletcher16(data, checksum) {
6284
- if (checksum.length !== 2)
6285
- return false;
6286
- const computed = fletcher16(data);
6287
- return computed[0] === checksum[0] && computed[1] === checksum[1];
6288
- }
6289
-
6290
- // ../core/dist/utils/crypto.js
6291
- var weakRandomState;
6292
- var init_crypto = __esm(() => {
6293
- weakRandomState = (Date.now() ^ 2654435769) >>> 0;
6294
- });
6295
-
6296
- // ../core/dist/id-codec/document-id.js
6297
- function encodeDocumentId(tableNumber, internalId) {
6298
- if (internalId.length !== INTERNAL_ID_LENGTH) {
6299
- throw new Error(`Internal ID must be exactly ${INTERNAL_ID_LENGTH} bytes, got ${internalId.length}`);
6300
- }
6301
- if (tableNumber < 1 || tableNumber > 4294967295) {
6302
- throw new Error(`Table number must be between 1 and 2^32-1, got ${tableNumber}`);
6303
- }
6304
- const tableBytes = vintEncode(tableNumber);
6305
- const payload = new Uint8Array(tableBytes.length + INTERNAL_ID_LENGTH);
6306
- payload.set(tableBytes, 0);
6307
- payload.set(internalId, tableBytes.length);
6308
- const checksum = fletcher16(payload);
6309
- const final = new Uint8Array(payload.length + 2);
6310
- final.set(payload, 0);
6311
- final.set(checksum, payload.length);
6312
- return base32Encode(final);
6313
- }
6314
- function decodeDocumentId(encoded) {
6315
- if (encoded.length < MIN_ENCODED_LENGTH || encoded.length > MAX_ENCODED_LENGTH) {
6316
- throw new Error(`Invalid document ID length: ${encoded.length} (expected ${MIN_ENCODED_LENGTH}-${MAX_ENCODED_LENGTH})`);
6317
- }
6318
- if (!isValidBase32(encoded)) {
6319
- throw new Error("Invalid document ID: contains invalid base32 characters");
6320
- }
6321
- const bytes = base32Decode(encoded);
6322
- if (bytes.length < 19) {
6323
- throw new Error(`Invalid document ID: decoded to ${bytes.length} bytes (minimum 19)`);
6324
- }
6325
- const checksum = bytes.slice(bytes.length - 2);
6326
- const payload = bytes.slice(0, bytes.length - 2);
6327
- if (!verifyFletcher16(payload, checksum)) {
6328
- throw new Error("Invalid document ID: checksum verification failed");
6660
+ validateValidator(fieldType, value[k], fieldPath, options);
6661
+ }
6662
+ }
6663
+ for (const k of Object.keys(value)) {
6664
+ if (validator2.value[k] === undefined) {
6665
+ throw new Error(`Object contains extra field \`${k}\` that is not in the validator.
6666
+
6667
+ Object: ${JSON.stringify(value)}
6668
+ Validator: v.object({...})`);
6669
+ }
6670
+ }
6671
+ return;
6672
+ }
6329
6673
  }
6330
- const { value: tableNumber, bytesRead } = vintDecode(payload, 0);
6331
- const internalId = payload.slice(bytesRead, bytesRead + INTERNAL_ID_LENGTH);
6332
- if (internalId.length !== INTERNAL_ID_LENGTH) {
6333
- throw new Error(`Invalid document ID: internal ID is ${internalId.length} bytes (expected ${INTERNAL_ID_LENGTH})`);
6674
+ }
6675
+ function tableNameFromId(id) {
6676
+ const parts = deserializeDeveloperId(id);
6677
+ if (!parts) {
6678
+ return null;
6334
6679
  }
6335
- return { tableNumber, internalId };
6680
+ return hexToString(parts.table);
6336
6681
  }
6337
- function isValidDocumentId(encoded) {
6682
+ function tableNameFromConvexId(id, options) {
6338
6683
  try {
6339
- decodeDocumentId(encoded);
6340
- return true;
6684
+ const decoded = decodeDocumentId(id);
6685
+ const fromMap = options.tableNumberToName?.get(decoded.tableNumber);
6686
+ if (fromMap) {
6687
+ return fromMap;
6688
+ }
6689
+ return null;
6341
6690
  } catch {
6342
- return false;
6691
+ return null;
6343
6692
  }
6344
6693
  }
6345
- function internalIdToHex(internalId) {
6346
- let hex = "";
6347
- for (let i2 = 0;i2 < internalId.length; i2++) {
6348
- hex += internalId[i2].toString(16).padStart(2, "0");
6694
+ function isMatchingValidatorTable(idTableName, validatorTableName, componentPath) {
6695
+ if (idTableName === validatorTableName) {
6696
+ return true;
6349
6697
  }
6350
- return hex;
6698
+ const { tableName: validatorBareName } = parseFullTableName(validatorTableName);
6699
+ const { tableName: idBareName } = parseFullTableName(idTableName);
6700
+ if (componentPath !== undefined) {
6701
+ const expectedFullName = getFullTableName(validatorBareName, componentPath);
6702
+ return idTableName === expectedFullName;
6703
+ }
6704
+ return idBareName === validatorBareName;
6351
6705
  }
6352
- var INTERNAL_ID_LENGTH = 16, MIN_ENCODED_LENGTH = 31, MAX_ENCODED_LENGTH = 37;
6353
- var init_document_id = __esm(() => {
6354
- init_base32();
6355
- init_crypto();
6706
+ function isSimpleObject2(value) {
6707
+ const isObject2 = typeof value === "object";
6708
+ const prototype = Object.getPrototypeOf(value);
6709
+ const isSimple = prototype === null || prototype === Object.prototype || prototype?.constructor?.name === "Object";
6710
+ return isObject2 && isSimple;
6711
+ }
6712
+ var ValidatorError;
6713
+ var init_validator2 = __esm(() => {
6714
+ init_utils();
6715
+ init_interface();
6716
+ init_module_loader();
6717
+ init_id_codec();
6718
+ ValidatorError = class ValidatorError extends Error {
6719
+ path;
6720
+ constructor(message2, path = "") {
6721
+ super(message2);
6722
+ this.path = path;
6723
+ this.name = "ValidatorError";
6724
+ }
6725
+ };
6356
6726
  });
6357
6727
 
6358
6728
  // src/sqlite-docstore.ts
@@ -6363,7 +6733,10 @@ init_values();
6363
6733
 
6364
6734
  // ../core/dist/docstore/interface.js
6365
6735
  function documentIdKey(id) {
6366
- const tableKey = id.table && id.table.length > 0 ? id.table : id.tableNumber !== undefined && Number.isInteger(id.tableNumber) && id.tableNumber > 0 ? `#${id.tableNumber}` : id.table;
6736
+ const tableKey = id.table && id.table.length > 0 ? id.table : id.tableNumber !== undefined && Number.isInteger(id.tableNumber) && id.tableNumber > 0 ? `#${id.tableNumber}` : null;
6737
+ if (!tableKey) {
6738
+ throw new Error("Invalid document ID: missing table and tableNumber");
6739
+ }
6367
6740
  return `${tableKey}:${id.internalId}`;
6368
6741
  }
6369
6742
  var Order;
@@ -6570,6 +6943,7 @@ class TimestampOracle {
6570
6943
  }
6571
6944
  }
6572
6945
  // ../core/dist/utils/keyspace.js
6946
+ init_utils();
6573
6947
  var TABLE_PREFIX = "table";
6574
6948
  var INDEX_PREFIX = "index";
6575
6949
  function encodeComponent(component) {
@@ -6610,6 +6984,13 @@ function decodeIndexId(indexId) {
6610
6984
  index: decoded.slice(separatorIndex + 1)
6611
6985
  };
6612
6986
  }
6987
+
6988
+ // ../core/dist/utils/index.js
6989
+ init_utils();
6990
+
6991
+ // ../core/dist/queryengine/indexing/index-manager.js
6992
+ init_utils();
6993
+
6613
6994
  // ../core/dist/queryengine/indexing/index-key-codec.js
6614
6995
  var TypeTag;
6615
6996
  (function(TypeTag2) {
@@ -6659,8 +7040,9 @@ function encodeBigInt(n) {
6659
7040
  return bytes;
6660
7041
  }
6661
7042
  function encodeString(s) {
6662
- const encoder = new TextEncoder;
6663
- const raw = encoder.encode(s);
7043
+ return encodeEscapedBytes(new TextEncoder().encode(s));
7044
+ }
7045
+ function encodeEscapedBytes(raw) {
6664
7046
  let nullCount = 0;
6665
7047
  for (const byte of raw) {
6666
7048
  if (byte === 0)
@@ -6724,11 +7106,10 @@ function encodeValue(value) {
6724
7106
  }
6725
7107
  if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
6726
7108
  const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
6727
- const result = new Uint8Array(1 + bytes.length + 2);
7109
+ const encoded = encodeEscapedBytes(bytes);
7110
+ const result = new Uint8Array(1 + encoded.length);
6728
7111
  result[0] = TypeTag.Bytes;
6729
- result.set(bytes, 1);
6730
- result[result.length - 2] = 0;
6731
- result[result.length - 1] = 0;
7112
+ result.set(encoded, 1);
6732
7113
  return result;
6733
7114
  }
6734
7115
  throw new Error(`Cannot encode value of type ${typeof value} in index key`);
@@ -6845,9 +7226,11 @@ class SchemaService {
6845
7226
  tableCache = new Map;
6846
7227
  schemaValidator;
6847
7228
  componentPath;
6848
- constructor(componentPath) {
7229
+ tableRegistry;
7230
+ constructor(componentPath, tableRegistry) {
6849
7231
  this.componentPath = componentPath;
6850
- this.schemaValidator = new SchemaValidator(componentPath);
7232
+ this.tableRegistry = tableRegistry;
7233
+ this.schemaValidator = new SchemaValidator(componentPath, tableRegistry);
6851
7234
  }
6852
7235
  async validate(tableName, document) {
6853
7236
  try {
@@ -6972,6 +7355,10 @@ class SchemaService {
6972
7355
  return this.cachedSchemaDefinition;
6973
7356
  }
6974
7357
  }
7358
+
7359
+ // ../core/dist/queryengine/index-query.js
7360
+ init_utils();
7361
+
6975
7362
  // ../core/dist/observability/udf-trace.js
6976
7363
  init_context_storage();
6977
7364
  var TRACE_CONTEXT = new ContextStorage;
@@ -7215,11 +7602,10 @@ function evaluateFieldPath(fieldPath, document) {
7215
7602
  }
7216
7603
  return current;
7217
7604
  }
7218
- // ../core/dist/id-codec/index.js
7219
- init_base32();
7220
- init_document_id();
7221
7605
 
7222
7606
  // ../core/dist/queryengine/developer-id.js
7607
+ init_utils();
7608
+ init_id_codec();
7223
7609
  function parseDeveloperId(developerId) {
7224
7610
  if (isValidDocumentId(developerId)) {
7225
7611
  try {
@@ -7237,6 +7623,25 @@ function parseDeveloperId(developerId) {
7237
7623
  }
7238
7624
  return { table: parts.table, internalId: parts.internalId };
7239
7625
  }
7626
+ async function parseDeveloperIdWithTableRegistry(developerId, tableRegistry) {
7627
+ if (isValidDocumentId(developerId)) {
7628
+ try {
7629
+ const decoded = decodeDocumentId(developerId);
7630
+ const tableInfo = await tableRegistry.getTableInfo(decoded.tableNumber);
7631
+ if (!tableInfo) {
7632
+ return null;
7633
+ }
7634
+ return {
7635
+ table: stringToHex(tableInfo.fullName),
7636
+ internalId: internalIdToHex(decoded.internalId),
7637
+ tableNumber: decoded.tableNumber
7638
+ };
7639
+ } catch {
7640
+ return null;
7641
+ }
7642
+ }
7643
+ return parseDeveloperId(developerId);
7644
+ }
7240
7645
  function parseStorageId(storageId) {
7241
7646
  const parsed = parseDeveloperId(storageId);
7242
7647
  if (parsed) {
@@ -7253,12 +7658,21 @@ function parseStorageId(storageId) {
7253
7658
  function isTablePlaceholder(table) {
7254
7659
  return table.startsWith("#");
7255
7660
  }
7661
+
7662
+ // ../core/dist/query/query-runtime.js
7663
+ init_utils();
7664
+
7256
7665
  // ../core/dist/query/planner.js
7257
7666
  init_interface();
7667
+ init_utils();
7668
+
7258
7669
  // ../core/dist/query/actions.js
7670
+ init_utils();
7259
7671
  init_interface();
7260
7672
 
7261
7673
  // ../core/dist/queryengine/indexing/read-write-set.js
7674
+ init_utils();
7675
+
7262
7676
  class RangeSet {
7263
7677
  ranges = new Map;
7264
7678
  addDocument(docId) {
@@ -7369,6 +7783,8 @@ function deserializeKeyRange(serialized) {
7369
7783
  }
7370
7784
 
7371
7785
  // ../core/dist/kernel/access-log.js
7786
+ init_utils();
7787
+
7372
7788
  class AccessLog {
7373
7789
  ranges = new RangeSet;
7374
7790
  addDocument(docId) {
@@ -7393,104 +7809,9 @@ class AccessLog {
7393
7809
  }
7394
7810
  }
7395
7811
 
7396
- // ../core/dist/tables/memory-table-registry.js
7812
+ // ../core/dist/kernel/kernel-context.js
7397
7813
  init_interface();
7398
7814
 
7399
- class MemoryTableRegistry {
7400
- tablesByName = new Map;
7401
- tablesByNumber = new Map;
7402
- nextTableNumber = FIRST_USER_TABLE_NUMBER;
7403
- constructor() {
7404
- this.registerSystemTables();
7405
- }
7406
- registerSystemTables() {
7407
- for (const [name, number] of Object.entries(SYSTEM_TABLE_NUMBERS)) {
7408
- const info = {
7409
- tableNumber: number,
7410
- name,
7411
- componentPath: "",
7412
- fullName: name,
7413
- isSystem: true,
7414
- createdAt: Date.now()
7415
- };
7416
- this.tablesByName.set(name, info);
7417
- this.tablesByNumber.set(number, info);
7418
- }
7419
- }
7420
- async getOrAllocateTableNumber(tableName, componentPath = "") {
7421
- const fullName = getFullTableName(tableName, componentPath);
7422
- const existing = this.tablesByName.get(fullName);
7423
- if (existing) {
7424
- return existing.tableNumber;
7425
- }
7426
- if (isSystemTable(tableName) && componentPath === "") {
7427
- const systemNumber = SYSTEM_TABLE_NUMBERS[tableName];
7428
- if (systemNumber !== undefined) {
7429
- return systemNumber;
7430
- }
7431
- }
7432
- const tableNumber = this.nextTableNumber++;
7433
- const info = {
7434
- tableNumber,
7435
- name: tableName,
7436
- componentPath,
7437
- fullName,
7438
- isSystem: false,
7439
- createdAt: Date.now()
7440
- };
7441
- this.tablesByName.set(fullName, info);
7442
- this.tablesByNumber.set(tableNumber, info);
7443
- return tableNumber;
7444
- }
7445
- async getTableInfo(tableNumber) {
7446
- return this.tablesByNumber.get(tableNumber) ?? null;
7447
- }
7448
- async getTableInfoByName(tableName, componentPath = "") {
7449
- const fullName = getFullTableName(tableName, componentPath);
7450
- return this.tablesByName.get(fullName) ?? null;
7451
- }
7452
- async listTables(componentPath) {
7453
- const tables = Array.from(this.tablesByNumber.values());
7454
- if (componentPath === undefined) {
7455
- return tables;
7456
- }
7457
- return tables.filter((t) => t.componentPath === componentPath);
7458
- }
7459
- async hasAccess(tableNumber, componentPath) {
7460
- const info = await this.getTableInfo(tableNumber);
7461
- if (!info) {
7462
- return false;
7463
- }
7464
- if (info.isSystem) {
7465
- return true;
7466
- }
7467
- return info.componentPath === componentPath;
7468
- }
7469
- getSystemTableNumber(systemTableName) {
7470
- return SYSTEM_TABLE_NUMBERS[systemTableName];
7471
- }
7472
- reset() {
7473
- this.tablesByName.clear();
7474
- this.tablesByNumber.clear();
7475
- this.nextTableNumber = FIRST_USER_TABLE_NUMBER;
7476
- this.registerSystemTables();
7477
- }
7478
- getState() {
7479
- return {
7480
- tableCount: this.tablesByNumber.size,
7481
- nextNumber: this.nextTableNumber
7482
- };
7483
- }
7484
- }
7485
- var globalRegistry = null;
7486
- function getGlobalTableRegistry() {
7487
- if (!globalRegistry) {
7488
- globalRegistry = new MemoryTableRegistry;
7489
- }
7490
- return globalRegistry;
7491
- }
7492
-
7493
- // ../core/dist/kernel/kernel-context.js
7494
7815
  class KernelContext {
7495
7816
  authContext;
7496
7817
  componentPath;
@@ -7507,11 +7828,14 @@ class KernelContext {
7507
7828
  this.authContext = options.authContext;
7508
7829
  this.componentPath = options.componentPath ?? "";
7509
7830
  this.mutationTransaction = options.mutationTransaction;
7510
- this.tableRegistry = options.tableRegistry ?? getGlobalTableRegistry();
7511
- this.useConvexIdFormat = options.useConvexIdFormat ?? false;
7831
+ if (!options.tableRegistry) {
7832
+ throw new Error("KernelContext requires an explicit tableRegistry");
7833
+ }
7834
+ this.tableRegistry = options.tableRegistry;
7835
+ this.useConvexIdFormat = options.useConvexIdFormat ?? true;
7512
7836
  }
7513
7837
  async getTableNumber(tableName) {
7514
- return this.tableRegistry.getOrAllocateTableNumber(tableName, this.componentPath);
7838
+ return this.tableRegistry.getOrAllocateTableNumber(tableName, isSystemTable(tableName) ? "" : this.componentPath);
7515
7839
  }
7516
7840
  nextSubrequestId(prefix, udfPath) {
7517
7841
  return `${prefix}:${udfPath}:${Date.now()}:${Math.random()}:${this.subrequestCounter++}`;
@@ -7556,7 +7880,7 @@ class KernelContext {
7556
7880
  this.writeLog.addDocument(docId);
7557
7881
  }
7558
7882
  recordLocalWrite(developerId, tableName, value, docId) {
7559
- this.localWrites.set(developerId, { table: tableName, value });
7883
+ this.localWrites.set(developerId, { table: tableName, value, docId });
7560
7884
  if (docId) {
7561
7885
  this.recordDocumentWrite(docId);
7562
7886
  return;
@@ -7598,7 +7922,13 @@ class KernelContext {
7598
7922
  }
7599
7923
  }
7600
7924
 
7925
+ // ../core/dist/kernel/udf-kernel.js
7926
+ init_id_codec();
7927
+
7601
7928
  // ../core/dist/kernel/blob-store-gateway.js
7929
+ init_id_codec();
7930
+ init_utils();
7931
+
7602
7932
  class BlobStoreGateway {
7603
7933
  context;
7604
7934
  docStore;
@@ -7647,7 +7977,7 @@ class BlobStoreGateway {
7647
7977
  if (!this.storage) {
7648
7978
  return null;
7649
7979
  }
7650
- const docId = parseStorageId(storageId);
7980
+ const docId = await parseDeveloperIdWithTableRegistry(storageId, this.context.tableRegistry) ?? parseStorageId(storageId);
7651
7981
  if (!docId) {
7652
7982
  console.debug(`[BlobStoreGateway] Failed to parse storage ID: ${storageId}`);
7653
7983
  return null;
@@ -7668,7 +7998,7 @@ class BlobStoreGateway {
7668
7998
  if (!this.storage) {
7669
7999
  return null;
7670
8000
  }
7671
- const docId = parseStorageId(storageId);
8001
+ const docId = await parseDeveloperIdWithTableRegistry(storageId, this.context.tableRegistry) ?? parseStorageId(storageId);
7672
8002
  if (!docId) {
7673
8003
  return null;
7674
8004
  }
@@ -7681,7 +8011,7 @@ class BlobStoreGateway {
7681
8011
  }
7682
8012
  async delete(storageId) {
7683
8013
  const storage2 = this.requireStorage();
7684
- const docId = parseStorageId(storageId);
8014
+ const docId = await parseDeveloperIdWithTableRegistry(storageId, this.context.tableRegistry) ?? parseStorageId(storageId);
7685
8015
  if (!docId) {
7686
8016
  return;
7687
8017
  }
@@ -7706,13 +8036,17 @@ class BlobStoreGateway {
7706
8036
 
7707
8037
  // ../core/dist/kernel/scheduler-gateway.js
7708
8038
  init_values();
8039
+ init_id_codec();
8040
+ init_utils();
8041
+
7709
8042
  // ../core/dist/kernel/syscalls/utils.js
7710
8043
  init_values();
8044
+ init_utils();
7711
8045
  async function resolveTableName(docId, tableRegistry) {
7712
8046
  if (docId.tableNumber !== undefined) {
7713
8047
  const info = await tableRegistry.getTableInfo(docId.tableNumber);
7714
8048
  if (info) {
7715
- return info.name;
8049
+ return info.fullName;
7716
8050
  }
7717
8051
  if (!isTablePlaceholder(docId.table)) {
7718
8052
  return hexToString(docId.table);
@@ -7893,7 +8227,7 @@ class SchedulerGateway {
7893
8227
  return developerId;
7894
8228
  }
7895
8229
  async cancel(id, state) {
7896
- const docId = parseDeveloperId(id);
8230
+ const docId = await parseDeveloperIdWithTableRegistry(id, this.context.tableRegistry);
7897
8231
  if (!docId) {
7898
8232
  throw new Error(`Scheduled job with id ${id} not found.`);
7899
8233
  }
@@ -8018,6 +8352,8 @@ class ActionSyscalls {
8018
8352
 
8019
8353
  // ../core/dist/kernel/syscalls/database-syscalls.js
8020
8354
  init_values();
8355
+ init_id_codec();
8356
+ init_utils();
8021
8357
  init_interface();
8022
8358
 
8023
8359
  class DatabaseSyscalls {
@@ -8054,7 +8390,8 @@ class DatabaseSyscalls {
8054
8390
  if (docId.tableNumber !== undefined) {
8055
8391
  return { id: idString };
8056
8392
  }
8057
- if (docId.table === stringToHex(tableName)) {
8393
+ const expectedFullTableName = getFullTableName(tableName, isSystemTable(tableName) ? "" : this.context.componentPath);
8394
+ if (docId.table === stringToHex(expectedFullTableName)) {
8058
8395
  return { id: idString };
8059
8396
  }
8060
8397
  return { id: null };
@@ -8113,29 +8450,28 @@ class DatabaseSyscalls {
8113
8450
  return { _id: developerId };
8114
8451
  }
8115
8452
  async handleGet(args) {
8116
- const { id } = args;
8453
+ const { id, table } = args;
8117
8454
  if (typeof id !== "string") {
8118
8455
  throw new Error("`id` argument for `get` must be a string.");
8119
8456
  }
8120
- const internalId = parseDeveloperId(id);
8121
- if (!internalId) {
8457
+ const resolved = await this.resolveDocumentTarget(id, table, "get");
8458
+ if (!resolved) {
8122
8459
  return null;
8123
8460
  }
8124
- this.context.recordDocumentRead(internalId);
8125
- const doc = await this.queryRuntime.getVisibleDocumentById(id, internalId);
8461
+ this.context.recordDocumentRead(resolved.docId);
8462
+ const doc = await this.queryRuntime.getVisibleDocumentById(id, resolved.docId);
8126
8463
  return doc ?? null;
8127
8464
  }
8128
8465
  async handleRemove(args) {
8129
- const { id } = args;
8466
+ const { id, table } = args;
8130
8467
  if (typeof id !== "string") {
8131
8468
  throw new Error("`id` argument for `remove` must be a string.");
8132
8469
  }
8133
- const docId = parseDeveloperId(id);
8134
- if (!docId) {
8470
+ const resolved = await this.resolveDocumentTarget(id, table, "remove", true);
8471
+ if (!resolved) {
8135
8472
  throw new Error(`Document with id ${id} not found.`);
8136
8473
  }
8137
- const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8138
- const { tableName: bareTableName } = parseFullTableName(fullTableName);
8474
+ const { docId, fullTableName, bareTableName } = resolved;
8139
8475
  const latest = await this.docStore.fetchLatestDocument(docId, this.context.snapshotTimestamp);
8140
8476
  if (!latest) {
8141
8477
  throw new Error(`Document with id ${id} not found.`);
@@ -8151,16 +8487,15 @@ class DatabaseSyscalls {
8151
8487
  return {};
8152
8488
  }
8153
8489
  async handleShallowMerge(args) {
8154
- const { id, value } = args;
8490
+ const { id, table, value } = args;
8155
8491
  if (typeof id !== "string") {
8156
8492
  throw new Error("`id` argument for `shallowMerge` must be a string.");
8157
8493
  }
8158
- const docId = parseDeveloperId(id);
8159
- if (!docId) {
8494
+ const resolved = await this.resolveDocumentTarget(id, table, "patch", true);
8495
+ if (!resolved) {
8160
8496
  throw new Error(`Document with id ${id} not found.`);
8161
8497
  }
8162
- const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8163
- const { tableName: bareTableName } = parseFullTableName(fullTableName);
8498
+ const { docId, fullTableName, bareTableName } = resolved;
8164
8499
  if (value && typeof value === "object") {
8165
8500
  if ("_id" in value) {
8166
8501
  throw new Error("System field `_id` cannot be modified in a patch operation.");
@@ -8211,16 +8546,15 @@ class DatabaseSyscalls {
8211
8546
  return {};
8212
8547
  }
8213
8548
  async handleReplace(args) {
8214
- const { id, value } = args;
8549
+ const { id, table, value } = args;
8215
8550
  if (typeof id !== "string") {
8216
8551
  throw new Error("`id` argument for `replace` must be a string.");
8217
8552
  }
8218
- const docId = parseDeveloperId(id);
8219
- if (!docId) {
8553
+ const resolved = await this.resolveDocumentTarget(id, table, "replace", true);
8554
+ if (!resolved) {
8220
8555
  throw new Error(`Document with id ${id} not found.`);
8221
8556
  }
8222
- const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8223
- const { tableName: bareTableName } = parseFullTableName(fullTableName);
8557
+ const { docId, fullTableName, bareTableName } = resolved;
8224
8558
  const replaceValue = jsonToConvex(value);
8225
8559
  if (typeof replaceValue !== "object" || replaceValue === null || Array.isArray(replaceValue)) {
8226
8560
  throw new Error("The replacement value for `replace` must be an object.");
@@ -8243,6 +8577,27 @@ class DatabaseSyscalls {
8243
8577
  this.context.recordLocalWrite(id, fullTableName, newValue, canonicalDocId);
8244
8578
  return {};
8245
8579
  }
8580
+ async resolveDocumentTarget(id, table, operation, throwOnMismatch = false) {
8581
+ if (table !== undefined && typeof table !== "string") {
8582
+ throw new Error(`\`table\` argument for \`${operation}\` must be a string.`);
8583
+ }
8584
+ const docId = await parseDeveloperIdWithTableRegistry(id, this.context.tableRegistry);
8585
+ if (!docId) {
8586
+ return null;
8587
+ }
8588
+ const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8589
+ if (typeof table === "string") {
8590
+ const expectedFullTableName = getFullTableName(table, isSystemTable(table) ? "" : this.context.componentPath);
8591
+ if (fullTableName !== expectedFullTableName) {
8592
+ if (throwOnMismatch) {
8593
+ throw new Error(`Document with id ${id} does not belong to table ${table}.`);
8594
+ }
8595
+ return null;
8596
+ }
8597
+ }
8598
+ const { tableName: bareTableName } = parseFullTableName(fullTableName);
8599
+ return { docId, fullTableName, bareTableName };
8600
+ }
8246
8601
  }
8247
8602
 
8248
8603
  // ../core/dist/kernel/syscalls/identity-syscalls.js
@@ -8558,11 +8913,203 @@ class KernelSyscalls {
8558
8913
  return this.jsRouter.dispatch(op, args);
8559
8914
  }
8560
8915
  }
8916
+
8917
+ // ../core/dist/tables/docstore-table-registry.js
8918
+ init_system_tables();
8919
+ init_utils();
8920
+ init_interface();
8921
+
8922
+ class DocStoreTableRegistry {
8923
+ docstore;
8924
+ tablesByNumber = new Map;
8925
+ tablesByName = new Map;
8926
+ loadPromise = null;
8927
+ cachedRegistryVersion = 0;
8928
+ constructor(docstore) {
8929
+ this.docstore = docstore;
8930
+ }
8931
+ async getOrAllocateTableNumber(tableName, componentPath = "") {
8932
+ await this.ensureLoaded();
8933
+ await this.ensureFresh();
8934
+ const normalizedComponent = isSystemTable(tableName) ? "" : componentPath;
8935
+ const fullName = getFullTableName(tableName, normalizedComponent);
8936
+ let existing = this.tablesByName.get(fullName);
8937
+ if (existing) {
8938
+ return existing.tableNumber;
8939
+ }
8940
+ await this.reloadTables();
8941
+ existing = this.tablesByName.get(fullName);
8942
+ if (existing) {
8943
+ return existing.tableNumber;
8944
+ }
8945
+ const oracle = this.docstore.timestampOracle;
8946
+ for (;; ) {
8947
+ const metadata = await readSystemMetadata(this.docstore) ?? createSystemMetadata({
8948
+ nextUserTableNumber: Math.max(FIRST_USER_TABLE_NUMBER, nextUserTableNumber(this.tablesByNumber.values()))
8949
+ });
8950
+ const candidate = Math.max(metadata.nextUserTableNumber, nextUserTableNumber(this.tablesByNumber.values()));
8951
+ const reserved = await this.docstore.writeGlobalIfAbsent(createTableNumberReservationKey(candidate), {
8952
+ fullName,
8953
+ reservedAt: Date.now()
8954
+ });
8955
+ if (!reserved) {
8956
+ await this.reloadTables();
8957
+ const raced = this.tablesByName.get(fullName);
8958
+ if (raced) {
8959
+ return raced.tableNumber;
8960
+ }
8961
+ continue;
8962
+ }
8963
+ const createdAt = Date.now();
8964
+ const info = createTableInfo(tableName, candidate, normalizedComponent, { createdAt, visibility: "public" });
8965
+ const timestamp2 = oracle?.allocateTimestamp?.() ?? BigInt(createdAt);
8966
+ const entry = createTableMetadataEntryForUserTable(info, timestamp2);
8967
+ try {
8968
+ await this.docstore.write([entry], new Set, "Error");
8969
+ } catch {
8970
+ await this.reloadTables();
8971
+ const raced = this.tablesByName.get(fullName);
8972
+ if (raced) {
8973
+ return raced.tableNumber;
8974
+ }
8975
+ throw new Error(`Failed to allocate table number for ${fullName}`);
8976
+ }
8977
+ const registryVersion = Number(timestamp2 > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Date.now()) : timestamp2);
8978
+ await this.docstore.writeGlobal(SYSTEM_METADATA_GLOBAL_KEY, createSystemMetadata({
8979
+ nextUserTableNumber: candidate + 1,
8980
+ registryVersion,
8981
+ bootstrappedAt: metadata.bootstrappedAt,
8982
+ updatedAt: registryVersion
8983
+ }));
8984
+ this.cachedRegistryVersion = registryVersion;
8985
+ this.tablesByName.set(fullName, info);
8986
+ this.tablesByNumber.set(candidate, info);
8987
+ return candidate;
8988
+ }
8989
+ }
8990
+ async getTableInfo(tableNumber) {
8991
+ await this.ensureLoaded();
8992
+ await this.ensureFresh();
8993
+ const existing = this.tablesByNumber.get(tableNumber);
8994
+ if (existing) {
8995
+ return existing;
8996
+ }
8997
+ await this.reloadTables();
8998
+ return this.tablesByNumber.get(tableNumber) ?? null;
8999
+ }
9000
+ async getTableInfoByName(tableName, componentPath = "") {
9001
+ await this.ensureLoaded();
9002
+ await this.ensureFresh();
9003
+ const fullName = getFullTableName(tableName, isSystemTable(tableName) ? "" : componentPath);
9004
+ const existing = this.tablesByName.get(fullName);
9005
+ if (existing) {
9006
+ return existing;
9007
+ }
9008
+ await this.reloadTables();
9009
+ return this.tablesByName.get(fullName) ?? null;
9010
+ }
9011
+ async listTables(componentPath) {
9012
+ await this.ensureLoaded();
9013
+ await this.ensureFresh();
9014
+ const values = Array.from(this.tablesByNumber.values());
9015
+ if (componentPath === undefined) {
9016
+ return values.sort((a, b) => a.tableNumber - b.tableNumber);
9017
+ }
9018
+ return values.filter((table) => table.componentPath === componentPath).sort((a, b) => a.tableNumber - b.tableNumber);
9019
+ }
9020
+ async hasAccess(tableNumber, componentPath) {
9021
+ const info = await this.getTableInfo(tableNumber);
9022
+ if (!info) {
9023
+ return false;
9024
+ }
9025
+ if (info.isSystem) {
9026
+ return true;
9027
+ }
9028
+ return info.componentPath === componentPath;
9029
+ }
9030
+ getSystemTableNumber(systemTableName) {
9031
+ return SYSTEM_TABLE_NUMBERS[systemTableName];
9032
+ }
9033
+ async ensureLoaded() {
9034
+ if (!this.loadPromise) {
9035
+ this.loadPromise = this.loadTables();
9036
+ }
9037
+ await this.loadPromise;
9038
+ }
9039
+ async ensureFresh() {
9040
+ const metadata = await readSystemMetadata(this.docstore);
9041
+ if (!metadata) {
9042
+ if (this.cachedRegistryVersion !== 0 || this.tablesByName.size > 0 || this.tablesByNumber.size > 0) {
9043
+ await this.reloadTables();
9044
+ }
9045
+ return;
9046
+ }
9047
+ if (metadata.registryVersion > this.cachedRegistryVersion) {
9048
+ await this.reloadTables();
9049
+ }
9050
+ }
9051
+ async reloadTables() {
9052
+ this.loadPromise = this.loadTables();
9053
+ await this.loadPromise;
9054
+ }
9055
+ async loadTables() {
9056
+ await ensureSystemTablesBootstrapped(this.docstore);
9057
+ const docs = await this.docstore.scan(stringToHex("_tables"));
9058
+ this.tablesByName.clear();
9059
+ this.tablesByNumber.clear();
9060
+ for (const doc of docs) {
9061
+ const info = tableInfoFromStoredDocument(doc.value.value);
9062
+ if (!info) {
9063
+ continue;
9064
+ }
9065
+ this.tablesByName.set(info.fullName, info);
9066
+ this.tablesByNumber.set(info.tableNumber, info);
9067
+ }
9068
+ if (this.tablesByNumber.size === 0) {
9069
+ for (const [name, tableNumber] of Object.entries(SYSTEM_TABLE_NUMBERS)) {
9070
+ const info = createTableInfo(name, tableNumber, "", { isSystem: true });
9071
+ this.tablesByName.set(info.fullName, info);
9072
+ this.tablesByNumber.set(info.tableNumber, info);
9073
+ }
9074
+ }
9075
+ const metadata = await readSystemMetadata(this.docstore);
9076
+ if (!metadata) {
9077
+ const now = Date.now();
9078
+ this.cachedRegistryVersion = now;
9079
+ await this.docstore.writeGlobal(SYSTEM_METADATA_GLOBAL_KEY, createSystemMetadata({
9080
+ nextUserTableNumber: Math.max(FIRST_USER_TABLE_NUMBER, nextUserTableNumber(this.tablesByNumber.values())),
9081
+ registryVersion: now,
9082
+ bootstrappedAt: now,
9083
+ updatedAt: now
9084
+ }));
9085
+ } else {
9086
+ this.cachedRegistryVersion = metadata.registryVersion;
9087
+ }
9088
+ }
9089
+ }
9090
+
9091
+ // ../core/dist/tables/transactional-table-registry.js
9092
+ init_system_tables();
9093
+ init_utils();
9094
+ init_interface();
8561
9095
  // ../core/dist/kernel/contexts.js
8562
9096
  init_context_storage();
8563
- var snapshotContext = new ContextStorage;
8564
- var transactionContext = new ContextStorage;
8565
- var idGeneratorContext = new ContextStorage;
9097
+ var SNAPSHOT_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/snapshot-context");
9098
+ var TRANSACTION_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/transaction-context");
9099
+ var ID_GENERATOR_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/id-generator-context");
9100
+ var globalContexts = globalThis;
9101
+ var snapshotContext = globalContexts[SNAPSHOT_CONTEXT_SYMBOL] ?? new ContextStorage;
9102
+ var transactionContext = globalContexts[TRANSACTION_CONTEXT_SYMBOL] ?? new ContextStorage;
9103
+ var idGeneratorContext = globalContexts[ID_GENERATOR_CONTEXT_SYMBOL] ?? new ContextStorage;
9104
+ if (!globalContexts[SNAPSHOT_CONTEXT_SYMBOL]) {
9105
+ globalContexts[SNAPSHOT_CONTEXT_SYMBOL] = snapshotContext;
9106
+ }
9107
+ if (!globalContexts[TRANSACTION_CONTEXT_SYMBOL]) {
9108
+ globalContexts[TRANSACTION_CONTEXT_SYMBOL] = transactionContext;
9109
+ }
9110
+ if (!globalContexts[ID_GENERATOR_CONTEXT_SYMBOL]) {
9111
+ globalContexts[ID_GENERATOR_CONTEXT_SYMBOL] = idGeneratorContext;
9112
+ }
8566
9113
  // ../core/dist/queryengine/convex-ops.js
8567
9114
  var debug = () => {};
8568
9115
  class CfConvex {
@@ -8615,6 +9162,8 @@ class BaseSqliteDocStore {
8615
9162
  vectorIndexesByTable = new Map;
8616
9163
  fts5Available = true;
8617
9164
  statementCache = new Map;
9165
+ configuredSearchIndexes = [];
9166
+ configuredVectorIndexes = [];
8618
9167
  constructor(adapter) {
8619
9168
  this.adapter = adapter;
8620
9169
  this.timestampOracle = new TimestampOracle;
@@ -8629,6 +9178,8 @@ class BaseSqliteDocStore {
8629
9178
  return statement;
8630
9179
  }
8631
9180
  async setupSchema(options) {
9181
+ this.configuredSearchIndexes = [...options?.searchIndexes ?? []];
9182
+ this.configuredVectorIndexes = [...options?.vectorIndexes ?? []];
8632
9183
  await this.adapter.exec(DOCUMENTS_TABLE_SCHEMA);
8633
9184
  await this.adapter.exec(DOCUMENTS_BY_TABLE_INDEX);
8634
9185
  await this.adapter.exec(INDEXES_TABLE_SCHEMA);
@@ -8636,6 +9187,24 @@ class BaseSqliteDocStore {
8636
9187
  await this.setupSearchIndexes(options?.searchIndexes ?? []);
8637
9188
  await this.setupVectorIndexes(options?.vectorIndexes ?? []);
8638
9189
  }
9190
+ async resetForTesting() {
9191
+ const rows = await this.adapter.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND sql IS NOT NULL").all();
9192
+ for (const row of rows) {
9193
+ const tableName = row?.name;
9194
+ if (typeof tableName !== "string" || tableName.length === 0) {
9195
+ continue;
9196
+ }
9197
+ await this.adapter.exec(`DROP TABLE IF EXISTS ${quoteSqlIdentifier(tableName)}`);
9198
+ }
9199
+ this.statementCache.clear();
9200
+ this.searchIndexesByTable.clear();
9201
+ this.vectorIndexesByTable.clear();
9202
+ this.fts5Available = true;
9203
+ await this.setupSchema({
9204
+ searchIndexes: this.configuredSearchIndexes,
9205
+ vectorIndexes: this.configuredVectorIndexes
9206
+ });
9207
+ }
8639
9208
  async setupSearchIndexes(searchIndexes) {
8640
9209
  try {
8641
9210
  await this.adapter.exec(SEARCH_INDEXES_FTS_SCHEMA);
@@ -8851,6 +9420,15 @@ class BaseSqliteDocStore {
8851
9420
  const stmt = this.getPreparedStatement("INSERT OR REPLACE INTO persistence_globals (key, json_value) VALUES (?, ?)");
8852
9421
  await stmt.run(key, JSON.stringify(value));
8853
9422
  }
9423
+ async writeGlobalIfAbsent(key, value) {
9424
+ const insertStmt = this.getPreparedStatement("INSERT OR IGNORE INTO persistence_globals (key, json_value) VALUES (?, ?)");
9425
+ const changesStmt = this.getPreparedStatement("SELECT changes() as changes");
9426
+ return this.adapter.transaction(async () => {
9427
+ await insertStmt.run(key, JSON.stringify(value));
9428
+ const row = await changesStmt.get();
9429
+ return Number(row?.changes ?? 0) > 0;
9430
+ });
9431
+ }
8854
9432
  async previous_revisions(queries) {
8855
9433
  const results = new Map;
8856
9434
  const stmt = this.getPreparedStatement(`
@@ -9146,6 +9724,9 @@ class BaseSqliteDocStore {
9146
9724
  return scored.slice(0, limit);
9147
9725
  }
9148
9726
  }
9727
+ function quoteSqlIdentifier(value) {
9728
+ return `"${value.replace(/"/g, '""')}"`;
9729
+ }
9149
9730
  // ../docstore-sqlite-base/dist/transaction-runner.js
9150
9731
  function createSerializedTransactionRunner(hooks) {
9151
9732
  let queue = Promise.resolve();