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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/{db-D9K_f5cF.js → BasePathResolver-Cm4apKRb.js} +2041 -127
  2. package/dist/BasePathResolver-Cm4apKRb.js.map +1 -0
  3. package/dist/{ClientManager-C-QXqUK9.js → ClientManager-i3nJASkg.js} +249 -147
  4. package/dist/ClientManager-i3nJASkg.js.map +1 -0
  5. package/dist/{Item-C7sUUu2B.js → Item-DBFchXpC.js} +259 -169
  6. package/dist/Item-DBFchXpC.js.map +1 -0
  7. package/dist/{ModelProperty-DJxeOOrc.js → ModelProperty-BS49g01Y.js} +166 -47
  8. package/dist/ModelProperty-BS49g01Y.js.map +1 -0
  9. package/dist/{Schema-fXtvd-yL.js → Schema-CpMNEnUO.js} +53 -42
  10. package/dist/Schema-CpMNEnUO.js.map +1 -0
  11. package/dist/{SchemaValidationService-CvRS2HSO.js → SchemaValidationService-DieV4KL-.js} +15 -17
  12. package/dist/{SchemaValidationService-CvRS2HSO.js.map → SchemaValidationService-DieV4KL-.js.map} +1 -1
  13. package/dist/{backfillMetadataPropertyIds-SXW-8C64.js → backfillMetadataPropertyIds-DSoOoTnX.js} +14 -7
  14. package/dist/{backfillMetadataPropertyIds-SXW-8C64.js.map → backfillMetadataPropertyIds-DSoOoTnX.js.map} +1 -1
  15. package/dist/{configurePlatform-BRw2j0ZN.js → configurePlatform-D0lQGAMQ.js} +5 -7
  16. package/dist/{configurePlatform-BRw2j0ZN.js.map → configurePlatform-D0lQGAMQ.js.map} +1 -1
  17. package/dist/detachRowsBeforeDelete-S0q-DJPT.js +50 -0
  18. package/dist/detachRowsBeforeDelete-S0q-DJPT.js.map +1 -0
  19. package/dist/{eas-DHxfswCt.js → eas-6pjU-OuX.js} +6 -8
  20. package/dist/eas-6pjU-OuX.js.map +1 -0
  21. package/dist/{getItem-d6N_aM6S.js → getItem-CxBNZ-WL.js} +10 -11
  22. package/dist/{getItem-d6N_aM6S.js.map → getItem-CxBNZ-WL.js.map} +1 -1
  23. package/dist/{getPublishPayload-BHrxVtzY.js → getPublishPayload-CTCvRUoU.js} +50 -18
  24. package/dist/getPublishPayload-CTCvRUoU.js.map +1 -0
  25. package/dist/{getPublishUploads-BEqRiKIS.js → getPublishUploads-SFHCbf_y.js} +13 -22
  26. package/dist/{getPublishUploads-BEqRiKIS.js.map → getPublishUploads-SFHCbf_y.js.map} +1 -1
  27. package/dist/{index-s15q14rm.js → index-8O3Uow-Y.js} +125 -57
  28. package/dist/index-8O3Uow-Y.js.map +1 -0
  29. package/dist/{index-DglvthOk.js → index-AVFTVp1m.js} +2 -2
  30. package/dist/index-AVFTVp1m.js.map +1 -0
  31. package/dist/index-Cvt5UBz4.js +30 -0
  32. package/dist/index-Cvt5UBz4.js.map +1 -0
  33. package/dist/{index.browser-Cm06tP4X.js → index.browser-DBhxRoe8.js} +11 -10
  34. package/dist/{index.browser-Cm06tP4X.js.map → index.browser-DBhxRoe8.js.map} +1 -1
  35. package/dist/{index.node-C30dmFgn.js → index.node-CJhlcNHM.js} +25 -13
  36. package/dist/index.node-CJhlcNHM.js.map +1 -0
  37. package/dist/main.js +27 -32
  38. package/dist/main.js.map +1 -1
  39. package/dist/node.js +19 -22
  40. package/dist/node.js.map +1 -1
  41. package/dist/platform.browser.js +9 -9
  42. package/dist/platform.node.js +18 -5
  43. package/dist/platform.node.js.map +1 -1
  44. package/dist/{property-DhmmYAvQ.js → property-DwPD283A.js} +11 -12
  45. package/dist/property-DwPD283A.js.map +1 -0
  46. package/dist/{publishDraftGraph-yYP74WRt.js → publishDraftGraph-BOn3_Occ.js} +6 -9
  47. package/dist/{publishDraftGraph-yYP74WRt.js.map → publishDraftGraph-BOn3_Occ.js.map} +1 -1
  48. package/dist/{resetAmbiguousLegacyItemData-Bk0QyDW8.js → resetAmbiguousLegacyItemData-BkYmBeJc.js} +14 -3
  49. package/dist/{resetAmbiguousLegacyItemData-Bk0QyDW8.js.map → resetAmbiguousLegacyItemData-BkYmBeJc.js.map} +1 -1
  50. package/dist/{resolveModelForSyncedSeed-8cAzvUFd.js → resolveModelForSyncedSeed-BL24nLa7.js} +2 -2
  51. package/dist/{resolveModelForSyncedSeed-8cAzvUFd.js.map → resolveModelForSyncedSeed-BL24nLa7.js.map} +1 -1
  52. package/dist/src/Item/Item.d.ts +20 -2
  53. package/dist/src/Item/Item.d.ts.map +1 -1
  54. package/dist/src/Item/service/actors/runPublish.d.ts +11 -2
  55. package/dist/src/Item/service/actors/runPublish.d.ts.map +1 -1
  56. package/dist/src/Item/service/itemMachineSingle.d.ts +12 -2
  57. package/dist/src/Item/service/itemMachineSingle.d.ts.map +1 -1
  58. package/dist/src/ItemProperty/ItemProperty.d.ts +5 -3
  59. package/dist/src/ItemProperty/ItemProperty.d.ts.map +1 -1
  60. package/dist/src/ItemProperty/service/actors/saveValueToDb/analyzeInput.d.ts.map +1 -1
  61. package/dist/src/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  62. package/dist/src/Model/Model.d.ts +10 -4
  63. package/dist/src/Model/Model.d.ts.map +1 -1
  64. package/dist/src/Model/index.d.ts +2 -2
  65. package/dist/src/ModelProperty/ModelProperty.d.ts +10 -2
  66. package/dist/src/ModelProperty/ModelProperty.d.ts.map +1 -1
  67. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts +3 -0
  68. package/dist/src/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  69. package/dist/src/Schema/Schema.d.ts +2 -2
  70. package/dist/src/Schema/Schema.d.ts.map +1 -1
  71. package/dist/src/Schema/index.d.ts +0 -1
  72. package/dist/src/Schema/index.d.ts.map +1 -1
  73. package/dist/src/client/ClientManager.d.ts +30 -11
  74. package/dist/src/client/ClientManager.d.ts.map +1 -1
  75. package/dist/src/client/actors/platformClassesInit.d.ts +6 -0
  76. package/dist/src/client/actors/platformClassesInit.d.ts.map +1 -1
  77. package/dist/src/client/actors/processSchemaFiles.d.ts.map +1 -1
  78. package/dist/src/client/actors/saveConfig.d.ts +13 -6
  79. package/dist/src/client/actors/saveConfig.d.ts.map +1 -1
  80. package/dist/src/db/read/getPublishPayload.d.ts +1 -1
  81. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  82. package/dist/src/db/write/claimUnpublishedDrafts.d.ts +2 -0
  83. package/dist/src/db/write/claimUnpublishedDrafts.d.ts.map +1 -1
  84. package/dist/src/eventBus.d.ts +5 -0
  85. package/dist/src/eventBus.d.ts.map +1 -1
  86. package/dist/src/helpers/cachedPropertyRefresh.d.ts +12 -0
  87. package/dist/src/helpers/cachedPropertyRefresh.d.ts.map +1 -0
  88. package/dist/src/helpers/db.d.ts +3 -0
  89. package/dist/src/helpers/db.d.ts.map +1 -1
  90. package/dist/src/helpers/easSdk.d.ts +16 -0
  91. package/dist/src/helpers/easSdk.d.ts.map +1 -0
  92. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts +16 -0
  93. package/dist/src/helpers/entity/detachRowsBeforeDelete.d.ts.map +1 -0
  94. package/dist/src/helpers/entity/entityDestroy.d.ts +2 -0
  95. package/dist/src/helpers/entity/entityDestroy.d.ts.map +1 -1
  96. package/dist/src/helpers/ownership.d.ts +9 -1
  97. package/dist/src/helpers/ownership.d.ts.map +1 -1
  98. package/dist/src/helpers/property/index.d.ts +37 -51
  99. package/dist/src/helpers/property/index.d.ts.map +1 -1
  100. package/dist/src/helpers/publishConfig.d.ts +27 -8
  101. package/dist/src/helpers/publishConfig.d.ts.map +1 -1
  102. package/dist/src/helpers/updateSchema.d.ts +5 -0
  103. package/dist/src/helpers/updateSchema.d.ts.map +1 -1
  104. package/dist/src/helpers/waitForEntityIdle.d.ts +5 -0
  105. package/dist/src/helpers/waitForEntityIdle.d.ts.map +1 -1
  106. package/dist/src/imports/json.d.ts +9 -0
  107. package/dist/src/imports/json.d.ts.map +1 -1
  108. package/dist/src/index.d.ts +6 -4
  109. package/dist/src/index.d.ts.map +1 -1
  110. package/dist/src/interfaces/IItem.d.ts +7 -1
  111. package/dist/src/interfaces/IItem.d.ts.map +1 -1
  112. package/dist/src/node/db/Db.d.ts.map +1 -1
  113. package/dist/src/node/helpers/PathResolver.d.ts.map +1 -1
  114. package/dist/src/node/index.d.ts +8 -1
  115. package/dist/src/node/index.d.ts.map +1 -1
  116. package/dist/src/platform/index.browser.d.ts +2 -0
  117. package/dist/src/platform/index.browser.d.ts.map +1 -1
  118. package/dist/src/platform/index.node.d.ts +2 -0
  119. package/dist/src/platform/index.node.d.ts.map +1 -1
  120. package/dist/src/types/index.d.ts +12 -1
  121. package/dist/src/types/index.d.ts.map +1 -1
  122. package/dist/src/types/machines.d.ts +2 -0
  123. package/dist/src/types/machines.d.ts.map +1 -1
  124. package/dist/src/types/property.d.ts +8 -0
  125. package/dist/src/types/property.d.ts.map +1 -1
  126. package/dist/{syncDbWithEas--HUA9WNb.js → syncDbWithEas-Bv2Fe38J.js} +15 -16
  127. package/dist/syncDbWithEas-Bv2Fe38J.js.map +1 -0
  128. package/dist/tabEvents-9s2WCYw-.js +335 -0
  129. package/dist/tabEvents-9s2WCYw-.js.map +1 -0
  130. package/dist/{tolerantWebAccess-BZYWt09Y.js → tolerantWebAccess-iUu80pAP.js} +9 -9
  131. package/dist/{tolerantWebAccess-BZYWt09Y.js.map → tolerantWebAccess-iUu80pAP.js.map} +1 -1
  132. package/dist/{updateSeedRevokedAt-D_EG-q3b.js → updateSeedRevokedAt-zBfi931j.js} +3 -3
  133. package/dist/{updateSeedRevokedAt-D_EG-q3b.js.map → updateSeedRevokedAt-zBfi931j.js.map} +1 -1
  134. package/package.json +11 -12
  135. package/src/node/easLodashRegister.js +4 -0
  136. package/dist/BasePathResolver-CfSfMW5_.js +0 -676
  137. package/dist/BasePathResolver-CfSfMW5_.js.map +0 -1
  138. package/dist/ClientManager-C-QXqUK9.js.map +0 -1
  139. package/dist/Item-C7sUUu2B.js.map +0 -1
  140. package/dist/ModelProperty-DJxeOOrc.js.map +0 -1
  141. package/dist/Schema-fXtvd-yL.js.map +0 -1
  142. package/dist/cjs/ModelProperty-DXZ39Wyv.js +0 -1978
  143. package/dist/cjs/ModelProperty-DXZ39Wyv.js.map +0 -1
  144. package/dist/cjs/Schema-DdP109QD.js +0 -5257
  145. package/dist/cjs/Schema-DdP109QD.js.map +0 -1
  146. package/dist/cjs/SchemaValidationService-CSXxx7sQ.js +0 -779
  147. package/dist/cjs/SchemaValidationService-CSXxx7sQ.js.map +0 -1
  148. package/dist/cjs/backfillMetadataPropertyIds-CPYoaMl4.js +0 -90
  149. package/dist/cjs/backfillMetadataPropertyIds-CPYoaMl4.js.map +0 -1
  150. package/dist/cjs/eas-B2YDQssV.js +0 -139
  151. package/dist/cjs/eas-B2YDQssV.js.map +0 -1
  152. package/dist/cjs/getItem-DgnaQzbE.js +0 -59
  153. package/dist/cjs/getItem-DgnaQzbE.js.map +0 -1
  154. package/dist/cjs/getPublishPayload-CqlqRdot.js +0 -1604
  155. package/dist/cjs/getPublishPayload-CqlqRdot.js.map +0 -1
  156. package/dist/cjs/getPublishUploads-DsXY9S4U.js +0 -872
  157. package/dist/cjs/getPublishUploads-DsXY9S4U.js.map +0 -1
  158. package/dist/cjs/index-BHaWOwNF.js +0 -71
  159. package/dist/cjs/index-BHaWOwNF.js.map +0 -1
  160. package/dist/cjs/index-C4XlgCJ4.js +0 -22801
  161. package/dist/cjs/index-C4XlgCJ4.js.map +0 -1
  162. package/dist/cjs/index.browser-BSf8HpnU.js +0 -22
  163. package/dist/cjs/index.browser-BSf8HpnU.js.map +0 -1
  164. package/dist/cjs/property-fa0iju0J.js +0 -328
  165. package/dist/cjs/property-fa0iju0J.js.map +0 -1
  166. package/dist/cjs/publishDraftGraph-3ASwAlD7.js +0 -403
  167. package/dist/cjs/publishDraftGraph-3ASwAlD7.js.map +0 -1
  168. package/dist/cjs/resetAmbiguousLegacyItemData-Bu_MBBYt.js +0 -117
  169. package/dist/cjs/resetAmbiguousLegacyItemData-Bu_MBBYt.js.map +0 -1
  170. package/dist/cjs/resolveModelForSyncedSeed-BANIiuFU.js +0 -49
  171. package/dist/cjs/resolveModelForSyncedSeed-BANIiuFU.js.map +0 -1
  172. package/dist/cjs/syncDbWithEas-CrmxxmUW.js +0 -887
  173. package/dist/cjs/syncDbWithEas-CrmxxmUW.js.map +0 -1
  174. package/dist/db-D9K_f5cF.js.map +0 -1
  175. package/dist/eas-DHxfswCt.js.map +0 -1
  176. package/dist/getPublishPayload-BHrxVtzY.js.map +0 -1
  177. package/dist/index-CiMEoGu3.js +0 -32
  178. package/dist/index-CiMEoGu3.js.map +0 -1
  179. package/dist/index-DglvthOk.js.map +0 -1
  180. package/dist/index-s15q14rm.js.map +0 -1
  181. package/dist/index.node-C30dmFgn.js.map +0 -1
  182. package/dist/main.cjs +0 -85
  183. package/dist/main.cjs.map +0 -1
  184. package/dist/property-DhmmYAvQ.js.map +0 -1
  185. package/dist/syncDbWithEas--HUA9WNb.js.map +0 -1
  186. package/dist/tabEvents-DguZpCCv.js +0 -1580
  187. package/dist/tabEvents-DguZpCCv.js.map +0 -1
