@datafn/server 0.0.2 → 0.0.3

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.js CHANGED
@@ -52,6 +52,65 @@ async function ensureInternalTable(adapter, tableName) {
52
52
  await adapter.internal.ensureTable(tableName, columns);
53
53
  }
54
54
 
55
+ // src/execution/sync/namespace-lock.ts
56
+ var AsyncMutex = class {
57
+ constructor() {
58
+ this.tail = Promise.resolve();
59
+ this.pendingCount = 0;
60
+ }
61
+ async runExclusive(task) {
62
+ this.pendingCount += 1;
63
+ const previous = this.tail;
64
+ let release;
65
+ this.tail = new Promise((resolve) => {
66
+ release = resolve;
67
+ });
68
+ await previous.catch(() => void 0);
69
+ try {
70
+ return await task();
71
+ } finally {
72
+ this.pendingCount -= 1;
73
+ release();
74
+ }
75
+ }
76
+ isIdle() {
77
+ return this.pendingCount === 0;
78
+ }
79
+ };
80
+ var adapterNamespaceMutexes = /* @__PURE__ */ new WeakMap();
81
+ function getNamespaceMutexes(adapter) {
82
+ let namespaceMutexes = adapterNamespaceMutexes.get(adapter);
83
+ if (!namespaceMutexes) {
84
+ namespaceMutexes = /* @__PURE__ */ new Map();
85
+ adapterNamespaceMutexes.set(adapter, namespaceMutexes);
86
+ }
87
+ return namespaceMutexes;
88
+ }
89
+ function getMutex(namespaceMutexes, namespace) {
90
+ let mutex = namespaceMutexes.get(namespace);
91
+ if (!mutex) {
92
+ mutex = new AsyncMutex();
93
+ namespaceMutexes.set(namespace, mutex);
94
+ }
95
+ return mutex;
96
+ }
97
+ function withAdapterNamespaceLock(adapter, namespace, task) {
98
+ const namespaceMutexes = getNamespaceMutexes(adapter);
99
+ const mutex = getMutex(namespaceMutexes, namespace);
100
+ return mutex.runExclusive(task).finally(() => {
101
+ if (!mutex.isIdle()) {
102
+ return;
103
+ }
104
+ if (namespaceMutexes.get(namespace) !== mutex) {
105
+ return;
106
+ }
107
+ namespaceMutexes.delete(namespace);
108
+ if (namespaceMutexes.size === 0) {
109
+ adapterNamespaceMutexes.delete(adapter);
110
+ }
111
+ });
112
+ }
113
+
55
114
  // src/execution/sync/sequence-store.ts
