@seedprotocol/sdk 0.4.4 → 0.4.6

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 (146) hide show
  1. package/README.md +38 -348
  2. package/dist/{ArweaveClient-DkNLWiSZ.js → ArweaveClient-Caio37h1.js} +8 -8
  3. package/dist/ArweaveClient-Caio37h1.js.map +1 -0
  4. package/dist/{ArweaveClient-CczHvccG.js → ArweaveClient-DLKAaS3K.js} +8 -8
  5. package/dist/ArweaveClient-DLKAaS3K.js.map +1 -0
  6. package/dist/{Db-DJvjXVlp.js → Db-C9fppVRl.js} +9 -9
  7. package/dist/Db-C9fppVRl.js.map +1 -0
  8. package/dist/{Db-BzQR2KX9.js → Db-DJAG-5Di.js} +13 -11
  9. package/dist/Db-DJAG-5Di.js.map +1 -0
  10. package/dist/{EasClient-CHQYmjj2.js → EasClient-DQGAIj-b.js} +8 -8
  11. package/dist/EasClient-DQGAIj-b.js.map +1 -0
  12. package/dist/{EasClient-CodrIgW-.js → EasClient-T7Nx9185.js} +8 -8
  13. package/dist/EasClient-T7Nx9185.js.map +1 -0
  14. package/dist/{FileManager-BbvkZJCH.js → FileManager-BohtoKYo.js} +10 -9
  15. package/dist/FileManager-BohtoKYo.js.map +1 -0
  16. package/dist/{FileManager-BIVsDnMu.js → FileManager-d64CkqXy.js} +8 -8
  17. package/dist/FileManager-d64CkqXy.js.map +1 -0
  18. package/dist/Item/Item.d.ts.map +1 -1
  19. package/dist/Item/service/actors/fetchDataFromEas.d.ts.map +1 -1
  20. package/dist/Item/service/actors/loadOrCreateItem.d.ts.map +1 -1
  21. package/dist/Item/service/actors/runPublish.d.ts.map +1 -1
  22. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  23. package/dist/ItemProperty/service/actors/hydrateFromDb.d.ts.map +1 -1
  24. package/dist/ItemProperty/service/actors/resolveRelatedValue.d.ts.map +1 -1
  25. package/dist/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  26. package/dist/ItemProperty/service/actors/saveValueToDb/saveRelation.d.ts.map +1 -1
  27. package/dist/Model/Model.d.ts.map +1 -1
  28. package/dist/Model/service/actors/createModelProperties.d.ts.map +1 -1
  29. package/dist/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  30. package/dist/Model/service/actors/validateModel.d.ts.map +1 -1
  31. package/dist/ModelProperty/ModelProperty.d.ts.map +1 -1
  32. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  33. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  34. package/dist/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  35. package/dist/{ModelProperty-gjcA83Mq.js → ModelProperty-Cpd9xiIM.js} +67 -768
  36. package/dist/ModelProperty-Cpd9xiIM.js.map +1 -0
  37. package/dist/{PathResolver-kGzba-zC.js → PathResolver-CLZUWoX2.js} +8 -8
  38. package/dist/PathResolver-CLZUWoX2.js.map +1 -0
  39. package/dist/{PathResolver-9zAzPhee.js → PathResolver-D6M0rzKV.js} +8 -8
  40. package/dist/PathResolver-D6M0rzKV.js.map +1 -0
  41. package/dist/{QueryClient-C7ZkTT0z.js → QueryClient-BUoz2Vb0.js} +8 -8
  42. package/dist/QueryClient-BUoz2Vb0.js.map +1 -0
  43. package/dist/{QueryClient-CEtsek7Q.js → QueryClient-COQ_Rs4-.js} +8 -8
  44. package/dist/QueryClient-COQ_Rs4-.js.map +1 -0
  45. package/dist/Schema/Schema.d.ts.map +1 -1
  46. package/dist/Schema/service/actors/createModelInstances.d.ts.map +1 -1
  47. package/dist/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  48. package/dist/Schema/service/actors/verifyModelInstancesInCache.d.ts.map +1 -1
  49. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  50. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  51. package/dist/{Schema-ClTcpgbt.js → Schema-BZKBy5Tx.js} +799 -62
  52. package/dist/Schema-BZKBy5Tx.js.map +1 -0
  53. package/dist/{SchemaValidationService-BfoEiHNr.js → SchemaValidationService-F8No7BHp.js} +7 -7
  54. package/dist/SchemaValidationService-F8No7BHp.js.map +1 -0
  55. package/dist/browser/helpers/FileManager.d.ts.map +1 -1
  56. package/dist/browser/react/itemProperty.d.ts.map +1 -1
  57. package/dist/cjs/{ModelProperty-BRKRREYP.js → ModelProperty-B4pV91tc.js} +78 -438
  58. package/dist/cjs/ModelProperty-B4pV91tc.js.map +1 -0
  59. package/dist/cjs/{Schema-CV9hMg8m.js → Schema-TErl3J36.js} +437 -93
  60. package/dist/cjs/Schema-TErl3J36.js.map +1 -0
  61. package/dist/cjs/{SchemaValidationService-DUtQUerg.js → SchemaValidationService-p5BbJV9T.js} +3 -3
  62. package/dist/cjs/{SchemaValidationService-DUtQUerg.js.map → SchemaValidationService-p5BbJV9T.js.map} +1 -1
  63. package/dist/cjs/{getItem-BThT-UOt.js → getItem-BrnLfC12.js} +3 -3
  64. package/dist/cjs/{getItem-BThT-UOt.js.map → getItem-BrnLfC12.js.map} +1 -1
  65. package/dist/cjs/{getPublishPayload-CKZ7rVbU.js → getPublishPayload-BcjCN_bD.js} +8 -6
  66. package/dist/cjs/getPublishPayload-BcjCN_bD.js.map +1 -0
  67. package/dist/cjs/{getPublishUploads-CuGIvV-Q.js → getPublishUploads-5_oXzwol.js} +4 -4
  68. package/dist/cjs/{getPublishUploads-CuGIvV-Q.js.map → getPublishUploads-5_oXzwol.js.map} +1 -1
  69. package/dist/cjs/{getSegmentedItemProperties-BCJXJlTR.js → getSegmentedItemProperties-WFdizUDv.js} +2 -2
  70. package/dist/cjs/{getSegmentedItemProperties-BCJXJlTR.js.map → getSegmentedItemProperties-WFdizUDv.js.map} +1 -1
  71. package/dist/cjs/{index-CbTBDqTJ.js → index-BrmvhXsG.js} +3 -3
  72. package/dist/cjs/index-BrmvhXsG.js.map +1 -0
  73. package/dist/cjs/{index-C3j3m34a.js → index-CXI4VF1H.js} +12351 -12189
  74. package/dist/cjs/index-CXI4VF1H.js.map +1 -0
  75. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  76. package/dist/client/actors/saveAppState.d.ts.map +1 -1
  77. package/dist/db/read/getModelSchemas.d.ts.map +1 -1
  78. package/dist/db/read/getPublishPayload.d.ts.map +1 -1
  79. package/dist/db/write/createNewItem.d.ts.map +1 -1
  80. package/dist/eas.d.ts.map +1 -1
  81. package/dist/events/files/download.d.ts.map +1 -1
  82. package/dist/events/item/syncDbWithEas.d.ts.map +1 -1
  83. package/dist/{getItem-BWPo8wd0.js → getItem-DaQVdeae.js} +8 -8
  84. package/dist/getItem-DaQVdeae.js.map +1 -0
  85. package/dist/{getPublishPayload-Caw2laZM.js → getPublishPayload-CWiLI1yd.js} +12 -10
  86. package/dist/getPublishPayload-CWiLI1yd.js.map +1 -0
  87. package/dist/{getPublishUploads-MlyBuoXh.js → getPublishUploads-DhvcKD_9.js} +9 -9
  88. package/dist/getPublishUploads-DhvcKD_9.js.map +1 -0
  89. package/dist/{getSegmentedItemProperties-COLLdDo4.js → getSegmentedItemProperties-Cp4kcWIF.js} +2 -2
  90. package/dist/getSegmentedItemProperties-Cp4kcWIF.js.map +1 -0
  91. package/dist/helpers/db.d.ts.map +1 -1
  92. package/dist/helpers/property.d.ts.map +1 -1
  93. package/dist/helpers/schema.d.ts.map +1 -1
  94. package/dist/helpers/updateSchema.d.ts.map +1 -1
  95. package/dist/imports/json.d.ts.map +1 -1
  96. package/dist/{index-D2OGsG4v.js → index-DBy53qbb.js} +2 -2
  97. package/dist/index-DBy53qbb.js.map +1 -0
  98. package/dist/{ClientManager-DoHUt8tU.js → index-Dk73a7JE.js} +11781 -11613
  99. package/dist/index-Dk73a7JE.js.map +1 -0
  100. package/dist/{index-B9i_mXXp.js → index-LfXKx_PE.js} +9 -9
  101. package/dist/index-LfXKx_PE.js.map +1 -0
  102. package/dist/main.cjs +2 -2
  103. package/dist/main.js +16 -13
  104. package/dist/main.js.map +1 -1
  105. package/dist/node/db/Db.d.ts.map +1 -1
  106. package/dist/node.js +15 -15
  107. package/dist/node.js.map +1 -1
  108. package/dist/{property-fK7tSUDX.js → property-1o2MvYTm.js} +10 -4
  109. package/dist/property-1o2MvYTm.js.map +1 -0
  110. package/dist/{queries-DGOk16cd.js → queries-DA4G0iEN.js} +2 -2
  111. package/dist/queries-DA4G0iEN.js.map +1 -0
  112. package/dist/services/publish/actors/preparePublishRequestData.d.ts.map +1 -1
  113. package/dist/services/publish/actors/upload.d.ts.map +1 -1
  114. package/dist/services/write/actors/validateEntity.d.ts.map +1 -1
  115. package/dist/services/write/actors/writeToDatabase.d.ts.map +1 -1
  116. package/dist/vite.js.map +1 -1
  117. package/package.json +8 -4
  118. package/dist/ArweaveClient-CczHvccG.js.map +0 -1
  119. package/dist/ArweaveClient-DkNLWiSZ.js.map +0 -1
  120. package/dist/ClientManager-DoHUt8tU.js.map +0 -1
  121. package/dist/Db-BzQR2KX9.js.map +0 -1
  122. package/dist/Db-DJvjXVlp.js.map +0 -1
  123. package/dist/EasClient-CHQYmjj2.js.map +0 -1
  124. package/dist/EasClient-CodrIgW-.js.map +0 -1
  125. package/dist/FileManager-BIVsDnMu.js.map +0 -1
  126. package/dist/FileManager-BbvkZJCH.js.map +0 -1
  127. package/dist/ModelProperty-gjcA83Mq.js.map +0 -1
  128. package/dist/PathResolver-9zAzPhee.js.map +0 -1
  129. package/dist/PathResolver-kGzba-zC.js.map +0 -1
  130. package/dist/QueryClient-C7ZkTT0z.js.map +0 -1
  131. package/dist/QueryClient-CEtsek7Q.js.map +0 -1
  132. package/dist/Schema-ClTcpgbt.js.map +0 -1
  133. package/dist/SchemaValidationService-BfoEiHNr.js.map +0 -1
  134. package/dist/cjs/ModelProperty-BRKRREYP.js.map +0 -1
  135. package/dist/cjs/Schema-CV9hMg8m.js.map +0 -1
  136. package/dist/cjs/getPublishPayload-CKZ7rVbU.js.map +0 -1
  137. package/dist/cjs/index-C3j3m34a.js.map +0 -1
  138. package/dist/cjs/index-CbTBDqTJ.js.map +0 -1
  139. package/dist/getItem-BWPo8wd0.js.map +0 -1
  140. package/dist/getPublishPayload-Caw2laZM.js.map +0 -1
  141. package/dist/getPublishUploads-MlyBuoXh.js.map +0 -1
  142. package/dist/getSegmentedItemProperties-COLLdDo4.js.map +0 -1
  143. package/dist/index-B9i_mXXp.js.map +0 -1
  144. package/dist/index-D2OGsG4v.js.map +0 -1
  145. package/dist/property-fK7tSUDX.js.map +0 -1
  146. package/dist/queries-DGOk16cd.js.map +0 -1
