@datafn/server 0.1.3 → 0.1.4-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}`,
@@ -3304,22 +3275,6 @@ function filterAncestorInactiveRecords(records, match, metadata) {
3304
3275
  }
3305
3276
  return records.filter((record) => record.isAncestorInactive !== true);
3306
3277
  }
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
3278
  function applyOmit(record, omit) {
3324
3279
  if (!omit || omit.length === 0) {
3325
3280
  return record;
@@ -3328,8 +3283,13 @@ function applyOmit(record, omit) {
3328
3283
  for (const [key, value] of Object.entries(record)) {
3329
3284
  if (key === "id" || !omit.includes(key)) {
3330
3285
  if (Array.isArray(value)) {
3331
- result[key] = value.map((item) => applyOmitToArrayValue(item, omit));
3332
- } else if (isPlainRecord(value) && key !== "$relation_metadata") {
3286
+ result[key] = value.map((item) => {
3287
+ if (typeof item === "object" && item !== null) {
3288
+ return applyOmit(item, omit);
3289
+ }
3290
+ return item;
3291
+ });
3292
+ } else if (typeof value === "object" && value !== null && key !== "$relation_metadata") {
3333
3293
  result[key] = applyOmit(value, omit);
3334
3294
  } else {
3335
3295
  result[key] = value;
@@ -3430,7 +3390,6 @@ function getFkFieldsToOmit(schema, targetResource) {
3430
3390
  function materializeSelect(record, resource, select, schema, store, omit, metadata) {
3431
3391
  const resourceSchema = schema.resources.find((r) => r.name === resource);
3432
3392
  if (!resourceSchema) return { id: record.id };
3433
- record = core.stripNullsForNonNullableFields(record, resourceSchema);
3434
3393
  const fkFieldsToOmit = getFkFieldsToOmit(schema, resource);
3435
3394
  const effectiveOmit = omit ? [...omit, ...Array.from(fkFieldsToOmit)] : Array.from(fkFieldsToOmit);
3436
3395
  if (!select || select.length === 0) {
@@ -3539,9 +3498,7 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3539
3498
  ),
3540
3499
  htreeRelation,
3541
3500
  metadata
3542
- ).map(
3543
- (c) => applyOmit(core.stripNullsForNonNullableFields(c, resourceSchema), omit)
3544
- );
3501
+ ).map((c) => applyOmit(c, omit));
3545
3502
  } else if (parsed.directive === "**") {
3546
3503
  result[parsed.baseName] = filterAncestorInactiveRecords(
3547
3504
  htreeChildren(
@@ -3553,9 +3510,7 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3553
3510
  ),
3554
3511
  htreeRelation,
3555
3512
  metadata
3556
- ).map(
3557
- (d) => applyOmit(core.stripNullsForNonNullableFields(d, resourceSchema), omit)
3558
- );
3513
+ ).map((d) => applyOmit(d, omit));
3559
3514
  }
3560
3515
  includedFields.add(parsed.baseName);
3561
3516
  } else if (parsed.baseName === "parent") {
@@ -3564,9 +3519,7 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3564
3519
  resource,
3565
3520
  htreeRelation.relation,
3566
3521
  store
3567
- ).map(
3568
- (a) => applyOmit(core.stripNullsForNonNullableFields(a, resourceSchema), omit)
3569
- );
3522
+ ).map((a) => applyOmit(a, omit));
3570
3523
  includedFields.add(parsed.baseName);
3571
3524
  }
3572
3525
  continue;
@@ -3862,10 +3815,8 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3862
3815
  }
3863
3816
  const aggregations = query.aggregations || {};
3864
3817
  let results = [];
3865
- const samples = /* @__PURE__ */ new WeakMap();
3866
3818
  for (const [, groupRecords] of groups.entries()) {
3867
3819
  const row = {};
3868
- samples.set(row, groupRecords[0]);
3869
3820
  groupBy.forEach((field) => {
3870
3821
  const sample = groupRecords[0];
3871
3822
  const val = resolveValue(
@@ -3876,9 +3827,7 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3876
3827
  query.resource,
3877
3828
  resourceSchema
3878
3829
  );
3879
- if (val !== void 0) {
3880
- row[field] = val;
3881
- }
3830
+ row[field] = val;
3882
3831
  });
3883
3832
  for (const group of temporalGroups) {
3884
3833
  row[group.alias] = core.resolveTemporalBucketValue(groupRecords[0], group);
@@ -3918,24 +3867,7 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3918
3867
  paginated.length = limit;
3919
3868
  }
3920
3869
  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
- }),
3870
+ groups: paginated,
3939
3871
  nextCursor
3940
3872
  };
3941
3873
  }
@@ -3964,10 +3896,9 @@ function orderGroupedResults(groups, sortTerms) {
3964
3896
  return 0;
3965
3897
  });
3966
3898
  }
3967
- function resolveValue(record, path, schema, store, resourceName, precomputedResource, normalize = false) {
3899
+ function resolveValue(record, path, schema, store, resourceName, precomputedResource) {
3968
3900
  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];
3901
+ return record[path];
3971
3902
  }
3972
3903
  const parts = path.split(".");
3973
3904
  const resource = precomputedResource ?? schema.resources.find((r) => r.name === resourceName);
@@ -4005,8 +3936,7 @@ function resolveValue(record, path, schema, store, resourceName, precomputedReso
4005
3936
  }
4006
3937
  }
4007
3938
  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];
3939
+ return currentRecord[lastField];
4010
3940
  }
4011
3941
  var DFQL_TO_ADAPTER_OP = {
4012
3942
  // $-prefixed DFQL operators
@@ -5236,7 +5166,6 @@ async function pushdownCore(query, schema, db, namespace) {
5236
5166
  function projectFieldsPushdown(record, resource, schema, select, omit) {
5237
5167
  const resourceSchema = schema.resources.find((r) => r.name === resource);
5238
5168
  if (!resourceSchema) return { id: record.id };
5239
- record = core.stripNullsForNonNullableFields(record, resourceSchema);
5240
5169
  const resolvedCapabilities = core.resolveCapabilities(
5241
5170
  schema.capabilities,
5242
5171
  resourceSchema.capabilities
@@ -6005,213 +5934,6 @@ var AuthResolverCache = class {
6005
5934
  function createAuthResolverCache() {
6006
5935
  return new AuthResolverCache();
6007
5936
  }
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
5937
  var DATAFN_ROUTING_ASSERTION_HEADER = "x-datafn-routing-assertion";
6216
5938
  var DATAFN_ROUTING_INTERNAL_HEADERS = [
6217
5939
  DATAFN_ROUTING_ASSERTION_HEADER,
@@ -6363,28 +6085,6 @@ async function claimDatafnNamespacePlacement(input) {
6363
6085
  async function validateDatafnPlacement(input) {
6364
6086
  const startedAt = Date.now();
6365
6087
  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
6088
  let placement;
6389
6089
  try {
6390
6090
  placement = await input.runtime.directory.get(input.namespace);
@@ -6422,7 +6122,7 @@ async function validateDatafnPlacement(input) {
6422
6122
  retryable: false
6423
6123
  });
6424
6124
  }
6425
- const assertion = ticket ? void 0 : await validateRoutingAssertion({
6125
+ const assertion = await validateRoutingAssertion({
6426
6126
  namespace: input.namespace,
6427
6127
  regionId: input.regionId,
6428
6128
  placement,
@@ -6478,7 +6178,7 @@ async function validateDatafnPlacement(input) {
6478
6178
  internal: Boolean(assertion)
6479
6179
  });
6480
6180
  }
6481
- if (assertion && assertion.epoch !== placement.epoch || ticket && ticket.epoch !== placement.epoch) {
6181
+ if (assertion && assertion.epoch !== placement.epoch) {
6482
6182
  await emitRoutingEvent(input.runtime, {
6483
6183
  type: "mismatch",
6484
6184
  requestId: requestId2,
@@ -6491,17 +6191,14 @@ async function validateDatafnPlacement(input) {
6491
6191
  });
6492
6192
  throw new DatafnRoutingError({
6493
6193
  code: "DATAFN_REGION_MISMATCH",
6494
- message: "Routing grant uses a stale placement epoch",
6194
+ message: "Routing assertion uses a stale placement epoch",
6495
6195
  status: 409,
6496
6196
  retryable: true,
6497
6197
  placement,
6498
- internal: Boolean(assertion)
6198
+ internal: true
6499
6199
  });
6500
6200
  }
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 } : {} };
6201
+ return { placement, ...assertion ? { assertion } : {} };
6505
6202
  }
6506
6203
  function createDatafnGatewayRouter(config) {
6507
6204
  const maxBodyBytes = validateDatafnRoutingBodyLimit(config.maxBodyBytes);
@@ -8457,8 +8154,9 @@ async function recordChangesWithRetry(changeTracking, entries, maxRetries = 2, l
8457
8154
  }
8458
8155
  }
8459
8156
  }
8157
+ var preparedNamespaces = /* @__PURE__ */ new WeakMap();
8460
8158
  var ChangeTrackingService = class _ChangeTrackingService {
8461
- constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false) {
8159
+ constructor(db, namespace = "datafn", sequenceStore, onChange, logger, metaEnsured = false, changesEnsured = false, namespaceMetaEnsured = false) {
8462
8160
  this.db = db;
8463
8161
  this.namespace = namespace;
8464
8162
  this.sequenceStore = sequenceStore;
@@ -8466,8 +8164,10 @@ var ChangeTrackingService = class _ChangeTrackingService {
8466
8164
  this.logger = logger;
8467
8165
  this.metaEnsured = false;
8468
8166
  this.changesEnsured = false;
8167
+ this.namespaceMetaEnsured = false;
8469
8168
  this.metaEnsured = metaEnsured;
8470
8169
  this.changesEnsured = changesEnsured;
8170
+ this.namespaceMetaEnsured = namespaceMetaEnsured;
8471
8171
  }
8472
8172
  /** Initialize every durable table before an enclosing transaction begins. */
8473
8173
  async ensureReady() {
@@ -8482,6 +8182,48 @@ var ChangeTrackingService = class _ChangeTrackingService {
8482
8182
  await ensureInternalTable(this.db, "__datafn_meta");
8483
8183
  this.metaEnsured = true;
8484
8184
  }
8185
+ await this.ensureNamespaceMeta();
8186
+ }
8187
+ /**
8188
+ * Creates this namespace's `__datafn_meta` row before an enclosing
8189
+ * transaction begins. Sequence allocation otherwise creates the row inside
8190
+ * the transaction on a namespace's first write, and when two first writes
8191
+ * race, the losing INSERT fails with a unique-key conflict. On PostgreSQL that
8192
+ * aborts the whole transaction, so the recovery read that follows fails with
8193
+ * "current transaction is aborted". Outside a transaction the conflict is
8194
+ * harmless: the row exists either way, and later allocations only read and
8195
+ * CAS-update it. Transaction-bound instances (from `withDb`) never prepare
8196
+ * the row; the base instance does so before the transaction opens.
8197
+ */
8198
+ async ensureNamespaceMeta() {
8199
+ if (this.namespaceMetaEnsured) {
8200
+ return;
8201
+ }
8202
+ let prepared = preparedNamespaces.get(this.db);
8203
+ if (!prepared) {
8204
+ prepared = /* @__PURE__ */ new Set();
8205
+ preparedNamespaces.set(this.db, prepared);
8206
+ }
8207
+ if (prepared.has(this.namespace)) {
8208
+ this.namespaceMetaEnsured = true;
8209
+ return;
8210
+ }
8211
+ const where = [{ field: "namespace", op: "eq", value: this.namespace }];
8212
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8213
+ try {
8214
+ await this.db.internal.create("__datafn_meta", {
8215
+ id: `meta:${this.namespace}`,
8216
+ namespace: this.namespace,
8217
+ next_server_seq: 1
8218
+ });
8219
+ } catch (error) {
8220
+ if (!await this.db.internal.findOne("__datafn_meta", where)) {
8221
+ throw error;
8222
+ }
8223
+ }
8224
+ }
8225
+ prepared.add(this.namespace);
8226
+ this.namespaceMetaEnsured = true;
8485
8227
  }
8486
8228
  /**
8487
8229
  * REL-011: Create a new ChangeTrackingService with a different db adapter.
@@ -8497,7 +8239,8 @@ var ChangeTrackingService = class _ChangeTrackingService {
8497
8239
  emitChanges ? this.onChange : void 0,
8498
8240
  this.logger,
8499
8241
  this.metaEnsured,
8500
- this.changesEnsured
8242
+ this.changesEnsured,
8243
+ true
8501
8244
  );
8502
8245
  }
8503
8246
  /**
@@ -8932,16 +8675,12 @@ function buildReplaceRecord(schema, resourceName, existingRecord, newRecord, res
8932
8675
  result[key] = existingRecord[key];
8933
8676
  continue;
8934
8677
  }
8935
- if (field.readonly) {
8936
- result[key] = Object.prototype.hasOwnProperty.call(newRecord, key) ? newRecord[key] : existingRecord[key];
8937
- continue;
8938
- }
8939
8678
  if (Object.prototype.hasOwnProperty.call(newRecord, key)) {
8940
8679
  result[key] = newRecord[key];
8941
8680
  } else {
8942
8681
  result[key] = field.default !== void 0 ? field.default : null;
8943
8682
  }
8944
- if (field.required && (result[key] === void 0 || result[key] === null && !field.nullable)) {
8683
+ if (field.required && (result[key] === null || result[key] === void 0)) {
8945
8684
  return {
8946
8685
  ok: false,
8947
8686
  code: "DFQL_INVALID",
@@ -9028,7 +8767,8 @@ function isRecordEffectivelyInactive(record) {
9028
8767
  return isRecordInactive(record) || record?.isAncestorInactive === true;
9029
8768
  }
9030
8769
  function resourceSupportsAncestorInactive(schema, resource) {
9031
- return core.resourceRequiresAncestorInactive(schema.relations, resource);
8770
+ const resourceSchema = schema.resources.find((candidate) => candidate.name === resource);
8771
+ return resourceSchema?.fields.some((field) => field.name === "isAncestorInactive") === true;
9032
8772
  }
9033
8773
  function dependentEndpoint(relation) {
9034
8774
  return relation.type === "many-one" ? relation.from : relation.to;
@@ -10447,7 +10187,7 @@ function decideMergeMode(schema, resource, id, delta) {
10447
10187
  for (const field of resourceDef.fields) {
10448
10188
  if (!field.required) continue;
10449
10189
  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);
10190
+ const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && delta[field.name] !== null;
10451
10191
  const hasDefault = field.default !== void 0;
10452
10192
  if (!hasProvided && !hasDefault) return { mode: "not_found" };
10453
10193
  }
@@ -12186,64 +11926,6 @@ async function drainPermissionDirectoryOutbox(db, runtime, logger, limit = 100)
12186
11926
  }
12187
11927
  return { processed, pending: tasks.length - processed };
12188
11928
  }
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
11929
 
12248
11930
  // src/execution/mutation/execute.ts
12249
11931
  var FAILED_SHARE_COMPENSATION_RESULT = /* @__PURE__ */ Symbol("failedShareCompensation");
@@ -12345,23 +12027,6 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12345
12027
  let additionalChanges = [];
12346
12028
  let skipChangeTracking = false;
12347
12029
  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
12030
  try {
12366
12031
  switch (mutation.operation) {
12367
12032
  case "insert":
@@ -14821,7 +14486,7 @@ function compareCanonicalChangeEntries(a, b) {
14821
14486
  function mergeCanonicalChangeStreamsBounded(streams, limit) {
14822
14487
  const heads = streams.filter((stream) => stream.changes.length > 0).map((stream) => ({ resource: stream.resource, changes: stream.changes, index: 0 }));
14823
14488
  const merged = [];
14824
- const latestCursorPerResource = /* @__PURE__ */ Object.create(null);
14489
+ const latestCursorPerResource = {};
14825
14490
  let peakWindow = heads.length;
14826
14491
  while (heads.length > 0 && merged.length < limit) {
14827
14492
  let bestIdx = 0;
@@ -15053,11 +14718,11 @@ async function executePullCanonical(request, schema, db, namespace, sequenceStor
15053
14718
  const requestedResourceKeys = Object.keys(request.cursors).filter(
15054
14719
  (resource) => resource !== ACTOR_FEED_CURSOR_KEY
15055
14720
  );
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);
14721
+ const records = {};
14722
+ const merged = {};
14723
+ const deleted = {};
14724
+ const joins = {};
14725
+ const cursors = {};
15061
14726
  for (const resource of requestedResourceKeys) {
15062
14727
  if (!resource.startsWith("join_") && !resource.startsWith("__datafn_")) {
15063
14728
  records[resource] = [];
@@ -15460,17 +15125,6 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15460
15125
  const batchLocalSeen = /* @__PURE__ */ new Map();
15461
15126
  async function executeMutationOp(mut, targetDb) {
15462
15127
  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
15128
  switch (mut.operation) {
15475
15129
  case "insert": {
15476
15130
  const coercedData = applyDateCoercion(schema, mut.resource, mut.record || {}, logger);
@@ -18001,7 +17655,6 @@ var WebSocketManager = class {
18001
17655
  * Reverse mapping: client → known principalIds for O(1) targeted index cleanup.
18002
17656
  */
18003
17657
  this.clientPrincipals = /* @__PURE__ */ new Map();
18004
- this.routeTickets = /* @__PURE__ */ new Map();
18005
17658
  this.clientPlacement = /* @__PURE__ */ new Map();
18006
17659
  /** Monotonic namespace fence generation closes the validation/registration race. */
18007
17660
  this.namespaceFenceGeneration = /* @__PURE__ */ new Map();
@@ -18153,11 +17806,6 @@ var WebSocketManager = class {
18153
17806
  */
18154
17807
  addClient(client, authContext) {
18155
17808
  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
17809
  if (this.closed) {
18162
17810
  this.closeClientSafely(client, 1001, "Going Away", "ws-closed-admission");
18163
17811
  return false;
@@ -18191,12 +17839,6 @@ var WebSocketManager = class {
18191
17839
  ...authContext.regionId ? { regionId: authContext.regionId } : {},
18192
17840
  ...Number.isSafeInteger(authContext.routingEpoch) ? { epoch: authContext.routingEpoch } : {}
18193
17841
  });
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
17842
  if (this.heartbeatTimer === null) {
18201
17843
  this.startHeartbeat();
18202
17844
  }
@@ -18205,24 +17847,7 @@ var WebSocketManager = class {
18205
17847
  /**
18206
17848
  * Handle disconnection.
18207
17849
  */
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
17850
  removeClient(client) {
18223
- const ticket = this.routeTickets.get(client);
18224
- if (ticket) clearTimeout(ticket.timer);
18225
- this.routeTickets.delete(client);
18226
17851
  const namespace = this.clientNamespace.get(client);
18227
17852
  if (namespace !== void 0) {
18228
17853
  this.removeTargetingIndexes(client, namespace);
@@ -18339,16 +17964,9 @@ var WebSocketManager = class {
18339
17964
  principals: mode === "targeted" ? Array.from(requestedPrincipals).sort() : void 0
18340
17965
  }
18341
17966
  });
18342
- let sent = 0;
18343
17967
  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
17968
  try {
18350
17969
  client.send(msg);
18351
- sent++;
18352
17970
  } catch (e) {
18353
17971
  this.logger?.error("Error sending to websocket client", { error: String(e), operation: "ws-broadcast" });
18354
17972
  this.removeClient(client);
@@ -18358,7 +17976,7 @@ var WebSocketManager = class {
18358
17976
  return {
18359
17977
  mode,
18360
17978
  degraded,
18361
- wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : sent
17979
+ wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : recipients.size
18362
17980
  };
18363
17981
  }
18364
17982
  /**
@@ -18377,8 +17995,6 @@ var WebSocketManager = class {
18377
17995
  this.clientNamespace.clear();
18378
17996
  this.clientPrincipals.clear();
18379
17997
  this.clientPlacement.clear();
18380
- for (const ticket of this.routeTickets.values()) clearTimeout(ticket.timer);
18381
- this.routeTickets.clear();
18382
17998
  this.pendingPong.clear();
18383
17999
  }
18384
18000
  /**
@@ -18585,6 +18201,35 @@ function relationReferencesInternalResource(relation, internalResourceNames) {
18585
18201
  function normalizeResourceEndpoint(endpoint) {
18586
18202
  return typeof endpoint === "string" ? [endpoint] : [...endpoint];
18587
18203
  }
18204
+ function payloadReferencesInternalResource(payload, internalResourceNames) {
18205
+ if (internalResourceNames.size === 0) {
18206
+ return false;
18207
+ }
18208
+ if (Array.isArray(payload)) {
18209
+ return payload.some((entry) => payloadReferencesInternalResource(entry, internalResourceNames));
18210
+ }
18211
+ if (!payload || typeof payload !== "object") {
18212
+ return false;
18213
+ }
18214
+ const record = payload;
18215
+ if (typeof record.resource === "string" && internalResourceNames.has(record.resource)) {
18216
+ return true;
18217
+ }
18218
+ if (Array.isArray(record.resources) && record.resources.some((resource) => typeof resource === "string" && internalResourceNames.has(resource))) {
18219
+ return true;
18220
+ }
18221
+ for (const key of ["mutations", "queries", "steps", "operations"]) {
18222
+ if (Array.isArray(record[key]) && payloadReferencesInternalResource(record[key], internalResourceNames)) {
18223
+ return true;
18224
+ }
18225
+ }
18226
+ for (const key of ["query", "mutation", "payload"]) {
18227
+ if (record[key] && payloadReferencesInternalResource(record[key], internalResourceNames)) {
18228
+ return true;
18229
+ }
18230
+ }
18231
+ return false;
18232
+ }
18588
18233
  function normalizePluginAuthorizationError(error, pluginName) {
18589
18234
  if (error && typeof error === "object") {
18590
18235
  const candidate = error;
@@ -19183,10 +18828,10 @@ async function createDatafnServer(config) {
19183
18828
  }
19184
18829
  return { ok: true };
19185
18830
  };
19186
- const withAuth = (action, handler, origin = "http", rest = false) => {
18831
+ const withAuth = (action, handler) => {
19187
18832
  return async (req, ctx) => {
19188
18833
  const enrichedCtx = createEnrichedContext(ctx);
19189
- const placementRequest = multiRegionRuntime?.placement && origin === "http" ? req.clone() : void 0;
18834
+ const placementRequest = multiRegionRuntime?.placement ? req.clone() : void 0;
19190
18835
  let payload = null;
19191
18836
  if (shuttingDown) {
19192
18837
  return completeDatafnResponse({
@@ -19315,36 +18960,7 @@ async function createDatafnServer(config) {
19315
18960
  }
19316
18961
  enrichedCtx.parsedBody = payload;
19317
18962
  }
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))) {
18963
+ if (payloadReferencesInternalResource(payload, internalResourceNames)) {
19348
18964
  await emitDataFnEvent({
19349
18965
  domain: "datafn",
19350
18966
  type: "datafn.authorization.denied",
@@ -19370,9 +18986,7 @@ async function createDatafnServer(config) {
19370
18986
  namespace: await extractNamespace(enrichedCtx),
19371
18987
  regionId: multiRegionRuntime.regionId,
19372
18988
  runtime: multiRegionRuntime.placement,
19373
- request: placementRequest,
19374
- scope: action,
19375
- trustedInternal: origin === "executor"
18989
+ request: placementRequest
19376
18990
  });
19377
18991
  } catch (error) {
19378
18992
  if (error instanceof DatafnRoutingError) {
@@ -19391,7 +19005,7 @@ async function createDatafnServer(config) {
19391
19005
  action,
19392
19006
  request: req,
19393
19007
  context: enrichedCtx,
19394
- payload: structuralPayload
19008
+ payload
19395
19009
  });
19396
19010
  if (!pluginAuthorization.ok) {
19397
19011
  await emitDataFnEvent({
@@ -19411,7 +19025,7 @@ async function createDatafnServer(config) {
19411
19025
  });
19412
19026
  }
19413
19027
  if (config.authorize) {
19414
- const authorized = await config.authorize(enrichedCtx, action, structuralPayload);
19028
+ const authorized = await config.authorize(enrichedCtx, action, payload);
19415
19029
  if (!authorized) {
19416
19030
  await emitDataFnEvent({
19417
19031
  domain: "datafn",
@@ -19486,7 +19100,7 @@ async function createDatafnServer(config) {
19486
19100
  try {
19487
19101
  const configuredContext = config.context;
19488
19102
  const executorContext = context ?? (typeof configuredContext === "function" ? await configuredContext(request) : configuredContext ?? {});
19489
- response = await withAuth(action, handler, "executor")(request, executorContext);
19103
+ response = await withAuth(action, handler)(request, executorContext);
19490
19104
  } catch {
19491
19105
  throw new DatafnExecutorError(
19492
19106
  { code: "INTERNAL", message: "Internal Server Error" },
@@ -19676,9 +19290,7 @@ async function createDatafnServer(config) {
19676
19290
  method: route.method,
19677
19291
  path: route.path,
19678
19292
  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)
19293
+ handler: withAuth(action, route.handler)
19682
19294
  });
19683
19295
  }
19684
19296
  }
@@ -19850,18 +19462,12 @@ async function createDatafnServer(config) {
19850
19462
  regionId: multiRegionRuntime.regionId,
19851
19463
  runtime: multiRegionRuntime.placement,
19852
19464
  request: handshakeRequest,
19853
- scope: "websocket",
19854
- trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion && !multiRegionRuntime.placement.routeTickets
19465
+ trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion
19855
19466
  });
19856
19467
  added = wsManager.addClient(client, {
19857
19468
  ...authContext,
19858
19469
  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
19470
+ routingEpoch: validated.placement.epoch
19865
19471
  });
19866
19472
  if (!added) return false;
19867
19473
  if (wsManager.getNamespaceFenceGeneration(authContext.namespace) !== fenceGeneration) {
@@ -19880,7 +19486,7 @@ async function createDatafnServer(config) {
19880
19486
  if (added) wsManager.removeClient(client);
19881
19487
  try {
19882
19488
  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,
19489
+ error instanceof DatafnRoutingError ? 4510 : 1011,
19884
19490
  error instanceof Error ? error.message : "Placement validation failed"
19885
19491
  );
19886
19492
  } catch {
@@ -19888,7 +19494,6 @@ async function createDatafnServer(config) {
19888
19494
  return false;
19889
19495
  }
19890
19496
  },
19891
- revokeRouteTicket: (ticketId) => wsManager.revokeRouteTicket(ticketId),
19892
19497
  fenceNamespace: (namespace, minimumEpoch) => wsManager.fenceNamespace(namespace, minimumEpoch),
19893
19498
  removeClient: (client) => wsManager.removeClient(client),
19894
19499
  handleMessage: (client, data) => wsManager.handleMessage(client, data),
@@ -20826,717 +20431,6 @@ function bytesToBase64Url(bytes) {
20826
20431
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20827
20432
  }
20828
20433
 
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
20434
  exports.AtomicSequenceStore = AtomicSequenceStore;
21541
20435
  exports.ChainedSequenceStore = ChainedSequenceStore;
21542
20436
  exports.DATAFN_MULTI_REGION_CAPABILITY = DATAFN_MULTI_REGION_CAPABILITY;
@@ -21544,50 +20438,26 @@ exports.DATAFN_ROUTING_ASSERTION_HEADER = DATAFN_ROUTING_ASSERTION_HEADER;
21544
20438
  exports.DATAFN_ROUTING_INTERNAL_HEADERS = DATAFN_ROUTING_INTERNAL_HEADERS;
21545
20439
  exports.DatabaseSequenceStore = DatabaseSequenceStore;
21546
20440
  exports.DatafnExecutorError = DatafnExecutorError;
21547
- exports.DatafnNamespaceStorageError = DatafnNamespaceStorageError;
21548
20441
  exports.DatafnPublicLinkInputError = DatafnPublicLinkInputError;
21549
20442
  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
20443
  exports.claimDatafnNamespacePlacement = claimDatafnNamespacePlacement;
21555
- exports.composeNamespaceStoragePlan = composeNamespaceStoragePlan;
21556
20444
  exports.createConditionalKvDatafnPlacementDirectory = createConditionalKvDatafnPlacementDirectory;
21557
20445
  exports.createDatafnGatewayRouter = createDatafnGatewayRouter;
21558
- exports.createDatafnHmacRouteTickets = createDatafnHmacRouteTickets;
21559
20446
  exports.createDatafnHmacRoutingAssertions = createDatafnHmacRoutingAssertions;
21560
20447
  exports.createDatafnMultiRegionPlugin = createDatafnMultiRegionPlugin;
21561
20448
  exports.createDatafnPublicLinksPlugin = createDatafnPublicLinksPlugin;
21562
- exports.createDatafnRouteBootstrap = createDatafnRouteBootstrap;
21563
20449
  exports.createDatafnServer = createDatafnServer;
21564
20450
  exports.createMemoryDatafnPlacementDirectory = createMemoryDatafnPlacementDirectory;
21565
20451
  exports.createMemoryDatafnRoutingReplayStore = createMemoryDatafnRoutingReplayStore;
21566
20452
  exports.createSequenceStore = createSequenceStore;
21567
20453
  exports.datafn = datafn;
21568
20454
  exports.datafnMultiRegionPlugin = datafnMultiRegionPlugin;
21569
- exports.drainNamespacePermissionDirectoryOutbox = drainNamespacePermissionDirectoryOutbox;
21570
- exports.drainNamespaceStorage = drainNamespaceStorage;
21571
- exports.inspectPostgresNamespaceStorage = inspectPostgresNamespaceStorage;
21572
20455
  exports.migrateDatafnNamespace = migrateDatafnNamespace;
21573
- exports.namespacedInternalTableRoles = namespacedInternalTableRoles;
21574
- exports.quotePostgresIdentifier = quotePostgresIdentifier;
21575
- exports.rankDatafnPlacementRegions = rankDatafnPlacementRegions;
21576
- exports.readDatafnCloudflarePlacementLocation = readDatafnCloudflarePlacementLocation;
21577
20456
  exports.readDatafnPublicLinkToken = readDatafnPublicLinkToken;
21578
- exports.readDatafnRouteTicket = readDatafnRouteTicket;
21579
- exports.recomputeAncestorInactive = recomputeAncestorInactive;
21580
- exports.recomputeAncestorInactiveAll = recomputeAncestorInactiveAll;
21581
20457
  exports.resolveDatafnPublicLink = resolveDatafnPublicLink;
21582
- exports.resolveNamespaceStoragePlan = resolveNamespaceStoragePlan;
21583
- exports.routeTicketError = routeTicketError;
21584
- exports.selectDatafnPlacementRegion = selectDatafnPlacementRegion;
21585
- exports.selectNamespaceStorageEntries = selectNamespaceStorageEntries;
21586
20458
  exports.validateDatafnPlacement = validateDatafnPlacement;
21587
- exports.validateDatafnRouteTicket = validateDatafnRouteTicket;
21588
20459
  exports.validateDatafnRoutingBodyLimit = validateDatafnRoutingBodyLimit;
21589
20460
  exports.withDatafnPublicLinksSchema = withDatafnPublicLinksSchema;
21590
- exports.withDatafnRegionalCors = withDatafnRegionalCors;
21591
20461
  exports.withDatafnRoutingAssertion = withDatafnRoutingAssertion;
21592
20462
  //# sourceMappingURL=index.cjs.map
21593
20463
  //# sourceMappingURL=index.cjs.map