@constructive-io/data 0.9.5 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1076,13 +1076,13 @@ var MetaContractError = class extends Error {
1076
1076
  code;
1077
1077
  compatibility;
1078
1078
  constructor(compatibility) {
1079
- const unavailable = compatibility.status === "unavailable";
1079
+ const unavailable2 = compatibility.status === "unavailable";
1080
1080
  const detail = compatibility.missing.length > 0 ? ` Missing: ${compatibility.missing.join(", ")}.` : "";
1081
1081
  super(
1082
- unavailable ? `This endpoint does not expose Constructive _meta ${compatibility.contractVersion}.${detail}` : `This endpoint must be upgraded to Constructive _meta ${compatibility.contractVersion}.${detail}`
1082
+ unavailable2 ? `This endpoint does not expose Constructive _meta ${compatibility.contractVersion}.${detail}` : `This endpoint must be upgraded to Constructive _meta ${compatibility.contractVersion}.${detail}`
1083
1083
  );
1084
1084
  this.name = "MetaContractError";
1085
- this.code = unavailable ? "META_CONTRACT_UNAVAILABLE" : "META_CONTRACT_INCOMPATIBLE";
1085
+ this.code = unavailable2 ? "META_CONTRACT_UNAVAILABLE" : "META_CONTRACT_INCOMPATIBLE";
1086
1086
  this.compatibility = compatibility;
1087
1087
  }
1088
1088
  };
@@ -1116,6 +1116,1971 @@ function parseMetaSearchWeights(config) {
1116
1116
  }
1117
1117
  }
1118
1118
 
