@constructive-io/schema-builder 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +12 -4
  3. package/dist/card-widths-CmIxkRfh.cjs +28 -0
  4. package/dist/card-widths-CmIxkRfh.cjs.map +1 -0
  5. package/dist/card-widths-pI4Kw4Xz.js +22 -0
  6. package/dist/card-widths-pI4Kw4Xz.js.map +1 -0
  7. package/dist/core-CVxnNLs7.cjs +66 -0
  8. package/dist/core-CVxnNLs7.cjs.map +1 -0
  9. package/dist/core-DJ5kA4r-.js +49 -0
  10. package/dist/core-DJ5kA4r-.js.map +1 -0
  11. package/dist/core.cjs +14 -212
  12. package/dist/core.d.cts +3 -54
  13. package/dist/core.d.ts +3 -54
  14. package/dist/core.js +3 -200
  15. package/dist/create-table-card-B6SMrt_g.js +7691 -0
  16. package/dist/create-table-card-B6SMrt_g.js.map +1 -0
  17. package/dist/create-table-card-BrQ7pB_U.cjs +7732 -0
  18. package/dist/create-table-card-BrQ7pB_U.cjs.map +1 -0
  19. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs +42 -0
  20. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs.map +1 -0
  21. package/dist/delete-confirm-dialog-K0AWE643.js +37 -0
  22. package/dist/delete-confirm-dialog-K0AWE643.js.map +1 -0
  23. package/dist/empty-state-card-5t7LygTB.cjs +62 -0
  24. package/dist/empty-state-card-5t7LygTB.cjs.map +1 -0
  25. package/dist/empty-state-card-C-Nylatg.js +57 -0
  26. package/dist/empty-state-card-C-Nylatg.js.map +1 -0
  27. package/dist/fields.cjs +8 -7763
  28. package/dist/fields.d.cts +38 -39
  29. package/dist/fields.d.ts +38 -39
  30. package/dist/fields.js +2 -7735
  31. package/dist/generated-types-DZMUyNBH.d.cts +27 -0
  32. package/dist/generated-types-DZMUyNBH.d.ts +27 -0
  33. package/dist/index--9KTz1LB.d.cts +56 -0
  34. package/dist/index-10idAfdb.d.cts +7 -0
  35. package/dist/index-BcdFaKFS.d.ts +7 -0
  36. package/dist/index-euaSKMQK.d.ts +56 -0
  37. package/dist/index.cjs +392 -13730
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +4 -10
  40. package/dist/index.d.ts +4 -10
  41. package/dist/index.js +381 -13698
  42. package/dist/index.js.map +1 -1
  43. package/dist/indexes-view-CBzYpKcd.js +736 -0
  44. package/dist/indexes-view-CBzYpKcd.js.map +1 -0
  45. package/dist/indexes-view-D1K24ts1.cjs +759 -0
  46. package/dist/indexes-view-D1K24ts1.cjs.map +1 -0
  47. package/dist/indexes.cjs +6 -1041
  48. package/dist/indexes.d.cts +27 -27
  49. package/dist/indexes.d.ts +27 -27
  50. package/dist/indexes.js +2 -1016
  51. package/dist/invalidate-database-entities-BFCWf5Zf.js +2561 -0
  52. package/dist/invalidate-database-entities-BFCWf5Zf.js.map +1 -0
  53. package/dist/invalidate-database-entities-Gs5k8A-M.cjs +2864 -0
  54. package/dist/invalidate-database-entities-Gs5k8A-M.cjs.map +1 -0
  55. package/dist/keyboard-activation-BQiV0scm.js +13 -0
  56. package/dist/keyboard-activation-BQiV0scm.js.map +1 -0
  57. package/dist/keyboard-activation-D-L0IU6Y.cjs +19 -0
  58. package/dist/keyboard-activation-D-L0IU6Y.cjs.map +1 -0
  59. package/dist/policies-view-CkvGpJBo.cjs +1023 -0
  60. package/dist/policies-view-CkvGpJBo.cjs.map +1 -0
  61. package/dist/policies-view-DTfAhX7G.js +1018 -0
  62. package/dist/policies-view-DTfAhX7G.js.map +1 -0
  63. package/dist/policies.cjs +10 -5939
  64. package/dist/policies.d.cts +55 -50
  65. package/dist/policies.d.ts +55 -50
  66. package/dist/policies.js +4 -5911
  67. package/dist/policy-config-form-EEcQ9ywL.js +2502 -0
  68. package/dist/policy-config-form-EEcQ9ywL.js.map +1 -0
  69. package/dist/policy-config-form-RP9010zj.cjs +2629 -0
  70. package/dist/policy-config-form-RP9010zj.cjs.map +1 -0
  71. package/dist/policy-types-D_sYWb-b.d.cts +81 -0
  72. package/dist/policy-types-D_sYWb-b.d.ts +81 -0
  73. package/dist/query-BGtzUV7Y.cjs +233 -0
  74. package/dist/query-BGtzUV7Y.cjs.map +1 -0
  75. package/dist/query-r6j8IjQB.js +192 -0
  76. package/dist/query-r6j8IjQB.js.map +1 -0
  77. package/dist/relationships-view-C884EvGj.js +2417 -0
  78. package/dist/relationships-view-C884EvGj.js.map +1 -0
  79. package/dist/relationships-view-DlBs-gCF.cjs +2452 -0
  80. package/dist/relationships-view-DlBs-gCF.cjs.map +1 -0
  81. package/dist/relationships.cjs +9 -4328
  82. package/dist/relationships.d.cts +92 -92
  83. package/dist/relationships.d.ts +92 -92
  84. package/dist/relationships.js +2 -4300
  85. package/dist/rolldown-runtime-D_qnwXdH.cjs +35 -0
  86. package/dist/schema-builder-sidebar-DAgK7ZTu.js +654 -0
  87. package/dist/schema-builder-sidebar-DAgK7ZTu.js.map +1 -0
  88. package/dist/schema-builder-sidebar-L3TcQeQr.cjs +671 -0
  89. package/dist/schema-builder-sidebar-L3TcQeQr.cjs.map +1 -0
  90. package/dist/table-editor-B-5i1M79.js +1906 -0
  91. package/dist/table-editor-B-5i1M79.js.map +1 -0
  92. package/dist/table-editor-BdLdVZfh.cjs +1935 -0
  93. package/dist/table-editor-BdLdVZfh.cjs.map +1 -0
  94. package/dist/tables.cjs +6 -5643
  95. package/dist/tables.d.cts +22 -21
  96. package/dist/tables.d.ts +22 -21
  97. package/dist/tables.js +3 -5618
  98. package/dist/testing.cjs +63 -62
  99. package/dist/testing.cjs.map +1 -1
  100. package/dist/testing.d.cts +4 -4
  101. package/dist/testing.d.ts +4 -4
  102. package/dist/testing.js +62 -61
  103. package/dist/testing.js.map +1 -1
  104. package/dist/types-CXNRA22N.d.cts +450 -0
  105. package/dist/types-CXNRA22N.d.ts +450 -0
  106. package/dist/use-update-table-DlLX9fdE.js +244 -0
  107. package/dist/use-update-table-DlLX9fdE.js.map +1 -0
  108. package/dist/use-update-table-vcoHVolI.cjs +291 -0
  109. package/dist/use-update-table-vcoHVolI.cjs.map +1 -0
  110. package/package.json +8 -6
  111. package/dist/core.cjs.map +0 -1
  112. package/dist/core.js.map +0 -1
  113. package/dist/fields.cjs.map +0 -1
  114. package/dist/fields.js.map +0 -1
  115. package/dist/generated-types-CnAlqHU_.d.cts +0 -25
  116. package/dist/generated-types-CnAlqHU_.d.ts +0 -25
  117. package/dist/indexes.cjs.map +0 -1
  118. package/dist/indexes.js.map +0 -1
  119. package/dist/policies.cjs.map +0 -1
  120. package/dist/policies.js.map +0 -1
  121. package/dist/policy-types-CEYAR5TN.d.cts +0 -79
  122. package/dist/policy-types-CEYAR5TN.d.ts +0 -79
  123. package/dist/relationships.cjs.map +0 -1
  124. package/dist/relationships.js.map +0 -1
  125. package/dist/tables.cjs.map +0 -1
  126. package/dist/tables.js.map +0 -1
  127. package/dist/types-Du86atZ8.d.cts +0 -199
  128. package/dist/types-Du86atZ8.d.ts +0 -199
  129. package/dist/types-bX2dCrdl.d.cts +0 -52
  130. package/dist/types-bX2dCrdl.d.ts +0 -52
