@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8567.1.a167594505

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/di.js +6 -2
  3. package/dist/modules/api_keys/di.js.map +2 -2
  4. package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
  5. package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
  6. package/dist/modules/audit_logs/di.js +2 -1
  7. package/dist/modules/audit_logs/di.js.map +2 -2
  8. package/dist/modules/audit_logs/services/actionLogService.js +65 -1
  9. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  10. package/dist/modules/auth/cli.js +1 -0
  11. package/dist/modules/auth/cli.js.map +2 -2
  12. package/dist/modules/auth/commands/users.js +10 -2
  13. package/dist/modules/auth/commands/users.js.map +2 -2
  14. package/dist/modules/auth/lib/setup-app.js +19 -5
  15. package/dist/modules/auth/lib/setup-app.js.map +2 -2
  16. package/dist/modules/configs/cli.js +26 -29
  17. package/dist/modules/configs/cli.js.map +2 -2
  18. package/dist/modules/configs/di.js +3 -1
  19. package/dist/modules/configs/di.js.map +2 -2
  20. package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
  21. package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
  22. package/dist/modules/configs/lib/instance-defaults.js +204 -0
  23. package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
  24. package/dist/modules/configs/lib/module-config-service.js +115 -1
  25. package/dist/modules/configs/lib/module-config-service.js.map +2 -2
  26. package/dist/modules/entities/api/definitions.batch.js +55 -25
  27. package/dist/modules/entities/api/definitions.batch.js.map +2 -2
  28. package/dist/modules/entities/api/definitions.js +35 -8
  29. package/dist/modules/entities/api/definitions.js.map +2 -2
  30. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
  31. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  32. package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
  33. package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
  34. package/dist/modules/notifications/setup.js +10 -0
  35. package/dist/modules/notifications/setup.js.map +2 -2
  36. package/dist/modules/translations/components/TranslationManager.js +47 -10
  37. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  38. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
  39. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
  40. package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
  41. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
  42. package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
  43. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  44. package/dist/modules/workflows/api/instances/route.js +1 -1
  45. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  46. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  47. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  48. package/dist/modules/workflows/di.js +3 -1
  49. package/dist/modules/workflows/di.js.map +2 -2
  50. package/dist/modules/workflows/lib/activity-executor.js +35 -7
  51. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  52. package/dist/modules/workflows/lib/condition-handler.js +1 -1
  53. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  54. package/dist/modules/workflows/lib/error-handler.js +1 -1
  55. package/dist/modules/workflows/lib/error-handler.js.map +2 -2
  56. package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
  57. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  58. package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
  59. package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
  60. package/dist/modules/workflows/lib/named-rules.js +42 -0
  61. package/dist/modules/workflows/lib/named-rules.js.map +7 -0
  62. package/dist/modules/workflows/lib/owned-definition.js +2 -0
  63. package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
  64. package/dist/modules/workflows/lib/parallel-handler.js +1 -1
  65. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  66. package/dist/modules/workflows/lib/signal-handler.js +1 -0
  67. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  68. package/dist/modules/workflows/lib/start-validator.js +87 -85
  69. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  70. package/dist/modules/workflows/lib/step-handler.js +1 -1
  71. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  72. package/dist/modules/workflows/lib/task-handler.js +1 -0
  73. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  74. package/dist/modules/workflows/lib/timer-handler.js +1 -0
  75. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  76. package/dist/modules/workflows/lib/transition-handler.js +48 -166
  77. package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
  78. package/dist/modules/workflows/lib/workflow-executor.js +3 -2
  79. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  80. package/package.json +8 -8
  81. package/src/modules/api_keys/di.ts +7 -2
  82. package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
  83. package/src/modules/audit_logs/di.ts +1 -0
  84. package/src/modules/audit_logs/services/actionLogService.ts +132 -1
  85. package/src/modules/auth/cli.ts +1 -0
  86. package/src/modules/auth/commands/users.ts +10 -2
  87. package/src/modules/auth/i18n/de.json +2 -0
  88. package/src/modules/auth/i18n/en.json +2 -0
  89. package/src/modules/auth/i18n/es.json +2 -0
  90. package/src/modules/auth/i18n/ko.json +2 -0
  91. package/src/modules/auth/i18n/pl.json +2 -0
  92. package/src/modules/auth/lib/setup-app.ts +30 -7
  93. package/src/modules/configs/cli.ts +39 -37
  94. package/src/modules/configs/di.ts +2 -0
  95. package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
  96. package/src/modules/configs/lib/instance-defaults.ts +262 -0
  97. package/src/modules/configs/lib/module-config-service.ts +156 -0
  98. package/src/modules/entities/api/definitions.batch.ts +65 -27
  99. package/src/modules/entities/api/definitions.ts +40 -11
  100. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
  101. package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
  102. package/src/modules/notifications/setup.ts +11 -0
  103. package/src/modules/translations/components/TranslationManager.tsx +49 -10
  104. package/src/modules/translations/i18n/de.json +1 -0
  105. package/src/modules/translations/i18n/en.json +1 -0
  106. package/src/modules/translations/i18n/es.json +1 -0
  107. package/src/modules/translations/i18n/ko.json +1 -0
  108. package/src/modules/translations/i18n/pl.json +1 -0
  109. package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
  110. package/src/modules/wms/i18n/de.json +1 -0
  111. package/src/modules/wms/i18n/en.json +1 -0
  112. package/src/modules/wms/i18n/es.json +1 -0
  113. package/src/modules/wms/i18n/ko.json +1 -0
  114. package/src/modules/wms/i18n/pl.json +1 -0
  115. package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
  116. package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
  117. package/src/modules/workflows/api/instances/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
  119. package/src/modules/workflows/di.ts +2 -0
  120. package/src/modules/workflows/lib/activity-executor.ts +48 -30
  121. package/src/modules/workflows/lib/condition-handler.ts +1 -1
  122. package/src/modules/workflows/lib/error-handler.ts +1 -1
  123. package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
  124. package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
  125. package/src/modules/workflows/lib/named-rules.ts +54 -0
  126. package/src/modules/workflows/lib/owned-definition.ts +4 -1
  127. package/src/modules/workflows/lib/parallel-handler.ts +1 -1
  128. package/src/modules/workflows/lib/signal-handler.ts +1 -0
  129. package/src/modules/workflows/lib/start-validator.ts +96 -94
  130. package/src/modules/workflows/lib/step-handler.ts +1 -1
  131. package/src/modules/workflows/lib/task-handler.ts +1 -0
  132. package/src/modules/workflows/lib/timer-handler.ts +1 -0
  133. package/src/modules/workflows/lib/transition-handler.ts +74 -238
  134. package/src/modules/workflows/lib/workflow-executor.ts +7 -4