@@ -1,1978 +0,0 @@
1
- 'use strict';
2
-
3
- var xstate = require('xstate');
4
- require('reflect-metadata');
5
- var main_cjs = require('./index-C4XlgCJ4.js');
6
- require('pluralize');
7
- var drizzleOrm = require('drizzle-orm');
8
- var debug = require('debug');
9
- var Schema = require('./Schema-DdP109QD.js');
10
- require('immer');
11
- require('drizzle-orm/sqlite-core');
12
- require('@seedprotocol/arweave');
13
- require('@seedprotocol/eas');
14
- require('@sinclair/typebox');
15
- require('drizzle-orm/casing');
16
- require('lodash-es');
17
- require('@noble/hashes/sha256');
18
- require('@noble/hashes/sha3');
19
- require('@noble/hashes/utils');
20
- require('nanoid');
21
- require('nanoid-dictionary');
22
- require('@seedprotocol/query');
23
- require('rxjs');
24
- require('fs/promises');
25
- require('fs');
26
- require('path');
27
- require('url');
28
- require('node:url');
29
- require('@libsql/client');
30
- require('drizzle-orm/libsql');
31
- require('drizzle-orm/libsql/migrator');
32
- require('js-yaml');
33
- require('child_process');
34
- require('@seedprotocol/arweave/node');
35
- require('@seedprotocol/eas/node');
36
- require('./SchemaValidationService-CSXxx7sQ.js');
37
- require('@sinclair/typebox/value');
38
-
39
- const logger$3 = debug('seedSdk:modelProperty:actors:saveToSchema');
40
- /**
41
- * Get schema name from model
42
- * This function finds which schema contains the given model
43
- * Exported so it can be reused by ModelProperty for setting schema name
44
- */
45
- async function getSchemaNameFromModel(modelName) {
46
- // Get the latest schema files and find which one contains this model
47
- const schemaHelpersMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.schema$1; });
48
- const { listLatestSchemaFiles } = schemaHelpersMod;
49
- const latestSchemas = await listLatestSchemaFiles();
50
- for (const schema of latestSchemas) {
51
- try {
52
- const fileManagerMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.BaseFileManager$1; });
53
- const { BaseFileManager } = fileManagerMod;
54
- const content = await BaseFileManager.readFileAsString(schema.filePath);
55
- const schemaFile = JSON.parse(content);
56
- if (schemaFile.models && schemaFile.models[modelName]) {
57
- return schema.name;
58
- }
59
- }
60
- catch (error) {
61
- logger$3('Error reading schema file:', error);
62
- continue;
63
- }
64
- }
65
- return undefined;
66
- }
67
- const saveToSchema = xstate.fromCallback(({ sendBack, input: { context }, self }) => {
68
- const _saveToSchema = async () => {
69
- // Use dynamic import to break circular dependency
70
- const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-CSXxx7sQ.js'); });
71
- const { SchemaValidationService } = validationServiceMod;
72
- const validationService = new SchemaValidationService();
73
- // Validate property structure before saving
74
- const validationResult = validationService.validatePropertyStructure(context);
75
- if (!validationResult.isValid) {
76
- throw new Error(`Property validation failed: ${validationResult.errors.map(e => e.message).join(', ')}`);
77
- }
78
- // Validate required fields
79
- if (!context.name) {
80
- throw new Error('Property name is required');
81
- }
82
- if (!context.dataType) {
83
- throw new Error('Data type is required');
84
- }
85
- if (!context.modelName) {
86
- throw new Error(`Model not found for modelId: ${context.modelId}`);
87
- }
88
- // Persist to database only - schema file is updated only when user calls Schema.saveNewVersion()
89
- const dbMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.db; });
90
- const { savePropertyToDb } = dbMod;
91
- await savePropertyToDb(context);
92
- // Mark schema as draft so user knows to save
93
- const schemaName = context._schemaName ?? (await getSchemaNameFromModel(context.modelName));
94
- if (schemaName) {
95
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DdP109QD.js'); });
96
- const { Schema } = schemaMod;
97
- // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
98
- if (main_cjs.isActorStopped(self))
99
- return;
100
- const schema = Schema.create(schemaName, { waitForReady: false });
101
- schema.getService().send({
102
- type: 'markAsDraft',
103
- propertyKey: `${context.modelName}:${context.name}`,
104
- });
105
- }
106
- logger$3(`Successfully saved property ${context.modelName}:${context.name} to database`);
107
- };
108
- _saveToSchema().then(() => {
109
- sendBack({ type: 'saveToSchemaSuccess' });
110
- }).catch((error) => {
111
- logger$3('Error saving to schema:', error);
112
- sendBack({ type: 'saveToSchemaError', error });
113
- });
114
- return () => {
115
- // Cleanup function (optional)
116
- };
117
- });
118
-
119
- const logger$2 = debug('seedSdk:modelProperty:actors:compareAndMarkDraft');
120
- const compareAndMarkDraft = xstate.fromCallback(({ sendBack, input: { context }, self }) => {
121
- const _compareAndMarkDraft = async () => {
122
- // Fill modelName/dataType from _originalValues when missing, then from DB by schemaFileId
123
- let fullContext = {
124
- ...context,
125
- modelName: context.modelName ?? context._originalValues?.modelName,
126
- dataType: context.dataType ?? context._originalValues?.dataType,
127
- };
128
- const schemaFileIdForResolve = fullContext._propertyFileId || (typeof fullContext.id === 'string' ? fullContext.id : undefined);
129
- if (schemaFileIdForResolve && (fullContext.modelName === undefined || fullContext.dataType === undefined)) {
130
- try {
131
- const dbMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.db; });
132
- const { getPropertyModelNameAndDataType, getModelNameByModelId } = dbMod;
133
- let fromDb;
134
- for (let attempt = 0; attempt < 6; attempt++) {
135
- fromDb = await getPropertyModelNameAndDataType(schemaFileIdForResolve);
136
- if (fromDb)
137
- break;
138
- if (attempt < 5)
139
- await new Promise((r) => setTimeout(r, 40));
140
- }
141
- if (fromDb) {
142
- fullContext = {
143
- ...fullContext,
144
- modelName: fullContext.modelName ?? fromDb.modelName,
145
- dataType: fullContext.dataType ?? fromDb.dataType,
146
- };
147
- }
148
- if (fullContext.modelName === undefined && schemaFileIdForResolve) {
149
- const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
150
- const ModelProperty = mod?.ModelProperty ?? mod?.default;
151
- const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileIdForResolve);
152
- if (pendingModelId != null) {
153
- const modelName = await getModelNameByModelId(pendingModelId);
154
- if (modelName) {
155
- fullContext = { ...fullContext, modelName };
156
- }
157
- }
158
- }
159
- }
160
- catch {
161
- // ignore
162
- }
163
- }
164
- const schemaFileId = fullContext._propertyFileId || (typeof fullContext.id === 'string' ? fullContext.id : undefined);
165
- // If _originalValues is not set, we still need to save to database if the property exists
166
- // This handles the case where the name is changed before _originalValues is initialized
167
- if (!fullContext._originalValues) {
168
- logger$2('No original values to compare against');
169
- logger$2(`[compareAndMarkDraft] Context: modelName=${fullContext.modelName}, name=${fullContext.name}, id=${fullContext.id}, _propertyFileId=${fullContext._propertyFileId}`);
170
- // If we have a name and modelName, try to save to database anyway
171
- // This ensures name changes are persisted even if _originalValues isn't initialized yet
172
- // We need either schemaFileId (id or _propertyFileId) to find the property in the database
173
- if (fullContext.modelName && fullContext.name && schemaFileId) {
174
- logger$2(`[compareAndMarkDraft] _originalValues not set, but saving to database anyway for property ${context.modelName}:${context.name} (schemaFileId: ${schemaFileId})`);
175
- try {
176
- const dbMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.db; });
177
- const { savePropertyToDb } = dbMod;
178
- // Ensure _propertyFileId is set for savePropertyToDb to find the property
179
- const contextWithFileId = {
180
- ...fullContext,
181
- _propertyFileId: schemaFileId,
182
- };
183
- await savePropertyToDb(contextWithFileId);
184
- logger$2(`[compareAndMarkDraft] Successfully saved property ${fullContext.modelName}:${fullContext.name} to database (no _originalValues)`);
185
- }
186
- catch (error) {
187
- logger$2(`[compareAndMarkDraft] Error saving property to database (no _originalValues): ${error}`);
188
- // Don't throw - this is a best-effort save, but log the error for debugging
189
- console.error(`[compareAndMarkDraft] Failed to save property ${fullContext.modelName}:${fullContext.name}:`, error);
190
- }
191
- }
192
- else {
193
- logger$2(`[compareAndMarkDraft] Cannot save property ${fullContext.modelName}:${fullContext.name} - missing required fields (schemaFileId: ${schemaFileId})`);
194
- }
195
- return;
196
- }
197
- logger$2(`[compareAndMarkDraft] Comparing: context.name=${fullContext.name}, _originalValues.name=${fullContext._originalValues?.name}`);
198
- // Compare current values with original
199
- // Only compare property fields, not internal fields
200
- const propertyFields = ['name', 'dataType', 'ref', 'refModelName', 'refModelId', 'refValueType', 'storageType', 'localStorageDir', 'filenameSuffix', 'modelName', 'modelId', 'required'];
201
- const hasChanges = propertyFields.some(key => {
202
- const currentValue = fullContext[key];
203
- const originalValue = fullContext._originalValues?.[key];
204
- // Handle name changes specifically
205
- if (key === 'name') {
206
- const nameChanged = currentValue !== originalValue;
207
- if (nameChanged) {
208
- logger$2(`[compareAndMarkDraft] Name change detected: "${originalValue}" -> "${currentValue}"`);
209
- }
210
- return nameChanged;
211
- }
212
- // Handle ref fields - compare by name
213
- if (key === 'ref' || key === 'refModelName') {
214
- const currentRef = fullContext.refModelName || fullContext.ref;
215
- const originalRef = fullContext._originalValues?.refModelName || fullContext._originalValues?.ref;
216
- // Both undefined/null means no ref, so they're the same
217
- if (!currentRef && !originalRef)
218
- return false;
219
- return currentRef !== originalRef;
220
- }
221
- // For other fields, compare values (handling undefined/null)
222
- if (currentValue === undefined && originalValue === undefined)
223
- return false;
224
- if (currentValue === null && originalValue === null)
225
- return false;
226
- if (currentValue === undefined && originalValue === null)
227
- return false;
228
- if (currentValue === null && originalValue === undefined)
229
- return false;
230
- return currentValue !== originalValue;
231
- });
232
- if (hasChanges) {
233
- logger$2(`Property ${fullContext.modelName}:${fullContext.name} has changes, marking as edited`);
234
- logger$2(`[compareAndMarkDraft] Context when saving: id=${fullContext.id}, _propertyFileId=${fullContext._propertyFileId}, name=${fullContext.name}, _originalValues.name=${fullContext._originalValues?.name}`);
235
- // Use dynamic import to break circular dependency
236
- const dbMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.db; });
237
- const { savePropertyToDb } = dbMod;
238
- // Save to database (but not JSON file) - always save to DB when there are changes
239
- try {
240
- await savePropertyToDb(fullContext);
241
- logger$2(`[compareAndMarkDraft] Successfully saved property ${fullContext.modelName}:${fullContext.name} to database`);
242
- }
243
- catch (error) {
244
- logger$2(`[compareAndMarkDraft] Error saving property to database: ${error}`);
245
- throw error;
246
- }
247
- // Mark schema as draft if schema name is available
248
- if (fullContext._schemaName) {
249
- // Get the Schema instance and mark it as draft
250
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DdP109QD.js'); });
251
- const { Schema } = schemaMod;
252
- // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
253
- if (main_cjs.isActorStopped(self))
254
- return;
255
- const schema = Schema.create(fullContext._schemaName, {
256
- waitForReady: false,
257
- });
258
- // Send event to Schema machine to mark as draft
259
- schema.getService().send({
260
- type: 'markAsDraft',
261
- propertyKey: `${fullContext.modelName}:${fullContext.name}`,
262
- });
263
- }
264
- }
265
- else {
266
- // No changes - clear edited flag in database and context
267
- logger$2(`Property ${fullContext.modelName}:${fullContext.name} has no changes`);
268
- // Clear isEdited flag in database
269
- try {
270
- const seedSchemaMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.schema; });
271
- const { properties: propertiesTable, models: modelsTable } = seedSchemaMod;
272
- const drizzleMod = await import('drizzle-orm');
273
- const { eq, and } = drizzleMod;
274
- const db = main_cjs.BaseDb.getAppDb();
275
- if (db && fullContext.modelName && fullContext.name) {
276
- // Find this property's model (model names are only unique per schema)
277
- const { resolveModelRecord } = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.resolveModelRecord$1; });
278
- const modelRecord = await resolveModelRecord(fullContext.modelName, {
279
- modelId: typeof fullContext.modelId === 'number' ? fullContext.modelId : undefined,
280
- schemaName: fullContext._schemaName,
281
- }, db);
282
- const modelRecords = modelRecord ? [modelRecord] : [];
283
- if (modelRecords.length > 0) {
284
- // Find property by name and modelId
285
- const propertyRecords = await db
286
- .select({ id: propertiesTable.id })
287
- .from(propertiesTable)
288
- .where(and(eq(propertiesTable.name, fullContext.name), eq(propertiesTable.modelId, modelRecords[0].id)))
289
- .limit(1);
290
- if (propertyRecords.length > 0) {
291
- // Clear isEdited flag in database
292
- await db
293
- .update(propertiesTable)
294
- .set({ isEdited: false })
295
- .where(eq(propertiesTable.id, propertyRecords[0].id));
296
- logger$2(`Cleared isEdited flag in database for property ${fullContext.modelName}:${fullContext.name}`);
297
- }
298
- }
299
- }
300
- }
301
- catch (error) {
302
- logger$2(`Error clearing isEdited flag in database: ${error}`);
303
- }
304
- sendBack({
305
- type: 'clearEdited',
306
- });
307
- }
308
- };
309
- _compareAndMarkDraft().then(() => {
310
- sendBack({ type: 'compareAndMarkDraftSuccess' });
311
- }).catch((error) => {
312
- logger$2('Error comparing and marking draft:', error);
313
- sendBack({ type: 'compareAndMarkDraftError', error });
314
- });
315
- return () => {
316
- // Cleanup function (optional)
317
- };
318
- });
319
-
320
- const logger$1 = debug('seedSdk:modelProperty:actors:validateProperty');
321
- const validateProperty = xstate.fromCallback(({ sendBack, input: { context }, self }) => {
322
- const _validateProperty = async () => {
323
- // Use full context for validation: fill modelName/dataType from _originalValues when missing, then
324
- // from DB by schemaFileId (context.id) so just-created renames don't fail structure validation.
325
- let fullContext = {
326
- ...context,
327
- modelName: context.modelName ?? context._originalValues?.modelName,
328
- dataType: context.dataType ?? context._originalValues?.dataType,
329
- };
330
- const schemaFileId = typeof context.id === 'string' ? context.id : undefined;
331
- if (schemaFileId && (fullContext.modelName === undefined || fullContext.dataType === undefined)) {
332
- // Brief wait so trackPendingWrite from ModelProperty.create() has time to run (it's in setTimeout(0))
333
- await new Promise((r) => setTimeout(r, 60));
334
- try {
335
- const dbMod = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.db; });
336
- const { getPropertyModelNameAndDataType, getModelNameByModelId } = dbMod;
337
- // Try pending write first (property row may not exist yet)
338
- if (fullContext.modelName === undefined && schemaFileId) {
339
- const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
340
- const ModelProperty = mod?.ModelProperty ?? mod?.default;
341
- const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileId);
342
- if (pendingModelId != null) {
343
- const modelName = await getModelNameByModelId(pendingModelId);
344
- if (modelName) {
345
- fullContext = { ...fullContext, modelName };
346
- }
347
- }
348
- }
349
- // Then DB property lookup with retry (catches row after initial write)
350
- let fromDb;
351
- for (let attempt = 0; attempt < 6; attempt++) {
352
- fromDb = await getPropertyModelNameAndDataType(schemaFileId);
353
- if (fromDb)
354
- break;
355
- if (attempt < 5)
356
- await new Promise((r) => setTimeout(r, 40));
357
- }
358
- if (fromDb) {
359
- fullContext = {
360
- ...fullContext,
361
- modelName: fullContext.modelName ?? fromDb.modelName,
362
- dataType: fullContext.dataType ?? fromDb.dataType,
363
- };
364
- }
365
- // If still no modelName, try pending write again (may have been set during retries)
366
- if (fullContext.modelName === undefined && schemaFileId) {
367
- const mod = await Promise.resolve().then(function () { return ModelProperty$1; });
368
- const ModelProperty = mod?.ModelProperty ?? mod?.default;
369
- const pendingModelId = ModelProperty?.getPendingModelId?.(schemaFileId);
370
- if (pendingModelId != null) {
371
- const modelName = await getModelNameByModelId(pendingModelId);
372
- if (modelName) {
373
- fullContext = { ...fullContext, modelName };
374
- }
375
- }
376
- }
377
- }
378
- catch {
379
- // ignore
380
- }
381
- }
382
- // Last resort for structure validation: TProperty requires dataType; allow name+id to pass if we have schemaFileId
383
- if (fullContext.dataType === undefined && (fullContext.modelName !== undefined || schemaFileId)) {
384
- fullContext = { ...fullContext, dataType: (fullContext.dataType ?? context._originalValues?.dataType) || 'Text' };
385
- }
386
- // Use dynamic imports to break circular dependencies
387
- const validationServiceMod = await Promise.resolve().then(function () { return require('./SchemaValidationService-CSXxx7sQ.js'); });
388
- const { SchemaValidationService } = validationServiceMod;
389
- const validationService = new SchemaValidationService();
390
- const schemaMod = await Promise.resolve().then(function () { return require('./Schema-DdP109QD.js'); });
391
- const { Schema } = schemaMod;
392
- // Validate property structure
393
- const structureResult = validationService.validatePropertyStructure(fullContext);
394
- if (!structureResult.isValid) {
395
- sendBack({ type: 'validationError', errors: structureResult.errors });
396
- return;
397
- }
398
- // If we have schema name and model name, validate against schema
399
- // Stopped meanwhile (unloaded, or evicted with its schema): don't load the schema again
400
- if (main_cjs.isActorStopped(self))
401
- return;
402
- if (fullContext._schemaName && fullContext.modelName) {
403
- try {
404
- const schema = Schema.create(fullContext._schemaName, {
405
- waitForReady: false,
406
- });
407
- const schemaSnapshot = schema.getService().getSnapshot();
408
- const schemaStatus = schemaSnapshot.value;
409
- // Only validate against schema if it's loaded (in idle state)
410
- // If still loading, skip schema validation and only do structure validation
411
- if (schemaStatus === 'idle') {
412
- const schemaContext = schemaSnapshot.context;
413
- // Check if models are actually loaded
414
- if (schemaContext.models && Object.keys(schemaContext.models).length > 0) {
415
- // If property name has changed, validate against the original name (from schema file)
416
- // This handles the case where a property is renamed - the schema file still has the old name
417
- const propertyNameToValidate = fullContext._originalValues?.name && fullContext._originalValues.name !== fullContext.name
418
- ? fullContext._originalValues.name
419
- : fullContext.name || '';
420
- const schemaResult = validationService.validateProperty(schemaContext, fullContext.modelName, propertyNameToValidate, fullContext);
421
- if (!schemaResult.isValid) {
422
- // If property was renamed, some validation errors are expected (like property_not_found, missing_type)
423
- // Only fail if it's a critical error that's not related to the rename
424
- const isRenamed = fullContext._originalValues?.name && fullContext._originalValues.name !== fullContext.name;
425
- const criticalErrors = schemaResult.errors.filter(err => {
426
- // Allow property_not_found and missing_type errors when property is renamed
427
- if (isRenamed && (err.code === 'property_not_found' || err.code === 'missing_type')) {
428
- return false; // Not critical
429
- }
430
- // For non-renamed properties, only allow property_not_found if we're validating with the same name
431
- if (err.code === 'property_not_found' && propertyNameToValidate === fullContext.name) {
432
- return false; // Not critical
433
- }
434
- return true; // Critical error
435
- });
436
- if (criticalErrors.length > 0) {
437
- sendBack({ type: 'validationError', errors: criticalErrors });
438
- return;
439
- }
440
- // Continue with validation - rename-related errors are acceptable
441
- }
442
- }
443
- else {
444
- logger$1('Schema models not loaded yet, skipping schema validation');
445
- // Continue with structure validation only
446
- }
447
- }
448
- else {
449
- logger$1(`Schema is in ${schemaStatus} state, skipping schema validation`);
450
- // Continue with structure validation only
451
- }
452
- }
453
- catch (error) {
454
- logger$1('Error validating property against schema:', error);
455
- // Continue with structure validation only
456
- }
457
- }
458
- // All validations passed
459
- sendBack({ type: 'validationSuccess', errors: [] });
460
- };
461
- _validateProperty().catch((error) => {
462
- logger$1('Error in validateProperty:', error);
463
- sendBack({
464
- type: 'validationError',
465
- errors: [{
466
- field: 'property',
467
- message: error instanceof Error ? error.message : 'Unknown validation error',
468
- code: 'validation_exception',
469
- severity: 'error',
470
- }],
471
- });
472
- });
473
- return () => {
474
- // Cleanup function (optional)
475
- };
476
- });
477
-
478
- const modelPropertyMachine = xstate.setup({
479
- types: {
480
- context: {},
481
- input: {},
482
- events: {},
483
- },
484
- actors: {
485
- saveToSchema,
486
- compareAndMarkDraft,
487
- validateProperty,
488
- writeProcessMachine: main_cjs.writeProcessMachine,
489
- },
490
- guards: {
491
- isPropertyValid: ({ context }) => {
492
- const valid = !context._validationErrors || context._validationErrors.length === 0;
493
- return valid;
494
- },
495
- },
496
- actions: {
497
- assignValidationErrors: xstate.assign(({ context, event }) => {
498
- if (event.type === 'validationError') {
499
- return {
500
- ...context,
501
- _validationErrors: event.errors,
502
- };
503
- }
504
- return context;
505
- }),
506
- },
507
- }).createMachine({
508
- id: 'modelProperty',
509
- initial: 'idle',
510
- context: ({ input }) => {
511
- const context = input;
512
- return context;
513
- },
514
- on: {
515
- updateContext: {
516
- actions: xstate.assign(({ context, event }) => {
517
- const newContext = Object.assign({}, context);
518
- // Check if this is only updating internal fields
519
- const onlyInternalFields = Object.keys(event).every((key) => {
520
- return key === 'type' || key.startsWith('_');
521
- });
522
- // Update the context with new values
523
- for (let i = 0; i < Object.keys(event).length; i++) {
524
- const key = Object.keys(event)[i];
525
- if (key === 'type') {
526
- continue;
527
- }
528
- let value = event[key];
529
- // Convert null to undefined for optional fields (TypeBox validation expects undefined, not null)
530
- // This is especially important for refValueType, refModelId, etc.
531
- if (value === null && (key === 'refValueType' || key === 'refModelId' || key === 'ref' || key === 'refModelName')) {
532
- value = undefined;
533
- }
534
- newContext[key] = value;
535
- }
536
- // Preserve modelName and dataType from context or _originalValues so validation and savePropertyToDb
537
- // never run with missing required/needed fields (e.g. when a just-created property is renamed before
538
- // the full context is available from the creator).
539
- if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
540
- newContext.modelName = context._originalValues.modelName;
541
- }
542
- if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
543
- newContext.dataType = context._originalValues.dataType;
544
- }
545
- // Compare with original values and set _isEdited flag (only for non-internal updates)
546
- if (!onlyInternalFields && context._originalValues) {
547
- const hasChanges = Object.keys(event).some((key) => {
548
- if (key === 'type' || key.startsWith('_'))
549
- return false;
550
- return newContext[key] !== context._originalValues?.[key];
551
- });
552
- newContext._isEdited = hasChanges;
553
- }
554
- // Clear validation errors on context update (will be re-validated if needed)
555
- newContext._validationErrors = undefined;
556
- // Convert null to undefined for optional fields (TypeBox validation expects undefined, not null)
557
- // This is especially important for refValueType, refModelId, etc.
558
- const optionalFields = ['refValueType', 'refModelId', 'ref', 'refModelName'];
559
- for (const field of optionalFields) {
560
- if (newContext[field] === null) {
561
- newContext[field] = undefined;
562
- }
563
- }
564
- return newContext;
565
- }),
566
- // Only trigger validation and compareAndMarkDraft if we're updating non-internal fields
567
- guard: ({ event }) => {
568
- const shouldTransition = !Object.keys(event).every((key) => {
569
- return key === 'type' || key.startsWith('_');
570
- });
571
- return shouldTransition;
572
- },
573
- target: '.validating',
574
- },
575
- validateProperty: {
576
- target: '.validating',
577
- },
578
- validationSuccess: {
579
- actions: xstate.assign(({ context, event }) => ({
580
- ...context,
581
- _validationErrors: [],
582
- })),
583
- },
584
- validationError: {
585
- actions: 'assignValidationErrors',
586
- // Note: State-specific transitions are handled in child states
587
- // This root handler ensures errors are always assigned to context
588
- },
589
- initializeOriginalValues: {
590
- actions: xstate.assign(({ context, event }) => ({
591
- ...context,
592
- _originalValues: event.originalValues,
593
- // Senders don't know the schema name; keep one setSchemaName already stored.
594
- _schemaName: event.schemaName ?? context._schemaName,
595
- _isEdited: event.isEdited ?? false,
596
- _validationErrors: undefined,
597
- })),
598
- },
599
- clearEdited: {
600
- actions: xstate.assign(({ context }) => ({
601
- ...context,
602
- _isEdited: false,
603
- _originalValues: { ...context },
604
- })),
605
- },
606
- setSchemaName: {
607
- actions: xstate.assign(({ context, event }) => ({
608
- ...context,
609
- _schemaName: event.schemaName,
610
- })),
611
- },
612
- destroyStarted: {
613
- actions: xstate.assign({ _destroyError: null }),
614
- },
615
- destroyError: {
616
- actions: xstate.assign(({ event }) => ({
617
- _destroyError: event.error instanceof Error
618
- ? { message: event.error.message, name: event.error.name }
619
- : { message: String(event.error) },
620
- })),
621
- },
622
- },
623
- states: {
624
- idle: {
625
- on: {
626
- saveToSchema: { target: 'saveToSchema' },
627
- validateProperty: {
628
- target: 'validating',
629
- },
630
- requestWrite: {
631
- actions: ({ context, event }) => {
632
- if (context.writeProcess) {
633
- context.writeProcess.send({
634
- type: 'startWrite',
635
- data: event.data,
636
- });
637
- }
638
- },
639
- },
640
- },
641
- entry: xstate.assign({
642
- writeProcess: ({ spawn, context }) => {
643
- // Spawn writeProcess if we have id (schemaFileId)
644
- // New properties will have id generated
645
- const entityId = context.id;
646
- if (!context.writeProcess && entityId) {
647
- return spawn(main_cjs.writeProcessMachine, {
648
- input: {
649
- entityType: 'modelProperty',
650
- entityId: String(entityId),
651
- entityData: context,
652
- },
653
- });
654
- }
655
- return context.writeProcess;
656
- },
657
- }),
658
- },
659
- validating: {
660
- on: {
661
- saveToSchema: { target: 'saveToSchema' },
662
- validationSuccess: {
663
- target: 'compareAndMarkDraft',
664
- actions: xstate.assign(({ context }) => ({
665
- ...context,
666
- _validationErrors: [],
667
- })),
668
- },
669
- // validationError: Uses root handler for assignment, but needs state-specific transition
670
- validationError: {
671
- target: 'idle',
672
- actions: 'assignValidationErrors',
673
- },
674
- },
675
- invoke: {
676
- src: 'validateProperty',
677
- input: ({ context }) => ({ context }),
678
- },
679
- },
680
- compareAndMarkDraft: {
681
- on: {
682
- saveToSchema: { target: 'saveToSchema' },
683
- compareAndMarkDraftSuccess: {
684
- target: 'idle',
685
- },
686
- compareAndMarkDraftError: {
687
- target: 'idle',
688
- },
689
- },
690
- invoke: {
691
- src: 'compareAndMarkDraft',
692
- input: ({ context }) => ({ context }),
693
- },
694
- },
695
- saveToSchema: {
696
- // Gate the save in a transient child. An `always` on this parent targeting `.saving` re-enters
697
- // the invoking child on every microstep and never settles (save() ran the process out of memory).
698
- initial: 'checking',
699
- on: {
700
- // Apply updateContext but do not re-invoke saveToSchema actor (avoids infinite loop).
701
- // Context is updated; in-flight save completes with original context.
702
- updateContext: [
703
- {
704
- guard: ({ context, event }) => {
705
- const onlyInternal = Object.keys(event).every((k) => k === 'type' || k.startsWith('_'));
706
- return !onlyInternal && event.name !== undefined && event.name !== context.name;
707
- },
708
- actions: xstate.assign(({ context, event }) => {
709
- const newContext = Object.assign({}, context);
710
- const onlyInternalFields = Object.keys(event).every((key) => key === 'type' || key.startsWith('_'));
711
- for (const key of Object.keys(event)) {
712
- if (key === 'type')
713
- continue;
714
- let value = event[key];
715
- if (value === null && ['refValueType', 'refModelId', 'ref', 'refModelName'].includes(key))
716
- value = undefined;
717
- newContext[key] = value;
718
- }
719
- if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
720
- newContext.modelName = context._originalValues.modelName;
721
- }
722
- if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
723
- newContext.dataType = context._originalValues.dataType;
724
- }
725
- if (!onlyInternalFields && context._originalValues) {
726
- const hasChanges = Object.keys(event).some((key) => {
727
- if (key === 'type' || key.startsWith('_'))
728
- return false;
729
- return newContext[key] !== context._originalValues?.[key];
730
- });
731
- newContext._isEdited = hasChanges;
732
- }
733
- newContext._validationErrors = undefined;
734
- return newContext;
735
- }),
736
- },
737
- {
738
- actions: xstate.assign(({ context, event }) => {
739
- const newContext = Object.assign({}, context);
740
- const onlyInternalFields = Object.keys(event).every((key) => key === 'type' || key.startsWith('_'));
741
- for (const key of Object.keys(event)) {
742
- if (key === 'type')
743
- continue;
744
- let value = event[key];
745
- if (value === null && ['refValueType', 'refModelId', 'ref', 'refModelName'].includes(key))
746
- value = undefined;
747
- newContext[key] = value;
748
- }
749
- if (newContext.modelName === undefined && context._originalValues?.modelName !== undefined) {
750
- newContext.modelName = context._originalValues.modelName;
751
- }
752
- if (newContext.dataType === undefined && context._originalValues?.dataType !== undefined) {
753
- newContext.dataType = context._originalValues.dataType;
754
- }
755
- if (!onlyInternalFields && context._originalValues) {
756
- const hasChanges = Object.keys(event).some((key) => {
757
- if (key === 'type' || key.startsWith('_'))
758
- return false;
759
- return newContext[key] !== context._originalValues?.[key];
760
- });
761
- newContext._isEdited = hasChanges;
762
- }
763
- newContext._validationErrors = undefined;
764
- return newContext;
765
- }),
766
- },
767
- ],
768
- // validationError: Uses root handler for assignment, but needs state-specific transition
769
- validationError: {
770
- target: 'idle',
771
- actions: 'assignValidationErrors',
772
- },
773
- },
774
- states: {
775
- checking: {
776
- always: [
777
- { guard: 'isPropertyValid', target: 'saving' },
778
- { target: '#modelProperty.idle' },
779
- ],
780
- },
781
- saving: {
782
- on: {
783
- saveToSchemaSuccess: {
784
- target: '#modelProperty.idle',
785
- },
786
- saveToSchemaError: {
787
- target: '#modelProperty.idle',
788
- },
789
- },
790
- invoke: {
791
- src: 'saveToSchema',
792
- input: ({ context }) => ({ context }),
793
- },
794
- },
795
- },
796
- },
797
- },
798
- });
799
-
800
- /**
801
- * Returns property rows for a model identified by modelFileId (model's schemaFileId).
802
- * Resolves modelFileId -> modelId via models table, then selects all properties where modelId = ?.
803
- * Each row includes schemaFileId for use with ModelProperty.createById(schemaFileId).
804
- */
805
- const getModelPropertiesData = async (modelFileId) => {
806
- const appDb = main_cjs.BaseDb.getAppDb();
807
- if (!appDb || !modelFileId) {
808
- return [];
809
- }
810
- const modelRows = await appDb
811
- .select({ id: main_cjs.models.id })
812
- .from(main_cjs.models)
813
- .where(drizzleOrm.eq(main_cjs.models.schemaFileId, modelFileId))
814
- .limit(1);
815
- if (modelRows.length === 0) {
816
- return [];
817
- }
818
- const modelId = modelRows[0].id;
819
- const rows = await appDb
820
- .select()
821
- .from(main_cjs.properties)
822
- .where(drizzleOrm.eq(main_cjs.properties.modelId, modelId));
823
- return rows;
824
- };
825
-
826
- const logger = debug('seedSdk:modelProperty:ModelProperty');
827
- // Define the property keys from TProperty
828
- const TPropertyKeys = [
829
- 'id',
830
- 'name',
831
- 'dataType',
832
- 'ref',
833
- 'modelId',
834
- 'refModelId',
835
- 'refValueType',
836
- 'storageType',
837
- 'localStorageDir',
838
- 'filenameSuffix',
839
- 'modelName',
840
- 'refModelName',
841
- ];
842
- class ModelProperty {
843
- constructor(property) {
844
- /** currentEvictionEpoch() at construction: lookups started for this instance don't outlive an eviction. */
845
- this._evictionEpoch = main_cjs.currentEvictionEpoch();
846
- // id is now the schemaFileId (string), _dbId is the database integer ID
847
- // Preserve _propertyFileId if it exists in the property object (from getPropertySchema)
848
- // Convert null to undefined for optional fields (TypeBox validation expects undefined, not null)
849
- const serviceInput = {
850
- ...property,
851
- _propertyFileId: property._propertyFileId || property.id,
852
- refValueType: property.refValueType ?? undefined,
853
- refModelId: property.refModelId ?? undefined,
854
- ref: property.ref ?? undefined,
855
- refModelName: property.refModelName ?? undefined,
856
- };
857
- this._service = xstate.createActor(modelPropertyMachine, {
858
- input: serviceInput,
859
- });
860
- this._service.start();
861
- // Initialize original values from the input property
862
- this._initializeOriginalValues(property);
863
- // Note: Property getters/setters are now handled by the Proxy in create()
864
- }
865
- /**
866
- * Send from fire-and-forget async work (DB lookups started in the constructor), which can finish
867
- * after the instance was unloaded or evicted with its schema.
868
- */
869
- _sendIfRunning(event) {
870
- if (main_cjs.isActorStopped(this._service))
871
- return;
872
- this._service.send(event);
873
- }
874
- /**
875
- * Initialize original values and schema name for tracking changes
876
- * This is called asynchronously after construction
877
- * If the property was loaded from the database and differs from the schema file,
878
- * it will be marked as edited.
879
- */
880
- _initializeOriginalValues(property) {
881
- // Resolve refModelId if ref/refModelName is provided but refModelId is missing
882
- const refModelName = property.refModelName || property.ref;
883
- if (refModelName && !property.refModelId) {
884
- // Resolve refModelId asynchronously and update context
885
- this._resolveRefModelId(refModelName, property).then((refModelId) => {
886
- if (refModelId) {
887
- // Update the context with the resolved refModelId
888
- this._sendIfRunning({
889
- type: 'updateContext',
890
- refModelId,
891
- });
892
- }
893
- }).catch(() => {
894
- // Ignore errors - model might not exist yet
895
- });
896
- }
897
- // Get schema file values to use as "original" values
898
- // This allows us to detect if the property was edited (DB value differs from schema file)
899
- this._getSchemaFileValues(property).then((schemaFileValues) => {
900
- // Use schema file values as original (not the current property values)
901
- // This way, if current values differ from schema file, _isEdited will be true
902
- const originalValues = schemaFileValues || {};
903
- // Compare current property values with schema file values to determine if edited
904
- // Only compare schema-relevant fields, not database-specific fields like id, modelId
905
- let isEdited = false;
906
- if (schemaFileValues) {
907
- // Fields that are schema-relevant and should be compared
908
- const schemaRelevantFields = [
909
- 'dataType',
910
- 'ref',
911
- 'refModelName',
912
- 'refValueType',
913
- 'storageType',
914
- 'localStorageDir',
915
- 'filenameSuffix',
916
- ];
917
- // Check if any schema-relevant field differs between current property and schema file
918
- isEdited = schemaRelevantFields.some((key) => {
919
- const currentValue = property[key];
920
- const originalValue = schemaFileValues[key];
921
- // Handle ref fields - compare by name
922
- if (key === 'ref' || key === 'refModelName') {
923
- const currentRef = property.refModelName || property.ref;
924
- const originalRef = schemaFileValues.refModelName || schemaFileValues.ref;
925
- // Both undefined/null means no ref, so they're the same
926
- if (!currentRef && !originalRef)
927
- return false;
928
- return currentRef !== originalRef;
929
- }
930
- // For other fields, compare values (handling undefined/null)
931
- if (currentValue === undefined && originalValue === undefined)
932
- return false;
933
- if (currentValue === null && originalValue === null)
934
- return false;
935
- if (currentValue === undefined && originalValue === null)
936
- return false;
937
- if (currentValue === null && originalValue === undefined)
938
- return false;
939
- return currentValue !== originalValue;
940
- });
941
- }
942
- else {
943
- // No schema file values found - this is a runtime-created property
944
- // Use current property as original, but mark as edited since it hasn't been exported to file
945
- TPropertyKeys.forEach((key) => {
946
- if (property[key] !== undefined) {
947
- originalValues[key] = property[key];
948
- }
949
- });
950
- // For runtime-created properties, set isEdited = true initially
951
- isEdited = true;
952
- }
953
- // Initialize with original values, including isEdited flag
954
- // Load isEdited from database if property exists in DB (async, fire-and-forget)
955
- this._loadIsEditedFromDb(property, isEdited).then((isEditedFromDb) => {
956
- this._sendIfRunning({
957
- type: 'initializeOriginalValues',
958
- originalValues,
959
- schemaName: undefined, // Will be set later if needed
960
- isEdited: isEditedFromDb,
961
- });
962
- }).catch(() => {
963
- // If we can't load from DB, use computed isEdited value
964
- this._sendIfRunning({
965
- type: 'initializeOriginalValues',
966
- originalValues,
967
- schemaName: undefined, // Will be set later if needed
968
- isEdited,
969
- });
970
- });
971
- }).catch(() => {
972
- // If we can't get schema file values, use current property as original
973
- const originalValues = {};
974
- TPropertyKeys.forEach((key) => {
975
- if (property[key] !== undefined) {
976
- originalValues[key] = property[key];
977
- }
978
- });
979
- this._sendIfRunning({
980
- type: 'initializeOriginalValues',
981
- originalValues,
982
- schemaName: undefined,
983
- });
984
- });
985
- // Get schema name from model asynchronously (fire-and-forget)
986
- if (property.modelName) {
987
- this._setSchemaName(property).catch(() => {
988
- // If we can't get schema name, that's okay - it will be set later if needed
989
- });
990
- }
991
- }
992
- /**
993
- * Load isEdited flag from database if property exists in DB
994
- * @param property - The property data
995
- * @param fallbackIsEdited - Fallback value if property doesn't exist in DB
996
- * @returns The isEdited flag from database or fallback value
997
- */
998
- async _loadIsEditedFromDb(property, fallbackIsEdited) {
999
- if (!property.modelName || !property.name) {
1000
- return fallbackIsEdited;
1001
- }
1002
- try {
1003
- const db = main_cjs.BaseDb.getAppDb();
1004
- if (!db) {
1005
- return fallbackIsEdited;
1006
- }
1007
- // Find this property's model (by modelId when known; model names are only unique per schema)
1008
- const { resolveModelRecord } = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.resolveModelRecord$1; });
1009
- const modelRecord = await resolveModelRecord(property.modelName, this._ownerModelScope(property), db);
1010
- const modelRecords = modelRecord ? [modelRecord] : [];
1011
- if (modelRecords.length === 0) {
1012
- return fallbackIsEdited;
1013
- }
1014
- // Find property by name and modelId
1015
- const propertyRecords = await db
1016
- .select({ isEdited: main_cjs.properties.isEdited })
1017
- .from(main_cjs.properties)
1018
- .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.properties.name, property.name), drizzleOrm.eq(main_cjs.properties.modelId, modelRecords[0].id)))
1019
- .limit(1);
1020
- if (propertyRecords.length > 0) {
1021
- return propertyRecords[0].isEdited ?? false;
1022
- }
1023
- }
1024
- catch (error) {
1025
- // Ignore errors - use fallback value
1026
- }
1027
- return fallbackIsEdited;
1028
- }
1029
- /**
1030
- * Resolve refModelId from refModelName by querying the database
1031
- * @param refModelName - The name of the referenced model
1032
- * @returns The database ID of the referenced model, or undefined if not found
1033
- */
1034
- async _resolveRefModelId(refModelName, property) {
1035
- if (!refModelName) {
1036
- return undefined;
1037
- }
1038
- try {
1039
- const db = main_cjs.BaseDb.getAppDb();
1040
- if (!db) {
1041
- return undefined;
1042
- }
1043
- // Resolve the ref within the owning model's schema
1044
- const { resolveRefModelRecord } = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.resolveModelRecord$1; });
1045
- const refModelRecord = await resolveRefModelRecord(refModelName, property ? this._ownerModelScope(property) : { schemaName: this._getSnapshotContext()._schemaName }, db);
1046
- if (refModelRecord?.id) {
1047
- return refModelRecord.id;
1048
- }
1049
- }
1050
- catch (error) {
1051
- // Ignore errors - model might not exist yet or database not available
1052
- logger(`Error resolving refModelId for model "${refModelName}":`, error);
1053
- }
1054
- return undefined;
1055
- }
1056
- /** Which model this property belongs to: its models row id and/or schema. */
1057
- _ownerModelScope(property) {
1058
- const context = this._getSnapshotContext();
1059
- const modelId = property.modelId ?? context.modelId;
1060
- return {
1061
- modelId: typeof modelId === 'number' ? modelId : undefined,
1062
- schemaName: context._schemaName,
1063
- };
1064
- }
1065
- /**
1066
- * Get schema file values for this property to use as "original" values
1067
- * This allows comparison with database values to detect edits
1068
- */
1069
- async _getSchemaFileValues(property) {
1070
- if (!property.modelName || !property.name) {
1071
- return undefined;
1072
- }
1073
- try {
1074
- const { modelId, schemaName } = this._ownerModelScope(property);
1075
- // Synchronous cache hits first: callers compare against these values right after construction,
1076
- // so an extra await here lets every property look "edited" (a draft save each). Only then the
1077
- // DB (by modelId), and never instantiate a Model while its own properties are initializing.
1078
- let model = schemaName ? main_cjs.Model.getByName(property.modelName, schemaName) : undefined;
1079
- if (!model) {
1080
- try {
1081
- model = main_cjs.Model.getByName(property.modelName);
1082
- }
1083
- catch {
1084
- model = undefined; // ambiguous name; resolve by modelId below
1085
- }
1086
- }
1087
- if (!model && modelId) {
1088
- const { resolveModelRecord } = await Promise.resolve().then(function () { return require('./index-C4XlgCJ4.js'); }).then(function (n) { return n.resolveModelRecord$1; });
1089
- const modelFileId = (await resolveModelRecord(property.modelName, { modelId }))?.schemaFileId;
1090
- model = modelFileId ? main_cjs.Model.getById(modelFileId) : undefined;
1091
- }
1092
- // Evicted (with its schema) or unloaded while the lookups above ran: don't instantiate its model
1093
- // again from rows that are being deleted.
1094
- if (!model && main_cjs.isActorStopped(this._service))
1095
- return undefined;
1096
- if (!model) {
1097
- try {
1098
- // The epoch from when this instance was built: an eviction of the model's schema since
1099
- // then (this instance may already be stopped) must not re-create the model.
1100
- model = await main_cjs.Model.getByNameAsync(property.modelName, undefined, {
1101
- evictionEpoch: this._evictionEpoch,
1102
- });
1103
- }
1104
- catch {
1105
- model = undefined;
1106
- }
1107
- }
1108
- if (!model || !model.properties || model.properties.length === 0) {
1109
- return undefined;
1110
- }
1111
- const schema = main_cjs.modelPropertiesToObject(model.properties);
1112
- // Get the schema file value for this property
1113
- const schemaFileValue = schema[property.name];
1114
- if (!schemaFileValue) {
1115
- return undefined;
1116
- }
1117
- // Return schema file values as original values
1118
- const originalValues = {
1119
- name: property.name,
1120
- modelName: property.modelName,
1121
- dataType: schemaFileValue.dataType,
1122
- storageType: schemaFileValue.storageType,
1123
- localStorageDir: schemaFileValue.localStorageDir,
1124
- filenameSuffix: schemaFileValue.filenameSuffix,
1125
- };
1126
- // Handle ref fields
1127
- if (schemaFileValue.ref) {
1128
- originalValues.ref = schemaFileValue.ref;
1129
- originalValues.refModelName = schemaFileValue.ref;
1130
- // Try to get refModelId from database
1131
- const refModelId = await this._resolveRefModelId(schemaFileValue.ref, property);
1132
- if (refModelId) {
1133
- originalValues.refModelId = refModelId;
1134
- }
1135
- }
1136
- if (schemaFileValue.refValueType) {
1137
- originalValues.refValueType = schemaFileValue.refValueType;
1138
- }
1139
- return originalValues;
1140
- }
1141
- catch (error) {
1142
- return undefined;
1143
- }
1144
- }
1145
- /**
1146
- * Set the schema name for this property by looking it up from the model
1147
- * Tries database first (more reliable), then falls back to schema files
1148
- */
1149
- async _setSchemaName(property) {
1150
- try {
1151
- // create() sets the schema name right after construction when its caller knows it. Don't look it
1152
- // up then: the file fallback below reads and parses every schema file, per property.
1153
- await Promise.resolve();
1154
- if (this._getSnapshotContext()._schemaName)
1155
- return;
1156
- let schemaName;
1157
- // From the property data: the instance's own modelId field is never assigned (the reactive proxy
1158
- // serves values from the machine context), so reading this.modelId skipped the DB lookup.
1159
- const { modelId } = this._ownerModelScope(property);
1160
- // Try to get schema name from database first (more reliable)
1161
- if (modelId) {
1162
- try {
1163
- const db = main_cjs.BaseDb.getAppDb();
1164
- if (db) {
1165
- const modelSchemaRecords = await db
1166
- .select({
1167
- schemaName: main_cjs.schemas.name,
1168
- })
1169
- .from(main_cjs.modelSchemas)
1170
- .innerJoin(main_cjs.schemas, drizzleOrm.eq(main_cjs.modelSchemas.schemaId, main_cjs.schemas.id))
1171
- .innerJoin(main_cjs.models, drizzleOrm.eq(main_cjs.modelSchemas.modelId, main_cjs.models.id))
1172
- .where(drizzleOrm.eq(main_cjs.models.id, modelId))
1173
- .limit(1);
1174
- if (modelSchemaRecords.length > 0) {
1175
- schemaName = modelSchemaRecords[0].schemaName;
1176
- }
1177
- }
1178
- }
1179
- catch (error) {
1180
- // Database lookup failed, continue to file-based lookup
1181
- }
1182
- }
1183
- // Fall back to schema file lookup if database didn't work
1184
- if (!schemaName) {
1185
- schemaName = await getSchemaNameFromModel(property.modelName);
1186
- }
1187
- if (schemaName) {
1188
- // Update the context with the schema name using dedicated event
1189
- this._sendIfRunning({
1190
- type: 'setSchemaName',
1191
- schemaName,
1192
- });
1193
- }
1194
- }
1195
- catch (error) {
1196
- // If we can't get schema name, that's okay - it will be set later if needed
1197
- }
1198
- }
1199
- /**
1200
- * Resolve schema name from DB when _schemaName is missing (e.g. destroy ran before _setSchemaName finished).
1201
- * Uses context.id (schemaFileId) and context.modelId to query properties → model_schemas → schemas.
1202
- */
1203
- async _resolveSchemaNameForDestroy(db, context) {
1204
- try {
1205
- let modelId = context.modelId;
1206
- const schemaFileId = context.id ?? context._propertyFileId;
1207
- // If we don't have modelId, get it from the property row by schemaFileId
1208
- if (modelId == null && schemaFileId) {
1209
- const propRows = await db
1210
- .select({ modelId: main_cjs.properties.modelId })
1211
- .from(main_cjs.properties)
1212
- .where(drizzleOrm.eq(main_cjs.properties.schemaFileId, schemaFileId))
1213
- .limit(1);
1214
- if (propRows.length > 0 && propRows[0].modelId != null) {
1215
- modelId = propRows[0].modelId;
1216
- }
1217
- }
1218
- if (modelId == null)
1219
- return undefined;
1220
- // Resolve modelFileId (string) to database ID (number) if needed - modelSchemas.modelId expects number
1221
- const modelIdNum = typeof modelId === 'string' ? await main_cjs.getModelIdByFileId(modelId) : modelId;
1222
- const modelSchemaRecords = await db
1223
- .select({ schemaName: main_cjs.schemas.name })
1224
- .from(main_cjs.modelSchemas)
1225
- .innerJoin(main_cjs.schemas, drizzleOrm.eq(main_cjs.modelSchemas.schemaId, main_cjs.schemas.id))
1226
- .where(drizzleOrm.eq(main_cjs.modelSchemas.modelId, modelIdNum))
1227
- .limit(1);
1228
- return modelSchemaRecords.length > 0 ? modelSchemaRecords[0].schemaName ?? undefined : undefined;
1229
- }
1230
- catch {
1231
- return undefined;
1232
- }
1233
- }
1234
- /**
1235
- * Manually set the schema name for this property
1236
- * Useful when you know the schema name from context (e.g., when working with Schema instances)
1237
- */
1238
- setSchemaName(schemaName) {
1239
- this._service.send({
1240
- type: 'setSchemaName',
1241
- schemaName,
1242
- });
1243
- }
1244
- static create(property, options) {
1245
- if (!property) {
1246
- throw new Error('Property is required');
1247
- }
1248
- const waitForReady = options?.waitForReady !== false;
1249
- const readyTimeout = options?.readyTimeout ?? 5000;
1250
- const schemaName = options?.schemaName;
1251
- // Handle 'type' field from JSON schema format - convert to 'dataType'
1252
- // Normalize to PascalCase so lowercase values from JSON (e.g. 'text') work
1253
- const propertyWithId = { ...property };
1254
- const rawType = propertyWithId.dataType ?? propertyWithId.type;
1255
- if (rawType) {
1256
- propertyWithId.dataType = main_cjs.normalizeDataType(rawType);
1257
- }
1258
- if (typeof propertyWithId.refValueType === 'string') {
1259
- propertyWithId.refValueType = main_cjs.normalizeDataType(propertyWithId.refValueType);
1260
- }
1261
- // Ensure id (schemaFileId) is set correctly
1262
- // Priority: _propertyFileId > id (if string) > generate new
1263
- // If id is a number (old format), use _propertyFileId instead
1264
- if (typeof propertyWithId.id === 'number') {
1265
- // id is a database integer ID, not schemaFileId - use _propertyFileId if available
1266
- if (propertyWithId._propertyFileId) {
1267
- propertyWithId.id = propertyWithId._propertyFileId;
1268
- }
1269
- else {
1270
- // Fallback: generate new schemaFileId (shouldn't happen, but safety)
1271
- propertyWithId.id = main_cjs.generateId();
1272
- logger(`ModelProperty.create: id was a number, generated new schemaFileId "${propertyWithId.id}" for property "${property.name}"`);
1273
- }
1274
- }
1275
- else if (!propertyWithId.id && propertyWithId._propertyFileId) {
1276
- // id is not set but _propertyFileId is available - use it
1277
- propertyWithId.id = propertyWithId._propertyFileId;
1278
- }
1279
- else if (!propertyWithId.id) {
1280
- // Generate id (schemaFileId) if not provided (for new properties)
1281
- // This ensures new properties can trigger write process
1282
- propertyWithId.id = main_cjs.generateId();
1283
- logger(`ModelProperty.create: Generated new id (schemaFileId) "${propertyWithId.id}" for property "${property.name}"`);
1284
- }
1285
- // Create cache key from modelName and name, or use id
1286
- let cacheKey = propertyWithId.modelName && propertyWithId.name
1287
- ? `${propertyWithId.modelName}:${propertyWithId.name}`
1288
- : propertyWithId.id
1289
- ? `id:${propertyWithId.id}`
1290
- : propertyWithId.name || 'unnamed';
1291
- // Model names are only unique per schema: a cached "Post:title" may be another schema's
1292
- // property. If the ids say it's a different property, key this one by its own id instead.
1293
- // (Not by file id: the same property is often created first with a generated id, then its real one.)
1294
- const isOtherProperty = (cachedContext) => (typeof propertyWithId.modelId === 'number' &&
1295
- typeof cachedContext.modelId === 'number' &&
1296
- cachedContext.modelId !== propertyWithId.modelId) ||
1297
- (!!schemaName && !!cachedContext._schemaName && cachedContext._schemaName !== schemaName);
1298
- const cachedByName = this.instanceCache.get(cacheKey);
1299
- if (cachedByName && propertyWithId.id && isOtherProperty(cachedByName.instance._getSnapshotContext())) {
1300
- // Reuse this property's own id-keyed entry if it already has one.
1301
- cacheKey = `id:${propertyWithId.id}`;
1302
- for (const [key, { instance }] of this.instanceCache.entries()) {
1303
- if (!key.startsWith('id:'))
1304
- continue;
1305
- const ctx = instance._getSnapshotContext();
1306
- if (ctx.modelName === propertyWithId.modelName && ctx.name === propertyWithId.name && !isOtherProperty(ctx)) {
1307
- cacheKey = key;
1308
- break;
1309
- }
1310
- }
1311
- }
1312
- // Check if instance exists in cache
1313
- if (this.instanceCache.has(cacheKey)) {
1314
- const { instance, refCount } = this.instanceCache.get(cacheKey);
1315
- const cachedContext = instance._getSnapshotContext();
1316
- // Update cached instance if new property data has fields that the cached instance doesn't have
1317
- // This handles cases where the property was created without ref initially, but now we have ref from schema
1318
- const needsUpdate = {};
1319
- if (propertyWithId.ref && !cachedContext.ref) {
1320
- needsUpdate.ref = propertyWithId.ref;
1321
- }
1322
- if (propertyWithId.refModelName && !cachedContext.refModelName) {
1323
- needsUpdate.refModelName = propertyWithId.refModelName;
1324
- }
1325
- if (propertyWithId.refModelId && !cachedContext.refModelId) {
1326
- needsUpdate.refModelId = propertyWithId.refModelId;
1327
- }
1328
- if (Object.keys(needsUpdate).length > 0) {
1329
- instance._service.send({
1330
- type: 'updateContext',
1331
- ...needsUpdate,
1332
- });
1333
- }
1334
- this.instanceCache.set(cacheKey, {
1335
- instance,
1336
- refCount: refCount + 1,
1337
- });
1338
- if (!waitForReady)
1339
- return instance;
1340
- return main_cjs.waitForEntityIdle(instance, { timeout: readyTimeout }).then(() => instance);
1341
- }
1342
- const newInstance = new this(propertyWithId);
1343
- // Set schema name before async operations so getModelId can resolve the correct model
1344
- if (schemaName) {
1345
- newInstance._service.send({
1346
- type: 'setSchemaName',
1347
- schemaName,
1348
- });
1349
- }
1350
- // Wrap instance in Proxy for reactive property access
1351
- const proxiedInstance = main_cjs.createReactiveProxy({
1352
- instance: newInstance,
1353
- service: newInstance._service,
1354
- trackedProperties: TPropertyKeys,
1355
- getContext: (instance) => {
1356
- const context = instance._getSnapshotContext();
1357
- return context;
1358
- },
1359
- sendUpdate: (instance, prop, value) => {
1360
- const currentContext = instance._getSnapshotContext();
1361
- if (currentContext[prop] === value)
1362
- return; // No-op, avoid triggering machine
1363
- instance._service.send({
1364
- type: 'updateContext',
1365
- [prop]: value,
1366
- });
1367
- },
1368
- });
1369
- this.instanceCache.set(cacheKey, {
1370
- instance: proxiedInstance,
1371
- refCount: 1,
1372
- });
1373
- this.indexCachedInstance(cacheKey, proxiedInstance);
1374
- // Trigger write process if property has modelId (or modelName) and id (schemaFileId)
1375
- // Wait for service to be ready (idle state) and have writeProcess spawned
1376
- const propertyFileId = propertyWithId.id; // id is now the schemaFileId (string)
1377
- const hasModelId = propertyWithId.modelId || propertyWithId.modelName;
1378
- // A _dbId means the data was loaded from an existing row (createById, getPropertySchema), so
1379
- // there's nothing to write. Writing it back anyway raced deletes of that row's model (FK error).
1380
- const isPersisted = typeof propertyWithId._dbId === 'number';
1381
- if (hasModelId && propertyFileId && !isPersisted) {
1382
- // Wait for writeProcess to be spawned (it's spawned in idle state entry action)
1383
- // Retry a few times if writeProcess isn't available yet
1384
- let retries = 0;
1385
- const maxRetries = 10;
1386
- const checkAndSend = async () => {
1387
- const service = proxiedInstance.getService();
1388
- const snapshot = service.getSnapshot();
1389
- // Unloaded or evicted (e.g. Schema.destroy) before the write started: nothing to write to
1390
- if (main_cjs.isActorStopped(service))
1391
- return;
1392
- if (snapshot.value === 'idle' && snapshot.context.writeProcess) {
1393
- const writeProcess = snapshot.context.writeProcess;
1394
- // Resolve dbModelId - convert from string (modelFileId) to number (database ID) if needed
1395
- let resolvedModelId = undefined;
1396
- if (propertyWithId.modelId) {
1397
- if (typeof propertyWithId.modelId === 'number') {
1398
- resolvedModelId = propertyWithId.modelId;
1399
- }
1400
- else if (typeof propertyWithId.modelId === 'string') {
1401
- // modelId is a string (modelFileId), need to convert to database ID
1402
- try {
1403
- resolvedModelId = await main_cjs.getModelIdByFileId(propertyWithId.modelId);
1404
- logger(`Converted modelFileId "${propertyWithId.modelId}" to database modelId: ${resolvedModelId}`);
1405
- }
1406
- catch (error) {
1407
- logger(`Failed to convert modelFileId "${propertyWithId.modelId}" to database ID: ${error}`);
1408
- console.error(`[ModelProperty.create] Failed to convert modelFileId: ${error}`);
1409
- }
1410
- }
1411
- }
1412
- // If we still don't have a modelId, try to resolve it from modelName
1413
- if (!resolvedModelId && propertyWithId.modelName) {
1414
- try {
1415
- // Get schemaName from context if available
1416
- const schemaName = snapshot.context._schemaName;
1417
- resolvedModelId = await main_cjs.getModelId(propertyWithId.modelName, schemaName);
1418
- logger(`Resolved modelId for model "${propertyWithId.modelName}": ${resolvedModelId}`);
1419
- }
1420
- catch (error) {
1421
- logger(`Failed to resolve modelId for model "${propertyWithId.modelName}": ${error}`);
1422
- console.error(`[ModelProperty.create] Failed to resolve modelId: ${error}`);
1423
- }
1424
- }
1425
- if (!resolvedModelId) {
1426
- logger(`ERROR: Cannot write property "${property.name}" - no modelId available`);
1427
- console.error(`[ModelProperty.create] ERROR: Cannot write property "${property.name}" - no modelId available. modelId: ${propertyWithId.modelId}, modelName: ${propertyWithId.modelName}`);
1428
- // Don't clear pending write here - it might resolve later
1429
- return;
1430
- }
1431
- // Resolving the modelId awaited the DB; the instance may have been stopped meanwhile
1432
- if (main_cjs.isActorStopped(service))
1433
- return;
1434
- // Track pending write now that we have the resolved modelId
1435
- this.trackPendingWrite(propertyFileId, resolvedModelId);
1436
- logger(`Triggering write process for property "${property.name}" (modelId: ${resolvedModelId}, propertyFileId: ${propertyFileId})`);
1437
- // Check current write state
1438
- const currentWriteState = writeProcess.getSnapshot();
1439
- if (currentWriteState.value === 'success') {
1440
- // Write already succeeded
1441
- void this.completePendingWrite(propertyFileId, resolvedModelId);
1442
- }
1443
- else {
1444
- // Set up subscription to catch future state changes
1445
- const writeSubscription = writeProcess.subscribe((writeSnapshot) => {
1446
- if (writeSnapshot.value === 'success') {
1447
- writeSubscription.unsubscribe();
1448
- logger(`[writeProcess subscription] Write succeeded for property "${property.name}" (propertyFileId: ${propertyFileId})`);
1449
- void this.completePendingWrite(propertyFileId, resolvedModelId);
1450
- }
1451
- else if (writeSnapshot.value === 'error') {
1452
- writeSubscription.unsubscribe();
1453
- const errorContext = writeSnapshot.context;
1454
- logger(`Write process failed for property "${property.name}" (propertyFileId: ${propertyFileId}): ${errorContext.error?.message || 'Unknown error'}`);
1455
- logger(`Write process error details:`, errorContext.error);
1456
- // Mark pending write as error
1457
- this.clearPendingWrite(propertyFileId, 'error');
1458
- }
1459
- });
1460
- }
1461
- const propertyData = {
1462
- modelId: resolvedModelId,
1463
- name: property.name,
1464
- dataType: property.dataType,
1465
- refModelId: property.refModelId,
1466
- refValueType: property.refValueType,
1467
- required: property.required,
1468
- storageType: property.storageType,
1469
- localStorageDir: property.localStorageDir,
1470
- filenameSuffix: property.filenameSuffix,
1471
- };
1472
- service.send({
1473
- type: 'requestWrite',
1474
- data: propertyData,
1475
- });
1476
- }
1477
- else if (retries < maxRetries) {
1478
- retries++;
1479
- setTimeout(checkAndSend, 50); // Retry after 50ms
1480
- }
1481
- else {
1482
- logger(`ERROR: writeProcess not available after ${maxRetries} retries for property "${property.name}" (propertyFileId: ${propertyFileId})`);
1483
- console.error(`[ModelProperty.create] ERROR: writeProcess not available after ${maxRetries} retries for property "${property.name}" (propertyFileId: ${propertyFileId})`);
1484
- // Mark as error if we couldn't even start the write process
1485
- this.clearPendingWrite(propertyFileId, 'error');
1486
- }
1487
- };
1488
- // Start checking after a short delay to allow state machine to initialize
1489
- setTimeout(checkAndSend, 0);
1490
- }
1491
- if (!waitForReady)
1492
- return proxiedInstance;
1493
- return main_cjs.waitForEntityIdle(proxiedInstance, { timeout: readyTimeout }).then(() => proxiedInstance);
1494
- }
1495
- /** Whether an idIndex entry still points at a cached instance with that id. */
1496
- static isIndexEntryCurrent(propertyFileId, entry) {
1497
- if (this.instanceCache.get(entry.cacheKey)?.instance !== entry.instance)
1498
- return false;
1499
- try {
1500
- return entry.instance._getSnapshotContext().id === propertyFileId;
1501
- }
1502
- catch {
1503
- return false;
1504
- }
1505
- }
1506
- /** Add a newly cached instance to idIndex, and keep its entry current when its id changes. */
1507
- static indexCachedInstance(cacheKey, instance) {
1508
- const index = (id) => {
1509
- if (!id)
1510
- return;
1511
- const existing = this.idIndex.get(id);
1512
- // Keep the instance cached first, as the old scan in insertion order returned
1513
- if (existing && existing.instance !== instance && this.isIndexEntryCurrent(id, existing))
1514
- return;
1515
- this.idIndex.set(id, { cacheKey, instance });
1516
- };
1517
- let indexedId = instance._getSnapshotContext().id;
1518
- index(indexedId);
1519
- instance._service.subscribe((snapshot) => {
1520
- const id = snapshot.context.id;
1521
- if (id === indexedId)
1522
- return;
1523
- indexedId = id;
1524
- index(id);
1525
- });
1526
- }
1527
- /**
1528
- * Get ModelProperty instance by propertyFileId from static cache
1529
- */
1530
- static getById(propertyFileId) {
1531
- if (!propertyFileId)
1532
- return undefined;
1533
- const indexed = this.idIndex.get(propertyFileId);
1534
- if (!indexed)
1535
- return undefined;
1536
- if (this.isIndexEntryCurrent(propertyFileId, indexed))
1537
- return indexed.instance;
1538
- // The indexed instance left the cache or changed id; another cached instance may still have it.
1539
- // Cache key might be "modelName:propertyName" or "id:propertyId"
1540
- this.idIndex.delete(propertyFileId);
1541
- for (const [cacheKey, { instance }] of this.instanceCache.entries()) {
1542
- // id is now the schemaFileId (string)
1543
- if (instance._getSnapshotContext().id === propertyFileId) {
1544
- this.idIndex.set(propertyFileId, { cacheKey, instance });
1545
- return instance;
1546
- }
1547
- }
1548
- return undefined;
1549
- }
1550
- /**
1551
- * Create or get ModelProperty instance by propertyFileId
1552
- * Queries the database to find the property if not cached
1553
- */
1554
- static async createById(propertyFileId, options) {
1555
- if (!propertyFileId) {
1556
- return undefined;
1557
- }
1558
- // First, check if we have an instance cached
1559
- const cachedInstance = this.getById(propertyFileId);
1560
- if (cachedInstance) {
1561
- return cachedInstance;
1562
- }
1563
- // Query database to get property data from ID
1564
- const db = main_cjs.BaseDb.getAppDb();
1565
- if (!db) {
1566
- return undefined;
1567
- }
1568
- const evictionEpoch = options?.evictionEpoch ?? main_cjs.currentEvictionEpoch();
1569
- const propertyRecords = await db
1570
- .select()
1571
- .from(main_cjs.properties)
1572
- .where(drizzleOrm.eq(main_cjs.properties.schemaFileId, propertyFileId))
1573
- .limit(1);
1574
- if (propertyRecords.length === 0) {
1575
- return undefined;
1576
- }
1577
- const propertyRecord = propertyRecords[0];
1578
- // Get model name
1579
- const modelRecords = await db
1580
- .select({ name: main_cjs.models.name })
1581
- .from(main_cjs.models)
1582
- .where(drizzleOrm.eq(main_cjs.models.id, propertyRecord.modelId))
1583
- .limit(1);
1584
- if (modelRecords.length === 0) {
1585
- return undefined;
1586
- }
1587
- const modelName = modelRecords[0].name;
1588
- // Build property data
1589
- // id is now the schemaFileId (string), _dbId is the database integer ID
1590
- const propertyData = {
1591
- id: propertyFileId, // schemaFileId (string) - public ID
1592
- _dbId: propertyRecord.id ?? undefined, // Database integer ID - internal only
1593
- name: propertyRecord.name,
1594
- dataType: propertyRecord.dataType,
1595
- modelId: propertyRecord.modelId,
1596
- modelName,
1597
- refModelId: propertyRecord.refModelId || undefined,
1598
- refValueType: propertyRecord.refValueType ? propertyRecord.refValueType : undefined,
1599
- required: propertyRecord.required ?? false,
1600
- storageType: propertyRecord.storageType ?? undefined,
1601
- localStorageDir: propertyRecord.localStorageDir ?? undefined,
1602
- filenameSuffix: propertyRecord.filenameSuffix ?? undefined,
1603
- };
1604
- // Load isEdited from database
1605
- const isEditedFromDb = propertyRecord.isEdited ?? false;
1606
- // Get ref model name if applicable
1607
- if (propertyRecord.refModelId) {
1608
- const refModelRecords = await db
1609
- .select({ name: main_cjs.models.name })
1610
- .from(main_cjs.models)
1611
- .where(drizzleOrm.eq(main_cjs.models.id, propertyRecord.refModelId))
1612
- .limit(1);
1613
- if (refModelRecords.length > 0) {
1614
- propertyData.refModelName = refModelRecords[0].name;
1615
- propertyData.ref = refModelRecords[0].name;
1616
- }
1617
- }
1618
- // Its model's schema was evicted while we read the rows (e.g. a model's property lookup in flight
1619
- // during Schema.destroy or test cleanup): don't bring the property back.
1620
- if (main_cjs.anyEvictionSince(evictionEpoch)) {
1621
- const schemaRows = await db
1622
- .select({ name: main_cjs.schemas.name })
1623
- .from(main_cjs.modelSchemas)
1624
- .innerJoin(main_cjs.schemas, drizzleOrm.eq(main_cjs.schemas.id, main_cjs.modelSchemas.schemaId))
1625
- .where(drizzleOrm.eq(main_cjs.modelSchemas.modelId, propertyRecord.modelId));
1626
- if (schemaRows.length === 0 ||
1627
- schemaRows.some((row) => main_cjs.schemaEvictedSince(row.name, evictionEpoch))) {
1628
- return undefined;
1629
- }
1630
- }
1631
- // Create ModelProperty instance (sync for createById so we can send updateContext)
1632
- const instance = this.create(propertyData, { waitForReady: false });
1633
- // Set isEdited from database after creation
1634
- if (isEditedFromDb) {
1635
- instance._service.send({
1636
- type: 'updateContext',
1637
- _isEdited: true,
1638
- });
1639
- }
1640
- return instance;
1641
- }
1642
- /**
1643
- * Find ModelProperty instance by propertyFileId
1644
- * Waits for the property to be fully loaded (idle state) by default
1645
- * @param options - Find options including propertyFileId and wait configuration
1646
- * @returns ModelProperty instance if found, undefined otherwise
1647
- */
1648
- static async find({ propertyFileId, waitForReady = true, readyTimeout = 5000, }) {
1649
- if (!propertyFileId) {
1650
- return undefined;
1651
- }
1652
- return await main_cjs.findEntity({
1653
- getById: (id) => ModelProperty.getById(id),
1654
- createById: (id) => ModelProperty.createById(id),
1655
- }, { id: propertyFileId }, {
1656
- waitForReady,
1657
- readyTimeout,
1658
- });
1659
- }
1660
- /**
1661
- * Get all ModelProperty instances for a model.
1662
- * Loads property rows from DB for the given modelFileId, creates instances via createById, optionally waits for idle.
1663
- */
1664
- static async all(modelFileId, options) {
1665
- const { waitForReady = false, readyTimeout = 5000 } = options ?? {};
1666
- if (!modelFileId) {
1667
- return [];
1668
- }
1669
- const rows = await getModelPropertiesData(modelFileId);
1670
- const instances = [];
1671
- for (const row of rows) {
1672
- if (row.schemaFileId) {
1673
- const instance = await this.createById(row.schemaFileId);
1674
- if (instance) {
1675
- instances.push(instance);
1676
- }
1677
- }
1678
- }
1679
- if (waitForReady && instances.length > 0) {
1680
- await Promise.all(instances.map((p) => main_cjs.waitForEntityIdle(p, {
1681
- timeout: readyTimeout,
1682
- })));
1683
- }
1684
- return instances;
1685
- }
1686
- /**
1687
- * Track a pending write for a property
1688
- */
1689
- static trackPendingWrite(propertyFileId, modelId) {
1690
- this.pendingWrites.set(propertyFileId, {
1691
- propertyFileId,
1692
- modelId,
1693
- status: 'pending',
1694
- timestamp: Date.now(),
1695
- });
1696
- }
1697
- /**
1698
- * A property write succeeded: add the property to its model's property ids, then drop the pending
1699
- * write. In that order, `Model.properties` (property ids + pending writes) never misses it; in Node,
1700
- * where the Model has no reactive liveQuery, nothing else would add it.
1701
- */
1702
- static async completePendingWrite(propertyFileId, modelId) {
1703
- try {
1704
- await main_cjs.Model.refreshPropertiesForDbId(modelId);
1705
- }
1706
- catch (error) {
1707
- logger(`Refreshing properties of model ${modelId} after writing "${propertyFileId}" failed: ${error}`);
1708
- }
1709
- this.clearPendingWrite(propertyFileId, 'success');
1710
- }
1711
- /**
1712
- * Clear or update pending write status
1713
- */
1714
- static clearPendingWrite(propertyFileId, status = 'success') {
1715
- const write = this.pendingWrites.get(propertyFileId);
1716
- if (write) {
1717
- if (status === 'success') {
1718
- // Remove successful writes from pendingWrites
1719
- this.pendingWrites.delete(propertyFileId);
1720
- logger(`Cleared pending write for property "${propertyFileId}" (status: success)`);
1721
- }
1722
- else {
1723
- // Update status to error but keep in map (for debugging/retry purposes)
1724
- write.status = 'error';
1725
- this.pendingWrites.set(propertyFileId, write);
1726
- logger(`Marked pending write as error for property "${propertyFileId}"`);
1727
- }
1728
- }
1729
- }
1730
- /**
1731
- * Get all pending property IDs for a model
1732
- */
1733
- static getPendingPropertyIds(modelId) {
1734
- return Array.from(this.pendingWrites.entries())
1735
- .filter(([_, write]) => write.modelId === modelId && write.status !== 'error')
1736
- .map(([propertyFileId]) => propertyFileId);
1737
- }
1738
- /**
1739
- * Get modelId for a property that has a pending write (row may not be in DB yet).
1740
- * Used to resolve modelName when validating a just-created property rename.
1741
- */
1742
- static getPendingModelId(propertyFileId) {
1743
- return this.pendingWrites.get(propertyFileId)?.modelId;
1744
- }
1745
- getService() {
1746
- return this._service;
1747
- }
1748
- _getSnapshot() {
1749
- return this._service.getSnapshot();
1750
- }
1751
- _getSnapshotContext() {
1752
- return this._getSnapshot().context;
1753
- }
1754
- get path() {
1755
- const workingDir = main_cjs.BaseFileManager.getWorkingDir();
1756
- if (!this.localStorageDir || !this.name || !this.filenameSuffix) {
1757
- return undefined;
1758
- }
1759
- return `${workingDir}/${this.localStorageDir}/${this.name}${this.filenameSuffix || ''}`;
1760
- }
1761
- get status() {
1762
- return this._getSnapshot().value;
1763
- }
1764
- get isEdited() {
1765
- const context = this._getSnapshotContext();
1766
- // First check in-memory state
1767
- if (context._isEdited !== undefined) {
1768
- return context._isEdited;
1769
- }
1770
- // Fall back to reading from database if we have _dbId
1771
- if (context._dbId) {
1772
- // Load from database asynchronously (fire-and-forget for now)
1773
- // For synchronous getter, we'll need to cache it or make it async
1774
- // For now, return false if not in context
1775
- return false;
1776
- }
1777
- return false;
1778
- }
1779
- get validationErrors() {
1780
- return this._getSnapshotContext()._validationErrors || [];
1781
- }
1782
- get isValid() {
1783
- const errors = this.validationErrors;
1784
- return errors.length === 0;
1785
- }
1786
- /**
1787
- * Validate the property
1788
- * @returns Validation result
1789
- */
1790
- async validate() {
1791
- return new Promise((resolve) => {
1792
- let resolved = false;
1793
- const subscription = this._service.subscribe((snapshot) => {
1794
- const state = snapshot.value;
1795
- // Wait for validation to complete (idle state after validating)
1796
- if (state === 'idle' && !resolved) {
1797
- resolved = true;
1798
- subscription.unsubscribe();
1799
- const errors = snapshot.context._validationErrors || [];
1800
- resolve({
1801
- isValid: errors.length === 0,
1802
- errors,
1803
- });
1804
- }
1805
- });
1806
- this._service.send({ type: 'validateProperty' });
1807
- // Timeout fallback
1808
- setTimeout(() => {
1809
- if (!resolved) {
1810
- resolved = true;
1811
- subscription.unsubscribe();
1812
- const errors = this._getSnapshotContext()._validationErrors || [];
1813
- resolve({
1814
- isValid: errors.length === 0,
1815
- errors,
1816
- });
1817
- }
1818
- }, 5000);
1819
- });
1820
- }
1821
- save() {
1822
- const snapshot = this._service.getSnapshot();
1823
- const isAlreadySaving = typeof snapshot.value === 'object' && snapshot.value !== null && 'saveToSchema' in snapshot.value;
1824
- if (isAlreadySaving) {
1825
- return;
1826
- }
1827
- const context = snapshot.context;
1828
- if (!context._isEdited)
1829
- return; // No changes to persist
1830
- // Validation will happen automatically in the machine before saving
1831
- this._service.send({
1832
- type: 'saveToSchema',
1833
- });
1834
- }
1835
- /**
1836
- * Reload property from database
1837
- * This refreshes the actor context with the latest data from the database
1838
- * Note: ModelProperty doesn't have a dedicated load actor, so this will
1839
- * re-initialize from the current property data
1840
- */
1841
- async reload() {
1842
- // ModelProperty doesn't have a separate load mechanism
1843
- // It's loaded as part of the Model/Schema
1844
- // This method is provided for API consistency
1845
- // To actually reload, you'd need to reload the parent Model or Schema
1846
- logger('ModelProperty.reload() called - ModelProperty is loaded as part of Model/Schema. Reload the parent Model or Schema instead.');
1847
- // No-op for now, but could be enhanced to reload from DB if needed
1848
- }
1849
- /**
1850
- * Force-evict cached ModelProperty instances for the given models, ignoring refCounts, and stop
1851
- * their services. Used by Schema.destroy() so a re-imported schema gets fresh instances instead of
1852
- * ones holding a deleted row's _dbId.
1853
- */
1854
- static evictForModels(modelNames, schemaName) {
1855
- if (modelNames.length === 0)
1856
- return;
1857
- const names = new Set(modelNames);
1858
- for (const [cacheKey, { instance }] of this.instanceCache.entries()) {
1859
- let context;
1860
- try {
1861
- context = instance._getSnapshotContext();
1862
- }
1863
- catch {
1864
- continue;
1865
- }
1866
- if (!context.modelName || !names.has(context.modelName))
1867
- continue;
1868
- if (schemaName && context._schemaName && context._schemaName !== schemaName)
1869
- continue;
1870
- this.instanceCache.delete(cacheKey);
1871
- try {
1872
- instance._service.stop();
1873
- }
1874
- catch {
1875
- // Service might already be stopped
1876
- }
1877
- }
1878
- }
1879
- unload() {
1880
- // ModelProperty doesn't have liveQuery subscriptions or complex cache management
1881
- // Just stop the service
1882
- try {
1883
- this._service.stop();
1884
- }
1885
- catch (error) {
1886
- // Service might already be stopped
1887
- }
1888
- }
1889
- /**
1890
- * Destroy the model property: remove from caches, delete from database, update Schema context, stop service.
1891
- */
1892
- async destroy() {
1893
- const context = this._getSnapshotContext();
1894
- // Stored under "modelName:name", or "id:<id>" when another schema's same-name property holds that key
1895
- const cacheKeys = [...ModelProperty.instanceCache.entries()]
1896
- .filter(([, entry]) => {
1897
- try {
1898
- return entry.instance._getSnapshotContext().id === context.id;
1899
- }
1900
- catch {
1901
- return false;
1902
- }
1903
- })
1904
- .map(([key]) => key);
1905
- if (cacheKeys.length === 0 && context.modelName && context.name) {
1906
- cacheKeys.push(`${context.modelName}:${context.name}`);
1907
- }
1908
- if (cacheKeys.length === 0)
1909
- return;
1910
- main_cjs.forceRemoveFromCaches(this, {
1911
- getCacheKeys: () => cacheKeys,
1912
- caches: [ModelProperty.instanceCache],
1913
- });
1914
- await main_cjs.runDestroyLifecycle(this, {
1915
- getService: (instance) => instance._service,
1916
- doDestroy: async () => {
1917
- const db = main_cjs.BaseDb.getAppDb();
1918
- let schemaName = context._schemaName;
1919
- const modelName = context.modelName;
1920
- const propertyName = context.name;
1921
- if (!modelName || !propertyName)
1922
- return;
1923
- // Resolve schema name from DB when _schemaName is missing (e.g. destroy ran before _setSchemaName finished)
1924
- if (!schemaName && db) {
1925
- schemaName = await this._resolveSchemaNameForDestroy(db, context);
1926
- }
1927
- if (db && schemaName) {
1928
- const propertyRecords = await db
1929
- .select({ propertyId: main_cjs.properties.id })
1930
- .from(main_cjs.properties)
1931
- .innerJoin(main_cjs.models, drizzleOrm.eq(main_cjs.properties.modelId, main_cjs.models.id))
1932
- .innerJoin(main_cjs.modelSchemas, drizzleOrm.eq(main_cjs.models.id, main_cjs.modelSchemas.modelId))
1933
- .innerJoin(main_cjs.schemas, drizzleOrm.eq(main_cjs.modelSchemas.schemaId, main_cjs.schemas.id))
1934
- .where(drizzleOrm.and(drizzleOrm.eq(main_cjs.schemas.name, schemaName), drizzleOrm.eq(main_cjs.models.name, modelName), drizzleOrm.eq(main_cjs.properties.name, propertyName)))
1935
- .limit(1);
1936
- if (propertyRecords.length > 0 && propertyRecords[0].propertyId != null) {
1937
- await db
1938
- .delete(main_cjs.properties)
1939
- .where(drizzleOrm.eq(main_cjs.properties.id, propertyRecords[0].propertyId));
1940
- }
1941
- }
1942
- if (schemaName) {
1943
- const schema = Schema.Schema.create(schemaName, { waitForReady: false });
1944
- const snapshot = schema.getService().getSnapshot();
1945
- const schemaContext = snapshot.context;
1946
- if (schemaContext.models?.[modelName]?.properties?.[propertyName]) {
1947
- const updatedModels = { ...schemaContext.models };
1948
- const updatedProperties = { ...updatedModels[modelName].properties };
1949
- delete updatedProperties[propertyName];
1950
- updatedModels[modelName] = { ...updatedModels[modelName], properties: updatedProperties };
1951
- schema.getService().send({ type: 'updateContext', models: updatedModels });
1952
- schema.getService().send({ type: 'markAsDraft', propertyKey: `property:${modelName}:${propertyName}` });
1953
- }
1954
- }
1955
- },
1956
- });
1957
- }
1958
- }
1959
- ModelProperty.instanceCache = new Map();
1960
- /**
1961
- * propertyFileId -> where the instance with that id is cached, so getById doesn't scan the cache
1962
- * (a model's properties are looked up one by one, which made loading one model O(n²)).
1963
- * Every cached instance's current id has an entry: it's added when the instance is cached and
1964
- * again whenever its context id changes (a property is often created with a generated id and
1965
- * then gets its real one). Entries aren't removed when an instance leaves the cache or changes
1966
- * id; getById checks an entry before using it.
1967
- */
1968
- ModelProperty.idIndex = new Map();
1969
- // Pending writes tracking
1970
- ModelProperty.pendingWrites = new Map();
1971
-
1972
- var ModelProperty$1 = /*#__PURE__*/Object.freeze({
1973
- __proto__: null,
1974
- ModelProperty: ModelProperty
1975
- });
1976
-
1977
- exports.ModelProperty = ModelProperty;
1978
- //# sourceMappingURL=ModelProperty-DXZ39Wyv.js.map