@ghentcdh/crouton-api 0.0.1-alpha.2 → 0.0.1-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
9
  var __export = (target, all) => {
@@ -16,6 +18,14 @@ var __copyProps = (to, from, except, desc2) => {
16
18
  }
17
19
  return to;
18
20
  };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
19
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
30
 
21
31
  // src/index.ts
@@ -27,6 +37,8 @@ __export(index_exports, {
27
37
  ResourceConfigLoader: () => ResourceConfigLoader2,
28
38
  ResourceConfigRegistry: () => ResourceConfigRegistry,
29
39
  isOperationEnabled: () => isOperationEnabled,
40
+ isRowProcedureAction: () => isRowProcedureAction,
41
+ isTableProcedureAction: () => isTableProcedureAction,
30
42
  loadDataSourcesFromDir: () => loadDataSourcesFromDir,
31
43
  loadResourceConfigsFromDir: () => loadResourceConfigsFromDir,
32
44
  resolveDefinition: () => resolveDefinition,
@@ -36,20 +48,36 @@ __export(index_exports, {
36
48
  module.exports = __toCommonJS(index_exports);
37
49
 
38
50
  // src/lib/crouton-api.module.ts
39
- var import_common13 = require("@nestjs/common");
51
+ var import_common12 = require("@nestjs/common");
40
52
  var import_core = require("@nestjs/core");
41
53
 
42
- // src/lib/crud/app-layout.controller.ts
43
- var import_common2 = require("@nestjs/common");
44
- var import_swagger = require("@nestjs/swagger");
54
+ // src/lib/crud/app-layout/app-layout.types.ts
55
+ var import_zod = require("zod");
56
+ var SidebarLeafSchema = import_zod.z.object({
57
+ kind: import_zod.z.literal("item").default("item"),
58
+ id: import_zod.z.string(),
59
+ label: import_zod.z.string(),
60
+ position: import_zod.z.number().optional()
61
+ });
62
+ var SidebarGroupSchema = import_zod.z.object({
63
+ kind: import_zod.z.literal("group").default("group"),
64
+ id: import_zod.z.string(),
65
+ label: import_zod.z.string(),
66
+ position: import_zod.z.number().optional(),
67
+ children: import_zod.z.array(SidebarLeafSchema).default([])
68
+ });
69
+ var SidebarNodeSchema = import_zod.z.discriminatedUnion("kind", [
70
+ SidebarLeafSchema,
71
+ SidebarGroupSchema
72
+ ]);
45
73
 
46
74
  // ../crouton-core/src/lib/request.model.ts
47
- var import_zod2 = require("zod");
75
+ var import_zod3 = require("zod");
48
76
 
49
77
  // ../crouton-core/src/lib/zod.types.ts
50
- var import_zod = require("zod");
51
- var PositiveRequestNumber = /* @__PURE__ */ __name(() => import_zod.z.coerce.number().int().positive().nonnegative(), "PositiveRequestNumber");
52
- var StringOrArray = /* @__PURE__ */ __name(() => import_zod.z.string().or(import_zod.z.array(import_zod.z.string())).transform((val) => {
78
+ var import_zod2 = require("zod");
79
+ var PositiveRequestNumber = /* @__PURE__ */ __name(() => import_zod2.z.coerce.number().int().positive().nonnegative(), "PositiveRequestNumber");
80
+ var StringOrArray = /* @__PURE__ */ __name(() => import_zod2.z.string().or(import_zod2.z.array(import_zod2.z.string())).transform((val) => {
53
81
  if (Array.isArray(val)) return val;
54
82
  return [
55
83
  val
@@ -57,14 +85,14 @@ var StringOrArray = /* @__PURE__ */ __name(() => import_zod.z.string().or(import
57
85
  }), "StringOrArray");
58
86
 
59
87
  // ../crouton-core/src/lib/request.model.ts
60
- var SortDirEnum = import_zod2.z.enum([
88
+ var SortDirEnum = import_zod3.z.enum([
61
89
  "asc",
62
90
  "desc"
63
91
  ]);
64
- var RequestSchema = import_zod2.z.object({
92
+ var RequestSchema = import_zod3.z.object({
65
93
  page: PositiveRequestNumber().optional().default(1),
66
94
  pageSize: PositiveRequestNumber().optional().default(20),
67
- sort: import_zod2.z.string().optional().default("id"),
95
+ sort: import_zod3.z.string().optional().default("id"),
68
96
  sortDir: SortDirEnum.optional().default("asc"),
69
97
  // Filter is of the format key:value:operator (e.g. name:john:eq) operator is optional
70
98
  filter: StringOrArray().optional().default([])
@@ -115,18 +143,18 @@ var buildSortKey = /* @__PURE__ */ __name((keys, sortDir) => {
115
143
  }, "buildSortKey");
116
144
 
117
145
  // ../crouton-core/src/lib/response.model.ts
118
- var import_zod4 = require("zod");
146
+ var import_zod5 = require("zod");
119
147
  var ResponseRequestSchema = RequestSchema.extend({
120
148
  count: PositiveRequestNumber(),
121
149
  totalPages: PositiveRequestNumber()
122
150
  });
123
- var ResponseSchema = import_zod4.z.object({
124
- data: import_zod4.z.array(import_zod4.z.unknown()),
151
+ var ResponseSchema = import_zod5.z.object({
152
+ data: import_zod5.z.array(import_zod5.z.unknown()),
125
153
  request: ResponseRequestSchema
126
154
  });
127
155
 
128
156
  // ../crouton-core/src/lib/create-schema.ts
129
- var import_zod6 = require("zod");
157
+ var import_zod7 = require("zod");
130
158
 
131
159
  // ../crouton-core/src/lib/layout/base.builder.ts
132
160
  var Builder = class {
@@ -384,23 +412,6 @@ var LayoutBuilder = class _LayoutBuilder extends BuilderWithElements {
384
412
  }
385
413
  };
386
414
 
387
- // ../crouton-core/src/lib/json-config.types.ts
388
- var labelFromId = /* @__PURE__ */ __name((id) => {
389
- const words = id.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
390
- return words.charAt(0).toUpperCase() + words.slice(1).toLowerCase();
391
- }, "labelFromId");
392
- var normalizeColumns = /* @__PURE__ */ __name((columns) => {
393
- if (!columns) return void 0;
394
- const raw = Array.isArray(columns) ? columns : Object.entries(columns).map(([id, col]) => ({
395
- id,
396
- ...col
397
- }));
398
- return raw.map((col) => ({
399
- ...col,
400
- label: col.label ?? labelFromId(col.id)
401
- }));
402
- }, "normalizeColumns");
403
-
404
415
  // ../crouton-core/src/lib/value-label.ts
405
416
  var wrapOne = /* @__PURE__ */ __name((value, values) => {
406
417
  const match = values.find((o) => o.value === value);
@@ -494,6 +505,515 @@ var TableBuilder = class _TableBuilder {
494
505
  }
495
506
  };
496
507
 
508
+ // ../crouton-core/src/lib/data-source/DataSourceSchema.ts
509
+ var import_zod8 = __toESM(require("zod"), 1);
510
+ var DataSourceShape = import_zod8.default.object({
511
+ /** Datasource name (folder + `name` in data-source.json). */
512
+ name: import_zod8.default.string(),
513
+ /** Env var holding the connection URL. */
514
+ urlEnv: import_zod8.default.string(),
515
+ /** Import path for this datasource's generated Zod types (for resource `schema.ts`). */
516
+ generatedTypesImport: import_zod8.default.string().optional(),
517
+ /** Datasource type tag. Default `postgres`. */
518
+ type: import_zod8.default.string().default("postgres"),
519
+ /** Mark this as the default datasource. Default `false`. */
520
+ default: import_zod8.default.boolean().default(false),
521
+ /** Prisma schema path, relative to project root. Default `prisma/<name>/schema.prisma`. */
522
+ prismaSchema: import_zod8.default.string().optional(),
523
+ /** Prisma config path, relative to project root. Default `prisma/<name>/prisma.config.ts`. */
524
+ prismaConfig: import_zod8.default.string().optional(),
525
+ /** zod-prisma-types output dir, relative to project root. Default `generated/<name>/src`. */
526
+ zodOutput: import_zod8.default.string().optional(),
527
+ /** Prisma client output dir, relative to project root. Default `generated/<name>/client`. */
528
+ clientOutput: import_zod8.default.string().optional()
529
+ });
530
+ var transformDataSource = /* @__PURE__ */ __name((data) => {
531
+ const name = data.name ?? "name";
532
+ return {
533
+ ...data,
534
+ generatedTypesImport: data.generatedTypesImport ?? `@your-scope/generated/${name}`,
535
+ prismaSchema: data.prismaSchema ?? `prisma/${name}/schema.prisma`,
536
+ prismaConfig: data.prismaConfig ?? `prisma/${name}/prisma.config.ts`,
537
+ zodOutput: data.zodOutput ?? `generated/${name}/src`,
538
+ clientOutput: data.clientOutput ?? `generated/${name}/client`
539
+ };
540
+ }, "transformDataSource");
541
+ var DataSourceSchema = DataSourceShape.transform(transformDataSource);
542
+
543
+ // ../crouton-core/src/lib/data-source/Operations.schema.ts
544
+ var import_zod9 = require("zod");
545
+ var BoolOrUpsertSchema = import_zod9.z.union([
546
+ import_zod9.z.boolean(),
547
+ import_zod9.z.object({
548
+ upsertOn: import_zod9.z.union([
549
+ import_zod9.z.string(),
550
+ import_zod9.z.array(import_zod9.z.string())
551
+ ])
552
+ })
553
+ ]);
554
+ var JsonOperationsSchema = import_zod9.z.object({
555
+ findAll: import_zod9.z.boolean().default(true),
556
+ findOne: import_zod9.z.boolean().default(true),
557
+ create: import_zod9.z.boolean().default(true),
558
+ update: import_zod9.z.boolean().default(true),
559
+ upsert: BoolOrUpsertSchema.default(false),
560
+ delete: import_zod9.z.boolean().default(true)
561
+ });
562
+
563
+ // ../crouton-core/src/lib/resource/ResourceJson.schema.ts
564
+ var import_zod16 = require("zod");
565
+
566
+ // ../crouton-core/src/lib/resource/CalculatedColumn.schema.ts
567
+ var import_zod11 = require("zod");
568
+
569
+ // ../crouton-core/src/lib/resource/FieldInput.schema.ts
570
+ var import_zod10 = require("zod");
571
+ var RelationType = import_zod10.z.enum([
572
+ "oneToOne",
573
+ "manyToOne",
574
+ "oneToMany",
575
+ "manyToMany"
576
+ ]);
577
+ var DetailControlSchema = import_zod10.z.object({
578
+ property: import_zod10.z.string(),
579
+ type: import_zod10.z.string().optional(),
580
+ options: import_zod10.z.record(import_zod10.z.string(), import_zod10.z.unknown()).optional(),
581
+ hideLabel: import_zod10.z.boolean().optional(),
582
+ width: import_zod10.z.string().optional()
583
+ });
584
+ var DetailConfigSchema = import_zod10.z.object({
585
+ layout: import_zod10.z.enum([
586
+ "collapse",
587
+ "row"
588
+ ]),
589
+ titleKey: import_zod10.z.string().optional(),
590
+ controls: import_zod10.z.array(DetailControlSchema)
591
+ });
592
+ var RelationFieldInputOptionsSchema = import_zod10.z.object({
593
+ /** Field to sort related records by, e.g. `"title"` or `"author.name"`. */
594
+ sort: import_zod10.z.string().optional(),
595
+ /** Sort direction. Defaults to `"asc"` when omitted. */
596
+ sortDir: import_zod10.z.enum([
597
+ "asc",
598
+ "desc"
599
+ ]).optional(),
600
+ /** CSS flex direction for the relation control button layout. */
601
+ direction: import_zod10.z.string().optional(),
602
+ /** Key used as the display label in the relation control. */
603
+ displayKey: import_zod10.z.string().optional(),
604
+ /** Path to the related resource (resolved to a URI at load time). */
605
+ resource: import_zod10.z.string().optional()
606
+ }).catchall(import_zod10.z.unknown());
607
+ var FieldInputSchema = import_zod10.z.object({
608
+ type: import_zod10.z.string().optional(),
609
+ customRender: import_zod10.z.string().optional(),
610
+ /**
611
+ * Render format hint for the frontend (e.g. `"relation"` for sub-resource
612
+ * relations). When `format` is `"relation"`, `resource` must also be set.
613
+ */
614
+ format: import_zod10.z.string().optional(),
615
+ /**
616
+ * Relative path to the child resource definition, e.g. `"./author.resource"`.
617
+ * Only used when `format` is `"relation"`. Resolved at load time to inject
618
+ * sub-resource URIs into `options`.
619
+ */
620
+ resource: import_zod10.z.string().optional(),
621
+ /**
622
+ * Cardinality of the relation. Used by the frontend to determine the correct
623
+ * renderer and behaviour (e.g. single-select vs multi-select).
624
+ * - `manyToOne` / `oneToOne` — single FK reference (autocomplete / relation control)
625
+ * - `oneToMany` / `manyToMany` — collection (sub-resource table / multi-select)
626
+ */
627
+ relationType: RelationType.optional(),
628
+ /** Override the display order in form views. Lower values come first. */
629
+ position: import_zod10.z.number().optional(),
630
+ options: import_zod10.z.union([
631
+ RelationFieldInputOptionsSchema,
632
+ import_zod10.z.unknown()
633
+ ]).optional(),
634
+ /** Nested array detail layout (renders via `detailFixed`). */
635
+ detail: DetailConfigSchema.optional()
636
+ });
637
+
638
+ // ../crouton-core/src/lib/schema/label.helper.ts
639
+ var labelFromId = /* @__PURE__ */ __name((id) => {
640
+ const words = id.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").trim();
641
+ return words.charAt(0).toUpperCase() + words.slice(1).toLowerCase();
642
+ }, "labelFromId");
643
+ var normalizeLabel = /* @__PURE__ */ __name((obj) => {
644
+ return {
645
+ label: labelFromId(obj.id),
646
+ ...obj
647
+ };
648
+ }, "normalizeLabel");
649
+
650
+ // ../crouton-core/src/lib/resource/CalculatedColumn.schema.ts
651
+ var CalculatedColumnSchema = import_zod11.z.object({
652
+ /** Column identifier used in the response payload and UI schema. */
653
+ id: import_zod11.z.string(),
654
+ /** SQL alias — must match `id`. */
655
+ alias: import_zod11.z.string(),
656
+ /** Human-readable label shown in the table header. */
657
+ label: import_zod11.z.string().optional(),
658
+ sqlExpression: import_zod11.z.string(),
659
+ /** JSON schema / cast type for the computed value. Defaults to `"number"`. `"string"` skips CAST. */
660
+ type: import_zod11.z.enum([
661
+ "number",
662
+ "boolean",
663
+ "string"
664
+ ]).optional(),
665
+ /**
666
+ * Insertion position relative to the other visible columns.
667
+ * Uses the same semantics as `fieldInput.position` on regular columns:
668
+ * `position: N` places this column before the element currently at index N.
669
+ * Can also be set via `fieldInput.position` (takes precedence).
670
+ */
671
+ position: import_zod11.z.number().optional(),
672
+ hiddenInTable: import_zod11.z.boolean().optional(),
673
+ hiddenInView: import_zod11.z.boolean().optional(),
674
+ /**
675
+ * Field input options for rendering in form / view schemas.
676
+ * Supports `colspan`, `format`, and any other options passed to the Control renderer.
677
+ * `position` here takes precedence over the top-level `position`.
678
+ */
679
+ fieldInput: FieldInputSchema.optional()
680
+ }).transform(normalizeLabel);
681
+
682
+ // ../crouton-core/src/lib/resource/Column.ts
683
+ var import_zod12 = require("zod");
684
+ var WhenConditionSchema = import_zod12.z.object({
685
+ field: import_zod12.z.string(),
686
+ eq: import_zod12.z.unknown().optional(),
687
+ neq: import_zod12.z.unknown().optional(),
688
+ exists: import_zod12.z.boolean().optional(),
689
+ notExists: import_zod12.z.boolean().optional()
690
+ });
691
+ var JsonColumnSchema = import_zod12.z.object({
692
+ id: import_zod12.z.string(),
693
+ column: import_zod12.z.string().optional(),
694
+ label: import_zod12.z.string().optional(),
695
+ hiddenInTable: import_zod12.z.boolean().default(false),
696
+ hiddenInForm: import_zod12.z.boolean().default(false),
697
+ hiddenInView: import_zod12.z.boolean().default(false),
698
+ sortable: import_zod12.z.boolean().default(false),
699
+ defaultSort: import_zod12.z.boolean().default(false),
700
+ searchable: import_zod12.z.boolean().default(false),
701
+ filterable: import_zod12.z.boolean().default(false),
702
+ createable: import_zod12.z.boolean().default(true),
703
+ updateable: import_zod12.z.boolean().default(true),
704
+ hideLabel: import_zod12.z.boolean().default(false),
705
+ showWhen: WhenConditionSchema.optional(),
706
+ hideWhen: WhenConditionSchema.optional(),
707
+ disabledWhen: WhenConditionSchema.optional(),
708
+ displayKey: import_zod12.z.string().optional(),
709
+ sortId: import_zod12.z.string().optional(),
710
+ /**
711
+ * Name of a shared enum in the project enum registry (`crouton.enums.json`).
712
+ * At load time the loader injects that enum's `{ value, label }[]` into
713
+ * `fieldInput.options.values`, so columns don't duplicate the option list.
714
+ */
715
+ enum: import_zod12.z.string().optional(),
716
+ idField: import_zod12.z.boolean().default(false),
717
+ showInLookup: import_zod12.z.boolean().default(false),
718
+ columnType: import_zod12.z.string().default("string"),
719
+ fieldInput: FieldInputSchema.optional(),
720
+ /**
721
+ * Path to another `resource.json` whose columns are expanded as nested sub-columns
722
+ * under this column's object key.
723
+ *
724
+ * Example: `"extend": "../internalAuthor/resource.json"` on a column `author`
725
+ * auto-generates virtual sub-columns like `author_name` (column: "author", displayKey: "name").
726
+ *
727
+ * Visibility (`hiddenInTable/Form/View`) on this column is inherited by all sub-columns as a
728
+ * default; the referenced resource's own column visibility further restricts it.
729
+ */
730
+ extend: import_zod12.z.string().optional(),
731
+ /**
732
+ * Per-sub-column overrides when using `extend`.
733
+ * Key: the virtual column id (`"{extendId}_{refColId}"`) or just the referenced column id.
734
+ * Value: any `JsonColumn` fields to merge over the generated virtual column.
735
+ */
736
+ columns: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown())).optional()
737
+ });
738
+
739
+ // ../crouton-core/src/lib/resource/Sidebar.schema.ts
740
+ var import_zod13 = __toESM(require("zod"), 1);
741
+ var SidebarGroupSchema2 = import_zod13.default.object({
742
+ /** Human-readable heading shown in the sidebar. Defaults to a title-cased version of the slug. */
743
+ label: import_zod13.default.string().optional(),
744
+ /** Controls the order of this group among top-level sidebar items. */
745
+ position: import_zod13.default.string().optional()
746
+ });
747
+ var SidebarSchema = import_zod13.default.object({
748
+ hide: import_zod13.default.boolean().default(false),
749
+ position: import_zod13.default.number().optional(),
750
+ label: import_zod13.default.string().optional(),
751
+ /**
752
+ * Slug of the group this resource belongs to.
753
+ * Must match a key in `sidebarGroups` in `crouton.json`.
754
+ * Resources with the same `group` are nested under a shared collapsible section.
755
+ */
756
+ group: import_zod13.default.string().optional()
757
+ });
758
+
759
+ // ../crouton-core/src/lib/resource/TableAction.schema.ts
760
+ var import_zod14 = require("zod");
761
+ var ActionConditionSchema = import_zod14.z.object({
762
+ /** Row field to evaluate. */
763
+ field: import_zod14.z.string(),
764
+ /**
765
+ * Comparison operator. Defaults to `"eq"`.
766
+ * - `eq` / `neq` — strict equality
767
+ * - `gt` / `gte` / `lt` / `lte` — numeric or date comparison
768
+ * - `exists` — field is not null / undefined / empty string
769
+ * - `notExists` — field is null / undefined / empty string
770
+ */
771
+ op: import_zod14.z.enum([
772
+ "eq",
773
+ "neq",
774
+ "gt",
775
+ "gte",
776
+ "lt",
777
+ "lte",
778
+ "exists",
779
+ "notExists"
780
+ ]).default("eq"),
781
+ /** Comparison value. Not required for `exists` / `notExists`. */
782
+ value: import_zod14.z.unknown().optional()
783
+ });
784
+ var ActionSchema = import_zod14.z.object({
785
+ type: import_zod14.z.string(),
786
+ /** Unique identifier for the action. */
787
+ id: import_zod14.z.string(),
788
+ /** Human-readable button label. */
789
+ label: import_zod14.z.string(),
790
+ /** MDI icon name, e.g. `"mdi:open-in-new"`. */
791
+ icon: import_zod14.z.string().optional(),
792
+ /** Tooltip text. Falls back to `label` when omitted. */
793
+ tooltip: import_zod14.z.string().optional(),
794
+ condition: ActionConditionSchema.optional()
795
+ });
796
+ var JsonProcedureActionSchema = ActionSchema.extend({
797
+ type: import_zod14.z.literal("procedure").default("procedure"),
798
+ /**
799
+ * Filename (without extension) inside the resource's `actions/` directory
800
+ * that exports the table-action procedure, e.g. `"syncZotero"`.
801
+ */
802
+ procedure: import_zod14.z.string(),
803
+ /** HTTP method for the frontend. Defaults to `"post"`. */
804
+ method: import_zod14.z.string().optional().default("post"),
805
+ /** Static query / body params passed to the endpoint. */
806
+ data: import_zod14.z.record(import_zod14.z.string(), import_zod14.z.unknown()).optional()
807
+ });
808
+ var JsonLinkActionSchema = ActionSchema.extend({
809
+ /** Optional condition evaluated per row. Button is hidden when the condition is false. */
810
+ type: import_zod14.z.literal("link").default("link"),
811
+ /** URL to open. May contain `{env.VAR}` placeholders. */
812
+ href: import_zod14.z.string()
813
+ });
814
+ var transformAction = /* @__PURE__ */ __name((action) => {
815
+ const label = action.label;
816
+ return {
817
+ tooltip: label,
818
+ ...action
819
+ };
820
+ }, "transformAction");
821
+ var JsonActionSchema = import_zod14.z.union([
822
+ JsonProcedureActionSchema,
823
+ JsonLinkActionSchema
824
+ ]).transform(transformAction);
825
+
826
+ // ../crouton-core/src/lib/resource/include.schema.ts
827
+ var import_zod15 = require("zod");
828
+ var JsonIncludeEntrySchema = import_zod15.z.lazy(() => import_zod15.z.union([
829
+ import_zod15.z.string(),
830
+ import_zod15.z.object({
831
+ relation: import_zod15.z.string(),
832
+ include: import_zod15.z.array(JsonIncludeEntrySchema).optional(),
833
+ /** Prisma-format orderBy clause applied to the included records. */
834
+ orderBy: import_zod15.z.record(import_zod15.z.string(), import_zod15.z.unknown()).optional()
835
+ })
836
+ ]));
837
+
838
+ // ../crouton-core/src/lib/resource/ResourceJson.schema.ts
839
+ var JsonColumnsMapSchema = import_zod16.z.record(import_zod16.z.string(), JsonColumnSchema.omit({
840
+ id: true
841
+ }).catchall(import_zod16.z.unknown()));
842
+ var ColumnsSchema = JsonColumnsMapSchema;
843
+ var JsonDisplaySchema = import_zod16.z.object({
844
+ mode: import_zod16.z.enum([
845
+ "page",
846
+ "modal"
847
+ ]).default("modal"),
848
+ customComponent: import_zod16.z.string().nullable().optional().default(null)
849
+ });
850
+ var normalizeColumns = /* @__PURE__ */ __name((columns) => {
851
+ if (!columns) return void 0;
852
+ const raw = Array.isArray(columns) ? columns : Object.entries(columns).map(([id, col]) => ({
853
+ id,
854
+ ...col
855
+ }));
856
+ return raw.map((col) => ({
857
+ ...col,
858
+ label: col.label ?? labelFromId(col.id)
859
+ }));
860
+ }, "normalizeColumns");
861
+ var ResourceJsonShape = import_zod16.z.object({
862
+ name: import_zod16.z.string(),
863
+ route: import_zod16.z.string(),
864
+ model: import_zod16.z.string(),
865
+ tag: import_zod16.z.string(),
866
+ title: import_zod16.z.string().optional(),
867
+ table: import_zod16.z.string().optional(),
868
+ database: import_zod16.z.string().optional(),
869
+ sidebar: SidebarSchema.default(SidebarSchema.parse({})),
870
+ display: JsonDisplaySchema.default(JsonDisplaySchema.parse({})),
871
+ operations: JsonOperationsSchema,
872
+ columns: ColumnsSchema.default(ColumnsSchema.parse({})),
873
+ calculatedColumns: import_zod16.z.array(CalculatedColumnSchema).default([]),
874
+ actions: import_zod16.z.array(JsonActionSchema).default([]),
875
+ /** Global table-level actions (no record id). Shown as toolbar buttons. */
876
+ tableActions: import_zod16.z.array(JsonActionSchema).default([]),
877
+ /** Modal width when opening a form for this resource. */
878
+ modalSize: import_zod16.z.enum([
879
+ "xs",
880
+ "sm",
881
+ "lg",
882
+ "xl"
883
+ ]).default("sm"),
884
+ /**
885
+ * Relations to include when querying this resource.
886
+ * Each entry is either a plain relation name (`"author"` → `include: { author: true }`)
887
+ * or an object for nested includes:
888
+ * `{ "relation": "text_author", "include": ["author"] }` →
889
+ * `include: { text_author: { include: { author: true } } }`
890
+ */
891
+ include: import_zod16.z.array(JsonIncludeEntrySchema).default([])
892
+ });
893
+ var ResourceJsonSchema = ResourceJsonShape.transform((obj) => {
894
+ const title = obj.title ?? labelFromId(obj.name);
895
+ return {
896
+ title,
897
+ ...obj,
898
+ columns: normalizeColumns(obj.columns)
899
+ };
900
+ });
901
+
902
+ // ../crouton-core/src/lib/config/CroutonConfig.schema.ts
903
+ var import_zod17 = require("zod");
904
+ var RulesetSchema = import_zod17.z.object({
905
+ hideIdInTable: import_zod17.z.boolean().default(true),
906
+ hideIdInForm: import_zod17.z.boolean().default(true),
907
+ hideIdInView: import_zod17.z.boolean().default(true),
908
+ hideTimestamps: import_zod17.z.boolean().default(true),
909
+ hideForeignKeys: import_zod17.z.boolean().default(true),
910
+ includeRelations: import_zod17.z.boolean().default(false),
911
+ hideRelationsInTable: import_zod17.z.boolean().default(true),
912
+ showRelationsInForm: import_zod17.z.boolean().default(true),
913
+ enumValueLabel: import_zod17.z.boolean().default(true),
914
+ sharedEnums: import_zod17.z.boolean().default(true),
915
+ defaultOperations: JsonOperationsSchema.default(JsonOperationsSchema.parse({}))
916
+ });
917
+ var CroutonConfigSchema = import_zod17.z.object({
918
+ /**
919
+ * Application title served to the frontend via `GET /_app/layout`.
920
+ * Displayed in the admin sidebar header.
921
+ */
922
+ title: import_zod17.z.string(),
923
+ /** Where resource directories live, relative to the project root. */
924
+ resourcesDir: import_zod17.z.string(),
925
+ /** Where datasource folders live (each with a `data-source.json`). */
926
+ dataSourcesDir: import_zod17.z.string(),
927
+ /**
928
+ * Template for a model's Zod export name. `{Model}` → Prisma model name.
929
+ * Defaults to `{Model}WithRelationsSchema` (the relations-aware schema
930
+ * emitted by zod-prisma-types when `createRelationValuesTypes` is on).
931
+ */
932
+ schemaExportName: import_zod17.z.string().default("{Model}WithRelationsSchema"),
933
+ /** Path to the shared enum registry, relative to project root. Default `crouton.enums.json`. */
934
+ enumsFile: import_zod17.z.string().default("croutons.enums.json"),
935
+ /** Optional overrides of the default visibility ruleset. */
936
+ rules: RulesetSchema.default(RulesetSchema.parse({})),
937
+ /**
938
+ * Sidebar group definitions, keyed by group slug (e.g. `"metadata"`).
939
+ * Resources reference a group via `sidebar.group` in their `resource.json`.
940
+ */
941
+ sidebarGroups: import_zod17.z.record(import_zod17.z.string(), SidebarGroupSchema2).default({}),
942
+ /**
943
+ * Whether form fields are saved automatically as the user edits them.
944
+ * @default true
945
+ */
946
+ autoSave: import_zod17.z.boolean().default(true)
947
+ });
948
+
949
+ // ../crouton-core/src/lib/config/readConfig.ts
950
+ var CONFIG_FILES = [
951
+ "crouton.json",
952
+ "crouton.mjs",
953
+ "crouton.js"
954
+ ];
955
+
956
+ // src/lib/crud/app-layout/app-layout.builder.ts
957
+ var byPosition = /* @__PURE__ */ __name((a, b) => {
958
+ if (a.position != null && b.position != null) return a.position - b.position;
959
+ if (a.position != null) return -1;
960
+ if (b.position != null) return 1;
961
+ return a.label.localeCompare(b.label);
962
+ }, "byPosition");
963
+ var buildLayoutPayload = /* @__PURE__ */ __name((configs, sidebarGroups = {}, title, autoSave = true) => {
964
+ const visible = configs.filter((c) => c.sidebar?.hide !== true && c.views?.["table"]);
965
+ const topLevel = [];
966
+ const groupMap = new Map(Object.entries(sidebarGroups).map(([slug, cfg]) => [
967
+ slug,
968
+ {
969
+ label: cfg.label ?? labelFromId(slug),
970
+ position: cfg.position,
971
+ children: []
972
+ }
973
+ ]));
974
+ for (const c of visible) {
975
+ const leaf = SidebarLeafSchema.parse({
976
+ id: c.name,
977
+ label: c.sidebar?.label ?? c.title ?? c.tag,
978
+ position: c.sidebar?.position
979
+ });
980
+ const groupSlug = c.sidebar?.group;
981
+ if (groupSlug) {
982
+ if (!groupMap.has(groupSlug)) {
983
+ groupMap.set(groupSlug, {
984
+ label: labelFromId(groupSlug),
985
+ children: []
986
+ });
987
+ }
988
+ groupMap.get(groupSlug).children.push(leaf);
989
+ } else {
990
+ topLevel.push(leaf);
991
+ }
992
+ }
993
+ const groups = [
994
+ ...groupMap.entries()
995
+ ].filter(([, g]) => g.children.length > 0).map(([id, g]) => ({
996
+ kind: "group",
997
+ id,
998
+ label: g.label,
999
+ position: g.position,
1000
+ children: g.children.sort(byPosition)
1001
+ }));
1002
+ const sidebar = [
1003
+ ...topLevel,
1004
+ ...groups
1005
+ ].sort(byPosition);
1006
+ return {
1007
+ sidebar,
1008
+ title,
1009
+ autoSave
1010
+ };
1011
+ }, "buildLayoutPayload");
1012
+
1013
+ // src/lib/crud/app-layout/app-layout.controller.ts
1014
+ var import_common2 = require("@nestjs/common");
1015
+ var import_swagger = require("@nestjs/swagger");
1016
+
497
1017
  // src/lib/crud/dev-mode.ts
498
1018
  var IS_DEV = process.env["NODE_ENV"] !== "production";
499
1019
 
@@ -542,7 +1062,7 @@ ResourceConfigRegistry = _ts_decorate([
542
1062
  ])
543
1063
  ], ResourceConfigRegistry);
544
1064
 
545
- // src/lib/crud/app-layout.controller.ts
1065
+ // src/lib/crud/app-layout/app-layout.controller.ts
546
1066
  function _ts_decorate2(decorators, target, key, desc2) {
547
1067
  var c = arguments.length, r = c < 3 ? target : desc2 === null ? desc2 = Object.getOwnPropertyDescriptor(target, key) : desc2, d;
548
1068
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc2);
@@ -554,62 +1074,6 @@ function _ts_metadata2(k, v) {
554
1074
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
555
1075
  }
556
1076
  __name(_ts_metadata2, "_ts_metadata");
557
- var byPosition = /* @__PURE__ */ __name((a, b) => {
558
- if (a.position != null && b.position != null) return a.position - b.position;
559
- if (a.position != null) return -1;
560
- if (b.position != null) return 1;
561
- return a.label.localeCompare(b.label);
562
- }, "byPosition");
563
- var buildLayoutPayload = /* @__PURE__ */ __name((configs, sidebarGroups = {}, title, autoSave = true) => {
564
- const visible = configs.filter((c) => c.sidebar?.hide !== true && c.views?.["table"]);
565
- const topLevel = [];
566
- const groupMap = new Map(Object.entries(sidebarGroups).map(([slug, cfg]) => [
567
- slug,
568
- {
569
- label: cfg.label ?? labelFromId(slug),
570
- position: cfg.position,
571
- children: []
572
- }
573
- ]));
574
- for (const c of visible) {
575
- const leaf = {
576
- kind: "item",
577
- id: c.name,
578
- label: c.sidebar?.label ?? c.title ?? c.tag,
579
- position: c.sidebar?.position
580
- };
581
- const groupSlug = c.sidebar?.group;
582
- if (groupSlug) {
583
- if (!groupMap.has(groupSlug)) {
584
- groupMap.set(groupSlug, {
585
- label: labelFromId(groupSlug),
586
- children: []
587
- });
588
- }
589
- groupMap.get(groupSlug).children.push(leaf);
590
- } else {
591
- topLevel.push(leaf);
592
- }
593
- }
594
- const groups = [
595
- ...groupMap.entries()
596
- ].filter(([, g]) => g.children.length > 0).map(([id, g]) => ({
597
- kind: "group",
598
- id,
599
- label: g.label,
600
- position: g.position,
601
- children: g.children.sort(byPosition)
602
- }));
603
- const sidebar = [
604
- ...topLevel,
605
- ...groups
606
- ].sort(byPosition);
607
- return {
608
- sidebar,
609
- title,
610
- autoSave
611
- };
612
- }, "buildLayoutPayload");
613
1077
  var createAppLayoutController = /* @__PURE__ */ __name((configs, sidebarGroups = {}, title, autoSave = true) => {
614
1078
  const layoutPayload = buildLayoutPayload(configs, sidebarGroups, title, autoSave);
615
1079
  let AppLayoutController = class AppLayoutController {
@@ -655,6 +1119,45 @@ var createAppLayoutController = /* @__PURE__ */ __name((configs, sidebarGroups =
655
1119
  return AppLayoutController;
656
1120
  }, "createAppLayoutController");
657
1121
 
1122
+ // src/lib/crud/config/read.ts
1123
+ var import_promises = require("fs/promises");
1124
+ var import_node_path = require("path");
1125
+ var fileExists = /* @__PURE__ */ __name(async (p) => {
1126
+ try {
1127
+ await (0, import_promises.access)(p);
1128
+ return true;
1129
+ } catch {
1130
+ return false;
1131
+ }
1132
+ }, "fileExists");
1133
+ var findConfigPath = /* @__PURE__ */ __name(async (cwd) => {
1134
+ let dir = (0, import_node_path.resolve)(cwd);
1135
+ while (true) {
1136
+ for (const name of CONFIG_FILES) {
1137
+ const candidate = (0, import_node_path.join)(dir, name);
1138
+ if (await fileExists(candidate)) return candidate;
1139
+ }
1140
+ const parent = (0, import_node_path.dirname)(dir);
1141
+ if (parent === dir) return void 0;
1142
+ dir = parent;
1143
+ }
1144
+ }, "findConfigPath");
1145
+ var loadConfig = /* @__PURE__ */ __name(async () => {
1146
+ const cwd = (0, import_node_path.resolve)(process.cwd());
1147
+ const path = await findConfigPath(cwd);
1148
+ if (!path) {
1149
+ throw new Error(`No crouton config found (looked for ${CONFIG_FILES.join(", ")} up from ${cwd}).`);
1150
+ }
1151
+ let config;
1152
+ if (path.endsWith(".json")) {
1153
+ config = JSON.parse(await (0, import_promises.readFile)(path, "utf-8"));
1154
+ } else {
1155
+ const mod = await import(path);
1156
+ config = mod.default ?? mod;
1157
+ }
1158
+ return CroutonConfigSchema.parse(config);
1159
+ }, "loadConfig");
1160
+
658
1161
  // src/lib/crud/crouton-validation.filter.ts
659
1162
  var import_common3 = require("@nestjs/common");
660
1163
 
@@ -697,25 +1200,158 @@ CroutonValidationExceptionFilter = _ts_decorate3([
697
1200
 
698
1201
  // src/lib/crud/crud-controller.factory.ts
699
1202
  var import_common11 = require("@nestjs/common");
700
- var import_common12 = require("@nestjs/common");
701
1203
  var import_swagger6 = require("@nestjs/swagger");
702
1204
 
703
- // src/lib/crud/crud.config.ts
704
- var resolveDefinition = /* @__PURE__ */ __name((config) => {
705
- const def2 = config.definition;
706
- return typeof def2 === "function" ? def2() : def2;
707
- }, "resolveDefinition");
708
- var isOperationEnabled = /* @__PURE__ */ __name((def2, op) => def2[op] != null, "isOperationEnabled");
709
- var schemaFor = /* @__PURE__ */ __name((def2, op) => {
710
- const entry = def2[op];
711
- if (!entry || entry === true) return void 0;
712
- return entry.schema;
713
- }, "schemaFor");
714
- var upsertOnFor = /* @__PURE__ */ __name((def2) => def2.upsert?.upsertOn, "upsertOnFor");
715
-
716
- // src/lib/crud/read.repository.ts
717
- var import_common4 = require("@nestjs/common");
718
-
1205
+ // src/lib/crud/action/action.types.ts
1206
+ var import_zod18 = require("zod");
1207
+ var ActionMetadataSchema = import_zod18.z.object({
1208
+ /** URL segment used in the endpoint. */
1209
+ id: import_zod18.z.string(),
1210
+ /** Human-readable label shown as a button. */
1211
+ label: import_zod18.z.string().optional(),
1212
+ /** MDI icon name, e.g. `"mdi:open-in-new"`. */
1213
+ icon: import_zod18.z.string().optional(),
1214
+ /** Tooltip text. Falls back to `label` when omitted. */
1215
+ tooltip: import_zod18.z.string().optional(),
1216
+ /** Per-row condition button is hidden when false. */
1217
+ condition: import_zod18.z.custom().optional()
1218
+ });
1219
+ var ResourceLinkActionSchema = ActionMetadataSchema.extend({
1220
+ type: import_zod18.z.literal("link"),
1221
+ /** URL to open. May contain `{id}` or `{env.VAR}` placeholders. */
1222
+ href: import_zod18.z.string()
1223
+ });
1224
+ var ResourceRowProcedureActionSchema = ActionMetadataSchema.extend({
1225
+ type: import_zod18.z.literal("procedure").optional(),
1226
+ /** HTTP method for the endpoint. Defaults to `"post"`. */
1227
+ method: import_zod18.z.string().optional(),
1228
+ /** Static data payload merged into the request body by the frontend. */
1229
+ data: import_zod18.z.record(import_zod18.z.string(), import_zod18.z.unknown()).optional(),
1230
+ /** Procedure called with `(prisma, recordId)`. */
1231
+ procedure: import_zod18.z.custom((v) => typeof v === "function")
1232
+ });
1233
+ var ResourceTableProcedureActionSchema = ActionMetadataSchema.extend({
1234
+ type: import_zod18.z.literal("procedure").optional(),
1235
+ /** HTTP method for the endpoint. Defaults to `"post"`. */
1236
+ method: import_zod18.z.string().optional(),
1237
+ /** Static data payload merged into the request body by the frontend. */
1238
+ data: import_zod18.z.record(import_zod18.z.string(), import_zod18.z.unknown()).optional(),
1239
+ /** Procedure called with `(prisma)` — no record id. */
1240
+ procedure: import_zod18.z.custom((v) => typeof v === "function")
1241
+ });
1242
+ var ResourceRowActionSchema = import_zod18.z.union([
1243
+ ResourceRowProcedureActionSchema,
1244
+ ResourceLinkActionSchema
1245
+ ]);
1246
+ var ResourceTableActionSchema = import_zod18.z.union([
1247
+ ResourceTableProcedureActionSchema,
1248
+ ResourceLinkActionSchema
1249
+ ]);
1250
+ var isRowProcedureAction = /* @__PURE__ */ __name((action) => action.type !== "link", "isRowProcedureAction");
1251
+ var isTableProcedureAction = /* @__PURE__ */ __name((action) => action.type !== "link", "isTableProcedureAction");
1252
+
1253
+ // src/lib/crud/loader/module.loader.ts
1254
+ var import_node_fs = require("fs");
1255
+ var import_node_module = require("module");
1256
+ var import_node_path2 = require("path");
1257
+ var import_meta = {};
1258
+ var _require = (0, import_node_module.createRequire)(import_meta.url ?? __filename);
1259
+ var findModule = /* @__PURE__ */ __name((dir, name) => {
1260
+ for (const ext of [
1261
+ ".ts",
1262
+ ".js"
1263
+ ]) {
1264
+ const p = (0, import_node_path2.join)(dir, `${name}${ext}`);
1265
+ if ((0, import_node_fs.existsSync)(p)) return p;
1266
+ }
1267
+ return void 0;
1268
+ }, "findModule");
1269
+ var IS_VITE = typeof globalThis.__vite_ssr_import__ === "function";
1270
+ var importDefault = /* @__PURE__ */ __name(async (filePath) => {
1271
+ try {
1272
+ if (IS_VITE) {
1273
+ const importPath = IS_DEV ? `${filePath}?t=${Date.now()}` : filePath;
1274
+ const mod = await import(importPath);
1275
+ return mod.default ?? mod;
1276
+ } else {
1277
+ const mod = _require(filePath);
1278
+ return mod.default;
1279
+ }
1280
+ } catch {
1281
+ return void 0;
1282
+ }
1283
+ }, "importDefault");
1284
+
1285
+ // src/lib/crud/action/action.loader.ts
1286
+ var import_node_path3 = require("path");
1287
+ var loadActions = /* @__PURE__ */ __name(async (jsonActions, basePath, scope) => {
1288
+ const tag = scope === "row" ? "actions" : "tableActions";
1289
+ const results = [];
1290
+ for (const action of jsonActions) {
1291
+ if (action.type === "link") {
1292
+ results.push({
1293
+ type: "link",
1294
+ id: action.id,
1295
+ label: action.label,
1296
+ href: action.href,
1297
+ ...action.icon && {
1298
+ icon: action.icon
1299
+ },
1300
+ ...action.tooltip && {
1301
+ tooltip: action.tooltip
1302
+ },
1303
+ ...action.condition && {
1304
+ condition: action.condition
1305
+ }
1306
+ });
1307
+ continue;
1308
+ }
1309
+ const file = findModule((0, import_node_path3.join)(basePath, "actions"), action.procedure);
1310
+ if (!file) {
1311
+ console.warn(`[${tag}] Procedure file not found for "${action.id}" in ${basePath}/actions/`);
1312
+ continue;
1313
+ }
1314
+ const mod = await importDefault(file);
1315
+ if (!mod) {
1316
+ console.warn(`[${tag}] No default export in ${file}`);
1317
+ continue;
1318
+ }
1319
+ results.push({
1320
+ id: action.id,
1321
+ label: action.label,
1322
+ method: action.method,
1323
+ data: action.data,
1324
+ ...action.icon && {
1325
+ icon: action.icon
1326
+ },
1327
+ ...action.tooltip && {
1328
+ tooltip: action.tooltip
1329
+ },
1330
+ ...action.condition && {
1331
+ condition: action.condition
1332
+ },
1333
+ procedure: mod
1334
+ });
1335
+ }
1336
+ return results;
1337
+ }, "loadActions");
1338
+
1339
+ // src/lib/crud/crud.config.ts
1340
+ var resolveDefinition = /* @__PURE__ */ __name((config) => {
1341
+ const def2 = config.definition;
1342
+ return typeof def2 === "function" ? def2() : def2;
1343
+ }, "resolveDefinition");
1344
+ var isOperationEnabled = /* @__PURE__ */ __name((def2, op) => def2[op] != null, "isOperationEnabled");
1345
+ var schemaFor = /* @__PURE__ */ __name((def2, op) => {
1346
+ const entry = def2[op];
1347
+ if (!entry || entry === true) return void 0;
1348
+ return entry.schema;
1349
+ }, "schemaFor");
1350
+ var upsertOnFor = /* @__PURE__ */ __name((def2) => def2.upsert?.upsertOn, "upsertOnFor");
1351
+
1352
+ // src/lib/crud/read.repository.ts
1353
+ var import_common4 = require("@nestjs/common");
1354
+
719
1355
  // src/lib/crud/sql.helpers.ts
720
1356
  var castExpression = /* @__PURE__ */ __name((col) => {
721
1357
  if (col.type === "string") return `(${col.sqlExpression})`;
@@ -1199,9 +1835,9 @@ var ReadRepository = class {
1199
1835
  };
1200
1836
 
1201
1837
  // src/lib/crud/schema.utils.ts
1202
- var import_zod7 = require("zod");
1838
+ var import_zod19 = require("zod");
1203
1839
  var dateOverride = /* @__PURE__ */ __name(({ zodSchema, jsonSchema }) => {
1204
- if (zodSchema instanceof import_zod7.z.ZodDate) {
1840
+ if (zodSchema instanceof import_zod19.z.ZodDate) {
1205
1841
  jsonSchema.type = "string";
1206
1842
  jsonSchema.format = "date-time";
1207
1843
  }
@@ -1211,7 +1847,7 @@ var jsonSchemaOpts = {
1211
1847
  override: dateOverride
1212
1848
  };
1213
1849
  function isZodSchema(schema) {
1214
- return schema instanceof import_zod7.ZodObject;
1850
+ return schema instanceof import_zod19.ZodObject;
1215
1851
  }
1216
1852
  __name(isZodSchema, "isZodSchema");
1217
1853
  var isNullableProperty = /* @__PURE__ */ __name((property) => {
@@ -1225,7 +1861,7 @@ var dropNullableFromRequired = /* @__PURE__ */ __name((jsonSchema) => {
1225
1861
  }, "dropNullableFromRequired");
1226
1862
  function toJsonSchema(schema) {
1227
1863
  if (isZodSchema(schema)) {
1228
- const jsonSchema = (0, import_zod7.toJSONSchema)(schema, {
1864
+ const jsonSchema = (0, import_zod19.toJSONSchema)(schema, {
1229
1865
  target: "openApi3",
1230
1866
  ...jsonSchemaOpts
1231
1867
  });
@@ -1600,21 +2236,27 @@ DataSourceRegistry = _ts_decorate4([
1600
2236
  ], DataSourceRegistry);
1601
2237
 
1602
2238
  // src/lib/crud/data-source/data-source.loader.ts
1603
- var import_node_fs = require("fs");
1604
- var import_node_path = require("path");
2239
+ var import_node_fs2 = require("fs");
2240
+ var import_node_path4 = require("path");
1605
2241
  var loadDataSourcesFromDir = /* @__PURE__ */ __name(async (dirPath) => {
1606
- if (!(0, import_node_fs.existsSync)(dirPath)) return [];
1607
- const entries = (0, import_node_fs.readdirSync)(dirPath, {
2242
+ if (!(0, import_node_fs2.existsSync)(dirPath)) return [];
2243
+ const entries = (0, import_node_fs2.readdirSync)(dirPath, {
1608
2244
  withFileTypes: true
1609
2245
  });
1610
2246
  const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
1611
2247
  const results = [];
1612
2248
  for (const dir of dirs) {
1613
- const basePath = (0, import_node_path.join)(dirPath, dir);
1614
- const jsonFile = (0, import_node_path.join)(basePath, "data-source.json");
1615
- if (!(0, import_node_fs.existsSync)(jsonFile)) continue;
1616
- const config = JSON.parse((0, import_node_fs.readFileSync)(jsonFile, "utf-8"));
1617
- const indexFile = findModule(basePath, "index");
2249
+ const basePath = (0, import_node_path4.join)(dirPath, dir);
2250
+ const jsonFile = (0, import_node_path4.join)(basePath, "data-source.json");
2251
+ if (!(0, import_node_fs2.existsSync)(jsonFile)) continue;
2252
+ const _config = JSON.parse((0, import_node_fs2.readFileSync)(jsonFile, "utf-8"));
2253
+ const datasource = DataSourceSchema.safeParse(_config);
2254
+ if (!datasource.success) {
2255
+ console.error(datasource.error);
2256
+ throw new Error(`Invalid datasource schema: ${jsonFile}`);
2257
+ }
2258
+ const config = datasource.data;
2259
+ const indexFile = findModule2(basePath, "index");
1618
2260
  if (!indexFile) continue;
1619
2261
  const mod = await import(indexFile);
1620
2262
  const client = mod.default;
@@ -1626,13 +2268,13 @@ var loadDataSourcesFromDir = /* @__PURE__ */ __name(async (dirPath) => {
1626
2268
  }
1627
2269
  return results;
1628
2270
  }, "loadDataSourcesFromDir");
1629
- var findModule = /* @__PURE__ */ __name((dir, name) => {
2271
+ var findModule2 = /* @__PURE__ */ __name((dir, name) => {
1630
2272
  for (const ext of [
1631
2273
  ".ts",
1632
2274
  ".js"
1633
2275
  ]) {
1634
- const p = (0, import_node_path.join)(dir, `${name}${ext}`);
1635
- if ((0, import_node_fs.existsSync)(p)) return p;
2276
+ const p = (0, import_node_path4.join)(dir, `${name}${ext}`);
2277
+ if ((0, import_node_fs2.existsSync)(p)) return p;
1636
2278
  }
1637
2279
  return void 0;
1638
2280
  }, "findModule");
@@ -1655,7 +2297,7 @@ var desc = /* @__PURE__ */ __name((cls, method) => Object.getOwnPropertyDescript
1655
2297
  var registerActionRoutes = /* @__PURE__ */ __name((ctx) => {
1656
2298
  const { cls, config } = ctx;
1657
2299
  const { name } = config;
1658
- const procedureActions = (config.actions ?? []).filter((a) => a.type !== "link");
2300
+ const procedureActions = (config.actions ?? []).filter(isRowProcedureAction);
1659
2301
  for (const action of procedureActions) {
1660
2302
  const methodName = `procedure_${action.id}`;
1661
2303
  def(cls, methodName, async function(recordId) {
@@ -1680,7 +2322,7 @@ var registerActionRoutes = /* @__PURE__ */ __name((ctx) => {
1680
2322
  var registerTableActionRoutes = /* @__PURE__ */ __name((ctx) => {
1681
2323
  const { cls, config } = ctx;
1682
2324
  const { name } = config;
1683
- const procedureActions = (config.tableActions ?? []).filter((a) => a.type !== "link");
2325
+ const procedureActions = (config.tableActions ?? []).filter(isTableProcedureAction);
1684
2326
  for (const action of procedureActions) {
1685
2327
  const methodName = `tableAction_${action.id}`;
1686
2328
  def(cls, methodName, async function() {
@@ -1782,38 +2424,56 @@ var ZodValidationPipe = class {
1782
2424
  };
1783
2425
 
1784
2426
  // src/lib/crud/operations/register-crud.ts
2427
+ var findAll = /* @__PURE__ */ __name(async (repo, params, q, lookupLabel) => {
2428
+ const effectiveParams = {
2429
+ ...params
2430
+ };
2431
+ if (q && lookupLabel) {
2432
+ effectiveParams.filter = [
2433
+ ...params.filter ?? [],
2434
+ `${lookupLabel}:${q}`
2435
+ ];
2436
+ }
2437
+ const [data, count] = await Promise.all([
2438
+ repo.findAll(effectiveParams),
2439
+ repo.count(effectiveParams.filter)
2440
+ ]);
2441
+ const totalPages = Math.max(1, Math.ceil(count / params.pageSize));
2442
+ return {
2443
+ data,
2444
+ request: {
2445
+ count,
2446
+ page: params.page,
2447
+ pageSize: params.pageSize,
2448
+ totalPages,
2449
+ sort: params.sort,
2450
+ sortDir: params.sortDir,
2451
+ filter: params.filter
2452
+ }
2453
+ };
2454
+ }, "findAll");
2455
+ var findOne = /* @__PURE__ */ __name(async (repo, id) => {
2456
+ return repo.findOne(id);
2457
+ }, "findOne");
2458
+ var create = /* @__PURE__ */ __name(async (repo, body) => {
2459
+ return repo.create(body);
2460
+ }, "create");
2461
+ var update = /* @__PURE__ */ __name(async (repo, id, body) => {
2462
+ return repo.update(id, body);
2463
+ }, "update");
2464
+ var upsert = /* @__PURE__ */ __name(async (repo, body) => {
2465
+ return repo.upsert(body);
2466
+ }, "upsert");
2467
+ var del = /* @__PURE__ */ __name(async (repo, id) => {
2468
+ return repo.delete(id);
2469
+ }, "del");
1785
2470
  var registerFindAll = /* @__PURE__ */ __name((ctx) => {
1786
2471
  if (!isOperationEnabled(ctx.definition, "findAll")) return;
1787
2472
  const { cls, config, listSchema } = ctx;
1788
2473
  const { name } = config;
1789
2474
  const lookupLabel = config.lookup?.label;
1790
2475
  def(cls, "findAll", async function(params, q) {
1791
- const effectiveParams = {
1792
- ...params
1793
- };
1794
- if (q && lookupLabel) {
1795
- effectiveParams.filter = [
1796
- ...params.filter ?? [],
1797
- `${lookupLabel}:${q}`
1798
- ];
1799
- }
1800
- const [data, count] = await Promise.all([
1801
- this.repo.findAll(effectiveParams),
1802
- this.repo.count(effectiveParams.filter)
1803
- ]);
1804
- const totalPages = Math.max(1, Math.ceil(count / params.pageSize));
1805
- return {
1806
- data,
1807
- request: {
1808
- count,
1809
- page: params.page,
1810
- pageSize: params.pageSize,
1811
- totalPages,
1812
- sort: params.sort,
1813
- sortDir: params.sortDir,
1814
- filter: params.filter
1815
- }
1816
- };
2476
+ return findAll(this.repo, params, q, lookupLabel);
1817
2477
  });
1818
2478
  const d = desc(cls, "findAll");
1819
2479
  (0, import_common8.Get)()(cls.prototype, "findAll", d);
@@ -1838,7 +2498,7 @@ var registerFindOne = /* @__PURE__ */ __name((ctx) => {
1838
2498
  const { cls, config, oneSchema, idParamMeta } = ctx;
1839
2499
  const { name } = config;
1840
2500
  def(cls, "findOne", function(id) {
1841
- return this.repo.findOne(id);
2501
+ return findOne(this.repo, id);
1842
2502
  });
1843
2503
  const d = desc(cls, "findOne");
1844
2504
  (0, import_common8.Get)(":id")(cls.prototype, "findOne", d);
@@ -1863,7 +2523,7 @@ var registerCreate = /* @__PURE__ */ __name((ctx) => {
1863
2523
  const { cls, config, createSchema, bodyDecorator } = ctx;
1864
2524
  const { name } = config;
1865
2525
  def(cls, "create", function(body) {
1866
- return this.repo.create(body);
2526
+ return create(this.repo, body);
1867
2527
  });
1868
2528
  const d = desc(cls, "create");
1869
2529
  (0, import_common8.Post)()(cls.prototype, "create", d);
@@ -1886,7 +2546,7 @@ var registerUpdate = /* @__PURE__ */ __name((ctx) => {
1886
2546
  const { cls, config, updateSchema, idParamMeta, bodyDecorator } = ctx;
1887
2547
  const { name } = config;
1888
2548
  def(cls, "update", function(id, body) {
1889
- return this.repo.update(id, body);
2549
+ return update(this.repo, id, body);
1890
2550
  });
1891
2551
  const d = desc(cls, "update");
1892
2552
  (0, import_common8.Patch)(":id")(cls.prototype, "update", d);
@@ -1912,7 +2572,7 @@ var registerUpsert = /* @__PURE__ */ __name((ctx) => {
1912
2572
  const { cls, config, upsertSchema, bodyDecorator } = ctx;
1913
2573
  const { name } = config;
1914
2574
  def(cls, "upsert", function(body) {
1915
- return this.repo.upsert(body);
2575
+ return upsert(this.repo, body);
1916
2576
  });
1917
2577
  const d = desc(cls, "upsert");
1918
2578
  (0, import_common8.Put)()(cls.prototype, "upsert", d);
@@ -1935,7 +2595,7 @@ var registerDelete = /* @__PURE__ */ __name((ctx) => {
1935
2595
  const { cls, config, idParamMeta } = ctx;
1936
2596
  const { name } = config;
1937
2597
  def(cls, "delete", function(id) {
1938
- return this.repo.delete(id);
2598
+ return del(this.repo, id);
1939
2599
  });
1940
2600
  const d = desc(cls, "delete");
1941
2601
  (0, import_common8.Delete)(":id")(cls.prototype, "delete", d);
@@ -2124,6 +2784,12 @@ var buildViewsPayload = /* @__PURE__ */ __name((config, baseUrl) => {
2124
2784
  id: a.id,
2125
2785
  label: a.label,
2126
2786
  href: resolveEnvPlaceholders(a.href),
2787
+ ...a.icon && {
2788
+ icon: a.icon
2789
+ },
2790
+ ...a.tooltip && {
2791
+ tooltip: a.tooltip
2792
+ },
2127
2793
  ...a.condition && {
2128
2794
  condition: a.condition
2129
2795
  }
@@ -2135,6 +2801,12 @@ var buildViewsPayload = /* @__PURE__ */ __name((config, baseUrl) => {
2135
2801
  ...a.data && {
2136
2802
  data: a.data
2137
2803
  },
2804
+ ...a.icon && {
2805
+ icon: a.icon
2806
+ },
2807
+ ...a.tooltip && {
2808
+ tooltip: a.tooltip
2809
+ },
2138
2810
  ...a.condition && {
2139
2811
  condition: a.condition
2140
2812
  }
@@ -2147,7 +2819,10 @@ var buildViewsPayload = /* @__PURE__ */ __name((config, baseUrl) => {
2147
2819
  label: a.label,
2148
2820
  icon: a.icon,
2149
2821
  tooltip: a.tooltip,
2150
- href: resolveEnvPlaceholders(a.href)
2822
+ href: resolveEnvPlaceholders(a.href),
2823
+ ...a.condition && {
2824
+ condition: a.condition
2825
+ }
2151
2826
  } : {
2152
2827
  id: a.id,
2153
2828
  label: a.label,
@@ -2157,6 +2832,9 @@ var buildViewsPayload = /* @__PURE__ */ __name((config, baseUrl) => {
2157
2832
  method: a.method ?? "post",
2158
2833
  ...a.data && {
2159
2834
  data: a.data
2835
+ },
2836
+ ...a.condition && {
2837
+ condition: a.condition
2160
2838
  }
2161
2839
  })
2162
2840
  }
@@ -2231,6 +2909,34 @@ var registerResourceJsonEndpoint = /* @__PURE__ */ __name((ctx) => {
2231
2909
  // src/lib/crud/operations/register-sub-resources.ts
2232
2910
  var import_common10 = require("@nestjs/common");
2233
2911
  var import_swagger5 = require("@nestjs/swagger");
2912
+ var findAllByParent = /* @__PURE__ */ __name(async (repo, id, childRoute, params) => {
2913
+ const { data, count } = await repo.findAllByParent(id, childRoute, params);
2914
+ const totalPages = Math.max(1, Math.ceil(count / params.pageSize));
2915
+ return {
2916
+ data,
2917
+ request: {
2918
+ count,
2919
+ page: params.page,
2920
+ pageSize: params.pageSize,
2921
+ totalPages,
2922
+ sort: params.sort,
2923
+ sortDir: params.sortDir,
2924
+ filter: params.filter
2925
+ }
2926
+ };
2927
+ }, "findAllByParent");
2928
+ var createChild = /* @__PURE__ */ __name(async (repo, id, sub, body) => {
2929
+ return repo.createChild(id, sub, body);
2930
+ }, "createChild");
2931
+ var findOneChild = /* @__PURE__ */ __name(async (repo, sub, childId, parentId) => {
2932
+ return repo.findOneChild(sub, childId, parentId);
2933
+ }, "findOneChild");
2934
+ var updateChild = /* @__PURE__ */ __name(async (repo, sub, childId, body) => {
2935
+ return repo.updateChild(sub, childId, body);
2936
+ }, "updateChild");
2937
+ var deleteChild = /* @__PURE__ */ __name(async (repo, sub, childId, parentId) => {
2938
+ return repo.deleteChild(sub, childId, parentId);
2939
+ }, "deleteChild");
2234
2940
  var registerSubResourceSchemas = /* @__PURE__ */ __name((ctx, sub) => {
2235
2941
  if (!sub.views) return;
2236
2942
  const { cls, config, baseUrl } = ctx;
@@ -2302,20 +3008,7 @@ var registerSubResourceFindAll = /* @__PURE__ */ __name((ctx, sub) => {
2302
3008
  const idParamMeta = ctx.idParamMeta;
2303
3009
  const methodName = `findAllBy_${sub.childRoute}`;
2304
3010
  def(cls, methodName, async function(id, params) {
2305
- const { data, count } = await this.repo.findAllByParent(id, sub.childRoute, params);
2306
- const totalPages = Math.max(1, Math.ceil(count / params.pageSize));
2307
- return {
2308
- data,
2309
- request: {
2310
- count,
2311
- page: params.page,
2312
- pageSize: params.pageSize,
2313
- totalPages,
2314
- sort: params.sort,
2315
- sortDir: params.sortDir,
2316
- filter: params.filter
2317
- }
2318
- };
3011
+ return findAllByParent(this.repo, id, sub.childRoute, params);
2319
3012
  });
2320
3013
  const d = desc(cls, methodName);
2321
3014
  (0, import_common10.Get)(`:id/${sub.childRoute}`)(cls.prototype, methodName, d);
@@ -2336,7 +3029,7 @@ var registerSubResourceCreate = /* @__PURE__ */ __name((ctx, sub) => {
2336
3029
  const { name } = config;
2337
3030
  const methodName = `createChild_${sub.childRoute}`;
2338
3031
  def(cls, methodName, async function(id, body) {
2339
- return this.repo.createChild(id, sub, body);
3032
+ return createChild(this.repo, id, sub, body);
2340
3033
  });
2341
3034
  const d = desc(cls, methodName);
2342
3035
  (0, import_common10.Post)(`:id/${sub.childRoute}`)(cls.prototype, methodName, d);
@@ -2356,7 +3049,7 @@ var registerSubResourceFindOne = /* @__PURE__ */ __name((ctx, sub) => {
2356
3049
  const { cls } = ctx;
2357
3050
  const methodName = `findOneChild_${sub.childRoute}`;
2358
3051
  def(cls, methodName, async function(parentId, childId) {
2359
- return this.repo.findOneChild(sub, childId, parentId);
3052
+ return findOneChild(this.repo, sub, childId, parentId);
2360
3053
  });
2361
3054
  const d = desc(cls, methodName);
2362
3055
  (0, import_common10.Get)(`:id/${sub.childRoute}/:childId`)(cls.prototype, methodName, d);
@@ -2376,7 +3069,7 @@ var registerSubResourceUpdate = /* @__PURE__ */ __name((ctx, sub) => {
2376
3069
  const { cls } = ctx;
2377
3070
  const methodName = `updateChild_${sub.childRoute}`;
2378
3071
  def(cls, methodName, async function(_id, childId, body) {
2379
- return this.repo.updateChild(sub, childId, body);
3072
+ return updateChild(this.repo, sub, childId, body);
2380
3073
  });
2381
3074
  const d = desc(cls, methodName);
2382
3075
  (0, import_common10.Patch)(`:id/${sub.childRoute}/:childId`)(cls.prototype, methodName, d);
@@ -2397,7 +3090,7 @@ var registerSubResourceDelete = /* @__PURE__ */ __name((ctx, sub) => {
2397
3090
  const { cls } = ctx;
2398
3091
  const methodName = `deleteChild_${sub.childRoute}`;
2399
3092
  def(cls, methodName, async function(parentId, childId) {
2400
- return this.repo.deleteChild(sub, childId, parentId);
3093
+ return deleteChild(this.repo, sub, childId, parentId);
2401
3094
  });
2402
3095
  const d = desc(cls, methodName);
2403
3096
  (0, import_common10.Delete)(`:id/${sub.childRoute}/:childId`)(cls.prototype, methodName, d);
@@ -2436,9 +3129,9 @@ function createCrudController(config, baseUrl) {
2436
3129
  throw new Error(`Resource "${name}" declares 'upsert' but no upsertOn`);
2437
3130
  }
2438
3131
  const bodyDecorator = /* @__PURE__ */ __name((schema, options) => {
2439
- if (!schema) return (0, import_common12.Body)();
2440
- if (isZodSchema(schema)) return (0, import_common12.Body)(new ZodValidationPipe(schema, options));
2441
- return (0, import_common12.Body)();
3132
+ if (!schema) return (0, import_common11.Body)();
3133
+ if (isZodSchema(schema)) return (0, import_common11.Body)(new ZodValidationPipe(schema, options));
3134
+ return (0, import_common11.Body)();
2442
3135
  }, "bodyDecorator");
2443
3136
  let CrudControllerBase = class CrudControllerBase {
2444
3137
  static {
@@ -2493,165 +3186,115 @@ function createCrudController(config, baseUrl) {
2493
3186
  }
2494
3187
  __name(createCrudController, "createCrudController");
2495
3188
 
2496
- // src/lib/crud/loader/module.loader.ts
2497
- var import_node_fs2 = require("fs");
2498
- var import_node_module = require("module");
2499
- var import_node_path2 = require("path");
2500
- var import_meta = {};
2501
- var _require = (0, import_node_module.createRequire)(import_meta.url);
2502
- var findModule2 = /* @__PURE__ */ __name((dir, name) => {
2503
- for (const ext of [
2504
- ".ts",
2505
- ".js"
2506
- ]) {
2507
- const p = (0, import_node_path2.join)(dir, `${name}${ext}`);
2508
- if ((0, import_node_fs2.existsSync)(p)) return p;
3189
+ // src/lib/crud/builder/column-predicates.ts
3190
+ var isBoolean = /* @__PURE__ */ __name((col) => col.fieldInput?.type === "boolean" || col.columnType === "boolean", "isBoolean");
3191
+ var isRelation = /* @__PURE__ */ __name((col) => col.fieldInput?.format === "relation", "isRelation");
3192
+ var isAutocomplete = /* @__PURE__ */ __name((col) => col.fieldInput?.type === "autocomplete", "isAutocomplete");
3193
+ var isRecordCell = /* @__PURE__ */ __name((col) => isRelation(col) || isAutocomplete(col), "isRecordCell");
3194
+ var isDateRange = /* @__PURE__ */ __name((col) => col.fieldInput?.format === "date-range", "isDateRange");
3195
+
3196
+ // src/lib/crud/builder/column.utils.ts
3197
+ var colPosition = /* @__PURE__ */ __name((col, i) => col.fieldInput?.position ?? i, "colPosition");
3198
+ var sortByPosition = /* @__PURE__ */ __name((cols) => cols.map((col, i) => ({
3199
+ col,
3200
+ i
3201
+ })).sort((a, b) => colPosition(a.col, a.i) - colPosition(b.col, b.i)).map(({ col }) => col), "sortByPosition");
3202
+ var toViewColumn = /* @__PURE__ */ __name((col) => ({
3203
+ id: col.id,
3204
+ ...col.label && {
3205
+ label: col.label
3206
+ },
3207
+ ...col.sortable != null && {
3208
+ sortable: col.sortable
3209
+ },
3210
+ ...col.searchable != null && {
3211
+ searchable: col.searchable
3212
+ },
3213
+ ...col.fieldInput && {
3214
+ fieldInput: col.fieldInput
2509
3215
  }
2510
- return void 0;
2511
- }, "findModule");
2512
- var IS_VITE = typeof globalThis.__vite_ssr_import__ === "function";
2513
- var importDefault = /* @__PURE__ */ __name(async (filePath) => {
2514
- try {
2515
- if (IS_VITE) {
2516
- const importPath = IS_DEV ? `${filePath}?t=${Date.now()}` : filePath;
2517
- const mod = await import(importPath);
2518
- return mod.default ?? mod;
2519
- } else {
2520
- const mod = _require(filePath);
2521
- return mod.default;
2522
- }
2523
- } catch {
2524
- return void 0;
3216
+ }), "toViewColumn");
3217
+
3218
+ // src/lib/crud/builder/sort.helpers.ts
3219
+ var deriveSortId = /* @__PURE__ */ __name((col) => {
3220
+ if (col.sortable === false) return null;
3221
+ if (col.sortId) return col.sortId;
3222
+ const base = col.column ?? col.id;
3223
+ const fi = col.fieldInput;
3224
+ const opts = fi?.options ?? {};
3225
+ const isRelation2 = fi?.format === "relation" || !!fi?.relationType || fi?.type === "autocomplete" || typeof opts.resource === "string";
3226
+ if (isRelation2) {
3227
+ const key = (typeof col.displayKey === "string" ? col.displayKey : void 0) ?? (typeof opts.displayKey === "string" ? opts.displayKey : void 0) ?? (typeof opts.labelKey === "string" ? opts.labelKey : void 0);
3228
+ if (!key) return null;
3229
+ const path2 = key.includes(".") ? key : `${base}.${key}`;
3230
+ return path2.endsWith(".label") ? path2.slice(0, -".label".length) : path2;
2525
3231
  }
2526
- }, "importDefault");
3232
+ if (!col.displayKey) return base;
3233
+ const path = `${base}.${col.displayKey}`;
3234
+ const isValueLabel = !!col.enum || opts.emitObject === true;
3235
+ if (isValueLabel && path.endsWith(".label")) return path.slice(0, -".label".length);
3236
+ return path;
3237
+ }, "deriveSortId");
3238
+ var resolveDefaultSort = /* @__PURE__ */ __name((tableCols, allColumns) => {
3239
+ const isSortable = /* @__PURE__ */ __name((c) => c.sortable !== false, "isSortable");
3240
+ const sortCol = tableCols.find((c) => c.defaultSort && isSortable(c)) ?? tableCols.find(isSortable) ?? allColumns?.find((c) => c.idField);
3241
+ return sortCol ? deriveSortId(sortCol) ?? sortCol.id : void 0;
3242
+ }, "resolveDefaultSort");
2527
3243
 
2528
- // src/lib/crud/loader/action.loader.ts
2529
- var import_node_path3 = require("path");
2530
- var loadActions = /* @__PURE__ */ __name(async (jsonActions, basePath) => {
2531
- const results = [];
2532
- for (const action of jsonActions) {
2533
- if (action.type === "link") {
2534
- results.push({
2535
- type: "link",
2536
- id: action.id,
2537
- label: action.label,
2538
- href: action.href,
2539
- ...action.condition && {
2540
- condition: action.condition
2541
- }
2542
- });
2543
- continue;
2544
- }
2545
- const file = findModule2((0, import_node_path3.join)(basePath, "actions"), action.procedure);
2546
- if (!file) {
2547
- console.warn(`[actions] Procedure file not found for "${action.id}" in ${basePath}/actions/`);
2548
- continue;
2549
- }
2550
- const mod = await importDefault(file);
2551
- if (!mod) {
2552
- console.warn(`[actions] No default export in ${file}`);
2553
- continue;
3244
+ // src/lib/crud/builder/schema-transforms.ts
3245
+ var allowAdditionalProperties = /* @__PURE__ */ __name((schema) => {
3246
+ if (schema["type"] === "object") {
3247
+ schema["additionalProperties"] = true;
3248
+ const props = schema["properties"];
3249
+ if (props) {
3250
+ for (const value of Object.values(props)) {
3251
+ allowAdditionalProperties(value);
3252
+ }
2554
3253
  }
2555
- results.push({
2556
- id: action.id,
2557
- label: action.label,
2558
- method: action.method,
2559
- data: action.data,
2560
- ...action.condition && {
2561
- condition: action.condition
2562
- },
2563
- procedure: mod
2564
- });
2565
3254
  }
2566
- return results;
2567
- }, "loadActions");
2568
- var loadTableActions = /* @__PURE__ */ __name(async (jsonActions, basePath) => {
2569
- const results = [];
2570
- for (const action of jsonActions) {
2571
- if (action.type === "link") {
2572
- results.push({
2573
- type: "link",
2574
- id: action.id,
2575
- label: action.label,
2576
- icon: action.icon,
2577
- tooltip: action.tooltip,
2578
- href: action.href
2579
- });
2580
- continue;
2581
- }
2582
- const file = findModule2((0, import_node_path3.join)(basePath, "actions"), action.procedure);
2583
- if (!file) {
2584
- console.warn(`[tableActions] Procedure file not found for "${action.id}" in ${basePath}/actions/`);
2585
- continue;
2586
- }
2587
- const mod = await importDefault(file);
2588
- if (!mod) {
2589
- console.warn(`[tableActions] No default export in ${file}`);
2590
- continue;
2591
- }
2592
- results.push({
2593
- id: action.id,
2594
- label: action.label,
2595
- icon: action.icon,
2596
- tooltip: action.tooltip,
2597
- method: action.method,
2598
- data: action.data,
2599
- procedure: mod
2600
- });
3255
+ if (schema["type"] === "array" && schema["items"]) {
3256
+ allowAdditionalProperties(schema["items"]);
2601
3257
  }
2602
- return results;
2603
- }, "loadTableActions");
2604
-
2605
- // src/lib/crud/loader/enum-registry.ts
2606
- var import_node_fs3 = require("fs");
2607
- var import_node_path4 = require("path");
2608
- var ENUMS_FILE = "crouton.enums.json";
2609
- var loadEnumRegistry = /* @__PURE__ */ __name((startDir, enumsFile) => {
2610
- let file = enumsFile;
2611
- if (!file) {
2612
- let dir = startDir;
2613
- while (true) {
2614
- const candidate = (0, import_node_path4.join)(dir, ENUMS_FILE);
2615
- if ((0, import_node_fs3.existsSync)(candidate)) {
2616
- file = candidate;
2617
- break;
2618
- }
2619
- const parent = (0, import_node_path4.dirname)(dir);
2620
- if (parent === dir) break;
2621
- dir = parent;
2622
- }
3258
+ }, "allowAdditionalProperties");
3259
+ var isNullableProperty2 = /* @__PURE__ */ __name((prop) => {
3260
+ const anyOf = prop?.["anyOf"];
3261
+ return Array.isArray(anyOf) && anyOf.some((s) => s?.["type"] === "null");
3262
+ }, "isNullableProperty");
3263
+ var dropNullableFromRequired2 = /* @__PURE__ */ __name((schema) => {
3264
+ if (schema["type"] !== "object") return;
3265
+ const props = schema["properties"];
3266
+ if (!props) return;
3267
+ const required = schema["required"];
3268
+ if (Array.isArray(required)) {
3269
+ schema["required"] = required.filter((key) => !isNullableProperty2(props[key]));
2623
3270
  }
2624
- if (!file || !(0, import_node_fs3.existsSync)(file)) return {};
2625
- try {
2626
- return JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8"));
2627
- } catch {
2628
- return {};
3271
+ for (const value of Object.values(props)) {
3272
+ dropNullableFromRequired2(value);
2629
3273
  }
2630
- }, "loadEnumRegistry");
2631
- var injectEnumValues = /* @__PURE__ */ __name((columns, enums) => {
2632
- if (!columns) return;
2633
- for (const col of columns) {
2634
- if (!col.enum) continue;
2635
- const values = enums[col.enum];
2636
- if (!values) continue;
2637
- col.fieldInput = col.fieldInput ?? {
2638
- type: "select"
2639
- };
2640
- const options = col.fieldInput.options ?? {};
2641
- if (!("values" in options)) options.values = values;
2642
- col.fieldInput.options = options;
3274
+ }, "dropNullableFromRequired");
3275
+ var enforceRequiredMinLength = /* @__PURE__ */ __name((schema) => {
3276
+ if (schema["type"] !== "object") return;
3277
+ const props = schema["properties"];
3278
+ if (!props) return;
3279
+ for (const prop of Object.values(props)) {
3280
+ if (prop?.["type"] === "string" && !("minLength" in prop)) {
3281
+ prop["minLength"] = 1;
3282
+ } else if (prop?.["type"] === "object") {
3283
+ enforceRequiredMinLength(prop);
3284
+ }
2643
3285
  }
2644
- }, "injectEnumValues");
2645
-
2646
- // src/lib/crud/loader/json-adapter.ts
2647
- var import_zod9 = require("zod");
3286
+ }, "enforceRequiredMinLength");
3287
+ var applySchemaTransforms = /* @__PURE__ */ __name((schema) => {
3288
+ allowAdditionalProperties(schema);
3289
+ dropNullableFromRequired2(schema);
3290
+ enforceRequiredMinLength(schema);
3291
+ }, "applySchemaTransforms");
2648
3292
 
2649
- // src/lib/crud/loader/schema.helpers.ts
3293
+ // src/lib/crud/builder/schema.helpers.ts
2650
3294
  var pickByColumns = /* @__PURE__ */ __name((schema, columns, filter) => {
2651
3295
  if (!schema) return void 0;
2652
3296
  if (!columns?.length) return schema;
2653
- const isRelation2 = /* @__PURE__ */ __name((c) => c.fieldInput?.format === "relation", "isRelation");
2654
- const baseFilter = /* @__PURE__ */ __name((c) => !isRelation2(c) && (filter ? filter(c) : true), "baseFilter");
3297
+ const baseFilter = /* @__PURE__ */ __name((c) => !isRelation(c) && (filter ? filter(c) : true), "baseFilter");
2655
3298
  const filtered = columns.filter(baseFilter);
2656
3299
  if (!filtered.length) return void 0;
2657
3300
  const mask = Object.fromEntries(filtered.map((c) => [
@@ -2682,10 +3325,75 @@ var upsertOp = /* @__PURE__ */ __name((entry, schema) => {
2682
3325
  return void 0;
2683
3326
  }, "upsertOp");
2684
3327
 
2685
- // src/lib/crud/loader/view.builders.ts
2686
- var import_zod8 = require("zod");
3328
+ // src/lib/crud/builder/table-schema.builder.ts
3329
+ var SHARED_CELL_OPTION_KEYS = [
3330
+ "values",
3331
+ "storeValue",
3332
+ "uri",
3333
+ "resourceUri",
3334
+ "schemasUri"
3335
+ ];
3336
+ var pickSharedCellOptions = /* @__PURE__ */ __name((col) => {
3337
+ const options = col.fieldInput?.options ?? {};
3338
+ return Object.fromEntries(SHARED_CELL_OPTION_KEYS.filter((key) => options[key] !== void 0).map((key) => [
3339
+ key,
3340
+ options[key]
3341
+ ]));
3342
+ }, "pickSharedCellOptions");
3343
+ var buildTableUiSchema = /* @__PURE__ */ __name((cols) => {
3344
+ const layout = TableBuilder.init().addControls(...cols.map((col) => {
3345
+ const cellBuilder = isBoolean(col) ? BooleanCellBuilder : TextCellBuilder;
3346
+ let builder = cellBuilder.properties(col.id);
3347
+ if (col.displayKey) builder = builder.key(col.displayKey);
3348
+ if (col.sortId) builder = builder.setSortId(col.sortId);
3349
+ return builder;
3350
+ })).build();
3351
+ const colMap = Object.fromEntries(cols.map((c) => [
3352
+ c.id,
3353
+ c
3354
+ ]));
3355
+ layout.elements = layout.elements.map((el) => {
3356
+ const id = el.scope?.replace("#/properties/", "");
3357
+ const col = id ? colMap[id] : void 0;
3358
+ if (!col) return el;
3359
+ const fieldInputOptions = isRecordCell(col) || isDateRange(col) ? col.fieldInput?.options ?? {} : pickSharedCellOptions(col);
3360
+ const dataPathOption = col.column ? {
3361
+ dataPath: col.column
3362
+ } : {};
3363
+ const derivedSortId = isRecordCell(col) || isDateRange(col) ? null : deriveSortId(col);
3364
+ const sortOptions = derivedSortId ? {
3365
+ sortId: derivedSortId
3366
+ } : {
3367
+ sortable: false
3368
+ };
3369
+ const relationTypeOption = col.fieldInput?.relationType ? {
3370
+ relationType: col.fieldInput.relationType
3371
+ } : {};
3372
+ return {
3373
+ ...el,
3374
+ options: {
3375
+ ...el.options ?? {},
3376
+ ...fieldInputOptions,
3377
+ ...dataPathOption,
3378
+ ...sortOptions,
3379
+ ...relationTypeOption,
3380
+ ...isDateRange(col) && {
3381
+ format: "date-range"
3382
+ },
3383
+ label: col.label
3384
+ },
3385
+ ...isRecordCell(col) && {
3386
+ type: "RecordCell"
3387
+ },
3388
+ ...isDateRange(col) && {
3389
+ type: "Control"
3390
+ }
3391
+ };
3392
+ });
3393
+ return layout;
3394
+ }, "buildTableUiSchema");
2687
3395
 
2688
- // src/lib/crud/loader/form-schema.builder.ts
3396
+ // src/lib/crud/builder/form-schema.builder.ts
2689
3397
  var buildConditionSchema = /* @__PURE__ */ __name((when) => {
2690
3398
  if (when.notExists) return {
2691
3399
  not: {
@@ -2805,232 +3513,7 @@ var buildFormUiSchema = /* @__PURE__ */ __name((cols) => {
2805
3513
  return layout;
2806
3514
  }, "buildFormUiSchema");
2807
3515
 
2808
- // src/lib/crud/loader/schema-transforms.ts
2809
- var allowAdditionalProperties = /* @__PURE__ */ __name((schema) => {
2810
- if (schema["type"] === "object") {
2811
- schema["additionalProperties"] = true;
2812
- const props = schema["properties"];
2813
- if (props) {
2814
- for (const value of Object.values(props)) {
2815
- allowAdditionalProperties(value);
2816
- }
2817
- }
2818
- }
2819
- if (schema["type"] === "array" && schema["items"]) {
2820
- allowAdditionalProperties(schema["items"]);
2821
- }
2822
- }, "allowAdditionalProperties");
2823
- var isNullableProperty2 = /* @__PURE__ */ __name((prop) => {
2824
- const anyOf = prop?.["anyOf"];
2825
- return Array.isArray(anyOf) && anyOf.some((s) => s?.["type"] === "null");
2826
- }, "isNullableProperty");
2827
- var dropNullableFromRequired2 = /* @__PURE__ */ __name((schema) => {
2828
- if (schema["type"] !== "object") return;
2829
- const props = schema["properties"];
2830
- if (!props) return;
2831
- const required = schema["required"];
2832
- if (Array.isArray(required)) {
2833
- schema["required"] = required.filter((key) => !isNullableProperty2(props[key]));
2834
- }
2835
- for (const value of Object.values(props)) {
2836
- dropNullableFromRequired2(value);
2837
- }
2838
- }, "dropNullableFromRequired");
2839
- var enforceRequiredMinLength = /* @__PURE__ */ __name((schema) => {
2840
- if (schema["type"] !== "object") return;
2841
- const props = schema["properties"];
2842
- if (!props) return;
2843
- for (const prop of Object.values(props)) {
2844
- if (prop?.["type"] === "string" && !("minLength" in prop)) {
2845
- prop["minLength"] = 1;
2846
- } else if (prop?.["type"] === "object") {
2847
- enforceRequiredMinLength(prop);
2848
- }
2849
- }
2850
- }, "enforceRequiredMinLength");
2851
-
2852
- // src/lib/crud/loader/table-schema.builder.ts
2853
- var isBoolean = /* @__PURE__ */ __name((col) => col.fieldInput?.type === "boolean" || col.columnType === "boolean", "isBoolean");
2854
- var isRelation = /* @__PURE__ */ __name((col) => col.fieldInput?.format === "relation", "isRelation");
2855
- var isAutocomplete = /* @__PURE__ */ __name((col) => col.fieldInput?.type === "autocomplete", "isAutocomplete");
2856
- var isRecordCell = /* @__PURE__ */ __name((col) => isRelation(col) || isAutocomplete(col), "isRecordCell");
2857
- var isDateRange = /* @__PURE__ */ __name((col) => col.fieldInput?.format === "date-range", "isDateRange");
2858
- var deriveSortId = /* @__PURE__ */ __name((col) => {
2859
- if (col.sortable === false) return null;
2860
- if (col.sortId) return col.sortId;
2861
- const base = col.column ?? col.id;
2862
- const fi = col.fieldInput;
2863
- const opts = fi?.options ?? {};
2864
- const isRelation2 = fi?.format === "relation" || !!fi?.relationType || fi?.type === "autocomplete" || typeof opts.resource === "string";
2865
- if (isRelation2) {
2866
- const key = (typeof col.displayKey === "string" ? col.displayKey : void 0) ?? (typeof opts.displayKey === "string" ? opts.displayKey : void 0) ?? (typeof opts.labelKey === "string" ? opts.labelKey : void 0);
2867
- if (!key) return null;
2868
- const path2 = key.includes(".") ? key : `${base}.${key}`;
2869
- return path2.endsWith(".label") ? path2.slice(0, -".label".length) : path2;
2870
- }
2871
- if (!col.displayKey) return base;
2872
- const path = `${base}.${col.displayKey}`;
2873
- const isValueLabel = !!col.enum || opts.emitObject === true;
2874
- if (isValueLabel && path.endsWith(".label")) return path.slice(0, -".label".length);
2875
- return path;
2876
- }, "deriveSortId");
2877
- var resolveDefaultSort = /* @__PURE__ */ __name((tableCols, allColumns) => {
2878
- const isSortable = /* @__PURE__ */ __name((c) => c.sortable !== false, "isSortable");
2879
- const sortCol = tableCols.find((c) => c.defaultSort && isSortable(c)) ?? tableCols.find(isSortable) ?? allColumns?.find((c) => c.idField);
2880
- return sortCol ? deriveSortId(sortCol) ?? sortCol.id : void 0;
2881
- }, "resolveDefaultSort");
2882
- var SHARED_CELL_OPTION_KEYS = [
2883
- "values",
2884
- "storeValue",
2885
- "uri",
2886
- "resourceUri",
2887
- "schemasUri"
2888
- ];
2889
- var pickSharedCellOptions = /* @__PURE__ */ __name((col) => {
2890
- const options = col.fieldInput?.options ?? {};
2891
- return Object.fromEntries(SHARED_CELL_OPTION_KEYS.filter((key) => options[key] !== void 0).map((key) => [
2892
- key,
2893
- options[key]
2894
- ]));
2895
- }, "pickSharedCellOptions");
2896
- var buildTableUiSchema = /* @__PURE__ */ __name((cols) => {
2897
- const layout = TableBuilder.init().addControls(...cols.map((col) => {
2898
- const cellBuilder = isBoolean(col) ? BooleanCellBuilder : TextCellBuilder;
2899
- let builder = cellBuilder.properties(col.id);
2900
- if (col.displayKey) builder = builder.key(col.displayKey);
2901
- if (col.sortId) builder = builder.setSortId(col.sortId);
2902
- return builder;
2903
- })).build();
2904
- const colMap = Object.fromEntries(cols.map((c) => [
2905
- c.id,
2906
- c
2907
- ]));
2908
- layout.elements = layout.elements.map((el) => {
2909
- const id = el.scope?.replace("#/properties/", "");
2910
- const col = id ? colMap[id] : void 0;
2911
- if (!col) return el;
2912
- const fieldInputOptions = isRecordCell(col) || isDateRange(col) ? col.fieldInput?.options ?? {} : pickSharedCellOptions(col);
2913
- const dataPathOption = col.column ? {
2914
- dataPath: col.column
2915
- } : {};
2916
- const derivedSortId = isRecordCell(col) || isDateRange(col) ? null : deriveSortId(col);
2917
- const sortOptions = derivedSortId ? {
2918
- sortId: derivedSortId
2919
- } : {
2920
- sortable: false
2921
- };
2922
- const relationTypeOption = col.fieldInput?.relationType ? {
2923
- relationType: col.fieldInput.relationType
2924
- } : {};
2925
- return {
2926
- ...el,
2927
- options: {
2928
- ...el.options ?? {},
2929
- ...fieldInputOptions,
2930
- ...dataPathOption,
2931
- ...sortOptions,
2932
- ...relationTypeOption,
2933
- ...isDateRange(col) && {
2934
- format: "date-range"
2935
- },
2936
- label: col.label
2937
- },
2938
- ...isRecordCell(col) && {
2939
- type: "RecordCell"
2940
- },
2941
- ...isDateRange(col) && {
2942
- type: "Control"
2943
- }
2944
- };
2945
- });
2946
- return layout;
2947
- }, "buildTableUiSchema");
2948
-
2949
- // src/lib/crud/loader/view.builders.ts
2950
- var patchFilterProperties = /* @__PURE__ */ __name((jsonSchema, columns) => {
2951
- if (!columns?.length) return;
2952
- const properties = jsonSchema.properties;
2953
- if (!properties) return;
2954
- for (const col of columns) {
2955
- if (col.fieldInput?.format === "date-range") {
2956
- delete properties[col.id];
2957
- const opts = col.fieldInput?.options ?? {};
2958
- const base = col.label ?? col.id;
2959
- const fromField = opts["fromField"] ?? "from";
2960
- const toField = opts["toField"] ?? "to";
2961
- const dateProp = /* @__PURE__ */ __name((title) => ({
2962
- type: "string",
2963
- format: "date",
2964
- title,
2965
- "x-field-type": "date"
2966
- }), "dateProp");
2967
- properties[`${col.id}->${fromField}`] = dateProp(opts["fromLabel"] ?? `${base} (from)`);
2968
- properties[`${col.id}->${toField}`] = dateProp(opts["toLabel"] ?? `${base} (to)`);
2969
- continue;
2970
- }
2971
- const prop = properties[col.id];
2972
- if (!prop) continue;
2973
- prop.title = col.label ?? col.id;
2974
- const values = col.fieldInput?.options?.["values"];
2975
- if (values) {
2976
- prop["x-values"] = values;
2977
- }
2978
- const ft = col.fieldInput?.type;
2979
- if (ft === "select" || col.enum) {
2980
- prop["x-field-type"] = "enum";
2981
- } else if (ft === "number" || prop.type === "number" || prop.type === "integer") {
2982
- prop["x-field-type"] = "number";
2983
- } else if (prop.format === "date-time" || prop.format === "date") {
2984
- prop["x-field-type"] = "date";
2985
- } else if (prop.type === "boolean") {
2986
- prop["x-field-type"] = "boolean";
2987
- }
2988
- }
2989
- }, "patchFilterProperties");
2990
- var colPosition = /* @__PURE__ */ __name((col, i) => col.fieldInput?.position ?? i, "colPosition");
2991
- var sortByPosition = /* @__PURE__ */ __name((cols) => cols.map((col, i) => ({
2992
- col,
2993
- i
2994
- })).sort((a, b) => colPosition(a.col, a.i) - colPosition(b.col, b.i)).map(({ col }) => col), "sortByPosition");
2995
- var toViewColumn = /* @__PURE__ */ __name((col) => ({
2996
- id: col.id,
2997
- ...col.label && {
2998
- label: col.label
2999
- },
3000
- ...col.sortable != null && {
3001
- sortable: col.sortable
3002
- },
3003
- ...col.searchable != null && {
3004
- searchable: col.searchable
3005
- },
3006
- ...col.fieldInput && {
3007
- fieldInput: col.fieldInput
3008
- }
3009
- }), "toViewColumn");
3010
- var buildView = /* @__PURE__ */ __name((schema, columns, visible, buildUiSchema, sort = false, schemaVisible) => {
3011
- if (!schema || !columns?.length) return void 0;
3012
- const visibleCols = sort ? sortByPosition(columns.filter(visible)) : columns.filter(visible);
3013
- if (!visibleCols.length) return void 0;
3014
- const schemaCols = schemaVisible ? columns.filter((c) => visible(c) || schemaVisible(c)) : visibleCols;
3015
- const schemaIds = schemaCols.map((c) => c.id);
3016
- const mask = Object.fromEntries(schemaIds.map((id) => [
3017
- id,
3018
- true
3019
- ]));
3020
- const picked = schema.pick(mask);
3021
- const jsonSchema = (0, import_zod8.toJSONSchema)(picked, {
3022
- target: "draft-07",
3023
- ...jsonSchemaOpts
3024
- });
3025
- allowAdditionalProperties(jsonSchema);
3026
- dropNullableFromRequired2(jsonSchema);
3027
- enforceRequiredMinLength(jsonSchema);
3028
- return {
3029
- json_schema: jsonSchema,
3030
- ui_schema: buildUiSchema(visibleCols),
3031
- columns: visibleCols.map(toViewColumn)
3032
- };
3033
- }, "buildView");
3516
+ // src/lib/crud/builder/calculated-columns.builder.ts
3034
3517
  var isVisibleInMode = /* @__PURE__ */ __name((c, mode) => mode === "table" ? !c.hiddenInTable : !c.hiddenInView, "isVisibleInMode");
3035
3518
  var buildCalculatedElement = /* @__PURE__ */ __name((c, mode) => mode === "table" ? {
3036
3519
  type: c.type === "boolean" ? "BooleanCell" : "TextCell",
@@ -3109,6 +3592,78 @@ var injectCalculatedColumnsIntoView = /* @__PURE__ */ __name((viewConfig, calcul
3109
3592
  }, "injectCalculatedColumnsIntoView");
3110
3593
  var injectCalculatedColumns = /* @__PURE__ */ __name((tableView, calculated) => injectCalculatedColumnsIntoView(tableView, calculated, "table"), "injectCalculatedColumns");
3111
3594
  var injectCalculatedColumnsToView = /* @__PURE__ */ __name((viewConfig, calculated) => injectCalculatedColumnsIntoView(viewConfig, calculated, "view"), "injectCalculatedColumnsToView");
3595
+
3596
+ // src/lib/crud/builder/view.builder.ts
3597
+ var import_zod20 = require("zod");
3598
+ var patchFilterProperties = /* @__PURE__ */ __name((jsonSchema, columns) => {
3599
+ if (!columns?.length) return;
3600
+ const properties = jsonSchema.properties;
3601
+ if (!properties) return;
3602
+ for (const col of columns) {
3603
+ if (col.fieldInput?.format === "date-range") {
3604
+ delete properties[col.id];
3605
+ const opts = col.fieldInput?.options ?? {};
3606
+ const base = col.label ?? col.id;
3607
+ const fromField = opts["fromField"] ?? "from";
3608
+ const toField = opts["toField"] ?? "to";
3609
+ const dateProp = /* @__PURE__ */ __name((title) => ({
3610
+ type: "string",
3611
+ format: "date",
3612
+ title,
3613
+ "x-field-type": "date"
3614
+ }), "dateProp");
3615
+ properties[`${col.id}->${fromField}`] = dateProp(opts["fromLabel"] ?? `${base} (from)`);
3616
+ properties[`${col.id}->${toField}`] = dateProp(opts["toLabel"] ?? `${base} (to)`);
3617
+ continue;
3618
+ }
3619
+ const prop = properties[col.id];
3620
+ if (!prop) continue;
3621
+ prop.title = col.label ?? col.id;
3622
+ const values = col.fieldInput?.options?.["values"];
3623
+ if (values) {
3624
+ prop["x-values"] = values;
3625
+ }
3626
+ const ft = col.fieldInput?.type;
3627
+ if (ft === "select" || col.enum) {
3628
+ prop["x-field-type"] = "enum";
3629
+ } else if (ft === "number" || prop.type === "number" || prop.type === "integer") {
3630
+ prop["x-field-type"] = "number";
3631
+ } else if (prop.format === "date-time" || prop.format === "date") {
3632
+ prop["x-field-type"] = "date";
3633
+ } else if (prop.type === "boolean") {
3634
+ prop["x-field-type"] = "boolean";
3635
+ }
3636
+ }
3637
+ }, "patchFilterProperties");
3638
+ var buildView = /* @__PURE__ */ __name((schema, columns, visible, buildUiSchema, sort = false, schemaVisible) => {
3639
+ if (!schema || !columns?.length) return void 0;
3640
+ const visibleCols = sort ? sortByPosition(columns.filter(visible)) : columns.filter(visible);
3641
+ if (!visibleCols.length) return void 0;
3642
+ const schemaCols = (schemaVisible ? columns.filter((c) => visible(c) || schemaVisible(c)) : visibleCols).filter((c) => !isRelation(c));
3643
+ const schemaIds = schemaCols.map((c) => c.id);
3644
+ const mask = Object.fromEntries(schemaIds.map((id) => [
3645
+ id,
3646
+ true
3647
+ ]));
3648
+ const picked = schema.pick(mask);
3649
+ const jsonSchema = (0, import_zod20.toJSONSchema)(picked, {
3650
+ target: "draft-07",
3651
+ ...jsonSchemaOpts
3652
+ });
3653
+ applySchemaTransforms(jsonSchema);
3654
+ if (schemaVisible) {
3655
+ const nonEditableIds = new Set(schemaCols.filter((c) => c.idField || c.createable === false && c.updateable === false).map((c) => c.id));
3656
+ const required = jsonSchema["required"];
3657
+ if (Array.isArray(required) && nonEditableIds.size) {
3658
+ jsonSchema["required"] = required.filter((k) => !nonEditableIds.has(k));
3659
+ }
3660
+ }
3661
+ return {
3662
+ json_schema: jsonSchema,
3663
+ ui_schema: buildUiSchema(visibleCols),
3664
+ columns: visibleCols.map(toViewColumn)
3665
+ };
3666
+ }, "buildView");
3112
3667
  var emptyTableView = /* @__PURE__ */ __name(() => ({
3113
3668
  json_schema: {
3114
3669
  type: "object",
@@ -3127,7 +3682,7 @@ var buildViews = /* @__PURE__ */ __name((schema, columns) => {
3127
3682
  } else if (columns?.length) {
3128
3683
  views.table = emptyTableView();
3129
3684
  }
3130
- const form = buildView(schema, columns, (c) => !c.hiddenInForm, buildFormUiSchema, true, (c) => c.createable === true || c.updateable === true);
3685
+ const form = buildView(schema, columns, (c) => !c.hiddenInForm, buildFormUiSchema, true, (c) => !c.idField && (c.createable === true || c.updateable === true));
3131
3686
  if (form) views.form = form;
3132
3687
  const filter = buildView(schema, columns, (c) => !!c.filterable, buildFormUiSchema, true);
3133
3688
  if (filter) {
@@ -3147,7 +3702,6 @@ var buildViewsFromColumns = /* @__PURE__ */ __name((columns) => {
3147
3702
  if (!properties[c.column]) {
3148
3703
  properties[c.column] = {
3149
3704
  type: "object",
3150
- additionalProperties: true,
3151
3705
  properties: {}
3152
3706
  };
3153
3707
  }
@@ -3158,7 +3712,6 @@ var buildViewsFromColumns = /* @__PURE__ */ __name((columns) => {
3158
3712
  if (!target[segment]) {
3159
3713
  target[segment] = {
3160
3714
  type: "object",
3161
- additionalProperties: true,
3162
3715
  properties: {}
3163
3716
  };
3164
3717
  }
@@ -3169,17 +3722,22 @@ var buildViewsFromColumns = /* @__PURE__ */ __name((columns) => {
3169
3722
  title: c.label ?? c.id
3170
3723
  };
3171
3724
  } else {
3725
+ const opts = c.fieldInput?.options;
3726
+ const isObject = opts?.emitObject === true || c.fieldInput?.type === "autocomplete";
3172
3727
  properties[c.id] = {
3173
- type: c.columnType ?? "string",
3728
+ ...isObject ? {} : {
3729
+ type: c.columnType ?? "string"
3730
+ },
3174
3731
  title: c.label ?? c.id
3175
3732
  };
3176
3733
  }
3177
3734
  }
3178
- return {
3735
+ const schema = {
3179
3736
  type: "object",
3180
- additionalProperties: true,
3181
3737
  properties
3182
3738
  };
3739
+ applySchemaTransforms(schema);
3740
+ return schema;
3183
3741
  }, "buildJsonSchema");
3184
3742
  const fixNestedScopes = /* @__PURE__ */ __name((uiSchema, cols) => {
3185
3743
  const colMap = Object.fromEntries(cols.map((c) => [
@@ -3229,33 +3787,223 @@ var buildViewsFromColumns = /* @__PURE__ */ __name((columns) => {
3229
3787
  return Object.keys(views).length ? views : void 0;
3230
3788
  }, "buildViewsFromColumns");
3231
3789
 
3232
- // src/lib/crud/loader/json-adapter.ts
3790
+ // src/lib/crud/enum-registry/enum-registry.types.ts
3791
+ var import_zod21 = require("zod");
3792
+ var EnumEntrySchema = import_zod21.z.object({
3793
+ value: import_zod21.z.unknown(),
3794
+ label: import_zod21.z.string()
3795
+ });
3796
+ var EnumRegistrySchema = import_zod21.z.record(import_zod21.z.string(), import_zod21.z.array(EnumEntrySchema)).default({});
3797
+
3798
+ // src/lib/crud/enum-registry/enum-registry.loader.ts
3799
+ var import_node_fs3 = require("fs");
3800
+ var import_node_path5 = require("path");
3801
+ var ENUMS_FILE = "crouton.enums.json";
3802
+ var loadEnumRegistry = /* @__PURE__ */ __name((startDir, enumsFile) => {
3803
+ let file = enumsFile;
3804
+ if (!file) {
3805
+ let dir = startDir;
3806
+ while (true) {
3807
+ const candidate = (0, import_node_path5.join)(dir, ENUMS_FILE);
3808
+ if ((0, import_node_fs3.existsSync)(candidate)) {
3809
+ file = candidate;
3810
+ break;
3811
+ }
3812
+ const parent = (0, import_node_path5.dirname)(dir);
3813
+ if (parent === dir) break;
3814
+ dir = parent;
3815
+ }
3816
+ }
3817
+ if (!file || !(0, import_node_fs3.existsSync)(file)) return EnumRegistrySchema.parse(void 0);
3818
+ try {
3819
+ return EnumRegistrySchema.parse(JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8")));
3820
+ } catch {
3821
+ return EnumRegistrySchema.parse(void 0);
3822
+ }
3823
+ }, "loadEnumRegistry");
3824
+
3825
+ // src/lib/crud/enum-registry/enum-registry.injector.ts
3826
+ var injectEnumValues = /* @__PURE__ */ __name((columns, enums) => {
3827
+ if (!columns) return;
3828
+ for (const col of columns) {
3829
+ if (!col.enum) continue;
3830
+ const values = enums[col.enum];
3831
+ if (!values) continue;
3832
+ col.fieldInput = col.fieldInput ?? {
3833
+ type: "select"
3834
+ };
3835
+ const options = col.fieldInput.options ?? {};
3836
+ if (!("values" in options)) options.values = values;
3837
+ col.fieldInput.options = options;
3838
+ }
3839
+ }, "injectEnumValues");
3840
+
3841
+ // src/lib/crud/adapter/relation-type.ts
3842
+ var import_zod22 = require("zod");
3843
+ var unwrapZodType = /* @__PURE__ */ __name((type) => {
3844
+ if (type instanceof import_zod22.ZodOptional || type instanceof import_zod22.ZodNullable) {
3845
+ return unwrapZodType(type.unwrap());
3846
+ }
3847
+ return type;
3848
+ }, "unwrapZodType");
3849
+ var deriveRelationType = /* @__PURE__ */ __name((schema, columnId) => {
3850
+ if (!schema) return void 0;
3851
+ const field = schema.shape[columnId];
3852
+ if (!field) return void 0;
3853
+ const inner = unwrapZodType(field);
3854
+ return inner instanceof import_zod22.ZodArray ? "oneToMany" : "manyToOne";
3855
+ }, "deriveRelationType");
3856
+ var deriveRelationTypeFromColumns = /* @__PURE__ */ __name((col, cols) => {
3857
+ const base = col.column ?? col.id;
3858
+ const fkNames = /* @__PURE__ */ new Set([
3859
+ `${base}_id`,
3860
+ `${col.id}_id`
3861
+ ]);
3862
+ return cols.some((c) => fkNames.has(c.id)) ? "manyToOne" : "oneToMany";
3863
+ }, "deriveRelationTypeFromColumns");
3864
+ var enrichRelationTypes = /* @__PURE__ */ __name((columns, schema) => {
3865
+ if (!schema) return columns;
3866
+ return columns.map((col) => {
3867
+ const fi = col.fieldInput;
3868
+ if (!fi) return col;
3869
+ const isRelationField = fi.type === "autocomplete" || fi.format === "relation";
3870
+ if (!isRelationField) return col;
3871
+ if (fi.relationType) return col;
3872
+ const derived = deriveRelationType(schema, col.id) ?? deriveRelationTypeFromColumns(col, columns);
3873
+ if (!derived) return col;
3874
+ return {
3875
+ ...col,
3876
+ fieldInput: {
3877
+ ...fi,
3878
+ relationType: derived
3879
+ }
3880
+ };
3881
+ });
3882
+ }, "enrichRelationTypes");
3883
+
3884
+ // src/lib/crud/resource/ReadResourceJson.ts
3233
3885
  var import_node_fs4 = require("fs");
3234
- var import_node_path5 = require("path");
3235
- var resolveChildResource = /* @__PURE__ */ __name((resourcePath, parentDir) => {
3236
- const directPath = (0, import_node_path5.resolve)(parentDir, resourcePath);
3237
- if (resourcePath.endsWith(".json") && (0, import_node_fs4.existsSync)(directPath)) {
3238
- try {
3239
- return {
3240
- json: JSON.parse((0, import_node_fs4.readFileSync)(directPath, "utf-8")),
3241
- dir: (0, import_node_path5.dirname)(directPath)
3242
- };
3243
- } catch {
3244
- return void 0;
3245
- }
3886
+ var import_node_path6 = require("path");
3887
+ var readResourceJson = /* @__PURE__ */ __name((jsonPath) => {
3888
+ if (!(0, import_node_fs4.existsSync)(jsonPath)) return void 0;
3889
+ const fileContent = JSON.parse((0, import_node_fs4.readFileSync)(jsonPath, "utf-8"));
3890
+ const resource = ResourceJsonSchema.safeParse(fileContent);
3891
+ if (resource.error) {
3892
+ console.error(resource.error);
3893
+ throw new Error(`Resource cannot be parsed ${jsonPath}`);
3246
3894
  }
3247
- const childName = resourcePath.replace(/^\.\//, "").replace(/\.resource$/, "");
3248
- const childJsonPath = (0, import_node_path5.resolve)((0, import_node_path5.dirname)(parentDir), childName, "resource.json");
3249
- if (!(0, import_node_fs4.existsSync)(childJsonPath)) return void 0;
3895
+ return {
3896
+ json: resource.data,
3897
+ dir: (0, import_node_path6.dirname)(jsonPath)
3898
+ };
3899
+ }, "readResourceJson");
3900
+
3901
+ // src/lib/crud/adapter/resource-resolver.ts
3902
+ var import_node_fs5 = require("fs");
3903
+ var import_node_path7 = require("path");
3904
+ var resolveChildResource = /* @__PURE__ */ __name((resourcePath, parentDir) => {
3905
+ const directPath = (0, import_node_path7.resolve)(parentDir, resourcePath);
3250
3906
  try {
3251
- return {
3252
- json: JSON.parse((0, import_node_fs4.readFileSync)(childJsonPath, "utf-8")),
3253
- dir: (0, import_node_path5.dirname)(childJsonPath)
3254
- };
3907
+ if (resourcePath.endsWith(".json") && (0, import_node_fs5.existsSync)(directPath)) {
3908
+ return readResourceJson(directPath);
3909
+ }
3910
+ const childName = resourcePath.replace(/^\.\//, "").replace(/\.resource$/, "");
3911
+ const childJsonPath = (0, import_node_path7.resolve)((0, import_node_path7.dirname)(parentDir), childName, "resource.json");
3912
+ return readResourceJson(childJsonPath);
3255
3913
  } catch {
3256
3914
  return void 0;
3257
3915
  }
3258
3916
  }, "resolveChildResource");
3917
+
3918
+ // src/lib/crud/adapter/column-enrichment.ts
3919
+ var enrichActionColumns = /* @__PURE__ */ __name((columns, parentRoute, subResources, baseUrl) => {
3920
+ if (!columns) return columns;
3921
+ const base = baseUrl ?? "";
3922
+ return columns.map((col) => {
3923
+ if (col.fieldInput?.format !== "relation") return col;
3924
+ const sub = subResources.find((s) => s.column === col.id);
3925
+ if (!sub) return col;
3926
+ return {
3927
+ ...col,
3928
+ fieldInput: {
3929
+ ...col.fieldInput,
3930
+ options: {
3931
+ ...col.fieldInput.options,
3932
+ uri: `${base}/${parentRoute}/{id}/${sub.childRoute}`,
3933
+ resourceUri: `${base}/${sub.childRoute}`,
3934
+ ...sub.views && {
3935
+ resource: `${base}/${parentRoute}/${sub.childRoute}/schemas`
3936
+ }
3937
+ }
3938
+ }
3939
+ };
3940
+ });
3941
+ }, "enrichActionColumns");
3942
+ var enrichResourceRefColumns = /* @__PURE__ */ __name((columns, parentDir, baseUrl) => {
3943
+ if (!columns || !parentDir) return columns;
3944
+ const base = baseUrl ?? "";
3945
+ return columns.map((col) => {
3946
+ if (!col.fieldInput?.resource || col.fieldInput.format === "relation") return col;
3947
+ const childResolved = resolveChildResource(col.fieldInput.resource, parentDir);
3948
+ const childRoute = childResolved?.json?.route ?? col.fieldInput.resource.replace(/^\.\//, "").replace(/\.resource$/, "");
3949
+ return {
3950
+ ...col,
3951
+ fieldInput: {
3952
+ ...col.fieldInput,
3953
+ options: {
3954
+ ...col.fieldInput.options,
3955
+ resourceUri: `${base}/${childRoute}`,
3956
+ schemasUri: `${base}/${childRoute}/schemas`
3957
+ }
3958
+ }
3959
+ };
3960
+ });
3961
+ }, "enrichResourceRefColumns");
3962
+ var enrichNestedRelationColumns = /* @__PURE__ */ __name((cols, dir, baseUrl) => {
3963
+ if (!cols || !dir) return cols;
3964
+ const base = baseUrl ?? "";
3965
+ return cols.map((col) => {
3966
+ if (col.fieldInput?.format !== "relation" || !col.fieldInput.resource) return col;
3967
+ const resolved = resolveChildResource(col.fieldInput.resource, dir);
3968
+ const targetRoute = resolved?.json?.route ?? col.fieldInput.resource.replace(/^\.\//, "").replace(/\/resource\.json$/, "").replace(/\.resource$/, "");
3969
+ const relationType = col.fieldInput.relationType ?? deriveRelationTypeFromColumns(col, cols);
3970
+ return {
3971
+ ...col,
3972
+ fieldInput: {
3973
+ ...col.fieldInput,
3974
+ relationType,
3975
+ options: {
3976
+ ...col.fieldInput.options,
3977
+ uri: `${base}/${targetRoute}`,
3978
+ resourceUri: `${base}/${targetRoute}`,
3979
+ resource: `${base}/${targetRoute}/schemas`
3980
+ }
3981
+ }
3982
+ };
3983
+ });
3984
+ }, "enrichNestedRelationColumns");
3985
+ var enrichIncludeWithSort = /* @__PURE__ */ __name((include, columns) => {
3986
+ if (!include?.length) return include;
3987
+ return include.map((entry) => {
3988
+ const relationName = typeof entry === "string" ? entry : entry.relation;
3989
+ const col = columns.find((c) => {
3990
+ const opts2 = c.fieldInput?.options;
3991
+ return (c.column ?? c.id) === relationName && opts2?.sort;
3992
+ });
3993
+ if (!col) return entry;
3994
+ const opts = col.fieldInput.options;
3995
+ const orderBy = buildChildSortClause(opts.sort, opts.sortDir ?? "asc");
3996
+ return typeof entry === "string" ? {
3997
+ relation: entry,
3998
+ orderBy
3999
+ } : {
4000
+ ...entry,
4001
+ orderBy
4002
+ };
4003
+ });
4004
+ }, "enrichIncludeWithSort");
4005
+
4006
+ // src/lib/crud/adapter/column-transforms.ts
3259
4007
  var expandExtendColumns = /* @__PURE__ */ __name((columns, dirPath) => {
3260
4008
  if (!dirPath) return columns;
3261
4009
  const result = [];
@@ -3270,7 +4018,7 @@ var expandExtendColumns = /* @__PURE__ */ __name((columns, dirPath) => {
3270
4018
  result.push(col);
3271
4019
  continue;
3272
4020
  }
3273
- const refColumns = normalizeColumns(resolved.json.columns) ?? [];
4021
+ const refColumns = resolved.json.columns;
3274
4022
  const parentColumnKey = col.column ?? col.id;
3275
4023
  for (const refCol of refColumns) {
3276
4024
  if (refCol.idField) continue;
@@ -3331,37 +4079,8 @@ var applyRelationFormatDefault = /* @__PURE__ */ __name((cols) => cols?.map((col
3331
4079
  }
3332
4080
  return col;
3333
4081
  }), "applyRelationFormatDefault");
3334
- var deriveRelationTypeFromColumns = /* @__PURE__ */ __name((col, cols) => {
3335
- const base = col.column ?? col.id;
3336
- const fkNames = /* @__PURE__ */ new Set([
3337
- `${base}_id`,
3338
- `${col.id}_id`
3339
- ]);
3340
- return cols.some((c) => fkNames.has(c.id)) ? "manyToOne" : "oneToMany";
3341
- }, "deriveRelationTypeFromColumns");
3342
- var enrichNestedRelationColumns = /* @__PURE__ */ __name((cols, dir, baseUrl) => {
3343
- if (!cols || !dir) return cols;
3344
- const base = baseUrl ?? "";
3345
- return cols.map((col) => {
3346
- if (col.fieldInput?.format !== "relation" || !col.fieldInput.resource) return col;
3347
- const resolved = resolveChildResource(col.fieldInput.resource, dir);
3348
- const targetRoute = resolved?.json?.route ?? col.fieldInput.resource.replace(/^\.\//, "").replace(/\/resource\.json$/, "").replace(/\.resource$/, "");
3349
- const relationType = col.fieldInput.relationType ?? deriveRelationTypeFromColumns(col, cols);
3350
- return {
3351
- ...col,
3352
- fieldInput: {
3353
- ...col.fieldInput,
3354
- relationType,
3355
- options: {
3356
- ...col.fieldInput.options,
3357
- uri: `${base}/${targetRoute}`,
3358
- resourceUri: `${base}/${targetRoute}`,
3359
- resource: `${base}/${targetRoute}/schemas`
3360
- }
3361
- }
3362
- };
3363
- });
3364
- }, "enrichNestedRelationColumns");
4082
+
4083
+ // src/lib/crud/adapter/sub-resource.builder.ts
3365
4084
  var buildSubResources = /* @__PURE__ */ __name((columns, parentRoute, parentModel, parentDir, enums = {}, baseUrl) => {
3366
4085
  if (!columns || !parentDir) return [];
3367
4086
  return columns.filter((c) => c.fieldInput?.format === "relation" && c.fieldInput?.resource).map((c) => {
@@ -3369,7 +4088,7 @@ var buildSubResources = /* @__PURE__ */ __name((columns, parentRoute, parentMode
3369
4088
  const childJson = childResolved?.json;
3370
4089
  const childDir = childResolved?.dir;
3371
4090
  const childRoute = childJson?.route ?? c.fieldInput.resource.replace(/^\.\//, "").replace(/\.resource$/, "");
3372
- const rawChildColumns = childJson ? normalizeColumns(childJson.columns) : void 0;
4091
+ const rawChildColumns = childJson?.columns;
3373
4092
  const expandedChildColumns = rawChildColumns ? expandExtendColumns(rawChildColumns, childDir) : void 0;
3374
4093
  const childColumns = applyRelationFormatDefault(expandedChildColumns) ?? expandedChildColumns;
3375
4094
  injectEnumValues(childColumns, enums);
@@ -3431,71 +4150,10 @@ var buildSubResources = /* @__PURE__ */ __name((columns, parentRoute, parentMode
3431
4150
  };
3432
4151
  });
3433
4152
  }, "buildSubResources");
3434
- var enrichActionColumns = /* @__PURE__ */ __name((columns, parentRoute, subResources, baseUrl) => {
3435
- if (!columns) return columns;
3436
- const base = baseUrl ?? "";
3437
- return columns.map((col) => {
3438
- if (col.fieldInput?.format !== "relation") return col;
3439
- const sub = subResources.find((s) => s.column === col.id);
3440
- if (!sub) return col;
3441
- return {
3442
- ...col,
3443
- fieldInput: {
3444
- ...col.fieldInput,
3445
- options: {
3446
- ...col.fieldInput.options,
3447
- uri: `${base}/${parentRoute}/{id}/${sub.childRoute}`,
3448
- resourceUri: `${base}/${sub.childRoute}`,
3449
- ...sub.views && {
3450
- resource: `${base}/${parentRoute}/${sub.childRoute}/schemas`
3451
- }
3452
- }
3453
- }
3454
- };
3455
- });
3456
- }, "enrichActionColumns");
3457
- var enrichResourceRefColumns = /* @__PURE__ */ __name((columns, parentDir, baseUrl) => {
3458
- if (!columns || !parentDir) return columns;
3459
- const base = baseUrl ?? "";
3460
- return columns.map((col) => {
3461
- if (!col.fieldInput?.resource || col.fieldInput.format === "relation") return col;
3462
- const childResolved = resolveChildResource(col.fieldInput.resource, parentDir);
3463
- const childRoute = childResolved?.json?.route ?? col.fieldInput.resource.replace(/^\.\//, "").replace(/\.resource$/, "");
3464
- return {
3465
- ...col,
3466
- fieldInput: {
3467
- ...col.fieldInput,
3468
- options: {
3469
- ...col.fieldInput.options,
3470
- resourceUri: `${base}/${childRoute}`,
3471
- schemasUri: `${base}/${childRoute}/schemas`
3472
- }
3473
- }
3474
- };
3475
- });
3476
- }, "enrichResourceRefColumns");
3477
- var enrichIncludeWithSort = /* @__PURE__ */ __name((include, columns) => {
3478
- if (!include?.length) return include;
3479
- return include.map((entry) => {
3480
- const relationName = typeof entry === "string" ? entry : entry.relation;
3481
- const col = columns.find((c) => {
3482
- const opts2 = c.fieldInput?.options;
3483
- return (c.column ?? c.id) === relationName && opts2?.sort;
3484
- });
3485
- if (!col) return entry;
3486
- const opts = col.fieldInput.options;
3487
- const orderBy = buildChildSortClause(opts.sort, opts.sortDir ?? "asc");
3488
- return typeof entry === "string" ? {
3489
- relation: entry,
3490
- orderBy
3491
- } : {
3492
- ...entry,
3493
- orderBy
3494
- };
3495
- });
3496
- }, "enrichIncludeWithSort");
4153
+
4154
+ // src/lib/crud/adapter/json-adapter.ts
3497
4155
  var fromJson = /* @__PURE__ */ __name((json, schema, hooks, dirPath, baseUrl, actions, tableActions, enums = {}) => {
3498
- const rawColumns = expandExtendColumns(normalizeColumns(json.columns) ?? [], dirPath);
4156
+ const rawColumns = expandExtendColumns(json.columns, dirPath);
3499
4157
  const columns = enrichRelationTypes(applyRelationFormatDefault(rawColumns) ?? rawColumns, schema);
3500
4158
  injectEnumValues(columns, enums);
3501
4159
  const subResources = buildSubResources(columns, json.route, json.model, dirPath, enums, baseUrl);
@@ -3539,22 +4197,14 @@ var fromJson = /* @__PURE__ */ __name((json, schema, hooks, dirPath, baseUrl, ac
3539
4197
  delete: true
3540
4198
  }
3541
4199
  };
3542
- const display = {
3543
- mode: json.display?.mode === "page" ? "page" : "modal",
3544
- customComponent: json.display?.customComponent ?? null
3545
- };
3546
4200
  return {
4201
+ ...json,
3547
4202
  name: json.name,
3548
4203
  route: json.route,
3549
4204
  model: json.model,
3550
4205
  tag: json.tag,
3551
- display,
3552
- ...json.title && {
3553
- title: json.title
3554
- },
3555
- ...json.sidebar && {
3556
- sidebar: json.sidebar
3557
- },
4206
+ sidebar: json.sidebar,
4207
+ display: json.display,
3558
4208
  ...json.idType && {
3559
4209
  idType: json.idType
3560
4210
  },
@@ -3597,38 +4247,6 @@ var fromJson = /* @__PURE__ */ __name((json, schema, hooks, dirPath, baseUrl, ac
3597
4247
  }
3598
4248
  };
3599
4249
  }, "fromJson");
3600
- var unwrapZodType = /* @__PURE__ */ __name((type) => {
3601
- if (type instanceof import_zod9.ZodOptional || type instanceof import_zod9.ZodNullable) {
3602
- return unwrapZodType(type.unwrap());
3603
- }
3604
- return type;
3605
- }, "unwrapZodType");
3606
- var deriveRelationType = /* @__PURE__ */ __name((schema, columnId) => {
3607
- if (!schema) return void 0;
3608
- const field = schema.shape[columnId];
3609
- if (!field) return void 0;
3610
- const inner = unwrapZodType(field);
3611
- return inner instanceof import_zod9.ZodArray ? "oneToMany" : "manyToOne";
3612
- }, "deriveRelationType");
3613
- var enrichRelationTypes = /* @__PURE__ */ __name((columns, schema) => {
3614
- if (!schema) return columns;
3615
- return columns.map((col) => {
3616
- const fi = col.fieldInput;
3617
- if (!fi) return col;
3618
- const isRelationField = fi.type === "autocomplete" || fi.format === "relation";
3619
- if (!isRelationField) return col;
3620
- if (fi.relationType) return col;
3621
- const derived = deriveRelationType(schema, col.id) ?? deriveRelationTypeFromColumns(col, columns);
3622
- if (!derived) return col;
3623
- return {
3624
- ...col,
3625
- fieldInput: {
3626
- ...fi,
3627
- relationType: derived
3628
- }
3629
- };
3630
- });
3631
- }, "enrichRelationTypes");
3632
4250
  var buildLookup = /* @__PURE__ */ __name((columns) => {
3633
4251
  if (!columns) return void 0;
3634
4252
  const keyCol = columns.find((c) => c.idField);
@@ -3642,41 +4260,65 @@ var buildLookup = /* @__PURE__ */ __name((columns) => {
3642
4260
  };
3643
4261
  }, "buildLookup");
3644
4262
 
3645
- // src/lib/crud/loader/index.ts
3646
- var import_node_fs5 = require("fs");
3647
- var import_node_path6 = require("path");
4263
+ // src/lib/crud/hooks/hooks.types.ts
4264
+ var import_zod23 = require("zod");
4265
+ var WriteOpSchema = import_zod23.z.enum([
4266
+ "create",
4267
+ "update",
4268
+ "upsert",
4269
+ "delete"
4270
+ ]);
4271
+ var ReadOpSchema = import_zod23.z.enum([
4272
+ "findAll",
4273
+ "findOne"
4274
+ ]);
4275
+ var ResourceHooksSchema = import_zod23.z.object({
4276
+ beforeWrite: import_zod23.z.custom().optional(),
4277
+ afterWrite: import_zod23.z.custom().optional(),
4278
+ afterRead: import_zod23.z.custom().optional()
4279
+ });
4280
+
4281
+ // src/lib/crud/hooks/hooks.loader.ts
4282
+ var import_node_path8 = require("path");
4283
+ var loadResourceHooks = /* @__PURE__ */ __name(async (basePath) => {
4284
+ const file = findModule(basePath, "hooks");
4285
+ return file ? importDefault(file) : void 0;
4286
+ }, "loadResourceHooks");
3648
4287
  var loadSubResourceHooks = /* @__PURE__ */ __name(async (subResources, basePath) => {
3649
4288
  for (const sub of subResources) {
3650
- const file = sub.name ? findModule2((0, import_node_path6.join)(basePath, "hooks"), sub.name) : void 0;
4289
+ const file = sub.name ? findModule((0, import_node_path8.join)(basePath, "hooks"), sub.name) : void 0;
3651
4290
  if (!file) continue;
3652
4291
  const hooks = await importDefault(file);
3653
4292
  if (hooks) sub.hooks = hooks;
3654
4293
  }
3655
4294
  }, "loadSubResourceHooks");
4295
+
4296
+ // src/lib/crud/loader/index.ts
4297
+ var import_node_fs6 = require("fs");
4298
+ var import_node_path9 = require("path");
3656
4299
  var loadResourceConfigsFromDir = /* @__PURE__ */ __name(async (dirPath, baseUrl, enumsFile) => {
3657
4300
  const enums = loadEnumRegistry(dirPath, enumsFile);
3658
- const entries = (0, import_node_fs5.readdirSync)(dirPath, {
4301
+ const entries = (0, import_node_fs6.readdirSync)(dirPath, {
3659
4302
  withFileTypes: true
3660
4303
  });
3661
4304
  const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
3662
4305
  const configs = [];
3663
4306
  for (const dir of dirs) {
3664
- const basePath = (0, import_node_path6.join)(dirPath, dir);
3665
- const schemaFile = findModule2(basePath, "schema");
4307
+ const basePath = (0, import_node_path9.join)(dirPath, dir);
4308
+ const schemaFile = findModule(basePath, "schema");
3666
4309
  const schema = schemaFile ? await importDefault(schemaFile) : void 0;
3667
- const hooksFile = findModule2(basePath, "hooks");
3668
- const hooks = hooksFile ? await importDefault(hooksFile) : void 0;
3669
- const jsonFile = (0, import_node_path6.join)(basePath, "resource.json");
3670
- if ((0, import_node_fs5.existsSync)(jsonFile)) {
3671
- const json = JSON.parse((0, import_node_fs5.readFileSync)(jsonFile, "utf-8"));
3672
- const actions = await loadActions(json.actions ?? [], basePath);
3673
- const tableActions = await loadTableActions(json.tableActions ?? [], basePath);
4310
+ const hooks = await loadResourceHooks(basePath);
4311
+ const jsonFile = (0, import_node_path9.join)(basePath, "resource.json");
4312
+ if ((0, import_node_fs6.existsSync)(jsonFile)) {
4313
+ const json = readResourceJson(jsonFile).json;
4314
+ const actions = await loadActions(json.actions ?? [], basePath, "row");
4315
+ const tableActions = await loadActions(json.tableActions ?? [], basePath, "table");
3674
4316
  const config = fromJson(json, schema, hooks, basePath, baseUrl, actions, tableActions, enums);
3675
4317
  await loadSubResourceHooks(config.subResources ?? [], basePath);
3676
4318
  configs.push(config);
3677
4319
  continue;
3678
4320
  }
3679
- const tsFile = findModule2(basePath, "resource");
4321
+ const tsFile = findModule(basePath, "resource");
3680
4322
  if (tsFile) {
3681
4323
  const config = await importDefault(tsFile);
3682
4324
  if (config) configs.push(hooks ? {
@@ -3727,11 +4369,18 @@ var CroutonApiModule = class _CroutonApiModule {
3727
4369
  static {
3728
4370
  __name(this, "CroutonApiModule");
3729
4371
  }
3730
- static forResources(configs, dataSources, loader, config) {
4372
+ onModuleInit() {
4373
+ if (!BigInt.prototype.toJSON) {
4374
+ BigInt.prototype.toJSON = function() {
4375
+ return Number(this);
4376
+ };
4377
+ }
4378
+ }
4379
+ static forResources(configs, dataSources, loader, { baseUrl }, config) {
3731
4380
  const dataSourceRegistry = new DataSourceRegistry(dataSources);
3732
4381
  const configRegistry = new ResourceConfigRegistry(loader, configs);
3733
4382
  const controllers = [
3734
- ...configs.map((c) => createCrudController(c, config.baseUrl)),
4383
+ ...configs.map((c) => createCrudController(c, baseUrl)),
3735
4384
  createAppLayoutController(configs, config.sidebarGroups, config.title, config.autoSave ?? true)
3736
4385
  ];
3737
4386
  return {
@@ -3753,18 +4402,22 @@ var CroutonApiModule = class _CroutonApiModule {
3753
4402
  ]
3754
4403
  };
3755
4404
  }
3756
- static async forResourceDir(dirPath, dataSourcesPath, config) {
3757
- const loader = new FileSystemResourceConfigLoader(dirPath, config.baseUrl, config.enumsFile);
3758
- const configs = await loadResourceConfigsFromDir(dirPath, config.baseUrl, config.enumsFile);
4405
+ static async forResourceDir(dirPath, dataSourcesPath, { baseUrl }) {
4406
+ const config = await loadConfig();
4407
+ const loader = new FileSystemResourceConfigLoader(dirPath, baseUrl, config.enumsFile);
4408
+ const configs = await loadResourceConfigsFromDir(dirPath, baseUrl, config.enumsFile);
3759
4409
  const dataSources = await loadDataSourcesFromDir(dataSourcesPath);
3760
- return _CroutonApiModule.forResources(configs, dataSources, loader, config);
4410
+ return _CroutonApiModule.forResources(configs, dataSources, loader, {
4411
+ baseUrl
4412
+ }, config);
3761
4413
  }
3762
- static forLoader(loader, configs, dataSources, config) {
3763
- return _CroutonApiModule.forResources(configs, dataSources, loader, config);
4414
+ static async forLoader(loader, configs, dataSources, appConfig) {
4415
+ const config = await loadConfig();
4416
+ return _CroutonApiModule.forResources(configs, dataSources, loader, appConfig, config);
3764
4417
  }
3765
4418
  };
3766
4419
  CroutonApiModule = _ts_decorate5([
3767
- (0, import_common13.Module)({
4420
+ (0, import_common12.Module)({
3768
4421
  controllers: [],
3769
4422
  providers: [],
3770
4423
  exports: []
@@ -3778,6 +4431,8 @@ CroutonApiModule = _ts_decorate5([
3778
4431
  ResourceConfigLoader,
3779
4432
  ResourceConfigRegistry,
3780
4433
  isOperationEnabled,
4434
+ isRowProcedureAction,
4435
+ isTableProcedureAction,
3781
4436
  loadDataSourcesFromDir,
3782
4437
  loadResourceConfigsFromDir,
3783
4438
  resolveDefinition,