1119
+ // src/table-model/meta-capabilities.ts
1120
+ var META_OPTIONAL_CAPABILITIES = {
1121
+ metaTable: { typeName: "MetaTable", fields: ["kind", "description", "isJunction", "tableName"] },
1122
+ metaField: {
1123
+ typeName: "MetaField",
1124
+ fields: ["allowedValues", "isRequiredOnCreate", "isWritableOnCreate", "isWritableOnUpdate", "isComputed", "file"]
1125
+ },
1126
+ metaType: { typeName: "MetaType", fields: ["maxLength", "precision", "scale"] },
1127
+ metaBelongsTo: { typeName: "MetaBelongsToRelation", fields: ["refKeys"] },
1128
+ metaHas: { typeName: "MetaHasRelation", fields: ["remoteKeys"] },
1129
+ metaStorage: { typeName: "MetaStorage", fields: ["filesType", "bucketsType", "downloadUrlField", "upload"] },
1130
+ metaFileField: { typeName: "MetaFileField", fields: ["kind", "isMultiple", "filesType"] },
1131
+ metaStorageUpload: {
1132
+ typeName: "MetaStorageUpload",
1133
+ fields: ["mutation", "inputType", "payloadType", "bulkMutation", "requiresOwnerId"]
1134
+ }
1135
+ };
1136
+ var capabilityAliases = /* @__PURE__ */ new Map();
1137
+ for (const [alias, { typeName }] of Object.entries(META_CONTRACT_REQUIREMENTS)) capabilityAliases.set(alias, typeName);
1138
+ for (const [alias, { typeName }] of Object.entries(META_OPTIONAL_CAPABILITIES)) capabilityAliases.set(alias, typeName);
1139
+ var META_CAPABILITY_INTROSPECTION_SOURCE = (
1140
+ /* GraphQL */
1141
+ `
1142
+ query ConstructiveMetaContract {
1143
+ ${[...capabilityAliases].map(([alias, typeName]) => `${alias}: __type(name: "${typeName}") { name fields { name } }`).join("\n ")}
1144
+ }
1145
+ `
1146
+ );
1147
+ var META_CAPABILITY_INTROSPECTION_DOCUMENT = new TypedDocumentString(META_CAPABILITY_INTROSPECTION_SOURCE);
1148
+ function fieldNames(type) {
1149
+ return new Set((type?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []));
1150
+ }
1151
+ function emptyMetaCapabilities() {
1152
+ return Object.fromEntries(
1153
+ Object.keys(META_OPTIONAL_CAPABILITIES).map((alias) => [alias, /* @__PURE__ */ new Set()])
1154
+ );
1155
+ }
1156
+ function assessMetaCapabilities(result) {
1157
+ const compatibility = assessMetaContract(result);
1158
+ const capabilities = Object.fromEntries(
1159
+ Object.entries(META_OPTIONAL_CAPABILITIES).map(([alias, requirement]) => {
1160
+ const available = fieldNames(result?.[alias]);
1161
+ const fields = requirement.fields;
1162
+ return [alias, new Set(fields.filter((field2) => available.has(field2)))];
1163
+ })
1164
+ );
1165
+ return { compatibility, capabilities };
1166
+ }
1167
+ function has(capabilities, alias, field2) {
1168
+ return capabilities[alias].has(field2);
1169
+ }
1170
+ function present(capabilities, alias, fields) {
1171
+ return fields.filter((field2) => has(capabilities, alias, field2)).join(" ");
1172
+ }
1173
+ function fileSelection(capabilities) {
1174
+ if (!has(capabilities, "metaField", "file") || !has(capabilities, "metaFileField", "kind")) return "";
1175
+ return `file { ${present(capabilities, "metaFileField", ["kind", "isMultiple", "filesType"])} }`;
1176
+ }
1177
+ function uploadSelection(capabilities) {
1178
+ if (!has(capabilities, "metaStorage", "upload")) return "";
1179
+ const fields = present(capabilities, "metaStorageUpload", [
1180
+ "mutation",
1181
+ "inputType",
1182
+ "payloadType",
1183
+ "bulkMutation",
1184
+ "requiresOwnerId"
1185
+ ]);
1186
+ return fields ? `upload { ${fields} }` : "";
1187
+ }
1188
+ function buildMetaQuerySource(capabilities = emptyMetaCapabilities()) {
1189
+ const tableExtras = present(capabilities, "metaTable", ["kind", "description", "isJunction", "tableName"]);
1190
+ const typeExtras = present(capabilities, "metaType", ["maxLength", "precision", "scale"]);
1191
+ const tableFieldExtras = [
1192
+ present(capabilities, "metaField", [
1193
+ "allowedValues",
1194
+ "isRequiredOnCreate",
1195
+ "isWritableOnCreate",
1196
+ "isWritableOnUpdate",
1197
+ "isComputed"
1198
+ ]),
1199
+ fileSelection(capabilities)
1200
+ ].filter(Boolean).join(" ");
1201
+ const refKeys = has(capabilities, "metaBelongsTo", "refKeys") ? "refKeys { ...ConstructiveMetaField }" : "";
1202
+ const remoteKeys = has(capabilities, "metaHas", "remoteKeys") ? "remoteKeys { ...ConstructiveMetaField }" : "";
1203
+ const storageExtras = [
1204
+ present(capabilities, "metaStorage", ["filesType", "bucketsType", "downloadUrlField"]),
1205
+ uploadSelection(capabilities)
1206
+ ].filter(Boolean).join(" ");
1207
+ const hasRelation = (name) => (
1208
+ /* GraphQL */
1209
+ `
1210
+ ${name} {
1211
+ fieldName
1212
+ isUnique
1213
+ type
1214
+ keys { ...ConstructiveMetaField }
1215
+ referencedBy { name }
1216
+ ${remoteKeys}
1217
+ }`
1218
+ );
1219
+ return (
1220
+ /* GraphQL */
1221
+ `
1222
+ query ConstructiveMeta {
1223
+ _meta {
1224
+ tables {
1225
+ name
1226
+ schemaName
1227
+ ${tableExtras}
1228
+ query { all one create update delete }
1229
+ fields { ...ConstructiveMetaTableField }
1230
+ inflection {
1231
+ tableType
1232
+ allRows
1233
+ connection
1234
+ edge
1235
+ filterType
1236
+ orderByType
1237
+ conditionType
1238
+ patchType
1239
+ createInputType
1240
+ createPayloadType
1241
+ updatePayloadType
1242
+ deletePayloadType
1243
+ }
1244
+ indexes {
1245
+ name
1246
+ isUnique
1247
+ isPrimary
1248
+ columns
1249
+ fields { ...ConstructiveMetaField }
1250
+ }
1251
+ constraints {
1252
+ primaryKey { name fields { ...ConstructiveMetaField } }
1253
+ unique { name fields { ...ConstructiveMetaField } }
1254
+ foreignKey { ...ConstructiveMetaForeignKey }
1255
+ }
1256
+ foreignKeyConstraints { ...ConstructiveMetaForeignKey }
1257
+ primaryKeyConstraints { name fields { ...ConstructiveMetaField } }
1258
+ uniqueConstraints { name fields { ...ConstructiveMetaField } }
1259
+ relations {
1260
+ belongsTo {
1261
+ fieldName
1262
+ isUnique
1263
+ type
1264
+ keys { ...ConstructiveMetaField }
1265
+ references { name }
1266
+ ${refKeys}
1267
+ }${hasRelation("has")}${hasRelation("hasOne")}${hasRelation("hasMany")}
1268
+ manyToMany {
1269
+ fieldName
1270
+ type
1271
+ junctionTable { name }
1272
+ junctionLeftConstraint { ...ConstructiveMetaForeignKey }
1273
+ junctionLeftKeyAttributes { ...ConstructiveMetaField }
1274
+ junctionRightConstraint { ...ConstructiveMetaForeignKey }
1275
+ junctionRightKeyAttributes { ...ConstructiveMetaField }
1276
+ leftKeyAttributes { ...ConstructiveMetaField }
1277
+ rightKeyAttributes { ...ConstructiveMetaField }
1278
+ rightTable { name }
1279
+ }
1280
+ }
1281
+ storage { isFilesTable isBucketsTable ${storageExtras} }
1282
+ search {
1283
+ algorithms
1284
+ columns { name algorithm }
1285
+ hasUnifiedSearch
1286
+ config { weights boostRecent boostRecencyField boostRecencyDecay }
1287
+ }
1288
+ i18n { translationTable translatableFields { name type } }
1289
+ realtime { subscriptionFieldName }
1290
+ scope { scope tier keyColumn entityTable source }
1291
+ }
1292
+ }
1293
+ }
1294
+
1295
+ fragment ConstructiveMetaType on MetaType {
1296
+ pgType
1297
+ gqlType
1298
+ isArray
1299
+ isNotNull
1300
+ hasDefault
1301
+ subtype
1302
+ encoding {
1303
+ kind
1304
+ elementType
1305
+ dimensions
1306
+ geometrySubtype
1307
+ srid
1308
+ dotPath
1309
+ }
1310
+ ${typeExtras}
1311
+ }
1312
+
1313
+ fragment ConstructiveMetaField on MetaField {
1314
+ name
1315
+ type { ...ConstructiveMetaType }
1316
+ isNotNull
1317
+ hasDefault
1318
+ isPrimaryKey
1319
+ isForeignKey
1320
+ description
1321
+ enumValues { name values }
1322
+ }
1323
+
1324
+ fragment ConstructiveMetaTableField on MetaField {
1325
+ ...ConstructiveMetaField
1326
+ ${tableFieldExtras}
1327
+ }
1328
+
1329
+ fragment ConstructiveMetaForeignKey on MetaForeignKeyConstraint {
1330
+ name
1331
+ fields { ...ConstructiveMetaField }
1332
+ referencedTable
1333
+ referencedFields
1334
+ refFields { ...ConstructiveMetaField }
1335
+ refTable { name }
1336
+ }
1337
+ `
1338
+ );
1339
+ }
1340
+ function buildMetaDocument(capabilities = emptyMetaCapabilities()) {
1341
+ return new TypedDocumentString(buildMetaQuerySource(capabilities));
1342
+ }
1343
+
1344
+ // src/table-model/schema-introspection.ts
1345
+ var TYPE_REF_SELECTION = "kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } }";
1346
+ var NAMED_TYPE_FRAGMENT = (
1347
+ /* GraphQL */
1348
+ `
1349
+ fragment ConstructiveTypeRef on __Type { ${TYPE_REF_SELECTION} }
1350
+ fragment ConstructiveNamedType on __Type {
1351
+ kind
1352
+ name
1353
+ fields(includeDeprecated: true) {
1354
+ name
1355
+ args { name defaultValue type { ...ConstructiveTypeRef } }
1356
+ type { ...ConstructiveTypeRef }
1357
+ }
1358
+ inputFields { name defaultValue type { ...ConstructiveTypeRef } }
1359
+ enumValues(includeDeprecated: true) { name }
1360
+ }
1361
+ `
1362
+ );
1363
+ var SCHEMA_ROOTS_SOURCE = (
1364
+ /* GraphQL */
1365
+ `
1366
+ query ConstructiveSchemaRoots {
1367
+ __schema {
1368
+ queryType { ...ConstructiveNamedType }
1369
+ mutationType { ...ConstructiveNamedType }
1370
+ }
1371
+ }
1372
+ ${NAMED_TYPE_FRAGMENT}
1373
+ `
1374
+ );
1375
+ var TYPE_BATCH_SIZE = 80;
1376
+ function buildSchemaTypesSource(count) {
1377
+ const variables = Array.from({ length: count }, (_, index) => `$n${index}: String!`).join(", ");
1378
+ const lookups = Array.from(
1379
+ { length: count },
1380
+ (_, index) => `t${index}: __type(name: $n${index}) { ...ConstructiveNamedType }`
1381
+ ).join("\n ");
1382
+ return (
1383
+ /* GraphQL */
1384
+ `
1385
+ query ConstructiveSchemaTypes(${variables}) {
1386
+ ${lookups}
1387
+ }
1388
+ ${NAMED_TYPE_FRAGMENT}
1389
+ `
1390
+ );
1391
+ }
1392
+ function namedTypeOf(ref) {
1393
+ let current = ref ?? null;
1394
+ while (current && (current.kind === "NON_NULL" || current.kind === "LIST")) current = current.ofType;
1395
+ return current?.name ? { kind: current.kind, name: current.name } : null;
1396
+ }
1397
+ function isListTypeRef(ref) {
1398
+ let current = ref ?? null;
1399
+ while (current) {
1400
+ if (current.kind === "LIST") return true;
1401
+ current = current.ofType;
1402
+ }
1403
+ return false;
1404
+ }
1405
+ function isNonNullTypeRef(ref) {
1406
+ return ref?.kind === "NON_NULL";
1407
+ }
1408
+ function printTypeRef(ref) {
1409
+ if (ref.kind === "NON_NULL") return ref.ofType ? `${printTypeRef(ref.ofType)}!` : "";
1410
+ if (ref.kind === "LIST") return ref.ofType ? `[${printTypeRef(ref.ofType)}]` : "";
1411
+ return ref.name ?? "";
1412
+ }
1413
+ function isRequiredInput(value) {
1414
+ return isNonNullTypeRef(value.type) && value.defaultValue == null;
1415
+ }
1416
+ var GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
1417
+ function createSchemaTypeLoader() {
1418
+ const types = /* @__PURE__ */ new Map();
1419
+ const pending = /* @__PURE__ */ new Map();
1420
+ let roots = null;
1421
+ let rootsPromise = null;
1422
+ const index = {
1423
+ get roots() {
1424
+ return roots;
1425
+ },
1426
+ get(name) {
1427
+ return types.has(name) ? types.get(name) ?? null : void 0;
1428
+ }
1429
+ };
1430
+ function remember(type) {
1431
+ if (type?.name) types.set(type.name, type);
1432
+ }
1433
+ async function fetchBatch(execute2, names2) {
1434
+ const variables = Object.fromEntries(names2.map((name, position) => [`n${position}`, name]));
1435
+ const response = await execute2(buildSchemaTypesSource(names2.length), variables);
1436
+ names2.forEach((name, position) => {
1437
+ const type = response?.[`t${position}`] ?? null;
1438
+ types.set(name, type && type.name === name ? type : null);
1439
+ });
1440
+ }
1441
+ return {
1442
+ index,
1443
+ wasRequested(name) {
1444
+ return types.has(name) || pending.has(name);
1445
+ },
1446
+ loadRoots(execute2) {
1447
+ if (roots) return Promise.resolve(roots);
1448
+ if (rootsPromise) return rootsPromise;
1449
+ const request = execute2(SCHEMA_ROOTS_SOURCE).then((response) => {
1450
+ const loaded = {
1451
+ query: response?.__schema?.queryType ?? null,
1452
+ mutation: response?.__schema?.mutationType ?? null
1453
+ };
1454
+ remember(loaded.query);
1455
+ remember(loaded.mutation);
1456
+ roots = loaded;
1457
+ return loaded;
1458
+ });
1459
+ rootsPromise = request;
1460
+ request.catch(() => {
1461
+ if (rootsPromise === request) rootsPromise = null;
1462
+ });
1463
+ return request;
1464
+ },
1465
+ async loadTypes(execute2, names2) {
1466
+ const wanted = [...new Set(names2)].filter((name) => GRAPHQL_NAME.test(name));
1467
+ const fresh = wanted.filter((name) => !types.has(name) && !pending.has(name));
1468
+ const inFlight = wanted.flatMap((name) => {
1469
+ const promise = pending.get(name);
1470
+ return promise ? [promise] : [];
1471
+ });
1472
+ const batches = [];
1473
+ for (let start = 0; start < fresh.length; start += TYPE_BATCH_SIZE) {
1474
+ const batch = fresh.slice(start, start + TYPE_BATCH_SIZE);
1475
+ const request = fetchBatch(execute2, batch).finally(() => {
1476
+ for (const name of batch) if (pending.get(name) === request) pending.delete(name);
1477
+ });
1478
+ for (const name of batch) pending.set(name, request);
1479
+ batches.push(request);
1480
+ }
1481
+ await Promise.all([...batches, ...inFlight]);
1482
+ }
1483
+ };
1484
+ }
1485
+
1486
+ // src/table-model/table-key.ts
1487
+ var TableModelError = class extends Error {
1488
+ code;
1489
+ /** The table the error concerns, when known. */
1490
+ tableKey;
1491
+ /** Table keys that matched an ambiguous name. */
1492
+ candidates;
1493
+ constructor(code, message, options = {}) {
1494
+ super(message);
1495
+ this.name = "TableModelError";
1496
+ this.code = code;
1497
+ this.tableKey = options.tableKey ?? null;
1498
+ this.candidates = options.candidates ?? [];
1499
+ }
1500
+ };
1501
+ function tableKeyOf(table) {
1502
+ return `${table.schemaName ?? ""}.${table.name}`;
1503
+ }
1504
+ function metaTablesOf(meta) {
1505
+ return (meta?._meta?.tables ?? []).filter((table) => Boolean(table?.name));
1506
+ }
1507
+ function findMetaTable(tables, ref) {
1508
+ const byKey = tables.find((table) => tableKeyOf(table) === ref);
1509
+ if (byKey) return byKey;
1510
+ const byName = tables.filter((table) => table.name === ref);
1511
+ if (byName.length === 1) return byName[0];
1512
+ if (byName.length > 1) {
1513
+ const candidates = byName.map(tableKeyOf);
1514
+ throw new TableModelError(
1515
+ "TABLE_AMBIGUOUS",
1516
+ `More than one table is called "${ref}". Choose one of: ${candidates.join(", ")}.`,
1517
+ { candidates }
1518
+ );
1519
+ }
1520
+ throw new TableModelError("TABLE_NOT_FOUND", `There is no table called "${ref}".`);
1521
+ }
1522
+ function tableKeyForName(tables, name) {
1523
+ if (!name) return null;
1524
+ const matches = tables.filter((table) => table.name === name);
1525
+ return matches.length === 1 ? tableKeyOf(matches[0]) : null;
1526
+ }
1527
+
1528
+ // src/row-identity.ts
1529
+ function primaryKeyColumnNames(table) {
1530
+ const constraints = table.constraints;
1531
+ if (constraints && !Array.isArray(constraints)) {
1532
+ const names2 = (constraints.primaryKey?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1533
+ if (names2.length > 0) return [...new Set(names2)];
1534
+ }
1535
+ for (const constraint of table.primaryKeyConstraints ?? []) {
1536
+ const names2 = (constraint?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1537
+ if (names2.length > 0) return [...new Set(names2)];
1538
+ }
1539
+ return [...new Set(
1540
+ (table.fields ?? []).flatMap((field2) => field2?.isPrimaryKey && field2.name ? [field2.name] : [])
1541
+ )];
1542
+ }
1543
+ function isRowIdentityValue(value) {
1544
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1545
+ if (typeof value === "number") return Number.isFinite(value);
1546
+ if (Array.isArray(value)) return value.every(isRowIdentityValue);
1547
+ if (typeof value !== "object" || value === null) return false;
1548
+ const prototype = Object.getPrototypeOf(value);
1549
+ if (prototype !== Object.prototype && prototype !== null) return false;
1550
+ return Object.values(value).every(isRowIdentityValue);
1551
+ }
1552
+ function sortIdentityValue(value) {
1553
+ if (Array.isArray(value)) return value.map(sortIdentityValue);
1554
+ if (typeof value !== "object" || value === null) return value;
1555
+ return Object.fromEntries(
1556
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortIdentityValue(item)])
1557
+ );
1558
+ }
1559
+ function getRowIdentityDefinition(table) {
1560
+ const schemaName = table.schemaName ?? null;
1561
+ const columnNames = primaryKeyColumnNames(table);
1562
+ if (columnNames.length === 0) {
1563
+ return {
1564
+ status: "read-only",
1565
+ schemaName,
1566
+ tableName: table.name,
1567
+ reason: "no-primary-key"
1568
+ };
1569
+ }
1570
+ return {
1571
+ status: "keyed",
1572
+ schemaName,
1573
+ tableName: table.name,
1574
+ fields: columnNames.map((columnName) => ({
1575
+ columnName,
1576
+ // `_meta` exposes GraphQL field names here (already inflected), so using
1577
+ // them verbatim also handles custom/renamed primary keys.
1578
+ fieldName: columnName
1579
+ }))
1580
+ };
1581
+ }
1582
+ function resolveRowIdentity(table, row) {
1583
+ const definition = getRowIdentityDefinition(table);
1584
+ if (definition.status === "read-only") return definition;
1585
+ const missingFields = [];
1586
+ const invalidFields = [];
1587
+ const fields = [];
1588
+ for (const field2 of definition.fields) {
1589
+ if (!Object.prototype.hasOwnProperty.call(row, field2.fieldName)) {
1590
+ missingFields.push(field2.fieldName);
1591
+ continue;
1592
+ }
1593
+ const value = row[field2.fieldName];
1594
+ if (value === null || !isRowIdentityValue(value)) {
1595
+ invalidFields.push(field2.fieldName);
1596
+ continue;
1597
+ }
1598
+ fields.push({ ...field2, value });
1599
+ }
1600
+ if (missingFields.length > 0 || invalidFields.length > 0) {
1601
+ return {
1602
+ status: "invalid-row",
1603
+ schemaName: definition.schemaName,
1604
+ tableName: definition.tableName,
1605
+ missingFields,
1606
+ invalidFields
1607
+ };
1608
+ }
1609
+ return {
1610
+ status: "identified",
1611
+ identity: {
1612
+ schemaName: definition.schemaName,
1613
+ tableName: definition.tableName,
1614
+ fields
1615
+ }
1616
+ };
1617
+ }
1618
+ function serializeRowIdentity(identity) {
1619
+ return JSON.stringify([
1620
+ identity.schemaName,
1621
+ identity.tableName,
1622
+ identity.fields.map((field2) => [
1623
+ field2.columnName,
1624
+ field2.fieldName,
1625
+ sortIdentityValue(field2.value)
1626
+ ])
1627
+ ]);
1628
+ }
1629
+ function rowIdentityToPrimaryKey(identity) {
1630
+ return Object.fromEntries(
1631
+ identity.fields.map((field2) => [field2.fieldName, field2.value])
1632
+ );
1633
+ }
1634
+ function assessTableWriteCapability(table) {
1635
+ const definition = getRowIdentityDefinition(table);
1636
+ if (definition.status === "read-only") return definition;
1637
+ return {
1638
+ status: "mutable",
1639
+ primaryKeyFields: definition.fields.map((field2) => field2.fieldName),
1640
+ operations: {
1641
+ create: Boolean(table.query?.create),
1642
+ update: Boolean(table.query?.update),
1643
+ delete: Boolean(table.query?.delete)
1644
+ }
1645
+ };
1646
+ }
1647
+
1648
+ // src/table-model/names.ts
1649
+ function canonicalName(value) {
1650
+ return value.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
1651
+ }
1652
+
1653
+ // src/table-model/selection.ts
1654
+ var MAX_SELECTION_DEPTH = 3;
1655
+ function buildOutputSelection(type, lookup, options = {}, depth = 0) {
1656
+ if (!type || type.kind !== "OBJECT" && type.kind !== "INTERFACE") return null;
1657
+ const parts = type.kind === "INTERFACE" ? ["__typename"] : [];
1658
+ for (const field2 of type.fields ?? []) {
1659
+ if (field2.args.some(isRequiredInput)) continue;
1660
+ const named = namedTypeOf(field2.type);
1661
+ if (!named) continue;
1662
+ if (named.kind === "SCALAR" || named.kind === "ENUM") {
1663
+ parts.push(field2.name);
1664
+ continue;
1665
+ }
1666
+ if (options.leavesOnly || depth + 1 >= MAX_SELECTION_DEPTH) continue;
1667
+ if (named.kind !== "OBJECT" && named.kind !== "INTERFACE") continue;
1668
+ const nested = buildOutputSelection(lookup.type(named.name), lookup, options, depth + 1);
1669
+ if (nested) parts.push(`${field2.name} ${nested}`);
1670
+ }
1671
+ return parts.some((part) => part !== "__typename") ? `{ ${parts.join(" ")} }` : null;
1672
+ }
1673
+
1674
+ // src/table-model/value-kind.ts
1675
+ var KIND_BY_ENCODING = {
1676
+ datetime: "datetime",
1677
+ date: "date",
1678
+ time: "time",
1679
+ interval: "interval",
1680
+ uuid: "uuid",
1681
+ geojson: "geometry",
1682
+ point: "point",
1683
+ inet: "network",
1684
+ ltree: "path",
1685
+ vector: "vector",
1686
+ bytea: "binary",
1687
+ composite: "composite"
1688
+ };
1689
+ var KIND_BY_CODEC = {
1690
+ tsvector: "fulltext",
1691
+ bit: "bitstring",
1692
+ varbit: "bitstring",
1693
+ macaddr: "network",
1694
+ macaddr8: "network",
1695
+ json: "json",
1696
+ jsonb: "json",
1697
+ email: "text",
1698
+ url: "text",
1699
+ hostname: "text",
1700
+ origin: "text"
1701
+ };
1702
+ var KIND_BY_SCALAR = {
1703
+ String: "text",
1704
+ ID: "text",
1705
+ Int: "integer",
1706
+ Float: "float",
1707
+ Boolean: "boolean",
1708
+ UUID: "uuid",
1709
+ JSON: "json",
1710
+ BigInt: "bigint",
1711
+ BigFloat: "decimal",
1712
+ Datetime: "datetime",
1713
+ Date: "date",
1714
+ Time: "time",
1715
+ GeoJSON: "geometry",
1716
+ InternetAddress: "network",
1717
+ CidrAddress: "network",
1718
+ MacAddress: "network",
1719
+ LTree: "path",
1720
+ FullText: "fulltext",
1721
+ BitString: "bitstring",
1722
+ Base64EncodedBinary: "binary"
1723
+ };
1724
+ var SEMANTIC_DOMAINS = /* @__PURE__ */ new Set([
1725
+ "email",
1726
+ "url",
1727
+ "hostname",
1728
+ "origin",
1729
+ "image",
1730
+ "upload",
1731
+ "attachment",
1732
+ "currency"
1733
+ ]);
1734
+ var FILE_DOMAINS = /* @__PURE__ */ new Set(["image", "upload", "attachment"]);
1735
+ function elementCodecName(field2) {
1736
+ const pgType = field2.type.pgType ?? "";
1737
+ return field2.type.isArray && pgType.endsWith("Array") ? pgType.slice(0, -"Array".length) : pgType;
1738
+ }
1739
+ var INTEGER_BOUNDS = {
1740
+ int2: { min: -32768, max: 32767 },
1741
+ int4: { min: -2147483648, max: 2147483647 }
1742
+ };
1743
+ function integerBoundsOf(field2) {
1744
+ return INTEGER_BOUNDS[elementCodecName(field2)] ?? null;
1745
+ }
1746
+ function isRangeType(type, lookup) {
1747
+ if (!type || type.kind !== "OBJECT") return false;
1748
+ const names2 = new Set((type.fields ?? []).map((field2) => field2.name));
1749
+ if (names2.size !== 2 || !names2.has("start") || !names2.has("end")) return false;
1750
+ return ["start", "end"].every((bound) => {
1751
+ const boundType = lookup.typeOf(lookup.field(type, bound)?.type);
1752
+ const boundFields = new Set((boundType?.fields ?? []).map((field2) => field2.name));
1753
+ return boundFields.has("value") && boundFields.has("inclusive");
1754
+ });
1755
+ }
1756
+ function columnFile(field2) {
1757
+ const meta = field2.file;
1758
+ if (meta?.kind && FILE_DOMAINS.has(meta.kind)) {
1759
+ return {
1760
+ kind: meta.kind,
1761
+ multiple: meta.isMultiple ?? field2.type.isArray,
1762
+ filesType: meta.filesType ?? null
1763
+ };
1764
+ }
1765
+ const codec = elementCodecName(field2);
1766
+ if (!FILE_DOMAINS.has(codec)) return null;
1767
+ return { kind: codec, multiple: field2.type.isArray, filesType: null };
1768
+ }
1769
+ function columnSemantic(field2, file) {
1770
+ if (file) return file.kind;
1771
+ const codec = elementCodecName(field2);
1772
+ if (codec === "money") return "currency";
1773
+ return SEMANTIC_DOMAINS.has(codec) ? codec : null;
1774
+ }
1775
+ function columnValueKind(field2, outputType, file, lookup) {
1776
+ if (file) return "file";
1777
+ if (outputType?.kind === "ENUM" || field2.enumValues?.name) return "enum";
1778
+ const encoding = field2.type.encoding?.kind;
1779
+ if (encoding === "bigint") return field2.type.gqlType === "BigFloat" ? "decimal" : "bigint";
1780
+ if (encoding && KIND_BY_ENCODING[encoding]) return KIND_BY_ENCODING[encoding];
1781
+ if (isRangeType(outputType, lookup)) return "range";
1782
+ const codecKind = KIND_BY_CODEC[elementCodecName(field2)];
1783
+ if (codecKind) return codecKind;
1784
+ const scalarName = outputType?.kind === "SCALAR" ? outputType.name : field2.type.gqlType;
1785
+ return KIND_BY_SCALAR[scalarName] ?? "unknown";
1786
+ }
1787
+
1788
+ // src/table-model/build-columns.ts
1789
+ var UNREADABLE = "This field cannot be shown here yet.";
1790
+ var UNSUPPORTED_WRITE = "This kind of value cannot be edited here yet.";
1791
+ var COMPUTED = "This value is calculated automatically.";
1792
+ function sortIndex(orderByType) {
1793
+ const index = /* @__PURE__ */ new Map();
1794
+ for (const { name } of orderByType?.enumValues ?? []) {
1795
+ const match = /^(.*)_(ASC|DESC)$/.exec(name);
1796
+ if (!match) continue;
1797
+ const key = canonicalName(match[1]);
1798
+ const entry = index.get(key) ?? { asc: [], desc: [] };
1799
+ (match[2] === "ASC" ? entry.asc : entry.desc).push(name);
1800
+ index.set(key, entry);
1801
+ }
1802
+ return index;
1803
+ }
1804
+ function columnSort(name, index) {
1805
+ const entry = index.get(canonicalName(name));
1806
+ return entry && entry.asc.length === 1 && entry.desc.length === 1 ? { asc: entry.asc[0], desc: entry.desc[0] } : null;
1807
+ }
1808
+ function columnFilter(name, filterType, lookup) {
1809
+ const field2 = filterType?.inputFields?.find((input) => input.name === name);
1810
+ const named = namedTypeOf(field2?.type);
1811
+ if (!field2 || named?.kind !== "INPUT_OBJECT") return null;
1812
+ const operatorType = lookup.type(named.name);
1813
+ if (!operatorType) return null;
1814
+ const operators = [];
1815
+ for (const operator of operatorType.inputFields ?? []) {
1816
+ const input = lookup.inputValue(operator.type);
1817
+ if (input) operators.push({ name: operator.name, input });
1818
+ }
1819
+ return operators.length > 0 ? { field: field2.name, typeName: named.name, operators } : null;
1820
+ }
1821
+ function prettyEnumLabel(value) {
1822
+ const words = value.replace(/^_+/, "").replace(/_+/g, " ").trim().toLowerCase();
1823
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : value;
1824
+ }
1825
+ function enumOptions(field2, enumType) {
1826
+ const values = (enumType?.enumValues ?? []).map((value) => value.name);
1827
+ if (values.length === 0) return null;
1828
+ const labels = field2.enumValues?.values ?? [];
1829
+ const byPosition = labels.length === values.length;
1830
+ return values.map((value, position) => ({ value, label: byPosition ? labels[position] : prettyEnumLabel(value) }));
1831
+ }
1832
+ function inputField(type, name) {
1833
+ return type?.inputFields?.find((field2) => field2.name === name) ?? null;
1834
+ }
1835
+ function columnWrite(field2, ctx, readable, hasInputShape) {
1836
+ const recordField = inputField(ctx.recordType, field2.name);
1837
+ const patchField = inputField(ctx.patchType, field2.name);
1838
+ const reasonFor = (operationExists, inInput, metaAllows, noOperation, notInInput) => {
1839
+ if (!operationExists) return noOperation;
1840
+ if (field2.isComputed === true) return COMPUTED;
1841
+ if (!inInput || metaAllows === false) return notInInput;
1842
+ if (!readable || !hasInputShape) return UNSUPPORTED_WRITE;
1843
+ return null;
1844
+ };
1845
+ const createReason = reasonFor(
1846
+ Boolean(ctx.operations.create),
1847
+ Boolean(recordField),
1848
+ field2.isWritableOnCreate,
1849
+ "This table does not allow adding records.",
1850
+ "This field is filled in automatically when a record is added."
1851
+ );
1852
+ const updateReason = reasonFor(
1853
+ Boolean(ctx.operations.update),
1854
+ Boolean(patchField),
1855
+ field2.isWritableOnUpdate,
1856
+ "This table does not allow changes.",
1857
+ "This field cannot be changed."
1858
+ );
1859
+ const create = createReason === null;
1860
+ return {
1861
+ create,
1862
+ update: updateReason === null,
1863
+ requiredOnCreate: create && ((recordField ? isRequiredInput(recordField) : false) || field2.isRequiredOnCreate === true),
1864
+ createReason,
1865
+ updateReason
1866
+ };
1867
+ }
1868
+ function buildColumn(field2, ctx, sorts) {
1869
+ const { lookup } = ctx;
1870
+ const rowField = lookup.field(ctx.rowType, field2.name);
1871
+ const named = namedTypeOf(rowField?.type);
1872
+ const isObject2 = named?.kind === "OBJECT" || named?.kind === "INTERFACE";
1873
+ const outputType = !named ? null : named.kind === "SCALAR" ? { kind: "SCALAR", name: named.name, fields: null, inputFields: null, enumValues: null } : lookup.type(named.name);
1874
+ const file = columnFile(field2);
1875
+ const kind = columnValueKind(field2, outputType, file, lookup);
1876
+ const selection = isObject2 ? buildOutputSelection(outputType, lookup, { leavesOnly: kind === "geometry" }) : null;
1877
+ const readReason = !rowField ? "This field is not available through this API." : rowField.args.some(isRequiredInput) || named?.kind === "UNION" || isObject2 && !selection ? UNREADABLE : null;
1878
+ const readable = readReason === null;
1879
+ const inputRef = (inputField(ctx.patchType, field2.name) ?? inputField(ctx.recordType, field2.name))?.type;
1880
+ const input = inputRef ? lookup.inputValue(inputRef) : null;
1881
+ const write = columnWrite(field2, ctx, readable, input !== null);
1882
+ const options = kind === "enum" ? enumOptions(field2, outputType?.kind === "ENUM" ? outputType : null) : field2.allowedValues?.length ? field2.allowedValues.map((value) => ({ value, label: value })) : null;
1883
+ const encoding = field2.type.encoding;
1884
+ return {
1885
+ name: field2.name,
1886
+ description: field2.description ?? null,
1887
+ value: {
1888
+ kind,
1889
+ isArray: field2.type.isArray,
1890
+ typeName: named?.name ?? field2.type.gqlType,
1891
+ semantic: columnSemantic(field2, file),
1892
+ options,
1893
+ selection,
1894
+ input,
1895
+ maxLength: field2.type.maxLength ?? null,
1896
+ precision: field2.type.precision ?? null,
1897
+ scale: field2.type.scale ?? null,
1898
+ integerBounds: kind === "integer" ? integerBoundsOf(field2) : null,
1899
+ dimensions: encoding?.dimensions ?? null,
1900
+ geometrySubtype: encoding?.geometrySubtype ?? field2.type.subtype ?? null,
1901
+ srid: encoding?.srid ?? null,
1902
+ file
1903
+ },
1904
+ nullable: !(field2.isNotNull ?? field2.type.isNotNull ?? false),
1905
+ hasDefault: Boolean(field2.hasDefault ?? field2.type.hasDefault),
1906
+ isPrimaryKey: ctx.primaryKey.includes(field2.name) || field2.isPrimaryKey === true,
1907
+ isForeignKey: field2.isForeignKey === true,
1908
+ readable,
1909
+ readReason,
1910
+ write,
1911
+ sort: readable ? columnSort(field2.name, sorts) : null,
1912
+ filter: readable ? columnFilter(field2.name, ctx.filterType, lookup) : null
1913
+ };
1914
+ }
1915
+ function buildColumns(ctx) {
1916
+ const sorts = sortIndex(ctx.orderByType);
1917
+ return ctx.fields.map((field2) => {
1918
+ const column = buildColumn(field2, ctx, sorts);
1919
+ if (column.readReason) {
1920
+ ctx.issues.push({ scope: "column", target: column.name, code: "COLUMN_UNREADABLE", message: column.readReason });
1921
+ } else if (column.write.updateReason === UNSUPPORTED_WRITE || column.write.createReason === UNSUPPORTED_WRITE) {
1922
+ ctx.issues.push({ scope: "column", target: column.name, code: "COLUMN_UNWRITABLE", message: UNSUPPORTED_WRITE });
1923
+ }
1924
+ return column;
1925
+ });
1926
+ }
1927
+
1928
+ // src/table-model/build-operations.ts
1929
+ var CLIENT_MUTATION_ID = "clientMutationId";
1930
+ var LOGICAL_OPERATORS = ["and", "or", "not"];
1931
+ var PAGE_INFO_FIELDS = ["hasNextPage", "hasPreviousPage", "startCursor", "endCursor"];
1932
+ function argumentModel(value) {
1933
+ const named = namedTypeOf(value.type);
1934
+ return named ? { name: value.name, type: printTypeRef(value.type), typeName: named.name } : null;
1935
+ }
1936
+ function operationIssue(issues, target, code, message) {
1937
+ issues.push({ scope: "operation", target, code, message });
1938
+ }
1939
+ function mutationInput(field2) {
1940
+ if (field2.args.length === 1) return field2.args[0];
1941
+ return field2.args.find((arg) => arg.name === "input") ?? null;
1942
+ }
1943
+ function payloadRowField(lookup, field2, rowTypeName) {
1944
+ const payload = lookup.typeOf(field2.type);
1945
+ const matches = (payload?.fields ?? []).filter(
1946
+ (candidate) => !isListTypeRef(candidate.type) && namedTypeOf(candidate.type)?.name === rowTypeName
1947
+ );
1948
+ return matches.length === 1 ? matches[0].name : null;
1949
+ }
1950
+ function recordFields(inputType) {
1951
+ return (inputType?.inputFields ?? []).filter(
1952
+ (field2) => field2.name !== CLIENT_MUTATION_ID && isNonNullTypeRef(field2.type) && namedTypeOf(field2.type)?.kind === "INPUT_OBJECT"
1953
+ );
1954
+ }
1955
+ function keyArguments(inputType, excluded, primaryKey) {
1956
+ const keys = (inputType?.inputFields ?? []).filter(
1957
+ (field2) => field2.name !== CLIENT_MUTATION_ID && !excluded.has(field2.name) && isNonNullTypeRef(field2.type)
1958
+ );
1959
+ const names2 = new Set(keys.map((field2) => field2.name));
1960
+ if (primaryKey.length === 0 || names2.size !== primaryKey.length) return null;
1961
+ return primaryKey.every((name) => names2.has(name)) ? [...primaryKey] : null;
1962
+ }
1963
+ function createRecordOf(table, roots, lookup) {
1964
+ const name = table.query?.create;
1965
+ const field2 = name ? lookup.field(roots.mutation, name) : null;
1966
+ const input = field2 ? mutationInput(field2) : null;
1967
+ if (!field2 || !input) return null;
1968
+ const records = recordFields(lookup.typeOf(input.type));
1969
+ if (records.length !== 1) return null;
1970
+ return { field: field2, input, recordField: records[0], recordType: lookup.typeOf(records[0].type) };
1971
+ }
1972
+ function buildList(ctx) {
1973
+ const { table, roots, lookup, issues } = ctx;
1974
+ const none = { list: null, filterType: null, orderByType: null };
1975
+ const field2 = table.query?.all ? lookup.field(roots.query, table.query.all) : null;
1976
+ if (!field2) {
1977
+ operationIssue(issues, "list", "LIST_UNAVAILABLE", "This table cannot be read through this API.");
1978
+ return none;
1979
+ }
1980
+ const returned = namedTypeOf(field2.type);
1981
+ let shape = null;
1982
+ let connection = null;
1983
+ if (returned?.name === table.name && isListTypeRef(field2.type)) {
1984
+ shape = "list";
1985
+ } else if (returned?.kind === "OBJECT") {
1986
+ connection = lookup.type(returned.name);
1987
+ const nodes = lookup.field(connection, "nodes");
1988
+ if (namedTypeOf(nodes?.type)?.name === table.name && isListTypeRef(nodes?.type)) shape = "connection";
1989
+ }
1990
+ if (!shape) {
1991
+ operationIssue(issues, "list", "LIST_UNAVAILABLE", "The list of records for this table has an unexpected shape.");
1992
+ return none;
1993
+ }
1994
+ const pageInfoType = lookup.typeOf(lookup.field(connection, "pageInfo")?.type);
1995
+ const pageInfo = PAGE_INFO_FIELDS.every((name) => lookup.field(pageInfoType, name) !== null);
1996
+ const filterArgs = field2.args.filter((arg) => {
1997
+ if (namedTypeOf(arg.type)?.kind !== "INPUT_OBJECT") return false;
1998
+ const inputs = lookup.typeOf(arg.type)?.inputFields ?? [];
1999
+ return inputs.some((input) => LOGICAL_OPERATORS.includes(input.name));
2000
+ });
2001
+ const orderByArgs = field2.args.filter(
2002
+ (arg) => isListTypeRef(arg.type) && namedTypeOf(arg.type)?.kind === "ENUM"
2003
+ );
2004
+ const filterArg = filterArgs.length === 1 ? filterArgs[0] : null;
2005
+ const orderByArg = orderByArgs.length === 1 ? orderByArgs[0] : null;
2006
+ const filterType = filterArg ? lookup.typeOf(filterArg.type) : null;
2007
+ const orderByType = orderByArg ? lookup.typeOf(orderByArg.type) : null;
2008
+ const pagingArg = (name, typeName) => {
2009
+ const arg = field2.args.find((candidate) => candidate.name === name);
2010
+ if (!arg || typeName && namedTypeOf(arg.type)?.name !== typeName) return null;
2011
+ return argumentModel(arg);
2012
+ };
2013
+ const filterFields = new Set((filterType?.inputFields ?? []).map((input) => input.name));
2014
+ return {
2015
+ list: {
2016
+ field: field2.name,
2017
+ shape,
2018
+ filter: filterArg ? argumentModel(filterArg) : null,
2019
+ orderBy: orderByArg ? argumentModel(orderByArg) : null,
2020
+ first: pagingArg("first", "Int"),
2021
+ offset: pagingArg("offset", "Int"),
2022
+ after: shape === "connection" ? pagingArg("after") : null,
2023
+ totalCount: shape === "connection" && Boolean(lookup.field(connection, "totalCount")),
2024
+ pageInfo: shape === "connection" && pageInfo,
2025
+ logicalOperators: LOGICAL_OPERATORS.filter((name) => filterFields.has(name))
2026
+ },
2027
+ filterType,
2028
+ orderByType
2029
+ };
2030
+ }
2031
+ function buildCreate(ctx) {
2032
+ const { table, roots, lookup, issues } = ctx;
2033
+ if (!table.query?.create) {
2034
+ operationIssue(issues, "create", "CREATE_UNAVAILABLE", "New records cannot be added to this table.");
2035
+ return { create: null, recordType: null };
2036
+ }
2037
+ const record = createRecordOf(table, roots, lookup);
2038
+ const argument2 = record ? argumentModel(record.input) : null;
2039
+ const payloadField = record ? payloadRowField(lookup, record.field, table.name) : null;
2040
+ const recordTypeName = record ? namedTypeOf(record.recordField.type)?.name : null;
2041
+ if (!record || !argument2 || !payloadField || !recordTypeName) {
2042
+ operationIssue(
2043
+ issues,
2044
+ "create",
2045
+ "CREATE_UNAVAILABLE",
2046
+ "Adding records is turned off because the add operation for this table has an unexpected shape."
2047
+ );
2048
+ return { create: null, recordType: null };
2049
+ }
2050
+ return {
2051
+ create: {
2052
+ field: record.field.name,
2053
+ input: argument2,
2054
+ recordField: record.recordField.name,
2055
+ recordType: recordTypeName,
2056
+ payloadField
2057
+ },
2058
+ recordType: record.recordType
2059
+ };
2060
+ }
2061
+ function noKeyReason(table, action) {
2062
+ return table.kind === "view" ? `This is a view of other tables, so its records cannot be ${action} here.` : `Records in this table cannot be ${action} because the table has no primary key.`;
2063
+ }
2064
+ function buildUpdate(ctx) {
2065
+ const { table, roots, lookup, issues, primaryKey } = ctx;
2066
+ if (!table.query?.update || primaryKey.length === 0) {
2067
+ operationIssue(
2068
+ issues,
2069
+ "update",
2070
+ "UPDATE_UNAVAILABLE",
2071
+ primaryKey.length === 0 ? noKeyReason(table, "changed") : "Records in this table cannot be changed."
2072
+ );
2073
+ return { update: null, patchType: null };
2074
+ }
2075
+ const field2 = lookup.field(roots.mutation, table.query.update);
2076
+ const input = field2 ? mutationInput(field2) : null;
2077
+ const inputType = input ? lookup.typeOf(input.type) : null;
2078
+ const patches = recordFields(inputType);
2079
+ const patch = patches.length === 1 ? patches[0] : null;
2080
+ const keyArgs = patch ? keyArguments(inputType, /* @__PURE__ */ new Set([patch.name]), primaryKey) : null;
2081
+ const argument2 = input ? argumentModel(input) : null;
2082
+ const payloadField = field2 ? payloadRowField(lookup, field2, table.name) : null;
2083
+ const patchTypeName = patch ? namedTypeOf(patch.type)?.name : null;
2084
+ if (!field2 || !argument2 || !patch || !keyArgs || !payloadField || !patchTypeName) {
2085
+ operationIssue(
2086
+ issues,
2087
+ "update",
2088
+ "UPDATE_UNAVAILABLE",
2089
+ "Changing records is turned off because the update operation for this table does not match its primary key."
2090
+ );
2091
+ return { update: null, patchType: null };
2092
+ }
2093
+ return {
2094
+ update: { field: field2.name, input: argument2, patchField: patch.name, patchType: patchTypeName, keyArgs, payloadField },
2095
+ patchType: lookup.typeOf(patch.type)
2096
+ };
2097
+ }
2098
+ function buildDelete(ctx) {
2099
+ const { table, roots, lookup, issues, primaryKey } = ctx;
2100
+ if (!table.query?.delete || primaryKey.length === 0) {
2101
+ operationIssue(
2102
+ issues,
2103
+ "delete",
2104
+ "DELETE_UNAVAILABLE",
2105
+ primaryKey.length === 0 ? noKeyReason(table, "deleted") : "Records in this table cannot be deleted."
2106
+ );
2107
+ return null;
2108
+ }
2109
+ const field2 = lookup.field(roots.mutation, table.query.delete);
2110
+ const input = field2 ? mutationInput(field2) : null;
2111
+ const keyArgs = input ? keyArguments(lookup.typeOf(input.type), /* @__PURE__ */ new Set(), primaryKey) : null;
2112
+ const argument2 = input ? argumentModel(input) : null;
2113
+ if (!field2 || !argument2 || !keyArgs) {
2114
+ operationIssue(
2115
+ issues,
2116
+ "delete",
2117
+ "DELETE_UNAVAILABLE",
2118
+ "Deleting records is turned off because the delete operation for this table does not match its primary key."
2119
+ );
2120
+ return null;
2121
+ }
2122
+ return { field: field2.name, input: argument2, keyArgs, payloadField: payloadRowField(lookup, field2, table.name) };
2123
+ }
2124
+ function buildOperations(ctx) {
2125
+ const { list, filterType, orderByType } = buildList(ctx);
2126
+ const { create, recordType } = buildCreate(ctx);
2127
+ const { update, patchType } = buildUpdate(ctx);
2128
+ return {
2129
+ operations: { list, create, update, delete: buildDelete(ctx) },
2130
+ recordType,
2131
+ patchType,
2132
+ filterType,
2133
+ orderByType
2134
+ };
2135
+ }
2136
+
2137
+ // src/table-model/display-fields.ts
2138
+ var NAME_FIELDS = [
2139
+ "displayName",
2140
+ "fullName",
2141
+ "name",
2142
+ "title",
2143
+ "label",
2144
+ "preferredName",
2145
+ "nickname",
2146
+ "username",
2147
+ "handle",
2148
+ "email",
2149
+ "firstName",
2150
+ "lastName",
2151
+ "givenName",
2152
+ "familyName",
2153
+ "slug",
2154
+ "code",
2155
+ "phone",
2156
+ "description"
2157
+ ];
2158
+ var NAME_LIKE = /(name|title|label|display)/i;
2159
+ var MAX_DISPLAY_FIELDS = 3;
2160
+ function isTextLike(candidate) {
2161
+ return candidate.isLeaf && !candidate.isArray && candidate.kind === "text";
2162
+ }
2163
+ function overrideFor(overrides, table) {
2164
+ if (!overrides) return null;
2165
+ return overrides[table.key] ?? overrides[table.name] ?? null;
2166
+ }
2167
+ function resolveDisplayFieldsFromCandidates(table, candidates, primaryKey, overrides) {
2168
+ const byName = new Map(candidates.map((candidate) => [candidate.name, candidate]));
2169
+ const hostFields = (overrideFor(overrides, table) ?? []).filter((name) => byName.get(name)?.isLeaf);
2170
+ if (hostFields.length > 0) return { fields: hostFields, source: "host" };
2171
+ const known = NAME_FIELDS.filter((name) => {
2172
+ const candidate = byName.get(name);
2173
+ return candidate ? isTextLike(candidate) : false;
2174
+ });
2175
+ const nameLike = candidates.filter((candidate) => isTextLike(candidate) && NAME_LIKE.test(candidate.name) && !known.includes(candidate.name)).map((candidate) => candidate.name).sort((left, right) => left.length - right.length);
2176
+ const named = [...known, ...nameLike].slice(0, MAX_DISPLAY_FIELDS);
2177
+ if (named.length > 0) return { fields: named, source: "name" };
2178
+ const text = candidates.find(
2179
+ (candidate) => isTextLike(candidate) && !candidate.isPrimaryKey && !candidate.isForeignKey
2180
+ );
2181
+ if (text) return { fields: [text.name], source: "text" };
2182
+ const key = primaryKey.filter((name) => byName.get(name)?.isLeaf);
2183
+ if (key.length > 0) return { fields: key, source: "key" };
2184
+ return { fields: [], source: "none" };
2185
+ }
2186
+ function resolveDisplayFields(table, overrides) {
2187
+ return resolveDisplayFieldsFromCandidates(
2188
+ table,
2189
+ table.columns.map((column) => ({
2190
+ name: column.name,
2191
+ kind: column.value.kind,
2192
+ isArray: column.value.isArray,
2193
+ isLeaf: column.readable && column.value.selection === null,
2194
+ isPrimaryKey: column.isPrimaryKey,
2195
+ isForeignKey: column.isForeignKey
2196
+ })),
2197
+ table.primaryKey,
2198
+ overrides
2199
+ );
2200
+ }
2201
+
2202
+ // src/table-model/build-relations.ts
2203
+ function names(fields) {
2204
+ return (fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
2205
+ }
2206
+ function sameSet(left, right) {
2207
+ const set = new Set(left);
2208
+ return left.length === right.length && right.every((name) => set.has(name));
2209
+ }
2210
+ function foreignKeysOf(table) {
2211
+ const nested = Array.isArray(table.constraints) ? null : table.constraints?.foreignKey;
2212
+ return (nested ?? table.foreignKeyConstraints ?? []).filter(
2213
+ (constraint) => constraint != null
2214
+ );
2215
+ }
2216
+ function fieldOf(table, name) {
2217
+ return table?.fields?.find((field2) => field2?.name === name) ?? null;
2218
+ }
2219
+ function isRequiredField(field2) {
2220
+ return Boolean(field2?.isNotNull ?? field2?.type.isNotNull);
2221
+ }
2222
+ function relationTarget(target, lookup, overrides) {
2223
+ if (!target) return { target: { primaryKey: [], labelFields: [] }, rowType: null };
2224
+ const rowType = lookup.type(target.name);
2225
+ const identity = getRowIdentityDefinition(target);
2226
+ const primaryKey = identity.status === "keyed" ? identity.fields.map((field2) => field2.fieldName) : [];
2227
+ const candidates = (target.fields ?? []).flatMap((field2) => {
2228
+ if (!field2) return [];
2229
+ const rowField = lookup.field(rowType, field2.name);
2230
+ const named = namedTypeOf(rowField?.type);
2231
+ const isLeaf = Boolean(rowField && named && (named.kind === "SCALAR" || named.kind === "ENUM") && !rowField.args.some(isRequiredInput));
2232
+ const outputType = named ? { kind: named.kind, name: named.name, fields: null, inputFields: null, enumValues: null } : null;
2233
+ return [{
2234
+ name: field2.name,
2235
+ kind: columnValueKind(field2, outputType, null, lookup),
2236
+ isArray: field2.type.isArray,
2237
+ isLeaf,
2238
+ isPrimaryKey: primaryKey.includes(field2.name),
2239
+ isForeignKey: field2.isForeignKey === true
2240
+ }];
2241
+ });
2242
+ const leafNames = new Set(candidates.filter((candidate) => candidate.isLeaf).map((candidate) => candidate.name));
2243
+ const display = resolveDisplayFieldsFromCandidates(
2244
+ { key: tableKeyOf(target), name: target.name },
2245
+ candidates,
2246
+ primaryKey,
2247
+ overrides
2248
+ );
2249
+ return {
2250
+ target: {
2251
+ primaryKey: primaryKey.every((name) => leafNames.has(name)) ? primaryKey : [],
2252
+ labelFields: display.fields
2253
+ },
2254
+ rowType
2255
+ };
2256
+ }
2257
+ function fieldShape(field2, targetName, single, lookup) {
2258
+ if (!field2 || field2.args.some(isRequiredInput)) return null;
2259
+ const named = namedTypeOf(field2.type);
2260
+ if (!named) return null;
2261
+ const firstArg = field2.args.find((arg) => arg.name === "first" && namedTypeOf(arg.type)?.name === "Int");
2262
+ if (named.name === targetName) {
2263
+ if (single && !isListTypeRef(field2.type)) return { shape: "object", pageArg: null, hasTotalCount: false };
2264
+ if (!single && isListTypeRef(field2.type)) return { shape: "list", pageArg: firstArg?.name ?? null, hasTotalCount: false };
2265
+ return null;
2266
+ }
2267
+ if (single || named.kind !== "OBJECT") return null;
2268
+ const connection = lookup.type(named.name);
2269
+ const nodes = lookup.field(connection, "nodes");
2270
+ if (namedTypeOf(nodes?.type)?.name !== targetName || !isListTypeRef(nodes?.type)) return null;
2271
+ return { shape: "connection", pageArg: firstArg?.name ?? null, hasTotalCount: Boolean(lookup.field(connection, "totalCount")) };
2272
+ }
2273
+ var LOGICAL_OPERATORS2 = ["and", "or", "not"];
2274
+ function existsFieldFor(filterType, fieldName) {
2275
+ const matches = (filterType.inputFields ?? []).filter(
2276
+ (input) => (input.name === `${fieldName}Exists` || input.name === `${fieldName}Exist`) && !isListTypeRef(input.type) && namedTypeOf(input.type)?.name === "Boolean"
2277
+ );
2278
+ return matches.length === 1 ? matches[0].name : null;
2279
+ }
2280
+ function relationFilter(filterType, fieldName, single, lookup) {
2281
+ const field2 = filterType?.inputFields?.find((input2) => input2.name === fieldName);
2282
+ const named = namedTypeOf(field2?.type);
2283
+ if (!filterType || !field2 || named?.kind !== "INPUT_OBJECT" || isListTypeRef(field2.type)) return null;
2284
+ const input = lookup.type(named.name);
2285
+ if (!input) return null;
2286
+ const inputFields = input.inputFields ?? [];
2287
+ const exists = existsFieldFor(filterType, fieldName);
2288
+ if (single) {
2289
+ if (!inputFields.some((inputField2) => LOGICAL_OPERATORS2.includes(inputField2.name))) return null;
2290
+ return { field: field2.name, typeName: named.name, exists, many: null, recordFilterType: named.name };
2291
+ }
2292
+ const quantifier = (name) => {
2293
+ const inputField2 = inputFields.find((candidate) => candidate.name === name);
2294
+ return inputField2 && namedTypeOf(inputField2.type)?.kind === "INPUT_OBJECT" ? inputField2 : null;
2295
+ };
2296
+ const many = { some: quantifier("some"), every: quantifier("every"), none: quantifier("none") };
2297
+ const present2 = Object.values(many).filter((inputField2) => inputField2 !== null);
2298
+ if (present2.length === 0) return null;
2299
+ const targets = new Set(present2.map((inputField2) => namedTypeOf(inputField2.type)?.name));
2300
+ const [recordFilterType] = [...targets];
2301
+ return {
2302
+ field: field2.name,
2303
+ typeName: named.name,
2304
+ exists,
2305
+ many: { some: many.some?.name ?? null, every: many.every?.name ?? null, none: many.none?.name ?? null },
2306
+ recordFilterType: targets.size === 1 && recordFilterType ? recordFilterType : null
2307
+ };
2308
+ }
2309
+ function allFieldsOf(table, fieldNames2) {
2310
+ return Boolean(table) && fieldNames2.every((name) => fieldOf(table, name) !== null);
2311
+ }
2312
+ function belongsToKeys(table, relation, referenced) {
2313
+ const local = names(relation.keys);
2314
+ if (local.length === 0) return null;
2315
+ const refKeys = names(relation.refKeys);
2316
+ if (refKeys.length > 0) {
2317
+ return refKeys.length === local.length && allFieldsOf(referenced, refKeys) ? local.map((name, position) => ({ local: name, remote: refKeys[position] })) : null;
2318
+ }
2319
+ const constraints = foreignKeysOf(table).filter((constraint2) => sameSet(names(constraint2.fields), local));
2320
+ if (constraints.length !== 1) return null;
2321
+ const constraint = constraints[0];
2322
+ const constraintLocal = names(constraint.fields);
2323
+ const constraintRemote = names(constraint.refFields).length > 0 ? names(constraint.refFields) : constraint.referencedFields ?? [];
2324
+ if (constraintRemote.length !== constraintLocal.length) return null;
2325
+ return local.map((name) => ({ local: name, remote: constraintRemote[constraintLocal.indexOf(name)] }));
2326
+ }
2327
+ function hasKeys(table, relation, related) {
2328
+ const local = names(relation.keys);
2329
+ const remoteKeys = names(relation.remoteKeys);
2330
+ if (local.length > 0 && remoteKeys.length > 0) {
2331
+ return remoteKeys.length === local.length && allFieldsOf(related, remoteKeys) ? { keys: local.map((name, position) => ({ local: name, remote: remoteKeys[position] })) } : { problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } };
2332
+ }
2333
+ if (!related || local.length === 0) {
2334
+ return { problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } };
2335
+ }
2336
+ const linksHere = [...table.relations?.hasOne ?? [], ...table.relations?.hasMany ?? []].filter(
2337
+ (candidate) => candidate?.referencedBy?.name === related.name
2338
+ );
2339
+ const backLinks = (related.relations?.belongsTo ?? []).filter(
2340
+ (candidate) => candidate?.references?.name === table.name
2341
+ );
2342
+ if (linksHere.length !== 1 || backLinks.length !== 1) {
2343
+ return {
2344
+ problem: {
2345
+ code: "RELATION_AMBIGUOUS",
2346
+ message: "More than one link connects these tables, so this field is read-only."
2347
+ }
2348
+ };
2349
+ }
2350
+ const pairs = belongsToKeys(related, backLinks[0], table);
2351
+ if (!pairs || !sameSet(pairs.map((pair) => pair.remote), local)) {
2352
+ return { problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } };
2353
+ }
2354
+ return { keys: local.map((name) => ({ local: name, remote: pairs.find((pair) => pair.remote === name).local })) };
2355
+ }
2356
+ function junctionModel(relation, ctx) {
2357
+ const junctionMeta = ctx.tables.find((candidate) => candidate.name === relation.junctionTable?.name);
2358
+ const leftJunction = names(relation.junctionLeftKeyAttributes);
2359
+ const leftLocal = names(relation.leftKeyAttributes);
2360
+ const rightJunction = names(relation.junctionRightKeyAttributes);
2361
+ const rightRemote = names(relation.rightKeyAttributes);
2362
+ const incomplete = {
2363
+ junction: null,
2364
+ problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." },
2365
+ unlinkProblem: "Links for this field cannot be removed here."
2366
+ };
2367
+ if (!junctionMeta || leftJunction.length === 0 || leftJunction.length !== leftLocal.length || rightJunction.length === 0 || rightJunction.length !== rightRemote.length) {
2368
+ return incomplete;
2369
+ }
2370
+ const keyFields = /* @__PURE__ */ new Set([...leftJunction, ...rightJunction]);
2371
+ const record = createRecordOf(junctionMeta, ctx.roots, ctx.lookup);
2372
+ const extraRequiredFields = record?.recordType ? (record.recordType.inputFields ?? []).filter((field2) => !keyFields.has(field2.name) && isRequiredInput(field2)).map((field2) => field2.name) : (junctionMeta.fields ?? []).flatMap((field2) => {
2373
+ if (!field2 || keyFields.has(field2.name)) return [];
2374
+ const required = field2.isRequiredOnCreate ?? (isRequiredField(field2) && !(field2.hasDefault ?? field2.type.hasDefault));
2375
+ return required ? [field2.name] : [];
2376
+ });
2377
+ const canCreate = Boolean(record?.recordType);
2378
+ const pure = canCreate && extraRequiredFields.length === 0;
2379
+ const canDelete = Boolean(junctionMeta.query?.delete && ctx.lookup.field(ctx.roots.mutation, junctionMeta.query.delete));
2380
+ return {
2381
+ junction: {
2382
+ tableKey: tableKeyOf(junctionMeta),
2383
+ tableName: junctionMeta.name,
2384
+ left: leftJunction.map((junction, position) => ({ junction, local: leftLocal[position] })),
2385
+ right: rightJunction.map((junction, position) => ({ junction, remote: rightRemote[position] })),
2386
+ pure,
2387
+ extraRequiredFields
2388
+ },
2389
+ problem: !canCreate ? { code: "RELATION_INCOMPLETE", message: "Links for this field cannot be added on this API." } : !pure ? {
2390
+ code: "RELATION_INCOMPLETE",
2391
+ message: `Adding a link needs more information (${extraRequiredFields.join(", ")}), so this field is read-only.`
2392
+ } : null,
2393
+ unlinkProblem: canDelete ? null : "Links for this field cannot be removed here."
2394
+ };
2395
+ }
2396
+ function draftRelations(ctx) {
2397
+ const { table, tables } = ctx;
2398
+ const relations = table.relations;
2399
+ const drafts = [];
2400
+ const findTable = (name) => tables.find((candidate) => candidate.name === name);
2401
+ for (const relation of relations?.belongsTo ?? []) {
2402
+ if (!relation?.fieldName) continue;
2403
+ const keys = belongsToKeys(table, relation, findTable(relation.references.name));
2404
+ const nullable = (keys ?? []).every((pair) => !isRequiredField(fieldOf(table, pair.local)));
2405
+ drafts.push({
2406
+ kind: "belongsTo",
2407
+ fieldName: relation.fieldName,
2408
+ targetName: relation.references.name,
2409
+ keys: keys ?? [],
2410
+ junction: null,
2411
+ keyProblem: keys ? null : { code: "RELATION_INCOMPLETE", message: "The linked record for this field cannot be identified." },
2412
+ unlinkProblem: nullable ? null : "This link is required, so it cannot be removed."
2413
+ });
2414
+ }
2415
+ for (const [kind, list] of [["hasOne", relations?.hasOne], ["hasMany", relations?.hasMany]]) {
2416
+ for (const relation of list ?? []) {
2417
+ if (!relation?.fieldName) continue;
2418
+ const related = findTable(relation.referencedBy.name);
2419
+ const resolved = hasKeys(table, relation, related);
2420
+ const keys = "keys" in resolved ? resolved.keys : [];
2421
+ const nullable = keys.every((pair) => !isRequiredField(fieldOf(related, pair.remote)));
2422
+ drafts.push({
2423
+ kind,
2424
+ fieldName: relation.fieldName,
2425
+ targetName: relation.referencedBy.name,
2426
+ keys,
2427
+ junction: null,
2428
+ keyProblem: "problem" in resolved ? resolved.problem : null,
2429
+ unlinkProblem: nullable ? null : "Each linked record must keep this link, so it cannot be removed."
2430
+ });
2431
+ }
2432
+ }
2433
+ for (const relation of relations?.manyToMany ?? []) {
2434
+ if (!relation?.fieldName) continue;
2435
+ const { junction, problem, unlinkProblem } = junctionModel(relation, ctx);
2436
+ drafts.push({
2437
+ kind: "manyToMany",
2438
+ fieldName: relation.fieldName,
2439
+ targetName: relation.rightTable.name,
2440
+ keys: [],
2441
+ junction,
2442
+ keyProblem: problem,
2443
+ unlinkProblem
2444
+ });
2445
+ }
2446
+ return drafts;
2447
+ }
2448
+ function buildRelations(ctx) {
2449
+ const { lookup, issues } = ctx;
2450
+ return draftRelations(ctx).map((draft) => {
2451
+ const targetMeta = ctx.tables.find((candidate) => candidate.name === draft.targetName);
2452
+ const targetKey = tableKeyForName(ctx.tables, draft.targetName);
2453
+ const { target } = relationTarget(targetMeta, lookup, ctx.displayOverrides);
2454
+ const single = draft.kind === "belongsTo" || draft.kind === "hasOne";
2455
+ const shape = fieldShape(lookup.field(ctx.rowType, draft.fieldName), draft.targetName, single, lookup);
2456
+ const selectable = target.primaryKey.length + target.labelFields.length > 0;
2457
+ const keyProblem = !targetKey ? { code: "RELATION_UNRESOLVED", message: "The linked table for this field cannot be found." } : draft.keyProblem ?? (target.primaryKey.length === 0 ? { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } : null);
2458
+ const readProblem = !shape || !selectable ? "The linked records for this field cannot be shown here." : null;
2459
+ const editable = !keyProblem && !readProblem;
2460
+ const unlinkable = editable && draft.unlinkProblem === null;
2461
+ const reason = readProblem ?? keyProblem?.message ?? draft.unlinkProblem;
2462
+ if (readProblem) {
2463
+ issues.push({ scope: "relation", target: draft.fieldName, code: "RELATION_UNREADABLE", message: readProblem });
2464
+ } else if (keyProblem) {
2465
+ issues.push({ scope: "relation", target: draft.fieldName, code: keyProblem.code, message: keyProblem.message });
2466
+ }
2467
+ return {
2468
+ kind: draft.kind,
2469
+ fieldName: draft.fieldName,
2470
+ targetKey,
2471
+ targetName: draft.targetName,
2472
+ shape: shape?.shape ?? (single ? "object" : "connection"),
2473
+ readable: readProblem === null,
2474
+ keys: draft.keys,
2475
+ junction: draft.junction,
2476
+ target,
2477
+ pageArg: shape?.pageArg ?? null,
2478
+ hasTotalCount: shape?.hasTotalCount ?? false,
2479
+ filter: relationFilter(ctx.filterType, draft.fieldName, single, lookup),
2480
+ editable,
2481
+ unlinkable,
2482
+ reason: editable && unlinkable ? null : reason
2483
+ };
2484
+ });
2485
+ }
2486
+
2487
+ // src/table-model/type-lookup.ts
2488
+ var MAX_INPUT_DEPTH = 4;
2489
+ function createTypeLookup(index) {
2490
+ const missing = /* @__PURE__ */ new Set();
2491
+ const type = (name) => {
2492
+ if (!name) return null;
2493
+ const found = index.get(name);
2494
+ if (found === void 0) {
2495
+ missing.add(name);
2496
+ return null;
2497
+ }
2498
+ return found;
2499
+ };
2500
+ const inputValue = (ref, depth = 0) => {
2501
+ const named = namedTypeOf(ref);
2502
+ if (!named) return null;
2503
+ const isList = isListTypeRef(ref);
2504
+ if (named.kind === "SCALAR") {
2505
+ return { typeName: named.name, shape: "scalar", isList, enumValues: null, fields: null };
2506
+ }
2507
+ if (named.kind === "ENUM") {
2508
+ const enumType = type(named.name);
2509
+ if (!enumType) return null;
2510
+ return {
2511
+ typeName: named.name,
2512
+ shape: "enum",
2513
+ isList,
2514
+ enumValues: (enumType.enumValues ?? []).map((value) => value.name),
2515
+ fields: null
2516
+ };
2517
+ }
2518
+ if (named.kind !== "INPUT_OBJECT") return null;
2519
+ if (depth >= MAX_INPUT_DEPTH) {
2520
+ return { typeName: named.name, shape: "object", isList, enumValues: null, fields: null };
2521
+ }
2522
+ const objectType = type(named.name);
2523
+ if (!objectType) return null;
2524
+ const fields = [];
2525
+ for (const field2 of objectType.inputFields ?? []) {
2526
+ const value = inputValue(field2.type, depth + 1);
2527
+ if (!value) return null;
2528
+ fields.push({ name: field2.name, required: isRequiredInput(field2), value });
2529
+ }
2530
+ return { typeName: named.name, shape: "object", isList, enumValues: null, fields };
2531
+ };
2532
+ return {
2533
+ type,
2534
+ typeOf: (ref) => type(namedTypeOf(ref)?.name),
2535
+ field: (owner, name) => owner?.fields?.find((candidate) => candidate.name === name) ?? null,
2536
+ inputValue,
2537
+ missing
2538
+ };
2539
+ }
2540
+
2541
+ // src/table-model/build-table-model.ts
2542
+ function storageModel(table) {
2543
+ const storage = table.storage;
2544
+ if (!storage || !storage.isFilesTable && !storage.isBucketsTable) return null;
2545
+ return {
2546
+ role: storage.isFilesTable ? "files" : "buckets",
2547
+ filesType: storage.filesType ?? null,
2548
+ bucketsType: storage.bucketsType ?? null,
2549
+ downloadUrlField: storage.downloadUrlField ?? null,
2550
+ upload: storage.upload ? {
2551
+ mutation: storage.upload.mutation ?? null,
2552
+ inputType: storage.upload.inputType ?? null,
2553
+ payloadType: storage.upload.payloadType ?? null,
2554
+ bulkMutation: storage.upload.bulkMutation ?? null,
2555
+ requiresOwnerId: storage.upload.requiresOwnerId ?? null
2556
+ } : null
2557
+ };
2558
+ }
2559
+ var UNIFIED_SEARCH_FIELD = "unifiedSearch";
2560
+ function searchModel(table, filterFields) {
2561
+ const search = table.search;
2562
+ if (!search) return null;
2563
+ return {
2564
+ algorithms: [...search.algorithms],
2565
+ columns: search.columns.flatMap((column) => column ? [{ name: column.name, algorithm: column.algorithm }] : []),
2566
+ unifiedSearchField: search.hasUnifiedSearch && filterFields.has(UNIFIED_SEARCH_FIELD) ? UNIFIED_SEARCH_FIELD : null,
2567
+ weights: parseMetaSearchWeights(search.config)
2568
+ };
2569
+ }
2570
+ function tableKind(table) {
2571
+ return table.kind === "table" || table.kind === "view" ? table.kind : "unknown";
2572
+ }
2573
+ function displayModel(table, columns, primaryKey, overrides) {
2574
+ return resolveDisplayFieldsFromCandidates(
2575
+ { key: tableKeyOf(table), name: table.name },
2576
+ columns.map((column) => ({
2577
+ name: column.name,
2578
+ kind: column.value.kind,
2579
+ isArray: column.value.isArray,
2580
+ isLeaf: column.readable && column.value.selection === null,
2581
+ isPrimaryKey: column.isPrimaryKey,
2582
+ isForeignKey: column.isForeignKey
2583
+ })),
2584
+ primaryKey,
2585
+ overrides
2586
+ );
2587
+ }
2588
+ function buildTableModel(input) {
2589
+ const { table, tables, schema, displayOverrides } = input;
2590
+ const lookup = createTypeLookup(schema);
2591
+ const issues = [];
2592
+ const key = tableKeyOf(table);
2593
+ const roots = schema.roots ?? { query: null, mutation: null };
2594
+ const identity = getRowIdentityDefinition(table);
2595
+ const primaryKey = identity.status === "keyed" ? identity.fields.map((field2) => field2.fieldName) : [];
2596
+ if (primaryKey.length === 0) {
2597
+ issues.push({
2598
+ scope: "table",
2599
+ target: null,
2600
+ code: "NO_PRIMARY_KEY",
2601
+ // A view shows rows of other tables; that, not a missing key, is what a person needs to hear.
2602
+ message: tableKind(table) === "view" ? "This is a view of other tables, so its records cannot be changed or deleted here." : "This table has no primary key, so its records cannot be changed or deleted."
2603
+ });
2604
+ }
2605
+ const rowType = lookup.type(table.name);
2606
+ if (schema.get(table.name) === null || rowType && rowType.kind !== "OBJECT") {
2607
+ issues.push({
2608
+ scope: "table",
2609
+ target: null,
2610
+ code: "TABLE_NOT_IN_SCHEMA",
2611
+ message: "This table is not available through this API."
2612
+ });
2613
+ }
2614
+ const built = buildOperations({ table, roots, lookup, primaryKey, issues });
2615
+ const fields = (table.fields ?? []).filter((field2) => Boolean(field2?.name));
2616
+ const columns = buildColumns({ ...built, fields, rowType, primaryKey, lookup, issues });
2617
+ const relations = buildRelations({
2618
+ table,
2619
+ tables,
2620
+ rowType,
2621
+ filterType: built.filterType,
2622
+ roots,
2623
+ lookup,
2624
+ issues,
2625
+ displayOverrides
2626
+ });
2627
+ const filterFields = new Set((built.filterType?.inputFields ?? []).map((field2) => field2.name));
2628
+ const model = {
2629
+ key,
2630
+ name: table.name,
2631
+ schemaName: table.schemaName ?? null,
2632
+ kind: tableKind(table),
2633
+ description: table.description ?? null,
2634
+ columns,
2635
+ primaryKey,
2636
+ relations,
2637
+ operations: built.operations,
2638
+ display: displayModel(table, columns, primaryKey, displayOverrides),
2639
+ storage: storageModel(table),
2640
+ search: searchModel(table, filterFields),
2641
+ isJunction: table.isJunction ?? null,
2642
+ issues
2643
+ };
2644
+ return { model, missingTypes: [...lookup.missing] };
2645
+ }
2646
+
2647
+ // src/table-model/resolver.ts
2648
+ var MAX_ROUNDS = 6;
2649
+ function initialTypeNames(table) {
2650
+ const inflection3 = table.inflection;
2651
+ const relations = table.relations;
2652
+ return [
2653
+ table.name,
2654
+ inflection3?.connection,
2655
+ inflection3?.filterType,
2656
+ inflection3?.orderByType,
2657
+ inflection3?.patchType,
2658
+ inflection3?.createInputType,
2659
+ inflection3?.createPayloadType,
2660
+ inflection3?.updatePayloadType,
2661
+ inflection3?.deletePayloadType,
2662
+ ...(relations?.belongsTo ?? []).flatMap((relation) => [relation?.references?.name, relation?.type]),
2663
+ ...(relations?.hasOne ?? []).flatMap((relation) => [relation?.referencedBy?.name, relation?.type]),
2664
+ ...(relations?.hasMany ?? []).flatMap((relation) => [relation?.referencedBy?.name, relation?.type]),
2665
+ ...(relations?.manyToMany ?? []).flatMap((relation) => [
2666
+ relation?.rightTable?.name,
2667
+ relation?.junctionTable?.name,
2668
+ relation?.type
2669
+ ])
2670
+ ].filter((name) => typeof name === "string" && name.length > 0);
2671
+ }
2672
+ function createTableModelResolver(meta) {
2673
+ const tables = Array.isArray(meta) ? meta : metaTablesOf(meta);
2674
+ const loader = createSchemaTypeLoader();
2675
+ async function loadRoots(execute2) {
2676
+ try {
2677
+ return await loader.loadRoots(execute2);
2678
+ } catch (error) {
2679
+ const detail = error instanceof Error && error.message ? ` ${error.message}` : "";
2680
+ throw new TableModelError("SCHEMA_UNAVAILABLE", `The API schema could not be read.${detail}`);
2681
+ }
2682
+ }
2683
+ return {
2684
+ tables,
2685
+ schema: loader.index,
2686
+ async prefetch(execute2) {
2687
+ await loadRoots(execute2);
2688
+ },
2689
+ async resolve(execute2, ref, options = {}) {
2690
+ const table = findMetaTable(tables, ref);
2691
+ const roots = await Promise.all([
2692
+ loadRoots(execute2),
2693
+ loader.loadTypes(execute2, initialTypeNames(table))
2694
+ ]).then(([loaded]) => loaded);
2695
+ if (!roots.query) {
2696
+ throw new TableModelError("SCHEMA_UNAVAILABLE", "The API schema has no query type.", {
2697
+ tableKey: `${table.schemaName ?? ""}.${table.name}`
2698
+ });
2699
+ }
2700
+ const build = () => buildTableModel({ table, tables, schema: loader.index, displayOverrides: options.displayOverrides });
2701
+ let result = build();
2702
+ let previous = "";
2703
+ for (let round = 0; round < MAX_ROUNDS && result.missingTypes.length > 0; round += 1) {
2704
+ const missing = [...result.missingTypes].sort().join(",");
2705
+ if (missing === previous) break;
2706
+ previous = missing;
2707
+ await loader.loadTypes(execute2, result.missingTypes);
2708
+ result = build();
2709
+ }
2710
+ return result.model;
2711
+ }
2712
+ };
2713
+ }
2714
+
2715
+ // src/table-model/value-codec.ts
2716
+ var DECIMAL_STRING_SCALARS = /* @__PURE__ */ new Set(["BigInt", "BigFloat"]);
2717
+ function isPlainObject(value) {
2718
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
2719
+ const prototype = Object.getPrototypeOf(value);
2720
+ return prototype === Object.prototype || prototype === null;
2721
+ }
2722
+ function invalid(ctx, detail) {
2723
+ return new TableModelError("INVALID_VALUE", `The value for "${ctx.column}" ${detail}.`);
2724
+ }
2725
+ function encodeEnum(input, value, ctx) {
2726
+ if (typeof value !== "string") throw invalid(ctx, "must be one of its choices");
2727
+ const values = input.enumValues ?? [];
2728
+ if (values.includes(value)) return value;
2729
+ const byLabel = ctx.options?.find(
2730
+ (option) => option.label === value && values.includes(option.value) && canonicalName(option.label) === canonicalName(option.value)
2731
+ );
2732
+ if (byLabel) return byLabel.value;
2733
+ throw invalid(ctx, `"${value}" is not one of its choices`);
2734
+ }
2735
+ function encodeScalar(input, value, ctx) {
2736
+ if (ctx.kind === "geometry" && isPlainObject(value) && "geojson" in value) return value.geojson;
2737
+ if (DECIMAL_STRING_SCALARS.has(input.typeName) && typeof value === "number") {
2738
+ if (!Number.isFinite(value)) throw invalid(ctx, "must be a finite number");
2739
+ return String(value);
2740
+ }
2741
+ return value;
2742
+ }
2743
+ function encodeObject(input, value, ctx) {
2744
+ if (!isPlainObject(value)) throw invalid(ctx, "must be a structured value");
2745
+ const nested = { ...ctx, kind: null, options: null };
2746
+ if (!input.fields) {
2747
+ const { __typename: _typename, ...rest } = value;
2748
+ return rest;
2749
+ }
2750
+ const encoded = {};
2751
+ for (const field2 of input.fields) {
2752
+ if (!Object.prototype.hasOwnProperty.call(value, field2.name)) continue;
2753
+ const fieldValue = value[field2.name];
2754
+ if (fieldValue === void 0) continue;
2755
+ encoded[field2.name] = encodeValue(field2.value, fieldValue, nested);
2756
+ }
2757
+ return encoded;
2758
+ }
2759
+ function encodeElement(input, value, ctx) {
2760
+ if (value === null || value === void 0) return value;
2761
+ if (input.shape === "enum") return encodeEnum(input, value, ctx);
2762
+ if (input.shape === "object") return encodeObject(input, value, ctx);
2763
+ return encodeScalar(input, value, ctx);
2764
+ }
2765
+ function encodeValue(input, value, ctx) {
2766
+ if (value === null || value === void 0) return value;
2767
+ if (input.isList && Array.isArray(value)) return value.map((element) => encodeElement(input, element, ctx));
2768
+ return encodeElement(input, value, ctx);
2769
+ }
2770
+ function encodeColumnValue(column, value) {
2771
+ const input = column.value.input;
2772
+ if (!input) {
2773
+ throw new TableModelError(
2774
+ "FIELD_NOT_WRITABLE",
2775
+ column.write.updateReason ?? column.write.createReason ?? `"${column.name}" cannot be written.`
2776
+ );
2777
+ }
2778
+ return encodeValue(input, value, { column: column.name, kind: column.value.kind, options: column.value.options });
2779
+ }
2780
+ function encodeWriteValues(model, values, operation) {
2781
+ const encoded = {};
2782
+ for (const [name, value] of Object.entries(values)) {
2783
+ if (value === void 0) continue;
2784
+ const column = model.columns.find((candidate) => candidate.name === name);
2785
+ if (!column) {
2786
+ throw new TableModelError("UNKNOWN_FIELD", `"${name}" is not a field of this table.`, { tableKey: model.key });
2787
+ }
2788
+ const allowed = operation === "create" ? column.write.create : column.write.update;
2789
+ if (!allowed) {
2790
+ const reason = operation === "create" ? column.write.createReason : column.write.updateReason;
2791
+ throw new TableModelError("FIELD_NOT_WRITABLE", `"${name}": ${reason ?? "this field cannot be written."}`, {
2792
+ tableKey: model.key
2793
+ });
2794
+ }
2795
+ encoded[name] = encodeColumnValue(column, value);
2796
+ }
2797
+ return encoded;
2798
+ }
2799
+
2800
+ // src/table-model/documents.ts
2801
+ var RELATION_TOTAL_COUNTS_KEY = "__relationTotalCounts";
2802
+ var CELL_ERRORS_KEY = "__cellErrors";
2803
+ var DEFAULT_RELATION_PAGE_SIZE = 20;
2804
+ function documentOf(source, variables) {
2805
+ return { document: new TypedDocumentString(source), source, variables };
2806
+ }
2807
+ function unavailable(model, operation) {
2808
+ const issue = model.issues.find((candidate) => candidate.scope === "operation" && candidate.target === operation);
2809
+ return new TableModelError("OPERATION_UNAVAILABLE", issue?.message ?? `This table does not support ${operation}.`, {
2810
+ tableKey: model.key
2811
+ });
2812
+ }
2813
+ function columnSelection(column) {
2814
+ return column.value.selection ? `${column.name} ${column.value.selection}` : column.name;
2815
+ }
2816
+ function columnsSelection(model, returning) {
2817
+ const columns = model.columns.filter((column) => column.readable);
2818
+ if (!returning) return columns.map(columnSelection).join(" ");
2819
+ return returning.map((name) => {
2820
+ const column = columns.find((candidate) => candidate.name === name);
2821
+ if (!column) throw new TableModelError("UNKNOWN_FIELD", `"${name}" cannot be returned by this table.`, { tableKey: model.key });
2822
+ return columnSelection(column);
2823
+ }).join(" ");
2824
+ }
2825
+ function listColumnNames(model, requested, relations) {
2826
+ if (!requested) return void 0;
2827
+ const readable = new Set(model.columns.filter((column) => column.readable).map((column) => column.name));
2828
+ for (const name of requested) {
2829
+ if (!readable.has(name)) {
2830
+ throw new TableModelError("UNKNOWN_FIELD", `"${name}" is not a column this table can show.`, { tableKey: model.key });
2831
+ }
2832
+ }
2833
+ const wanted = /* @__PURE__ */ new Set([
2834
+ ...requested,
2835
+ ...model.primaryKey,
2836
+ ...relations.flatMap((relation) => relation.keys.map((pair) => pair.local)),
2837
+ ...relations.flatMap((relation) => relation.junction?.left.map((pair) => pair.local) ?? [])
2838
+ ]);
2839
+ return model.columns.filter((column) => column.readable && wanted.has(column.name)).map((column) => column.name);
2840
+ }
2841
+ function relationSelection(relation, pageSize) {
2842
+ const fields = [.../* @__PURE__ */ new Set([...relation.target.primaryKey, ...relation.target.labelFields])].join(" ");
2843
+ const page = relation.pageArg ? `(${relation.pageArg}: ${pageSize})` : "";
2844
+ if (relation.shape === "object") return `${relation.fieldName} { ${fields} }`;
2845
+ if (relation.shape === "list") return `${relation.fieldName}${page} { ${fields} }`;
2846
+ return `${relation.fieldName}${page} { nodes { ${fields} }${relation.hasTotalCount ? " totalCount" : ""} }`;
2847
+ }
2848
+ function selectedRelations(model, choice) {
2849
+ if (!choice || choice === "none") return [];
2850
+ if (choice === "all") return model.relations.filter((relation) => relation.readable);
2851
+ return choice.flatMap((fieldName) => {
2852
+ const relation = model.relations.find((candidate) => candidate.fieldName === fieldName);
2853
+ if (!relation) {
2854
+ throw new TableModelError("UNKNOWN_FIELD", `"${fieldName}" is not a relation of this table.`, { tableKey: model.key });
2855
+ }
2856
+ return relation.readable ? [relation] : [];
2857
+ });
2858
+ }
2859
+ function pageSizeOf(options) {
2860
+ const size = options.relationPageSize ?? DEFAULT_RELATION_PAGE_SIZE;
2861
+ return Number.isInteger(size) && size > 0 ? size : DEFAULT_RELATION_PAGE_SIZE;
2862
+ }
2863
+ function readRow(row, relations) {
2864
+ if (!row || typeof row !== "object") return {};
2865
+ const next = { ...row };
2866
+ const totals = {};
2867
+ for (const relation of relations) {
2868
+ if (relation.shape !== "connection") continue;
2869
+ const value = next[relation.fieldName];
2870
+ if (!value || typeof value !== "object") continue;
2871
+ next[relation.fieldName] = Array.isArray(value.nodes) ? value.nodes : [];
2872
+ if (typeof value.totalCount === "number") totals[relation.fieldName] = value.totalCount;
2873
+ }
2874
+ if (Object.keys(totals).length > 0) next[RELATION_TOTAL_COUNTS_KEY] = totals;
2875
+ return next;
2876
+ }
2877
+ function readCellError(row, fieldName) {
2878
+ const errors2 = row?.[CELL_ERRORS_KEY];
2879
+ if (!errors2 || typeof errors2 !== "object") return null;
2880
+ const message = errors2[fieldName];
2881
+ return typeof message === "string" ? message : null;
2882
+ }
2883
+ function cellErrorsOf(errors2, listField, shape) {
2884
+ const byRow = /* @__PURE__ */ new Map();
2885
+ const offset = shape === "connection" ? 2 : 1;
2886
+ for (const error of errors2) {
2887
+ const path = error.path ?? [];
2888
+ const row = path[offset];
2889
+ const field2 = path[offset + 1];
2890
+ const located = path[0] === listField && (shape === "list" || path[1] === "nodes");
2891
+ if (!located || typeof row !== "number" || typeof field2 !== "string") {
2892
+ throw new TableModelError("READ_FAILED", error.message || "The rows could not be read.");
2893
+ }
2894
+ const cells = byRow.get(row) ?? {};
2895
+ cells[field2] ??= error.message || "This value cannot be shown.";
2896
+ byRow.set(row, cells);
2897
+ }
2898
+ return byRow;
2899
+ }
2900
+ function withCellErrors(rows, cellErrors) {
2901
+ if (cellErrors.size === 0) return rows;
2902
+ return rows.map((row, position) => {
2903
+ const cells = cellErrors.get(position);
2904
+ return cells ? { ...row, [CELL_ERRORS_KEY]: cells } : row;
2905
+ });
2906
+ }
2907
+ function readRelationTotalCount(row, fieldName) {
2908
+ const totals = row?.[RELATION_TOTAL_COUNTS_KEY];
2909
+ if (!totals || typeof totals !== "object") return null;
2910
+ const total = totals[fieldName];
2911
+ return typeof total === "number" ? total : null;
2912
+ }
2913
+ function orderByValues(model, orderBy) {
2914
+ return orderBy.map(({ field: field2, direction }) => {
2915
+ const column = model.columns.find((candidate) => candidate.name === field2);
2916
+ if (!column?.sort) {
2917
+ throw new TableModelError("SORT_UNAVAILABLE", `This table cannot be sorted by "${field2}".`, { tableKey: model.key });
2918
+ }
2919
+ return direction === "desc" ? column.sort.desc : column.sort.asc;
2920
+ });
2921
+ }
2922
+ function readPageInfo(value) {
2923
+ if (!value || typeof value !== "object") return null;
2924
+ const info = value;
2925
+ return {
2926
+ hasNextPage: info.hasNextPage === true,
2927
+ hasPreviousPage: info.hasPreviousPage === true,
2928
+ startCursor: typeof info.startCursor === "string" ? info.startCursor : null,
2929
+ endCursor: typeof info.endCursor === "string" ? info.endCursor : null
2930
+ };
2931
+ }
2932
+ function buildListDocument(model, options = {}) {
2933
+ const list = model.operations.list;
2934
+ if (!list) throw unavailable(model, "list");
2935
+ const definitions = [];
2936
+ const args = [];
2937
+ const variables = {};
2938
+ const bind = (argument2, variable2, value, code, message) => {
2939
+ if (!argument2) throw new TableModelError(code, message, { tableKey: model.key });
2940
+ definitions.push(`$${variable2}: ${argument2.type}`);
2941
+ args.push(`${argument2.name}: $${variable2}`);
2942
+ variables[variable2] = value;
2943
+ };
2944
+ if (options.first !== void 0) bind(list.first, "first", options.first, "PAGING_UNAVAILABLE", "This table cannot be read page by page.");
2945
+ if (options.offset !== void 0) bind(list.offset, "offset", options.offset, "PAGING_UNAVAILABLE", "This table cannot skip rows.");
2946
+ if (options.after) bind(list.after, "after", options.after, "PAGING_UNAVAILABLE", "This table cannot continue from a cursor.");
2947
+ if (options.where && Object.keys(options.where).length > 0) {
2948
+ bind(list.filter, "where", options.where, "FILTER_UNAVAILABLE", "This table cannot be filtered.");
2949
+ }
2950
+ if (options.orderBy && options.orderBy.length > 0) {
2951
+ bind(list.orderBy, "orderBy", orderByValues(model, options.orderBy), "SORT_UNAVAILABLE", "This table cannot be sorted.");
2952
+ }
2953
+ const relations = selectedRelations(model, options.relations);
2954
+ const pageSize = pageSizeOf(options);
2955
+ const rowSelection = [
2956
+ columnsSelection(model, listColumnNames(model, options.columns, relations)),
2957
+ ...relations.map((relation) => relationSelection(relation, pageSize))
2958
+ ].filter(Boolean).join(" ");
2959
+ const withTotal = list.totalCount && options.totalCount !== false;
2960
+ const withPageInfo = list.pageInfo && options.pageInfo !== false;
2961
+ const body = list.shape === "connection" ? `{ nodes { ${rowSelection} }${withTotal ? " totalCount" : ""}${withPageInfo ? ` pageInfo { ${PAGE_INFO_FIELDS.join(" ")} }` : ""} }` : `{ ${rowSelection} }`;
2962
+ const source = `query ModelList_${model.name}${definitions.length ? `(${definitions.join(", ")})` : ""} {
2963
+ ${list.field}${args.length ? `(${args.join(", ")})` : ""} ${body}
2964
+ }`;
2965
+ return {
2966
+ ...documentOf(source, variables),
2967
+ read(data, errors2 = []) {
2968
+ const value = data?.[list.field];
2969
+ if (errors2.length > 0 && value == null) {
2970
+ throw new TableModelError("READ_FAILED", errors2[0]?.message || "The rows could not be read.", { tableKey: model.key });
2971
+ }
2972
+ const cellErrors = cellErrorsOf(errors2, list.field, list.shape);
2973
+ if (list.shape === "list") {
2974
+ const rows = Array.isArray(value) ? value.map((row) => readRow(row, relations)) : [];
2975
+ return { rows: withCellErrors(rows, cellErrors), totalCount: null, pageInfo: null };
2976
+ }
2977
+ const connection = value ?? {};
2978
+ const nodes = Array.isArray(connection.nodes) ? connection.nodes : [];
2979
+ return {
2980
+ rows: withCellErrors(nodes.map((row) => readRow(row, relations)), cellErrors),
2981
+ totalCount: withTotal && typeof connection.totalCount === "number" ? connection.totalCount : null,
2982
+ pageInfo: withPageInfo ? readPageInfo(connection.pageInfo) : null
2983
+ };
2984
+ }
2985
+ };
2986
+ }
2987
+ function keyValues(model, key, fields) {
2988
+ const values = {};
2989
+ for (const field2 of fields) {
2990
+ const value = key[field2];
2991
+ if (value === void 0 || value === null) {
2992
+ throw new TableModelError("KEY_INCOMPLETE", `The record key is missing "${field2}".`, { tableKey: model.key });
2993
+ }
2994
+ const column = model.columns.find((candidate) => candidate.name === field2);
2995
+ values[field2] = column?.value.input ? encodeColumnValue(column, value) : value;
2996
+ }
2997
+ return values;
2998
+ }
2999
+ function buildFindOneDocument(model, key, options = {}) {
3000
+ if (model.primaryKey.length === 0) {
3001
+ throw new TableModelError("KEY_INCOMPLETE", "This table has no primary key, so one record cannot be looked up.", {
3002
+ tableKey: model.key
3003
+ });
3004
+ }
3005
+ const values = keyValues(model, key, model.primaryKey);
3006
+ const where = Object.fromEntries(
3007
+ model.primaryKey.map((field2) => {
3008
+ const column = model.columns.find((candidate) => candidate.name === field2);
3009
+ if (!column?.filter?.operators.some((operator) => operator.name === "equalTo")) {
3010
+ throw new TableModelError("FILTER_UNAVAILABLE", "One record cannot be looked up on this table.", {
3011
+ tableKey: model.key
3012
+ });
3013
+ }
3014
+ return [column.filter.field, { equalTo: values[field2] }];
3015
+ })
3016
+ );
3017
+ const list = buildListDocument(model, {
3018
+ ...options,
3019
+ where,
3020
+ first: model.operations.list?.first ? 1 : void 0,
3021
+ totalCount: false,
3022
+ pageInfo: false
3023
+ });
3024
+ return {
3025
+ document: list.document,
3026
+ source: list.source,
3027
+ variables: list.variables,
3028
+ read: (data, errors2) => list.read(data, errors2).rows[0] ?? null
3029
+ };
3030
+ }
3031
+ function payloadApplied(data, field2, payloadField) {
3032
+ if (!payloadField) return null;
3033
+ const payload = data?.[field2];
3034
+ if (payload === null || payload === void 0) return false;
3035
+ if (!(payloadField in payload)) return null;
3036
+ return payload[payloadField] !== null;
3037
+ }
3038
+ function readPayloadRow(data, field2, payloadField) {
3039
+ if (!payloadField) return null;
3040
+ const payload = data?.[field2];
3041
+ const row = payload?.[payloadField];
3042
+ return row && typeof row === "object" ? row : null;
3043
+ }
3044
+ function buildCreateDocument(model, values, options = {}) {
3045
+ const create = model.operations.create;
3046
+ if (!create) throw unavailable(model, "create");
3047
+ const variables = { input: { [create.recordField]: encodeWriteValues(model, values, "create") } };
3048
+ const source = `mutation ModelCreate_${model.name}($input: ${create.input.type}) {
3049
+ ${create.field}(${create.input.name}: $input) { ${create.payloadField} { ${columnsSelection(model, options.returning)} } }
3050
+ }`;
3051
+ return { ...documentOf(source, variables), read: (data) => readPayloadRow(data, create.field, create.payloadField) };
3052
+ }
3053
+ function buildUpdateDocument(model, key, patch, options = {}) {
3054
+ const update = model.operations.update;
3055
+ if (!update) throw unavailable(model, "update");
3056
+ const variables = {
3057
+ input: { ...keyValues(model, key, update.keyArgs), [update.patchField]: encodeWriteValues(model, patch, "update") }
3058
+ };
3059
+ const source = `mutation ModelUpdate_${model.name}($input: ${update.input.type}) {
3060
+ ${update.field}(${update.input.name}: $input) { ${update.payloadField} { ${columnsSelection(model, options.returning)} } }
3061
+ }`;
3062
+ return {
3063
+ ...documentOf(source, variables),
3064
+ read: (data) => readPayloadRow(data, update.field, update.payloadField),
3065
+ applied: (data) => payloadApplied(data, update.field, update.payloadField)
3066
+ };
3067
+ }
3068
+ function buildDeleteDocument(model, key) {
3069
+ const remove = model.operations.delete;
3070
+ if (!remove) throw unavailable(model, "delete");
3071
+ const variables = { input: keyValues(model, key, remove.keyArgs) };
3072
+ const keySelection = model.columns.filter((column) => column.readable && model.primaryKey.includes(column.name)).map(columnSelection).join(" ");
3073
+ const payload = remove.payloadField && keySelection ? `${remove.payloadField} { ${keySelection} }` : "__typename";
3074
+ const source = `mutation ModelDelete_${model.name}($input: ${remove.input.type}) {
3075
+ ${remove.field}(${remove.input.name}: $input) { ${payload} }
3076
+ }`;
3077
+ return {
3078
+ ...documentOf(source, variables),
3079
+ read: (data) => readPayloadRow(data, remove.field, remove.payloadField && keySelection ? remove.payloadField : null),
3080
+ applied: (data) => payloadApplied(data, remove.field, remove.payloadField && keySelection ? remove.payloadField : null)
3081
+ };
3082
+ }
3083
+
1119
3084
  // ../../node_modules/.pnpm/inflekt@0.5.1/node_modules/inflekt/esm/pluralize.js
