@orchestr-sh/orchestr 1.11.1 → 1.11.2

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 (303) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/dist/Cache/CacheManager.cjs +1 -1
  3. package/dist/Cache/CacheManager.mjs +1 -1
  4. package/dist/Cache/CacheManager.mjs.map +1 -1
  5. package/dist/Cache/Events/CacheFlushed.cjs +1 -1
  6. package/dist/Cache/Events/CacheFlushed.mjs +1 -1
  7. package/dist/Cache/Events/CacheFlushed.mjs.map +1 -1
  8. package/dist/Cache/Events/CacheHit.cjs +1 -1
  9. package/dist/Cache/Events/CacheHit.mjs +1 -1
  10. package/dist/Cache/Events/CacheHit.mjs.map +1 -1
  11. package/dist/Cache/Events/CacheMissed.cjs +1 -1
  12. package/dist/Cache/Events/CacheMissed.mjs +1 -1
  13. package/dist/Cache/Events/CacheMissed.mjs.map +1 -1
  14. package/dist/Cache/Events/KeyForgotten.cjs +1 -1
  15. package/dist/Cache/Events/KeyForgotten.mjs +1 -1
  16. package/dist/Cache/Events/KeyForgotten.mjs.map +1 -1
  17. package/dist/Cache/Events/KeyWritten.cjs +1 -1
  18. package/dist/Cache/Events/KeyWritten.mjs +1 -1
  19. package/dist/Cache/Events/KeyWritten.mjs.map +1 -1
  20. package/dist/Cache/Locks/CacheLock.cjs +1 -1
  21. package/dist/Cache/Locks/CacheLock.mjs +1 -1
  22. package/dist/Cache/Locks/CacheLock.mjs.map +1 -1
  23. package/dist/Cache/Locks/Lock.cjs +1 -1
  24. package/dist/Cache/Locks/Lock.mjs +1 -1
  25. package/dist/Cache/Locks/Lock.mjs.map +1 -1
  26. package/dist/Cache/Repository.cjs +1 -1
  27. package/dist/Cache/Repository.mjs +1 -1
  28. package/dist/Cache/Repository.mjs.map +1 -1
  29. package/dist/Cache/Stores/ArrayStore.cjs +1 -1
  30. package/dist/Cache/Stores/ArrayStore.mjs +1 -1
  31. package/dist/Cache/Stores/ArrayStore.mjs.map +1 -1
  32. package/dist/Cache/Stores/DatabaseStore.cjs +1 -1
  33. package/dist/Cache/Stores/DatabaseStore.mjs +1 -1
  34. package/dist/Cache/Stores/DatabaseStore.mjs.map +1 -1
  35. package/dist/Cache/Stores/FileStore.cjs +1 -1
  36. package/dist/Cache/Stores/FileStore.mjs +1 -1
  37. package/dist/Cache/Stores/FileStore.mjs.map +1 -1
  38. package/dist/Cache/Tags/TagSet.cjs +1 -1
  39. package/dist/Cache/Tags/TagSet.mjs +1 -1
  40. package/dist/Cache/Tags/TagSet.mjs.map +1 -1
  41. package/dist/Cache/Tags/TaggedCache.cjs +1 -1
  42. package/dist/Cache/Tags/TaggedCache.mjs +1 -1
  43. package/dist/Cache/Tags/TaggedCache.mjs.map +1 -1
  44. package/dist/Console/Commands/CacheClearCommand.cjs +1 -1
  45. package/dist/Console/Commands/CacheClearCommand.mjs +1 -1
  46. package/dist/Console/Commands/CacheClearCommand.mjs.map +1 -1
  47. package/dist/Console/Commands/CacheForgetCommand.cjs +1 -1
  48. package/dist/Console/Commands/CacheForgetCommand.mjs +1 -1
  49. package/dist/Console/Commands/CacheForgetCommand.mjs.map +1 -1
  50. package/dist/Console/Commands/CacheTableCommand.cjs +1 -1
  51. package/dist/Console/Commands/CacheTableCommand.mjs +1 -1
  52. package/dist/Console/Commands/CacheTableCommand.mjs.map +1 -1
  53. package/dist/Console/Commands/DeployCommand.mjs.map +1 -1
  54. package/dist/Console/Commands/DeployEnvCommand.mjs.map +1 -1
  55. package/dist/Console/Commands/DeployInitCommand.mjs.map +1 -1
  56. package/dist/Console/Commands/DeployProvisionCommand.mjs.map +1 -1
  57. package/dist/Console/Commands/DeployRollbackCommand.mjs.map +1 -1
  58. package/dist/Console/Commands/DeployServerCommand.mjs.map +1 -1
  59. package/dist/Console/Commands/DeployStatusCommand.mjs.map +1 -1
  60. package/dist/Console/Commands/EventCacheCommand.cjs +1 -1
  61. package/dist/Console/Commands/EventCacheCommand.mjs +1 -1
  62. package/dist/Console/Commands/EventCacheCommand.mjs.map +1 -1
  63. package/dist/Console/Commands/EventClearCommand.cjs +1 -1
  64. package/dist/Console/Commands/EventClearCommand.mjs +1 -1
  65. package/dist/Console/Commands/EventClearCommand.mjs.map +1 -1
  66. package/dist/Console/Commands/EventListCommand.cjs +1 -1
  67. package/dist/Console/Commands/EventListCommand.mjs +1 -1
  68. package/dist/Console/Commands/EventListCommand.mjs.map +1 -1
  69. package/dist/Console/Commands/MakeControllerCommand.cjs +1 -1
  70. package/dist/Console/Commands/MakeControllerCommand.mjs +1 -1
  71. package/dist/Console/Commands/MakeControllerCommand.mjs.map +1 -1
  72. package/dist/Console/Commands/MakeEventCommand.cjs +1 -1
  73. package/dist/Console/Commands/MakeEventCommand.mjs +1 -1
  74. package/dist/Console/Commands/MakeEventCommand.mjs.map +1 -1
  75. package/dist/Console/Commands/MakeJobCommand.cjs +1 -1
  76. package/dist/Console/Commands/MakeJobCommand.mjs +1 -1
  77. package/dist/Console/Commands/MakeJobCommand.mjs.map +1 -1
  78. package/dist/Console/Commands/MakeListenerCommand.cjs +1 -1
  79. package/dist/Console/Commands/MakeListenerCommand.mjs +1 -1
  80. package/dist/Console/Commands/MakeListenerCommand.mjs.map +1 -1
  81. package/dist/Console/Commands/MakeMigrationCommand.cjs +1 -1
  82. package/dist/Console/Commands/MakeMigrationCommand.mjs +1 -1
  83. package/dist/Console/Commands/MakeMigrationCommand.mjs.map +1 -1
  84. package/dist/Console/Commands/MakeSeederCommand.cjs +1 -1
  85. package/dist/Console/Commands/MakeSeederCommand.mjs +1 -1
  86. package/dist/Console/Commands/MakeSeederCommand.mjs.map +1 -1
  87. package/dist/Console/Commands/MakeViewCommand.cjs +1 -1
  88. package/dist/Console/Commands/MakeViewCommand.mjs +1 -1
  89. package/dist/Console/Commands/MakeViewCommand.mjs.map +1 -1
  90. package/dist/Console/Commands/MigrateCommand.cjs +1 -1
  91. package/dist/Console/Commands/MigrateCommand.mjs +1 -1
  92. package/dist/Console/Commands/MigrateCommand.mjs.map +1 -1
  93. package/dist/Console/Commands/MigrateFreshCommand.cjs +1 -1
  94. package/dist/Console/Commands/MigrateFreshCommand.mjs +1 -1
  95. package/dist/Console/Commands/MigrateFreshCommand.mjs.map +1 -1
  96. package/dist/Console/Commands/MigrateRefreshCommand.cjs +1 -1
  97. package/dist/Console/Commands/MigrateRefreshCommand.mjs +1 -1
  98. package/dist/Console/Commands/MigrateRefreshCommand.mjs.map +1 -1
  99. package/dist/Console/Commands/MigrateResetCommand.cjs +1 -1
  100. package/dist/Console/Commands/MigrateResetCommand.mjs +1 -1
  101. package/dist/Console/Commands/MigrateResetCommand.mjs.map +1 -1
  102. package/dist/Console/Commands/MigrateRollbackCommand.cjs +1 -1
  103. package/dist/Console/Commands/MigrateRollbackCommand.mjs +1 -1
  104. package/dist/Console/Commands/MigrateRollbackCommand.mjs.map +1 -1
  105. package/dist/Console/Commands/MigrateStatusCommand.cjs +1 -1
  106. package/dist/Console/Commands/MigrateStatusCommand.mjs +1 -1
  107. package/dist/Console/Commands/MigrateStatusCommand.mjs.map +1 -1
  108. package/dist/Console/Commands/QueueBatchesTableCommand.cjs +1 -1
  109. package/dist/Console/Commands/QueueBatchesTableCommand.mjs +1 -1
  110. package/dist/Console/Commands/QueueBatchesTableCommand.mjs.map +1 -1
  111. package/dist/Console/Commands/QueueClearCommand.cjs +1 -1
  112. package/dist/Console/Commands/QueueClearCommand.mjs +1 -1
  113. package/dist/Console/Commands/QueueClearCommand.mjs.map +1 -1
  114. package/dist/Console/Commands/QueueFailedCommand.cjs +1 -1
  115. package/dist/Console/Commands/QueueFailedCommand.mjs +1 -1
  116. package/dist/Console/Commands/QueueFailedCommand.mjs.map +1 -1
  117. package/dist/Console/Commands/QueueFailedTableCommand.cjs +1 -1
  118. package/dist/Console/Commands/QueueFailedTableCommand.mjs +1 -1
  119. package/dist/Console/Commands/QueueFailedTableCommand.mjs.map +1 -1
  120. package/dist/Console/Commands/QueueFlushCommand.cjs +1 -1
  121. package/dist/Console/Commands/QueueFlushCommand.mjs +1 -1
  122. package/dist/Console/Commands/QueueFlushCommand.mjs.map +1 -1
  123. package/dist/Console/Commands/QueueForgetCommand.cjs +1 -1
  124. package/dist/Console/Commands/QueueForgetCommand.mjs +1 -1
  125. package/dist/Console/Commands/QueueForgetCommand.mjs.map +1 -1
  126. package/dist/Console/Commands/QueueMonitorCommand.cjs +1 -1
  127. package/dist/Console/Commands/QueueMonitorCommand.mjs +1 -1
  128. package/dist/Console/Commands/QueueMonitorCommand.mjs.map +1 -1
  129. package/dist/Console/Commands/QueuePruneBatchesCommand.cjs +1 -1
  130. package/dist/Console/Commands/QueuePruneBatchesCommand.mjs +1 -1
  131. package/dist/Console/Commands/QueuePruneBatchesCommand.mjs.map +1 -1
  132. package/dist/Console/Commands/QueuePruneFailedCommand.cjs +1 -1
  133. package/dist/Console/Commands/QueuePruneFailedCommand.mjs +1 -1
  134. package/dist/Console/Commands/QueuePruneFailedCommand.mjs.map +1 -1
  135. package/dist/Console/Commands/QueueRestartCommand.cjs +1 -1
  136. package/dist/Console/Commands/QueueRestartCommand.mjs +1 -1
  137. package/dist/Console/Commands/QueueRestartCommand.mjs.map +1 -1
  138. package/dist/Console/Commands/QueueRetryCommand.cjs +1 -1
  139. package/dist/Console/Commands/QueueRetryCommand.mjs +1 -1
  140. package/dist/Console/Commands/QueueRetryCommand.mjs.map +1 -1
  141. package/dist/Console/Commands/QueueTableCommand.cjs +1 -1
  142. package/dist/Console/Commands/QueueTableCommand.mjs +1 -1
  143. package/dist/Console/Commands/QueueTableCommand.mjs.map +1 -1
  144. package/dist/Console/Commands/QueueWorkCommand.cjs +1 -1
  145. package/dist/Console/Commands/QueueWorkCommand.mjs +1 -1
  146. package/dist/Console/Commands/QueueWorkCommand.mjs.map +1 -1
  147. package/dist/Console/Commands/SeedCommand.cjs +1 -1
  148. package/dist/Console/Commands/SeedCommand.mjs +1 -1
  149. package/dist/Console/Commands/SeedCommand.mjs.map +1 -1
  150. package/dist/Console/ConsoleKernel.cjs +1 -1
  151. package/dist/Console/ConsoleKernel.mjs +1 -1
  152. package/dist/Console/ConsoleKernel.mjs.map +1 -1
  153. package/dist/Console/orchestr.mjs.map +1 -1
  154. package/dist/Container/Container.mjs.map +1 -1
  155. package/dist/Database/Adapters/DrizzleAdapter.cjs +1 -1
  156. package/dist/Database/Adapters/DrizzleAdapter.mjs +1 -1
  157. package/dist/Database/Adapters/DrizzleAdapter.mjs.map +1 -1
  158. package/dist/Database/Connection.cjs +1 -1
  159. package/dist/Database/Connection.mjs +1 -1
  160. package/dist/Database/Connection.mjs.map +1 -1
  161. package/dist/Database/DatabaseManager.cjs +1 -1
  162. package/dist/Database/DatabaseManager.mjs +1 -1
  163. package/dist/Database/DatabaseManager.mjs.map +1 -1
  164. package/dist/Database/Ensemble/Ensemble.mjs.map +1 -1
  165. package/dist/Database/Ensemble/EnsembleBuilder.mjs.map +1 -1
  166. package/dist/Database/Ensemble/EnsembleCollection.cjs +1 -1
  167. package/dist/Database/Ensemble/EnsembleCollection.mjs +1 -1
  168. package/dist/Database/Ensemble/EnsembleCollection.mjs.map +1 -1
  169. package/dist/Database/Ensemble/Relations/BelongsTo.mjs.map +1 -1
  170. package/dist/Database/Ensemble/Relations/BelongsToMany.cjs +1 -1
  171. package/dist/Database/Ensemble/Relations/BelongsToMany.mjs +1 -1
  172. package/dist/Database/Ensemble/Relations/BelongsToMany.mjs.map +1 -1
  173. package/dist/Database/Ensemble/Relations/HasMany.mjs.map +1 -1
  174. package/dist/Database/Ensemble/Relations/MorphTo.mjs.map +1 -1
  175. package/dist/Database/Ensemble/Relations/MorphToMany.mjs.map +1 -1
  176. package/dist/Database/Migrations/Blueprint.cjs +1 -1
  177. package/dist/Database/Migrations/Blueprint.mjs +1 -1
  178. package/dist/Database/Migrations/Blueprint.mjs.map +1 -1
  179. package/dist/Database/Migrations/MigrationCreator.cjs +1 -1
  180. package/dist/Database/Migrations/MigrationCreator.mjs +1 -1
  181. package/dist/Database/Migrations/MigrationCreator.mjs.map +1 -1
  182. package/dist/Database/Migrations/MigrationRepository.cjs +1 -1
  183. package/dist/Database/Migrations/MigrationRepository.mjs +1 -1
  184. package/dist/Database/Migrations/MigrationRepository.mjs.map +1 -1
  185. package/dist/Database/Migrations/Migrator.cjs +1 -1
  186. package/dist/Database/Migrations/Migrator.mjs +1 -1
  187. package/dist/Database/Migrations/Migrator.mjs.map +1 -1
  188. package/dist/Database/Migrations/SchemaBuilder.cjs +1 -1
  189. package/dist/Database/Migrations/SchemaBuilder.mjs +1 -1
  190. package/dist/Database/Migrations/SchemaBuilder.mjs.map +1 -1
  191. package/dist/Database/Query/Builder.cjs +1 -1
  192. package/dist/Database/Query/Builder.mjs +1 -1
  193. package/dist/Database/Query/Builder.mjs.map +1 -1
  194. package/dist/Database/Query/Expression.cjs +1 -1
  195. package/dist/Database/Query/Expression.mjs +1 -1
  196. package/dist/Database/Query/Expression.mjs.map +1 -1
  197. package/dist/Database/Seeders/SeederRunner.cjs +1 -1
  198. package/dist/Database/Seeders/SeederRunner.mjs +1 -1
  199. package/dist/Database/Seeders/SeederRunner.mjs.map +1 -1
  200. package/dist/Deploy/Deployer.cjs +1 -1
  201. package/dist/Deploy/Deployer.mjs +1 -1
  202. package/dist/Deploy/Deployer.mjs.map +1 -1
  203. package/dist/Deploy/ProjectConfig.mjs.map +1 -1
  204. package/dist/Deploy/Provisioner.cjs +1 -1
  205. package/dist/Deploy/Provisioner.mjs +1 -1
  206. package/dist/Deploy/Provisioner.mjs.map +1 -1
  207. package/dist/Deploy/SSHConnection.mjs.map +1 -1
  208. package/dist/Deploy/SymphonyClient.cjs +1 -1
  209. package/dist/Deploy/SymphonyClient.mjs +1 -1
  210. package/dist/Deploy/SymphonyClient.mjs.map +1 -1
  211. package/dist/Deploy/TarBuilder.mjs.map +1 -1
  212. package/dist/Deploy/prompt.mjs.map +1 -1
  213. package/dist/Events/Dispatcher.cjs +1 -1
  214. package/dist/Events/Dispatcher.mjs +1 -1
  215. package/dist/Events/Dispatcher.mjs.map +1 -1
  216. package/dist/Events/EventServiceProvider.cjs +1 -1
  217. package/dist/Events/EventServiceProvider.mjs.map +1 -1
  218. package/dist/Facades/Bus.mjs.map +1 -1
  219. package/dist/Facades/Cache.mjs.map +1 -1
  220. package/dist/Facades/Config.mjs.map +1 -1
  221. package/dist/Facades/DB.mjs.map +1 -1
  222. package/dist/Facades/Event.mjs.map +1 -1
  223. package/dist/Facades/Queue.mjs.map +1 -1
  224. package/dist/Facades/Route.mjs.map +1 -1
  225. package/dist/Facades/View.mjs.map +1 -1
  226. package/dist/Foundation/Application.mjs.map +1 -1
  227. package/dist/Foundation/Http/FormRequest.mjs.map +1 -1
  228. package/dist/Foundation/Http/Rules/AnyOfRule.mjs.map +1 -1
  229. package/dist/Foundation/Http/Rules/ImageFileRule.mjs.map +1 -1
  230. package/dist/Foundation/Http/Validator.mjs.map +1 -1
  231. package/dist/Queue/Batching/Batch.cjs +1 -1
  232. package/dist/Queue/Batching/Batch.mjs +1 -1
  233. package/dist/Queue/Batching/Batch.mjs.map +1 -1
  234. package/dist/Queue/Batching/PendingBatch.cjs +1 -1
  235. package/dist/Queue/Batching/PendingBatch.mjs +1 -1
  236. package/dist/Queue/Batching/PendingBatch.mjs.map +1 -1
  237. package/dist/Queue/Concerns/Dispatchable.mjs.map +1 -1
  238. package/dist/Queue/Drivers/DatabaseDriver.cjs +1 -1
  239. package/dist/Queue/Drivers/DatabaseDriver.mjs +1 -1
  240. package/dist/Queue/Drivers/DatabaseDriver.mjs.map +1 -1
  241. package/dist/Queue/Drivers/NullDriver.cjs +1 -1
  242. package/dist/Queue/Drivers/NullDriver.mjs +1 -1
  243. package/dist/Queue/Drivers/NullDriver.mjs.map +1 -1
  244. package/dist/Queue/Drivers/SyncDriver.cjs +1 -1
  245. package/dist/Queue/Drivers/SyncDriver.mjs +1 -1
  246. package/dist/Queue/Drivers/SyncDriver.mjs.map +1 -1
  247. package/dist/Queue/Events/JobExceptionOccurred.cjs +1 -1
  248. package/dist/Queue/Events/JobExceptionOccurred.mjs +1 -1
  249. package/dist/Queue/Events/JobExceptionOccurred.mjs.map +1 -1
  250. package/dist/Queue/Events/JobFailed.cjs +1 -1
  251. package/dist/Queue/Events/JobFailed.mjs +1 -1
  252. package/dist/Queue/Events/JobFailed.mjs.map +1 -1
  253. package/dist/Queue/Events/JobProcessed.cjs +1 -1
  254. package/dist/Queue/Events/JobProcessed.mjs +1 -1
  255. package/dist/Queue/Events/JobProcessed.mjs.map +1 -1
  256. package/dist/Queue/Events/JobProcessing.cjs +1 -1
  257. package/dist/Queue/Events/JobProcessing.mjs +1 -1
  258. package/dist/Queue/Events/JobProcessing.mjs.map +1 -1
  259. package/dist/Queue/Events/JobQueued.cjs +1 -1
  260. package/dist/Queue/Events/JobQueued.mjs +1 -1
  261. package/dist/Queue/Events/JobQueued.mjs.map +1 -1
  262. package/dist/Queue/Events/JobRetryRequested.cjs +1 -1
  263. package/dist/Queue/Events/JobRetryRequested.mjs +1 -1
  264. package/dist/Queue/Events/JobRetryRequested.mjs.map +1 -1
  265. package/dist/Queue/Events/WorkerStopping.cjs +1 -1
  266. package/dist/Queue/Events/WorkerStopping.mjs +1 -1
  267. package/dist/Queue/Events/WorkerStopping.mjs.map +1 -1
  268. package/dist/Queue/Failed/DatabaseFailedJobProvider.cjs +1 -1
  269. package/dist/Queue/Failed/DatabaseFailedJobProvider.mjs +1 -1
  270. package/dist/Queue/Failed/DatabaseFailedJobProvider.mjs.map +1 -1
  271. package/dist/Queue/Middleware/RateLimited.cjs +1 -1
  272. package/dist/Queue/Middleware/RateLimited.mjs +1 -1
  273. package/dist/Queue/Middleware/RateLimited.mjs.map +1 -1
  274. package/dist/Queue/Middleware/ThrottlesExceptions.cjs +1 -1
  275. package/dist/Queue/Middleware/ThrottlesExceptions.mjs +1 -1
  276. package/dist/Queue/Middleware/ThrottlesExceptions.mjs.map +1 -1
  277. package/dist/Queue/Middleware/WithoutOverlapping.cjs +1 -1
  278. package/dist/Queue/Middleware/WithoutOverlapping.mjs +1 -1
  279. package/dist/Queue/Middleware/WithoutOverlapping.mjs.map +1 -1
  280. package/dist/Queue/PendingChain.cjs +1 -1
  281. package/dist/Queue/PendingChain.mjs +1 -1
  282. package/dist/Queue/PendingChain.mjs.map +1 -1
  283. package/dist/Queue/PendingDispatch.cjs +1 -1
  284. package/dist/Queue/PendingDispatch.mjs +1 -1
  285. package/dist/Queue/PendingDispatch.mjs.map +1 -1
  286. package/dist/Queue/QueueManager.cjs +1 -1
  287. package/dist/Queue/QueueManager.mjs +1 -1
  288. package/dist/Queue/QueueManager.mjs.map +1 -1
  289. package/dist/Queue/QueueServiceProvider.mjs.map +1 -1
  290. package/dist/Queue/Workers/Worker.cjs +1 -1
  291. package/dist/Queue/Workers/Worker.mjs +1 -1
  292. package/dist/Queue/Workers/Worker.mjs.map +1 -1
  293. package/dist/Routing/Request.mjs.map +1 -1
  294. package/dist/Routing/Response.mjs.map +1 -1
  295. package/dist/Support/EventDiscovery.cjs +1 -1
  296. package/dist/Support/EventDiscovery.mjs +1 -1
  297. package/dist/Support/EventDiscovery.mjs.map +1 -1
  298. package/dist/Support/Testing/Fakes/EventFake.cjs +1 -1
  299. package/dist/Support/Testing/Fakes/EventFake.mjs +1 -1
  300. package/dist/Support/Testing/Fakes/EventFake.mjs.map +1 -1
  301. package/dist/Support/helpers.mjs.map +1 -1
  302. package/dist/View/Engines/TemplateEngine.mjs.map +1 -1
  303. package/package.json +17 -17
