@seedprotocol/sdk 0.4.4 → 0.4.5

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 (100) hide show
  1. package/README.md +38 -348
  2. package/dist/{ArweaveClient-DkNLWiSZ.js → ArweaveClient-CgWK-JgT.js} +8 -8
  3. package/dist/{ArweaveClient-DkNLWiSZ.js.map → ArweaveClient-CgWK-JgT.js.map} +1 -1
  4. package/dist/{ArweaveClient-CczHvccG.js → ArweaveClient-WcG8CZAE.js} +8 -8
  5. package/dist/{ArweaveClient-CczHvccG.js.map → ArweaveClient-WcG8CZAE.js.map} +1 -1
  6. package/dist/{Db-DJvjXVlp.js → Db-DjFdIdR9.js} +9 -9
  7. package/dist/{Db-DJvjXVlp.js.map → Db-DjFdIdR9.js.map} +1 -1
  8. package/dist/{Db-BzQR2KX9.js → Db-DjofXdeU.js} +9 -9
  9. package/dist/{Db-BzQR2KX9.js.map → Db-DjofXdeU.js.map} +1 -1
  10. package/dist/{EasClient-CHQYmjj2.js → EasClient-Aojewp6P.js} +8 -8
  11. package/dist/{EasClient-CodrIgW-.js.map → EasClient-Aojewp6P.js.map} +1 -1
  12. package/dist/{EasClient-CodrIgW-.js → EasClient-BVFXp2O6.js} +8 -8
  13. package/dist/{EasClient-CHQYmjj2.js.map → EasClient-BVFXp2O6.js.map} +1 -1
  14. package/dist/{FileManager-BbvkZJCH.js → FileManager-C9zr4AJe.js} +8 -8
  15. package/dist/{FileManager-BbvkZJCH.js.map → FileManager-C9zr4AJe.js.map} +1 -1
  16. package/dist/{FileManager-BIVsDnMu.js → FileManager-CxGJLw5C.js} +8 -8
  17. package/dist/{FileManager-BIVsDnMu.js.map → FileManager-CxGJLw5C.js.map} +1 -1
  18. package/dist/Item/Item.d.ts.map +1 -1
  19. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  20. package/dist/Model/Model.d.ts.map +1 -1
  21. package/dist/ModelProperty/ModelProperty.d.ts.map +1 -1
  22. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  23. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  24. package/dist/{ModelProperty-gjcA83Mq.js → ModelProperty-CGdkocQ8.js} +31 -766
  25. package/dist/ModelProperty-CGdkocQ8.js.map +1 -0
  26. package/dist/{PathResolver-kGzba-zC.js → PathResolver-CX6GHoTS.js} +8 -8
  27. package/dist/{PathResolver-kGzba-zC.js.map → PathResolver-CX6GHoTS.js.map} +1 -1
  28. package/dist/{PathResolver-9zAzPhee.js → PathResolver-z_WX47_o.js} +8 -8
  29. package/dist/{PathResolver-9zAzPhee.js.map → PathResolver-z_WX47_o.js.map} +1 -1
  30. package/dist/{QueryClient-C7ZkTT0z.js → QueryClient-ByKPdRmE.js} +8 -8
  31. package/dist/{QueryClient-C7ZkTT0z.js.map → QueryClient-ByKPdRmE.js.map} +1 -1
  32. package/dist/{QueryClient-CEtsek7Q.js → QueryClient-Cb1iJO-x.js} +8 -8
  33. package/dist/{QueryClient-CEtsek7Q.js.map → QueryClient-Cb1iJO-x.js.map} +1 -1
  34. package/dist/Schema/Schema.d.ts.map +1 -1
  35. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  36. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  37. package/dist/{Schema-ClTcpgbt.js → Schema-D1eqDHyt.js} +758 -60
  38. package/dist/Schema-D1eqDHyt.js.map +1 -0
  39. package/dist/{SchemaValidationService-BfoEiHNr.js → SchemaValidationService-DyttFaV_.js} +7 -7
  40. package/dist/{SchemaValidationService-BfoEiHNr.js.map → SchemaValidationService-DyttFaV_.js.map} +1 -1
  41. package/dist/cjs/{ModelProperty-BRKRREYP.js → ModelProperty-BeJvgKMw.js} +62 -436
  42. package/dist/cjs/ModelProperty-BeJvgKMw.js.map +1 -0
  43. package/dist/cjs/{Schema-CV9hMg8m.js → Schema-CVs9J6eP.js} +426 -91
  44. package/dist/cjs/Schema-CVs9J6eP.js.map +1 -0
  45. package/dist/cjs/{SchemaValidationService-DUtQUerg.js → SchemaValidationService-CDKcVRFQ.js} +3 -3
  46. package/dist/cjs/{SchemaValidationService-DUtQUerg.js.map → SchemaValidationService-CDKcVRFQ.js.map} +1 -1
  47. package/dist/cjs/{getItem-BThT-UOt.js → getItem-B5RYPvrG.js} +3 -3
  48. package/dist/cjs/{getItem-BThT-UOt.js.map → getItem-B5RYPvrG.js.map} +1 -1
  49. package/dist/cjs/{getPublishPayload-CKZ7rVbU.js → getPublishPayload-BD1qRob1.js} +6 -6
  50. package/dist/cjs/getPublishPayload-BD1qRob1.js.map +1 -0
  51. package/dist/cjs/{getPublishUploads-CuGIvV-Q.js → getPublishUploads-CnC9aYxs.js} +4 -4
  52. package/dist/cjs/{getPublishUploads-CuGIvV-Q.js.map → getPublishUploads-CnC9aYxs.js.map} +1 -1
  53. package/dist/cjs/{getSegmentedItemProperties-BCJXJlTR.js → getSegmentedItemProperties-B_njnntx.js} +2 -2
  54. package/dist/cjs/{getSegmentedItemProperties-BCJXJlTR.js.map → getSegmentedItemProperties-B_njnntx.js.map} +1 -1
  55. package/dist/cjs/{index-C3j3m34a.js → index-BeKPbbk0.js} +11466 -11546
  56. package/dist/cjs/index-BeKPbbk0.js.map +1 -0
  57. package/dist/cjs/{index-CbTBDqTJ.js → index-Dnywap_P.js} +3 -3
  58. package/dist/cjs/index-Dnywap_P.js.map +1 -0
  59. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  60. package/dist/client/actors/saveAppState.d.ts.map +1 -1
  61. package/dist/eas.d.ts.map +1 -1
  62. package/dist/{getItem-BWPo8wd0.js → getItem-BB5HBCbK.js} +8 -8
  63. package/dist/{getItem-BWPo8wd0.js.map → getItem-BB5HBCbK.js.map} +1 -1
  64. package/dist/{getPublishPayload-Caw2laZM.js → getPublishPayload-uLm0AqN_.js} +10 -10
  65. package/dist/getPublishPayload-uLm0AqN_.js.map +1 -0
  66. package/dist/{getPublishUploads-MlyBuoXh.js → getPublishUploads-Dc-HqhO8.js} +9 -9
  67. package/dist/{getPublishUploads-MlyBuoXh.js.map → getPublishUploads-Dc-HqhO8.js.map} +1 -1
  68. package/dist/{getSegmentedItemProperties-COLLdDo4.js → getSegmentedItemProperties-BrIqFNfD.js} +2 -2
  69. package/dist/{getSegmentedItemProperties-COLLdDo4.js.map → getSegmentedItemProperties-BrIqFNfD.js.map} +1 -1
  70. package/dist/helpers/schema.d.ts.map +1 -1
  71. package/dist/helpers/updateSchema.d.ts.map +1 -1
  72. package/dist/imports/json.d.ts.map +1 -1
  73. package/dist/{index-D2OGsG4v.js → index-2FcQHgKp.js} +2 -2
  74. package/dist/index-2FcQHgKp.js.map +1 -0
  75. package/dist/{ClientManager-DoHUt8tU.js → index-DPll6EAp.js} +11460 -11538
  76. package/dist/index-DPll6EAp.js.map +1 -0
  77. package/dist/{index-B9i_mXXp.js → index-LEY0Og1p.js} +9 -9
  78. package/dist/index-LEY0Og1p.js.map +1 -0
  79. package/dist/main.cjs +2 -2
  80. package/dist/main.js +13 -13
  81. package/dist/main.js.map +1 -1
  82. package/dist/node.js +15 -15
  83. package/dist/{property-fK7tSUDX.js → property-B15X7jLX.js} +4 -4
  84. package/dist/property-B15X7jLX.js.map +1 -0
  85. package/dist/{queries-DGOk16cd.js → queries-BPDSpiEX.js} +2 -2
  86. package/dist/{queries-DGOk16cd.js.map → queries-BPDSpiEX.js.map} +1 -1
  87. package/dist/services/write/actors/writeToDatabase.d.ts.map +1 -1
  88. package/package.json +6 -2
  89. package/dist/ClientManager-DoHUt8tU.js.map +0 -1
  90. package/dist/ModelProperty-gjcA83Mq.js.map +0 -1
  91. package/dist/Schema-ClTcpgbt.js.map +0 -1
  92. package/dist/cjs/ModelProperty-BRKRREYP.js.map +0 -1
  93. package/dist/cjs/Schema-CV9hMg8m.js.map +0 -1
  94. package/dist/cjs/getPublishPayload-CKZ7rVbU.js.map +0 -1
  95. package/dist/cjs/index-C3j3m34a.js.map +0 -1
  96. package/dist/cjs/index-CbTBDqTJ.js.map +0 -1
  97. package/dist/getPublishPayload-Caw2laZM.js.map +0 -1
  98. package/dist/index-B9i_mXXp.js.map +0 -1
  99. package/dist/index-D2OGsG4v.js.map +0 -1
  100. package/dist/property-fK7tSUDX.js.map +0 -1