1120
3085
  var inflection = __toESM(require_inflection());
1121
3086
  var LATIN_SUFFIX_OVERRIDES = [
@@ -1335,17 +3300,17 @@ function tableIdentifier(table) {
1335
3300
  }
1336
3301
  function includedTableNames(values) {
1337
3302
  if (!values) return null;
1338
- const names = /* @__PURE__ */ new Set();
3303
+ const names2 = /* @__PURE__ */ new Set();
1339
3304
  for (const value of values) {
1340
- names.add(value);
3305
+ names2.add(value);
1341
3306
  const separator = value.lastIndexOf(".");
1342
3307
  const schemaName = separator >= 0 ? value.slice(0, separator) : null;
1343
3308
  const physicalName = separator >= 0 ? value.slice(separator + 1) : value;
1344
3309
  const graphqlName = codecNameToTableName(pgFieldToCamelCase(physicalName));
1345
- names.add(graphqlName);
1346
- if (schemaName) names.add(`${schemaName}.${graphqlName}`);
3310
+ names2.add(graphqlName);
3311
+ if (schemaName) names2.add(`${schemaName}.${graphqlName}`);
1347
3312
  }
1348
- return names;
3313
+ return names2;
1349
3314
  }
1350
3315
  function collectJunctionTableNames(tables) {
1351
3316
  const junctions = /* @__PURE__ */ new Set();
@@ -1383,124 +3348,23 @@ function selectConsoleDataTables(metaTables, options = {}) {
1383
3348
  });
1384
3349
  }
