@stndrds/schema 1.0.0-alpha.72 → 1.0.0-alpha.74

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.
@@ -15,6 +15,9 @@ var _chunkNEVERCM3js = require('./chunk-NEVERCM3.js');
15
15
  var _chunk3WTK7ESHjs = require('./chunk-3WTK7ESH.js');
16
16
 
17
17
 
18
+ var _chunkJZO52C3Fjs = require('./chunk-JZO52C3F.js');
19
+
20
+
18
21
  var _chunk3RG5ZIWIjs = require('./chunk-3RG5ZIWI.js');
19
22
 
20
23
  // src/runtime/auth/workflow-jwt.service.ts
@@ -2138,7 +2141,7 @@ var EndExecutor = class {
2138
2141
  this.nodeType = "end";
2139
2142
  }
2140
2143
  execute(node, _context) {
2141
- return complete(_nullishCoalesce(node.status, () => ( "completed")));
2144
+ return complete(node.status || "completed");
2142
2145
  }
2143
2146
  canExecute(_node, _context) {
2144
2147
  return true;
@@ -2261,10 +2264,20 @@ var FormExecutor = class {
2261
2264
  const fieldRefs = this.collectFieldRefs(node);
2262
2265
  for (const fieldRef of fieldRefs) {
2263
2266
  const slot = slots.find((s) => s.id === fieldRef.slotId);
2264
- if (!slot) continue;
2267
+ if (!slot) {
2268
+ console.warn(
2269
+ `[FormExecutor] Slot "${fieldRef.slotId}" not found in workflow definition, skipping validation`
2270
+ );
2271
+ continue;
2272
+ }
2265
2273
  if (slot.mode === "select") continue;
2266
2274
  const object2 = objects.find((o) => o.name === slot.objectName);
2267
- if (!object2) continue;
2275
+ if (!object2) {
2276
+ console.warn(
2277
+ `[FormExecutor] Object "${slot.objectName}" not found for slot "${fieldRef.slotId}", skipping validation`
2278
+ );
2279
+ continue;
2280
+ }
2268
2281
  const attribute = object2.attributes.find((a) => a.name === fieldRef.attribute);
2269
2282
  if (!_optionalChain([attribute, 'optionalAccess', _30 => _30.required])) continue;
2270
2283
  const slotInput = input[fieldRef.slotId];
@@ -2309,7 +2322,7 @@ var StartExecutor = class {
2309
2322
  }
2310
2323
  execute(node, _context) {
2311
2324
  if (!node.next) {
2312
- throw new Error(`StartNode "${node.id}" has no 'next' target defined`);
2325
+ return error("MISSING_NEXT", `StartNode "${node.id}" has no 'next' target defined`);
2313
2326
  }
2314
2327
  return success(node.next);
2315
2328
  }
@@ -2523,13 +2536,11 @@ function hasRelationReferences(expression) {
2523
2536
  return regex.test(expression);
2524
2537
  }
2525
2538
  function flattenRelationsForEval(resolvedRelations) {
2526
- const flat = {};
2539
+ const result = {};
2527
2540
  for (const [relationName, values] of Object.entries(resolvedRelations)) {
2528
- for (const [key, value] of Object.entries(values)) {
2529
- flat[`${relationName}.${key}`] = value;
2530
- }
2541
+ result[relationName] = { ...values };
2531
2542
  }
2532
- return flat;
2543
+ return result;
2533
2544
  }
2534
2545
  async function evaluateFormulaWithRelations(expression, record, schema, resolver) {
2535
2546
  const relationNames = extractRelationNames(expression);
@@ -2799,6 +2810,15 @@ function createMockAIConversationsRepository(stores) {
2799
2810
  },
2800
2811
  addMessage(input) {
2801
2812
  const now = /* @__PURE__ */ new Date();
2813
+ const conversation = stores.aiConversations.get(input.conversationId);
2814
+ if (!conversation) {
2815
+ return Promise.reject(new Error("Conversation not found"));
2816
+ }
2817
+ const tenantId = getTenantId();
2818
+ const userId = requireUserId();
2819
+ if (conversation.tenantId !== tenantId || conversation.userId !== userId) {
2820
+ return Promise.reject(new Error("Conversation not found or access denied"));
2821
+ }
2802
2822
  const message = {
2803
2823
  id: _chunkNEVERCM3js.generateId.call(void 0, ),
2804
2824
  conversationId: input.conversationId,
@@ -2816,17 +2836,23 @@ function createMockAIConversationsRepository(stores) {
2816
2836
  createdAt: now
2817
2837
  };
2818
2838
  stores.aiMessages.set(message.id, message);
2819
- const conversation = stores.aiConversations.get(input.conversationId);
2820
- if (conversation) {
2821
- conversation.messageCount++;
2822
- conversation.totalTokens += (_nullishCoalesce(input.inputTokens, () => ( 0))) + (_nullishCoalesce(input.outputTokens, () => ( 0)));
2823
- conversation.totalCost += _nullishCoalesce(input.cost, () => ( 0));
2824
- conversation.updatedAt = now;
2825
- stores.aiConversations.set(input.conversationId, conversation);
2826
- }
2839
+ conversation.messageCount++;
2840
+ conversation.totalTokens += (_nullishCoalesce(input.inputTokens, () => ( 0))) + (_nullishCoalesce(input.outputTokens, () => ( 0)));
2841
+ conversation.totalCost += _nullishCoalesce(input.cost, () => ( 0));
2842
+ conversation.updatedAt = now;
2843
+ stores.aiConversations.set(input.conversationId, conversation);
2827
2844
  return Promise.resolve(message);
2828
2845
  },
2829
2846
  listMessages(conversationId, options) {
2847
+ const conversation = stores.aiConversations.get(conversationId);
2848
+ if (!conversation) {
2849
+ return Promise.resolve({ messages: [], total: 0 });
2850
+ }
2851
+ const tenantId = getTenantId();
2852
+ const userId = requireUserId();
2853
+ if (conversation.tenantId !== tenantId || conversation.userId !== userId) {
2854
+ return Promise.resolve({ messages: [], total: 0 });
2855
+ }
2830
2856
  let results = Array.from(stores.aiMessages.values()).filter((m) => m.conversationId === conversationId).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
2831
2857
  const total = results.length;
2832
2858
  if (_optionalChain([options, 'optionalAccess', _38 => _38.limit])) {
@@ -2835,6 +2861,15 @@ function createMockAIConversationsRepository(stores) {
2835
2861
  return Promise.resolve({ messages: results, total });
2836
2862
  },
2837
2863
  getRecentMessages(conversationId, count = 20) {
2864
+ const conversation = stores.aiConversations.get(conversationId);
2865
+ if (!conversation) {
2866
+ return Promise.resolve([]);
2867
+ }
2868
+ const tenantId = getTenantId();
2869
+ const userId = requireUserId();
2870
+ if (conversation.tenantId !== tenantId || conversation.userId !== userId) {
2871
+ return Promise.resolve([]);
2872
+ }
2838
2873
  const results = Array.from(stores.aiMessages.values()).filter((m) => m.conversationId === conversationId).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()).slice(-count);
2839
2874
  return Promise.resolve(results);
2840
2875
  }
@@ -3101,7 +3136,12 @@ function createMockFilesRepository(stores) {
3101
3136
  function createMockObjectsRepository(stores) {
3102
3137
  return {
3103
3138
  findById(id) {
3104
- return Promise.resolve(_nullishCoalesce(stores.objects.get(id), () => ( null)));
3139
+ const tenantId = getTenantId();
3140
+ const obj = stores.objects.get(id);
3141
+ if (!obj || obj.tenantId !== tenantId) {
3142
+ return Promise.resolve(null);
3143
+ }
3144
+ return Promise.resolve(obj);
3105
3145
  },
3106
3146
  findByName(name) {
3107
3147
  const tenantId = getTenantId();
@@ -3141,8 +3181,9 @@ function createMockObjectsRepository(stores) {
3141
3181
  return Promise.resolve(obj);
3142
3182
  },
3143
3183
  update(id, data) {
3184
+ const tenantId = getTenantId();
3144
3185
  const existing = stores.objects.get(id);
3145
- if (!existing) {
3186
+ if (!existing || existing.tenantId !== tenantId) {
3146
3187
  return Promise.reject(new Error(`Object ${id} not found`));
3147
3188
  }
3148
3189
  const updated = {
@@ -3154,6 +3195,11 @@ function createMockObjectsRepository(stores) {
3154
3195
  return Promise.resolve(updated);
3155
3196
  },
3156
3197
  delete(id) {
3198
+ const tenantId = getTenantId();
3199
+ const existing = stores.objects.get(id);
3200
+ if (!existing || existing.tenantId !== tenantId) {
3201
+ return Promise.reject(new Error(`Object ${id} not found`));
3202
+ }
3157
3203
  stores.objects.delete(id);
3158
3204
  return Promise.resolve();
3159
3205
  },
@@ -3167,7 +3213,7 @@ function createMockObjectsRepository(stores) {
3167
3213
  upsert(data) {
3168
3214
  const tenantId = getTenantId();
3169
3215
  for (const obj of stores.objects.values()) {
3170
- if (obj.system && obj.name === data.name) {
3216
+ if (obj.tenantId === tenantId && obj.system && obj.name === data.name) {
3171
3217
  const updated = {
3172
3218
  ...obj,
3173
3219
  label: data.label,
@@ -3700,13 +3746,24 @@ function parsePipeExpression(pipeExpr) {
3700
3746
  }
3701
3747
  function renderLabelExpression(template, values, fallback = DEFAULT_LABEL_FALLBACK) {
3702
3748
  const result = template.replace(/\{\{\s*([^}]+)\s*\}\}/g, (_, expr) => {
3703
- const parts = expr.split("|").map((s) => s.trim());
3704
- const path = parts[0];
3705
- let value = getValue(values, path);
3749
+ const orParts = expr.split("||").map((s) => s.trim());
3750
+ const lastPart = orParts[orParts.length - 1];
3751
+ const pipeSplit = lastPart.split("|").map((s) => s.trim());
3752
+ orParts[orParts.length - 1] = pipeSplit[0];
3753
+ const pipes = pipeSplit.slice(1).filter(Boolean);
3754
+ const alternatives = orParts.filter(Boolean);
3755
+ let value = "";
3756
+ for (const alt of alternatives) {
3757
+ const v = getValue(values, alt);
3758
+ if (v != null && v !== "") {
3759
+ value = v;
3760
+ break;
3761
+ }
3762
+ }
3706
3763
  const isEmpty3 = value == null || value === "";
3707
- if (isEmpty3 && parts.length === 1) return "";
3708
- for (let i = 1; i < parts.length; i++) {
3709
- const { name: pipeName, args } = parsePipeExpression(parts[i]);
3764
+ if (isEmpty3 && pipes.length === 0) return "";
3765
+ for (const pipeExpr of pipes) {
3766
+ const { name: pipeName, args } = parsePipeExpression(pipeExpr);
3710
3767
  const simpleFn = simplePipes[pipeName];
3711
3768
  if (simpleFn) {
3712
3769
  if (value != null && value !== "") {
@@ -3728,13 +3785,19 @@ function isLabelExpression(value) {
3728
3785
  }
3729
3786
  function extractAttributeNames(template) {
3730
3787
  const names = [];
3731
- const regex = /\{\{\s*([^|}]+)/g;
3788
+ const regex = /\{\{\s*([^}]+)\s*\}\}/g;
3732
3789
  let match;
3733
3790
  while ((match = regex.exec(template)) !== null) {
3734
- const path = match[1].trim();
3735
- const rootName = path.split(".")[0];
3736
- if (rootName && !names.includes(rootName)) {
3737
- names.push(rootName);
3791
+ const expr = match[1].trim();
3792
+ const orParts = expr.split("||").map((s) => s.trim());
3793
+ const lastPart = orParts[orParts.length - 1];
3794
+ orParts[orParts.length - 1] = lastPart.split("|")[0].trim();
3795
+ for (const part of orParts) {
3796
+ if (!part) continue;
3797
+ const rootName = part.split(".")[0];
3798
+ if (rootName && !names.includes(rootName)) {
3799
+ names.push(rootName);
3800
+ }
3738
3801
  }
3739
3802
  }
3740
3803
  return names;
@@ -3822,6 +3885,7 @@ function createMockObjectRecordsRepository(stores) {
3822
3885
  findById(id) {
3823
3886
  const internal = stores.objectRecords.get(id);
3824
3887
  if (!internal) return Promise.resolve(null);
3888
+ if (internal.deletedAt) return Promise.resolve(null);
3825
3889
  const { tenantId: _, ...record } = internal;
3826
3890
  return Promise.resolve(record);
3827
3891
  },
@@ -3829,7 +3893,7 @@ function createMockObjectRecordsRepository(stores) {
3829
3893
  const results = [];
3830
3894
  for (const id of ids) {
3831
3895
  const internal = stores.objectRecords.get(id);
3832
- if (internal) {
3896
+ if (internal && !internal.deletedAt) {
3833
3897
  const { tenantId: _, ...record } = internal;
3834
3898
  results.push(record);
3835
3899
  }
@@ -3890,13 +3954,18 @@ function createMockObjectRecordsRepository(stores) {
3890
3954
  return Promise.resolve(record);
3891
3955
  },
3892
3956
  delete(id) {
3893
- stores.objectRecords.delete(id);
3957
+ const existing = stores.objectRecords.get(id);
3958
+ if (!existing) {
3959
+ return Promise.reject(new Error(`ObjectRecord ${id} not found`));
3960
+ }
3961
+ existing.deletedAt = /* @__PURE__ */ new Date();
3962
+ stores.objectRecords.set(id, existing);
3894
3963
  return Promise.resolve();
3895
3964
  },
3896
3965
  list(objectId, options) {
3897
3966
  const tenantId = getTenantId();
3898
3967
  let results = Array.from(stores.objectRecords.values()).filter(
3899
- (r) => r.tenantId === tenantId && r.objectId === objectId
3968
+ (r) => r.tenantId === tenantId && r.objectId === objectId && !r.deletedAt
3900
3969
  );
3901
3970
  const total = results.length;
3902
3971
  if (_optionalChain([options, 'optionalAccess', _73 => _73.limit])) {
@@ -3909,7 +3978,7 @@ function createMockObjectRecordsRepository(stores) {
3909
3978
  const tenantId = getTenantId();
3910
3979
  const lowerQuery = query.toLowerCase();
3911
3980
  let results = Array.from(stores.objectRecords.values()).filter((r) => {
3912
- if (r.tenantId !== tenantId || r.objectId !== objectId) return false;
3981
+ if (r.tenantId !== tenantId || r.objectId !== objectId || r.deletedAt) return false;
3913
3982
  return Object.values(r.values).some(
3914
3983
  (val) => String(val).toLowerCase().includes(lowerQuery)
3915
3984
  );
@@ -3943,7 +4012,7 @@ function createMockObjectRecordsRepository(stores) {
3943
4012
  }
3944
4013
  }
3945
4014
  let matchingRecords = Array.from(stores.objectRecords.values()).filter((r) => {
3946
- if (r.tenantId !== tenantId) return false;
4015
+ if (r.tenantId !== tenantId || r.deletedAt) return false;
3947
4016
  if (!allowedObjectIds.has(r.objectId)) return false;
3948
4017
  return Object.values(r.values).some(
3949
4018
  (val) => String(val).toLowerCase().includes(lowerQuery)
@@ -4098,12 +4167,12 @@ function createMockObjectRecordsRepository(stores) {
4098
4167
  }
4099
4168
  return Promise.resolve(updated);
4100
4169
  },
4101
- findByRelation(objectName, relationAttributeName, targetRecordId) {
4102
- const obj = Array.from(stores.objects.values()).find((o) => o.name === objectName);
4170
+ findByRelation(objectId, relationAttributeName, targetRecordId) {
4171
+ const obj = stores.objects.get(objectId);
4103
4172
  if (!obj) return Promise.resolve([]);
4104
4173
  const results = [];
4105
4174
  for (const record of stores.objectRecords.values()) {
4106
- if (record.objectId !== obj.id) continue;
4175
+ if (record.objectId !== objectId) continue;
4107
4176
  const value = record.values[relationAttributeName];
4108
4177
  let matches = false;
4109
4178
  if (typeof value === "string" && value === targetRecordId) {
@@ -4263,7 +4332,12 @@ function createEmptyStores() {
4263
4332
  function createMockUserProfilesRepository(stores) {
4264
4333
  return {
4265
4334
  findById(id) {
4266
- return Promise.resolve(_nullishCoalesce(stores.userProfiles.get(id), () => ( null)));
4335
+ const tenantId = getTenantId();
4336
+ const profile = stores.userProfiles.get(id);
4337
+ if (!profile || profile.tenantId !== tenantId) {
4338
+ return Promise.resolve(null);
4339
+ }
4340
+ return Promise.resolve(profile);
4267
4341
  },
4268
4342
  findByIds(ids) {
4269
4343
  const tenantId = getTenantId();
@@ -4277,8 +4351,9 @@ function createMockUserProfilesRepository(stores) {
4277
4351
  return Promise.resolve(results);
4278
4352
  },
4279
4353
  findByAuthId(authId) {
4354
+ const tenantId = getTenantId();
4280
4355
  for (const profile of stores.userProfiles.values()) {
4281
- if (profile.authId === authId) {
4356
+ if (profile.tenantId === tenantId && profile.authId === authId) {
4282
4357
  return Promise.resolve(profile);
4283
4358
  }
4284
4359
  }
@@ -4303,7 +4378,6 @@ function createMockUserProfilesRepository(stores) {
4303
4378
  firstName: data.firstName,
4304
4379
  lastName: data.lastName,
4305
4380
  avatarUrl: data.avatarUrl,
4306
- role: _nullishCoalesce(data.role, () => ( "member")),
4307
4381
  status: _nullishCoalesce(data.status, () => ( "active")),
4308
4382
  createdAt: /* @__PURE__ */ new Date(),
4309
4383
  updatedAt: /* @__PURE__ */ new Date()
@@ -4336,12 +4410,23 @@ function createMockUserProfilesRepository(stores) {
4336
4410
  }
4337
4411
  return Promise.resolve(results);
4338
4412
  },
4339
- countByRole(role) {
4413
+ getUsersWithRoles(filters) {
4340
4414
  const tenantId = getTenantId();
4341
- const count = Array.from(stores.userProfiles.values()).filter(
4342
- (profile) => profile.tenantId === tenantId && profile.role === role
4343
- ).length;
4344
- return Promise.resolve(count);
4415
+ const profiles = Array.from(stores.userProfiles.values()).filter(
4416
+ (p) => p.tenantId === tenantId
4417
+ );
4418
+ const results = [];
4419
+ for (const profile of profiles) {
4420
+ const roleIds = Array.from(stores.userRoles.values()).filter((ur) => ur.userProfileId === profile.id && ur.tenantId === tenantId).map((ur) => ur.roleId);
4421
+ const roles = Array.from(stores.roles.values()).filter((r) => roleIds.includes(r.id));
4422
+ if (_optionalChain([filters, 'optionalAccess', _87 => _87.allowedRoles]) && filters.allowedRoles.length > 0) {
4423
+ const allowed = filters.allowedRoles;
4424
+ const hasMatchingRole = roles.some((r) => allowed.includes(r.name));
4425
+ if (!hasMatchingRole) continue;
4426
+ }
4427
+ results.push({ ...profile, roles });
4428
+ }
4429
+ return Promise.resolve(results);
4345
4430
  },
4346
4431
  updateLastLogin(id) {
4347
4432
  const profile = stores.userProfiles.get(id);
@@ -4360,7 +4445,6 @@ function createMockUserProfilesRepository(stores) {
4360
4445
  email: data.email,
4361
4446
  firstName: data.firstName,
4362
4447
  lastName: data.lastName,
4363
- role: _nullishCoalesce(data.role, () => ( "member")),
4364
4448
  status: "pending",
4365
4449
  createdAt: /* @__PURE__ */ new Date(),
4366
4450
  updatedAt: /* @__PURE__ */ new Date()
@@ -4419,7 +4503,7 @@ function createMockPermissionsRepository(stores) {
4419
4503
  },
4420
4504
  deleteRole(roleId) {
4421
4505
  const role = stores.roles.get(roleId);
4422
- if (_optionalChain([role, 'optionalAccess', _87 => _87.system])) {
4506
+ if (_optionalChain([role, 'optionalAccess', _88 => _88.system])) {
4423
4507
  return Promise.reject(new Error(`Cannot delete system role ${roleId}`));
4424
4508
  }
4425
4509
  stores.roles.delete(roleId);
@@ -4452,7 +4536,6 @@ function createMockPermissionsRepository(stores) {
4452
4536
  scope: input.scope,
4453
4537
  target: input.target,
4454
4538
  actions: input.actions,
4455
- filter: input.filter,
4456
4539
  createdAt: /* @__PURE__ */ new Date()
4457
4540
  };
4458
4541
  stores.permissions.set(perm.id, perm);
@@ -4497,7 +4580,7 @@ function createMockPermissionsRepository(stores) {
4497
4580
  const tenantId = getTenantId();
4498
4581
  const userRoleIds = Array.from(stores.userRoles.values()).filter((ur) => ur.userProfileId === userProfileId && ur.tenantId === tenantId).map((ur) => ur.roleId);
4499
4582
  const userRoles = Array.from(stores.roles.values()).filter((r) => userRoleIds.includes(r.id));
4500
- const isAdmin = userRoles.some((r) => r.name === "admin");
4583
+ const hasAdmin = userRoles.some((r) => _chunkJZO52C3Fjs.isAdminRole.call(void 0, r.name));
4501
4584
  const userPermissions = Array.from(stores.permissions.values()).filter(
4502
4585
  (p) => userRoleIds.includes(p.roleId)
4503
4586
  );
@@ -4524,7 +4607,18 @@ function createMockPermissionsRepository(stores) {
4524
4607
  }
4525
4608
  }
4526
4609
  }
4527
- return Promise.resolve({ isAdmin, objectPermissions, systemPermissions });
4610
+ return Promise.resolve({ isAdmin: hasAdmin, objectPermissions, systemPermissions });
4611
+ },
4612
+ countUsersWithRole(roleName) {
4613
+ const tenantId = getTenantId();
4614
+ const role = Array.from(stores.roles.values()).find(
4615
+ (r) => r.tenantId === tenantId && r.name === roleName
4616
+ );
4617
+ if (!role) return Promise.resolve(0);
4618
+ const userIds = new Set(
4619
+ Array.from(stores.userRoles.values()).filter((ur) => ur.roleId === role.id && ur.tenantId === tenantId).map((ur) => ur.userProfileId)
4620
+ );
4621
+ return Promise.resolve(userIds.size);
4528
4622
  }
4529
4623
  };
4530
4624
  }
@@ -4847,6 +4941,10 @@ function createMockWorkflowsRepository(stores) {
4847
4941
  if (!existing) {
4848
4942
  return Promise.reject(new Error(`Workflow ${id} not found`));
4849
4943
  }
4944
+ const tenantId = getTenantId();
4945
+ if (existing.tenant_id !== tenantId && !existing.system) {
4946
+ return Promise.reject(new Error(`Workflow ${id} not found`));
4947
+ }
4850
4948
  const updated = {
4851
4949
  ...existing,
4852
4950
  label: _nullishCoalesce(data.label, () => ( existing.label)),
@@ -4867,6 +4965,13 @@ function createMockWorkflowsRepository(stores) {
4867
4965
  return Promise.resolve(updated);
4868
4966
  },
4869
4967
  delete(id) {
4968
+ const existing = stores.workflows.get(id);
4969
+ if (existing) {
4970
+ const tenantId = getTenantId();
4971
+ if (existing.tenant_id !== tenantId && !existing.system) {
4972
+ return Promise.reject(new Error(`Workflow ${id} not found`));
4973
+ }
4974
+ }
4870
4975
  stores.workflows.delete(id);
4871
4976
  return Promise.resolve();
4872
4977
  },
@@ -4908,7 +5013,7 @@ function createMockWorkflowInstancesRepository(stores) {
4908
5013
  (i) => i.tenant_id === tenantId
4909
5014
  );
4910
5015
  const total = results.length;
4911
- if (_optionalChain([options, 'optionalAccess', _88 => _88.limit])) {
5016
+ if (_optionalChain([options, 'optionalAccess', _89 => _89.limit])) {
4912
5017
  results = results.slice(_nullishCoalesce(options.offset, () => ( 0)), (_nullishCoalesce(options.offset, () => ( 0))) + options.limit);
4913
5018
  }
4914
5019
  return Promise.resolve({ instances: results, total });
@@ -4936,7 +5041,7 @@ function createMockWorkflowInstancesRepository(stores) {
4936
5041
  pending_action: _nullishCoalesce(data.pendingAction, () => ( null)),
4937
5042
  error: null,
4938
5043
  started_by: data.startedBy,
4939
- expires_at: _nullishCoalesce(_optionalChain([data, 'access', _89 => _89.expiresAt, 'optionalAccess', _90 => _90.toISOString, 'call', _91 => _91()]), () => ( null)),
5044
+ expires_at: _nullishCoalesce(_optionalChain([data, 'access', _90 => _90.expiresAt, 'optionalAccess', _91 => _91.toISOString, 'call', _92 => _92()]), () => ( null)),
4940
5045
  created_at: now,
4941
5046
  updated_at: now,
4942
5047
  completed_at: null
@@ -4949,6 +5054,10 @@ function createMockWorkflowInstancesRepository(stores) {
4949
5054
  if (!existing) {
4950
5055
  return Promise.reject(new Error(`WorkflowInstance ${id} not found`));
4951
5056
  }
5057
+ const tenantId = getTenantId();
5058
+ if (existing.tenant_id !== tenantId) {
5059
+ return Promise.reject(new Error(`WorkflowInstance ${id} not found`));
5060
+ }
4952
5061
  const updated = {
4953
5062
  ...existing,
4954
5063
  status: _nullishCoalesce(data.status, () => ( existing.status)),
@@ -4957,8 +5066,8 @@ function createMockWorkflowInstancesRepository(stores) {
4957
5066
  history: _nullishCoalesce(data.history, () => ( existing.history)),
4958
5067
  pending_action: data.pendingAction !== void 0 ? data.pendingAction : existing.pending_action,
4959
5068
  error: data.error !== void 0 ? data.error : existing.error,
4960
- expires_at: data.expiresAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _92 => _92.expiresAt, 'optionalAccess', _93 => _93.toISOString, 'call', _94 => _94()]), () => ( null)) : existing.expires_at,
4961
- completed_at: data.completedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _95 => _95.completedAt, 'optionalAccess', _96 => _96.toISOString, 'call', _97 => _97()]), () => ( null)) : existing.completed_at,
5069
+ expires_at: data.expiresAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _93 => _93.expiresAt, 'optionalAccess', _94 => _94.toISOString, 'call', _95 => _95()]), () => ( null)) : existing.expires_at,
5070
+ completed_at: data.completedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _96 => _96.completedAt, 'optionalAccess', _97 => _97.toISOString, 'call', _98 => _98()]), () => ( null)) : existing.completed_at,
4962
5071
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
4963
5072
  };
4964
5073
  stores.workflowInstances.set(id, updated);
@@ -4991,7 +5100,7 @@ function createMockWorkflowInstancesRepository(stores) {
4991
5100
  pending_action: _nullishCoalesce(data.pendingAction, () => ( null)),
4992
5101
  error: null,
4993
5102
  started_by: data.startedBy,
4994
- expires_at: _nullishCoalesce(_optionalChain([data, 'access', _98 => _98.expiresAt, 'optionalAccess', _99 => _99.toISOString, 'call', _100 => _100()]), () => ( null)),
5103
+ expires_at: _nullishCoalesce(_optionalChain([data, 'access', _99 => _99.expiresAt, 'optionalAccess', _100 => _100.toISOString, 'call', _101 => _101()]), () => ( null)),
4995
5104
  created_at: now,
4996
5105
  updated_at: now,
4997
5106
  completed_at: null
@@ -5014,13 +5123,13 @@ function createMockWorkflowInstancesRepository(stores) {
5014
5123
  return slotData.id === recordId;
5015
5124
  });
5016
5125
  });
5017
- if (_optionalChain([options, 'optionalAccess', _101 => _101.status])) {
5126
+ if (_optionalChain([options, 'optionalAccess', _102 => _102.status])) {
5018
5127
  results = results.filter((i) => i.status === options.status);
5019
5128
  }
5020
5129
  const total = results.length;
5021
- if (_optionalChain([options, 'optionalAccess', _102 => _102.offset]) !== void 0 || _optionalChain([options, 'optionalAccess', _103 => _103.limit]) !== void 0) {
5022
- const start = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _104 => _104.offset]), () => ( 0));
5023
- const end = _optionalChain([options, 'optionalAccess', _105 => _105.limit]) ? start + options.limit : void 0;
5130
+ if (_optionalChain([options, 'optionalAccess', _103 => _103.offset]) !== void 0 || _optionalChain([options, 'optionalAccess', _104 => _104.limit]) !== void 0) {
5131
+ const start = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _105 => _105.offset]), () => ( 0));
5132
+ const end = _optionalChain([options, 'optionalAccess', _106 => _106.limit]) ? start + options.limit : void 0;
5024
5133
  results = results.slice(start, end);
5025
5134
  }
5026
5135
  return Promise.resolve({ instances: results, total });
@@ -5073,10 +5182,14 @@ function createMockWorkflowInvitationsRepository(stores) {
5073
5182
  if (!existing) {
5074
5183
  return Promise.reject(new Error(`WorkflowInvitation ${id} not found`));
5075
5184
  }
5185
+ const tenantId = getTenantId();
5186
+ if (existing.tenant_id !== tenantId) {
5187
+ return Promise.reject(new Error(`WorkflowInvitation ${id} not found`));
5188
+ }
5076
5189
  const updated = {
5077
5190
  ...existing,
5078
5191
  status: _nullishCoalesce(data.status, () => ( existing.status)),
5079
- accepted_at: data.acceptedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _106 => _106.acceptedAt, 'optionalAccess', _107 => _107.toISOString, 'call', _108 => _108()]), () => ( null)) : existing.accepted_at,
5192
+ accepted_at: data.acceptedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _107 => _107.acceptedAt, 'optionalAccess', _108 => _108.toISOString, 'call', _109 => _109()]), () => ( null)) : existing.accepted_at,
5080
5193
  expires_at: data.expiresAt !== void 0 ? data.expiresAt.toISOString() : existing.expires_at
5081
5194
  };
5082
5195
  stores.workflowInvitations.set(id, updated);
@@ -5138,11 +5251,15 @@ function createMockWorkflowAccessGrantsRepository(stores) {
5138
5251
  if (!existing) {
5139
5252
  return Promise.reject(new Error(`WorkflowAccessGrant ${id} not found`));
5140
5253
  }
5254
+ const tenantId = getTenantId();
5255
+ if (existing.tenant_id !== tenantId) {
5256
+ return Promise.reject(new Error(`WorkflowAccessGrant ${id} not found`));
5257
+ }
5141
5258
  const updated = {
5142
5259
  ...existing,
5143
5260
  last_used_at: data.lastUsedAt !== void 0 ? data.lastUsedAt.toISOString() : existing.last_used_at,
5144
5261
  revoked_token_jtis: _nullishCoalesce(data.revokedTokenJtis, () => ( existing.revoked_token_jtis)),
5145
- revoked_at: data.revokedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _109 => _109.revokedAt, 'optionalAccess', _110 => _110.toISOString, 'call', _111 => _111()]), () => ( null)) : existing.revoked_at
5262
+ revoked_at: data.revokedAt !== void 0 ? _nullishCoalesce(_optionalChain([data, 'access', _110 => _110.revokedAt, 'optionalAccess', _111 => _111.toISOString, 'call', _112 => _112()]), () => ( null)) : existing.revoked_at
5146
5263
  };
5147
5264
  stores.workflowAccessGrants.set(id, updated);
5148
5265
  return Promise.resolve(updated);
@@ -5271,6 +5388,20 @@ var PolicyRegistry = class {
5271
5388
  };
5272
5389
  var defaultPolicyRegistry = new PolicyRegistry();
5273
5390
 
5391
+ // src/runtime/search.ts
5392
+ var SORTABLE_ATTRIBUTE_TYPES = /* @__PURE__ */ new Set([
5393
+ "text",
5394
+ "textarea",
5395
+ "number",
5396
+ "date",
5397
+ "select",
5398
+ "status",
5399
+ "multiselect",
5400
+ "checkbox",
5401
+ "rating",
5402
+ "currency"
5403
+ ]);
5404
+
5274
5405
  // src/runtime/services/base.service.ts
5275
5406
  var BaseService = class {
5276
5407
  constructor(adapter) {
@@ -5351,7 +5482,7 @@ var BaseService = class {
5351
5482
  * @param key - Cache key to invalidate
5352
5483
  */
5353
5484
  async invalidateCache(key) {
5354
- await _optionalChain([this, 'access', _112 => _112.cache, 'optionalAccess', _113 => _113.delete, 'call', _114 => _114(key)]);
5485
+ await _optionalChain([this, 'access', _113 => _113.cache, 'optionalAccess', _114 => _114.delete, 'call', _115 => _115(key)]);
5355
5486
  }
5356
5487
  /**
5357
5488
  * Invalidate all cache keys matching a pattern.
@@ -5359,7 +5490,7 @@ var BaseService = class {
5359
5490
  * @param pattern - Glob-style pattern (e.g., "schema:tenant-123:*")
5360
5491
  */
5361
5492
  async invalidateCachePattern(pattern) {
5362
- await _optionalChain([this, 'access', _115 => _115.cache, 'optionalAccess', _116 => _116.deletePattern, 'call', _117 => _117(pattern)]);
5493
+ await _optionalChain([this, 'access', _116 => _116.cache, 'optionalAccess', _117 => _117.deletePattern, 'call', _118 => _118(pattern)]);
5363
5494
  }
5364
5495
  /**
5365
5496
  * Invalidate all cached lists for a resource.
@@ -5490,6 +5621,15 @@ function isBilateralRelation(attr) {
5490
5621
  function inferInverseCardinality(cardinality) {
5491
5622
  return cardinality === "one" ? "many" : "many";
5492
5623
  }
5624
+ var NON_SORTABLE_TYPES = /* @__PURE__ */ new Set([
5625
+ "richtext",
5626
+ "file",
5627
+ "document",
5628
+ "location"
5629
+ ]);
5630
+ function isAttributeSortable(attr) {
5631
+ return !NON_SORTABLE_TYPES.has(attr.type);
5632
+ }
5493
5633
 
5494
5634
  // src/types/relation-properties.ts
5495
5635
  var FORBIDDEN_PROPERTY_TYPES = [
@@ -5574,17 +5714,17 @@ function validateOptions(options, attributeName) {
5574
5714
  const ids = /* @__PURE__ */ new Set();
5575
5715
  const values = /* @__PURE__ */ new Set();
5576
5716
  for (const option of options) {
5577
- if (!_optionalChain([option, 'access', _118 => _118.id, 'optionalAccess', _119 => _119.trim, 'call', _120 => _120()])) {
5717
+ if (!_optionalChain([option, 'access', _119 => _119.id, 'optionalAccess', _120 => _120.trim, 'call', _121 => _121()])) {
5578
5718
  throw new Error(
5579
5719
  `[AttributeBuilder] Option in "${attributeName}" has an empty or missing id.`
5580
5720
  );
5581
5721
  }
5582
- if (!_optionalChain([option, 'access', _121 => _121.value, 'optionalAccess', _122 => _122.trim, 'call', _123 => _123()])) {
5722
+ if (!_optionalChain([option, 'access', _122 => _122.value, 'optionalAccess', _123 => _123.trim, 'call', _124 => _124()])) {
5583
5723
  throw new Error(
5584
5724
  `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing value.`
5585
5725
  );
5586
5726
  }
5587
- if (!_optionalChain([option, 'access', _124 => _124.label, 'optionalAccess', _125 => _125.trim, 'call', _126 => _126()])) {
5727
+ if (!_optionalChain([option, 'access', _125 => _125.label, 'optionalAccess', _126 => _126.trim, 'call', _127 => _127()])) {
5588
5728
  throw new Error(
5589
5729
  `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing label.`
5590
5730
  );
@@ -5682,8 +5822,8 @@ var BaseAttributeBuilder = class {
5682
5822
  featureGate(flagName, options) {
5683
5823
  this.attr.featureGate = {
5684
5824
  flag: flagName,
5685
- expectedValue: _optionalChain([options, 'optionalAccess', _127 => _127.expectedValue]),
5686
- fallback: _optionalChain([options, 'optionalAccess', _128 => _128.fallback])
5825
+ expectedValue: _optionalChain([options, 'optionalAccess', _128 => _128.expectedValue]),
5826
+ fallback: _optionalChain([options, 'optionalAccess', _129 => _129.fallback])
5687
5827
  };
5688
5828
  return this;
5689
5829
  }
@@ -6126,7 +6266,7 @@ var BaseRelationAttributeBuilder = class extends BaseAttributeBuilder {
6126
6266
  object: objectName,
6127
6267
  ...options
6128
6268
  };
6129
- _optionalChain([this, 'access', _129 => _129.attr, 'access', _130 => _130.targets, 'optionalAccess', _131 => _131.push, 'call', _132 => _132(target)]);
6269
+ _optionalChain([this, 'access', _130 => _130.attr, 'access', _131 => _131.targets, 'optionalAccess', _132 => _132.push, 'call', _133 => _133(target)]);
6130
6270
  return this;
6131
6271
  }
6132
6272
  /**
@@ -6209,6 +6349,20 @@ var SingleRelationAttributeBuilder = class extends BaseRelationAttributeBuilder
6209
6349
  isRequired: this.attr.required
6210
6350
  }
6211
6351
  );
6352
+ if (this.attr.system) multiBuilder.system();
6353
+ if (this.attr.hidden) multiBuilder.hidden();
6354
+ if (this.attr.disabled) multiBuilder.disabled();
6355
+ if (this.attr.placeholder) multiBuilder.placeholder(this.attr.placeholder);
6356
+ if (this.attr.description) multiBuilder.description(this.attr.description);
6357
+ if (this.attr.icon) multiBuilder.icon(this.attr.icon);
6358
+ if (this.attr.order !== void 0) multiBuilder.order(this.attr.order);
6359
+ if (this.attr.metadata) multiBuilder.metadata(this.attr.metadata);
6360
+ if (this.attr.featureGate) {
6361
+ multiBuilder.featureGate(this.attr.featureGate.flag, {
6362
+ expectedValue: this.attr.featureGate.expectedValue,
6363
+ fallback: this.attr.featureGate.fallback
6364
+ });
6365
+ }
6212
6366
  return multiBuilder;
6213
6367
  }
6214
6368
  required() {
@@ -6224,9 +6378,9 @@ var MultiRelationAttributeBuilder = class extends BaseRelationAttributeBuilder {
6224
6378
  constructor(name, label, initOptions) {
6225
6379
  super("relation", name, label);
6226
6380
  this.attr.cardinality = "many";
6227
- this.attr.targets = _nullishCoalesce(_optionalChain([initOptions, 'optionalAccess', _133 => _133.targets]), () => ( []));
6381
+ this.attr.targets = _nullishCoalesce(_optionalChain([initOptions, 'optionalAccess', _134 => _134.targets]), () => ( []));
6228
6382
  this.attr.defaultValue = [];
6229
- if (_optionalChain([initOptions, 'optionalAccess', _134 => _134.isRequired])) {
6383
+ if (_optionalChain([initOptions, 'optionalAccess', _135 => _135.isRequired])) {
6230
6384
  this.setRequired(true);
6231
6385
  }
6232
6386
  }
@@ -6449,6 +6603,13 @@ var DocumentAttributeBuilder = class extends BaseAttributeBuilder {
6449
6603
  this.setRequired(true);
6450
6604
  return this;
6451
6605
  }
6606
+ /**
6607
+ * Mark this attribute as optional (undo required).
6608
+ */
6609
+ optional() {
6610
+ this.setRequired(false);
6611
+ return this;
6612
+ }
6452
6613
  };
6453
6614
  function document(config) {
6454
6615
  return new DocumentAttributeBuilder(config.name, config.label);
@@ -6667,7 +6828,7 @@ var GroupBuilder = class {
6667
6828
  */
6668
6829
  fields(...names) {
6669
6830
  for (const name of names) {
6670
- _optionalChain([this, 'access', _135 => _135.data, 'access', _136 => _136.fields, 'optionalAccess', _137 => _137.push, 'call', _138 => _138({ attribute: name })]);
6831
+ _optionalChain([this, 'access', _136 => _136.data, 'access', _137 => _137.fields, 'optionalAccess', _138 => _138.push, 'call', _139 => _139({ attribute: name })]);
6671
6832
  }
6672
6833
  return this;
6673
6834
  }
@@ -6676,7 +6837,7 @@ var GroupBuilder = class {
6676
6837
  * @example .field("name", { span: 8, readOnly: true })
6677
6838
  */
6678
6839
  field(attribute, options) {
6679
- _optionalChain([this, 'access', _139 => _139.data, 'access', _140 => _140.fields, 'optionalAccess', _141 => _141.push, 'call', _142 => _142({ attribute, ...options })]);
6840
+ _optionalChain([this, 'access', _140 => _140.data, 'access', _141 => _141.fields, 'optionalAccess', _142 => _142.push, 'call', _143 => _143({ attribute, ...options })]);
6680
6841
  return this;
6681
6842
  }
6682
6843
  /**
@@ -6685,7 +6846,7 @@ var GroupBuilder = class {
6685
6846
  * @example .attributeGroup({ id: "address", label: "Address", attributes: ["street", "city", "postal_code"], displayTemplate: "{street}, {city}" })
6686
6847
  */
6687
6848
  attributeGroup(config, options) {
6688
- _optionalChain([this, 'access', _143 => _143.data, 'access', _144 => _144.fields, 'optionalAccess', _145 => _145.push, 'call', _146 => _146({ attributeGroup: config, ...options })]);
6849
+ _optionalChain([this, 'access', _144 => _144.data, 'access', _145 => _145.fields, 'optionalAccess', _146 => _146.push, 'call', _147 => _147({ attributeGroup: config, ...options })]);
6689
6850
  return this;
6690
6851
  }
6691
6852
  /**
@@ -7753,8 +7914,8 @@ var WorkflowFormRowBuilder = class {
7753
7914
  id: `${this.rowData.id}-${slotId}-${attribute}`,
7754
7915
  slotId,
7755
7916
  attribute,
7756
- label: _optionalChain([options, 'optionalAccess', _147 => _147.label]),
7757
- required: _optionalChain([options, 'optionalAccess', _148 => _148.required])
7917
+ label: _optionalChain([options, 'optionalAccess', _148 => _148.label]),
7918
+ required: _optionalChain([options, 'optionalAccess', _149 => _149.required])
7758
7919
  };
7759
7920
  this.rowData.fields.push(field);
7760
7921
  return this;
@@ -8045,7 +8206,7 @@ var WorkflowBuilder = class {
8045
8206
  * @param options - Slot configuration
8046
8207
  */
8047
8208
  slot(id, objectName, options) {
8048
- if (_optionalChain([this, 'access', _149 => _149.data, 'access', _150 => _150.slots, 'optionalAccess', _151 => _151.some, 'call', _152 => _152((s) => s.id === id)])) {
8209
+ if (_optionalChain([this, 'access', _150 => _150.data, 'access', _151 => _151.slots, 'optionalAccess', _152 => _152.some, 'call', _153 => _153((s) => s.id === id)])) {
8049
8210
  throw new Error(`[WorkflowBuilder] Duplicate slot id: "${id}"`);
8050
8211
  }
8051
8212
  const slot = {
@@ -8056,7 +8217,7 @@ var WorkflowBuilder = class {
8056
8217
  color: options.color,
8057
8218
  icon: options.icon
8058
8219
  };
8059
- _optionalChain([this, 'access', _153 => _153.data, 'access', _154 => _154.slots, 'optionalAccess', _155 => _155.push, 'call', _156 => _156(slot)]);
8220
+ _optionalChain([this, 'access', _154 => _154.data, 'access', _155 => _155.slots, 'optionalAccess', _156 => _156.push, 'call', _157 => _157(slot)]);
8060
8221
  return this;
8061
8222
  }
8062
8223
  // ============================================================================
@@ -8188,7 +8349,7 @@ var WorkflowBuilder = class {
8188
8349
  }
8189
8350
  }
8190
8351
  validateSlotReferences() {
8191
- const slotIds = _nullishCoalesce(_optionalChain([this, 'access', _157 => _157.data, 'access', _158 => _158.slots, 'optionalAccess', _159 => _159.reduce, 'call', _160 => _160((set, s) => set.add(s.id), /* @__PURE__ */ new Set())]), () => ( /* @__PURE__ */ new Set()));
8352
+ const slotIds = _nullishCoalesce(_optionalChain([this, 'access', _158 => _158.data, 'access', _159 => _159.slots, 'optionalAccess', _160 => _160.reduce, 'call', _161 => _161((set, s) => set.add(s.id), /* @__PURE__ */ new Set())]), () => ( /* @__PURE__ */ new Set()));
8192
8353
  for (const node of Object.values(_nullishCoalesce(this.data.nodes, () => ( {})))) {
8193
8354
  if (node.type === "form") {
8194
8355
  const referencedSlots = /* @__PURE__ */ new Set();
@@ -8506,7 +8667,7 @@ var ObjectSchemaService = class extends BaseService {
8506
8667
  constructor(adapter, nativeRegistry, options) {
8507
8668
  super(adapter);
8508
8669
  this.nativeRegistry = nativeRegistry;
8509
- this.auditService = _optionalChain([options, 'optionalAccess', _161 => _161.auditService]);
8670
+ this.auditService = _optionalChain([options, 'optionalAccess', _162 => _162.auditService]);
8510
8671
  this.bilateralValidationService = new BilateralValidationService(adapter, this);
8511
8672
  }
8512
8673
  /**
@@ -8749,7 +8910,7 @@ var ObjectSchemaService = class extends BaseService {
8749
8910
  resourceType: "attribute",
8750
8911
  resourceId: attributeId,
8751
8912
  resourceLabel: updatedDbAttr.label,
8752
- objectName: _optionalChain([dbObject, 'optionalAccess', _162 => _162.name]),
8913
+ objectName: _optionalChain([dbObject, 'optionalAccess', _163 => _163.name]),
8753
8914
  objectId: dbAttr.objectId,
8754
8915
  changes
8755
8916
  });
@@ -8782,7 +8943,7 @@ var ObjectSchemaService = class extends BaseService {
8782
8943
  );
8783
8944
  }
8784
8945
  const dbObject = await this.adapter.objects.findById(dbAttr.objectId);
8785
- if (_optionalChain([dbObject, 'optionalAccess', _163 => _163.labelExpression])) {
8946
+ if (_optionalChain([dbObject, 'optionalAccess', _164 => _164.labelExpression])) {
8786
8947
  const usedAttributes = extractAttributeNames(dbObject.labelExpression);
8787
8948
  if (usedAttributes.includes(dbAttr.name)) {
8788
8949
  throw new AttributeInUseError(dbAttr.name, "labelExpression");
@@ -8798,7 +8959,7 @@ var ObjectSchemaService = class extends BaseService {
8798
8959
  resourceType: "attribute",
8799
8960
  resourceId: attributeId,
8800
8961
  resourceLabel: dbAttr.label,
8801
- objectName: _optionalChain([dbObject, 'optionalAccess', _164 => _164.name]),
8962
+ objectName: _optionalChain([dbObject, 'optionalAccess', _165 => _165.name]),
8802
8963
  objectId: dbAttr.objectId
8803
8964
  });
8804
8965
  }
@@ -8813,9 +8974,9 @@ var ObjectSchemaService = class extends BaseService {
8813
8974
  async listAttributes(objectId, options) {
8814
8975
  const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
8815
8976
  let filtered = dbAttributes;
8816
- if (_optionalChain([options, 'optionalAccess', _165 => _165.systemOnly])) {
8977
+ if (_optionalChain([options, 'optionalAccess', _166 => _166.systemOnly])) {
8817
8978
  filtered = dbAttributes.filter((attr) => attr.system);
8818
- } else if (_optionalChain([options, 'optionalAccess', _166 => _166.customOnly])) {
8979
+ } else if (_optionalChain([options, 'optionalAccess', _167 => _167.customOnly])) {
8819
8980
  filtered = dbAttributes.filter((attr) => !attr.system);
8820
8981
  }
8821
8982
  return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
@@ -8851,14 +9012,14 @@ var ObjectSchemaService = class extends BaseService {
8851
9012
  pluralLabel: dbObject.pluralLabel,
8852
9013
  description: dbObject.description,
8853
9014
  labelExpression: dbObject.labelExpression,
8854
- icon: _optionalChain([dbObject, 'access', _167 => _167.metadata, 'optionalAccess', _168 => _168.icon])
9015
+ icon: _optionalChain([dbObject, 'access', _168 => _168.metadata, 'optionalAccess', _169 => _169.icon])
8855
9016
  };
8856
9017
  let metadata = dbObject.metadata;
8857
9018
  if (updates.icon !== void 0 || updates.metadata !== void 0) {
8858
9019
  metadata = {
8859
9020
  ...dbObject.metadata,
8860
9021
  ...updates.metadata,
8861
- icon: _nullishCoalesce(updates.icon, () => ( _optionalChain([dbObject, 'access', _169 => _169.metadata, 'optionalAccess', _170 => _170.icon])))
9022
+ icon: _nullishCoalesce(updates.icon, () => ( _optionalChain([dbObject, 'access', _170 => _170.metadata, 'optionalAccess', _171 => _171.icon])))
8862
9023
  };
8863
9024
  }
8864
9025
  const updatedDbObject = await this.adapter.objects.update(objectId, {
@@ -8901,6 +9062,19 @@ var ObjectSchemaService = class extends BaseService {
8901
9062
  });
8902
9063
  });
8903
9064
  await this.invalidateCachePattern(cacheKeys.allResolvedRelations(this.tenantId));
9065
+ if (this.adapter.search) {
9066
+ const { records } = await this.adapter.objectRecords.list(objectId, { limit: 1e4 });
9067
+ this.adapter.search.bulkIndex(
9068
+ records.map((r) => ({
9069
+ record: r,
9070
+ objectName: updatedDbObject.name,
9071
+ objectLabel: updatedDbObject.label,
9072
+ attributes
9073
+ }))
9074
+ ).catch(
9075
+ (err) => console.error("[search] Bulk re-index after label refresh failed", objectId, err)
9076
+ );
9077
+ }
8904
9078
  }
8905
9079
  return this.convertDBObjectToDefinition(updatedDbObject, dbAttributes);
8906
9080
  }
@@ -9101,7 +9275,7 @@ Reserved names: ${RESERVED_ATTRIBUTE_NAMES.join(", ")}`
9101
9275
  let properties = inverseDbAttr.config.properties;
9102
9276
  if (!properties) {
9103
9277
  const nativeObj = this.nativeRegistry.getByName(bilateral.object);
9104
- const nativeAttr = _optionalChain([nativeObj, 'optionalAccess', _171 => _171.attributes, 'access', _172 => _172.find, 'call', _173 => _173((a) => a.name === bilateral.attribute)]);
9278
+ const nativeAttr = _optionalChain([nativeObj, 'optionalAccess', _172 => _172.attributes, 'access', _173 => _173.find, 'call', _174 => _174((a) => a.name === bilateral.attribute)]);
9105
9279
  if (nativeAttr && "properties" in nativeAttr) {
9106
9280
  properties = nativeAttr.properties;
9107
9281
  }
@@ -9190,7 +9364,7 @@ Reserved names: ${RESERVED_ATTRIBUTE_NAMES.join(", ")}`
9190
9364
  label: dbObject.label,
9191
9365
  pluralLabel: dbObject.pluralLabel,
9192
9366
  description: dbObject.description,
9193
- icon: _optionalChain([dbObject, 'access', _174 => _174.metadata, 'optionalAccess', _175 => _175.icon]),
9367
+ icon: _optionalChain([dbObject, 'access', _175 => _175.metadata, 'optionalAccess', _176 => _176.icon]),
9194
9368
  labelExpression: dbObject.labelExpression,
9195
9369
  attributes,
9196
9370
  system: dbObject.system,
@@ -9290,7 +9464,7 @@ Reserved names: ${RESERVED_ATTRIBUTE_NAMES.join(", ")}`
9290
9464
  const hasRelationToTarget = attrs.some((attr) => {
9291
9465
  if (attr.type !== "relation") return false;
9292
9466
  const config = attr.config;
9293
- return _nullishCoalesce(_optionalChain([config, 'optionalAccess', _176 => _176.targets, 'optionalAccess', _177 => _177.some, 'call', _178 => _178((t) => t.object === targetObjectName)]), () => ( false));
9467
+ return _nullishCoalesce(_optionalChain([config, 'optionalAccess', _177 => _177.targets, 'optionalAccess', _178 => _178.some, 'call', _179 => _179((t) => t.object === targetObjectName)]), () => ( false));
9294
9468
  });
9295
9469
  if (hasRelationToTarget) {
9296
9470
  referencing.push(obj.name);
@@ -9368,7 +9542,7 @@ Native objects must have system=true. Did you forget to call .system() in your b
9368
9542
  const existing = this.objects.get(object2.name);
9369
9543
  throw new Error(
9370
9544
  `[NativeObjectRegistry] Duplicate object name "${object2.name}":
9371
- - Existing: "${_optionalChain([existing, 'optionalAccess', _179 => _179.label])}" (id: ${_optionalChain([existing, 'optionalAccess', _180 => _180.id])})
9545
+ - Existing: "${_optionalChain([existing, 'optionalAccess', _180 => _180.label])}" (id: ${_optionalChain([existing, 'optionalAccess', _181 => _181.id])})
9372
9546
  - New: "${object2.label}" (id: ${object2.id})
9373
9547
  Please use unique names for each native object.`
9374
9548
  );
@@ -9485,7 +9659,7 @@ var AuditService = class extends BaseService {
9485
9659
  this.isFlushing = false;
9486
9660
  /** Pending flush promise to allow waiting on concurrent flush */
9487
9661
  this.flushPromise = null;
9488
- if (_optionalChain([options, 'optionalAccess', _181 => _181.async]) && options.flushIntervalMs) {
9662
+ if (_optionalChain([options, 'optionalAccess', _182 => _182.async]) && options.flushIntervalMs) {
9489
9663
  this.startFlushTimer();
9490
9664
  }
9491
9665
  }
@@ -9682,7 +9856,7 @@ var AuditService = class extends BaseService {
9682
9856
  if (!this.adapter.audit) {
9683
9857
  return;
9684
9858
  }
9685
- if (_optionalChain([this, 'access', _182 => _182.options, 'optionalAccess', _183 => _183.async])) {
9859
+ if (_optionalChain([this, 'access', _183 => _183.options, 'optionalAccess', _184 => _184.async])) {
9686
9860
  this.buffer.push(entry);
9687
9861
  const batchSize = _nullishCoalesce(this.options.batchSize, () => ( 10));
9688
9862
  if (this.buffer.length >= batchSize) {
@@ -9696,7 +9870,7 @@ var AuditService = class extends BaseService {
9696
9870
  * Start the flush timer for async mode
9697
9871
  */
9698
9872
  startFlushTimer() {
9699
- const intervalMs = _nullishCoalesce(_optionalChain([this, 'access', _184 => _184.options, 'optionalAccess', _185 => _185.flushIntervalMs]), () => ( 1e3));
9873
+ const intervalMs = _nullishCoalesce(_optionalChain([this, 'access', _185 => _185.options, 'optionalAccess', _186 => _186.flushIntervalMs]), () => ( 1e3));
9700
9874
  this.flushTimer = setInterval(() => {
9701
9875
  this.flush().catch(() => {
9702
9876
  });
@@ -9726,7 +9900,7 @@ var browserStub4 = {
9726
9900
  run: (_store, callback) => callback()
9727
9901
  };
9728
9902
  var AsyncLocalStorageClass4 = null;
9729
- if (typeof process !== "undefined" && _optionalChain([process, 'access', _186 => _186.versions, 'optionalAccess', _187 => _187.node])) {
9903
+ if (typeof process !== "undefined" && _optionalChain([process, 'access', _187 => _187.versions, 'optionalAccess', _188 => _188.node])) {
9730
9904
  try {
9731
9905
  if (typeof _chunk3RG5ZIWIjs.__require !== "undefined") {
9732
9906
  const asyncHooks = _chunk3RG5ZIWIjs.__require.call(void 0, "async_hooks");
@@ -9785,7 +9959,7 @@ var BilateralSyncService = class extends BaseService {
9785
9959
  }
9786
9960
  const ctx = getSyncContext().getStore();
9787
9961
  const syncKey = `${sourceSchema.name}:${sourceRecordId}:${attributeName}`;
9788
- if (_optionalChain([ctx, 'optionalAccess', _188 => _188.syncing, 'access', _189 => _189.has, 'call', _190 => _190(syncKey)])) {
9962
+ if (_optionalChain([ctx, 'optionalAccess', _189 => _189.syncing, 'access', _190 => _190.has, 'call', _191 => _191(syncKey)])) {
9789
9963
  return;
9790
9964
  }
9791
9965
  await this.runWithSyncContext(syncKey, async () => {
@@ -10010,7 +10184,7 @@ var BilateralSyncService = class extends BaseService {
10010
10184
  const storage = getSyncContext();
10011
10185
  const existingCtx = storage.getStore();
10012
10186
  const ctx = {
10013
- syncing: new Set(_nullishCoalesce(_optionalChain([existingCtx, 'optionalAccess', _191 => _191.syncing]), () => ( [])))
10187
+ syncing: new Set(_nullishCoalesce(_optionalChain([existingCtx, 'optionalAccess', _192 => _192.syncing]), () => ( [])))
10014
10188
  };
10015
10189
  ctx.syncing.add(syncKey);
10016
10190
  return await storage.run(ctx, fn);
@@ -10072,6 +10246,21 @@ var UserService = class extends BaseService {
10072
10246
  }
10073
10247
  const users = await this.adapter.userProfiles.findByIds([...allIds]);
10074
10248
  const userMap = new Map(users.map((u) => [u.id, u]));
10249
+ const allAllowedRoles = /* @__PURE__ */ new Set();
10250
+ for (const [, { attr }] of attrIdMap) {
10251
+ if (attr.allowedRoles && attr.allowedRoles.length > 0) {
10252
+ for (const role of attr.allowedRoles) {
10253
+ allAllowedRoles.add(role);
10254
+ }
10255
+ }
10256
+ }
10257
+ let userRolesMap;
10258
+ if (allAllowedRoles.size > 0) {
10259
+ const usersWithRoles = await this.adapter.userProfiles.getUsersWithRoles({
10260
+ allowedRoles: [...allAllowedRoles]
10261
+ });
10262
+ userRolesMap = new Map(usersWithRoles.map((u) => [u.id, u.roles.map((r) => r.name)]));
10263
+ }
10075
10264
  for (const [attrName, { attr, ids }] of attrIdMap) {
10076
10265
  const invalidIds = [];
10077
10266
  const roleErrors = [];
@@ -10085,8 +10274,10 @@ var UserService = class extends BaseService {
10085
10274
  invalidIds.push(id);
10086
10275
  continue;
10087
10276
  }
10088
- if (attr.allowedRoles && attr.allowedRoles.length > 0) {
10089
- if (!attr.allowedRoles.includes(user2.role)) {
10277
+ if (attr.allowedRoles && attr.allowedRoles.length > 0 && userRolesMap) {
10278
+ const userRoleNames = _nullishCoalesce(userRolesMap.get(id), () => ( []));
10279
+ const hasAllowedRole = attr.allowedRoles.some((role) => userRoleNames.includes(role));
10280
+ if (!hasAllowedRole) {
10090
10281
  roleErrors.push(id);
10091
10282
  }
10092
10283
  }
@@ -10101,7 +10292,7 @@ var UserService = class extends BaseService {
10101
10292
  if (roleErrors.length > 0) {
10102
10293
  errors.push({
10103
10294
  attribute: attrName,
10104
- message: `Users do not have required role for ${attr.label}. Allowed roles: ${_optionalChain([attr, 'access', _192 => _192.allowedRoles, 'optionalAccess', _193 => _193.join, 'call', _194 => _194(", ")])}`,
10295
+ message: `Users do not have required role for ${attr.label}. Allowed roles: ${_optionalChain([attr, 'access', _193 => _193.allowedRoles, 'optionalAccess', _194 => _194.join, 'call', _195 => _195(", ")])}`,
10105
10296
  invalidIds: roleErrors
10106
10297
  });
10107
10298
  }
@@ -10625,7 +10816,7 @@ var RelationPropertiesService = class extends BaseService {
10625
10816
  }
10626
10817
  }
10627
10818
  }
10628
- const shouldStoreAsInverse = _optionalChain([attribute, 'access', _195 => _195.bilateral, 'optionalAccess', _196 => _196.storageOwner]) === false;
10819
+ const shouldStoreAsInverse = _optionalChain([attribute, 'access', _196 => _196.bilateral, 'optionalAccess', _197 => _197.storageOwner]) === false;
10629
10820
  let storageFromObject = schema.name;
10630
10821
  let storageFromAttribute = attributeName;
10631
10822
  if (shouldStoreAsInverse && attribute.bilateral) {
@@ -10637,7 +10828,7 @@ var RelationPropertiesService = class extends BaseService {
10637
10828
  if (shouldStoreAsInverse) {
10638
10829
  const results = await Promise.all(
10639
10830
  normalized.map(
10640
- (item) => _optionalChain([adapter, 'access', _197 => _197.relationAttributes, 'optionalAccess', _198 => _198.findBySource, 'call', _199 => _199(
10831
+ (item) => _optionalChain([adapter, 'access', _198 => _198.relationAttributes, 'optionalAccess', _199 => _199.findBySource, 'call', _200 => _200(
10641
10832
  storageFromObject,
10642
10833
  item.id,
10643
10834
  storageFromAttribute
@@ -10776,7 +10967,7 @@ var RecordQueryService = class extends BaseService {
10776
10967
  super(adapter);
10777
10968
  this.schemaService = schemaService;
10778
10969
  this.options = options;
10779
- this.policyRegistry = _optionalChain([options, 'optionalAccess', _200 => _200.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _201 => _201.policyRegistry]), () => ( defaultPolicyRegistry));
10970
+ this.policyRegistry = _optionalChain([options, 'optionalAccess', _201 => _201.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _202 => _202.policyRegistry]), () => ( defaultPolicyRegistry));
10780
10971
  this.relationPropertiesService = new RelationPropertiesService(adapter);
10781
10972
  }
10782
10973
  // ============================================================================
@@ -10827,12 +11018,12 @@ var RecordQueryService = class extends BaseService {
10827
11018
  * Internal list query execution
10828
11019
  */
10829
11020
  async executeListQuery(schema, objectId, options) {
10830
- if (_optionalChain([this, 'access', _202 => _202.options, 'optionalAccess', _203 => _203.permissionService]) && this.userId) {
11021
+ if (_optionalChain([this, 'access', _203 => _203.options, 'optionalAccess', _204 => _204.permissionService]) && this.userId) {
10831
11022
  await checkPermission(this.options.permissionService, this.userId, schema.name, "read");
10832
11023
  }
10833
- const policy = _optionalChain([options, 'optionalAccess', _204 => _204.skipPolicyFilter]) ? void 0 : getPolicy(this.policyRegistry, this.userId, schema.name);
11024
+ const policy = _optionalChain([options, 'optionalAccess', _205 => _205.skipPolicyFilter]) ? void 0 : getPolicy(this.policyRegistry, this.userId, schema.name);
10834
11025
  let effectiveOptions = options;
10835
- if (_optionalChain([policy, 'optionalAccess', _205 => _205.applyListFilter]) && this.userId) {
11026
+ if (_optionalChain([policy, 'optionalAccess', _206 => _206.applyListFilter]) && this.userId) {
10836
11027
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
10837
11028
  effectiveOptions = policy.applyListFilter(ctx, options);
10838
11029
  }
@@ -10842,10 +11033,10 @@ var RecordQueryService = class extends BaseService {
10842
11033
  );
10843
11034
  let filteredRecords = result.records;
10844
11035
  let effectiveTotal = result.total;
10845
- if (_optionalChain([policy, 'optionalAccess', _206 => _206.canAccessRecord]) && this.userId) {
11036
+ if (_optionalChain([policy, 'optionalAccess', _207 => _207.canAccessRecord]) && this.userId) {
10846
11037
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
10847
- const requestedLimit = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _207 => _207.limit]), () => ( 20));
10848
- const requestedOffset = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _208 => _208.offset]), () => ( 0));
11038
+ const requestedLimit = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _208 => _208.limit]), () => ( 20));
11039
+ const requestedOffset = _nullishCoalesce(_optionalChain([effectiveOptions, 'optionalAccess', _209 => _209.offset]), () => ( 0));
10849
11040
  const overfetchMultiplier = 5;
10850
11041
  const batchSize = requestedLimit * overfetchMultiplier;
10851
11042
  const maxScanRecords = 1e4;
@@ -10867,7 +11058,7 @@ var RecordQueryService = class extends BaseService {
10867
11058
  exhausted = true;
10868
11059
  break;
10869
11060
  }
10870
- const filtered = batch.records.filter((record) => _optionalChain([policy, 'access', _209 => _209.canAccessRecord, 'optionalCall', _210 => _210(ctx, record)]));
11061
+ const filtered = batch.records.filter((record) => _optionalChain([policy, 'access', _210 => _210.canAccessRecord, 'optionalCall', _211 => _211(ctx, record)]));
10871
11062
  collected.push(...filtered);
10872
11063
  dbOffset += batch.records.length;
10873
11064
  totalScanned += batch.records.length;
@@ -10883,7 +11074,7 @@ var RecordQueryService = class extends BaseService {
10883
11074
  filteredRecords,
10884
11075
  schema
10885
11076
  );
10886
- if (!_optionalChain([options, 'optionalAccess', _211 => _211.skipFormulas])) {
11077
+ if (!_optionalChain([options, 'optionalAccess', _212 => _212.skipFormulas])) {
10887
11078
  return {
10888
11079
  records: enrichRecordsWithFormulas(filteredRecords, schema),
10889
11080
  total: effectiveTotal
@@ -10943,18 +11134,37 @@ var RecordQueryService = class extends BaseService {
10943
11134
  * Internal search query execution
10944
11135
  */
10945
11136
  async executeSearchQuery(schema, objectId, query, options) {
10946
- if (_optionalChain([this, 'access', _212 => _212.options, 'optionalAccess', _213 => _213.permissionService]) && this.userId) {
11137
+ if (_optionalChain([this, 'access', _213 => _213.options, 'optionalAccess', _214 => _214.permissionService]) && this.userId) {
10947
11138
  await checkPermission(this.options.permissionService, this.userId, schema.name, "read");
10948
11139
  }
10949
- const result = await runWithSchemaContext(
10950
- [schema],
10951
- () => this.adapter.objectRecords.search(objectId, query, options)
10952
- );
11140
+ let result;
11141
+ if (this.adapter.search) {
11142
+ try {
11143
+ result = await this.adapter.search.searchRecords(objectId, query, {
11144
+ limit: _optionalChain([options, 'optionalAccess', _215 => _215.limit]),
11145
+ offset: _optionalChain([options, 'optionalAccess', _216 => _216.offset]),
11146
+ sorts: _optionalChain([options, 'optionalAccess', _217 => _217.sorts]),
11147
+ filters: _optionalChain([options, 'optionalAccess', _218 => _218.filters]),
11148
+ attributes: schema.attributes
11149
+ });
11150
+ result = await this.healSearchResults(result);
11151
+ } catch (e15) {
11152
+ result = await runWithSchemaContext(
11153
+ [schema],
11154
+ () => this.adapter.objectRecords.search(objectId, query, options)
11155
+ );
11156
+ }
11157
+ } else {
11158
+ result = await runWithSchemaContext(
11159
+ [schema],
11160
+ () => this.adapter.objectRecords.search(objectId, query, options)
11161
+ );
11162
+ }
10953
11163
  const enrichedRecords = await this.relationPropertiesService.enrichRecordsBatch(
10954
11164
  result.records,
10955
11165
  schema
10956
11166
  );
10957
- if (!_optionalChain([options, 'optionalAccess', _214 => _214.skipFormulas])) {
11167
+ if (!_optionalChain([options, 'optionalAccess', _219 => _219.skipFormulas])) {
10958
11168
  return {
10959
11169
  records: enrichRecordsWithFormulas(enrichedRecords, schema),
10960
11170
  total: result.total
@@ -10965,6 +11175,32 @@ var RecordQueryService = class extends BaseService {
10965
11175
  total: result.total
10966
11176
  };
10967
11177
  }
11178
+ // ==========================================================================
11179
+ // Self-healing: ghost record cleanup
11180
+ // ==========================================================================
11181
+ /**
11182
+ * Verify Meilisearch results against PostgreSQL and remove ghost records.
11183
+ * Fire-and-forget cleanup of records that no longer exist in PG.
11184
+ */
11185
+ async healSearchResults(meiliResult) {
11186
+ const { search } = this.adapter;
11187
+ if (!search || meiliResult.records.length === 0) {
11188
+ return meiliResult;
11189
+ }
11190
+ const ids = meiliResult.records.map((r) => r.id);
11191
+ const existing = await this.adapter.objectRecords.findByIds(ids);
11192
+ const existingSet = new Set(existing.map((r) => r.id));
11193
+ const ghosts = ids.filter((id) => !existingSet.has(id));
11194
+ if (ghosts.length > 0) {
11195
+ Promise.all(ghosts.map((id) => search.removeRecord(id))).catch(
11196
+ (err) => console.error("[search] Failed to clean ghost records from per-object search", err)
11197
+ );
11198
+ }
11199
+ return {
11200
+ records: meiliResult.records.filter((r) => existingSet.has(r.id)),
11201
+ total: meiliResult.total - ghosts.length
11202
+ };
11203
+ }
10968
11204
  };
10969
11205
 
10970
11206
  // src/runtime/services/record/record-resolver.service.ts
@@ -11137,7 +11373,7 @@ var RelationService = class extends BaseService {
11137
11373
  }
11138
11374
  const isUniversal = attr.targets.length === 1 && attr.targets[0].object === RELATION_TARGET_ANY;
11139
11375
  const validObjectIds = isUniversal ? null : await this.getValidObjectIds(attr.targets);
11140
- if (!isUniversal && _optionalChain([validObjectIds, 'optionalAccess', _215 => _215.size]) === 0) {
11376
+ if (!isUniversal && _optionalChain([validObjectIds, 'optionalAccess', _220 => _220.size]) === 0) {
11141
11377
  errors.push({
11142
11378
  attribute: attr.name,
11143
11379
  message: `No valid target objects found for ${attr.label}`
@@ -11190,10 +11426,10 @@ var RelationService = class extends BaseService {
11190
11426
  for (const target of targets) {
11191
11427
  try {
11192
11428
  const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
11193
- if (_optionalChain([objectSchema, 'optionalAccess', _216 => _216.id])) {
11429
+ if (_optionalChain([objectSchema, 'optionalAccess', _221 => _221.id])) {
11194
11430
  objectIds.add(objectSchema.id);
11195
11431
  }
11196
- } catch (e15) {
11432
+ } catch (e16) {
11197
11433
  }
11198
11434
  }
11199
11435
  return objectIds;
@@ -11259,7 +11495,7 @@ var RelationService = class extends BaseService {
11259
11495
  const targetResults = await Promise.all(
11260
11496
  filteredTargets.map(async (target) => {
11261
11497
  const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
11262
- if (!_optionalChain([objectSchema, 'optionalAccess', _217 => _217.id])) return { options: [], total: 0 };
11498
+ if (!_optionalChain([objectSchema, 'optionalAccess', _222 => _222.id])) return { options: [], total: 0 };
11263
11499
  const objectId = objectSchema.id;
11264
11500
  const result = query ? await queryService.searchRecords(objectId, query, queryOptions) : await queryService.listRecords(objectId, queryOptions);
11265
11501
  const options = await Promise.all(
@@ -11416,8 +11652,8 @@ var RelationService = class extends BaseService {
11416
11652
  continue;
11417
11653
  }
11418
11654
  const attribute = attributeMap.get(attributeId);
11419
- const targetConfig = _optionalChain([attribute, 'optionalAccess', _218 => _218.targets, 'optionalAccess', _219 => _219.find, 'call', _220 => _220((t) => t.object === objectSchema.name)]);
11420
- const customTemplate = _optionalChain([targetConfig, 'optionalAccess', _221 => _221.displayTemplate]);
11655
+ const targetConfig = _optionalChain([attribute, 'optionalAccess', _223 => _223.targets, 'optionalAccess', _224 => _224.find, 'call', _225 => _225((t) => t.object === objectSchema.name)]);
11656
+ const customTemplate = _optionalChain([targetConfig, 'optionalAccess', _226 => _226.displayTemplate]);
11421
11657
  const label = await this.resolveLabel(record, objectSchema, customTemplate);
11422
11658
  resolved.push({
11423
11659
  _compositeId: compositeId,
@@ -11580,14 +11816,14 @@ var RollupService = class extends BaseService {
11580
11816
  const sourceSchema = getSchemaByNameFromContext(sourceObjectName);
11581
11817
  let sourceObjectId;
11582
11818
  let reverseRelationAttrName;
11583
- if (_optionalChain([sourceSchema, 'optionalAccess', _222 => _222.id])) {
11819
+ if (_optionalChain([sourceSchema, 'optionalAccess', _227 => _227.id])) {
11584
11820
  sourceObjectId = sourceSchema.id;
11585
11821
  const reverseRelationAttr = sourceSchema.attributes.find((attr) => {
11586
11822
  if (attr.type !== "relation") return false;
11587
11823
  const relationConfig = attr;
11588
- return _optionalChain([relationConfig, 'optionalAccess', _223 => _223.targets, 'optionalAccess', _224 => _224.some, 'call', _225 => _225((t) => t.object === schema.name)]);
11824
+ return _optionalChain([relationConfig, 'optionalAccess', _228 => _228.targets, 'optionalAccess', _229 => _229.some, 'call', _230 => _230((t) => t.object === schema.name)]);
11589
11825
  });
11590
- reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _226 => _226.name]);
11826
+ reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _231 => _231.name]);
11591
11827
  } else {
11592
11828
  const sourceObject = await this.adapter.objects.findByName(sourceObjectName);
11593
11829
  if (!sourceObject) {
@@ -11598,9 +11834,9 @@ var RollupService = class extends BaseService {
11598
11834
  const reverseRelationAttr = sourceAttributes.find((attr) => {
11599
11835
  if (attr.type !== "relation") return false;
11600
11836
  const relationConfig = attr.config;
11601
- return _optionalChain([relationConfig, 'optionalAccess', _227 => _227.targets, 'optionalAccess', _228 => _228.some, 'call', _229 => _229((t) => t.object === schema.name)]);
11837
+ return _optionalChain([relationConfig, 'optionalAccess', _232 => _232.targets, 'optionalAccess', _233 => _233.some, 'call', _234 => _234((t) => t.object === schema.name)]);
11602
11838
  });
11603
- reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _230 => _230.name]);
11839
+ reverseRelationAttrName = _optionalChain([reverseRelationAttr, 'optionalAccess', _235 => _235.name]);
11604
11840
  }
11605
11841
  if (!reverseRelationAttrName) {
11606
11842
  return { value: null, recordCount: 0 };
@@ -11785,7 +12021,7 @@ var RollupService = class extends BaseService {
11785
12021
  if (typeof relatedId === "string" && relatedId.length > 0) {
11786
12022
  affectedIds.push(relatedId);
11787
12023
  } else if (Array.isArray(relatedId)) {
11788
- affectedIds.push(...relatedId.filter((id) => typeof id === "string"));
12024
+ affectedIds.push(...relatedId.filter((id) => typeof id === "string" && id.length > 0));
11789
12025
  }
11790
12026
  }
11791
12027
  return [...new Set(affectedIds)];
@@ -11856,13 +12092,13 @@ var RollupService = class extends BaseService {
11856
12092
  if (!obj) continue;
11857
12093
  for (const rollupDbAttr of rollupAttrs) {
11858
12094
  const rollupConfig = rollupDbAttr.config;
11859
- if (!_optionalChain([rollupConfig, 'optionalAccess', _231 => _231.relationAttribute])) continue;
12095
+ if (!_optionalChain([rollupConfig, 'optionalAccess', _236 => _236.relationAttribute])) continue;
11860
12096
  const relationAttr = attributes.find(
11861
12097
  (a) => a.type === "relation" && a.name === rollupConfig.relationAttribute
11862
12098
  );
11863
12099
  if (!relationAttr) continue;
11864
12100
  const relationConfig = relationAttr.config;
11865
- const targetsChangedObject = _optionalChain([relationConfig, 'optionalAccess', _232 => _232.targets, 'optionalAccess', _233 => _233.some, 'call', _234 => _234(
12101
+ const targetsChangedObject = _optionalChain([relationConfig, 'optionalAccess', _237 => _237.targets, 'optionalAccess', _238 => _238.some, 'call', _239 => _239(
11866
12102
  (t) => t.object === changedSchema.name
11867
12103
  )]);
11868
12104
  if (!targetsChangedObject) continue;
@@ -11887,11 +12123,11 @@ var RecordService = class extends BaseService {
11887
12123
  constructor(adapter, options) {
11888
12124
  super(adapter);
11889
12125
  this.schemaService = new ObjectSchemaService(adapter, registry, {
11890
- auditService: _optionalChain([options, 'optionalAccess', _235 => _235.auditService])
12126
+ auditService: _optionalChain([options, 'optionalAccess', _240 => _240.auditService])
11891
12127
  });
11892
- this.permissionService = _optionalChain([options, 'optionalAccess', _236 => _236.permissionService]);
11893
- this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _237 => _237.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
11894
- this.policyRegistry = _optionalChain([options, 'optionalAccess', _238 => _238.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _239 => _239.policyRegistry]), () => ( defaultPolicyRegistry));
12128
+ this.permissionService = _optionalChain([options, 'optionalAccess', _241 => _241.permissionService]);
12129
+ this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _242 => _242.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
12130
+ this.policyRegistry = _optionalChain([options, 'optionalAccess', _243 => _243.policyRegistry]) === null ? null : _nullishCoalesce(_optionalChain([options, 'optionalAccess', _244 => _244.policyRegistry]), () => ( defaultPolicyRegistry));
11895
12131
  this.recordResolver = new RecordResolverService(adapter);
11896
12132
  this.queryService = new RecordQueryService(adapter, this.schemaService, {
11897
12133
  permissionService: this.permissionService,
@@ -11906,7 +12142,7 @@ var RecordService = class extends BaseService {
11906
12142
  recordResolver: this.recordResolver
11907
12143
  });
11908
12144
  this.userService = new UserService(adapter);
11909
- this.hookRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _240 => _240.hookRegistry]), () => ( new NoopHookRegistry()));
12145
+ this.hookRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _245 => _245.hookRegistry]), () => ( new NoopHookRegistry()));
11910
12146
  this.bilateralSyncService = new BilateralSyncService(
11911
12147
  adapter,
11912
12148
  this.schemaService,
@@ -11946,25 +12182,25 @@ var RecordService = class extends BaseService {
11946
12182
  schema,
11947
12183
  this.tenantId,
11948
12184
  dataWithDefaults,
11949
- _optionalChain([options, 'optionalAccess', _241 => _241.hookMetadata])
12185
+ _optionalChain([options, 'optionalAccess', _246 => _246.hookMetadata])
11950
12186
  );
11951
- if (!_optionalChain([options, 'optionalAccess', _242 => _242.skipHooks])) {
12187
+ if (!_optionalChain([options, 'optionalAccess', _247 => _247.skipHooks])) {
11952
12188
  await this.hookRegistry.execute("beforeCreate", schema.name, hookCtx);
11953
12189
  }
11954
12190
  const normalizedData = this.relationPropertiesService.normalizeRelationValuesForStorage(
11955
12191
  schema,
11956
12192
  dataWithDefaults
11957
12193
  );
11958
- if (_optionalChain([options, 'optionalAccess', _243 => _243.validate]) !== false) {
11959
- if (_optionalChain([options, 'optionalAccess', _244 => _244.allowDraft])) {
12194
+ if (_optionalChain([options, 'optionalAccess', _248 => _248.validate]) !== false) {
12195
+ if (_optionalChain([options, 'optionalAccess', _249 => _249.allowDraft])) {
11960
12196
  _chunk3WTK7ESHjs.validateDraftOrThrow.call(void 0, schema, normalizedData);
11961
12197
  } else {
11962
12198
  _chunk3WTK7ESHjs.validateObjectOrThrow.call(void 0, schema, normalizedData);
11963
12199
  }
11964
- if (!_optionalChain([options, 'optionalAccess', _245 => _245.skipRelationValidation])) {
12200
+ if (!_optionalChain([options, 'optionalAccess', _250 => _250.skipRelationValidation])) {
11965
12201
  await this.relationService.validateRelationsOrThrow(schema, normalizedData);
11966
12202
  }
11967
- if (!_optionalChain([options, 'optionalAccess', _246 => _246.skipUserValidation])) {
12203
+ if (!_optionalChain([options, 'optionalAccess', _251 => _251.skipUserValidation])) {
11968
12204
  await this.userService.validateUsersOrThrow(schema, normalizedData);
11969
12205
  }
11970
12206
  }
@@ -11975,12 +12211,12 @@ var RecordService = class extends BaseService {
11975
12211
  data: normalizedData,
11976
12212
  label,
11977
12213
  completionStatus,
11978
- metadata: _optionalChain([options, 'optionalAccess', _247 => _247.metadata]),
12214
+ metadata: _optionalChain([options, 'optionalAccess', _252 => _252.metadata]),
11979
12215
  createdBy: this.userId
11980
12216
  });
11981
12217
  for (const [attrName, value] of Object.entries(dataWithDefaults)) {
11982
12218
  const attr = schema.attributes.find((a) => a.name === attrName);
11983
- if (_optionalChain([attr, 'optionalAccess', _248 => _248.type]) === "relation") {
12219
+ if (_optionalChain([attr, 'optionalAccess', _253 => _253.type]) === "relation") {
11984
12220
  const hasProperties2 = attr.properties !== void 0;
11985
12221
  const isBilateral = isBilateralRelation(attr);
11986
12222
  if (hasProperties2 || isBilateral) {
@@ -11996,7 +12232,7 @@ var RecordService = class extends BaseService {
11996
12232
  }
11997
12233
  for (const [attrName, value] of Object.entries(normalizedData)) {
11998
12234
  const attr = schema.attributes.find((a) => a.name === attrName);
11999
- if (_optionalChain([attr, 'optionalAccess', _249 => _249.type]) === "relation" && isBilateralRelation(attr)) {
12235
+ if (_optionalChain([attr, 'optionalAccess', _254 => _254.type]) === "relation" && isBilateralRelation(attr)) {
12000
12236
  await this.bilateralSyncService.syncBilateralRelation(
12001
12237
  schema,
12002
12238
  record.id,
@@ -12007,7 +12243,7 @@ var RecordService = class extends BaseService {
12007
12243
  );
12008
12244
  }
12009
12245
  }
12010
- if (!_optionalChain([options, 'optionalAccess', _250 => _250.skipHooks])) {
12246
+ if (!_optionalChain([options, 'optionalAccess', _255 => _255.skipHooks])) {
12011
12247
  const afterCtx = {
12012
12248
  ...hookCtx,
12013
12249
  recordId: record.id,
@@ -12017,6 +12253,11 @@ var RecordService = class extends BaseService {
12017
12253
  }
12018
12254
  await recalculateParentRollups(record, schema, this.rollupContext);
12019
12255
  await this.invalidateRecordCaches(record.id, objectId);
12256
+ _optionalChain([this, 'access', _256 => _256.adapter, 'access', _257 => _257.search, 'optionalAccess', _258 => _258.indexRecord, 'call', _259 => _259(record, {
12257
+ objectName: schema.name,
12258
+ objectLabel: schema.label,
12259
+ attributes: schema.attributes
12260
+ }), 'access', _260 => _260.catch, 'call', _261 => _261((err) => console.error("[search] Failed to index created record", record.id, err))]);
12020
12261
  if (this.auditService && this.userId) {
12021
12262
  this.auditService.logRecordAction({
12022
12263
  action: "record.created",
@@ -12025,7 +12266,7 @@ var RecordService = class extends BaseService {
12025
12266
  objectId: schema.id,
12026
12267
  recordId: record.id,
12027
12268
  recordLabel: record.label,
12028
- metadata: _optionalChain([options, 'optionalAccess', _251 => _251.hookMetadata])
12269
+ metadata: _optionalChain([options, 'optionalAccess', _262 => _262.hookMetadata])
12029
12270
  }).catch(() => {
12030
12271
  });
12031
12272
  }
@@ -12048,7 +12289,7 @@ var RecordService = class extends BaseService {
12048
12289
  return null;
12049
12290
  }
12050
12291
  const schema = await this.schemaService.getObjectSchema(record.objectId);
12051
- if (!_optionalChain([options, 'optionalAccess', _252 => _252.skipPolicyCheck])) {
12292
+ if (!_optionalChain([options, 'optionalAccess', _263 => _263.skipPolicyCheck])) {
12052
12293
  const policy = getPolicy(this.policyRegistry, this.userId, schema.name);
12053
12294
  if (policy) {
12054
12295
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
@@ -12058,11 +12299,11 @@ var RecordService = class extends BaseService {
12058
12299
  }
12059
12300
  }
12060
12301
  let enrichedRecord = record;
12061
- if (!_optionalChain([options, 'optionalAccess', _253 => _253.skipFormulas])) {
12302
+ if (!_optionalChain([options, 'optionalAccess', _264 => _264.skipFormulas])) {
12062
12303
  enrichedRecord = enrichWithFormulas(record, schema);
12063
12304
  }
12064
12305
  enrichedRecord = await this.enrichRelationProperties(enrichedRecord, schema);
12065
- if (_optionalChain([options, 'optionalAccess', _254 => _254.includeSchema])) {
12306
+ if (_optionalChain([options, 'optionalAccess', _265 => _265.includeSchema])) {
12066
12307
  const recordWithSchema = enrichedRecord;
12067
12308
  recordWithSchema.schema = schema;
12068
12309
  return recordWithSchema;
@@ -12112,7 +12353,7 @@ var RecordService = class extends BaseService {
12112
12353
  if (oldVal !== null && newVal !== null && typeof oldVal === "object" && typeof newVal === "object") {
12113
12354
  try {
12114
12355
  return JSON.stringify(oldVal) !== JSON.stringify(newVal);
12115
- } catch (e16) {
12356
+ } catch (e17) {
12116
12357
  return true;
12117
12358
  }
12118
12359
  }
@@ -12124,9 +12365,9 @@ var RecordService = class extends BaseService {
12124
12365
  existing,
12125
12366
  mergedData,
12126
12367
  changedAttributes,
12127
- _optionalChain([options, 'optionalAccess', _255 => _255.hookMetadata])
12368
+ _optionalChain([options, 'optionalAccess', _266 => _266.hookMetadata])
12128
12369
  );
12129
- if (!_optionalChain([options, 'optionalAccess', _256 => _256.skipHooks])) {
12370
+ if (!_optionalChain([options, 'optionalAccess', _267 => _267.skipHooks])) {
12130
12371
  await this.hookRegistry.execute("beforeUpdate", schema.name, hookCtx);
12131
12372
  }
12132
12373
  const hookModifiedValues = {};
@@ -12141,16 +12382,16 @@ var RecordService = class extends BaseService {
12141
12382
  dataToUpdate
12142
12383
  );
12143
12384
  const normalizedMergedData = { ...existing.values, ...normalizedUpdate };
12144
- if (_optionalChain([options, 'optionalAccess', _257 => _257.validate]) !== false) {
12145
- if (_optionalChain([options, 'optionalAccess', _258 => _258.partial])) {
12385
+ if (_optionalChain([options, 'optionalAccess', _268 => _268.validate]) !== false) {
12386
+ if (_optionalChain([options, 'optionalAccess', _269 => _269.partial])) {
12146
12387
  _chunk3WTK7ESHjs.validateDraftOrThrow.call(void 0, schema, normalizedMergedData);
12147
12388
  } else {
12148
12389
  _chunk3WTK7ESHjs.validateObjectOrThrow.call(void 0, schema, normalizedMergedData);
12149
12390
  }
12150
- if (!_optionalChain([options, 'optionalAccess', _259 => _259.skipRelationValidation])) {
12391
+ if (!_optionalChain([options, 'optionalAccess', _270 => _270.skipRelationValidation])) {
12151
12392
  await this.relationService.validateRelationsOrThrow(schema, normalizedUpdate);
12152
12393
  }
12153
- if (!_optionalChain([options, 'optionalAccess', _260 => _260.skipUserValidation])) {
12394
+ if (!_optionalChain([options, 'optionalAccess', _271 => _271.skipUserValidation])) {
12154
12395
  await this.userService.validateUsersOrThrow(schema, normalizedUpdate);
12155
12396
  }
12156
12397
  }
@@ -12163,7 +12404,7 @@ var RecordService = class extends BaseService {
12163
12404
  __lastUpdatedBy: this.userId,
12164
12405
  __expectedUpdatedAt: existing.updatedAt instanceof Date ? existing.updatedAt.toISOString() : existing.updatedAt
12165
12406
  };
12166
- if (_optionalChain([options, 'optionalAccess', _261 => _261.metadata]) !== void 0) {
12407
+ if (_optionalChain([options, 'optionalAccess', _272 => _272.metadata]) !== void 0) {
12167
12408
  const existingMetadata = _nullishCoalesce(existing.metadata, () => ( {}));
12168
12409
  const mergedMetadata = { ...existingMetadata, ...options.metadata };
12169
12410
  const cleanedMetadata = Object.fromEntries(
@@ -12174,15 +12415,20 @@ var RecordService = class extends BaseService {
12174
12415
  const bilateralOldValues = {};
12175
12416
  for (const attrName of Object.keys(normalizedUpdate)) {
12176
12417
  const attr = schema.attributes.find((a) => a.name === attrName);
12177
- if (_optionalChain([attr, 'optionalAccess', _262 => _262.type]) === "relation" && isBilateralRelation(attr)) {
12418
+ if (_optionalChain([attr, 'optionalAccess', _273 => _273.type]) === "relation" && isBilateralRelation(attr)) {
12178
12419
  bilateralOldValues[attrName] = existing.values[attrName];
12179
12420
  }
12180
12421
  }
12181
12422
  const updated = await this.adapter.objectRecords.update(recordId, updatePayload);
12182
12423
  await this.invalidateRecordCaches(recordId, existing.objectId);
12424
+ _optionalChain([this, 'access', _274 => _274.adapter, 'access', _275 => _275.search, 'optionalAccess', _276 => _276.indexRecord, 'call', _277 => _277(updated, {
12425
+ objectName: schema.name,
12426
+ objectLabel: schema.label,
12427
+ attributes: schema.attributes
12428
+ }), 'access', _278 => _278.catch, 'call', _279 => _279((err) => console.error("[search] Failed to index updated record", updated.id, err))]);
12183
12429
  for (const [attrName, value] of Object.entries(dataToUpdate)) {
12184
12430
  const attr = schema.attributes.find((a) => a.name === attrName);
12185
- if (_optionalChain([attr, 'optionalAccess', _263 => _263.type]) === "relation") {
12431
+ if (_optionalChain([attr, 'optionalAccess', _280 => _280.type]) === "relation") {
12186
12432
  const hasProperties2 = attr.properties !== void 0;
12187
12433
  const isBilateral = isBilateralRelation(attr);
12188
12434
  if (hasProperties2 || isBilateral) {
@@ -12198,7 +12444,7 @@ var RecordService = class extends BaseService {
12198
12444
  }
12199
12445
  for (const [attrName, value] of Object.entries(normalizedUpdate)) {
12200
12446
  const attr = schema.attributes.find((a) => a.name === attrName);
12201
- if (_optionalChain([attr, 'optionalAccess', _264 => _264.type]) === "relation" && isBilateralRelation(attr)) {
12447
+ if (_optionalChain([attr, 'optionalAccess', _281 => _281.type]) === "relation" && isBilateralRelation(attr)) {
12202
12448
  const oldValue = bilateralOldValues[attrName];
12203
12449
  await this.bilateralSyncService.syncBilateralRelation(
12204
12450
  schema,
@@ -12209,7 +12455,7 @@ var RecordService = class extends BaseService {
12209
12455
  );
12210
12456
  }
12211
12457
  }
12212
- if (!_optionalChain([options, 'optionalAccess', _265 => _265.skipHooks])) {
12458
+ if (!_optionalChain([options, 'optionalAccess', _282 => _282.skipHooks])) {
12213
12459
  const afterCtx = {
12214
12460
  ...hookCtx,
12215
12461
  record: updated
@@ -12224,7 +12470,7 @@ var RecordService = class extends BaseService {
12224
12470
  if (this.auditService && this.userId && allChangedAttributes.length > 0) {
12225
12471
  const changes = allChangedAttributes.map((attr) => ({
12226
12472
  field: attr,
12227
- oldValue: _optionalChain([hookCtx, 'access', _266 => _266.oldValues, 'optionalAccess', _267 => _267[attr]]),
12473
+ oldValue: _optionalChain([hookCtx, 'access', _283 => _283.oldValues, 'optionalAccess', _284 => _284[attr]]),
12228
12474
  newValue: hookCtx.newValues[attr]
12229
12475
  }));
12230
12476
  this.auditService.logRecordAction({
@@ -12235,7 +12481,7 @@ var RecordService = class extends BaseService {
12235
12481
  recordId: updated.id,
12236
12482
  recordLabel: updated.label,
12237
12483
  changes,
12238
- metadata: _optionalChain([options, 'optionalAccess', _268 => _268.hookMetadata])
12484
+ metadata: _optionalChain([options, 'optionalAccess', _285 => _285.hookMetadata])
12239
12485
  }).catch(() => {
12240
12486
  });
12241
12487
  }
@@ -12267,17 +12513,17 @@ var RecordService = class extends BaseService {
12267
12513
  const ctx = buildPolicyContext(schema.name, this.userId, this.tenantId);
12268
12514
  checkRecordDeleteOrThrow(policy, record, ctx);
12269
12515
  }
12270
- if (_optionalChain([options, 'optionalAccess', _269 => _269.checkSystem]) && schema.system) {
12516
+ if (_optionalChain([options, 'optionalAccess', _286 => _286.checkSystem]) && schema.system) {
12271
12517
  throw new ProtectedResourceError("object", schema.name, "delete");
12272
12518
  }
12273
- if (!_optionalChain([options, 'optionalAccess', _270 => _270.skipReferenceCheck])) {
12519
+ if (!_optionalChain([options, 'optionalAccess', _287 => _287.skipReferenceCheck])) {
12274
12520
  const references = await this.adapter.objectRecords.countRecordsReferencingId(recordId);
12275
12521
  if (references.length > 0) {
12276
12522
  throw new RecordReferencedError(recordId, references);
12277
12523
  }
12278
12524
  }
12279
- const hookCtx = createContextForDelete(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _271 => _271.hookMetadata]));
12280
- if (!_optionalChain([options, 'optionalAccess', _272 => _272.skipHooks])) {
12525
+ const hookCtx = createContextForDelete(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _288 => _288.hookMetadata]));
12526
+ if (!_optionalChain([options, 'optionalAccess', _289 => _289.skipHooks])) {
12281
12527
  await this.hookRegistry.execute("beforeDelete", schema.name, hookCtx);
12282
12528
  }
12283
12529
  for (const attr of schema.attributes) {
@@ -12295,7 +12541,8 @@ var RecordService = class extends BaseService {
12295
12541
  }
12296
12542
  await this.adapter.objectRecords.delete(recordId);
12297
12543
  await this.invalidateRecordCaches(recordId, record.objectId);
12298
- if (!_optionalChain([options, 'optionalAccess', _273 => _273.skipHooks])) {
12544
+ _optionalChain([this, 'access', _290 => _290.adapter, 'access', _291 => _291.search, 'optionalAccess', _292 => _292.removeRecord, 'call', _293 => _293(recordId), 'access', _294 => _294.catch, 'call', _295 => _295((err) => console.error("[search] Failed to remove deleted record", recordId, err))]);
12545
+ if (!_optionalChain([options, 'optionalAccess', _296 => _296.skipHooks])) {
12299
12546
  await this.hookRegistry.execute("afterDelete", schema.name, hookCtx);
12300
12547
  }
12301
12548
  await recalculateParentRollups(record, schema, this.rollupContext);
@@ -12307,7 +12554,7 @@ var RecordService = class extends BaseService {
12307
12554
  objectId: schema.id,
12308
12555
  recordId: record.id,
12309
12556
  recordLabel: record.label,
12310
- metadata: _optionalChain([options, 'optionalAccess', _274 => _274.hookMetadata])
12557
+ metadata: _optionalChain([options, 'optionalAccess', _297 => _297.hookMetadata])
12311
12558
  }).catch(() => {
12312
12559
  });
12313
12560
  }
@@ -12368,13 +12615,18 @@ var RecordService = class extends BaseService {
12368
12615
  this.tenantId
12369
12616
  );
12370
12617
  await checkPermission(this.permissionService, this.userId, schema.name, "update");
12371
- const hookCtx = createContextForRestore(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _275 => _275.hookMetadata]));
12372
- if (!_optionalChain([options, 'optionalAccess', _276 => _276.skipHooks])) {
12618
+ const hookCtx = createContextForRestore(schema, this.tenantId, record, _optionalChain([options, 'optionalAccess', _298 => _298.hookMetadata]));
12619
+ if (!_optionalChain([options, 'optionalAccess', _299 => _299.skipHooks])) {
12373
12620
  await this.hookRegistry.execute("beforeRestore", schema.name, hookCtx);
12374
12621
  }
12375
12622
  const restored = await this.adapter.objectRecords.restore(recordId);
12376
12623
  await this.invalidateRecordCaches(recordId, record.objectId);
12377
- if (!_optionalChain([options, 'optionalAccess', _277 => _277.skipHooks])) {
12624
+ _optionalChain([this, 'access', _300 => _300.adapter, 'access', _301 => _301.search, 'optionalAccess', _302 => _302.indexRecord, 'call', _303 => _303(restored, {
12625
+ objectName: schema.name,
12626
+ objectLabel: schema.label,
12627
+ attributes: schema.attributes
12628
+ }), 'access', _304 => _304.catch, 'call', _305 => _305((err) => console.error("[search] Failed to index restored record", restored.id, err))]);
12629
+ if (!_optionalChain([options, 'optionalAccess', _306 => _306.skipHooks])) {
12378
12630
  const afterCtx = {
12379
12631
  ...hookCtx,
12380
12632
  record: restored
@@ -12389,7 +12641,7 @@ var RecordService = class extends BaseService {
12389
12641
  objectId: schema.id,
12390
12642
  recordId: restored.id,
12391
12643
  recordLabel: restored.label,
12392
- metadata: _optionalChain([options, 'optionalAccess', _278 => _278.hookMetadata])
12644
+ metadata: _optionalChain([options, 'optionalAccess', _307 => _307.hookMetadata])
12393
12645
  }).catch(() => {
12394
12646
  });
12395
12647
  }
@@ -12820,7 +13072,7 @@ var DocumentRendererService = class {
12820
13072
  throw new StorageDownloadNotSupportedError();
12821
13073
  }
12822
13074
  let storagePath = fileId;
12823
- if (_optionalChain([this, 'access', _279 => _279.options, 'optionalAccess', _280 => _280.filesRepository])) {
13075
+ if (_optionalChain([this, 'access', _308 => _308.options, 'optionalAccess', _309 => _309.filesRepository])) {
12824
13076
  const file2 = await this.options.filesRepository.findById(fileId);
12825
13077
  if (!file2) {
12826
13078
  throw new Error(`Template file not found: ${fileId}`);
@@ -12838,8 +13090,8 @@ var DocumentRendererService = class {
12838
13090
  for (const field of fields) {
12839
13091
  const rawValue = getContextValue(context, field.contextPath);
12840
13092
  const attrInfo = await this.getAttributeInfo(field.contextPath, workflow2);
12841
- if (_optionalChain([attrInfo, 'optionalAccess', _281 => _281.attribute])) {
12842
- if (attrInfo.attribute.type === "relation" && rawValue && _optionalChain([this, 'access', _282 => _282.options, 'optionalAccess', _283 => _283.relationService])) {
13093
+ if (_optionalChain([attrInfo, 'optionalAccess', _310 => _310.attribute])) {
13094
+ if (attrInfo.attribute.type === "relation" && rawValue && _optionalChain([this, 'access', _311 => _311.options, 'optionalAccess', _312 => _312.relationService])) {
12843
13095
  const ids = Array.isArray(rawValue) ? rawValue : [rawValue];
12844
13096
  const stringIds = ids.filter((id) => typeof id === "string");
12845
13097
  if (stringIds.length > 0) {
@@ -12860,7 +13112,7 @@ var DocumentRendererService = class {
12860
13112
  resolved.set(field.id, this.formatValueSimple(rawValue, field.fallback));
12861
13113
  }
12862
13114
  }
12863
- if (relationBatch.length > 0 && _optionalChain([this, 'access', _284 => _284.options, 'optionalAccess', _285 => _285.relationService])) {
13115
+ if (relationBatch.length > 0 && _optionalChain([this, 'access', _313 => _313.options, 'optionalAccess', _314 => _314.relationService])) {
12864
13116
  try {
12865
13117
  const batchResult = await this.options.relationService.resolveIdsBatch(
12866
13118
  relationBatch.map((r) => ({ attributeId: r.attributeId, ids: r.ids }))
@@ -12869,12 +13121,12 @@ var DocumentRendererService = class {
12869
13121
  const options = _nullishCoalesce(batchResult[attributeId], () => ( []));
12870
13122
  const labels = options.map((o) => o.label);
12871
13123
  const field = fields.find((f) => f.id === fieldId);
12872
- resolved.set(fieldId, labels.join(", ") || _optionalChain([field, 'optionalAccess', _286 => _286.fallback]) || "");
13124
+ resolved.set(fieldId, labels.join(", ") || _optionalChain([field, 'optionalAccess', _315 => _315.fallback]) || "");
12873
13125
  }
12874
- } catch (e17) {
13126
+ } catch (e18) {
12875
13127
  for (const { fieldId, ids } of relationBatch) {
12876
13128
  const field = fields.find((f) => f.id === fieldId);
12877
- resolved.set(fieldId, ids.join(", ") || _optionalChain([field, 'optionalAccess', _287 => _287.fallback]) || "");
13129
+ resolved.set(fieldId, ids.join(", ") || _optionalChain([field, 'optionalAccess', _316 => _316.fallback]) || "");
12878
13130
  }
12879
13131
  }
12880
13132
  }
@@ -12885,7 +13137,7 @@ var DocumentRendererService = class {
12885
13137
  * Parses paths like "slots.client.firstName" to find the attribute definition
12886
13138
  */
12887
13139
  async getAttributeInfo(contextPath, workflow2) {
12888
- const schemaService = _optionalChain([this, 'access', _288 => _288.options, 'optionalAccess', _289 => _289.schemaService]);
13140
+ const schemaService = _optionalChain([this, 'access', _317 => _317.options, 'optionalAccess', _318 => _318.schemaService]);
12889
13141
  if (!schemaService) {
12890
13142
  return null;
12891
13143
  }
@@ -12898,7 +13150,7 @@ var DocumentRendererService = class {
12898
13150
  }
12899
13151
  const slotId = parts[1];
12900
13152
  const attributeName = parts[2];
12901
- const slot = _optionalChain([workflow2, 'access', _290 => _290.slots, 'optionalAccess', _291 => _291.find, 'call', _292 => _292((s) => s.id === slotId)]);
13153
+ const slot = _optionalChain([workflow2, 'access', _319 => _319.slots, 'optionalAccess', _320 => _320.find, 'call', _321 => _321((s) => s.id === slotId)]);
12902
13154
  if (!slot) {
12903
13155
  return null;
12904
13156
  }
@@ -12907,7 +13159,7 @@ var DocumentRendererService = class {
12907
13159
  try {
12908
13160
  schema = await schemaService.getObjectSchemaByName(slot.objectName);
12909
13161
  this.schemaCache.set(slot.objectName, schema);
12910
- } catch (e18) {
13162
+ } catch (e19) {
12911
13163
  return null;
12912
13164
  }
12913
13165
  }
@@ -13097,7 +13349,7 @@ var DocumentProcessingHook = class extends BaseService {
13097
13349
  const pendingIds = [];
13098
13350
  for (const [nodeId, doc] of Object.entries(context.documents)) {
13099
13351
  const metadata = doc.metadata;
13100
- if (_optionalChain([metadata, 'optionalAccess', _293 => _293.status]) === "pending") {
13352
+ if (_optionalChain([metadata, 'optionalAccess', _322 => _322.status]) === "pending") {
13101
13353
  pendingIds.push(nodeId);
13102
13354
  }
13103
13355
  }
@@ -13148,12 +13400,12 @@ var DocumentProcessingHook = class extends BaseService {
13148
13400
  }
13149
13401
  for (const slotId of targetSlotIds) {
13150
13402
  try {
13151
- const recordId = _optionalChain([context, 'access', _294 => _294.createdRecordIds, 'optionalAccess', _295 => _295[slotId]]);
13403
+ const recordId = _optionalChain([context, 'access', _323 => _323.createdRecordIds, 'optionalAccess', _324 => _324[slotId]]);
13152
13404
  if (!recordId) {
13153
13405
  continue;
13154
13406
  }
13155
- const slotDef = _optionalChain([workflow2, 'access', _296 => _296.slots, 'optionalAccess', _297 => _297.find, 'call', _298 => _298((s) => s.id === slotId)]);
13156
- const objectName = _optionalChain([slotDef, 'optionalAccess', _299 => _299.objectName]);
13407
+ const slotDef = _optionalChain([workflow2, 'access', _325 => _325.slots, 'optionalAccess', _326 => _326.find, 'call', _327 => _327((s) => s.id === slotId)]);
13408
+ const objectName = _optionalChain([slotDef, 'optionalAccess', _328 => _328.objectName]);
13157
13409
  if (!objectName) {
13158
13410
  continue;
13159
13411
  }
@@ -13170,14 +13422,14 @@ var DocumentProcessingHook = class extends BaseService {
13170
13422
  attachedDocumentIds.push(result.document.id);
13171
13423
  const record = await recordService.getRecord(recordId);
13172
13424
  if (record) {
13173
- const attachments = _nullishCoalesce(_optionalChain([record, 'access', _300 => _300.values, 'optionalAccess', _301 => _301.attachments]), () => ( []));
13425
+ const attachments = _nullishCoalesce(_optionalChain([record, 'access', _329 => _329.values, 'optionalAccess', _330 => _330.attachments]), () => ( []));
13174
13426
  await recordService.updateRecord(
13175
13427
  recordId,
13176
13428
  { attachments: [...attachments, result.document.id] },
13177
13429
  { partial: true }
13178
13430
  );
13179
13431
  }
13180
- } catch (e19) {
13432
+ } catch (e20) {
13181
13433
  }
13182
13434
  }
13183
13435
  return attachedDocumentIds;
@@ -13436,7 +13688,7 @@ var WorkflowAccessGrantService = class extends BaseService {
13436
13688
  * Check if a specific token has been revoked.
13437
13689
  */
13438
13690
  isTokenRevoked(dbGrant, jti) {
13439
- return _nullishCoalesce(_optionalChain([dbGrant, 'access', _302 => _302.revoked_token_jtis, 'optionalAccess', _303 => _303.includes, 'call', _304 => _304(jti)]), () => ( false));
13691
+ return _nullishCoalesce(_optionalChain([dbGrant, 'access', _331 => _331.revoked_token_jtis, 'optionalAccess', _332 => _332.includes, 'call', _333 => _333(jti)]), () => ( false));
13440
13692
  }
13441
13693
  /**
13442
13694
  * Validate access token payload against the grant.
@@ -13488,10 +13740,10 @@ var WorkflowInstanceService = class extends BaseService {
13488
13740
  constructor(adapter, workflowService, options) {
13489
13741
  super(adapter);
13490
13742
  this.workflowService = workflowService;
13491
- this.executorRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _305 => _305.executorRegistry]), () => ( getDefaultExecutorRegistry()));
13492
- this.schemaService = _optionalChain([options, 'optionalAccess', _306 => _306.schemaService]);
13493
- this.recordService = _optionalChain([options, 'optionalAccess', _307 => _307.recordService]);
13494
- this.documentProcessingHook = _optionalChain([options, 'optionalAccess', _308 => _308.documentProcessingHook]);
13743
+ this.executorRegistry = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _334 => _334.executorRegistry]), () => ( getDefaultExecutorRegistry()));
13744
+ this.schemaService = _optionalChain([options, 'optionalAccess', _335 => _335.schemaService]);
13745
+ this.recordService = _optionalChain([options, 'optionalAccess', _336 => _336.recordService]);
13746
+ this.documentProcessingHook = _optionalChain([options, 'optionalAccess', _337 => _337.documentProcessingHook]);
13495
13747
  }
13496
13748
  /**
13497
13749
  * Start a new workflow instance
@@ -13673,7 +13925,7 @@ var WorkflowInstanceService = class extends BaseService {
13673
13925
  if (!this.adapter.workflowInstances) {
13674
13926
  return { instances: [], total: 0 };
13675
13927
  }
13676
- if (_optionalChain([options, 'optionalAccess', _309 => _309.workflowName])) {
13928
+ if (_optionalChain([options, 'optionalAccess', _338 => _338.workflowName])) {
13677
13929
  const allDbInstances = await this.adapter.workflowInstances.findByWorkflowName(
13678
13930
  options.workflowName,
13679
13931
  { status: options.status }
@@ -13687,11 +13939,11 @@ var WorkflowInstanceService = class extends BaseService {
13687
13939
  return { instances: instances2, total: total2 };
13688
13940
  }
13689
13941
  const { instances: dbInstances, total } = await this.adapter.workflowInstances.list({
13690
- limit: _optionalChain([options, 'optionalAccess', _310 => _310.limit]),
13691
- offset: _optionalChain([options, 'optionalAccess', _311 => _311.offset])
13942
+ limit: _optionalChain([options, 'optionalAccess', _339 => _339.limit]),
13943
+ offset: _optionalChain([options, 'optionalAccess', _340 => _340.offset])
13692
13944
  });
13693
13945
  let instances = dbInstances.map((db) => this.convertDBInstanceToInstance(db));
13694
- if (_optionalChain([options, 'optionalAccess', _312 => _312.status])) {
13946
+ if (_optionalChain([options, 'optionalAccess', _341 => _341.status])) {
13695
13947
  instances = instances.filter((i) => i.status === options.status);
13696
13948
  }
13697
13949
  instances = await this.markExpiredInstances(instances);
@@ -13712,9 +13964,9 @@ var WorkflowInstanceService = class extends BaseService {
13712
13964
  return { instances: [], total: 0 };
13713
13965
  }
13714
13966
  const { instances: dbInstances, total } = await this.adapter.workflowInstances.findByRecordInSlots(objectName, recordId, {
13715
- status: _optionalChain([options, 'optionalAccess', _313 => _313.status]),
13716
- limit: _optionalChain([options, 'optionalAccess', _314 => _314.limit]),
13717
- offset: _optionalChain([options, 'optionalAccess', _315 => _315.offset])
13967
+ status: _optionalChain([options, 'optionalAccess', _342 => _342.status]),
13968
+ limit: _optionalChain([options, 'optionalAccess', _343 => _343.limit]),
13969
+ offset: _optionalChain([options, 'optionalAccess', _344 => _344.offset])
13718
13970
  });
13719
13971
  const instances = dbInstances.map((db) => this.convertDBInstanceToInstance(db));
13720
13972
  return { instances, total };
@@ -13780,13 +14032,13 @@ var WorkflowInstanceService = class extends BaseService {
13780
14032
  try {
13781
14033
  const schemas = await Promise.all(
13782
14034
  current.workflowSnapshot.slots.map(
13783
- (slot) => _optionalChain([this, 'access', _316 => _316.schemaService, 'optionalAccess', _317 => _317.getObjectSchemaByName, 'call', _318 => _318(slot.objectName)])
14035
+ (slot) => _optionalChain([this, 'access', _345 => _345.schemaService, 'optionalAccess', _346 => _346.getObjectSchemaByName, 'call', _347 => _347(slot.objectName)])
13784
14036
  )
13785
14037
  );
13786
14038
  objectDefinitions = schemas.filter(
13787
14039
  (s) => s !== void 0
13788
14040
  );
13789
- } catch (e20) {
14041
+ } catch (e21) {
13790
14042
  }
13791
14043
  }
13792
14044
  const executorContext = {
@@ -14045,9 +14297,9 @@ var WorkflowInstanceService = class extends BaseService {
14045
14297
  */
14046
14298
  async snapshotRecord(recordId) {
14047
14299
  try {
14048
- const record = await _optionalChain([this, 'access', _319 => _319.recordService, 'optionalAccess', _320 => _320.getRecord, 'call', _321 => _321(recordId, { skipPolicyCheck: true })]);
14049
- return _optionalChain([record, 'optionalAccess', _322 => _322.values]);
14050
- } catch (e21) {
14300
+ const record = await _optionalChain([this, 'access', _348 => _348.recordService, 'optionalAccess', _349 => _349.getRecord, 'call', _350 => _350(recordId, { skipPolicyCheck: true })]);
14301
+ return _optionalChain([record, 'optionalAccess', _351 => _351.values]);
14302
+ } catch (e22) {
14051
14303
  return void 0;
14052
14304
  }
14053
14305
  }
@@ -14065,18 +14317,18 @@ var WorkflowInstanceService = class extends BaseService {
14065
14317
  for (const op of [...operations].reverse()) {
14066
14318
  try {
14067
14319
  if (op.operation === "create") {
14068
- await _optionalChain([this, 'access', _323 => _323.recordService, 'optionalAccess', _324 => _324.deleteRecord, 'call', _325 => _325(op.recordId, {
14320
+ await _optionalChain([this, 'access', _352 => _352.recordService, 'optionalAccess', _353 => _353.deleteRecord, 'call', _354 => _354(op.recordId, {
14069
14321
  skipHooks: true,
14070
14322
  skipReferenceCheck: true
14071
14323
  })]);
14072
14324
  rolledBack.push(op.slotId);
14073
14325
  } else if (op.operation === "update" && op.previousData) {
14074
- await _optionalChain([this, 'access', _326 => _326.recordService, 'optionalAccess', _327 => _327.updateRecord, 'call', _328 => _328(op.recordId, op.previousData, {
14326
+ await _optionalChain([this, 'access', _355 => _355.recordService, 'optionalAccess', _356 => _356.updateRecord, 'call', _357 => _357(op.recordId, op.previousData, {
14075
14327
  partial: false
14076
14328
  })]);
14077
14329
  rolledBack.push(op.slotId);
14078
14330
  }
14079
- } catch (e22) {
14331
+ } catch (e23) {
14080
14332
  }
14081
14333
  }
14082
14334
  return rolledBack;
@@ -14195,7 +14447,7 @@ var WorkflowInstanceService = class extends BaseService {
14195
14447
  if (!this.adapter.workflowInstances) {
14196
14448
  return;
14197
14449
  }
14198
- const currentVersion = _nullishCoalesce(_optionalChain([instance, 'access', _329 => _329.context, 'access', _330 => _330.variables, 'optionalAccess', _331 => _331.__version]), () => ( 0));
14450
+ const currentVersion = _nullishCoalesce(_optionalChain([instance, 'access', _358 => _358.context, 'access', _359 => _359.variables, 'optionalAccess', _360 => _360.__version]), () => ( 0));
14199
14451
  const nextVersion = currentVersion + 1;
14200
14452
  const instanceWithVersion = {
14201
14453
  ...instance,
@@ -14476,7 +14728,7 @@ var WorkflowRelationService = class extends BaseService {
14476
14728
  if (attr.type !== "relation") continue;
14477
14729
  for (const slot of slots) {
14478
14730
  const slotData = context.slots[slot.id];
14479
- const slotRecordId = _optionalChain([slotData, 'optionalAccess', _332 => _332.id]);
14731
+ const slotRecordId = _optionalChain([slotData, 'optionalAccess', _361 => _361.id]);
14480
14732
  if (!slotRecordId) continue;
14481
14733
  const targetsSlotObject = attr.targets.some(
14482
14734
  (t) => t.object === slot.objectName
@@ -14544,7 +14796,7 @@ var WorkflowService = class extends BaseService {
14544
14796
  if (Array.isArray(options)) {
14545
14797
  this.systemWorkflows = new Map(options.map((w) => [w.name, w]));
14546
14798
  } else {
14547
- this.systemWorkflows = new Map((_nullishCoalesce(_optionalChain([options, 'optionalAccess', _333 => _333.systemWorkflows]), () => ( []))).map((w) => [w.name, w]));
14799
+ this.systemWorkflows = new Map((_nullishCoalesce(_optionalChain([options, 'optionalAccess', _362 => _362.systemWorkflows]), () => ( []))).map((w) => [w.name, w]));
14548
14800
  }
14549
14801
  }
14550
14802
  // ============================================================================
@@ -14842,7 +15094,7 @@ var WorkflowService = class extends BaseService {
14842
15094
  var UserProfileService = class extends BaseService {
14843
15095
  constructor(adapter, options) {
14844
15096
  super(adapter);
14845
- this.auditService = _optionalChain([options, 'optionalAccess', _334 => _334.auditService]);
15097
+ this.auditService = _optionalChain([options, 'optionalAccess', _363 => _363.auditService]);
14846
15098
  }
14847
15099
  // ============================================================================
14848
15100
  // CACHE MANAGEMENT
@@ -14877,7 +15129,6 @@ var UserProfileService = class extends BaseService {
14877
15129
  * email: authUser.email,
14878
15130
  * firstName: authUser.user_metadata.first_name,
14879
15131
  * lastName: authUser.user_metadata.last_name,
14880
- * role: "member",
14881
15132
  * status: "active"
14882
15133
  * });
14883
15134
  * ```
@@ -14956,7 +15207,6 @@ var UserProfileService = class extends BaseService {
14956
15207
  * {
14957
15208
  * authId: authUser.id,
14958
15209
  * email: authUser.email,
14959
- * role: "member",
14960
15210
  * status: "active"
14961
15211
  * }
14962
15212
  * );
@@ -14981,7 +15231,6 @@ var UserProfileService = class extends BaseService {
14981
15231
  const changes = buildAuditChanges(existing, data, [
14982
15232
  "firstName",
14983
15233
  "lastName",
14984
- "role",
14985
15234
  "status"
14986
15235
  ]);
14987
15236
  if (changes.length > 0) {
@@ -15005,11 +15254,13 @@ var UserProfileService = class extends BaseService {
15005
15254
  */
15006
15255
  async deleteProfile(profileId, options) {
15007
15256
  const profile = await this.getProfileOrThrow(profileId);
15008
- if (_optionalChain([options, 'optionalAccess', _335 => _335.checkAdmin])) {
15009
- if (profile.role === "admin") {
15010
- const adminCount = await this.adapter.userProfiles.countByRole("admin");
15011
- if (adminCount <= 1) {
15012
- throw new Error("Cannot delete the last admin user");
15257
+ if (_optionalChain([options, 'optionalAccess', _364 => _364.checkAdmin]) && this.adapter.permissions) {
15258
+ const ownerCount = await this.adapter.permissions.countUsersWithRole("owner");
15259
+ if (ownerCount <= 1) {
15260
+ const userRoles = await this.adapter.permissions.getUserRoles(profileId);
15261
+ const isOwner = userRoles.some((r) => r.name === "owner");
15262
+ if (isOwner) {
15263
+ throw new Error("Cannot delete the last owner user");
15013
15264
  }
15014
15265
  }
15015
15266
  }
@@ -15045,15 +15296,6 @@ var UserProfileService = class extends BaseService {
15045
15296
  async updateLastLogin(profileId) {
15046
15297
  await this.adapter.userProfiles.updateLastLogin(profileId);
15047
15298
  }
15048
- /**
15049
- * Change user role
15050
- *
15051
- * @param profileId - Profile UUID
15052
- * @param newRole - New role
15053
- */
15054
- async changeRole(profileId, newRole) {
15055
- return await this.updateProfile(profileId, { role: newRole });
15056
- }
15057
15299
  /**
15058
15300
  * Change user status
15059
15301
  *
@@ -15075,19 +15317,6 @@ var UserProfileService = class extends BaseService {
15075
15317
  () => this.adapter.userProfiles.findByEmail(email)
15076
15318
  );
15077
15319
  }
15078
- /**
15079
- * Check if user has role
15080
- */
15081
- async hasRole(profileId, role) {
15082
- const profile = await this.getProfile(profileId);
15083
- return _optionalChain([profile, 'optionalAccess', _336 => _336.role]) === role;
15084
- }
15085
- /**
15086
- * Check if user is admin
15087
- */
15088
- async isAdmin(profileId) {
15089
- return await this.hasRole(profileId, "admin");
15090
- }
15091
15320
  /**
15092
15321
  * Invite a new user by email.
15093
15322
  *
@@ -15108,7 +15337,6 @@ var UserProfileService = class extends BaseService {
15108
15337
  * email: "john@example.com",
15109
15338
  * firstName: "John",
15110
15339
  * lastName: "Doe",
15111
- * role: "member",
15112
15340
  * redirectTo: "https://app.example.com/welcome",
15113
15341
  * });
15114
15342
  * // Email sent automatically, profile.status === "pending"
@@ -15514,7 +15742,7 @@ var DocumentTemplateService = class extends BaseService {
15514
15742
  * Includes both system templates and tenant-specific templates.
15515
15743
  */
15516
15744
  async listTemplates(options) {
15517
- if (_optionalChain([options, 'optionalAccess', _337 => _337.systemOnly])) {
15745
+ if (_optionalChain([options, 'optionalAccess', _365 => _365.systemOnly])) {
15518
15746
  return SYSTEM_TEMPLATES;
15519
15747
  }
15520
15748
  const templates = [...SYSTEM_TEMPLATES];
@@ -15597,8 +15825,8 @@ var DocumentTemplateService = class extends BaseService {
15597
15825
  var DocumentService = class extends BaseService {
15598
15826
  constructor(adapter, options) {
15599
15827
  super(adapter);
15600
- this.templateService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _338 => _338.templateService]), () => ( new DocumentTemplateService(adapter)));
15601
- this.fileService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _339 => _339.fileService]), () => ( null));
15828
+ this.templateService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _366 => _366.templateService]), () => ( new DocumentTemplateService(adapter)));
15829
+ this.fileService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _367 => _367.fileService]), () => ( null));
15602
15830
  }
15603
15831
  // ============================================================================
15604
15832
  // CREATE
@@ -15849,7 +16077,7 @@ var DocumentService = class extends BaseService {
15849
16077
  */
15850
16078
  async isComplete(documentId) {
15851
16079
  const document2 = await this.getDocument(documentId);
15852
- return _optionalChain([document2, 'optionalAccess', _340 => _340.status]) !== "draft";
16080
+ return _optionalChain([document2, 'optionalAccess', _368 => _368.status]) !== "draft";
15853
16081
  }
15854
16082
  /**
15855
16083
  * Get document with its template and slots.
@@ -16107,7 +16335,7 @@ var DocumentProcessingService = class extends BaseService {
16107
16335
  type: "signature",
16108
16336
  provider: this.config.signatureAdapter.name,
16109
16337
  input: { signers, ...options },
16110
- expiresAt: _optionalChain([options, 'optionalAccess', _341 => _341.expiresAt])
16338
+ expiresAt: _optionalChain([options, 'optionalAccess', _369 => _369.expiresAt])
16111
16339
  });
16112
16340
  return job;
16113
16341
  }
@@ -16264,7 +16492,7 @@ var DocumentProcessingService = class extends BaseService {
16264
16492
  }
16265
16493
  const document2 = await this.documentService.getDocumentOrThrow(documentId);
16266
16494
  const template = await this.templateService.getTemplateOrThrow(document2.templateId);
16267
- if (!_optionalChain([template, 'access', _342 => _342.autoProcessing, 'optionalAccess', _343 => _343.identityVerification, 'optionalAccess', _344 => _344.enabled])) {
16495
+ if (!_optionalChain([template, 'access', _370 => _370.autoProcessing, 'optionalAccess', _371 => _371.identityVerification, 'optionalAccess', _372 => _372.enabled])) {
16268
16496
  throw new Error("Identity verification is not enabled for this document type");
16269
16497
  }
16270
16498
  const job = await this.adapter.documentJobs.create({
@@ -16350,13 +16578,13 @@ var DocumentProcessingService = class extends BaseService {
16350
16578
  const template = await this.templateService.getTemplateOrThrow(document2.templateId);
16351
16579
  const slots = await this.documentService.getSlots(documentId);
16352
16580
  const jobs = [];
16353
- if (_optionalChain([template, 'access', _345 => _345.autoProcessing, 'optionalAccess', _346 => _346.ocr, 'optionalAccess', _347 => _347.enabled]) && this.config.ocrAdapter) {
16581
+ if (_optionalChain([template, 'access', _373 => _373.autoProcessing, 'optionalAccess', _374 => _374.ocr, 'optionalAccess', _375 => _375.enabled]) && this.config.ocrAdapter) {
16354
16582
  for (const slot of slots) {
16355
16583
  const job = await this.processOcr(documentId, slot.slotName);
16356
16584
  jobs.push(job);
16357
16585
  }
16358
16586
  }
16359
- if (_optionalChain([template, 'access', _348 => _348.autoProcessing, 'optionalAccess', _349 => _349.identityVerification, 'optionalAccess', _350 => _350.enabled]) && this.config.identityAdapter) {
16587
+ if (_optionalChain([template, 'access', _376 => _376.autoProcessing, 'optionalAccess', _377 => _377.identityVerification, 'optionalAccess', _378 => _378.enabled]) && this.config.identityAdapter) {
16360
16588
  const job = await this.verifyIdentity(documentId);
16361
16589
  jobs.push(job);
16362
16590
  }
@@ -16427,15 +16655,15 @@ var DocumentProcessingService = class extends BaseService {
16427
16655
  return {
16428
16656
  ocr: {
16429
16657
  available: !!this.config.ocrAdapter,
16430
- provider: _optionalChain([this, 'access', _351 => _351.config, 'access', _352 => _352.ocrAdapter, 'optionalAccess', _353 => _353.name])
16658
+ provider: _optionalChain([this, 'access', _379 => _379.config, 'access', _380 => _380.ocrAdapter, 'optionalAccess', _381 => _381.name])
16431
16659
  },
16432
16660
  signature: {
16433
16661
  available: !!this.config.signatureAdapter,
16434
- provider: _optionalChain([this, 'access', _354 => _354.config, 'access', _355 => _355.signatureAdapter, 'optionalAccess', _356 => _356.name])
16662
+ provider: _optionalChain([this, 'access', _382 => _382.config, 'access', _383 => _383.signatureAdapter, 'optionalAccess', _384 => _384.name])
16435
16663
  },
16436
16664
  identityVerification: {
16437
16665
  available: !!this.config.identityAdapter,
16438
- provider: _optionalChain([this, 'access', _357 => _357.config, 'access', _358 => _358.identityAdapter, 'optionalAccess', _359 => _359.name])
16666
+ provider: _optionalChain([this, 'access', _385 => _385.config, 'access', _386 => _386.identityAdapter, 'optionalAccess', _387 => _387.name])
16439
16667
  }
16440
16668
  };
16441
16669
  }
@@ -16445,7 +16673,7 @@ var DocumentProcessingService = class extends BaseService {
16445
16673
  var FileService = class extends BaseService {
16446
16674
  constructor(adapter, options) {
16447
16675
  super(adapter);
16448
- this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _360 => _360.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
16676
+ this.auditService = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _388 => _388.auditService]), () => ( (adapter.audit ? new AuditService(adapter) : void 0)));
16449
16677
  }
16450
16678
  // ============================================================================
16451
16679
  // UPLOAD (requires StorageAdapter)
@@ -16584,7 +16812,7 @@ var FileService = class extends BaseService {
16584
16812
  */
16585
16813
  async getFile(fileId) {
16586
16814
  const file2 = await this.adapter.files.findById(fileId);
16587
- if (_optionalChain([file2, 'optionalAccess', _361 => _361.deletedAt])) {
16815
+ if (_optionalChain([file2, 'optionalAccess', _389 => _389.deletedAt])) {
16588
16816
  return null;
16589
16817
  }
16590
16818
  return file2;
@@ -16646,12 +16874,12 @@ var FileService = class extends BaseService {
16646
16874
  */
16647
16875
  async deleteFile(fileId, options) {
16648
16876
  const file2 = await this.getFileOrThrow(fileId);
16649
- if (_optionalChain([options, 'optionalAccess', _362 => _362.checkOwnership]) && options.userId) {
16877
+ if (_optionalChain([options, 'optionalAccess', _390 => _390.checkOwnership]) && options.userId) {
16650
16878
  if (file2.uploadedBy !== options.userId) {
16651
16879
  throw new Error("You can only delete files you uploaded");
16652
16880
  }
16653
16881
  }
16654
- if (_optionalChain([options, 'optionalAccess', _363 => _363.hard])) {
16882
+ if (_optionalChain([options, 'optionalAccess', _391 => _391.hard])) {
16655
16883
  await this.adapter.files.hardDelete(fileId);
16656
16884
  } else {
16657
16885
  await this.adapter.files.delete(fileId);
@@ -16682,7 +16910,7 @@ var FileService = class extends BaseService {
16682
16910
  }
16683
16911
  const file2 = await this.getFileOrThrow(fileId);
16684
16912
  await this.adapter.storage.delete(file2.storagePath);
16685
- if (_optionalChain([options, 'optionalAccess', _364 => _364.hard])) {
16913
+ if (_optionalChain([options, 'optionalAccess', _392 => _392.hard])) {
16686
16914
  await this.adapter.files.hardDelete(fileId);
16687
16915
  } else {
16688
16916
  await this.adapter.files.delete(fileId);
@@ -16708,15 +16936,15 @@ var FileService = class extends BaseService {
16708
16936
  const fileResults = await Promise.all(fileIds.map((id) => this.getFile(id)));
16709
16937
  const files = fileResults.filter((f) => f !== null);
16710
16938
  if (files.length === 0) return;
16711
- if (_optionalChain([options, 'optionalAccess', _365 => _365.deleteFromStorage]) && this.adapter.storage) {
16939
+ if (_optionalChain([options, 'optionalAccess', _393 => _393.deleteFromStorage]) && this.adapter.storage) {
16712
16940
  const BATCH_SIZE = 10;
16713
16941
  for (let i = 0; i < files.length; i += BATCH_SIZE) {
16714
16942
  const batch = files.slice(i, i + BATCH_SIZE);
16715
- await Promise.all(batch.map((file2) => _optionalChain([this, 'access', _366 => _366.adapter, 'access', _367 => _367.storage, 'optionalAccess', _368 => _368.delete, 'call', _369 => _369(file2.storagePath)])));
16943
+ await Promise.all(batch.map((file2) => _optionalChain([this, 'access', _394 => _394.adapter, 'access', _395 => _395.storage, 'optionalAccess', _396 => _396.delete, 'call', _397 => _397(file2.storagePath)])));
16716
16944
  }
16717
16945
  }
16718
16946
  const idsToDelete = files.map((f) => f.id);
16719
- if (_optionalChain([options, 'optionalAccess', _370 => _370.hard])) {
16947
+ if (_optionalChain([options, 'optionalAccess', _398 => _398.hard])) {
16720
16948
  await Promise.all(idsToDelete.map((id) => this.adapter.files.hardDelete(id)));
16721
16949
  } else {
16722
16950
  await Promise.all(idsToDelete.map((id) => this.adapter.files.delete(id)));
@@ -16724,12 +16952,12 @@ var FileService = class extends BaseService {
16724
16952
  if (this.auditService && this.userId) {
16725
16953
  await Promise.all(
16726
16954
  files.map(
16727
- (file2) => _optionalChain([this, 'access', _371 => _371.auditService, 'optionalAccess', _372 => _372.logFileAction, 'call', _373 => _373({
16955
+ (file2) => _optionalChain([this, 'access', _399 => _399.auditService, 'optionalAccess', _400 => _400.logFileAction, 'call', _401 => _401({
16728
16956
  action: "file.deleted",
16729
16957
  actorId: _nullishCoalesce(this.userId, () => ( "")),
16730
16958
  fileId: file2.id,
16731
16959
  fileName: file2.name,
16732
- metadata: { deletedFromStorage: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _374 => _374.deleteFromStorage]), () => ( false)) }
16960
+ metadata: { deletedFromStorage: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _402 => _402.deleteFromStorage]), () => ( false)) }
16733
16961
  })])
16734
16962
  )
16735
16963
  );
@@ -16807,7 +17035,7 @@ var FileService = class extends BaseService {
16807
17035
  if (!file2) {
16808
17036
  return false;
16809
17037
  }
16810
- if (_optionalChain([options, 'optionalAccess', _375 => _375.isAdmin])) {
17038
+ if (_optionalChain([options, 'optionalAccess', _403 => _403.isAdmin])) {
16811
17039
  return true;
16812
17040
  }
16813
17041
  if (file2.visibility === "public") {
@@ -16817,7 +17045,7 @@ var FileService = class extends BaseService {
16817
17045
  return true;
16818
17046
  }
16819
17047
  if (file2.visibility === "restricted") {
16820
- return _nullishCoalesce(_optionalChain([file2, 'access', _376 => _376.allowedUsers, 'optionalAccess', _377 => _377.includes, 'call', _378 => _378(userId)]), () => ( false));
17048
+ return _nullishCoalesce(_optionalChain([file2, 'access', _404 => _404.allowedUsers, 'optionalAccess', _405 => _405.includes, 'call', _406 => _406(userId)]), () => ( false));
16821
17049
  }
16822
17050
  return false;
16823
17051
  }
@@ -16912,7 +17140,7 @@ function withTimeout(promise, ms, label) {
16912
17140
  var GeocodingService = class {
16913
17141
  constructor(adapter, options) {
16914
17142
  this.adapter = adapter;
16915
- this.timeoutMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _379 => _379.timeoutMs]), () => ( GEOCODING_TIMEOUT_MS));
17143
+ this.timeoutMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _407 => _407.timeoutMs]), () => ( GEOCODING_TIMEOUT_MS));
16916
17144
  }
16917
17145
  /**
16918
17146
  * Search for address suggestions as the user types
@@ -16967,16 +17195,24 @@ var GlobalSearchService = class extends BaseService {
16967
17195
  if (!query || query.trim().length === 0) {
16968
17196
  return { results: [], total: 0 };
16969
17197
  }
16970
- return this.cachedList(
16971
- "globalSearch",
16972
- "search",
16973
- { query: query.trim(), ...options },
16974
- () => this.adapter.objectRecords.globalSearch(query.trim(), {
16975
- limit: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _380 => _380.limit]), () => ( 20)),
16976
- offset: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _381 => _381.offset]), () => ( 0)),
16977
- objectNames: _optionalChain([options, 'optionalAccess', _382 => _382.objectNames])
16978
- })
16979
- );
17198
+ const trimmed = query.trim();
17199
+ if (this.adapter.search) {
17200
+ try {
17201
+ const raw = await this.adapter.search.globalSearch(trimmed, {
17202
+ objectNames: _optionalChain([options, 'optionalAccess', _408 => _408.objectNames]),
17203
+ limit: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _409 => _409.limit]), () => ( 20)),
17204
+ offset: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _410 => _410.offset]), () => ( 0))
17205
+ });
17206
+ return await this.healGlobalSearchResults(raw);
17207
+ } catch (err) {
17208
+ console.error("[search] External search failed, falling back to PostgreSQL", err);
17209
+ }
17210
+ }
17211
+ return this.adapter.objectRecords.globalSearch(trimmed, {
17212
+ limit: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _411 => _411.limit]), () => ( 20)),
17213
+ offset: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _412 => _412.offset]), () => ( 0)),
17214
+ objectNames: _optionalChain([options, 'optionalAccess', _413 => _413.objectNames])
17215
+ });
16980
17216
  }
16981
17217
  /**
16982
17218
  * Search and group results by object type.
@@ -16990,15 +17226,72 @@ var GlobalSearchService = class extends BaseService {
16990
17226
  if (!query || query.trim().length === 0) {
16991
17227
  return { groups: [], total: 0 };
16992
17228
  }
16993
- return this.cachedList(
16994
- "globalSearch",
16995
- "grouped",
16996
- { query: query.trim(), ...options },
16997
- () => this.adapter.objectRecords.globalSearchGrouped(query.trim(), {
16998
- objectNames: _optionalChain([options, 'optionalAccess', _383 => _383.objectNames]),
16999
- limitPerGroup: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _384 => _384.limitPerGroup]), () => ( 5))
17000
- })
17001
- );
17229
+ const trimmed = query.trim();
17230
+ if (this.adapter.search) {
17231
+ try {
17232
+ const raw = await this.adapter.search.globalSearchGrouped(trimmed, {
17233
+ objectNames: _optionalChain([options, 'optionalAccess', _414 => _414.objectNames])
17234
+ });
17235
+ return await this.healGroupedSearchResults(raw);
17236
+ } catch (err) {
17237
+ console.error("[search] External grouped search failed, falling back to PostgreSQL", err);
17238
+ }
17239
+ }
17240
+ return this.adapter.objectRecords.globalSearchGrouped(trimmed, {
17241
+ objectNames: _optionalChain([options, 'optionalAccess', _415 => _415.objectNames]),
17242
+ limitPerGroup: _nullishCoalesce(_optionalChain([options, 'optionalAccess', _416 => _416.limitPerGroup]), () => ( 5))
17243
+ });
17244
+ }
17245
+ // ==========================================================================
17246
+ // Self-healing: ghost record cleanup
17247
+ // ==========================================================================
17248
+ /**
17249
+ * Verify Meilisearch results against PostgreSQL and remove ghost records.
17250
+ * GlobalSearchResultItem uses `recordId` (not `id`) as the record identifier.
17251
+ */
17252
+ async healGlobalSearchResults(meiliResult) {
17253
+ const { search } = this.adapter;
17254
+ if (!search || meiliResult.results.length === 0) {
17255
+ return meiliResult;
17256
+ }
17257
+ const ids = meiliResult.results.map((r) => r.recordId);
17258
+ const existing = await this.adapter.objectRecords.findByIds(ids);
17259
+ const existingSet = new Set(existing.map((r) => r.id));
17260
+ const ghosts = ids.filter((id) => !existingSet.has(id));
17261
+ if (ghosts.length > 0) {
17262
+ Promise.all(ghosts.map((id) => search.removeRecord(id))).catch(
17263
+ (err) => console.error("[search] Failed to clean ghost records", err)
17264
+ );
17265
+ }
17266
+ return {
17267
+ results: meiliResult.results.filter((r) => existingSet.has(r.recordId)),
17268
+ total: meiliResult.total - ghosts.length
17269
+ };
17270
+ }
17271
+ /**
17272
+ * Verify grouped Meilisearch results against PostgreSQL and remove ghost records.
17273
+ * Filters ghosts from each group and removes empty groups.
17274
+ */
17275
+ async healGroupedSearchResults(raw) {
17276
+ const { search } = this.adapter;
17277
+ if (!search) return raw;
17278
+ const allIds = raw.groups.flatMap((g) => g.results.map((r) => r.recordId));
17279
+ if (allIds.length === 0) return raw;
17280
+ const existing = await this.adapter.objectRecords.findByIds(allIds);
17281
+ const existingSet = new Set(existing.map((r) => r.id));
17282
+ const ghosts = allIds.filter((id) => !existingSet.has(id));
17283
+ if (ghosts.length > 0) {
17284
+ Promise.all(ghosts.map((id) => search.removeRecord(id))).catch(
17285
+ (err) => console.error("[search] Failed to clean ghost records", err)
17286
+ );
17287
+ }
17288
+ return {
17289
+ groups: raw.groups.map((g) => {
17290
+ const filtered = g.results.filter((r) => existingSet.has(r.recordId));
17291
+ return { ...g, results: filtered, totalInGroup: filtered.length };
17292
+ }).filter((g) => g.results.length > 0),
17293
+ total: raw.total - ghosts.length
17294
+ };
17002
17295
  }
17003
17296
  };
17004
17297
 
@@ -17013,7 +17306,7 @@ var PermissionService = class extends BaseService {
17013
17306
  }
17014
17307
  this.permissionsRepo = adapter.permissions;
17015
17308
  this.permissionCache = _nullishCoalesce(adapter.cache, () => ( new NoopCacheAdapter()));
17016
- this.auditService = _optionalChain([options, 'optionalAccess', _385 => _385.auditService]);
17309
+ this.auditService = _optionalChain([options, 'optionalAccess', _417 => _417.auditService]);
17017
17310
  }
17018
17311
  // ============================================================================
17019
17312
  // PERMISSION CHECKS
@@ -17032,11 +17325,11 @@ var PermissionService = class extends BaseService {
17032
17325
  return true;
17033
17326
  }
17034
17327
  const wildcardPerms = permissions.objectPermissions["*"];
17035
- if (_optionalChain([wildcardPerms, 'optionalAccess', _386 => _386.includes, 'call', _387 => _387(action)])) {
17328
+ if (_optionalChain([wildcardPerms, 'optionalAccess', _418 => _418.includes, 'call', _419 => _419(action)])) {
17036
17329
  return true;
17037
17330
  }
17038
17331
  const objectPerms = permissions.objectPermissions[objectName];
17039
- return _nullishCoalesce(_optionalChain([objectPerms, 'optionalAccess', _388 => _388.includes, 'call', _389 => _389(action)]), () => ( false));
17332
+ return _nullishCoalesce(_optionalChain([objectPerms, 'optionalAccess', _420 => _420.includes, 'call', _421 => _421(action)]), () => ( false));
17040
17333
  }
17041
17334
  /**
17042
17335
  * Check if user can access an object, throw ForbiddenError if not.
@@ -17091,12 +17384,12 @@ var PermissionService = class extends BaseService {
17091
17384
  if (permissions.isAdmin) {
17092
17385
  return true;
17093
17386
  }
17094
- const wildcardPerms = _optionalChain([permissions, 'access', _390 => _390.systemPermissions, 'optionalAccess', _391 => _391["*"]]);
17095
- if (_optionalChain([wildcardPerms, 'optionalAccess', _392 => _392.includes, 'call', _393 => _393(action)])) {
17387
+ const wildcardPerms = _optionalChain([permissions, 'access', _422 => _422.systemPermissions, 'optionalAccess', _423 => _423["*"]]);
17388
+ if (_optionalChain([wildcardPerms, 'optionalAccess', _424 => _424.includes, 'call', _425 => _425(action)])) {
17096
17389
  return true;
17097
17390
  }
17098
- const resourcePerms = _optionalChain([permissions, 'access', _394 => _394.systemPermissions, 'optionalAccess', _395 => _395[resource]]);
17099
- return _nullishCoalesce(_optionalChain([resourcePerms, 'optionalAccess', _396 => _396.includes, 'call', _397 => _397(action)]), () => ( false));
17391
+ const resourcePerms = _optionalChain([permissions, 'access', _426 => _426.systemPermissions, 'optionalAccess', _427 => _427[resource]]);
17392
+ return _nullishCoalesce(_optionalChain([resourcePerms, 'optionalAccess', _428 => _428.includes, 'call', _429 => _429(action)]), () => ( false));
17100
17393
  }
17101
17394
  /**
17102
17395
  * Check if user can access a system resource, throw ForbiddenError if not.
@@ -17125,8 +17418,8 @@ var PermissionService = class extends BaseService {
17125
17418
  if (permissions.isAdmin) {
17126
17419
  return { canRead: true, canCreate: true, canUpdate: true, canDelete: true };
17127
17420
  }
17128
- const wildcardPerms = _nullishCoalesce(_optionalChain([permissions, 'access', _398 => _398.systemPermissions, 'optionalAccess', _399 => _399["*"]]), () => ( []));
17129
- const resourcePerms = _nullishCoalesce(_optionalChain([permissions, 'access', _400 => _400.systemPermissions, 'optionalAccess', _401 => _401[resource]]), () => ( []));
17421
+ const wildcardPerms = _nullishCoalesce(_optionalChain([permissions, 'access', _430 => _430.systemPermissions, 'optionalAccess', _431 => _431["*"]]), () => ( []));
17422
+ const resourcePerms = _nullishCoalesce(_optionalChain([permissions, 'access', _432 => _432.systemPermissions, 'optionalAccess', _433 => _433[resource]]), () => ( []));
17130
17423
  const allPerms = /* @__PURE__ */ new Set([...wildcardPerms, ...resourcePerms]);
17131
17424
  return {
17132
17425
  canRead: allPerms.has("read"),
@@ -17269,7 +17562,7 @@ var PermissionService = class extends BaseService {
17269
17562
  action: "role.updated",
17270
17563
  actorId: this.userId,
17271
17564
  roleId,
17272
- roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _402 => _402.label]), () => ( roleId)),
17565
+ roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _434 => _434.label]), () => ( roleId)),
17273
17566
  metadata: { permissionsUpdated: true, permissionCount: permissions.length }
17274
17567
  });
17275
17568
  }
@@ -17299,7 +17592,7 @@ var PermissionService = class extends BaseService {
17299
17592
  action: "role.assigned",
17300
17593
  actorId: this.userId,
17301
17594
  roleId,
17302
- roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _403 => _403.label]), () => ( roleId)),
17595
+ roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _435 => _435.label]), () => ( roleId)),
17303
17596
  targetUserId: userProfileId
17304
17597
  });
17305
17598
  }
@@ -17317,7 +17610,7 @@ var PermissionService = class extends BaseService {
17317
17610
  action: "role.revoked",
17318
17611
  actorId: this.userId,
17319
17612
  roleId,
17320
- roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _404 => _404.label]), () => ( roleId)),
17613
+ roleLabel: _nullishCoalesce(_optionalChain([role, 'optionalAccess', _436 => _436.label]), () => ( roleId)),
17321
17614
  targetUserId: userProfileId
17322
17615
  });
17323
17616
  }
@@ -17348,7 +17641,7 @@ var PermissionService = class extends BaseService {
17348
17641
  DEFAULT_ROLE_LABELS,
17349
17642
  DEFAULT_ROLE_DESCRIPTIONS,
17350
17643
  DEFAULT_ROLE_PERMISSIONS
17351
- } = await Promise.resolve().then(() => _interopRequireWildcard(require("./default-roles-C3FYDYMN.js")));
17644
+ } = await Promise.resolve().then(() => _interopRequireWildcard(require("./default-roles-76HUWY6T.js")));
17352
17645
  const existingRoles = await this.getRoles();
17353
17646
  const existingRoleNames = existingRoles.reduce((set, r) => set.add(r.name), /* @__PURE__ */ new Set());
17354
17647
  for (const roleName of Object.values(DEFAULT_ROLES)) {
@@ -17792,7 +18085,7 @@ var ViewService = class extends BaseService {
17792
18085
  dbView.objectName,
17793
18086
  dbView.type,
17794
18087
  objectDefinition,
17795
- dbView.type === "detail" ? _nullishCoalesce(_optionalChain([dbView, 'access', _405 => _405.config, 'optionalAccess', _406 => _406.layout]), () => ( "page")) : void 0
18088
+ dbView.type === "detail" ? _nullishCoalesce(_optionalChain([dbView, 'access', _437 => _437.config, 'optionalAccess', _438 => _438.layout]), () => ( "page")) : void 0
17796
18089
  );
17797
18090
  const newConfig = generated.config;
17798
18091
  const updated = await this.adapter.views.update(viewId, { config: newConfig });
@@ -18186,7 +18479,7 @@ async function syncSingleObject(adapter, nativeObject, result, options) {
18186
18479
  `Cannot sync shared object "${nativeObject.name}": masterTenantId must be configured in tenant options`
18187
18480
  );
18188
18481
  }
18189
- if (options.tenantId && options.tenantId !== options.masterTenantId) {
18482
+ if (!options.tenantId || options.tenantId !== options.masterTenantId) {
18190
18483
  throw new Error(
18191
18484
  `Cannot sync shared object "${nativeObject.name}": only master tenant "${options.masterTenantId}" can sync shared objects (current: "${options.tenantId}")`
18192
18485
  );
@@ -18194,12 +18487,13 @@ async function syncSingleObject(adapter, nativeObject, result, options) {
18194
18487
  }
18195
18488
  const existingObject = await adapter.objects.findSystemByName(nativeObject.name);
18196
18489
  const isNew = !existingObject;
18197
- updateObjectStats(result, isNew);
18198
18490
  if (options.dryRun) {
18491
+ updateObjectStats(result, isNew);
18199
18492
  await handleDryRun(adapter, nativeObject, existingObject, result, options, isNew);
18200
18493
  return;
18201
18494
  }
18202
18495
  const dbObject = await upsertObject(adapter, nativeObject, options);
18496
+ updateObjectStats(result, isNew);
18203
18497
  await syncAttributes(adapter, nativeObject, dbObject, existingObject, result);
18204
18498
  if (!isNew) {
18205
18499
  await cleanupAttributes(adapter, dbObject.id, nativeObject, result);
@@ -18228,6 +18522,11 @@ async function handleDryRun(adapter, nativeObject, existingObject, result, optio
18228
18522
  }
18229
18523
  result.attributesSynced++;
18230
18524
  }
18525
+ const codeAttributeNames = nativeObject.attributes.map((attr) => attr.name);
18526
+ const wouldBeDeleted = existingAttrs.filter(
18527
+ (a) => a.system && !codeAttributeNames.includes(a.name)
18528
+ );
18529
+ result.attributesDeleted += wouldBeDeleted.length;
18231
18530
  }
18232
18531
  async function upsertObject(adapter, nativeObject, _options) {
18233
18532
  return await adapter.objects.upsert({
@@ -18663,4 +18962,7 @@ var NoopGeocodingAdapter = class {
18663
18962
 
18664
18963
 
18665
18964
 
18666
- exports.IDENTITY_PROPERTIES = IDENTITY_PROPERTIES; exports.BEHAVIOR_PROPERTIES = BEHAVIOR_PROPERTIES; exports.PRESENTATION_PROPERTIES = PRESENTATION_PROPERTIES; exports.isIdentityProperty = isIdentityProperty; exports.isBehaviorProperty = isBehaviorProperty; exports.isPresentationProperty = isPresentationProperty; exports.RELATION_TARGET_ANY = RELATION_TARGET_ANY; exports.isUniversalRelation = isUniversalRelation; exports.isBilateralRelation = isBilateralRelation; exports.inferInverseCardinality = inferInverseCardinality; exports.RecordReferencedError = RecordReferencedError; exports.AttributeInUseError = AttributeInUseError; exports.ObjectReferencedError = ObjectReferencedError; exports.getErrorMessage = getErrorMessage; exports.NoopGeocodingAdapter = NoopGeocodingAdapter; exports.SYSTEM_FIELD_NAMES = SYSTEM_FIELD_NAMES; exports.RESERVED_ATTRIBUTE_NAMES = RESERVED_ATTRIBUTE_NAMES; exports.PolicyViolationError = PolicyViolationError; exports.FORBIDDEN_PROPERTY_TYPES = FORBIDDEN_PROPERTY_TYPES; exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES; exports.getSystemAttributeList = getSystemAttributeList; exports.isSystemAttribute = isSystemAttribute; exports.isSystemAttributeObject = isSystemAttributeObject; exports.isSimpleFormNode = isSimpleFormNode; exports.isAdvancedFormNode = isAdvancedFormNode; exports.isStartNode = isStartNode; exports.isFormNode = isFormNode; exports.isConditionNode = isConditionNode; exports.isDocumentNode = isDocumentNode; exports.isEndNode = isEndNode; exports.getNodeOutputs = getNodeOutputs; exports.isConditionRule = isConditionRule; exports.isConditionGroup = isConditionGroup; exports.eq = eq; exports.neq = neq; exports.and = and; exports.or = or; exports.inValues = inValues; exports.isWorkflowDefinition = isWorkflowDefinition; exports.isWorkflowPublished = isWorkflowPublished; exports.isSystemWorkflow = isSystemWorkflow; exports.isInstanceTerminal = isInstanceTerminal; exports.isInstanceWaiting = isInstanceWaiting; exports.canResumeInstance = canResumeInstance; exports.createStartTransition = createStartTransition; exports.isInvitationValid = isInvitationValid; exports.isInvitationAccepted = isInvitationAccepted; exports.isInvitationExpired = isInvitationExpired; exports.isGrantValid = isGrantValid; exports.isGrantRevoked = isGrantRevoked; exports.isTokenRevoked = isTokenRevoked; exports.isGrantExpired = isGrantExpired; exports.canAccessNode = canAccessNode; exports.createEmptyContext = createEmptyContext; exports.getContextValue = getContextValue; exports.setContextValue = setContextValue; exports.DEFAULT_THEME = DEFAULT_THEME; exports.mergeWithDefaults = mergeWithDefaults; exports.generateCssVariables = generateCssVariables; exports.isInstanceEvent = isInstanceEvent; exports.isNodeEvent = isNodeEvent; exports.isInvitationOrGrantEvent = isInvitationOrGrantEvent; exports.ConditionOperatorSchema = ConditionOperatorSchema; exports.ConditionRuleSchema = ConditionRuleSchema; exports.ConditionGroupSchema = ConditionGroupSchema; exports.StartNodeSchema = StartNodeSchema; exports.FormFieldRefSchema = FormFieldRefSchema; exports.FlowRowFieldSchema = FlowRowFieldSchema; exports.FlowRowSchema = FlowRowSchema; exports.FormNodeSchema = FormNodeSchema; exports.ConditionNodeSchema = ConditionNodeSchema; exports.DocumentNodeSchema = DocumentNodeSchema; exports.EndNodeSchema = EndNodeSchema; exports.WorkflowNodeSchema = WorkflowNodeSchema; exports.SlotModeSchema = SlotModeSchema; exports.WorkflowSlotSchema = WorkflowSlotSchema; exports.AuthMethodSchema = AuthMethodSchema; exports.ShareStatusSchema = ShareStatusSchema; exports.WorkflowShareSchema = WorkflowShareSchema; exports.CreateShareInputSchema = CreateShareInputSchema; exports.NodePositionSchema = NodePositionSchema; exports.ViewportSchema = ViewportSchema; exports.WorkflowLayoutSchema = WorkflowLayoutSchema; exports.ThemeColorsSchema = ThemeColorsSchema; exports.ThemeLogoSchema = ThemeLogoSchema; exports.WorkflowThemeSchema = WorkflowThemeSchema; exports.WorkflowConfigSchema = WorkflowConfigSchema; exports.WorkflowStatusSchema = WorkflowStatusSchema; exports.WorkflowDefinitionSchema = WorkflowDefinitionSchema; exports.isEmpty = isEmpty; exports.isNotEmpty = isNotEmpty; exports.toUndefinedIfEmpty = toUndefinedIfEmpty; exports.hasProperties = hasProperties; exports.EMPTY_VALUE_PLACEHOLDER = EMPTY_VALUE_PLACEHOLDER; exports.formatAttributeValue = formatAttributeValue; exports.DEFAULT_LABEL_FALLBACK = DEFAULT_LABEL_FALLBACK; exports.renderLabelExpression = renderLabelExpression; exports.isLabelExpression = isLabelExpression; exports.extractAttributeNames = extractAttributeNames; exports.enrichValuesForDisplay = enrichValuesForDisplay; exports.enrichValuesWithSelectLabels = enrichValuesWithSelectLabels; exports.extractRelationIds = extractRelationIds; exports.computeLabelWithRelations = computeLabelWithRelations; exports.SchemaErrorCode = SchemaErrorCode; exports.SchemaError = SchemaError; exports.NotFoundError = NotFoundError; exports.ObjectNotFoundError = ObjectNotFoundError; exports.AttributeNotFoundError = AttributeNotFoundError; exports.RecordNotFoundError = RecordNotFoundError; exports.UserProfileNotFoundError = UserProfileNotFoundError; exports.FileNotFoundError = FileNotFoundError; exports.ValidationError = ValidationError; exports.ProtectedResourceError = ProtectedResourceError; exports.SyncError = SyncError; exports.NotSystemObjectError = NotSystemObjectError; exports.DuplicateError = DuplicateError; exports.isSchemaError = isSchemaError; exports.isNotFoundError = isNotFoundError; exports.isValidationError = isValidationError; exports.isProtectedResourceError = isProtectedResourceError; exports.ForbiddenError = ForbiddenError; exports.ProtectedRoleError = ProtectedRoleError; exports.RoleNotFoundError = RoleNotFoundError; exports.isForbiddenError = isForbiddenError; exports.ConcurrentModificationError = ConcurrentModificationError; exports.text = text; exports.textarea = textarea; exports.richtext = richtext; exports.number = number; exports.checkbox = checkbox; exports.date = date; exports.phone = phone; exports.currency = currency; exports.status = status; exports.select = select; exports.multiselect = multiselect; exports.location = location; exports.file = file; exports.user = user; exports.relation = relation; exports.rating = rating; exports.formula = formula; exports.rollup = rollup; exports.document = document; exports.ObjectBuilder = ObjectBuilder; exports.object = object; exports.GroupBuilder = GroupBuilder; exports.RelationGroupBuilder = RelationGroupBuilder; exports.TableTabConfig = TableTabConfig; exports.CustomTabConfig = CustomTabConfig; exports.RichtextTabConfig = RichtextTabConfig; exports.ActivityTabConfig = ActivityTabConfig; exports.FlowsTabConfig = FlowsTabConfig; exports.DocumentsTabConfig = DocumentsTabConfig; exports.TabBuilder = TabBuilder; exports.DetailViewBuilder = DetailViewBuilder; exports.ViewBuilder = ViewBuilder; exports.detailView = detailView; exports.view = view; exports.ListViewBuilder = ListViewBuilder; exports.ListViewTabConfigBuilder = ListViewTabConfigBuilder; exports.listView = listView; exports.group = group; exports.relationGroup = relationGroup; exports.WorkflowFormRowBuilder = WorkflowFormRowBuilder; exports.WorkflowFormBuilder = WorkflowFormBuilder; exports.WorkflowSimpleFormBuilder = WorkflowSimpleFormBuilder; exports.WorkflowConditionBuilder = WorkflowConditionBuilder; exports.WorkflowEndBuilder = WorkflowEndBuilder; exports.WorkflowStartBuilder = WorkflowStartBuilder; exports.WorkflowBuilder = WorkflowBuilder; exports.workflow = workflow; exports.registry = registry; exports.SYSTEM_TEMPLATE_IDS = SYSTEM_TEMPLATE_IDS; exports.FRENCH_ID_CARD = FRENCH_ID_CARD; exports.PASSPORT = PASSPORT; exports.DRIVING_LICENSE = DRIVING_LICENSE; exports.PROOF_OF_ADDRESS = PROOF_OF_ADDRESS; exports.SIGNABLE_CONTRACT = SIGNABLE_CONTRACT; exports.GENERIC_DOCUMENT = GENERIC_DOCUMENT; exports.SYSTEM_TEMPLATES = SYSTEM_TEMPLATES; exports.getSystemTemplate = getSystemTemplate; exports.isSystemTemplate = isSystemTemplate; exports.WorkflowJwtService = WorkflowJwtService; exports.hashOptions = hashOptions; exports.cacheKeys = cacheKeys; exports.cacheTtl = cacheTtl; exports.defaultTtl = defaultTtl; exports.NoopCacheAdapter = NoopCacheAdapter; exports.formatRecord = formatRecord; exports.formatRecords = formatRecords; exports.createDefaultState = createDefaultState; exports.SHORTCUT_TO_FILTER_OPERATOR = SHORTCUT_TO_FILTER_OPERATOR; exports.QueryNoResultError = QueryNoResultError; exports.QueryMultipleResultsError = QueryMultipleResultsError; exports.TenantContextError = TenantContextError; exports.FeatureFlagsContextError = FeatureFlagsContextError; exports.isFeatureEnabled = isFeatureEnabled; exports.getFeatureValue = getFeatureValue; exports.getFeatureFlags = getFeatureFlags; exports.tryGetFeatureValue = tryGetFeatureValue; exports.hasFeatureFlagsContext = hasFeatureFlagsContext; exports.runWithFeatureFlags = runWithFeatureFlags; exports.withFeatureFlags = withFeatureFlags; exports.getSchemaFromContext = getSchemaFromContext; exports.getSchemaByNameFromContext = getSchemaByNameFromContext; exports.hasSchemaContext = hasSchemaContext; exports.getSchemaContext = getSchemaContext; exports.addSchemaToContext = addSchemaToContext; exports.runWithSchemaContext = runWithSchemaContext; exports.runWithMergedSchemaContext = runWithMergedSchemaContext; exports.getContext = getContext2; exports.getTenantId = getTenantId; exports.getUserId = getUserId; exports.hasContext = hasContext; exports.runWithContext = runWithContext; exports.withTenantContext = withTenantContext; exports.QueryBuilder = QueryBuilder; exports.createQueryBuilder = createQueryBuilder; exports.evaluateCondition = evaluateCondition; exports.evaluate = evaluate; exports.evaluateWithTrace = evaluateWithTrace; exports.ExecutorRegistry = ExecutorRegistry; exports.success = success; exports.wait = wait; exports.complete = complete; exports.error = error; exports.ConditionExecutor = ConditionExecutor; exports.DocumentExecutor = DocumentExecutor; exports.EndExecutor = EndExecutor; exports.FormExecutor = FormExecutor; exports.StartExecutor = StartExecutor; exports.createDefaultExecutorRegistry = createDefaultExecutorRegistry; exports.getDefaultExecutorRegistry = getDefaultExecutorRegistry; exports.evaluateFormula = evaluateFormula; exports.evaluateFormulaWithResult = evaluateFormulaWithResult; exports.formatFormulaResult = formatFormulaResult; exports.evaluateFormulaAttribute = evaluateFormulaAttribute; exports.validateFormulaExpression = validateFormulaExpression; exports.extractFormulaVariables = extractFormulaVariables; exports.extractRelationReferences = extractRelationReferences; exports.extractRelationNames = extractRelationNames; exports.hasRelationReferences = hasRelationReferences; exports.flattenRelationsForEval = flattenRelationsForEval; exports.evaluateFormulaWithRelations = evaluateFormulaWithRelations; exports.evaluateFormulaAttributeWithRelations = evaluateFormulaAttributeWithRelations; exports.InvalidPathError = InvalidPathError; exports.MaxDepthExceededError = MaxDepthExceededError; exports.parsePath = parsePath; exports.validatePath = validatePath; exports.pathHasManyCardinality = pathHasManyCardinality; exports.getPathDepth = getPathDepth; exports.getTargetAttributeName = getTargetAttributeName; exports.getRelationPath = getRelationPath; exports.traversePath = traversePath; exports.resolveSingleValue = resolveSingleValue; exports.resolveMultiplePaths = resolveMultiplePaths; exports.NoopHookRegistry = NoopHookRegistry; exports.createMockAdapter = createMockAdapter; exports.PolicyRegistry = PolicyRegistry; exports.defaultPolicyRegistry = defaultPolicyRegistry; exports.BaseService = BaseService; exports.BaseRepository = BaseRepository; exports.SchemaContextAwareRepository = SchemaContextAwareRepository; exports.buildAuditChanges = buildAuditChanges; exports.ObjectSchemaService = ObjectSchemaService; exports.AuditService = AuditService; exports.UserService = UserService; exports.applyDefaultValues = applyDefaultValues; exports.checkPermission = checkPermission; exports.getPolicy = getPolicy; exports.buildPolicyContext = buildPolicyContext; exports.checkRecordAccess = checkRecordAccess; exports.checkRecordModifyOrThrow = checkRecordModifyOrThrow; exports.checkRecordDeleteOrThrow = checkRecordDeleteOrThrow; exports.checkSharedObjectWriteAccess = checkSharedObjectWriteAccess; exports.computeLabel = computeLabel; exports.enrichWithFormulas = enrichWithFormulas; exports.enrichRecordsWithFormulas = enrichRecordsWithFormulas; exports.createContextForCreate = createContextForCreate; exports.createContextForUpdate = createContextForUpdate; exports.createContextForDelete = createContextForDelete; exports.createContextForRestore = createContextForRestore; exports.recalculateParentRollups = recalculateParentRollups; exports.RelationPropertiesService = RelationPropertiesService; exports.RecordQueryService = RecordQueryService; exports.RecordResolverService = RecordResolverService; exports.RelationService = RelationService; exports.RollupService = RollupService; exports.RecordService = RecordService; exports.FormulaResolverService = FormulaResolverService; exports.RollupScheduler = RollupScheduler; exports.DocumentRenderError = DocumentRenderError; exports.StorageDownloadNotSupportedError = StorageDownloadNotSupportedError; exports.DocumentRendererService = DocumentRendererService; exports.DocumentProcessingHook = DocumentProcessingHook; exports.GrantNotFoundError = GrantNotFoundError; exports.GrantExpiredError = GrantExpiredError; exports.GrantRevokedError = GrantRevokedError; exports.TokenRevokedError = TokenRevokedError; exports.WorkflowAccessGrantService = WorkflowAccessGrantService; exports.WorkflowInstanceService = WorkflowInstanceService; exports.InvitationNotFoundError = InvitationNotFoundError; exports.InvitationExpiredError = InvitationExpiredError; exports.InvitationAlreadyAcceptedError = InvitationAlreadyAcceptedError; exports.InvitationRevokedError = InvitationRevokedError; exports.WorkflowInvitationService = WorkflowInvitationService; exports.WorkflowRelationService = WorkflowRelationService; exports.WorkflowService = WorkflowService; exports.UserProfileService = UserProfileService; exports.DocumentGenerationTemplateNotFoundError = DocumentGenerationTemplateNotFoundError; exports.DocumentGenerationNotConfiguredError = DocumentGenerationNotConfiguredError; exports.DocumentGenerationService = DocumentGenerationService; exports.DocumentTemplateService = DocumentTemplateService; exports.DocumentService = DocumentService; exports.DocumentProcessingService = DocumentProcessingService; exports.FileService = FileService; exports.GeocodingService = GeocodingService; exports.GlobalSearchService = GlobalSearchService; exports.PermissionService = PermissionService; exports.ViewService = ViewService; exports.seedRegistryViews = seedRegistryViews; exports.syncNativeViews = syncNativeViews; exports.verifyRegistryViewsSeeded = verifyRegistryViewsSeeded; exports.verifyNativeViewsSync = verifyNativeViewsSync; exports.getViewSeedPreview = getViewSeedPreview; exports.getViewSyncPreview = getViewSyncPreview; exports.syncNativeObjects = syncNativeObjects; exports.verifyNativeObjectsSync = verifyNativeObjectsSync; exports.getSyncPreview = getSyncPreview; exports.syncAll = syncAll;
18965
+
18966
+
18967
+
18968
+ exports.IDENTITY_PROPERTIES = IDENTITY_PROPERTIES; exports.BEHAVIOR_PROPERTIES = BEHAVIOR_PROPERTIES; exports.PRESENTATION_PROPERTIES = PRESENTATION_PROPERTIES; exports.isIdentityProperty = isIdentityProperty; exports.isBehaviorProperty = isBehaviorProperty; exports.isPresentationProperty = isPresentationProperty; exports.RELATION_TARGET_ANY = RELATION_TARGET_ANY; exports.isUniversalRelation = isUniversalRelation; exports.isBilateralRelation = isBilateralRelation; exports.inferInverseCardinality = inferInverseCardinality; exports.NON_SORTABLE_TYPES = NON_SORTABLE_TYPES; exports.isAttributeSortable = isAttributeSortable; exports.RecordReferencedError = RecordReferencedError; exports.AttributeInUseError = AttributeInUseError; exports.ObjectReferencedError = ObjectReferencedError; exports.getErrorMessage = getErrorMessage; exports.NoopGeocodingAdapter = NoopGeocodingAdapter; exports.SYSTEM_FIELD_NAMES = SYSTEM_FIELD_NAMES; exports.RESERVED_ATTRIBUTE_NAMES = RESERVED_ATTRIBUTE_NAMES; exports.PolicyViolationError = PolicyViolationError; exports.FORBIDDEN_PROPERTY_TYPES = FORBIDDEN_PROPERTY_TYPES; exports.SYSTEM_ATTRIBUTES = SYSTEM_ATTRIBUTES; exports.getSystemAttributeList = getSystemAttributeList; exports.isSystemAttribute = isSystemAttribute; exports.isSystemAttributeObject = isSystemAttributeObject; exports.isSimpleFormNode = isSimpleFormNode; exports.isAdvancedFormNode = isAdvancedFormNode; exports.isStartNode = isStartNode; exports.isFormNode = isFormNode; exports.isConditionNode = isConditionNode; exports.isDocumentNode = isDocumentNode; exports.isEndNode = isEndNode; exports.getNodeOutputs = getNodeOutputs; exports.isConditionRule = isConditionRule; exports.isConditionGroup = isConditionGroup; exports.eq = eq; exports.neq = neq; exports.and = and; exports.or = or; exports.inValues = inValues; exports.isWorkflowDefinition = isWorkflowDefinition; exports.isWorkflowPublished = isWorkflowPublished; exports.isSystemWorkflow = isSystemWorkflow; exports.isInstanceTerminal = isInstanceTerminal; exports.isInstanceWaiting = isInstanceWaiting; exports.canResumeInstance = canResumeInstance; exports.createStartTransition = createStartTransition; exports.isInvitationValid = isInvitationValid; exports.isInvitationAccepted = isInvitationAccepted; exports.isInvitationExpired = isInvitationExpired; exports.isGrantValid = isGrantValid; exports.isGrantRevoked = isGrantRevoked; exports.isTokenRevoked = isTokenRevoked; exports.isGrantExpired = isGrantExpired; exports.canAccessNode = canAccessNode; exports.createEmptyContext = createEmptyContext; exports.getContextValue = getContextValue; exports.setContextValue = setContextValue; exports.DEFAULT_THEME = DEFAULT_THEME; exports.mergeWithDefaults = mergeWithDefaults; exports.generateCssVariables = generateCssVariables; exports.isInstanceEvent = isInstanceEvent; exports.isNodeEvent = isNodeEvent; exports.isInvitationOrGrantEvent = isInvitationOrGrantEvent; exports.ConditionOperatorSchema = ConditionOperatorSchema; exports.ConditionRuleSchema = ConditionRuleSchema; exports.ConditionGroupSchema = ConditionGroupSchema; exports.StartNodeSchema = StartNodeSchema; exports.FormFieldRefSchema = FormFieldRefSchema; exports.FlowRowFieldSchema = FlowRowFieldSchema; exports.FlowRowSchema = FlowRowSchema; exports.FormNodeSchema = FormNodeSchema; exports.ConditionNodeSchema = ConditionNodeSchema; exports.DocumentNodeSchema = DocumentNodeSchema; exports.EndNodeSchema = EndNodeSchema; exports.WorkflowNodeSchema = WorkflowNodeSchema; exports.SlotModeSchema = SlotModeSchema; exports.WorkflowSlotSchema = WorkflowSlotSchema; exports.AuthMethodSchema = AuthMethodSchema; exports.ShareStatusSchema = ShareStatusSchema; exports.WorkflowShareSchema = WorkflowShareSchema; exports.CreateShareInputSchema = CreateShareInputSchema; exports.NodePositionSchema = NodePositionSchema; exports.ViewportSchema = ViewportSchema; exports.WorkflowLayoutSchema = WorkflowLayoutSchema; exports.ThemeColorsSchema = ThemeColorsSchema; exports.ThemeLogoSchema = ThemeLogoSchema; exports.WorkflowThemeSchema = WorkflowThemeSchema; exports.WorkflowConfigSchema = WorkflowConfigSchema; exports.WorkflowStatusSchema = WorkflowStatusSchema; exports.WorkflowDefinitionSchema = WorkflowDefinitionSchema; exports.isEmpty = isEmpty; exports.isNotEmpty = isNotEmpty; exports.toUndefinedIfEmpty = toUndefinedIfEmpty; exports.hasProperties = hasProperties; exports.EMPTY_VALUE_PLACEHOLDER = EMPTY_VALUE_PLACEHOLDER; exports.formatAttributeValue = formatAttributeValue; exports.DEFAULT_LABEL_FALLBACK = DEFAULT_LABEL_FALLBACK; exports.renderLabelExpression = renderLabelExpression; exports.isLabelExpression = isLabelExpression; exports.extractAttributeNames = extractAttributeNames; exports.enrichValuesForDisplay = enrichValuesForDisplay; exports.enrichValuesWithSelectLabels = enrichValuesWithSelectLabels; exports.extractRelationIds = extractRelationIds; exports.computeLabelWithRelations = computeLabelWithRelations; exports.SchemaErrorCode = SchemaErrorCode; exports.SchemaError = SchemaError; exports.NotFoundError = NotFoundError; exports.ObjectNotFoundError = ObjectNotFoundError; exports.AttributeNotFoundError = AttributeNotFoundError; exports.RecordNotFoundError = RecordNotFoundError; exports.UserProfileNotFoundError = UserProfileNotFoundError; exports.FileNotFoundError = FileNotFoundError; exports.ValidationError = ValidationError; exports.ProtectedResourceError = ProtectedResourceError; exports.SyncError = SyncError; exports.NotSystemObjectError = NotSystemObjectError; exports.DuplicateError = DuplicateError; exports.isSchemaError = isSchemaError; exports.isNotFoundError = isNotFoundError; exports.isValidationError = isValidationError; exports.isProtectedResourceError = isProtectedResourceError; exports.ForbiddenError = ForbiddenError; exports.ProtectedRoleError = ProtectedRoleError; exports.RoleNotFoundError = RoleNotFoundError; exports.isForbiddenError = isForbiddenError; exports.ConcurrentModificationError = ConcurrentModificationError; exports.text = text; exports.textarea = textarea; exports.richtext = richtext; exports.number = number; exports.checkbox = checkbox; exports.date = date; exports.phone = phone; exports.currency = currency; exports.status = status; exports.select = select; exports.multiselect = multiselect; exports.location = location; exports.file = file; exports.user = user; exports.relation = relation; exports.rating = rating; exports.formula = formula; exports.rollup = rollup; exports.document = document; exports.ObjectBuilder = ObjectBuilder; exports.object = object; exports.GroupBuilder = GroupBuilder; exports.RelationGroupBuilder = RelationGroupBuilder; exports.TableTabConfig = TableTabConfig; exports.CustomTabConfig = CustomTabConfig; exports.RichtextTabConfig = RichtextTabConfig; exports.ActivityTabConfig = ActivityTabConfig; exports.FlowsTabConfig = FlowsTabConfig; exports.DocumentsTabConfig = DocumentsTabConfig; exports.TabBuilder = TabBuilder; exports.DetailViewBuilder = DetailViewBuilder; exports.ViewBuilder = ViewBuilder; exports.detailView = detailView; exports.view = view; exports.ListViewBuilder = ListViewBuilder; exports.ListViewTabConfigBuilder = ListViewTabConfigBuilder; exports.listView = listView; exports.group = group; exports.relationGroup = relationGroup; exports.WorkflowFormRowBuilder = WorkflowFormRowBuilder; exports.WorkflowFormBuilder = WorkflowFormBuilder; exports.WorkflowSimpleFormBuilder = WorkflowSimpleFormBuilder; exports.WorkflowConditionBuilder = WorkflowConditionBuilder; exports.WorkflowEndBuilder = WorkflowEndBuilder; exports.WorkflowStartBuilder = WorkflowStartBuilder; exports.WorkflowBuilder = WorkflowBuilder; exports.workflow = workflow; exports.registry = registry; exports.SYSTEM_TEMPLATE_IDS = SYSTEM_TEMPLATE_IDS; exports.FRENCH_ID_CARD = FRENCH_ID_CARD; exports.PASSPORT = PASSPORT; exports.DRIVING_LICENSE = DRIVING_LICENSE; exports.PROOF_OF_ADDRESS = PROOF_OF_ADDRESS; exports.SIGNABLE_CONTRACT = SIGNABLE_CONTRACT; exports.GENERIC_DOCUMENT = GENERIC_DOCUMENT; exports.SYSTEM_TEMPLATES = SYSTEM_TEMPLATES; exports.getSystemTemplate = getSystemTemplate; exports.isSystemTemplate = isSystemTemplate; exports.WorkflowJwtService = WorkflowJwtService; exports.hashOptions = hashOptions; exports.cacheKeys = cacheKeys; exports.cacheTtl = cacheTtl; exports.defaultTtl = defaultTtl; exports.NoopCacheAdapter = NoopCacheAdapter; exports.formatRecord = formatRecord; exports.formatRecords = formatRecords; exports.createDefaultState = createDefaultState; exports.SHORTCUT_TO_FILTER_OPERATOR = SHORTCUT_TO_FILTER_OPERATOR; exports.QueryNoResultError = QueryNoResultError; exports.QueryMultipleResultsError = QueryMultipleResultsError; exports.TenantContextError = TenantContextError; exports.FeatureFlagsContextError = FeatureFlagsContextError; exports.isFeatureEnabled = isFeatureEnabled; exports.getFeatureValue = getFeatureValue; exports.getFeatureFlags = getFeatureFlags; exports.tryGetFeatureValue = tryGetFeatureValue; exports.hasFeatureFlagsContext = hasFeatureFlagsContext; exports.runWithFeatureFlags = runWithFeatureFlags; exports.withFeatureFlags = withFeatureFlags; exports.getSchemaFromContext = getSchemaFromContext; exports.getSchemaByNameFromContext = getSchemaByNameFromContext; exports.hasSchemaContext = hasSchemaContext; exports.getSchemaContext = getSchemaContext; exports.addSchemaToContext = addSchemaToContext; exports.runWithSchemaContext = runWithSchemaContext; exports.runWithMergedSchemaContext = runWithMergedSchemaContext; exports.getContext = getContext2; exports.getTenantId = getTenantId; exports.getUserId = getUserId; exports.hasContext = hasContext; exports.runWithContext = runWithContext; exports.withTenantContext = withTenantContext; exports.QueryBuilder = QueryBuilder; exports.createQueryBuilder = createQueryBuilder; exports.evaluateCondition = evaluateCondition; exports.evaluate = evaluate; exports.evaluateWithTrace = evaluateWithTrace; exports.ExecutorRegistry = ExecutorRegistry; exports.success = success; exports.wait = wait; exports.complete = complete; exports.error = error; exports.ConditionExecutor = ConditionExecutor; exports.DocumentExecutor = DocumentExecutor; exports.EndExecutor = EndExecutor; exports.FormExecutor = FormExecutor; exports.StartExecutor = StartExecutor; exports.createDefaultExecutorRegistry = createDefaultExecutorRegistry; exports.getDefaultExecutorRegistry = getDefaultExecutorRegistry; exports.evaluateFormula = evaluateFormula; exports.evaluateFormulaWithResult = evaluateFormulaWithResult; exports.formatFormulaResult = formatFormulaResult; exports.evaluateFormulaAttribute = evaluateFormulaAttribute; exports.validateFormulaExpression = validateFormulaExpression; exports.extractFormulaVariables = extractFormulaVariables; exports.extractRelationReferences = extractRelationReferences; exports.extractRelationNames = extractRelationNames; exports.hasRelationReferences = hasRelationReferences; exports.flattenRelationsForEval = flattenRelationsForEval; exports.evaluateFormulaWithRelations = evaluateFormulaWithRelations; exports.evaluateFormulaAttributeWithRelations = evaluateFormulaAttributeWithRelations; exports.InvalidPathError = InvalidPathError; exports.MaxDepthExceededError = MaxDepthExceededError; exports.parsePath = parsePath; exports.validatePath = validatePath; exports.pathHasManyCardinality = pathHasManyCardinality; exports.getPathDepth = getPathDepth; exports.getTargetAttributeName = getTargetAttributeName; exports.getRelationPath = getRelationPath; exports.traversePath = traversePath; exports.resolveSingleValue = resolveSingleValue; exports.resolveMultiplePaths = resolveMultiplePaths; exports.NoopHookRegistry = NoopHookRegistry; exports.createMockAdapter = createMockAdapter; exports.PolicyRegistry = PolicyRegistry; exports.defaultPolicyRegistry = defaultPolicyRegistry; exports.SORTABLE_ATTRIBUTE_TYPES = SORTABLE_ATTRIBUTE_TYPES; exports.BaseService = BaseService; exports.BaseRepository = BaseRepository; exports.SchemaContextAwareRepository = SchemaContextAwareRepository; exports.buildAuditChanges = buildAuditChanges; exports.ObjectSchemaService = ObjectSchemaService; exports.AuditService = AuditService; exports.UserService = UserService; exports.applyDefaultValues = applyDefaultValues; exports.checkPermission = checkPermission; exports.getPolicy = getPolicy; exports.buildPolicyContext = buildPolicyContext; exports.checkRecordAccess = checkRecordAccess; exports.checkRecordModifyOrThrow = checkRecordModifyOrThrow; exports.checkRecordDeleteOrThrow = checkRecordDeleteOrThrow; exports.checkSharedObjectWriteAccess = checkSharedObjectWriteAccess; exports.computeLabel = computeLabel; exports.enrichWithFormulas = enrichWithFormulas; exports.enrichRecordsWithFormulas = enrichRecordsWithFormulas; exports.createContextForCreate = createContextForCreate; exports.createContextForUpdate = createContextForUpdate; exports.createContextForDelete = createContextForDelete; exports.createContextForRestore = createContextForRestore; exports.recalculateParentRollups = recalculateParentRollups; exports.RelationPropertiesService = RelationPropertiesService; exports.RecordQueryService = RecordQueryService; exports.RecordResolverService = RecordResolverService; exports.RelationService = RelationService; exports.RollupService = RollupService; exports.RecordService = RecordService; exports.FormulaResolverService = FormulaResolverService; exports.RollupScheduler = RollupScheduler; exports.DocumentRenderError = DocumentRenderError; exports.StorageDownloadNotSupportedError = StorageDownloadNotSupportedError; exports.DocumentRendererService = DocumentRendererService; exports.DocumentProcessingHook = DocumentProcessingHook; exports.GrantNotFoundError = GrantNotFoundError; exports.GrantExpiredError = GrantExpiredError; exports.GrantRevokedError = GrantRevokedError; exports.TokenRevokedError = TokenRevokedError; exports.WorkflowAccessGrantService = WorkflowAccessGrantService; exports.WorkflowInstanceService = WorkflowInstanceService; exports.InvitationNotFoundError = InvitationNotFoundError; exports.InvitationExpiredError = InvitationExpiredError; exports.InvitationAlreadyAcceptedError = InvitationAlreadyAcceptedError; exports.InvitationRevokedError = InvitationRevokedError; exports.WorkflowInvitationService = WorkflowInvitationService; exports.WorkflowRelationService = WorkflowRelationService; exports.WorkflowService = WorkflowService; exports.UserProfileService = UserProfileService; exports.DocumentGenerationTemplateNotFoundError = DocumentGenerationTemplateNotFoundError; exports.DocumentGenerationNotConfiguredError = DocumentGenerationNotConfiguredError; exports.DocumentGenerationService = DocumentGenerationService; exports.DocumentTemplateService = DocumentTemplateService; exports.DocumentService = DocumentService; exports.DocumentProcessingService = DocumentProcessingService; exports.FileService = FileService; exports.GeocodingService = GeocodingService; exports.GlobalSearchService = GlobalSearchService; exports.PermissionService = PermissionService; exports.ViewService = ViewService; exports.seedRegistryViews = seedRegistryViews; exports.syncNativeViews = syncNativeViews; exports.verifyRegistryViewsSeeded = verifyRegistryViewsSeeded; exports.verifyNativeViewsSync = verifyNativeViewsSync; exports.getViewSeedPreview = getViewSeedPreview; exports.getViewSyncPreview = getViewSyncPreview; exports.syncNativeObjects = syncNativeObjects; exports.verifyNativeObjectsSync = verifyNativeObjectsSync; exports.getSyncPreview = getSyncPreview; exports.syncAll = syncAll;