@@ -0,0 +1,204 @@
1
+ import { tryGetModules } from "@open-mercato/shared/lib/modules/registry";
2
+ import {
3
+ SEARCH_AUTO_INDEX_CONFIG_KEY,
4
+ SEARCH_AUTO_INDEX_CONFIG_MODULE
5
+ } from "@open-mercato/shared/lib/search/auto-indexing";
6
+ import { moduleConfigKeySchema } from "../data/validators.js";
7
+ const RESERVED_LEGACY_NAMESPACE_OWNER = "search";
8
+ const RESERVED_LEGACY_NAMESPACE = SEARCH_AUTO_INDEX_CONFIG_MODULE;
9
+ const RESERVED_LEGACY_KEY = SEARCH_AUTO_INDEX_CONFIG_KEY;
10
+ function isPlainObject(value) {
11
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
12
+ return false;
13
+ }
14
+ const proto = Object.getPrototypeOf(value);
15
+ return proto === Object.prototype || proto === null;
16
+ }
17
+ function validateAndCloneFiniteJsonValue(value, ownerLabel, keyLabel, ancestors = /* @__PURE__ */ new Set()) {
18
+ if (value === void 0) {
19
+ throw new Error(
20
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": value must be a finite JSON value (undefined is not allowed).`
21
+ );
22
+ }
23
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
24
+ return value;
25
+ }
26
+ if (typeof value === "number") {
27
+ if (!Number.isFinite(value)) {
28
+ throw new Error(
29
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": numeric value must be finite.`
30
+ );
31
+ }
32
+ return value;
33
+ }
34
+ if (typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") {
35
+ throw new Error(
36
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": unsupported JSON value type "${typeof value}".`
37
+ );
38
+ }
39
+ if (Array.isArray(value)) {
40
+ if (ancestors.has(value)) {
41
+ throw new Error(
42
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": circular reference detected.`
43
+ );
44
+ }
45
+ ancestors.add(value);
46
+ try {
47
+ const cloned = new Array(value.length);
48
+ for (let i = 0; i < value.length; i += 1) {
49
+ if (!(i in value)) {
50
+ throw new Error(
51
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": sparse arrays are not valid JSON.`
52
+ );
53
+ }
54
+ cloned[i] = validateAndCloneFiniteJsonValue(value[i], ownerLabel, keyLabel, ancestors);
55
+ }
56
+ return cloned;
57
+ } finally {
58
+ ancestors.delete(value);
59
+ }
60
+ }
61
+ if (!isPlainObject(value)) {
62
+ throw new Error(
63
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": value must be a plain JSON object.`
64
+ );
65
+ }
66
+ if (Object.getOwnPropertySymbols(value).length > 0) {
67
+ throw new Error(
68
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": symbol keys are not allowed in JSON defaults.`
69
+ );
70
+ }
71
+ if (ancestors.has(value)) {
72
+ throw new Error(
73
+ `[configs] Invalid instance config default "${keyLabel}" from "${ownerLabel}": circular reference detected.`
74
+ );
75
+ }
76
+ ancestors.add(value);
77
+ try {
78
+ const entries = [];
79
+ for (const [propKey, propValue] of Object.entries(value)) {
80
+ if (propValue === void 0) {
81
+ continue;
82
+ }
83
+ entries.push([propKey, validateAndCloneFiniteJsonValue(propValue, ownerLabel, keyLabel, ancestors)]);
84
+ }
85
+ return Object.fromEntries(entries);
86
+ } finally {
87
+ ancestors.delete(value);
88
+ }
89
+ }
90
+ function compareConfigKeys(left, right) {
91
+ if (left.moduleId !== right.moduleId) {
92
+ return left.moduleId < right.moduleId ? -1 : 1;
93
+ }
94
+ if (left.name !== right.name) {
95
+ return left.name < right.name ? -1 : 1;
96
+ }
97
+ return 0;
98
+ }
99
+ function isAllowedLegacyStorageNamespace(ownerModuleId, storageNamespace, name) {
100
+ return ownerModuleId === RESERVED_LEGACY_NAMESPACE_OWNER && storageNamespace === RESERVED_LEGACY_NAMESPACE && name === RESERVED_LEGACY_KEY;
101
+ }
102
+ function collectInstanceConfigDefaults(modules) {
103
+ const enabledModules = modules ?? tryGetModules();
104
+ if (!enabledModules) {
105
+ throw new Error(
106
+ "[configs] Cannot resolve instance config defaults: enabled module registry is not initialized."
107
+ );
108
+ }
109
+ const resolved = [];
110
+ const seenKeys = /* @__PURE__ */ new Map();
111
+ for (const mod of enabledModules) {
112
+ const ownerModuleId = typeof mod?.id === "string" ? mod.id.trim() : "";
113
+ const provider = mod?.setup?.instanceConfigDefaults;
114
+ if (provider === void 0) continue;
115
+ if (!ownerModuleId) {
116
+ throw new Error(
117
+ "[configs] Invalid instanceConfigDefaults contribution: owning module has an empty id."
118
+ );
119
+ }
120
+ if (typeof provider !== "function") {
121
+ throw new Error(
122
+ `[configs] Invalid instanceConfigDefaults provider on module "${ownerModuleId}": expected a synchronous function.`
123
+ );
124
+ }
125
+ const rawEntries = provider();
126
+ if (rawEntries !== null && typeof rawEntries === "object" && typeof rawEntries.then === "function") {
127
+ ;
128
+ rawEntries.then(void 0, () => {
129
+ });
130
+ throw new Error(
131
+ `[configs] Invalid instanceConfigDefaults provider on module "${ownerModuleId}": provider must be synchronous and cannot return a Promise.`
132
+ );
133
+ }
134
+ if (!Array.isArray(rawEntries)) {
135
+ throw new Error(
136
+ `[configs] Invalid instanceConfigDefaults provider on module "${ownerModuleId}": expected an array of default entries.`
137
+ );
138
+ }
139
+ for (let index = 0; index < rawEntries.length; index += 1) {
140
+ const entry = rawEntries[index];
141
+ if (!isPlainObject(entry)) {
142
+ throw new Error(
143
+ `[configs] Invalid instance config default entry #${index} from module "${ownerModuleId}": expected a plain object.`
144
+ );
145
+ }
146
+ if (typeof entry.name !== "string") {
147
+ throw new Error(
148
+ `[configs] Invalid instance config default entry #${index} from module "${ownerModuleId}": "name" must be a string.`
149
+ );
150
+ }
151
+ if (entry.legacyStorageNamespace !== void 0 && typeof entry.legacyStorageNamespace !== "string") {
152
+ throw new Error(
153
+ `[configs] Invalid instance config default "${entry.name}" from module "${ownerModuleId}": "legacyStorageNamespace" must be a string when provided.`
154
+ );
155
+ }
156
+ const rawNamespace = entry.legacyStorageNamespace ?? ownerModuleId;
157
+ const parsedKey = moduleConfigKeySchema.safeParse({
158
+ moduleId: rawNamespace,
159
+ name: entry.name
160
+ });
161
+ if (!parsedKey.success) {
162
+ throw new Error(
163
+ `[configs] Invalid instance config default key from module "${ownerModuleId}" (entry #${index}): ${parsedKey.error.issues[0]?.message ?? "invalid key"}.`
164
+ );
165
+ }
166
+ const { moduleId, name } = parsedKey.data;
167
+ if (entry.legacyStorageNamespace !== void 0) {
168
+ if (!isAllowedLegacyStorageNamespace(ownerModuleId, moduleId, name)) {
169
+ throw new Error(
170
+ `[configs] Unauthorized cross-namespace instance config default "${moduleId}.${name}" declared by module "${ownerModuleId}".`
171
+ );
172
+ }
173
+ }
174
+ const keyLabel = `${moduleId}.${name}`;
175
+ const sanitizedValue = validateAndCloneFiniteJsonValue(
176
+ entry.value,
177
+ ownerModuleId,
178
+ keyLabel
179
+ );
180
+ const dedupeKey = JSON.stringify([moduleId, name]);
181
+ const previousOwner = seenKeys.get(dedupeKey);
182
+ if (previousOwner !== void 0) {
183
+ throw new Error(
184
+ `[configs] Duplicate instance config default key "${keyLabel}" declared by module "${ownerModuleId}" (already declared by "${previousOwner}").`
185
+ );
186
+ }
187
+ seenKeys.set(dedupeKey, ownerModuleId);
188
+ resolved.push({
189
+ ownerModuleId,
190
+ moduleId,
191
+ name,
192
+ value: sanitizedValue
193
+ });
194
+ }
195
+ }
196
+ resolved.sort(compareConfigKeys);
197
+ return resolved;
198
+ }
199
+ export {
200
+ collectInstanceConfigDefaults,
201
+ compareConfigKeys,
202
+ validateAndCloneFiniteJsonValue
203
+ };
204
+ //# sourceMappingURL=instance-defaults.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/configs/lib/instance-defaults.ts"],
4
+ "sourcesContent": ["import { tryGetModules } from '@open-mercato/shared/lib/modules/registry'\nimport type { Module } from '@open-mercato/shared/modules/registry'\nimport {\n SEARCH_AUTO_INDEX_CONFIG_KEY,\n SEARCH_AUTO_INDEX_CONFIG_MODULE,\n} from '@open-mercato/shared/lib/search/auto-indexing'\nimport { moduleConfigKeySchema } from '../data/validators'\n\nexport type ResolvedInstanceConfigDefault = {\n ownerModuleId: string\n moduleId: string\n name: string\n value: unknown\n}\n\nconst RESERVED_LEGACY_NAMESPACE_OWNER = 'search'\nconst RESERVED_LEGACY_NAMESPACE = SEARCH_AUTO_INDEX_CONFIG_MODULE\nconst RESERVED_LEGACY_KEY = SEARCH_AUTO_INDEX_CONFIG_KEY\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false\n }\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * Validates that a default value is a finite JSON value (no NaN, +/-Infinity,\n * BigInt, functions, symbols, circular references, non-plain class instances,\n * top-level undefined, or array undefined elements) and returns a detached clone.\n * Error messages intentionally omit the raw value.\n */\nexport function validateAndCloneFiniteJsonValue(\n value: unknown,\n ownerLabel: string,\n keyLabel: string,\n ancestors: Set<object> = new Set(),\n): unknown {\n if (value === undefined) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": value must be a finite JSON value (undefined is not allowed).`,\n )\n }\n if (value === null || typeof value === 'boolean' || typeof value === 'string') {\n return value\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": numeric value must be finite.`,\n )\n }\n return value\n }\n if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": unsupported JSON value type \"${typeof value}\".`,\n )\n }\n if (Array.isArray(value)) {\n if (ancestors.has(value)) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": circular reference detected.`,\n )\n }\n ancestors.add(value)\n try {\n const cloned: unknown[] = new Array(value.length)\n for (let i = 0; i < value.length; i += 1) {\n if (!(i in value)) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": sparse arrays are not valid JSON.`,\n )\n }\n cloned[i] = validateAndCloneFiniteJsonValue(value[i], ownerLabel, keyLabel, ancestors)\n }\n return cloned\n } finally {\n ancestors.delete(value)\n }\n }\n if (!isPlainObject(value)) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": value must be a plain JSON object.`,\n )\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": symbol keys are not allowed in JSON defaults.`,\n )\n }\n if (ancestors.has(value)) {\n throw new Error(\n `[configs] Invalid instance config default \"${keyLabel}\" from \"${ownerLabel}\": circular reference detected.`,\n )\n }\n ancestors.add(value)\n try {\n const entries: Array<[string, unknown]> = []\n for (const [propKey, propValue] of Object.entries(value)) {\n if (propValue === undefined) {\n continue\n }\n entries.push([propKey, validateAndCloneFiniteJsonValue(propValue, ownerLabel, keyLabel, ancestors)])\n }\n return Object.fromEntries(entries)\n } finally {\n ancestors.delete(value)\n }\n}\n\nexport function compareConfigKeys(\n left: { moduleId: string; name: string },\n right: { moduleId: string; name: string },\n): number {\n if (left.moduleId !== right.moduleId) {\n return left.moduleId < right.moduleId ? -1 : 1\n }\n if (left.name !== right.name) {\n return left.name < right.name ? -1 : 1\n }\n return 0\n}\n\nfunction isAllowedLegacyStorageNamespace(\n ownerModuleId: string,\n storageNamespace: string,\n name: string,\n): boolean {\n return (\n ownerModuleId === RESERVED_LEGACY_NAMESPACE_OWNER &&\n storageNamespace === RESERVED_LEGACY_NAMESPACE &&\n name === RESERVED_LEGACY_KEY\n )\n}\n\n/**\n * Collects, validates, and deterministically orders instance configuration defaults\n * contributed by enabled modules' `setup.instanceConfigDefaults` providers.\n *\n * Fails before any persistence occurs if the module registry is uninitialized,\n * a provider is non-synchronous or returns malformed descriptors, an unauthorized\n * cross-namespace write is attempted, or normalized final keys collide.\n */\nexport function collectInstanceConfigDefaults(\n modules?: readonly Module[],\n): ResolvedInstanceConfigDefault[] {\n const enabledModules = modules ?? tryGetModules()\n if (!enabledModules) {\n throw new Error(\n '[configs] Cannot resolve instance config defaults: enabled module registry is not initialized.',\n )\n }\n\n const resolved: ResolvedInstanceConfigDefault[] = []\n const seenKeys = new Map<string, string>()\n\n for (const mod of enabledModules) {\n const ownerModuleId = typeof mod?.id === 'string' ? mod.id.trim() : ''\n const provider = mod?.setup?.instanceConfigDefaults\n if (provider === undefined) continue\n\n if (!ownerModuleId) {\n throw new Error(\n '[configs] Invalid instanceConfigDefaults contribution: owning module has an empty id.',\n )\n }\n if (typeof provider !== 'function') {\n throw new Error(\n `[configs] Invalid instanceConfigDefaults provider on module \"${ownerModuleId}\": expected a synchronous function.`,\n )\n }\n\n const rawEntries = provider()\n if (\n rawEntries !== null &&\n typeof rawEntries === 'object' &&\n typeof (rawEntries as { then?: unknown }).then === 'function'\n ) {\n // Prevent unhandled rejection noise when an accidentally async provider rejects.\n ;(rawEntries as unknown as PromiseLike<unknown>).then(undefined, () => {})\n throw new Error(\n `[configs] Invalid instanceConfigDefaults provider on module \"${ownerModuleId}\": provider must be synchronous and cannot return a Promise.`,\n )\n }\n if (!Array.isArray(rawEntries)) {\n throw new Error(\n `[configs] Invalid instanceConfigDefaults provider on module \"${ownerModuleId}\": expected an array of default entries.`,\n )\n }\n\n for (let index = 0; index < rawEntries.length; index += 1) {\n const entry = rawEntries[index]\n if (!isPlainObject(entry)) {\n throw new Error(\n `[configs] Invalid instance config default entry #${index} from module \"${ownerModuleId}\": expected a plain object.`,\n )\n }\n if (typeof entry.name !== 'string') {\n throw new Error(\n `[configs] Invalid instance config default entry #${index} from module \"${ownerModuleId}\": \"name\" must be a string.`,\n )\n }\n if (\n entry.legacyStorageNamespace !== undefined &&\n typeof entry.legacyStorageNamespace !== 'string'\n ) {\n throw new Error(\n `[configs] Invalid instance config default \"${entry.name}\" from module \"${ownerModuleId}\": \"legacyStorageNamespace\" must be a string when provided.`,\n )\n }\n\n const rawNamespace = entry.legacyStorageNamespace ?? ownerModuleId\n const parsedKey = moduleConfigKeySchema.safeParse({\n moduleId: rawNamespace,\n name: entry.name,\n })\n if (!parsedKey.success) {\n throw new Error(\n `[configs] Invalid instance config default key from module \"${ownerModuleId}\" (entry #${index}): ${parsedKey.error.issues[0]?.message ?? 'invalid key'}.`,\n )\n }\n\n const { moduleId, name } = parsedKey.data\n\n if (entry.legacyStorageNamespace !== undefined) {\n if (!isAllowedLegacyStorageNamespace(ownerModuleId, moduleId, name)) {\n throw new Error(\n `[configs] Unauthorized cross-namespace instance config default \"${moduleId}.${name}\" declared by module \"${ownerModuleId}\".`,\n )\n }\n }\n\n const keyLabel = `${moduleId}.${name}`\n const sanitizedValue = validateAndCloneFiniteJsonValue(\n entry.value,\n ownerModuleId,\n keyLabel,\n )\n\n const dedupeKey = JSON.stringify([moduleId, name])\n const previousOwner = seenKeys.get(dedupeKey)\n if (previousOwner !== undefined) {\n throw new Error(\n `[configs] Duplicate instance config default key \"${keyLabel}\" declared by module \"${ownerModuleId}\" (already declared by \"${previousOwner}\").`,\n )\n }\n seenKeys.set(dedupeKey, ownerModuleId)\n\n resolved.push({\n ownerModuleId,\n moduleId,\n name,\n value: sanitizedValue,\n })\n }\n }\n\n resolved.sort(compareConfigKeys)\n return resolved\n}\n"],
5
+ "mappings": "AAAA,SAAS,qBAAqB;AAE9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AAStC,MAAM,kCAAkC;AACxC,MAAM,4BAA4B;AAClC,MAAM,sBAAsB;AAE5B,SAAS,cAAc,OAAkD;AACvE,MAAI,OAAO,UAAU,YAAY,UAAU,QAA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AAAA,MACd,CAAC;AACD,UAAI,CAAC,UAAU,SAAS;AACtB,cAAM,IAAI;AAAA,UACR,8DAA8D,aAAa,aAAa,KAAK,MAAM,UAAU,MAAM,OAAO,CAAC,GAAG,WAAW,aAAa;AAAA,QACxJ;AAAA,MACF;AAEA,YAAM,EAAE,UAAU,KAAK,IAAI,UAAU;AAErC,UAAI,MAAM,2BAA2B,QAAW;AAC9C,YAAI,CAAC,gCAAgC,eAAe,UAAU,IAAI,GAAG;AACnE,gBAAM,IAAI;AAAA,YACR,mEAAmE,QAAQ,IAAI,IAAI,yBAAyB,aAAa;AAAA,UAC3H;AAAA,QACF;AAAA,MACF;AAEA,YAAM,WAAW,GAAG,QAAQ,IAAI,IAAI;AACpC,YAAM,iBAAiB;AAAA,QACrB,MAAM;AAAA,QACN;AAAA,QACA;AAAA,MACF;AAEA,YAAM,YAAY,KAAK,UAAU,CAAC,UAAU,IAAI,CAAC;AACjD,YAAM,gBAAgB,SAAS,IAAI,SAAS;AAC5C,UAAI,kBAAkB,QAAW;AAC/B,cAAM,IAAI;AAAA,UACR,oDAAoD,QAAQ,yBAAyB,aAAa,2BAA2B,aAAa;AAAA,QAC5I;AAAA,MACF;AACA,eAAS,IAAI,WAAW,aAAa;AAErC,eAAS,KAAK;AAAA,QACZ;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AAEA,WAAS,KAAK,iBAAiB;AAC/B,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -1,6 +1,8 @@
1
1
  import { getCurrentCacheTenant, runWithCacheTenant } from "@open-mercato/cache";