@@ -1,22 +1,740 @@
1
1
  import { fromCallback, setup, assign, createActor } from 'xstate';
2
- import { aG as SEED_PROTOCOL_SCHEMA_NAME, p as BaseDb, W as schemas, aH as addSchemaToDb, ag as generateId, ae as createModelsFromJson, a2 as addModelsToDb, q as models, G as modelSchemas, r as properties, aE as listCompleteSchemaFiles, s as BaseFileManager, aI as loadModelsFromDbForSchema, ad as getLatestSchemaVersion, aJ as isInternalSchema, aK as createModelFromJson, M as Model, af as writeProcessMachine, ah as waitForEntityIdle, ai as createReactiveProxy, aj as findEntity, aq as loadAllSchemasFromDb, aL as ConflictError, aM as unloadEntity, aN as clearDestroySubscriptions, ak as forceRemoveFromCaches, al as runDestroyLifecycle, aO as setupEntityLiveQuery } from './ClientManager-DoHUt8tU.js';
2
+ import { a as ModelPropertyDataTypes, aG as getLatestSchemaVersion, x as BaseFileManager, p as BaseDb, q as models, W as schemas, ae as generateId, aH as createModelsFromJson, aa as loadSchemaFromFile, aI as SEED_PROTOCOL_SCHEMA_NAME, aJ as addSchemaToDb, a2 as addModelsToDb, G as modelSchemas, r as properties, aE as listCompleteSchemaFiles, aK as loadModelsFromDbForSchema, aL as isInternalSchema, aM as createModelFromJson, M as Model, ad as writeProcessMachine, af as waitForEntityIdle, ag as createReactiveProxy, ah as findEntity, aq as loadAllSchemasFromDb, aN as ConflictError, am as getClient, an as ClientManagerState, aO as unloadEntity, aP as clearDestroySubscriptions, ai as forceRemoveFromCaches, aj as runDestroyLifecycle, aQ as setupEntityLiveQuery } from './index-Dk73a7JE.js';
3
3
  import { eq, desc, and } from 'drizzle-orm';
4
4
  import debug from 'debug';
5
- import { SchemaValidationService } from './SchemaValidationService-BfoEiHNr.js';
6
- import { M as ModelProperty, c as convertPropertyToSchemaUpdate, w as writeFullSchemaNewVersion, u as updateModelProperties } from './ModelProperty-gjcA83Mq.js';
5
+ import { SchemaValidationService } from './SchemaValidationService-F8No7BHp.js';
7
6
  import 'pluralize';
