@datafn/server 0.1.4-maint.0 → 0.2.1

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/server.ts
9
+ // src/index.ts
10
10
 
11
11
  // src/execution/internal-tables.ts
12
12
  var META_COLUMNS = [
@@ -56,6 +56,9 @@ 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
+ }
59
62
  async function ensureInternalTable(adapter, tableName) {
60
63
  const columns = INTERNAL_TABLE_SCHEMAS[tableName];
61
64
  if (!columns) {
@@ -472,8 +475,8 @@ function createSequenceStore(config) {
472
475
  // src/http/json.ts
473
476
  async function parseJsonBody(req) {
474
477
  try {
475
- const text = await req.text();
476
- if (!text || text.trim() === "") {
478
+ const text2 = await req.text();
479
+ if (!text2 || text2.trim() === "") {
477
480
  return {
478
481
  ok: false,
479
482
  error: {
@@ -483,7 +486,7 @@ async function parseJsonBody(req) {
483
486
  }
484
487
  };
485
488
  }
486
- const data = JSON.parse(text);
489
+ const data = JSON.parse(text2);
487
490
  return { ok: true, data };
488
491
  } catch (error) {
489
492
  return {
@@ -733,6 +736,13 @@ function validateRecordKeys(index, resourceName, record, basePath, mode = "write
733
736
  for (const key of Object.keys(record)) {
734
737
  if (key === "id") continue;
735
738
  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
+ }
736
746
  return vErr(
737
747
  "DFQL_UNKNOWN_FIELD",
738
748
  `Unknown field: ${key} on ${resourceName}`,
@@ -1021,13 +1031,32 @@ function validateMutation(mutation, index, basePath = "$", opts) {
1021
1031
  `${basePath}.record.${fieldName}`
1022
1032
  );
1023
1033
  }
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
+ }
1024
1053
  }
1025
1054
  if (m.operation === "insert" || m.operation === "replace") {
1026
1055
  const resource2 = resourceResult.result;
1027
1056
  const record2 = m.record;
1028
1057
  for (const field of resource2.fields) {
1029
1058
  if (field.required && field.default === void 0 && field.name !== "id" && !field.readonly) {
1030
- if (!(field.name in record2) || record2[field.name] === null || record2[field.name] === void 0) {
1059
+ if (!(field.name in record2) || record2[field.name] === void 0 || record2[field.name] === null && !field.nullable) {
1031
1060
  return vErr(
1032
1061
  "DFQL_INVALID",
1033
1062
  `Required field missing: ${field.name}`,
@@ -3275,6 +3304,22 @@ function filterAncestorInactiveRecords(records, match, metadata) {
3275
3304
  }
3276
3305
  return records.filter((record) => record.isAncestorInactive !== true);
3277
3306
  }
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
+ }
3278
3323
  function applyOmit(record, omit) {
3279
3324
  if (!omit || omit.length === 0) {
3280
3325
  return record;
@@ -3283,13 +3328,8 @@ function applyOmit(record, omit) {
3283
3328
  for (const [key, value] of Object.entries(record)) {
3284
3329
  if (key === "id" || !omit.includes(key)) {
3285
3330
  if (Array.isArray(value)) {
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") {
3331
+ result[key] = value.map((item) => applyOmitToArrayValue(item, omit));
3332
+ } else if (isPlainRecord(value) && key !== "$relation_metadata") {
3293
3333
  result[key] = applyOmit(value, omit);
3294
3334
  } else {
3295
3335
  result[key] = value;
@@ -3390,6 +3430,7 @@ function getFkFieldsToOmit(schema, targetResource) {
3390
3430
  function materializeSelect(record, resource, select, schema, store, omit, metadata) {
3391
3431
  const resourceSchema = schema.resources.find((r) => r.name === resource);
3392
3432
  if (!resourceSchema) return { id: record.id };
3433
+ record = core.stripNullsForNonNullableFields(record, resourceSchema);
3393
3434
  const fkFieldsToOmit = getFkFieldsToOmit(schema, resource);
3394
3435
  const effectiveOmit = omit ? [...omit, ...Array.from(fkFieldsToOmit)] : Array.from(fkFieldsToOmit);
3395
3436
  if (!select || select.length === 0) {
@@ -3498,7 +3539,9 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3498
3539
  ),
3499
3540
  htreeRelation,
3500
3541
  metadata
3501
- ).map((c) => applyOmit(c, omit));
3542
+ ).map(
3543
+ (c) => applyOmit(core.stripNullsForNonNullableFields(c, resourceSchema), omit)
3544
+ );
3502
3545
  } else if (parsed.directive === "**") {
3503
3546
  result[parsed.baseName] = filterAncestorInactiveRecords(
3504
3547
  htreeChildren(
@@ -3510,7 +3553,9 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3510
3553
  ),
3511
3554
  htreeRelation,
3512
3555
  metadata
3513
- ).map((d) => applyOmit(d, omit));
3556
+ ).map(
3557
+ (d) => applyOmit(core.stripNullsForNonNullableFields(d, resourceSchema), omit)
3558
+ );
3514
3559
  }
3515
3560
  includedFields.add(parsed.baseName);
3516
3561
  } else if (parsed.baseName === "parent") {
@@ -3519,7 +3564,9 @@ function materializeSelect(record, resource, select, schema, store, omit, metada
3519
3564
  resource,
3520
3565
  htreeRelation.relation,
3521
3566
  store
3522
- ).map((a) => applyOmit(a, omit));
3567
+ ).map(
3568
+ (a) => applyOmit(core.stripNullsForNonNullableFields(a, resourceSchema), omit)
3569
+ );
3523
3570
  includedFields.add(parsed.baseName);
3524
3571
  }
3525
3572
  continue;
@@ -3815,8 +3862,10 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3815
3862
  }
3816
3863
  const aggregations = query.aggregations || {};
3817
3864
  let results = [];
3865
+ const samples = /* @__PURE__ */ new WeakMap();
3818
3866
  for (const [, groupRecords] of groups.entries()) {
3819
3867
  const row = {};
3868
+ samples.set(row, groupRecords[0]);
3820
3869
  groupBy.forEach((field) => {
3821
3870
  const sample = groupRecords[0];
3822
3871
  const val = resolveValue(
@@ -3827,7 +3876,9 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3827
3876
  query.resource,
3828
3877
  resourceSchema
3829
3878
  );
3830
- row[field] = val;
3879
+ if (val !== void 0) {
3880
+ row[field] = val;
3881
+ }
3831
3882
  });
3832
3883
  for (const group of temporalGroups) {
3833
3884
  row[group.alias] = core.resolveTemporalBucketValue(groupRecords[0], group);
@@ -3867,7 +3918,24 @@ function executeAggregateQuery(query, records, schema, store, temporal) {
3867
3918
  paginated.length = limit;
3868
3919
  }
3869
3920
  return {
3870
- groups: paginated,
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
+ }),
3871
3939
  nextCursor
3872
3940
  };
3873
3941
  }
@@ -3896,9 +3964,10 @@ function orderGroupedResults(groups, sortTerms) {
3896
3964
  return 0;
3897
3965
  });
3898
3966
  }
3899
- function resolveValue(record, path, schema, store, resourceName, precomputedResource) {
3967
+ function resolveValue(record, path, schema, store, resourceName, precomputedResource, normalize = false) {
3900
3968
  if (!path.includes(".")) {
3901
- return record[path];
3969
+ const definition2 = precomputedResource?.fields.find((field) => field.name === path);
3970
+ return normalize && record[path] === null && definition2 && definition2.nullable !== true ? void 0 : record[path];
3902
3971
  }
3903
3972
  const parts = path.split(".");
3904
3973
  const resource = precomputedResource ?? schema.resources.find((r) => r.name === resourceName);
@@ -3936,7 +4005,8 @@ function resolveValue(record, path, schema, store, resourceName, precomputedReso
3936
4005
  }
3937
4006
  }
3938
4007
  const lastField = parts[parts.length - 1];
3939
- return currentRecord[lastField];
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];
3940
4010
  }
3941
4011
  var DFQL_TO_ADAPTER_OP = {
3942
4012
  // $-prefixed DFQL operators
@@ -5166,6 +5236,7 @@ async function pushdownCore(query, schema, db, namespace) {
5166
5236
  function projectFieldsPushdown(record, resource, schema, select, omit) {
5167
5237
  const resourceSchema = schema.resources.find((r) => r.name === resource);
5168
5238
  if (!resourceSchema) return { id: record.id };
5239
+ record = core.stripNullsForNonNullableFields(record, resourceSchema);
5169
5240
  const resolvedCapabilities = core.resolveCapabilities(
5170
5241
  schema.capabilities,
5171
5242
  resourceSchema.capabilities
@@ -5934,6 +6005,292 @@ var AuthResolverCache = class {
5934
6005
  function createAuthResolverCache() {
5935
6006
  return new AuthResolverCache();
5936
6007
  }
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
+ var routeKeyId = (value) => /^[A-Za-z0-9_-]{1,128}$/.test(value);
6073
+ var routeSigningInput = (content) => Buffer.from(`datafn-regional-route-v1:${content}`);
6074
+ function createDatafnEd25519RouteTicketSigner(input) {
6075
+ if (!routeKeyId(input.activeKeyId)) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6076
+ let key;
6077
+ try {
6078
+ key = typeof input.privateKey === "string" ? crypto$1.createPrivateKey(input.privateKey) : input.privateKey;
6079
+ } catch {
6080
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6081
+ }
6082
+ if (key.type !== "private" || key.asymmetricKeyType !== "ed25519") throw new Error("DATAFN_ROUTE_KEY_INVALID");
6083
+ return {
6084
+ sign(claims) {
6085
+ assertClaims(claims);
6086
+ const header = Buffer.from(JSON.stringify({ typ: "datafn-route-v1", alg: "EdDSA", kid: input.activeKeyId })).toString("base64url");
6087
+ const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
6088
+ const content = `${header}.${payload}`;
6089
+ return `${content}.${crypto$1.sign(null, routeSigningInput(content), key).toString("base64url")}`;
6090
+ }
6091
+ };
6092
+ }
6093
+ function createDatafnEd25519RouteTicketVerifier(input) {
6094
+ const keys = new Map(Object.entries(input.publicKeys).map(([id, value]) => {
6095
+ if (!routeKeyId(id)) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6096
+ if (typeof value === "string" && !value.startsWith("-----BEGIN PUBLIC KEY-----")) {
6097
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6098
+ }
6099
+ let key;
6100
+ try {
6101
+ key = typeof value === "string" ? crypto$1.createPublicKey(value) : value;
6102
+ } catch {
6103
+ throw new Error("DATAFN_ROUTE_KEY_INVALID");
6104
+ }
6105
+ if (key.type !== "public" || key.asymmetricKeyType !== "ed25519") throw new Error("DATAFN_ROUTE_KEY_INVALID");
6106
+ return [id, key];
6107
+ }));
6108
+ if (keys.size === 0) throw new Error("DATAFN_ROUTE_KEY_INVALID");
6109
+ return {
6110
+ verify(ticket) {
6111
+ try {
6112
+ if (typeof ticket !== "string" || ticket.length > 16384 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(ticket)) throw new Error();
6113
+ const [header, payload, signature] = ticket.split(".");
6114
+ const protectedHeader = JSON.parse(Buffer.from(header, "base64url").toString());
6115
+ const key = keys.get(protectedHeader.kid);
6116
+ if (!key || protectedHeader.typ !== "datafn-route-v1" || protectedHeader.alg !== "EdDSA") throw new Error();
6117
+ if (!crypto$1.verify(null, routeSigningInput(`${header}.${payload}`), key, Buffer.from(signature, "base64url"))) throw new Error();
6118
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
6119
+ assertClaims(claims);
6120
+ return claims;
6121
+ } catch {
6122
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6123
+ }
6124
+ }
6125
+ };
6126
+ }
6127
+ function createDatafnRouteBootstrap(config) {
6128
+ const ttl = config.ttlMs ?? 6e4;
6129
+ if (!text(config.issuer) || !Number.isSafeInteger(ttl) || ttl < 1e3 || ttl > core.DATAFN_ROUTE_MAX_TTL_MS) {
6130
+ throw new Error("DATAFN_ROUTE_BOOTSTRAP_CONFIG_INVALID");
6131
+ }
6132
+ const now = config.now ?? Date.now;
6133
+ return async (request) => {
6134
+ try {
6135
+ if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST", "cache-control": "no-store" } });
6136
+ const identity = await config.authenticate(request);
6137
+ if (!identity || !text(identity.subject) || !text(identity.namespace)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6138
+ let placement;
6139
+ try {
6140
+ placement = await config.directory.get(identity.namespace);
6141
+ } catch {
6142
+ throw new DatafnRoutingError({ code: "DATAFN_PLACEMENT_UNAVAILABLE", message: "Placement unavailable", status: 503, retryable: true });
6143
+ }
6144
+ if (!placement || placement.namespace !== identity.namespace || placement.state === "tombstoned") {
6145
+ throw new DatafnRoutingError({ code: "DATAFN_PLACEMENT_NOT_FOUND", message: "Placement not found", status: 404, retryable: false });
6146
+ }
6147
+ if (placement.state !== "active" || placement.migration) {
6148
+ throw new DatafnRoutingError({ code: "DATAFN_NAMESPACE_MOVING", message: "Placement is fenced", status: 409, retryable: true });
6149
+ }
6150
+ const permitted = [...await config.authorize(identity)];
6151
+ const endpoint = await config.resolveEndpoint(placement);
6152
+ const issuedAt = now();
6153
+ const expiresAt = Math.min(issuedAt + ttl, identity.expiresAt ?? Infinity);
6154
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= issuedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6155
+ const httpUrl = core.validateDatafnRegionalEndpoint(endpoint.httpUrl);
6156
+ const wsUrl = endpoint.wsUrl ? core.validateDatafnRegionalEndpoint(endpoint.wsUrl, true) : void 0;
6157
+ if (permitted.includes("websocket") && !wsUrl) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6158
+ const ticket = await config.signer.sign({
6159
+ version: 1,
6160
+ issuer: config.issuer,
6161
+ audience: endpoint.audience,
6162
+ subject: identity.subject,
6163
+ namespace: identity.namespace,
6164
+ regionId: placement.regionId,
6165
+ epoch: placement.epoch,
6166
+ scopes: permitted,
6167
+ issuedAt,
6168
+ notBefore: issuedAt,
6169
+ expiresAt,
6170
+ ticketId: crypto$1.randomUUID(),
6171
+ ...identity.sessionBinding ? { sessionBinding: identity.sessionBinding } : {}
6172
+ });
6173
+ const descriptor = {
6174
+ version: 1,
6175
+ httpUrl,
6176
+ ...wsUrl ? { wsUrl } : {},
6177
+ ticket,
6178
+ expiresAt,
6179
+ renewAfter: issuedAt + Math.floor((expiresAt - issuedAt) * 0.8)
6180
+ };
6181
+ emit(config, { type: "issued" });
6182
+ return Response.json(descriptor, { headers: { "cache-control": "no-store", pragma: "no-cache" } });
6183
+ } catch (error) {
6184
+ emit(config, { type: "rejected", code: error instanceof DatafnRoutingError ? error.code : "DATAFN_ROUTE_FORBIDDEN" });
6185
+ return (error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_FORBIDDEN")).toResponse();
6186
+ }
6187
+ };
6188
+ }
6189
+ function readDatafnRouteTicket(request, websocket = false) {
6190
+ const header = request.headers.get(core.DATAFN_ROUTE_TICKET_HEADER);
6191
+ const protocols = (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
6192
+ const tickets = protocols.filter((s) => s.startsWith(core.DATAFN_ROUTE_WS_TICKET_PREFIX));
6193
+ 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");
6194
+ return header ?? tickets[0]?.slice(core.DATAFN_ROUTE_WS_TICKET_PREFIX.length);
6195
+ }
6196
+ async function verifyDatafnRegionalTicketIdentity(input) {
6197
+ const { request, regionId, runtime } = input;
6198
+ try {
6199
+ const origin = request.headers.get("origin");
6200
+ if (origin && !runtime.allowedOrigins?.includes(origin)) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6201
+ if (!runtime.authenticate && request.headers.has("cookie")) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6202
+ const token = readDatafnRouteTicket(request, input.websocket);
6203
+ if (!token) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6204
+ const claims = await runtime.verifier.verify(token);
6205
+ assertClaims(claims);
6206
+ const now = (runtime.now ?? Date.now)();
6207
+ const skew = runtime.clockSkewMs ?? 5e3;
6208
+ if (!Number.isFinite(skew) || skew < 0 || skew > 3e4) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6209
+ if (claims.expiresAt <= now) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6210
+ if (claims.issuedAt > now + skew || claims.notBefore > now + skew || claims.issuer !== runtime.issuer || claims.audience !== runtime.audience || claims.regionId !== regionId) throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6211
+ return claims;
6212
+ } catch (error) {
6213
+ const safe = error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6214
+ emit(runtime, { type: "rejected", code: safe.code });
6215
+ throw safe;
6216
+ }
6217
+ }
6218
+ async function validateDatafnRouteTicket(input) {
6219
+ const { runtime } = input;
6220
+ const claims = await verifyDatafnRegionalTicketIdentity({
6221
+ request: input.request,
6222
+ regionId: input.regionId,
6223
+ runtime,
6224
+ websocket: input.scope === "websocket"
6225
+ });
6226
+ try {
6227
+ if (claims.namespace !== input.namespace || !claims.scopes.includes(input.scope)) {
6228
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6229
+ }
6230
+ let identity;
6231
+ if (runtime.authenticate) {
6232
+ identity = await runtime.authenticate(input.request);
6233
+ 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)())) {
6234
+ throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6235
+ }
6236
+ if (identity.expiresAt !== void 0 && claims.expiresAt > identity.expiresAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6237
+ }
6238
+ if (runtime.isActive && !await runtime.isActive(claims)) throw routeTicketError("DATAFN_ROUTE_TICKET_REVOKED");
6239
+ if (runtime.allowRequest && !await runtime.allowRequest(claims)) throw routeTicketError("DATAFN_ROUTE_RATE_LIMITED");
6240
+ const admittedAt = (runtime.now ?? Date.now)();
6241
+ if (identity?.expiresAt !== void 0 && identity.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_FORBIDDEN");
6242
+ if (claims.expiresAt <= admittedAt) throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6243
+ emit(runtime, { type: "accepted" });
6244
+ return claims;
6245
+ } catch (error) {
6246
+ const safe = error instanceof DatafnRoutingError ? error : routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6247
+ emit(runtime, { type: "rejected", code: safe.code });
6248
+ throw safe;
6249
+ }
6250
+ }
6251
+ function withDatafnRegionalCors(handler, options) {
6252
+ const origins = new Set(options.origins.map((origin) => {
6253
+ if (new URL(origin).origin !== origin || origin === "null") throw new Error("DATAFN_ROUTE_ORIGIN_INVALID");
6254
+ return origin;
6255
+ }));
6256
+ const allowedHeaders = /* @__PURE__ */ new Set([
6257
+ "content-type",
6258
+ "authorization",
6259
+ core.DATAFN_ROUTE_TICKET_HEADER,
6260
+ ...(options.headers ?? []).map((header) => header.toLowerCase())
6261
+ ]);
6262
+ const allowedMethods = ["GET", "POST", "PATCH", "DELETE"];
6263
+ return async (request) => {
6264
+ const origin = request.headers.get("origin");
6265
+ if (origin && !origins.has(origin)) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6266
+ if (request.headers.has("cookie")) return routeTicketError("DATAFN_ROUTE_FORBIDDEN").toResponse();
6267
+ if (request.method === "OPTIONS") {
6268
+ const method = request.headers.get("access-control-request-method");
6269
+ const headers2 = (request.headers.get("access-control-request-headers") ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
6270
+ if (!origin || !allowedMethods.includes(method ?? "") || headers2.some((h) => !allowedHeaders.has(h))) return new Response(null, { status: 403 });
6271
+ return new Response(null, { status: 204, headers: {
6272
+ "access-control-allow-origin": origin,
6273
+ "access-control-allow-methods": allowedMethods.join(", "),
6274
+ "access-control-allow-headers": [...allowedHeaders].join(", "),
6275
+ vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
6276
+ "cache-control": "no-store"
6277
+ } });
6278
+ }
6279
+ const response = await handler(request);
6280
+ const headers = new Headers(response.headers);
6281
+ headers.append("vary", "Origin");
6282
+ headers.delete("access-control-allow-credentials");
6283
+ headers.set("cache-control", "no-store");
6284
+ if (origin) headers.set("access-control-allow-origin", origin);
6285
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
6286
+ };
6287
+ }
6288
+ function emit(config, event) {
6289
+ try {
6290
+ config.onEvent?.(event);
6291
+ } catch {
6292
+ }
6293
+ }
5937
6294
  var DATAFN_ROUTING_ASSERTION_HEADER = "x-datafn-routing-assertion";
5938
6295
  var DATAFN_ROUTING_INTERNAL_HEADERS = [
5939
6296
  DATAFN_ROUTING_ASSERTION_HEADER,
@@ -5948,9 +6305,13 @@ var DEFAULT_MIGRATION_RECOVERY_LEASE_MS = 3e4;
5948
6305
  var DatafnRoutingError = class extends Error {
5949
6306
  constructor(input) {
5950
6307
  super(input.message);
6308
+ /** HTTP-shaped metadata so framework routers map an uncaught routing error to its status
6309
+ * (e.g. a ticket-only context provider rejection) instead of a generic 500. */
6310
+ this.isHttpError = true;
5951
6311
  this.name = "DatafnRoutingError";
5952
6312
  this.code = input.code;
5953
6313
  this.status = input.status;
6314
+ this.statusCode = input.status;
5954
6315
  this.retryable = input.retryable;
5955
6316
  this.executionStarted = input.executionStarted ?? false;
5956
6317
  this.placement = input.placement;
@@ -6085,6 +6446,28 @@ async function claimDatafnNamespacePlacement(input) {
6085
6446
  async function validateDatafnPlacement(input) {
6086
6447
  const startedAt = Date.now();
6087
6448
  const requestId2 = input.request?.headers.get("x-request-id") ?? void 0;
6449
+ let ticket;
6450
+ const hasAssertion = Boolean(input.request?.headers.get(input.runtime.assertionHeader ?? DATAFN_ROUTING_ASSERTION_HEADER)?.trim());
6451
+ if (input.request) {
6452
+ const token = readDatafnRouteTicket(input.request, input.scope === "websocket");
6453
+ if (token !== void 0 && (hasAssertion || !input.runtime.routeTickets)) {
6454
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6455
+ }
6456
+ if (input.runtime.routeTickets && (!hasAssertion || token !== void 0)) {
6457
+ if (DATAFN_ROUTING_INTERNAL_HEADERS.some((name) => input.request.headers.has(name))) {
6458
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6459
+ }
6460
+ ticket = await validateDatafnRouteTicket({
6461
+ request: input.request,
6462
+ namespace: input.namespace,
6463
+ regionId: input.regionId,
6464
+ scope: input.scope ?? "custom",
6465
+ runtime: input.runtime.routeTickets
6466
+ });
6467
+ }
6468
+ } else if (input.runtime.routeTickets && !input.trustedInternal) {
6469
+ throw routeTicketError("DATAFN_ROUTE_TICKET_INVALID");
6470
+ }
6088
6471
  let placement;
6089
6472
  try {
6090
6473
  placement = await input.runtime.directory.get(input.namespace);
@@ -6122,7 +6505,7 @@ async function validateDatafnPlacement(input) {
6122
6505
  retryable: false
6123
6506
  });
6124
6507
  }
6125
- const assertion = await validateRoutingAssertion({
6508
+ const assertion = ticket ? void 0 : await validateRoutingAssertion({
6126
6509
  namespace: input.namespace,
6127
6510
  regionId: input.regionId,
6128
6511
  placement,
@@ -6178,7 +6561,7 @@ async function validateDatafnPlacement(input) {
6178
6561
  internal: Boolean(assertion)
6179
6562
  });
6180
6563
  }
6181
- if (assertion && assertion.epoch !== placement.epoch) {
6564
+ if (assertion && assertion.epoch !== placement.epoch || ticket && ticket.epoch !== placement.epoch) {
6182
6565
  await emitRoutingEvent(input.runtime, {
6183
6566
  type: "mismatch",
6184
6567
  requestId: requestId2,
@@ -6191,14 +6574,17 @@ async function validateDatafnPlacement(input) {
6191
6574
  });
6192
6575
  throw new DatafnRoutingError({
6193
6576
  code: "DATAFN_REGION_MISMATCH",
6194
- message: "Routing assertion uses a stale placement epoch",
6577
+ message: "Routing grant uses a stale placement epoch",
6195
6578
  status: 409,
6196
6579
  retryable: true,
6197
6580
  placement,
6198
- internal: true
6581
+ internal: Boolean(assertion)
6199
6582
  });
6200
6583
  }
6201
- return { placement, ...assertion ? { assertion } : {} };
6584
+ if (ticket && ticket.expiresAt <= (input.runtime.routeTickets?.now ?? Date.now)()) {
6585
+ throw routeTicketError("DATAFN_ROUTE_TICKET_EXPIRED");
6586
+ }
6587
+ return { placement, ...assertion ? { assertion } : {}, ...ticket ? { ticket } : {} };
6202
6588
  }
6203
6589
  function createDatafnGatewayRouter(config) {
6204
6590
  const maxBodyBytes = validateDatafnRoutingBodyLimit(config.maxBodyBytes);
@@ -8675,12 +9061,16 @@ function buildReplaceRecord(schema, resourceName, existingRecord, newRecord, res
8675
9061
  result[key] = existingRecord[key];
8676
9062
  continue;
8677
9063
  }
9064
+ if (field.readonly) {
9065
+ result[key] = Object.prototype.hasOwnProperty.call(newRecord, key) ? newRecord[key] : existingRecord[key];
9066
+ continue;
9067
+ }
8678
9068
  if (Object.prototype.hasOwnProperty.call(newRecord, key)) {
8679
9069
  result[key] = newRecord[key];
8680
9070
  } else {
8681
9071
  result[key] = field.default !== void 0 ? field.default : null;
8682
9072
  }
8683
- if (field.required && (result[key] === null || result[key] === void 0)) {
9073
+ if (field.required && (result[key] === void 0 || result[key] === null && !field.nullable)) {
8684
9074
  return {
8685
9075
  ok: false,
8686
9076
  code: "DFQL_INVALID",
@@ -8767,8 +9157,7 @@ function isRecordEffectivelyInactive(record) {
8767
9157
  return isRecordInactive(record) || record?.isAncestorInactive === true;
8768
9158
  }
8769
9159
  function resourceSupportsAncestorInactive(schema, resource) {
8770
- const resourceSchema = schema.resources.find((candidate) => candidate.name === resource);
8771
- return resourceSchema?.fields.some((field) => field.name === "isAncestorInactive") === true;
9160
+ return core.resourceRequiresAncestorInactive(schema.relations, resource);
8772
9161
  }
8773
9162
  function dependentEndpoint(relation) {
8774
9163
  return relation.type === "many-one" ? relation.from : relation.to;
@@ -10187,7 +10576,7 @@ function decideMergeMode(schema, resource, id, delta) {
10187
10576
  for (const field of resourceDef.fields) {
10188
10577
  if (!field.required) continue;
10189
10578
  if (field.name === "id" || field.name === "__ns") continue;
10190
- const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && delta[field.name] !== null;
10579
+ const hasProvided = Object.prototype.hasOwnProperty.call(delta, field.name) && delta[field.name] !== void 0 && (delta[field.name] !== null || field.nullable === true);
10191
10580
  const hasDefault = field.default !== void 0;
10192
10581
  if (!hasProvided && !hasDefault) return { mode: "not_found" };
10193
10582
  }
@@ -11926,6 +12315,64 @@ async function drainPermissionDirectoryOutbox(db, runtime, logger, limit = 100)
11926
12315
  }
11927
12316
  return { processed, pending: tasks.length - processed };
11928
12317
  }
12318
+ async function drainNamespacePermissionDirectoryOutbox(db, namespace, runtime, logger, options = {}) {
12319
+ await ensurePermissionDirectoryOutbox(db);
12320
+ const limit = options.limit ?? 100;
12321
+ const maxRounds = options.maxRounds ?? 32;
12322
+ let processed = 0;
12323
+ for (let round = 0; round < maxRounds; round += 1) {
12324
+ const tasks = await db.internal.findMany(OUTBOX_TABLE, [
12325
+ { field: "namespace", op: "eq", value: namespace },
12326
+ { field: "region_id", op: "eq", value: runtime.regionId },
12327
+ { field: "next_attempt_at", op: "lte", value: (/* @__PURE__ */ new Date()).toISOString() }
12328
+ ], {
12329
+ orderBy: "next_attempt_at",
12330
+ limit
12331
+ });
12332
+ if (tasks.length === 0) {
12333
+ break;
12334
+ }
12335
+ let roundProcessed = 0;
12336
+ for (const task of tasks) {
12337
+ const taskId = String(task.id);
12338
+ const selectedNextAttemptAt = String(task.next_attempt_at);
12339
+ const claimedNextAttemptAt = new Date(
12340
+ Date.now() + DRAIN_CLAIM_LEASE_MS
12341
+ ).toISOString();
12342
+ const claimed = await db.internal.update(OUTBOX_TABLE, [
12343
+ { field: "id", op: "eq", value: taskId },
12344
+ { field: "namespace", op: "eq", value: namespace },
12345
+ { field: "region_id", op: "eq", value: runtime.regionId },
12346
+ { field: "next_attempt_at", op: "eq", value: selectedNextAttemptAt }
12347
+ ], {
12348
+ next_attempt_at: claimedNextAttemptAt
12349
+ });
12350
+ if (claimed === 0) continue;
12351
+ if (await drainPermissionDirectorySync(
12352
+ db,
12353
+ taskId,
12354
+ runtime,
12355
+ logger,
12356
+ { expectedNextAttemptAt: claimedNextAttemptAt }
12357
+ )) {
12358
+ processed += 1;
12359
+ roundProcessed += 1;
12360
+ }
12361
+ }
12362
+ if (roundProcessed === 0) {
12363
+ const remaining2 = await db.internal.findMany(OUTBOX_TABLE, [
12364
+ { field: "namespace", op: "eq", value: namespace },
12365
+ { field: "region_id", op: "eq", value: runtime.regionId }
12366
+ ], { limit: 1 });
12367
+ return { processed, pending: remaining2.length };
12368
+ }
12369
+ }
12370
+ const remaining = await db.internal.findMany(OUTBOX_TABLE, [
12371
+ { field: "namespace", op: "eq", value: namespace },
12372
+ { field: "region_id", op: "eq", value: runtime.regionId }
12373
+ ], { limit: 1 });
12374
+ return { processed, pending: remaining.length };
12375
+ }
11929
12376
 
11930
12377
  // src/execution/mutation/execute.ts
11931
12378
  var FAILED_SHARE_COMPENSATION_RESULT = /* @__PURE__ */ Symbol("failedShareCompensation");
@@ -12027,6 +12474,23 @@ async function executeMutationCore(mutation, db, schema, namespace, effectiveMut
12027
12474
  let additionalChanges = [];
12028
12475
  let skipChangeTracking = false;
12029
12476
  let failedShareCompensation = null;
12477
+ if ((mutation.operation === "insert" || mutation.operation === "merge" || mutation.operation === "replace") && mutation.record) {
12478
+ const systemField = core.findSystemFieldWrite(schema.relations, mutation.resource, mutation.record);
12479
+ if (systemField) {
12480
+ return {
12481
+ ok: false,
12482
+ mutationId: effectiveMutationId,
12483
+ affectedIds: [],
12484
+ errors: [{
12485
+ code: "DFQL_INVALID",
12486
+ message: `Field is read-only: ${systemField} on ${mutation.resource}`,
12487
+ path: `record.${systemField}`,
12488
+ retryable: false
12489
+ }],
12490
+ deduped: false
12491
+ };
12492
+ }
12493
+ }
12030
12494
  try {
12031
12495
  switch (mutation.operation) {
12032
12496
  case "insert":
@@ -13339,6 +13803,16 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
13339
13803
  const steps = request.steps;
13340
13804
  const isAtomic = request.atomic !== false;
13341
13805
  const hasMutations = steps.some((step) => Boolean(step.mutation));
13806
+ if (isAtomic && hasMutations && db.capabilities?.transactions?.supported === false) {
13807
+ return {
13808
+ ok: false,
13809
+ error: {
13810
+ code: "DFQL_UNSUPPORTED",
13811
+ message: "Atomic transact with mutations requires database transactions, which this adapter does not support; send atomic: false to apply steps one at a time",
13812
+ details: { path: "atomic" }
13813
+ }
13814
+ };
13815
+ }
13342
13816
  const multiRegionRuntime = getDatafnMultiRegionRuntimeConfig(plugins);
13343
13817
  const needsPermissionDirectoryOutbox = Boolean(
13344
13818
  hasMutations && multiRegionRuntime && steps.some(
@@ -13461,7 +13935,7 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
13461
13935
  }
13462
13936
  return null;
13463
13937
  };
13464
- if (isAtomic && typeof db.transaction === "function") {
13938
+ if (isAtomic && db.capabilities?.transactions?.supported !== false && typeof db.transaction === "function") {
13465
13939
  const deferredPermissionDirectorySyncs = [];
13466
13940
  const reconcilePermissionDirectoryAfterSettlement = async () => {
13467
13941
  await drainPrequeuedUnshareTasks();
@@ -14486,7 +14960,7 @@ function compareCanonicalChangeEntries(a, b) {
14486
14960
  function mergeCanonicalChangeStreamsBounded(streams, limit) {
14487
14961
  const heads = streams.filter((stream) => stream.changes.length > 0).map((stream) => ({ resource: stream.resource, changes: stream.changes, index: 0 }));
14488
14962
  const merged = [];
14489
- const latestCursorPerResource = {};
14963
+ const latestCursorPerResource = /* @__PURE__ */ Object.create(null);
14490
14964
  let peakWindow = heads.length;
14491
14965
  while (heads.length > 0 && merged.length < limit) {
14492
14966
  let bestIdx = 0;
@@ -14718,11 +15192,11 @@ async function executePullCanonical(request, schema, db, namespace, sequenceStor
14718
15192
  const requestedResourceKeys = Object.keys(request.cursors).filter(
14719
15193
  (resource) => resource !== ACTOR_FEED_CURSOR_KEY
14720
15194
  );
14721
- const records = {};
14722
- const merged = {};
14723
- const deleted = {};
14724
- const joins = {};
14725
- const cursors = {};
15195
+ const records = /* @__PURE__ */ Object.create(null);
15196
+ const merged = /* @__PURE__ */ Object.create(null);
15197
+ const deleted = /* @__PURE__ */ Object.create(null);
15198
+ const joins = /* @__PURE__ */ Object.create(null);
15199
+ const cursors = /* @__PURE__ */ Object.create(null);
14726
15200
  for (const resource of requestedResourceKeys) {
14727
15201
  if (!resource.startsWith("join_") && !resource.startsWith("__datafn_")) {
14728
15202
  records[resource] = [];
@@ -15125,6 +15599,17 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
15125
15599
  const batchLocalSeen = /* @__PURE__ */ new Map();
15126
15600
  async function executeMutationOp(mut, targetDb) {
15127
15601
  const resolvedCapabilities = resolveCapabilitiesForResource2(schema, mut.resource);
15602
+ if ((mut.operation === "insert" || mut.operation === "merge" || mut.operation === "replace") && typeof mut.record === "object" && mut.record !== null) {
15603
+ const systemField = core.findSystemFieldWrite(schema.relations, mut.resource, mut.record);
15604
+ if (systemField) {
15605
+ return {
15606
+ ok: false,
15607
+ code: "DFQL_INVALID",
15608
+ message: `Field is read-only: ${systemField} on ${mut.resource}`,
15609
+ path: `record.${systemField}`
15610
+ };
15611
+ }
15612
+ }
15128
15613
  switch (mut.operation) {
15129
15614
  case "insert": {
15130
15615
  const coercedData = applyDateCoercion(schema, mut.resource, mut.record || {}, logger);
@@ -17655,6 +18140,7 @@ var WebSocketManager = class {
17655
18140
  * Reverse mapping: client → known principalIds for O(1) targeted index cleanup.
17656
18141
  */
17657
18142
  this.clientPrincipals = /* @__PURE__ */ new Map();
18143
+ this.routeTickets = /* @__PURE__ */ new Map();
17658
18144
  this.clientPlacement = /* @__PURE__ */ new Map();
17659
18145
  /** Monotonic namespace fence generation closes the validation/registration race. */
17660
18146
  this.namespaceFenceGeneration = /* @__PURE__ */ new Map();
@@ -17806,6 +18292,11 @@ var WebSocketManager = class {
17806
18292
  */
17807
18293
  addClient(client, authContext) {
17808
18294
  const { namespace } = authContext;
18295
+ if (this.clientNamespace.has(client)) return false;
18296
+ if (authContext.routeTicket && authContext.routeTicket.expiresAt <= (authContext.routeTicket.now ?? Date.now)()) {
18297
+ this.closeClientSafely(client, 4511, "DATAFN_ROUTE_TICKET_EXPIRED", "ws-ticket-expired");
18298
+ return false;
18299
+ }
17809
18300
  if (this.closed) {
17810
18301
  this.closeClientSafely(client, 1001, "Going Away", "ws-closed-admission");
17811
18302
  return false;
@@ -17839,6 +18330,12 @@ var WebSocketManager = class {
17839
18330
  ...authContext.regionId ? { regionId: authContext.regionId } : {},
17840
18331
  ...Number.isSafeInteger(authContext.routingEpoch) ? { epoch: authContext.routingEpoch } : {}
17841
18332
  });
18333
+ if (authContext.routeTicket) {
18334
+ const { id, expiresAt, now = Date.now } = authContext.routeTicket;
18335
+ const timer = setTimeout(() => this.expireRouteClient(client), Math.max(0, expiresAt - now()));
18336
+ timer.unref?.();
18337
+ this.routeTickets.set(client, { id, expiresAt, now, timer });
18338
+ }
17842
18339
  if (this.heartbeatTimer === null) {
17843
18340
  this.startHeartbeat();
17844
18341
  }
@@ -17847,7 +18344,24 @@ var WebSocketManager = class {
17847
18344
  /**
17848
18345
  * Handle disconnection.
17849
18346
  */
18347
+ expireRouteClient(client) {
18348
+ this.removeClient(client);
18349
+ this.closeClientSafely(client, 4511, "DATAFN_ROUTE_TICKET_EXPIRED", "ws-ticket-expired");
18350
+ }
18351
+ revokeRouteTicket(ticketId) {
18352
+ let count = 0;
18353
+ for (const [client, ticket] of this.routeTickets) {
18354
+ if (ticket.id !== ticketId) continue;
18355
+ this.removeClient(client);
18356
+ this.closeClientSafely(client, 4403, "DATAFN_ROUTE_TICKET_REVOKED", "ws-ticket-revoked");
18357
+ count++;
18358
+ }
18359
+ return count;
18360
+ }
17850
18361
  removeClient(client) {
18362
+ const ticket = this.routeTickets.get(client);
18363
+ if (ticket) clearTimeout(ticket.timer);
18364
+ this.routeTickets.delete(client);
17851
18365
  const namespace = this.clientNamespace.get(client);
17852
18366
  if (namespace !== void 0) {
17853
18367
  this.removeTargetingIndexes(client, namespace);
@@ -17964,9 +18478,16 @@ var WebSocketManager = class {
17964
18478
  principals: mode === "targeted" ? Array.from(requestedPrincipals).sort() : void 0
17965
18479
  }
17966
18480
  });
18481
+ let sent = 0;
17967
18482
  for (const client of recipients) {
18483
+ const ticket = this.routeTickets.get(client);
18484
+ if (ticket && ticket.expiresAt <= ticket.now()) {
18485
+ this.expireRouteClient(client);
18486
+ continue;
18487
+ }
17968
18488
  try {
17969
18489
  client.send(msg);
18490
+ sent++;
17970
18491
  } catch (e) {
17971
18492
  this.logger?.error("Error sending to websocket client", { error: String(e), operation: "ws-broadcast" });
17972
18493
  this.removeClient(client);
@@ -17976,7 +18497,7 @@ var WebSocketManager = class {
17976
18497
  return {
17977
18498
  mode,
17978
18499
  degraded,
17979
- wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : recipients.size
18500
+ wokenClients: mode === "namespace-broadcast" ? "all-in-namespace" : sent
17980
18501
  };
17981
18502
  }
17982
18503
  /**
@@ -17995,6 +18516,8 @@ var WebSocketManager = class {
17995
18516
  this.clientNamespace.clear();
17996
18517
  this.clientPrincipals.clear();
17997
18518
  this.clientPlacement.clear();
18519
+ for (const ticket of this.routeTickets.values()) clearTimeout(ticket.timer);
18520
+ this.routeTickets.clear();
17998
18521
  this.pendingPong.clear();
17999
18522
  }
18000
18523
  /**
@@ -18201,35 +18724,6 @@ function relationReferencesInternalResource(relation, internalResourceNames) {
18201
18724
  function normalizeResourceEndpoint(endpoint) {
18202
18725
  return typeof endpoint === "string" ? [endpoint] : [...endpoint];
18203
18726
  }
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
- }
18233
18727
  function normalizePluginAuthorizationError(error, pluginName) {
18234
18728
  if (error && typeof error === "object") {
18235
18729
  const candidate = error;
@@ -18828,10 +19322,10 @@ async function createDatafnServer(config) {
18828
19322
  }
18829
19323
  return { ok: true };
18830
19324
  };
18831
- const withAuth = (action, handler) => {
19325
+ const withAuth = (action, handler, origin = "http", rest = false) => {
18832
19326
  return async (req, ctx) => {
18833
19327
  const enrichedCtx = createEnrichedContext(ctx);
18834
- const placementRequest = multiRegionRuntime?.placement ? req.clone() : void 0;
19328
+ const placementRequest = multiRegionRuntime?.placement && origin === "http" ? req.clone() : void 0;
18835
19329
  let payload = null;
18836
19330
  if (shuttingDown) {
18837
19331
  return completeDatafnResponse({
@@ -18960,7 +19454,36 @@ async function createDatafnServer(config) {
18960
19454
  }
18961
19455
  enrichedCtx.parsedBody = payload;
18962
19456
  }
18963
- if (payloadReferencesInternalResource(payload, internalResourceNames)) {
19457
+ let structuralPayload = payload;
19458
+ if (rest) {
19459
+ let resource;
19460
+ try {
19461
+ const segment = sanitizePathSegment(new URL(req.url).pathname.split("/")[3] ?? "");
19462
+ if (!segment.ok) throw new Error("Invalid path segment");
19463
+ resource = segment.value;
19464
+ } catch {
19465
+ return completeDatafnResponse({
19466
+ action,
19467
+ request: req,
19468
+ context: enrichedCtx,
19469
+ payload,
19470
+ response: errorResponse({ code: "DFQL_INVALID", message: "Invalid path segment", details: { path: "resource" } }, 400)
19471
+ });
19472
+ }
19473
+ structuralPayload = { resource };
19474
+ }
19475
+ const parsedProtocol = core.parseDatafnRequest(action, structuralPayload, { schema: validatedSchema });
19476
+ if (!parsedProtocol.ok) {
19477
+ return completeDatafnResponse({
19478
+ action,
19479
+ request: req,
19480
+ context: enrichedCtx,
19481
+ payload,
19482
+ response: errorResponse(parsedProtocol.error, 400)
19483
+ });
19484
+ }
19485
+ const selection = core.collectStructuralResourceSelectors(parsedProtocol.result);
19486
+ if (selection.selectors.some((resource) => internalResourceNames.has(resource))) {
18964
19487
  await emitDataFnEvent({
18965
19488
  domain: "datafn",
18966
19489
  type: "datafn.authorization.denied",
@@ -18986,7 +19509,9 @@ async function createDatafnServer(config) {
18986
19509
  namespace: await extractNamespace(enrichedCtx),
18987
19510
  regionId: multiRegionRuntime.regionId,
18988
19511
  runtime: multiRegionRuntime.placement,
18989
- request: placementRequest
19512
+ request: placementRequest,
19513
+ scope: action,
19514
+ trustedInternal: origin === "executor"
18990
19515
  });
18991
19516
  } catch (error) {
18992
19517
  if (error instanceof DatafnRoutingError) {
@@ -19005,7 +19530,7 @@ async function createDatafnServer(config) {
19005
19530
  action,
19006
19531
  request: req,
19007
19532
  context: enrichedCtx,
19008
- payload
19533
+ payload: structuralPayload
19009
19534
  });
19010
19535
  if (!pluginAuthorization.ok) {
19011
19536
  await emitDataFnEvent({
@@ -19025,7 +19550,7 @@ async function createDatafnServer(config) {
19025
19550
  });
19026
19551
  }
19027
19552
  if (config.authorize) {
19028
- const authorized = await config.authorize(enrichedCtx, action, payload);
19553
+ const authorized = await config.authorize(enrichedCtx, action, structuralPayload);
19029
19554
  if (!authorized) {
19030
19555
  await emitDataFnEvent({
19031
19556
  domain: "datafn",
@@ -19100,7 +19625,7 @@ async function createDatafnServer(config) {
19100
19625
  try {
19101
19626
  const configuredContext = config.context;
19102
19627
  const executorContext = context ?? (typeof configuredContext === "function" ? await configuredContext(request) : configuredContext ?? {});
19103
- response = await withAuth(action, handler)(request, executorContext);
19628
+ response = await withAuth(action, handler, "executor")(request, executorContext);
19104
19629
  } catch {
19105
19630
  throw new DatafnExecutorError(
19106
19631
  { code: "INTERNAL", message: "Internal Server Error" },
@@ -19290,7 +19815,9 @@ async function createDatafnServer(config) {
19290
19815
  method: route.method,
19291
19816
  path: route.path,
19292
19817
  meta: route.meta,
19293
- handler: withAuth(action, route.handler)
19818
+ // withAuth and the REST handler validate URL segments and complete DataFn response hooks.
19819
+ decodeParams: false,
19820
+ handler: withAuth(action, route.handler, "http", true)
19294
19821
  });
19295
19822
  }
19296
19823
  }
@@ -19462,12 +19989,18 @@ async function createDatafnServer(config) {
19462
19989
  regionId: multiRegionRuntime.regionId,
19463
19990
  runtime: multiRegionRuntime.placement,
19464
19991
  request: handshakeRequest,
19465
- trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion
19992
+ scope: "websocket",
19993
+ trustedInternal: !handshakeRequest && !multiRegionRuntime.placement.requireRoutingAssertion && !multiRegionRuntime.placement.routeTickets
19466
19994
  });
19467
19995
  added = wsManager.addClient(client, {
19468
19996
  ...authContext,
19469
19997
  regionId: validated.placement.regionId,
19470
- routingEpoch: validated.placement.epoch
19998
+ routingEpoch: validated.placement.epoch,
19999
+ routeTicket: validated.ticket ? {
20000
+ id: validated.ticket.ticketId,
20001
+ expiresAt: validated.ticket.expiresAt,
20002
+ now: multiRegionRuntime.placement.routeTickets?.now
20003
+ } : void 0
19471
20004
  });
19472
20005
  if (!added) return false;
19473
20006
  if (wsManager.getNamespaceFenceGeneration(authContext.namespace) !== fenceGeneration) {
@@ -19486,7 +20019,7 @@ async function createDatafnServer(config) {
19486
20019
  if (added) wsManager.removeClient(client);
19487
20020
  try {
19488
20021
  client.close(
19489
- error instanceof DatafnRoutingError ? 4510 : 1011,
20022
+ 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,
19490
20023
  error instanceof Error ? error.message : "Placement validation failed"
19491
20024
  );
19492
20025
  } catch {
@@ -19494,6 +20027,7 @@ async function createDatafnServer(config) {
19494
20027
  return false;
19495
20028
  }
19496
20029
  },
20030
+ revokeRouteTicket: (ticketId) => wsManager.revokeRouteTicket(ticketId),
19497
20031
  fenceNamespace: (namespace, minimumEpoch) => wsManager.fenceNamespace(namespace, minimumEpoch),
19498
20032
  removeClient: (client) => wsManager.removeClient(client),
19499
20033
  handleMessage: (client, data) => wsManager.handleMessage(client, data),
@@ -20431,6 +20965,717 @@ function bytesToBase64Url(bytes) {
20431
20965
  return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
20432
20966
  }
20433
20967
 
20968
+ // src/placement-policy.ts
20969
+ var CONTINENT_CENTERS = {
20970
+ AF: [1.65, 17.68],
20971
+ AN: [-82.86, 135],
20972
+ AS: [34.05, 100.62],
20973
+ EU: [54.53, 15.26],
20974
+ NA: [54.53, -105.26],
20975
+ OC: [-22.74, 140.02],
20976
+ SA: [-14.24, -51.93]
20977
+ };
20978
+ function finiteCoordinate(value, minimum, maximum) {
20979
+ return value !== void 0 && Number.isFinite(value) && value >= minimum && value <= maximum;
20980
+ }
20981
+ function normalizedCandidates(input) {
20982
+ const context = {
20983
+ location: input.location ?? null,
20984
+ preferredRegionId: normalizedPreferredRegionId(input.preferredRegionId)
20985
+ };
20986
+ const seen = /* @__PURE__ */ new Set();
20987
+ const candidates = input.candidates.map((candidate) => {
20988
+ const regionId = candidate.regionId.trim();
20989
+ if (!regionId) throw new Error("DATAFN_PLACEMENT_REGION_ID_REQUIRED");
20990
+ if (seen.has(regionId)) {
20991
+ throw new Error(`DATAFN_PLACEMENT_REGION_DUPLICATE: ${regionId}`);
20992
+ }
20993
+ seen.add(regionId);
20994
+ return regionId === candidate.regionId ? candidate : { ...candidate, regionId };
20995
+ });
20996
+ return candidates.filter(
20997
+ (candidate) => (input.constraints ?? []).every(
20998
+ (constraint) => constraint(candidate, context)
20999
+ )
21000
+ );
21001
+ }
21002
+ function normalizedPreferredRegionId(preferredRegionId) {
21003
+ return preferredRegionId?.trim() || null;
21004
+ }
21005
+ function compareRegionIds(left, right) {
21006
+ return left < right ? -1 : left > right ? 1 : 0;
21007
+ }
21008
+ function sourceCoordinates(location) {
21009
+ if (!location) return null;
21010
+ if (finiteCoordinate(location.latitude, -90, 90) && finiteCoordinate(location.longitude, -180, 180)) {
21011
+ return {
21012
+ coordinates: [location.latitude, location.longitude],
21013
+ source: "coordinates"
21014
+ };
21015
+ }
21016
+ const continent = location.continent?.toUpperCase();
21017
+ const coordinates = continent ? CONTINENT_CENTERS[continent] : void 0;
21018
+ return coordinates ? { coordinates, source: "continent" } : null;
21019
+ }
21020
+ function radians(degrees) {
21021
+ return degrees * Math.PI / 180;
21022
+ }
21023
+ function distanceKilometers(source, target) {
21024
+ const sourceLatitude = radians(source[0]);
21025
+ const targetLatitude = radians(target[0]);
21026
+ const latitudeDelta = radians(target[0] - source[0]);
21027
+ const longitudeDelta = radians(target[1] - source[1]);
21028
+ const haversine = Math.sin(latitudeDelta / 2) ** 2 + Math.cos(sourceLatitude) * Math.cos(targetLatitude) * Math.sin(longitudeDelta / 2) ** 2;
21029
+ const clampedHaversine = Math.min(1, Math.max(0, haversine));
21030
+ return 6371 * 2 * Math.atan2(Math.sqrt(clampedHaversine), Math.sqrt(1 - clampedHaversine));
21031
+ }
21032
+ function rankDatafnPlacementRegions(input) {
21033
+ const candidates = normalizedCandidates(input);
21034
+ const source = sourceCoordinates(input.location ?? null);
21035
+ if (!source) return [];
21036
+ return candidates.flatMap((candidate) => {
21037
+ const { latitude, longitude } = candidate;
21038
+ return finiteCoordinate(latitude, -90, 90) && finiteCoordinate(longitude, -180, 180) ? [
21039
+ {
21040
+ regionId: candidate.regionId,
21041
+ source: source.source,
21042
+ distanceKilometers: distanceKilometers(source.coordinates, [
21043
+ latitude,
21044
+ longitude
21045
+ ])
21046
+ }
21047
+ ] : [];
21048
+ }).sort(
21049
+ (left, right) => (left.distanceKilometers ?? 0) - (right.distanceKilometers ?? 0) || compareRegionIds(left.regionId, right.regionId)
21050
+ );
21051
+ }
21052
+ function stableIndex(key, length) {
21053
+ let hash = 2166136261;
21054
+ for (const byte of new TextEncoder().encode(key)) {
21055
+ hash ^= byte;
21056
+ hash = Math.imul(hash, 16777619) >>> 0;
21057
+ }
21058
+ return hash % length;
21059
+ }
21060
+ function selectDatafnPlacementRegion(input) {
21061
+ const candidates = normalizedCandidates(input);
21062
+ const preferredRegionId = normalizedPreferredRegionId(
21063
+ input.preferredRegionId
21064
+ );
21065
+ if (preferredRegionId && candidates.some((candidate) => candidate.regionId === preferredRegionId)) {
21066
+ return { regionId: preferredRegionId, source: "preferred" };
21067
+ }
21068
+ const ranked = rankDatafnPlacementRegions({
21069
+ candidates,
21070
+ location: input.location ?? null
21071
+ });
21072
+ const nearest = ranked[0];
21073
+ if (nearest) return nearest;
21074
+ if (input.stableKey !== void 0 && candidates.length > 0) {
21075
+ const stableCandidates = [...candidates].sort(
21076
+ (left, right) => compareRegionIds(left.regionId, right.regionId)
21077
+ );
21078
+ const selected = stableCandidates[stableIndex(input.stableKey, stableCandidates.length)];
21079
+ if (selected) {
21080
+ return { regionId: selected.regionId, source: "stable-fallback" };
21081
+ }
21082
+ }
21083
+ return null;
21084
+ }
21085
+ function coordinate(value, minimum, maximum) {
21086
+ const parsed = typeof value === "number" ? value : Number(value);
21087
+ return Number.isFinite(parsed) && parsed >= minimum && parsed <= maximum ? parsed : void 0;
21088
+ }
21089
+ function readDatafnCloudflarePlacementLocation(request) {
21090
+ const cf = request.cf;
21091
+ if (!cf) return null;
21092
+ const latitude = coordinate(cf.latitude, -90, 90);
21093
+ const longitude = coordinate(cf.longitude, -180, 180);
21094
+ const continent = typeof cf.continent === "string" && /^[A-Za-z]{2}$/u.test(cf.continent) ? cf.continent.toUpperCase() : void 0;
21095
+ if (latitude === void 0 && longitude === void 0 && !continent)
21096
+ return null;
21097
+ return {
21098
+ ...latitude === void 0 ? {} : { latitude },
21099
+ ...longitude === void 0 ? {} : { longitude },
21100
+ ...continent ? { continent } : {}
21101
+ };
21102
+ }
21103
+ var POSTGRES_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
21104
+ var DATAFN_INTERNAL_TABLE_RE = /^__datafn_[a-z0-9_]+$/;
21105
+ var LEGACY_PERMISSIONS_TABLE_RE = /^__datafn_permissions_(?!global$)[A-Za-z0-9_]+$/;
21106
+ var POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL = `
21107
+ SELECT c.table_name, c.column_name
21108
+ FROM information_schema.columns AS c
21109
+ JOIN information_schema.tables AS t
21110
+ ON t.table_schema = c.table_schema
21111
+ AND t.table_name = c.table_name
21112
+ WHERE c.table_schema = current_schema()
21113
+ AND t.table_type = 'BASE TABLE'
21114
+ ORDER BY c.table_name, c.ordinal_position
21115
+ `.trim();
21116
+ var INTERNAL_ROLE_BY_TABLE = {
21117
+ __datafn_meta: "sync_meta",
21118
+ __datafn_changes: "sync_changes",
21119
+ __datafn_idempotency: "idempotency",
21120
+ __datafn_seed: "seed",
21121
+ __datafn_permission_directory_outbox: "permission_directory_outbox"
21122
+ };
21123
+ var SHARING_RESOURCE_TABLES = [
21124
+ {
21125
+ logicalRole: "permissions_global",
21126
+ relation: "__datafn_permissions_global"
21127
+ },
21128
+ {
21129
+ logicalRole: "principal_memberships",
21130
+ relation: "__datafn_principal_memberships"
21131
+ },
21132
+ {
21133
+ logicalRole: "principal_hierarchy",
21134
+ relation: "__datafn_principal_hierarchy"
21135
+ }
21136
+ ];
21137
+ var SELECTOR_COLUMN = {
21138
+ resource_ns: "__ns",
21139
+ internal_namespace: "namespace"
21140
+ };
21141
+ var DatafnNamespaceStorageError = class extends Error {
21142
+ constructor(input) {
21143
+ super(input.message);
21144
+ this.name = "DatafnNamespaceStorageError";
21145
+ this.code = input.code;
21146
+ this.details = input.details;
21147
+ }
21148
+ };
21149
+ function fail(code, message, details) {
21150
+ throw new DatafnNamespaceStorageError({ code, message, details });
21151
+ }
21152
+ function quotePostgresIdentifier(identifier) {
21153
+ if (!POSTGRES_IDENTIFIER_RE.test(identifier)) {
21154
+ fail(
21155
+ "DATAFN_NAMESPACE_STORAGE_INVALID",
21156
+ `Invalid PostgreSQL identifier "${identifier}"`,
21157
+ { identifier }
21158
+ );
21159
+ }
21160
+ return `"${identifier}"`;
21161
+ }
21162
+ function namespacedInternalTableRoles() {
21163
+ return INTERNAL_ROLE_BY_TABLE;
21164
+ }
21165
+ function catalogByName(catalog) {
21166
+ const map = /* @__PURE__ */ new Map();
21167
+ for (const relation of catalog.relations) {
21168
+ if (map.has(relation.name)) fail("DATAFN_NAMESPACE_STORAGE_INVALID", "Duplicate catalog relation.");
21169
+ map.set(relation.name, relation);
21170
+ }
21171
+ return map;
21172
+ }
21173
+ function hasColumn(relation, column) {
21174
+ return Boolean(relation?.columns.includes(column));
21175
+ }
21176
+ function isShareableResource(schema, resourceName) {
21177
+ const resource = schema.resources.find((entry) => entry.name === resourceName);
21178
+ if (!resource) return false;
21179
+ const resolved = core.resolveCapabilities(schema.capabilities, resource.capabilities);
21180
+ return resolved.some(
21181
+ (entry) => typeof entry === "object" && entry !== null && "shareable" in entry
21182
+ );
21183
+ }
21184
+ function schemaDerivedRelations(schema) {
21185
+ const planned = [];
21186
+ const resourceRole = core.namespaceStorageManifestEntry("resource");
21187
+ schema.resources.forEach((resource, index) => {
21188
+ planned.push({
21189
+ logicalRole: "resource",
21190
+ relation: resource.name,
21191
+ requiredColumns: [
21192
+ "id",
21193
+ ...resource.fields.map((field) => field.name),
21194
+ ...core.getCapabilityFields(core.resolveCapabilities(schema.capabilities, resource.capabilities)).map((field) => field.name)
21195
+ ].map(physicalColumn),
21196
+ copyOrder: resourceRole.copyOrder + index
21197
+ });
21198
+ });
21199
+ const joinRole = core.namespaceStorageManifestEntry("join");
21200
+ const joinTables = /* @__PURE__ */ new Set();
21201
+ for (const relation of schema.relations ?? []) {
21202
+ if (relation.type !== "many-many") continue;
21203
+ const table = core.getRelationJoinTableName(relation);
21204
+ if (joinTables.has(table)) continue;
21205
+ joinTables.add(table);
21206
+ planned.push({
21207
+ logicalRole: "join",
21208
+ relation: table,
21209
+ requiredColumns: [
21210
+ "id",
21211
+ relation.joinColumns?.from ?? "from",
21212
+ relation.joinColumns?.to ?? "to",
21213
+ ...(relation.metadata ?? []).map((field) => field.name)
21214
+ ].map(physicalColumn),
21215
+ copyOrder: joinRole.copyOrder + joinTables.size
21216
+ });
21217
+ }
21218
+ const legacyRole = core.namespaceStorageManifestEntry("permissions_legacy");
21219
+ schema.resources.forEach((resource, index) => {
21220
+ if (!isShareableResource(schema, resource.name)) return;
21221
+ planned.push({
21222
+ logicalRole: "permissions_legacy",
21223
+ relation: getLegacyPermissionsTable(resource.name),
21224
+ copyOrder: legacyRole.copyOrder + index
21225
+ });
21226
+ });
21227
+ return planned;
21228
+ }
21229
+ function internalPlannedRelations() {
21230
+ return Object.entries(INTERNAL_ROLE_BY_TABLE).map(([relation, logicalRole]) => ({
21231
+ logicalRole,
21232
+ relation,
21233
+ copyOrder: core.namespaceStorageManifestEntry(logicalRole).copyOrder
21234
+ }));
21235
+ }
21236
+ function sharingPlannedRelations() {
21237
+ return SHARING_RESOURCE_TABLES.map((entry) => ({
21238
+ logicalRole: entry.logicalRole,
21239
+ relation: entry.relation,
21240
+ copyOrder: core.namespaceStorageManifestEntry(entry.logicalRole).copyOrder
21241
+ }));
21242
+ }
21243
+ function physicalColumn(name) {
21244
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
21245
+ }
21246
+ var SHARING_REQUIRED_COLUMNS = {
21247
+ permissions_global: ["id", "resource_type", "resource_ns", "resource_id", "principal_id", "level", "grant_kind", "source_ref", "granted_by", "granted_at", "revoked_at"],
21248
+ permissions_legacy: ["id", "resource_id", "user_id", "level", "granted_by", "granted_at", "revoked_at"],
21249
+ principal_memberships: ["id", "namespace", "actor_id", "principal_id", "granted_at", "revoked_at"],
21250
+ principal_hierarchy: ["id", "namespace", "principal_id", "parent_principal_id", "created_at", "revoked_at"]
21251
+ };
21252
+ function toEntry(planned, catalog) {
21253
+ const manifest = core.namespaceStorageManifestEntry(planned.logicalRole);
21254
+ const namespaceColumn = SELECTOR_COLUMN[manifest.selectorKind];
21255
+ const relation = catalog.get(planned.relation);
21256
+ if (!relation) {
21257
+ if (manifest.presence === "schema-derived") {
21258
+ fail(
21259
+ "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21260
+ `Required namespace storage relation "${planned.relation}" is missing from the installed schema.`,
21261
+ { logicalRole: planned.logicalRole, relation: planned.relation }
21262
+ );
21263
+ }
21264
+ return null;
21265
+ }
21266
+ if (!hasColumn(relation, namespaceColumn)) {
21267
+ fail(
21268
+ "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21269
+ `Namespace storage relation "${planned.relation}" is missing selector column "${namespaceColumn}".`,
21270
+ {
21271
+ logicalRole: planned.logicalRole,
21272
+ relation: planned.relation,
21273
+ expectedColumn: namespaceColumn,
21274
+ columns: relation.columns
21275
+ }
21276
+ );
21277
+ }
21278
+ const required = planned.requiredColumns ?? INTERNAL_TABLE_SCHEMAS[planned.relation]?.map((column) => column.name) ?? SHARING_REQUIRED_COLUMNS[planned.logicalRole] ?? ["id"];
21279
+ const missing = required.filter((column) => !hasColumn(relation, column));
21280
+ if (missing.length > 0) {
21281
+ fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", `Relation "${planned.relation}" is missing required columns: ${missing.join(", ")}.`);
21282
+ }
21283
+ const hasIdentity = relation.indexes?.some((index) => index.unique && index.primary === true && index.columns.includes("id") && index.columns.every((column) => column === "id" || column === namespaceColumn));
21284
+ if (!hasIdentity) {
21285
+ fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", `Relation "${planned.relation}" is missing a validated unique identity index.`);
21286
+ }
21287
+ return {
21288
+ logicalRole: planned.logicalRole,
21289
+ ownership: "datafn",
21290
+ relation: planned.relation,
21291
+ quotedRelation: quotePostgresIdentifier(planned.relation),
21292
+ namespaceColumn,
21293
+ quotedNamespaceColumn: quotePostgresIdentifier(namespaceColumn),
21294
+ operations: manifest.operations,
21295
+ copyOrder: planned.copyOrder,
21296
+ present: true
21297
+ };
21298
+ }
21299
+ function isDatafnOwnedCatalogRelation(name, columns) {
21300
+ if (columns.includes("__ns")) return true;
21301
+ return DATAFN_INTERNAL_TABLE_RE.test(name) && columns.includes("namespace");
21302
+ }
21303
+ function unexpectedCatalogRelations(catalog, plannedNames) {
21304
+ const unexpected = [];
21305
+ for (const relation of catalog.relations) {
21306
+ if (plannedNames.has(relation.name)) continue;
21307
+ if (!isDatafnOwnedCatalogRelation(relation.name, relation.columns)) continue;
21308
+ unexpected.push(relation.name);
21309
+ }
21310
+ return unexpected.sort();
21311
+ }
21312
+ function resolveNamespaceStoragePlan(input) {
21313
+ try {
21314
+ core.assertSupportedNamespaceStorageVersions({
21315
+ manifestVersion: input.manifestVersion,
21316
+ schemaVersion: input.schemaVersion
21317
+ });
21318
+ } catch (error) {
21319
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "DATAFN_NAMESPACE_STORAGE_VERSION_MISMATCH";
21320
+ fail(
21321
+ code,
21322
+ error instanceof Error ? error.message : String(error)
21323
+ );
21324
+ }
21325
+ if (input.catalog.dialect !== "postgres") {
21326
+ fail(
21327
+ "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21328
+ `Namespace storage plans are supported for PostgreSQL only. Received dialect "${String(input.catalog.dialect)}".`
21329
+ );
21330
+ }
21331
+ if (!core.isNamespaced(input.schema)) {
21332
+ fail(
21333
+ "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21334
+ "Namespace storage plans require a namespaced DataFn schema."
21335
+ );
21336
+ }
21337
+ const catalog = catalogByName(input.catalog);
21338
+ const planned = [
21339
+ ...schemaDerivedRelations(input.schema),
21340
+ ...sharingPlannedRelations(),
21341
+ ...internalPlannedRelations()
21342
+ ];
21343
+ for (const relation of input.catalog.relations) {
21344
+ if (LEGACY_PERMISSIONS_TABLE_RE.test(relation.name) && !planned.some((entry) => entry.relation === relation.name)) {
21345
+ planned.push({
21346
+ logicalRole: "permissions_legacy",
21347
+ relation: relation.name,
21348
+ copyOrder: core.namespaceStorageManifestEntry("permissions_legacy").copyOrder + 50
21349
+ });
21350
+ }
21351
+ }
21352
+ const plannedNames = new Set(planned.map((entry) => entry.relation));
21353
+ const unexpected = unexpectedCatalogRelations(input.catalog, plannedNames);
21354
+ if (unexpected.length > 0) {
21355
+ fail(
21356
+ "DATAFN_NAMESPACE_STORAGE_UNKNOWN",
21357
+ `Installed schema contains DataFn namespace storage that is not in the supported contract: ${unexpected.join(", ")}.`,
21358
+ { relations: unexpected }
21359
+ );
21360
+ }
21361
+ const entries = planned.map((entry) => toEntry(entry, catalog)).filter((entry) => entry !== null).sort((left, right) => {
21362
+ if (left.copyOrder !== right.copyOrder) return left.copyOrder - right.copyOrder;
21363
+ return left.relation.localeCompare(right.relation);
21364
+ });
21365
+ return {
21366
+ manifestVersion: core.DATAFN_NAMESPACE_STORAGE_MANIFEST_VERSION,
21367
+ schemaVersion: core.DATAFN_NAMESPACE_STORAGE_SCHEMA_VERSION,
21368
+ dialect: "postgres",
21369
+ entries
21370
+ };
21371
+ }
21372
+ function selectNamespaceStorageEntries(plan, operation) {
21373
+ const selected = plan.entries.filter((entry) => entry.operations.includes(operation));
21374
+ if (operation === "cleanup") {
21375
+ return [...selected].sort((left, right) => {
21376
+ if (left.copyOrder !== right.copyOrder) return right.copyOrder - left.copyOrder;
21377
+ return right.relation.localeCompare(left.relation);
21378
+ });
21379
+ }
21380
+ return selected;
21381
+ }
21382
+ function composeNamespaceStoragePlan(plan, applicationEntries) {
21383
+ const existing = new Set(plan.entries.map((entry) => entry.relation));
21384
+ const composed = [...plan.entries];
21385
+ for (const entry of applicationEntries) {
21386
+ if (existing.has(entry.relation)) {
21387
+ fail(
21388
+ "DATAFN_NAMESPACE_STORAGE_INVALID",
21389
+ `Application storage relation "${entry.relation}" collides with DataFn-owned storage.`,
21390
+ { relation: entry.relation }
21391
+ );
21392
+ }
21393
+ existing.add(entry.relation);
21394
+ composed.push({
21395
+ logicalRole: "application",
21396
+ ownership: "application",
21397
+ relation: entry.relation,
21398
+ quotedRelation: quotePostgresIdentifier(entry.relation),
21399
+ namespaceColumn: entry.namespaceColumn,
21400
+ quotedNamespaceColumn: quotePostgresIdentifier(entry.namespaceColumn),
21401
+ operations: entry.operations ?? ["copy", "verify", "cleanup", "fence", "backup"],
21402
+ copyOrder: entry.copyOrder ?? 10,
21403
+ present: true
21404
+ });
21405
+ }
21406
+ composed.sort((left, right) => {
21407
+ if (left.copyOrder !== right.copyOrder) return left.copyOrder - right.copyOrder;
21408
+ return left.relation.localeCompare(right.relation);
21409
+ });
21410
+ return { ...plan, entries: composed };
21411
+ }
21412
+ var POSTGRES_NAMESPACE_STORAGE_INDEX_SQL = `
21413
+ SELECT t.relname AS table_name,
21414
+ array_agg(a.attname ORDER BY k.ordinality) AS index_columns,
21415
+ i.indisunique AS index_unique, i.indisprimary AS index_primary
21416
+ FROM pg_index i
21417
+ JOIN pg_class t ON t.oid = i.indrelid
21418
+ JOIN pg_namespace n ON n.oid = t.relnamespace
21419
+ CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ordinality)
21420
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
21421
+ WHERE n.nspname = current_schema() AND i.indisvalid AND i.indisready
21422
+ AND i.indpred IS NULL AND i.indexprs IS NULL
21423
+ AND k.ordinality <= i.indnkeyatts
21424
+ GROUP BY t.relname, i.indexrelid, i.indisunique, i.indisprimary
21425
+ ORDER BY t.relname, i.indexrelid
21426
+ `.trim();
21427
+ async function inspectPostgresNamespaceStorage(query) {
21428
+ const rows = await query(POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL);
21429
+ const indexRows = await query(POSTGRES_NAMESPACE_STORAGE_INDEX_SQL);
21430
+ const relations = /* @__PURE__ */ new Map();
21431
+ for (const row of rows) {
21432
+ if (typeof row.column_name !== "string") fail("DATAFN_NAMESPACE_STORAGE_INCOMPLETE", "Catalog column metadata is missing.");
21433
+ const columns = relations.get(row.table_name) ?? [];
21434
+ columns.push(row.column_name);
21435
+ relations.set(row.table_name, columns);
21436
+ }
21437
+ return {
21438
+ dialect: "postgres",
21439
+ 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 })) }))
21440
+ };
21441
+ }
21442
+ function assertInternalNamespaceStorageMetadataComplete() {
21443
+ const namespaced = listNamespacedInternalTables();
21444
+ const mapped = Object.keys(INTERNAL_ROLE_BY_TABLE).sort();
21445
+ if (namespaced.join("\0") !== mapped.join("\0")) {
21446
+ fail(
21447
+ "DATAFN_NAMESPACE_STORAGE_INCOMPLETE",
21448
+ "Internal namespace tables are missing from the storage contract.",
21449
+ {
21450
+ namespacedInternalTables: namespaced,
21451
+ mappedInternalTables: mapped,
21452
+ schemas: Object.keys(INTERNAL_TABLE_SCHEMAS).sort()
21453
+ }
21454
+ );
21455
+ }
21456
+ }
21457
+ async function drainNamespaceStorage(input) {
21458
+ const drainEntries = selectNamespaceStorageEntries(input.plan, "drain");
21459
+ if (drainEntries.length === 0) {
21460
+ return { processed: 0, pending: 0 };
21461
+ }
21462
+ const unsupported = drainEntries.filter(
21463
+ (entry) => entry.logicalRole !== "permission_directory_outbox"
21464
+ );
21465
+ if (unsupported.length > 0) {
21466
+ fail(
21467
+ "DATAFN_NAMESPACE_STORAGE_UNSUPPORTED",
21468
+ `No drain implementation for logical roles: ${unsupported.map((entry) => entry.logicalRole).join(", ")}.`,
21469
+ { roles: unsupported.map((entry) => entry.logicalRole) }
21470
+ );
21471
+ }
21472
+ return drainNamespacePermissionDirectoryOutbox(
21473
+ input.adapter,
21474
+ input.namespace,
21475
+ input.runtime,
21476
+ input.logger
21477
+ );
21478
+ }
21479
+ async function resolveAuthoritativeAncestorInactive(adapter, schema, resource, record, namespace, maxGraphNodes) {
21480
+ const active = /* @__PURE__ */ new Set();
21481
+ const resolved = /* @__PURE__ */ new Map();
21482
+ let visited = 0;
21483
+ async function visit(model, row, root = false) {
21484
+ if (typeof row.id !== "string" || row.id.length === 0) {
21485
+ throw new Error("Ancestor repair: malformed record identifier");
21486
+ }
21487
+ const key = JSON.stringify([model, row.id]);
21488
+ if (active.has(key)) throw new Error("Ancestor repair: cycle detected");
21489
+ if (resolved.has(key)) return resolved.get(key);
21490
+ if (++visited > maxGraphNodes) throw new Error("Ancestor repair: maxGraphNodes exceeded");
21491
+ active.add(key);
21492
+ let inherited = false;
21493
+ for (const relation of schema.relations ?? []) {
21494
+ if (relation.inheritsInactive !== true || relation.type === "many-many") continue;
21495
+ const dependent = relation.type === "many-one" ? relation.from : relation.to;
21496
+ if (!core.endpointIncludes(dependent, model)) continue;
21497
+ const endpoint = relation.type === "many-one" ? relation.to : relation.from;
21498
+ const field = relation.type === "many-one" ? core.relationFkFieldForManyOne(relation) : relation.type === "htree" ? relation.fkField || relation.foreignKey || relation.inverse || "parentId" : core.relationFkFieldForOneMany(relation);
21499
+ const parentId = row[field];
21500
+ if (parentId === null || parentId === void 0 || parentId === "") continue;
21501
+ if (typeof parentId !== "string") throw new Error("Ancestor repair: malformed parent link");
21502
+ 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`);
21503
+ const discriminator = row[resourceField];
21504
+ const inferred = core.resolveEndpointResource(endpoint, parentId, schema);
21505
+ let parentResource = inferred;
21506
+ if (core.endpointList(endpoint).length > 1 && discriminator != null) {
21507
+ if (typeof discriminator !== "string" || !core.endpointIncludes(endpoint, discriminator) || inferred && inferred !== discriminator) {
21508
+ throw new Error("Ancestor repair: invalid parent resource discriminator");
21509
+ }
21510
+ parentResource = discriminator;
21511
+ }
21512
+ if (!parentResource) throw new Error("Ancestor repair: ambiguous parent resource");
21513
+ const parent = await adapter.findOne({
21514
+ model: parentResource,
21515
+ where: [{ field: "id", operator: "eq", value: parentId }],
21516
+ namespace
21517
+ });
21518
+ if (!parent) throw new Error("Ancestor repair: missing parent record");
21519
+ const parentInactive = await visit(parentResource, parent);
21520
+ inherited = inherited || parentInactive;
21521
+ }
21522
+ active.delete(key);
21523
+ const effective = inherited || row.isArchived === true || row.trashedAt != null;
21524
+ resolved.set(key, effective);
21525
+ return root ? inherited : effective;
21526
+ }
21527
+ return visit(resource, record, true);
21528
+ }
21529
+
21530
+ // src/execution/migration/ancestor-inactive.ts
21531
+ var DEFAULT_BATCH_SIZE = 500;
21532
+ function compareCodePoints(a, b) {
21533
+ return a < b ? -1 : a > b ? 1 : 0;
21534
+ }
21535
+ function ancestorInactiveResources(schema) {
21536
+ return [...core.getAncestorInactiveResources(schema.relations)].sort(compareCodePoints);
21537
+ }
21538
+ async function recomputeAncestorInactive(adapter, schema, options) {
21539
+ const { namespace, dryRun = false, logger } = options;
21540
+ const batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
21541
+ const maxGraphNodes = options.maxGraphNodes ?? 1e4;
21542
+ for (const value of [batchSize, maxGraphNodes]) {
21543
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error("Ancestor repair: limits must be positive safe integers");
21544
+ }
21545
+ const resources = ancestorInactiveResources(schema);
21546
+ if (resources.length === 0) return { scanned: 0, updated: 0, skipped: 0, nextCursor: null };
21547
+ let cursor = options.cursor ?? { resource: resources[0], afterId: null };
21548
+ let resourceIndex = resources.indexOf(cursor.resource);
21549
+ if (resourceIndex === -1) {
21550
+ throw new Error(`recomputeAncestorInactive: unknown cursor resource "${cursor.resource}"`);
21551
+ }
21552
+ let scanned = 0;
21553
+ let updated = 0;
21554
+ let skipped = 0;
21555
+ let remaining = batchSize;
21556
+ while (remaining > 0) {
21557
+ const resource = resources[resourceIndex];
21558
+ const requested = remaining;
21559
+ const rows = await adapter.findMany({
21560
+ model: resource,
21561
+ where: cursor.afterId === null ? [] : [{ field: "id", operator: "gt", value: cursor.afterId }],
21562
+ orderBy: [{ field: "id", direction: "asc" }],
21563
+ limit: requested,
21564
+ namespace
21565
+ });
21566
+ for (const row of rows) {
21567
+ const id = row.id;
21568
+ if (typeof id !== "string" || id.length === 0) throw new Error("Ancestor repair: malformed record identifier");
21569
+ scanned += 1;
21570
+ const next = await resolveAuthoritativeAncestorInactive(adapter, schema, resource, row, namespace, maxGraphNodes);
21571
+ const previous = row[core.ANCESTOR_INACTIVE_FIELD];
21572
+ if (previous !== next) {
21573
+ if (dryRun) {
21574
+ updated += 1;
21575
+ } else {
21576
+ const affected = await adapter.updateMany({
21577
+ model: resource,
21578
+ where: [
21579
+ { field: "id", operator: "eq", value: id },
21580
+ {
21581
+ field: core.ANCESTOR_INACTIVE_FIELD,
21582
+ operator: "eq",
21583
+ value: previous ?? null
21584
+ }
21585
+ ],
21586
+ data: { [core.ANCESTOR_INACTIVE_FIELD]: next },
21587
+ namespace
21588
+ });
21589
+ updated += affected > 0 ? 1 : 0;
21590
+ skipped += affected > 0 ? 0 : 1;
21591
+ }
21592
+ }
21593
+ cursor = { resource, afterId: id };
21594
+ }
21595
+ remaining -= rows.length;
21596
+ if (rows.length < requested) {
21597
+ resourceIndex += 1;
21598
+ if (resourceIndex >= resources.length) {
21599
+ logger?.info("datafn.ancestorInactive.recompute.complete", { namespace, scanned, updated, skipped, dryRun });
21600
+ return { scanned, updated, skipped, nextCursor: null };
21601
+ }
21602
+ cursor = { resource: resources[resourceIndex], afterId: null };
21603
+ }
21604
+ }
21605
+ return { scanned, updated, skipped, nextCursor: cursor };
21606
+ }
21607
+ async function recomputeAncestorInactiveAll(adapter, schema, options) {
21608
+ const maxSweeps = options.maxSweeps ?? 32;
21609
+ if (!Number.isSafeInteger(maxSweeps) || maxSweeps < 1) throw new Error("Ancestor repair: maxSweeps must be a positive safe integer");
21610
+ let scanned = 0;
21611
+ let updated = 0;
21612
+ let skipped = 0;
21613
+ let sweeps = 0;
21614
+ let converged = false;
21615
+ while (sweeps < maxSweeps) {
21616
+ sweeps += 1;
21617
+ let sweepUpdated = 0;
21618
+ let sweepSkipped = 0;
21619
+ let cursor = null;
21620
+ do {
21621
+ const result = await recomputeAncestorInactive(adapter, schema, { ...options, cursor });
21622
+ scanned += result.scanned;
21623
+ sweepUpdated += result.updated;
21624
+ sweepSkipped += result.skipped;
21625
+ cursor = result.nextCursor;
21626
+ } while (cursor !== null);
21627
+ updated += sweepUpdated;
21628
+ skipped += sweepSkipped;
21629
+ if (sweepUpdated === 0 && sweepSkipped === 0) {
21630
+ converged = true;
21631
+ break;
21632
+ }
21633
+ if (options.dryRun) break;
21634
+ }
21635
+ if (!converged) {
21636
+ options.logger?.warn("datafn.ancestorInactive.recompute.notConverged", {
21637
+ namespace: options.namespace,
21638
+ sweeps,
21639
+ updated,
21640
+ skipped,
21641
+ dryRun: options.dryRun === true
21642
+ });
21643
+ }
21644
+ return { scanned, updated, skipped, sweeps, converged };
21645
+ }
21646
+
21647
+ Object.defineProperty(exports, "DATAFN_REQUEST_ACTIONS", {
21648
+ enumerable: true,
21649
+ get: function () { return core.DATAFN_REQUEST_ACTIONS; }
21650
+ });
21651
+ Object.defineProperty(exports, "DATAFN_REQUEST_PROTOCOL_VERSION", {
21652
+ enumerable: true,
21653
+ get: function () { return core.DATAFN_REQUEST_PROTOCOL_VERSION; }
21654
+ });
21655
+ Object.defineProperty(exports, "DATAFN_REQUEST_PROTOCOL_VERSIONS", {
21656
+ enumerable: true,
21657
+ get: function () { return core.DATAFN_REQUEST_PROTOCOL_VERSIONS; }
21658
+ });
21659
+ Object.defineProperty(exports, "DATAFN_STRUCTURAL_SELECTOR_POSITIONS", {
21660
+ enumerable: true,
21661
+ get: function () { return core.DATAFN_STRUCTURAL_SELECTOR_POSITIONS; }
21662
+ });
21663
+ Object.defineProperty(exports, "collectStructuralResourceSelectors", {
21664
+ enumerable: true,
21665
+ get: function () { return core.collectStructuralResourceSelectors; }
21666
+ });
21667
+ Object.defineProperty(exports, "extractStructuralResourceSelectors", {
21668
+ enumerable: true,
21669
+ get: function () { return core.extractStructuralResourceSelectors; }
21670
+ });
21671
+ Object.defineProperty(exports, "isDatafnRequestAction", {
21672
+ enumerable: true,
21673
+ get: function () { return core.isDatafnRequestAction; }
21674
+ });
21675
+ Object.defineProperty(exports, "parseDatafnRequest", {
21676
+ enumerable: true,
21677
+ get: function () { return core.parseDatafnRequest; }
21678
+ });
20434
21679
  exports.AtomicSequenceStore = AtomicSequenceStore;
20435
21680
  exports.ChainedSequenceStore = ChainedSequenceStore;
20436
21681
  exports.DATAFN_MULTI_REGION_CAPABILITY = DATAFN_MULTI_REGION_CAPABILITY;
@@ -20438,26 +21683,53 @@ exports.DATAFN_ROUTING_ASSERTION_HEADER = DATAFN_ROUTING_ASSERTION_HEADER;
20438
21683
  exports.DATAFN_ROUTING_INTERNAL_HEADERS = DATAFN_ROUTING_INTERNAL_HEADERS;
20439
21684
  exports.DatabaseSequenceStore = DatabaseSequenceStore;
20440
21685
  exports.DatafnExecutorError = DatafnExecutorError;
21686
+ exports.DatafnNamespaceStorageError = DatafnNamespaceStorageError;
20441
21687
  exports.DatafnPublicLinkInputError = DatafnPublicLinkInputError;
20442
21688
  exports.DatafnRoutingError = DatafnRoutingError;
21689
+ exports.POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL = POSTGRES_NAMESPACE_STORAGE_CATALOG_SQL;
21690
+ exports.POSTGRES_NAMESPACE_STORAGE_INDEX_SQL = POSTGRES_NAMESPACE_STORAGE_INDEX_SQL;
21691
+ exports.ancestorInactiveResources = ancestorInactiveResources;
21692
+ exports.assertInternalNamespaceStorageMetadataComplete = assertInternalNamespaceStorageMetadataComplete;
20443
21693
  exports.claimDatafnNamespacePlacement = claimDatafnNamespacePlacement;
21694
+ exports.composeNamespaceStoragePlan = composeNamespaceStoragePlan;
20444
21695
  exports.createConditionalKvDatafnPlacementDirectory = createConditionalKvDatafnPlacementDirectory;
21696
+ exports.createDatafnEd25519RouteTicketSigner = createDatafnEd25519RouteTicketSigner;
21697
+ exports.createDatafnEd25519RouteTicketVerifier = createDatafnEd25519RouteTicketVerifier;
20445
21698
  exports.createDatafnGatewayRouter = createDatafnGatewayRouter;
21699
+ exports.createDatafnHmacRouteTickets = createDatafnHmacRouteTickets;
20446
21700
  exports.createDatafnHmacRoutingAssertions = createDatafnHmacRoutingAssertions;
20447
21701
  exports.createDatafnMultiRegionPlugin = createDatafnMultiRegionPlugin;
20448
21702
  exports.createDatafnPublicLinksPlugin = createDatafnPublicLinksPlugin;
21703
+ exports.createDatafnRouteBootstrap = createDatafnRouteBootstrap;
20449
21704
  exports.createDatafnServer = createDatafnServer;
20450
21705
  exports.createMemoryDatafnPlacementDirectory = createMemoryDatafnPlacementDirectory;
20451
21706
  exports.createMemoryDatafnRoutingReplayStore = createMemoryDatafnRoutingReplayStore;
20452
21707
  exports.createSequenceStore = createSequenceStore;
20453
21708
  exports.datafn = datafn;
20454
21709
  exports.datafnMultiRegionPlugin = datafnMultiRegionPlugin;
21710
+ exports.drainNamespacePermissionDirectoryOutbox = drainNamespacePermissionDirectoryOutbox;
21711
+ exports.drainNamespaceStorage = drainNamespaceStorage;
21712
+ exports.inspectPostgresNamespaceStorage = inspectPostgresNamespaceStorage;
20455
21713
  exports.migrateDatafnNamespace = migrateDatafnNamespace;
21714
+ exports.namespacedInternalTableRoles = namespacedInternalTableRoles;
21715
+ exports.quotePostgresIdentifier = quotePostgresIdentifier;
21716
+ exports.rankDatafnPlacementRegions = rankDatafnPlacementRegions;
21717
+ exports.readDatafnCloudflarePlacementLocation = readDatafnCloudflarePlacementLocation;
20456
21718
  exports.readDatafnPublicLinkToken = readDatafnPublicLinkToken;
21719
+ exports.readDatafnRouteTicket = readDatafnRouteTicket;
21720
+ exports.recomputeAncestorInactive = recomputeAncestorInactive;
21721
+ exports.recomputeAncestorInactiveAll = recomputeAncestorInactiveAll;
20457
21722
  exports.resolveDatafnPublicLink = resolveDatafnPublicLink;
21723
+ exports.resolveNamespaceStoragePlan = resolveNamespaceStoragePlan;
21724
+ exports.routeTicketError = routeTicketError;
21725
+ exports.selectDatafnPlacementRegion = selectDatafnPlacementRegion;
21726
+ exports.selectNamespaceStorageEntries = selectNamespaceStorageEntries;
20458
21727
  exports.validateDatafnPlacement = validateDatafnPlacement;
21728
+ exports.validateDatafnRouteTicket = validateDatafnRouteTicket;
20459
21729
  exports.validateDatafnRoutingBodyLimit = validateDatafnRoutingBodyLimit;
21730
+ exports.verifyDatafnRegionalTicketIdentity = verifyDatafnRegionalTicketIdentity;
20460
21731
  exports.withDatafnPublicLinksSchema = withDatafnPublicLinksSchema;
21732
+ exports.withDatafnRegionalCors = withDatafnRegionalCors;
20461
21733
  exports.withDatafnRoutingAssertion = withDatafnRoutingAssertion;
20462
21734
  //# sourceMappingURL=index.cjs.map
20463
21735
  //# sourceMappingURL=index.cjs.map