@datafn/server 0.1.3 → 0.1.5-maint.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
@@ -6,7 +6,7 @@ var db = require('@superfunctions/db');
6
6
  var observability = require('@superfunctions/observability');
7
7
  var crypto$1 = require('crypto');
8
8
 
9
- // src/index.ts
9
+ // src/server.ts
10
10
 
11
11
  // src/execution/internal-tables.ts
12
12
  var META_COLUMNS = [
@@ -56,9 +56,6 @@ var INTERNAL_TABLE_SCHEMAS = {
56
56
  __datafn_seed: SEED_COLUMNS,
57
57
  __datafn_permission_directory_outbox: PERMISSION_DIRECTORY_OUTBOX_COLUMNS
58
58
  };
59
- function listNamespacedInternalTables() {
60
- return Object.entries(INTERNAL_TABLE_SCHEMAS).filter(([, columns]) => columns.some((column) => column.name === "namespace")).map(([name]) => name).sort();
61
- }
62
59
  async function ensureInternalTable(adapter, tableName) {
63
60
  const columns = INTERNAL_TABLE_SCHEMAS[tableName];
64
61
  if (!columns) {
@@ -475,8 +472,8 @@ function createSequenceStore(config) {
475
472
  // src/http/json.ts
476
473
  async function parseJsonBody(req) {
477
474
  try {
478
- const text2 = await req.text();
479
- if (!text2 || text2.trim() === "") {
475
+ const text = await req.text();
476
+ if (!text || text.trim() === "") {
480
477
  return {
481
478
  ok: false,
482
479
  error: {
@@ -486,7 +483,7 @@ async function parseJsonBody(req) {
486
483
  }
487
484
  };
488
485
  }
489
- const data = JSON.parse(text2);
486
+ const data = JSON.parse(text);
490
487
  return { ok: true, data };
491
488
  } catch (error) {
492
489
  return {
@@ -736,13 +733,6 @@ function validateRecordKeys(index, resourceName, record, basePath, mode = "write
736
733
  for (const key of Object.keys(record)) {
737
734
  if (key === "id") continue;
738
735
  if (!fields.has(key)) {
739
- if (mode === "write" && index.fieldsByResource.get(resourceName)?.has(key)) {
740
- return vErr(
741
- "DFQL_INVALID",
742
- `Field is read-only: ${key} on ${resourceName}`,
743
- `${basePath}.${key}`
744
- );
745
- }
746
736
  return vErr(
747
737
  "DFQL_UNKNOWN_FIELD",
748
738
  `Unknown field: ${key} on ${resourceName}`,
@@ -1031,32 +1021,13 @@ function validateMutation(mutation, index, basePath = "$", opts) {
1031
1021
  `${basePath}.record.${fieldName}`
1032
1022
  );
1033
1023
  }
1034
- if (fieldDef.type === "date" && (fieldDef.min !== void 0 || fieldDef.max !== void 0)) {
1035
- const epoch = core.toBoundsEpochMs(value);
1036
- if (Number.isFinite(epoch)) {
1037
- if (fieldDef.min !== void 0 && epoch < fieldDef.min) {
1038
- return vErr(
1039
- "DFQL_INVALID",
1040
- `Field '${fieldName}' must be on or after ${core.formatBoundEpochMs(fieldDef.min)}`,
1041
- `${basePath}.record.${fieldName}`
1042
- );
1043
- }
1044
- if (fieldDef.max !== void 0 && epoch > fieldDef.max) {
1045
- return vErr(
1046
- "DFQL_INVALID",
1047
- `Field '${fieldName}' must be on or before ${core.formatBoundEpochMs(fieldDef.max)}`,
1048
- `${basePath}.record.${fieldName}`
1049
- );
1050
- }
1051
- }
1052
- }
1053
1024
  }
1054
1025
  if (m.operation === "insert" || m.operation === "replace") {
1055
1026
  const resource2 = resourceResult.result;
1056
1027
  const record2 = m.record;
1057
1028
  for (const field of resource2.fields) {
1058
1029
  if (field.required && field.default === void 0 && field.name !== "id" && !field.readonly) {
1059
- if (!(field.name in record2) || record2[field.name] === void 0 || record2[field.name] === null && !field.nullable) {
1030
+ if (!(field.name in record2) || record2[field.name] === null || record2[field.name] === void 0) {
1060
1031
  return vErr(
1061
1032
  "DFQL_INVALID",
1062
1033
  `Required field missing: ${field.name}`,
@@ -1362,7 +1333,11 @@ function validateQuery(query, index, basePath = "$", limits) {
1362
1333
  }
1363
1334
  }
1364
1335
  if (q.temporal !== void 0) {
1365
- const temporalResult = validateTemporal(q, fieldNames);
1336
+ const temporalResult = validateTemporal(
1337
+ q,
1338
+ fieldNames,
1339
+ (field) => resolveFieldType(index, resourceName, field)
1340
+ );
1366
1341
  if (!temporalResult.ok) {
1367
1342
  return temporalResult;
1368
1343
  }
@@ -1606,7 +1581,19 @@ function validateGroupBy(q, fieldNames, relationNames) {
1606
1581
  }
1607
1582
  return vOk(void 0);
1608
1583
  }
1609
- function validateTemporal(q, fieldNames) {
1584
+ function resolveFieldType(index, resourceName, field) {
1585
+ const resource = index.schema.resources.find((r) => r.name === resourceName);
1586
+ if (!resource) return void 0;
1587
+ const capabilityFields = core.getCapabilityFields(
1588
+ core.resolveCapabilities(index.schema.capabilities, resource.capabilities)
1589
+ );
1590
+ const injected = capabilityFields.find((f) => f.name === field);
1591
+ if (injected) return { type: injected.type, capability: true };
1592
+ const declared = resource.fields.find((f) => f.name === field);
1593
+ return declared ? { type: declared.type, capability: false } : void 0;
1594
+ }
1595
+ var NON_NUMERIC_TEMPORAL_STORAGE = /* @__PURE__ */ new Set(["date", "iso"]);
1596
+ function validateTemporal(q, fieldNames, fieldType = () => void 0) {
1610
1597
  const clauses = Array.isArray(q.temporal) ? q.temporal : [q.temporal];
1611
1598
  const validScales = /* @__PURE__ */ new Set(["hour", "day", "week", "month", "quarter", "year"]);
1612
1599
  const validStorage = /* @__PURE__ */ new Set(["unix-ms", "unix-s", "date", "iso"]);
@@ -1626,6 +1613,16 @@ function validateTemporal(q, fieldNames) {
1626
1613
  if (temporal.storage !== void 0 && !validStorage.has(String(temporal.storage))) {
1627
1614
  return vErr("DFQL_INVALID", "Invalid temporal storage", `${path}.storage`);
1628
1615
  }
1616
+ const target = fieldType(temporal.field);
1617
+ const storage = temporal.storage === void 0 ? void 0 : String(temporal.storage);
1618
+ const mismatched = storage !== void 0 && (target?.type === "number" && NON_NUMERIC_TEMPORAL_STORAGE.has(storage) || target?.type === "date" && target.capability && storage !== "unix-ms");
1619
+ if (mismatched) {
1620
+ return vErr(
1621
+ "DFQL_INVALID",
1622
+ target.type === "date" ? `Invalid DFQL: temporal storage "${storage}" does not match ${temporal.field}, which DataFn stores as epoch milliseconds; use "unix-ms" (the default)` : `Invalid DFQL: temporal storage "${storage}" does not match number field ${temporal.field}`,
1623
+ `${path}.storage`
1624
+ );
1625
+ }
1629
1626
  if (temporal.period !== void 0) {
1630
1627
  if (typeof temporal.period !== "object" || temporal.period === null || Array.isArray(temporal.period)) {
1631
1628
  return vErr("DFQL_INVALID", "Invalid DFQL: temporal period must be object", `${path}.period`);
@@ -2777,6 +2774,11 @@ function getShareableCapability(resource, schema) {
2777
2774
  const resolved = core.resolveCapabilities(schema.capabilities, resource.capabilities);
2778
2775
  return resolved.find(isShareableCapability2);
2779
2776
  }
2777
+ function isNamespaceOwnerActor(actorId, namespace) {
2778
+ if (!actorId) return false;
2779
+ const namespacePrincipal = normalizeNonEmptyString3(namespace);
2780
+ return !!namespacePrincipal && canonicalizeActorPrincipal(actorId) === namespacePrincipal;
2781
+ }
2780
2782
  function isPrivateShareableResource(schema, resourceName) {
2781
2783
  const resource = schema.resources.find((r) => r.name === resourceName);
2782
2784
  if (!resource) return false;
@@ -2955,8 +2957,7 @@ async function resolveAccessLevel(db, schema, resource, recordId, actorId, names
2955
2957
  }
2956
2958
  const recordObject = record;
2957
2959
  const actorPrincipal = canonicalizeActorPrincipal(actorId);
2958
- const namespacePrincipal = normalizeNonEmptyString3(namespace);
2959
- if (namespacePrincipal && actorPrincipal === namespacePrincipal) {
2960
+ if (isNamespaceOwnerActor(actorId, namespace)) {
2960
2961
  return "owner";
2961
2962
  }
2962
2963
  const createdByValue = normalizeNonEmptyString3(recordObject.createdBy);
@@ -3304,22 +3305,6 @@ function filterAncestorInactiveRecords(records, match, metadata) {
3304
3305
  }
3305
3306
  return records.filter((record) => record.isAncestorInactive !== true);
3306
3307
  }
3307
- function isPlainRecord(value) {
3308
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
3309
- return false;
3310
- }
3311
- const prototype = Object.getPrototypeOf(value);
3312
- return prototype === Object.prototype || prototype === null;
3313
- }
3314
- function applyOmitToArrayValue(value, omit) {
3315
- if (Array.isArray(value)) {
3316
- return value.map((item) => applyOmitToArrayValue(item, omit));
3317
- }
3318
- if (isPlainRecord(value)) {
3319
- return applyOmit(value, omit);
3320
- }
3321
- return value;
3322
- }
3323
3308
  function applyOmit(record, omit) {
3324
3309
  if (!omit || omit.length === 0) {
3325
3310
  return record;
@@ -3328,8 +3313,13 @@ function applyOmit(record, omit) {
3328
3313
  for (const [key, value] of Object.entries(record)) {
3329
3314
  if (key === "id" || !omit.includes(key)) {
3330
3315
  if (Array.isArray(value)) {
3331
- result[key] = value.map((item) => applyOmitToArrayValue(item, omit));
3332
- } else if (isPlainRecord(value) && key !== "$relation_metadata") {
3316
+ result[key] = value.map((item) => {
3317
+ if (typeof item === "object" && item !== null) {
3318
+ return applyOmit(item, omit);
3319
+ }
3320
+ return item;
3321
+ });
3322
+ } else if (typeof value === "object" && value !== null && key !== "$relation_metadata") {
3333
3323
  result[key] = applyOmit(value, omit);
3334
3324
  } else {
3335
3325
  result[key] = value;
@@ -3430,7 +3420,6 @@ function getFkFieldsToOmit(schema, targetResource) {
3430
3420
  function materializeSelect(record, resource, select, schema, store, omit, metadata) {
3431
3421
  const resourceSchema = schema.resources.find((r) => r.name === resource);
3432
3422
  if (!resourceSchema) return { id: record.id };
3433
- record = core.stripNullsForNonNullableFields(record, resourceSchema);
3434
3423
  const fkFieldsToOmit = getFkFieldsToOmit(schema, resource);
3435
3424
  const effectiveOmit = omit ? [...omit, ...Array.from(fkFieldsToOmit)] : Array.from(fkFieldsToOmit);
3436
3425
  if (!select || select.length === 0) {
@@ -3539,9 +3528,7 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3539
3528
  ),
3540
3529
  htreeRelation,
3541
3530
  metadata
3542
- ).map(
3543
- (c) => applyOmit(core.stripNullsForNonNullableFields(c, resourceSchema), omit)
3544
- );
3531
+ ).map((c) => applyOmit(c, omit));
3545
3532
  } else if (parsed.directive === "**") {
3546
3533
  result[parsed.baseName] = filterAncestorInactiveRecords(
3547
3534
  htreeChildren(
@@ -3553,9 +3540,7 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3553
3540
  ),
3554
3541
  htreeRelation,
3555
3542
  metadata
3556
- ).map(
3557
- (d) => applyOmit(core.stripNullsForNonNullableFields(d, resourceSchema), omit)
3558
- );
3543
+ ).map((d) => applyOmit(d, omit));
3559
3544
  }
3560
3545
  includedFields.add(parsed.baseName);
3561
3546
  } else if (parsed.baseName === "parent") {
@@ -3564,9 +3549,7 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3564
3549
  resource,
3565
3550
  htreeRelation.relation,
3566
3551
  store
3567
- ).map(
3568
- (a) => applyOmit(core.stripNullsForNonNullableFields(a, resourceSchema), omit)
3569
- );
3552
+ ).map((a) => applyOmit(a, omit));
3570
3553
  includedFields.add(parsed.baseName);
3571
3554
  }
3572
3555
  continue;
@@ -3862,10 +3845,8 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3862
3845
  }
3863
3846
  const aggregations = query.aggregations || {};
3864
3847
  let results = [];
3865
- const samples = /* @__PURE__ */ new WeakMap();
3866
3848
  for (const [, groupRecords] of groups.entries()) {
3867
3849
  const row = {};
3868
- samples.set(row, groupRecords[0]);
3869
3850
  groupBy.forEach((field) => {
3870
3851
  const sample = groupRecords[0];
3871
3852
  const val = resolveValue(
@@ -3876,9 +3857,7 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3876
3857
  query.resource,
3877
3858
  resourceSchema
3878
3859
  );
3879
- if (val !== void 0) {
3880
- row[field] = val;
3881
- }
3860
+ row[field] = val;
3882
3861
  });
3883
3862
  for (const group of temporalGroups) {
3884
3863
  row[group.alias] = core.resolveTemporalBucketValue(groupRecords[0], group);
@@ -3918,24 +3897,7 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3918
3897
  paginated.length = limit;
3919
3898
  }
3920
3899
  return {
3921
- groups: paginated.map((row) => {
3922
- const output = { ...row };
3923
- for (const field of groupBy) {
3924
- if (Object.prototype.hasOwnProperty.call(aggregations, field)) continue;
3925
- if (output[field] === null && resolveValue(
3926
- samples.get(row),
3927
- field,
3928
- schema,
3929
- store,
3930
- query.resource,
3931
- resourceSchema,
3932
- true
3933
- ) === void 0) {
3934
- delete output[field];
3935
- }
3936
- }
3937
- return output;
3938
- }),
3900
+ groups: paginated,
3939
3901
  nextCursor
3940
3902
  };
3941
3903
  }
@@ -3964,10 +3926,9 @@ function orderGroupedResults(groups, sortTerms) {
3964
3926
  return 0;
3965
3927
  });
3966
3928
  }
3967
- function resolveValue(record, path, schema, store, resourceName, precomputedResource, normalize = false) {
3929
+ function resolveValue(record, path, schema, store, resourceName, precomputedResource) {
3968
3930
  if (!path.includes(".")) {
3969
- const definition2 = precomputedResource?.fields.find((field) => field.name === path);
3970
- return normalize && record[path] === null && definition2 && definition2.nullable !== true ? void 0 : record[path];
3931
+ return record[path];
3971
3932
  }
3972
3933
  const parts = path.split(".");
3973
3934
  const resource = precomputedResource ?? schema.resources.find((r) => r.name === resourceName);
@@ -4005,8 +3966,26 @@ function resolveValue(record, path, schema, store, resourceName, precomputedReso
4005
3966
  }
4006
3967
  }
4007
3968
  const lastField = parts[parts.length - 1];
4008
- const definition = schema.resources.find((entry) => entry.name === currentResource)?.fields.find((field) => field.name === lastField);
4009
- return normalize && currentRecord[lastField] === null && definition && definition.nullable !== true ? void 0 : currentRecord[lastField];
3969
+ return currentRecord[lastField];
3970
+ }
3971
+ var MAX_PUSHDOWN_IN_VALUES = 3e4;
3972
+ function isOversizedInList(adapterOp, value) {
3973
+ return adapterOp === "in" && Array.isArray(value) && value.length > MAX_PUSHDOWN_IN_VALUES;
3974
+ }
3975
+ function countInValues(filters) {
3976
+ if (Array.isArray(filters)) {
3977
+ return filters.reduce((sum, item) => sum + countInValues(item), 0);
3978
+ }
3979
+ if (typeof filters !== "object" || filters === null) return 0;
3980
+ let total = 0;
3981
+ for (const [key, value] of Object.entries(filters)) {
3982
+ if ((key === "$in" || key === "in") && Array.isArray(value)) {
3983
+ total += value.length;
3984
+ } else if (typeof value === "object" && value !== null) {
3985
+ total += countInValues(value);
3986
+ }
3987
+ }
3988
+ return total;
4010
3989
  }
4011
3990
  var DFQL_TO_ADAPTER_OP = {
4012
3991
  // $-prefixed DFQL operators
@@ -4077,6 +4056,9 @@ function convertDfqlFilters(filters, resource, schema) {
4077
4056
  if (adapterOp === null) {
4078
4057
  return null;
4079
4058
  }
4059
+ if (isOversizedInList(adapterOp, opVal)) {
4060
+ return null;
4061
+ }
4080
4062
  if (op === "$is_null" || op === "is_null") {
4081
4063
  result.push({
4082
4064
  field: key,
@@ -4162,8 +4144,26 @@ function extractPushableFilters(filters, resource, schema) {
4162
4144
  hasRemaining = true;
4163
4145
  }
4164
4146
  }
4147
+ let inBudget = MAX_PUSHDOWN_IN_VALUES;
4148
+ const withinBudget = [];
4149
+ const overBudget = [];
4150
+ for (const clause of pushable) {
4151
+ if (clause.operator === "in" && Array.isArray(clause.value)) {
4152
+ if (clause.value.length > inBudget) {
4153
+ overBudget.push({ [clause.field]: { $in: clause.value } });
4154
+ continue;
4155
+ }
4156
+ inBudget -= clause.value.length;
4157
+ }
4158
+ withinBudget.push(clause);
4159
+ }
4160
+ if (overBudget.length > 0) {
4161
+ const existing = Array.isArray(remaining.$and) ? remaining.$and : [];
4162
+ remaining.$and = [...existing, ...overBudget];
4163
+ hasRemaining = true;
4164
+ }
4165
4165
  return {
4166
- pushable,
4166
+ pushable: withinBudget,
4167
4167
  remaining: hasRemaining ? remaining : null
4168
4168
  };
4169
4169
  }
@@ -4178,6 +4178,16 @@ function classifyQuery(query, schema) {
4178
4178
  if (hasInMemoryFilterPatterns(query.filters)) {
4179
4179
  return "IN_MEMORY";
4180
4180
  }
4181
+ if (countInValues(query.filters) > MAX_PUSHDOWN_IN_VALUES) {
4182
+ return "IN_MEMORY";
4183
+ }
4184
+ if (convertDfqlFilters(
4185
+ query.filters,
4186
+ typeof query.resource === "string" ? query.resource : void 0,
4187
+ schema
4188
+ ) === null) {
4189
+ return "IN_MEMORY";
4190
+ }
4181
4191
  }
4182
4192
  if (Array.isArray(query.select)) {
4183
4193
  const relationNames = buildRelationNames(
@@ -4207,6 +4217,9 @@ function hasInMemoryFilterPatterns(filters) {
4207
4217
  if (!(op in DFQL_TO_ADAPTER_OP) || DFQL_TO_ADAPTER_OP[op] === null) {
4208
4218
  return true;
4209
4219
  }
4220
+ if (isOversizedInList(DFQL_TO_ADAPTER_OP[op], ops[op])) {
4221
+ return true;
4222
+ }
4210
4223
  }
4211
4224
  }
4212
4225
  if ((key === "$and" || key === "$or") && Array.isArray(value)) {
@@ -4240,6 +4253,7 @@ function convertSingleFilter(key, value) {
4240
4253
  if (!(op in DFQL_TO_ADAPTER_OP)) return null;
4241
4254
  const adapterOp = DFQL_TO_ADAPTER_OP[op];
4242
4255
  if (adapterOp === null) return null;
4256
+ if (isOversizedInList(adapterOp, opVal)) return null;
4243
4257
  if (op === "$is_null" || op === "is_null") {
4244
4258
  result.push({
4245
4259
  field: key,
@@ -4267,6 +4281,7 @@ function isRelationKey(key, resource, schema) {
4267
4281
  (r) => core.endpointIncludes(r.from, resource) && r.relation === key || core.endpointIncludes(r.to, resource) && r.inverse === key
4268
4282
  );
4269
4283
  }
4284
+ var FIND_BY_IDS_CHUNK = 3e4;
4270
4285
  var DbDataStore = class _DbDataStore {
4271
4286
  constructor() {
4272
4287
  this.recordsCache = /* @__PURE__ */ new Map();
@@ -4291,7 +4306,26 @@ var DbDataStore = class _DbDataStore {
4291
4306
  )
4292
4307
  );
4293
4308
  }
4309
+ /**
4310
+ * `field IN ids` in chunks, so a lookup over every record of a large table
4311
+ * stays under a driver's bound-parameter limit (Postgres: 65,535).
4312
+ */
4313
+ static async findManyByIds(db, model, field, ids, namespace) {
4314
+ const rows = [];
4315
+ for (let i = 0; i < ids.length; i += FIND_BY_IDS_CHUNK) {
4316
+ const chunk = await db.findMany({
4317
+ model,
4318
+ where: [{ field, operator: "in", value: ids.slice(i, i + FIND_BY_IDS_CHUNK) }],
4319
+ namespace
4320
+ });
4321
+ for (const row of chunk) rows.push(row);
4322
+ }
4323
+ return rows;
4324
+ }
4294
4325
  static async applyActorVisibilityFilter(store, db, schema, namespace, actorId, logger) {
4326
+ if (isNamespaceOwnerActor(actorId, namespace)) {
4327
+ return;
4328
+ }
4295
4329
  for (const [resourceName, rows] of store.recordsCache.entries()) {
4296
4330
  if (!isPrivateShareableResource(schema, resourceName)) {
4297
4331
  continue;
@@ -4390,11 +4424,7 @@ var DbDataStore = class _DbDataStore {
4390
4424
  idsByResource.set(resource, current);
4391
4425
  }
4392
4426
  for (const [resource, resourceIds] of idsByResource.entries()) {
4393
- const rows = resourceIds.length > 0 ? await db.findMany({
4394
- model: resource,
4395
- where: [{ field: "id", operator: "in", value: resourceIds }],
4396
- namespace
4397
- }) : [];
4427
+ const rows = resourceIds.length > 0 ? await _DbDataStore.findManyByIds(db, resource, "id", resourceIds, namespace) : [];
4398
4428
  store.mergeRecords(resource, rows);
4399
4429
  }
4400
4430
  for (const resource of core.endpointList(endpoint)) {
@@ -4433,11 +4463,7 @@ var DbDataStore = class _DbDataStore {
4433
4463
  const fkField = rel.fkField || rel.foreignKey || `${rel.inverse}Id`;
4434
4464
  try {
4435
4465
  for (const fromResource of core.endpointList(rel.from)) {
4436
- const rows = primaryIds.length > 0 ? await db.findMany({
4437
- model: fromResource,
4438
- where: [{ field: fkField, operator: "in", value: primaryIds }],
4439
- namespace
4440
- }) : [];
4466
+ const rows = primaryIds.length > 0 ? await _DbDataStore.findManyByIds(db, fromResource, fkField, primaryIds, namespace) : [];
4441
4467
  store.recordsCache.set(fromResource, rows);
4442
4468
  }
4443
4469
  } catch (error) {
@@ -4448,11 +4474,7 @@ var DbDataStore = class _DbDataStore {
4448
4474
  const fkField = rel.fkField || rel.foreignKey || `${rel.inverse}Id`;
4449
4475
  try {
4450
4476
  for (const toResource of core.endpointList(rel.to)) {
4451
- const rows = primaryIds.length > 0 ? await db.findMany({
4452
- model: toResource,
4453
- where: [{ field: fkField, operator: "in", value: primaryIds }],
4454
- namespace
4455
- }) : [];
4477
+ const rows = primaryIds.length > 0 ? await _DbDataStore.findManyByIds(db, toResource, fkField, primaryIds, namespace) : [];
4456
4478
  store.recordsCache.set(toResource, rows);
4457
4479
  }
4458
4480
  } catch (error) {
@@ -4480,11 +4502,7 @@ var DbDataStore = class _DbDataStore {
4480
4502
  let joinRows = [];
4481
4503
  try {
4482
4504
  const filterField = isForward ? fromCol : toCol;
4483
- joinRows = primaryIds.length > 0 ? await db.findMany({
4484
- model: tableName,
4485
- where: [{ field: filterField, operator: "in", value: primaryIds }],
4486
- namespace
4487
- }) : [];
4505
+ joinRows = primaryIds.length > 0 ? await _DbDataStore.findManyByIds(db, tableName, filterField, primaryIds, namespace) : [];
4488
4506
  } catch (error) {
4489
4507
  logger?.warn("forPushdownResult: many-many join load failed", { error: String(error), operation: "db-store-pushdown" });
4490
4508
  joinRows = [];
@@ -4547,11 +4565,7 @@ var DbDataStore = class _DbDataStore {
4547
4565
  const relationKey2 = core.relationKeyFor(fromResource, rel2);
4548
4566
  let joinRows2 = [];
4549
4567
  try {
4550
- joinRows2 = intermediateIds.length > 0 ? await db.findMany({
4551
- model: tableName2,
4552
- where: [{ field: isF2 ? fromCol2 : toCol2, operator: "in", value: intermediateIds }],
4553
- namespace
4554
- }) : [];
4568
+ joinRows2 = intermediateIds.length > 0 ? await _DbDataStore.findManyByIds(db, tableName2, isF2 ? fromCol2 : toCol2, intermediateIds, namespace) : [];
4555
4569
  } catch (error) {
4556
4570
  logger?.warn("forPushdownResult: nested many-many join load failed", { error: String(error), operation: "db-store-pushdown" });
4557
4571
  joinRows2 = [];
@@ -4584,11 +4598,7 @@ var DbDataStore = class _DbDataStore {
4584
4598
  const fkField2 = rel2.fkField || rel2.foreignKey || `${rel2.inverse}Id`;
4585
4599
  try {
4586
4600
  for (const targetResource of core.endpointList(rel2.to)) {
4587
- const rows2 = intermediateIds.length > 0 ? await db.findMany({
4588
- model: targetResource,
4589
- where: [{ field: fkField2, operator: "in", value: intermediateIds }],
4590
- namespace
4591
- }) : [];
4601
+ const rows2 = intermediateIds.length > 0 ? await _DbDataStore.findManyByIds(db, targetResource, fkField2, intermediateIds, namespace) : [];
4592
4602
  store.mergeRecords(targetResource, rows2);
4593
4603
  }
4594
4604
  } catch (error) {
@@ -4842,14 +4852,13 @@ var DbDataStore = class _DbDataStore {
4842
4852
  const filterField = primaryIsFrom ? fromCol : toCol;
4843
4853
  const secondaryEndpoint = primaryIsFrom ? rel.to : rel.from;
4844
4854
  try {
4845
- let joinRows = [];
4846
- if (primaryIds.length > 0) {
4847
- joinRows = await db.findMany({
4848
- model: tableName,
4849
- where: [{ field: filterField, operator: "in", value: primaryIds }],
4850
- namespace
4851
- });
4852
- }
4855
+ const joinRows = await _DbDataStore.findManyByIds(
4856
+ db,
4857
+ tableName,
4858
+ filterField,
4859
+ primaryIds,
4860
+ namespace
4861
+ );
4853
4862
  const normalizedRows = _DbDataStore.normalizeJoinRows(joinRows, fromCol, toCol);
4854
4863
  const rowsForRelation = _DbDataStore.filterJoinRowsForResource(
4855
4864
  schema,
@@ -4873,13 +4882,13 @@ var DbDataStore = class _DbDataStore {
4873
4882
  idsByResource.set(secondaryResource, ids);
4874
4883
  }
4875
4884
  for (const [secondaryModel, ids] of idsByResource.entries()) {
4876
- const records = ids.length > 0 ? await db.findMany({
4877
- model: secondaryModel,
4878
- where: [
4879
- { field: "id", operator: "in", value: ids }
4880
- ],
4885
+ const records = await _DbDataStore.findManyByIds(
4886
+ db,
4887
+ secondaryModel,
4888
+ "id",
4889
+ ids,
4881
4890
  namespace
4882
- }) : [];
4891
+ );
4883
4892
  store.mergeRecords(secondaryModel, records);
4884
4893
  manyManySecondaries.add(secondaryModel);
4885
4894
  }
@@ -4924,29 +4933,17 @@ var DbDataStore = class _DbDataStore {
4924
4933
  )
4925
4934
  ];
4926
4935
  if (fkValues.length > 0) {
4927
- records = await db.findMany({
4928
- model: secondaryResource,
4929
- where: [{ field: "id", operator: "in", value: fkValues }],
4930
- namespace
4931
- });
4936
+ records = await _DbDataStore.findManyByIds(db, secondaryResource, "id", fkValues, namespace);
4932
4937
  }
4933
4938
  } else if (rel.type === "many-one" && !isForward) {
4934
4939
  const fkField = rel.fkField || rel.foreignKey || `${rel.relation}Id`;
4935
4940
  if (primaryIds.length > 0) {
4936
- records = await db.findMany({
4937
- model: secondaryResource,
4938
- where: [{ field: fkField, operator: "in", value: primaryIds }],
4939
- namespace
4940
- });
4941
+ records = await _DbDataStore.findManyByIds(db, secondaryResource, fkField, primaryIds, namespace);
4941
4942
  }
4942
4943
  } else if (rel.type === "one-many" && isForward) {
4943
4944
  const fkField = rel.fkField || rel.foreignKey || rel.inverse || `${query.resource}Id`;
4944
4945
  if (primaryIds.length > 0) {
4945
- records = await db.findMany({
4946
- model: secondaryResource,
4947
- where: [{ field: fkField, operator: "in", value: primaryIds }],
4948
- namespace
4949
- });
4946
+ records = await _DbDataStore.findManyByIds(db, secondaryResource, fkField, primaryIds, namespace);
4950
4947
  }
4951
4948
  } else if (rel.type === "one-many" && !isForward) {
4952
4949
  const fkField = rel.fkField || rel.foreignKey || rel.relation || `${secondaryResource}Id`;
@@ -4956,11 +4953,7 @@ var DbDataStore = class _DbDataStore {
4956
4953
  )
4957
4954
  ];
4958
4955
  if (fkValues.length > 0) {
4959
- records = await db.findMany({
4960
- model: secondaryResource,
4961
- where: [{ field: "id", operator: "in", value: fkValues }],
4962
- namespace
4963
- });
4956
+ records = await _DbDataStore.findManyByIds(db, secondaryResource, "id", fkValues, namespace);
4964
4957
  }
4965
4958
  } else {
4966
4959
  logger?.warn("Unhandled relation type for secondary resource; returning empty set instead of full scan", {
@@ -5156,11 +5149,22 @@ async function pushdownCore(query, schema, db, namespace) {
5156
5149
  if (metadata?.accessMode === "sharedWithMe" && (metadata.enforceAclIndexCatalog === true || Array.isArray(metadata.aclIndexCatalog))) {
5157
5150
  assertRequiredAclIndexes(metadata.aclIndexCatalog ?? []);
5158
5151
  }
5159
- const whereClauses = queryWithAutoFilters.filters ? convertDfqlFilters(
5160
- queryWithAutoFilters.filters,
5161
- queryWithAutoFilters.resource,
5162
- schema
5163
- ) ?? [] : [];
5152
+ let whereClauses = [];
5153
+ if (queryWithAutoFilters.filters) {
5154
+ const converted = convertDfqlFilters(
5155
+ queryWithAutoFilters.filters,
5156
+ queryWithAutoFilters.resource,
5157
+ schema
5158
+ );
5159
+ if (converted === null) {
5160
+ throw new DatafnExecutionError(
5161
+ "INTERNAL",
5162
+ "Query filters cannot be pushed down to the database",
5163
+ "filters"
5164
+ );
5165
+ }
5166
+ whereClauses = converted;
5167
+ }
5164
5168
  const orderBy = convertDfqlSort(queryWithAutoFilters.sort);
5165
5169
  const sortTerms = parseSortTerms(queryWithAutoFilters.sort);
5166
5170
  const hasCursor = queryWithAutoFilters.cursor?.after != null || queryWithAutoFilters.cursor?.before != null;
@@ -5236,7 +5240,6 @@ async function pushdownCore(query, schema, db, namespace) {
5236
5240
  function projectFieldsPushdown(record, resource, schema, select, omit) {
5237
5241
  const resourceSchema = schema.resources.find((r) => r.name === resource);
5238
5242
  if (!resourceSchema) return { id: record.id };
5239
- record = core.stripNullsForNonNullableFields(record, resourceSchema);
5240
5243
  const resolvedCapabilities = core.resolveCapabilities(
5241
5244
  schema.capabilities,
5242
5245
  resourceSchema.capabilities
@@ -6005,213 +6008,6 @@ var AuthResolverCache = class {
6005
6008
  function createAuthResolverCache() {
6006
6009
  return new AuthResolverCache();
6007
6010
  }
6008
- var scopes = /* @__PURE__ */ new Set([
6009
- "query",
6010
- "search",
6011
- "mutation",
6012
- "transact",
6013
- "seed",
6014
- "clone",
6015
- "pull",
6016
- "push",
6017
- "reconcile",
6018
- "custom",
6019
- "websocket"
6020
- ]);
6021
- var text = (value) => typeof value === "string" && value.trim().length > 0 && value.length <= 1024;
6022
- function routeTicketError(code) {
6023
- return new DatafnRoutingError({
6024
- code,
6025
- message: code,
6026
- status: code === "DATAFN_ROUTE_RATE_LIMITED" ? 429 : code === "DATAFN_ROUTE_FORBIDDEN" ? 403 : 401,
6027
- retryable: code === "DATAFN_ROUTE_TICKET_EXPIRED" || code === "DATAFN_ROUTE_RATE_LIMITED",
6028
- executionStarted: false
6029
- });
6030
- }
6031
- function assertClaims(value) {
6032
- if (!value || value.version !== 1 || ![value.issuer, value.audience, value.subject, value.namespace, value.regionId, value.ticketId].every(text) || !Number.isSafeInteger(value.epoch) || value.epoch < 1 || ![value.issuedAt, value.notBefore, value.expiresAt].every(Number.isSafeInteger) || value.notBefore < value.issuedAt || value.notBefore >= value.expiresAt || value.expiresAt - value.issuedAt > core.DATAFN_ROUTE_MAX_TTL_MS || !Array.isArray(value.scopes) || value.scopes.length === 0 || value.scopes.some((scope) => !scopes.has(scope)) || new Set(value.scopes).size !== value.scopes.length || value.sessionBinding !== void 0 && !text(value.sessionBinding)) {
6033
- throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6034
- }
6035
- }
6036
- function createDatafnHmacRouteTickets(input) {
6037
- const keys = new Map(Object.entries(input.keys).map(([id, key]) => {
6038
- if (!/^[A-Za-z0-9_-]{1,128}$/.test(id) || Buffer.byteLength(key) < 32) {
6039
- throw new Error("DATAFN_ROUTE_KEY_INVALID");
6040
- }
6041
- return [id, Buffer.from(key)];
6042
- }));
6043
- if (!keys.has(input.activeKeyId)) throw new Error("DATAFN_ROUTE_ACTIVE_KEY_MISSING");
6044
- const signature = (content, key) => crypto$1.createHmac("sha256", key).update(`datafn-regional-route-v1:${content}`).digest();
6045
- return {
6046
- sign(claims) {
6047
- assertClaims(claims);
6048
- const header = Buffer.from(JSON.stringify({ typ: "datafn-route-v1", alg: "HS256", kid: input.activeKeyId })).toString("base64url");
6049
- const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
6050
- const content = `${header}.${payload}`;
6051
- return `${content}.${signature(content, keys.get(input.activeKeyId)).toString("base64url")}`;
6052
- },
6053
- verify(ticket) {
6054
- try {
6055
- if (typeof ticket !== "string" || ticket.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(ticket)) throw new Error();
6056
- const [header, payload, mac] = ticket.split(".");
6057
- const protectedHeader = JSON.parse(Buffer.from(header, "base64url").toString());
6058
- const key = keys.get(protectedHeader.kid);
6059
- if (!key || protectedHeader.typ !== "datafn-route-v1" || protectedHeader.alg !== "HS256") throw new Error();
6060
- const expected = signature(`${header}.${payload}`, key);
6061
- const actual = Buffer.from(mac, "base64url");
6062
- if (actual.length !== expected.length || !crypto$1.timingSafeEqual(actual, expected)) throw new Error();
6063
- const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
6064
- assertClaims(claims);
6065
- return claims;
6066
- } catch {
6067
- throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6068
- }
6069
- }
6070
- };
6071
- }
6072
- function createDatafnRouteBootstrap(config) {
6073
- const ttl = config.ttlMs ?? 6e4;
6074
- if (!text(config.issuer) || !Number.isSafeInteger(ttl) || ttl < 1e3 || ttl > core.DATAFN_ROUTE_MAX_TTL_MS) {
6075
- throw new Error("DATAFN_ROUTE_BOOTSTRAP_CONFIG_INVALID");
6076
- }
6077
- const now = config.now ?? Date.now;
6078
- return async (request) => {
6079
- try {
6080
- if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST", "cache-control": "no-store" } });
6081
- const identity = await config.authenticate(request);
6082
- if (!identity || !text(identity.subject) || !text(identity.namespace)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6083
- let placement;
6084
- try {
6085
- placement = await config.directory.get(identity.namespace);
6086
- } catch {
6087
- throw new DatafnRoutingError({ code: "DATAFN_PLACEMENT_UNAVAILABLE", message: "Placement unavailable", status: 503, retryable: true });
6088
- }
6089
- if (!placement || placement.namespace !== identity.namespace || placement.state === "tombstoned") {
6090
- throw new DatafnRoutingError({ code: "DATAFN_PLACEMENT_NOT_FOUND", message: "Placement not found", status: 404, retryable: false });
6091
- }
6092
- if (placement.state !== "active" || placement.migration) {
6093
- throw new DatafnRoutingError({ code: "DATAFN_NAMESPACE_MOVING", message: "Placement is fenced", status: 409, retryable: true });
6094
- }
6095
- const permitted = [...await config.authorize(identity)];
6096
- const endpoint = await config.resolveEndpoint(placement);
6097
- const issuedAt = now();
6098
- const expiresAt = Math.min(issuedAt + ttl, identity.expiresAt ?? Infinity);
6099
- if (!Number.isSafeInteger(expiresAt) || expiresAt <= issuedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6100
- const httpUrl = core.validateDatafnRegionalEndpoint(endpoint.httpUrl);
6101
- const wsUrl = endpoint.wsUrl ? core.validateDatafnRegionalEndpoint(endpoint.wsUrl, true) : void 0;
6102
- if (permitted.includes("websocket") && !wsUrl) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6103
- const ticket = await config.signer.sign({
6104
- version: 1,
6105
- issuer: config.issuer,
6106
- audience: endpoint.audience,
6107
- subject: identity.subject,
6108
- namespace: identity.namespace,
6109
- regionId: placement.regionId,
6110
- epoch: placement.epoch,
6111
- scopes: permitted,
6112
- issuedAt,
6113
- notBefore: issuedAt,
6114
- expiresAt,
6115
- ticketId: crypto$1.randomUUID(),
6116
- ...identity.sessionBinding ? { sessionBinding: identity.sessionBinding } : {}
6117
- });
6118
- const descriptor = {
6119
- version: 1,
6120
- httpUrl,
6121
- ...wsUrl ? { wsUrl } : {},
6122
- ticket,
6123
- expiresAt,
6124
- renewAfter: issuedAt + Math.floor((expiresAt - issuedAt) * 0.8)
6125
- };
6126
- emit(config, { type: "issued" });
6127
- return Response.json(descriptor, { headers: { "cache-control": "no-store", pragma: "no-cache" } });
6128
- } catch (error) {
6129
- emit(config, { type: "rejected", code: error instanceof DatafnRoutingError ? error.code : "DATAFN_ROUTE_FORBIDDEN" });
6130
- return (error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_FORBIDDEN")).toResponse();
6131
- }
6132
- };
6133
- }
6134
- function readDatafnRouteTicket(request, websocket = false) {
6135
- const header = request.headers.get(core.DATAFN_ROUTE_TICKET_HEADER);
6136
- const protocols = (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
6137
- const tickets = protocols.filter((s) => s.startsWith(core.DATAFN_ROUTE_WS_TICKET_PREFIX));
6138
- if (tickets.length > 1 || header && tickets.length || !websocket && tickets.length || tickets.length && !protocols.includes(core.DATAFN_ROUTE_WS_PROTOCOL)) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6139
- return header ?? tickets[0]?.slice(core.DATAFN_ROUTE_WS_TICKET_PREFIX.length);
6140
- }
6141
- async function validateDatafnRouteTicket(input) {
6142
- const { runtime } = input;
6143
- try {
6144
- const origin = input.request.headers.get("origin");
6145
- if (origin && !runtime.allowedOrigins?.includes(origin)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6146
- const token = readDatafnRouteTicket(input.request, input.scope === "websocket");
6147
- if (!token) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6148
- const claims = await runtime.verifier.verify(token);
6149
- assertClaims(claims);
6150
- const now = (runtime.now ?? Date.now)();
6151
- const skew = runtime.clockSkewMs ?? 5e3;
6152
- if (!Number.isFinite(skew) || skew < 0 || skew > 3e4) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6153
- if (claims.expiresAt <= now) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6154
- if (claims.issuedAt > now + skew || claims.notBefore > now + skew || claims.issuer !== runtime.issuer || claims.audience !== runtime.audience || claims.regionId !== input.regionId || claims.namespace !== input.namespace || !claims.scopes.includes(input.scope)) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6155
- const identity = await runtime.authenticate(input.request);
6156
- if (!identity || identity.subject !== claims.subject || identity.namespace !== claims.namespace || identity.sessionBinding !== claims.sessionBinding || identity.expiresAt !== void 0 && (!Number.isFinite(identity.expiresAt) || identity.expiresAt <= (runtime.now ?? Date.now)())) {
6157
- throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6158
- }
6159
- if (identity.expiresAt !== void 0 && claims.expiresAt > identity.expiresAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6160
- if (runtime.isActive && !await runtime.isActive(claims)) throw routeTicketError("DATAFN_ROUTE_TICKET_REVOKED");
6161
- if (runtime.allowRequest && !await runtime.allowRequest(claims)) throw routeTicketError("DATAFN_ROUTE_RATE_LIMITED");
6162
- const admittedAt = (runtime.now ?? Date.now)();
6163
- if (identity.expiresAt !== void 0 && identity.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6164
- if (claims.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6165
- emit(runtime, { type: "accepted" });
6166
- return claims;
6167
- } catch (error) {
6168
- const safe = error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6169
- emit(runtime, { type: "rejected", code: safe.code });
6170
- throw safe;
6171
- }
6172
- }
6173
- function withDatafnRegionalCors(handler, options) {
6174
- const origins = new Set(options.origins.map((origin) => {
6175
- if (new URL(origin).origin !== origin || origin === "null") throw new Error("DATAFN_ROUTE_ORIGIN_INVALID");
6176
- return origin;
6177
- }));
6178
- const allowedHeaders = /* @__PURE__ */ new Set([
6179
- "content-type",
6180
- "authorization",
6181
- core.DATAFN_ROUTE_TICKET_HEADER,
6182
- ...(options.headers ?? []).map((header) => header.toLowerCase())
6183
- ]);
6184
- const allowedMethods = ["GET", "POST", "PATCH", "DELETE"];
6185
- return async (request) => {
6186
- const origin = request.headers.get("origin");
6187
- if (origin && !origins.has(origin)) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6188
- if (request.method === "OPTIONS") {
6189
- const method = request.headers.get("access-control-request-method");
6190
- const headers2 = (request.headers.get("access-control-request-headers") ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
6191
- if (!origin || !allowedMethods.includes(method ?? "") || headers2.some((h) => !allowedHeaders.has(h))) return new Response(null, { status: 403 });
6192
- return new Response(null, { status: 204, headers: {
6193
- "access-control-allow-origin": origin,
6194
- "access-control-allow-methods": allowedMethods.join(", "),
6195
- "access-control-allow-headers": [...allowedHeaders].join(", "),
6196
- vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
6197
- "cache-control": "no-store"
6198
- } });
6199
- }
6200
- const response = await handler(request);
6201
- const headers = new Headers(response.headers);
6202
- headers.append("vary", "Origin");
6203
- headers.delete("access-control-allow-credentials");
6204
- headers.set("cache-control", "no-store");
6205
- if (origin) headers.set("access-control-allow-origin", origin);
6206
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
6207
- };
6208
- }
6209
- function emit(config, event) {
6210
- try {
6211
- config.onEvent?.(event);
6212
- } catch {
6213
- }
6214
- }
6215
6011
  var DATAFN_ROUTING_ASSERTION_HEADER = "x-datafn-routing-assertion";
6216
6012
  var DATAFN_ROUTING_INTERNAL_HEADERS = [
6217
6013
  DATAFN_ROUTING_ASSERTION_HEADER,
@@ -6363,28 +6159,6 @@ async function claimDatafnNamespacePlacement(input) {
6363
6159
  async function validateDatafnPlacement(input) {
6364
6160
  const startedAt = Date.now();
6365
6161
  const requestId2 = input.request?.headers.get("x-request-id") ?? void 0;
6366
- let ticket;
6367
- const hasAssertion = Boolean(input.request?.headers.get(input.runtime.assertionHeader ?? DATAFN_ROUTING_ASSERTION_HEADER)?.trim());
6368
- if (input.request) {
6369
- const token = readDatafnRouteTicket(input.request, input.scope === "websocket");
6370
- if (token !== void 0 && (hasAssertion || !input.runtime.routeTickets)) {
6371
- throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6372
- }
6373
- if (input.runtime.routeTickets && (!hasAssertion || token !== void 0)) {
6374
- if (DATAFN_ROUTING_INTERNAL_HEADERS.some((name) => input.request.headers.has(name))) {
6375
- throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6376
- }
6377
- ticket = await validateDatafnRouteTicket({
6378
- request: input.request,
6379
- namespace: input.namespace,
6380
- regionId: input.regionId,
6381
- scope: input.scope ?? "custom",
6382
- runtime: input.runtime.routeTickets
6383
- });
6384
- }
6385
- } else if (input.runtime.routeTickets && !input.trustedInternal) {
6386
- throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6387
- }
6388
6162
  let placement;
6389
6163
  try {
6390
6164
  placement = await input.runtime.directory.get(input.namespace);
@@ -6422,7 +6196,7 @@ async function validateDatafnPlacement(input) {
6422
6196
  retryable: false
6423
6197
  });
6424
6198
  }
6425
- const assertion = ticket ? void 0 : await validateRoutingAssertion({
6199
+ const assertion = await validateRoutingAssertion({
6426
6200
  namespace: input.namespace,
6427
6201
  regionId: input.regionId,
6428
6202
  placement,
@@ -6478,7 +6252,7 @@ async function validateDatafnPlacement(input) {
6478
6252
  internal: Boolean(assertion)
6479
6253
  });
6480
6254
  }
6481
- if (assertion && assertion.epoch !== placement.epoch || ticket && ticket.epoch !== placement.epoch) {
6255
+ if (assertion && assertion.epoch !== placement.epoch) {
6482
6256
  await emitRoutingEvent(input.runtime, {
6483
6257
  type: "mismatch",
6484
6258
  requestId: requestId2,
@@ -6491,17 +6265,14 @@ async function validateDatafnPlacement(input) {
6491
6265
  });
6492
6266
  throw new DatafnRoutingError({
6493
6267
  code: "DATAFN_REGION_MISMATCH",
6494
- message: "Routing grant uses a stale placement epoch",
6268
+ message: "Routing assertion uses a stale placement epoch",
6495
6269
  status: 409,
6496
6270
  retryable: true,
6497
6271
  placement,
6498
- internal: Boolean(assertion)
6272
+ internal: true
6499
6273
  });
6500
6274
  }
6501
- if (ticket && ticket.expiresAt <= (input.runtime.routeTickets?.now ?? Date.now)()) {
6502
- throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6503
- }
6504
- return { placement, ...assertion ? { assertion } : {}, ...ticket ? { ticket } : {} };
6275
+ return { placement, ...assertion ? { assertion } : {} };
6505
6276
  }
6506
6277
  function createDatafnGatewayRouter(config) {
6507
6278
  const maxBodyBytes = validateDatafnRoutingBodyLimit(config.maxBodyBytes);
@@ -7791,6 +7562,9 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
7791
7562
  if (!actorId) {
7792
7563
  return { shareableAccessIds: [] };
7793
7564
  }
7565
+ if (isNamespaceOwnerActor(actorId, namespace)) {
7566
+ return { shareableAccessIds: [], hasShareableScopeAccess: true };
7567
+ }
7794
7568
  const ids = /* @__PURE__ */ new Set();
7795
7569
  const readMode = getSpv2MigrationRuntimeConfig().readMode;
7796
7570
  const ownedRows = await db.findMany({
@@ -8334,10 +8108,15 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
8334
8108
  namespace,
8335
8109
  actorId
8336
8110
  ).then((shareableAccess) => {
8111
+ const {
8112
+ shareableAccessIds: _clientAccessIds,
8113
+ hasShareableScopeAccess: _clientScopeAccess,
8114
+ ...clientMetadata
8115
+ } = metadata ?? {};
8337
8116
  const queryWithMetadata = {
8338
8117
  ...query,
8339
8118
  metadata: {
8340
- ...metadata ?? {},
8119
+ ...clientMetadata,
8341
8120
  ...shareableAccess ?? {}
8342
8121
  }
8343
8122
  };
@@ -8457,8 +8236,9 @@ async function recordChangesWithRetry(changeTracking, entries, maxRetries = 2, l
8457
8236
  }
8458
8237
  }
8459
8238
  }
8239
+ var preparedNamespaces = /* @__PURE__ */ new WeakMap();
8460
8240
  var ChangeTrackingService = class _ChangeTrackingService {
8461
- constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false) {
8241
+ constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false, namespaceMetaEnsured = false) {
8462
8242
  this.db = db;
8463
8243
  this.namespace = namespace;
8464
8244
  this.sequenceStore = sequenceStore;
@@ -8466,8 +8246,10 @@ var ChangeTrackingService = class _ChangeTrackingService {
8466
8246
  this.logger = logger;
8467
8247
  this.metaEnsured = false;
8468
8248
  this.changesEnsured = false;
8249
+ this.namespaceMetaEnsured = false;
8469
8250
  this.metaEnsured = metaEnsured;
8470
8251
  this.changesEnsured = changesEnsured;
8252
+ this.namespaceMetaEnsured = namespaceMetaEnsured;
8471
8253
  }
8472
8254
  /** Initialize every durable table before an enclosing transaction begins. */
8473
8255
  async ensureReady() {
@@ -8482,6 +8264,48 @@ var ChangeTrackingService = class _ChangeTrackingService {
8482
8264
  await ensureInternalTable(this.db, "__datafn_meta");
8483
8265
  this.metaEnsured = true;
8484
8266
  }
8267
+ await this.ensureNamespaceMeta();
8268
+ }
8269
+ /**
8270
+ * Creates this namespace's `__datafn_meta` row before an enclosing
8271
+ * transaction begins. Sequence allocation otherwise creates the row inside
8272
+ * the transaction on a namespace's first write, and when two first writes
8273
+ * race, the losing INSERT fails with a unique-key conflict. On PostgreSQL that
8274
+ * aborts the whole transaction, so the recovery read that follows fails with
8275
+ * "current transaction is aborted". Outside a transaction the conflict is
8276
+ * harmless: the row exists either way, and later allocations only read and
8277
+ * CAS-update it. Transaction-bound instances (from `withDb`) never prepare
8278
+ * the row; the base instance does so before the transaction opens.
8279
+ */
8280
+ async ensureNamespaceMeta() {
8281
+ if (this.namespaceMetaEnsured) {
8282
+ return;
8283
+ }
8284
+ let prepared = preparedNamespaces.get(this.db);
8285
+ if (!prepared) {
8286
+ prepared = /* @__PURE__ */ new Set();
8287
+ preparedNamespaces.set(this.db, prepared);
8288
+ }
8289
+ if (prepared.has(this.namespace)) {
8290
+ this.namespaceMetaEnsured = true;
8291
+ return;
8292
+ }
8293
+ const where = [{ field: "namespace", op: "eq", value: this.namespace }];
8294
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8295
+ try {
8296
+ await this.db.internal.create("__datafn_meta", {
8297
+ id: `meta:${this.namespace}`,
8298
+ namespace: this.namespace,
8299
+ next_server_seq: 1
8300
+ });
8301
+ } catch (error) {
8302
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8303
+ throw error;
8304
+ }
8305
+ }
8306
+ }
8307
+ prepared.add(this.namespace);
8308
+ this.namespaceMetaEnsured = true;
8485
8309
  }
8486
8310
  /**
8487
8311
  * REL-011: Create a new ChangeTrackingService with a different db adapter.
@@ -8497,7 +8321,8 @@ var ChangeTrackingService = class _ChangeTrackingService {
8497
8321
  emitChanges ? this.onChange : void 0,
8498
8322
  this.logger,
8499
8323
  this.metaEnsured,
8500
- this.changesEnsured
8324
+ this.changesEnsured,
8325
+ true
8501
8326
  );
8502
8327
  }
8503
8328
  /**
@@ -8932,16 +8757,12 @@ function buildReplaceRecord(schema, resourceName, existingRecord, newRecord, res
8932
8757
  result[key] = existingRecord[key];
8933
8758
  continue;
8934
8759
  }
8935
- if (field.readonly) {
8936
- result[key] = Object.prototype.hasOwnProperty.call(newRecord, key) ? newRecord[key] : existingRecord[key];
8937
- continue;
8938
- }
8939
8760
  if (Object.prototype.hasOwnProperty.call(newRecord, key)) {
8940
8761
  result[key] = newRecord[key];
8941
8762
  } else {
8942
8763
  result[key] = field.default !== void 0 ? field.default : null;
8943
8764
  }
8944
- if (field.required && (result[key] === void 0 || result[key] === null && !field.nullable)) {
8765
+ if (field.required && (result[key] === null || result[key] === void 0)) {
8945
8766
  return {
8946
8767
  ok: false,
8947
8768
  code: "DFQL_INVALID",
@@ -9028,7 +8849,8 @@ function isRecordEffectivelyInactive(record) {
9028
8849
  return isRecordInactive(record) || record?.isAncestorInactive === true;
9029
8850
  }
9030
8851
  function resourceSupportsAncestorInactive(schema, resource) {
9031
- return core.resourceRequiresAncestorInactive(schema.relations, resource);
8852
+ const resourceSchema = schema.resources.find((candidate) => candidate.name === resource);
8853
+ return resourceSchema?.fields.some((field) => field.name === "isAncestorInactive") === true;
9032
8854
  }
9033
8855
  function dependentEndpoint(relation) {
9034
8856
  return relation.type === "many-one" ? relation.from : relation.to;
@@ -10447,7 +10269,7 @@ function decideMergeMode(schema, resource, id, delta) {
10447
10269
  for (const field of resourceDef.fields) {
10448
10270
  if (!field.required) continue;
10449
10271
  if (field.name === "id" || field.name === "__ns") continue;
10450
- const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && (delta[field.name] !== null || field.nullable === true);
10272
+ const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && delta[field.name] !== null;
10451
10273
  const hasDefault = field.default !== void 0;
10452
10274
  if (!hasProvided && !hasDefault) return { mode: "not_found" };
10453
10275
  }
@@ -12186,64 +12008,6 @@ async function drainPermissionDirectoryOutbox(db, runtime, logger, limit = 100)
12186
12008
  }
12187
12009
  return { processed, pending: tasks.length - processed };
12188
12010
  }
12189
- async function drainNamespacePermissionDirectoryOutbox(db, namespace, runtime, logger, options = {}) {
12190
- await ensurePermissionDirectoryOutbox(db);
12191
- const limit = options.limit ?? 100;
12192
- const maxRounds = options.maxRounds ?? 32;
12193
- let processed = 0;
12194
- for (let round = 0; round < maxRounds; round += 1) {
12195
- const tasks = await db.internal.findMany(OUTBOX_TABLE, [
12196
- { field: "namespace", op: "eq", value: namespace },
12197
- { field: "region_id", op: "eq", value: runtime.regionId },
12198
- { field: "next_attempt_at", op: "lte", value: (/* @__PURE__ */ new Date()).toISOString() }
12199
- ], {
12200
- orderBy: "next_attempt_at",
12201
- limit
12202
- });
12203
- if (tasks.length === 0) {
12204
- break;
12205
- }
12206
- let roundProcessed = 0;
12207
- for (const task of tasks) {
12208
- const taskId = String(task.id);
12209
- const selectedNextAttemptAt = String(task.next_attempt_at);
12210
- const claimedNextAttemptAt = new Date(
12211
- Date.now() + DRAIN_CLAIM_LEASE_MS
12212
- ).toISOString();
12213
- const claimed = await db.internal.update(OUTBOX_TABLE, [
12214
- { field: "id", op: "eq", value: taskId },
12215
- { field: "namespace", op: "eq", value: namespace },
12216
- { field: "region_id", op: "eq", value: runtime.regionId },
12217
- { field: "next_attempt_at", op: "eq", value: selectedNextAttemptAt }
12218
- ], {
12219
- next_attempt_at: claimedNextAttemptAt
12220
- });
12221
- if (claimed === 0) continue;
12222
- if (await drainPermissionDirectorySync(
12223
- db,
12224
- taskId,
12225
- runtime,
12226
- logger,
12227
- { expectedNextAttemptAt: claimedNextAttemptAt }
12228
- )) {
12229
- processed += 1;
12230
- roundProcessed += 1;
12231
- }
12232
- }
12233
- if (roundProcessed === 0) {
12234
- const remaining2 = await db.internal.findMany(OUTBOX_TABLE, [
12235
- { field: "namespace", op: "eq", value: namespace },
12236
- { field: "region_id", op: "eq", value: runtime.regionId }
12237
- ], { limit: 1 });
12238
- return { processed, pending: remaining2.length };
12239
- }
12240
- }
12241
- const remaining = await db.internal.findMany(OUTBOX_TABLE, [
12242
- { field: "namespace", op: "eq", value: namespace },
12243
- { field: "region_id", op: "eq", value: runtime.regionId }
12244
- ], { limit: 1 });
12245
- return { processed, pending: remaining.length };
12246
- }
12247
12011
 
12248
12012
  // src/execution/mutation/execute.ts
12249
12013
  var FAILED_SHARE_COMPENSATION_RESULT = /* @__PURE__ */ Symbol("failedShareCompensation");
@@ -12345,23 +12109,6 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12345
12109
  let additionalChanges = [];
12346
12110
  let skipChangeTracking = false;
12347
12111
  let failedShareCompensation = null;
12348
- if ((mutation.operation === "insert" || mutation.operation === "merge" || mutation.operation === "replace") && mutation.record) {
12349
- const systemField = core.findSystemFieldWrite(schema.relations, mutation.resource, mutation.record);
12350
- if (systemField) {
12351
- return {
12352
- ok: false,
12353
- mutationId: effectiveMutationId,
12354
- affectedIds: [],
12355
- errors: [{
12356
- code: "DFQL_INVALID",
12357
- message: `Field is read-only: ${systemField} on ${mutation.resource}`,
12358
- path: `record.${systemField}`,
12359
- retryable: false
12360
- }],
12361
- deduped: false
12362
- };
12363
- }
12364
- }
12365
12112
  try {
12366
12113
  switch (mutation.operation) {
12367
12114
  case "insert":
@@ -14110,6 +13857,14 @@ function resourceIdMatches(schema, candidates, resourceName, id) {
14110
13857
  }
14111
13858
 
14112
13859
  // src/execution/sync/clone.ts
13860
+ var JoinVisibilityError = class extends Error {
13861
+ constructor(reason) {
13862
+ super("Clone: join endpoint access check failed");
13863
+ this.reason = reason;
13864
+ }
13865
+ };
13866
+ var JOIN_LOOKUP_CHUNK = 90;
13867
+ var JOIN_LOOKUP_BUDGET = 16;
14113
13868
  async function executeClone(request, schema, db, namespace, sequenceStore, maxCloneRecords = 1e4, logger) {
14114
13869
  if (!request.clientId || typeof request.clientId !== "string") {
14115
13870
  return {
@@ -14127,6 +13882,11 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14127
13882
  const cursors = {};
14128
13883
  const next = {};
14129
13884
  let joins;
13885
+ let cappedClone = false;
13886
+ const fullyLoadedTables = /* @__PURE__ */ new Set();
13887
+ const accessDecisions = /* @__PURE__ */ new Map();
13888
+ const accessKey = (resource, id) => `${resource}\0${id}`;
13889
+ const countFailedTables = /* @__PURE__ */ new Set();
14130
13890
  const tablesToClone = request.tables || schema.resources.map((r) => r.name);
14131
13891
  const actorId = request.actorId;
14132
13892
  const filterActorVisibleRows = async (resource, rows) => {
@@ -14136,6 +13896,9 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14136
13896
  if (!actorId) {
14137
13897
  return [];
14138
13898
  }
13899
+ if (isNamespaceOwnerActor(actorId, namespace)) {
13900
+ return rows;
13901
+ }
14139
13902
  const visible = [];
14140
13903
  for (const row of rows) {
14141
13904
  const recordId = typeof row.id === "string" ? row.id : null;
@@ -14153,6 +13916,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14153
13916
  if (level) {
14154
13917
  visible.push(row);
14155
13918
  }
13919
+ accessDecisions.set(accessKey(resource, recordId), !!level);
14156
13920
  }
14157
13921
  return visible;
14158
13922
  };
@@ -14249,6 +14013,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14249
14013
  } catch (error) {
14250
14014
  logger?.warn("Clone: table count failed", { error: String(error), resource: tableName, operation: "clone-count" });
14251
14015
  tableCounts[tableName] = 0;
14016
+ countFailedTables.add(tableName);
14252
14017
  }
14253
14018
  }
14254
14019
  let paginated = false;
@@ -14259,22 +14024,24 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14259
14024
  try {
14260
14025
  if (remaining <= 0) {
14261
14026
  data[tableName] = [];
14262
- next[tableName] = tableCounts[tableName] > 0 ? "" : null;
14027
+ next[tableName] = tableCounts[tableName] > 0 || countFailedTables.has(tableName) ? "" : null;
14263
14028
  } else {
14029
+ const readLimit = remaining;
14264
14030
  const records = await db.findMany({
14265
14031
  model: tableName,
14266
14032
  where: [],
14267
14033
  orderBy: [{ field: "id", direction: "asc" }],
14268
- limit: remaining,
14034
+ limit: readLimit,
14269
14035
  namespace
14270
14036
  });
14271
14037
  data[tableName] = await filterActorVisibleRows(tableName, records);
14272
14038
  remaining -= records.length;
14273
- if (records.length < tableCounts[tableName]) {
14039
+ if (records.length < tableCounts[tableName] || countFailedTables.has(tableName) && records.length >= readLimit) {
14274
14040
  const lastRecord = records[records.length - 1];
14275
14041
  next[tableName] = lastRecord?.id ?? null;
14276
14042
  } else {
14277
14043
  next[tableName] = null;
14044
+ fullyLoadedTables.add(tableName);
14278
14045
  }
14279
14046
  }
14280
14047
  const latestSeq = await changeTracking.getLatestServerSeq({ resource: tableName });
@@ -14296,6 +14063,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14296
14063
  namespace
14297
14064
  });
14298
14065
  data[tableName] = await filterActorVisibleRows(tableName, records);
14066
+ fullyLoadedTables.add(tableName);
14299
14067
  const latestSeq = await changeTracking.getLatestServerSeq({ resource: tableName });
14300
14068
  cursors[tableName] = String(latestSeq);
14301
14069
  } catch (error) {
@@ -14305,19 +14073,63 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14305
14073
  }
14306
14074
  }
14307
14075
  }
14308
- if (paginated) {
14309
- return {
14310
- ok: true,
14311
- data,
14312
- cursors,
14313
- joins,
14314
- next: Object.keys(next).length > 0 ? next : void 0,
14315
- paginated: true
14316
- };
14317
- }
14076
+ cappedClone = paginated;
14318
14077
  }
14319
14078
  if (request.includeJoins && schema.relations) {
14320
14079
  joins = {};
14080
+ const actorIsOwner = isNamespaceOwnerActor(actorId, namespace);
14081
+ const returnedIds = /* @__PURE__ */ new Map();
14082
+ for (const [table, rows] of Object.entries(data)) {
14083
+ returnedIds.set(
14084
+ table,
14085
+ new Set(rows.map((row) => row.id).filter((id) => typeof id === "string"))
14086
+ );
14087
+ }
14088
+ const endpointAccess = /* @__PURE__ */ new Map();
14089
+ const isEndpointVisible = async (resource, id) => {
14090
+ if (actorIsOwner || !isPrivateShareableResource(schema, resource)) return true;
14091
+ if (typeof id !== "string" || !actorId) return false;
14092
+ if (returnedIds.get(resource)?.has(id)) return true;
14093
+ const decided = accessDecisions.get(accessKey(resource, id));
14094
+ if (decided !== void 0) return decided;
14095
+ if (fullyLoadedTables.has(resource)) return false;
14096
+ const key = `${resource}\0${id}`;
14097
+ let visible = endpointAccess.get(key);
14098
+ if (visible === void 0) {
14099
+ try {
14100
+ visible = !!await resolveAccessLevel(db, schema, resource, id, actorId, namespace);
14101
+ } catch (error) {
14102
+ throw new JoinVisibilityError(error);
14103
+ }
14104
+ endpointAccess.set(key, visible);
14105
+ }
14106
+ return visible;
14107
+ };
14108
+ let scopedIds;
14109
+ if (request.page || cappedClone) {
14110
+ scopedIds = /* @__PURE__ */ new Map();
14111
+ for (const [table, rows] of Object.entries(data)) {
14112
+ const ids = new Set(
14113
+ rows.map((row) => row.id).filter((id) => typeof id === "string")
14114
+ );
14115
+ if (ids.size > 0) scopedIds.set(table, ids);
14116
+ }
14117
+ }
14118
+ let useIdLookups = false;
14119
+ if (scopedIds && request.page && tablesToClone.length === 1) {
14120
+ let lookups = 0;
14121
+ for (const relation of schema.relations) {
14122
+ if (relation.type !== "many-many") continue;
14123
+ const froms = Array.isArray(relation.from) ? relation.from : [relation.from];
14124
+ const tos = Array.isArray(relation.to) ? relation.to : [relation.to];
14125
+ for (const side of [froms, tos]) {
14126
+ let ids = 0;
14127
+ for (const resource of side) ids += scopedIds.get(resource)?.size ?? 0;
14128
+ lookups += Math.ceil(ids / JOIN_LOOKUP_CHUNK);
14129
+ }
14130
+ }
14131
+ useIdLookups = lookups <= JOIN_LOOKUP_BUDGET;
14132
+ }
14321
14133
  for (const relation of schema.relations) {
14322
14134
  if (relation.type !== "many-many") continue;
14323
14135
  const froms = Array.isArray(relation.from) ? relation.from : [relation.from];
@@ -14325,28 +14137,75 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14325
14137
  const joinTableName = core.getRelationJoinTableName(relation, froms[0]);
14326
14138
  const fromCol = relation.joinColumns?.from || "from";
14327
14139
  const toCol = relation.joinColumns?.to || "to";
14140
+ const fromScopes = scopedIds ? froms.filter((resource) => scopedIds.has(resource)) : [];
14141
+ const toScopes = scopedIds ? tos.filter((resource) => scopedIds.has(resource)) : [];
14142
+ if (scopedIds && fromScopes.length === 0 && toScopes.length === 0) {
14143
+ continue;
14144
+ }
14328
14145
  try {
14329
- const joinRecords = await db.findMany({
14330
- model: joinTableName,
14331
- where: [],
14332
- orderBy: [{ field: "id", direction: "asc" }],
14333
- namespace
14334
- });
14146
+ let joinRecords;
14147
+ if (scopedIds && useIdLookups) {
14148
+ const byId = /* @__PURE__ */ new Map();
14149
+ const lookups = /* @__PURE__ */ new Map();
14150
+ const addLookup = (column, resources) => {
14151
+ const ids = lookups.get(column) ?? /* @__PURE__ */ new Set();
14152
+ for (const resource of resources) {
14153
+ for (const id of scopedIds.get(resource)) ids.add(id);
14154
+ }
14155
+ if (ids.size > 0) lookups.set(column, ids);
14156
+ };
14157
+ addLookup(fromCol, fromScopes);
14158
+ addLookup(toCol, toScopes);
14159
+ for (const [column, ids] of lookups) {
14160
+ const values = [...ids];
14161
+ for (let i = 0; i < values.length; i += JOIN_LOOKUP_CHUNK) {
14162
+ const rows = await db.findMany({
14163
+ model: joinTableName,
14164
+ where: [
14165
+ { field: column, operator: "in", value: values.slice(i, i + JOIN_LOOKUP_CHUNK) }
14166
+ ],
14167
+ namespace
14168
+ });
14169
+ for (const row of rows) byId.set(row.id, row);
14170
+ }
14171
+ }
14172
+ joinRecords = [...byId.values()].sort((a, b) => {
14173
+ const left = String(a.id ?? "");
14174
+ const right = String(b.id ?? "");
14175
+ return left < right ? -1 : left > right ? 1 : 0;
14176
+ });
14177
+ } else {
14178
+ joinRecords = await db.findMany({
14179
+ model: joinTableName,
14180
+ where: [],
14181
+ orderBy: [{ field: "id", direction: "asc" }],
14182
+ namespace
14183
+ });
14184
+ }
14335
14185
  const normalizedRows = joinRecords.map(
14336
14186
  (row) => normalizeJoinCloneRow(row, fromCol, toCol)
14337
14187
  );
14338
14188
  for (const from of froms) {
14339
14189
  for (const to of tos) {
14340
14190
  const joinStoreKey = core.getJoinStoreKey(from, relation.relation, to);
14341
- const rowsForStore = normalizedRows.filter(
14342
- (row) => shouldIncludeJoinRowForStore(row, relation, schema, from, to)
14191
+ const candidateRows = normalizedRows.filter(
14192
+ (row) => shouldIncludeJoinRowForStore(row, relation, schema, from, to) && (!scopedIds || typeof row.from === "string" && !!scopedIds.get(from)?.has(row.from) || typeof row.to === "string" && !!scopedIds.get(to)?.has(row.to))
14343
14193
  );
14194
+ const rowsForStore = [];
14195
+ for (const row of candidateRows) {
14196
+ if (await isEndpointVisible(from, row.from) && await isEndpointVisible(to, row.to)) {
14197
+ rowsForStore.push(row);
14198
+ }
14199
+ }
14344
14200
  if (rowsForStore.length > 0) {
14345
14201
  joins[joinStoreKey] = rowsForStore;
14346
14202
  }
14347
14203
  }
14348
14204
  }
14349
14205
  } catch (error) {
14206
+ if (error instanceof JoinVisibilityError) {
14207
+ throw error.reason;
14208
+ }
14350
14209
  logger?.warn("Clone: join table fetch failed", { error: String(error), operation: "clone-joins" });
14351
14210
  continue;
14352
14211
  }
@@ -14357,7 +14216,8 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
14357
14216
  data,
14358
14217
  cursors,
14359
14218
  joins,
14360
- next: Object.keys(next).length > 0 ? next : void 0
14219
+ next: Object.keys(next).length > 0 ? next : void 0,
14220
+ ...cappedClone ? { paginated: true } : {}
14361
14221
  };
14362
14222
  }
14363
14223
  function normalizeJoinCloneRow(row, fromCol, toCol) {
@@ -14821,7 +14681,7 @@ function compareCanonicalChangeEntries(a, b) {
14821
14681
  function mergeCanonicalChangeStreamsBounded(streams, limit) {
14822
14682
  const heads = streams.filter((stream) => stream.changes.length > 0).map((stream) => ({ resource: stream.resource, changes: stream.changes, index: 0 }));
14823
14683
  const merged = [];
14824
- const latestCursorPerResource = /* @__PURE__ */ Object.create(null);
14684
+ const latestCursorPerResource = {};
14825
14685
  let peakWindow = heads.length;
14826
14686
  while (heads.length > 0 && merged.length < limit) {
14827
14687
  let bestIdx = 0;
@@ -15053,11 +14913,11 @@ async function executePullCanonical(request, schema, db, namespace, sequenceStor
15053
14913
  const requestedResourceKeys = Object.keys(request.cursors).filter(
15054
14914
  (resource) => resource !== ACTOR_FEED_CURSOR_KEY
15055
14915
  );
15056
- const records = /* @__PURE__ */ Object.create(null);
15057
- const merged = /* @__PURE__ */ Object.create(null);
15058
- const deleted = /* @__PURE__ */ Object.create(null);
15059
- const joins = /* @__PURE__ */ Object.create(null);
15060
- const cursors = /* @__PURE__ */ Object.create(null);
14916
+ const records = {};
14917
+ const merged = {};
14918
+ const deleted = {};
14919
+ const joins = {};
14920
+ const cursors = {};
15061
14921
  for (const resource of requestedResourceKeys) {
15062
14922
  if (!resource.startsWith("join_") && !resource.startsWith("__datafn_")) {
15063
14923
  records[resource] = [];
@@ -15460,17 +15320,6 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15460
15320
  const batchLocalSeen = /* @__PURE__ */ new Map();
15461
15321
  async function executeMutationOp(mut, targetDb) {
15462
15322
  const resolvedCapabilities = resolveCapabilitiesForResource2(schema, mut.resource);
15463
- if ((mut.operation === "insert" || mut.operation === "merge" || mut.operation === "replace") && typeof mut.record === "object" && mut.record !== null) {
15464
- const systemField = core.findSystemFieldWrite(schema.relations, mut.resource, mut.record);
15465
- if (systemField) {
15466
- return {
15467
- ok: false,
15468
- code: "DFQL_INVALID",
15469
- message: `Field is read-only: ${systemField} on ${mut.resource}`,
15470
- path: `record.${systemField}`
15471
- };
15472
- }
15473
- }
15474
15323
  switch (mut.operation) {
15475
15324
  case "insert": {
15476
15325
  const coercedData = applyDateCoercion(schema, mut.resource, mut.record || {}, logger);
@@ -16358,6 +16207,7 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
16358
16207
  const counts = {};
16359
16208
  let joinCounts;
16360
16209
  const actorId = request.actorId;
16210
+ const checkedVisibleIds = /* @__PURE__ */ new Map();
16361
16211
  for (const resourceName of request.resources) {
16362
16212
  const resource = schema.resources.find((r) => r.name === resourceName);
16363
16213
  if (!resource) {
@@ -16381,7 +16231,7 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
16381
16231
  };
16382
16232
  }
16383
16233
  try {
16384
- if (isPrivateShareableResource(schema, resourceName)) {
16234
+ if (isPrivateShareableResource(schema, resourceName) && !isNamespaceOwnerActor(actorId, namespace)) {
16385
16235
  if (!actorId) {
16386
16236
  counts[resourceName] = 0;
16387
16237
  continue;
@@ -16392,6 +16242,7 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
16392
16242
  namespace
16393
16243
  });
16394
16244
  let visibleCount = 0;
16245
+ const visibleIds = /* @__PURE__ */ new Set();
16395
16246
  for (const row of rows) {
16396
16247
  const recordId = typeof row.id === "string" ? row.id : null;
16397
16248
  if (!recordId) {
@@ -16407,9 +16258,11 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
16407
16258
  );
16408
16259
  if (level) {
16409
16260
  visibleCount++;
16261
+ visibleIds.add(recordId);
16410
16262
  }
16411
16263
  }
16412
16264
  counts[resourceName] = visibleCount;
16265
+ checkedVisibleIds.set(resourceName, visibleIds);
16413
16266
  continue;
16414
16267
  }
16415
16268
  if (typeof db.count === "function") {
@@ -16437,6 +16290,21 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
16437
16290
  }
16438
16291
  if (request.includeJoins && schema.relations) {
16439
16292
  joinCounts = {};
16293
+ const actorIsOwner = isNamespaceOwnerActor(actorId, namespace);
16294
+ const endpointAccess = /* @__PURE__ */ new Map();
16295
+ const isJoinEndpointVisible = async (resource, id) => {
16296
+ if (!isPrivateShareableResource(schema, resource)) return true;
16297
+ if (typeof id !== "string" || !actorId) return false;
16298
+ const checked = checkedVisibleIds.get(resource);
16299
+ if (checked) return checked.has(id);
16300
+ const key = `${resource}\0${id}`;
16301
+ let visible = endpointAccess.get(key);
16302
+ if (visible === void 0) {
16303
+ visible = !!await resolveAccessLevel(db, schema, resource, id, actorId, namespace);
16304
+ endpointAccess.set(key, visible);
16305
+ }
16306
+ return visible;
16307
+ };
16440
16308
  for (const relation of schema.relations) {
16441
16309
  if (relation.type !== "many-many") continue;
16442
16310
  const fromResources = Array.isArray(relation.from) ? relation.from : [relation.from];
@@ -16494,9 +16362,29 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
16494
16362
  joinCounts[joinStoreKey] = 0;
16495
16363
  continue;
16496
16364
  }
16497
- joinCounts[joinStoreKey] = normalizedRows.filter(
16365
+ const storeRows = normalizedRows.filter(
16498
16366
  (row) => shouldIncludeJoinRowForStore2(row, relation, schema, fromResource, toResource)
16499
- ).length;
16367
+ );
16368
+ if (!relationTouchesPrivateResource || actorIsOwner) {
16369
+ joinCounts[joinStoreKey] = storeRows.length;
16370
+ continue;
16371
+ }
16372
+ let visibleRows = 0;
16373
+ try {
16374
+ for (const row of storeRows) {
16375
+ if (await isJoinEndpointVisible(fromResource, row.from) && await isJoinEndpointVisible(toResource, row.to)) {
16376
+ visibleRows += 1;
16377
+ }
16378
+ }
16379
+ } catch (error) {
16380
+ logger?.warn("Reconcile: join visibility check failed", {
16381
+ error: String(error),
16382
+ joinTable: joinTableName,
16383
+ operation: "reconcile-join-count"
16384
+ });
16385
+ visibleRows = 0;
16386
+ }
16387
+ joinCounts[joinStoreKey] = visibleRows;
16500
16388
  }
16501
16389
  }
16502
16390
  }
@@ -18001,7 +17889,6 @@ var WebSocketManager = class {
18001
17889
  * Reverse mapping: client → known principalIds for O(1) targeted index cleanup.
18002
17890
  */
18003
17891
  this.clientPrincipals = /* @__PURE__ */ new Map();
18004
- this.routeTickets = /* @__PURE__ */ new Map();
18005
17892
  this.clientPlacement = /* @__PURE__ */ new Map();
18006
17893
  /** Monotonic namespace fence generation closes the validation/registration race. */
18007
17894
  this.namespaceFenceGeneration = /* @__PURE__ */ new Map();
@@ -18153,11 +18040,6 @@ var WebSocketManager = class {
18153
18040
  */
18154
18041
  addClient(client, authContext) {
18155
18042
  const { namespace } = authContext;
18156
- if (this.clientNamespace.has(client)) return false;
18157
- if (authContext.routeTicket && authContext.routeTicket.expiresAt <= (authContext.routeTicket.now ?? Date.now)()) {
18158
- this.closeClientSafely(client, 4511, "DATAFN_ROUTE_TICKET_EXPIRED", "ws-ticket-expired");
18159
- return false;
18160
- }
18161
18043
  if (this.closed) {
18162
18044
  this.closeClientSafely(client, 1001, "Going Away", "ws-closed-admission");
18163
18045
  return false;
@@ -18191,12 +18073,6 @@ var WebSocketManager = class {
18191
18073
  ...authContext.regionId ? { regionId: authContext.regionId } : {},
18192
18074
  ...Number.isSafeInteger(authContext.routingEpoch) ? { epoch: authContext.routingEpoch } : {}
18193
18075
  });
18194
- if (authContext.routeTicket) {
18195
- const { id, expiresAt, now = Date.now } = authContext.routeTicket;
18196
- const timer = setTimeout(() => this.expireRouteClient(client), Math.max(0, expiresAt - now()));
18197
- timer.unref?.();
18198
- this.routeTickets.set(client, { id, expiresAt, now, timer });
18199
- }
18200
18076
  if (this.heartbeatTimer === null) {
18201
18077
  this.startHeartbeat();
18202
18078
  }
@@ -18205,24 +18081,7 @@ var WebSocketManager = class {
18205
18081
  /**
18206
18082
  * Handle disconnection.
18207
18083
  */
18208
- expireRouteClient(client) {
18209
- this.removeClient(client);
18210
- this.closeClientSafely(client, 4511, "DATAFN_ROUTE_TICKET_EXPIRED", "ws-ticket-expired");
18211
- }
18212
- revokeRouteTicket(ticketId) {
18213
- let count = 0;
18214
- for (const [client, ticket] of this.routeTickets) {
18215
- if (ticket.id !== ticketId) continue;
18216
- this.removeClient(client);
18217
- this.closeClientSafely(client, 4403, "DATAFN_ROUTE_TICKET_REVOKED", "ws-ticket-revoked");
18218
- count++;
18219
- }
18220
- return count;
18221
- }
18222
18084
  removeClient(client) {
18223
- const ticket = this.routeTickets.get(client);
18224
- if (ticket) clearTimeout(ticket.timer);
18225
- this.routeTickets.delete(client);
18226
18085
  const namespace = this.clientNamespace.get(client);
18227
18086
  if (namespace !== void 0) {
18228
18087
  this.removeTargetingIndexes(client, namespace);
@@ -18339,16 +18198,9 @@ var WebSocketManager = class {
18339
18198
  principals: mode === "targeted" ? Array.from(requestedPrincipals).sort() : void 0
18340
18199
  }
18341
18200
  });
18342
- let sent = 0;
18343
18201
  for (const client of recipients) {
18344
- const ticket = this.routeTickets.get(client);
18345
- if (ticket && ticket.expiresAt <= ticket.now()) {
18346
- this.expireRouteClient(client);
18347
- continue;
18348
- }
18349
18202
  try {
18350
18203
  client.send(msg);
18351
- sent++;
18352
18204
  } catch (e) {
18353
18205
  this.logger?.error("Error sending to websocket client", { error: String(e), operation: "ws-broadcast" });
18354
18206
  this.removeClient(client);
@@ -18358,7 +18210,7 @@ var WebSocketManager = class {
18358
18210
  return {
18359
18211
  mode,
18360
18212
  degraded,
18361
- wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : sent
18213
+ wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : recipients.size
18362
18214
  };
18363
18215
  }
18364
18216
  /**
@@ -18377,8 +18229,6 @@ var WebSocketManager = class {
18377
18229
  this.clientNamespace.clear();
18378
18230
  this.clientPrincipals.clear();
18379
18231
  this.clientPlacement.clear();
18380
- for (const ticket of this.routeTickets.values()) clearTimeout(ticket.timer);
18381
- this.routeTickets.clear();
18382
18232
  this.pendingPong.clear();
18383
18233
  }
18384
18234
  /**
@@ -18513,7 +18363,9 @@ function createRateLimitMiddleware(config) {
18513
18363
  error: {
18514
18364
  code: "RATE_LIMITED",
18515
18365
  message: "Too many requests",
18516
- details: { path: "$" }
18366
+ // Also in the body: browsers hide Retry-After from cross-origin
18367
+ // callers unless the server exposes it.
18368
+ details: { path: "$", retryAfterMs: windowSec * 1e3 }
18517
18369
  }
18518
18370
  }),
18519
18371
  {
@@ -18585,6 +18437,35 @@ function relationReferencesInternalResource(relation, internalResourceNames) {
18585
18437
  function normalizeResourceEndpoint(endpoint) {
18586
18438
  return typeof endpoint === "string" ? [endpoint] : [...endpoint];
18587
18439
  }
18440
+ function payloadReferencesInternalResource(payload, internalResourceNames) {
18441
+ if (internalResourceNames.size === 0) {
18442
+ return false;
18443
+ }
18444
+ if (Array.isArray(payload)) {
18445
+ return payload.some((entry) => payloadReferencesInternalResource(entry, internalResourceNames));
18446
+ }
18447
+ if (!payload || typeof payload !== "object") {
18448
+ return false;
18449
+ }
18450
+ const record = payload;
18451
+ if (typeof record.resource === "string" && internalResourceNames.has(record.resource)) {
18452
+ return true;
18453
+ }
18454
+ if (Array.isArray(record.resources) && record.resources.some((resource) => typeof resource === "string" && internalResourceNames.has(resource))) {
18455
+ return true;
18456
+ }
18457
+ for (const key of ["mutations", "queries", "steps", "operations"]) {
18458
+ if (Array.isArray(record[key]) && payloadReferencesInternalResource(record[key], internalResourceNames)) {
18459
+ return true;
18460
+ }
18461
+ }
18462
+ for (const key of ["query", "mutation", "payload"]) {
18463
+ if (record[key] && payloadReferencesInternalResource(record[key], internalResourceNames)) {
18464
+ return true;
18465
+ }
18466
+ }
18467
+ return false;
18468
+ }
18588
18469
  function normalizePluginAuthorizationError(error, pluginName) {
18589
18470
  if (error && typeof error === "object") {
18590
18471
  const candidate = error;
@@ -19183,10 +19064,10 @@ async function createDatafnServer(config) {
19183
19064
  }
19184
19065
  return { ok: true };
19185
19066
  };
19186
- const withAuth = (action, handler, origin = "http", rest = false) => {
19067
+ const withAuth = (action, handler) => {
19187
19068
  return async (req, ctx) => {
19188
19069
  const enrichedCtx = createEnrichedContext(ctx);
19189
- const placementRequest = multiRegionRuntime?.placement && origin === "http" ? req.clone() : void 0;
19070
+ const placementRequest = multiRegionRuntime?.placement ? req.clone() : void 0;
19190
19071
  let payload = null;
19191
19072
  if (shuttingDown) {
19192
19073
  return completeDatafnResponse({
@@ -19315,36 +19196,7 @@ async function createDatafnServer(config) {
19315
19196
  }
19316
19197
  enrichedCtx.parsedBody = payload;
19317
19198
  }
19318
- let structuralPayload = payload;
19319
- if (rest) {
19320
- let resource;
19321
- try {
19322
- const segment = sanitizePathSegment(new URL(req.url).pathname.split("/")[3] ?? "");
19323
- if (!segment.ok) throw new Error("Invalid path segment");
19324
- resource = segment.value;
19325
- } catch {
19326
- return completeDatafnResponse({
19327
- action,
19328
- request: req,
19329
- context: enrichedCtx,
19330
- payload,
19331
- response: errorResponse({ code: "DFQL_INVALID", message: "Invalid path segment", details: { path: "resource" } }, 400)
19332
- });
19333
- }
19334
- structuralPayload = { resource };
19335
- }
19336
- const parsedProtocol = core.parseDatafnRequest(action, structuralPayload, { schema: validatedSchema });
19337
- if (!parsedProtocol.ok) {
19338
- return completeDatafnResponse({
19339
- action,
19340
- request: req,
19341
- context: enrichedCtx,
19342
- payload,
19343
- response: errorResponse(parsedProtocol.error, 400)
19344
- });
19345
- }
19346
- const selection = core.collectStructuralResourceSelectors(parsedProtocol.result);
19347
- if (selection.selectors.some((resource) => internalResourceNames.has(resource))) {
19199
+ if (payloadReferencesInternalResource(payload, internalResourceNames)) {
19348
19200
  await emitDataFnEvent({
19349
19201
  domain: "datafn",
19350
19202
  type: "datafn.authorization.denied",
@@ -19370,9 +19222,7 @@ async function createDatafnServer(config) {
19370
19222
  namespace: await extractNamespace(enrichedCtx),
19371
19223
  regionId: multiRegionRuntime.regionId,
19372
19224
  runtime: multiRegionRuntime.placement,
19373
- request: placementRequest,
19374
- scope: action,
19375
- trustedInternal: origin === "executor"
19225
+ request: placementRequest
19376
19226
  });
19377
19227
  } catch (error) {
19378
19228
  if (error instanceof DatafnRoutingError) {
@@ -19391,7 +19241,7 @@ async function createDatafnServer(config) {
19391
19241
  action,
19392
19242
  request: req,
19393
19243
  context: enrichedCtx,
19394
- payload: structuralPayload
19244
+ payload
19395
19245
  });
19396
19246
  if (!pluginAuthorization.ok) {
19397
19247
  await emitDataFnEvent({
@@ -19411,7 +19261,7 @@ async function createDatafnServer(config) {
19411
19261
  });
19412
19262
  }
19413
19263
  if (config.authorize) {
19414
- const authorized = await config.authorize(enrichedCtx, action, structuralPayload);
19264
+ const authorized = await config.authorize(enrichedCtx, action, payload);
19415
19265
  if (!authorized) {
19416
19266
  await emitDataFnEvent({
19417
19267
  domain: "datafn",
@@ -19486,7 +19336,7 @@ async function createDatafnServer(config) {
19486
19336
  try {
19487
19337
  const configuredContext = config.context;
19488
19338
  const executorContext = context ?? (typeof configuredContext === "function" ? await configuredContext(request) : configuredContext ?? {});
19489
- response = await withAuth(action, handler, "executor")(request, executorContext);
19339
+ response = await withAuth(action, handler)(request, executorContext);
19490
19340
  } catch {
19491
19341
  throw new DatafnExecutorError(
19492
19342
  { code: "INTERNAL", message: "Internal Server Error" },
@@ -19676,9 +19526,7 @@ async function createDatafnServer(config) {
19676
19526
  method: route.method,
19677
19527
  path: route.path,
19678
19528
  meta: route.meta,
19679
- // withAuth and the REST handler validate URL segments and complete DataFn response hooks.
19680
- decodeParams: false,
19681
- handler: withAuth(action, route.handler, "http", true)
19529
+ handler: withAuth(action, route.handler)
19682
19530
  });
19683
19531
  }
19684
19532
  }
@@ -19850,18 +19698,12 @@ async function createDatafnServer(config) {
19850
19698
  regionId: multiRegionRuntime.regionId,
19851
19699
  runtime: multiRegionRuntime.placement,
19852
19700
  request: handshakeRequest,
19853
- scope: "websocket",
19854
- trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion && !multiRegionRuntime.placement.routeTickets
19701
+ trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion
19855
19702
  });
19856
19703
  added = wsManager.addClient(client, {
19857
19704
  ...authContext,
19858
19705
  regionId: validated.placement.regionId,
19859
- routingEpoch: validated.placement.epoch,
19860
- routeTicket: validated.ticket ? {
19861
- id: validated.ticket.ticketId,
19862
- expiresAt: validated.ticket.expiresAt,
19863
- now: multiRegionRuntime.placement.routeTickets?.now
19864
- } : void 0
19706
+ routingEpoch: validated.placement.epoch
19865
19707
  });
19866
19708
  if (!added) return false;
19867
19709
  if (wsManager.getNamespaceFenceGeneration(authContext.namespace) !== fenceGeneration) {
@@ -19880,7 +19722,7 @@ async function createDatafnServer(config) {
19880
19722
  if (added) wsManager.removeClient(client);
19881
19723
  try {
19882
19724
  client.close(
19883
- error instanceof DatafnRoutingError ? error.code === "DATAFN_ROUTE_RATE_LIMITED" ? 4503 : error.code === "DATAFN_ROUTE_TICKET_EXPIRED" ? 4511 : error.code.startsWith("DATAFN_ROUTE_") ? 4403 : 4510 : 1011,
19725
+ error instanceof DatafnRoutingError ? 4510 : 1011,
19884
19726
  error instanceof Error ? error.message : "Placement validation failed"
19885
19727
  );
19886
19728
  } catch {
@@ -19888,7 +19730,6 @@ async function createDatafnServer(config) {
19888
19730
  return false;
19889
19731
  }
19890
19732
  },
19891
- revokeRouteTicket: (ticketId) => wsManager.revokeRouteTicket(ticketId),
19892
19733
  fenceNamespace: (namespace, minimumEpoch) => wsManager.fenceNamespace(namespace, minimumEpoch),
19893
19734
  removeClient: (client) => wsManager.removeClient(client),
19894
19735
  handleMessage: (client, data) => wsManager.handleMessage(client, data),
@@ -20826,717 +20667,6 @@ function bytesToBase64Url(bytes) {
20826
20667
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20827
20668
  }
20828
20669
 
20829
- // src/placement-policy.ts
20830
- var CONTINENT_CENTERS = {
20831
- AF: [1.65, 17.68],
20832
- AN: [-82.86, 135],
20833
- AS: [34.05, 100.62],
20834
- EU: [54.53, 15.26],
20835
- NA: [54.53, -105.26],
20836
- OC: [-22.74, 140.02],
20837
- SA: [-14.24, -51.93]
20838
- };
20839
- function finiteCoordinate(value, minimum, maximum) {
20840
- return value !== void 0 && Number.isFinite(value) && value >= minimum && value <= maximum;
20841
- }
20842
- function normalizedCandidates(input) {
20843
- const context = {
20844
- location: input.location ?? null,
20845
- preferredRegionId: normalizedPreferredRegionId(input.preferredRegionId)
20846
- };
20847
- const seen = /* @__PURE__ */ new Set();
20848
- const candidates = input.candidates.map((candidate) => {
20849
- const regionId = candidate.regionId.trim();
20850
- if (!regionId) throw new Error("DATAFN_PLACEMENT_REGION_ID_REQUIRED");
20851
- if (seen.has(regionId)) {
20852
- throw new Error(`DATAFN_PLACEMENT_REGION_DUPLICATE: ${regionId}`);
20853
- }
20854
- seen.add(regionId);
20855
- return regionId === candidate.regionId ? candidate : { ...candidate, regionId };
20856
- });
20857
- return candidates.filter(
20858
- (candidate) => (input.constraints ?? []).every(
20859
- (constraint) => constraint(candidate, context)
20860
- )
20861
- );
20862
- }
20863
- function normalizedPreferredRegionId(preferredRegionId) {
20864
- return preferredRegionId?.trim() || null;
20865
- }
20866
- function compareRegionIds(left, right) {
20867
- return left < right ? -1 : left > right ? 1 : 0;
20868
- }
20869
- function sourceCoordinates(location) {
20870
- if (!location) return null;
20871
- if (finiteCoordinate(location.latitude, -90, 90) && finiteCoordinate(location.longitude, -180, 180)) {
20872
- return {
20873
- coordinates: [location.latitude, location.longitude],
20874
- source: "coordinates"
20875
- };
20876
- }
20877
- const continent = location.continent?.toUpperCase();
20878
- const coordinates = continent ? CONTINENT_CENTERS[continent] : void 0;
20879
- return coordinates ? { coordinates, source: "continent" } : null;
20880
- }
20881
- function radians(degrees) {
20882
- return degrees * Math.PI / 180;
20883
- }
20884
- function distanceKilometers(source, target) {
20885
- const sourceLatitude = radians(source[0]);
20886
- const targetLatitude = radians(target[0]);
20887
- const latitudeDelta = radians(target[0] - source[0]);
20888
- const longitudeDelta = radians(target[1] - source[1]);
20889
- const haversine = Math.sin(latitudeDelta / 2) ** 2 + Math.cos(sourceLatitude) * Math.cos(targetLatitude) * Math.sin(longitudeDelta / 2) ** 2;
20890
- const clampedHaversine = Math.min(1, Math.max(0, haversine));
20891
- return 6371 * 2 * Math.atan2(Math.sqrt(clampedHaversine), Math.sqrt(1 - clampedHaversine));
20892
- }
20893
- function rankDatafnPlacementRegions(input) {
20894
- const candidates = normalizedCandidates(input);
20895
- const source = sourceCoordinates(input.location ?? null);
20896
- if (!source) return [];
20897
- return candidates.flatMap((candidate) => {
20898
- const { latitude, longitude } = candidate;
20899
- return finiteCoordinate(latitude, -90, 90) && finiteCoordinate(longitude, -180, 180) ? [
20900
- {
20901
- regionId: candidate.regionId,
20902
- source: source.source,
20903
- distanceKilometers: distanceKilometers(source.coordinates, [
20904
- latitude,
20905
- longitude
20906
- ])
20907
- }
20908
- ] : [];
20909
- }).sort(
20910
- (left, right) => (left.distanceKilometers ?? 0) - (right.distanceKilometers ?? 0) || compareRegionIds(left.regionId, right.regionId)
20911
- );
20912
- }
20913
- function stableIndex(key, length) {
20914
- let hash = 2166136261;
20915
- for (const byte of new TextEncoder().encode(key)) {
20916
- hash ^= byte;
20917
- hash = Math.imul(hash, 16777619) >>> 0;
20918
- }
20919
- return hash % length;
20920
- }
20921
- function selectDatafnPlacementRegion(input) {
20922
- const candidates = normalizedCandidates(input);
20923
- const preferredRegionId = normalizedPreferredRegionId(
20924
- input.preferredRegionId
20925
- );
20926
- if (preferredRegionId && candidates.some((candidate) => candidate.regionId === preferredRegionId)) {
20927
- return { regionId: preferredRegionId, source: "preferred" };
20928
- }
20929
- const ranked = rankDatafnPlacementRegions({
20930
- candidates,
20931
- location: input.location ?? null
20932
- });
20933
- const nearest = ranked[0];
20934
- if (nearest) return nearest;
20935
- if (input.stableKey !== void 0 && candidates.length > 0) {
20936
- const stableCandidates = [...candidates].sort(
20937
- (left, right) => compareRegionIds(left.regionId, right.regionId)
20938
- );
20939
- const selected = stableCandidates[stableIndex(input.stableKey, stableCandidates.length)];
20940
- if (selected) {
20941
- return { regionId: selected.regionId, source: "stable-fallback" };
20942
- }
20943
- }
20944
- return null;
20945
- }
20946
- function coordinate(value, minimum, maximum) {
20947
- const parsed = typeof value === "number" ? value : Number(value);
20948
- return Number.isFinite(parsed) && parsed >= minimum && parsed <= maximum ? parsed : void 0;
20949
- }
20950
- function readDatafnCloudflarePlacementLocation(request) {
20951
- const cf = request.cf;
20952
- if (!cf) return null;
20953
- const latitude = coordinate(cf.latitude, -90, 90);
20954
- const longitude = coordinate(cf.longitude, -180, 180);
20955
- const continent = typeof cf.continent === "string" && /^[A-Za-z]{2}$/u.test(cf.continent) ? cf.continent.toUpperCase() : void 0;
20956
- if (latitude === void 0 && longitude === void 0 && !continent)
20957
- return null;
20958
- return {
20959
- ...latitude === void 0 ? {} : { latitude },
20960
- ...longitude === void 0 ? {} : { longitude },
20961
- ...continent ? { continent } : {}
20962
- };
20963
- }
20964
- var POSTGRES_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
20965
- var DATAFN_INTERNAL_TABLE_RE = /^__datafn_[a-z0-9_]+$/;
20966
- var LEGACY_PERMISSIONS_TABLE_RE = /^__datafn_permissions_(?!global$)[A-Za-z0-9_]+$/;
20967
- var POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL = `
20968
- SELECT c.table_name, c.column_name
20969
- FROM information_schema.columns AS c
20970
- JOIN information_schema.tables AS t
20971
- ON t.table_schema = c.table_schema
20972
- AND t.table_name = c.table_name
20973
- WHERE c.table_schema = current_schema()
20974
- AND t.table_type = 'BASE TABLE'
20975
- ORDER BY c.table_name, c.ordinal_position
20976
- `.trim();
20977
- var INTERNAL_ROLE_BY_TABLE = {
20978
- __datafn_meta: "sync_meta",
20979
- __datafn_changes: "sync_changes",
20980
- __datafn_idempotency: "idempotency",
20981
- __datafn_seed: "seed",
20982
- __datafn_permission_directory_outbox: "permission_directory_outbox"
20983
- };
20984
- var SHARING_RESOURCE_TABLES = [
20985
- {
20986
- logicalRole: "permissions_global",
20987
- relation: "__datafn_permissions_global"
20988
- },
20989
- {
20990
- logicalRole: "principal_memberships",
20991
- relation: "__datafn_principal_memberships"
20992
- },
20993
- {
20994
- logicalRole: "principal_hierarchy",
20995
- relation: "__datafn_principal_hierarchy"
20996
- }
20997
- ];
20998
- var SELECTOR_COLUMN = {
20999
- resource_ns: "__ns",
21000
- internal_namespace: "namespace"
21001
- };
21002
- var DatafnNamespaceStorageError = class extends Error {
21003
- constructor(input) {
21004
- super(input.message);
21005
- this.name = "DatafnNamespaceStorageError";
21006
- this.code = input.code;
21007
- this.details = input.details;
21008
- }
21009
- };
21010
- function fail(code, message, details) {
21011
- throw new DatafnNamespaceStorageError({ code, message, details });
21012
- }
21013
- function quotePostgresIdentifier(identifier) {
21014
- if (!POSTGRES_IDENTIFIER_RE.test(identifier)) {
21015
- fail(
21016
- "DATAFN_NAMESPACE_STORAGE_INVALID",
21017
- `Invalid PostgreSQL identifier "${identifier}"`,
21018
- { identifier }
21019
- );
21020
- }
21021
- return `"${identifier}"`;
21022
- }
21023
- function namespacedInternalTableRoles() {
21024
- return INTERNAL_ROLE_BY_TABLE;
21025
- }
21026
- function catalogByName(catalog) {
21027
- const map = /* @__PURE__ */ new Map();
21028
- for (const relation of catalog.relations) {
21029
- if (map.has(relation.name)) fail("DATAFN_NAMESPACE_STORAGE_INVALID", "Duplicate catalog relation.");
21030
- map.set(relation.name, relation);
21031
- }
21032
- return map;
21033
- }
21034
- function hasColumn(relation, column) {
21035
- return Boolean(relation?.columns.includes(column));
21036
- }
21037
- function isShareableResource(schema, resourceName) {
21038
- const resource = schema.resources.find((entry) => entry.name === resourceName);
21039
- if (!resource) return false;
21040
- const resolved = core.resolveCapabilities(schema.capabilities, resource.capabilities);
21041
- return resolved.some(
21042
- (entry) => typeof entry === "object" && entry !== null && "shareable" in entry
21043
- );
21044
- }
21045
- function schemaDerivedRelations(schema) {
21046
- const planned = [];
21047
- const resourceRole = core.namespaceStorageManifestEntry("resource");
21048
- schema.resources.forEach((resource, index) => {
21049
- planned.push({
21050
- logicalRole: "resource",
21051
- relation: resource.name,
21052
- requiredColumns: [
21053
- "id",
21054
- ...resource.fields.map((field) => field.name),
21055
- ...core.getCapabilityFields(core.resolveCapabilities(schema.capabilities, resource.capabilities)).map((field) => field.name)
21056
- ].map(physicalColumn),
21057
- copyOrder: resourceRole.copyOrder + index
21058
- });
21059
- });
21060
- const joinRole = core.namespaceStorageManifestEntry("join");
21061
- const joinTables = /* @__PURE__ */ new Set();
21062
- for (const relation of schema.relations ?? []) {
21063
- if (relation.type !== "many-many") continue;
21064
- const table = core.getRelationJoinTableName(relation);
21065
- if (joinTables.has(table)) continue;
21066
- joinTables.add(table);
21067
- planned.push({
21068
- logicalRole: "join",
21069
- relation: table,
21070
- requiredColumns: [
21071
- "id",
21072
- relation.joinColumns?.from ?? "from",
21073
- relation.joinColumns?.to ?? "to",
21074
- ...(relation.metadata ?? []).map((field) => field.name)
21075
- ].map(physicalColumn),
21076
- copyOrder: joinRole.copyOrder + joinTables.size
21077
- });
21078
- }
21079
- const legacyRole = core.namespaceStorageManifestEntry("permissions_legacy");
21080
- schema.resources.forEach((resource, index) => {
21081
- if (!isShareableResource(schema, resource.name)) return;
21082
- planned.push({
21083
- logicalRole: "permissions_legacy",
21084
- relation: getLegacyPermissionsTable(resource.name),
21085
- copyOrder: legacyRole.copyOrder + index
21086
- });
21087
- });
21088
- return planned;
21089
- }
21090
- function internalPlannedRelations() {
21091
- return Object.entries(INTERNAL_ROLE_BY_TABLE).map(([relation, logicalRole]) => ({
21092
- logicalRole,
21093
- relation,
21094
- copyOrder: core.namespaceStorageManifestEntry(logicalRole).copyOrder
21095
- }));
21096
- }
21097
- function sharingPlannedRelations() {
21098
- return SHARING_RESOURCE_TABLES.map((entry) => ({
21099
- logicalRole: entry.logicalRole,
21100
- relation: entry.relation,
21101
- copyOrder: core.namespaceStorageManifestEntry(entry.logicalRole).copyOrder
21102
- }));
21103
- }
21104
- function physicalColumn(name) {
21105
- return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
21106
- }
21107
- var SHARING_REQUIRED_COLUMNS = {
21108
- permissions_global: ["id", "resource_type", "resource_ns", "resource_id", "principal_id", "level", "grant_kind", "source_ref", "granted_by", "granted_at", "revoked_at"],
21109
- permissions_legacy: ["id", "resource_id", "user_id", "level", "granted_by", "granted_at", "revoked_at"],
21110
- principal_memberships: ["id", "namespace", "actor_id", "principal_id", "granted_at", "revoked_at"],
21111
- principal_hierarchy: ["id", "namespace", "principal_id", "parent_principal_id", "created_at", "revoked_at"]
21112
- };
21113
- function toEntry(planned, catalog) {
21114
- const manifest = core.namespaceStorageManifestEntry(planned.logicalRole);
21115
- const namespaceColumn = SELECTOR_COLUMN[manifest.selectorKind];
21116
- const relation = catalog.get(planned.relation);
21117
- if (!relation) {
21118
- if (manifest.presence === "schema-derived") {
21119
- fail(
21120
- "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21121
- `Required namespace storage relation "${planned.relation}" is missing from the installed schema.`,
21122
- { logicalRole: planned.logicalRole, relation: planned.relation }
21123
- );
21124
- }
21125
- return null;
21126
- }
21127
- if (!hasColumn(relation, namespaceColumn)) {
21128
- fail(
21129
- "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21130
- `Namespace storage relation "${planned.relation}" is missing selector column "${namespaceColumn}".`,
21131
- {
21132
- logicalRole: planned.logicalRole,
21133
- relation: planned.relation,
21134
- expectedColumn: namespaceColumn,
21135
- columns: relation.columns
21136
- }
21137
- );
21138
- }
21139
- const required = planned.requiredColumns ?? INTERNAL_TABLE_SCHEMAS[planned.relation]?.map((column) => column.name) ?? SHARING_REQUIRED_COLUMNS[planned.logicalRole] ?? ["id"];
21140
- const missing = required.filter((column) => !hasColumn(relation, column));
21141
- if (missing.length > 0) {
21142
- fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", `Relation "${planned.relation}" is missing required columns: ${missing.join(", ")}.`);
21143
- }
21144
- const hasIdentity = relation.indexes?.some((index) => index.unique && index.primary === true && index.columns.includes("id") && index.columns.every((column) => column === "id" || column === namespaceColumn));
21145
- if (!hasIdentity) {
21146
- fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", `Relation "${planned.relation}" is missing a validated unique identity index.`);
21147
- }
21148
- return {
21149
- logicalRole: planned.logicalRole,
21150
- ownership: "datafn",
21151
- relation: planned.relation,
21152
- quotedRelation: quotePostgresIdentifier(planned.relation),
21153
- namespaceColumn,
21154
- quotedNamespaceColumn: quotePostgresIdentifier(namespaceColumn),
21155
- operations: manifest.operations,
21156
- copyOrder: planned.copyOrder,
21157
- present: true
21158
- };
21159
- }
21160
- function isDatafnOwnedCatalogRelation(name, columns) {
21161
- if (columns.includes("__ns")) return true;
21162
- return DATAFN_INTERNAL_TABLE_RE.test(name) && columns.includes("namespace");
21163
- }
21164
- function unexpectedCatalogRelations(catalog, plannedNames) {
21165
- const unexpected = [];
21166
- for (const relation of catalog.relations) {
21167
- if (plannedNames.has(relation.name)) continue;
21168
- if (!isDatafnOwnedCatalogRelation(relation.name, relation.columns)) continue;
21169
- unexpected.push(relation.name);
21170
- }
21171
- return unexpected.sort();
21172
- }
21173
- function resolveNamespaceStoragePlan(input) {
21174
- try {
21175
- core.assertSupportedNamespaceStorageVersions({
21176
- manifestVersion: input.manifestVersion,
21177
- schemaVersion: input.schemaVersion
21178
- });
21179
- } catch (error) {
21180
- const code = error && typeof error === "object" && "code" in error ? String(error.code) : "DATAFN_NAMESPACE_STORAGE_VERSION_MISMATCH";
21181
- fail(
21182
- code,
21183
- error instanceof Error ? error.message : String(error)
21184
- );
21185
- }
21186
- if (input.catalog.dialect !== "postgres") {
21187
- fail(
21188
- "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21189
- `Namespace storage plans are supported for PostgreSQL only. Received dialect "${String(input.catalog.dialect)}".`
21190
- );
21191
- }
21192
- if (!core.isNamespaced(input.schema)) {
21193
- fail(
21194
- "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21195
- "Namespace storage plans require a namespaced DataFn schema."
21196
- );
21197
- }
21198
- const catalog = catalogByName(input.catalog);
21199
- const planned = [
21200
- ...schemaDerivedRelations(input.schema),
21201
- ...sharingPlannedRelations(),
21202
- ...internalPlannedRelations()
21203
- ];
21204
- for (const relation of input.catalog.relations) {
21205
- if (LEGACY_PERMISSIONS_TABLE_RE.test(relation.name) && !planned.some((entry) => entry.relation === relation.name)) {
21206
- planned.push({
21207
- logicalRole: "permissions_legacy",
21208
- relation: relation.name,
21209
- copyOrder: core.namespaceStorageManifestEntry("permissions_legacy").copyOrder + 50
21210
- });
21211
- }
21212
- }
21213
- const plannedNames = new Set(planned.map((entry) => entry.relation));
21214
- const unexpected = unexpectedCatalogRelations(input.catalog, plannedNames);
21215
- if (unexpected.length > 0) {
21216
- fail(
21217
- "DATAFN_NAMESPACE_STORAGE_UNKNOWN",
21218
- `Installed schema contains DataFn namespace storage that is not in the supported contract: ${unexpected.join(", ")}.`,
21219
- { relations: unexpected }
21220
- );
21221
- }
21222
- const entries = planned.map((entry) => toEntry(entry, catalog)).filter((entry) => entry !== null).sort((left, right) => {
21223
- if (left.copyOrder !== right.copyOrder) return left.copyOrder - right.copyOrder;
21224
- return left.relation.localeCompare(right.relation);
21225
- });
21226
- return {
21227
- manifestVersion: core.DATAFN_NAMESPACE_STORAGE_MANIFEST_VERSION,
21228
- schemaVersion: core.DATAFN_NAMESPACE_STORAGE_SCHEMA_VERSION,
21229
- dialect: "postgres",
21230
- entries
21231
- };
21232
- }
21233
- function selectNamespaceStorageEntries(plan, operation) {
21234
- const selected = plan.entries.filter((entry) => entry.operations.includes(operation));
21235
- if (operation === "cleanup") {
21236
- return [...selected].sort((left, right) => {
21237
- if (left.copyOrder !== right.copyOrder) return right.copyOrder - left.copyOrder;
21238
- return right.relation.localeCompare(left.relation);
21239
- });
21240
- }
21241
- return selected;
21242
- }
21243
- function composeNamespaceStoragePlan(plan, applicationEntries) {
21244
- const existing = new Set(plan.entries.map((entry) => entry.relation));
21245
- const composed = [...plan.entries];
21246
- for (const entry of applicationEntries) {
21247
- if (existing.has(entry.relation)) {
21248
- fail(
21249
- "DATAFN_NAMESPACE_STORAGE_INVALID",
21250
- `Application storage relation "${entry.relation}" collides with DataFn-owned storage.`,
21251
- { relation: entry.relation }
21252
- );
21253
- }
21254
- existing.add(entry.relation);
21255
- composed.push({
21256
- logicalRole: "application",
21257
- ownership: "application",
21258
- relation: entry.relation,
21259
- quotedRelation: quotePostgresIdentifier(entry.relation),
21260
- namespaceColumn: entry.namespaceColumn,
21261
- quotedNamespaceColumn: quotePostgresIdentifier(entry.namespaceColumn),
21262
- operations: entry.operations ?? ["copy", "verify", "cleanup", "fence", "backup"],
21263
- copyOrder: entry.copyOrder ?? 10,
21264
- present: true
21265
- });
21266
- }
21267
- composed.sort((left, right) => {
21268
- if (left.copyOrder !== right.copyOrder) return left.copyOrder - right.copyOrder;
21269
- return left.relation.localeCompare(right.relation);
21270
- });
21271
- return { ...plan, entries: composed };
21272
- }
21273
- var POSTGRES_NAMESPACE_STORAGE_INDEX_SQL = `
21274
- SELECT t.relname AS table_name,
21275
- array_agg(a.attname ORDER BY k.ordinality) AS index_columns,
21276
- i.indisunique AS index_unique, i.indisprimary AS index_primary
21277
- FROM pg_index i
21278
- JOIN pg_class t ON t.oid = i.indrelid
21279
- JOIN pg_namespace n ON n.oid = t.relnamespace
21280
- CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ordinality)
21281
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
21282
- WHERE n.nspname = current_schema() AND i.indisvalid AND i.indisready
21283
- AND i.indpred IS NULL AND i.indexprs IS NULL
21284
- AND k.ordinality <= i.indnkeyatts
21285
- GROUP BY t.relname, i.indexrelid, i.indisunique, i.indisprimary
21286
- ORDER BY t.relname, i.indexrelid
21287
- `.trim();
21288
- async function inspectPostgresNamespaceStorage(query) {
21289
- const rows = await query(POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL);
21290
- const indexRows = await query(POSTGRES_NAMESPACE_STORAGE_INDEX_SQL);
21291
- const relations = /* @__PURE__ */ new Map();
21292
- for (const row of rows) {
21293
- if (typeof row.column_name !== "string") fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", "Catalog column metadata is missing.");
21294
- const columns = relations.get(row.table_name) ?? [];
21295
- columns.push(row.column_name);
21296
- relations.set(row.table_name, columns);
21297
- }
21298
- return {
21299
- dialect: "postgres",
21300
- relations: [...relations.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([name, columns]) => ({ name, columns, indexes: indexRows.filter((row) => row.table_name === name && Array.isArray(row.index_columns) && typeof row.index_unique === "boolean").map((row) => ({ columns: row.index_columns, unique: row.index_unique, primary: row.index_primary === true })) }))
21301
- };
21302
- }
21303
- function assertInternalNamespaceStorageMetadataComplete() {
21304
- const namespaced = listNamespacedInternalTables();
21305
- const mapped = Object.keys(INTERNAL_ROLE_BY_TABLE).sort();
21306
- if (namespaced.join("\0") !== mapped.join("\0")) {
21307
- fail(
21308
- "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21309
- "Internal namespace tables are missing from the storage contract.",
21310
- {
21311
- namespacedInternalTables: namespaced,
21312
- mappedInternalTables: mapped,
21313
- schemas: Object.keys(INTERNAL_TABLE_SCHEMAS).sort()
21314
- }
21315
- );
21316
- }
21317
- }
21318
- async function drainNamespaceStorage(input) {
21319
- const drainEntries = selectNamespaceStorageEntries(input.plan, "drain");
21320
- if (drainEntries.length === 0) {
21321
- return { processed: 0, pending: 0 };
21322
- }
21323
- const unsupported = drainEntries.filter(
21324
- (entry) => entry.logicalRole !== "permission_directory_outbox"
21325
- );
21326
- if (unsupported.length > 0) {
21327
- fail(
21328
- "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21329
- `No drain implementation for logical roles: ${unsupported.map((entry) => entry.logicalRole).join(", ")}.`,
21330
- { roles: unsupported.map((entry) => entry.logicalRole) }
21331
- );
21332
- }
21333
- return drainNamespacePermissionDirectoryOutbox(
21334
- input.adapter,
21335
- input.namespace,
21336
- input.runtime,
21337
- input.logger
21338
- );
21339
- }
21340
- async function resolveAuthoritativeAncestorInactive(adapter, schema, resource, record, namespace, maxGraphNodes) {
21341
- const active = /* @__PURE__ */ new Set();
21342
- const resolved = /* @__PURE__ */ new Map();
21343
- let visited = 0;
21344
- async function visit(model, row, root = false) {
21345
- if (typeof row.id !== "string" || row.id.length === 0) {
21346
- throw new Error("Ancestor repair: malformed record identifier");
21347
- }
21348
- const key = JSON.stringify([model, row.id]);
21349
- if (active.has(key)) throw new Error("Ancestor repair: cycle detected");
21350
- if (resolved.has(key)) return resolved.get(key);
21351
- if (++visited > maxGraphNodes) throw new Error("Ancestor repair: maxGraphNodes exceeded");
21352
- active.add(key);
21353
- let inherited = false;
21354
- for (const relation of schema.relations ?? []) {
21355
- if (relation.inheritsInactive !== true || relation.type === "many-many") continue;
21356
- const dependent = relation.type === "many-one" ? relation.from : relation.to;
21357
- if (!core.endpointIncludes(dependent, model)) continue;
21358
- const endpoint = relation.type === "many-one" ? relation.to : relation.from;
21359
- const field = relation.type === "many-one" ? core.relationFkFieldForManyOne(relation) : relation.type === "htree" ? relation.fkField || relation.foreignKey || relation.inverse || "parentId" : core.relationFkFieldForOneMany(relation);
21360
- const parentId = row[field];
21361
- if (parentId === null || parentId === void 0 || parentId === "") continue;
21362
- if (typeof parentId !== "string") throw new Error("Ancestor repair: malformed parent link");
21363
- const resourceField = relation.fkResourceField || (relation.type === "htree" ? `${field.replace(/Id$/, "")}Resource` : `${(relation.type === "many-one" ? relation.relation || "target" : relation.inverse || relation.relation || "source").replace(/Id$/, "")}Resource`);
21364
- const discriminator = row[resourceField];
21365
- const inferred = core.resolveEndpointResource(endpoint, parentId, schema);
21366
- let parentResource = inferred;
21367
- if (core.endpointList(endpoint).length > 1 && discriminator != null) {
21368
- if (typeof discriminator !== "string" || !core.endpointIncludes(endpoint, discriminator) || inferred && inferred !== discriminator) {
21369
- throw new Error("Ancestor repair: invalid parent resource discriminator");
21370
- }
21371
- parentResource = discriminator;
21372
- }
21373
- if (!parentResource) throw new Error("Ancestor repair: ambiguous parent resource");
21374
- const parent = await adapter.findOne({
21375
- model: parentResource,
21376
- where: [{ field: "id", operator: "eq", value: parentId }],
21377
- namespace
21378
- });
21379
- if (!parent) throw new Error("Ancestor repair: missing parent record");
21380
- const parentInactive = await visit(parentResource, parent);
21381
- inherited = inherited || parentInactive;
21382
- }
21383
- active.delete(key);
21384
- const effective = inherited || row.isArchived === true || row.trashedAt != null;
21385
- resolved.set(key, effective);
21386
- return root ? inherited : effective;
21387
- }
21388
- return visit(resource, record, true);
21389
- }
21390
-
21391
- // src/execution/migration/ancestor-inactive.ts
21392
- var DEFAULT_BATCH_SIZE = 500;
21393
- function compareCodePoints(a, b) {
21394
- return a < b ? -1 : a > b ? 1 : 0;
21395
- }
21396
- function ancestorInactiveResources(schema) {
21397
- return [...core.getAncestorInactiveResources(schema.relations)].sort(compareCodePoints);
21398
- }
21399
- async function recomputeAncestorInactive(adapter, schema, options) {
21400
- const { namespace, dryRun = false, logger } = options;
21401
- const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
21402
- const maxGraphNodes = options.maxGraphNodes ?? 1e4;
21403
- for (const value of [batchSize, maxGraphNodes]) {
21404
- if (!Number.isSafeInteger(value) || value < 1) throw new Error("Ancestor repair: limits must be positive safe integers");
21405
- }
21406
- const resources = ancestorInactiveResources(schema);
21407
- if (resources.length === 0) return { scanned: 0, updated: 0, skipped: 0, nextCursor: null };
21408
- let cursor = options.cursor ?? { resource: resources[0], afterId: null };
21409
- let resourceIndex = resources.indexOf(cursor.resource);
21410
- if (resourceIndex === -1) {
21411
- throw new Error(`recomputeAncestorInactive: unknown cursor resource "${cursor.resource}"`);
21412
- }
21413
- let scanned = 0;
21414
- let updated = 0;
21415
- let skipped = 0;
21416
- let remaining = batchSize;
21417
- while (remaining > 0) {
21418
- const resource = resources[resourceIndex];
21419
- const requested = remaining;
21420
- const rows = await adapter.findMany({
21421
- model: resource,
21422
- where: cursor.afterId === null ? [] : [{ field: "id", operator: "gt", value: cursor.afterId }],
21423
- orderBy: [{ field: "id", direction: "asc" }],
21424
- limit: requested,
21425
- namespace
21426
- });
21427
- for (const row of rows) {
21428
- const id = row.id;
21429
- if (typeof id !== "string" || id.length === 0) throw new Error("Ancestor repair: malformed record identifier");
21430
- scanned += 1;
21431
- const next = await resolveAuthoritativeAncestorInactive(adapter, schema, resource, row, namespace, maxGraphNodes);
21432
- const previous = row[core.ANCESTOR_INACTIVE_FIELD];
21433
- if (previous !== next) {
21434
- if (dryRun) {
21435
- updated += 1;
21436
- } else {
21437
- const affected = await adapter.updateMany({
21438
- model: resource,
21439
- where: [
21440
- { field: "id", operator: "eq", value: id },
21441
- {
21442
- field: core.ANCESTOR_INACTIVE_FIELD,
21443
- operator: "eq",
21444
- value: previous ?? null
21445
- }
21446
- ],
21447
- data: { [core.ANCESTOR_INACTIVE_FIELD]: next },
21448
- namespace
21449
- });
21450
- updated += affected > 0 ? 1 : 0;
21451
- skipped += affected > 0 ? 0 : 1;
21452
- }
21453
- }
21454
- cursor = { resource, afterId: id };
21455
- }
21456
- remaining -= rows.length;
21457
- if (rows.length < requested) {
21458
- resourceIndex += 1;
21459
- if (resourceIndex >= resources.length) {
21460
- logger?.info("datafn.ancestorInactive.recompute.complete", { namespace, scanned, updated, skipped, dryRun });
21461
- return { scanned, updated, skipped, nextCursor: null };
21462
- }
21463
- cursor = { resource: resources[resourceIndex], afterId: null };
21464
- }
21465
- }
21466
- return { scanned, updated, skipped, nextCursor: cursor };
21467
- }
21468
- async function recomputeAncestorInactiveAll(adapter, schema, options) {
21469
- const maxSweeps = options.maxSweeps ?? 32;
21470
- if (!Number.isSafeInteger(maxSweeps) || maxSweeps < 1) throw new Error("Ancestor repair: maxSweeps must be a positive safe integer");
21471
- let scanned = 0;
21472
- let updated = 0;
21473
- let skipped = 0;
21474
- let sweeps = 0;
21475
- let converged = false;
21476
- while (sweeps < maxSweeps) {
21477
- sweeps += 1;
21478
- let sweepUpdated = 0;
21479
- let sweepSkipped = 0;
21480
- let cursor = null;
21481
- do {
21482
- const result = await recomputeAncestorInactive(adapter, schema, { ...options, cursor });
21483
- scanned += result.scanned;
21484
- sweepUpdated += result.updated;
21485
- sweepSkipped += result.skipped;
21486
- cursor = result.nextCursor;
21487
- } while (cursor !== null);
21488
- updated += sweepUpdated;
21489
- skipped += sweepSkipped;
21490
- if (sweepUpdated === 0 && sweepSkipped === 0) {
21491
- converged = true;
21492
- break;
21493
- }
21494
- if (options.dryRun) break;
21495
- }
21496
- if (!converged) {
21497
- options.logger?.warn("datafn.ancestorInactive.recompute.notConverged", {
21498
- namespace: options.namespace,
21499
- sweeps,
21500
- updated,
21501
- skipped,
21502
- dryRun: options.dryRun === true
21503
- });
21504
- }
21505
- return { scanned, updated, skipped, sweeps, converged };
21506
- }
21507
-
21508
- Object.defineProperty(exports, "DATAFN_REQUEST_ACTIONS", {
21509
- enumerable: true,
21510
- get: function () { return core.DATAFN_REQUEST_ACTIONS; }
21511
- });
21512
- Object.defineProperty(exports, "DATAFN_REQUEST_PROTOCOL_VERSION", {
21513
- enumerable: true,
21514
- get: function () { return core.DATAFN_REQUEST_PROTOCOL_VERSION; }
21515
- });
21516
- Object.defineProperty(exports, "DATAFN_REQUEST_PROTOCOL_VERSIONS", {
21517
- enumerable: true,
21518
- get: function () { return core.DATAFN_REQUEST_PROTOCOL_VERSIONS; }
21519
- });
21520
- Object.defineProperty(exports, "DATAFN_STRUCTURAL_SELECTOR_POSITIONS", {
21521
- enumerable: true,
21522
- get: function () { return core.DATAFN_STRUCTURAL_SELECTOR_POSITIONS; }
21523
- });
21524
- Object.defineProperty(exports, "collectStructuralResourceSelectors", {
21525
- enumerable: true,
21526
- get: function () { return core.collectStructuralResourceSelectors; }
21527
- });
21528
- Object.defineProperty(exports, "extractStructuralResourceSelectors", {
21529
- enumerable: true,
21530
- get: function () { return core.extractStructuralResourceSelectors; }
21531
- });
21532
- Object.defineProperty(exports, "isDatafnRequestAction", {
21533
- enumerable: true,
21534
- get: function () { return core.isDatafnRequestAction; }
21535
- });
21536
- Object.defineProperty(exports, "parseDatafnRequest", {
21537
- enumerable: true,
21538
- get: function () { return core.parseDatafnRequest; }
21539
- });
21540
20670
  exports.AtomicSequenceStore = AtomicSequenceStore;
21541
20671
  exports.ChainedSequenceStore = ChainedSequenceStore;
21542
20672
  exports.DATAFN_MULTI_REGION_CAPABILITY = DATAFN_MULTI_REGION_CAPABILITY;
@@ -21544,50 +20674,26 @@ exports.DATAFN_ROUTING_ASSERTION_HEADER = DATAFN_ROUTING_ASSERTION_HEADER;
21544
20674
  exports.DATAFN_ROUTING_INTERNAL_HEADERS = DATAFN_ROUTING_INTERNAL_HEADERS;
21545
20675
  exports.DatabaseSequenceStore = DatabaseSequenceStore;
21546
20676
  exports.DatafnExecutorError = DatafnExecutorError;
21547
- exports.DatafnNamespaceStorageError = DatafnNamespaceStorageError;
21548
20677
  exports.DatafnPublicLinkInputError = DatafnPublicLinkInputError;
21549
20678
  exports.DatafnRoutingError = DatafnRoutingError;
21550
- exports.POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL = POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL;
21551
- exports.POSTGRES_NAMESPACE_STORAGE_INDEX_SQL = POSTGRES_NAMESPACE_STORAGE_INDEX_SQL;
21552
- exports.ancestorInactiveResources = ancestorInactiveResources;
21553
- exports.assertInternalNamespaceStorageMetadataComplete = assertInternalNamespaceStorageMetadataComplete;
21554
20679
  exports.claimDatafnNamespacePlacement = claimDatafnNamespacePlacement;
21555
- exports.composeNamespaceStoragePlan = composeNamespaceStoragePlan;
21556
20680
  exports.createConditionalKvDatafnPlacementDirectory = createConditionalKvDatafnPlacementDirectory;
21557
20681
  exports.createDatafnGatewayRouter = createDatafnGatewayRouter;
21558
- exports.createDatafnHmacRouteTickets = createDatafnHmacRouteTickets;
21559
20682
  exports.createDatafnHmacRoutingAssertions = createDatafnHmacRoutingAssertions;
21560
20683
  exports.createDatafnMultiRegionPlugin = createDatafnMultiRegionPlugin;
21561
20684
  exports.createDatafnPublicLinksPlugin = createDatafnPublicLinksPlugin;
21562
- exports.createDatafnRouteBootstrap = createDatafnRouteBootstrap;
21563
20685
  exports.createDatafnServer = createDatafnServer;
21564
20686
  exports.createMemoryDatafnPlacementDirectory = createMemoryDatafnPlacementDirectory;
21565
20687
  exports.createMemoryDatafnRoutingReplayStore = createMemoryDatafnRoutingReplayStore;
21566
20688
  exports.createSequenceStore = createSequenceStore;
21567
20689
  exports.datafn = datafn;
21568
20690
  exports.datafnMultiRegionPlugin = datafnMultiRegionPlugin;
21569
- exports.drainNamespacePermissionDirectoryOutbox = drainNamespacePermissionDirectoryOutbox;
21570
- exports.drainNamespaceStorage = drainNamespaceStorage;
21571
- exports.inspectPostgresNamespaceStorage = inspectPostgresNamespaceStorage;
21572
20691
  exports.migrateDatafnNamespace = migrateDatafnNamespace;
21573
- exports.namespacedInternalTableRoles = namespacedInternalTableRoles;
21574
- exports.quotePostgresIdentifier = quotePostgresIdentifier;
21575
- exports.rankDatafnPlacementRegions = rankDatafnPlacementRegions;
21576
- exports.readDatafnCloudflarePlacementLocation = readDatafnCloudflarePlacementLocation;
21577
20692
  exports.readDatafnPublicLinkToken = readDatafnPublicLinkToken;
21578
- exports.readDatafnRouteTicket = readDatafnRouteTicket;
21579
- exports.recomputeAncestorInactive = recomputeAncestorInactive;
21580
- exports.recomputeAncestorInactiveAll = recomputeAncestorInactiveAll;
21581
20693
  exports.resolveDatafnPublicLink = resolveDatafnPublicLink;
21582
- exports.resolveNamespaceStoragePlan = resolveNamespaceStoragePlan;
21583
- exports.routeTicketError = routeTicketError;
21584
- exports.selectDatafnPlacementRegion = selectDatafnPlacementRegion;
21585
- exports.selectNamespaceStorageEntries = selectNamespaceStorageEntries;
21586
20694
  exports.validateDatafnPlacement = validateDatafnPlacement;
21587
- exports.validateDatafnRouteTicket = validateDatafnRouteTicket;
21588
20695
  exports.validateDatafnRoutingBodyLimit = validateDatafnRoutingBodyLimit;
21589
20696
  exports.withDatafnPublicLinksSchema = withDatafnPublicLinksSchema;
21590
- exports.withDatafnRegionalCors = withDatafnRegionalCors;
21591
20697
  exports.withDatafnRoutingAssertion = withDatafnRoutingAssertion;
21592
20698
  //# sourceMappingURL=index.cjs.map
21593
20699
  //# sourceMappingURL=index.cjs.map