8
- import 'rxjs';
9
- import 'lodash-es';
10
- import 'drizzle-orm/casing';
11
- import '@sinclair/typebox';
12
- import 'arweave';
13
- import 'eventemitter3';
14
- import 'drizzle-orm/sqlite-core';
15
- import 'nanoid';
16
- import 'nanoid-dictionary';
17
- import 'ethers';
18
- import '@sinclair/typebox/value';
19
- import 'reflect-metadata';
7
+
8
+ const logger$d = debug('seedSdk:helpers:updateSchema');
9
+ /**
10
+ * Get the file path for a schema file
11
+ */
12
+ /**
13
+ * Sanitize a schema name to be filesystem-safe
14
+ * Replaces all special characters (except alphanumeric, hyphens, underscores) with underscores
15
+ * Converts spaces to underscores
16
+ * Removes leading/trailing underscores
17
+ *
18
+ * @param name - Schema name to sanitize
19
+ * @returns Sanitized name safe for use in filenames
20
+ */
21
+ const sanitizeSchemaName$1 = (name) => {
22
+ return name
23
+ .replace(/[^a-zA-Z0-9\s_-]/g, '_') // Replace special chars (except spaces, hyphens, underscores) with underscore
24
+ .replace(/\s+/g, '_') // Convert spaces to underscores
25
+ .replace(/^_+|_+$/g, '') // Remove leading/trailing underscores
26
+ .replace(/_+/g, '_'); // Collapse multiple underscores to single
27
+ };
28
+ /**
29
+ * Get the full file path for a schema
30
+ * Format: {schemaFileId}_{schemaName}_v{version}.json
31
+ *
32
+ * The ID-first format ensures all files for a schema group together when sorted alphabetically.
33
+ *
34
+ * @param name - Schema name
35
+ * @param version - Schema version
36
+ * @param schemaFileId - Schema file ID (required)
37
+ */
38
+ const getSchemaFilePath$2 = (name, version, schemaFileId) => {
39
+ const path = BaseFileManager.getPathModule();
40
+ const workingDir = BaseFileManager.getWorkingDir();
41
+ const sanitizedName = sanitizeSchemaName$1(name);
42
+ const filename = schemaFileId
43
+ ? `${schemaFileId}_${sanitizedName}_v${version}.json`
44
+ : `${sanitizedName}_v${version}.json`;
45
+ return path.join(workingDir, filename);
46
+ };
47
+ /**
48
+ * Get schemaFileId from database for a schema
49
+ * @param schemaName - Schema name
50
+ * @returns Schema file ID
51
+ * @throws Error if schema not found or missing schemaFileId
52
+ */
53
+ async function getSchemaFileId(schemaName) {
54
+ const db = BaseDb.getAppDb();
55
+ if (!db)
56
+ throw new Error('Database not available');
57
+ const dbSchema = await db
58
+ .select()
59
+ .from(schemas)
60
+ .where(eq(schemas.name, schemaName))
61
+ .orderBy(desc(schemas.version))
62
+ .limit(1);
63
+ if (dbSchema.length === 0 || !dbSchema[0].schemaFileId) {
64
+ throw new Error(`Schema ${schemaName} not found in database or missing schemaFileId`);
65
+ }
66
+ return dbSchema[0].schemaFileId;
67
+ }
68
+ /**
69
+ * Write the full schema to a new version file (e.g. when new models were added).
70
+ * Used when _editedProperties contains 'schema:models' and there are no property-level updates.
71
+ * @param schemaName - Schema name
72
+ * @param schema - Full schema object (e.g. from _buildModelsFromInstances)
73
+ * @returns The file path of the new schema version
74
+ */
75
+ async function writeFullSchemaNewVersion(schemaName, schema) {
76
+ const latestVersion = await getLatestSchemaVersion(schemaName);
77
+ const newVersion = latestVersion + 1;
78
+ const schemaWithNewVersion = {
79
+ ...schema,
80
+ version: newVersion,
81
+ metadata: {
82
+ ...schema.metadata,
83
+ updatedAt: new Date().toISOString(),
84
+ },
85
+ migrations: [
86
+ ...(schema.migrations || []),
87
+ {
88
+ version: newVersion,
89
+ timestamp: new Date().toISOString(),
90
+ description: 'New schema version (e.g. new models added)',
91
+ changes: [{ type: 'full_schema_write' }],
92
+ },
93
+ ],
94
+ };
95
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, schema.id ?? (await getSchemaFileId(schemaName)));
96
+ const newContent = JSON.stringify(schemaWithNewVersion, null, 2);
97
+ await BaseFileManager.saveFile(newFilePath, newContent);
98
+ await BaseFileManager.waitForFileWithContent(newFilePath);
99
+ logger$d(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
100
+ return newFilePath;
101
+ }
102
+ /**
103
+ * Get model name from modelId
104
+ * @param modelId - The model ID to look up
105
+ * @returns The model name, or undefined if not found
106
+ */
107
+ async function getModelNameFromId(modelId) {
108
+ if (!modelId) {
109
+ return undefined;
110
+ }
111
+ const db = BaseDb.getAppDb();
112
+ if (!db) {
113
+ throw new Error('Database not found');
114
+ }
115
+ const modelRecords = await db
116
+ .select()
117
+ .from(models)
118
+ .where(eq(models.id, modelId))
119
+ .limit(1);
120
+ if (modelRecords.length === 0) {
121
+ return undefined;
122
+ }
123
+ return modelRecords[0].name;
124
+ }
125
+ /**
126
+ * Convert a TProperty/ModelPropertyMachineContext to SchemaPropertyUpdate format
127
+ * This function converts the internal property representation to the schema file format
128
+ * @param property - The TProperty instance to convert
129
+ * @param modelName - The name of the model this property belongs to
130
+ * @param propertyName - The name of the property
131
+ * @returns A SchemaPropertyUpdate object ready to be passed to updateModelProperties
132
+ */
133
+ async function convertPropertyToSchemaUpdate(property, modelName, propertyName) {
134
+ const updates = {};
135
+ // Convert dataType to type
136
+ if (property.dataType) {
137
+ updates.type = property.dataType;
138
+ }
139
+ // Handle Relation type
140
+ if (property.dataType === ModelPropertyDataTypes.Relation) {
141
+ if (property.ref) {
142
+ updates.model = property.ref;
143
+ }
144
+ else if (property.refModelId) {
145
+ // If ref is not set but refModelId is, get the model name from the database
146
+ const refModelName = await getModelNameFromId(property.refModelId);
147
+ if (refModelName) {
148
+ updates.model = refModelName;
149
+ }
150
+ }
151
+ }
152
+ // Handle List type
153
+ if (property.dataType === ModelPropertyDataTypes.List) {
154
+ if (property.refValueType) {
155
+ updates.items = {
156
+ type: property.refValueType,
157
+ };
158
+ if (property.ref) {
159
+ updates.items.model = property.ref;
160
+ }
161
+ else if (property.refModelId) {
162
+ // If ref is not set but refModelId is, get the model name from the database
163
+ const refModelName = await getModelNameFromId(property.refModelId);
164
+ if (refModelName) {
165
+ updates.items.model = refModelName;
166
+ }
167
+ }
168
+ }
169
+ }
170
+ // Handle storage configuration (for Text properties with storage)
171
+ if (property.storageType || property.localStorageDir || property.filenameSuffix) {
172
+ const storageType = property.storageType || 'ItemStorage'; // Default to ItemStorage if not specified
173
+ updates.storage = {
174
+ type: storageType,
175
+ };
176
+ if (property.localStorageDir) {
177
+ updates.storage.path = property.localStorageDir;
178
+ }
179
+ if (property.filenameSuffix) {
180
+ updates.storage.extension = property.filenameSuffix;
181
+ }
182
+ }
183
+ return {
184
+ modelName,
185
+ propertyName,
186
+ updates,
187
+ };
188
+ }
189
+ /**
190
+ * Update model properties in a schema and create a new version
191
+ * @param schemaName - The name of the schema to update
192
+ * @param propertyUpdates - Array of property updates to apply
193
+ * @param modelUpdates - Optional array of model renames
194
+ * @returns The file path of the new schema version
195
+ * @throws Error if schema not found or updates are invalid
196
+ */
197
+ async function updateModelProperties(schemaName, propertyUpdates, modelUpdates) {
198
+ // Get the latest version of the schema
199
+ const latestVersion = await getLatestSchemaVersion(schemaName);
200
+ if (latestVersion === 0) {
201
+ throw new Error(`Schema ${schemaName} not found`);
202
+ }
203
+ // Get schemaFileId from database
204
+ const schemaFileId = await getSchemaFileId(schemaName);
205
+ // Load the latest schema file
206
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
207
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
208
+ const schemaFile = JSON.parse(content);
209
+ if (!schemaFile.$schema) {
210
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
211
+ }
212
+ // Create a copy of the schema for the new version
213
+ // Preserve schema ID and all model/property IDs
214
+ const newVersion = latestVersion + 1;
215
+ const updatedSchema = {
216
+ ...schemaFile,
217
+ version: newVersion,
218
+ // Preserve schema ID from previous version
219
+ id: schemaFile.id,
220
+ metadata: {
221
+ ...schemaFile.metadata,
222
+ updatedAt: new Date().toISOString(),
223
+ },
224
+ // Deep copy models to preserve IDs
225
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
226
+ modelName,
227
+ {
228
+ ...model,
229
+ // Preserve model ID
230
+ id: model.id,
231
+ // Deep copy properties to preserve IDs
232
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
233
+ propName,
234
+ {
235
+ ...prop,
236
+ // Preserve property ID
237
+ id: prop.id,
238
+ },
239
+ ])),
240
+ },
241
+ ])),
242
+ migrations: [
243
+ ...schemaFile.migrations,
244
+ {
245
+ version: newVersion,
246
+ timestamp: new Date().toISOString(),
247
+ description: `Updated model properties: ${propertyUpdates.map(u => `${u.modelName}.${u.propertyName}`).join(', ')}`,
248
+ changes: propertyUpdates.map(update => ({
249
+ type: 'property_update',
250
+ modelName: update.modelName,
251
+ propertyName: update.propertyName,
252
+ updates: update.updates,
253
+ })),
254
+ },
255
+ ],
256
+ };
257
+ // Apply model renames first (if any)
258
+ if (modelUpdates && modelUpdates.length > 0) {
259
+ for (const modelUpdate of modelUpdates) {
260
+ if (updatedSchema.models[modelUpdate.oldName]) {
261
+ // Rename the model in the models object
262
+ updatedSchema.models[modelUpdate.newName] = updatedSchema.models[modelUpdate.oldName];
263
+ delete updatedSchema.models[modelUpdate.oldName];
264
+ // Update any property references to this model
265
+ for (const modelName in updatedSchema.models) {
266
+ const model = updatedSchema.models[modelName];
267
+ for (const propertyName in model.properties) {
268
+ const property = model.properties[propertyName];
269
+ if (property.model === modelUpdate.oldName) {
270
+ property.model = modelUpdate.newName;
271
+ }
272
+ if (property.items?.model === modelUpdate.oldName) {
273
+ property.items.model = modelUpdate.newName;
274
+ }
275
+ }
276
+ }
277
+ // Add to migration changes
278
+ updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
279
+ type: 'model_rename',
280
+ oldName: modelUpdate.oldName,
281
+ newName: modelUpdate.newName,
282
+ });
283
+ }
284
+ }
285
+ }
286
+ // Apply property updates
287
+ for (const update of propertyUpdates) {
288
+ const model = updatedSchema.models[update.modelName];
289
+ if (!model) {
290
+ throw new Error(`Model ${update.modelName} not found in schema ${schemaName}`);
291
+ }
292
+ if (!model.properties[update.propertyName]) {
293
+ throw new Error(`Property ${update.propertyName} not found in model ${update.modelName} of schema ${schemaName}`);
294
+ }
295
+ // Update the property with new values
296
+ const property = model.properties[update.propertyName];
297
+ Object.assign(property, update.updates);
298
+ }
299
+ // Write the new schema version to file using ID-based naming (preferred)
300
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
301
+ const newContent = JSON.stringify(updatedSchema, null, 2);
302
+ await BaseFileManager.saveFile(newFilePath, newContent);
303
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
304
+ await BaseFileManager.waitForFileWithContent(newFilePath);
305
+ logger$d(`Created new schema version ${newVersion} for ${schemaName} at ${newFilePath}`);
306
+ // Load the new schema file to process models and add them to the database
307
+ // Extract model renames from migrations to pass to database update
308
+ const modelRenames = new Map();
309
+ const latestMigration = updatedSchema.migrations[updatedSchema.migrations.length - 1];
310
+ for (const change of latestMigration.changes) {
311
+ if (change.type === 'model_rename') {
312
+ modelRenames.set(change.oldName, change.newName);
313
+ }
314
+ }
315
+ // Load schema with model renames handled
316
+ await loadSchemaWithRenames(newFilePath, modelRenames);
317
+ return newFilePath;
318
+ }
319
+ /**
320
+ * Load a schema file and handle model renames in the database
321
+ * This is a helper function that processes model renames before loading
322
+ */
323
+ async function loadSchemaWithRenames(schemaFilePath, modelRenames) {
324
+ const content = await BaseFileManager.readFileAsString(schemaFilePath);
325
+ const schemaFile = JSON.parse(content);
326
+ if (!schemaFile.$schema) {
327
+ throw new Error(`File ${schemaFilePath} is not a complete schema file (missing $schema field).`);
328
+ }
329
+ const schemaName = schemaFile.metadata?.name;
330
+ const version = schemaFile.version;
331
+ if (!schemaName) {
332
+ throw new Error('Schema name is required in metadata.name');
333
+ }
334
+ // Convert to JsonImportSchema format for processing
335
+ // Remove id fields for JsonImportSchema format (they're not part of the import format)
336
+ const importData = {
337
+ name: schemaName,
338
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([modelName, model]) => [
339
+ modelName,
340
+ {
341
+ description: model.description,
342
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
343
+ propName,
344
+ {
345
+ type: prop.type || 'string', // Ensure type is present
346
+ ...prop,
347
+ // Remove id field for import format (not part of JsonImportSchema)
348
+ },
349
+ ])),
350
+ indexes: model.indexes,
351
+ },
352
+ ])),
353
+ };
354
+ // Generate schema ID if missing
355
+ if (!schemaFile.id) {
356
+ schemaFile.id = generateId();
357
+ logger$d('Generated schema ID for schema:', schemaFile.id);
358
+ }
359
+ // Extract schemaFileIds from JSON file and generate missing ones BEFORE creating models
360
+ // This ensures Model instances are created with correct IDs
361
+ const modelFileIds = new Map();
362
+ const propertyFileIds = new Map();
363
+ for (const [modelName, model] of Object.entries(schemaFile.models)) {
364
+ // Generate model ID if missing
365
+ if (!model.id) {
366
+ model.id = generateId();
367
+ logger$d(`Generated model ID for ${modelName}:`, model.id);
368
+ }
369
+ modelFileIds.set(modelName, model.id);
370
+ const propIds = new Map();
371
+ for (const [propName, prop] of Object.entries(model.properties)) {
372
+ // Generate property ID if missing
373
+ if (!prop.id) {
374
+ prop.id = generateId();
375
+ logger$d(`Generated property ID for ${modelName}.${propName}:`, prop.id);
376
+ }
377
+ propIds.set(propName, prop.id);
378
+ }
379
+ if (propIds.size > 0) {
380
+ propertyFileIds.set(modelName, propIds);
381
+ }
382
+ }
383
+ // Convert JSON models to Model classes, passing modelFileIds and propertyFileIds so Model instances use correct IDs
384
+ const modelDefinitions = await createModelsFromJson(importData, modelFileIds, propertyFileIds);
385
+ // Convert schema file metadata to schema input for database
386
+ const schemaInput = {
387
+ name: schemaName,
388
+ version,
389
+ schemaFileId: schemaFile.id || null,
390
+ schemaData: null,
391
+ isDraft: false,
392
+ isEdited: false,
393
+ createdAt: new Date(schemaFile.metadata.createdAt).getTime(),
394
+ updatedAt: new Date(schemaFile.metadata.updatedAt).getTime(),
395
+ };
396
+ // Use dynamic import to break circular dependency
397
+ const _mod_0 = await import('./index-Dk73a7JE.js');
398
+ const _ns_0 = _mod_0.aT;
399
+ const dbMod = _ns_0;
400
+ const { addSchemaToDb, addModelsToDb } = dbMod;
401
+ // Add schema to database with schemaFileId
402
+ const schemaRecord = await addSchemaToDb(schemaInput, schemaFile.id);
403
+ // Add models to database with model renames handled and schemaFileIds
404
+ await addModelsToDb(modelDefinitions, schemaRecord, modelRenames, {
405
+ schemaFileId: schemaFile.id,
406
+ modelFileIds,
407
+ propertyFileIds,
408
+ });
409
+ // Models are now Model instances, no registration needed
410
+ // They should be created via Model.create() and are accessible via Model static methods
411
+ for (const [modelName] of Object.entries(modelDefinitions)) {
412
+ logger$d('loadSchemaWithRenames - model available:', modelName);
413
+ }
414
+ return schemaFilePath;
415
+ }
416
+ /**
417
+ * Rename a property in a model
418
+ * This is a convenience function that updates the property name
419
+ * Note: This creates a new property and you may want to handle the old property separately
420
+ * @param schemaName - The name of the schema
421
+ * @param modelName - The name of the model
422
+ * @param oldPropertyName - The current property name
423
+ * @param newPropertyName - The new property name
424
+ * @returns The file path of the new schema version
425
+ */
426
+ async function renameModelProperty(schemaName, modelName, oldPropertyName, newPropertyName) {
427
+ // Get the latest version
428
+ const latestVersion = await getLatestSchemaVersion(schemaName);
429
+ if (latestVersion === 0) {
430
+ throw new Error(`Schema ${schemaName} not found`);
431
+ }
432
+ // Get schemaFileId from database
433
+ const schemaFileId = await getSchemaFileId(schemaName);
434
+ // Load the latest schema file
435
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
436
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
437
+ const schemaFile = JSON.parse(content);
438
+ if (!schemaFile.$schema) {
439
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
440
+ }
441
+ const model = schemaFile.models[modelName];
442
+ if (!model) {
443
+ throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
444
+ }
445
+ if (!model.properties[oldPropertyName]) {
446
+ throw new Error(`Property ${oldPropertyName} not found in model ${modelName} of schema ${schemaName}`);
447
+ }
448
+ if (model.properties[newPropertyName]) {
449
+ throw new Error(`Property ${newPropertyName} already exists in model ${modelName} of schema ${schemaName}`);
450
+ }
451
+ // Create new version with renamed property
452
+ // Preserve all IDs - when renaming, we keep the same property ID
453
+ const newVersion = latestVersion + 1;
454
+ const oldProperty = model.properties[oldPropertyName];
455
+ const updatedSchema = {
456
+ ...schemaFile,
457
+ version: newVersion,
458
+ id: schemaFile.id, // Preserve schema ID
459
+ metadata: {
460
+ ...schemaFile.metadata,
461
+ updatedAt: new Date().toISOString(),
462
+ },
463
+ models: {
464
+ ...schemaFile.models,
465
+ [modelName]: {
466
+ ...model,
467
+ id: model.id, // Preserve model ID
468
+ properties: {
469
+ ...Object.fromEntries(Object.entries(model.properties)
470
+ .filter(([name]) => name !== oldPropertyName)
471
+ .map(([name, prop]) => [name, { ...prop, id: prop.id }])),
472
+ [newPropertyName]: {
473
+ ...oldProperty,
474
+ id: oldProperty.id, // Preserve property ID when renaming
475
+ },
476
+ },
477
+ },
478
+ },
479
+ migrations: [
480
+ ...schemaFile.migrations,
481
+ {
482
+ version: newVersion,
483
+ timestamp: new Date().toISOString(),
484
+ description: `Renamed property ${modelName}.${oldPropertyName} to ${newPropertyName}`,
485
+ changes: [
486
+ {
487
+ type: 'property_rename',
488
+ modelName,
489
+ oldPropertyName,
490
+ newPropertyName,
491
+ },
492
+ ],
493
+ },
494
+ ],
495
+ };
496
+ // Remove the old property name
497
+ delete updatedSchema.models[modelName].properties[oldPropertyName];
498
+ // Write the new schema version using ID-based naming (preferred)
499
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
500
+ const newContent = JSON.stringify(updatedSchema, null, 2);
501
+ // Ensure the directory exists before saving
502
+ const path = BaseFileManager.getPathModule();
503
+ const dir = path.dirname(newFilePath);
504
+ await BaseFileManager.createDirIfNotExists(dir);
505
+ await BaseFileManager.saveFile(newFilePath, newContent);
506
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
507
+ await BaseFileManager.waitForFileWithContent(newFilePath);
508
+ logger$d(`Renamed property ${oldPropertyName} to ${newPropertyName} in schema ${schemaName} v${newVersion}`);
509
+ // Load the new schema file
510
+ await loadSchemaFromFile(newFilePath);
511
+ return newFilePath;
512
+ }
513
+ /**
514
+ * Delete a model from a schema
515
+ * @param schemaName - The name of the schema
516
+ * @param modelName - The name of the model to delete
517
+ * @param options - Optional deletion options
518
+ * @returns The file path of the new schema version
519
+ * @throws Error if schema or model not found
520
+ */
521
+ async function deleteModelFromSchema(schemaName, modelName, options = {}) {
522
+ const { removeReferencingProperties = false } = options;
523
+ // Get the latest version
524
+ const latestVersion = await getLatestSchemaVersion(schemaName);
525
+ if (latestVersion === 0) {
526
+ throw new Error(`Schema ${schemaName} not found`);
527
+ }
528
+ // Get schemaFileId from database
529
+ const schemaFileId = await getSchemaFileId(schemaName);
530
+ // Load the latest schema file
531
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
532
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
533
+ const schemaFile = JSON.parse(content);
534
+ if (!schemaFile.$schema) {
535
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
536
+ }
537
+ if (!schemaFile.models[modelName]) {
538
+ throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
539
+ }
540
+ // Create new version without the model
541
+ // Preserve IDs for remaining models and properties
542
+ const newVersion = latestVersion + 1;
543
+ const updatedSchema = {
544
+ ...schemaFile,
545
+ version: newVersion,
546
+ id: schemaFile.id, // Preserve schema ID
547
+ metadata: {
548
+ ...schemaFile.metadata,
549
+ updatedAt: new Date().toISOString(),
550
+ },
551
+ // Preserve IDs for remaining models and their properties
552
+ models: Object.fromEntries(Object.entries(schemaFile.models)
553
+ .filter(([name]) => name !== modelName)
554
+ .map(([name, model]) => [
555
+ name,
556
+ {
557
+ ...model,
558
+ id: model.id, // Preserve model ID
559
+ properties: Object.fromEntries(Object.entries(model.properties).map(([propName, prop]) => [
560
+ propName,
561
+ { ...prop, id: prop.id }, // Preserve property ID
562
+ ])),
563
+ },
564
+ ])),
565
+ migrations: [
566
+ ...schemaFile.migrations,
567
+ {
568
+ version: newVersion,
569
+ timestamp: new Date().toISOString(),
570
+ description: `Deleted model ${modelName} from schema`,
571
+ changes: [
572
+ {
573
+ type: 'model_delete',
574
+ modelName,
575
+ removeReferencingProperties,
576
+ },
577
+ ],
578
+ },
579
+ ],
580
+ };
581
+ // Remove the model
582
+ delete updatedSchema.models[modelName];
583
+ // Handle properties that reference this model
584
+ const propertiesToRemove = [];
585
+ for (const [otherModelName, model] of Object.entries(updatedSchema.models)) {
586
+ for (const [propertyName, property] of Object.entries(model.properties)) {
587
+ // Check if property references the deleted model
588
+ if (property.model === modelName || property.items?.model === modelName) {
589
+ if (removeReferencingProperties) {
590
+ // Mark for removal
591
+ propertiesToRemove.push({ modelName: otherModelName, propertyName });
592
+ }
593
+ else {
594
+ // Remove the reference (set to null or remove model field)
595
+ if (property.model === modelName) {
596
+ delete property.model;
597
+ }
598
+ if (property.items?.model === modelName) {
599
+ delete property.items.model;
600
+ // If items only had model, we might want to remove items entirely
601
+ // But for now, just remove the model reference
602
+ }
603
+ }
604
+ }
605
+ }
606
+ }
607
+ // Remove properties if requested
608
+ if (removeReferencingProperties) {
609
+ for (const { modelName: mName, propertyName } of propertiesToRemove) {
610
+ delete updatedSchema.models[mName].properties[propertyName];
611
+ updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
612
+ type: 'property_delete',
613
+ modelName: mName,
614
+ propertyName,
615
+ reason: `Referenced deleted model ${modelName}`,
616
+ });
617
+ }
618
+ }
619
+ else {
620
+ // Update migration to note which properties were updated
621
+ const updatedProperties = [];
622
+ for (const [otherModelName, model] of Object.entries(updatedSchema.models)) {
623
+ for (const [propertyName, property] of Object.entries(model.properties)) {
624
+ if (property.model === modelName || property.items?.model === modelName) {
625
+ updatedProperties.push({ modelName: otherModelName, propertyName });
626
+ }
627
+ }
628
+ }
629
+ if (updatedProperties.length > 0) {
630
+ updatedSchema.migrations[updatedSchema.migrations.length - 1].changes.push({
631
+ type: 'properties_updated',
632
+ properties: updatedProperties,
633
+ reason: `Removed references to deleted model ${modelName}`,
634
+ });
635
+ }
636
+ }
637
+ // Write the new schema version using ID-based naming (preferred)
638
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
639
+ const newContent = JSON.stringify(updatedSchema, null, 2);
640
+ // Ensure the directory exists before saving
641
+ const path = BaseFileManager.getPathModule();
642
+ const dir = path.dirname(newFilePath);
643
+ await BaseFileManager.createDirIfNotExists(dir);
644
+ await BaseFileManager.saveFile(newFilePath, newContent);
645
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
646
+ await BaseFileManager.waitForFileWithContent(newFilePath);
647
+ logger$d(`Deleted model ${modelName} from schema ${schemaName} v${newVersion}`);
648
+ // Load the new schema file
649
+ await loadSchemaFromFile(newFilePath);
650
+ return newFilePath;
651
+ }
652
+ /**
653
+ * Delete a property from a model in a schema
654
+ * @param schemaName - The name of the schema
655
+ * @param modelName - The name of the model
656
+ * @param propertyName - The name of the property to delete
657
+ * @param options - Optional deletion options
658
+ * @returns The file path of the new schema version
659
+ * @throws Error if schema, model, or property not found
660
+ */
661
+ async function deletePropertyFromModel(schemaName, modelName, propertyName, options = {}) {
662
+ // Get the latest version
663
+ const latestVersion = await getLatestSchemaVersion(schemaName);
664
+ if (latestVersion === 0) {
665
+ throw new Error(`Schema ${schemaName} not found`);
666
+ }
667
+ // Get schemaFileId from database
668
+ const schemaFileId = await getSchemaFileId(schemaName);
669
+ // Load the latest schema file
670
+ const latestFilePath = getSchemaFilePath$2(schemaName, latestVersion, schemaFileId);
671
+ const content = await BaseFileManager.readFileAsString(latestFilePath);
672
+ const schemaFile = JSON.parse(content);
673
+ if (!schemaFile.$schema) {
674
+ throw new Error(`Schema file ${latestFilePath} is not a complete schema file`);
675
+ }
676
+ const model = schemaFile.models[modelName];
677
+ if (!model) {
678
+ throw new Error(`Model ${modelName} not found in schema ${schemaName}`);
679
+ }
680
+ if (!model.properties[propertyName]) {
681
+ throw new Error(`Property ${propertyName} not found in model ${modelName} of schema ${schemaName}`);
682
+ }
683
+ // Create new version without the property
684
+ // Preserve IDs for schema, models, and remaining properties
685
+ const newVersion = latestVersion + 1;
686
+ const updatedSchema = {
687
+ ...schemaFile,
688
+ version: newVersion,
689
+ id: schemaFile.id, // Preserve schema ID
690
+ metadata: {
691
+ ...schemaFile.metadata,
692
+ updatedAt: new Date().toISOString(),
693
+ },
694
+ models: Object.fromEntries(Object.entries(schemaFile.models).map(([mName, m]) => [
695
+ mName,
696
+ {
697
+ ...m,
698
+ id: m.id, // Preserve model ID
699
+ properties: Object.fromEntries(Object.entries(m.properties)
700
+ .filter(([propName]) => !(mName === modelName && propName === propertyName))
701
+ .map(([propName, prop]) => [
702
+ propName,
703
+ { ...prop, id: prop.id }, // Preserve property ID
704
+ ])),
705
+ },
706
+ ])),
707
+ migrations: [
708
+ ...schemaFile.migrations,
709
+ {
710
+ version: newVersion,
711
+ timestamp: new Date().toISOString(),
712
+ description: `Deleted property ${modelName}.${propertyName} from schema`,
713
+ changes: [
714
+ {
715
+ type: 'property_delete',
716
+ modelName,
717
+ propertyName,
718
+ },
719
+ ],
720
+ },
721
+ ],
722
+ };
723
+ // Write the new schema version using ID-based naming (preferred)
724
+ const newFilePath = getSchemaFilePath$2(schemaName, newVersion, updatedSchema.id ?? undefined);
725
+ const newContent = JSON.stringify(updatedSchema, null, 2);
726
+ // Ensure the directory exists before saving
727
+ const path = BaseFileManager.getPathModule();
728
+ const dir = path.dirname(newFilePath);
729
+ await BaseFileManager.createDirIfNotExists(dir);
730
+ await BaseFileManager.saveFile(newFilePath, newContent);
731
+ // Wait for the file to be available with content (important for browser/OPFS where writes may not be immediately readable)
732
+ await BaseFileManager.waitForFileWithContent(newFilePath);
733
+ logger$d(`Deleted property ${propertyName} from model ${modelName} in schema ${schemaName} v${newVersion}`);
734
+ // Load the new schema file
735
+ await loadSchemaFromFile(newFilePath);
736
+ return newFilePath;
737
+ }
20
738
 