2
+ import { isUniqueViolation } from "@open-mercato/shared/lib/db/pg-errors";
2
3
  import { ModuleConfig } from "../data/entities.js";
3
4
  import { moduleConfigKeySchema } from "../data/validators.js";
5
+ import { compareConfigKeys, validateAndCloneFiniteJsonValue } from "./instance-defaults.js";
4
6
  const CACHE_VERSION = "v3";
5
7
  const CACHE_TTL_MS = 6e4;
6
8
  const scopeKeyPart = (tenantId) => tenantId ?? "global";
@@ -69,6 +71,115 @@ const deleteCacheByModule = async (cache, moduleId, tenantIds) => {
69
71
  }
70
72
  };
71
73
  const normalizeKey = (moduleId, name) => moduleConfigKeySchema.parse({ moduleId, name });
74
+ function prepareStrictDefaults(defaults) {
75
+ if (!Array.isArray(defaults)) {
76
+ throw new Error("[configs] Invalid instance config defaults catalog: expected an array.");
77
+ }
78
+ const seen = /* @__PURE__ */ new Set();
79
+ const validated = [];
80
+ for (let index = 0; index < defaults.length; index += 1) {
81
+ const entry = defaults[index];
82
+ const parsedKey = moduleConfigKeySchema.safeParse({
83
+ moduleId: entry?.moduleId,
84
+ name: entry?.name
85
+ });
86
+ if (!parsedKey.success) {
87
+ throw new Error(
88
+ `[configs] Invalid instance config default key at index ${index}: ${parsedKey.error.issues[0]?.message ?? "invalid key"}.`
89
+ );
90
+ }
91
+ const { moduleId, name } = parsedKey.data;
92
+ const keyLabel = `${moduleId}.${name}`;
93
+ const dedupeKey = JSON.stringify([moduleId, name]);
94
+ if (seen.has(dedupeKey)) {
95
+ throw new Error(`[configs] Duplicate instance config default key "${keyLabel}".`);
96
+ }
97
+ seen.add(dedupeKey);
98
+ const value = validateAndCloneFiniteJsonValue(entry.value, moduleId, keyLabel);
99
+ validated.push({ moduleId, name, value });
100
+ }
101
+ validated.sort(compareConfigKeys);
102
+ return validated;
103
+ }
104
+ async function restoreInstanceDefaultsStrict(container, defaults, options) {
105
+ const validated = prepareStrictDefaults(defaults);
106
+ if (validated.length === 0) return [];
107
+ const em = resolveEm(container);
108
+ if (!em) {
109
+ throw new Error(
110
+ "[configs] Cannot restore instance defaults: EntityManager is not registered in the container."
111
+ );
112
+ }
113
+ const force = options?.force ?? true;
114
+ const maxAttempts = Number.isFinite(options?.maxConflictRetries) ? Math.max(1, Math.trunc(options.maxConflictRetries)) : 3;
115
+ let committedRecords = null;
116
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
117
+ const freshEm = typeof em.fork === "function" ? em.fork({
118
+ clear: true,
119
+ freshEventManager: true,
120
+ useContext: false
121
+ }) : em;
122
+ if (typeof freshEm.transactional !== "function") {
123
+ throw new Error(
124
+ "[configs] Cannot restore instance defaults: EntityManager does not support transactions."
125
+ );
126
+ }
127
+ try {
128
+ committedRecords = await freshEm.transactional(async (txEm) => {
129
+ const repo = txEm.getRepository(ModuleConfig);
130
+ const touched = [];
131
+ for (const entry of validated) {
132
+ const existing = await repo.findOne({
133
+ moduleId: entry.moduleId,
134
+ name: entry.name,
135
+ tenantId: null
136
+ });
137
+ const now = /* @__PURE__ */ new Date();
138
+ if (!existing) {
139
+ const created = repo.create({
140
+ moduleId: entry.moduleId,
141
+ name: entry.name,
142
+ valueJson: entry.value,
143
+ tenantId: null,
144
+ organizationId: null,
145
+ createdAt: now,
146
+ updatedAt: now
147
+ });
148
+ txEm.persist(created);
149
+ touched.push(created);
150
+ } else if (force) {
151
+ existing.valueJson = entry.value;
152
+ existing.updatedAt = now;
153
+ txEm.persist(existing);
154
+ touched.push(existing);
155
+ }
156
+ }
157
+ if (touched.length > 0) {
158
+ await txEm.flush();
159
+ }
160
+ return touched.map((entity) => toRecord(entity, "instance"));
161
+ });
162
+ break;
163
+ } catch (error) {
164
+ if (isUniqueViolation(error) && attempt < maxAttempts) {
165
+ continue;
166
+ }
167
+ throw error;
168
+ }
169
+ }
170
+ const records = committedRecords ?? [];
171
+ const cache = resolveCache(container);
172
+ for (const record of records) {
173
+ await writeCache(
174
+ cache,
175
+ cacheKey(record.moduleId, record.name, null),
176
+ { found: true, record },
177
+ record.moduleId,
178
+ null
179
+ );
180
+ }
181
+ return records;
182
+ }
72
183
  function createModuleConfigService(container) {
73
184
  const loadRow = async (cache, moduleId, name, tenantId) => {
74
185
  const key = cacheKey(moduleId, name, tenantId);
@@ -189,15 +300,18 @@ function createModuleConfigService(container) {
189
300
  const moduleId = moduleConfigKeySchema.shape.moduleId.parse(rawModuleId);
190
301
  await deleteCacheByModule(cache, moduleId, [tenantId, getCurrentCacheTenant(), null]);
191
302
  };
303
+ const restoreDefaultsStrict = async (defaults, options) => restoreInstanceDefaultsStrict(container, defaults, options);
192
304
  return {
193
305
  getRecord,
194
306
  getValue,
195
307
  setValue,
196
308
  restoreDefaults,
309
+ restoreDefaultsStrict,
197
310
  invalidate
198
311
  };
199
312
  }
200
313
  export {
201
- createModuleConfigService
314
+ createModuleConfigService,
315
+ restoreInstanceDefaultsStrict
202
316
  };
203
317
  //# sourceMappingURL=module-config-service.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/configs/lib/module-config-service.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { getCurrentCacheTenant, runWithCacheTenant } from '@open-mercato/cache'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { ModuleConfig } from '../data/entities'\nimport { moduleConfigKeySchema } from '../data/validators'\n\nconst CACHE_VERSION = 'v3'\nconst CACHE_TTL_MS = 60_000\n\ntype CachePayload = {\n found: boolean\n record?: ModuleConfigRecord | null\n}\n\nconst scopeKeyPart = (tenantId?: string | null) => (tenantId ?? 'global')\n\nconst cacheKey = (moduleId: string, name: string, tenantId?: string | null) =>\n `module-config:${CACHE_VERSION}:${moduleId}:${name}:${scopeKeyPart(tenantId)}`\nconst moduleTag = (moduleId: string) => `module-config:module:${moduleId}`\n\nconst resolveEm = (container: AppContainer): EntityManager | null => {\n try {\n return (container.resolve('em') as EntityManager)\n } catch {\n return null\n }\n}\n\nconst resolveCache = (container: AppContainer): CacheStrategy | null => {\n try {\n return (container.resolve('cache') as CacheStrategy)\n } catch {\n return null\n }\n}\n\nconst toRecord = (entity: ModuleConfig, source: ModuleConfigSource): ModuleConfigRecord => ({\n moduleId: entity.moduleId,\n name: entity.name,\n value: entity.valueJson ?? null,\n tenantId: entity.tenantId ?? null,\n organizationId: entity.organizationId ?? null,\n source,\n createdAt: entity.createdAt.toISOString(),\n updatedAt: entity.updatedAt.toISOString(),\n})\n\nconst readCache = async (\n cache: CacheStrategy | null,\n key: string,\n tenantId: string | null,\n): Promise<CachePayload | null> => {\n if (!cache) return null\n try {\n const cached = await runWithCacheTenant(tenantId, () => cache.get(key))\n if (cached && typeof cached === 'object' && 'found' in cached) {\n return cached as CachePayload\n }\n } catch {}\n return null\n}\n\nconst writeCache = async (\n cache: CacheStrategy | null,\n key: string,\n payload: CachePayload,\n moduleId: string,\n tenantId: string | null,\n) => {\n if (!cache) return\n try {\n await runWithCacheTenant(tenantId, () =>\n cache.set(key, payload, { ttl: CACHE_TTL_MS, tags: [moduleTag(moduleId)] }),\n )\n } catch {}\n}\n\nconst deleteCacheKey = async (cache: CacheStrategy | null, key: string, tenantId: string | null) => {\n if (!cache) return\n try {\n await runWithCacheTenant(tenantId, () => cache.delete(key))\n } catch {}\n}\n\nconst deleteCacheByModule = async (cache: CacheStrategy | null, moduleId: string, tenantIds: Array<string | null>) => {\n if (!cache) return\n const scopes = Array.from(new Set(tenantIds))\n for (const tenantId of scopes) {\n try {\n await runWithCacheTenant(tenantId, () => cache.deleteByTags([moduleTag(moduleId)]))\n } catch {}\n }\n}\n\nconst normalizeKey = (moduleId: string, name: string) => moduleConfigKeySchema.parse({ moduleId, name })\n\nexport type ModuleConfigSource = 'tenant' | 'instance'\n\nexport type ConfigScope = {\n tenantId?: string | null\n organizationId?: string | null\n}\n\nexport type ModuleConfigRecord = {\n moduleId: string\n name: string\n value: unknown\n tenantId: string | null\n organizationId: string | null\n source: ModuleConfigSource\n createdAt: string\n updatedAt: string\n}\n\nexport type ModuleConfigDefault = {\n moduleId: string\n name: string\n value: unknown\n}\n\nexport type ModuleConfigService = {\n getRecord(moduleId: string, name: string, scope?: ConfigScope): Promise<ModuleConfigRecord | null>\n getValue<T = unknown>(\n moduleId: string,\n name: string,\n options?: { defaultValue?: T | null; scope?: ConfigScope },\n ): Promise<T | null>\n setValue(moduleId: string, name: string, value: unknown, scope?: ConfigScope): Promise<ModuleConfigRecord | null>\n restoreDefaults(defaults: ModuleConfigDefault[], options?: { force?: boolean }): Promise<void>\n invalidate(moduleId: string, name?: string, scope?: ConfigScope): Promise<void>\n}\n\nexport function createModuleConfigService(container: AppContainer): ModuleConfigService {\n const loadRow = async (\n cache: CacheStrategy | null,\n moduleId: string,\n name: string,\n tenantId: string | null,\n ): Promise<ModuleConfigRecord | null> => {\n const key = cacheKey(moduleId, name, tenantId)\n const cached = await readCache(cache, key, tenantId)\n if (cached) {\n if (!cached.found) return null\n if (cached.record) return cached.record\n }\n const em = resolveEm(container)\n if (!em) return null\n const entity = await em.getRepository(ModuleConfig).findOne({ moduleId, name, tenantId })\n if (!entity) {\n await writeCache(cache, key, { found: false }, moduleId, tenantId)\n return null\n }\n const record = toRecord(entity, tenantId ? 'tenant' : 'instance')\n await writeCache(cache, key, { found: true, record }, moduleId, tenantId)\n return record\n }\n\n const getRecord = async (rawModuleId: string, rawName: string, scope?: ConfigScope): Promise<ModuleConfigRecord | null> => {\n const { moduleId, name } = normalizeKey(rawModuleId, rawName)\n const tenantId = scope?.tenantId ?? null\n const cache = resolveCache(container)\n if (tenantId) {\n const scoped = await loadRow(cache, moduleId, name, tenantId)\n if (scoped) return scoped\n }\n return loadRow(cache, moduleId, name, null)\n }\n\n const getValue = async <T>(\n rawModuleId: string,\n rawName: string,\n options?: { defaultValue?: T | null; scope?: ConfigScope },\n ): Promise<T | null> => {\n const record = await getRecord(rawModuleId, rawName, options?.scope)\n if (!record) return options?.defaultValue ?? null\n const value = record.value as T | null | undefined\n if (value === undefined || value === null) return options?.defaultValue ?? null\n return value\n }\n\n const setValue = async (\n rawModuleId: string,\n rawName: string,\n value: unknown,\n scope?: ConfigScope,\n ): Promise<ModuleConfigRecord | null> => {\n const em = resolveEm(container)\n if (!em) return null\n const { moduleId, name } = normalizeKey(rawModuleId, rawName)\n const tenantId = scope?.tenantId ?? null\n const organizationId = scope?.organizationId ?? null\n const repo = em.getRepository(ModuleConfig)\n const now = new Date()\n let entity = await repo.findOne({ moduleId, name, tenantId })\n if (!entity) {\n entity = repo.create({\n moduleId,\n name,\n valueJson: value ?? null,\n tenantId,\n organizationId,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(entity)\n } else {\n entity.valueJson = value ?? null\n entity.organizationId = organizationId\n entity.updatedAt = now\n }\n await em.flush()\n const record = toRecord(entity, tenantId ? 'tenant' : 'instance')\n const cache = resolveCache(container)\n await writeCache(cache, cacheKey(moduleId, name, tenantId), { found: true, record }, moduleId, tenantId)\n return record\n }\n\n const restoreDefaults = async (defaults: ModuleConfigDefault[], options?: { force?: boolean }) => {\n if (!Array.isArray(defaults) || defaults.length === 0) return\n const em = resolveEm(container)\n if (!em) return\n const repo = em.getRepository(ModuleConfig)\n const cache = resolveCache(container)\n let dirty = false\n const touched: ModuleConfig[] = []\n for (const entry of defaults) {\n let entity: ModuleConfig | null = null\n try {\n const { moduleId, name } = normalizeKey(entry.moduleId, entry.name)\n entity = await repo.findOne({ moduleId, name, tenantId: null })\n if (!entity) {\n entity = repo.create({\n moduleId,\n name,\n valueJson: entry.value ?? null,\n tenantId: null,\n organizationId: null,\n })\n em.persist(entity)\n dirty = true\n touched.push(entity)\n } else if (options?.force) {\n entity.valueJson = entry.value ?? null\n entity.updatedAt = new Date()\n dirty = true\n touched.push(entity)\n }\n } catch {}\n }\n if (!dirty) return\n await em.flush()\n for (const entity of touched) {\n const record = toRecord(entity, 'instance')\n await writeCache(cache, cacheKey(entity.moduleId, entity.name, null), { found: true, record }, entity.moduleId, null)\n }\n }\n\n const invalidate = async (rawModuleId: string, rawName?: string, scope?: ConfigScope) => {\n const cache = resolveCache(container)\n if (!cache) return\n const tenantId = scope?.tenantId ?? null\n if (rawName) {\n const { moduleId, name } = normalizeKey(rawModuleId, rawName)\n if (tenantId) await deleteCacheKey(cache, cacheKey(moduleId, name, tenantId), tenantId)\n await deleteCacheKey(cache, cacheKey(moduleId, name, null), null)\n return\n }\n const moduleId = moduleConfigKeySchema.shape.moduleId.parse(rawModuleId)\n await deleteCacheByModule(cache, moduleId, [tenantId, getCurrentCacheTenant(), null])\n }\n\n return {\n getRecord,\n getValue,\n setValue,\n restoreDefaults,\n invalidate,\n }\n}\n"],
5
- "mappings": "AACA,SAAS,uBAAuB,0BAA0B;AAG1D,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AAEtC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAOrB,MAAM,eAAe,CAAC,aAA8B,YAAY;AAEhE,MAAM,WAAW,CAAC,UAAkB,MAAc,aAChD,iBAAiB,aAAa,IAAI,QAAQ,IAAI,IAAI,IAAI,aAAa,QAAQ,CAAC;AAC9E,MAAM,YAAY,CAAC,aAAqB,wBAAwB,QAAQ;AAExE,MAAM,YAAY,CAAC,cAAkD;AACnE,MAAI;AACF,WAAQ,UAAU,QAAQ,IAAI;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,MAAM,eAAe,CAAC,cAAkD;AACtE,MAAI;AACF,WAAQ,UAAU,QAAQ,OAAO;AAAA,EACnC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,MAAM,WAAW,CAAC,QAAsB,YAAoD;AAAA,EAC1F,UAAU,OAAO;AAAA,EACjB,MAAM,OAAO;AAAA,EACb,OAAO,OAAO,aAAa;AAAA,EAC3B,UAAU,OAAO,YAAY;AAAA,EAC7B,gBAAgB,OAAO,kBAAkB;AAAA,EACzC;AAAA,EACA,WAAW,OAAO,UAAU,YAAY;AAAA,EACxC,WAAW,OAAO,UAAU,YAAY;AAC1C;AAEA,MAAM,YAAY,OAChB,OACA,KACA,aACiC;AACjC,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,UAAM,SAAS,MAAM,mBAAmB,UAAU,MAAM,MAAM,IAAI,GAAG,CAAC;AACtE,QAAI,UAAU,OAAO,WAAW,YAAY,WAAW,QAAQ;AAC7D,aAAO;AAAA,IACT;AAAA,EACF,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AM,SAAS;AAClC,iBAAO,YAAY,oBAAI,KAAK;AAC5B,kBAAQ;AACR,kBAAQ,KAAK,MAAM;AAAA,QACrB;AAAA,MACF,QAAQ;AAAA,MAAC;AAAA,IACX;AACA,QAAI,CAAC,MAAO;AACZ,UAAM,GAAG,MAAM;AACf,eAAW,UAAU,SAAS;AAC5B,YAAM,SAAS,SAAS,QAAQ,UAAU;AAC1C,YAAM,WAAW,OAAO,SAAS,OAAO,UAAU,OAAO,MAAM,IAAI,GAAG,EAAE,OAAO,MAAM,OAAO,GAAG,OAAO,UAAU,IAAI;AAAA,IACtH;AAAA,EACF;AAEA,QAAM,aAAa,OAAO,aAAqB,SAAkB,UAAwB;AACvF,UAAM,QAAQ,aAAa,SAAS;AACpC,QAAI,CAAC,MAAO;AACZ,UAAM,WAAW,OAAO,YAAY;AACpC,QAAI,SAAS;AACX,YAAM,EAAE,UAAAA,WAAU,KAAK,IAAI,aAAa,aAAa,OAAO;AAC5D,UAAI,SAAU,OAAM,eAAe,OAAO,SAASA,WAAU,MAAM,QAAQ,GAAG,QAAQ;AACtF,YAAM,eAAe,OAAO,SAASA,WAAU,MAAM,IAAI,GAAG,IAAI;AAChE;AAAA,IACF;AACA,UAAM,WAAW,sBAAsB,MAAM,SAAS,MAAM,WAAW;AACvE,UAAM,oBAAoB,OAAO,UAAU,CAAC,UAAU,sBAAsB,GAAG,IAAI,CAAC;AAAA,EACtF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { getCurrentCacheTenant, runWithCacheTenant } from '@open-mercato/cache'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { isUniqueViolation } from '@open-mercato/shared/lib/db/pg-errors'\nimport { ModuleConfig } from '../data/entities'\nimport { moduleConfigKeySchema } from '../data/validators'\nimport { compareConfigKeys, validateAndCloneFiniteJsonValue } from './instance-defaults'\n\nconst CACHE_VERSION = 'v3'\nconst CACHE_TTL_MS = 60_000\n\ntype CachePayload = {\n found: boolean\n record?: ModuleConfigRecord | null\n}\n\nconst scopeKeyPart = (tenantId?: string | null) => (tenantId ?? 'global')\n\nconst cacheKey = (moduleId: string, name: string, tenantId?: string | null) =>\n `module-config:${CACHE_VERSION}:${moduleId}:${name}:${scopeKeyPart(tenantId)}`\nconst moduleTag = (moduleId: string) => `module-config:module:${moduleId}`\n\nconst resolveEm = (container: AppContainer): EntityManager | null => {\n try {\n return (container.resolve('em') as EntityManager)\n } catch {\n return null\n }\n}\n\nconst resolveCache = (container: AppContainer): CacheStrategy | null => {\n try {\n return (container.resolve('cache') as CacheStrategy)\n } catch {\n return null\n }\n}\n\nconst toRecord = (entity: ModuleConfig, source: ModuleConfigSource): ModuleConfigRecord => ({\n moduleId: entity.moduleId,\n name: entity.name,\n value: entity.valueJson ?? null,\n tenantId: entity.tenantId ?? null,\n organizationId: entity.organizationId ?? null,\n source,\n createdAt: entity.createdAt.toISOString(),\n updatedAt: entity.updatedAt.toISOString(),\n})\n\nconst readCache = async (\n cache: CacheStrategy | null,\n key: string,\n tenantId: string | null,\n): Promise<CachePayload | null> => {\n if (!cache) return null\n try {\n const cached = await runWithCacheTenant(tenantId, () => cache.get(key))\n if (cached && typeof cached === 'object' && 'found' in cached) {\n return cached as CachePayload\n }\n } catch {}\n return null\n}\n\nconst writeCache = async (\n cache: CacheStrategy | null,\n key: string,\n payload: CachePayload,\n moduleId: string,\n tenantId: string | null,\n) => {\n if (!cache) return\n try {\n await runWithCacheTenant(tenantId, () =>\n cache.set(key, payload, { ttl: CACHE_TTL_MS, tags: [moduleTag(moduleId)] }),\n )\n } catch {}\n}\n\nconst deleteCacheKey = async (cache: CacheStrategy | null, key: string, tenantId: string | null) => {\n if (!cache) return\n try {\n await runWithCacheTenant(tenantId, () => cache.delete(key))\n } catch {}\n}\n\nconst deleteCacheByModule = async (cache: CacheStrategy | null, moduleId: string, tenantIds: Array<string | null>) => {\n if (!cache) return\n const scopes = Array.from(new Set(tenantIds))\n for (const tenantId of scopes) {\n try {\n await runWithCacheTenant(tenantId, () => cache.deleteByTags([moduleTag(moduleId)]))\n } catch {}\n }\n}\n\nconst normalizeKey = (moduleId: string, name: string) => moduleConfigKeySchema.parse({ moduleId, name })\n\nexport type ModuleConfigSource = 'tenant' | 'instance'\n\nexport type ConfigScope = {\n tenantId?: string | null\n organizationId?: string | null\n}\n\nexport type ModuleConfigRecord = {\n moduleId: string\n name: string\n value: unknown\n tenantId: string | null\n organizationId: string | null\n source: ModuleConfigSource\n createdAt: string\n updatedAt: string\n}\n\nexport type ModuleConfigDefault = {\n moduleId: string\n name: string\n value: unknown\n}\n\nexport type RestoreDefaultsStrictOptions = {\n force?: boolean\n maxConflictRetries?: number\n}\n\nexport type ModuleConfigService = {\n getRecord(moduleId: string, name: string, scope?: ConfigScope): Promise<ModuleConfigRecord | null>\n getValue<T = unknown>(\n moduleId: string,\n name: string,\n options?: { defaultValue?: T | null; scope?: ConfigScope },\n ): Promise<T | null>\n setValue(moduleId: string, name: string, value: unknown, scope?: ConfigScope): Promise<ModuleConfigRecord | null>\n restoreDefaults(defaults: ModuleConfigDefault[], options?: { force?: boolean }): Promise<void>\n restoreDefaultsStrict?(\n defaults: readonly ModuleConfigDefault[],\n options?: RestoreDefaultsStrictOptions,\n ): Promise<ModuleConfigRecord[]>\n invalidate(moduleId: string, name?: string, scope?: ConfigScope): Promise<void>\n}\n\nfunction prepareStrictDefaults(\n defaults: readonly ModuleConfigDefault[],\n): Array<{ moduleId: string; name: string; value: unknown }> {\n if (!Array.isArray(defaults)) {\n throw new Error('[configs] Invalid instance config defaults catalog: expected an array.')\n }\n const seen = new Set<string>()\n const validated: Array<{ moduleId: string; name: string; value: unknown }> = []\n for (let index = 0; index < defaults.length; index += 1) {\n const entry = defaults[index]\n const parsedKey = moduleConfigKeySchema.safeParse({\n moduleId: entry?.moduleId,\n name: entry?.name,\n })\n if (!parsedKey.success) {\n throw new Error(\n `[configs] Invalid instance config default key at index ${index}: ${parsedKey.error.issues[0]?.message ?? 'invalid key'}.`,\n )\n }\n const { moduleId, name } = parsedKey.data\n const keyLabel = `${moduleId}.${name}`\n const dedupeKey = JSON.stringify([moduleId, name])\n if (seen.has(dedupeKey)) {\n throw new Error(`[configs] Duplicate instance config default key \"${keyLabel}\".`)\n }\n seen.add(dedupeKey)\n const value = validateAndCloneFiniteJsonValue(entry.value, moduleId, keyLabel)\n validated.push({ moduleId, name, value })\n }\n validated.sort(compareConfigKeys)\n return validated\n}\n\n/**\n * Strictly restores instance-scoped module configuration defaults in a single\n * transaction on a fresh EntityManager.\n *\n * - An empty catalog is a successful no-op.\n * - All keys and finite JSON values are validated before any DB writes occur.\n * - Missing EntityManager, lookup, persistence, flush, or commit errors propagate\n * with transaction rollback and zero cache writes.\n * - Concurrent unique-index conflicts (SQLSTATE 23505) retry with a fresh EM fork.\n * - Cache entries are published only after the transaction commits.\n */\nexport async function restoreInstanceDefaultsStrict(\n container: AppContainer,\n defaults: readonly ModuleConfigDefault[],\n options?: RestoreDefaultsStrictOptions,\n): Promise<ModuleConfigRecord[]> {\n const validated = prepareStrictDefaults(defaults)\n if (validated.length === 0) return []\n\n const em = resolveEm(container)\n if (!em) {\n throw new Error(\n '[configs] Cannot restore instance defaults: EntityManager is not registered in the container.',\n )\n }\n\n const force = options?.force ?? true\n const maxAttempts = Number.isFinite(options?.maxConflictRetries)\n ? Math.max(1, Math.trunc(options!.maxConflictRetries!))\n : 3\n let committedRecords: ModuleConfigRecord[] | null = null\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const freshEm =\n typeof (em as { fork?: unknown }).fork === 'function'\n ? (em.fork({\n clear: true,\n freshEventManager: true,\n useContext: false,\n }) as EntityManager)\n : em\n\n if (typeof (freshEm as { transactional?: unknown }).transactional !== 'function') {\n throw new Error(\n '[configs] Cannot restore instance defaults: EntityManager does not support transactions.',\n )\n }\n\n try {\n committedRecords = await freshEm.transactional(async (txEm) => {\n const repo = txEm.getRepository(ModuleConfig)\n const touched: ModuleConfig[] = []\n for (const entry of validated) {\n const existing = await repo.findOne({\n moduleId: entry.moduleId,\n name: entry.name,\n tenantId: null,\n })\n const now = new Date()\n if (!existing) {\n const created = repo.create({\n moduleId: entry.moduleId,\n name: entry.name,\n valueJson: entry.value,\n tenantId: null,\n organizationId: null,\n createdAt: now,\n updatedAt: now,\n })\n txEm.persist(created)\n touched.push(created)\n } else if (force) {\n existing.valueJson = entry.value\n existing.updatedAt = now\n txEm.persist(existing)\n touched.push(existing)\n }\n }\n if (touched.length > 0) {\n await txEm.flush()\n }\n return touched.map((entity) => toRecord(entity, 'instance'))\n })\n break\n } catch (error) {\n if (isUniqueViolation(error) && attempt < maxAttempts) {\n continue\n }\n throw error\n }\n }\n\n const records = committedRecords ?? []\n const cache = resolveCache(container)\n for (const record of records) {\n await writeCache(\n cache,\n cacheKey(record.moduleId, record.name, null),\n { found: true, record },\n record.moduleId,\n null,\n )\n }\n return records\n}\n\nexport function createModuleConfigService(container: AppContainer): ModuleConfigService {\n const loadRow = async (\n cache: CacheStrategy | null,\n moduleId: string,\n name: string,\n tenantId: string | null,\n ): Promise<ModuleConfigRecord | null> => {\n const key = cacheKey(moduleId, name, tenantId)\n const cached = await readCache(cache, key, tenantId)\n if (cached) {\n if (!cached.found) return null\n if (cached.record) return cached.record\n }\n const em = resolveEm(container)\n if (!em) return null\n const entity = await em.getRepository(ModuleConfig).findOne({ moduleId, name, tenantId })\n if (!entity) {\n await writeCache(cache, key, { found: false }, moduleId, tenantId)\n return null\n }\n const record = toRecord(entity, tenantId ? 'tenant' : 'instance')\n await writeCache(cache, key, { found: true, record }, moduleId, tenantId)\n return record\n }\n\n const getRecord = async (rawModuleId: string, rawName: string, scope?: ConfigScope): Promise<ModuleConfigRecord | null> => {\n const { moduleId, name } = normalizeKey(rawModuleId, rawName)\n const tenantId = scope?.tenantId ?? null\n const cache = resolveCache(container)\n if (tenantId) {\n const scoped = await loadRow(cache, moduleId, name, tenantId)\n if (scoped) return scoped\n }\n return loadRow(cache, moduleId, name, null)\n }\n\n const getValue = async <T>(\n rawModuleId: string,\n rawName: string,\n options?: { defaultValue?: T | null; scope?: ConfigScope },\n ): Promise<T | null> => {\n const record = await getRecord(rawModuleId, rawName, options?.scope)\n if (!record) return options?.defaultValue ?? null\n const value = record.value as T | null | undefined\n if (value === undefined || value === null) return options?.defaultValue ?? null\n return value\n }\n\n const setValue = async (\n rawModuleId: string,\n rawName: string,\n value: unknown,\n scope?: ConfigScope,\n ): Promise<ModuleConfigRecord | null> => {\n const em = resolveEm(container)\n if (!em) return null\n const { moduleId, name } = normalizeKey(rawModuleId, rawName)\n const tenantId = scope?.tenantId ?? null\n const organizationId = scope?.organizationId ?? null\n const repo = em.getRepository(ModuleConfig)\n const now = new Date()\n let entity = await repo.findOne({ moduleId, name, tenantId })\n if (!entity) {\n entity = repo.create({\n moduleId,\n name,\n valueJson: value ?? null,\n tenantId,\n organizationId,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(entity)\n } else {\n entity.valueJson = value ?? null\n entity.organizationId = organizationId\n entity.updatedAt = now\n }\n await em.flush()\n const record = toRecord(entity, tenantId ? 'tenant' : 'instance')\n const cache = resolveCache(container)\n await writeCache(cache, cacheKey(moduleId, name, tenantId), { found: true, record }, moduleId, tenantId)\n return record\n }\n\n const restoreDefaults = async (defaults: ModuleConfigDefault[], options?: { force?: boolean }) => {\n if (!Array.isArray(defaults) || defaults.length === 0) return\n const em = resolveEm(container)\n if (!em) return\n const repo = em.getRepository(ModuleConfig)\n const cache = resolveCache(container)\n let dirty = false\n const touched: ModuleConfig[] = []\n for (const entry of defaults) {\n let entity: ModuleConfig | null = null\n try {\n const { moduleId, name } = normalizeKey(entry.moduleId, entry.name)\n entity = await repo.findOne({ moduleId, name, tenantId: null })\n if (!entity) {\n entity = repo.create({\n moduleId,\n name,\n valueJson: entry.value ?? null,\n tenantId: null,\n organizationId: null,\n })\n em.persist(entity)\n dirty = true\n touched.push(entity)\n } else if (options?.force) {\n entity.valueJson = entry.value ?? null\n entity.updatedAt = new Date()\n dirty = true\n touched.push(entity)\n }\n } catch {}\n }\n if (!dirty) return\n await em.flush()\n for (const entity of touched) {\n const record = toRecord(entity, 'instance')\n await writeCache(cache, cacheKey(entity.moduleId, entity.name, null), { found: true, record }, entity.moduleId, null)\n }\n }\n\n const invalidate = async (rawModuleId: string, rawName?: string, scope?: ConfigScope) => {\n const cache = resolveCache(container)\n if (!cache) return\n const tenantId = scope?.tenantId ?? null\n if (rawName) {\n const { moduleId, name } = normalizeKey(rawModuleId, rawName)\n if (tenantId) await deleteCacheKey(cache, cacheKey(moduleId, name, tenantId), tenantId)\n await deleteCacheKey(cache, cacheKey(moduleId, name, null), null)\n return\n }\n const moduleId = moduleConfigKeySchema.shape.moduleId.parse(rawModuleId)\n await deleteCacheByModule(cache, moduleId, [tenantId, getCurrentCacheTenant(), null])\n }\n\n const restoreDefaultsStrict = async (\n defaults: readonly ModuleConfigDefault[],\n options?: RestoreDefaultsStrictOptions,\n ): Promise<ModuleConfigRecord[]> => restoreInstanceDefaultsStrict(container, defaults, options)\n\n return {\n getRecord,\n getValue,\n setValue,\n restoreDefaults,\n restoreDefaultsStrict,\n invalidate,\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,uBAAuB,0BAA0B;AAG1D,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,mBAAmB,uCAAuC;AAEnE,MAAM,gBAAgB;AACtB,MAAM,eAAe;AAOrB,MAAM,eAAe,CAAC,aAA8B,YAAY;AAEhE,MAAM,WAAW,CAAC,UAAkB,MAAc,aAChD,iBAAiB,aAAa,IAAI,QAAQ,IAAI,IAAI,IAAI,aAAa,QAAQ,CAAC;AAC9E,MAAM,YAAY,CAAC,aAAqB,wBAAwB,QAAQ;AAExE,MAAM,YAAY,CAAC,cAAkD;AAC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;AACZ,UAAM,GAAG,MAAM;AACf,eAAW,UAAU,SAAS;AAC5B,YAAM,SAAS,SAAS,QAAQ,UAAU;AAC1C,YAAM,WAAW,OAAO,SAAS,OAAO,UAAU,OAAO,MAAM,IAAI,GAAG,EAAE,OAAO,MAAM,OAAO,GAAG,OAAO,UAAU,IAAI;AAAA,IACtH;AAAA,EACF;AAEA,QAAM,aAAa,OAAO,aAAqB,SAAkB,UAAwB;AACvF,UAAM,QAAQ,aAAa,SAAS;AACpC,QAAI,CAAC,MAAO;AACZ,UAAM,WAAW,OAAO,YAAY;AACpC,QAAI,SAAS;AACX,YAAM,EAAE,UAAAA,WAAU,KAAK,IAAI,aAAa,aAAa,OAAO;AAC5D,UAAI,SAAU,OAAM,eAAe,OAAO,SAASA,WAAU,MAAM,QAAQ,GAAG,QAAQ;AACtF,YAAM,eAAe,OAAO,SAASA,WAAU,MAAM,IAAI,GAAG,IAAI;AAChE;AAAA,IACF;AACA,UAAM,WAAW,sBAAsB,MAAM,SAAS,MAAM,WAAW;AACvE,UAAM,oBAAoB,OAAO,UAAU,CAAC,UAAU,sBAAsB,GAAG,IAAI,CAAC;AAAA,EACtF;AAEA,QAAM,wBAAwB,OAC5B,UACA,YACkC,8BAA8B,WAAW,UAAU,OAAO;AAE9F,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": ["moduleId"]
7
7
  }