@@ -1 +1 @@
1
- {"version":3,"file":"Connection.mjs","names":[],"sources":["../../src/Database/Connection.ts"],"sourcesContent":["/**\n * Connection Class\n *\n * Represents a database connection\n */\n\nimport { DatabaseAdapter, DatabaseConfig } from './Contracts/DatabaseAdapter';\nimport { Builder } from './Query/Builder';\n\nexport class Connection {\n protected queryLog: Array<{ query: string; bindings: any[]; time: number }> = [];\n protected loggingEnabled: boolean = false;\n\n constructor(\n protected adapter: DatabaseAdapter,\n protected config: DatabaseConfig\n ) {}\n\n /**\n * Get a query builder instance\n */\n table(tableName: string): Builder {\n return new Builder(this.adapter).from(tableName);\n }\n\n /**\n * Execute a raw SQL query\n */\n async query(sql: string, bindings: any[] = []): Promise<any> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.query(sql, bindings));\n }\n\n /**\n * Execute a SELECT query\n */\n async select(sql: string, bindings: any[] = []): Promise<any[]> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.select(sql, bindings));\n }\n\n /**\n * Execute an INSERT query\n */\n async insert(sql: string, bindings: any[] = []): Promise<any> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.insert(sql, bindings));\n }\n\n /**\n * Execute an UPDATE query\n */\n async update(sql: string, bindings: any[] = []): Promise<number> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.update(sql, bindings));\n }\n\n /**\n * Execute a DELETE query\n */\n async delete(sql: string, bindings: any[] = []): Promise<number> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.delete(sql, bindings));\n }\n\n /**\n * Begin a transaction\n */\n async beginTransaction(): Promise<void> {\n await this.adapter.beginTransaction();\n }\n\n /**\n * Commit a transaction\n */\n async commit(): Promise<void> {\n await this.adapter.commit();\n }\n\n /**\n * Rollback a transaction\n */\n async rollback(): Promise<void> {\n await this.adapter.rollback();\n }\n\n /**\n * Execute a callback within a transaction\n */\n async transaction<T>(callback: (connection: Connection) => Promise<T>): Promise<T> {\n await this.beginTransaction();\n\n try {\n const result = await callback(this);\n await this.commit();\n return result;\n } catch (error) {\n await this.rollback();\n throw error;\n }\n }\n\n /**\n * Connect to the database\n */\n async connect(): Promise<void> {\n await this.adapter.connect();\n }\n\n /**\n * Disconnect from the database\n */\n async disconnect(): Promise<void> {\n await this.adapter.disconnect();\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.adapter.isConnected();\n }\n\n /**\n * Get all table names in the connected database\n */\n async getTables(): Promise<string[]> {\n return this.adapter.getTables();\n }\n\n /**\n * Get the underlying adapter\n */\n getAdapter(): DatabaseAdapter {\n return this.adapter;\n }\n\n /**\n * Get the configuration\n */\n getConfig(): DatabaseConfig {\n return this.config;\n }\n\n /**\n * Enable query logging\n */\n enableQueryLog(): void {\n this.loggingEnabled = true;\n }\n\n /**\n * Disable query logging\n */\n disableQueryLog(): void {\n this.loggingEnabled = false;\n }\n\n /**\n * Get the query log\n */\n getQueryLog(): Array<{ query: string; bindings: any[]; time: number }> {\n return this.queryLog;\n }\n\n /**\n * Clear the query log\n */\n flushQueryLog(): void {\n this.queryLog = [];\n }\n\n /**\n * Run a query with logging\n */\n protected async runQueryWithLogging<T>(query: string, bindings: any[], callback: () => Promise<T>): Promise<T> {\n if (!this.loggingEnabled) {\n return callback();\n }\n\n const start = Date.now();\n\n try {\n const result = await callback();\n const time = Date.now() - start;\n\n this.queryLog.push({ query, bindings, time });\n\n return result;\n } catch (error) {\n const time = Date.now() - start;\n this.queryLog.push({ query, bindings, time });\n throw error;\n }\n }\n}\n"],"mappings":"8CASA,IAAa,EAAb,KAAwB,CACtB,SAA8E,EAAE,CAChF,eAAoC,GAEpC,YACE,EACA,EACA,CAFU,KAAA,QAAA,EACA,KAAA,OAAA,EAMZ,MAAM,EAA4B,CAChC,OAAO,IAAI,EAAQ,KAAK,QAAQ,CAAC,KAAK,EAAU,CAMlD,MAAM,MAAM,EAAa,EAAkB,EAAE,CAAgB,CAC3D,OAAO,KAAK,oBAAoB,EAAK,MAAgB,KAAK,QAAQ,MAAM,EAAK,EAAS,CAAC,CAMzF,MAAM,OAAO,EAAa,EAAkB,EAAE,CAAkB,CAC9D,OAAO,KAAK,oBAAoB,EAAK,MAAgB,KAAK,QAAQ,OAAO,EAAK,EAAS,CAAC,CAM1F,MAAM,OAAO,EAAa,EAAkB,EAAE,CAAgB,CAC5D,OAAO,KAAK,oBAAoB,EAAK,MAAgB,KAAK,QAAQ,OAAO,EAAK,EAAS,CAAC,CAM1F,MAAM,OAAO,EAAa,EAAkB,EAAE,CAAmB,CAC/D,OAAO,KA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K,CAAG,EAE1B,MADA,KAAK,SAAS,KAAK,CAAE,QAAO,WAAU,OAAM,CAAC,CACvC"}
1
+ {"version":3,"file":"Connection.mjs","names":[],"sources":["../../src/Database/Connection.ts"],"sourcesContent":["/**\n * Connection Class\n *\n * Represents a database connection\n */\n\nimport { DatabaseAdapter, DatabaseConfig } from './Contracts/DatabaseAdapter';\nimport { Builder } from './Query/Builder';\n\nexport class Connection {\n protected queryLog: Array<{ query: string; bindings: any[]; time: number }> = [];\n protected loggingEnabled: boolean = false;\n\n constructor(\n protected adapter: DatabaseAdapter,\n protected config: DatabaseConfig\n ) {}\n\n /**\n * Get a query builder instance\n */\n table(tableName: string): Builder {\n return new Builder(this.adapter).from(tableName);\n }\n\n /**\n * Execute a raw SQL query\n */\n async query(sql: string, bindings: any[] = []): Promise<any> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.query(sql, bindings));\n }\n\n /**\n * Execute a SELECT query\n */\n async select(sql: string, bindings: any[] = []): Promise<any[]> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.select(sql, bindings));\n }\n\n /**\n * Execute an INSERT query\n */\n async insert(sql: string, bindings: any[] = []): Promise<any> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.insert(sql, bindings));\n }\n\n /**\n * Execute an UPDATE query\n */\n async update(sql: string, bindings: any[] = []): Promise<number> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.update(sql, bindings));\n }\n\n /**\n * Execute a DELETE query\n */\n async delete(sql: string, bindings: any[] = []): Promise<number> {\n return this.runQueryWithLogging(sql, bindings, () => this.adapter.delete(sql, bindings));\n }\n\n /**\n * Begin a transaction\n */\n async beginTransaction(): Promise<void> {\n await this.adapter.beginTransaction();\n }\n\n /**\n * Commit a transaction\n */\n async commit(): Promise<void> {\n await this.adapter.commit();\n }\n\n /**\n * Rollback a transaction\n */\n async rollback(): Promise<void> {\n await this.adapter.rollback();\n }\n\n /**\n * Execute a callback within a transaction\n */\n async transaction<T>(callback: (connection: Connection) => Promise<T>): Promise<T> {\n await this.beginTransaction();\n\n try {\n const result = await callback(this);\n await this.commit();\n return result;\n } catch (error) {\n await this.rollback();\n throw error;\n }\n }\n\n /**\n * Connect to the database\n */\n async connect(): Promise<void> {\n await this.adapter.connect();\n }\n\n /**\n * Disconnect from the database\n */\n async disconnect(): Promise<void> {\n await this.adapter.disconnect();\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.adapter.isConnected();\n }\n\n /**\n * Get all table names in the connected database\n */\n async getTables(): Promise<string[]> {\n return this.adapter.getTables();\n }\n\n /**\n * Get the underlying adapter\n */\n getAdapter(): DatabaseAdapter {\n return this.adapter;\n }\n\n /**\n * Get the configuration\n */\n getConfig(): DatabaseConfig {\n return this.config;\n }\n\n /**\n * Enable query logging\n */\n enableQueryLog(): void {\n this.loggingEnabled = true;\n }\n\n /**\n * Disable query logging\n */\n disableQueryLog(): void {\n this.loggingEnabled = false;\n }\n\n /**\n * Get the query log\n */\n getQueryLog(): Array<{ query: string; bindings: any[]; time: number }> {\n return this.queryLog;\n }\n\n /**\n * Clear the query log\n */\n flushQueryLog(): void {\n this.queryLog = [];\n }\n\n /**\n * Run a query with logging\n */\n protected async runQueryWithLogging<T>(query: string, bindings: any[], callback: () => Promise<T>): Promise<T> {\n if (!this.loggingEnabled) {\n return callback();\n }\n\n const start = Date.now();\n\n try {\n const result = await callback();\n const time = Date.now() - start;\n\n this.queryLog.push({ query, bindings, time });\n\n return result;\n } catch (error) {\n const time = Date.now() - start;\n this.queryLog.push({ query, bindings, time });\n throw error;\n }\n }\n}\n"],"mappings":"8CASA,IAAa,EAAb,KAAwB,CAKV,QACA,OALZ,SAA8E,EAAE,CAChF,eAAoC,GAEpC,YACE,EACA,EACA,CAFU,KAAA,QAAA,EACA,KAAA,OAAA,EAMZ,MAAM,EAA4B,CAChC,OAAO,IAAI,EAAQ,KAAK,QAAQ,CAAC,KAAK,EAAU,CAMlD,MAAM,MAAM,EAAa,EAAkB,EAAE,CA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iBAAwB,CACtB,KAAK,eAAiB,GAMxB,aAAuE,CACrE,OAAO,KAAK,SAMd,eAAsB,CACpB,KAAK,SAAW,EAAE,CAMpB,MAAgB,oBAAuB,EAAe,EAAiB,EAAwC,CAC7G,GAAI,CAAC,KAAK,eACR,OAAO,GAAU,CAGnB,IAAM,EAAQ,KAAK,KAAK,CAExB,GAAI,CACF,IAAM,EAAS,MAAM,GAAU,CACzB,EAAO,KAAK,KAAK,CAAG,EAI1B,OAFA,KAAK,SAAS,KAAK,CAAE,QAAO,WAAU,OAAM,CAAC,CAEtC,QACA,EAAO,CACd,IAAM,EAAO,KAAK,KAAK,CAAG,EAE1B,MADA,KAAK,SAAS,KAAK,CAAE,QAAO,WAAU,OAAM,CAAC,CACvC"}
@@ -1 +1 @@
1
- require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./Connection.cjs`);var t=class{connections=new Map;adapterFactories=new Map;constructor(e){this.config=e}registerAdapter(e,t){this.adapterFactories.set(e,t)}connection(e){let t=e||this.config.default;if(this.connections.has(t))return this.connections.get(t);let n=this.createConnection(t);return this.connections.set(t,n),n}createConnection(t){let n=this.config.connections[t];if(!n)throw Error(`Database connection [${t}] not configured.`);let r=this.adapterFactories.get(n.adapter);if(!r)throw Error(`Database adapter [${n.adapter}] not registered.`);return new e.Connection(r(n),n)}async disconnect(e){let t=e||this.config.default,n=this.connections.get(t);n&&(await n.disconnect(),this.connections.delete(t))}async disconnectAll(){let e=Array.from(this.connections.keys()).map(e=>this.disconnect(e));await Promise.all(e)}async purge(e){await this.disconnect(e)}getDefaultConnection(){return this.config.default}setDefaultConnection(e){this.config.default=e}getConnections(){return Object.keys(this.config.connections)}extend(e,t){this[e]=t}};exports.DatabaseManager=t;
1
+ require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./Connection.cjs`);var t=class{config;connections=new Map;adapterFactories=new Map;constructor(e){this.config=e}registerAdapter(e,t){this.adapterFactories.set(e,t)}connection(e){let t=e||this.config.default;if(this.connections.has(t))return this.connections.get(t);let n=this.createConnection(t);return this.connections.set(t,n),n}createConnection(t){let n=this.config.connections[t];if(!n)throw Error(`Database connection [${t}] not configured.`);let r=this.adapterFactories.get(n.adapter);if(!r)throw Error(`Database adapter [${n.adapter}] not registered.`);return new e.Connection(r(n),n)}async disconnect(e){let t=e||this.config.default,n=this.connections.get(t);n&&(await n.disconnect(),this.connections.delete(t))}async disconnectAll(){let e=Array.from(this.connections.keys()).map(e=>this.disconnect(e));await Promise.all(e)}async purge(e){await this.disconnect(e)}getDefaultConnection(){return this.config.default}setDefaultConnection(e){this.config.default=e}getConnections(){return Object.keys(this.config.connections)}extend(e,t){this[e]=t}};exports.DatabaseManager=t;
@@ -1,2 +1,2 @@
1
- import{Connection as e}from"./Connection.mjs";var t=class{connections=new Map;adapterFactories=new Map;constructor(e){this.config=e}registerAdapter(e,t){this.adapterFactories.set(e,t)}connection(e){let t=e||this.config.default;if(this.connections.has(t))return this.connections.get(t);let n=this.createConnection(t);return this.connections.set(t,n),n}createConnection(t){let n=this.config.connections[t];if(!n)throw Error(`Database connection [${t}] not configured.`);let r=this.adapterFactories.get(n.adapter);if(!r)throw Error(`Database adapter [${n.adapter}] not registered.`);return new e(r(n),n)}async disconnect(e){let t=e||this.config.default,n=this.connections.get(t);n&&(await n.disconnect(),this.connections.delete(t))}async disconnectAll(){let e=Array.from(this.connections.keys()).map(e=>this.disconnect(e));await Promise.all(e)}async purge(e){await this.disconnect(e)}getDefaultConnection(){return this.config.default}setDefaultConnection(e){this.config.default=e}getConnections(){return Object.keys(this.config.connections)}extend(e,t){this[e]=t}};export{t as DatabaseManager};
1
+ import{Connection as e}from"./Connection.mjs";var t=class{config;connections=new Map;adapterFactories=new Map;constructor(e){this.config=e}registerAdapter(e,t){this.adapterFactories.set(e,t)}connection(e){let t=e||this.config.default;if(this.connections.has(t))return this.connections.get(t);let n=this.createConnection(t);return this.connections.set(t,n),n}createConnection(t){let n=this.config.connections[t];if(!n)throw Error(`Database connection [${t}] not configured.`);let r=this.adapterFactories.get(n.adapter);if(!r)throw Error(`Database adapter [${n.adapter}] not registered.`);return new e(r(n),n)}async disconnect(e){let t=e||this.config.default,n=this.connections.get(t);n&&(await n.disconnect(),this.connections.delete(t))}async disconnectAll(){let e=Array.from(this.connections.keys()).map(e=>this.disconnect(e));await Promise.all(e)}async purge(e){await this.disconnect(e)}getDefaultConnection(){return this.config.default}setDefaultConnection(e){this.config.default=e}getConnections(){return Object.keys(this.config.connections)}extend(e,t){this[e]=t}};export{t as DatabaseManager};
2
2
  //# sourceMappingURL=DatabaseManager.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"DatabaseManager.mjs","names":[],"sources":["../../src/Database/DatabaseManager.ts"],"sourcesContent":["/**\n * DatabaseManager Class\n *\n * Manages multiple database connections\n */\n\nimport { Connection } from './Connection';\nimport { DatabaseAdapter, DatabaseConfig } from './Contracts/DatabaseAdapter';\n\nexport interface DatabaseConnectionConfig extends DatabaseConfig {\n adapter: string;\n}\n\nexport interface DatabaseManagerConfig {\n default: string;\n connections: Record<string, DatabaseConnectionConfig>;\n}\n\nexport class DatabaseManager {\n protected connections: Map<string, Connection> = new Map();\n protected adapterFactories: Map<string, (config: DatabaseConfig) => DatabaseAdapter> = new Map();\n\n constructor(protected config: DatabaseManagerConfig) {}\n\n /**\n * Register an adapter factory\n */\n registerAdapter(name: string, factory: (config: DatabaseConfig) => DatabaseAdapter): void {\n this.adapterFactories.set(name, factory);\n }\n\n /**\n * Get a database connection\n */\n connection(name?: string): Connection {\n const connectionName = name || this.config.default;\n\n // Return existing connection if available\n if (this.connections.has(connectionName)) {\n return this.connections.get(connectionName)!;\n }\n\n // Create new connection\n const connection = this.createConnection(connectionName);\n this.connections.set(connectionName, connection);\n\n return connection;\n }\n\n /**\n * Create a new connection\n */\n protected createConnection(name: string): Connection {\n const config = this.config.connections[name];\n\n if (!config) {\n throw new Error(`Database connection [${name}] not configured.`);\n }\n\n const adapterFactory = this.adapterFactories.get(config.adapter);\n\n if (!adapterFactory) {\n throw new Error(`Database adapter [${config.adapter}] not registered.`);\n }\n\n const adapter = adapterFactory(config);\n return new Connection(adapter, config);\n }\n\n /**\n * Disconnect a connection\n */\n async disconnect(name?: string): Promise<void> {\n const connectionName = name || this.config.default;\n const connection = this.connections.get(connectionName);\n\n if (connection) {\n await connection.disconnect();\n this.connections.delete(connectionName);\n }\n }\n\n /**\n * Disconnect all connections\n */\n async disconnectAll(): Promise<void> {\n const promises = Array.from(this.connections.keys()).map((name) => this.disconnect(name));\n await Promise.all(promises);\n }\n\n /**\n * Purge a connection (disconnect and remove from cache)\n */\n async purge(name?: string): Promise<void> {\n await this.disconnect(name);\n }\n\n /**\n * Get the default connection name\n */\n getDefaultConnection(): string {\n return this.config.default;\n }\n\n /**\n * Set the default connection name\n */\n setDefaultConnection(name: string): void {\n this.config.default = name;\n }\n\n /**\n * Get all connection names\n */\n getConnections(): string[] {\n return Object.keys(this.config.connections);\n }\n\n /**\n * Extend the database manager with a macro\n */\n extend(name: string, resolver: () => any): void {\n (this as any)[name] = resolver;\n }\n}\n"],"mappings":"8CAkBA,IAAa,EAAb,KAA6B,CAC3B,YAAiD,IAAI,IACrD,iBAAuF,IAAI,IAE3F,YAAY,EAAyC,CAA/B,KAAA,OAAA,EAKtB,gBAAgB,EAAc,EAA4D,CACxF,KAAK,iBAAiB,IAAI,EAAM,EAAQ,CAM1C,WAAW,EAA2B,CACpC,IAAM,EAAiB,GAAQ,KAAK,OAAO,QAG3C,GAAI,KAAK,YAAY,IAAI,EAAe,CACtC,OAAO,KAAK,YAAY,IAAI,EAAe,CAI7C,IAAM,EAAa,KAAK,iBAAiB,EAAe,CAGxD,OAFA,KAAK,YAAY,IAAI,EAAgB,EAAW,CAEzC,EAMT,iBAA2B,EAA0B,CACnD,IAAM,EAAS,KAAK,OAAO,YAAY,GAEvC,GAAI,CAAC,EACH,MAAU,MAAM,wBAAwB,EAAK,mBAAmB,CAGlE,IAAM,EAAiB,KAAK,iBAAiB,IAAI,EAAO,QAAQ,CAEhE,GAAI,CAAC,EACH,MAAU,MAAM,qBAAqB,EAAO,QAAQ,mBAAmB,CAIzE,OAAO,IAAI,EADK,EAAe,EAAO,CACP,EAAO,CAMxC,MAAM,WAAW,EAA8B,CAC7C,IAAM,EAAiB,GAAQ,KAAK,OAAO,QACrC,EAAa,KAAK,YAAY,IAAI,EAAe,CAEnD,IACF,MAAM,EAAW,YAAY,CAC7B,KAAK,YAAY,OAAO,EAAe,EAO3C,MAAM,eAA+B,CACnC,IAAM,EAAW,MAAM,KAAK,KAAK,YAAY,MAAM,CAAC,CAAC,IAAK,GAAS,KAAK,WAAW,EAAK,CAAC,CACzF,MAAM,QAAQ,IAAI,EAAS,CAM7B,MAAM,MAAM,EAA8B,CACxC,MAAM,KAAK,WAAW,EAAK,CAM7B,sBAA+B,CAC7B,OAAO,KAAK,OAAO,QAMrB,qBAAqB,EAAoB,CACvC,KAAK,OAAO,QAAU,EAMxB,gBAA2B,CACzB,OAAO,OAAO,KAAK,KAAK,OAAO,YAAY,CAM7C,OAAO,EAAc,EAA2B,CAC7C,KAAa,GAAQ"}