56
115
  var RedisSequenceStore = class {
57
116
  constructor(redis) {
@@ -127,51 +186,9 @@ var DatabaseSequenceStore = class {
127
186
  await ensureInternalTable(this.db, "__datafn_meta");
128
187
  this.ensured = true;
129
188
  }
189
+ const needed = minSeq + 1;
130
190
  try {
131
- const meta = await this.db.internal.findOne("__datafn_meta", [
132
- { field: "namespace", op: "eq", value: namespace }
133
- ]);
134
- const needed = minSeq + 1;
135
- if (!meta) {
136
- try {
137
- await this.db.internal.create("__datafn_meta", {
138
- id: `meta:${namespace}`,
139
- namespace,
140
- next_server_seq: needed
141
- });
142
- } catch {
143
- }
144
- } else {
145
- const current = meta.next_server_seq || 1;
146
- if (current < needed) {
147
- await this.db.internal.update(
148
- "__datafn_meta",
149
- [{ field: "namespace", op: "eq", value: namespace }],
150
- { next_server_seq: needed }
151
- );
152
- }
153
- }
154
- } catch (error) {
155
- this.logger?.warn("Failed to ensureMinSeq during failover", {
156
- error: String(error),
157
- operation: "ensureMinSeq"
158
- });
159
- }
160
- }
161
- async getNext(namespace) {
162
- return (await this.getNextN(namespace, 1))[0];
163
- }
164
- async getNextN(namespace, count) {
165
- if (!Number.isInteger(count) || count < 1 || count > 1e3) {
166
- throw new Error("count must be a positive integer between 1 and 1000");
167
- }
168
- if (!this.ensured) {
169
- await ensureInternalTable(this.db, "__datafn_meta");
170
- this.ensured = true;
171
- }
172
- const MAX_RETRIES = 10;
173
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
174
- try {
191
+ await withAdapterNamespaceLock(this.db, namespace, async () => {
175
192
  const meta = await this.db.internal.findOne("__datafn_meta", [
176
193
  { field: "namespace", op: "eq", value: namespace }
177
194
  ]);
@@ -180,45 +197,116 @@ var DatabaseSequenceStore = class {
180
197
  await this.db.internal.create("__datafn_meta", {
181
198
  id: `meta:${namespace}`,
182
199
  namespace,
183
- next_server_seq: 1 + count
200
+ next_server_seq: needed
184
201
  });
185
- return Array.from({ length: count }, (_, i) => 1 + i);
186
- } catch (error) {
187
- this.logger?.warn("Sequence allocation create retry", { attempt, error: String(error), operation: "seq-create" });
188
- continue;
202
+ } catch {
203
+ const currentMeta = await this.db.internal.findOne("__datafn_meta", [
204
+ { field: "namespace", op: "eq", value: namespace }
205
+ ]);
206
+ const current = currentMeta?.next_server_seq || 1;
207
+ if (current < needed) {
208
+ await this.db.internal.update(
209
+ "__datafn_meta",
210
+ [
211
+ { field: "namespace", op: "eq", value: namespace },
212
+ { field: "next_server_seq", op: "eq", value: current }
213
+ ],
214
+ { next_server_seq: needed }
215
+ );
216
+ }
189
217
  }
190
218
  } else {
191
- const currentSeq = meta.next_server_seq || 1;
192
- try {
193
- const affected = await this.db.internal.update(
219
+ const current = meta.next_server_seq || 1;
220
+ if (current < needed) {
221
+ await this.db.internal.update(
194
222
  "__datafn_meta",
195
223
  [
196
224
  { field: "namespace", op: "eq", value: namespace },
197
- { field: "next_server_seq", op: "eq", value: currentSeq }
225
+ { field: "next_server_seq", op: "eq", value: current }
198
226
  ],
199
- { next_server_seq: currentSeq + count }
227
+ { next_server_seq: needed }
200
228
  );
201
- if (affected === 0) {
229
+ }
230
+ }
231
+ });
232
+ } catch (error) {
233
+ this.logger?.warn("Failed to ensureMinSeq during failover", {
234
+ error: String(error),
235
+ operation: "ensureMinSeq"
236
+ });
237
+ }
238
+ }
239
+ async getNext(namespace) {
240
+ return (await this.getNextN(namespace, 1))[0];
241
+ }
242
+ async getNextN(namespace, count) {
243
+ if (!Number.isInteger(count) || count < 1 || count > 1e3) {
244
+ throw new Error("count must be a positive integer between 1 and 1000");
245
+ }
246
+ return await withAdapterNamespaceLock(this.db, namespace, async () => {
247
+ if (!this.ensured) {
248
+ await ensureInternalTable(this.db, "__datafn_meta");
249
+ this.ensured = true;
250
+ }
251
+ const MAX_RETRIES = 10;
252
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
253
+ try {
254
+ const meta = await this.db.internal.findOne("__datafn_meta", [
255
+ { field: "namespace", op: "eq", value: namespace }
256
+ ]);
257
+ if (!meta) {
258
+ try {
259
+ await this.db.internal.create("__datafn_meta", {
260
+ id: `meta:${namespace}`,
261
+ namespace,
262
+ next_server_seq: 1 + count
263
+ });
264
+ return Array.from({ length: count }, (_, i) => 1 + i);
265
+ } catch (error) {
266
+ this.logger?.warn("Sequence allocation create retry", {
267
+ attempt,
268
+ error: String(error),
269
+ operation: "seq-create"
270
+ });
271
+ continue;
272
+ }
273
+ } else {
274
+ const currentSeq = meta.next_server_seq || 1;
275
+ try {
276
+ const affected = await this.db.internal.update(
277
+ "__datafn_meta",
278
+ [
279
+ { field: "namespace", op: "eq", value: namespace },
280
+ { field: "next_server_seq", op: "eq", value: currentSeq }
281
+ ],
282
+ { next_server_seq: currentSeq + count }
283
+ );
284
+ if (affected === 0) {
285
+ continue;
286
+ }
287
+ return Array.from({ length: count }, (_, i) => currentSeq + i);
288
+ } catch (error) {
289
+ this.logger?.warn("Sequence allocation CAS retry", {
290
+ attempt,
291
+ error: String(error),
292
+ operation: "seq-cas"
293
+ });
202
294
  continue;
203
295
  }
204
- return Array.from({ length: count }, (_, i) => currentSeq + i);
205
- } catch (error) {
206
- this.logger?.warn("Sequence allocation CAS retry", { attempt, error: String(error), operation: "seq-cas" });
207
- continue;
208
296
  }
209
- }
210
- } catch (error) {
211
- if (attempt === MAX_RETRIES - 1) {
212
- this.logger?.error("Failed to get next serverSeq after max retries", {
213
- error: String(error),
214
- operation: "getNextN",
215
- resource: "__datafn_meta"
216
- });
217
- throw new Error("INTERNAL: Failed to allocate serverSeq after maximum retries");
297
+ } catch (error) {
298
+ if (attempt === MAX_RETRIES - 1) {
299
+ this.logger?.error("Failed to get next serverSeq after max retries", {
300
+ error: String(error),
301
+ operation: "getNextN",
302
+ resource: "__datafn_meta"
303
+ });
304
+ throw new Error("INTERNAL: Failed to allocate serverSeq after maximum retries");
305
+ }
218
306
  }
219
307
  }
220
- }
221
- throw new Error("INTERNAL: Failed to allocate serverSeq after maximum retries");
308
+ throw new Error("INTERNAL: Failed to allocate serverSeq after maximum retries");
309
+ });
222
310
  }
223
311
  async getCurrent(namespace) {
224
312
  if (!this.ensured) {
@@ -413,8 +501,11 @@ function createStatusHandler(validatedSchema, limits, getServerTime = () => Date
413
501
  "dfql.query",
414
502
  "dfql.mutation",
415
503
  "dfql.transact",
416
- "dfql.sync",
417
- "dfql.seed"
504
+ "sync.seed",
505
+ "sync.clone",
506
+ "sync.pull",
507
+ "sync.push",
508
+ "sync.reconcile"
418
509
  ],
419
510
  limits,
420
511
  // SRV-008: Round to nearest minute to avoid fingerprinting via exact timestamps
@@ -618,6 +709,9 @@ var VALID_OPERATIONS = /* @__PURE__ */ new Set([
618
709
  var RECORD_REQUIRED_OPERATIONS = /* @__PURE__ */ new Set(["insert", "merge", "replace"]);
619
710
  var DFQL_SHARE_SCOPE_INVALID_CODE = "DFQL_SHARE_SCOPE_INVALID";
620
711
  var DFQL_PRINCIPAL_INVALID_CODE = "DFQL_PRINCIPAL_INVALID";
712
+ function isShareableCapability(entry) {
713
+ return typeof entry === "object" && entry !== null && "shareable" in entry;
714
+ }
621
715
  function normalizeNonEmptyString(value) {
622
716
  if (typeof value !== "string") {
623
717
  return null;
@@ -687,9 +781,7 @@ function validateMutation(mutation, index, basePath = "$", opts) {
687
781
  const hasArchivableCapability3 = resolvedCapabilities.some(
688
782
  (capability) => capability === "archivable"
689
783
  );
690
- const shareableCapability = resolvedCapabilities.find(
691
- (capability) => typeof capability === "object" && capability !== null && "shareable" in capability
692
- );
784
+ const shareableCapability = resolvedCapabilities.find(isShareableCapability);
693
785
  const isShareOperation = m.operation === "share" || m.operation === "unshare";
694
786
  if ((m.operation === "trash" || m.operation === "restore") && !hasTrashCapability3) {
695
787
  return vErr(
@@ -816,7 +908,7 @@ function validateMutation(mutation, index, basePath = "$", opts) {
816
908
  );
817
909
  }
818
910
  const allowedLevels = shareableCapability?.shareable.levels ?? [];
819
- if (!allowedLevels.includes(shareWith.level)) {
911
+ if (!allowedLevels.some((candidate) => candidate === shareWith.level)) {
820
912
  return vErr(
821
913
  "DFQL_INVALID",
822
914
  `Invalid DFQL: shareWith.level must be one of [${allowedLevels.join(", ")}]`,
@@ -883,7 +975,7 @@ function validateMutation(mutation, index, basePath = "$", opts) {
883
975
  const resource2 = resourceResult.result;
884
976
  const record2 = m.record;
885
977
  for (const field of resource2.fields) {
886
- if (field.required && !field.default && field.name !== "id" && !field.readonly) {
978
+ if (field.required && field.default === void 0 && field.name !== "id" && !field.readonly) {
887
979
  if (!(field.name in record2) || record2[field.name] === null || record2[field.name] === void 0) {
888
980
  return vErr(
889
981
  "DFQL_INVALID",
@@ -1026,7 +1118,7 @@ function validateRelationDepth(token, maxDepth) {
1026
1118
  // src/validation/query.ts
1027
1119
  function validateQuery(query, index, basePath = "$", limits) {
1028
1120
  if (typeof query !== "object" || query === null || Array.isArray(query)) {
1029
- return vErr("DFQL_INVALID", "Invalid DFQL: expected object or array", basePath);
1121
+ return vErr("DFQL_INVALID", "Invalid DFQL: expected object", basePath);
1030
1122
  }
1031
1123
  const q = query;
1032
1124
  const queryPollutionCheck = checkPrototypePollution(q);
@@ -1077,7 +1169,7 @@ function validateQuery(query, index, basePath = "$", limits) {
1077
1169
  }
1078
1170
  if (q.cursor && typeof q.cursor === "object") {
1079
1171
  const cursor = q.cursor;
1080
- const hasCursor = cursor.after || cursor.before;
1172
+ const hasCursor = cursor.after !== void 0 || cursor.before !== void 0;
1081
1173
  if (hasCursor) {
1082
1174
  if (!q.sort) {
1083
1175
  q.sort = ["id:asc"];
@@ -1339,10 +1431,10 @@ function validateSelectTokens(select, resourceName, resource, index, fieldNames,
1339
1431
  return vOk(void 0);
1340
1432
  }
1341
1433
  function validateCursor(cursor, sort) {
1342
- if (cursor.after && (typeof cursor.after !== "object" || cursor.after === null)) {
1434
+ if (cursor.after !== void 0 && (typeof cursor.after !== "object" || cursor.after === null)) {
1343
1435
  return vErr("DFQL_INVALID", "Invalid DFQL: cursor.after must be object", "cursor.after");
1344
1436
  }
1345
- if (cursor.before && (typeof cursor.before !== "object" || cursor.before === null)) {
1437
+ if (cursor.before !== void 0 && (typeof cursor.before !== "object" || cursor.before === null)) {
1346
1438
  return vErr("DFQL_INVALID", "Invalid DFQL: cursor.before must be object", "cursor.before");
1347
1439
  }
1348
1440
  return vOk(void 0);
@@ -1373,6 +1465,9 @@ function validateGroupBy(q, fieldNames, relationNames) {
1373
1465
  if (q.select && Array.isArray(q.select)) {
1374
1466
  for (let i = 0; i < q.select.length; i++) {
1375
1467
  const token = q.select[i];
1468
+ if (typeof token !== "string") {
1469
+ continue;
1470
+ }
1376
1471
  if (token.includes(".*") || token.includes(".**") || token.endsWith(".#")) {
1377
1472
  return vErr(
1378
1473
  "DFQL_UNSUPPORTED",
@@ -2105,6 +2200,9 @@ function resolveDualReadAccessDecision(params) {
2105
2200
  }
2106
2201
 
2107
2202
  // src/validation/authz.ts
2203
+ function isShareableCapability2(entry) {
2204
+ return typeof entry === "object" && entry !== null && "shareable" in entry;
2205
+ }
2108
2206
  function getCapabilityFieldSets(schema, resource) {
2109
2207
  const resolvedCapabilities = resolveCapabilities(
2110
2208
  schema.capabilities,
@@ -2418,9 +2516,7 @@ function canonicalizePrincipalFromUserId2(value) {
2418
2516
  }
2419
2517
  function getShareableCapability(resource, schema) {
2420
2518
  const resolved = resolveCapabilities(schema.capabilities, resource.capabilities);
2421
- return resolved.find(
2422
- (entry) => typeof entry === "object" && entry !== null && "shareable" in entry
2423
- );
2519
+ return resolved.find(isShareableCapability2);
2424
2520
  }
2425
2521
  function isPrivateShareableResource(schema, resourceName) {
2426
2522
  const resource = schema.resources.find((r) => r.name === resourceName);
@@ -2508,6 +2604,76 @@ async function resolveAccessLevelFromV2(db, resource, recordId, actorId, namespa
2508
2604
  }
2509
2605
  return null;
2510
2606
  }
2607
+ async function hasResourceScopeOwnerAccess(db, resource, actorId, namespace) {
2608
+ if (!actorId) {
2609
+ return false;
2610
+ }
2611
+ const principalResult = await resolveEffectivePrincipals({
2612
+ namespace,
2613
+ actorId,
2614
+ store: {
2615
+ getDirectMemberships: async ({ namespace: actorNamespace, actorId: actor }) => {
2616
+ const rows = await db.findMany({
2617
+ model: PRINCIPAL_MEMBERSHIPS_TABLE,
2618
+ where: [{ field: "actorId", operator: "eq", value: actor }],
2619
+ namespace: actorNamespace
2620
+ });
2621
+ return rows.map((row) => row).filter((row) => isGrantActive2(row)).map(
2622
+ (row) => typeof row.principalId === "string" ? row.principalId : ""
2623
+ ).filter((principalId) => principalId.length > 0);
2624
+ },
2625
+ getHierarchyParents: async ({ namespace: actorNamespace, principalIds }) => {
2626
+ const edges = [];
2627
+ for (const principalId of principalIds) {
2628
+ const rows = await db.findMany({
2629
+ model: PRINCIPAL_HIERARCHY_TABLE,
2630
+ where: [{ field: "principalId", operator: "eq", value: principalId }],
2631
+ namespace: actorNamespace
2632
+ });
2633
+ for (const row of rows) {
2634
+ const edge = row;
2635
+ if (!isGrantActive2(edge)) {
2636
+ continue;
2637
+ }
2638
+ if (typeof edge.principalId === "string" && typeof edge.parentPrincipalId === "string") {
2639
+ edges.push({
2640
+ principalId: edge.principalId,
2641
+ parentPrincipalId: edge.parentPrincipalId
2642
+ });
2643
+ }
2644
+ }
2645
+ }
2646
+ return edges;
2647
+ }
2648
+ }
2649
+ });
2650
+ if (principalResult.effectivePrincipals.includes(namespace)) {
2651
+ return true;
2652
+ }
2653
+ for (const principalId of principalResult.effectivePrincipals) {
2654
+ const rows = await db.findMany({
2655
+ model: GLOBAL_PERMISSIONS_TABLE,
2656
+ where: [
2657
+ { field: "resourceType", operator: "eq", value: resource },
2658
+ { field: "resourceNs", operator: "eq", value: namespace },
2659
+ { field: "principalId", operator: "eq", value: principalId },
2660
+ { field: "level", operator: "eq", value: "owner" }
2661
+ ],
2662
+ namespace
2663
+ });
2664
+ const hasScopeOwnerGrant = rows.some((row) => {
2665
+ const grant = row;
2666
+ if (!isGrantActive2(grant)) {
2667
+ return false;
2668
+ }
2669
+ return grant.grantKind === "scope" || grant.resourceId === null;
2670
+ });
2671
+ if (hasScopeOwnerGrant) {
2672
+ return true;
2673
+ }
2674
+ }
2675
+ return false;
2676
+ }
2511
2677
  async function resolveAccessLevel(db, schema, resource, recordId, actorId, namespace) {
2512
2678
  if (!actorId) {
2513
2679
  return null;
@@ -2583,7 +2749,23 @@ async function validateShareableOperationAccess(input) {
2583
2749
  path: "operation"
2584
2750
  };
2585
2751
  }
2586
- if (input.operation === "insert" || input.operation === "share" || input.operation === "unshare") {
2752
+ if (input.operation === "insert") {
2753
+ return { ok: true };
2754
+ }
2755
+ if ((input.operation === "share" || input.operation === "unshare") && (typeof input.id !== "string" || input.id.length === 0)) {
2756
+ if (!await hasResourceScopeOwnerAccess(
2757
+ input.db,
2758
+ input.resource,
2759
+ input.actorId,
2760
+ input.namespace
2761
+ )) {
2762
+ return {
2763
+ ok: false,
2764
+ code: "FORBIDDEN",
2765
+ message: "Authorization denied",
2766
+ path: "operation"
2767
+ };
2768
+ }
2587
2769
  return { ok: true };
2588
2770
  }
2589
2771
  if (typeof input.id !== "string" || input.id.length === 0) {
@@ -2620,6 +2802,7 @@ async function validateShareableOperationAccess(input) {
2620
2802
  async function runBounded(tasks, concurrency) {
2621
2803
  const results = new Array(tasks.length);
2622
2804
  let nextIndex = 0;
2805
+ const effectiveConcurrency = tasks.length === 0 ? 0 : Math.max(1, concurrency);
2623
2806
  async function worker() {
2624
2807
  while (nextIndex < tasks.length) {
2625
2808
  const idx = nextIndex++;
@@ -2627,7 +2810,7 @@ async function runBounded(tasks, concurrency) {
2627
2810
  }
2628
2811
  }
2629
2812
  const workers = Array.from(
2630
- { length: Math.min(concurrency, tasks.length) },
2813
+ { length: Math.min(effectiveConcurrency, tasks.length) },
2631
2814
  () => worker()
2632
2815
  );
2633
2816
  await Promise.all(workers);
@@ -2772,7 +2955,7 @@ function validateSortForCursor(sortTerms) {
2772
2955
  // src/execution/query/pagination.ts
2773
2956
  function applyLimitOffset(records, limit, offset) {
2774
2957
  const start = offset || 0;
2775
- const end = limit ? start + limit : void 0;
2958
+ const end = limit == null ? void 0 : start + limit;
2776
2959
  return records.slice(start, end);
2777
2960
  }
2778
2961
  function computeNextCursor(results, sortTerms, limit) {
@@ -2861,7 +3044,7 @@ function isNestedSelectToken(token) {
2861
3044
  }
2862
3045
  if (parts.length === 2) {
2863
3046
  const child = parts[1];
2864
- return child !== "*" && child !== "#" && child !== "*#";
3047
+ return child !== "*" && child !== "**" && child !== "#" && child !== "*#";
2865
3048
  }
2866
3049
  return true;
2867
3050
  }
@@ -3625,6 +3808,7 @@ function classifyQuery(query, schema) {
3625
3808
  }
3626
3809
  function hasInMemoryFilterPatterns(filters) {
3627
3810
  for (const [key, value] of Object.entries(filters)) {
3811
+ if (key === "$or") return true;
3628
3812
  if (key.includes(".")) return true;
3629
3813
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
3630
3814
  const ops = value;
@@ -4367,6 +4551,9 @@ var REQUIRED_ACL_INDEXES = [
4367
4551
  "idx_perm_principal",
4368
4552
  "idx_perm_resource_ns_principal"
4369
4553
  ];
4554
+ function isShareableCapability3(entry) {
4555
+ return typeof entry === "object" && entry !== null && "shareable" in entry;
4556
+ }
4370
4557
  function normalizeIndexNames(indexes) {
4371
4558
  const normalized = /* @__PURE__ */ new Set();
4372
4559
  for (const index of indexes) {
@@ -4439,15 +4626,15 @@ function injectCapabilityAutoFilters(query, schema) {
4439
4626
  if (resolvedCapabilities.some((capability) => capability === "archivable") && metadata.includeArchived !== true) {
4440
4627
  autoFilters.push({ isArchived: { $ne: true } });
4441
4628
  }
4442
- const shareableCapability = resolvedCapabilities.find(
4443
- (capability) => typeof capability === "object" && capability !== null && "shareable" in capability
4444
- );
4629
+ const shareableCapability = resolvedCapabilities.find(isShareableCapability3);
4445
4630
  if (shareableCapability?.shareable.default === "private" && metadata.accessMode !== "sharedWithMe") {
4446
- const accessIds = Array.isArray(metadata.shareableAccessIds) ? metadata.shareableAccessIds : [];
4447
- if (accessIds.length === 0) {
4448
- autoFilters.push({ id: { $in: ["__datafn_no_access__"] } });
4449
- } else {
4450
- autoFilters.push({ id: { $in: accessIds } });
4631
+ if (metadata.hasShareableScopeAccess === true) ; else {
4632
+ const accessIds = Array.isArray(metadata.shareableAccessIds) ? metadata.shareableAccessIds : [];
4633
+ if (accessIds.length === 0) {
4634
+ autoFilters.push({ id: { $in: ["__datafn_no_access__"] } });
4635
+ } else {
4636
+ autoFilters.push({ id: { $in: accessIds } });
4637
+ }
4451
4638
  }
4452
4639
  }
4453
4640
  if (autoFilters.length === 0) {
@@ -4604,21 +4791,20 @@ function projectFieldsPushdown(record, resource, schema, select, omit) {
4604
4791
  baseFields.add(capabilityField.name);
4605
4792
  }
4606
4793
  for (const f of resourceSchema.fields) baseFields.add(f.name);
4607
- let result;
4608
- if (!select || select.length === 0) {
4609
- result = { id: record.id };
4610
- for (const f of resourceSchema.fields) {
4611
- if (record[f.name] !== void 0) {
4612
- result[f.name] = record[f.name];
4794
+ const assignBaseFields = (target) => {
4795
+ for (const field of baseFields) {
4796
+ if (record[field] !== void 0) {
4797
+ target[field] = record[field];
4613
4798
  }
4614
4799
  }
4800
+ };
4801
+ let result;
4802
+ if (!select || select.length === 0) {
4803
+ result = {};
4804
+ assignBaseFields(result);
4615
4805
  } else if (select.includes("*")) {
4616
- result = { id: record.id };
4617
- for (const f of resourceSchema.fields) {
4618
- if (record[f.name] !== void 0) {
4619
- result[f.name] = record[f.name];
4620
- }
4621
- }
4806
+ result = {};
4807
+ assignBaseFields(result);
4622
4808
  for (const token of select) {
4623
4809
  if (token !== "*" && baseFields.has(token) && !(token in result)) {
4624
4810
  result[token] = record[token];
@@ -5015,6 +5201,12 @@ async function executeSearchQuery(query, schema, store, searchProvider, resolveC
5015
5201
  const chunkQuery = {
5016
5202
  ...query,
5017
5203
  filters: mergedFilters,
5204
+ select: ["id"],
5205
+ omit: void 0,
5206
+ groupBy: void 0,
5207
+ aggregations: void 0,
5208
+ having: void 0,
5209
+ count: void 0,
5018
5210
  limit: void 0,
5019
5211
  offset: void 0,
5020
5212
  sort: void 0,
@@ -5199,7 +5391,7 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
5199
5391
  return void 0;
5200
5392
  }
5201
5393
  if (!actorId) {
5202
- return [];
5394
+ return { shareableAccessIds: [] };
5203
5395
  }
5204
5396
  const ids = /* @__PURE__ */ new Set();
5205
5397
  const readMode = getSpv2MigrationRuntimeConfig().readMode;
@@ -5260,19 +5452,15 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
5260
5452
  }
5261
5453
  }
5262
5454
  if (hasScopeGrant) {
5263
- const scopedRows = await db.findMany({
5264
- model: resource,
5265
- where: [],
5266
- namespace
5267
- });
5268
- for (const row of scopedRows) {
5269
- if (typeof row.id === "string") {
5270
- ids.add(row.id);
5271
- }
5272
- }
5455
+ return {
5456
+ shareableAccessIds: [...ids].sort((a, b) => a.localeCompare(b)),
5457
+ hasShareableScopeAccess: true
5458
+ };
5273
5459
  }
5274
5460
  }
5275
- return [...ids].sort((a, b) => a.localeCompare(b));
5461
+ return {
5462
+ shareableAccessIds: [...ids].sort((a, b) => a.localeCompare(b))
5463
+ };
5276
5464
  };
5277
5465
  const mergeFilters = (existingFilters, nextFilter) => {
5278
5466
  if (!existingFilters || Object.keys(existingFilters).length === 0) {
@@ -5670,12 +5858,12 @@ function createQueryHandler(validatedSchema, maxLimit, extractNamespace, extract
5670
5858
  String(query.resource),
5671
5859
  namespace,
5672
5860
  actorId
5673
- ).then((shareableAccessIds) => {
5861
+ ).then((shareableAccess) => {
5674
5862
  const queryWithMetadata = {
5675
5863
  ...query,
5676
5864
  metadata: {
5677
5865
  ...metadata ?? {},
5678
- ...shareableAccessIds !== void 0 ? { shareableAccessIds } : {}
5866
+ ...shareableAccess ?? {}
5679
5867
  }
5680
5868
  };
5681
5869
  const queryWithAutoFilters = injectCapabilityAutoFilters(
@@ -5840,66 +6028,72 @@ var ChangeTrackingService = class _ChangeTrackingService {
5840
6028
  return (await this.getNextServerSeqBatchFromDb(1))[0];
5841
6029
  }
5842
6030
  async getNextServerSeqBatchFromDb(count) {
5843
- if (!this.metaEnsured) {
5844
- await ensureInternalTable(this.db, "__datafn_meta");
5845
- this.metaEnsured = true;
5846
- }
5847
- const MAX_RETRIES = 10;
5848
- for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
5849
- if (attempt > 0) {
5850
- await sleep(10 * Math.pow(2, attempt - 1));
6031
+ return await withAdapterNamespaceLock(this.db, this.namespace, async () => {
6032
+ if (!this.metaEnsured) {
6033
+ await ensureInternalTable(this.db, "__datafn_meta");
6034
+ this.metaEnsured = true;
5851
6035
  }
5852
- try {
5853
- const meta = await this.db.internal.findOne("__datafn_meta", [
5854
- { field: "namespace", op: "eq", value: this.namespace }
5855
- ]);
5856
- if (!meta) {
5857
- try {
5858
- await this.db.internal.create("__datafn_meta", {
5859
- id: `meta:${this.namespace}`,
5860
- namespace: this.namespace,
5861
- next_server_seq: 1 + count
5862
- });
5863
- return Array.from({ length: count }, (_, i) => 1 + i);
5864
- } catch (createError) {
5865
- continue;
5866
- }
5867
- } else {
5868
- const currentSeq = meta.next_server_seq || 1;
5869
- try {
5870
- const affected = await this.db.internal.update(
5871
- "__datafn_meta",
5872
- [
5873
- { field: "namespace", op: "eq", value: this.namespace },
5874
- { field: "next_server_seq", op: "eq", value: currentSeq }
5875
- ],
5876
- { next_server_seq: currentSeq + count }
5877
- );
5878
- if (affected === 0) {
6036
+ const MAX_RETRIES = 10;
6037
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
6038
+ if (attempt > 0) {
6039
+ await sleep(10 * Math.pow(2, attempt - 1));
6040
+ }
6041
+ try {
6042
+ const meta = await this.db.internal.findOne("__datafn_meta", [
6043
+ { field: "namespace", op: "eq", value: this.namespace }
6044
+ ]);
6045
+ if (!meta) {
6046
+ try {
6047
+ await this.db.internal.create("__datafn_meta", {
6048
+ id: `meta:${this.namespace}`,
6049
+ namespace: this.namespace,
6050
+ next_server_seq: 1 + count
6051
+ });
6052
+ return Array.from({ length: count }, (_, i) => 1 + i);
6053
+ } catch (createError) {
6054
+ continue;
6055
+ }
6056
+ } else {
6057
+ const currentSeq = meta.next_server_seq || 1;
6058
+ try {
6059
+ const affected = await this.db.internal.update(
6060
+ "__datafn_meta",
6061
+ [
6062
+ { field: "namespace", op: "eq", value: this.namespace },
6063
+ { field: "next_server_seq", op: "eq", value: currentSeq }
6064
+ ],
6065
+ { next_server_seq: currentSeq + count }
6066
+ );
6067
+ if (affected === 0) {
6068
+ continue;
6069
+ }
6070
+ return Array.from({ length: count }, (_, i) => currentSeq + i);
6071
+ } catch (updateError) {
5879
6072
  continue;
5880
6073
  }
5881
- return Array.from({ length: count }, (_, i) => currentSeq + i);
5882
- } catch (updateError) {
5883
- continue;
5884
6074
  }
5885
- }
5886
- } catch (error) {
5887
- if (attempt === MAX_RETRIES - 1) {
5888
- this.logger?.error("Failed to get next serverSeq after max retries", {
6075
+ } catch (error) {
6076
+ if (attempt === MAX_RETRIES - 1) {
6077
+ this.logger?.error("Failed to get next serverSeq after max retries", {
6078
+ error: String(error),
6079
+ operation: "getNextServerSeqBatchFromDb",
6080
+ resource: "__datafn_meta"
6081
+ });
6082
+ throw new Error(
6083
+ "INTERNAL: Failed to allocate serverSeq after maximum retries"
6084
+ );
6085
+ }
6086
+ this.logger?.warn("Sequence batch CAS retry", {
6087
+ attempt,
5889
6088
  error: String(error),
5890
- operation: "getNextServerSeqBatchFromDb",
5891
- resource: "__datafn_meta"
6089
+ operation: "seq-batch-cas"
5892
6090
  });
5893
- throw new Error(
5894
- "INTERNAL: Failed to allocate serverSeq after maximum retries"
5895
- );
5896
6091
  }
5897
- this.logger?.warn("Sequence batch CAS retry", { attempt, error: String(error), operation: "seq-batch-cas" });
5898
6092
  }
5899
- }
5900
- throw new Error(
5901
- "INTERNAL: Failed to allocate serverSeq after maximum retries"
5902
- );
6093
+ throw new Error(
6094
+ "INTERNAL: Failed to allocate serverSeq after maximum retries"
6095
+ );
6096
+ });
5903
6097
  }
5904
6098
  /**
5905
6099
  * Record a change entry for a mutation (delegates to recordChanges)
@@ -6081,12 +6275,15 @@ var ChangeTrackingService = class _ChangeTrackingService {
6081
6275
  "__datafn_changes",
6082
6276
  [
6083
6277
  { field: "namespace", op: "eq", value: this.namespace },
6084
- { field: "server_seq", op: "gt", value: params.sinceSeq }
6278
+ { field: "server_seq", op: "gt", value: params.sinceSeq },
6279
+ { field: "resource", op: "in", value: params.resources }
6085
6280
  ],
6086
- { orderBy: "server_seq" }
6281
+ {
6282
+ orderBy: "server_seq",
6283
+ ...typeof params.limit === "number" && params.limit > 0 ? { limit: params.limit } : {}
6284
+ }
6087
6285
  );
6088
- const resourceSet = new Set(params.resources);
6089
- const filtered = rows.filter((row) => resourceSet.has(String(row.resource ?? ""))).map((change) => ({
6286
+ return rows.map((change) => ({
6090
6287
  namespace: this.namespace,
6091
6288
  serverSeq: change.server_seq,
6092
6289
  resource: change.resource,
@@ -6094,10 +6291,6 @@ var ChangeTrackingService = class _ChangeTrackingService {
6094
6291
  op: change.op,
6095
6292
  record: change.record ? JSON.parse(change.record) : null
6096
6293
  }));
6097
- if (typeof params.limit === "number" && params.limit > 0) {
6098
- return filtered.slice(0, params.limit);
6099
- }
6100
- return filtered;
6101
6294
  } catch (error) {
6102
6295
  this.logger?.error("Failed to get resource-filtered changes", {
6103
6296
  error: String(error),
@@ -6926,7 +7119,12 @@ async function executeShare(db, mutation, resolvedCapabilities, namespace, actor
6926
7119
  if (!ownerCheck.ok) {
6927
7120
  return ownerCheck;
6928
7121
  }
6929
- } else if (!actorId) {
7122
+ } else if (!await hasResourceScopeOwnerAccess(
7123
+ db,
7124
+ mutation.resource,
7125
+ actorId,
7126
+ namespace
7127
+ )) {
6930
7128
  return {
6931
7129
  ok: false,
6932
7130
  code: "FORBIDDEN",
@@ -7080,7 +7278,12 @@ async function executeUnshare(db, mutation, resolvedCapabilities, namespace, act
7080
7278
  if (!ownerCheck.ok) {
7081
7279
  return ownerCheck;
7082
7280
  }
7083
- } else if (!actorId) {
7281
+ } else if (!await hasResourceScopeOwnerAccess(
7282
+ db,
7283
+ mutation.resource,
7284
+ actorId,
7285
+ namespace
7286
+ )) {
7084
7287
  return {
7085
7288
  ok: false,
7086
7289
  code: "FORBIDDEN",
@@ -7177,6 +7380,9 @@ function includesResourceName(name, resource) {
7177
7380
  function pickResourceName2(name) {
7178
7381
  return Array.isArray(name) ? name[0] : name;
7179
7382
  }
7383
+ function isShareableCapability4(entry) {
7384
+ return typeof entry === "object" && entry !== null && "shareable" in entry;
7385
+ }
7180
7386
  function getResource2(schema, resourceName) {
7181
7387
  return schema.resources.find((resource) => resource.name === resourceName);
7182
7388
  }
@@ -7189,9 +7395,7 @@ function getInheritanceConfig(schema, resourceName) {
7189
7395
  schema.capabilities,
7190
7396
  resource.capabilities
7191
7397
  );
7192
- const shareable = resolvedCapabilities.find(
7193
- (entry) => typeof entry === "object" && entry !== null && "shareable" in entry
7194
- );
7398
+ const shareable = resolvedCapabilities.find(isShareableCapability4);
7195
7399
  const relationInheritance = shareable?.shareable.relationInheritance;
7196
7400
  if (!relationInheritance?.enabled) {
7197
7401
  return null;
@@ -8847,9 +9051,10 @@ async function executeTransaction(request, schema, db, idempotencyStore, limits,
8847
9051
  resource: step.mutation?.resource ?? step.query?.resource ?? "?",
8848
9052
  error: String(e?.message || e)
8849
9053
  });
9054
+ const errorCode = typeof e?.code === "string" && e.code.length > 0 ? e.code : "INTERNAL";
8850
9055
  results.push({
8851
9056
  ok: false,
8852
- error: { code: e.code || "INTERNAL", message: e.message }
9057
+ error: { code: errorCode, message: e?.message || String(e) }
8853
9058
  });
8854
9059
  if (isAtomic) return { ok: true, result: { ok: false, results } };
8855
9060
  }
@@ -8936,17 +9141,28 @@ function createTransactHandler(validatedSchema, db, idempotencyStore, limits, ex
8936
9141
  };
8937
9142
  for (let i = 0; i < body.steps.length; i++) {
8938
9143
  const step = body.steps[i];
8939
- const isMutation = !!(step.mutation || typeof step.operation === "string");
8940
9144
  let authzResult;
8941
- if (isMutation) {
9145
+ if (step.mutation) {
9146
+ authzResult = validateMutationAuthz(
9147
+ step.mutation,
9148
+ validatedSchema,
9149
+ authzOpts
9150
+ );
9151
+ } else if (step.query) {
9152
+ authzResult = validateQueryAuthz(
9153
+ step.query,
9154
+ validatedSchema,
9155
+ authzOpts
9156
+ );
9157
+ } else if (typeof step.operation === "string") {
8942
9158
  authzResult = validateMutationAuthz(
8943
- step.mutation || step,
9159
+ step,
8944
9160
  validatedSchema,
8945
9161
  authzOpts
8946
9162
  );
8947
9163
  } else {
8948
9164
  authzResult = validateQueryAuthz(
8949
- step.query || step,
9165
+ step,
8950
9166
  validatedSchema,
8951
9167
  authzOpts
8952
9168
  );
@@ -9160,7 +9376,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
9160
9376
  try {
9161
9377
  if (remaining <= 0) {
9162
9378
  data[tableName] = [];
9163
- next[tableName] = tableCounts[tableName] > 0 ? null : null;
9379
+ next[tableName] = tableCounts[tableName] > 0 ? "" : null;
9164
9380
  } else {
9165
9381
  const records = await db.findMany({
9166
9382
  model: tableName,
@@ -9184,6 +9400,7 @@ async function executeClone(request, schema, db, namespace, sequenceStore, maxCl
9184
9400
  logger?.warn("Clone: auto-paginate fetch failed", { error: String(error), resource: tableName, operation: "clone-paginate" });
9185
9401
  data[tableName] = [];
9186
9402
  cursors[tableName] = "0";
9403
+ next[tableName] = null;
9187
9404
  }
9188
9405
  }
9189
9406
  } else {
@@ -9960,6 +10177,9 @@ async function executePullCanonical(request, schema, db, namespace, sequenceStor
9960
10177
  }
9961
10178
  continue;
9962
10179
  }
10180
+ if (!isDataResourceKey(resource)) {
10181
+ continue;
10182
+ }
9963
10183
  const isPrivate = isPrivateShareableResource(schema, resource);
9964
10184
  if (isPrivate && !actorId) {
9965
10185
  continue;
@@ -10297,15 +10517,34 @@ async function executePush(request, schema, db, idempotencyStore, namespace, seq
10297
10517
  case "replace": {
10298
10518
  const coercedData = applyDateCoercion(schema, mut.resource, mut.record || {}, logger);
10299
10519
  const strippedRecord = stripReadonlyCapabilityFields(coercedData, resolvedCapabilities);
10300
- const replaceData = injectCapabilityFieldsOnUpdate2(
10520
+ const createData = injectCapabilityFieldsOnInsert2(
10521
+ strippedRecord,
10522
+ resolvedCapabilities,
10523
+ actorId
10524
+ );
10525
+ const updateData = injectCapabilityFieldsOnUpdate2(
10301
10526
  strippedRecord,
10302
10527
  resolvedCapabilities,
10303
10528
  actorId
10304
10529
  );
10305
- await targetDb.upsert({ model: mut.resource, where: [{ field: "id", operator: "eq", value: mut.id }], create: { id: mut.id, ...replaceData }, update: replaceData, namespace, conflictTarget: "id" });
10530
+ const persistedRecord = await targetDb.upsert({
10531
+ model: mut.resource,
10532
+ where: [{ field: "id", operator: "eq", value: mut.id }],
10533
+ create: { id: mut.id, ...createData },
10534
+ update: updateData,
10535
+ namespace,
10536
+ conflictTarget: "id"
10537
+ });
10306
10538
  return {
10307
10539
  ok: true,
10308
- changes: [{ resource: mut.resource, id: mut.id, op: "replace", record: { id: mut.id, ...replaceData } }]
10540
+ changes: [
10541
+ {
10542
+ resource: mut.resource,
10543
+ id: mut.id,
10544
+ op: "replace",
10545
+ record: { id: mut.id, ...persistedRecord }
10546
+ }
10547
+ ]
10309
10548
  };
10310
10549
  }
10311
10550
  case "delete":
@@ -10879,7 +11118,12 @@ async function executeReconcile(request, schema, db, namespace, sequenceStore, l
10879
11118
  const toResource = toResources[0];
10880
11119
  const joinStoreKey = getJoinStoreKey(fromResource, relation.relation, toResource);
10881
11120
  const joinTableName = getJoinTableName(fromResource, relation.relation, relation.joinTable);
11121
+ const relationTouchesPrivateResource = isPrivateShareableResource(schema, fromResource) || isPrivateShareableResource(schema, toResource);
10882
11122
  try {
11123
+ if (relationTouchesPrivateResource && !actorId) {
11124
+ joinCounts[joinStoreKey] = 0;
11125
+ continue;
11126
+ }
10883
11127
  if (typeof db.count === "function") {
10884
11128
  joinCounts[joinStoreKey] = await db.count({
10885
11129
  model: joinTableName,
@@ -10980,7 +11224,7 @@ function createCloneHandler(validatedSchema, extractNamespace, extractActorId, d
10980
11224
  code: "INTERNAL",
10981
11225
  message: "Internal error",
10982
11226
  details: { path: "$" }
10983
- });
11227
+ }, 500);
10984
11228
  } finally {
10985
11229
  logRequest({
10986
11230
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11059,7 +11303,7 @@ function createPullHandler(validatedSchema, extractNamespace, extractActorId, db
11059
11303
  code: "INTERNAL",
11060
11304
  message: "Internal error",
11061
11305
  details: { path: "$" }
11062
- });
11306
+ }, 500);
11063
11307
  } finally {
11064
11308
  logRequest({
11065
11309
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11247,7 +11491,7 @@ function createPushHandler(validatedSchema, extractNamespace, extractActorId, db
11247
11491
  code: "INTERNAL",
11248
11492
  message: "Internal error",
11249
11493
  details: { path: "$" }
11250
- });
11494
+ }, 500);
11251
11495
  } finally {
11252
11496
  logRequest({
11253
11497
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11330,7 +11574,7 @@ function createReconcileHandler(validatedSchema, extractNamespace, extractActorI
11330
11574
  code: "INTERNAL",
11331
11575
  message: "Internal error",
11332
11576
  details: { path: "$" }
11333
- });
11577
+ }, 500);
11334
11578
  } finally {
11335
11579
  logRequest({
11336
11580
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -11897,7 +12141,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
11897
12141
  {
11898
12142
  method: "GET",
11899
12143
  path: "/datafn/resources/:resource",
11900
- handler: async (req) => {
12144
+ handler: async (req, ctx) => {
11901
12145
  const url = new URL(req.url);
11902
12146
  const pathParts = url.pathname.split("/");
11903
12147
  const rawResource = pathParts[3] ?? "";
@@ -11927,11 +12171,11 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
11927
12171
  }
11928
12172
  }
11929
12173
  const dfql = {
12174
+ ...queryBody,
11930
12175
  resource,
11931
- version: getResourceVersion(resource),
11932
- ...queryBody
12176
+ version: getResourceVersion(resource)
11933
12177
  };
11934
- const result = await executeQuery2(dfql);
12178
+ const result = await executeQuery2(dfql, ctx);
11935
12179
  return jsonResponse({ ok: true, result });
11936
12180
  } catch (err) {
11937
12181
  if (err.code === "DFQL_UNKNOWN_RESOURCE") {
@@ -11994,7 +12238,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
11994
12238
  id: body.id,
11995
12239
  record: body.record
11996
12240
  };
11997
- const result = await executeMutation2(mutation);
12241
+ const result = await executeMutation2(mutation, ctx);
11998
12242
  return jsonResponse({ ok: true, result });
11999
12243
  } catch (err) {
12000
12244
  if (err.code === "DFQL_UNKNOWN_RESOURCE") {
@@ -12059,7 +12303,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
12059
12303
  id,
12060
12304
  record: body.record
12061
12305
  };
12062
- const result = await executeMutation2(mutation);
12306
+ const result = await executeMutation2(mutation, ctx);
12063
12307
  return jsonResponse({ ok: true, result });
12064
12308
  } catch (err) {
12065
12309
  if (err.code === "DFQL_UNKNOWN_RESOURCE") {
@@ -12074,7 +12318,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
12074
12318
  {
12075
12319
  method: "DELETE",
12076
12320
  path: "/datafn/resources/:resource/:id",
12077
- handler: async (req) => {
12321
+ handler: async (req, ctx) => {
12078
12322
  const url = new URL(req.url);
12079
12323
  const pathParts = url.pathname.split("/");
12080
12324
  const rawResource = pathParts[3] ?? "";
@@ -12118,7 +12362,7 @@ function createRestRoutes(schema, executeMutation2, executeQuery2, logger) {
12118
12362
  mutationId,
12119
12363
  id
12120
12364
  };
12121
- const result = await executeMutation2(mutation);
12365
+ const result = await executeMutation2(mutation, ctx);
12122
12366
  return jsonResponse({ ok: true, result });
12123
12367
  } catch (err) {
12124
12368
  if (err.code === "DFQL_UNKNOWN_RESOURCE") {
@@ -12231,6 +12475,19 @@ var WebSocketManager = class {
12231
12475
  canonicalizeActorPrincipal(actorId) {
12232
12476
  return actorId.includes(":") ? actorId : `user:${actorId}`;
12233
12477
  }
12478
+ closeClientSafely(client, code, reason, operation) {
12479
+ if (typeof client.close !== "function") {
12480
+ return;
12481
+ }
12482
+ try {
12483
+ client.close(code, reason);
12484
+ } catch (error) {
12485
+ this.logger?.warn("WebSocket close error", {
12486
+ error: String(error),
12487
+ operation
12488
+ });
12489
+ }
12490
+ }
12234
12491
  resolveClientPrincipals(authContext) {
12235
12492
  const principals = /* @__PURE__ */ new Set();
12236
12493
  if (Array.isArray(authContext.principalIds)) {
@@ -12311,13 +12568,13 @@ var WebSocketManager = class {
12311
12568
  } catch (e) {
12312
12569
  this.logger?.warn("Heartbeat ping failed", { error: String(e), operation: "ws-heartbeat" });
12313
12570
  this.removeClient(client);
12314
- client.close?.(1001, "Heartbeat ping failed");
12571
+ this.closeClientSafely(client, 1001, "Heartbeat ping failed", "ws-heartbeat-close");
12315
12572
  continue;
12316
12573
  }
12317
12574
  setTimeout(() => {
12318
12575
  if (this.pendingPong.has(client)) {
12319
12576
  this.removeClient(client);
12320
- client.close?.(1001, "Heartbeat timeout");
12577
+ this.closeClientSafely(client, 1001, "Heartbeat timeout", "ws-heartbeat-timeout-close");
12321
12578
  }
12322
12579
  }, timeoutMs);
12323
12580
  }
@@ -12336,11 +12593,16 @@ var WebSocketManager = class {
12336
12593
  addClient(client, authContext) {
12337
12594
  const { namespace } = authContext;
12338
12595
  if (this.totalCount >= this.maxConnections) {
12339
- client.close?.(4503, "Connection limit reached");
12596
+ this.closeClientSafely(client, 4503, "Connection limit reached", "ws-limit-close");
12340
12597
  return false;
12341
12598
  }
12342
12599
  if (this.getNamespaceCount(namespace) >= this.maxConnectionsPerNamespace) {
12343
- client.close?.(4503, "Namespace connection limit reached");
12600
+ this.closeClientSafely(
12601
+ client,
12602
+ 4503,
12603
+ "Namespace connection limit reached",
12604
+ "ws-namespace-limit-close"
12605
+ );
12344
12606
  return false;
12345
12607
  }
12346
12608
  let nsSet = this.namespaceClients.get(namespace);
@@ -12457,6 +12719,7 @@ var WebSocketManager = class {
12457
12719
  } catch (e) {
12458
12720
  this.logger?.error("Error sending to websocket client", { error: String(e), operation: "ws-broadcast" });
12459
12721
  this.removeClient(client);
12722
+ this.closeClientSafely(client, 1001, "Broadcast send failed", "ws-broadcast-close");
12460
12723
  }
12461
12724
  }
12462
12725
  return {
@@ -12472,11 +12735,7 @@ var WebSocketManager = class {
12472
12735
  close() {
12473
12736
  this.destroy();
12474
12737
  for (const [client] of this.clientNamespace) {
12475
- try {
12476
- client.close?.(1001, "Going Away");
12477
- } catch (e) {
12478
- this.logger?.warn("WebSocket close error", { error: String(e), operation: "ws-close" });
12479
- }
12738
+ this.closeClientSafely(client, 1001, "Going Away", "ws-close");
12480
12739
  }
12481
12740
  this.namespaceClients.clear();
12482
12741
  this.namespacePrincipalClients.clear();
@@ -12614,9 +12873,9 @@ function createDefaultLogger(debug) {
12614
12873
  };
12615
12874
  }
12616
12875
  return {
12617
- info: (msg, ctx) => console.log(JSON.stringify({ level: "info", msg, ...ctx, ts: Date.now() })),
12618
- warn: (msg, ctx) => console.warn(JSON.stringify({ level: "warn", msg, ...ctx, ts: Date.now() })),
12619
- error: (msg, ctx) => console.error(JSON.stringify({ level: "error", msg, ...ctx, ts: Date.now() })),
12876
+ info: (msg, ctx) => console.log(JSON.stringify({ ...ctx ?? {}, level: "info", msg, ts: Date.now() })),
12877
+ warn: (msg, ctx) => console.warn(JSON.stringify({ ...ctx ?? {}, level: "warn", msg, ts: Date.now() })),
12878
+ error: (msg, ctx) => console.error(JSON.stringify({ ...ctx ?? {}, level: "error", msg, ts: Date.now() })),
12620
12879
  debug: () => {
12621
12880
  }
12622
12881
  };
@@ -12913,9 +13172,75 @@ async function createDatafnServer(config) {
12913
13172
  let inFlightCount = 0;
12914
13173
  let shuttingDown = false;
12915
13174
  let shutdownResolve = null;
13175
+ let shutdownTimer = null;
13176
+ const isPlainObjectContext = (value) => {
13177
+ if (!value || typeof value !== "object") {
13178
+ return false;
13179
+ }
13180
+ const prototype = Object.getPrototypeOf(value);
13181
+ return prototype === Object.prototype || prototype === null;
13182
+ };
13183
+ const createEnrichedContext = (ctx) => {
13184
+ if (isPlainObjectContext(ctx)) {
13185
+ return { ...ctx };
13186
+ }
13187
+ if (ctx && typeof ctx === "object") {
13188
+ let parsedBody;
13189
+ let hasParsedBody = false;
13190
+ const target = ctx;
13191
+ return new Proxy(target, {
13192
+ get(currentTarget, prop) {
13193
+ if (prop === "parsedBody") {
13194
+ if (hasParsedBody) {
13195
+ return parsedBody;
13196
+ }
13197
+ return Reflect.get(currentTarget, prop, currentTarget);
13198
+ }
13199
+ const value = Reflect.get(currentTarget, prop, currentTarget);
13200
+ return typeof value === "function" ? value.bind(currentTarget) : value;
13201
+ },
13202
+ set(currentTarget, prop, value) {
13203
+ if (prop === "parsedBody") {
13204
+ hasParsedBody = true;
13205
+ parsedBody = value;
13206
+ return true;
13207
+ }
13208
+ return Reflect.set(currentTarget, prop, value, currentTarget);
13209
+ },
13210
+ has(currentTarget, prop) {
13211
+ if (prop === "parsedBody") {
13212
+ return hasParsedBody || Reflect.has(currentTarget, prop);
13213
+ }
13214
+ return Reflect.has(currentTarget, prop);
13215
+ },
13216
+ ownKeys(currentTarget) {
13217
+ const keys = Reflect.ownKeys(currentTarget);
13218
+ if (hasParsedBody && !keys.includes("parsedBody")) {
13219
+ return [...keys, "parsedBody"];
13220
+ }
13221
+ return keys;
13222
+ },
13223
+ getOwnPropertyDescriptor(currentTarget, prop) {
13224
+ if (prop === "parsedBody") {
13225
+ if (!hasParsedBody) {
13226
+ return Reflect.getOwnPropertyDescriptor(currentTarget, prop);
13227
+ }
13228
+ return {
13229
+ configurable: true,
13230
+ enumerable: true,
13231
+ writable: true,
13232
+ value: parsedBody
13233
+ };
13234
+ }
13235
+ return Reflect.getOwnPropertyDescriptor(currentTarget, prop);
13236
+ }
13237
+ });
13238
+ }
13239
+ return { parsedBody: void 0 };
13240
+ };
12916
13241
  const withAuth = (action, handler) => {
12917
13242
  return async (req, ctx) => {
12918
- const enrichedCtx = ctx;
13243
+ const enrichedCtx = createEnrichedContext(ctx);
12919
13244
  if (shuttingDown) {
12920
13245
  return new Response(
12921
13246
  JSON.stringify({ ok: false, error: { code: "SERVICE_UNAVAILABLE", message: "Server is shutting down" } }),
@@ -12925,7 +13250,7 @@ async function createDatafnServer(config) {
12925
13250
  inFlightCount++;
12926
13251
  try {
12927
13252
  if (rateLimitMiddleware) {
12928
- const rateLimitResponse = await rateLimitMiddleware(action, ctx);
13253
+ const rateLimitResponse = await rateLimitMiddleware(action, enrichedCtx);
12929
13254
  if (rateLimitResponse) return rateLimitResponse;
12930
13255
  }
12931
13256
  if (limits.maxPayloadBytes) {
@@ -12970,6 +13295,10 @@ async function createDatafnServer(config) {
12970
13295
  if (shuttingDown && inFlightCount === 0 && shutdownResolve) {
12971
13296
  const resolve = shutdownResolve;
12972
13297
  shutdownResolve = null;
13298
+ if (shutdownTimer) {
13299
+ clearTimeout(shutdownTimer);
13300
+ shutdownTimer = null;
13301
+ }
12973
13302
  resolve();
12974
13303
  }
12975
13304
  }
@@ -13028,14 +13357,20 @@ async function createDatafnServer(config) {
13028
13357
  }
13029
13358
  ];
13030
13359
  if (config.rest) {
13031
- const internalMutate = async (m) => {
13032
- const res = await mutationHandler(void 0, { parsedBody: m });
13360
+ const internalMutate = async (m, ctx) => {
13361
+ const res = await mutationHandler(void 0, {
13362
+ ...ctx ?? {},
13363
+ parsedBody: m
13364
+ });
13033
13365
  const env = await res.json();
13034
13366
  if (!env.ok) throw env.error;
13035
13367
  return env.result;
13036
13368
  };
13037
- const internalQuery = async (q) => {
13038
- const res = await queryHandler(void 0, { parsedBody: q });
13369
+ const internalQuery = async (q, ctx) => {
13370
+ const res = await queryHandler(void 0, {
13371
+ ...ctx ?? {},
13372
+ parsedBody: q
13373
+ });
13039
13374
  const env = await res.json();
13040
13375
  if (!env.ok) throw env.error;
13041
13376
  return env.result;
@@ -13049,29 +13384,36 @@ async function createDatafnServer(config) {
13049
13384
  for (const route of restRoutes) {
13050
13385
  const action = route.method === "GET" ? "query" : "mutation";
13051
13386
  routes.push({
13052
- ...route,
13387
+ method: route.method,
13388
+ path: route.path,
13389
+ meta: route.meta,
13053
13390
  handler: withAuth(action, route.handler)
13054
13391
  });
13055
13392
  }
13056
13393
  }
13057
13394
  const router = createRouter({
13058
13395
  routes,
13059
- basePath: "/"
13396
+ basePath: "/",
13397
+ context: config.context
13060
13398
  });
13061
13399
  const serverClose = async () => {
13062
13400
  if (shuttingDown) return;
13063
13401
  shuttingDown = true;
13402
+ process.off("SIGTERM", sigHandler);
13403
+ process.off("SIGINT", sigHandler);
13064
13404
  wsManager.close();
13065
13405
  if (inFlightCount > 0) {
13066
13406
  const timeoutMs = config.shutdownTimeoutMs ?? 1e4;
13067
13407
  await new Promise((resolve) => {
13068
13408
  shutdownResolve = resolve;
13069
- setTimeout(() => {
13409
+ shutdownTimer = setTimeout(() => {
13070
13410
  if (shutdownResolve === resolve) {
13071
13411
  shutdownResolve = null;
13412
+ shutdownTimer = null;
13072
13413
  resolve();
13073
13414
  }
13074
13415
  }, timeoutMs);
13416
+ shutdownTimer.unref?.();
13075
13417
  });
13076
13418
  }
13077
13419
  if (config.searchProvider?.dispose) {
@@ -13091,8 +13433,8 @@ async function createDatafnServer(config) {
13091
13433
  }
13092
13434
  };
13093
13435
  const sigHandler = () => serverClose().catch((e) => logger.error("Graceful shutdown error", { error: String(e), operation: "shutdown" }));
13094
- process.once("SIGTERM", sigHandler);
13095
- process.once("SIGINT", sigHandler);
13436
+ process.on("SIGTERM", sigHandler);
13437
+ process.on("SIGINT", sigHandler);
13096
13438
  const serverSearch = async (params, _ctx) => {
13097
13439
  if (!db) {
13098
13440
  throw new Error("Database is not configured");