@@ -1,6 +1,9 @@
1
+ import { isDeepStrictEqual } from "node:util";
1
2
  import { NextResponse } from "next/server";
2
3
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
3
4
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
5
+ import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
6
+ import { normalizeCustomFieldOptions } from "@open-mercato/shared/modules/entities/options";
4
7
  import { CustomFieldDef, CustomFieldEntityConfig } from "@open-mercato/core/modules/entities/data/entities";
5
8
  import { customFieldEntityConfigSchema, upsertCustomFieldDefSchema } from "@open-mercato/core/modules/entities/data/validators";
6
9
  import { z } from "zod";
@@ -21,12 +24,16 @@ import {
21
24
  resolveDefinitionMutationScope,
22
25
  selectVisibleDefinitionWinner
23
26
  } from "../lib/definition-scope.js";
27
+ import { createVisibleDefinitionScopeClause } from "../lib/definition-scope-where.js";
24
28
  const metadata = {
25
29
  POST: { requireAuth: true, requireFeatures: ["entities.definitions.manage"] }
26
30
  };
27
31
  const MAX_DEFINITIONS_PER_BATCH = 1e3;
28
32
  const batchSchema = z.object({
29
33
  entityId: z.string().regex(/^[a-z0-9_]+:[a-z0-9_]+$/),
34
+ preserveOrder: z.boolean().optional().describe(
35
+ "Keep existing priorities, append new definitions, and leave unchanged visible definitions untouched."
36
+ ),
30
37
  definitions: z.array(
31
38
  upsertCustomFieldDefSchema.omit({ entityId: true }).extend({
32
39
  configJson: z.any().optional()
@@ -47,6 +54,20 @@ function cloneFieldsets(fieldsets) {
47
54
  })) : void 0
48
55
  }));