@@ -0,0 +1,2502 @@
1
+ 'use client';
2
+ import { i as useSchemaBuilder, t as schemaBuilderQueryKey } from "./query-r6j8IjQB.js";
3
+ import { _ as useCreateFieldMutation, a as useCreateSecureTableProvisionMutation, f as toFieldType, h as useSchemaBuilderRuntime, j as useSchemaBuilderSdkClient, l as useSchemaBuilderSelectors, n as databasePoliciesQueryKeys, r as useDatabasePolicies, t as invalidateDatabaseEntities, u as fieldTypeToTypeName, x as useCreateTableGrantMutation } from "./invalidate-database-entities-BFCWf5Zf.js";
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+ import { Tooltip, TooltipContent, TooltipTrigger } from "@constructive-io/ui/tooltip";
7
+ import { CheckIcon, Clock, Eye, Globe, Info, Layers, Link, Lock, Network, PencilIcon, Plus, RotateCcwIcon, Shield, Table2, Trash2, Unlock, User, UserCheck, Users, XIcon } from "lucide-react";
8
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
9
+ import { Button } from "@constructive-io/ui/button";
10
+ import { Combobox, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList, ComboboxPopup } from "@constructive-io/ui/combobox";
11
+ import { Input } from "@constructive-io/ui/input";
12
+ import { Label } from "@constructive-io/ui/label";
13
+ import * as NodeTypes from "node-type-registry";
14
+ import { Select, SelectContent, SelectFieldItem, SelectRichItem, SelectTrigger, SelectValue } from "@constructive-io/ui/select";
15
+ import { Switch } from "@constructive-io/ui/switch";
16
+
17
+ //#region src/compat/admin-sdk.ts
18
+ function useAdminSdkClient() {
19
+ const { adapter, scope } = useSchemaBuilder();
20
+ return {
21
+ fetchAppPermissionsQuery: (variables, signal) => adapter.policies.appPermissions(variables, {
22
+ scope,
23
+ signal
24
+ }),
25
+ fetchOrgPermissionsQuery: (variables, signal) => adapter.policies.orgPermissions(variables, {
26
+ scope,
27
+ signal
28
+ })
29
+ };
30
+ }
31
+
32
+ //#endregion
33
+ //#region src/schema/schema-builder-core/lib/data/policy-provisioning.ts
34
+ const MEMBERSHIP_TYPES$1 = {
35
+ APP: 1,
36
+ ORGANIZATION: 2,
37
+ GROUP: 3
38
+ };
39
+ const POLICY_PROVISIONING_CONFIG = {
40
+ AuthzDirectOwner: {
41
+ category: "has-module",
42
+ hasDataNode: true,
43
+ dataNodeType: "DataDirectOwner",
44
+ fieldOverrides: { entity_field: {
45
+ type: "string",
46
+ required: true,
47
+ label: "Owner Field Name",
48
+ placeholder: "owner_id",
49
+ description: "Column that stores the owner user ID",
50
+ defaultValue: "owner_id"
51
+ } }
52
+ },
53
+ AuthzEntityMembership: {
54
+ category: "has-module",
55
+ hasDataNode: true,
56
+ dataNodeType: "DataEntityMembership",
57
+ fieldOverrides: {
58
+ entity_field: {
59
+ type: "string",
60
+ required: true,
61
+ label: "Entity Field Name",
62
+ placeholder: "entity_id",
63
+ description: "Column referencing the org/group",
64
+ defaultValue: "entity_id"
65
+ },
66
+ membership_type: {
67
+ type: "integer",
68
+ hidden: true,
69
+ defaultValue: MEMBERSHIP_TYPES$1.ORGANIZATION
70
+ },
71
+ permission: {
72
+ type: "string",
73
+ component: "permission-select",
74
+ label: "Required Permission",
75
+ description: "Optional permission the user must have"
76
+ },
77
+ is_admin: {
78
+ type: "boolean",
79
+ label: "Admins",
80
+ description: "People with admin access can view this."
81
+ },
82
+ is_owner: {
83
+ type: "boolean",
84
+ label: "Owners",
85
+ description: "People who own the membership can view this."
86
+ }
87
+ }
88
+ },
89
+ AuthzDirectOwnerAny: {
90
+ category: "needs-fields",
91
+ hasDataNode: false,
92
+ fieldOverrides: { entity_fields: {
93
+ type: "uuid[]",
94
+ required: true,
95
+ label: "Owner Fields",
96
+ description: "UUID columns to check for ownership (OR logic)",
97
+ defaultValue: ["owner_id"],
98
+ pgType: "uuid"
99
+ } }
100
+ },
101
+ AuthzAppMembership: {
102
+ category: "no-fields",
103
+ hasDataNode: false,
104
+ fieldOverrides: {
105
+ permission: {
106
+ type: "string",
107
+ component: "permission-select",
108
+ label: "Required Permission",
109
+ description: "Optional permission the user must have"
110
+ },
111
+ is_admin: {
112
+ type: "boolean",
113
+ label: "Admins",
114
+ description: "People with admin access can view this."
115
+ },
116
+ is_owner: {
117
+ type: "boolean",
118
+ label: "Owners",
119
+ description: "People who own the membership can view this."
120
+ }
121
+ }
122
+ },
123
+ AuthzPublishable: {
124
+ category: "has-module",
125
+ hasDataNode: true,
126
+ dataNodeType: "DataPublishable",
127
+ fieldOverrides: {
128
+ is_published_field: {
129
+ type: "string",
130
+ label: "Published Flag Field",
131
+ placeholder: "is_published",
132
+ defaultValue: "is_published"
133
+ },
134
+ published_at_field: {
135
+ type: "string",
136
+ label: "Published At Field",
137
+ placeholder: "published_at",
138
+ defaultValue: "published_at"
139
+ },
140
+ require_published_at: {
141
+ type: "boolean",
142
+ label: "Require Published At",
143
+ description: "Also require that the publish date has passed",
144
+ defaultValue: true
145
+ }
146
+ }
147
+ },
148
+ AuthzTemporal: {
149
+ category: "needs-fields",
150
+ hasDataNode: false,
151
+ fieldOverrides: {
152
+ valid_from_field: {
153
+ type: "string",
154
+ required: true,
155
+ label: "Valid From Field",
156
+ placeholder: "valid_from",
157
+ description: "Column for start time",
158
+ defaultValue: "valid_from",
159
+ pgType: "timestamptz"
160
+ },
161
+ valid_until_field: {
162
+ type: "string",
163
+ required: true,
164
+ label: "Valid Until Field",
165
+ placeholder: "valid_until",
166
+ description: "Column for end time",
167
+ defaultValue: "valid_until",
168
+ pgType: "timestamptz"
169
+ },
170
+ valid_from_inclusive: {
171
+ type: "boolean",
172
+ label: "Include Start",
173
+ description: "Include start boundary",
174
+ defaultValue: true
175
+ },
176
+ valid_until_inclusive: {
177
+ type: "boolean",
178
+ label: "Include End",
179
+ description: "Include end boundary",
180
+ defaultValue: false
181
+ }
182
+ }
183
+ },
184
+ AuthzMemberList: {
185
+ category: "needs-fields",
186
+ hasDataNode: false,
187
+ fieldOverrides: { array_field: {
188
+ type: "string",
189
+ required: true,
190
+ label: "Member List Field",
191
+ placeholder: "allowed_users",
192
+ description: "Column containing list of user IDs",
193
+ defaultValue: "allowed_users",
194
+ pgType: "uuid[]"
195
+ } }
196
+ },
197
+ AuthzRelatedMemberList: {
198
+ category: "needs-table",
199
+ hasDataNode: false,
200
+ fieldOverrides: {
201
+ owned_schema: { hidden: true },
202
+ owned_table: {
203
+ type: "string",
204
+ required: true,
205
+ component: "table-select",
206
+ label: "Related Table",
207
+ placeholder: "groups",
208
+ description: "Table containing the member list"
209
+ },
210
+ owned_table_key: {
211
+ type: "uuid",
212
+ required: true,
213
+ label: "Member List Column",
214
+ placeholder: "member_ids",
215
+ description: "List column in related table",
216
+ dependsOn: "owned_table"
217
+ },
218
+ owned_table_ref_key: {
219
+ type: "uuid",
220
+ required: true,
221
+ label: "Reference Key",
222
+ placeholder: "id",
223
+ description: "FK column in related table",
224
+ dependsOn: "owned_table"
225
+ },
226
+ this_object_key: {
227
+ type: "uuid",
228
+ required: true,
229
+ label: "Foreign Key",
230
+ placeholder: "group_id",
231
+ description: "FK on this table to related table"
232
+ }
233
+ }
234
+ },
235
+ AuthzRelatedEntityMembership: {
236
+ category: "needs-table",
237
+ hasDataNode: false,
238
+ fieldOverrides: {
239
+ entity_field: {
240
+ type: "uuid",
241
+ required: true,
242
+ label: "Foreign Key Field",
243
+ description: "Field on this table referencing the linked table"
244
+ },
245
+ membership_type: {
246
+ type: "integer",
247
+ required: true,
248
+ component: "membership-type-select",
249
+ label: "Membership Scope"
250
+ },
251
+ obj_schema: { hidden: true },
252
+ obj_table: {
253
+ type: "string",
254
+ required: true,
255
+ component: "table-select",
256
+ label: "Linked Table",
257
+ description: "Table to check for membership"
258
+ },
259
+ obj_field: {
260
+ type: "uuid",
261
+ required: true,
262
+ label: "Entity Field on Linked Table",
263
+ description: "Field containing entity ID for membership check",
264
+ dependsOn: "obj_table"
265
+ },
266
+ permission: {
267
+ type: "string",
268
+ component: "permission-select",
269
+ label: "Required Permission"
270
+ },
271
+ is_admin: {
272
+ type: "boolean",
273
+ label: "Admins",
274
+ description: "People with admin access can view this."
275
+ },
276
+ is_owner: {
277
+ type: "boolean",
278
+ label: "Owners",
279
+ description: "People who own the membership can view this."
280
+ }
281
+ }
282
+ },
283
+ AuthzOrgHierarchy: {
284
+ category: "has-module",
285
+ hasDataNode: true,
286
+ dataNodeType: "DataOwnershipInEntity",
287
+ disabled: true,
288
+ fieldOverrides: {
289
+ direction: {
290
+ type: "string",
291
+ required: true,
292
+ label: "Direction",
293
+ description: "Which direction to traverse the org hierarchy",
294
+ defaultValue: "down",
295
+ options: [{
296
+ value: "down",
297
+ label: "Down",
298
+ description: "Managers can see their subordinates"
299
+ }, {
300
+ value: "up",
301
+ label: "Up",
302
+ description: "Subordinates can see their managers"
303
+ }]
304
+ },
305
+ entity_field: {
306
+ type: "string",
307
+ label: "Entity Field Name",
308
+ placeholder: "entity_id",
309
+ description: "Field referencing the org entity",
310
+ defaultValue: "entity_id"
311
+ },
312
+ anchor_field: {
313
+ type: "string",
314
+ required: true,
315
+ label: "Anchor Field",
316
+ placeholder: "owner_id",
317
+ description: "Field referencing the user (e.g., owner_id)",
318
+ defaultValue: "owner_id"
319
+ },
320
+ max_depth: {
321
+ type: "integer",
322
+ label: "Max Depth",
323
+ description: "Optional max depth to limit visibility"
324
+ }
325
+ }
326
+ },
327
+ AuthzAllowAll: {
328
+ category: "no-fields",
329
+ hasDataNode: false
330
+ },
331
+ AuthzDenyAll: {
332
+ category: "no-fields",
333
+ hasDataNode: false
334
+ },
335
+ AuthzComposite: {
336
+ category: "no-fields",
337
+ hasDataNode: false
338
+ }
339
+ };
340
+ const DATA_NODE_GENERATED_FIELDS$1 = {
341
+ DataDirectOwner: [{
342
+ name: "owner_id",
343
+ type: "uuid",
344
+ nullable: false,
345
+ description: "References the owning user"
346
+ }],
347
+ DataEntityMembership: [{
348
+ name: "entity_id",
349
+ type: "uuid",
350
+ nullable: false,
351
+ description: "References the organization or group"
352
+ }],
353
+ DataOwnershipInEntity: [{
354
+ name: "owner_id",
355
+ type: "uuid",
356
+ nullable: false,
357
+ description: "References the owning user"
358
+ }, {
359
+ name: "entity_id",
360
+ type: "uuid",
361
+ nullable: false,
362
+ description: "References the organization or group"
363
+ }],
364
+ DataPublishable: [{
365
+ name: "is_published",
366
+ type: "boolean",
367
+ nullable: false,
368
+ description: "Whether the record is published"
369
+ }, {
370
+ name: "published_at",
371
+ type: "timestamptz",
372
+ nullable: true,
373
+ description: "When the record was published"
374
+ }],
375
+ DataTimestamps: [{
376
+ name: "created_at",
377
+ type: "timestamptz",
378
+ nullable: false,
379
+ description: "When the record was created"
380
+ }, {
381
+ name: "updated_at",
382
+ type: "timestamptz",
383
+ nullable: false,
384
+ description: "When the record was last updated"
385
+ }],
386
+ DataPeoplestamps: [{
387
+ name: "created_by",
388
+ type: "uuid",
389
+ nullable: true,
390
+ description: "User who created the record"
391
+ }, {
392
+ name: "updated_by",
393
+ type: "uuid",
394
+ nullable: true,
395
+ description: "User who last updated the record"
396
+ }],
397
+ DataSoftDelete: [{
398
+ name: "is_deleted",
399
+ type: "boolean",
400
+ nullable: false,
401
+ description: "Whether the record is soft-deleted"
402
+ }, {
403
+ name: "deleted_at",
404
+ type: "timestamptz",
405
+ nullable: true,
406
+ description: "When the record was deleted"
407
+ }]
408
+ };
409
+ const AUTO_INJECT_SCHEMA_FIELDS = /* @__PURE__ */ new Set(["owned_schema", "obj_schema"]);
410
+ function getPolicyCategory$1(policyType) {
411
+ return POLICY_PROVISIONING_CONFIG[policyType]?.category ?? "no-fields";
412
+ }
413
+ function getDataNodeForPolicy$1(policyType) {
414
+ return POLICY_PROVISIONING_CONFIG[policyType]?.dataNodeType;
415
+ }
416
+ function getGeneratedFields$1(dataNodeType) {
417
+ return DATA_NODE_GENERATED_FIELDS$1[dataNodeType] ?? [];
418
+ }
419
+ function getFieldsRequiringColumns$1(policyType) {
420
+ const config = POLICY_PROVISIONING_CONFIG[policyType];
421
+ if (!config?.fieldOverrides) return [];
422
+ const result = [];
423
+ for (const [key, override] of Object.entries(config.fieldOverrides)) {
424
+ if (!override.pgType) continue;
425
+ const defaultName = Array.isArray(override.defaultValue) ? override.defaultValue : typeof override.defaultValue === "string" ? override.defaultValue : key;
426
+ result.push({
427
+ key,
428
+ defaultName,
429
+ pgType: override.pgType
430
+ });
431
+ }
432
+ return result;
433
+ }
434
+ function sanitizePolicyData$1(data) {
435
+ const sanitized = {};
436
+ for (const [key, value] of Object.entries(data)) {
437
+ if (value === void 0 || value === null) continue;
438
+ if (typeof value === "string" && value.trim() === "") continue;
439
+ if (Array.isArray(value) && value.length === 0) continue;
440
+ sanitized[key] = value;
441
+ }
442
+ return sanitized;
443
+ }
444
+ function injectSchemaFields$1(policyData, schemaId, policyType) {
445
+ const config = POLICY_PROVISIONING_CONFIG[policyType];
446
+ if (!config?.fieldOverrides) return policyData;
447
+ const next = { ...policyData };
448
+ for (const [key, override] of Object.entries(config.fieldOverrides)) {
449
+ if (!AUTO_INJECT_SCHEMA_FIELDS.has(key)) continue;
450
+ if (override.hidden && next[key] === void 0) next[key] = schemaId;
451
+ }
452
+ return next;
453
+ }
454
+ function buildNodeDataForDataNodeType(dataNodeType, policyData) {
455
+ if (!dataNodeType) return {};
456
+ const data = {};
457
+ if (dataNodeType === "DataDirectOwner") {
458
+ if (policyData.entity_field && policyData.entity_field !== "owner_id") data.owner_field_name = policyData.entity_field;
459
+ }
460
+ if (dataNodeType === "DataEntityMembership") {
461
+ if (policyData.entity_field && policyData.entity_field !== "entity_id") data.entity_field_name = policyData.entity_field;
462
+ }
463
+ if (dataNodeType === "DataOwnershipInEntity") {
464
+ if (policyData.entity_field && policyData.entity_field !== "entity_id") data.entity_field_name = policyData.entity_field;
465
+ if (policyData.anchor_field && policyData.anchor_field !== "owner_id") data.owner_field_name = policyData.anchor_field;
466
+ }
467
+ return data;
468
+ }
469
+ function buildNodeData$1(policyType, policyData) {
470
+ return buildNodeDataForDataNodeType(getDataNodeForPolicy$1(policyType), policyData);
471
+ }
472
+
473
+ //#endregion
474
+ //#region src/schema/schema-builder-policies/lib/gql/hooks/schema-builder/use-table-grants.ts
475
+ /**
476
+ * Hook for managing table grants (permissions)
477
+ * Tier 4 wrapper: orchestrates table lookup + grant creation using SDK hooks
478
+ */
479
+ /**
480
+ * Fetches table metadata including fields by database ID and table name.
481
+ * Required for grant operations to get table ID and field IDs.
482
+ * Uses SDK hooks via composition.
483
+ */
484
+ async function getTableByName(databaseId, tableName, client) {
485
+ try {
486
+ const table = (await client.fetchTablesQuery({ selection: {
487
+ fields: {
488
+ id: true,
489
+ name: true,
490
+ useRls: true
491
+ },
492
+ where: {
493
+ databaseId: { equalTo: databaseId },
494
+ name: { equalTo: tableName }
495
+ },
496
+ first: 1
497
+ } }))?.tables?.nodes?.[0];
498
+ if (!table?.id) return null;
499
+ const fields = (await client.fetchFieldsQuery({ selection: {
500
+ fields: {
501
+ id: true,
502
+ name: true
503
+ },
504
+ where: { tableId: { equalTo: table.id } }
505
+ } }))?.fields?.nodes ?? [];
506
+ return {
507
+ id: table.id,
508
+ name: table.name ?? tableName,
509
+ useRls: table.useRls ?? false,
510
+ fields: fields.map((f) => ({
511
+ id: f.id ?? "",
512
+ name: f.name ?? ""
513
+ })).filter((f) => f.id && f.name)
514
+ };
515
+ } catch (error) {
516
+ console.error(`Failed to fetch table ${tableName}:`, error);
517
+ return null;
518
+ }
519
+ }
520
+ /**
521
+ * Resolves field names to field IDs using table metadata.
522
+ */
523
+ function resolveFieldIds(table, fieldNames) {
524
+ const fieldIds = [];
525
+ for (const fieldName of fieldNames) {
526
+ const field = table.fields.find((f) => f.name === fieldName);
527
+ if (field) fieldIds.push(field.id);
528
+ else console.warn(`Field ${fieldName} not found in table ${table.name}, skipping from grant`);
529
+ }
530
+ return fieldIds;
531
+ }
532
+ /**
533
+ * Hook for creating table grants (permissions).
534
+ * Supports both table-level grants (all fields) and field-level grants (specific fields).
535
+ *
536
+ * @example
537
+ * // Table-level grant (all fields)
538
+ * createGrant({
539
+ * databaseId: 'xxx',
540
+ * tableName: 'products',
541
+ * privileges: ['select', 'delete']
542
+ * })
543
+ *
544
+ * @example
545
+ * // Field-level grant (specific fields only)
546
+ * createGrant({
547
+ * databaseId: 'xxx',
548
+ * tableName: 'products',
549
+ * privileges: ['insert'],
550
+ * fieldNames: ['name', 'description', 'price']
551
+ * })
552
+ */
553
+ function useCreateTableGrant() {
554
+ const queryClient = useQueryClient();
555
+ const sdkClient = useSchemaBuilderSdkClient();
556
+ const createGrantMutation = useCreateTableGrantMutation({ selection: { fields: { id: true } } });
557
+ return useMutation({
558
+ mutationFn: async (input) => {
559
+ const { databaseId, tableName, privileges, fieldNames, roleName = "authenticated" } = input;
560
+ const table = await getTableByName(databaseId, tableName, sdkClient);
561
+ if (!table) throw new Error(`Table ${tableName} not found`);
562
+ let fieldIds;
563
+ if (fieldNames && fieldNames.length > 0) {
564
+ fieldIds = resolveFieldIds(table, fieldNames);
565
+ if (fieldIds.length === 0) throw new Error(`No valid fields found for grant on table ${tableName}`);
566
+ }
567
+ const results = [];
568
+ for (const privilege of privileges) try {
569
+ const grantInput = {
570
+ tableId: table.id,
571
+ privilege,
572
+ granteeName: roleName,
573
+ ...fieldIds && fieldIds.length > 0 && { fieldIds }
574
+ };
575
+ const result = await createGrantMutation.mutateAsync(grantInput);
576
+ results.push(result);
577
+ } catch (error) {
578
+ if (error?.message?.includes("already exists") || error?.message?.includes("duplicate key") || error?.message?.includes("unique constraint") || error?.message?.includes("unique violation")) continue;
579
+ throw new Error(`Failed to create ${privilege} grant on ${tableName}: ${error.message}`);
580
+ }
581
+ return results;
582
+ },
583
+ onSuccess: async (_result, variables) => {
584
+ await invalidateDatabaseEntities(queryClient, variables.databaseId);
585
+ },
586
+ onError: (error) => {
587
+ console.error("Failed to create table grant:", error);
588
+ }
589
+ });
590
+ }
591
+ /**
592
+ * Hook for creating multiple table grants in batch.
593
+ * Useful when setting up a new table with standard permissions.
594
+ *
595
+ * @example
596
+ * batchCreateGrants({
597
+ * databaseId: 'xxx',
598
+ * tableName: 'products',
599
+ * grants: [
600
+ * { privileges: ['select', 'delete'] }, // All fields
601
+ * { privileges: ['insert'], fieldNames: ['name', 'price'] }, // Specific fields
602
+ * { privileges: ['update'], fieldNames: ['name', 'description'] },
603
+ * ]
604
+ * })
605
+ */
606
+ function useBatchCreateTableGrants() {
607
+ const { mutateAsync: createGrant } = useCreateTableGrant();
608
+ return useMutation({
609
+ mutationFn: async (input) => {
610
+ const { databaseId, tableName, grants } = input;
611
+ const results = [];
612
+ for (const grant of grants) try {
613
+ const result = await createGrant({
614
+ databaseId,
615
+ tableName,
616
+ ...grant
617
+ });
618
+ results.push(result);
619
+ } catch (error) {
620
+ console.error(`Failed to create grant for ${tableName}:`, error);
621
+ }
622
+ return results;
623
+ },
624
+ onError: (error) => {
625
+ console.error("Failed to create batch grants:", error);
626
+ }
627
+ });
628
+ }
629
+
630
+ //#endregion
631
+ //#region src/schema/schema-builder-core/lib/constants/membership-types.ts
632
+ const MEMBERSHIP_TYPES = {
633
+ APP: 1,
634
+ ORGANIZATION: 2,
635
+ GROUP: 3
636
+ };
637
+
638
+ //#endregion
639
+ //#region src/schema/schema-builder-core/components/policies/policy-config.ts
640
+ /**
641
+ * Frontend UI decorator for policy types.
642
+ *
643
+ * Backend node_type_registry is the source of truth for policy type identity
644
+ * (name, displayName). This config adds frontend-only concerns:
645
+ * icons, descriptions, workflow categories, field overrides.
646
+ * Display order is determined by object insertion order.
647
+ *
648
+ * Policy types NOT in this config will not appear in the wizard.
649
+ */
650
+ const paramOf = (def) => def.parameter_schema.properties;
651
+ const POLICY_TYPE_UI_CONFIG = {
652
+ AuthzDirectOwner: {
653
+ fallbackTitle: NodeTypes.AuthzDirectOwner.display_name,
654
+ description: NodeTypes.AuthzDirectOwner.description,
655
+ icon: User,
656
+ category: "has-module",
657
+ hasDataNode: true,
658
+ dataNodeType: NodeTypes.DataDirectOwner.name,
659
+ fieldOverrides: { entity_field: {
660
+ type: "string",
661
+ required: true,
662
+ label: "Owner Field Name",
663
+ placeholder: "owner_id",
664
+ description: paramOf(NodeTypes.AuthzDirectOwner)?.entity_field?.description,
665
+ defaultValue: "owner_id"
666
+ } }
667
+ },
668
+ AuthzEntityMembership: {
669
+ fallbackTitle: NodeTypes.AuthzEntityMembership.display_name,
670
+ description: NodeTypes.AuthzEntityMembership.description,
671
+ icon: Shield,
672
+ category: "has-module",
673
+ hasDataNode: true,
674
+ dataNodeType: NodeTypes.DataEntityMembership.name,
675
+ fieldOverrides: {
676
+ entity_field: {
677
+ type: "string",
678
+ required: true,
679
+ label: "Entity Field Name",
680
+ placeholder: "entity_id",
681
+ description: paramOf(NodeTypes.AuthzEntityMembership)?.entity_field?.description,
682
+ defaultValue: "entity_id"
683
+ },
684
+ membership_type: {
685
+ type: "integer",
686
+ hidden: true,
687
+ defaultValue: MEMBERSHIP_TYPES.ORGANIZATION
688
+ },
689
+ permission: {
690
+ type: "string",
691
+ component: "permission-select",
692
+ label: "Required Permission",
693
+ description: paramOf(NodeTypes.AuthzEntityMembership)?.permission?.description
694
+ },
695
+ is_admin: {
696
+ type: "boolean",
697
+ label: "Admins",
698
+ description: paramOf(NodeTypes.AuthzEntityMembership)?.is_admin?.description
699
+ },
700
+ is_owner: {
701
+ type: "boolean",
702
+ label: "Owners",
703
+ description: paramOf(NodeTypes.AuthzEntityMembership)?.is_owner?.description
704
+ }
705
+ }
706
+ },
707
+ AuthzDirectOwnerAny: {
708
+ fallbackTitle: NodeTypes.AuthzDirectOwnerAny.display_name,
709
+ description: NodeTypes.AuthzDirectOwnerAny.description,
710
+ icon: Users,
711
+ category: "needs-fields",
712
+ hasDataNode: false,
713
+ fieldOverrides: { entity_fields: {
714
+ type: "uuid[]",
715
+ required: true,
716
+ label: "Owner Fields",
717
+ description: paramOf(NodeTypes.AuthzDirectOwnerAny)?.entity_fields?.description,
718
+ defaultValue: ["owner_id"],
719
+ pgType: "uuid"
720
+ } }
721
+ },
722
+ AuthzAppMembership: {
723
+ fallbackTitle: NodeTypes.AuthzAppMembership.display_name,
724
+ description: NodeTypes.AuthzAppMembership.description,
725
+ icon: Globe,
726
+ category: "no-fields",
727
+ hasDataNode: false,
728
+ fieldOverrides: {
729
+ permission: {
730
+ type: "string",
731
+ component: "permission-select",
732
+ label: "Required Permission",
733
+ description: paramOf(NodeTypes.AuthzAppMembership)?.permission?.description
734
+ },
735
+ is_admin: {
736
+ type: "boolean",
737
+ label: "Admins",
738
+ description: paramOf(NodeTypes.AuthzAppMembership)?.is_admin?.description
739
+ },
740
+ is_owner: {
741
+ type: "boolean",
742
+ label: "Owners",
743
+ description: paramOf(NodeTypes.AuthzAppMembership)?.is_owner?.description
744
+ }
745
+ }
746
+ },
747
+ AuthzPublishable: {
748
+ fallbackTitle: NodeTypes.AuthzPublishable.display_name,
749
+ description: NodeTypes.AuthzPublishable.description,
750
+ icon: Eye,
751
+ category: "has-module",
752
+ hasDataNode: true,
753
+ dataNodeType: NodeTypes.DataPublishable.name,
754
+ fieldOverrides: {
755
+ is_published_field: {
756
+ type: "string",
757
+ label: "Published Flag Field",
758
+ placeholder: "is_published",
759
+ description: paramOf(NodeTypes.AuthzPublishable)?.is_published_field?.description,
760
+ defaultValue: paramOf(NodeTypes.AuthzPublishable)?.is_published_field?.default ?? "is_published"
761
+ },
762
+ published_at_field: {
763
+ type: "string",
764
+ label: "Published At Field",
765
+ placeholder: "published_at",
766
+ description: paramOf(NodeTypes.AuthzPublishable)?.published_at_field?.description,
767
+ defaultValue: paramOf(NodeTypes.AuthzPublishable)?.published_at_field?.default ?? "published_at"
768
+ },
769
+ require_published_at: {
770
+ type: "boolean",
771
+ label: "Require Published At",
772
+ description: paramOf(NodeTypes.AuthzPublishable)?.require_published_at?.description,
773
+ defaultValue: paramOf(NodeTypes.AuthzPublishable)?.require_published_at?.default ?? true
774
+ }
775
+ }
776
+ },
777
+ AuthzTemporal: {
778
+ fallbackTitle: NodeTypes.AuthzTemporal.display_name,
779
+ description: NodeTypes.AuthzTemporal.description,
780
+ icon: Clock,
781
+ category: "needs-fields",
782
+ hasDataNode: false,
783
+ fieldOverrides: {
784
+ valid_from_field: {
785
+ type: "string",
786
+ required: true,
787
+ label: "Valid From Field",
788
+ placeholder: "valid_from",
789
+ description: paramOf(NodeTypes.AuthzTemporal)?.valid_from_field?.description,
790
+ defaultValue: "valid_from",
791
+ pgType: "timestamptz"
792
+ },
793
+ valid_until_field: {
794
+ type: "string",
795
+ required: true,
796
+ label: "Valid Until Field",
797
+ placeholder: "valid_until",
798
+ description: paramOf(NodeTypes.AuthzTemporal)?.valid_until_field?.description,
799
+ defaultValue: "valid_until",
800
+ pgType: "timestamptz"
801
+ },
802
+ valid_from_inclusive: {
803
+ type: "boolean",
804
+ label: "Include Start",
805
+ description: paramOf(NodeTypes.AuthzTemporal)?.valid_from_inclusive?.description,
806
+ defaultValue: paramOf(NodeTypes.AuthzTemporal)?.valid_from_inclusive?.default ?? true
807
+ },
808
+ valid_until_inclusive: {
809
+ type: "boolean",
810
+ label: "Include End",
811
+ description: paramOf(NodeTypes.AuthzTemporal)?.valid_until_inclusive?.description,
812
+ defaultValue: paramOf(NodeTypes.AuthzTemporal)?.valid_until_inclusive?.default ?? false
813
+ }
814
+ }
815
+ },
816
+ AuthzMemberList: {
817
+ fallbackTitle: NodeTypes.AuthzMemberList.display_name,
818
+ description: NodeTypes.AuthzMemberList.description,
819
+ icon: Users,
820
+ category: "needs-fields",
821
+ hasDataNode: false,
822
+ fieldOverrides: { array_field: {
823
+ type: "string",
824
+ required: true,
825
+ label: "Member List Field",
826
+ placeholder: "allowed_users",
827
+ description: paramOf(NodeTypes.AuthzMemberList)?.array_field?.description,
828
+ defaultValue: "allowed_users",
829
+ pgType: "uuid[]"
830
+ } }
831
+ },
832
+ AuthzRelatedMemberList: {
833
+ fallbackTitle: NodeTypes.AuthzRelatedMemberList.display_name,
834
+ description: NodeTypes.AuthzRelatedMemberList.description,
835
+ icon: UserCheck,
836
+ category: "needs-table",
837
+ hasDataNode: false,
838
+ fieldOverrides: {
839
+ owned_schema: { hidden: true },
840
+ owned_table: {
841
+ type: "string",
842
+ required: true,
843
+ component: "table-select",
844
+ label: "Related Table",
845
+ placeholder: "groups",
846
+ description: paramOf(NodeTypes.AuthzRelatedMemberList)?.owned_table?.description
847
+ },
848
+ owned_table_key: {
849
+ type: "uuid",
850
+ required: true,
851
+ label: "Member List Column",
852
+ placeholder: "member_ids",
853
+ description: paramOf(NodeTypes.AuthzRelatedMemberList)?.owned_table_key?.description,
854
+ dependsOn: "owned_table"
855
+ },
856
+ owned_table_ref_key: {
857
+ type: "uuid",
858
+ required: true,
859
+ label: "Reference Key",
860
+ placeholder: "id",
861
+ description: paramOf(NodeTypes.AuthzRelatedMemberList)?.owned_table_ref_key?.description,
862
+ dependsOn: "owned_table"
863
+ },
864
+ this_object_key: {
865
+ type: "uuid",
866
+ required: true,
867
+ label: "Foreign Key",
868
+ placeholder: "group_id",
869
+ description: paramOf(NodeTypes.AuthzRelatedMemberList)?.this_object_key?.description
870
+ }
871
+ }
872
+ },
873
+ AuthzRelatedEntityMembership: {
874
+ fallbackTitle: NodeTypes.AuthzRelatedEntityMembership.display_name,
875
+ description: NodeTypes.AuthzRelatedEntityMembership.description,
876
+ icon: Link,
877
+ category: "needs-table",
878
+ hasDataNode: false,
879
+ fieldOverrides: {
880
+ entity_field: {
881
+ type: "uuid",
882
+ required: true,
883
+ label: "Foreign Key Field",
884
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.entity_field?.description
885
+ },
886
+ membership_type: {
887
+ type: "integer",
888
+ required: true,
889
+ component: "membership-type-select",
890
+ label: "Membership Scope",
891
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.membership_type?.description
892
+ },
893
+ obj_schema: { hidden: true },
894
+ obj_table: {
895
+ type: "string",
896
+ required: true,
897
+ component: "table-select",
898
+ label: "Linked Table",
899
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.obj_table?.description
900
+ },
901
+ obj_field: {
902
+ type: "uuid",
903
+ required: true,
904
+ label: "Entity Field on Linked Table",
905
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.obj_field?.description,
906
+ dependsOn: "obj_table"
907
+ },
908
+ permission: {
909
+ type: "string",
910
+ component: "permission-select",
911
+ label: "Required Permission",
912
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.permission?.description
913
+ },
914
+ is_admin: {
915
+ type: "boolean",
916
+ label: "Admins",
917
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.is_admin?.description
918
+ },
919
+ is_owner: {
920
+ type: "boolean",
921
+ label: "Owners",
922
+ description: paramOf(NodeTypes.AuthzRelatedEntityMembership)?.is_owner?.description
923
+ }
924
+ }
925
+ },
926
+ AuthzOrgHierarchy: {
927
+ fallbackTitle: NodeTypes.AuthzOrgHierarchy.display_name,
928
+ description: NodeTypes.AuthzOrgHierarchy.description,
929
+ icon: Network,
930
+ category: "has-module",
931
+ hasDataNode: true,
932
+ dataNodeType: NodeTypes.DataOwnershipInEntity.name,
933
+ disabled: true,
934
+ fieldOverrides: {
935
+ direction: {
936
+ type: "string",
937
+ required: true,
938
+ label: "Direction",
939
+ description: paramOf(NodeTypes.AuthzOrgHierarchy)?.direction?.description,
940
+ defaultValue: "down",
941
+ options: [{
942
+ value: "down",
943
+ label: "Down",
944
+ description: "Managers can see their subordinates"
945
+ }, {
946
+ value: "up",
947
+ label: "Up",
948
+ description: "Subordinates can see their managers"
949
+ }]
950
+ },
951
+ entity_field: {
952
+ type: "string",
953
+ label: "Entity Field Name",
954
+ placeholder: "entity_id",
955
+ description: paramOf(NodeTypes.AuthzOrgHierarchy)?.entity_field?.description,
956
+ defaultValue: paramOf(NodeTypes.AuthzOrgHierarchy)?.entity_field?.default ?? "entity_id"
957
+ },
958
+ anchor_field: {
959
+ type: "string",
960
+ required: true,
961
+ label: "Anchor Field",
962
+ placeholder: "owner_id",
963
+ description: paramOf(NodeTypes.AuthzOrgHierarchy)?.anchor_field?.description,
964
+ defaultValue: "owner_id"
965
+ },
966
+ max_depth: {
967
+ type: "integer",
968
+ label: "Max Depth",
969
+ description: paramOf(NodeTypes.AuthzOrgHierarchy)?.max_depth?.description
970
+ }
971
+ }
972
+ },
973
+ AuthzAllowAll: {
974
+ fallbackTitle: NodeTypes.AuthzAllowAll.display_name,
975
+ description: NodeTypes.AuthzAllowAll.description,
976
+ icon: Unlock,
977
+ category: "no-fields",
978
+ hasDataNode: false
979
+ },
980
+ AuthzDenyAll: {
981
+ fallbackTitle: NodeTypes.AuthzDenyAll.display_name,
982
+ description: NodeTypes.AuthzDenyAll.description,
983
+ icon: Lock,
984
+ category: "no-fields",
985
+ hasDataNode: false
986
+ },
987
+ AuthzComposite: {
988
+ fallbackTitle: NodeTypes.AuthzComposite.display_name,
989
+ description: NodeTypes.AuthzComposite.description,
990
+ icon: Layers,
991
+ category: "no-fields",
992
+ hasDataNode: false
993
+ }
994
+ };
995
+ const MEMBERSHIP_TYPE_OPTIONS$1 = [
996
+ {
997
+ value: MEMBERSHIP_TYPES.APP,
998
+ label: "App Member",
999
+ description: "Memberships to the app."
1000
+ },
1001
+ {
1002
+ value: MEMBERSHIP_TYPES.ORGANIZATION,
1003
+ label: "Organization Member",
1004
+ description: "Membership to an organization."
1005
+ },
1006
+ {
1007
+ value: MEMBERSHIP_TYPES.GROUP,
1008
+ label: "Group Member",
1009
+ description: "User's membership to a group."
1010
+ }
1011
+ ];
1012
+ /**
1013
+ * Fields that are auto-generated by each data node type.
1014
+ *
1015
+ * When a policy uses a data node (hasDataNode: true), these fields
1016
+ * will be automatically created on the table.
1017
+ */
1018
+ const DATA_NODE_GENERATED_FIELDS = {
1019
+ DataDirectOwner: [{
1020
+ name: "owner_id",
1021
+ type: "uuid",
1022
+ nullable: false,
1023
+ description: "References the owning user"
1024
+ }],
1025
+ DataEntityMembership: [{
1026
+ name: "entity_id",
1027
+ type: "uuid",
1028
+ nullable: false,
1029
+ description: "References the organization or group"
1030
+ }],
1031
+ DataOwnershipInEntity: [{
1032
+ name: "owner_id",
1033
+ type: "uuid",
1034
+ nullable: false,
1035
+ description: "References the owning user"
1036
+ }, {
1037
+ name: "entity_id",
1038
+ type: "uuid",
1039
+ nullable: false,
1040
+ description: "References the organization or group"
1041
+ }],
1042
+ DataPublishable: [{
1043
+ name: "is_published",
1044
+ type: "boolean",
1045
+ nullable: false,
1046
+ description: "Whether the record is published"
1047
+ }, {
1048
+ name: "published_at",
1049
+ type: "timestamptz",
1050
+ nullable: true,
1051
+ description: "When the record was published"
1052
+ }],
1053
+ DataTimestamps: [{
1054
+ name: "created_at",
1055
+ type: "timestamptz",
1056
+ nullable: false,
1057
+ description: "When the record was created"
1058
+ }, {
1059
+ name: "updated_at",
1060
+ type: "timestamptz",
1061
+ nullable: false,
1062
+ description: "When the record was last updated"
1063
+ }],
1064
+ DataPeoplestamps: [{
1065
+ name: "created_by",
1066
+ type: "uuid",
1067
+ nullable: true,
1068
+ description: "User who created the record"
1069
+ }, {
1070
+ name: "updated_by",
1071
+ type: "uuid",
1072
+ nullable: true,
1073
+ description: "User who last updated the record"
1074
+ }],
1075
+ DataSoftDelete: [{
1076
+ name: "is_deleted",
1077
+ type: "boolean",
1078
+ nullable: false,
1079
+ description: "Whether the record is soft-deleted"
1080
+ }, {
1081
+ name: "deleted_at",
1082
+ type: "timestamptz",
1083
+ nullable: true,
1084
+ description: "When the record was deleted"
1085
+ }]
1086
+ };
1087
+ /**
1088
+ * Get generated fields for a data node type
1089
+ */
1090
+ function getGeneratedFields(dataNodeType) {
1091
+ return getGeneratedFields$1(dataNodeType);
1092
+ }
1093
+ /**
1094
+ * Derives the mapping from generated field names to policy keys for a given policy type.
1095
+ * This is computed from fieldOverrides where defaultValue matches a generated field name.
1096
+ *
1097
+ * Returns: { generatedFieldName: { policyKey, defaultValue } }
1098
+ */
1099
+ function getGeneratedFieldMappings(policyType) {
1100
+ if (!policyType.dataNodeType) return void 0;
1101
+ const generatedFields = DATA_NODE_GENERATED_FIELDS[policyType.dataNodeType];
1102
+ if (!generatedFields) return void 0;
1103
+ const generatedFieldNames = new Set(generatedFields.map((f) => f.name));
1104
+ const result = {};
1105
+ for (const [policyKey, override] of Object.entries(policyType.fieldOverrides ?? {})) {
1106
+ const defaultValue = override?.defaultValue;
1107
+ if (typeof defaultValue === "string" && generatedFieldNames.has(defaultValue)) result[defaultValue] = {
1108
+ policyKey,
1109
+ defaultValue
1110
+ };
1111
+ }
1112
+ return Object.keys(result).length > 0 ? result : void 0;
1113
+ }
1114
+ /**
1115
+ * Get the data node type for a policy type.
1116
+ */
1117
+ function getDataNodeForPolicy(policyType) {
1118
+ return getDataNodeForPolicy$1(policyType);
1119
+ }
1120
+ /**
1121
+ * Sanitize policy data by removing undefined/null values
1122
+ */
1123
+ function sanitizePolicyData(data) {
1124
+ return sanitizePolicyData$1(data);
1125
+ }
1126
+ /**
1127
+ * Build node data from policy data for the provision call.
1128
+ *
1129
+ * Some node types need specific configuration from the policy data
1130
+ * (e.g., DataDirectOwner may need a custom field name)
1131
+ */
1132
+ function buildNodeData(policyData, policyType) {
1133
+ return buildNodeData$1(policyType.name, policyData);
1134
+ }
1135
+ /**
1136
+ * Inject schema ID into policy data for fields that require it.
1137
+ * These fields are hidden from the form but need to be populated at submit time.
1138
+ */
1139
+ function injectSchemaFields(policyData, schemaId, policyType) {
1140
+ return injectSchemaFields$1(policyData, schemaId, policyType);
1141
+ }
1142
+ /**
1143
+ * Get the policy category for a policy type
1144
+ */
1145
+ function getPolicyCategory(policyType) {
1146
+ return getPolicyCategory$1(policyType);
1147
+ }
1148
+ /**
1149
+ * Get fields that need database columns created (those with pgType in fieldOverrides)
1150
+ */
1151
+ function getFieldsRequiringColumns(policyType) {
1152
+ return getFieldsRequiringColumns$1(policyType);
1153
+ }
1154
+ /**
1155
+ * Walk a composite condition tree and inject schema fields into each leaf's data.
1156
+ * Returns a new tree (immutable).
1157
+ */
1158
+ function injectSchemaFieldsIntoCompositeTree(tree, schemaId) {
1159
+ return {
1160
+ ...tree,
1161
+ children: tree.children.map((child) => {
1162
+ if (child.type === "condition") return {
1163
+ ...child,
1164
+ data: {
1165
+ ...child.data,
1166
+ data: injectSchemaFields(child.data.data, schemaId, child.data.policyType)
1167
+ }
1168
+ };
1169
+ return injectSchemaFieldsIntoCompositeTree(child, schemaId);
1170
+ })
1171
+ };
1172
+ }
1173
+
1174
+ //#endregion
1175
+ //#region src/schema/schema-builder-policies/lib/gql/hooks/schema-builder/policies/use-create-policy-field.ts
1176
+ /**
1177
+ * Hook for creating fields for policies
1178
+ * Tier 4 wrapper: uses SDK + transform + custom cache invalidation
1179
+ */
1180
+ function useCreatePolicyField() {
1181
+ const queryClient = useQueryClient();
1182
+ const createFieldMutation = useCreateFieldMutation({ selection: { fields: {
1183
+ id: true,
1184
+ name: true,
1185
+ type: true
1186
+ } } });
1187
+ return useMutation({
1188
+ mutationFn: async (input) => {
1189
+ const createdField = (await createFieldMutation.mutateAsync({
1190
+ name: input.name,
1191
+ tableId: input.tableId,
1192
+ databaseId: input.databaseId,
1193
+ type: toFieldType(input.fieldType),
1194
+ isRequired: false
1195
+ })).createField?.field;
1196
+ if (!createdField?.id) throw new Error("Failed to create field");
1197
+ return {
1198
+ id: createdField.id,
1199
+ name: createdField.name ?? "",
1200
+ type: fieldTypeToTypeName(createdField.type)
1201
+ };
1202
+ },
1203
+ onSuccess: async (_createdField, variables) => {
1204
+ await queryClient.invalidateQueries({ queryKey: databasePoliciesQueryKeys.byDatabase(variables.databaseId) });
1205
+ }
1206
+ });
1207
+ }
1208
+
1209
+ //#endregion
1210
+ //#region src/schema/schema-builder-core/components/policies/policy-types.ts
1211
+ /**
1212
+ * Reverse mapping from SQL privileges to CRUD operations
1213
+ */
1214
+ const PRIVILEGE_TO_OPERATION = {
1215
+ INSERT: "create",
1216
+ SELECT: "read",
1217
+ UPDATE: "update",
1218
+ DELETE: "delete"
1219
+ };
1220
+ /**
1221
+ * All CRUD operations in display order
1222
+ */
1223
+ const CRUD_OPERATIONS = [
1224
+ "create",
1225
+ "read",
1226
+ "update",
1227
+ "delete"
1228
+ ];
1229
+ const OPERATION_STYLES = {
1230
+ create: {
1231
+ bgClass: "bg-emerald-500/10 ring-1 ring-emerald-500/30",
1232
+ textClass: "text-emerald-600 dark:text-emerald-400",
1233
+ iconName: "Plus"
1234
+ },
1235
+ read: {
1236
+ bgClass: "bg-sky-500/10 ring-1 ring-sky-500/30",
1237
+ textClass: "text-sky-600 dark:text-sky-400",
1238
+ iconName: "Search"
1239
+ },
1240
+ update: {
1241
+ bgClass: "bg-amber-500/10 ring-1 ring-amber-500/30",
1242
+ textClass: "text-amber-600 dark:text-amber-400",
1243
+ iconName: "Pencil"
1244
+ },
1245
+ delete: {
1246
+ bgClass: "bg-rose-500/10 ring-1 ring-rose-500/30",
1247
+ textClass: "text-rose-600 dark:text-rose-400",
1248
+ iconName: "Trash2"
1249
+ }
1250
+ };
1251
+
1252
+ //#endregion
1253
+ //#region src/schema/schema-builder-core/lib/policies/provision-helpers.ts
1254
+ /** Full-CRUD grant on all columns. */
1255
+ const ALL_CRUD_PRIVILEGES = [
1256
+ ["select", "*"],
1257
+ ["insert", "*"],
1258
+ ["update", "*"],
1259
+ ["delete", "*"]
1260
+ ];
1261
+ const CRUD_OP_TO_LOWER_PRIVILEGE = {
1262
+ create: "insert",
1263
+ read: "select",
1264
+ update: "update",
1265
+ delete: "delete"
1266
+ };
1267
+ /** Convert a CRUD op (`'read'`, `'create'`, …) to the lowercase privilege verb the backend expects. */
1268
+ function crudOpToPrivilege(op) {
1269
+ return CRUD_OP_TO_LOWER_PRIVILEGE[op];
1270
+ }
1271
+ /** Convert many CRUD ops to their lowercase privilege verbs. */
1272
+ function crudOpsToPrivileges(ops) {
1273
+ return ops.map(crudOpToPrivilege);
1274
+ }
1275
+ /**
1276
+ * Build a single-entry `grants[]` array: one role group with the given privileges.
1277
+ * Defaults to `['authenticated']` with full-CRUD on all columns.
1278
+ */
1279
+ function buildGrants(roles = ["authenticated"], privileges = ALL_CRUD_PRIVILEGES) {
1280
+ return [{
1281
+ roles,
1282
+ privileges
1283
+ }];
1284
+ }
1285
+ /**
1286
+ * Build a single `policies[]` entry. Only `$type` is required; other fields are omitted
1287
+ * when falsy/empty so the backend defaults kick in.
1288
+ */
1289
+ function buildPolicyEntry(type, opts = {}) {
1290
+ const entry = { $type: type };
1291
+ if (opts.data && Object.keys(opts.data).length > 0) entry.data = opts.data;
1292
+ if (opts.privileges && opts.privileges.length > 0) entry.privileges = opts.privileges;
1293
+ if (opts.policy_role) entry.policy_role = opts.policy_role;
1294
+ if (opts.permissive !== void 0) entry.permissive = opts.permissive;
1295
+ if (opts.policy_name) entry.policy_name = opts.policy_name;
1296
+ return entry;
1297
+ }
1298
+ /**
1299
+ * Group enabled CRUD operations by (roleName, isPermissive). Each distinct group
1300
+ * becomes one `policies[]` entry, since the backend models them as separate policies.
1301
+ */
1302
+ function groupOperationsByConfig(enabledOperations, operations) {
1303
+ const groupMap = /* @__PURE__ */ new Map();
1304
+ for (const op of enabledOperations) {
1305
+ const config = operations[op];
1306
+ const key = `${config.roleName}:${config.isPermissive}`;
1307
+ let group = groupMap.get(key);
1308
+ if (!group) {
1309
+ group = {
1310
+ roleName: config.roleName,
1311
+ isPermissive: config.isPermissive,
1312
+ privileges: []
1313
+ };
1314
+ groupMap.set(key, group);
1315
+ }
1316
+ group.privileges.push(...crudOpsToPrivileges([op]));
1317
+ }
1318
+ return [...groupMap.values()];
1319
+ }
1320
+
1321
+ //#endregion
1322
+ //#region src/schema/schema-builder-core/lib/policies/add-policies-to-table.ts
1323
+ /**
1324
+ * Non-React core for adding RLS policies to an existing table.
1325
+ *
1326
+ * Shared by:
1327
+ * - `useCreateTableWithPolicies` (existing-table standard branch in policy-hooks.ts)
1328
+ * - `executeAddPolicies` chat tool (exec-add-policies.ts)
1329
+ *
1330
+ * Scope: standard policy categories only (`has-module`, `no-fields`, `needs-table`).
1331
+ * `needs-fields` and `AuthzComposite` need column creation / multi-step orchestration
1332
+ * that lives in the React hook for now.
1333
+ */
1334
+ const SUPPORTED_CATEGORIES = /* @__PURE__ */ new Set([
1335
+ "has-module",
1336
+ "no-fields",
1337
+ "needs-table"
1338
+ ]);
1339
+ var UnsupportedPolicyCategoryError = class extends Error {
1340
+ policyType;
1341
+ category;
1342
+ constructor(policyType, category) {
1343
+ super(`Policy type "${policyType}" has category "${category}" which requires column creation or composite handling — use the policies UI instead.`);
1344
+ this.policyType = policyType;
1345
+ this.category = category;
1346
+ this.name = "UnsupportedPolicyCategoryError";
1347
+ }
1348
+ };
1349
+ /**
1350
+ * Install all policy entries in a single `secureTableProvision.create` call.
1351
+ * The backend `policies[]` and `nodes[]` arrays accept multiple items per call, so the
1352
+ * whole batch is atomic — either all policies land or none do.
1353
+ */
1354
+ async function addPoliciesToExistingTable(input) {
1355
+ for (const entry of input.policies) {
1356
+ const category = getPolicyCategory(entry.policyType);
1357
+ if (!SUPPORTED_CATEGORIES.has(category)) throw new UnsupportedPolicyCategoryError(entry.policyType, category);
1358
+ }
1359
+ const policiesArray = [];
1360
+ const nodesByType = /* @__PURE__ */ new Map();
1361
+ for (const entry of input.policies) {
1362
+ const groups = groupOperationsByConfig(entry.enabledOperations ?? CRUD_OPERATIONS, entry.operations);
1363
+ for (const group of groups) {
1364
+ const ops = group.privileges.join("_");
1365
+ const rand = Math.random().toString(36).slice(2, 8);
1366
+ policiesArray.push(buildPolicyEntry(entry.policyType, {
1367
+ privileges: group.privileges,
1368
+ policy_role: group.roleName,
1369
+ permissive: group.isPermissive,
1370
+ data: entry.sharedPolicyData,
1371
+ policy_name: `${ops}_${rand}`
1372
+ }));
1373
+ }
1374
+ if (entry.dataNodeType && !nodesByType.has(entry.dataNodeType)) {
1375
+ const nodeData = entry.nodeData ?? {};
1376
+ nodesByType.set(entry.dataNodeType, {
1377
+ $type: entry.dataNodeType,
1378
+ ...Object.keys(nodeData).length > 0 ? { data: nodeData } : {}
1379
+ });
1380
+ }
1381
+ }
1382
+ const provisionInput = {
1383
+ databaseId: input.databaseId,
1384
+ schemaId: input.schemaId,
1385
+ tableId: input.tableId,
1386
+ grants: buildGrants(),
1387
+ policies: policiesArray
1388
+ };
1389
+ if (nodesByType.size > 0) provisionInput.nodes = [...nodesByType.values()];
1390
+ await input.createSecureTableProvision(provisionInput);
1391
+ return { success: true };
1392
+ }
1393
+
1394
+ //#endregion
1395
+ //#region src/schema/schema-builder-policies/components/policies/policy-hooks.ts
1396
+ /**
1397
+ * Build policy types from UI config only (fallback when backend unavailable)
1398
+ */
1399
+ function buildPolicyTypesFromUIConfig() {
1400
+ return Object.entries(POLICY_TYPE_UI_CONFIG).filter(([, c]) => !c.disabled).map(([name, uiConfig]) => ({
1401
+ name,
1402
+ title: uiConfig.fallbackTitle,
1403
+ description: uiConfig.description,
1404
+ icon: uiConfig.icon,
1405
+ category: uiConfig.category,
1406
+ hasDataNode: uiConfig.hasDataNode,
1407
+ dataNodeType: uiConfig.dataNodeType,
1408
+ generatedFields: uiConfig.dataNodeType ? getGeneratedFields(uiConfig.dataNodeType) : [],
1409
+ fieldOverrides: uiConfig.fieldOverrides,
1410
+ advancedFields: uiConfig.advancedFields,
1411
+ diagramKey: name
1412
+ }));
1413
+ }
1414
+ /**
1415
+ * Hook to fetch policy types from the backend registry and merge with UI config.
1416
+ *
1417
+ * Falls back to UI config only if backend returns no data.
1418
+ * Display order follows POLICY_TYPE_UI_CONFIG insertion order.
1419
+ */
1420
+ function usePolicyTypes() {
1421
+ return {
1422
+ policyTypes: useMemo(() => {
1423
+ return buildPolicyTypesFromUIConfig();
1424
+ }, []),
1425
+ isLoading: false,
1426
+ error: null
1427
+ };
1428
+ }
1429
+ /**
1430
+ * Hook to get a single policy type by name
1431
+ */
1432
+ function usePolicyType(policyTypeName) {
1433
+ const { policyTypes, isLoading, error } = usePolicyTypes();
1434
+ return {
1435
+ policyType: useMemo(() => {
1436
+ if (!policyTypeName) return null;
1437
+ return policyTypes.find((pt) => pt.name === policyTypeName) ?? null;
1438
+ }, [policyTypes, policyTypeName]),
1439
+ isLoading,
1440
+ error
1441
+ };
1442
+ }
1443
+ /**
1444
+ * Resolve a FieldOverride to a FormFieldType.
1445
+ * component takes priority over type.
1446
+ */
1447
+ function resolveFormFieldType(override) {
1448
+ if (override.component) return override.component;
1449
+ switch (override.type) {
1450
+ case "boolean": return "boolean";
1451
+ case "integer": return "number";
1452
+ case "uuid": return "field-select";
1453
+ case "uuid[]": return "field-multi-select";
1454
+ default: return "text";
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Build form fields from fieldOverrides config.
1459
+ */
1460
+ function buildFormFields(overrides) {
1461
+ if (!overrides) return [];
1462
+ const fields = [];
1463
+ for (const [key, override] of Object.entries(overrides)) {
1464
+ if (override.hidden) continue;
1465
+ if (!override.type && !override.component) continue;
1466
+ fields.push({
1467
+ key,
1468
+ type: resolveFormFieldType(override),
1469
+ label: override.label ?? formatKeyAsLabel(key),
1470
+ description: override.description,
1471
+ placeholder: override.placeholder,
1472
+ required: override.required ?? false,
1473
+ defaultValue: override.defaultValue,
1474
+ dependsOn: override.dependsOn,
1475
+ options: override.options,
1476
+ pgType: override.pgType
1477
+ });
1478
+ }
1479
+ return fields;
1480
+ }
1481
+ /**
1482
+ * Format a snake_case key as a human-readable label
1483
+ */
1484
+ function formatKeyAsLabel(key) {
1485
+ return key.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1486
+ }
1487
+ /**
1488
+ * Hook to convert a policy type's field overrides to form fields
1489
+ *
1490
+ * Returns:
1491
+ * - mainFields: Fields shown in the main form area
1492
+ * - advancedFields: Fields shown in the collapsible advanced section
1493
+ */
1494
+ function useFormSchema(policyType) {
1495
+ return useMemo(() => {
1496
+ if (!policyType) return {
1497
+ mainFields: [],
1498
+ advancedFields: [],
1499
+ allFields: []
1500
+ };
1501
+ const allFields = buildFormFields(policyType.fieldOverrides);
1502
+ const advancedKeys = new Set(policyType.advancedFields ?? []);
1503
+ return {
1504
+ mainFields: allFields.filter((f) => !advancedKeys.has(f.key)),
1505
+ advancedFields: allFields.filter((f) => advancedKeys.has(f.key)),
1506
+ allFields
1507
+ };
1508
+ }, [policyType]);
1509
+ }
1510
+ /**
1511
+ * Get default values for all fields in a policy type
1512
+ */
1513
+ function getDefaultFormValues(policyType) {
1514
+ if (!policyType) return {};
1515
+ const fields = buildFormFields(policyType.fieldOverrides);
1516
+ const defaults = {};
1517
+ for (const field of fields) if (field.defaultValue !== void 0) defaults[field.key] = field.defaultValue;
1518
+ if (policyType.fieldOverrides) {
1519
+ for (const [key, override] of Object.entries(policyType.fieldOverrides)) if (override.hidden && override.defaultValue !== void 0 && defaults[key] === void 0) defaults[key] = override.defaultValue;
1520
+ }
1521
+ return defaults;
1522
+ }
1523
+ /**
1524
+ * Check if a policy type has fields that need user configuration.
1525
+ * Returns true if any required or non-defaulted field is empty.
1526
+ */
1527
+ function hasRequiredFieldsMissing(policyType, data) {
1528
+ if (!policyType) return false;
1529
+ const fields = buildFormFields(policyType.fieldOverrides);
1530
+ for (const field of fields) {
1531
+ if (field.type === "boolean") continue;
1532
+ if (field.type === "permission-select") continue;
1533
+ const value = data[field.key];
1534
+ if (!(value === null || value === void 0 || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0)) continue;
1535
+ if (field.required) return true;
1536
+ if (field.defaultValue === void 0 || field.defaultValue === null || field.defaultValue === "") return true;
1537
+ }
1538
+ return false;
1539
+ }
1540
+ /**
1541
+ * Hook to create a table with CRUD policies via `secure_table_provision`.
1542
+ *
1543
+ * One provision call now carries all grants + all policies for a table atomically,
1544
+ * so operations grouped by (role, permissive) become separate `policies[]` entries
1545
+ * in a single call rather than a sequence of calls.
1546
+ *
1547
+ * - Standard (has-module / no-fields / needs-table): single call.
1548
+ * - Needs-fields: table-creation call, per-field createField calls, then single policy call.
1549
+ * - Composite: table-creation call bundles all sub-policy data nodes, per-leaf createField calls
1550
+ * for needs-fields leaves, then single composite-policy call.
1551
+ */
1552
+ function useCreateTableWithPolicies() {
1553
+ const queryClient = useQueryClient();
1554
+ const { selectTable } = useSchemaBuilderSelectors();
1555
+ const createProvision = useCreateSecureTableProvisionMutation({ selection: { fields: {
1556
+ id: true,
1557
+ tableId: true,
1558
+ tableName: true
1559
+ } } });
1560
+ const createField = useCreatePolicyField();
1561
+ const mutation = useMutation({
1562
+ mutationFn: async (input) => {
1563
+ const { databaseId, schemaId, tableId: existingTableId, tableName, policyType, dataNodeType, nodeData = {}, sharedPolicyData, operations, enabledOperations = CRUD_OPERATIONS, fieldNameOverrides = {}, compositeTree } = input;
1564
+ const category = getPolicyCategory(policyType);
1565
+ let tableId = existingTableId;
1566
+ if (policyType === "AuthzComposite" && compositeTree) {
1567
+ const leaves = compositeTree.children.filter((c) => c.type === "condition");
1568
+ const seenModules = /* @__PURE__ */ new Set();
1569
+ const seenFields = /* @__PURE__ */ new Set();
1570
+ const firstModuleLeaf = leaves.find((leaf) => {
1571
+ const subCategory = getPolicyCategory(leaf.data.policyType);
1572
+ const subConfig = POLICY_TYPE_UI_CONFIG[leaf.data.policyType];
1573
+ return subCategory === "has-module" && subConfig?.dataNodeType;
1574
+ });
1575
+ const step1Input = {
1576
+ databaseId,
1577
+ schemaId,
1578
+ grants: buildGrants()
1579
+ };
1580
+ if (tableId) step1Input.tableId = tableId;
1581
+ else step1Input.tableName = tableName;
1582
+ if (firstModuleLeaf) {
1583
+ const subConfig = POLICY_TYPE_UI_CONFIG[firstModuleLeaf.data.policyType];
1584
+ if (subConfig?.dataNodeType) {
1585
+ seenModules.add(subConfig.dataNodeType);
1586
+ const modData = buildNodeData(firstModuleLeaf.data.data, { dataNodeType: subConfig.dataNodeType });
1587
+ const moduleNode = {
1588
+ $type: subConfig.dataNodeType,
1589
+ ...Object.keys(modData).length > 0 ? { data: modData } : {}
1590
+ };
1591
+ step1Input.nodes = !tableId ? [{ $type: "DataId" }, moduleNode] : [moduleNode];
1592
+ }
1593
+ }
1594
+ const r = await createProvision.mutateAsync(step1Input);
1595
+ if (!tableId) {
1596
+ tableId = r.createSecureTableProvision?.secureTableProvision?.tableId ?? void 0;
1597
+ if (!tableId) throw new Error("Provision failed: no tableId returned");
1598
+ }
1599
+ for (const leaf of leaves) {
1600
+ const subType = leaf.data.policyType;
1601
+ const subData = leaf.data.data;
1602
+ const subCategory = getPolicyCategory(subType);
1603
+ const subConfig = POLICY_TYPE_UI_CONFIG[subType];
1604
+ if (subCategory === "has-module" && subConfig?.dataNodeType && !seenModules.has(subConfig.dataNodeType)) {
1605
+ seenModules.add(subConfig.dataNodeType);
1606
+ const modData = buildNodeData(subData, { dataNodeType: subConfig.dataNodeType });
1607
+ await createProvision.mutateAsync({
1608
+ databaseId,
1609
+ schemaId,
1610
+ tableId,
1611
+ nodes: [{
1612
+ $type: subConfig.dataNodeType,
1613
+ ...Object.keys(modData).length > 0 ? { data: modData } : {}
1614
+ }]
1615
+ });
1616
+ }
1617
+ if (subCategory === "needs-fields") for (const fieldConfig of getFieldsRequiringColumns(subType)) {
1618
+ const resolved = subData[fieldConfig.key] || fieldConfig.defaultName;
1619
+ const names = Array.isArray(resolved) ? resolved : [resolved];
1620
+ for (const name of names) if (!seenFields.has(name)) {
1621
+ seenFields.add(name);
1622
+ await createField.mutateAsync({
1623
+ name,
1624
+ tableId,
1625
+ databaseId,
1626
+ fieldType: fieldConfig.pgType
1627
+ });
1628
+ }
1629
+ }
1630
+ }
1631
+ const config = operations[enabledOperations[0]];
1632
+ await createProvision.mutateAsync({
1633
+ databaseId,
1634
+ schemaId,
1635
+ tableId,
1636
+ policies: [buildPolicyEntry("AuthzComposite", {
1637
+ privileges: crudOpsToPrivileges(enabledOperations),
1638
+ policy_role: config.roleName,
1639
+ permissive: config.isPermissive,
1640
+ data: sharedPolicyData
1641
+ })]
1642
+ });
1643
+ return {
1644
+ tableId,
1645
+ tableName,
1646
+ policyIds: []
1647
+ };
1648
+ }
1649
+ if (category === "needs-fields") {
1650
+ if (!tableId) {
1651
+ tableId = (await createProvision.mutateAsync({
1652
+ databaseId,
1653
+ schemaId,
1654
+ tableName,
1655
+ grants: buildGrants()
1656
+ })).createSecureTableProvision?.secureTableProvision?.tableId ?? void 0;
1657
+ if (!tableId) throw new Error("Provision failed: no tableId returned");
1658
+ }
1659
+ const createdFieldNames = {};
1660
+ const fieldsToCreate = getFieldsRequiringColumns(policyType);
1661
+ for (const fieldConfig of fieldsToCreate) {
1662
+ const resolved = fieldNameOverrides?.[fieldConfig.key] || fieldConfig.defaultName;
1663
+ const fieldNames = Array.isArray(resolved) ? resolved : [resolved];
1664
+ for (const name of fieldNames) await createField.mutateAsync({
1665
+ name,
1666
+ tableId,
1667
+ databaseId,
1668
+ fieldType: fieldConfig.pgType
1669
+ });
1670
+ createdFieldNames[fieldConfig.key] = Array.isArray(fieldConfig.defaultName) ? fieldNames : fieldNames[0];
1671
+ }
1672
+ const policyData = {
1673
+ ...sharedPolicyData,
1674
+ ...createdFieldNames
1675
+ };
1676
+ const groups = groupOperationsByConfig(enabledOperations, operations);
1677
+ await createProvision.mutateAsync({
1678
+ databaseId,
1679
+ schemaId,
1680
+ tableId,
1681
+ policies: groups.map((group) => buildPolicyEntry(policyType, {
1682
+ privileges: group.privileges,
1683
+ policy_role: group.roleName,
1684
+ permissive: group.isPermissive,
1685
+ data: policyData,
1686
+ policy_name: group.privileges.join("_")
1687
+ }))
1688
+ });
1689
+ return {
1690
+ tableId,
1691
+ tableName,
1692
+ policyIds: []
1693
+ };
1694
+ }
1695
+ if (tableId) {
1696
+ await addPoliciesToExistingTable({
1697
+ createSecureTableProvision: (input) => createProvision.mutateAsync(input),
1698
+ databaseId,
1699
+ schemaId,
1700
+ tableId,
1701
+ policies: [{
1702
+ policyType,
1703
+ dataNodeType,
1704
+ nodeData,
1705
+ sharedPolicyData,
1706
+ operations,
1707
+ enabledOperations
1708
+ }]
1709
+ });
1710
+ return {
1711
+ tableId,
1712
+ tableName,
1713
+ policyIds: []
1714
+ };
1715
+ }
1716
+ const policiesArray = groupOperationsByConfig(enabledOperations, operations).map((group) => buildPolicyEntry(policyType, {
1717
+ privileges: group.privileges,
1718
+ policy_role: group.roleName,
1719
+ permissive: group.isPermissive,
1720
+ data: sharedPolicyData,
1721
+ policy_name: group.privileges.join("_")
1722
+ }));
1723
+ const provisionInput = {
1724
+ databaseId,
1725
+ schemaId,
1726
+ tableName,
1727
+ grants: buildGrants(),
1728
+ policies: policiesArray
1729
+ };
1730
+ if (dataNodeType) provisionInput.nodes = [{ $type: "DataId" }, {
1731
+ $type: dataNodeType,
1732
+ ...Object.keys(nodeData).length > 0 ? { data: nodeData } : {}
1733
+ }];
1734
+ const newTableId = (await createProvision.mutateAsync(provisionInput)).createSecureTableProvision?.secureTableProvision?.tableId ?? void 0;
1735
+ if (!newTableId) throw new Error("Provision failed: no tableId returned");
1736
+ return {
1737
+ tableId: newTableId,
1738
+ tableName,
1739
+ policyIds: []
1740
+ };
1741
+ },
1742
+ onSuccess: async (result, variables) => {
1743
+ await invalidateDatabaseEntities(queryClient, variables.databaseId);
1744
+ if (!variables.tableId) selectTable(result.tableId, result.tableName);
1745
+ },
1746
+ onError: (error) => {
1747
+ console.error("Failed to create table with policies:", error);
1748
+ }
1749
+ });
1750
+ return {
1751
+ createTableWithPolicies: mutation.mutateAsync,
1752
+ isCreating: mutation.isPending,
1753
+ error: mutation.error
1754
+ };
1755
+ }
1756
+
1757
+ //#endregion
1758
+ //#region src/schema/schema-builder-policies/components/policies/policy-config-form/auto-generated-fields-info.tsx
1759
+ /**
1760
+ * Info box showing fields that will be automatically created by a table module.
1761
+ * Supports inline editing of field names when mappings are provided.
1762
+ */
1763
+ function AutoGeneratedFieldsInfo({ fields, value, onChange, fieldMappings, disabled }) {
1764
+ const [editingField, setEditingField] = useState(null);
1765
+ const [editValue, setEditValue] = useState("");
1766
+ if (!fields.length) return null;
1767
+ const handleStartEdit = (fieldName, currentValue) => {
1768
+ setEditingField(fieldName);
1769
+ setEditValue(currentValue);
1770
+ };
1771
+ const handleSave = (fieldName) => {
1772
+ const mapping = fieldMappings?.[fieldName];
1773
+ if (mapping && onChange && editValue.trim()) onChange(mapping.policyKey, editValue.trim());
1774
+ setEditingField(null);
1775
+ setEditValue("");
1776
+ };
1777
+ const handleCancel = () => {
1778
+ setEditingField(null);
1779
+ setEditValue("");
1780
+ };
1781
+ const handleKeyDown = (e, fieldName) => {
1782
+ if (e.key === "Enter") handleSave(fieldName);
1783
+ else if (e.key === "Escape") handleCancel();
1784
+ };
1785
+ const getDisplayName = (field) => {
1786
+ const mapping = fieldMappings?.[field.name];
1787
+ if (mapping && value) {
1788
+ const customValue = value[mapping.policyKey];
1789
+ if (typeof customValue === "string" && customValue !== mapping.defaultValue) return customValue;
1790
+ }
1791
+ return field.name;
1792
+ };
1793
+ const hasFieldMapping = (fieldName) => {
1794
+ return !!fieldMappings?.[fieldName] && !!onChange;
1795
+ };
1796
+ const handleReset = (fieldName) => {
1797
+ const mapping = fieldMappings?.[fieldName];
1798
+ if (mapping && onChange) {
1799
+ onChange(mapping.policyKey, mapping.defaultValue);
1800
+ setEditValue(mapping.defaultValue);
1801
+ }
1802
+ };
1803
+ return /* @__PURE__ */ jsxs("div", {
1804
+ className: "border-border/60 overflow-hidden rounded-lg border",
1805
+ children: [/* @__PURE__ */ jsxs("div", {
1806
+ className: "bg-muted/50 flex items-center gap-2 border-b px-4 py-2.5",
1807
+ children: [/* @__PURE__ */ jsx(Table2, { className: "text-muted-foreground h-4 w-4" }), /* @__PURE__ */ jsx("span", {
1808
+ className: "text-muted-foreground text-xs font-medium",
1809
+ children: "The following fields will be auto-generated:"
1810
+ })]
1811
+ }), /* @__PURE__ */ jsx("div", {
1812
+ className: "divide-border divide-y",
1813
+ children: fields.map((field) => {
1814
+ const displayName = getDisplayName(field);
1815
+ const canEdit = hasFieldMapping(field.name);
1816
+ return /* @__PURE__ */ jsxs("div", {
1817
+ className: "space-y-1 px-4 py-3",
1818
+ children: [/* @__PURE__ */ jsxs("div", {
1819
+ className: "flex items-center gap-2",
1820
+ children: [editingField === field.name ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Input, {
1821
+ type: "text",
1822
+ value: editValue,
1823
+ onChange: (e) => setEditValue(e.target.value),
1824
+ onKeyDown: (e) => handleKeyDown(e, field.name),
1825
+ className: "w-40 text-xs",
1826
+ size: "sm",
1827
+ autoFocus: true
1828
+ }), /* @__PURE__ */ jsxs("div", {
1829
+ className: "flex items-center gap-0.5",
1830
+ children: [
1831
+ /* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
1832
+ asChild: true,
1833
+ children: /* @__PURE__ */ jsx("button", {
1834
+ type: "button",
1835
+ onClick: () => handleSave(field.name),
1836
+ "aria-label": `Save ${displayName} field name`,
1837
+ className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg\n transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]",
1838
+ children: /* @__PURE__ */ jsx(CheckIcon, { className: "h-3.5 w-3.5" })
1839
+ })
1840
+ }), /* @__PURE__ */ jsx(TooltipContent, { children: "Save" })] }),
1841
+ /* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
1842
+ asChild: true,
1843
+ children: /* @__PURE__ */ jsx("button", {
1844
+ type: "button",
1845
+ onClick: handleCancel,
1846
+ "aria-label": "Cancel field name edit",
1847
+ className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg\n transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]",
1848
+ children: /* @__PURE__ */ jsx(XIcon, { className: "h-3.5 w-3.5" })
1849
+ })
1850
+ }), /* @__PURE__ */ jsx(TooltipContent, { children: "Cancel" })] }),
1851
+ /* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
1852
+ asChild: true,
1853
+ children: /* @__PURE__ */ jsx("button", {
1854
+ type: "button",
1855
+ onClick: () => handleReset(field.name),
1856
+ "aria-label": `Reset ${displayName} field name`,
1857
+ className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg\n transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]",
1858
+ children: /* @__PURE__ */ jsx(RotateCcwIcon, { className: "h-3.5 w-3.5" })
1859
+ })
1860
+ }), /* @__PURE__ */ jsx(TooltipContent, { children: "Reset to default" })] })
1861
+ ]
1862
+ })] }) : /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
1863
+ className: "text-sm font-medium",
1864
+ children: displayName
1865
+ }), canEdit && /* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
1866
+ asChild: true,
1867
+ children: /* @__PURE__ */ jsx("button", {
1868
+ type: "button",
1869
+ onClick: () => handleStartEdit(field.name, displayName),
1870
+ disabled,
1871
+ "aria-label": `Edit ${displayName} field name`,
1872
+ className: "hover:bg-muted text-muted-foreground hover:text-foreground grid size-10 place-items-center rounded-lg opacity-60\n transition-[background-color,color,opacity,scale] duration-150 ease-out hover:opacity-100 motion-safe:active:scale-[0.96]\n disabled:cursor-not-allowed disabled:opacity-30\n disabled:hover:bg-transparent",
1873
+ children: /* @__PURE__ */ jsx(PencilIcon, { className: "h-3 w-3" })
1874
+ })
1875
+ }), /* @__PURE__ */ jsx(TooltipContent, { children: "Edit field name" })] })] }), /* @__PURE__ */ jsx("span", {
1876
+ className: "bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px] font-medium",
1877
+ children: field.type
1878
+ })]
1879
+ }), /* @__PURE__ */ jsx("p", {
1880
+ className: "text-muted-foreground text-xs",
1881
+ children: field.description
1882
+ })]
1883
+ }, field.name);
1884
+ })
1885
+ })]
1886
+ });
1887
+ }
1888
+
1889
+ //#endregion
1890
+ //#region src/schema/schema-builder-policies/lib/gql/hooks/schema-builder/policies/use-permissions.ts
1891
+ /**
1892
+ * Hook for fetching app and membership permissions
1893
+ * Tier 4 wrapper: Uses SDK hooks + cache invalidation
1894
+ */
1895
+ function usePermissions(options = {}) {
1896
+ const isEnabled = options.enabled !== false;
1897
+ const { scope } = useSchemaBuilderRuntime();
1898
+ const { fetchAppPermissionsQuery, fetchOrgPermissionsQuery } = useAdminSdkClient();
1899
+ return useQuery({
1900
+ queryKey: schemaBuilderQueryKey(scope, "policies", "permissions"),
1901
+ queryFn: async () => {
1902
+ const [appResult, orgResult] = await Promise.all([fetchAppPermissionsQuery({ selection: {
1903
+ fields: {
1904
+ id: true,
1905
+ name: true,
1906
+ bitnum: true,
1907
+ bitstr: true,
1908
+ description: true
1909
+ },
1910
+ orderBy: ["NAME_ASC"]
1911
+ } }), fetchOrgPermissionsQuery({ selection: {
1912
+ fields: {
1913
+ id: true,
1914
+ name: true,
1915
+ bitnum: true,
1916
+ bitstr: true,
1917
+ description: true
1918
+ },
1919
+ orderBy: ["NAME_ASC"]
1920
+ } })]);
1921
+ return {
1922
+ appPermissions: (appResult.appPermissions?.nodes ?? []).map((node) => ({
1923
+ id: node.id ?? "",
1924
+ name: node.name ?? "",
1925
+ bitnum: node.bitnum ?? null,
1926
+ bitstr: node.bitstr ?? null,
1927
+ description: node.description ?? null
1928
+ })),
1929
+ membershipPermissions: (orgResult.orgPermissions?.nodes ?? []).map((node) => ({
1930
+ id: node.id ?? "",
1931
+ name: node.name ?? "",
1932
+ bitnum: node.bitnum ?? null,
1933
+ bitstr: node.bitstr ?? null,
1934
+ description: node.description ?? null
1935
+ }))
1936
+ };
1937
+ },
1938
+ enabled: isEnabled,
1939
+ staleTime: 300 * 1e3,
1940
+ refetchOnMount: isEnabled,
1941
+ refetchOnWindowFocus: false,
1942
+ refetchOnReconnect: false
1943
+ });
1944
+ }
1945
+
1946
+ //#endregion
1947
+ //#region src/schema/schema-builder-policies/components/policies/multi-value-field-editor.tsx
1948
+ function normalizeValue(value) {
1949
+ if (Array.isArray(value)) return value.map((v) => String(v));
1950
+ if (typeof value === "string") return value.trim() ? [value] : [];
1951
+ return [];
1952
+ }
1953
+ function MultiValueFieldEditor({ value, onChange, disabled, emptyText = "No fields yet", addButtonText = "Add field", typeBadge }) {
1954
+ const normalizedValue = useMemo(() => normalizeValue(value), [value]);
1955
+ const idsRef = useRef([]);
1956
+ const inputRefs = useRef([]);
1957
+ const pendingFocusIndex = useRef(null);
1958
+ useEffect(() => {
1959
+ const nextIds = idsRef.current.slice(0, normalizedValue.length);
1960
+ while (nextIds.length < normalizedValue.length) nextIds.push(`mv-${crypto.randomUUID()}`);
1961
+ idsRef.current = nextIds;
1962
+ }, [normalizedValue.length]);
1963
+ useEffect(() => {
1964
+ if (pendingFocusIndex.current === null) return;
1965
+ const idx = pendingFocusIndex.current;
1966
+ const el = inputRefs.current[idx] ?? null;
1967
+ if (el) {
1968
+ el.focus();
1969
+ el.select();
1970
+ }
1971
+ pendingFocusIndex.current = null;
1972
+ }, [normalizedValue.length]);
1973
+ const addOption = useCallback(() => {
1974
+ pendingFocusIndex.current = normalizedValue.length;
1975
+ idsRef.current = [...idsRef.current, `mv-${crypto.randomUUID()}`];
1976
+ onChange([...normalizedValue, ""]);
1977
+ }, [normalizedValue, onChange]);
1978
+ const updateOption = useCallback((index, nextValue) => {
1979
+ const next = normalizedValue.slice();
1980
+ next[index] = nextValue;
1981
+ onChange(next);
1982
+ }, [normalizedValue, onChange]);
1983
+ const removeOption = useCallback((index) => {
1984
+ idsRef.current = idsRef.current.filter((_, i) => i !== index);
1985
+ onChange(normalizedValue.filter((_, i) => i !== index));
1986
+ }, [normalizedValue, onChange]);
1987
+ const insertAfter = useCallback((index) => {
1988
+ const next = normalizedValue.slice();
1989
+ next.splice(index + 1, 0, "");
1990
+ const nextIds = idsRef.current.slice();
1991
+ nextIds.splice(index + 1, 0, `mv-${crypto.randomUUID()}`);
1992
+ idsRef.current = nextIds;
1993
+ pendingFocusIndex.current = index + 1;
1994
+ onChange(next);
1995
+ }, [normalizedValue, onChange]);
1996
+ const rowIds = idsRef.current;
1997
+ return /* @__PURE__ */ jsxs("div", {
1998
+ className: "space-y-2",
1999
+ children: [/* @__PURE__ */ jsx("div", {
2000
+ className: "space-y-2",
2001
+ children: normalizedValue.length === 0 ? /* @__PURE__ */ jsx("div", {
2002
+ className: "text-muted-foreground rounded-md border border-dashed p-3 text-xs",
2003
+ children: emptyText
2004
+ }) : normalizedValue.map((opt, index) => /* @__PURE__ */ jsxs("div", {
2005
+ className: "bg-background flex items-center gap-2 rounded-md border px-2 py-1.5",
2006
+ children: [
2007
+ /* @__PURE__ */ jsx(Input, {
2008
+ ref: (el) => {
2009
+ inputRefs.current[index] = el;
2010
+ },
2011
+ value: opt,
2012
+ onChange: (e) => updateOption(index, e.target.value),
2013
+ onKeyDown: (e) => {
2014
+ if (e.key === "Enter") {
2015
+ e.preventDefault();
2016
+ insertAfter(index);
2017
+ }
2018
+ },
2019
+ disabled,
2020
+ className: "h-8 border-none shadow-none focus-visible:ring-0"
2021
+ }),
2022
+ typeBadge && /* @__PURE__ */ jsx("span", {
2023
+ className: "text-muted-foreground shrink-0 text-xs",
2024
+ children: typeBadge
2025
+ }),
2026
+ /* @__PURE__ */ jsx(Button, {
2027
+ type: "button",
2028
+ variant: "ghost",
2029
+ size: "sm",
2030
+ onClick: () => removeOption(index),
2031
+ disabled,
2032
+ className: "text-muted-foreground/80 hover:text-destructive h-8 w-8 p-0",
2033
+ "aria-label": "Remove field",
2034
+ children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
2035
+ })
2036
+ ]
2037
+ }, rowIds[index] ?? `mv-${index}`))
2038
+ }), /* @__PURE__ */ jsx("div", {
2039
+ className: "pt-1",
2040
+ children: /* @__PURE__ */ jsxs(Button, {
2041
+ type: "button",
2042
+ variant: "outline",
2043
+ size: "sm",
2044
+ onClick: addOption,
2045
+ disabled,
2046
+ className: "h-7 gap-1.5 px-2",
2047
+ children: [/* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }), addButtonText]
2048
+ })
2049
+ })]
2050
+ });
2051
+ }
2052
+
2053
+ //#endregion
2054
+ //#region src/schema/schema-builder-policies/components/policies/policy-config-form/dynamic-form-field.tsx
2055
+ const MEMBERSHIP_TYPE_OPTIONS = [
2056
+ {
2057
+ value: "1",
2058
+ label: "App Member",
2059
+ description: "Check membership to the application"
2060
+ },
2061
+ {
2062
+ value: "2",
2063
+ label: "Organization Member",
2064
+ description: "Check membership to an organization"
2065
+ },
2066
+ {
2067
+ value: "3",
2068
+ label: "Group Member",
2069
+ description: "Check membership to a group"
2070
+ }
2071
+ ];
2072
+ const MEMBERSHIP_LABEL_MAP = {
2073
+ "1": "App Member",
2074
+ "2": "Organization Member",
2075
+ "3": "Group Member"
2076
+ };
2077
+ const normalizeFieldType = (type) => (type ?? "").toLowerCase();
2078
+ const isUuidType = (type) => {
2079
+ const t = normalizeFieldType(type);
2080
+ return (t === "uuid" || t === "uuid!") && !t.includes("[");
2081
+ };
2082
+ const isUuidArrayType = (type) => {
2083
+ const t = normalizeFieldType(type);
2084
+ return t === "uuid[]" || t === "uuid[]!" || t.startsWith("uuid[");
2085
+ };
2086
+ function getFieldsFromTable(tables, tableName) {
2087
+ return tables.find((t) => t.name === tableName)?.fields?.slice().sort((a, b) => (a.fieldOrder ?? 0) - (b.fieldOrder ?? 0)).map((f) => ({
2088
+ name: f.name,
2089
+ type: f.type ?? null
2090
+ })) ?? [];
2091
+ }
2092
+ /**
2093
+ * Table select using searchable Combobox
2094
+ */
2095
+ function TableSelectField({ field, value, onChange, disabled, tables }) {
2096
+ const tableOptions = useMemo(() => tables.filter((t) => t.category === "APP").map((t) => ({
2097
+ label: t.name,
2098
+ value: t.id
2099
+ })), [tables]);
2100
+ const selectedTable = tables.find((t) => t.name === value);
2101
+ return /* @__PURE__ */ jsxs(Combobox, {
2102
+ items: tableOptions,
2103
+ value: tableOptions.find((o) => o.value === selectedTable?.id) ?? null,
2104
+ onValueChange: (next) => {
2105
+ if (next) {
2106
+ const table = tables.find((t) => t.id === next.value);
2107
+ if (table) onChange(table.name);
2108
+ }
2109
+ },
2110
+ children: [/* @__PURE__ */ jsx(ComboboxInput, {
2111
+ placeholder: field.placeholder ?? "Search tables...",
2112
+ showClear: false
2113
+ }), /* @__PURE__ */ jsxs(ComboboxPopup, { children: [/* @__PURE__ */ jsx(ComboboxEmpty, { children: "No tables found" }), /* @__PURE__ */ jsx(ComboboxList, {
2114
+ className: "scrollbar-neutral-thin max-h-[180px] overflow-y-auto",
2115
+ children: (table) => /* @__PURE__ */ jsx(ComboboxItem, {
2116
+ value: table,
2117
+ children: /* @__PURE__ */ jsx("span", {
2118
+ className: "truncate",
2119
+ children: table.label
2120
+ })
2121
+ }, table.value)
2122
+ })] })]
2123
+ });
2124
+ }
2125
+ /**
2126
+ * Determine if a field key expects UUID array type
2127
+ */
2128
+ function expectsUuidArray(key) {
2129
+ return key === "owned_table_key";
2130
+ }
2131
+ /**
2132
+ * Determine if a field key expects UUID type
2133
+ */
2134
+ function expectsUuid(key) {
2135
+ return key.includes("_key") || key.includes("_ref_key");
2136
+ }
2137
+ /**
2138
+ * Field select dropdown, populated from fields of a dependent table
2139
+ */
2140
+ function DependentFieldSelectField({ field, value, onChange, disabled, tables, formData }) {
2141
+ const dependentTableName = field.dependsOn ? formData[field.dependsOn] : "";
2142
+ const isUuidArrayField = expectsUuidArray(field.key);
2143
+ const isUuidField = expectsUuid(field.key) && !isUuidArrayField;
2144
+ const hasTypeFilter = isUuidField || isUuidArrayField;
2145
+ const { fieldOptions, allFieldCount } = useMemo(() => {
2146
+ if (!dependentTableName) return {
2147
+ fieldOptions: [],
2148
+ allFieldCount: 0
2149
+ };
2150
+ const allFields = getFieldsFromTable(tables, dependentTableName);
2151
+ let filtered = allFields;
2152
+ if (isUuidArrayField) filtered = allFields.filter((f) => isUuidArrayType(f.type));
2153
+ else if (isUuidField) filtered = allFields.filter((f) => isUuidType(f.type));
2154
+ return {
2155
+ fieldOptions: filtered,
2156
+ allFieldCount: allFields.length
2157
+ };
2158
+ }, [
2159
+ dependentTableName,
2160
+ tables,
2161
+ field.key,
2162
+ isUuidArrayField,
2163
+ isUuidField
2164
+ ]);
2165
+ const isDisabled = disabled || !dependentTableName;
2166
+ const placeholder = !dependentTableName ? "Select table first" : field.placeholder ?? "Select field";
2167
+ const typeLabel = isUuidArrayField ? "UUID array" : "UUID";
2168
+ const hasHiddenFields = hasTypeFilter && allFieldCount > fieldOptions.length;
2169
+ return /* @__PURE__ */ jsxs(Select, {
2170
+ value: value || "",
2171
+ onValueChange: onChange,
2172
+ disabled: isDisabled,
2173
+ children: [/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder }) }), /* @__PURE__ */ jsx(SelectContent, {
2174
+ className: "max-h-48",
2175
+ children: !dependentTableName ? /* @__PURE__ */ jsx("div", {
2176
+ className: "text-muted-foreground py-4 text-center text-xs",
2177
+ children: "Select a table first"
2178
+ }) : fieldOptions.length === 0 ? /* @__PURE__ */ jsx("div", {
2179
+ className: "text-muted-foreground py-4 text-center text-xs",
2180
+ children: hasTypeFilter ? `No ${typeLabel} fields on "${dependentTableName}"` : "No fields available"
2181
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [fieldOptions.map((f) => /* @__PURE__ */ jsx(SelectFieldItem, {
2182
+ value: f.name,
2183
+ name: f.name,
2184
+ type: f.type ?? void 0
2185
+ }, f.name)), hasHiddenFields && /* @__PURE__ */ jsxs("div", {
2186
+ className: "text-muted-foreground flex items-center gap-1.5 border-t px-2 py-1.5 text-xs",
2187
+ children: [/* @__PURE__ */ jsx(Info, { className: "h-3 w-3 shrink-0" }), /* @__PURE__ */ jsxs("span", { children: [
2188
+ "Non-",
2189
+ typeLabel,
2190
+ " fields are hidden"
2191
+ ] })]
2192
+ })] })
2193
+ })]
2194
+ });
2195
+ }
2196
+ /**
2197
+ * Permission select dropdown, populated from usePermissions
2198
+ */
2199
+ function PermissionSelectField({ field, value, onChange, disabled, formData }) {
2200
+ const { data: permissions, isLoading } = usePermissions();
2201
+ const isAppLevel = formData?.membership_type === MEMBERSHIP_TYPES.APP;
2202
+ const permissionsList = isAppLevel ? permissions?.appPermissions || [] : permissions?.membershipPermissions || [];
2203
+ return /* @__PURE__ */ jsxs(Select, {
2204
+ value: value || "",
2205
+ onValueChange: (v) => onChange(v || void 0),
2206
+ disabled,
2207
+ children: [/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: isLoading ? "Loading..." : `Select ${isAppLevel ? "app" : "membership"} permission` }) }), /* @__PURE__ */ jsx(SelectContent, {
2208
+ className: "max-h-48",
2209
+ children: permissionsList.filter((p) => p.name).map((permission) => /* @__PURE__ */ jsx(SelectRichItem, {
2210
+ value: permission.name,
2211
+ label: permission.name ?? void 0,
2212
+ description: permission.description
2213
+ }, permission.id))
2214
+ })]
2215
+ });
2216
+ }
2217
+ /**
2218
+ * Renders a form field based on its type.
2219
+ * When tables data is available, uses proper dropdowns for table/field selection.
2220
+ */
2221
+ function DynamicFormField({ field, value, onChange, disabled, tables, formData }) {
2222
+ const hasTables = tables && tables.length > 0;
2223
+ const renderField = () => {
2224
+ switch (field.type) {
2225
+ case "table-select":
2226
+ if (hasTables) return /* @__PURE__ */ jsx(TableSelectField, {
2227
+ field,
2228
+ value: value ?? "",
2229
+ onChange,
2230
+ disabled,
2231
+ tables
2232
+ });
2233
+ return /* @__PURE__ */ jsx(Input, {
2234
+ type: "text",
2235
+ value: value ?? "",
2236
+ onChange: (e) => onChange(e.target.value),
2237
+ placeholder: field.placeholder,
2238
+ disabled
2239
+ });
2240
+ case "field-select":
2241
+ if (field.dependsOn && hasTables && formData) return /* @__PURE__ */ jsx(DependentFieldSelectField, {
2242
+ field,
2243
+ value: value ?? "",
2244
+ onChange,
2245
+ disabled,
2246
+ tables,
2247
+ formData
2248
+ });
2249
+ return /* @__PURE__ */ jsx(Input, {
2250
+ type: "text",
2251
+ value: value ?? "",
2252
+ onChange: (e) => onChange(e.target.value),
2253
+ placeholder: field.placeholder,
2254
+ disabled
2255
+ });
2256
+ case "field-multi-select": return /* @__PURE__ */ jsx(MultiValueFieldEditor, {
2257
+ value,
2258
+ onChange,
2259
+ disabled,
2260
+ emptyText: "No fields added yet",
2261
+ addButtonText: "Add field",
2262
+ typeBadge: field.pgType
2263
+ });
2264
+ case "membership-type-select": return /* @__PURE__ */ jsxs(Select, {
2265
+ value: value !== null && value !== void 0 ? String(value) : "",
2266
+ onValueChange: (v) => onChange(parseInt(v, 10)),
2267
+ disabled,
2268
+ children: [/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {
2269
+ placeholder: "Select scope",
2270
+ children: value !== null && value !== void 0 ? MEMBERSHIP_LABEL_MAP[String(value)] ?? String(value) : void 0
2271
+ }) }), /* @__PURE__ */ jsx(SelectContent, { children: MEMBERSHIP_TYPE_OPTIONS.map((opt) => /* @__PURE__ */ jsx(SelectRichItem, {
2272
+ value: opt.value,
2273
+ label: opt.label,
2274
+ description: opt.description
2275
+ }, opt.value)) })]
2276
+ });
2277
+ case "permission-select": return /* @__PURE__ */ jsx(PermissionSelectField, {
2278
+ field,
2279
+ value: value ?? void 0,
2280
+ onChange,
2281
+ disabled,
2282
+ formData
2283
+ });
2284
+ case "boolean": return null;
2285
+ case "number": return /* @__PURE__ */ jsx(Input, {
2286
+ type: "number",
2287
+ value: value !== null && value !== void 0 ? String(value) : "",
2288
+ onChange: (e) => onChange(e.target.value ? parseInt(e.target.value, 10) : null),
2289
+ placeholder: field.placeholder,
2290
+ disabled
2291
+ });
2292
+ default:
2293
+ if (field.options) {
2294
+ const selectedLabel = field.options.find((o) => o.value === value)?.label;
2295
+ return /* @__PURE__ */ jsxs(Select, {
2296
+ value: value ?? "",
2297
+ onValueChange: onChange,
2298
+ disabled,
2299
+ children: [/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {
2300
+ placeholder: field.placeholder ?? "Select...",
2301
+ children: selectedLabel
2302
+ }) }), /* @__PURE__ */ jsx(SelectContent, { children: field.options.map((opt) => /* @__PURE__ */ jsx(SelectRichItem, {
2303
+ value: opt.value,
2304
+ label: opt.label,
2305
+ description: opt.description
2306
+ }, opt.value)) })]
2307
+ });
2308
+ }
2309
+ return /* @__PURE__ */ jsx(Input, {
2310
+ type: "text",
2311
+ value: value ?? "",
2312
+ onChange: (e) => onChange(e.target.value),
2313
+ placeholder: field.placeholder,
2314
+ disabled
2315
+ });
2316
+ }
2317
+ };
2318
+ if (field.type === "boolean") return /* @__PURE__ */ jsxs("div", {
2319
+ className: "flex items-center justify-between rounded-lg border px-4 py-3 pt-2.5",
2320
+ children: [/* @__PURE__ */ jsxs("div", {
2321
+ className: "space-y-0.5",
2322
+ children: [/* @__PURE__ */ jsxs(Label, {
2323
+ className: "inline-flex items-center text-sm font-medium",
2324
+ children: [field.label, !field.required && /* @__PURE__ */ jsx("span", {
2325
+ className: "text-muted-foreground ml-1 text-xs font-normal",
2326
+ children: "(optional)"
2327
+ })]
2328
+ }), field.description && /* @__PURE__ */ jsx("p", {
2329
+ className: "text-muted-foreground text-xs",
2330
+ children: field.description
2331
+ })]
2332
+ }), /* @__PURE__ */ jsx(Switch, {
2333
+ checked: value === true || value === "true",
2334
+ onCheckedChange: (v) => onChange(v),
2335
+ disabled
2336
+ })]
2337
+ });
2338
+ return /* @__PURE__ */ jsxs("div", {
2339
+ className: "space-y-1.5",
2340
+ children: [
2341
+ /* @__PURE__ */ jsxs(Label, {
2342
+ className: "inline-flex items-center",
2343
+ children: [field.label, !field.required && /* @__PURE__ */ jsx("span", {
2344
+ className: "text-muted-foreground ml-1 text-xs font-normal",
2345
+ children: "(optional)"
2346
+ })]
2347
+ }),
2348
+ field.description && /* @__PURE__ */ jsx("p", {
2349
+ className: "text-muted-foreground text-xs mb-2",
2350
+ children: field.description
2351
+ }),
2352
+ renderField()
2353
+ ]
2354
+ });
2355
+ }
2356
+
2357
+ //#endregion
2358
+ //#region src/schema/schema-builder-policies/components/policies/policy-config-form/access-control-group.tsx
2359
+ function getAccessSummary(fields, values) {
2360
+ const enabled = fields.filter((f) => values[f.key] === true || values[f.key] === "true");
2361
+ if (enabled.length === 0) return "Members";
2362
+ const labels = enabled.map((f) => f.label);
2363
+ if (labels.length === 1) return `Members who are ${labels[0]}`;
2364
+ return `Members who are ${labels.slice(0, -1).join(", ")} or ${labels[labels.length - 1]}`;
2365
+ }
2366
+ /**
2367
+ * Grouped card for is_admin / is_owner boolean fields.
2368
+ * Renders a "Who can access this?" card with checkboxes, switches, and a dynamic summary.
2369
+ */
2370
+ function AccessControlGroup({ fields, values, onChange, disabled }) {
2371
+ const summary = getAccessSummary(fields, values);
2372
+ return /* @__PURE__ */ jsxs("div", {
2373
+ "data-chat-component": "access-control-group",
2374
+ className: "rounded-lg border",
2375
+ children: [
2376
+ /* @__PURE__ */ jsxs("div", {
2377
+ className: "px-4 pt-4 pb-3",
2378
+ children: [/* @__PURE__ */ jsx("h4", {
2379
+ className: "text-balance text-sm font-semibold",
2380
+ children: "Who can access this?"
2381
+ }), /* @__PURE__ */ jsx("p", {
2382
+ className: "text-muted-foreground text-xs",
2383
+ children: "Limit access to certain members. Choose which types of members can access."
2384
+ })]
2385
+ }),
2386
+ fields.map((field) => {
2387
+ const checked = values[field.key] === true || values[field.key] === "true";
2388
+ return /* @__PURE__ */ jsxs("div", {
2389
+ className: "flex items-center justify-between border-t px-4 py-3",
2390
+ children: [/* @__PURE__ */ jsxs("div", {
2391
+ className: "min-w-0 flex-1 space-y-0.5",
2392
+ children: [/* @__PURE__ */ jsx("p", {
2393
+ className: "text-sm font-medium leading-none",
2394
+ children: field.label
2395
+ }), /* @__PURE__ */ jsx("p", {
2396
+ className: "text-muted-foreground text-xs",
2397
+ children: field.description
2398
+ })]
2399
+ }), /* @__PURE__ */ jsx(Switch, {
2400
+ checked,
2401
+ onCheckedChange: (v) => onChange(field.key, v),
2402
+ disabled
2403
+ })]
2404
+ }, field.key);
2405
+ }),
2406
+ /* @__PURE__ */ jsx("div", {
2407
+ className: "border-t px-4 py-3",
2408
+ children: /* @__PURE__ */ jsxs("p", {
2409
+ className: "text-xs",
2410
+ children: [
2411
+ /* @__PURE__ */ jsx("span", {
2412
+ className: "font-semibold",
2413
+ children: "Access:"
2414
+ }),
2415
+ " ",
2416
+ summary
2417
+ ]
2418
+ })
2419
+ })
2420
+ ]
2421
+ });
2422
+ }
2423
+
2424
+ //#endregion
2425
+ //#region src/schema/schema-builder-policies/components/policies/policy-config-form/policy-config-form.tsx
2426
+ const ACCESS_CONTROL_KEYS = /* @__PURE__ */ new Set(["is_admin", "is_owner"]);
2427
+ /**
2428
+ * Dynamic form for configuring a policy type.
2429
+ *
2430
+ * Renders fields based on the policy type's field overrides.
2431
+ * All fields are shown inline (no advanced section).
2432
+ */
2433
+ function PolicyConfigForm({ policyType, value, onChange, disabled, hideAutoGeneratedInfo }) {
2434
+ const { mainFields: allMainFields, advancedFields: allAdvancedFields } = useFormSchema(policyType);
2435
+ const { currentDatabase } = useSchemaBuilderSelectors();
2436
+ const databaseId = currentDatabase?.databaseId ?? "";
2437
+ const { data: tables = [] } = useDatabasePolicies(databaseId, { enabled: Boolean(databaseId) });
2438
+ const allFields = useMemo(() => [...allMainFields, ...allAdvancedFields], [allMainFields, allAdvancedFields]);
2439
+ const handleFieldChange = (key, fieldValue) => {
2440
+ const updates = { [key]: fieldValue };
2441
+ for (const f of allFields) if (f.dependsOn === key) updates[f.key] = f.type === "field-multi-select" ? [] : "";
2442
+ onChange({
2443
+ ...value,
2444
+ ...updates
2445
+ });
2446
+ };
2447
+ const fieldMappings = useMemo(() => getGeneratedFieldMappings(policyType), [policyType]);
2448
+ const inlineEditedKeys = useMemo(() => {
2449
+ if (!fieldMappings) return /* @__PURE__ */ new Set();
2450
+ return new Set(Object.values(fieldMappings).map((m) => m.policyKey));
2451
+ }, [fieldMappings]);
2452
+ const filteredFields = useMemo(() => {
2453
+ if (hideAutoGeneratedInfo) return allFields;
2454
+ return allFields.filter((field) => !inlineEditedKeys.has(field.key));
2455
+ }, [
2456
+ allFields,
2457
+ inlineEditedKeys,
2458
+ hideAutoGeneratedInfo
2459
+ ]);
2460
+ const accessControlFields = useMemo(() => filteredFields.filter((f) => ACCESS_CONTROL_KEYS.has(f.key)), [filteredFields]);
2461
+ const regularFields = useMemo(() => filteredFields.filter((f) => !ACCESS_CONTROL_KEYS.has(f.key)), [filteredFields]);
2462
+ const hasNoConfig = filteredFields.length === 0 && policyType.generatedFields.length === 0 && inlineEditedKeys.size === 0;
2463
+ return /* @__PURE__ */ jsxs("div", {
2464
+ "data-chat-component": "policy-config-form",
2465
+ "data-chat-policy-type": policyType.name,
2466
+ className: "space-y-4",
2467
+ children: [
2468
+ !hideAutoGeneratedInfo && /* @__PURE__ */ jsx(AutoGeneratedFieldsInfo, {
2469
+ fields: policyType.generatedFields,
2470
+ value,
2471
+ onChange: handleFieldChange,
2472
+ fieldMappings,
2473
+ disabled
2474
+ }),
2475
+ regularFields.length > 0 && /* @__PURE__ */ jsx("div", {
2476
+ className: "space-y-4",
2477
+ children: regularFields.map((field) => /* @__PURE__ */ jsx(DynamicFormField, {
2478
+ field,
2479
+ value: value[field.key],
2480
+ onChange: (v) => handleFieldChange(field.key, v),
2481
+ disabled,
2482
+ tables,
2483
+ formData: value
2484
+ }, field.key))
2485
+ }),
2486
+ accessControlFields.length > 0 && /* @__PURE__ */ jsx(AccessControlGroup, {
2487
+ fields: accessControlFields,
2488
+ values: value,
2489
+ onChange: handleFieldChange,
2490
+ disabled
2491
+ }),
2492
+ hasNoConfig && /* @__PURE__ */ jsx("p", {
2493
+ className: "text-muted-foreground text-sm italic",
2494
+ children: "This policy type requires no configuration."
2495
+ })
2496
+ ]
2497
+ });
2498
+ }
2499
+
2500
+ //#endregion
2501
+ export { injectSchemaFields as _, useCreateTableWithPolicies as a, useBatchCreateTableGrants as b, buildGrants as c, OPERATION_STYLES as d, PRIVILEGE_TO_OPERATION as f, getFieldsRequiringColumns as g, getDataNodeForPolicy as h, hasRequiredFieldsMissing as i, buildPolicyEntry as l, buildNodeData as m, usePermissions as n, usePolicyType as o, POLICY_TYPE_UI_CONFIG as p, getDefaultFormValues as r, usePolicyTypes as s, PolicyConfigForm as t, CRUD_OPERATIONS as u, injectSchemaFieldsIntoCompositeTree as v, useCreateTableGrant as x, sanitizePolicyData as y };
2502
+ //# sourceMappingURL=policy-config-form-EEcQ9ywL.js.map