@seedprotocol/sdk 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +38 -348
  2. package/dist/{ArweaveClient-CleX_4Gw.js → ArweaveClient-CgWK-JgT.js} +8 -8
  3. package/dist/{ArweaveClient-CleX_4Gw.js.map → ArweaveClient-CgWK-JgT.js.map} +1 -1
  4. package/dist/{ArweaveClient-BvJ1FhQ5.js → ArweaveClient-WcG8CZAE.js} +8 -8
  5. package/dist/{ArweaveClient-BvJ1FhQ5.js.map → ArweaveClient-WcG8CZAE.js.map} +1 -1
  6. package/dist/{Db-DX08SxS9.js → Db-DjFdIdR9.js} +9 -16
  7. package/dist/{Db-DX08SxS9.js.map → Db-DjFdIdR9.js.map} +1 -1
  8. package/dist/{Db-BPnO1-_p.js → Db-DjofXdeU.js} +9 -9
  9. package/dist/{Db-BPnO1-_p.js.map → Db-DjofXdeU.js.map} +1 -1
  10. package/dist/{EasClient-BwhUcPjY.js → EasClient-Aojewp6P.js} +8 -8
  11. package/dist/{EasClient-CJSs38Db.js.map → EasClient-Aojewp6P.js.map} +1 -1
  12. package/dist/{EasClient-CJSs38Db.js → EasClient-BVFXp2O6.js} +8 -8
  13. package/dist/{EasClient-BwhUcPjY.js.map → EasClient-BVFXp2O6.js.map} +1 -1
  14. package/dist/{FileManager-B1tdLMsX.js → FileManager-C9zr4AJe.js} +8 -8
  15. package/dist/{FileManager-B1tdLMsX.js.map → FileManager-C9zr4AJe.js.map} +1 -1
  16. package/dist/{FileManager-Ct91ZhOE.js → FileManager-CxGJLw5C.js} +8 -8
  17. package/dist/{FileManager-Ct91ZhOE.js.map → FileManager-CxGJLw5C.js.map} +1 -1
  18. package/dist/Item/Item.d.ts +28 -7
  19. package/dist/Item/Item.d.ts.map +1 -1
  20. package/dist/Item/service/actors/runPublish.d.ts +5 -0
  21. package/dist/Item/service/actors/runPublish.d.ts.map +1 -0
  22. package/dist/Item/service/itemMachineSingle.d.ts +10 -5
  23. package/dist/Item/service/itemMachineSingle.d.ts.map +1 -1
  24. package/dist/ItemProperty/ItemProperty.d.ts +30 -5
  25. package/dist/ItemProperty/ItemProperty.d.ts.map +1 -1
  26. package/dist/ItemProperty/service/actors/loadOrCreateProperty.d.ts.map +1 -1
  27. package/dist/ItemProperty/service/propertyMachine.d.ts +10 -10
  28. package/dist/ItemProperty/service/propertyMachine.d.ts.map +1 -1
  29. package/dist/Model/Model.d.ts +27 -20
  30. package/dist/Model/Model.d.ts.map +1 -1
  31. package/dist/Model/index.d.ts +1 -1
  32. package/dist/Model/service/actors/createModelProperties.d.ts.map +1 -1
  33. package/dist/Model/service/actors/loadOrCreateModel.d.ts.map +1 -1
  34. package/dist/Model/service/actors/validateModel.d.ts.map +1 -1
  35. package/dist/Model/service/modelMachine.d.ts +18 -3
  36. package/dist/Model/service/modelMachine.d.ts.map +1 -1
  37. package/dist/ModelProperty/ModelProperty.d.ts +25 -2
  38. package/dist/ModelProperty/ModelProperty.d.ts.map +1 -1
  39. package/dist/ModelProperty/service/actors/compareAndMarkDraft.d.ts.map +1 -1
  40. package/dist/ModelProperty/service/actors/saveToSchema.d.ts.map +1 -1
  41. package/dist/ModelProperty/service/actors/validateProperty.d.ts.map +1 -1
  42. package/dist/ModelProperty/service/modelPropertyMachine.d.ts +17 -3
  43. package/dist/ModelProperty/service/modelPropertyMachine.d.ts.map +1 -1
  44. package/dist/{ModelProperty-Cr3BmgkC.js → ModelProperty-CGdkocQ8.js} +349 -817
  45. package/dist/ModelProperty-CGdkocQ8.js.map +1 -0
  46. package/dist/{PathResolver-DJdxE_OK.js → PathResolver-CX6GHoTS.js} +8 -8
  47. package/dist/{PathResolver-DJdxE_OK.js.map → PathResolver-CX6GHoTS.js.map} +1 -1
  48. package/dist/{PathResolver-BErmcZqP.js → PathResolver-z_WX47_o.js} +8 -8
  49. package/dist/{PathResolver-BErmcZqP.js.map → PathResolver-z_WX47_o.js.map} +1 -1
  50. package/dist/{QueryClient-DIu9c-w6.js → QueryClient-ByKPdRmE.js} +8 -8
  51. package/dist/{QueryClient-DIu9c-w6.js.map → QueryClient-ByKPdRmE.js.map} +1 -1
  52. package/dist/{QueryClient-D2mv63gP.js → QueryClient-Cb1iJO-x.js} +8 -8
  53. package/dist/{QueryClient-D2mv63gP.js.map → QueryClient-Cb1iJO-x.js.map} +1 -1
  54. package/dist/Schema/Schema.d.ts +24 -3
  55. package/dist/Schema/Schema.d.ts.map +1 -1
  56. package/dist/Schema/service/actors/checkExistingSchema.d.ts.map +1 -1
  57. package/dist/Schema/service/actors/createPropertyInstances.d.ts.map +1 -1
  58. package/dist/Schema/service/actors/loadOrCreateSchema.d.ts.map +1 -1
  59. package/dist/Schema/service/actors/verifyPropertyInstancesInCache.d.ts.map +1 -1
  60. package/dist/Schema/service/actors/writeModelsToDb.d.ts.map +1 -1
  61. package/dist/Schema/service/actors/writePropertiesToDb.d.ts.map +1 -1
  62. package/dist/Schema/service/actors/writeSchemaToDb.d.ts.map +1 -1
  63. package/dist/Schema/service/addModelsMachine.d.ts.map +1 -1
  64. package/dist/Schema/service/schemaMachine.d.ts +17 -3
  65. package/dist/Schema/service/schemaMachine.d.ts.map +1 -1
  66. package/dist/{Schema-DeKabJ0T.js → Schema-D1eqDHyt.js} +995 -186
  67. package/dist/Schema-D1eqDHyt.js.map +1 -0
  68. package/dist/{SchemaValidationService-cTlURuDt.js → SchemaValidationService-DyttFaV_.js} +7 -7
  69. package/dist/{SchemaValidationService-cTlURuDt.js.map → SchemaValidationService-DyttFaV_.js.map} +1 -1
  70. package/dist/browser/db/Db.d.ts.map +1 -1
  71. package/dist/browser/react/SeedProvider.d.ts +30 -0
  72. package/dist/browser/react/SeedProvider.d.ts.map +1 -0
  73. package/dist/browser/react/index.d.ts +4 -1
  74. package/dist/browser/react/index.d.ts.map +1 -1
  75. package/dist/browser/react/item.d.ts +10 -6
  76. package/dist/browser/react/item.d.ts.map +1 -1
  77. package/dist/browser/react/itemProperty.d.ts +37 -1
  78. package/dist/browser/react/itemProperty.d.ts.map +1 -1
  79. package/dist/browser/react/liveQuery.d.ts.map +1 -1
  80. package/dist/browser/react/model.d.ts +21 -7
  81. package/dist/browser/react/model.d.ts.map +1 -1
  82. package/dist/browser/react/modelProperty.d.ts +23 -0
  83. package/dist/browser/react/modelProperty.d.ts.map +1 -1
  84. package/dist/browser/react/queryClient.d.ts +28 -0
  85. package/dist/browser/react/queryClient.d.ts.map +1 -0
  86. package/dist/browser/react/schema.d.ts +8 -0
  87. package/dist/browser/react/schema.d.ts.map +1 -1
  88. package/dist/browser/react/trash.d.ts +5 -2
  89. package/dist/browser/react/trash.d.ts.map +1 -1
  90. package/dist/cjs/{ModelProperty-MkN5Rmx7.js → ModelProperty-BeJvgKMw.js} +377 -477
  91. package/dist/cjs/ModelProperty-BeJvgKMw.js.map +1 -0
  92. package/dist/cjs/{Schema-B5cr_JVK.js → Schema-CVs9J6eP.js} +709 -263
  93. package/dist/cjs/Schema-CVs9J6eP.js.map +1 -0
  94. package/dist/cjs/{SchemaValidationService-BgIzc3-r.js → SchemaValidationService-CDKcVRFQ.js} +4 -4
  95. package/dist/cjs/{SchemaValidationService-BgIzc3-r.js.map → SchemaValidationService-CDKcVRFQ.js.map} +1 -1
  96. package/dist/cjs/{getItem-CVJJPky2.js → getItem-B5RYPvrG.js} +4 -4
  97. package/dist/cjs/{getItem-CVJJPky2.js.map → getItem-B5RYPvrG.js.map} +1 -1
  98. package/dist/cjs/{getPublishPayload-DbOc3WA-.js → getPublishPayload-BD1qRob1.js} +26 -11
  99. package/dist/cjs/getPublishPayload-BD1qRob1.js.map +1 -0
  100. package/dist/cjs/{getPublishUploads-NzioLz-3.js → getPublishUploads-CnC9aYxs.js} +5 -5
  101. package/dist/cjs/getPublishUploads-CnC9aYxs.js.map +1 -0
  102. package/dist/cjs/{getSegmentedItemProperties-BsaklLwI.js → getSegmentedItemProperties-B_njnntx.js} +2 -2
  103. package/dist/cjs/{getSegmentedItemProperties-BsaklLwI.js.map → getSegmentedItemProperties-B_njnntx.js.map} +1 -1
  104. package/dist/cjs/{index-BmIVfqGN.js → index-BeKPbbk0.js} +12715 -12384
  105. package/dist/cjs/index-BeKPbbk0.js.map +1 -0
  106. package/dist/cjs/{index-C_0angRB.js → index-Dnywap_P.js} +4 -4
  107. package/dist/cjs/index-Dnywap_P.js.map +1 -0
  108. package/dist/client/actors/platformClassesInit.d.ts.map +1 -1
  109. package/dist/client/actors/processSchemaFiles.d.ts.map +1 -1
  110. package/dist/client/actors/saveAppState.d.ts.map +1 -1
  111. package/dist/db/read/getItemData.d.ts.map +1 -1
  112. package/dist/db/read/getItems.d.ts.map +1 -1
  113. package/dist/db/read/getModelPropertiesData.d.ts +19 -0
  114. package/dist/db/read/getModelPropertiesData.d.ts.map +1 -0
  115. package/dist/db/read/getModelsData.d.ts +15 -0
  116. package/dist/db/read/getModelsData.d.ts.map +1 -0
  117. package/dist/db/read/getPublishPayload.d.ts.map +1 -1
  118. package/dist/db/read/getPublishUploads.d.ts +1 -7
  119. package/dist/db/read/getPublishUploads.d.ts.map +1 -1
  120. package/dist/db/read/getSchemaUidForModel.d.ts.map +1 -1
  121. package/dist/db/write/updateSeedUid.d.ts +7 -0
  122. package/dist/db/write/updateSeedUid.d.ts.map +1 -0
  123. package/dist/eas.d.ts.map +1 -1
  124. package/dist/events/item/index.d.ts.map +1 -1
  125. package/dist/events/item/syncDbWithEas.d.ts.map +1 -1
  126. package/dist/{getItem-CcttmUY_.js → getItem-BB5HBCbK.js} +8 -8
  127. package/dist/{getItem-CcttmUY_.js.map → getItem-BB5HBCbK.js.map} +1 -1
  128. package/dist/{getPublishPayload-NFpqbd_H.js → getPublishPayload-uLm0AqN_.js} +29 -14
  129. package/dist/getPublishPayload-uLm0AqN_.js.map +1 -0
  130. package/dist/{getPublishUploads-Cpb9vgwE.js → getPublishUploads-Dc-HqhO8.js} +9 -9
  131. package/dist/getPublishUploads-Dc-HqhO8.js.map +1 -0
  132. package/dist/{getSegmentedItemProperties-DiyQPMgI.js → getSegmentedItemProperties-BrIqFNfD.js} +2 -2
  133. package/dist/{getSegmentedItemProperties-DiyQPMgI.js.map → getSegmentedItemProperties-BrIqFNfD.js.map} +1 -1
  134. package/dist/helpers/db.d.ts +12 -0
  135. package/dist/helpers/db.d.ts.map +1 -1
  136. package/dist/helpers/entity/entityDestroy.d.ts +41 -0
  137. package/dist/helpers/entity/entityDestroy.d.ts.map +1 -0
  138. package/dist/helpers/entity/index.d.ts +1 -0
  139. package/dist/helpers/entity/index.d.ts.map +1 -1
  140. package/dist/helpers/index.d.ts +1 -0
  141. package/dist/helpers/index.d.ts.map +1 -1
  142. package/dist/helpers/property/index.d.ts +12 -12
  143. package/dist/helpers/property/index.d.ts.map +1 -1
  144. package/dist/helpers/reactiveProxy.d.ts.map +1 -1
  145. package/dist/helpers/schema.d.ts.map +1 -1
  146. package/dist/helpers/updateSchema.d.ts +9 -0
  147. package/dist/helpers/updateSchema.d.ts.map +1 -1
  148. package/dist/helpers/waitForEntityIdle.d.ts +2 -2
  149. package/dist/helpers/waitForEntityIdle.d.ts.map +1 -1
  150. package/dist/imports/json.d.ts.map +1 -1
  151. package/dist/{index-r45w9hEq.js → index-2FcQHgKp.js} +2 -2
  152. package/dist/index-2FcQHgKp.js.map +1 -0
  153. package/dist/{json-I3vJhXo8.js → index-DPll6EAp.js} +12450 -12121
  154. package/dist/index-DPll6EAp.js.map +1 -0
  155. package/dist/{index-CRuq6HVi.js → index-LEY0Og1p.js} +9 -9
  156. package/dist/index-LEY0Og1p.js.map +1 -0
  157. package/dist/index.d.ts +3 -1
  158. package/dist/index.d.ts.map +1 -1
  159. package/dist/interfaces/IItem.d.ts +2 -0
  160. package/dist/interfaces/IItem.d.ts.map +1 -1
  161. package/dist/interfaces/IItemProperty.d.ts +1 -0
  162. package/dist/interfaces/IItemProperty.d.ts.map +1 -1
  163. package/dist/main.cjs +3 -3
  164. package/dist/main.js +999 -1033
  165. package/dist/main.js.map +1 -1
  166. package/dist/node.js +16 -16
  167. package/dist/node.js.map +1 -1
  168. package/dist/{property-Dy09KTxg.js → property-B15X7jLX.js} +7 -5
  169. package/dist/property-B15X7jLX.js.map +1 -0
  170. package/dist/{queries-LZYSuhtz.js → queries-BPDSpiEX.js} +2 -2
  171. package/dist/{queries-LZYSuhtz.js.map → queries-BPDSpiEX.js.map} +1 -1
  172. package/dist/services/write/actors/validateEntity.d.ts.map +1 -1
  173. package/dist/services/write/actors/writeToDatabase.d.ts.map +1 -1
  174. package/dist/services/write/writeProcessMachine.d.ts +1 -1
  175. package/dist/types/index.d.ts +9 -0
  176. package/dist/types/index.d.ts.map +1 -1
  177. package/dist/types/item.d.ts +12 -0
  178. package/dist/types/item.d.ts.map +1 -1
  179. package/dist/types/property.d.ts +6 -0
  180. package/dist/types/property.d.ts.map +1 -1
  181. package/dist/types/publish.d.ts +9 -0
  182. package/dist/types/publish.d.ts.map +1 -0
  183. package/package.json +12 -4
  184. package/dist/ModelProperty-Cr3BmgkC.js.map +0 -1
  185. package/dist/Schema-DeKabJ0T.js.map +0 -1
  186. package/dist/cjs/ModelProperty-MkN5Rmx7.js.map +0 -1
  187. package/dist/cjs/Schema-B5cr_JVK.js.map +0 -1
  188. package/dist/cjs/getPublishPayload-DbOc3WA-.js.map +0 -1
  189. package/dist/cjs/getPublishUploads-NzioLz-3.js.map +0 -1
  190. package/dist/cjs/index-BmIVfqGN.js.map +0 -1
  191. package/dist/cjs/index-C_0angRB.js.map +0 -1
  192. package/dist/events/item/publish.d.ts +0 -7
  193. package/dist/events/item/publish.d.ts.map +0 -1
  194. package/dist/getPublishPayload-NFpqbd_H.js.map +0 -1
  195. package/dist/getPublishUploads-Cpb9vgwE.js.map +0 -1
  196. package/dist/index-CRuq6HVi.js.map +0 -1
  197. package/dist/index-r45w9hEq.js.map +0 -1
  198. package/dist/json-I3vJhXo8.js.map +0 -1
  199. package/dist/property-Dy09KTxg.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"Db-DX08SxS9.js","sources":["../src/browser/db/drizzleFiles.ts","../src/browser/db/Db.ts"],"sourcesContent":["// This file embeds the drizzle migration files as strings for browser runtime\n// These files are copied from src/db/drizzle at build time\n\n// Individual migration SQL files\nexport const migrationSql_0000_married_malice = `CREATE TABLE \\`appState\\` (\n\t\\`key\\` text,\n\t\\`value\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`appState_key_unique\\` ON \\`appState\\` (\\`key\\`);--> statement-breakpoint\nCREATE TABLE \\`config\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`key\\` text NOT NULL,\n\t\\`text\\` text,\n\t\\`json\\` text,\n\t\\`blob\\` blob\n);\n--> statement-breakpoint\nCREATE TABLE \\`metadata\\` (\n\t\\`local_id\\` text,\n\t\\`uid\\` text,\n\t\\`property_name\\` text,\n\t\\`property_value\\` text,\n\t\\`schema_uid\\` text,\n\t\\`model_type\\` text,\n\t\\`seed_local_id\\` text,\n\t\\`seed_uid\\` text,\n\t\\`version_local_id\\` text,\n\t\\`version_uid\\` text,\n\t\\`eas_data_type\\` text,\n\t\\`ref_value_type\\` text,\n\t\\`ref_schema_uid\\` text,\n\t\\`ref_seed_type\\` text,\n\t\\`ref_resolved_value\\` text,\n\t\\`ref_resolved_display_value\\` text,\n\t\\`local_storage_dir\\` text,\n\t\\`attestation_raw\\` text,\n\t\\`attestation_created_at\\` integer,\n\t\\`content_hash\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`metadata_local_id_unique\\` ON \\`metadata\\` (\\`local_id\\`);--> statement-breakpoint\nCREATE TABLE \\`models\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`name\\` text NOT NULL,\n\t\\`schema_file_id\\` text\n);\n--> statement-breakpoint\nCREATE TABLE \\`properties\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`name\\` text NOT NULL,\n\t\\`data_type\\` text NOT NULL,\n\t\\`model_id\\` integer NOT NULL,\n\t\\`ref_model_id\\` integer,\n\t\\`ref_value_type\\` text,\n\t\\`schema_file_id\\` text,\n\tFOREIGN KEY (\\`model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (\\`ref_model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`unique_name_model_id\\` ON \\`properties\\` (\\`name\\`,\\`model_id\\`);--> statement-breakpoint\nCREATE TABLE \\`model_schemas\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`model_id\\` integer,\n\t\\`schema_id\\` integer,\n\tFOREIGN KEY (\\`model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (\\`schema_id\\`) REFERENCES \\`schemas\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE TABLE \\`model_uids\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`uid\\` text NOT NULL,\n\t\\`model_id\\` integer NOT NULL,\n\tFOREIGN KEY (\\`model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`model_uids_model_id_unique\\` ON \\`model_uids\\` (\\`model_id\\`);--> statement-breakpoint\nCREATE TABLE \\`property_uids\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`uid\\` text NOT NULL,\n\t\\`property_id\\` integer NOT NULL,\n\tFOREIGN KEY (\\`property_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`property_uids_property_id_unique\\` ON \\`property_uids\\` (\\`property_id\\`);--> statement-breakpoint\nCREATE TABLE \\`schemas\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`name\\` text NOT NULL,\n\t\\`version\\` integer NOT NULL,\n\t\\`schema_file_id\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer\n);\n--> statement-breakpoint\nCREATE TABLE \\`seeds\\` (\n\t\\`local_id\\` text,\n\t\\`uid\\` text,\n\t\\`schema_uid\\` text,\n\t\\`type\\` text,\n\t\\`attestation_raw\\` text,\n\t\\`attestation_created_at\\` integer,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer,\n\t\\`_marked_for_deletion\\` integer\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`seeds_local_id_unique\\` ON \\`seeds\\` (\\`local_id\\`);--> statement-breakpoint\nCREATE TABLE \\`versions\\` (\n\t\\`local_id\\` text,\n\t\\`uid\\` text,\n\t\\`seed_local_id\\` text,\n\t\\`seed_uid\\` text,\n\t\\`seed_type\\` text,\n\t\\`note\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer,\n\t\\`attestation_created_at\\` integer,\n\t\\`attestation_raw\\` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`versions_local_id_unique\\` ON \\`versions\\` (\\`local_id\\`);`\n\nexport const migrationSql_0001_sweet_bruce_banner = `ALTER TABLE \\`schemas\\` ADD \\`schema_data\\` text;--> statement-breakpoint\nALTER TABLE \\`schemas\\` ADD \\`is_draft\\` integer;`\n\nexport const migrationSql_0002_bitter_proudstar = `CREATE UNIQUE INDEX \\`unique_schema_file_id\\` ON \\`models\\` (\\`schema_file_id\\`);--> statement-breakpoint\nCREATE UNIQUE INDEX \\`unique_property_schema_file_id\\` ON \\`properties\\` (\\`schema_file_id\\`);--> statement-breakpoint\nCREATE UNIQUE INDEX \\`unique_schema_schema_file_id\\` ON \\`schemas\\` (\\`schema_file_id\\`);`\n\nexport const migrationSql_0003_cultured_senator_kelly = `ALTER TABLE \\`models\\` ADD \\`is_edited\\` integer;--> statement-breakpoint\nALTER TABLE \\`properties\\` ADD \\`is_edited\\` integer;--> statement-breakpoint\nALTER TABLE \\`schemas\\` ADD \\`is_edited\\` integer;`\n\n// Journal JSON file\nexport const journalJson = `{\n \"version\": \"7\",\n \"dialect\": \"sqlite\",\n \"entries\": [\n {\n \"idx\": 0,\n \"version\": \"6\",\n \"when\": 1765976502903,\n \"tag\": \"0000_married_malice\",\n \"breakpoints\": true\n },\n {\n \"idx\": 1,\n \"version\": \"6\",\n \"when\": 1766010851770,\n \"tag\": \"0001_sweet_bruce_banner\",\n \"breakpoints\": true\n },\n {\n \"idx\": 2,\n \"version\": \"6\",\n \"when\": 1767621120087,\n \"tag\": \"0002_bitter_proudstar\",\n \"breakpoints\": true\n },\n {\n \"idx\": 3,\n \"version\": \"6\",\n \"when\": 1768415440282,\n \"tag\": \"0003_cultured_senator_kelly\",\n \"breakpoints\": true\n }\n ]\n}`\n\n// Snapshot JSON file - this is large, so we'll import it dynamically if needed\n// For now, we'll read it from the actual file if ?raw works, otherwise we'll need to embed it\nexport const snapshotJson = `{\n \"version\": \"6\",\n \"dialect\": \"sqlite\",\n \"id\": \"0e6a6a99-2eb1-4b1d-815b-3d45dcae04a1\",\n \"prevId\": \"49b9a020-1b1c-4107-85ee-a5f8a958f1a2\",\n \"tables\": {\n \"appState\": {\n \"name\": \"appState\",\n \"columns\": {\n \"key\": {\n \"name\": \"key\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"value\": {\n \"name\": \"value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"appState_key_unique\": {\n \"name\": \"appState_key_unique\",\n \"columns\": [\n \"key\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"config\": {\n \"name\": \"config\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"key\": {\n \"name\": \"key\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"text\": {\n \"name\": \"text\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"json\": {\n \"name\": \"json\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"blob\": {\n \"name\": \"blob\",\n \"type\": \"blob\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {},\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"metadata\": {\n \"name\": \"metadata\",\n \"columns\": {\n \"local_id\": {\n \"name\": \"local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"property_name\": {\n \"name\": \"property_name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"property_value\": {\n \"name\": \"property_value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_uid\": {\n \"name\": \"schema_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"model_type\": {\n \"name\": \"model_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_local_id\": {\n \"name\": \"seed_local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_uid\": {\n \"name\": \"seed_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"version_local_id\": {\n \"name\": \"version_local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"version_uid\": {\n \"name\": \"version_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"eas_data_type\": {\n \"name\": \"eas_data_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_value_type\": {\n \"name\": \"ref_value_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_schema_uid\": {\n \"name\": \"ref_schema_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_seed_type\": {\n \"name\": \"ref_seed_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_resolved_value\": {\n \"name\": \"ref_resolved_value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_resolved_display_value\": {\n \"name\": \"ref_resolved_display_value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"local_storage_dir\": {\n \"name\": \"local_storage_dir\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_raw\": {\n \"name\": \"attestation_raw\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_created_at\": {\n \"name\": \"attestation_created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"content_hash\": {\n \"name\": \"content_hash\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"metadata_local_id_unique\": {\n \"name\": \"metadata_local_id_unique\",\n \"columns\": [\n \"local_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"models\": {\n \"name\": \"models\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"name\": {\n \"name\": \"name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"schema_file_id\": {\n \"name\": \"schema_file_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_edited\": {\n \"name\": \"is_edited\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"unique_schema_file_id\": {\n \"name\": \"unique_schema_file_id\",\n \"columns\": [\n \"schema_file_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"properties\": {\n \"name\": \"properties\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"name\": {\n \"name\": \"name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"data_type\": {\n \"name\": \"data_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"model_id\": {\n \"name\": \"model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"ref_model_id\": {\n \"name\": \"ref_model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_value_type\": {\n \"name\": \"ref_value_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_file_id\": {\n \"name\": \"schema_file_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_edited\": {\n \"name\": \"is_edited\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"unique_name_model_id\": {\n \"name\": \"unique_name_model_id\",\n \"columns\": [\n \"name\",\n \"model_id\"\n ],\n \"isUnique\": true\n },\n \"unique_property_schema_file_id\": {\n \"name\": \"unique_property_schema_file_id\",\n \"columns\": [\n \"schema_file_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {\n \"properties_model_id_models_id_fk\": {\n \"name\": \"properties_model_id_models_id_fk\",\n \"tableFrom\": \"properties\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n },\n \"properties_ref_model_id_models_id_fk\": {\n \"name\": \"properties_ref_model_id_models_id_fk\",\n \"tableFrom\": \"properties\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"ref_model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"model_schemas\": {\n \"name\": \"model_schemas\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"model_id\": {\n \"name\": \"model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_id\": {\n \"name\": \"schema_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {},\n \"foreignKeys\": {\n \"model_schemas_model_id_models_id_fk\": {\n \"name\": \"model_schemas_model_id_models_id_fk\",\n \"tableFrom\": \"model_schemas\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n },\n \"model_schemas_schema_id_schemas_id_fk\": {\n \"name\": \"model_schemas_schema_id_schemas_id_fk\",\n \"tableFrom\": \"model_schemas\",\n \"tableTo\": \"schemas\",\n \"columnsFrom\": [\n \"schema_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"model_uids\": {\n \"name\": \"model_uids\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"model_id\": {\n \"name\": \"model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"model_uids_model_id_unique\": {\n \"name\": \"model_uids_model_id_unique\",\n \"columns\": [\n \"model_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {\n \"model_uids_model_id_models_id_fk\": {\n \"name\": \"model_uids_model_id_models_id_fk\",\n \"tableFrom\": \"model_uids\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"property_uids\": {\n \"name\": \"property_uids\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"property_id\": {\n \"name\": \"property_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"property_uids_property_id_unique\": {\n \"name\": \"property_uids_property_id_unique\",\n \"columns\": [\n \"property_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {\n \"property_uids_property_id_models_id_fk\": {\n \"name\": \"property_uids_property_id_models_id_fk\",\n \"tableFrom\": \"property_uids\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"property_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"schemas\": {\n \"name\": \"schemas\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"name\": {\n \"name\": \"name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"version\": {\n \"name\": \"version\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"schema_file_id\": {\n \"name\": \"schema_file_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_data\": {\n \"name\": \"schema_data\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_draft\": {\n \"name\": \"is_draft\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_edited\": {\n \"name\": \"is_edited\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"unique_schema_schema_file_id\": {\n \"name\": \"unique_schema_schema_file_id\",\n \"columns\": [\n \"schema_file_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"seeds\": {\n \"name\": \"seeds\",\n \"columns\": {\n \"local_id\": {\n \"name\": \"local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_uid\": {\n \"name\": \"schema_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"type\": {\n \"name\": \"type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_raw\": {\n \"name\": \"attestation_raw\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_created_at\": {\n \"name\": \"attestation_created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"_marked_for_deletion\": {\n \"name\": \"_marked_for_deletion\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"seeds_local_id_unique\": {\n \"name\": \"seeds_local_id_unique\",\n \"columns\": [\n \"local_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"versions\": {\n \"name\": \"versions\",\n \"columns\": {\n \"local_id\": {\n \"name\": \"local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_local_id\": {\n \"name\": \"seed_local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_uid\": {\n \"name\": \"seed_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_type\": {\n \"name\": \"seed_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"note\": {\n \"name\": \"note\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_created_at\": {\n \"name\": \"attestation_created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_raw\": {\n \"name\": \"attestation_raw\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"versions_local_id_unique\": {\n \"name\": \"versions_local_id_unique\",\n \"columns\": [\n \"local_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n }\n },\n \"views\": {},\n \"enums\": {},\n \"_meta\": {\n \"schemas\": {},\n \"tables\": {},\n \"columns\": {}\n },\n \"internal\": {\n \"indexes\": {}\n }\n}`\n","import { BaseDb } from \"@/db/Db/BaseDb\";\nimport { IDb } from \"@/interfaces/IDb\";\nimport debug from \"debug\";\nimport { sql } from \"drizzle-orm\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { drizzle, SqliteRemoteDatabase } from \"drizzle-orm/sqlite-proxy\";\nimport { migrate as drizzleMigrate } from \"drizzle-orm/sqlite-proxy/migrator\";\nimport { BROWSER_FS_TOP_DIR } from \"@/client/constants\";\nimport { BaseFileManager } from \"@/helpers\";\nimport * as schema from '@/seedSchema'\n// @ts-ignore - sqlocal/drizzle types may not be available during build\nimport { SQLocalDrizzle } from 'sqlocal/drizzle'\nimport {} from 'sqlocal'\nimport * as drizzleFiles from './drizzleFiles'\nimport { journalJson, snapshotJson } from './drizzleFiles'\nimport { Observable, distinctUntilChanged } from 'rxjs'\n\nconst logger = debug('seedSdk:browser:db:Db')\n\n\nclass Db extends BaseDb implements IDb {\n\n static sqliteWasmClient: any\n static filesDir: string | undefined\n static pathToDb: string | undefined\n static dbId: string | undefined\n static appDb: SqliteRemoteDatabase<Record<string, unknown>> | undefined\n static sqlocalInstance: SQLocalDrizzle | undefined\n\n constructor() {\n super()\n }\n\n static getAppDb() {\n return this.appDb\n }\n\n static isAppDbReady() {\n return !!this.appDb\n }\n\n static async prepareDb(filesDir: string) {\n\n logger('[Db.prepareDb] preparing database')\n\n this.filesDir = filesDir\n\n try {\n // Copy drizzle migration files from src/db/drizzle to filesDir/db\n await this.copyDrizzleFiles(filesDir)\n\n // Ensure meta directory exists\n const metaDirPath = `${filesDir}/db/meta`\n await BaseFileManager.createDirIfNotExists(metaDirPath)\n\n // Ensure _journal.json file exists in meta directory\n const journalFilePath = `${metaDirPath}/_journal.json`\n const journalExists = await BaseFileManager.pathExists(journalFilePath)\n if (!journalExists) {\n await BaseFileManager.saveFile(journalFilePath, JSON.stringify({\n version: 1,\n dialect: 'sqlite',\n entries: [],\n }, null, 2))\n }\n\n // Wait for journal file to be fully written before proceeding with migration\n // This is critical in browser/OPFS where writes may not be immediately readable\n logger('[Db.prepareDb] waiting for journal file to be fully written...')\n await BaseFileManager.waitForFileWithContent(journalFilePath, 100, 5000)\n logger('[Db.prepareDb] journal file is ready')\n\n // Initialize SQLocalDrizzle with reactive: true to enable reactive queries\n const sqlocalDrizzle = new SQLocalDrizzle({\n databasePath: `${this.filesDir}/db/seed.db`,\n reactive: true // Enable reactive queries\n })\n \n const { driver, batchDriver } = sqlocalDrizzle\n \n // Store SQLocalDrizzle instance for reactive queries\n this.sqlocalInstance = sqlocalDrizzle\n\n this.appDb = drizzle(\n driver, \n batchDriver, \n { \n schema, \n })\n\n logger('[Db.prepareDb] database prepared')\n\n await this.migrate()\n\n return this.appDb\n } catch (error) {\n logger('[Db.prepareDb] error', JSON.stringify(error))\n throw error\n }\n }\n\n // static async prepareDb(filesDir: string) {\n // console.log('prepareDb', filesDir)\n // if (Db.sqliteWasmClient) {\n // return this.dbId\n // }\n\n // this.filesDir = filesDir\n // this.pathToDb = `${filesDir}/db/${DB_NAME_APP}.db`\n\n // if (typeof document === 'undefined') {\n // return\n // }\n\n // let promiser\n\n // try {\n\n // let sqlite3Worker1Promiser\n\n // const sqliteWasm = await import('@sqlite.org/sqlite-wasm')\n\n // if (sqliteWasm && sqliteWasm.sqlite3Worker1Promiser) {\n // sqlite3Worker1Promiser = sqliteWasm.sqlite3Worker1Promiser\n // }\n\n // if (!sqlite3Worker1Promiser && window.sqlite3Worker1Promiser) {\n // sqlite3Worker1Promiser = window.sqlite3Worker1Promiser\n // }\n\n // if (!sqlite3Worker1Promiser) {\n // throw new Error('Failed to load sqlite3Worker1Promiser')\n // }\n\n // promiser = await new Promise<(event: string, config: Record<string, unknown>) => Promise<any>>((resolve) => {\n // const _promiser = sqlite3Worker1Promiser({\n // onready: () => {\n // resolve(_promiser);\n // },\n // });\n // }).catch((error) => {\n // console.error('Error from sqlite proxy server: ', JSON.stringify(error))\n // });\n\n // } catch ( e ) {\n // console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n // }\n\n\n // if (!promiser) {\n // throw new Error('Failed to create promiser')\n // }\n\n // this.sqliteWasmClient = promiser\n\n // const responseGet = await this.sqliteWasmClient('config-get', {});\n\n // logger('[Db.prepareDb] Running SQLite3 version', responseGet.result.version.libVersion);\n\n // const responseOpen = await this.sqliteWasmClient('open', {\n // filename: `file:${filesDir}/db/${DB_NAME_APP}.db?vfs=opfs`,\n // });\n // const { dbId } = responseOpen;\n // logger(\n // '[Db.prepareDb] OPFS is available, created persisted database at',\n // responseOpen.result.filename.replace(/^file:(.*?)\\?vfs=opfs/, '$1'),\n // );\n\n // logger('[Db.prepareDb] dbId', dbId)\n \n // this.dbId = dbId\n \n // await this.migrate()\n // }\n\n static async connectToDb(filesDir: string,): Promise<string | undefined> {\n\n\n\n return this.dbId\n }\n\n static async copyDrizzleFiles(filesDir: string): Promise<void> {\n logger('[Db.copyDrizzleFiles] copying drizzle migration files')\n\n try {\n // Ensure db directory exists\n const dbDirPath = `${filesDir}/db`\n await BaseFileManager.createDirIfNotExists(dbDirPath)\n\n // Ensure meta directory exists\n const metaDirPath = `${dbDirPath}/meta`\n await BaseFileManager.createDirIfNotExists(metaDirPath)\n\n // Parse journal JSON to get all migration entries\n const journal = JSON.parse(journalJson)\n const entries = journal.entries || []\n\n if (entries.length === 0) {\n logger('[Db.copyDrizzleFiles] no migration entries found in journal')\n return\n }\n\n // Copy each migration SQL file (always overwrite to ensure they're up-to-date)\n // Each migration is exported as a separate variable (e.g., migrationSql_0000_married_malice)\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i]\n const tag = entry.tag // e.g., \"0000_married_malice\"\n const migrationFileName = `${tag}.sql`\n const migrationPath = `${dbDirPath}/${migrationFileName}`\n \n // Get the SQL for this migration from the exported variable\n const migrationVarName = `migrationSql_${tag}` as keyof typeof drizzleFiles\n const migrationContent = drizzleFiles[migrationVarName] as string | undefined\n \n if (!migrationContent) {\n logger(`[Db.copyDrizzleFiles] ERROR: No migration content found for ${migrationFileName} (variable: ${migrationVarName})`)\n throw new Error(`No migration content found for ${migrationFileName}. Expected variable: ${migrationVarName}`)\n }\n \n await BaseFileManager.saveFile(migrationPath, migrationContent.trim())\n logger(`[Db.copyDrizzleFiles] copied/updated migration SQL file: ${migrationFileName}`)\n }\n\n // Copy journal JSON file (always overwrite to ensure it's up-to-date with all migrations)\n const journalPath = `${metaDirPath}/_journal.json`\n await BaseFileManager.saveFile(journalPath, journalJson)\n logger('[Db.copyDrizzleFiles] copied/updated journal JSON file')\n\n // Copy snapshot JSON file (use the latest snapshot based on the highest idx in journal)\n // Snapshot files are named like: 0000_snapshot.json, 0001_snapshot.json, etc.\n // The tag format is like \"0000_married_malice\", so we extract the numeric prefix\n const latestEntry = entries[entries.length - 1]\n const tagPrefixMatch = latestEntry.tag.match(/^(\\d+_)/)\n const tagPrefix = tagPrefixMatch ? tagPrefixMatch[1] : '0000_'\n const snapshotFileName = `${tagPrefix}snapshot.json`\n const snapshotPath = `${metaDirPath}/${snapshotFileName}`\n // Always overwrite snapshot to ensure it's up-to-date\n await BaseFileManager.saveFile(snapshotPath, snapshotJson)\n logger(`[Db.copyDrizzleFiles] copied/updated snapshot JSON file: ${snapshotFileName}`)\n\n logger('[Db.copyDrizzleFiles] drizzle files copied successfully')\n } catch (error) {\n logger('[Db.copyDrizzleFiles] error copying drizzle files', error)\n // Don't throw - the files might already exist or migration might work without them\n // The migration will fail later if the files are truly needed\n }\n }\n\n static async migrate(): Promise<void> {\n\n if (!this.appDb) {\n throw new Error('Database not prepared')\n }\n\n const pathToDbDir = `${this.filesDir}/db`\n\n try {\n\n logger('[Db.migrate] calling readMigrationFiles')\n \n const migrations = readMigrationFiles({\n migrationsFolder: pathToDbDir,\n })\n\n logger('[Db.migrate] migrations', migrations)\n \n await drizzleMigrate(\n this.appDb,\n async (queriesToRun) => {\n logger('queriesToRun', queriesToRun)\n for (const query of queriesToRun) {\n logger('query', query)\n await this.appDb?.run(sql.raw(query))\n }\n },\n {\n migrationsFolder: pathToDbDir,\n },\n )\n\n logger('[Db.migrate] migrations completed')\n \n } catch (error) {\n logger('[Db.migrate] error', JSON.stringify(error))\n throw error\n }\n \n\n }\n\n // static async migrate(): Promise<void> {\n\n // const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`\n // const pathToDbDir = `${this.filesDir}/db`\n // const dbName = DB_NAME_APP\n\n // logger('[Db.migrate] running migrations')\n\n // const drizzleDb = drizzle(\n // async (sql, params,) => {\n // try {\n // logger(\n // `executing sql`,\n // sql,\n // )\n\n // const finalResult = await this.exec(sql, params)\n\n // // logger(`finalResult with method: ${method}`, finalResult)\n // // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.\n\n // // When the method is get, you should return a value as {rows: string[]}.\n // // Otherwise, you should return {rows: string[][]}.\n\n // return { rows: finalResult }\n // } catch (e: any) {\n // console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n // return { rows: [] }\n // }\n // },\n // {\n // schema,\n // // logger: true,\n // },\n // )\n\n // try {\n // const zenfs = await BaseFileManager.getFs()\n\n // logger('[Db.migrate] calling readMigrationFiles')\n\n // const migrations = readMigrationFiles({\n // migrationsFolder: pathToDbDir,\n // })\n\n // logger('[Db.migrate] migrations', migrations)\n\n // if (migrations.length > 0) {\n // const incomingMigrationHashes = migrations.map(\n // (migration) => migration.hash,\n // )\n\n // let existingMigrationHashes\n // let rows = []\n\n // try {\n\n // const queryMigrationsTable = await drizzleDb.run(\n // sql.raw(\n // `SELECT name \n // FROM sqlite_master \n // WHERE type='table' \n // AND name='__drizzle_migrations';`,\n // ),\n // )\n\n // logger('queryMigrationsTable', queryMigrationsTable)\n\n // if (queryMigrationsTable && queryMigrationsTable.rows && queryMigrationsTable.rows.length > 0) {\n // const query = await drizzleDb.run(\n // sql.raw(\n // `SELECT hash, created_at\n // FROM main.__drizzle_migrations;`,\n // ),\n // )\n \n // rows = query.rows\n // }\n\n // } catch (e) {\n // rows = []\n // }\n\n // if (rows && rows.length > 0) {\n // existingMigrationHashes = rows.map((row) => row[0])\n // }\n\n // if (existingMigrationHashes) {\n // let shouldRebuildDb = false\n // for (const existingHash of existingMigrationHashes) {\n // if (!incomingMigrationHashes.includes(existingHash)) {\n // shouldRebuildDb = true\n // break\n // }\n // }\n // if (shouldRebuildDb) {\n // await zenfs.promises.unlink(`${pathToDbDir}/${dbName}.db`)\n // }\n // }\n // }\n\n // logger('[Db.migrate] running migrations')\n\n // await drizzleMigrate(\n // drizzleDb,\n // async (queriesToRun) => {\n // // logger('queriesToRun', queriesToRun)\n // for (const query of queriesToRun) {\n // // logger('query', query)\n // await drizzleDb.run(sql.raw(query))\n // }\n // },\n // {\n // migrationsFolder: pathToDbDir,\n // },\n // )\n // } catch (error) {\n // logger('[Db.migrate] error', JSON.stringify(error))\n // // await BaseFileManager.waitForFile(`${pathToDbDir}/meta/_journal.json`)\n\n // // const journalExists = await BaseFileManager.pathExists(\n // // `${pathToDbDir}/meta/_journal.json`,\n // // )\n\n // // if (journalExists) {\n // // await this.migrate(pathToDbDir, dbName,)\n // // }\n\n // // if (!journalExists) {\n // // throw new Error('Failed to migrate database')\n // // }\n\n\n // }\n\n // this.appDb = drizzleDb\n\n // // Old code for migrating the database\n // // const createTempTableQuery = await appDb.run(\n // // sql.raw(\n // // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,\n // // ),\n // // )\n // //\n // // logger(\n // // '[db/actors] [migrate] createTempTableQuery',\n // // createTempTableQuery,\n // // )\n\n // // const triggersQuery = await appDb.run(\n // // sql.raw(\n // // `SELECT name\n // // FROM main.sqlite_master\n // // WHERE type = 'trigger';`,\n // // ),\n // // )\n // //\n // // logger('[db/actors] [migrate] triggersQuery', triggersQuery)\n // //\n // // const triggers = triggersQuery.rows.map((row) => row[0])\n // //\n // // const tablesQuery = await appDb.run(\n // // sql.raw(\n // // `SELECT name\n // // FROM main.sqlite_master\n // // WHERE type = 'table';`,\n // // ),\n // // )\n // //\n // // logger('[db/actors] [migrate] tablesQuery', tablesQuery)\n // //\n // // const tableNames = tablesQuery.rows.map((row) => row[0])\n // // logger('[db/actors] [migrate] tableNames', tableNames)\n // // for (const tableName of tableNames) {\n // // const triggerName = `after_insert_${tableName}`\n // // if (triggers.includes(triggerName)) {\n // // continue\n // // }\n // // const createTriggerQuery = await appDb.run(\n // // sql.raw(\n // // `CREATE TRIGGER after_insert_${tableName}\n // // AFTER INSERT ON ${tableName}\n // // BEGIN\n // // DELETE FROM temp_last_inserted_id;\n // // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);\n // // END;`,\n // // ),\n // // )\n // //\n // // logger(\n // // '[db/actors] [migrate] createTriggerQuery',\n // // createTriggerQuery,\n // // )\n // // }\n // }\n\n // static async exec(sql: string, params: any[]) {\n // const rowsToReturnRaw: SqliteWasmResult[] = []\n // const rowsValues: string[][] = []\n \n // // For a single exec command, the callback potentially gets called several times -- once for each row.\n // // So we need to collect all rows into a final array to return (execResult).\n // const rowsToReturn = await new Promise((resolve, reject) => {\n\n\n // this.sqliteWasmClient('exec', {\n // dbId:this.dbId,\n // sql,\n // bind: params,\n // callback: (result) => {\n // // Checks if this is the final callback of the query\n // if (!result || !result.row || !result.rowNumber) {\n // const returnResult = []\n // for (const currRow of rowsToReturnRaw) {\n // returnResult.push(currRow.row)\n // }\n // resolve(returnResult)\n // } else {\n // // If not the final response, add this row to the return array\n // rowsToReturnRaw.push(result)\n // }\n // },\n // }).catch(async (error) => {\n // reject(error)\n // })\n // })\n \n // return rowsToReturn || []\n // }\n\n /**\n * Execute a reactive query that emits new results whenever the underlying data changes.\n * \n * Supports two usage patterns:\n * 1. SQL tag function: liveQuery((sql) => sql`SELECT * FROM models`)\n * 2. Drizzle query builder: liveQuery(db.select().from(models))\n * \n * @param query - SQL query function or Drizzle query builder\n * @returns Observable that emits arrays of query results\n * \n * @example\n * ```typescript\n * // Using SQL tag function\n * const models$ = Db.liveQuery<ModelRow>(\n * (sql) => sql`SELECT * FROM models WHERE schema_file_id = ${schemaId}`\n * )\n * \n * // Using Drizzle query builder\n * const models$ = Db.liveQuery<ModelRow>(\n * appDb.select().from(models).where(eq(models.schemaFileId, schemaId))\n * )\n * \n * models$.subscribe(models => {\n * console.log('Models updated:', models)\n * })\n * ```\n */\n static liveQuery<T>(\n query: ((sql: any) => any) | any\n ): Observable<T[]> {\n if (!this.sqlocalInstance) {\n throw new Error('Database not initialized. Call prepareDb first.')\n }\n \n if (!this.sqlocalInstance.reactiveQuery) {\n throw new Error('Reactive queries not enabled. Initialize SQLocalDrizzle with reactive: true.')\n }\n\n const baseObservable = new Observable<T[]>((subscriber) => {\n // Call SQLocal's reactiveQuery\n const reactiveQueryResult = this.sqlocalInstance!.reactiveQuery(query)\n \n // Subscribe to SQLocal's subscription API\n const subscription = reactiveQueryResult.subscribe(\n (data: Record<string, any>[]) => {\n // Log the actual data structure for debugging\n if (data && data.length > 0) {\n // Try to extract IDs/names for logging (check common field names)\n const sampleIds = data.map((d: any) => {\n return d.id || d.modelId || d.schemaId || d.modelFileId || d.schemaFileId || d.name || d.modelName || JSON.stringify(d).substring(0, 50)\n })\n }\n // Emit data through RxJS Observable (cast to T[] since SQLocal returns Record<string, any>[])\n subscriber.next(data as T[])\n },\n (err: Error) => {\n console.error('[BaseDb.liveQuery] SQLocal reactiveQuery error:', err)\n // Emit error through RxJS Observable\n subscriber.error(err)\n }\n )\n \n // Cleanup: unsubscribe when Observable is unsubscribed\n return () => {\n subscription.unsubscribe()\n }\n })\n \n // Use distinctUntilChanged with JSON.stringify comparison\n // The comparator returns true if values are the same (skip emission)\n return baseObservable.pipe(\n distinctUntilChanged((prev, curr) => {\n // On first emission, prev will be undefined, so we always emit\n if (prev === undefined) {\n return false // false = different, so emit\n }\n \n // Compare using JSON.stringify\n try {\n const prevJson = JSON.stringify(prev)\n const currJson = JSON.stringify(curr)\n // Return true if same (skip), false if different (emit)\n return prevJson === currJson\n } catch (error) {\n // If JSON.stringify fails, fall back to reference equality\n console.warn('[BaseDb.liveQuery] distinctUntilChanged: JSON.stringify failed, using reference equality', error)\n return prev === curr\n }\n })\n )\n }\n}\n\nexport { Db }\n"],"names":["drizzleMigrate"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;AACO,MAAM,gCAAgC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAI,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;AAC1I,oBAAA,CAAC;gBACH;;AAEA,gBAAA,UAAU,CAAC,IAAI,CAAC,IAAW,CAAC;AAC9B,YAAA,CAAC,EACD,CAAC,GAAU,KAAI;AACb,gBAAA,OAAO,CAAC,KAAK,CAAC,iDAAiD,EAAE,GAAG,CAAC;;AAErE,gBAAA,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC;AACvB,YAAA,CAAC,CACF;;AAGD,YAAA,OAAO,MAAK;gBACV,YAAY,CAAC,WAAW,EAAE;AAC5B,YAAA,CAAC;AACH,QAAA,CAAC,CAAC;;;QAIF,OAAO,cAAc,CAAC,IAAI,CACxB,oBAAoB,CAAC,CAAC,IAAI,EAAE,IAAI,KAAI;;AAElC,YAAA,IAAI,IAAI,KAAK,SAAS,EAAE;gBACtB,OAAO,KAAK,CAAA;YACd;;AAGA,YAAA,IAAI;gBACF,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;gBACrC,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;;gBAErC,OAAO,QAAQ,KAAK,QAAQ;YAC9B;YAAE,OAAO,KAAK,EAAE;;AAEd,gBAAA,OAAO,CAAC,IAAI,CAAC,0FAA0F,EAAE,KAAK,CAAC;gBAC/G,OAAO,IAAI,KAAK,IAAI;YACtB;QACF,CAAC,CAAC,CACH;IACH;AACD;;;;"}
1
+ {"version":3,"file":"Db-DjFdIdR9.js","sources":["../src/browser/db/drizzleFiles.ts","../src/browser/db/Db.ts"],"sourcesContent":["// This file embeds the drizzle migration files as strings for browser runtime\n// These files are copied from src/db/drizzle at build time\n\n// Individual migration SQL files\nexport const migrationSql_0000_married_malice = `CREATE TABLE \\`appState\\` (\n\t\\`key\\` text,\n\t\\`value\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`appState_key_unique\\` ON \\`appState\\` (\\`key\\`);--> statement-breakpoint\nCREATE TABLE \\`config\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`key\\` text NOT NULL,\n\t\\`text\\` text,\n\t\\`json\\` text,\n\t\\`blob\\` blob\n);\n--> statement-breakpoint\nCREATE TABLE \\`metadata\\` (\n\t\\`local_id\\` text,\n\t\\`uid\\` text,\n\t\\`property_name\\` text,\n\t\\`property_value\\` text,\n\t\\`schema_uid\\` text,\n\t\\`model_type\\` text,\n\t\\`seed_local_id\\` text,\n\t\\`seed_uid\\` text,\n\t\\`version_local_id\\` text,\n\t\\`version_uid\\` text,\n\t\\`eas_data_type\\` text,\n\t\\`ref_value_type\\` text,\n\t\\`ref_schema_uid\\` text,\n\t\\`ref_seed_type\\` text,\n\t\\`ref_resolved_value\\` text,\n\t\\`ref_resolved_display_value\\` text,\n\t\\`local_storage_dir\\` text,\n\t\\`attestation_raw\\` text,\n\t\\`attestation_created_at\\` integer,\n\t\\`content_hash\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`metadata_local_id_unique\\` ON \\`metadata\\` (\\`local_id\\`);--> statement-breakpoint\nCREATE TABLE \\`models\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`name\\` text NOT NULL,\n\t\\`schema_file_id\\` text\n);\n--> statement-breakpoint\nCREATE TABLE \\`properties\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`name\\` text NOT NULL,\n\t\\`data_type\\` text NOT NULL,\n\t\\`model_id\\` integer NOT NULL,\n\t\\`ref_model_id\\` integer,\n\t\\`ref_value_type\\` text,\n\t\\`schema_file_id\\` text,\n\tFOREIGN KEY (\\`model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (\\`ref_model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`unique_name_model_id\\` ON \\`properties\\` (\\`name\\`,\\`model_id\\`);--> statement-breakpoint\nCREATE TABLE \\`model_schemas\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`model_id\\` integer,\n\t\\`schema_id\\` integer,\n\tFOREIGN KEY (\\`model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (\\`schema_id\\`) REFERENCES \\`schemas\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE TABLE \\`model_uids\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`uid\\` text NOT NULL,\n\t\\`model_id\\` integer NOT NULL,\n\tFOREIGN KEY (\\`model_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`model_uids_model_id_unique\\` ON \\`model_uids\\` (\\`model_id\\`);--> statement-breakpoint\nCREATE TABLE \\`property_uids\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`uid\\` text NOT NULL,\n\t\\`property_id\\` integer NOT NULL,\n\tFOREIGN KEY (\\`property_id\\`) REFERENCES \\`models\\`(\\`id\\`) ON UPDATE no action ON DELETE no action\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`property_uids_property_id_unique\\` ON \\`property_uids\\` (\\`property_id\\`);--> statement-breakpoint\nCREATE TABLE \\`schemas\\` (\n\t\\`id\\` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n\t\\`name\\` text NOT NULL,\n\t\\`version\\` integer NOT NULL,\n\t\\`schema_file_id\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer\n);\n--> statement-breakpoint\nCREATE TABLE \\`seeds\\` (\n\t\\`local_id\\` text,\n\t\\`uid\\` text,\n\t\\`schema_uid\\` text,\n\t\\`type\\` text,\n\t\\`attestation_raw\\` text,\n\t\\`attestation_created_at\\` integer,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer,\n\t\\`_marked_for_deletion\\` integer\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`seeds_local_id_unique\\` ON \\`seeds\\` (\\`local_id\\`);--> statement-breakpoint\nCREATE TABLE \\`versions\\` (\n\t\\`local_id\\` text,\n\t\\`uid\\` text,\n\t\\`seed_local_id\\` text,\n\t\\`seed_uid\\` text,\n\t\\`seed_type\\` text,\n\t\\`note\\` text,\n\t\\`created_at\\` integer,\n\t\\`updated_at\\` integer,\n\t\\`attestation_created_at\\` integer,\n\t\\`attestation_raw\\` text\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX \\`versions_local_id_unique\\` ON \\`versions\\` (\\`local_id\\`);`\n\nexport const migrationSql_0001_sweet_bruce_banner = `ALTER TABLE \\`schemas\\` ADD \\`schema_data\\` text;--> statement-breakpoint\nALTER TABLE \\`schemas\\` ADD \\`is_draft\\` integer;`\n\nexport const migrationSql_0002_bitter_proudstar = `CREATE UNIQUE INDEX \\`unique_schema_file_id\\` ON \\`models\\` (\\`schema_file_id\\`);--> statement-breakpoint\nCREATE UNIQUE INDEX \\`unique_property_schema_file_id\\` ON \\`properties\\` (\\`schema_file_id\\`);--> statement-breakpoint\nCREATE UNIQUE INDEX \\`unique_schema_schema_file_id\\` ON \\`schemas\\` (\\`schema_file_id\\`);`\n\nexport const migrationSql_0003_cultured_senator_kelly = `ALTER TABLE \\`models\\` ADD \\`is_edited\\` integer;--> statement-breakpoint\nALTER TABLE \\`properties\\` ADD \\`is_edited\\` integer;--> statement-breakpoint\nALTER TABLE \\`schemas\\` ADD \\`is_edited\\` integer;`\n\n// Journal JSON file\nexport const journalJson = `{\n \"version\": \"7\",\n \"dialect\": \"sqlite\",\n \"entries\": [\n {\n \"idx\": 0,\n \"version\": \"6\",\n \"when\": 1765976502903,\n \"tag\": \"0000_married_malice\",\n \"breakpoints\": true\n },\n {\n \"idx\": 1,\n \"version\": \"6\",\n \"when\": 1766010851770,\n \"tag\": \"0001_sweet_bruce_banner\",\n \"breakpoints\": true\n },\n {\n \"idx\": 2,\n \"version\": \"6\",\n \"when\": 1767621120087,\n \"tag\": \"0002_bitter_proudstar\",\n \"breakpoints\": true\n },\n {\n \"idx\": 3,\n \"version\": \"6\",\n \"when\": 1768415440282,\n \"tag\": \"0003_cultured_senator_kelly\",\n \"breakpoints\": true\n }\n ]\n}`\n\n// Snapshot JSON file - this is large, so we'll import it dynamically if needed\n// For now, we'll read it from the actual file if ?raw works, otherwise we'll need to embed it\nexport const snapshotJson = `{\n \"version\": \"6\",\n \"dialect\": \"sqlite\",\n \"id\": \"0e6a6a99-2eb1-4b1d-815b-3d45dcae04a1\",\n \"prevId\": \"49b9a020-1b1c-4107-85ee-a5f8a958f1a2\",\n \"tables\": {\n \"appState\": {\n \"name\": \"appState\",\n \"columns\": {\n \"key\": {\n \"name\": \"key\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"value\": {\n \"name\": \"value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"appState_key_unique\": {\n \"name\": \"appState_key_unique\",\n \"columns\": [\n \"key\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"config\": {\n \"name\": \"config\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"key\": {\n \"name\": \"key\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"text\": {\n \"name\": \"text\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"json\": {\n \"name\": \"json\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"blob\": {\n \"name\": \"blob\",\n \"type\": \"blob\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {},\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"metadata\": {\n \"name\": \"metadata\",\n \"columns\": {\n \"local_id\": {\n \"name\": \"local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"property_name\": {\n \"name\": \"property_name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"property_value\": {\n \"name\": \"property_value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_uid\": {\n \"name\": \"schema_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"model_type\": {\n \"name\": \"model_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_local_id\": {\n \"name\": \"seed_local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_uid\": {\n \"name\": \"seed_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"version_local_id\": {\n \"name\": \"version_local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"version_uid\": {\n \"name\": \"version_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"eas_data_type\": {\n \"name\": \"eas_data_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_value_type\": {\n \"name\": \"ref_value_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_schema_uid\": {\n \"name\": \"ref_schema_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_seed_type\": {\n \"name\": \"ref_seed_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_resolved_value\": {\n \"name\": \"ref_resolved_value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_resolved_display_value\": {\n \"name\": \"ref_resolved_display_value\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"local_storage_dir\": {\n \"name\": \"local_storage_dir\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_raw\": {\n \"name\": \"attestation_raw\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_created_at\": {\n \"name\": \"attestation_created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"content_hash\": {\n \"name\": \"content_hash\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"metadata_local_id_unique\": {\n \"name\": \"metadata_local_id_unique\",\n \"columns\": [\n \"local_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"models\": {\n \"name\": \"models\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"name\": {\n \"name\": \"name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"schema_file_id\": {\n \"name\": \"schema_file_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_edited\": {\n \"name\": \"is_edited\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"unique_schema_file_id\": {\n \"name\": \"unique_schema_file_id\",\n \"columns\": [\n \"schema_file_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"properties\": {\n \"name\": \"properties\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"name\": {\n \"name\": \"name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"data_type\": {\n \"name\": \"data_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"model_id\": {\n \"name\": \"model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"ref_model_id\": {\n \"name\": \"ref_model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"ref_value_type\": {\n \"name\": \"ref_value_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_file_id\": {\n \"name\": \"schema_file_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_edited\": {\n \"name\": \"is_edited\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"unique_name_model_id\": {\n \"name\": \"unique_name_model_id\",\n \"columns\": [\n \"name\",\n \"model_id\"\n ],\n \"isUnique\": true\n },\n \"unique_property_schema_file_id\": {\n \"name\": \"unique_property_schema_file_id\",\n \"columns\": [\n \"schema_file_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {\n \"properties_model_id_models_id_fk\": {\n \"name\": \"properties_model_id_models_id_fk\",\n \"tableFrom\": \"properties\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n },\n \"properties_ref_model_id_models_id_fk\": {\n \"name\": \"properties_ref_model_id_models_id_fk\",\n \"tableFrom\": \"properties\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"ref_model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"model_schemas\": {\n \"name\": \"model_schemas\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"model_id\": {\n \"name\": \"model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_id\": {\n \"name\": \"schema_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {},\n \"foreignKeys\": {\n \"model_schemas_model_id_models_id_fk\": {\n \"name\": \"model_schemas_model_id_models_id_fk\",\n \"tableFrom\": \"model_schemas\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n },\n \"model_schemas_schema_id_schemas_id_fk\": {\n \"name\": \"model_schemas_schema_id_schemas_id_fk\",\n \"tableFrom\": \"model_schemas\",\n \"tableTo\": \"schemas\",\n \"columnsFrom\": [\n \"schema_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"model_uids\": {\n \"name\": \"model_uids\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"model_id\": {\n \"name\": \"model_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"model_uids_model_id_unique\": {\n \"name\": \"model_uids_model_id_unique\",\n \"columns\": [\n \"model_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {\n \"model_uids_model_id_models_id_fk\": {\n \"name\": \"model_uids_model_id_models_id_fk\",\n \"tableFrom\": \"model_uids\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"model_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"property_uids\": {\n \"name\": \"property_uids\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"property_id\": {\n \"name\": \"property_id\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"property_uids_property_id_unique\": {\n \"name\": \"property_uids_property_id_unique\",\n \"columns\": [\n \"property_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {\n \"property_uids_property_id_models_id_fk\": {\n \"name\": \"property_uids_property_id_models_id_fk\",\n \"tableFrom\": \"property_uids\",\n \"tableTo\": \"models\",\n \"columnsFrom\": [\n \"property_id\"\n ],\n \"columnsTo\": [\n \"id\"\n ],\n \"onDelete\": \"no action\",\n \"onUpdate\": \"no action\"\n }\n },\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"schemas\": {\n \"name\": \"schemas\",\n \"columns\": {\n \"id\": {\n \"name\": \"id\",\n \"type\": \"integer\",\n \"primaryKey\": true,\n \"notNull\": true,\n \"autoincrement\": true\n },\n \"name\": {\n \"name\": \"name\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"version\": {\n \"name\": \"version\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": true,\n \"autoincrement\": false\n },\n \"schema_file_id\": {\n \"name\": \"schema_file_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_data\": {\n \"name\": \"schema_data\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_draft\": {\n \"name\": \"is_draft\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"is_edited\": {\n \"name\": \"is_edited\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"unique_schema_schema_file_id\": {\n \"name\": \"unique_schema_schema_file_id\",\n \"columns\": [\n \"schema_file_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"seeds\": {\n \"name\": \"seeds\",\n \"columns\": {\n \"local_id\": {\n \"name\": \"local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"schema_uid\": {\n \"name\": \"schema_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"type\": {\n \"name\": \"type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_raw\": {\n \"name\": \"attestation_raw\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_created_at\": {\n \"name\": \"attestation_created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"_marked_for_deletion\": {\n \"name\": \"_marked_for_deletion\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"seeds_local_id_unique\": {\n \"name\": \"seeds_local_id_unique\",\n \"columns\": [\n \"local_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n },\n \"versions\": {\n \"name\": \"versions\",\n \"columns\": {\n \"local_id\": {\n \"name\": \"local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"uid\": {\n \"name\": \"uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_local_id\": {\n \"name\": \"seed_local_id\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_uid\": {\n \"name\": \"seed_uid\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"seed_type\": {\n \"name\": \"seed_type\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"note\": {\n \"name\": \"note\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"created_at\": {\n \"name\": \"created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"updated_at\": {\n \"name\": \"updated_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_created_at\": {\n \"name\": \"attestation_created_at\",\n \"type\": \"integer\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n },\n \"attestation_raw\": {\n \"name\": \"attestation_raw\",\n \"type\": \"text\",\n \"primaryKey\": false,\n \"notNull\": false,\n \"autoincrement\": false\n }\n },\n \"indexes\": {\n \"versions_local_id_unique\": {\n \"name\": \"versions_local_id_unique\",\n \"columns\": [\n \"local_id\"\n ],\n \"isUnique\": true\n }\n },\n \"foreignKeys\": {},\n \"compositePrimaryKeys\": {},\n \"uniqueConstraints\": {},\n \"checkConstraints\": {}\n }\n },\n \"views\": {},\n \"enums\": {},\n \"_meta\": {\n \"schemas\": {},\n \"tables\": {},\n \"columns\": {}\n },\n \"internal\": {\n \"indexes\": {}\n }\n}`\n","import { BaseDb } from \"@/db/Db/BaseDb\";\nimport { IDb } from \"@/interfaces/IDb\";\nimport debug from \"debug\";\nimport { sql } from \"drizzle-orm\";\nimport { readMigrationFiles } from \"drizzle-orm/migrator\";\nimport { drizzle, SqliteRemoteDatabase } from \"drizzle-orm/sqlite-proxy\";\nimport { migrate as drizzleMigrate } from \"drizzle-orm/sqlite-proxy/migrator\";\nimport { BROWSER_FS_TOP_DIR } from \"@/client/constants\";\nimport { BaseFileManager } from \"@/helpers\";\nimport * as schema from '@/seedSchema'\n// @ts-ignore - sqlocal/drizzle types may not be available during build\nimport { SQLocalDrizzle } from 'sqlocal/drizzle'\nimport {} from 'sqlocal'\nimport * as drizzleFiles from './drizzleFiles'\nimport { journalJson, snapshotJson } from './drizzleFiles'\nimport { Observable, distinctUntilChanged } from 'rxjs'\n\nconst logger = debug('seedSdk:browser:db:Db')\n\n\nclass Db extends BaseDb implements IDb {\n\n static sqliteWasmClient: any\n static filesDir: string | undefined\n static pathToDb: string | undefined\n static dbId: string | undefined\n static appDb: SqliteRemoteDatabase<Record<string, unknown>> | undefined\n static sqlocalInstance: SQLocalDrizzle | undefined\n\n constructor() {\n super()\n }\n\n static getAppDb() {\n return this.appDb\n }\n\n static isAppDbReady() {\n return !!this.appDb\n }\n\n static async prepareDb(filesDir: string) {\n\n logger('[Db.prepareDb] preparing database')\n\n this.filesDir = filesDir\n\n try {\n // Copy drizzle migration files from src/db/drizzle to filesDir/db\n await this.copyDrizzleFiles(filesDir)\n\n // Ensure meta directory exists\n const metaDirPath = `${filesDir}/db/meta`\n await BaseFileManager.createDirIfNotExists(metaDirPath)\n\n // Ensure _journal.json file exists in meta directory\n const journalFilePath = `${metaDirPath}/_journal.json`\n const journalExists = await BaseFileManager.pathExists(journalFilePath)\n if (!journalExists) {\n await BaseFileManager.saveFile(journalFilePath, JSON.stringify({\n version: 1,\n dialect: 'sqlite',\n entries: [],\n }, null, 2))\n }\n\n // Wait for journal file to be fully written before proceeding with migration\n // This is critical in browser/OPFS where writes may not be immediately readable\n logger('[Db.prepareDb] waiting for journal file to be fully written...')\n await BaseFileManager.waitForFileWithContent(journalFilePath, 100, 5000)\n logger('[Db.prepareDb] journal file is ready')\n\n // Initialize SQLocalDrizzle with reactive: true to enable reactive queries\n const sqlocalDrizzle = new SQLocalDrizzle({\n databasePath: `${this.filesDir}/db/seed.db`,\n reactive: true // Enable reactive queries\n })\n \n const { driver, batchDriver } = sqlocalDrizzle\n \n // Store SQLocalDrizzle instance for reactive queries\n this.sqlocalInstance = sqlocalDrizzle\n\n this.appDb = drizzle(\n driver, \n batchDriver, \n { \n schema, \n })\n\n logger('[Db.prepareDb] database prepared')\n\n await this.migrate()\n\n return this.appDb\n } catch (error) {\n logger('[Db.prepareDb] error', JSON.stringify(error))\n throw error\n }\n }\n\n // static async prepareDb(filesDir: string) {\n // console.log('prepareDb', filesDir)\n // if (Db.sqliteWasmClient) {\n // return this.dbId\n // }\n\n // this.filesDir = filesDir\n // this.pathToDb = `${filesDir}/db/${DB_NAME_APP}.db`\n\n // if (typeof document === 'undefined') {\n // return\n // }\n\n // let promiser\n\n // try {\n\n // let sqlite3Worker1Promiser\n\n // const sqliteWasm = await import('@sqlite.org/sqlite-wasm')\n\n // if (sqliteWasm && sqliteWasm.sqlite3Worker1Promiser) {\n // sqlite3Worker1Promiser = sqliteWasm.sqlite3Worker1Promiser\n // }\n\n // if (!sqlite3Worker1Promiser && window.sqlite3Worker1Promiser) {\n // sqlite3Worker1Promiser = window.sqlite3Worker1Promiser\n // }\n\n // if (!sqlite3Worker1Promiser) {\n // throw new Error('Failed to load sqlite3Worker1Promiser')\n // }\n\n // promiser = await new Promise<(event: string, config: Record<string, unknown>) => Promise<any>>((resolve) => {\n // const _promiser = sqlite3Worker1Promiser({\n // onready: () => {\n // resolve(_promiser);\n // },\n // });\n // }).catch((error) => {\n // console.error('Error from sqlite proxy server: ', JSON.stringify(error))\n // });\n\n // } catch ( e ) {\n // console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n // }\n\n\n // if (!promiser) {\n // throw new Error('Failed to create promiser')\n // }\n\n // this.sqliteWasmClient = promiser\n\n // const responseGet = await this.sqliteWasmClient('config-get', {});\n\n // logger('[Db.prepareDb] Running SQLite3 version', responseGet.result.version.libVersion);\n\n // const responseOpen = await this.sqliteWasmClient('open', {\n // filename: `file:${filesDir}/db/${DB_NAME_APP}.db?vfs=opfs`,\n // });\n // const { dbId } = responseOpen;\n // logger(\n // '[Db.prepareDb] OPFS is available, created persisted database at',\n // responseOpen.result.filename.replace(/^file:(.*?)\\?vfs=opfs/, '$1'),\n // );\n\n // logger('[Db.prepareDb] dbId', dbId)\n \n // this.dbId = dbId\n \n // await this.migrate()\n // }\n\n static async connectToDb(filesDir: string,): Promise<string | undefined> {\n\n\n\n return this.dbId\n }\n\n static async copyDrizzleFiles(filesDir: string): Promise<void> {\n logger('[Db.copyDrizzleFiles] copying drizzle migration files')\n\n try {\n // Ensure db directory exists\n const dbDirPath = `${filesDir}/db`\n await BaseFileManager.createDirIfNotExists(dbDirPath)\n\n // Ensure meta directory exists\n const metaDirPath = `${dbDirPath}/meta`\n await BaseFileManager.createDirIfNotExists(metaDirPath)\n\n // Parse journal JSON to get all migration entries\n const journal = JSON.parse(journalJson)\n const entries = journal.entries || []\n\n if (entries.length === 0) {\n logger('[Db.copyDrizzleFiles] no migration entries found in journal')\n return\n }\n\n // Copy each migration SQL file (always overwrite to ensure they're up-to-date)\n // Each migration is exported as a separate variable (e.g., migrationSql_0000_married_malice)\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i]\n const tag = entry.tag // e.g., \"0000_married_malice\"\n const migrationFileName = `${tag}.sql`\n const migrationPath = `${dbDirPath}/${migrationFileName}`\n \n // Get the SQL for this migration from the exported variable\n const migrationVarName = `migrationSql_${tag}` as keyof typeof drizzleFiles\n const migrationContent = drizzleFiles[migrationVarName] as string | undefined\n \n if (!migrationContent) {\n logger(`[Db.copyDrizzleFiles] ERROR: No migration content found for ${migrationFileName} (variable: ${migrationVarName})`)\n throw new Error(`No migration content found for ${migrationFileName}. Expected variable: ${migrationVarName}`)\n }\n \n await BaseFileManager.saveFile(migrationPath, migrationContent.trim())\n logger(`[Db.copyDrizzleFiles] copied/updated migration SQL file: ${migrationFileName}`)\n }\n\n // Copy journal JSON file (always overwrite to ensure it's up-to-date with all migrations)\n const journalPath = `${metaDirPath}/_journal.json`\n await BaseFileManager.saveFile(journalPath, journalJson)\n logger('[Db.copyDrizzleFiles] copied/updated journal JSON file')\n\n // Copy snapshot JSON file (use the latest snapshot based on the highest idx in journal)\n // Snapshot files are named like: 0000_snapshot.json, 0001_snapshot.json, etc.\n // The tag format is like \"0000_married_malice\", so we extract the numeric prefix\n const latestEntry = entries[entries.length - 1]\n const tagPrefixMatch = latestEntry.tag.match(/^(\\d+_)/)\n const tagPrefix = tagPrefixMatch ? tagPrefixMatch[1] : '0000_'\n const snapshotFileName = `${tagPrefix}snapshot.json`\n const snapshotPath = `${metaDirPath}/${snapshotFileName}`\n // Always overwrite snapshot to ensure it's up-to-date\n await BaseFileManager.saveFile(snapshotPath, snapshotJson)\n logger(`[Db.copyDrizzleFiles] copied/updated snapshot JSON file: ${snapshotFileName}`)\n\n logger('[Db.copyDrizzleFiles] drizzle files copied successfully')\n } catch (error) {\n logger('[Db.copyDrizzleFiles] error copying drizzle files', error)\n // Don't throw - the files might already exist or migration might work without them\n // The migration will fail later if the files are truly needed\n }\n }\n\n static async migrate(): Promise<void> {\n\n if (!this.appDb) {\n throw new Error('Database not prepared')\n }\n\n const pathToDbDir = `${this.filesDir}/db`\n\n try {\n\n logger('[Db.migrate] calling readMigrationFiles')\n \n const migrations = readMigrationFiles({\n migrationsFolder: pathToDbDir,\n })\n\n logger('[Db.migrate] migrations', migrations)\n \n await drizzleMigrate(\n this.appDb,\n async (queriesToRun) => {\n logger('queriesToRun', queriesToRun)\n for (const query of queriesToRun) {\n logger('query', query)\n await this.appDb?.run(sql.raw(query))\n }\n },\n {\n migrationsFolder: pathToDbDir,\n },\n )\n\n logger('[Db.migrate] migrations completed')\n \n } catch (error) {\n logger('[Db.migrate] error', JSON.stringify(error))\n throw error\n }\n \n\n }\n\n // static async migrate(): Promise<void> {\n\n // const schemaGlobString = `${BROWSER_FS_TOP_DIR}/schema/*`\n // const pathToDbDir = `${this.filesDir}/db`\n // const dbName = DB_NAME_APP\n\n // logger('[Db.migrate] running migrations')\n\n // const drizzleDb = drizzle(\n // async (sql, params,) => {\n // try {\n // logger(\n // `executing sql`,\n // sql,\n // )\n\n // const finalResult = await this.exec(sql, params)\n\n // // logger(`finalResult with method: ${method}`, finalResult)\n // // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.\n\n // // When the method is get, you should return a value as {rows: string[]}.\n // // Otherwise, you should return {rows: string[][]}.\n\n // return { rows: finalResult }\n // } catch (e: any) {\n // console.error('Error from sqlite proxy server: ', JSON.stringify(e))\n // return { rows: [] }\n // }\n // },\n // {\n // schema,\n // // logger: true,\n // },\n // )\n\n // try {\n // const zenfs = await BaseFileManager.getFs()\n\n // logger('[Db.migrate] calling readMigrationFiles')\n\n // const migrations = readMigrationFiles({\n // migrationsFolder: pathToDbDir,\n // })\n\n // logger('[Db.migrate] migrations', migrations)\n\n // if (migrations.length > 0) {\n // const incomingMigrationHashes = migrations.map(\n // (migration) => migration.hash,\n // )\n\n // let existingMigrationHashes\n // let rows = []\n\n // try {\n\n // const queryMigrationsTable = await drizzleDb.run(\n // sql.raw(\n // `SELECT name \n // FROM sqlite_master \n // WHERE type='table' \n // AND name='__drizzle_migrations';`,\n // ),\n // )\n\n // logger('queryMigrationsTable', queryMigrationsTable)\n\n // if (queryMigrationsTable && queryMigrationsTable.rows && queryMigrationsTable.rows.length > 0) {\n // const query = await drizzleDb.run(\n // sql.raw(\n // `SELECT hash, created_at\n // FROM main.__drizzle_migrations;`,\n // ),\n // )\n \n // rows = query.rows\n // }\n\n // } catch (e) {\n // rows = []\n // }\n\n // if (rows && rows.length > 0) {\n // existingMigrationHashes = rows.map((row) => row[0])\n // }\n\n // if (existingMigrationHashes) {\n // let shouldRebuildDb = false\n // for (const existingHash of existingMigrationHashes) {\n // if (!incomingMigrationHashes.includes(existingHash)) {\n // shouldRebuildDb = true\n // break\n // }\n // }\n // if (shouldRebuildDb) {\n // await zenfs.promises.unlink(`${pathToDbDir}/${dbName}.db`)\n // }\n // }\n // }\n\n // logger('[Db.migrate] running migrations')\n\n // await drizzleMigrate(\n // drizzleDb,\n // async (queriesToRun) => {\n // // logger('queriesToRun', queriesToRun)\n // for (const query of queriesToRun) {\n // // logger('query', query)\n // await drizzleDb.run(sql.raw(query))\n // }\n // },\n // {\n // migrationsFolder: pathToDbDir,\n // },\n // )\n // } catch (error) {\n // logger('[Db.migrate] error', JSON.stringify(error))\n // // await BaseFileManager.waitForFile(`${pathToDbDir}/meta/_journal.json`)\n\n // // const journalExists = await BaseFileManager.pathExists(\n // // `${pathToDbDir}/meta/_journal.json`,\n // // )\n\n // // if (journalExists) {\n // // await this.migrate(pathToDbDir, dbName,)\n // // }\n\n // // if (!journalExists) {\n // // throw new Error('Failed to migrate database')\n // // }\n\n\n // }\n\n // this.appDb = drizzleDb\n\n // // Old code for migrating the database\n // // const createTempTableQuery = await appDb.run(\n // // sql.raw(\n // // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,\n // // ),\n // // )\n // //\n // // logger(\n // // '[db/actors] [migrate] createTempTableQuery',\n // // createTempTableQuery,\n // // )\n\n // // const triggersQuery = await appDb.run(\n // // sql.raw(\n // // `SELECT name\n // // FROM main.sqlite_master\n // // WHERE type = 'trigger';`,\n // // ),\n // // )\n // //\n // // logger('[db/actors] [migrate] triggersQuery', triggersQuery)\n // //\n // // const triggers = triggersQuery.rows.map((row) => row[0])\n // //\n // // const tablesQuery = await appDb.run(\n // // sql.raw(\n // // `SELECT name\n // // FROM main.sqlite_master\n // // WHERE type = 'table';`,\n // // ),\n // // )\n // //\n // // logger('[db/actors] [migrate] tablesQuery', tablesQuery)\n // //\n // // const tableNames = tablesQuery.rows.map((row) => row[0])\n // // logger('[db/actors] [migrate] tableNames', tableNames)\n // // for (const tableName of tableNames) {\n // // const triggerName = `after_insert_${tableName}`\n // // if (triggers.includes(triggerName)) {\n // // continue\n // // }\n // // const createTriggerQuery = await appDb.run(\n // // sql.raw(\n // // `CREATE TRIGGER after_insert_${tableName}\n // // AFTER INSERT ON ${tableName}\n // // BEGIN\n // // DELETE FROM temp_last_inserted_id;\n // // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);\n // // END;`,\n // // ),\n // // )\n // //\n // // logger(\n // // '[db/actors] [migrate] createTriggerQuery',\n // // createTriggerQuery,\n // // )\n // // }\n // }\n\n // static async exec(sql: string, params: any[]) {\n // const rowsToReturnRaw: SqliteWasmResult[] = []\n // const rowsValues: string[][] = []\n \n // // For a single exec command, the callback potentially gets called several times -- once for each row.\n // // So we need to collect all rows into a final array to return (execResult).\n // const rowsToReturn = await new Promise((resolve, reject) => {\n\n\n // this.sqliteWasmClient('exec', {\n // dbId:this.dbId,\n // sql,\n // bind: params,\n // callback: (result) => {\n // // Checks if this is the final callback of the query\n // if (!result || !result.row || !result.rowNumber) {\n // const returnResult = []\n // for (const currRow of rowsToReturnRaw) {\n // returnResult.push(currRow.row)\n // }\n // resolve(returnResult)\n // } else {\n // // If not the final response, add this row to the return array\n // rowsToReturnRaw.push(result)\n // }\n // },\n // }).catch(async (error) => {\n // reject(error)\n // })\n // })\n \n // return rowsToReturn || []\n // }\n\n /**\n * Execute a reactive query that emits new results whenever the underlying data changes.\n * \n * Supports two usage patterns:\n * 1. SQL tag function: liveQuery((sql) => sql`SELECT * FROM models`)\n * 2. Drizzle query builder: liveQuery(db.select().from(models))\n * \n * @param query - SQL query function or Drizzle query builder\n * @returns Observable that emits arrays of query results\n * \n * @example\n * ```typescript\n * // Using SQL tag function\n * const models$ = Db.liveQuery<ModelRow>(\n * (sql) => sql`SELECT * FROM models WHERE schema_file_id = ${schemaId}`\n * )\n * \n * // Using Drizzle query builder\n * const models$ = Db.liveQuery<ModelRow>(\n * appDb.select().from(models).where(eq(models.schemaFileId, schemaId))\n * )\n * \n * models$.subscribe(models => {\n * console.log('Models updated:', models)\n * })\n * ```\n */\n static liveQuery<T>(\n query: ((sql: any) => any) | any\n ): Observable<T[]> {\n if (!this.sqlocalInstance) {\n throw new Error('Database not initialized. Call prepareDb first.')\n }\n \n if (!this.sqlocalInstance.reactiveQuery) {\n throw new Error('Reactive queries not enabled. Initialize SQLocalDrizzle with reactive: true.')\n }\n\n const baseObservable = new Observable<T[]>((subscriber) => {\n // Call SQLocal's reactiveQuery\n const reactiveQueryResult = this.sqlocalInstance!.reactiveQuery(query)\n \n // Subscribe to SQLocal's subscription API\n const subscription = reactiveQueryResult.subscribe(\n (data: Record<string, any>[]) => {\n // Emit data through RxJS Observable (cast to T[] since SQLocal returns Record<string, any>[])\n subscriber.next(data as T[])\n },\n (err: Error) => {\n console.error('[BaseDb.liveQuery] SQLocal reactiveQuery error:', err)\n // Emit error through RxJS Observable\n subscriber.error(err)\n }\n )\n \n // Cleanup: unsubscribe when Observable is unsubscribed\n return () => {\n subscription.unsubscribe()\n }\n })\n \n // Use distinctUntilChanged with JSON.stringify comparison\n // The comparator returns true if values are the same (skip emission)\n return baseObservable.pipe(\n distinctUntilChanged((prev, curr) => {\n // On first emission, prev will be undefined, so we always emit\n if (prev === undefined) {\n return false // false = different, so emit\n }\n \n // Compare using JSON.stringify\n try {\n const prevJson = JSON.stringify(prev)\n const currJson = JSON.stringify(curr)\n // Return true if same (skip), false if different (emit)\n return prevJson === currJson\n } catch (error) {\n // If JSON.stringify fails, fall back to reference equality\n console.warn('[BaseDb.liveQuery] distinctUntilChanged: JSON.stringify failed, using reference equality', error)\n return prev === curr\n }\n })\n )\n }\n}\n\nexport { Db }\n"],"names":["drizzleMigrate"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAEA;AACO,MAAM,gCAAgC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iFAwHiC;AAE1E,MAAM,oCAAoC,GAAG,CAAA;kDACF;AAE3C,MAAM,kCAAkC,GAAG,CAAA;;0FAEwC;AAEnF,MAAM,wCAAwC,GAAG,CAAA;;mDAEL;AAEnD;AACO,MAAM,WAAW,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiCzB;AAEF;AACA;AACO,MAAM,YAAY,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,SAAS,CAAC,IAAI,CAAC;;gBAErC,OAAO,QAAQ,KAAK,QAAQ;YAC9B;YAAE,OAAO,KAAK,EAAE;;AAEd,gBAAA,OAAO,CAAC,IAAI,CAAC,0FAA0F,EAAE,KAAK,CAAC;gBAC/G,OAAO,IAAI,KAAK,IAAI;YACtB;QACF,CAAC,CAAC,CACH;IACH;AACD;;;;"}
@@ -1,24 +1,24 @@
1
- import { p as BaseDb, u as appState } from './json-I3vJhXo8.js';
1
+ import { p as BaseDb, y as appState } from './index-DPll6EAp.js';
2
2
  import path from 'path';
3
3
  import debug from 'debug';
4
- import { s as schema } from './index-r45w9hEq.js';
4
+ import { s as schema } from './index-2FcQHgKp.js';
5
5
  import fs__default from 'fs';
6
6
  import { createClient } from '@libsql/client';
7
7
  import { drizzle } from 'drizzle-orm/libsql';
8
8
  import { pushSQLiteSchema } from 'drizzle-kit/api';
9
9
  import { interval, startWith, switchMap, distinctUntilChanged } from 'rxjs';
10
10
  import 'xstate';
11
+ import 'drizzle-orm/sqlite-core';
11
12
  import 'drizzle-orm';
13
+ import 'nanoid';
14
+ import 'nanoid-dictionary';
12
15
  import 'pluralize';
16
+ import 'ethers';
13
17
  import 'lodash-es';
14
18
  import 'drizzle-orm/casing';
15
- import '@sinclair/typebox';
16
- import 'arweave';
17
19
  import 'eventemitter3';
18
- import 'drizzle-orm/sqlite-core';
19
- import 'ethers';
20
- import 'nanoid';
21
- import 'nanoid-dictionary';
20
+ import 'arweave';
21
+ import '@sinclair/typebox';
22
22
 
23
23
  const logger = debug('seedSdk:node:db:Db');
24
24
  const getConfig = async (dotSeedDir, config) => {
@@ -340,4 +340,4 @@ class Db extends BaseDb {
340
340
  BaseDb.setPlatformClass(Db);
341
341
 
342
342
  export { Db };
343
- //# sourceMappingURL=Db-BPnO1-_p.js.map
343
+ //# sourceMappingURL=Db-DjofXdeU.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Db-BPnO1-_p.js","sources":["../src/node/db/Db.ts"],"sourcesContent":["import { BaseDb } from \"@/db/Db/BaseDb\";\nimport { IDb } from \"@/interfaces\";\nimport path from \"path\";\nimport { DrizzleConfig, } from \"drizzle-orm\";\nimport debug from 'debug'\nimport { appState } from '@/seedSchema'\nimport fs from 'fs'\nimport { createClient } from '@libsql/client'\nimport { drizzle } from 'drizzle-orm/libsql'\nimport { pushSQLiteSchema } from 'drizzle-kit/api'\nimport * as schema from '@/seedSchema'\nimport { Observable, interval, switchMap, distinctUntilChanged, startWith } from 'rxjs'\n\nconst logger = debug('seedSdk:node:db:Db')\n\nexport interface DbConfig {\n dbUrl?: string\n schemaDir?: string\n outDir?: string\n}\n\nconst getConfig = async (dotSeedDir: string, config?: DbConfig) => {\n // Create config inline - config values can be passed in or use defaults\n const { defineConfig } = await import('drizzle-kit')\n const appSchemaDir = config?.schemaDir || path.join(dotSeedDir, 'schema')\n const outDir = config?.outDir || `${dotSeedDir}/db`\n const dbUrl = config?.dbUrl || `${dotSeedDir}/db/seed.db`\n\n const nodeDbConfig = defineConfig({\n schema: appSchemaDir,\n dialect: 'sqlite',\n out: outDir,\n dbCredentials: {\n url: dbUrl,\n }\n }) as DrizzleConfig & { dbCredentials: { url: string } }\n\n return nodeDbConfig\n}\n\nclass Db extends BaseDb implements IDb {\n static db: any\n\n constructor() {\n super()\n }\n\n static getAppDb() {\n return this.db\n }\n\n static isAppDbReady() {\n return true\n }\n\n static async prepareDb(filesDir: string, config?: DbConfig) {\n // Resolve and normalize the filesDir path\n const resolvedFilesDir = path.resolve(filesDir)\n \n // Ensure the filesDir exists first (parent directory)\n if (!fs.existsSync(resolvedFilesDir)) {\n fs.mkdirSync(resolvedFilesDir, { recursive: true })\n }\n \n const nodeDbConfig = await getConfig(resolvedFilesDir, config)\n const dbPath = nodeDbConfig.dbCredentials?.url || path.join(resolvedFilesDir, 'db', 'seed.db')\n\n // Ensure the database directory exists\n const dbDir = path.dirname(dbPath)\n const dbDirExists = fs.existsSync(dbDir)\n if (!dbDirExists) {\n fs.mkdirSync(dbDir, { recursive: true })\n }\n \n // Use the dbUrl from config if provided, otherwise construct from filesDir\n const dbUrl = config?.dbUrl \n ? (config.dbUrl.startsWith('file:') ? config.dbUrl : `file:${path.resolve(config.dbUrl)}`)\n : `file:${path.resolve(dbPath)}`\n const client = createClient({ url: dbUrl })\n \n const db = drizzle(client, {schema})\n \n const { apply, hasDataLoss, warnings, statementsToExecute } = await pushSQLiteSchema(schema, db);\n \n // You can inspect what will happen before applying\n await apply();\n\n this.db = db\n\n // OLD CODE: Resolve better-sqlite3 from project's node_modules first, then fall back to SDK's node_modules\n // This is important for tests and when the SDK is used as a dependency\n // const projectDir = path.dirname(filesDir) // filesDir is .seed, so projectDir is the project root\n // const projectBetterSqlite3Path = path.join(projectDir, 'node_modules', 'better-sqlite3')\n // \n // let Database: any\n // try {\n // const fs = await import('fs')\n // if (fs.existsSync(projectBetterSqlite3Path)) {\n // // Try to resolve from project's node_modules using the full path\n // // For Bun, we can try importing directly from the path\n // try {\n // // First try using createRequire (works in Node.js)\n // const { createRequire } = await import('module')\n // const projectRequire = createRequire(path.join(projectDir, 'package.json'))\n // const betterSqlite3Module = projectRequire('better-sqlite3')\n // Database = betterSqlite3Module.default || betterSqlite3Module\n // logger('[node/db/Db] Using better-sqlite3 from project node_modules via createRequire')\n // } catch (requireError: any) {\n // // If createRequire fails (e.g., in Bun), try direct path import\n // logger('[node/db/Db] createRequire failed, trying direct import:', requireError.message)\n // const betterSqlite3MainPath = path.join(projectBetterSqlite3Path, 'lib', 'database.js')\n // if (fs.existsSync(betterSqlite3MainPath)) {\n // // Use dynamic import with the full path\n // const betterSqlite3Module = await import(betterSqlite3MainPath)\n // Database = betterSqlite3Module.default || betterSqlite3Module.Database || betterSqlite3Module\n // logger('[node/db/Db] Using better-sqlite3 from project node_modules via direct import')\n // } else {\n // throw new Error(`better-sqlite3 main file not found at ${betterSqlite3MainPath}`)\n // }\n // }\n // } else {\n // // Fall back to regular import (from SDK's node_modules)\n // const betterSqlite3Module = await import('better-sqlite3')\n // Database = betterSqlite3Module.default || betterSqlite3Module\n // logger('[node/db/Db] Using better-sqlite3 from SDK node_modules')\n // }\n // } catch (importError: any) {\n // logger('[node/db/Db] Error importing better-sqlite3:', importError.message)\n // logger('[node/db/Db] projectDir:', projectDir)\n // logger('[node/db/Db] projectBetterSqlite3Path:', projectBetterSqlite3Path)\n // throw new Error(`Failed to import better-sqlite3: ${importError.message}. Please install better-sqlite3 in your project.`)\n // }\n\n // OLD CODE: Create Database instance\n // const sqlite = new Database(dbPath)\n // \n // OLD CODE: Create drizzle instance with the Database\n // const {drizzle} = await import('drizzle-orm/better-sqlite3')\n // this.db = drizzle(sqlite, {\n // logger: true,\n // })\n\n // // NEW CODE: Use libsql instead of better-sqlite3\n // // Resolve @libsql/client from project's node_modules first, then fall back to SDK's node_modules\n // const projectDir = path.dirname(filesDir) // filesDir is .seed, so projectDir is the project root\n // const projectLibsqlClientPath = path.join(projectDir, 'node_modules', '@libsql', 'client')\n \n // let createClient: any\n // try {\n // const fs = await import('fs')\n // if (fs.existsSync(projectLibsqlClientPath)) {\n // // Try to resolve from project's node_modules using the full path\n // try {\n // // First try using createRequire (works in Node.js)\n // const { createRequire } = await import('module')\n // const projectRequire = createRequire(path.join(projectDir, 'package.json'))\n // const libsqlClientModule = projectRequire('@libsql/client')\n // createClient = libsqlClientModule.createClient || libsqlClientModule.default?.createClient || libsqlClientModule.default\n // logger('[node/db/Db] Using @libsql/client from project node_modules via createRequire')\n // } catch (requireError: any) {\n // // If createRequire fails, try direct import\n // logger('[node/db/Db] createRequire failed, trying direct import:', requireError.message)\n // const libsqlClientModule = await import('@libsql/client')\n // createClient = libsqlClientModule.createClient\n // logger('[node/db/Db] Using @libsql/client from project node_modules via direct import')\n // }\n // } else {\n // // Fall back to regular import (from SDK's node_modules)\n // const libsqlClientModule = await import('@libsql/client')\n // createClient = libsqlClientModule.createClient\n // logger('[node/db/Db] Using @libsql/client from SDK node_modules')\n // }\n // } catch (importError: any) {\n // logger('[node/db/Db] Error importing @libsql/client:', importError.message)\n // logger('[node/db/Db] projectDir:', projectDir)\n // logger('[node/db/Db] projectLibsqlClientPath:', projectLibsqlClientPath)\n // throw new Error(`Failed to import @libsql/client: ${importError.message}. Please install @libsql/client in your project.`)\n // }\n\n // // Convert file path to file: URL for libsql\n // // If dbPath is already a file: URL, use it as is, otherwise convert it\n // const dbUrl = dbPath.startsWith('file:') ? dbPath : `file:${path.resolve(dbPath)}`\n \n // // Create libsql client instance\n // const client = createClient({ url: dbUrl })\n \n // // Create drizzle instance with the libsql client\n // const {drizzle} = await import('drizzle-orm/libsql')\n // this.db = drizzle(client, {\n // logger: true,\n // })\n\n // if (!this.db) {\n // throw new Error('Db not found')\n // }\n\n return this.db\n }\n\n static async connectToDb(pathToDir: string,) {\n\n return {\n id: this.db ? this.db.constructor.name : ''\n }\n }\n\n static async migrate(pathToDbDir: string, dbName: string, dbId: string) {\n const fs = await import('fs')\n const path = await import('path')\n \n // Ensure meta directory and _journal.json exist\n const metaDir = path.join(pathToDbDir, 'meta')\n const journalPath = path.join(metaDir, '_journal.json')\n \n try {\n if (!fs.existsSync(metaDir)) {\n fs.mkdirSync(metaDir, { recursive: true })\n }\n \n // Create a minimal _journal.json if it doesn't exist\n if (!fs.existsSync(journalPath)) {\n const minimalJournal = {\n version: \"7\",\n dialect: \"sqlite\",\n entries: []\n }\n fs.writeFileSync(journalPath, JSON.stringify(minimalJournal, null, 2))\n logger('Created minimal _journal.json file')\n } else {\n // Verify the journal file is valid JSON\n try {\n const journalContent = fs.readFileSync(journalPath, 'utf-8')\n const journal = JSON.parse(journalContent)\n if (!journal.dialect || !journal.version) {\n // Fix invalid journal\n const fixedJournal = {\n version: journal.version || \"7\",\n dialect: journal.dialect || \"sqlite\",\n entries: journal.entries || []\n }\n fs.writeFileSync(journalPath, JSON.stringify(fixedJournal, null, 2))\n logger('Fixed invalid _journal.json file')\n }\n } catch (parseError) {\n // If journal is invalid, recreate it\n const minimalJournal = {\n version: \"7\",\n dialect: \"sqlite\",\n entries: []\n }\n fs.writeFileSync(journalPath, JSON.stringify(minimalJournal, null, 2))\n logger('Recreated corrupted _journal.json file')\n }\n }\n } catch (error: any) {\n logger('Warning: Could not create meta/_journal.json:', error.message)\n // Continue anyway - the migrator might handle it\n }\n \n try {\n if (!this.db) {\n throw new Error('Database not initialized. Call prepareDb first.')\n }\n \n // OLD CODE: const {migrate} = await import('drizzle-orm/better-sqlite3/migrator')\n // migrationsFolder should point to the directory containing migration SQL files\n // In drizzle-kit, migrations are generated in the 'out' directory (which is pathToDbDir)\n // migrate(this.db, { migrationsFolder: pathToDbDir })\n \n // NEW CODE: Use libsql migrator\n const {migrate} = await import('drizzle-orm/libsql/migrator')\n // migrationsFolder should point to the directory containing migration SQL files\n // In drizzle-kit, migrations are generated in the 'out' directory (which is pathToDbDir)\n await migrate(this.db, { migrationsFolder: pathToDbDir })\n const queryResult = await this.db.select().from(appState)\n logger('queryResult', queryResult)\n } catch (error: any) {\n // Handle various migration errors gracefully in test environments\n const errorMessage = error.message || String(error) || ''\n const errorString = String(error)\n const isMigrationError = \n errorMessage.includes(\"Can't find meta/_journal.json\") || \n errorMessage.includes('_journal.json') ||\n errorMessage.includes(\"Cannot read properties of undefined\") ||\n errorMessage.includes(\"reading 'dialect'\") ||\n errorMessage.includes(\"undefined is not an object\") ||\n errorString.includes(\"dialect\") ||\n errorString.includes(\"undefined is not an object\")\n \n if (isMigrationError) {\n if (process.env.NODE_ENV === 'test' || process.env.IS_SEED_DEV) {\n logger('Warning: Migration failed, but continuing in test environment:', errorMessage || errorString)\n // Try to query the database anyway to see if it's usable\n try {\n if (this.db) {\n const queryResult = await this.db.select().from(appState)\n logger('Database is accessible despite migration error')\n return this.db\n }\n } catch (queryError) {\n logger('Database query also failed, but continuing in test environment')\n return this.db\n }\n }\n }\n throw error\n }\n\n return this.db\n }\n\n /**\n * Execute a reactive query that emits new results whenever the underlying data changes.\n * \n * NOTE: This is a stub implementation using polling. For production use, consider enhancing\n * with database triggers, change streams, or other real-time mechanisms.\n * \n * Currently supports Drizzle query builders. SQL tag functions are not supported in node\n * environment (use browser implementation for SQL tag functions).\n * \n * @param query - Drizzle query builder (SQL tag functions not supported in node)\n * @returns Observable that emits arrays of query results\n * \n * @example\n * ```typescript\n * import { models } from '@/seedSchema'\n * import { eq } from 'drizzle-orm'\n * \n * const appDb = Db.getAppDb()\n * const models$ = Db.liveQuery<ModelRow>(\n * appDb.select().from(models).where(eq(models.schemaFileId, schemaId))\n * )\n * \n * models$.subscribe(models => {\n * console.log('Models updated:', models)\n * })\n * ```\n */\n static liveQuery<T>(\n query: ((sql: any) => any) | any\n ): Observable<T[]> {\n if (!this.db) {\n throw new Error('Database not initialized. Call prepareDb first.')\n }\n \n // Polling interval (configurable, default: 1000ms)\n const pollInterval = 1000\n \n // Check if query is a function (SQL tag function) - not supported in node stub\n if (typeof query === 'function') {\n throw new Error('SQL tag functions are not supported in node liveQuery stub implementation. Use Drizzle query builders instead.')\n }\n \n // For Drizzle query builders, we need to execute them\n // Store the query builder for polling\n const queryBuilder = query\n \n return interval(pollInterval).pipe(\n startWith(0), // Execute immediately on subscription\n switchMap(async () => {\n try {\n // Execute the Drizzle query builder\n // Drizzle query builders return promises when executed\n const result = await Promise.resolve(queryBuilder)\n return result as T[]\n } catch (error) {\n logger('[Db.liveQuery] Error executing query:', error)\n throw error\n }\n }),\n distinctUntilChanged((prev, curr) => {\n // Only emit if results actually changed\n // Use JSON.stringify for deep comparison\n return JSON.stringify(prev) === JSON.stringify(curr)\n })\n )\n }\n}\n\nBaseDb.setPlatformClass(Db)\n\nexport { Db }\n"],"names":["fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,MAAM,GAAG,KAAK,CAAC,oBAAoB,CAAC;AAQ1C,MAAM,SAAS,GAAG,OAAO,UAAkB,EAAE,MAAiB,KAAI;;IAEhE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,OAAO,aAAa,CAAC;AACpD,IAAA,MAAM,YAA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KAAK;AAE1B,QAAA,OAAO,QAAQ,CAAC,YAAY,CAAC,CAAC,IAAI,CAChC,SAAS,CAAC,CAAC,CAAC;QACZ,SAAS,CAAC,YAAW;AACnB,YAAA,IAAI;;;gBAGF,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC;AAClD,gBAAA,OAAO,MAAa;YACtB;YAAE,OAAO,KAAK,EAAE;AACd,gBAAA,MAAM,CAAC,uCAAuC,EAAE,KAAK,CAAC;AACtD,gBAAA,MAAM,KAAK;YACb;QACF,CAAC,CAAC,EACF,oBAAoB,CAAC,CAAC,IAAI,EAAE,IAAI,KAAI;;;AAGlC,YAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;QACtD,CAAC,CAAC,CACH;IACH;AACD;AAED,MAAM,CAAC,gBAAgB,CAAC,EAAE,CAAC;;;;"}
1
+ {"version":3,"file":"Db-DjofXdeU.js","sources":["../src/node/db/Db.ts"],"sourcesContent":["import { BaseDb } from \"@/db/Db/BaseDb\";\nimport { IDb } from \"@/interfaces\";\nimport path from \"path\";\nimport { DrizzleConfig, } from \"drizzle-orm\";\nimport debug from 'debug'\nimport { appState } from '@/seedSchema'\nimport fs from 'fs'\nimport { createClient } from '@libsql/client'\nimport { drizzle } from 'drizzle-orm/libsql'\nimport { pushSQLiteSchema } from 'drizzle-kit/api'\nimport * as schema from '@/seedSchema'\nimport { Observable, interval, switchMap, distinctUntilChanged, startWith } from 'rxjs'\n\nconst logger = debug('seedSdk:node:db:Db')\n\nexport interface DbConfig {\n dbUrl?: string\n schemaDir?: string\n outDir?: string\n}\n\nconst getConfig = async (dotSeedDir: string, config?: DbConfig) => {\n // Create config inline - config values can be passed in or use defaults\n const { defineConfig } = await import('drizzle-kit')\n const appSchemaDir = config?.schemaDir || path.join(dotSeedDir, 'schema')\n const outDir = config?.outDir || `${dotSeedDir}/db`\n const dbUrl = config?.dbUrl || `${dotSeedDir}/db/seed.db`\n\n const nodeDbConfig = defineConfig({\n schema: appSchemaDir,\n dialect: 'sqlite',\n out: outDir,\n dbCredentials: {\n url: dbUrl,\n }\n }) as DrizzleConfig & { dbCredentials: { url: string } }\n\n return nodeDbConfig\n}\n\nclass Db extends BaseDb implements IDb {\n static db: any\n\n constructor() {\n super()\n }\n\n static getAppDb() {\n return this.db\n }\n\n static isAppDbReady() {\n return true\n }\n\n static async prepareDb(filesDir: string, config?: DbConfig) {\n // Resolve and normalize the filesDir path\n const resolvedFilesDir = path.resolve(filesDir)\n \n // Ensure the filesDir exists first (parent directory)\n if (!fs.existsSync(resolvedFilesDir)) {\n fs.mkdirSync(resolvedFilesDir, { recursive: true })\n }\n \n const nodeDbConfig = await getConfig(resolvedFilesDir, config)\n const dbPath = nodeDbConfig.dbCredentials?.url || path.join(resolvedFilesDir, 'db', 'seed.db')\n\n // Ensure the database directory exists\n const dbDir = path.dirname(dbPath)\n const dbDirExists = fs.existsSync(dbDir)\n if (!dbDirExists) {\n fs.mkdirSync(dbDir, { recursive: true })\n }\n \n // Use the dbUrl from config if provided, otherwise construct from filesDir\n const dbUrl = config?.dbUrl \n ? (config.dbUrl.startsWith('file:') ? config.dbUrl : `file:${path.resolve(config.dbUrl)}`)\n : `file:${path.resolve(dbPath)}`\n const client = createClient({ url: dbUrl })\n \n const db = drizzle(client, {schema})\n \n const { apply, hasDataLoss, warnings, statementsToExecute } = await pushSQLiteSchema(schema, db);\n \n // You can inspect what will happen before applying\n await apply();\n\n this.db = db\n\n // OLD CODE: Resolve better-sqlite3 from project's node_modules first, then fall back to SDK's node_modules\n // This is important for tests and when the SDK is used as a dependency\n // const projectDir = path.dirname(filesDir) // filesDir is .seed, so projectDir is the project root\n // const projectBetterSqlite3Path = path.join(projectDir, 'node_modules', 'better-sqlite3')\n // \n // let Database: any\n // try {\n // const fs = await import('fs')\n // if (fs.existsSync(projectBetterSqlite3Path)) {\n // // Try to resolve from project's node_modules using the full path\n // // For Bun, we can try importing directly from the path\n // try {\n // // First try using createRequire (works in Node.js)\n // const { createRequire } = await import('module')\n // const projectRequire = createRequire(path.join(projectDir, 'package.json'))\n // const betterSqlite3Module = projectRequire('better-sqlite3')\n // Database = betterSqlite3Module.default || betterSqlite3Module\n // logger('[node/db/Db] Using better-sqlite3 from project node_modules via createRequire')\n // } catch (requireError: any) {\n // // If createRequire fails (e.g., in Bun), try direct path import\n // logger('[node/db/Db] createRequire failed, trying direct import:', requireError.message)\n // const betterSqlite3MainPath = path.join(projectBetterSqlite3Path, 'lib', 'database.js')\n // if (fs.existsSync(betterSqlite3MainPath)) {\n // // Use dynamic import with the full path\n // const betterSqlite3Module = await import(betterSqlite3MainPath)\n // Database = betterSqlite3Module.default || betterSqlite3Module.Database || betterSqlite3Module\n // logger('[node/db/Db] Using better-sqlite3 from project node_modules via direct import')\n // } else {\n // throw new Error(`better-sqlite3 main file not found at ${betterSqlite3MainPath}`)\n // }\n // }\n // } else {\n // // Fall back to regular import (from SDK's node_modules)\n // const betterSqlite3Module = await import('better-sqlite3')\n // Database = betterSqlite3Module.default || betterSqlite3Module\n // logger('[node/db/Db] Using better-sqlite3 from SDK node_modules')\n // }\n // } catch (importError: any) {\n // logger('[node/db/Db] Error importing better-sqlite3:', importError.message)\n // logger('[node/db/Db] projectDir:', projectDir)\n // logger('[node/db/Db] projectBetterSqlite3Path:', projectBetterSqlite3Path)\n // throw new Error(`Failed to import better-sqlite3: ${importError.message}. Please install better-sqlite3 in your project.`)\n // }\n\n // OLD CODE: Create Database instance\n // const sqlite = new Database(dbPath)\n // \n // OLD CODE: Create drizzle instance with the Database\n // const {drizzle} = await import('drizzle-orm/better-sqlite3')\n // this.db = drizzle(sqlite, {\n // logger: true,\n // })\n\n // // NEW CODE: Use libsql instead of better-sqlite3\n // // Resolve @libsql/client from project's node_modules first, then fall back to SDK's node_modules\n // const projectDir = path.dirname(filesDir) // filesDir is .seed, so projectDir is the project root\n // const projectLibsqlClientPath = path.join(projectDir, 'node_modules', '@libsql', 'client')\n \n // let createClient: any\n // try {\n // const fs = await import('fs')\n // if (fs.existsSync(projectLibsqlClientPath)) {\n // // Try to resolve from project's node_modules using the full path\n // try {\n // // First try using createRequire (works in Node.js)\n // const { createRequire } = await import('module')\n // const projectRequire = createRequire(path.join(projectDir, 'package.json'))\n // const libsqlClientModule = projectRequire('@libsql/client')\n // createClient = libsqlClientModule.createClient || libsqlClientModule.default?.createClient || libsqlClientModule.default\n // logger('[node/db/Db] Using @libsql/client from project node_modules via createRequire')\n // } catch (requireError: any) {\n // // If createRequire fails, try direct import\n // logger('[node/db/Db] createRequire failed, trying direct import:', requireError.message)\n // const libsqlClientModule = await import('@libsql/client')\n // createClient = libsqlClientModule.createClient\n // logger('[node/db/Db] Using @libsql/client from project node_modules via direct import')\n // }\n // } else {\n // // Fall back to regular import (from SDK's node_modules)\n // const libsqlClientModule = await import('@libsql/client')\n // createClient = libsqlClientModule.createClient\n // logger('[node/db/Db] Using @libsql/client from SDK node_modules')\n // }\n // } catch (importError: any) {\n // logger('[node/db/Db] Error importing @libsql/client:', importError.message)\n // logger('[node/db/Db] projectDir:', projectDir)\n // logger('[node/db/Db] projectLibsqlClientPath:', projectLibsqlClientPath)\n // throw new Error(`Failed to import @libsql/client: ${importError.message}. Please install @libsql/client in your project.`)\n // }\n\n // // Convert file path to file: URL for libsql\n // // If dbPath is already a file: URL, use it as is, otherwise convert it\n // const dbUrl = dbPath.startsWith('file:') ? dbPath : `file:${path.resolve(dbPath)}`\n \n // // Create libsql client instance\n // const client = createClient({ url: dbUrl })\n \n // // Create drizzle instance with the libsql client\n // const {drizzle} = await import('drizzle-orm/libsql')\n // this.db = drizzle(client, {\n // logger: true,\n // })\n\n // if (!this.db) {\n // throw new Error('Db not found')\n // }\n\n return this.db\n }\n\n static async connectToDb(pathToDir: string,) {\n\n return {\n id: this.db ? this.db.constructor.name : ''\n }\n }\n\n static async migrate(pathToDbDir: string, dbName: string, dbId: string) {\n const fs = await import('fs')\n const path = await import('path')\n \n // Ensure meta directory and _journal.json exist\n const metaDir = path.join(pathToDbDir, 'meta')\n const journalPath = path.join(metaDir, '_journal.json')\n \n try {\n if (!fs.existsSync(metaDir)) {\n fs.mkdirSync(metaDir, { recursive: true })\n }\n \n // Create a minimal _journal.json if it doesn't exist\n if (!fs.existsSync(journalPath)) {\n const minimalJournal = {\n version: \"7\",\n dialect: \"sqlite\",\n entries: []\n }\n fs.writeFileSync(journalPath, JSON.stringify(minimalJournal, null, 2))\n logger('Created minimal _journal.json file')\n } else {\n // Verify the journal file is valid JSON\n try {\n const journalContent = fs.readFileSync(journalPath, 'utf-8')\n const journal = JSON.parse(journalContent)\n if (!journal.dialect || !journal.version) {\n // Fix invalid journal\n const fixedJournal = {\n version: journal.version || \"7\",\n dialect: journal.dialect || \"sqlite\",\n entries: journal.entries || []\n }\n fs.writeFileSync(journalPath, JSON.stringify(fixedJournal, null, 2))\n logger('Fixed invalid _journal.json file')\n }\n } catch (parseError) {\n // If journal is invalid, recreate it\n const minimalJournal = {\n version: \"7\",\n dialect: \"sqlite\",\n entries: []\n }\n fs.writeFileSync(journalPath, JSON.stringify(minimalJournal, null, 2))\n logger('Recreated corrupted _journal.json file')\n }\n }\n } catch (error: any) {\n logger('Warning: Could not create meta/_journal.json:', error.message)\n // Continue anyway - the migrator might handle it\n }\n \n try {\n if (!this.db) {\n throw new Error('Database not initialized. Call prepareDb first.')\n }\n \n // OLD CODE: const {migrate} = await import('drizzle-orm/better-sqlite3/migrator')\n // migrationsFolder should point to the directory containing migration SQL files\n // In drizzle-kit, migrations are generated in the 'out' directory (which is pathToDbDir)\n // migrate(this.db, { migrationsFolder: pathToDbDir })\n \n // NEW CODE: Use libsql migrator\n const {migrate} = await import('drizzle-orm/libsql/migrator')\n // migrationsFolder should point to the directory containing migration SQL files\n // In drizzle-kit, migrations are generated in the 'out' directory (which is pathToDbDir)\n await migrate(this.db, { migrationsFolder: pathToDbDir })\n const queryResult = await this.db.select().from(appState)\n logger('queryResult', queryResult)\n } catch (error: any) {\n // Handle various migration errors gracefully in test environments\n const errorMessage = error.message || String(error) || ''\n const errorString = String(error)\n const isMigrationError = \n errorMessage.includes(\"Can't find meta/_journal.json\") || \n errorMessage.includes('_journal.json') ||\n errorMessage.includes(\"Cannot read properties of undefined\") ||\n errorMessage.includes(\"reading 'dialect'\") ||\n errorMessage.includes(\"undefined is not an object\") ||\n errorString.includes(\"dialect\") ||\n errorString.includes(\"undefined is not an object\")\n \n if (isMigrationError) {\n if (process.env.NODE_ENV === 'test' || process.env.IS_SEED_DEV) {\n logger('Warning: Migration failed, but continuing in test environment:', errorMessage || errorString)\n // Try to query the database anyway to see if it's usable\n try {\n if (this.db) {\n const queryResult = await this.db.select().from(appState)\n logger('Database is accessible despite migration error')\n return this.db\n }\n } catch (queryError) {\n logger('Database query also failed, but continuing in test environment')\n return this.db\n }\n }\n }\n throw error\n }\n\n return this.db\n }\n\n /**\n * Execute a reactive query that emits new results whenever the underlying data changes.\n * \n * NOTE: This is a stub implementation using polling. For production use, consider enhancing\n * with database triggers, change streams, or other real-time mechanisms.\n * \n * Currently supports Drizzle query builders. SQL tag functions are not supported in node\n * environment (use browser implementation for SQL tag functions).\n * \n * @param query - Drizzle query builder (SQL tag functions not supported in node)\n * @returns Observable that emits arrays of query results\n * \n * @example\n * ```typescript\n * import { models } from '@/seedSchema'\n * import { eq } from 'drizzle-orm'\n * \n * const appDb = Db.getAppDb()\n * const models$ = Db.liveQuery<ModelRow>(\n * appDb.select().from(models).where(eq(models.schemaFileId, schemaId))\n * )\n * \n * models$.subscribe(models => {\n * console.log('Models updated:', models)\n * })\n * ```\n */\n static liveQuery<T>(\n query: ((sql: any) => any) | any\n ): Observable<T[]> {\n if (!this.db) {\n throw new Error('Database not initialized. Call prepareDb first.')\n }\n \n // Polling interval (configurable, default: 1000ms)\n const pollInterval = 1000\n \n // Check if query is a function (SQL tag function) - not supported in node stub\n if (typeof query === 'function') {\n throw new Error('SQL tag functions are not supported in node liveQuery stub implementation. Use Drizzle query builders instead.')\n }\n \n // For Drizzle query builders, we need to execute them\n // Store the query builder for polling\n const queryBuilder = query\n \n return interval(pollInterval).pipe(\n startWith(0), // Execute immediately on subscription\n switchMap(async () => {\n try {\n // Execute the Drizzle query builder\n // Drizzle query builders return promises when executed\n const result = await Promise.resolve(queryBuilder)\n return result as T[]\n } catch (error) {\n logger('[Db.liveQuery] Error executing query:', error)\n throw error\n }\n }),\n distinctUntilChanged((prev, curr) => {\n // Only emit if results actually changed\n // Use JSON.stringify for deep comparison\n return JSON.stringify(prev) === JSON.stringify(curr)\n })\n )\n }\n}\n\nBaseDb.setPlatformClass(Db)\n\nexport { Db }\n"],"names":["fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,MAAM,GAAG,KAAK,CAAC,oBAAoB,CAAC;AAQ1C,MAAM,SAAS,GAAG,OAAO,UAAkB,EAAE,MAAiB,KAAI;;IAEhE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,OAAO,aAAa,CAAC;AACpD,IAAA,MAAM,YAAY,GAAG,MAAM,EAAE,SAAS,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC;IACzE,MAAM,MAAM,GAAG,MAAM,EAAE,MAAM,IAAI,CAAA,EAAG,UAAU,CAAA,GAAA,CAAK;IACnD,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,IAAI,CAAA,EAAG,UAAU,CAAA,WAAA,CAAa;IAEzD,MAAM,YAAY,GAAG,YAAY,CAAC;AAChC,QAAA,MAAM,EAAE,YAAY;AACpB,QAAA,OAAO,EAAE,QAAQ;AACjB,QAAA,GAAG,EAAE,MAAM;AACX,QAAA,aAAa,EAAE;AACb,YAAA,GAAG,EAAE,KAAK;AACX;AACF,KAAA,CAAuD;AAExD,IAAA,OAAO,YAAY;AACrB,CAAC;AAED,MAAM,EAAG,SAAQ,MAAM,CAAA;AAGrB,IAAA,WAAA,GAAA;AACE,QAAA,KAAK,EAAE;IACT;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AC;;;;"}
@@ -1,19 +1,19 @@
1
- import { x as BaseEasClient, E as EAS_ENDPOINT } from './json-I3vJhXo8.js';
1
+ import { w as BaseEasClient, E as EAS_ENDPOINT } from './index-DPll6EAp.js';
2
2
  import { GraphQLClient } from 'graphql-request';
3
3
  import 'xstate';
4
+ import 'drizzle-orm/sqlite-core';
4
5
  import 'drizzle-orm';
6
+ import 'nanoid';
7
+ import 'nanoid-dictionary';
5
8
  import 'debug';
6
9
  import 'pluralize';
10
+ import 'ethers';
7
11
  import 'rxjs';
8
12
  import 'lodash-es';
9
13
  import 'drizzle-orm/casing';
10
- import '@sinclair/typebox';
11
- import 'arweave';
12
14
  import 'eventemitter3';
13
- import 'drizzle-orm/sqlite-core';
14
- import 'ethers';
15
- import 'nanoid';
16
- import 'nanoid-dictionary';
15
+ import 'arweave';
16
+ import '@sinclair/typebox';
17
17
 
18
18
  class EasClient extends BaseEasClient {
19
19
  static getEasClient() {
@@ -26,4 +26,4 @@ class EasClient extends BaseEasClient {
26
26
  BaseEasClient.setPlatformClass(EasClient);
27
27
 
28
28
  export { EasClient };
29
- //# sourceMappingURL=EasClient-BwhUcPjY.js.map
29
+ //# sourceMappingURL=EasClient-Aojewp6P.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"EasClient-CJSs38Db.js","sources":["../src/browser/helpers/EasClient.ts"],"sourcesContent":["import { BaseEasClient } from '@/helpers/EasClient/BaseEasClient'\nimport { EAS_ENDPOINT } from '@/client/constants'\nimport { GraphQLClient } from 'graphql-request'\n\nclass EasClient extends BaseEasClient {\n static getEasClient() {\n if (!this.easClient) {\n this.easClient = new GraphQLClient(EAS_ENDPOINT)\n }\n return this.easClient\n }\n}\n\nBaseEasClient.setPlatformClass(EasClient)\n\nexport { EasClient }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAIA,MAAM,SAAU,SAAQ,aAAa,CAAA;AACnC,IAAA,OAAO,YAAY,GAAA;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,aAAa,CAAC,YAAY,CAAC;QAClD;QACA,OAAO,IAAI,CAAC,SAAS;IACvB;AACD;AAED,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC;;;;"}
1
+ {"version":3,"file":"EasClient-Aojewp6P.js","sources":["../src/browser/helpers/EasClient.ts"],"sourcesContent":["import { BaseEasClient } from '@/helpers/EasClient/BaseEasClient'\nimport { EAS_ENDPOINT } from '@/client/constants'\nimport { GraphQLClient } from 'graphql-request'\n\nclass EasClient extends BaseEasClient {\n static getEasClient() {\n if (!this.easClient) {\n this.easClient = new GraphQLClient(EAS_ENDPOINT)\n }\n return this.easClient\n }\n}\n\nBaseEasClient.setPlatformClass(EasClient)\n\nexport { EasClient }\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAIA,MAAM,SAAU,SAAQ,aAAa,CAAA;AACnC,IAAA,OAAO,YAAY,GAAA;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,aAAa,CAAC,YAAY,CAAC;QAClD;QACA,OAAO,IAAI,CAAC,SAAS;IACvB;AACD;AAED,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC;;;;"}
@@ -1,19 +1,19 @@
1
- import { x as BaseEasClient, E as EAS_ENDPOINT } from './json-I3vJhXo8.js';
1
+ import { w as BaseEasClient, E as EAS_ENDPOINT } from './index-DPll6EAp.js';
2
2
  import { GraphQLClient } from 'graphql-request';
3
3
  import 'xstate';
4
+ import 'drizzle-orm/sqlite-core';
4
5
  import 'drizzle-orm';
6
+ import 'nanoid';
7
+ import 'nanoid-dictionary';
5
8
  import 'debug';
6
9
  import 'pluralize';
10
+ import 'ethers';
7
11
  import 'rxjs';
8
12
  import 'lodash-es';
9
13
  import 'drizzle-orm/casing';
10
- import '@sinclair/typebox';
11
- import 'arweave';
12
14
  import 'eventemitter3';
13
- import 'drizzle-orm/sqlite-core';
14
- import 'ethers';
15
- import 'nanoid';
16
- import 'nanoid-dictionary';
15
+ import 'arweave';
16
+ import '@sinclair/typebox';
17
17
 
18
18
  class EasClient extends BaseEasClient {
19
19
  static getEasClient() {
@@ -26,4 +26,4 @@ class EasClient extends BaseEasClient {
26
26
  BaseEasClient.setPlatformClass(EasClient);
27
27
 
28
28
  export { EasClient };
29
- //# sourceMappingURL=EasClient-CJSs38Db.js.map
29
+ //# sourceMappingURL=EasClient-BVFXp2O6.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"EasClient-BwhUcPjY.js","sources":["../src/node/helpers/EasClient.ts"],"sourcesContent":["import { BaseEasClient } from \"@/helpers/EasClient/BaseEasClient\"\nimport { EAS_ENDPOINT } from \"@/client/constants\"\nimport { GraphQLClient } from \"graphql-request\"\n\nclass EasClient extends BaseEasClient {\n static getEasClient() {\n if (!this.easClient) {\n this.easClient = new GraphQLClient(EAS_ENDPOINT)\n }\n return this.easClient\n }\n\n}\n\nBaseEasClient.setPlatformClass(EasClient)\n\nexport { EasClient }"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAIA,MAAM,SAAU,SAAQ,aAAa,CAAA;AACnC,IAAA,OAAO,YAAY,GAAA;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,aAAa,CAAC,YAAY,CAAC;QAClD;QACA,OAAO,IAAI,CAAC,SAAS;IACvB;AAED;AAED,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC;;;;"}
1
+ {"version":3,"file":"EasClient-BVFXp2O6.js","sources":["../src/node/helpers/EasClient.ts"],"sourcesContent":["import { BaseEasClient } from \"@/helpers/EasClient/BaseEasClient\"\nimport { EAS_ENDPOINT } from \"@/client/constants\"\nimport { GraphQLClient } from \"graphql-request\"\n\nclass EasClient extends BaseEasClient {\n static getEasClient() {\n if (!this.easClient) {\n this.easClient = new GraphQLClient(EAS_ENDPOINT)\n }\n return this.easClient\n }\n\n}\n\nBaseEasClient.setPlatformClass(EasClient)\n\nexport { EasClient }"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAIA,MAAM,SAAU,SAAQ,aAAa,CAAA;AACnC,IAAA,OAAO,YAAY,GAAA;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACnB,IAAI,CAAC,SAAS,GAAG,IAAI,aAAa,CAAC,YAAY,CAAC;QAClD;QACA,OAAO,IAAI,CAAC,SAAS;IACvB;AAED;AAED,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC;;;;"}