21
739
  const logger$c = debug('seedSdk:schema:actors:loadOrCreateSchema');
22
740
  /**
@@ -60,7 +778,10 @@ const createModelInstances$2 = async (modelIds) => {
60
778
  return;
61
779
  }
62
780
  try {
63
- const { Model } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
781
+ const _mod_1 = await import('./index-Dk73a7JE.js');
782
+ const _ns_1 = _mod_1.aW;
783
+ const modelMod = _ns_1;
784
+ const { Model } = modelMod;
64
785
  // Create instances for all model IDs in parallel
65
786
  // Model.createById() will check cache first, then query DB and create if needed
66
787
  const createPromises = modelIds.map(async (modelFileId) => {
@@ -173,7 +894,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
173
894
  logger$c(`Loading internal Seed Protocol schema from SDK`);
174
895
  console.log('[loadOrCreateSchema] Loading internal Seed Protocol schema from SDK');
175
896
  try {
176
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
897
+ const _mod_2 = await import('./index-Dk73a7JE.js');
898
+ const _ns_2 = _mod_2.aV;
899
+ const internalSchema = _ns_2;
177
900
  const schemaFile = internalSchema.default;
178
901
  console.log('[loadOrCreateSchema] Loaded schema file, models count:', Object.keys(schemaFile.models || {}).length);
179
902
  // Check if it exists in database, if not, add it
@@ -673,7 +1396,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
673
1396
  // Ensure models are populated (fallback for seed-protocol if missing)
674
1397
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
675
1398
  try {
676
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1399
+ const _mod_3 = await import('./index-Dk73a7JE.js');
1400
+ const _ns_3 = _mod_3.aV;
1401
+ const internalSchema = _ns_3;
677
1402
  const internalSchemaFile = internalSchema.default;
678
1403
  mergedModels = { ...(internalSchemaFile.models || {}) };
679
1404
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -868,7 +1593,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
868
1593
  // Ensure models are populated (fallback for seed-protocol if missing)
869
1594
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
870
1595
  try {
871
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1596
+ const _mod_4 = await import('./index-Dk73a7JE.js');
1597
+ const _ns_4 = _mod_4.aV;
1598
+ const internalSchema = _ns_4;
872
1599
  const internalSchemaFile = internalSchema.default;
873
1600
  mergedModels = { ...(internalSchemaFile.models || {}) };
874
1601
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -940,7 +1667,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
940
1667
  // Ensure models are populated (fallback for seed-protocol if missing)
941
1668
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
942
1669
  try {
943
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1670
+ const _mod_5 = await import('./index-Dk73a7JE.js');
1671
+ const _ns_5 = _mod_5.aV;
1672
+ const internalSchema = _ns_5;
944
1673
  const internalSchemaFile = internalSchema.default;
945
1674
  mergedModels = { ...(internalSchemaFile.models || {}) };
946
1675
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -1009,7 +1738,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
1009
1738
  // If schemaData is missing, try to load from internal schema file for seed-protocol
1010
1739
  if (!dbSchema.schemaData && schemaName === 'Seed Protocol') {
1011
1740
  try {
1012
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1741
+ const _mod_6 = await import('./index-Dk73a7JE.js');
1742
+ const _ns_6 = _mod_6.aV;
1743
+ const internalSchema = _ns_6;
1013
1744
  const schemaFile = internalSchema.default;
1014
1745
  logger$c(`Found seed-protocol schema in internal file (schemaData missing, using internal schema)`);
1015
1746
  // Update database with schemaData for future loads
@@ -1118,7 +1849,9 @@ const loadOrCreateSchema = fromCallback(({ sendBack, input: { context } }) => {
1118
1849
  // Ensure models are populated (fallback for seed-protocol if missing)
1119
1850
  if ((!mergedModels || Object.keys(mergedModels).length === 0) && schemaName === 'Seed Protocol') {
1120
1851
  try {
1121
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
1852
+ const _mod_7 = await import('./index-Dk73a7JE.js');
1853
+ const _ns_7 = _mod_7.aV;
1854
+ const internalSchema = _ns_7;
1122
1855
  const internalSchemaFile = internalSchema.default;
1123
1856
  mergedModels = { ...(internalSchemaFile.models || {}) };
1124
1857
  logger$c(`Populated models for seed-protocol schema from internal file`);
@@ -1434,20 +2167,16 @@ const addModelsMachine = setup({
1434
2167
  }),
1435
2168
  createModelInstances: fromCallback(({ sendBack, input }) => {
1436
2169
  const _createInstances = async () => {
1437
- const { Schema } = await Promise.resolve().then(function () { return Schema$1; });
1438
- const { BaseDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aP; });
1439
- const { models: modelsTable } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aQ; });
1440
- const { eq } = await import('drizzle-orm');
1441
- const { generateId } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aS; });
1442
2170
  const debug = (await import('debug')).default;
1443
2171
  const logger = debug('seedSdk:schema:addModels:createInstances');
2172
+ const schemaMod = await Promise.resolve().then(function () { return Schema$1; });
2173
+ const { Schema: SchemaClass, schemaInstanceState } = schemaMod;
1444
2174
  const schemaName = input.schemaContext.metadata?.name || input.schemaContext.schemaName;
1445
- const schemaInstance = Schema.create(schemaName, {
2175
+ const schemaInstance = SchemaClass.create(schemaName, {
1446
2176
  waitForReady: false,
1447
2177
  });
1448
2178
  const modelInstances = new Map();
1449
2179
  // Get instance state to store model instances
1450
- const { schemaInstanceState } = await Promise.resolve().then(function () { return Schema$1; });
1451
2180
  const instanceState = schemaInstanceState.get(schemaInstance);
1452
2181
  if (!instanceState) {
1453
2182
  throw new Error('Schema instance state not found');
@@ -1462,8 +2191,8 @@ const addModelsMachine = setup({
1462
2191
  if (db) {
1463
2192
  const dbModels = await db
1464
2193
  .select()
1465
- .from(modelsTable)
1466
- .where(eq(modelsTable.name, modelName))
2194
+ .from(models)
2195
+ .where(eq(models.name, modelName))
1467
2196
  .limit(1);
1468
2197
  if (dbModels.length > 0 && dbModels[0].schemaFileId) {
1469
2198
  modelFileId = dbModels[0].schemaFileId;
@@ -1665,9 +2394,6 @@ const addModelsMachine = setup({
1665
2394
  const _persist = async () => {
1666
2395
  const debug = (await import('debug')).default;
1667
2396
  const logger = debug('seedSdk:schema:addModels:persist');
1668
- const { BaseDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aP; });
1669
- const { schemas: schemasTable } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aU; });
1670
- const { eq } = await import('drizzle-orm');
1671
2397
  // Only process in browser environment where store is available
1672
2398
  if (typeof window === 'undefined') {
1673
2399
  logger('Not in browser environment, skipping store update');
@@ -1703,8 +2429,8 @@ const addModelsMachine = setup({
1703
2429
  logger(`Looking up schema by schemaFileId: ${schemaFileId} (attempt ${attempt + 1})`);
1704
2430
  const schemasById = await db
1705
2431
  .select()
1706
- .from(schemasTable)
1707
- .where(eq(schemasTable.schemaFileId, schemaFileId))
2432
+ .from(schemas)
2433
+ .where(eq(schemas.schemaFileId, schemaFileId))
1708
2434
  .limit(1);
1709
2435
  if (schemasById.length > 0) {
1710
2436
  schemaRecord = schemasById[0];
@@ -1720,12 +2446,11 @@ const addModelsMachine = setup({
1720
2446
  // FALLBACK: If not found by schemaFileId, try by name (prefer draft records)
1721
2447
  if (!schemaRecord) {
1722
2448
  logger(`Looking up schema by name: "${schemaName}" (attempt ${attempt + 1})`);
1723
- const { desc } = await import('drizzle-orm');
1724
2449
  const schemasByName = await db
1725
2450
  .select()
1726
- .from(schemasTable)
1727
- .where(eq(schemasTable.name, schemaName))
1728
- .orderBy(desc(schemasTable.isDraft), desc(schemasTable.version))
2451
+ .from(schemas)
2452
+ .where(eq(schemas.name, schemaName))
2453
+ .orderBy(desc(schemas.isDraft), desc(schemas.version))
1729
2454
  .limit(10); // Get multiple to find drafts
1730
2455
  if (schemasByName.length > 0) {
1731
2456
  // Prefer draft records
@@ -2024,7 +2749,9 @@ const createModelInstances$1 = async (modelIds) => {
2024
2749
  return;
2025
2750
  }
2026
2751
  try {
2027
- const mod = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
2752
+ const _mod_8 = await import('./index-Dk73a7JE.js');
2753
+ const _ns_8 = _mod_8.aW;
2754
+ const mod = _ns_8;
2028
2755
  const Model = mod?.Model ?? mod?.default;
2029
2756
  if (!Model) {
2030
2757
  logger$b('Model not available from dynamic import');
@@ -2069,7 +2796,9 @@ const checkExistingSchema = fromCallback(({ sendBack, input: { context } }) => {
2069
2796
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
2070
2797
  // For Seed Protocol, check if it exists in database
2071
2798
  try {
2072
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
2799
+ const _mod_9 = await import('./index-Dk73a7JE.js');
2800
+ const _ns_9 = _mod_9.aV;
2801
+ const internalSchema = _ns_9;
2073
2802
  const schemaFile = internalSchema.default;
2074
2803
  if (db && schemaFile.id) {
2075
2804
  const existing = await db
@@ -2427,7 +3156,9 @@ const writeSchemaToDb = fromCallback(({ sendBack, input }) => {
2427
3156
  if (isInternal && schemaName === SEED_PROTOCOL_SCHEMA_NAME) {
2428
3157
  // For Seed Protocol, load from internal file
2429
3158
  logger$a(`Loading internal Seed Protocol schema from SDK`);
2430
- const internalSchema = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aZ; });
3159
+ const _mod_10 = await import('./index-Dk73a7JE.js');
3160
+ const _ns_10 = _mod_10.aV;
3161
+ const internalSchema = _ns_10;
2431
3162
  finalSchema = internalSchema.default;
2432
3163
  const db = BaseDb.getAppDb();
2433
3164
  if (db && finalSchema.id) {
@@ -2895,7 +3626,10 @@ const createModelInstances = fromCallback(({ sendBack, input }) => {
2895
3626
  return;
2896
3627
  }
2897
3628
  try {
2898
- const { Model } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
3629
+ const _mod_11 = await import('./index-Dk73a7JE.js');
3630
+ const _ns_11 = _mod_11.aW;
3631
+ const modelMod = _ns_11;
3632
+ const { Model } = modelMod;
2899
3633
  // Create instances for all model IDs in parallel
2900
3634
  // Model.createById() will check cache first, then query DB and create if needed
2901
3635
  const createPromises = modelIds.map(async (modelFileId) => {
@@ -2980,7 +3714,10 @@ const verifyModelInstancesInCache = fromCallback(({ sendBack, input }) => {
2980
3714
  }
2981
3715
  try {
2982
3716
  const result = await verifyWithRetry$2(async () => {
2983
- const { Model } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
3717
+ const _mod_12 = await import('./index-Dk73a7JE.js');
3718
+ const _ns_12 = _mod_12.aW;
3719
+ const modelMod = _ns_12;
3720
+ const { Model } = modelMod;
2984
3721
  // Check each model ID in the cache
2985
3722
  const verifiedInstances = [];
2986
3723
  const missingIds = [];
@@ -3036,9 +3773,12 @@ const writePropertiesToDb = fromCallback(({ sendBack, input }) => {
3036
3773
  const _write = async () => {
3037
3774
  const { modelIds } = input;
3038
3775
  try {
3039
- const { BaseDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aP; });
3040
- const { models: modelsTable, properties: propertiesTable } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aQ; });
3041
- const { eq } = await import('drizzle-orm');
3776
+ const _mod_13 = await import('./index-Dk73a7JE.js');
3777
+ const _ns_13 = _mod_13.aR;
3778
+ const modelSchemaMod = _ns_13;
3779
+ const { models: modelsTable, properties: propertiesTable } = modelSchemaMod;
3780
+ const drizzleMod = await import('drizzle-orm');
3781
+ const { eq } = drizzleMod;
3042
3782
  const db = BaseDb.getAppDb();
3043
3783
  if (!db) {
3044
3784
  throw new Error('Database not available');
@@ -3223,9 +3963,11 @@ const createPropertyInstances = fromCallback(({ sendBack, input }) => {
3223
3963
  return;
3224
3964
  }
3225
3965
  try {
3226
- const modProp = await import('./ModelProperty-gjcA83Mq.js').then(function (n) { return n.b; });
3966
+ const modProp = await import('./ModelProperty-Cpd9xiIM.js');
3227
3967
  const ModelProperty = modProp?.ModelProperty ?? modProp?.default;
3228
- const modModel = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aX; });
3968
+ const _mod_14 = await import('./index-Dk73a7JE.js');
3969
+ const _ns_14 = _mod_14.aW;
3970
+ const modModel = _ns_14;
3229
3971
  const Model = modModel?.Model ?? modModel?.default;
3230
3972
  if (!ModelProperty || !Model) {
3231
3973
  logger$2('ModelProperty or Model not available from dynamic import');
@@ -3330,7 +4072,7 @@ const verifyPropertyInstancesInCache = fromCallback(({ sendBack, input }) => {
3330
4072
  }
3331
4073
  try {
3332
4074
  const result = await verifyWithRetry(async () => {
3333
- const mod = await import('./ModelProperty-gjcA83Mq.js').then(function (n) { return n.b; });
4075
+ const mod = await import('./ModelProperty-Cpd9xiIM.js');
3334
4076
  const ModelProperty = mod?.ModelProperty ?? mod?.default;
3335
4077
  if (!ModelProperty) {
3336
4078
  throw new Error('ModelProperty not available from dynamic import');
@@ -4910,7 +5652,6 @@ class Schema {
4910
5652
  throw new ConflictError(errorMessage, conflictCheck);
4911
5653
  }
4912
5654
  const context = this._getSnapshotContext();
4913
- const { addSchemaToDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aW; });
4914
5655
  if (!context._isDraft || !context._editedProperties || context._editedProperties.size === 0) {
4915
5656
  logger('No changes to save');
4916
5657
  return '';
@@ -4957,6 +5698,8 @@ class Schema {
4957
5698
  .limit(1);
4958
5699
  // Collect all edited properties and convert them to SchemaPropertyUpdate format
4959
5700
  const propertyUpdates = [];
5701
+ const modelPropertyMod = await import('./ModelProperty-Cpd9xiIM.js');
5702
+ const { ModelProperty } = modelPropertyMod;
4960
5703
  for (const propertyKey of context._editedProperties) {
4961
5704
  // Skip schema-level changes (like schema name changes)
4962
5705
  if (propertyKey === 'schema:name') {
@@ -4986,7 +5729,6 @@ class Schema {
4986
5729
  // When only new models were added, _editedProperties contains 'schema:models' and we write the full schema
4987
5730
  if (context._editedProperties.has('schema:models')) {
4988
5731
  const newFilePath = await writeFullSchemaNewVersion(this.schemaName, currentSchema);
4989
- const { BaseFileManager } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aR; });
4990
5732
  const fileContent = await BaseFileManager.readFileAsString(newFilePath);
4991
5733
  const publishedSchema = JSON.parse(fileContent);
4992
5734
  if (dbSchema.length > 0) {
@@ -5016,7 +5758,6 @@ class Schema {
5016
5758
  const newFilePath = await updateModelProperties(this.schemaName, propertyUpdates);
5017
5759
  // STEP 3: After file is written, update database to mark as published (isDraft = false)
5018
5760
  // Load the file to get the final schema with IDs
5019
- const { BaseFileManager } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aR; });
5020
5761
  const fileContent = await BaseFileManager.readFileAsString(newFilePath);
5021
5762
  const publishedSchema = JSON.parse(fileContent);
5022
5763
  // Update database record: set isDraft = false and update schemaFileId
@@ -5211,9 +5952,6 @@ class Schema {
5211
5952
  saveDraftLogger(`Client check: cacheIsStale=${cacheIsStale}, shouldRecheck=${shouldRecheck}, cachedValue=${cachedClientInitialized}, timeSinceCheck=${now - clientCheckTime}ms`);
5212
5953
  if (shouldRecheck) {
5213
5954
  try {
5214
- // Use dynamic import for browser compatibility (require() doesn't work in browsers)
5215
- const { getClient } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.a_; });
5216
- const { ClientManagerState } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aT; });
5217
5955
  const client = getClient();
5218
5956
  const clientSnapshot = client.getService().getSnapshot();
5219
5957
  // Check if state is IDLE (primary check) - isInitialized is set in entry action so should be true
@@ -5284,8 +6022,6 @@ class Schema {
5284
6022
  _editedProperties: new Set(),
5285
6023
  };
5286
6024
  }
5287
- const { addSchemaToDb } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aW; });
5288
- const { generateId } = await import('./ClientManager-DoHUt8tU.js').then(function (n) { return n.aS; });
5289
6025
  const db = BaseDb.getAppDb();
5290
6026
  if (!db) {
5291
6027
  throw new Error('Database not found');
@@ -5654,7 +6390,8 @@ class Schema {
5654
6390
  .filter((id) => id != null);
5655
6391
  if (schemaIds.length === 0)
5656
6392
  return;
5657
- const { inArray } = await import('drizzle-orm');
6393
+ const drizzleMod = await import('drizzle-orm');
6394
+ const { inArray } = drizzleMod;
5658
6395
  const joinRows = await db
5659
6396
  .select({ modelId: modelSchemas.modelId })
5660
6397
  .from(modelSchemas)
@@ -5852,5 +6589,5 @@ var Schema$1 = /*#__PURE__*/Object.freeze({
5852
6589
  schemaInstanceState: schemaInstanceState
5853
6590
  });
5854
6591
 
5855
- export { Schema, schemaInstanceState };
5856
- //# sourceMappingURL=Schema-ClTcpgbt.js.map
6592
+ export { Schema as S, deleteModelFromSchema as a, Schema$1 as b, convertPropertyToSchemaUpdate as c, deletePropertyFromModel as d, renameModelProperty as r, updateModelProperties as u };
6593
+ //# sourceMappingURL=Schema-BZKBy5Tx.js.map