@seedprotocol/sdk 0.7.3-next.654.g52217f6 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/{db-D9K_f5cF.js → BasePathResolver-Cm4apKRb.js} +2041 -127
  2. package/dist/BasePathResolver-Cm4apKRb.js.map +1 -0
  3. package/dist/{ClientManager-C-QXqUK9.js → ClientManager-i3nJASkg.js} +249 -147
  4. package/dist/ClientManager-i3nJASkg.js.map +1 -0
  5. package/dist/{Item-C7sUUu2B.js → Item-DBFchXpC.js} +259 -169
  6. package/dist/Item-DBFchXpC.js.map +1 -0
  7. package/dist/{ModelProperty-DJxeOOrc.js → ModelProperty-BS49g01Y.js} +166 -47
  8. package/dist/ModelProperty-BS49g01Y.js.map +1 -0
  9. package/dist/{Schema-fXtvd-yL.js → Schema-CpMNEnUO.js} +53 -42
  10. package/dist/Schema-CpMNEnUO.js.map +1 -0
  11. package/dist/{SchemaValidationService-CvRS2HSO.js → SchemaValidationService-DieV4KL-.js} +15 -17
  12. package/dist/{SchemaValidationService-CvRS2HSO.js.map → SchemaValidationService-DieV4KL-.js.map} +1 -1
  13. package/dist/{backfillMetadataPropertyIds-SXW-8C64.js → backfillMetadataPropertyIds-DSoOoTnX.js} +14 -7
  14. package/dist/{backfillMetadataPropertyIds-SXW-8C64.js.map → backfillMetadataPropertyIds-DSoOoTnX.js.map} +1 -1
  15. package/dist/{configurePlatform-BRw2j0ZN.js → configurePlatform-D0lQGAMQ.js} +5 -7
  16. package/dist/{configurePlatform-BRw2j0ZN.js.map → configurePlatform-D0lQGAMQ.js.map} +1 -1
  17. package/dist/detachRowsBeforeDelete-S0q-DJPT.js +50 -0
  18. package/dist/detachRowsBeforeDelete-S0q-DJPT.js.map +1 -0
  19. package/dist/{eas-DHxfswCt.js → eas-6pjU-OuX.js} +6 -8
  20. package/dist/eas-6pjU-OuX.js.map +1 -0
  21. package/dist/{getItem-d6N_aM6S.js → getItem-CxBNZ-WL.js} +10 -11
  22. package/dist/{getItem-d6N_aM6S.js.map → getItem-CxBNZ-WL.js.map} +1 -1
  23. package/dist/{getPublishPayload-BHrxVtzY.js → getPublishPayload-CTCvRUoU.js} +50 -18
  24. package/dist/getPublishPayload-CTCvRUoU.js.map +1 -0
  25. package/dist/{getPublishUploads-BEqRiKIS.js → getPublishUploads-SFHCbf_y.js} +13 -22
  26. package/dist/{getPublishUploads-BEqRiKIS.js.map → getPublishUploads-SFHCbf_y.js.map} +1 -1
  27. package/dist/{index-s15q14rm.js → index-8O3Uow-Y.js} +125 -57
  28. package/dist/index-8O3Uow-Y.js.map +1 -0
  29. package/dist/{index-DglvthOk.js → index-AVFTVp1m.js} +2 -2
  30. package/dist/index-AVFTVp1m.js.map +1 -0
  31. package/dist/index-Cvt5UBz4.js +30 -0
  32. package/dist/index-Cvt5UBz4.js.map +1 -0
  33. package/dist/{index.browser-Cm06tP4X.js → index.browser-DBhxRoe8.js} +11 -10
  34. package/dist/{index.browser-Cm06tP4X.js.map → index.browser-DBhxRoe8.js.map} +1 -1
  35. package/dist/{index.node-C30dmFgn.js → index.node-CJhlcNHM.js} +25 -13
  36. package/dist/index.node-CJhlcNHM.js.map +1 -0
  37. package/dist/main.js +27 -32
  38. package/dist/main.js.map +1 -1
  39. package/dist/node.js +19 -22
  40. package/dist/node.js.map +1 -1
  41. package/dist/platform.browser.js +9 -9
  42. package/dist/platform.node.js +18 -5
  43. package/dist/platform.node.js.map +1 -1
  44. package/dist/{property-DhmmYAvQ.js → property-DwPD283A.js} +11 -12
  45. package/dist/property-DwPD283A.js.map +1 -0
  46. package/dist/{publishDraftGraph-yYP74WRt.js → publishDraftGraph-BOn3_Occ.js} +6 -9
  47. package/dist/{publishDraftGraph-yYP74WRt.js.map → publishDraftGraph-BOn3_Occ.js.map} +1 -1
  48. package/dist/{resetAmbiguousLegacyItemData-Bk0QyDW8.js → resetAmbiguousLegacyItemData-BkYmBeJc.js} +14 -3
  49. package/dist/{resetAmbiguousLegacyItemData-Bk0QyDW8.js.map → resetAmbiguousLegacyItemData-BkYmBeJc.js.map} +1 -1
  50. package/dist/{resolveModelForSyncedSeed-8cAzvUFd.js → resolveModelForSyncedSeed-BL24nLa7.js} +2 -2
  51. package/dist/{resolveModelForSyncedSeed-8cAzvUFd.js.map → resolveModelForSyncedSeed-BL24nLa7.js.map} +1 -1
  52. package/dist/src/Item/Item.d.ts +20 -2
  53. package/dist/src/Item/Item.d.ts.map +1 -1
  54. package/dist/src/Item/service/actors/runPublish.d.ts +11 -2
  55. package/dist/src/Item/service/actors/runPublish.d.ts.map +1 -1
  56. package/dist/src/Item/service/itemMachineSingle.d.ts +12 -2
  57. package/dist/src/Item/service/itemMachineSingle.d.ts.map +1 -1
  58. package/dist/src/ItemProperty/ItemProperty.d.ts +5 -3
  59. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  60. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  61. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  62. package/dist/src/Model/Model.d.ts +10 -4
  63. package/dist/src/Model/Model.d.ts.map +1 -1
  64. package/dist/src/Model/index.d.ts +2 -2
  65. package/dist/src/ModelProperty/ModelProperty.d.ts +10 -2
  66. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  67. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +3 -0
  68. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  69. package/dist/src/Schema/Schema.d.ts +2 -2
  70. package/dist/src/Schema/Schema.d.ts.map +1 -1
  71. package/dist/src/Schema/index.d.ts +0 -1
  72. package/dist/src/Schema/index.d.ts.map +1 -1
  73. package/dist/src/client/ClientManager.d.ts +30 -11
  74. package/dist/src/client/ClientManager.d.ts.map +1 -1
  75. package/dist/src/client/actors/platformClassesInit.d.ts +6 -0
  76. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  77. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  78. package/dist/src/client/actors/saveConfig.d.ts +13 -6
  79. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  80. package/dist/src/db/read/getPublishPayload.d.ts +1 -1
  81. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  82. package/dist/src/db/write/claimUnpublishedDrafts.d.ts +2 -0
  83. package/dist/src/db/write/claimUnpublishedDrafts.d.ts.map +1 -1
  84. package/dist/src/eventBus.d.ts +5 -0
  85. package/dist/src/eventBus.d.ts.map +1 -1
  86. package/dist/src/helpers/cachedPropertyRefresh.d.ts +12 -0
  87. package/dist/src/helpers/cachedPropertyRefresh.d.ts.map +1 -0
  88. package/dist/src/helpers/db.d.ts +3 -0
  89. package/dist/src/helpers/db.d.ts.map +1 -1
  90. package/dist/src/helpers/easSdk.d.ts +16 -0
  91. package/dist/src/helpers/easSdk.d.ts.map +1 -0
  92. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts +16 -0
  93. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts.map +1 -0
  94. package/dist/src/helpers/entity/entityDestroy.d.ts +2 -0
  95. package/dist/src/helpers/entity/entityDestroy.d.ts.map +1 -1
  96. package/dist/src/helpers/ownership.d.ts +9 -1
  97. package/dist/src/helpers/ownership.d.ts.map +1 -1
  98. package/dist/src/helpers/property/index.d.ts +37 -51
  99. package/dist/src/helpers/property/index.d.ts.map +1 -1
  100. package/dist/src/helpers/publishConfig.d.ts +27 -8
  101. package/dist/src/helpers/publishConfig.d.ts.map +1 -1
  102. package/dist/src/helpers/updateSchema.d.ts +5 -0
  103. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  104. package/dist/src/helpers/waitForEntityIdle.d.ts +5 -0
  105. package/dist/src/helpers/waitForEntityIdle.d.ts.map +1 -1
  106. package/dist/src/imports/json.d.ts +9 -0
  107. package/dist/src/imports/json.d.ts.map +1 -1
  108. package/dist/src/index.d.ts +6 -4
  109. package/dist/src/index.d.ts.map +1 -1
  110. package/dist/src/interfaces/IItem.d.ts +7 -1
  111. package/dist/src/interfaces/IItem.d.ts.map +1 -1
  112. package/dist/src/node/db/Db.d.ts.map +1 -1
  113. package/dist/src/node/helpers/PathResolver.d.ts.map +1 -1
  114. package/dist/src/node/index.d.ts +8 -1
  115. package/dist/src/node/index.d.ts.map +1 -1
  116. package/dist/src/platform/index.browser.d.ts +2 -0
  117. package/dist/src/platform/index.browser.d.ts.map +1 -1
  118. package/dist/src/platform/index.node.d.ts +2 -0
  119. package/dist/src/platform/index.node.d.ts.map +1 -1
  120. package/dist/src/types/index.d.ts +12 -1
  121. package/dist/src/types/index.d.ts.map +1 -1
  122. package/dist/src/types/machines.d.ts +2 -0
  123. package/dist/src/types/machines.d.ts.map +1 -1
  124. package/dist/src/types/property.d.ts +8 -0
  125. package/dist/src/types/property.d.ts.map +1 -1
  126. package/dist/{syncDbWithEas--HUA9WNb.js → syncDbWithEas-Bv2Fe38J.js} +15 -16
  127. package/dist/syncDbWithEas-Bv2Fe38J.js.map +1 -0
  128. package/dist/tabEvents-9s2WCYw-.js +335 -0
  129. package/dist/tabEvents-9s2WCYw-.js.map +1 -0
  130. package/dist/{tolerantWebAccess-BZYWt09Y.js → tolerantWebAccess-iUu80pAP.js} +9 -9
  131. package/dist/{tolerantWebAccess-BZYWt09Y.js.map → tolerantWebAccess-iUu80pAP.js.map} +1 -1
  132. package/dist/{updateSeedRevokedAt-D_EG-q3b.js → updateSeedRevokedAt-zBfi931j.js} +3 -3
  133. package/dist/{updateSeedRevokedAt-D_EG-q3b.js.map → updateSeedRevokedAt-zBfi931j.js.map} +1 -1
  134. package/package.json +11 -12
  135. package/src/node/easLodashRegister.js +4 -0
  136. package/dist/BasePathResolver-CfSfMW5_.js +0 -676
  137. package/dist/BasePathResolver-CfSfMW5_.js.map +0 -1
  138. package/dist/ClientManager-C-QXqUK9.js.map +0 -1
  139. package/dist/Item-C7sUUu2B.js.map +0 -1
  140. package/dist/ModelProperty-DJxeOOrc.js.map +0 -1
  141. package/dist/Schema-fXtvd-yL.js.map +0 -1
  142. package/dist/cjs/ModelProperty-DXZ39Wyv.js +0 -1978
  143. package/dist/cjs/ModelProperty-DXZ39Wyv.js.map +0 -1
  144. package/dist/cjs/Schema-DdP109QD.js +0 -5257
  145. package/dist/cjs/Schema-DdP109QD.js.map +0 -1
  146. package/dist/cjs/SchemaValidationService-CSXxx7sQ.js +0 -779
  147. package/dist/cjs/SchemaValidationService-CSXxx7sQ.js.map +0 -1
  148. package/dist/cjs/backfillMetadataPropertyIds-CPYoaMl4.js +0 -90
  149. package/dist/cjs/backfillMetadataPropertyIds-CPYoaMl4.js.map +0 -1
  150. package/dist/cjs/eas-B2YDQssV.js +0 -139
  151. package/dist/cjs/eas-B2YDQssV.js.map +0 -1
  152. package/dist/cjs/getItem-DgnaQzbE.js +0 -59
  153. package/dist/cjs/getItem-DgnaQzbE.js.map +0 -1
  154. package/dist/cjs/getPublishPayload-CqlqRdot.js +0 -1604
  155. package/dist/cjs/getPublishPayload-CqlqRdot.js.map +0 -1
  156. package/dist/cjs/getPublishUploads-DsXY9S4U.js +0 -872
  157. package/dist/cjs/getPublishUploads-DsXY9S4U.js.map +0 -1
  158. package/dist/cjs/index-BHaWOwNF.js +0 -71
  159. package/dist/cjs/index-BHaWOwNF.js.map +0 -1
  160. package/dist/cjs/index-C4XlgCJ4.js +0 -22801
  161. package/dist/cjs/index-C4XlgCJ4.js.map +0 -1
  162. package/dist/cjs/index.browser-BSf8HpnU.js +0 -22
  163. package/dist/cjs/index.browser-BSf8HpnU.js.map +0 -1
  164. package/dist/cjs/property-fa0iju0J.js +0 -328
  165. package/dist/cjs/property-fa0iju0J.js.map +0 -1
  166. package/dist/cjs/publishDraftGraph-3ASwAlD7.js +0 -403
  167. package/dist/cjs/publishDraftGraph-3ASwAlD7.js.map +0 -1
  168. package/dist/cjs/resetAmbiguousLegacyItemData-Bu_MBBYt.js +0 -117
  169. package/dist/cjs/resetAmbiguousLegacyItemData-Bu_MBBYt.js.map +0 -1
  170. package/dist/cjs/resolveModelForSyncedSeed-BANIiuFU.js +0 -49
  171. package/dist/cjs/resolveModelForSyncedSeed-BANIiuFU.js.map +0 -1
  172. package/dist/cjs/syncDbWithEas-CrmxxmUW.js +0 -887
  173. package/dist/cjs/syncDbWithEas-CrmxxmUW.js.map +0 -1
  174. package/dist/db-D9K_f5cF.js.map +0 -1
  175. package/dist/eas-DHxfswCt.js.map +0 -1
  176. package/dist/getPublishPayload-BHrxVtzY.js.map +0 -1
  177. package/dist/index-CiMEoGu3.js +0 -32
  178. package/dist/index-CiMEoGu3.js.map +0 -1
  179. package/dist/index-DglvthOk.js.map +0 -1
  180. package/dist/index-s15q14rm.js.map +0 -1
  181. package/dist/index.node-C30dmFgn.js.map +0 -1
  182. package/dist/main.cjs +0 -85
  183. package/dist/main.cjs.map +0 -1
  184. package/dist/property-DhmmYAvQ.js.map +0 -1
  185. package/dist/syncDbWithEas--HUA9WNb.js.map +0 -1
  186. package/dist/tabEvents-DguZpCCv.js +0 -1580
  187. package/dist/tabEvents-DguZpCCv.js.map +0 -1