49
56
  }
57
+ function normalizeDefinitionConfig(key, kind, input) {
58
+ const config = { ...input };
59
+ if (config.label == null || String(config.label).trim() === "") config.label = key;
60
+ if (config.formEditable === void 0) config.formEditable = true;
61
+ if (config.listVisible === void 0) config.listVisible = true;
62
+ if (kind === "multiline" && (config.editor == null || String(config.editor).trim() === "")) {
63
+ config.editor = "markdown";
64
+ }
65
+ delete config.priority;
66
+ return config;
67
+ }
68
+ function comparableDefinitionConfig(config) {
69
+ return Array.isArray(config.options) ? { ...config, options: normalizeCustomFieldOptions(config.options) } : config;
70
+ }
50
71
  async function POST(req) {
51
72
  const auth = await getAuthFromRequest(req);
52
73
  if (!auth || !auth.orgId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
@@ -58,7 +79,7 @@ async function POST(req) {
58
79
  }
59
80
  const parsed = batchSchema.safeParse(body);
60
81
  if (!parsed.success) return NextResponse.json({ error: "Validation failed", details: parsed.error.flatten() }, { status: 400 });
61
- const { entityId, definitions, fieldsets, singleFieldsetPerRecord } = parsed.data;
82
+ const { entityId, definitions, fieldsets, singleFieldsetPerRecord, preserveOrder = false } = parsed.data;
62
83
  const container = await createRequestContainer();
63
84
  const scope = await resolveDefinitionMutationScope({ auth, container, request: req });
64
85
  const { resolve } = container;
@@ -106,37 +127,46 @@ async function POST(req) {
106
127
  });
107
128
  for (const existing of existingDefs) defByKey.set(existing.key, existing);
108
129
  }