@@ -1,38 +1,388 @@
1
1
  'use strict';
2
2
 
3
3
  var xstate = require('xstate');
4
- var main_cjs = require('./index-C3j3m34a.js');
4
+ var main_cjs = require('./index-BeKPbbk0.js');
5
5
  var drizzleOrm = require('drizzle-orm');
6
6
  var debug = require('debug');
7
- var SchemaValidationService = require('./SchemaValidationService-DUtQUerg.js');
8
- var ModelProperty = require('./ModelProperty-BRKRREYP.js');
9
- require('immer');
10
- require('reflect-metadata');
11
- require('drizzle-orm/sqlite-core');
12
- require('nanoid');
13
- require('nanoid-dictionary');
7
+ var SchemaValidationService = require('./SchemaValidationService-CDKcVRFQ.js');
14
8
  require('pluralize');
15
- require('ethers');
16
- require('rxjs');
17
- require('lodash-es');
18
- require('drizzle-orm/casing');
19
- require('eventemitter3');
20
- require('@sinclair/typebox');
21
- require('fs/promises');
22
- require('fs');
23
- require('path');
24
- require('@libsql/client');
25
- require('drizzle-orm/libsql');
26
- require('drizzle-kit/api');
27
- require('js-yaml');
28
- require('arweave');
29
- require('ts-import');
30
- require('glob');
31
- require('rimraf');
32
- require('child_process');
33
- require('url');
34
- require('graphql-request');
35
- require('@sinclair/typebox/value');
9
+
10
+ const logger$d = debug('seedSdk:helpers:updateSchema');
11
+ /**
12
+ * Get the file path for a schema file
13
+ */
14
+ /**
15
+ * Sanitize a schema name to be filesystem-safe
16
+ * Replaces all special characters (except alphanumeric, hyphens, underscores) with underscores
17
+ * Converts spaces to underscores
18
+ * Removes leading/trailing underscores
19
+ *
20
+ * @param name - Schema name to sanitize
21
+ * @returns Sanitized name safe for use in filenames
22
+ */
23
+ const sanitizeSchemaName$1 = (name) => {
24
+ return name
25
+ .replace(/[^a-zA-Z0-9\s_-]/g, '_') // Replace special chars (except spaces, hyphens, underscores) with underscore
26
+ .replace(/\s+/g, '_') // Convert spaces to underscores
27
+ .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores
28
+ .replace(/_+/g, '_'); // Collapse multiple underscores to single
29
+ };
30
+ /**
31
+ * Get the full file path for a schema
32
+ * Format: {schemaFileId}_{schemaName}_v{version}.json
33
+ *
34
+ * The ID-first format ensures all files for a schema group together when sorted alphabetically.
35
+ *
36
+ * @param name - Schema name
37
+ * @param version - Schema version
38
+ * @param schemaFileId - Schema file ID (required)
39
+ */
40
+ const getSchemaFilePath$2 = (name, version, schemaFileId) => {
41
+ const path = main_cjs.BaseFileManager.getPathModule();
42
+ const workingDir = main_cjs.BaseFileManager.getWorkingDir();
43
+ const sanitizedName = sanitizeSchemaName$1(name);
44
+ const filename = schemaFileId
45
+ ? `${schemaFileId}_${sanitizedName}_v${version}.json`
46
+ : `${sanitizedName}_v${version}.json`;
47
+ return path.join(workingDir, filename);
48
+ };
49
+ /**
50
+ * Get schemaFileId from database for a schema
51
+ * @param schemaName - Schema name
52
+ * @returns Schema file ID
53
+ * @throws Error if schema not found or missing schemaFileId
54
+ */
55
+ async function getSchemaFileId(schemaName) {
56
+ const db = main_cjs.BaseDb.getAppDb();
57
+ if (!db)
58
+ throw new Error('Database not available');
59
+ const dbSchema = await db
60
+ .select()
61
+ .from(main_cjs.schemas)
62
+ .where(drizzleOrm.eq(main_cjs.schemas.name, schemaName))
63
+ .orderBy(drizzleOrm.desc(main_cjs.schemas.version))
64
+ .limit(1);
65
+ if (dbSchema.length === 0 || !dbSchema[0].schemaFileId) {
66
+ throw new Error(`Schema ${schemaName} not found in database or missing schemaFileId`);
67
+ }
68
+ return dbSchema[0].schemaFileId;
69
+ }
70
+ /**
71
+ * Write the full schema to a new version file (e.g. when new models were added).
72
+ * Used when _editedProperties contains 'schema:models' and there are no property-level updates.
73
+ * @param schemaName - Schema name
74
+ * @param schema - Full schema object (e.g. from _buildModelsFromInstances)
75
+ * @returns The file path of the new schema version
76
+ */
77
+ async function writeFullSchemaNewVersion(schemaName, schema) {
78
+ const latestVersion = await main_cjs.getLatestSchemaVersion(schemaName);
79
+ const newVersion = latestVersion + 1;
80
+ const schemaWithNewVersion = {
81
+ ...schema,
82
+ version: newVersion,
83
+ metadata: {
84
+ ...schema.metadata,
85
+ updatedAt: new Date().toISOString(),
86
+ },
87
+ migrations: [
88
+ ...(schema.migrations || []),
89
+ {
90
+ version: newVersion,
91
+ timestamp: new Date().toISOString(),
92
+ description: 'New schema version (e.g. new models added)',
93
+ changes: [{ type: 'full_schema_write' }],
94
+ },
95
+ ],
96
+ };
97
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, schema.id ?? (await getSchemaFileId(schemaName)));
98
+ const newContent = JSON.stringify(schemaWithNewVersion, null, 2);
99
+ await main_cjs.BaseFileManager.saveFile(newFilePath, newContent);
100
+ await main_cjs.BaseFileManager.waitForFileWithContent(newFilePath);
101
+ logger$d(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
102
+ return newFilePath;
103
+ }
104
+ /**
105
+ * Get model name from modelId
106
+ * @param modelId - The model ID to look up
107
+ * @returns The model name, or undefined if not found
108
+ */
109
+ async function getModelNameFromId(modelId) {
110
+ if (!modelId) {
111
+ return undefined;
112
+ }
113
+ const db = main_cjs.BaseDb.getAppDb();
114
+ if (!db) {
115
+ throw new Error('Database not found');
116
+ }
117
+ const modelRecords = await db
118
+ .select()
119
+ .from(main_cjs.models)
120
+ .where(drizzleOrm.eq(main_cjs.models.id, modelId))
121
+ .limit(1);
122
+ if (modelRecords.length === 0) {
123
+ return undefined;
124
+ }
125
+ return modelRecords[0].name;
126
+ }
127
+ /**
128
+ * Convert a TProperty/ModelPropertyMachineContext to SchemaPropertyUpdate format
129
+ * This function converts the internal property representation to the schema file format
130
+ * @param property - The TProperty instance to convert
131
+ * @param modelName - The name of the model this property belongs to
132
+ * @param propertyName - The name of the property
133
+ * @returns A SchemaPropertyUpdate object ready to be passed to updateModelProperties
134
+ */
135
+ async function convertPropertyToSchemaUpdate(property, modelName, propertyName) {
136
+ const updates = {};
137
+ // Convert dataType to type
138
+ if (property.dataType) {
139
+ updates.type = property.dataType;
140
+ }
141
+ // Handle Relation type
142
+ if (property.dataType === main_cjs.ModelPropertyDataTypes.Relation) {
143
+ if (property.ref) {
144
+ updates.model = property.ref;
145
+ }
146
+ else if (property.refModelId) {
147
+ // If ref is not set but refModelId is, get the model name from the database
148
+ const refModelName = await getModelNameFromId(property.refModelId);
149
+ if (refModelName) {
150
+ updates.model = refModelName;
151
+ }
152
+ }
153
+ }
154
+ // Handle List type
155
+ if (property.dataType === main_cjs.ModelPropertyDataTypes.List) {
156
+ if (property.refValueType) {
157
+ updates.items = {
158
+ type: property.refValueType,
159
+ };
160
+ if (property.ref) {
161
+ updates.items.model = property.ref;
162
+ }
163
+ else if (property.refModelId) {
164
+ // If ref is not set but refModelId is, get the model name from the database
165
+ const refModelName = await getModelNameFromId(property.refModelId);
166
+ if (refModelName) {
167
+ updates.items.model = refModelName;
168
+ }
169
+ }
170
+ }
171
+ }
172
+ // Handle storage configuration (for Text properties with storage)
173
+ if (property.storageType || property.localStorageDir || property.filenameSuffix) {
174
+ const storageType = property.storageType || 'ItemStorage'; // Default to ItemStorage if not specified
175
+ updates.storage = {
176
+ type: storageType,
177
+ };
178
+ if (property.localStorageDir) {
179
+ updates.storage.path = property.localStorageDir;
180
+ }
181
+ if (property.filenameSuffix) {
182
+ updates.storage.extension = property.filenameSuffix;
183
+ }
184
+ }
185
+ return {
186
+ modelName,
187
+ propertyName,
188
+ updates,
189
+ };
190
+ }
191
+ /**
192
+ * Update model properties in a schema and create a new version
193
+ * @param schemaName - The name of the schema to update
194
+ * @param propertyUpdates - Array of property updates to apply
195
+ * @param modelUpdates - Optional array of model renames
196
+ * @returns The file path of the new schema version
197
+ * @throws Error if schema not found or updates are invalid
198
+ */
199
+ async function updateModelProperties(schemaName, propertyUpdates, modelUpdates) {
200
+ // Get the latest version of the schema
201
+ const latestVersion = await main_cjs.getLatestSchemaVersion(schemaName);
202
+ if (latestVersion === 0) {
203
+ throw new Error(`Schema ${schemaName} not found`);
204
+ }
205
+ // Get schemaFileId from database
206
+ const schemaFileId = await getSchemaFileId(schemaName);
207
+ // Load the latest schema file
208
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
209
+ const content = await main_cjs.BaseFileManager.readFileAsString(latestFilePath);
210
+ const schemaFile = JSON.parse(content);
211
+ if (!schemaFile.$schema) {
212
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
213
+ }
214
+ // Create a copy of the schema for the new version
215
+ // Preserve schema ID and all model/property IDs
216
+ const newVersion = latestVersion + 1;
217
+ const updatedSchema = {
218
+ ...schemaFile,
219
+ version: newVersion,
220
+ // Preserve schema ID from previous version
221
+ id: schemaFile.id,
222
+ metadata: {
223
+ ...schemaFile.metadata,
224
+ updatedAt: new Date().toISOString(),
225
+ },
226
+ // Deep copy models to preserve IDs
227
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
228
+ modelName,
229
+ {
230
+ ...model,
231
+ // Preserve model ID
232
+ id: model.id,
233
+ // Deep copy properties to preserve IDs
234
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
235
+ propName,
236
+ {
237
+ ...prop,
238
+ // Preserve property ID
239
+ id: prop.id,
240
+ },
241
+ ])),
242
+ },
243
+ ])),
244
+ migrations: [
245
+ ...schemaFile.migrations,
246
+ {
247
+ version: newVersion,
248
+ timestamp: new Date().toISOString(),
249
+ description: `Updated model properties: ${propertyUpdates.map(u => `${u.modelName}.${u.propertyName}`).join(', ')}`,
250
+ changes: propertyUpdates.map(update => ({
251
+ type: 'property_update',
252
+ modelName: update.modelName,
253
+ propertyName: update.propertyName,
254
+ updates: update.updates,
255
+ })),
256
+ },
257
+ ],
258
+ };
259
+ // Apply property updates
260
+ for (const update of propertyUpdates) {
261
+ const model = updatedSchema.models[update.modelName];
262
+ if (!model) {
263
+ throw new Error(`Model ${update.modelName} not found in schema ${schemaName}`);
264
+ }
265
+ if (!model.properties[update.propertyName]) {
266
+ throw new Error(`Property ${update.propertyName} not found in model ${update.modelName} of schema ${schemaName}`);
267
+ }
268
+ // Update the property with new values
269
+ const property = model.properties[update.propertyName];
270
+ Object.assign(property, update.updates);
271
+ }
272
+ // Write the new schema version to file using ID-based naming (preferred)
273
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
274
+ const newContent = JSON.stringify(updatedSchema, null, 2);
275
+ await main_cjs.BaseFileManager.saveFile(newFilePath, newContent);
276
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
277
+ await main_cjs.BaseFileManager.waitForFileWithContent(newFilePath);
278
+ logger$d(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
279
+ // Load the new schema file to process models and add them to the database
280
+ // Extract model renames from migrations to pass to database update
281
+ const modelRenames = new Map();
282
+ const latestMigration = updatedSchema.migrations[updatedSchema.migrations.length - 1];
283
+ for (const change of latestMigration.changes) {
284
+ if (change.type === 'model_rename') {
285
+ modelRenames.set(change.oldName, change.newName);
286
+ }
287
+ }
288
+ // Load schema with model renames handled
289
+ await loadSchemaWithRenames(newFilePath, modelRenames);
290
+ return newFilePath;
291
+ }
292
+ /**
293
+ * Load a schema file and handle model renames in the database
294
+ * This is a helper function that processes model renames before loading
295
+ */
296
+ async function loadSchemaWithRenames(schemaFilePath, modelRenames) {
297
+ const content = await main_cjs.BaseFileManager.readFileAsString(schemaFilePath);
298
+ const schemaFile = JSON.parse(content);
299
+ if (!schemaFile.$schema) {
300
+ throw new Error(`File ${schemaFilePath} is not a complete schema file (missing $schema field).`);
301
+ }
302
+ const schemaName = schemaFile.metadata?.name;
303
+ const version = schemaFile.version;
304
+ if (!schemaName) {
305
+ throw new Error('Schema name is required in metadata.name');
306
+ }
307
+ // Convert to JsonImportSchema format for processing
308
+ // Remove id fields for JsonImportSchema format (they're not part of the import format)
309
+ const importData = {
310
+ name: schemaName,
311
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
312
+ modelName,
313
+ {
314
+ description: model.description,
315
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
316
+ propName,
317
+ {
318
+ type: prop.type || 'string', // Ensure type is present
319
+ ...prop,
320
+ // Remove id field for import format (not part of JsonImportSchema)
321
+ },
322
+ ])),
323
+ indexes: model.indexes,
324
+ },
325
+ ])),
326
+ };
327
+ // Generate schema ID if missing
328
+ if (!schemaFile.id) {
329
+ schemaFile.id = main_cjs.generateId();
330
+ logger$d('Generated schema ID for schema:', schemaFile.id);
331
+ }
332
+ // Extract schemaFileIds from JSON file and generate missing ones BEFORE creating models
333
+ // This ensures Model instances are created with correct IDs
334
+ const modelFileIds = new Map();
335
+ const propertyFileIds = new Map();
336
+ for (const [modelName, model] of Object.entries(schemaFile.models)) {
337
+ // Generate model ID if missing
338
+ if (!model.id) {
339
+ model.id = main_cjs.generateId();
340
+ logger$d(`Generated model ID for ${modelName}:`, model.id);
341
+ }
342
+ modelFileIds.set(modelName, model.id);
343
+ const propIds = new Map();
344
+ for (const [propName, prop] of Object.entries(model.properties)) {
345
+ // Generate property ID if missing
346
+ if (!prop.id) {
347
+ prop.id = main_cjs.generateId();
348
+ logger$d(`Generated property ID for ${modelName}.${propName}:`, prop.id);
349
+ }
350
+ propIds.set(propName, prop.id);
351
+ }
352
+ if (propIds.size > 0) {
353
+ propertyFileIds.set(modelName, propIds);
354
+ }
355
+ }
356
+ // Convert JSON models to Model classes, passing modelFileIds and propertyFileIds so Model instances use correct IDs
357
+ const modelDefinitions = await main_cjs.createModelsFromJson(importData, modelFileIds, propertyFileIds);
358
+ // Convert schema file metadata to schema input for database
359
+ const schemaInput = {
360
+ name: schemaName,
361
+ version,
362
+ schemaFileId: schemaFile.id || null,
363
+ schemaData: null,
364
+ isDraft: false,
365
+ isEdited: false,
366
+ createdAt: new Date(schemaFile.metadata.createdAt).getTime(),
367
+ updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
368
+ };
369
+ // Use dynamic import to break circular dependency
370
+ const { addSchemaToDb, addModelsToDb } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.db; });
371
+ // Add schema to database with schemaFileId
372
+ const schemaRecord = await addSchemaToDb(schemaInput, schemaFile.id);
373
+ // Add models to database with model renames handled and schemaFileIds
374
+ await addModelsToDb(modelDefinitions, schemaRecord, modelRenames, {
375
+ schemaFileId: schemaFile.id,
376
+ modelFileIds,
377
+ propertyFileIds,
378
+ });
379
+ // Models are now Model instances, no registration needed
380
+ // They should be created via Model.create() and are accessible via Model static methods
381
+ for (const [modelName] of Object.entries(modelDefinitions)) {
382
+ logger$d('loadSchemaWithRenames - model available:', modelName);
383
+ }
384
+ return schemaFilePath;
385
+ }
36
386
 