1
+ {"version":3,"file":"DatabaseManager.mjs","names":[],"sources":["../../src/Database/DatabaseManager.ts"],"sourcesContent":["/**\n * DatabaseManager Class\n *\n * Manages multiple database connections\n */\n\nimport { Connection } from './Connection';\nimport { DatabaseAdapter, DatabaseConfig } from './Contracts/DatabaseAdapter';\n\nexport interface DatabaseConnectionConfig extends DatabaseConfig {\n adapter: string;\n}\n\nexport interface DatabaseManagerConfig {\n default: string;\n connections: Record<string, DatabaseConnectionConfig>;\n}\n\nexport class DatabaseManager {\n protected connections: Map<string, Connection> = new Map();\n protected adapterFactories: Map<string, (config: DatabaseConfig) => DatabaseAdapter> = new Map();\n\n constructor(protected config: DatabaseManagerConfig) {}\n\n /**\n * Register an adapter factory\n */\n registerAdapter(name: string, factory: (config: DatabaseConfig) => DatabaseAdapter): void {\n this.adapterFactories.set(name, factory);\n }\n\n /**\n * Get a database connection\n */\n connection(name?: string): Connection {\n const connectionName = name || this.config.default;\n\n // Return existing connection if available\n if (this.connections.has(connectionName)) {\n return this.connections.get(connectionName)!;\n }\n\n // Create new connection\n const connection = this.createConnection(connectionName);\n this.connections.set(connectionName, connection);\n\n return connection;\n }\n\n /**\n * Create a new connection\n */\n protected createConnection(name: string): Connection {\n const config = this.config.connections[name];\n\n if (!config) {\n throw new Error(`Database connection [${name}] not configured.`);\n }\n\n const adapterFactory = this.adapterFactories.get(config.adapter);\n\n if (!adapterFactory) {\n throw new Error(`Database adapter [${config.adapter}] not registered.`);\n }\n\n const adapter = adapterFactory(config);\n return new Connection(adapter, config);\n }\n\n /**\n * Disconnect a connection\n */\n async disconnect(name?: string): Promise<void> {\n const connectionName = name || this.config.default;\n const connection = this.connections.get(connectionName);\n\n if (connection) {\n await connection.disconnect();\n this.connections.delete(connectionName);\n }\n }\n\n /**\n * Disconnect all connections\n */\n async disconnectAll(): Promise<void> {\n const promises = Array.from(this.connections.keys()).map((name) => this.disconnect(name));\n await Promise.all(promises);\n }\n\n /**\n * Purge a connection (disconnect and remove from cache)\n */\n async purge(name?: string): Promise<void> {\n await this.disconnect(name);\n }\n\n /**\n * Get the default connection name\n */\n getDefaultConnection(): string {\n return this.config.default;\n }\n\n /**\n * Set the default connection name\n */\n setDefaultConnection(name: string): void {\n this.config.default = name;\n }\n\n /**\n * Get all connection names\n */\n getConnections(): string[] {\n return Object.keys(this.config.connections);\n }\n\n /**\n * Extend the database manager with a macro\n */\n extend(name: string, resolver: () => any): void {\n (this as any)[name] = resolver;\n }\n}\n"],"mappings":"8CAkBA,IAAa,EAAb,KAA6B,CAIL,OAHtB,YAAiD,IAAI,IACrD,iBAAuF,IAAI,IAE3F,YAAY,EAAyC,CAA/B,KAAA,OAAA,EAKtB,gBAAgB,EAAc,EAA4D,CACxF,KAAK,iBAAiB,IAAI,EAAM,EAAQ,CAM1C,WAAW,EAA2B,CACpC,IAAM,EAAiB,GAAQ,KAAK,OAAO,QAG3C,GAAI,KAAK,YAAY,IAAI,EAAe,CACtC,OAAO,KAAK,YAAY,IAAI,EAAe,CAI7C,IAAM,EAAa,KAAK,iBAAiB,EAAe,CAGxD,OAFA,KAAK,YAAY,IAAI,EAAgB,EAAW,CAEzC,EAMT,iBAA2B,EAA0B,CACnD,IAAM,EAAS,KAAK,OAAO,YAAY,GAEvC,GAAI,CAAC,EACH,MAAU,MAAM,wBAAwB,EAAK,mBAAmB,CAGlE,IAAM,EAAiB,KAAK,iBAAiB,IAAI,EAAO,QAAQ,CAEhE,GAAI,CAAC,EACH,MAAU,MAAM,qBAAqB,EAAO,QAAQ,mBAAmB,CAIzE,OAAO,IAAI,EADK,EAAe,EACF,CAAE,EAAO,CAMxC,MAAM,WAAW,EAA8B,CAC7C,IAAM,EAAiB,GAAQ,KAAK,OAAO,QACrC,EAAa,KAAK,YAAY,IAAI,EAAe,CAEnD,IACF,MAAM,EAAW,YAAY,CAC7B,KAAK,YAAY,OAAO,EAAe,EAO3C,MAAM,eAA+B,CACnC,IAAM,EAAW,MAAM,KAAK,KAAK,YAAY,MAAM,CAAC,CAAC,IAAK,GAAS,KAAK,WAAW,EAAK,CAAC,CACzF,MAAM,QAAQ,IAAI,EAAS,CAM7B,MAAM,MAAM,EAA8B,CACxC,MAAM,KAAK,WAAW,EAAK,CAM7B,sBAA+B,CAC7B,OAAO,KAAK,OAAO,QAMrB,qBAAqB,EAAoB,CACvC,KAAK,OAAO,QAAU,EAMxB,gBAA2B,CACzB,OAAO,OAAO,KAAK,KAAK,OAAO,YAAY,CAM7C,OAAO,EAAc,EAA2B,CAC9C,KAAc,GAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"Ensemble.mjs","names":[],"sources":["../../../src/Database/Ensemble/Ensemble.ts"],"sourcesContent":["/**\n * Ensemble Class\n *\n * Base class for Ensemble models with ActiveRecord pattern\n * In Orchestr, your data models are called Ensembles - groups that work in harmony\n */\n\nimport { Connection } from '@/Database/Connection';\nimport { DatabaseManager } from '@/Database/DatabaseManager';\nimport { HasRelationshipsMixin } from './Concerns/HasRelationships';\nimport { EnsembleBuilder } from './EnsembleBuilder';\nimport {\n ModelRetrieved,\n ModelCreating,\n ModelCreated,\n ModelUpdating,\n ModelUpdated,\n ModelSaving,\n ModelSaved,\n ModelDeleting,\n ModelDeleted,\n} from './Events';\n\nexport abstract class Ensemble extends HasRelationshipsMixin {\n /**\n * The connection resolver instance\n */\n protected static connectionResolver: DatabaseManager;\n\n /**\n * The table associated with the model\n */\n protected table?: string;\n\n /**\n * The primary key for the model\n */\n protected primaryKey: string = 'id';\n\n /**\n * Indicates if the IDs are auto-incrementing\n */\n protected incrementing: boolean = true;\n\n /**\n * The data type of the primary key\n */\n protected keyType: string = 'int';\n\n /**\n * The attributes that are mass assignable (instance property).\n *\n * Subclasses may also declare `static fillable: string[]` instead.\n * Static properties are resolved at construction time so they are safe\n * to use even when a subclass constructor has not yet run its own field\n * initialisers.\n */\n protected fillable: string[] = [];\n\n /**\n * The attributes that aren't mass assignable (instance property).\n *\n * Subclasses may also declare `static guarded: string[]` instead of\n * (or in addition to) the instance property.\n */\n protected guarded: string[] = ['*'];\n\n /**\n * Static fillable list. Subclasses that declare `static fillable` here\n * will have those attributes made mass-assignable without needing a\n * constructor override.\n */\n static fillable?: string[];\n\n /**\n * Static guarded list. Subclasses that declare `static guarded` here\n * will have those attributes protected from mass assignment without\n * needing a constructor override.\n */\n static guarded?: string[];\n\n /**\n * The attributes that should be hidden for serialization\n */\n protected hidden: string[] = [];\n\n /**\n * The attributes that should be visible for serialization\n */\n protected visible: string[] = [];\n\n /**\n * The accessors to append to the model's array form\n */\n protected appends: string[] = [];\n\n /**\n * The attributes that should be cast\n */\n protected casts: Record<string, string> = {};\n\n /**\n * Indicates if the model should be timestamped\n */\n protected timestamps: boolean = true;\n\n /**\n * The name of the \"created at\" column\n */\n protected static CREATED_AT: string = 'created_at';\n\n /**\n * The name of the \"updated at\" column\n */\n protected static UPDATED_AT: string = 'updated_at';\n\n /**\n * The name of the \"deleted at\" column (for soft deletes)\n */\n protected static DELETED_AT: string = 'deleted_at';\n\n /**\n * The model's attributes\n */\n protected attributes: Record<string, any> = {};\n\n /**\n * The model's original attributes\n */\n protected original: Record<string, any> = {};\n\n /**\n * Indicates if the model exists in the database\n */\n public exists: boolean = false;\n\n /**\n * Indicates if the model was inserted during this request\n */\n public wasRecentlyCreated: boolean = false;\n\n /**\n * The connection name for the model\n */\n protected connection?: string;\n\n /**\n * Enable dynamic relationship access (user.posts instead of user.posts().get())\n * Set to true to enable PHP-like __get behavior for relationships\n */\n protected dynamicRelations: boolean = false;\n\n /**\n * Create a new Eloquent model instance\n */\n constructor(attributes: Record<string, any> = {}, fromDatabase: boolean = false) {\n super();\n if (fromDatabase) {\n // When hydrating from database, set all attributes directly\n this.setRawAttributes(attributes);\n } else {\n // When creating manually, respect fillable/guarded\n this.fill(attributes);\n }\n }\n\n /**\n * Fill the model with an array of attributes\n */\n fill(attributes: Record<string, any>): this {\n for (const [key, value] of Object.entries(attributes)) {\n if (this.isFillable(key)) {\n this.setAttribute(key, value);\n }\n }\n return this;\n }\n\n /**\n * Set a given attribute on the model\n */\n setAttribute(key: string, value: any): this {\n // Check for mutator\n const mutator = `set${this.studly(key)}Attribute`;\n if (typeof (this as any)[mutator] === 'function') {\n (this as any)[mutator](value);\n return this;\n }\n\n this.attributes[key] = value;\n return this;\n }\n\n /**\n * Set the array of model attributes (bypasses fillable/guarded)\n * Used when hydrating from database\n */\n setRawAttributes(attributes: Record<string, any>): this {\n this.attributes = attributes;\n return this;\n }\n\n /**\n * Get an attribute from the model\n */\n getAttribute(key: string): any {\n if (!key) {\n return undefined;\n }\n\n // Check if we have an accessor\n const accessor = `get${this.studly(key)}Attribute`;\n if (typeof (this as any)[accessor] === 'function') {\n return (this as any)[accessor]();\n }\n\n // Get the attribute value\n const value = this.attributes[key];\n\n // Cast the attribute if needed\n if (this.hasCast(key)) {\n return this.castAttribute(key, value);\n }\n\n return value;\n }\n\n /**\n * Determine if the given attribute may be mass assigned.\n *\n * Resolution order for `fillable` and `guarded`:\n * 1. Static property on the concrete class (e.g. `static fillable = [...]`)\n * – safe because static properties exist before any constructor runs.\n * 2. Instance property (`this.fillable` / `this.guarded`) – populated either\n * by Ensemble's own field initialiser or by a subclass constructor\n * workaround that calls `this.fill()` a second time after `super()`.\n *\n * If the concrete class defines `static fillable`, it takes full precedence\n * over the instance property (matching Laravel's behaviour where a non-empty\n * fillable list is the authoritative allow-list).\n */\n protected isFillable(key: string): boolean {\n const ctor = this.constructor as typeof Ensemble;\n\n // Prefer static fillable if the subclass has defined one on itself\n // (not inherited – check own property to avoid reading Ensemble's\n // `undefined` declaration as a truthy value).\n const staticFillable: string[] | undefined = Object.prototype.hasOwnProperty.call(ctor, 'fillable')\n ? ctor.fillable\n : undefined;\n\n const effectiveFillable: string[] = staticFillable ?? this.fillable;\n\n if (effectiveFillable.length > 0) {\n return effectiveFillable.includes(key);\n }\n\n // No fillable list – fall back to guarded logic.\n const staticGuarded: string[] | undefined = Object.prototype.hasOwnProperty.call(ctor, 'guarded')\n ? ctor.guarded\n : undefined;\n\n const effectiveGuarded: string[] = staticGuarded ?? this.guarded;\n\n if (effectiveGuarded.length > 0 && !effectiveGuarded.includes('*')) {\n return !effectiveGuarded.includes(key);\n }\n\n return effectiveGuarded[0] !== '*';\n }\n\n /**\n * Determine if a get mutator exists for an attribute\n */\n protected hasGetMutator(key: string): boolean {\n return typeof (this as any)[`get${this.studly(key)}Attribute`] === 'function';\n }\n\n /**\n * Determine if a set mutator exists for an attribute\n */\n protected hasSetMutator(key: string): boolean {\n return typeof (this as any)[`set${this.studly(key)}Attribute`] === 'function';\n }\n\n /**\n * Determine if a cast is defined for an attribute\n */\n protected hasCast(key: string): boolean {\n return key in this.casts;\n }\n\n /**\n * Cast an attribute to a native PHP type\n */\n protected castAttribute(key: string, value: any): any {\n if (value === null) {\n return value;\n }\n\n const castType = this.casts[key];\n\n switch (castType) {\n case 'int':\n case 'integer':\n return parseInt(value);\n case 'real':\n case 'float':\n case 'double':\n return parseFloat(value);\n case 'string':\n return String(value);\n case 'bool':\n case 'boolean':\n return Boolean(value);\n case 'object':\n return typeof value === 'string' ? JSON.parse(value) : value;\n case 'array':\n case 'json':\n return typeof value === 'string' ? JSON.parse(value) : value;\n case 'collection':\n return typeof value === 'string' ? JSON.parse(value) : value;\n case 'date':\n case 'datetime':\n case 'timestamp':\n return value instanceof Date ? value : new Date(value);\n default:\n return value;\n }\n }\n\n /**\n * Convert the model to a plain object\n */\n toObject(): Record<string, any> {\n const attributes: Record<string, any> = {};\n\n for (const key of Object.keys(this.attributes)) {\n if (this.isVisible(key)) {\n attributes[key] = this.getAttribute(key);\n }\n }\n\n // Add appended accessors\n for (const key of this.appends) {\n attributes[key] = this.getAttribute(key);\n }\n\n // Add loaded relationships\n for (const [key, value] of Object.entries(this.relations)) {\n if (Array.isArray(value)) {\n attributes[key] = value.map((model) => model.toObject());\n } else if (value && typeof value.toObject === 'function') {\n attributes[key] = value.toObject();\n } else {\n attributes[key] = value;\n }\n }\n\n return attributes;\n }\n\n /**\n * Convert the model to JSON\n */\n toJSON(): Record<string, any> {\n return this.toObject();\n }\n\n /**\n * Determine if an attribute is visible\n */\n protected isVisible(key: string): boolean {\n if (this.visible.length > 0) {\n return this.visible.includes(key);\n }\n\n return !this.hidden.includes(key);\n }\n\n /**\n * Get the table associated with the model\n */\n getTable(): string {\n if (this.table) {\n return this.table;\n }\n\n // Convert class name to snake_case plural\n // e.g., User -> users, BlogPost -> blog_posts\n const className = this.constructor.name;\n return this.pluralize(this.snake(className));\n }\n\n /**\n * Get the primary key for the model\n */\n getKeyName(): string {\n return this.primaryKey;\n }\n\n /**\n * Get the value of the model's primary key\n */\n getKey(): any {\n return this.getAttribute(this.getKeyName());\n }\n\n /**\n * Set the connection resolver instance\n */\n static setConnectionResolver(resolver: DatabaseManager): void {\n (Ensemble as any).connectionResolver = resolver;\n }\n\n /**\n * Get the database connection for the model\n */\n getConnection(): Connection {\n return (this.constructor as typeof Ensemble).connectionResolver.connection(this.connection);\n }\n\n /**\n * Begin querying the model\n */\n static query<T extends Ensemble>(this: { new (): T }): EnsembleBuilder<T> {\n const instance = new this();\n return new EnsembleBuilder<T>(instance.getConnection().getAdapter(), instance);\n }\n\n /**\n * Get all of the models from the database\n */\n static async all<T extends Ensemble>(this: { new (): T }, columns: string[] = ['*']): Promise<T[]> {\n return (this as any)\n .query()\n .select(...columns)\n .get();\n }\n\n /**\n * Find a model by its primary key\n */\n static async find<T extends Ensemble>(this: { new (): T }, id: any, columns: string[] = ['*']): Promise<T | null> {\n return (this as any)\n .query()\n .select(...columns)\n .find(id);\n }\n\n /**\n * Find a model by its primary key or throw an exception\n */\n static async findOrFail<T extends Ensemble>(this: { new (): T }, id: any, columns: string[] = ['*']): Promise<T> {\n const model = await (this as any).find(id, columns);\n if (!model) {\n throw new Error(`Ensemble not found with id: ${id}`);\n }\n return model;\n }\n\n /**\n * Find multiple models by their primary keys\n */\n static async findMany<T extends Ensemble>(this: { new (): T }, ids: any[], columns: string[] = ['*']): Promise<T[]> {\n const instance = new this();\n return (this as any)\n .query()\n .select(...columns)\n .whereIn(instance.getKeyName(), ids)\n .get();\n }\n\n /**\n * Create a new instance and save it to the database\n */\n static async create<T extends Ensemble>(\n this: { new (attrs?: Record<string, any>): T },\n attributes: Record<string, any>\n ): Promise<T> {\n const instance = new this(attributes);\n await instance.save();\n return instance;\n }\n\n /**\n * Update or create a model matching the attributes\n */\n static async updateOrCreate<T extends Ensemble>(\n this: { new (): T },\n attributes: Record<string, any>,\n values: Record<string, any> = {}\n ): Promise<T> {\n const instance = await (this as any).query().where(attributes).first();\n\n if (instance) {\n instance.fill(values);\n await instance.save();\n return instance;\n }\n\n return (this as any).create({ ...attributes, ...values });\n }\n\n /**\n * Save the model to the database\n */\n async save(): Promise<boolean> {\n // Fire saving event\n if ((await this.fireModelEvent('saving')) === false) {\n return false;\n }\n\n if (this.exists) {\n return this.performUpdate();\n }\n\n return this.performInsert();\n }\n\n /**\n * Perform a model insert operation\n */\n protected async performInsert(): Promise<boolean> {\n // Fire creating event\n if ((await this.fireModelEvent('creating')) === false) {\n return false;\n }\n\n const attributes = this.getAttributesForInsert();\n\n if (this.timestamps) {\n this.updateTimestamps();\n }\n\n const connection = this.getConnection();\n const table = this.getTable();\n\n const id = await connection.table(table).insertGetId(attributes);\n\n if (this.incrementing) {\n this.setAttribute(this.getKeyName(), id);\n }\n\n this.exists = true;\n this.wasRecentlyCreated = true;\n this.syncOriginal();\n\n // Fire created event\n await this.fireModelEvent('created');\n\n // Fire saved event\n await this.fireModelEvent('saved');\n\n return true;\n }\n\n /**\n * Perform a model update operation\n */\n protected async performUpdate(): Promise<boolean> {\n const dirty = this.getDirty();\n\n if (Object.keys(dirty).length === 0) {\n return true;\n }\n\n // Fire updating event\n if ((await this.fireModelEvent('updating')) === false) {\n return false;\n }\n\n if (this.timestamps) {\n this.updateTimestamps();\n }\n\n const connection = this.getConnection();\n const table = this.getTable();\n\n await connection.table(table).where(this.getKeyName(), '=', this.getKey()).update(dirty);\n\n this.syncOriginal();\n\n // Fire updated event\n await this.fireModelEvent('updated');\n\n // Fire saved event\n await this.fireModelEvent('saved');\n\n return true;\n }\n\n /**\n * Update the model's timestamps\n */\n protected updateTimestamps(): void {\n const time = new Date();\n\n const updatedAtColumn = (this.constructor as typeof Ensemble).UPDATED_AT;\n if (updatedAtColumn && !this.isDirty(updatedAtColumn)) {\n this.setAttribute(updatedAtColumn, time);\n }\n\n const createdAtColumn = (this.constructor as typeof Ensemble).CREATED_AT;\n if (!this.exists && createdAtColumn && !this.isDirty(createdAtColumn)) {\n this.setAttribute(createdAtColumn, time);\n }\n }\n\n /**\n * Get the attributes that have been changed\n */\n getDirty(): Record<string, any> {\n const dirty: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(this.attributes)) {\n if (!this.originalIsEquivalent(key, value)) {\n dirty[key] = value;\n }\n }\n\n return dirty;\n }\n\n /**\n * Determine if the given attribute has been changed\n */\n isDirty(attribute?: string): boolean {\n if (!attribute) {\n return Object.keys(this.getDirty()).length > 0;\n }\n\n return attribute in this.getDirty();\n }\n\n /**\n * Determine if the original value is equivalent to the current value\n */\n protected originalIsEquivalent(key: string, current: any): boolean {\n if (!(key in this.original)) {\n return false;\n }\n\n const original = this.original[key];\n\n if (current === original) {\n return true;\n }\n\n if (current === null) {\n return false;\n }\n\n if (this.isDateAttribute(key)) {\n return this.compareDates(current, original);\n }\n\n return String(current) === String(original);\n }\n\n /**\n * Determine if the given attribute is a date or date castable\n */\n protected isDateAttribute(key: string): boolean {\n const cast = this.casts[key];\n return cast === 'date' || cast === 'datetime' || cast === 'timestamp';\n }\n\n /**\n * Compare two dates\n */\n protected compareDates(current: any, original: any): boolean {\n const currentDate = current instanceof Date ? current : new Date(current);\n const originalDate = original instanceof Date ? original : new Date(original);\n return currentDate.getTime() === originalDate.getTime();\n }\n\n /**\n * Get the attributes for insert\n */\n protected getAttributesForInsert(): Record<string, any> {\n return { ...this.attributes };\n }\n\n /**\n * Sync the original attributes with the current\n */\n protected syncOriginal(): this {\n this.original = { ...this.attributes };\n return this;\n }\n\n /**\n * Delete the model from the database\n */\n async delete(): Promise<boolean> {\n if (!this.exists) {\n return false;\n }\n\n // Fire deleting event\n if ((await this.fireModelEvent('deleting')) === false) {\n return false;\n }\n\n const connection = this.getConnection();\n const table = this.getTable();\n\n await connection.table(table).where(this.getKeyName(), '=', this.getKey()).delete();\n\n this.exists = false;\n\n // Fire deleted event\n await this.fireModelEvent('deleted');\n\n return true;\n }\n\n /**\n * Reload the current model instance from the database\n */\n async refresh(): Promise<this> {\n if (!this.exists) {\n return this;\n }\n\n const fresh = await (this.constructor as any).find(this.getKey());\n\n if (!fresh) {\n throw new Error('Ensemble not found');\n }\n\n this.attributes = (fresh as any).attributes;\n this.syncOriginal();\n\n return this;\n }\n\n /**\n * Convert a string to studly case\n */\n protected studly(value: string): string {\n return value\n .split('_')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('');\n }\n\n /**\n * Convert a string to snake case\n */\n protected snake(value: string): string {\n return value\n .replace(/([A-Z])/g, '_$1')\n .toLowerCase()\n .replace(/^_/, '');\n }\n\n /**\n * Pluralize a string (simple implementation)\n */\n protected pluralize(value: string): string {\n if (value.endsWith('y')) {\n return value.slice(0, -1) + 'ies';\n }\n if (value.endsWith('s')) {\n return value + 'es';\n }\n return value + 's';\n }\n\n /**\n * Create a new query instance for the model\n */\n newQuery(): EnsembleBuilder<any> {\n return (this.constructor as any).query();\n }\n\n /**\n * Create a new instance of the given model\n */\n newInstance(attributes: Record<string, any> = {}, exists: boolean = false): this {\n const ModelClass = this.constructor as new (attributes: Record<string, any>, fromDatabase: boolean) => this;\n const instance = new ModelClass(attributes, exists);\n instance.exists = exists;\n\n if (exists) {\n instance.syncOriginal();\n }\n\n return instance;\n }\n\n /**\n * Get the name of the \"updated at\" column\n */\n getUpdatedAtColumn(): string | null {\n return this.timestamps ? (this.constructor as typeof Ensemble).UPDATED_AT : null;\n }\n\n /**\n * Get the name of the \"created at\" column\n */\n getCreatedAtColumn(): string | null {\n return this.timestamps ? (this.constructor as typeof Ensemble).CREATED_AT : null;\n }\n\n /**\n * Fire the given model event\n *\n * @param event - Event name (saving, saved, creating, created, etc.)\n * @returns false if event is halting and a listener returned false, undefined otherwise\n */\n protected async fireModelEvent(event: string): Promise<boolean | undefined> {\n // Try to get the event dispatcher\n let dispatcher: any;\n try {\n // Import the Dispatcher and get from static resolver if available\n const { Dispatcher } = await import('@/Events/Dispatcher');\n const { Facade } = await import('@/Support/Facade');\n\n try {\n dispatcher = Facade.getFacadeApplication()?.make?.('events');\n } catch {\n // No dispatcher registered\n }\n } catch (error) {\n // Event system not set up, skip firing events\n return undefined;\n }\n\n if (!dispatcher || typeof dispatcher.dispatch !== 'function') {\n return undefined;\n }\n\n // Map event names to event classes\n const eventMap: Record<string, any> = {\n retrieved: ModelRetrieved,\n creating: ModelCreating,\n created: ModelCreated,\n updating: ModelUpdating,\n updated: ModelUpdated,\n saving: ModelSaving,\n saved: ModelSaved,\n deleting: ModelDeleting,\n deleted: ModelDeleted,\n };\n\n const EventClass = eventMap[event];\n if (!EventClass) {\n return undefined;\n }\n\n const eventInstance = new EventClass(this);\n\n // For halting events (creating, updating, saving, deleting), use until()\n // which returns the first non-null result (false halts the operation)\n if (['creating', 'updating', 'saving', 'deleting'].includes(event)) {\n const result = await dispatcher.until?.(eventInstance);\n // If any listener returns false, halt the operation\n if (result === false) {\n return false;\n }\n } else {\n // For non-halting events, just dispatch normally\n await dispatcher.dispatch(eventInstance);\n }\n\n return undefined;\n }\n}\n"],"mappings":"qoBAuBA,IAAsB,EAAtB,MAAsB,UAAiB,CAAsB,CAI3D,OAAiB,mBAKjB,MAKA,WAA+B,KAK/B,aAAkC,GAKlC,QAA4B,MAU5B,SAA+B,EAAE,CAQjC,QAA8B,CAAC,IAAI,CAOnC,OAAO,SAOP,OAAO,QAKP,OAA6B,EAAE,CAK/B,QAA8B,EAAE,CAKhC,QAA8B,EAAE,CAKhC,MAA0C,EAAE,CAK5C,WAAgC,GAKhC,OAAiB,WAAqB,aAKtC,OAAiB,WAAqB,aAKtC,OAAiB,WAAqB,aAKtC,WAA4C,EAAE,CAK9C,SAA0C,EAAE,CAK5C,OAAyB,GAKzB,mBAAqC,GAKrC,WAMA,iBAAsC,GAKtC,YAAY,EAAkC,EAAE,CAAE,EAAwB,GAAO,CAC/E,OAAO,CACH,EAEF,KAAK,iBAAiB,EAAW,CAGjC,KAAK,KAAK,EAAW,CAOzB,KAAK,EAAuC,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAW,CAC/C,KAAK,WAAW,EAAI,EACtB,KAAK,aAAa,EAAK,EAAM,CAGjC,OAAO,KAMT,aAAa,EAAa,EAAkB,CAE1C,IAAM,EAAU,MAAM,KAAK,OAAO,EAAI,CAAC,WAOvC,OANI,OAAQ,KAAa,IAAa,YACnC,KAAa,GAAS,EAAM,CACtB,OAGT,KA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vC,GACb,MAAO,QAIT,MAAM,EAAW,SAAS,EAAc"}
1
+ {"version":3,"file":"Ensemble.mjs","names":[],"sources":["../../../src/Database/Ensemble/Ensemble.ts"],"sourcesContent":["/**\n * Ensemble Class\n *\n * Base class for Ensemble models with ActiveRecord pattern\n * In Orchestr, your data models are called Ensembles - groups that work in harmony\n */\n\nimport { Connection } from '@/Database/Connection';\nimport { DatabaseManager } from '@/Database/DatabaseManager';\nimport { HasRelationshipsMixin } from './Concerns/HasRelationships';\nimport { EnsembleBuilder } from './EnsembleBuilder';\nimport {\n ModelRetrieved,\n ModelCreating,\n ModelCreated,\n ModelUpdating,\n ModelUpdated,\n ModelSaving,\n ModelSaved,\n ModelDeleting,\n ModelDeleted,\n} from './Events';\n\nexport abstract class Ensemble extends HasRelationshipsMixin {\n /**\n * The connection resolver instance\n */\n protected static connectionResolver: DatabaseManager;\n\n /**\n * The table associated with the model\n */\n protected table?: string;\n\n /**\n * The primary key for the model\n */\n protected primaryKey: string = 'id';\n\n /**\n * Indicates if the IDs are auto-incrementing\n */\n protected incrementing: boolean = true;\n\n /**\n * The data type of the primary key\n */\n protected keyType: string = 'int';\n\n /**\n * The attributes that are mass assignable (instance property).\n *\n * Subclasses may also declare `static fillable: string[]` instead.\n * Static properties are resolved at construction time so they are safe\n * to use even when a subclass constructor has not yet run its own field\n * initialisers.\n */\n protected fillable: string[] = [];\n\n /**\n * The attributes that aren't mass assignable (instance property).\n *\n * Subclasses may also declare `static guarded: string[]` instead of\n * (or in addition to) the instance property.\n */\n protected guarded: string[] = ['*'];\n\n /**\n * Static fillable list. Subclasses that declare `static fillable` here\n * will have those attributes made mass-assignable without needing a\n * constructor override.\n */\n static fillable?: string[];\n\n /**\n * Static guarded list. Subclasses that declare `static guarded` here\n * will have those attributes protected from mass assignment without\n * needing a constructor override.\n */\n static guarded?: string[];\n\n /**\n * The attributes that should be hidden for serialization\n */\n protected hidden: string[] = [];\n\n /**\n * The attributes that should be visible for serialization\n */\n protected visible: string[] = [];\n\n /**\n * The accessors to append to the model's array form\n */\n protected appends: string[] = [];\n\n /**\n * The attributes that should be cast\n */\n protected casts: Record<string, string> = {};\n\n /**\n * Indicates if the model should be timestamped\n */\n protected timestamps: boolean = true;\n\n /**\n * The name of the \"created at\" column\n */\n protected static CREATED_AT: string = 'created_at';\n\n /**\n * The name of the \"updated at\" column\n */\n protected static UPDATED_AT: string = 'updated_at';\n\n /**\n * The name of the \"deleted at\" column (for soft deletes)\n */\n protected static DELETED_AT: string = 'deleted_at';\n\n /**\n * The model's attributes\n */\n protected attributes: Record<string, any> = {};\n\n /**\n * The model's original attributes\n */\n protected original: Record<string, any> = {};\n\n /**\n * Indicates if the model exists in the database\n */\n public exists: boolean = false;\n\n /**\n * Indicates if the model was inserted during this request\n */\n public wasRecentlyCreated: boolean = false;\n\n /**\n * The connection name for the model\n */\n protected connection?: string;\n\n /**\n * Enable dynamic relationship access (user.posts instead of user.posts().get())\n * Set to true to enable PHP-like __get behavior for relationships\n */\n protected dynamicRelations: boolean = false;\n\n /**\n * Create a new Eloquent model instance\n */\n constructor(attributes: Record<string, any> = {}, fromDatabase: boolean = false) {\n super();\n if (fromDatabase) {\n // When hydrating from database, set all attributes directly\n this.setRawAttributes(attributes);\n } else {\n // When creating manually, respect fillable/guarded\n this.fill(attributes);\n }\n }\n\n /**\n * Fill the model with an array of attributes\n */\n fill(attributes: Record<string, any>): this {\n for (const [key, value] of Object.entries(attributes)) {\n if (this.isFillable(key)) {\n this.setAttribute(key, value);\n }\n }\n return this;\n }\n\n /**\n * Set a given attribute on the model\n */\n setAttribute(key: string, value: any): this {\n // Check for mutator\n const mutator = `set${this.studly(key)}Attribute`;\n if (typeof (this as any)[mutator] === 'function') {\n (this as any)[mutator](value);\n return this;\n }\n\n this.attributes[key] = value;\n return this;\n }\n\n /**\n * Set the array of model attributes (bypasses fillable/guarded)\n * Used when hydrating from database\n */\n setRawAttributes(attributes: Record<string, any>): this {\n this.attributes = attributes;\n return this;\n }\n\n /**\n * Get an attribute from the model\n */\n getAttribute(key: string): any {\n if (!key) {\n return undefined;\n }\n\n // Check if we have an accessor\n const accessor = `get${this.studly(key)}Attribute`;\n if (typeof (this as any)[accessor] === 'function') {\n return (this as any)[accessor]();\n }\n\n // Get the attribute value\n const value = this.attributes[key];\n\n // Cast the attribute if needed\n if (this.hasCast(key)) {\n return this.castAttribute(key, value);\n }\n\n return value;\n }\n\n /**\n * Determine if the given attribute may be mass assigned.\n *\n * Resolution order for `fillable` and `guarded`:\n * 1. Static property on the concrete class (e.g. `static fillable = [...]`)\n * – safe because static properties exist before any constructor runs.\n * 2. Instance property (`this.fillable` / `this.guarded`) – populated either\n * by Ensemble's own field initialiser or by a subclass constructor\n * workaround that calls `this.fill()` a second time after `super()`.\n *\n * If the concrete class defines `static fillable`, it takes full precedence\n * over the instance property (matching Laravel's behaviour where a non-empty\n * fillable list is the authoritative allow-list).\n */\n protected isFillable(key: string): boolean {\n const ctor = this.constructor as typeof Ensemble;\n\n // Prefer static fillable if the subclass has defined one on itself\n // (not inherited – check own property to avoid reading Ensemble's\n // `undefined` declaration as a truthy value).\n const staticFillable: string[] | undefined = Object.prototype.hasOwnProperty.call(ctor, 'fillable')\n ? ctor.fillable\n : undefined;\n\n const effectiveFillable: string[] = staticFillable ?? this.fillable;\n\n if (effectiveFillable.length > 0) {\n return effectiveFillable.includes(key);\n }\n\n // No fillable list – fall back to guarded logic.\n const staticGuarded: string[] | undefined = Object.prototype.hasOwnProperty.call(ctor, 'guarded')\n ? ctor.guarded\n : undefined;\n\n const effectiveGuarded: string[] = staticGuarded ?? this.guarded;\n\n if (effectiveGuarded.length > 0 && !effectiveGuarded.includes('*')) {\n return !effectiveGuarded.includes(key);\n }\n\n return effectiveGuarded[0] !== '*';\n }\n\n /**\n * Determine if a get mutator exists for an attribute\n */\n protected hasGetMutator(key: string): boolean {\n return typeof (this as any)[`get${this.studly(key)}Attribute`] === 'function';\n }\n\n /**\n * Determine if a set mutator exists for an attribute\n */\n protected hasSetMutator(key: string): boolean {\n return typeof (this as any)[`set${this.studly(key)}Attribute`] === 'function';\n }\n\n /**\n * Determine if a cast is defined for an attribute\n */\n protected hasCast(key: string): boolean {\n return key in this.casts;\n }\n\n /**\n * Cast an attribute to a native PHP type\n */\n protected castAttribute(key: string, value: any): any {\n if (value === null) {\n return value;\n }\n\n const castType = this.casts[key];\n\n switch (castType) {\n case 'int':\n case 'integer':\n return parseInt(value);\n case 'real':\n case 'float':\n case 'double':\n return parseFloat(value);\n case 'string':\n return String(value);\n case 'bool':\n case 'boolean':\n return Boolean(value);\n case 'object':\n return typeof value === 'string' ? JSON.parse(value) : value;\n case 'array':\n case 'json':\n return typeof value === 'string' ? JSON.parse(value) : value;\n case 'collection':\n return typeof value === 'string' ? JSON.parse(value) : value;\n case 'date':\n case 'datetime':\n case 'timestamp':\n return value instanceof Date ? value : new Date(value);\n default:\n return value;\n }\n }\n\n /**\n * Convert the model to a plain object\n */\n toObject(): Record<string, any> {\n const attributes: Record<string, any> = {};\n\n for (const key of Object.keys(this.attributes)) {\n if (this.isVisible(key)) {\n attributes[key] = this.getAttribute(key);\n }\n }\n\n // Add appended accessors\n for (const key of this.appends) {\n attributes[key] = this.getAttribute(key);\n }\n\n // Add loaded relationships\n for (const [key, value] of Object.entries(this.relations)) {\n if (Array.isArray(value)) {\n attributes[key] = value.map((model) => model.toObject());\n } else if (value && typeof value.toObject === 'function') {\n attributes[key] = value.toObject();\n } else {\n attributes[key] = value;\n }\n }\n\n return attributes;\n }\n\n /**\n * Convert the model to JSON\n */\n toJSON(): Record<string, any> {\n return this.toObject();\n }\n\n /**\n * Determine if an attribute is visible\n */\n protected isVisible(key: string): boolean {\n if (this.visible.length > 0) {\n return this.visible.includes(key);\n }\n\n return !this.hidden.includes(key);\n }\n\n /**\n * Get the table associated with the model\n */\n getTable(): string {\n if (this.table) {\n return this.table;\n }\n\n // Convert class name to snake_case plural\n // e.g., User -> users, BlogPost -> blog_posts\n const className = this.constructor.name;\n return this.pluralize(this.snake(className));\n }\n\n /**\n * Get the primary key for the model\n */\n getKeyName(): string {\n return this.primaryKey;\n }\n\n /**\n * Get the value of the model's primary key\n */\n getKey(): any {\n return this.getAttribute(this.getKeyName());\n }\n\n /**\n * Set the connection resolver instance\n */\n static setConnectionResolver(resolver: DatabaseManager): void {\n (Ensemble as any).connectionResolver = resolver;\n }\n\n /**\n * Get the database connection for the model\n */\n getConnection(): Connection {\n return (this.constructor as typeof Ensemble).connectionResolver.connection(this.connection);\n }\n\n /**\n * Begin querying the model\n */\n static query<T extends Ensemble>(this: { new (): T }): EnsembleBuilder<T> {\n const instance = new this();\n return new EnsembleBuilder<T>(instance.getConnection().getAdapter(), instance);\n }\n\n /**\n * Get all of the models from the database\n */\n static async all<T extends Ensemble>(this: { new (): T }, columns: string[] = ['*']): Promise<T[]> {\n return (this as any)\n .query()\n .select(...columns)\n .get();\n }\n\n /**\n * Find a model by its primary key\n */\n static async find<T extends Ensemble>(this: { new (): T }, id: any, columns: string[] = ['*']): Promise<T | null> {\n return (this as any)\n .query()\n .select(...columns)\n .find(id);\n }\n\n /**\n * Find a model by its primary key or throw an exception\n */\n static async findOrFail<T extends Ensemble>(this: { new (): T }, id: any, columns: string[] = ['*']): Promise<T> {\n const model = await (this as any).find(id, columns);\n if (!model) {\n throw new Error(`Ensemble not found with id: ${id}`);\n }\n return model;\n }\n\n /**\n * Find multiple models by their primary keys\n */\n static async findMany<T extends Ensemble>(this: { new (): T }, ids: any[], columns: string[] = ['*']): Promise<T[]> {\n const instance = new this();\n return (this as any)\n .query()\n .select(...columns)\n .whereIn(instance.getKeyName(), ids)\n .get();\n }\n\n /**\n * Create a new instance and save it to the database\n */\n static async create<T extends Ensemble>(\n this: { new (attrs?: Record<string, any>): T },\n attributes: Record<string, any>\n ): Promise<T> {\n const instance = new this(attributes);\n await instance.save();\n return instance;\n }\n\n /**\n * Update or create a model matching the attributes\n */\n static async updateOrCreate<T extends Ensemble>(\n this: { new (): T },\n attributes: Record<string, any>,\n values: Record<string, any> = {}\n ): Promise<T> {\n const instance = await (this as any).query().where(attributes).first();\n\n if (instance) {\n instance.fill(values);\n await instance.save();\n return instance;\n }\n\n return (this as any).create({ ...attributes, ...values });\n }\n\n /**\n * Save the model to the database\n */\n async save(): Promise<boolean> {\n // Fire saving event\n if ((await this.fireModelEvent('saving')) === false) {\n return false;\n }\n\n if (this.exists) {\n return this.performUpdate();\n }\n\n return this.performInsert();\n }\n\n /**\n * Perform a model insert operation\n */\n protected async performInsert(): Promise<boolean> {\n // Fire creating event\n if ((await this.fireModelEvent('creating')) === false) {\n return false;\n }\n\n const attributes = this.getAttributesForInsert();\n\n if (this.timestamps) {\n this.updateTimestamps();\n }\n\n const connection = this.getConnection();\n const table = this.getTable();\n\n const id = await connection.table(table).insertGetId(attributes);\n\n if (this.incrementing) {\n this.setAttribute(this.getKeyName(), id);\n }\n\n this.exists = true;\n this.wasRecentlyCreated = true;\n this.syncOriginal();\n\n // Fire created event\n await this.fireModelEvent('created');\n\n // Fire saved event\n await this.fireModelEvent('saved');\n\n return true;\n }\n\n /**\n * Perform a model update operation\n */\n protected async performUpdate(): Promise<boolean> {\n const dirty = this.getDirty();\n\n if (Object.keys(dirty).length === 0) {\n return true;\n }\n\n // Fire updating event\n if ((await this.fireModelEvent('updating')) === false) {\n return false;\n }\n\n if (this.timestamps) {\n this.updateTimestamps();\n }\n\n const connection = this.getConnection();\n const table = this.getTable();\n\n await connection.table(table).where(this.getKeyName(), '=', this.getKey()).update(dirty);\n\n this.syncOriginal();\n\n // Fire updated event\n await this.fireModelEvent('updated');\n\n // Fire saved event\n await this.fireModelEvent('saved');\n\n return true;\n }\n\n /**\n * Update the model's timestamps\n */\n protected updateTimestamps(): void {\n const time = new Date();\n\n const updatedAtColumn = (this.constructor as typeof Ensemble).UPDATED_AT;\n if (updatedAtColumn && !this.isDirty(updatedAtColumn)) {\n this.setAttribute(updatedAtColumn, time);\n }\n\n const createdAtColumn = (this.constructor as typeof Ensemble).CREATED_AT;\n if (!this.exists && createdAtColumn && !this.isDirty(createdAtColumn)) {\n this.setAttribute(createdAtColumn, time);\n }\n }\n\n /**\n * Get the attributes that have been changed\n */\n getDirty(): Record<string, any> {\n const dirty: Record<string, any> = {};\n\n for (const [key, value] of Object.entries(this.attributes)) {\n if (!this.originalIsEquivalent(key, value)) {\n dirty[key] = value;\n }\n }\n\n return dirty;\n }\n\n /**\n * Determine if the given attribute has been changed\n */\n isDirty(attribute?: string): boolean {\n if (!attribute) {\n return Object.keys(this.getDirty()).length > 0;\n }\n\n return attribute in this.getDirty();\n }\n\n /**\n * Determine if the original value is equivalent to the current value\n */\n protected originalIsEquivalent(key: string, current: any): boolean {\n if (!(key in this.original)) {\n return false;\n }\n\n const original = this.original[key];\n\n if (current === original) {\n return true;\n }\n\n if (current === null) {\n return false;\n }\n\n if (this.isDateAttribute(key)) {\n return this.compareDates(current, original);\n }\n\n return String(current) === String(original);\n }\n\n /**\n * Determine if the given attribute is a date or date castable\n */\n protected isDateAttribute(key: string): boolean {\n const cast = this.casts[key];\n return cast === 'date' || cast === 'datetime' || cast === 'timestamp';\n }\n\n /**\n * Compare two dates\n */\n protected compareDates(current: any, original: any): boolean {\n const currentDate = current instanceof Date ? current : new Date(current);\n const originalDate = original instanceof Date ? original : new Date(original);\n return currentDate.getTime() === originalDate.getTime();\n }\n\n /**\n * Get the attributes for insert\n */\n protected getAttributesForInsert(): Record<string, any> {\n return { ...this.attributes };\n }\n\n /**\n * Sync the original attributes with the current\n */\n protected syncOriginal(): this {\n this.original = { ...this.attributes };\n return this;\n }\n\n /**\n * Delete the model from the database\n */\n async delete(): Promise<boolean> {\n if (!this.exists) {\n return false;\n }\n\n // Fire deleting event\n if ((await this.fireModelEvent('deleting')) === false) {\n return false;\n }\n\n const connection = this.getConnection();\n const table = this.getTable();\n\n await connection.table(table).where(this.getKeyName(), '=', this.getKey()).delete();\n\n this.exists = false;\n\n // Fire deleted event\n await this.fireModelEvent('deleted');\n\n return true;\n }\n\n /**\n * Reload the current model instance from the database\n */\n async refresh(): Promise<this> {\n if (!this.exists) {\n return this;\n }\n\n const fresh = await (this.constructor as any).find(this.getKey());\n\n if (!fresh) {\n throw new Error('Ensemble not found');\n }\n\n this.attributes = (fresh as any).attributes;\n this.syncOriginal();\n\n return this;\n }\n\n /**\n * Convert a string to studly case\n */\n protected studly(value: string): string {\n return value\n .split('_')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join('');\n }\n\n /**\n * Convert a string to snake case\n */\n protected snake(value: string): string {\n return value\n .replace(/([A-Z])/g, '_$1')\n .toLowerCase()\n .replace(/^_/, '');\n }\n\n /**\n * Pluralize a string (simple implementation)\n */\n protected pluralize(value: string): string {\n if (value.endsWith('y')) {\n return value.slice(0, -1) + 'ies';\n }\n if (value.endsWith('s')) {\n return value + 'es';\n }\n return value + 's';\n }\n\n /**\n * Create a new query instance for the model\n */\n newQuery(): EnsembleBuilder<any> {\n return (this.constructor as any).query();\n }\n\n /**\n * Create a new instance of the given model\n */\n newInstance(attributes: Record<string, any> = {}, exists: boolean = false): this {\n const ModelClass = this.constructor as new (attributes: Record<string, any>, fromDatabase: boolean) => this;\n const instance = new ModelClass(attributes, exists);\n instance.exists = exists;\n\n if (exists) {\n instance.syncOriginal();\n }\n\n return instance;\n }\n\n /**\n * Get the name of the \"updated at\" column\n */\n getUpdatedAtColumn(): string | null {\n return this.timestamps ? (this.constructor as typeof Ensemble).UPDATED_AT : null;\n }\n\n /**\n * Get the name of the \"created at\" column\n */\n getCreatedAtColumn(): string | null {\n return this.timestamps ? (this.constructor as typeof Ensemble).CREATED_AT : null;\n }\n\n /**\n * Fire the given model event\n *\n * @param event - Event name (saving, saved, creating, created, etc.)\n * @returns false if event is halting and a listener returned false, undefined otherwise\n */\n protected async fireModelEvent(event: string): Promise<boolean | undefined> {\n // Try to get the event dispatcher\n let dispatcher: any;\n try {\n // Import the Dispatcher and get from static resolver if available\n const { Dispatcher } = await import('@/Events/Dispatcher');\n const { Facade } = await import('@/Support/Facade');\n\n try {\n dispatcher = Facade.getFacadeApplication()?.make?.('events');\n } catch {\n // No dispatcher registered\n }\n } catch (error) {\n // Event system not set up, skip firing events\n return undefined;\n }\n\n if (!dispatcher || typeof dispatcher.dispatch !== 'function') {\n return undefined;\n }\n\n // Map event names to event classes\n const eventMap: Record<string, any> = {\n retrieved: ModelRetrieved,\n creating: ModelCreating,\n created: ModelCreated,\n updating: ModelUpdating,\n updated: ModelUpdated,\n saving: ModelSaving,\n saved: ModelSaved,\n deleting: ModelDeleting,\n deleted: ModelDeleted,\n };\n\n const EventClass = eventMap[event];\n if (!EventClass) {\n return undefined;\n }\n\n const eventInstance = new EventClass(this);\n\n // For halting events (creating, updating, saving, deleting), use until()\n // which returns the first non-null result (false halts the operation)\n if (['creating', 'updating', 'saving', 'deleting'].includes(event)) {\n const result = await dispatcher.until?.(eventInstance);\n // If any listener returns false, halt the operation\n if (result === false) {\n return false;\n }\n } else {\n // For non-halting events, just dispatch normally\n await dispatcher.dispatch(eventInstance);\n }\n\n return undefined;\n }\n}\n"],"mappings":"qoBAuBA,IAAsB,EAAtB,MAAsB,UAAiB,CAAsB,CAI3D,OAAiB,mBAKjB,MAKA,WAA+B,KAK/B,aAAkC,GAKlC,QAA4B,MAU5B,SAA+B,EAAE,CAQjC,QAA8B,CAAC,IAAI,CAOnC,OAAO,SAOP,OAAO,QAKP,OAA6B,EAAE,CAK/B,QAA8B,EAAE,CAKhC,QAA8B,EAAE,CAKhC,MAA0C,EAAE,CAK5C,WAAgC,GAKhC,OAAiB,WAAqB,aAKtC,OAAiB,WAAqB,aAKtC,OAAiB,WAAqB,aAKtC,WAA4C,EAAE,CAK9C,SAA0C,EAAE,CAK5C,OAAyB,GAKzB,mBAAqC,GAKrC,WAMA,iBAAsC,GAKtC,YAAY,EAAkC,EAAE,CAAE,EAAwB,GAAO,CAC/E,OAAO,CACH,EAEF,KAAK,iBAAiB,EAAW,CAGjC,KAAK,KAAK,EAAW,CAOzB,KAAK,EAAuC,CAC1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,UAAW,EACX,SAAU,EACV,QAAS,EACT,SAAU,EACV,QAAS,EACT,OAAQ,EACR,MAAO,EACP,SAAU,EACV,QAAS,EAGgB,CAAC,GAC5B,GAAI,CAAC,EACH,OAGF,IAAM,EAAgB,IAAI,EAAW,KAAK,CAI1C,GAAI,CAAC,WAAY,WAAY,SAAU,WAAW,CAAC,SAAS,EAAM,KAG5D,MAFiB,EAAW,QAAQ,EAAc,GAEvC,GACb,MAAO,QAIT,MAAM,EAAW,SAAS,EAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"EnsembleBuilder.mjs","names":["QueryBuilder"],"sources":["../../../src/Database/Ensemble/EnsembleBuilder.ts"],"sourcesContent":["/**\n * EnsembleBuilder\n *\n * Extends the query builder to work with Ensemble models\n */\n\nimport { DatabaseAdapter } from '@/Database/Contracts/DatabaseAdapter';\nimport { Builder as QueryBuilder } from '@/Database/Query/Builder';\nimport { Ensemble } from './Ensemble';\nimport { EnsembleCollection } from './EnsembleCollection';\nimport { Relation } from './Relations';\n\nexport class EnsembleBuilder<T extends Ensemble> extends QueryBuilder<T> {\n /**\n * The model being queried\n */\n protected model: T;\n\n /**\n * The relationships that should be eager loaded\n */\n protected eagerLoad: Record<string, (query: any) => void> = {};\n\n constructor(adapter: DatabaseAdapter, model: T) {\n super(adapter);\n this.model = model;\n this.from(model.getTable());\n }\n\n /**\n * Find a model by its primary key\n */\n async find(id: any): Promise<T | null> {\n return this.where(this.model.getKeyName(), '=', id).first();\n }\n\n /**\n * Execute the query and get all results\n */\n async get(): Promise<T[]> {\n const results = await super.get();\n const models = this.hydrate(results);\n\n if (Object.keys(this.eagerLoad).length > 0) {\n await this.eagerLoadRelations(models);\n }\n\n return models;\n }\n\n /**\n * Get the first record\n */\n async first(): Promise<T | null> {\n const results = await this.limit(1).get();\n return results[0] || null;\n }\n\n /**\n * Create a collection of models from plain arrays\n */\n protected hydrate(items: any[]): T[] {\n return items.map((item) => this.newModelInstance(item, true));\n }\n\n /**\n * Create a new instance of the model\n */\n protected newModelInstance(attributes: Record<string, any> = {}, exists: boolean = false): T {\n const ModelClass = this.model.constructor as new (attributes: Record<string, any>, fromDatabase: boolean) => T;\n // Pass true for fromDatabase to bypass fillable/guarded checks when hydrating from DB\n const instance = new ModelClass(attributes, exists);\n (instance as any).exists = exists;\n (instance as any).syncOriginal();\n\n // Fire retrieved event if this is from database\n if (exists) {\n // Fire asynchronously but don't wait for it\n (instance as any).fireModelEvent?.('retrieved').catch(() => {\n // Silently ignore errors from event firing during hydration\n });\n }\n\n return instance;\n }\n\n /**\n * Add a select statement to the query\n */\n addSelect(...columns: string[]): this {\n if (this._columns.length === 1 && this._columns[0] === '*') {\n this._columns = [];\n }\n this._columns.push(...columns);\n return this;\n }\n\n /**\n * Set the relationships that should be eager loaded\n */\n with(relations: string | string[] | Record<string, (query: any) => void>): this {\n if (typeof relations === 'string') {\n this.eagerLoad[relations] = () => {};\n } else if (Array.isArray(relations)) {\n for (const relation of relations) {\n this.eagerLoad[relation] = () => {};\n }\n } else {\n for (const [relation, callback] of Object.entries(relations)) {\n this.eagerLoad[relation] = callback;\n }\n }\n\n return this;\n }\n\n /**\n * Eager load the relationships for the models\n */\n protected async eagerLoadRelations(models: T[]): Promise<void> {\n for (const [name, constraints] of Object.entries(this.eagerLoad)) {\n if (models.length === 0) {\n continue;\n }\n\n // Parse nested relations (e.g., \"posts.comments\")\n const segments = name.split('.');\n\n if (segments.length > 1) {\n await this.eagerLoadNestedRelations(models, name, constraints);\n } else {\n await this.eagerLoadRelation(models, name, constraints);\n }\n }\n }\n\n /**\n * Eagerly load the relationship on a set of models\n */\n protected async eagerLoadRelation(models: T[], name: string, constraints: (query: any) => void): Promise<void> {\n // Get the relation instance from the first model\n const relation = this.getRelation(models[0], name);\n\n // Set the eager constraints\n relation.addEagerConstraints(models);\n\n // Apply any additional constraints\n constraints(relation);\n\n // Initialize the relation on all models\n relation.initRelation(models, name);\n\n // Get the eager results\n const results = await relation.getEager();\n\n // Match the results back to their parent models\n relation.match(models, new EnsembleCollection(results), name);\n }\n\n /**\n * Eagerly load nested relationships\n */\n protected async eagerLoadNestedRelations(\n models: T[],\n name: string,\n constraints: (query: any) => void\n ): Promise<void> {\n const segments = name.split('.');\n const firstSegment = segments[0];\n const remainingSegments = segments.slice(1).join('.');\n\n // Load the first level relationship\n await this.eagerLoadRelation(models, firstSegment, () => {});\n\n // Get all the loaded models from the first relationship\n const relatedModels: Ensemble[] = [];\n for (const model of models) {\n const related = model.getRelation(firstSegment);\n if (related) {\n if (Array.isArray(related)) {\n relatedModels.push(...related);\n } else if (related instanceof EnsembleCollection) {\n relatedModels.push(...related);\n } else {\n relatedModels.push(related);\n }\n }\n }\n\n // Recursively load the nested relationships\n if (relatedModels.length > 0 && relatedModels[0]) {\n const nestedBuilder = relatedModels[0].newQuery();\n nestedBuilder.eagerLoad[remainingSegments] = constraints;\n await nestedBuilder.eagerLoadRelations(relatedModels as any[]);\n }\n }\n\n /**\n * Get the relation instance for the given relation name\n */\n protected getRelation(model: T, name: string): Relation<any, any> {\n const relationMethod = (model as any)[name];\n\n if (typeof relationMethod !== 'function') {\n throw new Error(`Call to undefined relationship [${name}] on model [${model.constructor.name}]`);\n }\n\n const relation = relationMethod.call(model);\n\n if (!(relation instanceof Relation)) {\n throw new Error(`Relationship method [${name}] must return a Relation instance`);\n }\n\n // Disable default constraints for eager loading\n const originalConstraints = Relation['constraints'];\n Relation['constraints'] = false;\n const freshRelation = relationMethod.call(model);\n Relation['constraints'] = originalConstraints;\n\n return freshRelation;\n }\n\n /**\n * Create a new model and store it in the database\n */\n async create(attributes: Record<string, any>): Promise<T> {\n const instance = this.newModelInstance(attributes);\n await instance.save();\n return instance;\n }\n\n /**\n * Update records in the database\n */\n async update(values: Record<string, any>): Promise<number> {\n return await super.update(values);\n }\n\n /**\n * Delete records from the database\n */\n async delete(): Promise<number> {\n return await super.delete();\n }\n\n /**\n * Get a paginated result\n */\n async paginate(\n perPage: number = 15,\n page: number = 1\n ): Promise<{\n data: T[];\n total: number;\n perPage: number;\n currentPage: number;\n lastPage: number;\n from: number;\n to: number;\n }> {\n const total = await this.clone().count();\n const offset = (page - 1) * perPage;\n\n const data = await this.clone().offset(offset).limit(perPage).get();\n\n const lastPage = Math.ceil(total / perPage);\n const from = total > 0 ? offset + 1 : 0;\n const to = Math.min(offset + perPage, total);\n\n return {\n data,\n total,\n perPage,\n currentPage: page,\n lastPage,\n from,\n to,\n };\n }\n\n /**\n * Chunk the results of the query\n */\n async chunk(count: number, callback: (models: T[]) => Promise<boolean | void>): Promise<void> {\n let page = 1;\n\n while (true) {\n const results = await this.clone()\n .offset((page - 1) * count)\n .limit(count)\n .get();\n\n if (results.length === 0) {\n break;\n }\n\n const shouldContinue = await callback(results);\n if (shouldContinue === false) {\n break;\n }\n\n page++;\n }\n }\n\n /**\n * Clone the query builder\n */\n clone(): EnsembleBuilder<T> {\n const cloned = new EnsembleBuilder<T>(this.adapter, this.model);\n cloned._columns = [...this._columns];\n cloned._distinct = this._distinct;\n cloned._table = this._table;\n cloned._wheres = [...this._wheres];\n cloned._joins = [...this._joins];\n cloned._orders = [...this._orders];\n cloned._groups = [...this._groups];\n cloned._havings = [...this._havings];\n cloned._limit = this._limit;\n cloned._offset = this._offset;\n cloned._bindings = [...this._bindings];\n cloned.eagerLoad = { ...this.eagerLoad };\n return cloned;\n }\n}\n"],"mappings":"iMAS0D,CAG1D,IAAa,EAAb,MAAa,UAA4CA,CAAgB,CAIvE,MAKA,UAA4D,EAAE,CAE9D,YAAY,EAA0B,EAAU,CAC9C,MAAM,EAAQ,CACd,KAAK,MAAQ,EACb,KAAK,KAAK,EAAM,UAAU,CAAC,CAM7B,MAAM,KAAK,EAA4B,CACrC,OAAO,KAAK,MAAM,KAAK,MAAM,YAAY,CAAE,IAAK,EAAG,CAAC,OAAO,CAM7D,MAAM,KAAoB,CACxB,IAAM,EAAU,MAAM,MAAM,KAAK,CAC3B,EAAS,KAAK,QAAQ,EAAQ,CAMpC,OAJI,OAAO,KAA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GAClB,EAAe,EASd,CACD,IAAM,EAAQ,MAAM,KAAK,OAAO,CAAC,OAAO,CAClC,GAAU,EAAO,GAAK,EAQ5B,MAAO,CACL,KAPW,MAAM,KAAK,OAAO,CAAC,OAAO,EAAO,CAAC,MAAM,EAAQ,CAAC,KAAK,CAQjE,QACA,UACA,YAAa,EACb,SATe,KAAK,KAAK,EAAQ,EAAQ,CAUzC,KATW,EAAQ,EAAI,EAAS,EAAI,EAUpC,GATS,KAAK,IAAI,EAAS,EAAS,EAAM,CAU3C,CAMH,MAAM,MAAM,EAAe,EAAmE,CAC5F,IAAI,EAAO,EAEX,OAAa,CACX,IAAM,EAAU,MAAM,KAAK,OAAO,CAC/B,QAAQ,EAAO,GAAK,EAAM,CAC1B,MAAM,EAAM,CACZ,KAAK,CAOR,GALI,EAAQ,SAAW,GAIA,MAAM,EAAS,EAAQ,GACvB,GACrB,MAGF,KAOJ,OAA4B,CAC1B,IAAM,EAAS,IAAI,EAAmB,KAAK,QAAS,KAAK,MAAM,CAa/D,MAZA,GAAO,SAAW,CAAC,GAAG,KAAK,SAAS,CACpC,EAAO,UAAY,KAAK,UACxB,EAAO,OAAS,KAAK,OACrB,EAAO,QAAU,CAAC,GAAG,KAAK,QAAQ,CAClC,EAAO,OAAS,CAAC,GAAG,KAAK,OAAO,CAChC,EAAO,QAAU,CAAC,GAAG,KAAK,QAAQ,CAClC,EAAO,QAAU,CAAC,GAAG,KAAK,QAAQ,CAClC,EAAO,SAAW,CAAC,GAAG,KAAK,SAAS,CACpC,EAAO,OAAS,KAAK,OACrB,EAAO,QAAU,KAAK,QACtB,EAAO,UAAY,CAAC,GAAG,KAAK,UAAU,CACtC,EAAO,UAAY,CAAE,GAAG,KAAK,UAAW,CACjC"}
1
+ {"version":3,"file":"EnsembleBuilder.mjs","names":["QueryBuilder"],"sources":["../../../src/Database/Ensemble/EnsembleBuilder.ts"],"sourcesContent":["/**\n * EnsembleBuilder\n *\n * Extends the query builder to work with Ensemble models\n */\n\nimport { DatabaseAdapter } from '@/Database/Contracts/DatabaseAdapter';\nimport { Builder as QueryBuilder } from '@/Database/Query/Builder';\nimport { Ensemble } from './Ensemble';\nimport { EnsembleCollection } from './EnsembleCollection';\nimport { Relation } from './Relations';\n\nexport class EnsembleBuilder<T extends Ensemble> extends QueryBuilder<T> {\n /**\n * The model being queried\n */\n protected model: T;\n\n /**\n * The relationships that should be eager loaded\n */\n protected eagerLoad: Record<string, (query: any) => void> = {};\n\n constructor(adapter: DatabaseAdapter, model: T) {\n super(adapter);\n this.model = model;\n this.from(model.getTable());\n }\n\n /**\n * Find a model by its primary key\n */\n async find(id: any): Promise<T | null> {\n return this.where(this.model.getKeyName(), '=', id).first();\n }\n\n /**\n * Execute the query and get all results\n */\n async get(): Promise<T[]> {\n const results = await super.get();\n const models = this.hydrate(results);\n\n if (Object.keys(this.eagerLoad).length > 0) {\n await this.eagerLoadRelations(models);\n }\n\n return models;\n }\n\n /**\n * Get the first record\n */\n async first(): Promise<T | null> {\n const results = await this.limit(1).get();\n return results[0] || null;\n }\n\n /**\n * Create a collection of models from plain arrays\n */\n protected hydrate(items: any[]): T[] {\n return items.map((item) => this.newModelInstance(item, true));\n }\n\n /**\n * Create a new instance of the model\n */\n protected newModelInstance(attributes: Record<string, any> = {}, exists: boolean = false): T {\n const ModelClass = this.model.constructor as new (attributes: Record<string, any>, fromDatabase: boolean) => T;\n // Pass true for fromDatabase to bypass fillable/guarded checks when hydrating from DB\n const instance = new ModelClass(attributes, exists);\n (instance as any).exists = exists;\n (instance as any).syncOriginal();\n\n // Fire retrieved event if this is from database\n if (exists) {\n // Fire asynchronously but don't wait for it\n (instance as any).fireModelEvent?.('retrieved').catch(() => {\n // Silently ignore errors from event firing during hydration\n });\n }\n\n return instance;\n }\n\n /**\n * Add a select statement to the query\n */\n addSelect(...columns: string[]): this {\n if (this._columns.length === 1 && this._columns[0] === '*') {\n this._columns = [];\n }\n this._columns.push(...columns);\n return this;\n }\n\n /**\n * Set the relationships that should be eager loaded\n */\n with(relations: string | string[] | Record<string, (query: any) => void>): this {\n if (typeof relations === 'string') {\n this.eagerLoad[relations] = () => {};\n } else if (Array.isArray(relations)) {\n for (const relation of relations) {\n this.eagerLoad[relation] = () => {};\n }\n } else {\n for (const [relation, callback] of Object.entries(relations)) {\n this.eagerLoad[relation] = callback;\n }\n }\n\n return this;\n }\n\n /**\n * Eager load the relationships for the models\n */\n protected async eagerLoadRelations(models: T[]): Promise<void> {\n for (const [name, constraints] of Object.entries(this.eagerLoad)) {\n if (models.length === 0) {\n continue;\n }\n\n // Parse nested relations (e.g., \"posts.comments\")\n const segments = name.split('.');\n\n if (segments.length > 1) {\n await this.eagerLoadNestedRelations(models, name, constraints);\n } else {\n await this.eagerLoadRelation(models, name, constraints);\n }\n }\n }\n\n /**\n * Eagerly load the relationship on a set of models\n */\n protected async eagerLoadRelation(models: T[], name: string, constraints: (query: any) => void): Promise<void> {\n // Get the relation instance from the first model\n const relation = this.getRelation(models[0], name);\n\n // Set the eager constraints\n relation.addEagerConstraints(models);\n\n // Apply any additional constraints\n constraints(relation);\n\n // Initialize the relation on all models\n relation.initRelation(models, name);\n\n // Get the eager results\n const results = await relation.getEager();\n\n // Match the results back to their parent models\n relation.match(models, new EnsembleCollection(results), name);\n }\n\n /**\n * Eagerly load nested relationships\n */\n protected async eagerLoadNestedRelations(\n models: T[],\n name: string,\n constraints: (query: any) => void\n ): Promise<void> {\n const segments = name.split('.');\n const firstSegment = segments[0];\n const remainingSegments = segments.slice(1).join('.');\n\n // Load the first level relationship\n await this.eagerLoadRelation(models, firstSegment, () => {});\n\n // Get all the loaded models from the first relationship\n const relatedModels: Ensemble[] = [];\n for (const model of models) {\n const related = model.getRelation(firstSegment);\n if (related) {\n if (Array.isArray(related)) {\n relatedModels.push(...related);\n } else if (related instanceof EnsembleCollection) {\n relatedModels.push(...related);\n } else {\n relatedModels.push(related);\n }\n }\n }\n\n // Recursively load the nested relationships\n if (relatedModels.length > 0 && relatedModels[0]) {\n const nestedBuilder = relatedModels[0].newQuery();\n nestedBuilder.eagerLoad[remainingSegments] = constraints;\n await nestedBuilder.eagerLoadRelations(relatedModels as any[]);\n }\n }\n\n /**\n * Get the relation instance for the given relation name\n */\n protected getRelation(model: T, name: string): Relation<any, any> {\n const relationMethod = (model as any)[name];\n\n if (typeof relationMethod !== 'function') {\n throw new Error(`Call to undefined relationship [${name}] on model [${model.constructor.name}]`);\n }\n\n const relation = relationMethod.call(model);\n\n if (!(relation instanceof Relation)) {\n throw new Error(`Relationship method [${name}] must return a Relation instance`);\n }\n\n // Disable default constraints for eager loading\n const originalConstraints = Relation['constraints'];\n Relation['constraints'] = false;\n const freshRelation = relationMethod.call(model);\n Relation['constraints'] = originalConstraints;\n\n return freshRelation;\n }\n\n /**\n * Create a new model and store it in the database\n */\n async create(attributes: Record<string, any>): Promise<T> {\n const instance = this.newModelInstance(attributes);\n await instance.save();\n return instance;\n }\n\n /**\n * Update records in the database\n */\n async update(values: Record<string, any>): Promise<number> {\n return await super.update(values);\n }\n\n /**\n * Delete records from the database\n */\n async delete(): Promise<number> {\n return await super.delete();\n }\n\n /**\n * Get a paginated result\n */\n async paginate(\n perPage: number = 15,\n page: number = 1\n ): Promise<{\n data: T[];\n total: number;\n perPage: number;\n currentPage: number;\n lastPage: number;\n from: number;\n to: number;\n }> {\n const total = await this.clone().count();\n const offset = (page - 1) * perPage;\n\n const data = await this.clone().offset(offset).limit(perPage).get();\n\n const lastPage = Math.ceil(total / perPage);\n const from = total > 0 ? offset + 1 : 0;\n const to = Math.min(offset + perPage, total);\n\n return {\n data,\n total,\n perPage,\n currentPage: page,\n lastPage,\n from,\n to,\n };\n }\n\n /**\n * Chunk the results of the query\n */\n async chunk(count: number, callback: (models: T[]) => Promise<boolean | void>): Promise<void> {\n let page = 1;\n\n while (true) {\n const results = await this.clone()\n .offset((page - 1) * count)\n .limit(count)\n .get();\n\n if (results.length === 0) {\n break;\n }\n\n const shouldContinue = await callback(results);\n if (shouldContinue === false) {\n break;\n }\n\n page++;\n }\n }\n\n /**\n * Clone the query builder\n */\n clone(): EnsembleBuilder<T> {\n const cloned = new EnsembleBuilder<T>(this.adapter, this.model);\n cloned._columns = [...this._columns];\n cloned._distinct = this._distinct;\n cloned._table = this._table;\n cloned._wheres = [...this._wheres];\n cloned._joins = [...this._joins];\n cloned._orders = [...this._orders];\n cloned._groups = [...this._groups];\n cloned._havings = [...this._havings];\n cloned._limit = this._limit;\n cloned._offset = this._offset;\n cloned._bindings = [...this._bindings];\n cloned.eagerLoad = { ...this.eagerLoad };\n return cloned;\n }\n}\n"],"mappings":"iMAS0D,CAG1D,IAAa,EAAb,MAAa,UAA4CA,CAAgB,CAIvE,MAKA,UAA4D,EAAE,CAE9D,YAAY,EAA0B,EAAU,CAC9C,MAAM,EAAQ,CACd,KAAK,MAAQ,EACb,KAAK,KAAK,EAAM,UAAU,CAAC,CAM7B,MAAM,KAAK,EAA4B,CACrC,OAAO,KAAK,MAAM,KAAK,MAAM,YAAY,CAAE,IAAK,EAAG,CAAC,OAAO,CAM7D,MAAM,KAAoB,CACxB,IAAM,EAAU,MAAM,MAAM,KAAK,CAC3B,EAAS,KAAK,QAAQ,EAAQ,CAMpC,OAJI,OAAO,KAAK,KAAK,UAAU,CAAC,OAAS,GACvC,MAAM,KAAK,mBAAmB,EAAO,CAGhC,EAMT,MAAM,OAA2B,CAE/B,OAAO,MADe,KAAK,MAAM,EAAE,CAAC,KAAK,EAC1B,IAAM,KAMvB,QAAkB,EAAmB,CACnC,OAAO,EAAM,IAAK,GAAS,KAAK,iBAAiB,EAAM,GAAK,CAAC,CAM/D,iBAA2B,EAAkC,EAAE,CAAE,EAAkB,GAAU,CAC3F,IAAM,EAAa,KAAK,MAAM,YAExB,EAAW,IAAI,EAAW,EAAY,EAAO,CAYnD,MAXA,GAAkB,OAAS,EAC3B,EAAkB,cAAc,CAG5B,GAEF,EAAkB,iBAAiB,YAAY,CAAC,UAAY,GAE1D,CAGG,EAMT,UAAU,GAAG,EAAyB,CA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Z,KAAK,CAOR,GALI,EAAQ,SAAW,GAKnB,MADyB,EAAS,EAAQ,GACvB,GACrB,MAGF,KAOJ,OAA4B,CAC1B,IAAM,EAAS,IAAI,EAAmB,KAAK,QAAS,KAAK,MAAM,CAa/D,MAZA,GAAO,SAAW,CAAC,GAAG,KAAK,SAAS,CACpC,EAAO,UAAY,KAAK,UACxB,EAAO,OAAS,KAAK,OACrB,EAAO,QAAU,CAAC,GAAG,KAAK,QAAQ,CAClC,EAAO,OAAS,CAAC,GAAG,KAAK,OAAO,CAChC,EAAO,QAAU,CAAC,GAAG,KAAK,QAAQ,CAClC,EAAO,QAAU,CAAC,GAAG,KAAK,QAAQ,CAClC,EAAO,SAAW,CAAC,GAAG,KAAK,SAAS,CACpC,EAAO,OAAS,KAAK,OACrB,EAAO,QAAU,KAAK,QACtB,EAAO,UAAY,CAAC,GAAG,KAAK,UAAU,CACtC,EAAO,UAAY,CAAE,GAAG,KAAK,UAAW,CACjC"}
@@ -1 +1 @@
1
- const e=require(`../../_virtual/_rolldown/runtime.cjs`);var t,n=e.__esmMin((()=>{t=class e extends Array{constructor(t=[]){super(...t),Object.setPrototypeOf(this,e.prototype)}all(){return[...this]}first(e){return e?this.find(e):this[0]}last(e){if(e){let t=this.filter(e);return t[t.length-1]}return this[this.length-1]}reject(t){return new e(this.filter((e,n)=>!t(e,n)))}mapIntoCollection(e){return this.map((t,n)=>e(t,n))}unique(t){if(!t)return new e([...new Set(this)]);let n=new Set,r=[];for(let e of this){let i=e[t];n.has(i)||(n.add(i),r.push(e))}return new e(r)}toArray(){return this.map(e=>e.toObject())}toJSON(){return this.toArray()}isEmpty(){return this.length===0}isNotEmpty(){return this.length>0}sum(e){return e?this.reduce((t,n)=>t+Number(n[e]||0),0):0}avg(e){return this.isEmpty()?0:this.sum(e)/this.length}min(e){if(!(this.isEmpty()||!e))return Math.min(...this.map(t=>Number(t[e]||0)))}max(e){if(!(this.isEmpty()||!e))return Math.max(...this.map(t=>Number(t[e]||0)))}pluck(e){return this.map(t=>t[e])}modelKeys(){return this.map(e=>e.getKey())}sortBy(t){let n=[...this];return typeof t==`function`?n.sort(t):n.sort((e,n)=>{let r=e[t],i=n[t];return r<i?-1:r>i?1:0}),new e(n)}sortByDesc(e){return this.sortBy((t,n)=>{let r=t[e],i=n[e];return r<i?1:r>i?-1:0})}groupBy(t){let n={};for(let e of this){let r=String(e[t]);n[r]||(n[r]=[]),n[r].push(e)}let r={};for(let[t,i]of Object.entries(n))r[t]=new e(i);return r}chunkModels(t){let n=[];for(let r=0;r<this.length;r+=t)n.push(new e(this.slice(r,r+t)));return n}take(t){return new e(this.slice(0,t))}skip(t){return new e(this.slice(t))}merge(t){return new e([...this,...t])}except(t){let n=new Set(t);return new e(this.filter(e=>!n.has(e.getKey())))}only(t){let n=new Set(t);return new e(this.filter(e=>n.has(e.getKey())))}async load(e){return this}find(e){return typeof e==`function`?super.find(e):super.find(t=>t.getKey()===e)}contains(e){return this.find(e)!==void 0}whereIn(t,n){let r=new Set(n);return new e(super.filter(e=>r.has(e[t])))}whereNotIn(t,n){let r=new Set(n);return new e(super.filter(e=>!r.has(e[t])))}count(){return this.length}}}));n(),exports.EnsembleCollection=t,Object.defineProperty(exports,`init_EnsembleCollection`,{enumerable:!0,get:function(){return n}});
1
+ const e=require(`../../_virtual/_rolldown/runtime.cjs`);var t,n=e.__esmMin((()=>{t=class e extends Array{constructor(t=[]){super(...t),Object.setPrototypeOf(this,e.prototype)}all(){return[...this]}first(e){return e?this.find(e):this[0]}last(e){if(e){let t=this.filter(e);return t[t.length-1]}return this[this.length-1]}reject(t){return new e(this.filter((e,n)=>!t(e,n)))}mapIntoCollection(e){return this.map((t,n)=>e(t,n))}unique(t){if(!t)return new e([...new Set(this)]);let n=new Set,r=[];for(let e of this){let i=e[t];n.has(i)||(n.add(i),r.push(e))}return new e(r)}toArray(){return this.map(e=>e.toObject())}toJSON(){return this.toArray()}isEmpty(){return this.length===0}isNotEmpty(){return this.length>0}sum(e){return e?this.reduce((t,n)=>t+Number(n[e]||0),0):0}avg(e){return this.isEmpty()?0:this.sum(e)/this.length}min(e){if(!(this.isEmpty()||!e))return Math.min(...this.map(t=>Number(t[e]||0)))}max(e){if(!(this.isEmpty()||!e))return Math.max(...this.map(t=>Number(t[e]||0)))}pluck(e){return this.map(t=>t[e])}modelKeys(){return this.map(e=>e.getKey())}sortBy(t){let n=[...this];return typeof t==`function`?n.sort(t):n.sort((e,n)=>{let r=e[t],i=n[t];return r<i?-1:+(r>i)}),new e(n)}sortByDesc(e){return this.sortBy((t,n)=>{let r=t[e],i=n[e];return r<i?1:r>i?-1:0})}groupBy(t){let n={};for(let e of this){let r=String(e[t]);n[r]||(n[r]=[]),n[r].push(e)}let r={};for(let[t,i]of Object.entries(n))r[t]=new e(i);return r}chunkModels(t){let n=[];for(let r=0;r<this.length;r+=t)n.push(new e(this.slice(r,r+t)));return n}take(t){return new e(this.slice(0,t))}skip(t){return new e(this.slice(t))}merge(t){return new e([...this,...t])}except(t){let n=new Set(t);return new e(this.filter(e=>!n.has(e.getKey())))}only(t){let n=new Set(t);return new e(this.filter(e=>n.has(e.getKey())))}async load(e){return this}find(e){return typeof e==`function`?super.find(e):super.find(t=>t.getKey()===e)}contains(e){return this.find(e)!==void 0}whereIn(t,n){let r=new Set(n);return new e(super.filter(e=>r.has(e[t])))}whereNotIn(t,n){let r=new Set(n);return new e(super.filter(e=>!r.has(e[t])))}count(){return this.length}}}));n(),exports.EnsembleCollection=t,Object.defineProperty(exports,`init_EnsembleCollection`,{enumerable:!0,get:function(){return n}});
@@ -1,2 +1,2 @@
1
- import{__esmMin as e}from"../../_virtual/_rolldown/runtime.mjs";var t,n=e((()=>{t=class e extends Array{constructor(t=[]){super(...t),Object.setPrototypeOf(this,e.prototype)}all(){return[...this]}first(e){return e?this.find(e):this[0]}last(e){if(e){let t=this.filter(e);return t[t.length-1]}return this[this.length-1]}reject(t){return new e(this.filter((e,n)=>!t(e,n)))}mapIntoCollection(e){return this.map((t,n)=>e(t,n))}unique(t){if(!t)return new e([...new Set(this)]);let n=new Set,r=[];for(let e of this){let i=e[t];n.has(i)||(n.add(i),r.push(e))}return new e(r)}toArray(){return this.map(e=>e.toObject())}toJSON(){return this.toArray()}isEmpty(){return this.length===0}isNotEmpty(){return this.length>0}sum(e){return e?this.reduce((t,n)=>t+Number(n[e]||0),0):0}avg(e){return this.isEmpty()?0:this.sum(e)/this.length}min(e){if(!(this.isEmpty()||!e))return Math.min(...this.map(t=>Number(t[e]||0)))}max(e){if(!(this.isEmpty()||!e))return Math.max(...this.map(t=>Number(t[e]||0)))}pluck(e){return this.map(t=>t[e])}modelKeys(){return this.map(e=>e.getKey())}sortBy(t){let n=[...this];return typeof t==`function`?n.sort(t):n.sort((e,n)=>{let r=e[t],i=n[t];return r<i?-1:r>i?1:0}),new e(n)}sortByDesc(e){return this.sortBy((t,n)=>{let r=t[e],i=n[e];return r<i?1:r>i?-1:0})}groupBy(t){let n={};for(let e of this){let r=String(e[t]);n[r]||(n[r]=[]),n[r].push(e)}let r={};for(let[t,i]of Object.entries(n))r[t]=new e(i);return r}chunkModels(t){let n=[];for(let r=0;r<this.length;r+=t)n.push(new e(this.slice(r,r+t)));return n}take(t){return new e(this.slice(0,t))}skip(t){return new e(this.slice(t))}merge(t){return new e([...this,...t])}except(t){let n=new Set(t);return new e(this.filter(e=>!n.has(e.getKey())))}only(t){let n=new Set(t);return new e(this.filter(e=>n.has(e.getKey())))}async load(e){return this}find(e){return typeof e==`function`?super.find(e):super.find(t=>t.getKey()===e)}contains(e){return this.find(e)!==void 0}whereIn(t,n){let r=new Set(n);return new e(super.filter(e=>r.has(e[t])))}whereNotIn(t,n){let r=new Set(n);return new e(super.filter(e=>!r.has(e[t])))}count(){return this.length}}}));n();export{t as EnsembleCollection,n as init_EnsembleCollection};
1
+ import{__esmMin as e}from"../../_virtual/_rolldown/runtime.mjs";var t,n=e((()=>{t=class e extends Array{constructor(t=[]){super(...t),Object.setPrototypeOf(this,e.prototype)}all(){return[...this]}first(e){return e?this.find(e):this[0]}last(e){if(e){let t=this.filter(e);return t[t.length-1]}return this[this.length-1]}reject(t){return new e(this.filter((e,n)=>!t(e,n)))}mapIntoCollection(e){return this.map((t,n)=>e(t,n))}unique(t){if(!t)return new e([...new Set(this)]);let n=new Set,r=[];for(let e of this){let i=e[t];n.has(i)||(n.add(i),r.push(e))}return new e(r)}toArray(){return this.map(e=>e.toObject())}toJSON(){return this.toArray()}isEmpty(){return this.length===0}isNotEmpty(){return this.length>0}sum(e){return e?this.reduce((t,n)=>t+Number(n[e]||0),0):0}avg(e){return this.isEmpty()?0:this.sum(e)/this.length}min(e){if(!(this.isEmpty()||!e))return Math.min(...this.map(t=>Number(t[e]||0)))}max(e){if(!(this.isEmpty()||!e))return Math.max(...this.map(t=>Number(t[e]||0)))}pluck(e){return this.map(t=>t[e])}modelKeys(){return this.map(e=>e.getKey())}sortBy(t){let n=[...this];return typeof t==`function`?n.sort(t):n.sort((e,n)=>{let r=e[t],i=n[t];return r<i?-1:+(r>i)}),new e(n)}sortByDesc(e){return this.sortBy((t,n)=>{let r=t[e],i=n[e];return r<i?1:r>i?-1:0})}groupBy(t){let n={};for(let e of this){let r=String(e[t]);n[r]||(n[r]=[]),n[r].push(e)}let r={};for(let[t,i]of Object.entries(n))r[t]=new e(i);return r}chunkModels(t){let n=[];for(let r=0;r<this.length;r+=t)n.push(new e(this.slice(r,r+t)));return n}take(t){return new e(this.slice(0,t))}skip(t){return new e(this.slice(t))}merge(t){return new e([...this,...t])}except(t){let n=new Set(t);return new e(this.filter(e=>!n.has(e.getKey())))}only(t){let n=new Set(t);return new e(this.filter(e=>n.has(e.getKey())))}async load(e){return this}find(e){return typeof e==`function`?super.find(e):super.find(t=>t.getKey()===e)}contains(e){return this.find(e)!==void 0}whereIn(t,n){let r=new Set(n);return new e(super.filter(e=>r.has(e[t])))}whereNotIn(t,n){let r=new Set(n);return new e(super.filter(e=>!r.has(e[t])))}count(){return this.length}}}));n();export{t as EnsembleCollection,n as init_EnsembleCollection};
2
2
  //# sourceMappingURL=EnsembleCollection.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"EnsembleCollection.mjs","names":[],"sources":["../../../src/Database/Ensemble/EnsembleCollection.ts"],"sourcesContent":["/**\n * EnsembleCollection Class\n *\n * A collection of Ensemble models\n */\n\nimport { Ensemble } from './Ensemble';\n\nexport class EnsembleCollection<T extends Ensemble> extends Array<T> {\n /**\n * Create a new collection\n */\n constructor(items: T[] = []) {\n super(...items);\n Object.setPrototypeOf(this, EnsembleCollection.prototype);\n }\n\n /**\n * Get all items in the collection\n */\n all(): T[] {\n return [...this];\n }\n\n /**\n * Get the first item from the collection\n */\n first(callback?: (item: T) => boolean): T | undefined {\n if (callback) {\n return this.find(callback);\n }\n return this[0];\n }\n\n /**\n * Get the last item from the collection\n */\n last(callback?: (item: T) => boolean): T | undefined {\n if (callback) {\n const filtered = this.filter(callback);\n return filtered[filtered.length - 1];\n }\n return this[this.length - 1];\n }\n\n /**\n * Reject items from the collection using a callback\n */\n reject(callback: (item: T, index: number) => boolean): EnsembleCollection<T> {\n return new EnsembleCollection(this.filter((item, index) => !callback(item, index)));\n }\n\n /**\n * Map the collection and return a new collection\n */\n mapIntoCollection<U>(callback: (item: T, index: number) => U): U[] {\n return this.map((item, index) => callback(item, index));\n }\n\n /**\n * Get a collection with only unique items\n */\n unique(key?: keyof T): EnsembleCollection<T> {\n if (!key) {\n return new EnsembleCollection([...new Set(this)]);\n }\n\n const seen = new Set();\n const unique: T[] = [];\n\n for (const item of this) {\n const value = item[key];\n if (!seen.has(value)) {\n seen.add(value);\n unique.push(item);\n }\n }\n\n return new EnsembleCollection(unique);\n }\n\n /**\n * Get the collection of items as a plain array\n */\n toArray(): Record<string, any>[] {\n return this.map((item) => item.toObject());\n }\n\n /**\n * Get the collection of items as JSON\n */\n toJSON(): Record<string, any>[] {\n return this.toArray();\n }\n\n /**\n * Determine if the collection is empty\n */\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n /**\n * Determine if the collection is not empty\n */\n isNotEmpty(): boolean {\n return this.length > 0;\n }\n\n /**\n * Get the sum of the given values\n */\n sum(key?: keyof T): number {\n if (!key) {\n return 0;\n }\n\n return this.reduce((sum, item) => sum + Number(item[key] || 0), 0);\n }\n\n /**\n * Get the average value of a given key\n */\n avg(key?: keyof T): number {\n if (this.isEmpty()) {\n return 0;\n }\n\n return this.sum(key) / this.length;\n }\n\n /**\n * Get the min value of a given key\n */\n min(key?: keyof T): number | undefined {\n if (this.isEmpty() || !key) {\n return undefined;\n }\n\n return Math.min(...this.map((item) => Number(item[key] || 0)));\n }\n\n /**\n * Get the max value of a given key\n */\n max(key?: keyof T): number | undefined {\n if (this.isEmpty() || !key) {\n return undefined;\n }\n\n return Math.max(...this.map((item) => Number(item[key] || 0)));\n }\n\n /**\n * Pluck an attribute from each model\n */\n pluck(key: keyof T): any[] {\n return this.map((item) => item[key]);\n }\n\n /**\n * Get the keys of the collection items\n */\n modelKeys(): any[] {\n return this.map((item) => item.getKey());\n }\n\n /**\n * Sort the collection by a callback or key\n */\n sortBy(keyOrCallback: keyof T | ((a: T, b: T) => number)): EnsembleCollection<T> {\n const sorted = [...this];\n\n if (typeof keyOrCallback === 'function') {\n sorted.sort(keyOrCallback);\n } else {\n sorted.sort((a, b) => {\n const aVal = a[keyOrCallback];\n const bVal = b[keyOrCallback];\n\n if (aVal < bVal) return -1;\n if (aVal > bVal) return 1;\n return 0;\n });\n }\n\n return new EnsembleCollection(sorted);\n }\n\n /**\n * Sort the collection in descending order\n */\n sortByDesc(key: keyof T): EnsembleCollection<T> {\n return this.sortBy((a, b) => {\n const aVal = a[key];\n const bVal = b[key];\n\n if (aVal < bVal) return 1;\n if (aVal > bVal) return -1;\n return 0;\n });\n }\n\n /**\n * Group the collection by a given key\n */\n groupBy(key: keyof T): Record<string, EnsembleCollection<T>> {\n const groups: Record<string, T[]> = {};\n\n for (const item of this) {\n const groupKey = String(item[key]);\n\n if (!groups[groupKey]) {\n groups[groupKey] = [];\n }\n\n groups[groupKey].push(item);\n }\n\n const result: Record<string, EnsembleCollection<T>> = {};\n for (const [key, items] of Object.entries(groups)) {\n result[key] = new EnsembleCollection(items);\n }\n\n return result;\n }\n\n /**\n * Chunk the collection into smaller collections\n */\n chunkModels(size: number): EnsembleCollection<T>[] {\n const chunks: EnsembleCollection<T>[] = [];\n\n for (let i = 0; i < this.length; i += size) {\n chunks.push(new EnsembleCollection(this.slice(i, i + size)));\n }\n\n return chunks;\n }\n\n /**\n * Take the first n items\n */\n take(limit: number): EnsembleCollection<T> {\n return new EnsembleCollection(this.slice(0, limit));\n }\n\n /**\n * Skip the first n items\n */\n skip(count: number): EnsembleCollection<T> {\n return new EnsembleCollection(this.slice(count));\n }\n\n /**\n * Merge the collection with the given items\n */\n merge(items: T[]): EnsembleCollection<T> {\n return new EnsembleCollection([...this, ...items]);\n }\n\n /**\n * Get the collection without the specified items\n */\n except(keys: any[]): EnsembleCollection<T> {\n const keySet = new Set(keys);\n return new EnsembleCollection(this.filter((item) => !keySet.has(item.getKey())));\n }\n\n /**\n * Get only the specified items from the collection\n */\n only(keys: any[]): EnsembleCollection<T> {\n const keySet = new Set(keys);\n return new EnsembleCollection(this.filter((item) => keySet.has(item.getKey())));\n }\n\n /**\n * Load a set of relationships onto the collection\n */\n async load(relations: string | string[]): Promise<this> {\n // TODO: Implement eager loading\n // This will be implemented when we add relationship support\n return this;\n }\n\n /**\n * Find a model in the collection by key\n */\n find(keyOrCallback: any | ((item: T) => boolean)): T | undefined {\n if (typeof keyOrCallback === 'function') {\n return super.find(keyOrCallback);\n }\n\n return super.find((item) => item.getKey() === keyOrCallback);\n }\n\n /**\n * Determine if a key exists in the collection\n */\n contains(keyOrCallback: any | ((item: T) => boolean)): boolean {\n return this.find(keyOrCallback) !== undefined;\n }\n\n /**\n * Get the items with the specified keys\n */\n whereIn(key: keyof T, values: any[]): EnsembleCollection<T> {\n const valueSet = new Set(values);\n return new EnsembleCollection(super.filter((item) => valueSet.has(item[key])));\n }\n\n /**\n * Get the items where a key is not in the given values\n */\n whereNotIn(key: keyof T, values: any[]): EnsembleCollection<T> {\n const valueSet = new Set(values);\n return new EnsembleCollection(super.filter((item) => !valueSet.has(item[key])));\n }\n\n /**\n * Count the number of items in the collection\n */\n count(): number {\n return this.length;\n }\n}\n"],"mappings":"gFAQa,EAAb,MAAa,UAA+C,KAAS,CAInE,YAAY,EAAa,EAAE,CAAE,CAC3B,MAAM,GAAG,EAAM,CACf,OAAO,eAAe,KAAM,EAAmB,UAAU,CAM3D,KAAW,CACT,MAAO,CAAC,GAAG,KAAK,CAMlB,MAAM,EAAgD,CAIpD,OAHI,EACK,KAAK,KAAK,EAAS,CAErB,KAAK,GAMd,KAAK,EAAgD,CACnD,GAAI,EAAU,CACZ,IAAM,EAAW,KAAK,OAAO,EAAS,CACtC,OAAO,EAAS,EAAS,OAAS,GAEpC,OAAO,KAAK,KAAK,OAAS,GAM5B,OAAO,EAAsE,CAC3E,OAAO,IAAI,EAAmB,KAAK,QAAQ,EAAM,IAAU,CAAC,EAAS,EAAM,EAAM,CAAC,CAAC,CAMrF,kBAAqB,EAA8C,CACjE,OAAO,KAAK,KAAK,EAAM,IAAU,EAAS,EAAM,EAAM,CAAC,CAMzD,OAAO,EAAsC,CAC3C,GAAI,CAAC,EACH,OAAO,IAAI,EAAmB,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAGnD,IAAM,EAAO,IAAI,IACX,EAAc,EAAE,CAEtB,IAAK,IAAM,KAAQ,KAAM,CACvB,IAAM,EAAQ,EAAK,GACd,EAAK,IAAI,EAAM,GAClB,EAAK,IAAI,EAAM,CACf,EAAO,KAAK,EAAK,EAIrB,OAAO,IAAI,EAAmB,EAAO,CAMvC,SAAiC,CAC/B,OAAO,KAAK,IAAK,GAAS,EAAK,UAAU,CAAC,CAM5C,QAAgC,CAC9B,OAAO,KAAK,SAAS,CAMvB,SAAmB,CACjB,OAAO,KAAK,SAAW,EAMzB,YAAsB,CACpB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IAAM,EAAW,IAAI,IAAI,EAAO,CAChC,OAAO,IAAI,EAAmB,MAAM,OAAQ,GAAS,CAAC,EAAS,IAAI,EAAK,GAAK,CAAC,CAAC,CAMjF,OAAgB,CACd,OAAO,KAAK"}
1
+ {"version":3,"file":"EnsembleCollection.mjs","names":[],"sources":["../../../src/Database/Ensemble/EnsembleCollection.ts"],"sourcesContent":["/**\n * EnsembleCollection Class\n *\n * A collection of Ensemble models\n */\n\nimport { Ensemble } from './Ensemble';\n\nexport class EnsembleCollection<T extends Ensemble> extends Array<T> {\n /**\n * Create a new collection\n */\n constructor(items: T[] = []) {\n super(...items);\n Object.setPrototypeOf(this, EnsembleCollection.prototype);\n }\n\n /**\n * Get all items in the collection\n */\n all(): T[] {\n return [...this];\n }\n\n /**\n * Get the first item from the collection\n */\n first(callback?: (item: T) => boolean): T | undefined {\n if (callback) {\n return this.find(callback);\n }\n return this[0];\n }\n\n /**\n * Get the last item from the collection\n */\n last(callback?: (item: T) => boolean): T | undefined {\n if (callback) {\n const filtered = this.filter(callback);\n return filtered[filtered.length - 1];\n }\n return this[this.length - 1];\n }\n\n /**\n * Reject items from the collection using a callback\n */\n reject(callback: (item: T, index: number) => boolean): EnsembleCollection<T> {\n return new EnsembleCollection(this.filter((item, index) => !callback(item, index)));\n }\n\n /**\n * Map the collection and return a new collection\n */\n mapIntoCollection<U>(callback: (item: T, index: number) => U): U[] {\n return this.map((item, index) => callback(item, index));\n }\n\n /**\n * Get a collection with only unique items\n */\n unique(key?: keyof T): EnsembleCollection<T> {\n if (!key) {\n return new EnsembleCollection([...new Set(this)]);\n }\n\n const seen = new Set();\n const unique: T[] = [];\n\n for (const item of this) {\n const value = item[key];\n if (!seen.has(value)) {\n seen.add(value);\n unique.push(item);\n }\n }\n\n return new EnsembleCollection(unique);\n }\n\n /**\n * Get the collection of items as a plain array\n */\n toArray(): Record<string, any>[] {\n return this.map((item) => item.toObject());\n }\n\n /**\n * Get the collection of items as JSON\n */\n toJSON(): Record<string, any>[] {\n return this.toArray();\n }\n\n /**\n * Determine if the collection is empty\n */\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n /**\n * Determine if the collection is not empty\n */\n isNotEmpty(): boolean {\n return this.length > 0;\n }\n\n /**\n * Get the sum of the given values\n */\n sum(key?: keyof T): number {\n if (!key) {\n return 0;\n }\n\n return this.reduce((sum, item) => sum + Number(item[key] || 0), 0);\n }\n\n /**\n * Get the average value of a given key\n */\n avg(key?: keyof T): number {\n if (this.isEmpty()) {\n return 0;\n }\n\n return this.sum(key) / this.length;\n }\n\n /**\n * Get the min value of a given key\n */\n min(key?: keyof T): number | undefined {\n if (this.isEmpty() || !key) {\n return undefined;\n }\n\n return Math.min(...this.map((item) => Number(item[key] || 0)));\n }\n\n /**\n * Get the max value of a given key\n */\n max(key?: keyof T): number | undefined {\n if (this.isEmpty() || !key) {\n return undefined;\n }\n\n return Math.max(...this.map((item) => Number(item[key] || 0)));\n }\n\n /**\n * Pluck an attribute from each model\n */\n pluck(key: keyof T): any[] {\n return this.map((item) => item[key]);\n }\n\n /**\n * Get the keys of the collection items\n */\n modelKeys(): any[] {\n return this.map((item) => item.getKey());\n }\n\n /**\n * Sort the collection by a callback or key\n */\n sortBy(keyOrCallback: keyof T | ((a: T, b: T) => number)): EnsembleCollection<T> {\n const sorted = [...this];\n\n if (typeof keyOrCallback === 'function') {\n sorted.sort(keyOrCallback);\n } else {\n sorted.sort((a, b) => {\n const aVal = a[keyOrCallback];\n const bVal = b[keyOrCallback];\n\n if (aVal < bVal) return -1;\n if (aVal > bVal) return 1;\n return 0;\n });\n }\n\n return new EnsembleCollection(sorted);\n }\n\n /**\n * Sort the collection in descending order\n */\n sortByDesc(key: keyof T): EnsembleCollection<T> {\n return this.sortBy((a, b) => {\n const aVal = a[key];\n const bVal = b[key];\n\n if (aVal < bVal) return 1;\n if (aVal > bVal) return -1;\n return 0;\n });\n }\n\n /**\n * Group the collection by a given key\n */\n groupBy(key: keyof T): Record<string, EnsembleCollection<T>> {\n const groups: Record<string, T[]> = {};\n\n for (const item of this) {\n const groupKey = String(item[key]);\n\n if (!groups[groupKey]) {\n groups[groupKey] = [];\n }\n\n groups[groupKey].push(item);\n }\n\n const result: Record<string, EnsembleCollection<T>> = {};\n for (const [key, items] of Object.entries(groups)) {\n result[key] = new EnsembleCollection(items);\n }\n\n return result;\n }\n\n /**\n * Chunk the collection into smaller collections\n */\n chunkModels(size: number): EnsembleCollection<T>[] {\n const chunks: EnsembleCollection<T>[] = [];\n\n for (let i = 0; i < this.length; i += size) {\n chunks.push(new EnsembleCollection(this.slice(i, i + size)));\n }\n\n return chunks;\n }\n\n /**\n * Take the first n items\n */\n take(limit: number): EnsembleCollection<T> {\n return new EnsembleCollection(this.slice(0, limit));\n }\n\n /**\n * Skip the first n items\n */\n skip(count: number): EnsembleCollection<T> {\n return new EnsembleCollection(this.slice(count));\n }\n\n /**\n * Merge the collection with the given items\n */\n merge(items: T[]): EnsembleCollection<T> {\n return new EnsembleCollection([...this, ...items]);\n }\n\n /**\n * Get the collection without the specified items\n */\n except(keys: any[]): EnsembleCollection<T> {\n const keySet = new Set(keys);\n return new EnsembleCollection(this.filter((item) => !keySet.has(item.getKey())));\n }\n\n /**\n * Get only the specified items from the collection\n */\n only(keys: any[]): EnsembleCollection<T> {\n const keySet = new Set(keys);\n return new EnsembleCollection(this.filter((item) => keySet.has(item.getKey())));\n }\n\n /**\n * Load a set of relationships onto the collection\n */\n async load(relations: string | string[]): Promise<this> {\n // TODO: Implement eager loading\n // This will be implemented when we add relationship support\n return this;\n }\n\n /**\n * Find a model in the collection by key\n */\n find(keyOrCallback: any | ((item: T) => boolean)): T | undefined {\n if (typeof keyOrCallback === 'function') {\n return super.find(keyOrCallback);\n }\n\n return super.find((item) => item.getKey() === keyOrCallback);\n }\n\n /**\n * Determine if a key exists in the collection\n */\n contains(keyOrCallback: any | ((item: T) => boolean)): boolean {\n return this.find(keyOrCallback) !== undefined;\n }\n\n /**\n * Get the items with the specified keys\n */\n whereIn(key: keyof T, values: any[]): EnsembleCollection<T> {\n const valueSet = new Set(values);\n return new EnsembleCollection(super.filter((item) => valueSet.has(item[key])));\n }\n\n /**\n * Get the items where a key is not in the given values\n */\n whereNotIn(key: keyof T, values: any[]): EnsembleCollection<T> {\n const valueSet = new Set(values);\n return new EnsembleCollection(super.filter((item) => !valueSet.has(item[key])));\n }\n\n /**\n * Count the number of items in the collection\n */\n count(): number {\n return this.length;\n }\n}\n"],"mappings":"gFAQa,EAAb,MAAa,UAA+C,KAAS,CAInE,YAAY,EAAa,EAAE,CAAE,CAC3B,MAAM,GAAG,EAAM,CACf,OAAO,eAAe,KAAM,EAAmB,UAAU,CAM3D,KAAW,CACT,MAAO,CAAC,GAAG,KAAK,CAMlB,MAAM,EAAgD,CAIpD,OAHI,EACK,KAAK,KAAK,EAAS,CAErB,KAAK,GAMd,KAAK,EAAgD,CACnD,GAAI,EAAU,CACZ,IAAM,EAAW,KAAK,OAAO,EAAS,CACtC,OAAO,EAAS,EAAS,OAAS,GAEpC,OAAO,KAAK,KAAK,OAAS,GAM5B,OAAO,EAAsE,CAC3E,OAAO,IAAI,EAAmB,KAAK,QAAQ,EAAM,IAAU,CAAC,EAAS,EAAM,EAAM,CAAC,CAAC,CAMrF,kBAAqB,EAA8C,CACjE,OAAO,KAAK,KAAK,EAAM,IAAU,EAAS,EAAM,EAAM,CAAC,CAMzD,OAAO,EAAsC,CAC3C,GAAI,CAAC,EACH,OAAO,IAAI,EAAmB,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,CAAC,CAGnD,IAAM,EAAO,IAAI,IACX,EAAc,EAAE,CAEtB,IAAK,IAAM,KAAQ,KAAM,CACvB,IAAM,EAAQ,EAAK,GACd,EAAK,IAAI,EAAM,GAClB,EAAK,IAAI,EAAM,CACf,EAAO,KAAK,EAAK,EAIrB,OAAO,IAAI,EAAmB,EAAO,CAMvC,SAAiC,CAC/B,OAAO,KAAK,IAAK,GAAS,EAAK,UAAU,CAAC,CAM5C,QAAgC,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,GAAS,EAAS,IAAI,EAAK,GAAK,CAAC,CAAC,CAMhF,WAAW,EAAc,EAAsC,CAC7D,IAAM,EAAW,IAAI,IAAI,EAAO,CAChC,OAAO,IAAI,EAAmB,MAAM,OAAQ,GAAS,CAAC,EAAS,IAAI,EAAK,GAAK,CAAC,CAAC,CAMjF,OAAgB,CACd,OAAO,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"BelongsTo.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/BelongsTo.ts"],"sourcesContent":["/**\n * BelongsTo Relationship\n *\n * Represents an inverse one-to-one or many relationship\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { Relation } from './Relation';\n\nexport class BelongsTo<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The foreign key of the parent model\n */\n protected foreignKey: string;\n\n /**\n * The associated key on the parent model\n */\n protected ownerKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * Create a new belongs to relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n foreignKey: string,\n ownerKey: string,\n relationName: string\n ) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.ownerKey = ownerKey;\n this.relationName = relationName;\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n if (Relation['constraints']) {\n const foreignKeyValue = this.getForeignKeyValue();\n\n // Only add constraint if foreign key value exists\n if (foreignKeyValue !== null && foreignKeyValue !== undefined) {\n this.query.where(this.ownerKey, '=', foreignKeyValue);\n }\n }\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n const keys = this.getEagerModelKeys(models);\n this.query.whereIn(this.ownerKey, keys);\n }\n\n /**\n * Gather the keys from an array of related models\n */\n protected getEagerModelKeys(models: TParent[]): any[] {\n const keys: any[] = [];\n\n for (const model of models) {\n const value = model.getAttribute(this.foreignKey);\n\n if (value !== null && value !== undefined) {\n keys.push(value);\n }\n }\n\n return [...new Set(keys)];\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, null);\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<TRelated>, relation: string): TParent[] {\n const dictionary = this.buildDictionary(results);\n\n for (const model of models) {\n const key = model.getAttribute(this.foreignKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, dictionary[key]);\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's owner key\n */\n protected buildDictionary(results: EnsembleCollection<TRelated>): Record<any, TRelated> {\n const dictionary: Record<any, TRelated> = {};\n\n for (const result of results) {\n const key = result.getAttribute(this.ownerKey);\n\n if (key !== null && key !== undefined) {\n dictionary[key] = result;\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated | null> {\n const foreignKeyValue = this.getForeignKeyValue();\n\n if (!foreignKeyValue) {\n return null;\n }\n\n this.ensureConstraints();\n return this.query.first();\n }\n\n /**\n * Get the value of the model's foreign key\n */\n protected getForeignKeyValue(): any {\n return this.parent.getAttribute(this.foreignKey);\n }\n\n /**\n * Get the foreign key for the relationship\n */\n getForeignKeyName(): string {\n return this.foreignKey;\n }\n\n /**\n * Get the owner key for the relationship\n */\n getOwnerKeyName(): string {\n return this.ownerKey;\n }\n\n /**\n * Get the name of the relationship\n */\n getRelationName(): string {\n return this.relationName;\n }\n\n /**\n * Associate the model instance to the given parent\n */\n associate(model: TRelated | null): TParent {\n const ownerKey = model ? model.getAttribute(this.ownerKey) : null;\n\n this.parent.setAttribute(this.foreignKey, ownerKey);\n\n if (model) {\n this.parent.setRelation(this.relationName, model);\n } else {\n this.parent.unsetRelation(this.relationName);\n }\n\n return this.parent;\n }\n\n /**\n * Dissociate previously associated model from the given parent\n */\n dissociate(): TParent {\n this.parent.setAttribute(this.foreignKey, null);\n this.parent.setRelation(this.relationName, null);\n\n return this.parent;\n }\n\n /**\n * Execute the query as a \"select\" statement\n * Override base to return single model instead of array\n */\n // @ts-expect-error - BelongsTo returns single model, not array\n async get(): Promise<TRelated | null> {\n return this.getResults();\n }\n\n /**\n * Update the parent model on the relationship\n */\n async update(attributes: Record<string, any>): Promise<number> {\n return this.query.update(attributes);\n }\n\n /**\n * Get the default foreign key name for the relationship\n */\n protected getDefaultForeignKeyName(): string {\n return this.snake(this.relationName) + '_' + this.related.getKeyName();\n }\n\n /**\n * Convert a string to snake case\n */\n protected snake(value: string): string {\n return value\n .replace(/([A-Z])/g, '_$1')\n .toLowerCase()\n .replace(/^_/, '');\n }\n}\n"],"mappings":"gEASsC,CAEtC,IAAa,EAAb,cAAoF,CAA4B,CAI9G,WAKA,SAKA,aAKA,YACE,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,SAAW,EAChB,KAAK,aAAe,EACpB,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,GAAI,EAAS,YAAgB,CAC3B,IAAM,EAAkB,KAAK,oBAAoB,CAG7C,GAAoB,MACtB,KAAK,MAAM,MAAM,KAAK,SAAU,IAAK,EAAgB,EAQ3D,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,kBAAkB,EAAO,CAC3C,KAAK,MAAM,QAAQ,KAAK,SAAU,EAAK,CAMzC,kBAA4B,EAA0B,CACpD,IAAM,EAAc,EAAE,CAEtB,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAQ,EAAM,aAAa,KAAK,WAAW,CAE7C,GAAU,MACZ,EAAK,KAAK,EAAM,CAIpB,MAAO,CAAC,GAAG,IAAI,IAAI,EAAK,CAAC,CAM3B,aAAa,EAAmB,E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IAAM,KAAK,QAAQ,YAAY,CAMxE,MAAgB,EAAuB,CACrC,OAAO,EACJ,QAAQ,WAAY,MAAM,CAC1B,aAAa,CACb,QAAQ,KAAM,GAAG"}
1
+ {"version":3,"file":"BelongsTo.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/BelongsTo.ts"],"sourcesContent":["/**\n * BelongsTo Relationship\n *\n * Represents an inverse one-to-one or many relationship\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { Relation } from './Relation';\n\nexport class BelongsTo<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The foreign key of the parent model\n */\n protected foreignKey: string;\n\n /**\n * The associated key on the parent model\n */\n protected ownerKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * Create a new belongs to relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n foreignKey: string,\n ownerKey: string,\n relationName: string\n ) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.ownerKey = ownerKey;\n this.relationName = relationName;\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n if (Relation['constraints']) {\n const foreignKeyValue = this.getForeignKeyValue();\n\n // Only add constraint if foreign key value exists\n if (foreignKeyValue !== null && foreignKeyValue !== undefined) {\n this.query.where(this.ownerKey, '=', foreignKeyValue);\n }\n }\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n const keys = this.getEagerModelKeys(models);\n this.query.whereIn(this.ownerKey, keys);\n }\n\n /**\n * Gather the keys from an array of related models\n */\n protected getEagerModelKeys(models: TParent[]): any[] {\n const keys: any[] = [];\n\n for (const model of models) {\n const value = model.getAttribute(this.foreignKey);\n\n if (value !== null && value !== undefined) {\n keys.push(value);\n }\n }\n\n return [...new Set(keys)];\n }\n\n /**\n * Initialize the relation on a set of models\n */\n initRelation(models: TParent[], relation: string): TParent[] {\n for (const model of models) {\n model.setRelation(relation, null);\n }\n\n return models;\n }\n\n /**\n * Match the eagerly loaded results to their parents\n */\n match(models: TParent[], results: EnsembleCollection<TRelated>, relation: string): TParent[] {\n const dictionary = this.buildDictionary(results);\n\n for (const model of models) {\n const key = model.getAttribute(this.foreignKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, dictionary[key]);\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's owner key\n */\n protected buildDictionary(results: EnsembleCollection<TRelated>): Record<any, TRelated> {\n const dictionary: Record<any, TRelated> = {};\n\n for (const result of results) {\n const key = result.getAttribute(this.ownerKey);\n\n if (key !== null && key !== undefined) {\n dictionary[key] = result;\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated | null> {\n const foreignKeyValue = this.getForeignKeyValue();\n\n if (!foreignKeyValue) {\n return null;\n }\n\n this.ensureConstraints();\n return this.query.first();\n }\n\n /**\n * Get the value of the model's foreign key\n */\n protected getForeignKeyValue(): any {\n return this.parent.getAttribute(this.foreignKey);\n }\n\n /**\n * Get the foreign key for the relationship\n */\n getForeignKeyName(): string {\n return this.foreignKey;\n }\n\n /**\n * Get the owner key for the relationship\n */\n getOwnerKeyName(): string {\n return this.ownerKey;\n }\n\n /**\n * Get the name of the relationship\n */\n getRelationName(): string {\n return this.relationName;\n }\n\n /**\n * Associate the model instance to the given parent\n */\n associate(model: TRelated | null): TParent {\n const ownerKey = model ? model.getAttribute(this.ownerKey) : null;\n\n this.parent.setAttribute(this.foreignKey, ownerKey);\n\n if (model) {\n this.parent.setRelation(this.relationName, model);\n } else {\n this.parent.unsetRelation(this.relationName);\n }\n\n return this.parent;\n }\n\n /**\n * Dissociate previously associated model from the given parent\n */\n dissociate(): TParent {\n this.parent.setAttribute(this.foreignKey, null);\n this.parent.setRelation(this.relationName, null);\n\n return this.parent;\n }\n\n /**\n * Execute the query as a \"select\" statement\n * Override base to return single model instead of array\n */\n // @ts-expect-error - BelongsTo returns single model, not array\n async get(): Promise<TRelated | null> {\n return this.getResults();\n }\n\n /**\n * Update the parent model on the relationship\n */\n async update(attributes: Record<string, any>): Promise<number> {\n return this.query.update(attributes);\n }\n\n /**\n * Get the default foreign key name for the relationship\n */\n protected getDefaultForeignKeyName(): string {\n return this.snake(this.relationName) + '_' + this.related.getKeyName();\n }\n\n /**\n * Convert a string to snake case\n */\n protected snake(value: string): string {\n return value\n .replace(/([A-Z])/g, '_$1')\n .toLowerCase()\n .replace(/^_/, '');\n }\n}\n"],"mappings":"gEASsC,CAEtC,IAAa,EAAb,cAAoF,CAA4B,CAI9G,WAKA,SAKA,aAKA,YACE,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,SAAW,EAChB,KAAK,aAAe,EACpB,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,GAAI,EAAS,YAAgB,CAC3B,IAAM,EAAkB,KAAK,oBAAoB,CAG7C,GAAoB,MACtB,KAAK,MAAM,MAAM,KAAK,SAAU,IAAK,EAAgB,EAQ3D,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,kBAAkB,EAAO,CAC3C,KAAK,MAAM,QAAQ,KAAK,SAAU,EAAK,CAMzC,kBAA4B,EAA0B,CACpD,IAAM,EAAc,EAAE,CAEtB,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAQ,EAAM,aAAa,KAAK,WAAW,CAE7C,GAAU,MACZ,EAAK,KAAK,EAAM,CAIpB,MAAO,CAAC,GAAG,IAAI,IAAI,EAAK,CAAC,CAM3B,aAAa,EAAmB,EAA6B,CAC3D,IAAK,IAAM,KAAS,EAClB,EAAM,YAAY,EAAU,KAAK,CAGnC,OAAO,EAMT,MAAM,EAAmB,EAAuC,EAA6B,CAC3F,IA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"}
@@ -1 +1 @@
1
- const e=require(`../../../_virtual/_rolldown/runtime.cjs`),t=require(`./Relation.cjs`),n=require(`../EnsembleCollection.cjs`);var r,i=e.__esmMin((()=>{n.init_EnsembleCollection(),t.init_Relation(),r=class extends t.Relation{table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;relationName;pivotColumns=[];pivotWheres=[];pivotValues=[];usingTimestamps=!1;using;pivotCreatedAt;pivotUpdatedAt;accessor=`pivot`;constructor(e,t,n,r,i,a,o,s){super(e,t),this.table=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o,this.relationName=s||``,this.initializeRelation()}addConstraints(){this.performJoin(),t.Relation.constraints&&this.addWhereConstraints()}performJoin(e){e||=this.query,e.join(this.table,`${this.getQualifiedRelatedKeyName()}`,`=`,`${this.getQualifiedRelatedPivotKeyName()}`)}addWhereConstraints(){let e=this.parent.getAttribute(this.parentKey);e!=null&&this.query.where(this.getQualifiedForeignPivotKeyName(),`=`,e)}addEagerConstraints(e){let t=this.getKeys(e,this.parentKey);this.query.whereIn(this.getQualifiedForeignPivotKeyName(),t)}initRelation(e,t){for(let r of e)r.setRelation(t,new n.EnsembleCollection);return e}match(e,t,r){let i=this.buildDictionary(t);for(let t of e){let e=t.getAttribute(this.parentKey);e!=null&&i[e]&&t.setRelation(r,new n.EnsembleCollection(i[e]))}return e}buildDictionary(e){let t={};for(let n of e){let e=this.migratePivotAttributes(n)[this.foreignPivotKey];e!=null&&(t[e]||(t[e]=[]),t[e].push(n))}return t}async getResults(){return this.parent.getAttribute(this.parentKey)?this.get():[]}async get(){this.ensureConstraints();let e=await this.query.addSelect(...this.shouldSelect()).get();return this.hydratePivotRelation(e),e}shouldSelect(e=[`*`]){return e.length===1&&e[0]===`*`&&(e=[`${this.related.getTable()}.*`]),[...e,...this.aliasedPivotColumns()]}aliasedPivotColumns(){return[...[this.foreignPivotKey,this.relatedPivotKey],...this.pivotColumns].map(e=>`${this.table}.${e} as pivot_${e}`)}hydratePivotRelation(e){for(let t of e){let e=this.migratePivotAttributes(t);t.setRelation(this.accessor,e)}}migratePivotAttributes(e){let t={},n=e.attributes||{};for(let[r,i]of Object.entries(n))if(r.startsWith(`pivot_`)){let n=r.substring(6);t[n]=i,delete e.attributes[r]}return t}getQualifiedForeignPivotKeyName(){return`${this.table}.${this.foreignPivotKey}`}getQualifiedRelatedPivotKeyName(){return`${this.table}.${this.relatedPivotKey}`}getQualifiedParentKeyName(){return`${this.parent.getTable()}.${this.parentKey}`}getQualifiedRelatedKeyName(){return`${this.related.getTable()}.${this.relatedKey}`}withPivot(...e){return this.pivotColumns=[...this.pivotColumns,...e],this}withTimestamps(e,t){return this.usingTimestamps=!0,this.pivotCreatedAt=e||`created_at`,this.pivotUpdatedAt=t||`updated_at`,this.withPivot(this.pivotCreatedAt,this.pivotUpdatedAt)}wherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.pivotWheres.push({column:`${this.table}.${e}`,operator:t,value:n,boolean:`and`}),this.query.where(`${this.table}.${e}`,t,n)}wherePivotIn(e,t){return this.query.whereIn(`${this.table}.${e}`,t)}wherePivotNotIn(e,t){return this.query.whereNotIn(`${this.table}.${e}`,t)}wherePivotNull(e){return this.query.whereNull(`${this.table}.${e}`)}wherePivotNotNull(e){return this.query.whereNotNull(`${this.table}.${e}`)}orWherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.query.orWhere(`${this.table}.${e}`,t,n)}async attach(e,t={}){let n=this.formatAttachRecords(this.parseIds(e),t);n.length!==0&&await this.parent.getConnection().table(this.table).insert(n)}async detach(e){let t=this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey));if(e!==void 0){let n=this.parseIds(e);t=t.whereIn(this.relatedPivotKey,n)}return await t.delete()}async sync(e){let t={attached:[],detached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e)),i=n.filter(e=>!r.some(t=>t.id===e));return i.length>0&&(await this.detach(i),t.detached=i),t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async syncWithoutDetaching(e){let t={attached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e));return t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async toggle(e){let t={attached:[],detached:[]},n=this.parseIds(e),r=await this.getCurrentlyAttachedPivots(),i=n.filter(e=>r.includes(e)),a=n.filter(e=>!r.includes(e));return i.length>0&&(await this.detach(i),t.detached=i),a.length>0&&(await this.attach(a),t.attached=a),t}async updateExistingPivot(e,t){return this.usingTimestamps&&this.pivotUpdatedAt&&(t[this.pivotUpdatedAt]=new Date),await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).where(this.relatedPivotKey,`=`,e).update(t)}async getCurrentlyAttachedPivots(){return await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).pluck(this.relatedPivotKey)}async attachNew(e,t){let n=e.filter(e=>!t.includes(e.id));return n.length===0?[]:(await this.attach(n.map(e=>e.id),n[0]?.attributes||{}),n.map(e=>e.id))}async updateExisting(e,t){let n=[];for(let r of e)t.includes(r.id)&&Object.keys(r.attributes).length>0&&(await this.updateExistingPivot(r.id,r.attributes),n.push(r.id));return n}formatAttachRecords(e,t){let n=[],r=this.usingTimestamps;for(let i of e){let e={[this.foreignPivotKey]:this.parent.getAttribute(this.parentKey),[this.relatedPivotKey]:i,...t};if(r){let t=new Date;this.pivotCreatedAt&&(e[this.pivotCreatedAt]=t),this.pivotUpdatedAt&&(e[this.pivotUpdatedAt]=t)}n.push(e)}return n}formatRecordsList(e){return e.map(e=>{if(typeof e==`object`&&!Array.isArray(e)){let{id:t,...n}=e;return{id:t,attributes:n}}return{id:e,attributes:{}}})}parseIds(e){return e instanceof n.EnsembleCollection?e.modelKeys():Array.isArray(e)?e:typeof e==`object`&&e?Object.keys(e).map(t=>({id:isNaN(Number(t))?t:Number(t),...e[t]})):[e]}getPivotAccessor(){return this.accessor}as(e){return this.accessor=e,this}getTable(){return this.table}getForeignPivotKeyName(){return this.foreignPivotKey}getRelatedPivotKeyName(){return this.relatedPivotKey}getParentKeyName(){return this.parentKey}getRelatedKeyName(){return this.relatedKey}getRelationName(){return this.relationName}}}));i(),exports.BelongsToMany=r,Object.defineProperty(exports,`init_BelongsToMany`,{enumerable:!0,get:function(){return i}});
1
+ const e=require(`../../../_virtual/_rolldown/runtime.cjs`),t=require(`./Relation.cjs`),n=require(`../EnsembleCollection.cjs`);var r,i=e.__esmMin((()=>{n.init_EnsembleCollection(),t.init_Relation(),r=class extends t.Relation{table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;relationName;pivotColumns=[];pivotWheres=[];pivotValues=[];usingTimestamps=!1;using;pivotCreatedAt;pivotUpdatedAt;accessor=`pivot`;constructor(e,t,n,r,i,a,o,s){super(e,t),this.table=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o,this.relationName=s||``,this.initializeRelation()}addConstraints(){this.performJoin(),t.Relation.constraints&&this.addWhereConstraints()}performJoin(e){e||=this.query,e.join(this.table,`${this.getQualifiedRelatedKeyName()}`,`=`,`${this.getQualifiedRelatedPivotKeyName()}`)}addWhereConstraints(){let e=this.parent.getAttribute(this.parentKey);e!=null&&this.query.where(this.getQualifiedForeignPivotKeyName(),`=`,e)}addEagerConstraints(e){let t=this.getKeys(e,this.parentKey);this.query.whereIn(this.getQualifiedForeignPivotKeyName(),t)}initRelation(e,t){for(let r of e)r.setRelation(t,new n.EnsembleCollection);return e}match(e,t,r){let i=this.buildDictionary(t);for(let t of e){let e=t.getAttribute(this.parentKey);e!=null&&i[e]&&t.setRelation(r,new n.EnsembleCollection(i[e]))}return e}buildDictionary(e){let t={};for(let n of e){let e=this.migratePivotAttributes(n)[this.foreignPivotKey];e!=null&&(t[e]||(t[e]=[]),t[e].push(n))}return t}async getResults(){return this.parent.getAttribute(this.parentKey)?this.get():[]}async get(){this.ensureConstraints();let e=await this.query.addSelect(...this.shouldSelect()).get();return this.hydratePivotRelation(e),e}shouldSelect(e=[`*`]){return e.length===1&&e[0]===`*`&&(e=[`${this.related.getTable()}.*`]),[...e,...this.aliasedPivotColumns()]}aliasedPivotColumns(){return[this.foreignPivotKey,this.relatedPivotKey,...this.pivotColumns].map(e=>`${this.table}.${e} as pivot_${e}`)}hydratePivotRelation(e){for(let t of e){let e=this.migratePivotAttributes(t);t.setRelation(this.accessor,e)}}migratePivotAttributes(e){let t={},n=e.attributes||{};for(let[r,i]of Object.entries(n))if(r.startsWith(`pivot_`)){let n=r.substring(6);t[n]=i,delete e.attributes[r]}return t}getQualifiedForeignPivotKeyName(){return`${this.table}.${this.foreignPivotKey}`}getQualifiedRelatedPivotKeyName(){return`${this.table}.${this.relatedPivotKey}`}getQualifiedParentKeyName(){return`${this.parent.getTable()}.${this.parentKey}`}getQualifiedRelatedKeyName(){return`${this.related.getTable()}.${this.relatedKey}`}withPivot(...e){return this.pivotColumns=[...this.pivotColumns,...e],this}withTimestamps(e,t){return this.usingTimestamps=!0,this.pivotCreatedAt=e||`created_at`,this.pivotUpdatedAt=t||`updated_at`,this.withPivot(this.pivotCreatedAt,this.pivotUpdatedAt)}wherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.pivotWheres.push({column:`${this.table}.${e}`,operator:t,value:n,boolean:`and`}),this.query.where(`${this.table}.${e}`,t,n)}wherePivotIn(e,t){return this.query.whereIn(`${this.table}.${e}`,t)}wherePivotNotIn(e,t){return this.query.whereNotIn(`${this.table}.${e}`,t)}wherePivotNull(e){return this.query.whereNull(`${this.table}.${e}`)}wherePivotNotNull(e){return this.query.whereNotNull(`${this.table}.${e}`)}orWherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.query.orWhere(`${this.table}.${e}`,t,n)}async attach(e,t={}){let n=this.formatAttachRecords(this.parseIds(e),t);n.length!==0&&await this.parent.getConnection().table(this.table).insert(n)}async detach(e){let t=this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey));if(e!==void 0){let n=this.parseIds(e);t=t.whereIn(this.relatedPivotKey,n)}return await t.delete()}async sync(e){let t={attached:[],detached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e)),i=n.filter(e=>!r.some(t=>t.id===e));return i.length>0&&(await this.detach(i),t.detached=i),t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async syncWithoutDetaching(e){let t={attached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e));return t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async toggle(e){let t={attached:[],detached:[]},n=this.parseIds(e),r=await this.getCurrentlyAttachedPivots(),i=n.filter(e=>r.includes(e)),a=n.filter(e=>!r.includes(e));return i.length>0&&(await this.detach(i),t.detached=i),a.length>0&&(await this.attach(a),t.attached=a),t}async updateExistingPivot(e,t){return this.usingTimestamps&&this.pivotUpdatedAt&&(t[this.pivotUpdatedAt]=new Date),await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).where(this.relatedPivotKey,`=`,e).update(t)}async getCurrentlyAttachedPivots(){return await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).pluck(this.relatedPivotKey)}async attachNew(e,t){let n=e.filter(e=>!t.includes(e.id));return n.length===0?[]:(await this.attach(n.map(e=>e.id),n[0]?.attributes||{}),n.map(e=>e.id))}async updateExisting(e,t){let n=[];for(let r of e)t.includes(r.id)&&Object.keys(r.attributes).length>0&&(await this.updateExistingPivot(r.id,r.attributes),n.push(r.id));return n}formatAttachRecords(e,t){let n=[],r=this.usingTimestamps;for(let i of e){let e={[this.foreignPivotKey]:this.parent.getAttribute(this.parentKey),[this.relatedPivotKey]:i,...t};if(r){let t=new Date;this.pivotCreatedAt&&(e[this.pivotCreatedAt]=t),this.pivotUpdatedAt&&(e[this.pivotUpdatedAt]=t)}n.push(e)}return n}formatRecordsList(e){return e.map(e=>{if(typeof e==`object`&&!Array.isArray(e)){let{id:t,...n}=e;return{id:t,attributes:n}}return{id:e,attributes:{}}})}parseIds(e){return e instanceof n.EnsembleCollection?e.modelKeys():Array.isArray(e)?e:typeof e==`object`&&e?Object.keys(e).map(t=>({id:isNaN(Number(t))?t:Number(t),...e[t]})):[e]}getPivotAccessor(){return this.accessor}as(e){return this.accessor=e,this}getTable(){return this.table}getForeignPivotKeyName(){return this.foreignPivotKey}getRelatedPivotKeyName(){return this.relatedPivotKey}getParentKeyName(){return this.parentKey}getRelatedKeyName(){return this.relatedKey}getRelationName(){return this.relationName}}}));i(),exports.BelongsToMany=r,Object.defineProperty(exports,`init_BelongsToMany`,{enumerable:!0,get:function(){return i}});
@@ -1,2 +1,2 @@
1
- import{__esmMin as e}from"../../../_virtual/_rolldown/runtime.mjs";import{Relation as t,init_Relation as n}from"./Relation.mjs";import{EnsembleCollection as r,init_EnsembleCollection as i}from"../EnsembleCollection.mjs";var a,o=e((()=>{i(),n(),a=class extends t{table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;relationName;pivotColumns=[];pivotWheres=[];pivotValues=[];usingTimestamps=!1;using;pivotCreatedAt;pivotUpdatedAt;accessor=`pivot`;constructor(e,t,n,r,i,a,o,s){super(e,t),this.table=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o,this.relationName=s||``,this.initializeRelation()}addConstraints(){this.performJoin(),t.constraints&&this.addWhereConstraints()}performJoin(e){e||=this.query,e.join(this.table,`${this.getQualifiedRelatedKeyName()}`,`=`,`${this.getQualifiedRelatedPivotKeyName()}`)}addWhereConstraints(){let e=this.parent.getAttribute(this.parentKey);e!=null&&this.query.where(this.getQualifiedForeignPivotKeyName(),`=`,e)}addEagerConstraints(e){let t=this.getKeys(e,this.parentKey);this.query.whereIn(this.getQualifiedForeignPivotKeyName(),t)}initRelation(e,t){for(let n of e)n.setRelation(t,new r);return e}match(e,t,n){let i=this.buildDictionary(t);for(let t of e){let e=t.getAttribute(this.parentKey);e!=null&&i[e]&&t.setRelation(n,new r(i[e]))}return e}buildDictionary(e){let t={};for(let n of e){let e=this.migratePivotAttributes(n)[this.foreignPivotKey];e!=null&&(t[e]||(t[e]=[]),t[e].push(n))}return t}async getResults(){return this.parent.getAttribute(this.parentKey)?this.get():[]}async get(){this.ensureConstraints();let e=await this.query.addSelect(...this.shouldSelect()).get();return this.hydratePivotRelation(e),e}shouldSelect(e=[`*`]){return e.length===1&&e[0]===`*`&&(e=[`${this.related.getTable()}.*`]),[...e,...this.aliasedPivotColumns()]}aliasedPivotColumns(){return[...[this.foreignPivotKey,this.relatedPivotKey],...this.pivotColumns].map(e=>`${this.table}.${e} as pivot_${e}`)}hydratePivotRelation(e){for(let t of e){let e=this.migratePivotAttributes(t);t.setRelation(this.accessor,e)}}migratePivotAttributes(e){let t={},n=e.attributes||{};for(let[r,i]of Object.entries(n))if(r.startsWith(`pivot_`)){let n=r.substring(6);t[n]=i,delete e.attributes[r]}return t}getQualifiedForeignPivotKeyName(){return`${this.table}.${this.foreignPivotKey}`}getQualifiedRelatedPivotKeyName(){return`${this.table}.${this.relatedPivotKey}`}getQualifiedParentKeyName(){return`${this.parent.getTable()}.${this.parentKey}`}getQualifiedRelatedKeyName(){return`${this.related.getTable()}.${this.relatedKey}`}withPivot(...e){return this.pivotColumns=[...this.pivotColumns,...e],this}withTimestamps(e,t){return this.usingTimestamps=!0,this.pivotCreatedAt=e||`created_at`,this.pivotUpdatedAt=t||`updated_at`,this.withPivot(this.pivotCreatedAt,this.pivotUpdatedAt)}wherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.pivotWheres.push({column:`${this.table}.${e}`,operator:t,value:n,boolean:`and`}),this.query.where(`${this.table}.${e}`,t,n)}wherePivotIn(e,t){return this.query.whereIn(`${this.table}.${e}`,t)}wherePivotNotIn(e,t){return this.query.whereNotIn(`${this.table}.${e}`,t)}wherePivotNull(e){return this.query.whereNull(`${this.table}.${e}`)}wherePivotNotNull(e){return this.query.whereNotNull(`${this.table}.${e}`)}orWherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.query.orWhere(`${this.table}.${e}`,t,n)}async attach(e,t={}){let n=this.formatAttachRecords(this.parseIds(e),t);n.length!==0&&await this.parent.getConnection().table(this.table).insert(n)}async detach(e){let t=this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey));if(e!==void 0){let n=this.parseIds(e);t=t.whereIn(this.relatedPivotKey,n)}return await t.delete()}async sync(e){let t={attached:[],detached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e)),i=n.filter(e=>!r.some(t=>t.id===e));return i.length>0&&(await this.detach(i),t.detached=i),t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async syncWithoutDetaching(e){let t={attached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e));return t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async toggle(e){let t={attached:[],detached:[]},n=this.parseIds(e),r=await this.getCurrentlyAttachedPivots(),i=n.filter(e=>r.includes(e)),a=n.filter(e=>!r.includes(e));return i.length>0&&(await this.detach(i),t.detached=i),a.length>0&&(await this.attach(a),t.attached=a),t}async updateExistingPivot(e,t){return this.usingTimestamps&&this.pivotUpdatedAt&&(t[this.pivotUpdatedAt]=new Date),await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).where(this.relatedPivotKey,`=`,e).update(t)}async getCurrentlyAttachedPivots(){return await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).pluck(this.relatedPivotKey)}async attachNew(e,t){let n=e.filter(e=>!t.includes(e.id));return n.length===0?[]:(await this.attach(n.map(e=>e.id),n[0]?.attributes||{}),n.map(e=>e.id))}async updateExisting(e,t){let n=[];for(let r of e)t.includes(r.id)&&Object.keys(r.attributes).length>0&&(await this.updateExistingPivot(r.id,r.attributes),n.push(r.id));return n}formatAttachRecords(e,t){let n=[],r=this.usingTimestamps;for(let i of e){let e={[this.foreignPivotKey]:this.parent.getAttribute(this.parentKey),[this.relatedPivotKey]:i,...t};if(r){let t=new Date;this.pivotCreatedAt&&(e[this.pivotCreatedAt]=t),this.pivotUpdatedAt&&(e[this.pivotUpdatedAt]=t)}n.push(e)}return n}formatRecordsList(e){return e.map(e=>{if(typeof e==`object`&&!Array.isArray(e)){let{id:t,...n}=e;return{id:t,attributes:n}}return{id:e,attributes:{}}})}parseIds(e){return e instanceof r?e.modelKeys():Array.isArray(e)?e:typeof e==`object`&&e?Object.keys(e).map(t=>({id:isNaN(Number(t))?t:Number(t),...e[t]})):[e]}getPivotAccessor(){return this.accessor}as(e){return this.accessor=e,this}getTable(){return this.table}getForeignPivotKeyName(){return this.foreignPivotKey}getRelatedPivotKeyName(){return this.relatedPivotKey}getParentKeyName(){return this.parentKey}getRelatedKeyName(){return this.relatedKey}getRelationName(){return this.relationName}}}));o();export{a as BelongsToMany,o as init_BelongsToMany};
1
+ import{__esmMin as e}from"../../../_virtual/_rolldown/runtime.mjs";import{Relation as t,init_Relation as n}from"./Relation.mjs";import{EnsembleCollection as r,init_EnsembleCollection as i}from"../EnsembleCollection.mjs";var a,o=e((()=>{i(),n(),a=class extends t{table;foreignPivotKey;relatedPivotKey;parentKey;relatedKey;relationName;pivotColumns=[];pivotWheres=[];pivotValues=[];usingTimestamps=!1;using;pivotCreatedAt;pivotUpdatedAt;accessor=`pivot`;constructor(e,t,n,r,i,a,o,s){super(e,t),this.table=n,this.foreignPivotKey=r,this.relatedPivotKey=i,this.parentKey=a,this.relatedKey=o,this.relationName=s||``,this.initializeRelation()}addConstraints(){this.performJoin(),t.constraints&&this.addWhereConstraints()}performJoin(e){e||=this.query,e.join(this.table,`${this.getQualifiedRelatedKeyName()}`,`=`,`${this.getQualifiedRelatedPivotKeyName()}`)}addWhereConstraints(){let e=this.parent.getAttribute(this.parentKey);e!=null&&this.query.where(this.getQualifiedForeignPivotKeyName(),`=`,e)}addEagerConstraints(e){let t=this.getKeys(e,this.parentKey);this.query.whereIn(this.getQualifiedForeignPivotKeyName(),t)}initRelation(e,t){for(let n of e)n.setRelation(t,new r);return e}match(e,t,n){let i=this.buildDictionary(t);for(let t of e){let e=t.getAttribute(this.parentKey);e!=null&&i[e]&&t.setRelation(n,new r(i[e]))}return e}buildDictionary(e){let t={};for(let n of e){let e=this.migratePivotAttributes(n)[this.foreignPivotKey];e!=null&&(t[e]||(t[e]=[]),t[e].push(n))}return t}async getResults(){return this.parent.getAttribute(this.parentKey)?this.get():[]}async get(){this.ensureConstraints();let e=await this.query.addSelect(...this.shouldSelect()).get();return this.hydratePivotRelation(e),e}shouldSelect(e=[`*`]){return e.length===1&&e[0]===`*`&&(e=[`${this.related.getTable()}.*`]),[...e,...this.aliasedPivotColumns()]}aliasedPivotColumns(){return[this.foreignPivotKey,this.relatedPivotKey,...this.pivotColumns].map(e=>`${this.table}.${e} as pivot_${e}`)}hydratePivotRelation(e){for(let t of e){let e=this.migratePivotAttributes(t);t.setRelation(this.accessor,e)}}migratePivotAttributes(e){let t={},n=e.attributes||{};for(let[r,i]of Object.entries(n))if(r.startsWith(`pivot_`)){let n=r.substring(6);t[n]=i,delete e.attributes[r]}return t}getQualifiedForeignPivotKeyName(){return`${this.table}.${this.foreignPivotKey}`}getQualifiedRelatedPivotKeyName(){return`${this.table}.${this.relatedPivotKey}`}getQualifiedParentKeyName(){return`${this.parent.getTable()}.${this.parentKey}`}getQualifiedRelatedKeyName(){return`${this.related.getTable()}.${this.relatedKey}`}withPivot(...e){return this.pivotColumns=[...this.pivotColumns,...e],this}withTimestamps(e,t){return this.usingTimestamps=!0,this.pivotCreatedAt=e||`created_at`,this.pivotUpdatedAt=t||`updated_at`,this.withPivot(this.pivotCreatedAt,this.pivotUpdatedAt)}wherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.pivotWheres.push({column:`${this.table}.${e}`,operator:t,value:n,boolean:`and`}),this.query.where(`${this.table}.${e}`,t,n)}wherePivotIn(e,t){return this.query.whereIn(`${this.table}.${e}`,t)}wherePivotNotIn(e,t){return this.query.whereNotIn(`${this.table}.${e}`,t)}wherePivotNull(e){return this.query.whereNull(`${this.table}.${e}`)}wherePivotNotNull(e){return this.query.whereNotNull(`${this.table}.${e}`)}orWherePivot(e,t,n){return arguments.length===2&&(n=t,t=`=`),this.query.orWhere(`${this.table}.${e}`,t,n)}async attach(e,t={}){let n=this.formatAttachRecords(this.parseIds(e),t);n.length!==0&&await this.parent.getConnection().table(this.table).insert(n)}async detach(e){let t=this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey));if(e!==void 0){let n=this.parseIds(e);t=t.whereIn(this.relatedPivotKey,n)}return await t.delete()}async sync(e){let t={attached:[],detached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e)),i=n.filter(e=>!r.some(t=>t.id===e));return i.length>0&&(await this.detach(i),t.detached=i),t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async syncWithoutDetaching(e){let t={attached:[],updated:[]},n=await this.getCurrentlyAttachedPivots(),r=this.formatRecordsList(this.parseIds(e));return t.attached=await this.attachNew(r,n),t.updated=await this.updateExisting(r,n),t}async toggle(e){let t={attached:[],detached:[]},n=this.parseIds(e),r=await this.getCurrentlyAttachedPivots(),i=n.filter(e=>r.includes(e)),a=n.filter(e=>!r.includes(e));return i.length>0&&(await this.detach(i),t.detached=i),a.length>0&&(await this.attach(a),t.attached=a),t}async updateExistingPivot(e,t){return this.usingTimestamps&&this.pivotUpdatedAt&&(t[this.pivotUpdatedAt]=new Date),await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).where(this.relatedPivotKey,`=`,e).update(t)}async getCurrentlyAttachedPivots(){return await this.parent.getConnection().table(this.table).where(this.foreignPivotKey,`=`,this.parent.getAttribute(this.parentKey)).pluck(this.relatedPivotKey)}async attachNew(e,t){let n=e.filter(e=>!t.includes(e.id));return n.length===0?[]:(await this.attach(n.map(e=>e.id),n[0]?.attributes||{}),n.map(e=>e.id))}async updateExisting(e,t){let n=[];for(let r of e)t.includes(r.id)&&Object.keys(r.attributes).length>0&&(await this.updateExistingPivot(r.id,r.attributes),n.push(r.id));return n}formatAttachRecords(e,t){let n=[],r=this.usingTimestamps;for(let i of e){let e={[this.foreignPivotKey]:this.parent.getAttribute(this.parentKey),[this.relatedPivotKey]:i,...t};if(r){let t=new Date;this.pivotCreatedAt&&(e[this.pivotCreatedAt]=t),this.pivotUpdatedAt&&(e[this.pivotUpdatedAt]=t)}n.push(e)}return n}formatRecordsList(e){return e.map(e=>{if(typeof e==`object`&&!Array.isArray(e)){let{id:t,...n}=e;return{id:t,attributes:n}}return{id:e,attributes:{}}})}parseIds(e){return e instanceof r?e.modelKeys():Array.isArray(e)?e:typeof e==`object`&&e?Object.keys(e).map(t=>({id:isNaN(Number(t))?t:Number(t),...e[t]})):[e]}getPivotAccessor(){return this.accessor}as(e){return this.accessor=e,this}getTable(){return this.table}getForeignPivotKeyName(){return this.foreignPivotKey}getRelatedPivotKeyName(){return this.relatedPivotKey}getParentKeyName(){return this.parentKey}getRelatedKeyName(){return this.relatedKey}getRelationName(){return this.relationName}}}));o();export{a as BelongsToMany,o as init_BelongsToMany};
2
2
  //# sourceMappingURL=BelongsToMany.mjs.map