109
- const inheritedByKey = /* @__PURE__ */ new Map();
110
- const inactiveKeys = definitions.filter((d) => d.isActive === false).map((d) => d.key);
111
- if (inactiveKeys.length > 0) {
112
- const visibleDefs = await em.find(CustomFieldDef, createVisibleDefinitionWhere(
113
- entityId,
114
- { $in: inactiveKeys },
115
- scope,
116
- { deletedAt: null, isActive: true }
117
- ));
118
- const grouped = /* @__PURE__ */ new Map();
119
- for (const visible of visibleDefs) {
120
- if (!grouped.has(visible.key)) grouped.set(visible.key, []);
121
- grouped.get(visible.key).push(visible);
130
+ const visibleByKey = /* @__PURE__ */ new Map();
131
+ const inactiveKeys = definitions.filter((definition) => definition.isActive === false).map((definition) => definition.key);
132
+ if (preserveOrder && keys.length > 0 || inactiveKeys.length > 0) {
133
+ const visibility = { deletedAt: null, isActive: true };
134
+ const where = preserveOrder ? { entityId, ...createVisibleDefinitionScopeClause(scope), ...visibility } : createVisibleDefinitionWhere(entityId, { $in: inactiveKeys }, scope, visibility);
135
+ const visibleDefinitions = await findWithDecryption(em, CustomFieldDef, where, void 0, scope);
136
+ for (const visible of visibleDefinitions) {
137
+ const previous = visibleByKey.get(visible.key);
138
+ if (!previous) visibleByKey.set(visible.key, visible);
139
+ else {
140
+ const winner = selectVisibleDefinitionWinner([previous, visible]);
141
+ if (winner) visibleByKey.set(visible.key, winner);
142
+ }
122
143
  }
123
- for (const [key, group] of grouped) {
124
- inheritedByKey.set(key, selectVisibleDefinitionWinner(group));
144
+ }
145
+ let nextPriority = 0;
146
+ if (preserveOrder) {
147
+ for (const visible of visibleByKey.values()) {
148
+ const priority = Number(visible.configJson?.priority ?? 0);
149
+ if (Number.isFinite(priority)) nextPriority = Math.max(nextPriority, priority + 1);
125
150
  }
126
151
  }
127
152
  for (const [idx, d] of definitions.entries()) {
128
153
  const where = createExactDefinitionWhere(entityId, d.key, scope);
129
154
  let def = defByKey.get(d.key);
130
- const inCfg = d.configJson ?? {};
131
- const cfg = { ...inCfg };
132
- if (cfg.label == null || String(cfg.label).trim() === "") cfg.label = d.key;
133
- if (cfg.formEditable === void 0) cfg.formEditable = true;
134
- if (cfg.listVisible === void 0) cfg.listVisible = true;
135
- if (d.kind === "multiline" && (cfg.editor == null || String(cfg.editor).trim() === "")) cfg.editor = "markdown";
136
- cfg.priority = idx;
155
+ const visible = visibleByKey.get(d.key);
156
+ const cfg = normalizeDefinitionConfig(d.key, d.kind, d.configJson);
157
+ if (preserveOrder) {
158
+ const previous = def ?? visible;
159
+ if (d.isActive !== false && previous && previous.isActive !== false && !previous.deletedAt && previous.kind === d.kind && isDeepStrictEqual(
160
+ comparableDefinitionConfig(cfg),
161
+ comparableDefinitionConfig(normalizeDefinitionConfig(d.key, previous.kind, previous.configJson))
162
+ )) continue;
163
+ if (!previous) cfg.priority = nextPriority++;
164
+ else if (previous.configJson?.priority !== void 0) cfg.priority = previous.configJson.priority;
165
+ } else {
166
+ cfg.priority = idx;
167
+ }
137
168
  if (d.isActive === false) {
138
169
  const now = /* @__PURE__ */ new Date();
139
- const inherited = inheritedByKey.get(d.key);
140
170
  if (!def) {
141
171
  def = createScopedDefinitionTombstone(
142
172
  em,
@@ -144,7 +174,7 @@ async function POST(req) {
144
174
  entityId,
145
175
  key: d.key,
146
176
  kind: d.kind,
147
- configJson: inherited?.configJson ?? cfg
177
+ configJson: visible?.configJson ?? cfg
148
178
  },
149
179
  scope,
150
180
  now