1385
3350
 
1386
- // src/row-identity.ts
1387
- function primaryKeyColumnNames(table) {
1388
- const constraints = table.constraints;
1389
- if (constraints && !Array.isArray(constraints)) {
1390
- const names = (constraints.primaryKey?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1391
- if (names.length > 0) return [...new Set(names)];
1392
- }
1393
- for (const constraint of table.primaryKeyConstraints ?? []) {
1394
- const names = (constraint?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1395
- if (names.length > 0) return [...new Set(names)];
1396
- }
1397
- return [...new Set(
1398
- (table.fields ?? []).flatMap((field2) => field2?.isPrimaryKey && field2.name ? [field2.name] : [])
1399
- )];
1400
- }
1401
- function isRowIdentityValue(value) {
1402
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1403
- if (typeof value === "number") return Number.isFinite(value);
1404
- if (Array.isArray(value)) return value.every(isRowIdentityValue);
1405
- if (typeof value !== "object" || value === null) return false;
1406
- const prototype = Object.getPrototypeOf(value);
1407
- if (prototype !== Object.prototype && prototype !== null) return false;
1408
- return Object.values(value).every(isRowIdentityValue);
1409
- }
1410
- function sortIdentityValue(value) {
1411
- if (Array.isArray(value)) return value.map(sortIdentityValue);
1412
- if (typeof value !== "object" || value === null) return value;
1413
- return Object.fromEntries(
1414
- Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortIdentityValue(item)])
1415
- );
1416
- }
1417
- function getRowIdentityDefinition(table) {
1418
- const schemaName = table.schemaName ?? null;
1419
- const columnNames = primaryKeyColumnNames(table);
1420
- if (columnNames.length === 0) {
1421
- return {
1422
- status: "read-only",
1423
- schemaName,
1424
- tableName: table.name,
1425
- reason: "no-primary-key"
1426
- };
1427
- }
1428
- return {
1429
- status: "keyed",
1430
- schemaName,
1431
- tableName: table.name,
1432
- fields: columnNames.map((columnName) => ({
1433
- columnName,
1434
- // `_meta` exposes GraphQL field names here (already inflected), so using
1435
- // them verbatim also handles custom/renamed primary keys.
1436
- fieldName: columnName
1437
- }))
1438
- };
3351
+ // src/system-tables.ts
3352
+ function physicalKey(schemaName, tableName) {
3353
+ return `${schemaName}.${tableName}`;
1439
3354
  }
1440
- function resolveRowIdentity(table, row) {
1441
- const definition = getRowIdentityDefinition(table);
1442
- if (definition.status === "read-only") return definition;
1443
- const missingFields = [];
1444
- const invalidFields = [];
1445
- const fields = [];
1446
- for (const field2 of definition.fields) {
1447
- if (!Object.prototype.hasOwnProperty.call(row, field2.fieldName)) {
1448
- missingFields.push(field2.fieldName);
1449
- continue;
1450
- }
1451
- const value = row[field2.fieldName];
1452
- if (value === null || !isRowIdentityValue(value)) {
1453
- invalidFields.push(field2.fieldName);
1454
- continue;
1455
- }
1456
- fields.push({ ...field2, value });
1457
- }
1458
- if (missingFields.length > 0 || invalidFields.length > 0) {
1459
- return {
1460
- status: "invalid-row",
1461
- schemaName: definition.schemaName,
1462
- tableName: definition.tableName,
1463
- missingFields,
1464
- invalidFields
1465
- };
3355
+ function tableRolesFromCatalog(tables) {
3356
+ const roles = /* @__PURE__ */ new Map();
3357
+ for (const table of tables) {
3358
+ const schemaName = table.schema?.schemaName;
3359
+ if (!schemaName || !table.name || !table.category) continue;
3360
+ roles.set(physicalKey(schemaName, table.name), table.category.toUpperCase() === "APP" ? "app" : "system");
1466
3361
  }
1467
- return {
1468
- status: "identified",
1469
- identity: {
1470
- schemaName: definition.schemaName,
1471
- tableName: definition.tableName,
1472
- fields
1473
- }
1474
- };
1475
- }
1476
- function serializeRowIdentity(identity) {
1477
- return JSON.stringify([
1478
- identity.schemaName,
1479
- identity.tableName,
1480
- identity.fields.map((field2) => [
1481
- field2.columnName,
1482
- field2.fieldName,
1483
- sortIdentityValue(field2.value)
1484
- ])
1485
- ]);
1486
- }
1487
- function rowIdentityToPrimaryKey(identity) {
1488
- return Object.fromEntries(
1489
- identity.fields.map((field2) => [field2.fieldName, field2.value])
1490
- );
3362
+ return roles;
1491
3363
  }
1492
- function assessTableWriteCapability(table) {
1493
- const definition = getRowIdentityDefinition(table);
1494
- if (definition.status === "read-only") return definition;
1495
- return {
1496
- status: "mutable",
1497
- primaryKeyFields: definition.fields.map((field2) => field2.fieldName),
1498
- operations: {
1499
- create: Boolean(table.query?.create),
1500
- update: Boolean(table.query?.update),
1501
- delete: Boolean(table.query?.delete)
1502
- }
1503
- };
3364
+ function isSystemTable(table, roles) {
3365
+ const role = roles && table.schemaName && table.tableName ? roles.get(physicalKey(table.schemaName, table.tableName)) : void 0;
3366
+ if (role === "system") return true;
3367
+ return Boolean(table.storage?.isFilesTable || table.storage?.isBucketsTable || table.scope?.scope === "database");
1504
3368
  }
1505
3369
  var document = ({ definitions }) => ({
1506
3370
  kind: graphql.Kind.DOCUMENT,
@@ -2951,16 +4815,16 @@ function convertCustomSelectionToOptions(table, allTables, selection) {
2951
4815
  });
2952
4816
  }
2953
4817
  if (selection.include) {
2954
- Object.entries(selection.include).forEach(([relationField, relationSelection]) => {
4818
+ Object.entries(selection.include).forEach(([relationField, relationSelection2]) => {
2955
4819
  if (isRelationalField2(relationField, table)) {
2956
- if (relationSelection === true) {
4820
+ if (relationSelection2 === true) {
2957
4821
  options[relationField] = {
2958
4822
  select: getRelatedTableScalarFields(relationField, table, allTables),
2959
4823
  variables: {}
2960
4824
  };
2961
- } else if (Array.isArray(relationSelection)) {
4825
+ } else if (Array.isArray(relationSelection2)) {
2962
4826
  const selectObj = {};
2963
- relationSelection.forEach((field2) => {
4827
+ relationSelection2.forEach((field2) => {
2964
4828
  selectObj[field2] = true;
2965
4829
  });
2966
4830
  options[relationField] = {
@@ -4094,9 +5958,9 @@ function analyzeSchemaIntrospectionCompatibility(introspection, metaQuery) {
4094
5958
  missing.add(fallbackPath);
4095
5959
  return false;
4096
5960
  }
4097
- const inputField = inputType.inputFields?.find((field2) => field2.name === fieldName);
4098
- if (!inputField) return true;
4099
- if (baseTypeName(inputField.type) !== enumTypeName) {
5961
+ const inputField2 = inputType.inputFields?.find((field2) => field2.name === fieldName);
5962
+ if (!inputField2) return true;
5963
+ if (baseTypeName(inputField2.type) !== enumTypeName) {
4100
5964
  missing.add(`${typePath(inputType.name)}.inputFields.${fieldName}.type.${enumTypeName}`);
4101
5965
  return false;
4102
5966
  }
@@ -4293,12 +6157,27 @@ function wait(ms) {
4293
6157
  function getErrorCode(error) {
4294
6158
  return errors.parse(error).code;
4295
6159
  }
4296
- var AUTH_ERROR_CODES = /* @__PURE__ */ new Set(["UNAUTHENTICATED", "BAD_TOKEN_DEFINITION"]);
4297
- var AUTH_MESSAGE_PATTERN = /unauthenticated|unauthorized|not authorized|authentication|session expired|token expired/;
6160
+ var AUTHENTICATION_ERROR_CODES = ["UNAUTHENTICATED", "BAD_TOKEN_DEFINITION"];
6161
+ function isAuthenticationCode(code) {
6162
+ return typeof code === "string" && AUTHENTICATION_ERROR_CODES.includes(code);
6163
+ }
6164
+ var AUTH_STATUS = 401;
6165
+ function asShape(value) {
6166
+ return value && typeof value === "object" ? value : null;
6167
+ }
6168
+ function hasAuthCode(node) {
6169
+ return isAuthenticationCode(asShape(asShape(node)?.extensions)?.code);
6170
+ }
6171
+ function hasAuthCodeIn(errors2) {
6172
+ return Array.isArray(errors2) && errors2.some(hasAuthCode);
6173
+ }
4298
6174
  function isAuthenticationError(error) {
4299
- const parsed = errors.parse(error);
4300
- if (parsed.code && AUTH_ERROR_CODES.has(parsed.code)) return true;
4301
- return AUTH_MESSAGE_PATTERN.test((parsed.rawMessage ?? "").toLowerCase());
6175
+ if (error instanceof errors.ConstructiveError) return isAuthenticationCode(error.code);
6176
+ const shape = asShape(error);
6177
+ if (!shape) return false;
6178
+ const response = asShape(shape.response);
6179
+ if (shape.status === AUTH_STATUS || shape.statusCode === AUTH_STATUS || response?.status === AUTH_STATUS) return true;
6180
+ return hasAuthCode(shape) || hasAuthCodeIn(shape.errors) || hasAuthCodeIn(response?.errors);
4302
6181
  }
4303
6182
  var RETRYABLE_CODES = /* @__PURE__ */ new Set(["NETWORK_ERROR", "TIMEOUT_ERROR", "RATE_LIMITED", "TOO_MANY_REQUESTS"]);
4304
6183
  function isRetryable(error) {
@@ -4378,7 +6257,7 @@ function stripEmpty(value) {
4378
6257
  return value;
4379
6258
  }
4380
6259
  var asFieldIds = (ids) => ids;
4381
- function isPlainObject(value) {
6260
+ function isPlainObject2(value) {
4382
6261
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
4383
6262
  }
4384
6263
  function hasNestedDirtyFields(dirtyFields, prefix) {
@@ -4454,7 +6333,7 @@ function prepareMutationInput(input, options) {
4454
6333
  result[key] = value;
4455
6334
  continue;
4456
6335
  }
4457
- if (isPlainObject(value)) {
6336
+ if (isPlainObject2(value)) {
4458
6337
  const hasRelevantDirtyFields = !hasDirtyTracking || isDirty || hasNestedDirtyFields(dirtyFields, fullPath);
4459
6338
  if (!hasRelevantDirtyFields) {
4460
6339
  continue;
@@ -5386,40 +7265,59 @@ Object.defineProperty(exports, "toError", {
5386
7265
  enumerable: true,
5387
7266
  get: function () { return errors.toError; }
5388
7267
  });
7268
+ exports.AUTHENTICATION_ERROR_CODES = AUTHENTICATION_ERROR_CODES;
7269
+ exports.CELL_ERRORS_KEY = CELL_ERRORS_KEY;
5389
7270
  exports.CONSTRAINT_MESSAGES = CONSTRAINT_MESSAGES;
5390
7271
  exports.CRUD_OPERATIONS = CRUD_OPERATIONS;
5391
7272
  exports.CRUD_TO_PRIVILEGE = CRUD_TO_PRIVILEGE;
5392
7273
  exports.DATA_NODE_GENERATED_FIELDS = DATA_NODE_GENERATED_FIELDS;
5393
7274
  exports.DEFAULT_CONSOLE_APPLICATION_SCOPES = DEFAULT_CONSOLE_APPLICATION_SCOPES;
5394
7275
  exports.DEFAULT_CRUD_GRANT_PRIVILEGES = DEFAULT_CRUD_GRANT_PRIVILEGES;
7276
+ exports.DEFAULT_RELATION_PAGE_SIZE = DEFAULT_RELATION_PAGE_SIZE;
5395
7277
  exports.MEMBERSHIP_TYPES = MEMBERSHIP_TYPES;
7278
+ exports.META_CAPABILITY_INTROSPECTION_DOCUMENT = META_CAPABILITY_INTROSPECTION_DOCUMENT;
7279
+ exports.META_CAPABILITY_INTROSPECTION_SOURCE = META_CAPABILITY_INTROSPECTION_SOURCE;
5396
7280
  exports.META_CONTRACT_INTROSPECTION_DOCUMENT = META_CONTRACT_INTROSPECTION_DOCUMENT;
5397
7281
  exports.META_CONTRACT_INTROSPECTION_SOURCE = META_CONTRACT_INTROSPECTION_SOURCE;
5398
7282
  exports.META_CONTRACT_REQUIREMENTS = META_CONTRACT_REQUIREMENTS;
5399
7283
  exports.META_CONTRACT_VERSION = META_CONTRACT_VERSION;
5400
7284
  exports.META_DOCUMENT = META_DOCUMENT;
7285
+ exports.META_OPTIONAL_CAPABILITIES = META_OPTIONAL_CAPABILITIES;
5401
7286
  exports.META_QUERY_SOURCE = META_QUERY_SOURCE;
5402
7287
  exports.MetaContractError = MetaContractError;
5403
7288
  exports.POLICY_PROVISIONING_CONFIG = POLICY_PROVISIONING_CONFIG;
5404
7289
  exports.QueryBuilder = QueryBuilder;
7290
+ exports.RELATION_TOTAL_COUNTS_KEY = RELATION_TOTAL_COUNTS_KEY;
5405
7291
  exports.SCHEMA_INTROSPECTION_QUERY = SCHEMA_INTROSPECTION_QUERY;
7292
+ exports.SCHEMA_ROOTS_SOURCE = SCHEMA_ROOTS_SOURCE;
7293
+ exports.TableModelError = TableModelError;
5406
7294
  exports.TypedDocumentString = TypedDocumentString;
5407
7295
  exports.analyzeSchemaIntrospectionCompatibility = analyzeSchemaIntrospectionCompatibility;
5408
7296
  exports.asFieldIds = asFieldIds;
5409
7297
  exports.assertMetaContract = assertMetaContract;
5410
7298
  exports.assertMetaQuery = assertMetaQuery;
7299
+ exports.assessMetaCapabilities = assessMetaCapabilities;
5411
7300
  exports.assessMetaContract = assessMetaContract;
5412
7301
  exports.assessSchemaIntrospectionCompatibility = assessSchemaIntrospectionCompatibility;
5413
7302
  exports.assessTableWriteCapability = assessTableWriteCapability;
5414
7303
  exports.buildCount = buildCount;
7304
+ exports.buildCreateDocument = buildCreateDocument;
7305
+ exports.buildDeleteDocument = buildDeleteDocument;
5415
7306
  exports.buildFindOne = buildFindOne;
7307
+ exports.buildFindOneDocument = buildFindOneDocument;
7308
+ exports.buildListDocument = buildListDocument;
7309
+ exports.buildMetaDocument = buildMetaDocument;
7310
+ exports.buildMetaQuerySource = buildMetaQuerySource;
5416
7311
  exports.buildNodeData = buildNodeData;
5417
7312
  exports.buildNodeDataForDataNodeType = buildNodeDataForDataNodeType;
5418
7313
  exports.buildPostGraphileCreate = buildPostGraphileCreate;
5419
7314
  exports.buildPostGraphileDelete = buildPostGraphileDelete;
5420
7315
  exports.buildPostGraphileUpdate = buildPostGraphileUpdate;
7316
+ exports.buildSchemaTypesSource = buildSchemaTypesSource;
5421
7317
  exports.buildSelect = buildSelect;
7318
+ exports.buildTableModel = buildTableModel;
5422
7319
  exports.buildTypeRegistry = buildTypeRegistry;
7320
+ exports.buildUpdateDocument = buildUpdateDocument;
5423
7321
  exports.cleanTable = cleanTable;
5424
7322
  exports.cleanTableToMetaObject = cleanTableToMetaObject;
5425
7323
  exports.convertFromMetaSchema = convertFromMetaSchema;
@@ -5427,8 +7325,14 @@ exports.convertToSelectionOptions = convertToSelectionOptions;
5427
7325
  exports.createASTQueryBuilder = createASTQueryBuilder;
5428
7326
  exports.createError = createError2;
5429
7327
  exports.createOne = createOne;
7328
+ exports.createSchemaTypeLoader = createSchemaTypeLoader;
7329
+ exports.createTableModelResolver = createTableModelResolver;
5430
7330
  exports.deleteOne = deleteOne;
7331
+ exports.emptyMetaCapabilities = emptyMetaCapabilities;
7332
+ exports.encodeColumnValue = encodeColumnValue;
7333
+ exports.encodeWriteValues = encodeWriteValues;
5431
7334
  exports.filterOperations = filterOperations;
7335
+ exports.findMetaTable = findMetaTable;
5432
7336
  exports.generateIntrospectionSchema = generateIntrospectionSchema;
5433
7337
  exports.geometryAst = geometryAst;
5434
7338
  exports.geometryCollectionAst = geometryCollectionAst;
@@ -5457,13 +7361,20 @@ exports.groupCrudOperationsByConfig = groupCrudOperationsByConfig;
5457
7361
  exports.hasGeneratedFields = hasGeneratedFields;
5458
7362
  exports.injectSchemaFields = injectSchemaFields;
5459
7363
  exports.intervalAst = intervalAst;
7364
+ exports.isAuthenticationCode = isAuthenticationCode;
5460
7365
  exports.isAuthenticationError = isAuthenticationError;
5461
7366
  exports.isGraphQLVariableValue = isGraphQLVariableValue;
5462
7367
  exports.isGraphQLVariables = isGraphQLVariables;
5463
7368
  exports.isIntervalType = isIntervalType;
7369
+ exports.isListTypeRef = isListTypeRef;
7370
+ exports.isNonNullTypeRef = isNonNullTypeRef;
5464
7371
  exports.isRelationalField = isRelationalField2;
7372
+ exports.isRequiredInput = isRequiredInput;
5465
7373
  exports.isRetryable = isRetryable;
7374
+ exports.isSystemTable = isSystemTable;
5466
7375
  exports.isTableOperation = isTableOperation;
7376
+ exports.metaTablesOf = metaTablesOf;
7377
+ exports.namedTypeOf = namedTypeOf;
5467
7378
  exports.normalizeInflectionValue = normalizeInflectionValue;
5468
7379
  exports.normalizeSchemaEnumInputValues = normalizeSchemaEnumInputValues;
5469
7380
  exports.parseError = parseError;
@@ -5477,13 +7388,20 @@ exports.prepareCreateInput = prepareCreateInput;
5477
7388
  exports.prepareMutationInput = prepareMutationInput;
5478
7389
  exports.preparePatchInput = preparePatchInput;
5479
7390
  exports.prepareUpdateInput = prepareUpdateInput;
7391
+ exports.printTypeRef = printTypeRef;
7392
+ exports.readCellError = readCellError;
7393
+ exports.readRelationTotalCount = readRelationTotalCount;
5480
7394
  exports.requiresSubfieldSelection = requiresSubfieldSelection;
7395
+ exports.resolveDisplayFields = resolveDisplayFields;
5481
7396
  exports.resolveRowIdentity = resolveRowIdentity;
5482
7397
  exports.rowIdentityToPrimaryKey = rowIdentityToPrimaryKey;
5483
7398
  exports.sanitizePolicyData = sanitizePolicyData;
5484
7399
  exports.selectConsoleDataTables = selectConsoleDataTables;
5485
7400
  exports.serializeRowIdentity = serializeRowIdentity;
5486
7401
  exports.stripEmpty = stripEmpty;
7402
+ exports.tableKeyForName = tableKeyForName;
7403
+ exports.tableKeyOf = tableKeyOf;
7404
+ exports.tableRolesFromCatalog = tableRolesFromCatalog;
5487
7405
  exports.toCamelCasePlural = toCamelCasePlural;
5488
7406
  exports.toCamelCaseSingular = toCamelCaseSingular;
5489
7407
  exports.toCreateInputTypeName = toCreateInputTypeName;