37
387
  const logger$c = debug('seedSdk:schema:actors:loadOrCreateSchema');
38
388
  /**
@@ -76,7 +426,7 @@ const createModelInstances$2 = async (modelIds) => {
76
426
  return;
77
427
  }
78
428
  try {
79
- const { Model } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.Model$1; });
429
+ const { Model } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.Model$1; });
80
430
  // Create instances for all model IDs in parallel
81
431
  // Model.createById() will check cache first, then query DB and create if needed
82
432
  const createPromises = modelIds.map(async (modelFileId) => {
@@ -189,7 +539,7 @@ const loadOrCreateSchema = xstate.fromCallback(({ sendBack, input: { context } }
189
539
  logger$c(`Loading internal Seed Protocol schema from SDK`);
190
540
  console.log('[loadOrCreateSchema] Loading internal Seed Protocol schema from SDK');
191
541
  try {
192
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
542
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
193
543
  const schemaFile = internalSchema.default;
194
544
  console.log('[loadOrCreateSchema] Loaded schema file, models count:', Object.keys(schemaFile.models || {}).length);
195
545
  // Check if it exists in database, if not, add it
@@ -689,7 +1039,7 @@ const loadOrCreateSchema = xstate.fromCallback(({ sendBack, input: { context } }
689
1039
  // Ensure models are populated (fallback for seed-protocol if missing)
690
1040
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
691
1041
  try {
692
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1042
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
693
1043
  const internalSchemaFile = internalSchema.default;
694
1044
  mergedModels = { ...(internalSchemaFile.models || {}) };
695
1045
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -884,7 +1234,7 @@ const loadOrCreateSchema = xstate.fromCallback(({ sendBack, input: { context } }
884
1234
  // Ensure models are populated (fallback for seed-protocol if missing)
885
1235
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
886
1236
  try {
887
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1237
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
888
1238
  const internalSchemaFile = internalSchema.default;
889
1239
  mergedModels = { ...(internalSchemaFile.models || {}) };
890
1240
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -956,7 +1306,7 @@ const loadOrCreateSchema = xstate.fromCallback(({ sendBack, input: { context } }
956
1306
  // Ensure models are populated (fallback for seed-protocol if missing)
957
1307
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
958
1308
  try {
959
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1309
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
960
1310
  const internalSchemaFile = internalSchema.default;
961
1311
  mergedModels = { ...(internalSchemaFile.models || {}) };
962
1312
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -1025,7 +1375,7 @@ const loadOrCreateSchema = xstate.fromCallback(({ sendBack, input: { context } }
1025
1375
  // If schemaData is missing, try to load from internal schema file for seed-protocol
1026
1376
  if (!dbSchema.schemaData && schemaName === 'Seed Protocol') {
1027
1377
  try {
1028
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1378
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1029
1379
  const schemaFile = internalSchema.default;
1030
1380
  logger$c(`Found seed-protocol schema in internal file (schemaData missing, using internal schema)`);
1031
1381
  // Update database with schemaData for future loads
@@ -1134,7 +1484,7 @@ const loadOrCreateSchema = xstate.fromCallback(({ sendBack, input: { context } }
1134
1484
  // Ensure models are populated (fallback for seed-protocol if missing)
1135
1485
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
1136
1486
  try {
1137
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1487
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
1138
1488
  const internalSchemaFile = internalSchema.default;
1139
1489
  mergedModels = { ...(internalSchemaFile.models || {}) };
1140
1490
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -1450,20 +1800,15 @@ const addModelsMachine = xstate.setup({
1450
1800
  }),
1451
1801
  createModelInstances: xstate.fromCallback(({ sendBack, input }) => {
1452
1802
  const _createInstances = async () => {
1453
- const { Schema } = await Promise.resolve().then(function () { return Schema$1; });
1454
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.BaseDb$1; });
1455
- const { models: modelsTable } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.ModelSchema; });
1456
- const { eq } = await import('drizzle-orm');
1457
- const { generateId } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.index; });
1458
1803
  const debug = (await import('debug')).default;
1459
1804
  const logger = debug('seedSdk:schema:addModels:createInstances');
1805
+ const { Schema: SchemaClass, schemaInstanceState } = await Promise.resolve().then(function () { return Schema$1; });
1460
1806
  const schemaName = input.schemaContext.metadata?.name || input.schemaContext.schemaName;
1461
- const schemaInstance = Schema.create(schemaName, {
1807
+ const schemaInstance = SchemaClass.create(schemaName, {
1462
1808
  waitForReady: false,
1463
1809
  });
1464
1810
  const modelInstances = new Map();
1465
1811
  // Get instance state to store model instances
1466
- const { schemaInstanceState } = await Promise.resolve().then(function () { return Schema$1; });
1467
1812
  const instanceState = schemaInstanceState.get(schemaInstance);
1468
1813
  if (!instanceState) {
1469
1814
  throw new Error('Schema instance state not found');
@@ -1474,12 +1819,12 @@ const addModelsMachine = xstate.setup({
1474
1819
  // Look up modelFileId from database BEFORE creating the Model instance
1475
1820
  let modelFileId = undefined;
1476
1821
  try {
1477
- const db = BaseDb.getAppDb();
1822
+ const db = main_cjs.BaseDb.getAppDb();
1478
1823
  if (db) {
1479
1824
  const dbModels = await db
1480
1825
  .select()
1481
- .from(modelsTable)
1482
- .where(eq(modelsTable.name, modelName))
1826
+ .from(main_cjs.models)
1827
+ .where(drizzleOrm.eq(main_cjs.models.name, modelName))
1483
1828
  .limit(1);
1484
1829
  if (dbModels.length > 0 && dbModels[0].schemaFileId) {
1485
1830
  modelFileId = dbModels[0].schemaFileId;
@@ -1492,7 +1837,7 @@ const addModelsMachine = xstate.setup({
1492
1837
  }
1493
1838
  // If not found in database, generate a new modelFileId for new models
1494
1839
  if (!modelFileId) {
1495
- modelFileId = generateId();
1840
+ modelFileId = main_cjs.generateId();
1496
1841
  logger(`Generated new modelFileId "${modelFileId}" for new model "${modelName}"`);
1497
1842
  }
1498
1843
  // Create new Model instance with modelFileId
@@ -1681,9 +2026,6 @@ const addModelsMachine = xstate.setup({
1681
2026
  const _persist = async () => {
1682
2027
  const debug = (await import('debug')).default;
1683
2028
  const logger = debug('seedSdk:schema:addModels:persist');
1684
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.BaseDb$1; });
1685
- const { schemas: schemasTable } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SchemaSchema; });
1686
- const { eq } = await import('drizzle-orm');
1687
2029
  // Only process in browser environment where store is available
1688
2030
  if (typeof window === 'undefined') {
1689
2031
  logger('Not in browser environment, skipping store update');
@@ -1695,7 +2037,7 @@ const addModelsMachine = xstate.setup({
1695
2037
  }
1696
2038
  const schemaName = input.schemaContext.metadata?.name || input.schemaContext.schemaName;
1697
2039
  const schemaFileId = input.schemaContext.id; // id is the schemaFileId (string) in SchemaMachineContext
1698
- const db = BaseDb.getAppDb();
2040
+ const db = main_cjs.BaseDb.getAppDb();
1699
2041
  if (!db) {
1700
2042
  logger('Database not found, skipping model store update');
1701
2043
  sendBack({
@@ -1719,8 +2061,8 @@ const addModelsMachine = xstate.setup({
1719
2061
  logger(`Looking up schema by schemaFileId: ${schemaFileId} (attempt ${attempt + 1})`);
1720
2062
  const schemasById = await db
1721
2063
  .select()
1722
- .from(schemasTable)
1723
- .where(eq(schemasTable.schemaFileId, schemaFileId))
2064
+ .from(main_cjs.schemas)
2065
+ .where(drizzleOrm.eq(main_cjs.schemas.schemaFileId, schemaFileId))
1724
2066
  .limit(1);
1725
2067
  if (schemasById.length > 0) {
1726
2068
  schemaRecord = schemasById[0];
@@ -1736,12 +2078,11 @@ const addModelsMachine = xstate.setup({
1736
2078
  // FALLBACK: If not found by schemaFileId, try by name (prefer draft records)
1737
2079
  if (!schemaRecord) {
1738
2080
  logger(`Looking up schema by name: "${schemaName}" (attempt ${attempt + 1})`);
1739
- const { desc } = await import('drizzle-orm');
1740
2081
  const schemasByName = await db
1741
2082
  .select()
1742
- .from(schemasTable)
1743
- .where(eq(schemasTable.name, schemaName))
1744
- .orderBy(desc(schemasTable.isDraft), desc(schemasTable.version))
2083
+ .from(main_cjs.schemas)
2084
+ .where(drizzleOrm.eq(main_cjs.schemas.name, schemaName))
2085
+ .orderBy(drizzleOrm.desc(main_cjs.schemas.isDraft), drizzleOrm.desc(main_cjs.schemas.version))
1745
2086
  .limit(10); // Get multiple to find drafts
1746
2087
  if (schemasByName.length > 0) {
1747
2088
  // Prefer draft records
@@ -2040,7 +2381,7 @@ const createModelInstances$1 = async (modelIds) => {
2040
2381
  return;
2041
2382
  }
2042
2383
  try {
2043
- const mod = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.Model$1; });
2384
+ const mod = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.Model$1; });
2044
2385
  const Model = mod?.Model ?? mod?.default;
2045
2386
  if (!Model) {
2046
2387
  logger$b('Model not available from dynamic import');
@@ -2085,7 +2426,7 @@ const checkExistingSchema = xstate.fromCallback(({ sendBack, input: { context }
2085
2426
  if (isInternal && schemaName === main_cjs.SEED_PROTOCOL_SCHEMA_NAME) {
2086
2427
  // For Seed Protocol, check if it exists in database
2087
2428
  try {
2088
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
2429
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
2089
2430
  const schemaFile = internalSchema.default;
2090
2431
  if (db && schemaFile.id) {
2091
2432
  const existing = await db
@@ -2443,7 +2784,7 @@ const writeSchemaToDb = xstate.fromCallback(({ sendBack, input }) => {
2443
2784
  if (isInternal && schemaName === main_cjs.SEED_PROTOCOL_SCHEMA_NAME) {
2444
2785
  // For Seed Protocol, load from internal file
2445
2786
  logger$a(`Loading internal Seed Protocol schema from SDK`);
2446
- const internalSchema = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
2787
+ const internalSchema = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.SEEDPROTOCOL_Seed_Protocol_v1; });
2447
2788
  finalSchema = internalSchema.default;
2448
2789
  const db = main_cjs.BaseDb.getAppDb();
2449
2790
  if (db && finalSchema.id) {
@@ -2911,7 +3252,7 @@ const createModelInstances = xstate.fromCallback(({ sendBack, input }) => {
2911
3252
  return;
2912
3253
  }
2913
3254
  try {
2914
- const { Model } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.Model$1; });
3255
+ const { Model } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.Model$1; });
2915
3256
  // Create instances for all model IDs in parallel
2916
3257
  // Model.createById() will check cache first, then query DB and create if needed
2917
3258
  const createPromises = modelIds.map(async (modelFileId) => {
@@ -2996,7 +3337,7 @@ const verifyModelInstancesInCache = xstate.fromCallback(({ sendBack, input }) =>
2996
3337
  }
2997
3338
  try {
2998
3339
  const result = await verifyWithRetry$2(async () => {
2999
- const { Model } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.Model$1; });
3340
+ const { Model } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.Model$1; });
3000
3341
  // Check each model ID in the cache
3001
3342
  const verifiedInstances = [];
3002
3343
  const missingIds = [];
@@ -3052,10 +3393,9 @@ const writePropertiesToDb = xstate.fromCallback(({ sendBack, input }) => {
3052
3393
  const _write = async () => {
3053
3394
  const { modelIds } = input;
3054
3395
  try {
3055
- const { BaseDb } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.BaseDb$1; });
3056
- const { models: modelsTable, properties: propertiesTable } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.ModelSchema; });
3396
+ const { models: modelsTable, properties: propertiesTable } = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.ModelSchema; });
3057
3397
  const { eq } = await import('drizzle-orm');
3058
- const db = BaseDb.getAppDb();
3398
+ const db = main_cjs.BaseDb.getAppDb();
3059
3399
  if (!db) {
3060
3400
  throw new Error('Database not available');
3061
3401
  }
@@ -3239,9 +3579,9 @@ const createPropertyInstances = xstate.fromCallback(({ sendBack, input }) => {
3239
3579
  return;
3240
3580
  }
3241
3581
  try {
3242
- const modProp = await Promise.resolve().then(function () { return require('./ModelProperty-BRKRREYP.js'); }).then(function (n) { return n.ModelProperty$1; });
3582
+ const modProp = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
3243
3583
  const ModelProperty = modProp?.ModelProperty ?? modProp?.default;
3244
- const modModel = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.Model$1; });
3584
+ const modModel = await Promise.resolve().then(function () { return require('./index-BeKPbbk0.js'); }).then(function (n) { return n.Model$1; });
3245
3585
  const Model = modModel?.Model ?? modModel?.default;
3246
3586
  if (!ModelProperty || !Model) {
3247
3587
  logger$2('ModelProperty or Model not available from dynamic import');
@@ -3346,7 +3686,7 @@ const verifyPropertyInstancesInCache = xstate.fromCallback(({ sendBack, input })
3346
3686
  }
3347
3687
  try {
3348
3688
  const result = await verifyWithRetry(async () => {
3349
- const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BRKRREYP.js'); }).then(function (n) { return n.ModelProperty$1; });
3689
+ const mod = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
3350
3690
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
3351
3691
  if (!ModelProperty) {
3352
3692
  throw new Error('ModelProperty not available from dynamic import');
@@ -4926,7 +5266,6 @@ class Schema {
4926
5266
  throw new main_cjs.ConflictError(errorMessage, conflictCheck);
4927
5267
  }
4928
5268
  const context = this._getSnapshotContext();
4929
- const { addSchemaToDb } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.db; });
4930
5269
  if (!context._isDraft || !context._editedProperties || context._editedProperties.size === 0) {
4931
5270
  logger('No changes to save');
4932
5271
  return '';
@@ -4960,7 +5299,7 @@ class Schema {
4960
5299
  migrations: context.migrations || [],
4961
5300
  };
4962
5301
  // Update draft in database with current state
4963
- await addSchemaToDb({
5302
+ await main_cjs.addSchemaToDb({
4964
5303
  name: this.schemaName,
4965
5304
  version: currentSchema.version,
4966
5305
  createdAt: new Date(currentSchema.metadata.createdAt).getTime(),
@@ -4973,6 +5312,7 @@ class Schema {
4973
5312
  .limit(1);
4974
5313
  // Collect all edited properties and convert them to SchemaPropertyUpdate format
4975
5314
  const propertyUpdates = [];
5315
+ const { ModelProperty } = await Promise.resolve().then(function () { return require('./ModelProperty-BeJvgKMw.js'); });
4976
5316
  for (const propertyKey of context._editedProperties) {
4977
5317
  // Skip schema-level changes (like schema name changes)
4978
5318
  if (propertyKey === 'schema:name') {
@@ -4986,7 +5326,7 @@ class Schema {
4986
5326
  }
4987
5327
  // Get ModelProperty instance from cache
4988
5328
  const cacheKey = `${modelName}:${propertyName}`;
4989
- const ModelPropertyClass = ModelProperty.ModelProperty;
5329
+ const ModelPropertyClass = ModelProperty;
4990
5330
  const cachedInstance = ModelPropertyClass.instanceCache.get(cacheKey);
4991
5331
  if (!cachedInstance) {
4992
5332
  logger(`ModelProperty instance not found for ${cacheKey}`);
@@ -4995,15 +5335,14 @@ class Schema {
4995
5335
  const modelProperty = cachedInstance.instance;
4996
5336
  const propertyContext = modelProperty.getService().getSnapshot().context;
4997
5337
  // Convert to SchemaPropertyUpdate
4998
- const propertyUpdate = await ModelProperty.convertPropertyToSchemaUpdate(propertyContext, modelName, propertyName);
5338
+ const propertyUpdate = await convertPropertyToSchemaUpdate(propertyContext, modelName, propertyName);
4999
5339
  propertyUpdates.push(propertyUpdate);
5000
5340
  }
5001
5341
  if (propertyUpdates.length === 0) {
5002
5342
  // When only new models were added, _editedProperties contains 'schema:models' and we write the full schema
5003
5343
  if (context._editedProperties.has('schema:models')) {
5004
- const newFilePath = await ModelProperty.writeFullSchemaNewVersion(this.schemaName, currentSchema);
5005
- const { BaseFileManager } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.BaseFileManager$1; });
5006
- const fileContent = await BaseFileManager.readFileAsString(newFilePath);
5344
+ const newFilePath = await writeFullSchemaNewVersion(this.schemaName, currentSchema);
5345
+ const fileContent = await main_cjs.BaseFileManager.readFileAsString(newFilePath);
5007
5346
  const publishedSchema = JSON.parse(fileContent);
5008
5347
  if (dbSchema.length > 0) {
5009
5348
  await db
@@ -5029,11 +5368,10 @@ class Schema {
5029
5368
  return '';
5030
5369
  }
5031
5370
  // STEP 2: Save to new schema version (writes file)
5032
- const newFilePath = await ModelProperty.updateModelProperties(this.schemaName, propertyUpdates);
5371
+ const newFilePath = await updateModelProperties(this.schemaName, propertyUpdates);
5033
5372
  // STEP 3: After file is written, update database to mark as published (isDraft = false)
5034
5373
  // Load the file to get the final schema with IDs
5035
- const { BaseFileManager } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.BaseFileManager$1; });
5036
- const fileContent = await BaseFileManager.readFileAsString(newFilePath);
5374
+ const fileContent = await main_cjs.BaseFileManager.readFileAsString(newFilePath);
5037
5375
  const publishedSchema = JSON.parse(fileContent);
5038
5376
  // Update database record: set isDraft = false and update schemaFileId
5039
5377
  if (dbSchema.length > 0) {
@@ -5051,7 +5389,7 @@ class Schema {
5051
5389
  }
5052
5390
  else {
5053
5391
  // Create new record if it doesn't exist (shouldn't happen, but safety)
5054
- await addSchemaToDb({
5392
+ await main_cjs.addSchemaToDb({
5055
5393
  name: this.schemaName,
5056
5394
  version: publishedSchema.version,
5057
5395
  createdAt: new Date(publishedSchema.metadata.createdAt).getTime(),
@@ -5069,7 +5407,7 @@ class Schema {
5069
5407
  for (const propertyKey of context._editedProperties) {
5070
5408
  const [modelName, propertyName] = propertyKey.split(':');
5071
5409
  const cacheKey = `${modelName}:${propertyName}`;
5072
- const ModelPropertyClass = ModelProperty.ModelProperty;
5410
+ const ModelPropertyClass = ModelProperty;
5073
5411
  const cachedInstance = ModelPropertyClass.instanceCache.get(cacheKey);
5074
5412
  if (cachedInstance) {
5075
5413
  const modelProperty = cachedInstance.instance;
@@ -5227,14 +5565,11 @@ class Schema {
5227
5565
  saveDraftLogger(`Client check: cacheIsStale=${cacheIsStale}, shouldRecheck=${shouldRecheck}, cachedValue=${cachedClientInitialized}, timeSinceCheck=${now - clientCheckTime}ms`);
5228
5566
  if (shouldRecheck) {
5229
5567
  try {
5230
- // Use dynamic import for browser compatibility (require() doesn't work in browsers)
5231
- const { getClient } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.ClientManager$1; });
5232
- const { ClientManagerState } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.constants; });
5233
- const client = getClient();
5568
+ const client = main_cjs.getClient();
5234
5569
  const clientSnapshot = client.getService().getSnapshot();
5235
5570
  // Check if state is IDLE (primary check) - isInitialized is set in entry action so should be true
5236
5571
  // But we check it as a secondary safeguard
5237
- const isIdle = clientSnapshot.value === ClientManagerState.IDLE;
5572
+ const isIdle = clientSnapshot.value === main_cjs.ClientManagerState.IDLE;
5238
5573
  const isInitialized = clientSnapshot.context.isInitialized;
5239
5574
  // If state is IDLE, trust it even if isInitialized isn't set yet (entry action should set it)
5240
5575
  // This aligns with useIsClientReady which only checks the state value
@@ -5300,8 +5635,6 @@ class Schema {
5300
5635
  _editedProperties: new Set(),
5301
5636
  };
5302
5637
  }
5303
- const { addSchemaToDb } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.db; });
5304
- const { generateId } = await Promise.resolve().then(function () { return require('./index-C3j3m34a.js'); }).then(function (n) { return n.index; });
5305
5638
  const db = main_cjs.BaseDb.getAppDb();
5306
5639
  if (!db) {
5307
5640
  throw new Error('Database not found');
@@ -5376,7 +5709,7 @@ class Schema {
5376
5709
  }
5377
5710
  // Build current schema state from context
5378
5711
  // Use existing schemaFileId if we found one, otherwise use the one from context, or generate new
5379
- const schemaFileId = existingSchemaId || context.id || generateId(); // id is now the schemaFileId (string)
5712
+ const schemaFileId = existingSchemaId || context.id || main_cjs.generateId(); // id is now the schemaFileId (string)
5380
5713
  // Build metadata - if name changed, use newName, otherwise use context metadata
5381
5714
  // Always ensure metadata.name matches finalNewName to prevent inconsistencies
5382
5715
  const currentMetadata = context.metadata ? {
@@ -5554,7 +5887,7 @@ class Schema {
5554
5887
  throw new Error(`Failed to update schema name: existing record not found or update failed`);
5555
5888
  }
5556
5889
  // Otherwise, use addSchemaToDb which will handle create/update logic (for normal saves, not name changes)
5557
- await addSchemaToDb({
5890
+ await main_cjs.addSchemaToDb({
5558
5891
  name: finalNewName,
5559
5892
  version: currentSchema.version,
5560
5893
  createdAt: new Date(currentSchema.metadata.createdAt).getTime(),
@@ -5869,5 +6202,7 @@ var Schema$1 = /*#__PURE__*/Object.freeze({
5869
6202
  });
5870
6203
 
5871
6204
  exports.Schema = Schema;
5872
- exports.schemaInstanceState = schemaInstanceState;
5873
- //# sourceMappingURL=Schema-CV9hMg8m.js.map
6205
+ exports.Schema$1 = Schema$1;
6206
+ exports.convertPropertyToSchemaUpdate = convertPropertyToSchemaUpdate;
6207
+ exports.updateModelProperties = updateModelProperties;
6208
+ //# sourceMappingURL=Schema-CVs9J6eP.js.map