@@ -1,779 +0,0 @@
1
- 'use strict';
2
-
3
- var value = require('@sinclair/typebox/value');
4
- require('reflect-metadata');
5
- var main_cjs = require('./index-C4XlgCJ4.js');
6
- require('pluralize');
7
- require('drizzle-orm');
8
- var typebox = require('@sinclair/typebox');
9
- var debug = require('debug');
10
- require('immer');
11
- require('xstate');
12
- require('drizzle-orm/sqlite-core');
13
- require('@seedprotocol/arweave');
14
- require('@seedprotocol/eas');
15
- require('drizzle-orm/casing');
16
- require('lodash-es');
17
- require('@noble/hashes/sha256');
18
- require('@noble/hashes/sha3');
19
- require('@noble/hashes/utils');
20
- require('nanoid');
21
- require('nanoid-dictionary');
22
- require('@seedprotocol/query');
23
- require('rxjs');
24
- require('fs/promises');
25
- require('fs');
26
- require('path');
27
- require('url');
28
- require('node:url');
29
- require('@libsql/client');
30
- require('drizzle-orm/libsql');
31
- require('drizzle-orm/libsql/migrator');
32
- require('js-yaml');
33
- require('child_process');
34
- require('@seedprotocol/arweave/node');
35
- require('@seedprotocol/eas/node');
36
-
37
- const logger = debug('seedSdk:schema:validation');
38
- /**
39
- * Service for validating schemas, models, and properties using TypeBox
40
- */
41
- class SchemaValidationService {
42
- /**
43
- * Enhance TypeBox error message with expected values for union/literal types
44
- */
45
- enhanceErrorMessage(error, schema, fieldPath) {
46
- const originalMessage = error.message || 'Validation failed';
47
- // Handle Union type errors (like TPropertyDataType)
48
- if (error.type === 'Union' || originalMessage.includes('union')) {
49
- const expectedValues = this.extractExpectedValues(schema, fieldPath);
50
- if (expectedValues.length > 0) {
51
- return `Expected one of: ${expectedValues.join(', ')}. Received: ${JSON.stringify(error.value)}`;
52
- }
53
- }
54
- // Handle Literal type errors
55
- if (error.type === 'Literal') {
56
- const expectedValue = this.extractLiteralValue(schema, fieldPath);
57
- if (expectedValue !== undefined) {
58
- return `Expected: ${JSON.stringify(expectedValue)}. Received: ${JSON.stringify(error.value)}`;
59
- }
60
- }
61
- // Return enhanced message with value info if available
62
- if (error.value !== undefined) {
63
- return `${originalMessage}. Received: ${JSON.stringify(error.value)}`;
64
- }
65
- return originalMessage;
66
- }
67
- /**
68
- * Extract expected values from a schema for a given field path
69
- */
70
- extractExpectedValues(schema, fieldPath) {
71
- try {
72
- // Handle TProperty schema - check if this is the dataType field
73
- if (fieldPath === '/dataType' || fieldPath.endsWith('/dataType')) {
74
- // Return all ModelPropertyDataTypes enum values
75
- return Object.values(main_cjs.ModelPropertyDataTypes);
76
- }
77
- // Handle TStorageType
78
- if (fieldPath === '/storageType' || fieldPath.endsWith('/storageType')) {
79
- return ['ItemStorage', 'PropertyStorage'];
80
- }
81
- // If we have a schema, try to extract from it
82
- if (!schema) {
83
- return [];
84
- }
85
- // Try to extract from TypeBox Union type using the schema directly
86
- const schemaObj = schema;
87
- const kind = schemaObj[Symbol.for('TypeBox.Kind')];
88
- if (kind === 'Union') {
89
- const union = schemaObj;
90
- const anyOf = union.anyOf || [];
91
- const values = [];
92
- for (const item of anyOf) {
93
- const itemKind = item?.[Symbol.for('TypeBox.Kind')];
94
- if (itemKind === 'Literal') {
95
- const literal = item;
96
- if (literal.const !== undefined) {
97
- values.push(String(literal.const));
98
- }
99
- }
100
- }
101
- if (values.length > 0) {
102
- return values;
103
- }
104
- }
105
- // Fallback: try to extract from JSON schema format
106
- if (typeof schema === 'object' && 'anyOf' in schema) {
107
- const union = schema;
108
- if (Array.isArray(union.anyOf)) {
109
- return union.anyOf
110
- .map((item) => {
111
- if (item.const !== undefined)
112
- return String(item.const);
113
- if (item.enum && Array.isArray(item.enum))
114
- return item.enum.map(String);
115
- return null;
116
- })
117
- .filter((val) => val !== null)
118
- .flat()
119
- .map(String);
120
- }
121
- }
122
- }
123
- catch (error) {
124
- logger('Error extracting expected values:', error);
125
- }
126
- return [];
127
- }
128
- /**
129
- * Extract literal value from a schema
130
- */
131
- extractLiteralValue(schema, fieldPath) {
132
- try {
133
- if (schema && typeof schema === 'object') {
134
- const schemaObj = schema;
135
- if (schemaObj[Symbol.for('TypeBox.Kind')] === 'Literal') {
136
- return schemaObj.const;
137
- }
138
- if (schemaObj.const !== undefined) {
139
- return schemaObj.const;
140
- }
141
- }
142
- }
143
- catch (error) {
144
- logger('Error extracting literal value:', error);
145
- }
146
- return undefined;
147
- }
148
- /**
149
- * Get the schema for a specific field path
150
- */
151
- getSchemaForField(schema, fieldPath) {
152
- try {
153
- if (!schema || typeof schema !== 'object')
154
- return null;
155
- // Remove leading slash
156
- const path = fieldPath.replace(/^\//, '');
157
- if (!path)
158
- return schema;
159
- const schemaObj = schema;
160
- const kind = schemaObj[Symbol.for('TypeBox.Kind')];
161
- // For TProperty (Object type), check properties
162
- if (kind === 'Object') {
163
- const properties = schemaObj.properties;
164
- if (properties && properties[path]) {
165
- return properties[path];
166
- }
167
- }
168
- // Special handling for known fields - return the actual schema
169
- if (path === 'dataType') {
170
- return main_cjs.TPropertyDataType;
171
- }
172
- // Fallback: check if schema has the property
173
- if (path in schemaObj) {
174
- return schemaObj[path];
175
- }
176
- }
177
- catch (error) {
178
- logger('Error getting schema for field:', error);
179
- }
180
- return null;
181
- }
182
- /**
183
- * Validate a property structure against TProperty schema
184
- */
185
- validatePropertyStructure(property) {
186
- try {
187
- // Normalize dataType and refValueType for case-insensitive schema support (e.g. "relation" -> "Relation")
188
- const normalized = { ...property };
189
- if (typeof normalized.dataType === 'string') {
190
- normalized.dataType = main_cjs.normalizeDataType(normalized.dataType);
191
- }
192
- if (typeof normalized.refValueType === 'string') {
193
- normalized.refValueType = main_cjs.normalizeDataType(normalized.refValueType);
194
- }
195
- const isValid = value.Value.Check(main_cjs.TProperty, normalized);
196
- const errors = [];
197
- if (!isValid) {
198
- const typeBoxErrors = [...value.Value.Errors(main_cjs.TProperty, normalized)];
199
- errors.push(...typeBoxErrors.map(err => {
200
- const fieldPath = err.path || 'unknown';
201
- const fieldSchema = this.getSchemaForField(main_cjs.TProperty, fieldPath);
202
- const enhancedMessage = this.enhanceErrorMessage(err, fieldSchema || main_cjs.TProperty, fieldPath);
203
- return {
204
- field: fieldPath,
205
- message: enhancedMessage,
206
- code: String(err.type || 'validation_error'),
207
- severity: 'error',
208
- };
209
- }));
210
- }
211
- // Non-List types: refValueType is only valid for Relation+Image (related entity type). Reject otherwise.
212
- const nonListTypes = [
213
- main_cjs.ModelPropertyDataTypes.Text,
214
- main_cjs.ModelPropertyDataTypes.Number,
215
- main_cjs.ModelPropertyDataTypes.Boolean,
216
- main_cjs.ModelPropertyDataTypes.Date,
217
- main_cjs.ModelPropertyDataTypes.Json,
218
- main_cjs.ModelPropertyDataTypes.Image,
219
- main_cjs.ModelPropertyDataTypes.File,
220
- main_cjs.ModelPropertyDataTypes.Html,
221
- main_cjs.ModelPropertyDataTypes.Relation,
222
- ];
223
- if (nonListTypes.includes(normalized.dataType)) {
224
- const hasRefValueType = normalized.refValueType != null && String(normalized.refValueType).trim() !== '';
225
- if (hasRefValueType) {
226
- // Relation may keep refValueType only for Image (relation to Image entity)
227
- if (normalized.dataType === main_cjs.ModelPropertyDataTypes.Relation && normalized.refValueType === main_cjs.ModelPropertyDataTypes.Image) {
228
- // Allowed: Relation to Image
229
- }
230
- else {
231
- errors.push({
232
- field: 'refValueType',
233
- message: `refValueType is only valid for List properties. Use dataType 'List' with refValueType '${normalized.refValueType}' for lists of ${normalized.refValueType}.`,
234
- code: 'invalid_ref_value_type',
235
- severity: 'error',
236
- });
237
- }
238
- }
239
- }
240
- // List: refValueType is required
241
- if (normalized.dataType === main_cjs.ModelPropertyDataTypes.List) {
242
- const hasRefValueType = normalized.refValueType != null && String(normalized.refValueType).trim() !== '';
243
- if (!hasRefValueType) {
244
- errors.push({
245
- field: 'refValueType',
246
- message: `List properties require refValueType (e.g. 'Text', 'Number', 'Relation') to specify the element type.`,
247
- code: 'missing_ref_value_type',
248
- severity: 'error',
249
- });
250
- }
251
- // List of relations: ref is required
252
- if (hasRefValueType && normalized.refValueType === main_cjs.ModelPropertyDataTypes.Relation) {
253
- const hasRef = normalized.ref && normalized.ref.trim() !== '';
254
- const hasRefModelName = normalized.refModelName && normalized.refModelName.trim() !== '';
255
- const hasRefModelId = normalized.refModelId !== undefined && normalized.refModelId !== null;
256
- if (!hasRef && !hasRefModelName && !hasRefModelId) {
257
- errors.push({
258
- field: 'ref',
259
- message: `List properties with refValueType 'Relation' require either a "ref", "refModelName", or "refModelId" field to be defined`,
260
- code: 'missing_ref',
261
- severity: 'error',
262
- });
263
- }
264
- }
265
- }
266
- // Relation (single): ref is required
267
- if (normalized.dataType === main_cjs.ModelPropertyDataTypes.Relation) {
268
- const hasRef = normalized.ref && normalized.ref.trim() !== '';
269
- const hasRefModelName = normalized.refModelName && normalized.refModelName.trim() !== '';
270
- const hasRefModelId = normalized.refModelId !== undefined && normalized.refModelId !== null;
271
- if (!hasRef && !hasRefModelName && !hasRefModelId) {
272
- errors.push({
273
- field: 'ref',
274
- message: `Property with dataType "Relation" requires either a "ref", "refModelName", or "refModelId" field to be defined`,
275
- code: 'missing_ref',
276
- severity: 'error',
277
- });
278
- }
279
- if ((hasRef || hasRefModelName) && !hasRefModelId) {
280
- logger(`Property "${normalized.name}" has ref/refModelName but no refModelId - will be resolved asynchronously`);
281
- }
282
- }
283
- return {
284
- isValid: errors.length === 0,
285
- errors,
286
- };
287
- }
288
- catch (error) {
289
- logger('Error validating property structure:', error);
290
- return {
291
- isValid: false,
292
- errors: [{
293
- field: 'property',
294
- message: error instanceof Error ? error.message : 'Unknown validation error',
295
- code: 'validation_exception',
296
- severity: 'error',
297
- }],
298
- };
299
- }
300
- }
301
- /**
302
- * Validate a property value against its validation rules
303
- * @param value - The value to validate
304
- * @param dataType - The property's data type
305
- * @param validationRules - Optional validation rules (enum, pattern, minLength, maxLength)
306
- * @param refValueType - For List properties: the element type (Text, Number, etc.). When set, each array element is validated against this type + validationRules.
307
- */
308
- validatePropertyValue(value$1, dataType, validationRules, refValueType) {
309
- dataType = main_cjs.normalizeDataType(dataType);
310
- const errors = [];
311
- const warnings = [];
312
- try {
313
- // Array values are only allowed for List properties
314
- if (dataType !== main_cjs.ModelPropertyDataTypes.List && Array.isArray(value$1)) {
315
- errors.push({
316
- field: 'value',
317
- message: 'Array values are only allowed for List properties. Use dataType "List" with refValueType to store multiple values.',
318
- code: 'array_not_allowed',
319
- severity: 'error',
320
- });
321
- }
322
- // File/Image: accept File objects from OS picker, and Blobs for Image (saveImage persists both).
323
- // The TypeBox schema only allows string|null.
324
- const isFileObject = typeof File !== 'undefined' && value$1 instanceof File;
325
- const isBlobObject = typeof Blob !== 'undefined' && value$1 instanceof Blob;
326
- if ((dataType === main_cjs.ModelPropertyDataTypes.File && isFileObject) ||
327
- (dataType === main_cjs.ModelPropertyDataTypes.Image && isBlobObject)) {
328
- if (validationRules) {
329
- const customErrors = this.validateCustomRules(value$1, validationRules);
330
- errors.push(...customErrors);
331
- }
332
- return {
333
- isValid: errors.length === 0,
334
- errors,
335
- warnings: warnings.length > 0 ? warnings : undefined,
336
- };
337
- }
338
- // List with refValueType: validate each element against element schema + validation rules
339
- if (dataType === main_cjs.ModelPropertyDataTypes.List && refValueType && Array.isArray(value$1)) {
340
- const elementDataType = main_cjs.normalizeDataType(String(refValueType));
341
- // Apply default maxLength for Text elements in List. Html elements hold arbitrary-length content.
342
- const elementEffectiveRules = validationRules ? { ...validationRules } : {};
343
- if (elementDataType === main_cjs.ModelPropertyDataTypes.Text && elementEffectiveRules.maxLength === undefined) {
344
- elementEffectiveRules.maxLength = main_cjs.DEFAULT_TEXT_MAX_LENGTH;
345
- }
346
- for (let i = 0; i < value$1.length; i++) {
347
- const elementResult = this.validatePropertyValue(value$1[i], elementDataType, elementEffectiveRules);
348
- if (!elementResult.isValid && elementResult.errors.length > 0) {
349
- for (const err of elementResult.errors) {
350
- errors.push({
351
- field: `value[${i}]`,
352
- message: `Element at index ${i}: ${err.message}`,
353
- code: validationRules?.enum && Array.isArray(validationRules.enum) && validationRules.enum.length > 0 ? 'enum_violation' : err.code,
354
- severity: err.severity,
355
- });
356
- }
357
- }
358
- }
359
- if (validationRules) {
360
- const customErrors = this.validateCustomRules(value$1, validationRules);
361
- errors.push(...customErrors);
362
- }
363
- return {
364
- isValid: errors.length === 0,
365
- errors,
366
- warnings: warnings.length > 0 ? warnings : undefined,
367
- };
368
- }
369
- // List without refValueType or non-array: validate as scalar/array
370
- if (dataType === main_cjs.ModelPropertyDataTypes.List && !Array.isArray(value$1) && value$1 != null) {
371
- errors.push({
372
- field: 'value',
373
- message: 'List properties require an array value.',
374
- code: 'array_required',
375
- severity: 'error',
376
- });
377
- return { isValid: false, errors };
378
- }
379
- // Build base TypeBox schema from dataType
380
- let schema = this.getBaseSchemaForDataType(dataType);
381
- // Apply default maxLength for Text when not explicitly set. Html holds arbitrary-length content (e.g. article body) and must not default to 255.
382
- const effectiveRules = validationRules ? { ...validationRules } : {};
383
- if (dataType === main_cjs.ModelPropertyDataTypes.Text && effectiveRules.maxLength === undefined) {
384
- effectiveRules.maxLength = main_cjs.DEFAULT_TEXT_MAX_LENGTH;
385
- }
386
- // Apply validation rules
387
- const hasEnumRules = !!(validationRules?.enum && Array.isArray(validationRules.enum) && validationRules.enum.length > 0);
388
- if (Object.keys(effectiveRules).length > 0) {
389
- schema = this.applyValidationRules(schema, dataType, effectiveRules);
390
- }
391
- // Validate using TypeBox
392
- const isValid = value.Value.Check(schema, value$1);
393
- if (!isValid) {
394
- const typeBoxErrors = [...value.Value.Errors(schema, value$1)];
395
- const effectiveMaxLength = effectiveRules.maxLength;
396
- const isDefaultTextLimit = dataType === main_cjs.ModelPropertyDataTypes.Text &&
397
- effectiveMaxLength === main_cjs.DEFAULT_TEXT_MAX_LENGTH &&
398
- validationRules?.maxLength === undefined;
399
- errors.push(...typeBoxErrors.map(err => {
400
- const fieldPath = err.path || 'value';
401
- const originalMessage = (err.message || '').toLowerCase();
402
- // TypeBox maxLength errors have message like "Expected string length less or equal to X"
403
- const isMaxLengthError = originalMessage.includes('length') && (originalMessage.includes('less') || originalMessage.includes('equal') || originalMessage.includes('max'));
404
- let enhancedMessage;
405
- if (isMaxLengthError && effectiveMaxLength !== undefined) {
406
- const typeLabel = dataType === main_cjs.ModelPropertyDataTypes.Html ? 'Html' : 'Text';
407
- if (isDefaultTextLimit) {
408
- enhancedMessage = `Text properties have a default limit of 255 characters. For longer content, use a File property instead, which can hold arbitrary amounts of text or data.`;
409
- }
410
- else {
411
- enhancedMessage = `${typeLabel} must be ${effectiveMaxLength} characters or less. For longer content, use a File property instead, which can hold arbitrary amounts of text or data.`;
412
- }
413
- }
414
- else {
415
- enhancedMessage = this.enhanceErrorMessage(err, schema, fieldPath);
416
- }
417
- // Use max_length_exceeded when failure is due to maxLength; enum_violation when enum rules; else generic
418
- const code = isMaxLengthError
419
- ? 'max_length_exceeded'
420
- : hasEnumRules
421
- ? 'enum_violation'
422
- : String(err.type || 'value_validation_error');
423
- return {
424
- field: fieldPath,
425
- message: enhancedMessage,
426
- code,
427
- severity: 'error',
428
- };
429
- }));
430
- }
431
- // Additional custom validations
432
- if (validationRules) {
433
- const customErrors = this.validateCustomRules(value$1, validationRules);
434
- errors.push(...customErrors);
435
- }
436
- return {
437
- isValid: errors.length === 0,
438
- errors,
439
- warnings: warnings.length > 0 ? warnings : undefined,
440
- };
441
- }
442
- catch (error) {
443
- logger('Error validating property value:', error);
444
- return {
445
- isValid: false,
446
- errors: [{
447
- field: 'value',
448
- message: error instanceof Error ? error.message : 'Unknown validation error',
449
- code: 'validation_exception',
450
- severity: 'error',
451
- }],
452
- };
453
- }
454
- }
455
- /**
456
- * Validate a specific property within a schema
457
- */
458
- validateProperty(schema, modelName, propertyName, propertyData) {
459
- const errors = [];
460
- // Check if model exists
461
- if (!schema.models || !schema.models[modelName]) {
462
- errors.push({
463
- field: 'model',
464
- message: `Model "${modelName}" not found in schema`,
465
- code: 'model_not_found',
466
- severity: 'error',
467
- });
468
- return { isValid: false, errors };
469
- }
470
- const model = schema.models[modelName];
471
- // Check if property exists in model
472
- // If the property name has changed (renamed), check if the original name exists
473
- let propertyDefinition = model.properties?.[propertyName];
474
- if (!propertyDefinition && propertyData?._originalValues?.name) {
475
- const originalName = propertyData._originalValues.name;
476
- // If the current name differs from the original, check if original exists
477
- if (originalName !== propertyName && model.properties?.[originalName]) {
478
- propertyDefinition = model.properties[originalName];
479
- // Property is being renamed, which is allowed - continue validation
480
- }
481
- }
482
- if (!propertyDefinition) {
483
- errors.push({
484
- field: 'property',
485
- message: `Property "${propertyName}" not found in model "${modelName}"`,
486
- code: 'property_not_found',
487
- severity: 'error',
488
- });
489
- return { isValid: false, errors };
490
- }
491
- // If propertyData is provided, validate its structure
492
- if (propertyData) {
493
- const structureResult = this.validatePropertyStructure(propertyData);
494
- errors.push(...structureResult.errors);
495
- }
496
- // Schema context definitions come in two shapes: schema-file ({ type, model }) and runtime
497
- // ({ dataType, ref/refModelName }, e.g. models added from Model instances). Accept both, as the
498
- // List check below already does; requiring `type` rejected every edit to a runtime-shaped property.
499
- const definitionType = propertyDefinition.type ?? propertyDefinition.dataType;
500
- const definitionRefModel = propertyDefinition.model ?? propertyDefinition.ref ?? propertyDefinition.refModelName;
501
- // Validate property definition structure
502
- if (!definitionType) {
503
- errors.push({
504
- field: 'property.type',
505
- message: 'Property type is required',
506
- code: 'missing_type',
507
- severity: 'error',
508
- });
509
- }
510
- // Validate Relation: requires model
511
- if (main_cjs.isDataType(definitionType, main_cjs.ModelPropertyDataTypes.Relation)) {
512
- if (!definitionRefModel || definitionRefModel.trim() === '') {
513
- errors.push({
514
- field: 'property.model',
515
- message: `Property with type "Relation" requires a "model" field to be defined`,
516
- code: 'missing_ref',
517
- severity: 'error',
518
- });
519
- }
520
- else if (!schema.models[definitionRefModel]) {
521
- errors.push({
522
- field: 'property.model',
523
- message: `Referenced model "${definitionRefModel}" not found in schema`,
524
- code: 'invalid_reference',
525
- severity: 'error',
526
- });
527
- }
528
- }
529
- // Validate List: requires refValueType; ref (model) required only when refValueType === 'Relation' (case-insensitive)
530
- if (main_cjs.isDataType(propertyDefinition.type, main_cjs.ModelPropertyDataTypes.List) || main_cjs.isDataType(propertyDefinition.dataType, main_cjs.ModelPropertyDataTypes.List)) {
531
- const rawRefValueType = propertyDefinition.refValueType ?? propertyDefinition.items?.type ?? propertyDefinition.refvaluetype;
532
- const refValueType = rawRefValueType ? main_cjs.normalizeDataType(String(rawRefValueType)) : undefined;
533
- if (!refValueType || String(refValueType).trim() === '') {
534
- errors.push({
535
- field: 'property.refValueType',
536
- message: 'List properties require "refValueType" (e.g. refValueType: "Text" or refValueType: "Relation" with ref: "Tag")',
537
- code: 'missing_ref_value_type',
538
- severity: 'error',
539
- });
540
- }
541
- else if (refValueType === 'Relation' || refValueType === 'RelationProperty') {
542
- const model = propertyDefinition.ref ?? propertyDefinition.model ?? propertyDefinition.items?.model;
543
- if (!model || String(model).trim() === '') {
544
- errors.push({
545
- field: 'property.ref',
546
- message: 'List of relations requires "ref" to specify the related model',
547
- code: 'missing_ref',
548
- severity: 'error',
549
- });
550
- }
551
- else if (schema.models && !schema.models[model]) {
552
- errors.push({
553
- field: 'property.ref',
554
- message: `Referenced model "${model}" not found in schema`,
555
- code: 'invalid_reference',
556
- severity: 'error',
557
- });
558
- }
559
- }
560
- }
561
- return {
562
- isValid: errors.length === 0,
563
- errors,
564
- };
565
- }
566
- /**
567
- * Validate model structure (basic structure checks)
568
- */
569
- validateModelStructure(model) {
570
- const errors = [];
571
- // Validate model name
572
- if (!model.modelName || model.modelName.trim() === '') {
573
- errors.push({
574
- field: 'modelName',
575
- message: 'Model name is required',
576
- code: 'missing_model_name',
577
- severity: 'error',
578
- });
579
- }
580
- // Validate schema name
581
- if (!model.schemaName || model.schemaName.trim() === '') {
582
- errors.push({
583
- field: 'schemaName',
584
- message: 'Schema name is required',
585
- code: 'missing_schema_name',
586
- severity: 'error',
587
- });
588
- }
589
- // Validate properties is an object
590
- if (model.properties && typeof model.properties !== 'object') {
591
- errors.push({
592
- field: 'properties',
593
- message: 'Properties must be an object',
594
- code: 'invalid_properties',
595
- severity: 'error',
596
- });
597
- }
598
- return {
599
- isValid: errors.length === 0,
600
- errors,
601
- };
602
- }
603
- /**
604
- * Validate a model against a schema WITHOUT requiring it to be in the schema's context
605
- * This allows validation before registration, preventing update loops
606
- */
607
- validateModelAgainstSchema(schema, modelName, modelData) {
608
- // Create a temporary schema context that includes this model for validation purposes
609
- // This allows validateProperty to work without actually adding the model to the real schema
610
- const tempSchemaContext = {
611
- ...schema,
612
- models: {
613
- ...schema.models,
614
- [modelName]: {
615
- properties: modelData.properties || {},
616
- },
617
- },
618
- };
619
- // Use validateModel which now works because the model is in the temp context
620
- return this.validateModel(tempSchemaContext, modelName, modelData);
621
- }
622
- /**
623
- * Validate a model within a schema (requires model to already be in schema context)
624
- */
625
- validateModel(schema, modelName, modelData) {
626
- const errors = [];
627
- if (!schema.models || !schema.models[modelName]) {
628
- errors.push({
629
- field: 'model',
630
- message: `Model "${modelName}" not found in schema`,
631
- code: 'model_not_found',
632
- severity: 'error',
633
- });
634
- return { isValid: false, errors };
635
- }
636
- const model = schema.models[modelName];
637
- // Validate all properties in the model
638
- if (model.properties) {
639
- for (const [propertyName, propertyDef] of Object.entries(model.properties)) {
640
- const propertyResult = this.validateProperty(schema, modelName, propertyName);
641
- if (!propertyResult.isValid) {
642
- errors.push(...propertyResult.errors.map(err => ({
643
- ...err,
644
- field: `${modelName}.${propertyName}.${err.field}`,
645
- })));
646
- }
647
- }
648
- }
649
- return {
650
- isValid: errors.length === 0,
651
- errors,
652
- };
653
- }
654
- /**
655
- * Validate entire schema
656
- */
657
- validateSchema(schema) {
658
- const errors = [];
659
- // Validate schema name
660
- if (!schema.schemaName || schema.schemaName.trim() === '') {
661
- errors.push({
662
- field: 'schemaName',
663
- message: 'Schema name is required',
664
- code: 'missing_schema_name',
665
- severity: 'error',
666
- });
667
- }
668
- // Validate metadata
669
- if (!schema.metadata) {
670
- errors.push({
671
- field: 'metadata',
672
- message: 'Schema metadata is required',
673
- code: 'missing_metadata',
674
- severity: 'error',
675
- });
676
- }
677
- else {
678
- if (!schema.metadata.name || schema.metadata.name.trim() === '') {
679
- errors.push({
680
- field: 'metadata.name',
681
- message: 'Schema metadata name is required',
682
- code: 'missing_metadata_name',
683
- severity: 'error',
684
- });
685
- }
686
- }
687
- // Validate models if they exist
688
- if (schema.models && Object.keys(schema.models).length > 0) {
689
- // Validate each model
690
- for (const modelName of Object.keys(schema.models)) {
691
- const modelResult = this.validateModel(schema, modelName);
692
- if (!modelResult.isValid) {
693
- errors.push(...modelResult.errors);
694
- }
695
- }
696
- }
697
- return {
698
- isValid: errors.length === 0,
699
- errors,
700
- };
701
- }
702
- /**
703
- * Get base TypeBox schema for a data type
704
- */
705
- getBaseSchemaForDataType(dataType) {
706
- switch (dataType) {
707
- case main_cjs.ModelPropertyDataTypes.Text:
708
- case main_cjs.ModelPropertyDataTypes.Html:
709
- return typebox.Type.String();
710
- case main_cjs.ModelPropertyDataTypes.Number:
711
- return typebox.Type.Number();
712
- case main_cjs.ModelPropertyDataTypes.Boolean:
713
- return typebox.Type.Boolean();
714
- case main_cjs.ModelPropertyDataTypes.Date:
715
- return typebox.Type.String({ format: 'date-time' });
716
- case main_cjs.ModelPropertyDataTypes.Json:
717
- return typebox.Type.Any();
718
- case main_cjs.ModelPropertyDataTypes.List:
719
- return typebox.Type.Array(typebox.Type.Any());
720
- case main_cjs.ModelPropertyDataTypes.Relation:
721
- case main_cjs.ModelPropertyDataTypes.Image:
722
- case main_cjs.ModelPropertyDataTypes.File:
723
- return typebox.Type.Union([typebox.Type.String(), typebox.Type.Null()]);
724
- default:
725
- return typebox.Type.Any();
726
- }
727
- }
728
- /**
729
- * Apply validation rules to a TypeBox schema
730
- */
731
- applyValidationRules(schema, dataType, rules) {
732
- let result = schema;
733
- // Apply pattern (regex) for strings
734
- if (rules.pattern && (dataType === main_cjs.ModelPropertyDataTypes.Text || dataType === main_cjs.ModelPropertyDataTypes.Html)) {
735
- try {
736
- const regex = new RegExp(rules.pattern);
737
- result = typebox.Type.RegExp(regex);
738
- }
739
- catch (error) {
740
- logger('Invalid regex pattern:', rules.pattern, error);
741
- }
742
- }
743
- // Apply minLength/maxLength for strings
744
- if (dataType === main_cjs.ModelPropertyDataTypes.Text || dataType === main_cjs.ModelPropertyDataTypes.Html) {
745
- typebox.Type.String();
746
- if (rules.minLength !== undefined) {
747
- result = typebox.Type.String({ minLength: rules.minLength });
748
- }
749
- if (rules.maxLength !== undefined) {
750
- if (rules.minLength !== undefined) {
751
- result = typebox.Type.String({ minLength: rules.minLength, maxLength: rules.maxLength });
752
- }
753
- else {
754
- result = typebox.Type.String({ maxLength: rules.maxLength });
755
- }
756
- }
757
- }
758
- // Apply enum
759
- if (rules.enum && Array.isArray(rules.enum) && rules.enum.length > 0) {
760
- result = typebox.Type.Union(rules.enum.map(val => typebox.Type.Literal(val)));
761
- }
762
- return result;
763
- }
764
- /**
765
- * Validate custom validation rules
766
- */
767
- validateCustomRules(value, rules) {
768
- const errors = [];
769
- // Custom validator reference (would need to be implemented based on your needs)
770
- if (rules.custom) {
771
- // TODO: Implement custom validator lookup and execution
772
- logger('Custom validator not yet implemented:', rules.custom);
773
- }
774
- return errors;
775
- }
776
- }
777
-
778
- exports.SchemaValidationService = SchemaValidationService;
779
- //# sourceMappingURL=SchemaValidationService-CSXxx7sQ.js.map