@orchestr-sh/orchestr 1.11.0 → 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 (340) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/CODE_OF_CONDUCT.md +43 -0
  3. package/CONTRIBUTING.md +274 -0
  4. package/dist/Cache/CacheManager.cjs +1 -1
  5. package/dist/Cache/CacheManager.mjs +1 -1
  6. package/dist/Cache/CacheManager.mjs.map +1 -1
  7. package/dist/Cache/Events/CacheFlushed.cjs +1 -1
  8. package/dist/Cache/Events/CacheFlushed.mjs +1 -1
  9. package/dist/Cache/Events/CacheFlushed.mjs.map +1 -1
  10. package/dist/Cache/Events/CacheHit.cjs +1 -1
  11. package/dist/Cache/Events/CacheHit.mjs +1 -1
  12. package/dist/Cache/Events/CacheHit.mjs.map +1 -1
  13. package/dist/Cache/Events/CacheMissed.cjs +1 -1
  14. package/dist/Cache/Events/CacheMissed.mjs +1 -1
  15. package/dist/Cache/Events/CacheMissed.mjs.map +1 -1
  16. package/dist/Cache/Events/KeyForgotten.cjs +1 -1
  17. package/dist/Cache/Events/KeyForgotten.mjs +1 -1
  18. package/dist/Cache/Events/KeyForgotten.mjs.map +1 -1
  19. package/dist/Cache/Events/KeyWritten.cjs +1 -1
  20. package/dist/Cache/Events/KeyWritten.mjs +1 -1
  21. package/dist/Cache/Events/KeyWritten.mjs.map +1 -1
  22. package/dist/Cache/Locks/CacheLock.cjs +1 -1
  23. package/dist/Cache/Locks/CacheLock.mjs +1 -1
  24. package/dist/Cache/Locks/CacheLock.mjs.map +1 -1
  25. package/dist/Cache/Locks/Lock.cjs +1 -1
  26. package/dist/Cache/Locks/Lock.mjs +1 -1
  27. package/dist/Cache/Locks/Lock.mjs.map +1 -1
  28. package/dist/Cache/Repository.cjs +1 -1
  29. package/dist/Cache/Repository.mjs +1 -1
  30. package/dist/Cache/Repository.mjs.map +1 -1
  31. package/dist/Cache/Stores/ArrayStore.cjs +1 -1
  32. package/dist/Cache/Stores/ArrayStore.mjs +1 -1
  33. package/dist/Cache/Stores/ArrayStore.mjs.map +1 -1
  34. package/dist/Cache/Stores/DatabaseStore.cjs +1 -1
  35. package/dist/Cache/Stores/DatabaseStore.mjs +1 -1
  36. package/dist/Cache/Stores/DatabaseStore.mjs.map +1 -1
  37. package/dist/Cache/Stores/FileStore.cjs +1 -1
  38. package/dist/Cache/Stores/FileStore.mjs +1 -1
  39. package/dist/Cache/Stores/FileStore.mjs.map +1 -1
  40. package/dist/Cache/Tags/TagSet.cjs +1 -1
  41. package/dist/Cache/Tags/TagSet.mjs +1 -1
  42. package/dist/Cache/Tags/TagSet.mjs.map +1 -1
  43. package/dist/Cache/Tags/TaggedCache.cjs +1 -1
  44. package/dist/Cache/Tags/TaggedCache.mjs +1 -1
  45. package/dist/Cache/Tags/TaggedCache.mjs.map +1 -1
  46. package/dist/Console/Commands/CacheClearCommand.cjs +1 -1
  47. package/dist/Console/Commands/CacheClearCommand.mjs +1 -1
  48. package/dist/Console/Commands/CacheClearCommand.mjs.map +1 -1
  49. package/dist/Console/Commands/CacheForgetCommand.cjs +1 -1
  50. package/dist/Console/Commands/CacheForgetCommand.mjs +1 -1
  51. package/dist/Console/Commands/CacheForgetCommand.mjs.map +1 -1
  52. package/dist/Console/Commands/CacheTableCommand.cjs +1 -1
  53. package/dist/Console/Commands/CacheTableCommand.mjs +1 -1
  54. package/dist/Console/Commands/CacheTableCommand.mjs.map +1 -1
  55. package/dist/Console/Commands/DeployCommand.mjs.map +1 -1
  56. package/dist/Console/Commands/DeployEnvCommand.mjs.map +1 -1
  57. package/dist/Console/Commands/DeployInitCommand.mjs.map +1 -1
  58. package/dist/Console/Commands/DeployProvisionCommand.mjs.map +1 -1
  59. package/dist/Console/Commands/DeployRollbackCommand.mjs.map +1 -1
  60. package/dist/Console/Commands/DeployServerCommand.mjs.map +1 -1
  61. package/dist/Console/Commands/DeployStatusCommand.mjs.map +1 -1
  62. package/dist/Console/Commands/EventCacheCommand.cjs +1 -1
  63. package/dist/Console/Commands/EventCacheCommand.mjs +1 -1
  64. package/dist/Console/Commands/EventCacheCommand.mjs.map +1 -1
  65. package/dist/Console/Commands/EventClearCommand.cjs +1 -1
  66. package/dist/Console/Commands/EventClearCommand.mjs +1 -1
  67. package/dist/Console/Commands/EventClearCommand.mjs.map +1 -1
  68. package/dist/Console/Commands/EventListCommand.cjs +1 -1
  69. package/dist/Console/Commands/EventListCommand.mjs +1 -1
  70. package/dist/Console/Commands/EventListCommand.mjs.map +1 -1
  71. package/dist/Console/Commands/MakeControllerCommand.cjs +1 -1
  72. package/dist/Console/Commands/MakeControllerCommand.mjs +1 -1
  73. package/dist/Console/Commands/MakeControllerCommand.mjs.map +1 -1
  74. package/dist/Console/Commands/MakeEventCommand.cjs +1 -1
  75. package/dist/Console/Commands/MakeEventCommand.mjs +1 -1
  76. package/dist/Console/Commands/MakeEventCommand.mjs.map +1 -1
  77. package/dist/Console/Commands/MakeJobCommand.cjs +1 -1
  78. package/dist/Console/Commands/MakeJobCommand.mjs +1 -1
  79. package/dist/Console/Commands/MakeJobCommand.mjs.map +1 -1
  80. package/dist/Console/Commands/MakeListenerCommand.cjs +1 -1
  81. package/dist/Console/Commands/MakeListenerCommand.mjs +1 -1
  82. package/dist/Console/Commands/MakeListenerCommand.mjs.map +1 -1
  83. package/dist/Console/Commands/MakeMigrationCommand.cjs +1 -1
  84. package/dist/Console/Commands/MakeMigrationCommand.mjs +1 -1
  85. package/dist/Console/Commands/MakeMigrationCommand.mjs.map +1 -1
  86. package/dist/Console/Commands/MakeSeederCommand.cjs +1 -1
  87. package/dist/Console/Commands/MakeSeederCommand.mjs +1 -1
  88. package/dist/Console/Commands/MakeSeederCommand.mjs.map +1 -1
  89. package/dist/Console/Commands/MakeViewCommand.cjs +1 -1
  90. package/dist/Console/Commands/MakeViewCommand.mjs +1 -1
  91. package/dist/Console/Commands/MakeViewCommand.mjs.map +1 -1
  92. package/dist/Console/Commands/MigrateCommand.cjs +1 -1
  93. package/dist/Console/Commands/MigrateCommand.mjs +1 -1
  94. package/dist/Console/Commands/MigrateCommand.mjs.map +1 -1
  95. package/dist/Console/Commands/MigrateFreshCommand.cjs +1 -1
  96. package/dist/Console/Commands/MigrateFreshCommand.mjs +1 -1
  97. package/dist/Console/Commands/MigrateFreshCommand.mjs.map +1 -1
  98. package/dist/Console/Commands/MigrateRefreshCommand.cjs +1 -1
  99. package/dist/Console/Commands/MigrateRefreshCommand.mjs +1 -1
  100. package/dist/Console/Commands/MigrateRefreshCommand.mjs.map +1 -1
  101. package/dist/Console/Commands/MigrateResetCommand.cjs +1 -1
  102. package/dist/Console/Commands/MigrateResetCommand.mjs +1 -1
  103. package/dist/Console/Commands/MigrateResetCommand.mjs.map +1 -1
  104. package/dist/Console/Commands/MigrateRollbackCommand.cjs +1 -1
  105. package/dist/Console/Commands/MigrateRollbackCommand.mjs +1 -1
  106. package/dist/Console/Commands/MigrateRollbackCommand.mjs.map +1 -1
  107. package/dist/Console/Commands/MigrateStatusCommand.cjs +1 -1
  108. package/dist/Console/Commands/MigrateStatusCommand.mjs +1 -1
  109. package/dist/Console/Commands/MigrateStatusCommand.mjs.map +1 -1
  110. package/dist/Console/Commands/QueueBatchesTableCommand.cjs +1 -1
  111. package/dist/Console/Commands/QueueBatchesTableCommand.mjs +1 -1
  112. package/dist/Console/Commands/QueueBatchesTableCommand.mjs.map +1 -1
  113. package/dist/Console/Commands/QueueClearCommand.cjs +1 -1
  114. package/dist/Console/Commands/QueueClearCommand.mjs +1 -1
  115. package/dist/Console/Commands/QueueClearCommand.mjs.map +1 -1
  116. package/dist/Console/Commands/QueueFailedCommand.cjs +1 -1
  117. package/dist/Console/Commands/QueueFailedCommand.mjs +1 -1
  118. package/dist/Console/Commands/QueueFailedCommand.mjs.map +1 -1
  119. package/dist/Console/Commands/QueueFailedTableCommand.cjs +1 -1
  120. package/dist/Console/Commands/QueueFailedTableCommand.mjs +1 -1
  121. package/dist/Console/Commands/QueueFailedTableCommand.mjs.map +1 -1
  122. package/dist/Console/Commands/QueueFlushCommand.cjs +1 -1
  123. package/dist/Console/Commands/QueueFlushCommand.mjs +1 -1
  124. package/dist/Console/Commands/QueueFlushCommand.mjs.map +1 -1
  125. package/dist/Console/Commands/QueueForgetCommand.cjs +1 -1
  126. package/dist/Console/Commands/QueueForgetCommand.mjs +1 -1
  127. package/dist/Console/Commands/QueueForgetCommand.mjs.map +1 -1
  128. package/dist/Console/Commands/QueueMonitorCommand.cjs +1 -1
  129. package/dist/Console/Commands/QueueMonitorCommand.mjs +1 -1
  130. package/dist/Console/Commands/QueueMonitorCommand.mjs.map +1 -1
  131. package/dist/Console/Commands/QueuePruneBatchesCommand.cjs +1 -1
  132. package/dist/Console/Commands/QueuePruneBatchesCommand.mjs +1 -1
  133. package/dist/Console/Commands/QueuePruneBatchesCommand.mjs.map +1 -1
  134. package/dist/Console/Commands/QueuePruneFailedCommand.cjs +1 -1
  135. package/dist/Console/Commands/QueuePruneFailedCommand.mjs +1 -1
  136. package/dist/Console/Commands/QueuePruneFailedCommand.mjs.map +1 -1
  137. package/dist/Console/Commands/QueueRestartCommand.cjs +1 -1
  138. package/dist/Console/Commands/QueueRestartCommand.mjs +1 -1
  139. package/dist/Console/Commands/QueueRestartCommand.mjs.map +1 -1
  140. package/dist/Console/Commands/QueueRetryCommand.cjs +1 -1
  141. package/dist/Console/Commands/QueueRetryCommand.mjs +1 -1
  142. package/dist/Console/Commands/QueueRetryCommand.mjs.map +1 -1
  143. package/dist/Console/Commands/QueueTableCommand.cjs +1 -1
  144. package/dist/Console/Commands/QueueTableCommand.mjs +1 -1
  145. package/dist/Console/Commands/QueueTableCommand.mjs.map +1 -1
  146. package/dist/Console/Commands/QueueWorkCommand.cjs +1 -1
  147. package/dist/Console/Commands/QueueWorkCommand.mjs +1 -1
  148. package/dist/Console/Commands/QueueWorkCommand.mjs.map +1 -1
  149. package/dist/Console/Commands/SeedCommand.cjs +1 -1
  150. package/dist/Console/Commands/SeedCommand.mjs +1 -1
  151. package/dist/Console/Commands/SeedCommand.mjs.map +1 -1
  152. package/dist/Console/ConsoleKernel.cjs +1 -1
  153. package/dist/Console/ConsoleKernel.mjs +1 -1
  154. package/dist/Console/ConsoleKernel.mjs.map +1 -1
  155. package/dist/Console/orchestr.cjs +2 -0
  156. package/dist/Console/orchestr.d.cts +1 -0
  157. package/dist/Console/orchestr.d.mts +1 -0
  158. package/dist/Console/orchestr.mjs +3 -0
  159. package/dist/Console/orchestr.mjs.map +1 -0
  160. package/dist/Container/Container.mjs.map +1 -1
  161. package/dist/Database/Adapters/DrizzleAdapter.cjs +1 -1
  162. package/dist/Database/Adapters/DrizzleAdapter.mjs +1 -1
  163. package/dist/Database/Adapters/DrizzleAdapter.mjs.map +1 -1
  164. package/dist/Database/Connection.cjs +1 -1
  165. package/dist/Database/Connection.mjs +1 -1
  166. package/dist/Database/Connection.mjs.map +1 -1
  167. package/dist/Database/DatabaseManager.cjs +1 -1
  168. package/dist/Database/DatabaseManager.mjs +1 -1
  169. package/dist/Database/DatabaseManager.mjs.map +1 -1
  170. package/dist/Database/Ensemble/Ensemble.mjs.map +1 -1
  171. package/dist/Database/Ensemble/EnsembleBuilder.mjs.map +1 -1
  172. package/dist/Database/Ensemble/EnsembleCollection.cjs +1 -1
  173. package/dist/Database/Ensemble/EnsembleCollection.mjs +1 -1
  174. package/dist/Database/Ensemble/EnsembleCollection.mjs.map +1 -1
  175. package/dist/Database/Ensemble/Relations/BelongsTo.mjs.map +1 -1
  176. package/dist/Database/Ensemble/Relations/BelongsToMany.cjs +1 -1
  177. package/dist/Database/Ensemble/Relations/BelongsToMany.mjs +1 -1
  178. package/dist/Database/Ensemble/Relations/BelongsToMany.mjs.map +1 -1
  179. package/dist/Database/Ensemble/Relations/HasMany.mjs.map +1 -1
  180. package/dist/Database/Ensemble/Relations/MorphTo.mjs.map +1 -1
  181. package/dist/Database/Ensemble/Relations/MorphToMany.mjs.map +1 -1
  182. package/dist/Database/Migrations/Blueprint.cjs +1 -1
  183. package/dist/Database/Migrations/Blueprint.mjs +1 -1
  184. package/dist/Database/Migrations/Blueprint.mjs.map +1 -1
  185. package/dist/Database/Migrations/MigrationCreator.cjs +1 -1
  186. package/dist/Database/Migrations/MigrationCreator.mjs +1 -1
  187. package/dist/Database/Migrations/MigrationCreator.mjs.map +1 -1
  188. package/dist/Database/Migrations/MigrationRepository.cjs +1 -1
  189. package/dist/Database/Migrations/MigrationRepository.mjs +1 -1
  190. package/dist/Database/Migrations/MigrationRepository.mjs.map +1 -1
  191. package/dist/Database/Migrations/Migrator.cjs +1 -1
  192. package/dist/Database/Migrations/Migrator.mjs +1 -1
  193. package/dist/Database/Migrations/Migrator.mjs.map +1 -1
  194. package/dist/Database/Migrations/SchemaBuilder.cjs +1 -1
  195. package/dist/Database/Migrations/SchemaBuilder.mjs +1 -1
  196. package/dist/Database/Migrations/SchemaBuilder.mjs.map +1 -1
  197. package/dist/Database/Query/Builder.cjs +1 -1
  198. package/dist/Database/Query/Builder.mjs +1 -1
  199. package/dist/Database/Query/Builder.mjs.map +1 -1
  200. package/dist/Database/Query/Expression.cjs +1 -1
  201. package/dist/Database/Query/Expression.mjs +1 -1
  202. package/dist/Database/Query/Expression.mjs.map +1 -1
  203. package/dist/Database/Seeders/SeederRunner.cjs +1 -1
  204. package/dist/Database/Seeders/SeederRunner.mjs +1 -1
  205. package/dist/Database/Seeders/SeederRunner.mjs.map +1 -1
  206. package/dist/Deploy/Deployer.cjs +1 -1
  207. package/dist/Deploy/Deployer.mjs +1 -1
  208. package/dist/Deploy/Deployer.mjs.map +1 -1
  209. package/dist/Deploy/ProjectConfig.mjs.map +1 -1
  210. package/dist/Deploy/Provisioner.cjs +1 -1
  211. package/dist/Deploy/Provisioner.mjs +1 -1
  212. package/dist/Deploy/Provisioner.mjs.map +1 -1
  213. package/dist/Deploy/SSHConnection.mjs.map +1 -1
  214. package/dist/Deploy/SymphonyClient.cjs +1 -1
  215. package/dist/Deploy/SymphonyClient.mjs +1 -1
  216. package/dist/Deploy/SymphonyClient.mjs.map +1 -1
  217. package/dist/Deploy/TarBuilder.mjs.map +1 -1
  218. package/dist/Deploy/prompt.mjs.map +1 -1
  219. package/dist/Events/Dispatcher.cjs +1 -1
  220. package/dist/Events/Dispatcher.d.cts +1 -1
  221. package/dist/Events/Dispatcher.d.mts +1 -1
  222. package/dist/Events/Dispatcher.mjs +1 -1
  223. package/dist/Events/Dispatcher.mjs.map +1 -1
  224. package/dist/Events/EventServiceProvider.cjs +1 -1
  225. package/dist/Events/EventServiceProvider.d.cts +1 -1
  226. package/dist/Events/EventServiceProvider.d.mts +1 -1
  227. package/dist/Events/EventServiceProvider.mjs.map +1 -1
  228. package/dist/Events/index.cjs +1 -0
  229. package/dist/Events/index.d.cts +7 -0
  230. package/dist/Events/index.d.mts +7 -0
  231. package/dist/Events/index.mjs +1 -0
  232. package/dist/Facades/Bus.mjs.map +1 -1
  233. package/dist/Facades/Cache.mjs.map +1 -1
  234. package/dist/Facades/Config.mjs.map +1 -1
  235. package/dist/Facades/DB.mjs.map +1 -1
  236. package/dist/Facades/Event.d.cts +1 -1
  237. package/dist/Facades/Event.d.mts +1 -1
  238. package/dist/Facades/Event.mjs.map +1 -1
  239. package/dist/Facades/Queue.mjs.map +1 -1
  240. package/dist/Facades/Route.d.cts +1 -1
  241. package/dist/Facades/Route.d.mts +1 -1
  242. package/dist/Facades/Route.mjs.map +1 -1
  243. package/dist/Facades/View.mjs.map +1 -1
  244. package/dist/Facades/index.cjs +1 -0
  245. package/dist/Facades/index.d.cts +9 -0
  246. package/dist/Facades/index.d.mts +9 -0
  247. package/dist/Facades/index.mjs +1 -0
  248. package/dist/Foundation/Application.mjs.map +1 -1
  249. package/dist/Foundation/Config/ConfigServiceProvider.d.cts +1 -1
  250. package/dist/Foundation/Config/ConfigServiceProvider.d.mts +1 -1
  251. package/dist/Foundation/Http/FormRequest.d.cts +1 -1
  252. package/dist/Foundation/Http/FormRequest.d.mts +1 -1
  253. package/dist/Foundation/Http/FormRequest.mjs.map +1 -1
  254. package/dist/Foundation/Http/Rules/AnyOfRule.mjs.map +1 -1
  255. package/dist/Foundation/Http/Rules/ImageFileRule.mjs.map +1 -1
  256. package/dist/Foundation/Http/Validator.mjs.map +1 -1
  257. package/dist/Queue/Batching/Batch.cjs +1 -1
  258. package/dist/Queue/Batching/Batch.mjs +1 -1
  259. package/dist/Queue/Batching/Batch.mjs.map +1 -1
  260. package/dist/Queue/Batching/PendingBatch.cjs +1 -1
  261. package/dist/Queue/Batching/PendingBatch.mjs +1 -1
  262. package/dist/Queue/Batching/PendingBatch.mjs.map +1 -1
  263. package/dist/Queue/Concerns/Dispatchable.mjs.map +1 -1
  264. package/dist/Queue/Drivers/DatabaseDriver.cjs +1 -1
  265. package/dist/Queue/Drivers/DatabaseDriver.mjs +1 -1
  266. package/dist/Queue/Drivers/DatabaseDriver.mjs.map +1 -1
  267. package/dist/Queue/Drivers/NullDriver.cjs +1 -1
  268. package/dist/Queue/Drivers/NullDriver.mjs +1 -1
  269. package/dist/Queue/Drivers/NullDriver.mjs.map +1 -1
  270. package/dist/Queue/Drivers/SyncDriver.cjs +1 -1
  271. package/dist/Queue/Drivers/SyncDriver.mjs +1 -1
  272. package/dist/Queue/Drivers/SyncDriver.mjs.map +1 -1
  273. package/dist/Queue/Events/JobExceptionOccurred.cjs +1 -1
  274. package/dist/Queue/Events/JobExceptionOccurred.mjs +1 -1
  275. package/dist/Queue/Events/JobExceptionOccurred.mjs.map +1 -1
  276. package/dist/Queue/Events/JobFailed.cjs +1 -1
  277. package/dist/Queue/Events/JobFailed.mjs +1 -1
  278. package/dist/Queue/Events/JobFailed.mjs.map +1 -1
  279. package/dist/Queue/Events/JobProcessed.cjs +1 -1
  280. package/dist/Queue/Events/JobProcessed.mjs +1 -1
  281. package/dist/Queue/Events/JobProcessed.mjs.map +1 -1
  282. package/dist/Queue/Events/JobProcessing.cjs +1 -1
  283. package/dist/Queue/Events/JobProcessing.mjs +1 -1
  284. package/dist/Queue/Events/JobProcessing.mjs.map +1 -1
  285. package/dist/Queue/Events/JobQueued.cjs +1 -1
  286. package/dist/Queue/Events/JobQueued.mjs +1 -1
  287. package/dist/Queue/Events/JobQueued.mjs.map +1 -1
  288. package/dist/Queue/Events/JobRetryRequested.cjs +1 -1
  289. package/dist/Queue/Events/JobRetryRequested.mjs +1 -1
  290. package/dist/Queue/Events/JobRetryRequested.mjs.map +1 -1
  291. package/dist/Queue/Events/WorkerStopping.cjs +1 -1
  292. package/dist/Queue/Events/WorkerStopping.mjs +1 -1
  293. package/dist/Queue/Events/WorkerStopping.mjs.map +1 -1
  294. package/dist/Queue/Failed/DatabaseFailedJobProvider.cjs +1 -1
  295. package/dist/Queue/Failed/DatabaseFailedJobProvider.mjs +1 -1
  296. package/dist/Queue/Failed/DatabaseFailedJobProvider.mjs.map +1 -1
  297. package/dist/Queue/Middleware/RateLimited.cjs +1 -1
  298. package/dist/Queue/Middleware/RateLimited.mjs +1 -1
  299. package/dist/Queue/Middleware/RateLimited.mjs.map +1 -1
  300. package/dist/Queue/Middleware/ThrottlesExceptions.cjs +1 -1
  301. package/dist/Queue/Middleware/ThrottlesExceptions.mjs +1 -1
  302. package/dist/Queue/Middleware/ThrottlesExceptions.mjs.map +1 -1
  303. package/dist/Queue/Middleware/WithoutOverlapping.cjs +1 -1
  304. package/dist/Queue/Middleware/WithoutOverlapping.mjs +1 -1
  305. package/dist/Queue/Middleware/WithoutOverlapping.mjs.map +1 -1
  306. package/dist/Queue/PendingChain.cjs +1 -1
  307. package/dist/Queue/PendingChain.mjs +1 -1
  308. package/dist/Queue/PendingChain.mjs.map +1 -1
  309. package/dist/Queue/PendingDispatch.cjs +1 -1
  310. package/dist/Queue/PendingDispatch.mjs +1 -1
  311. package/dist/Queue/PendingDispatch.mjs.map +1 -1
  312. package/dist/Queue/QueueManager.cjs +1 -1
  313. package/dist/Queue/QueueManager.mjs +1 -1
  314. package/dist/Queue/QueueManager.mjs.map +1 -1
  315. package/dist/Queue/QueueServiceProvider.mjs.map +1 -1
  316. package/dist/Queue/Workers/Worker.cjs +1 -1
  317. package/dist/Queue/Workers/Worker.mjs +1 -1
  318. package/dist/Queue/Workers/Worker.mjs.map +1 -1
  319. package/dist/Routing/Request.mjs.map +1 -1
  320. package/dist/Routing/Response.mjs.map +1 -1
  321. package/dist/Routing/Route.d.cts +1 -1
  322. package/dist/Routing/Route.d.mts +1 -1
  323. package/dist/Routing/Router.d.cts +1 -1
  324. package/dist/Routing/Router.d.mts +1 -1
  325. package/dist/Support/EventDiscovery.cjs +1 -1
  326. package/dist/Support/EventDiscovery.mjs +1 -1
  327. package/dist/Support/EventDiscovery.mjs.map +1 -1
  328. package/dist/Support/Testing/Fakes/EventFake.cjs +1 -1
  329. package/dist/Support/Testing/Fakes/EventFake.d.cts +1 -1
  330. package/dist/Support/Testing/Fakes/EventFake.d.mts +1 -1
  331. package/dist/Support/Testing/Fakes/EventFake.mjs +1 -1
  332. package/dist/Support/Testing/Fakes/EventFake.mjs.map +1 -1
  333. package/dist/Support/helpers.mjs.map +1 -1
  334. package/dist/View/Engines/TemplateEngine.mjs.map +1 -1
  335. package/dist/index.d.cts +19 -19
  336. package/dist/index.d.mts +19 -19
  337. package/docs/events-typescript-usage.md +126 -0
  338. package/docs/future-improvements.md +49 -0
  339. package/docs/validation.md +201 -0
  340. package/package.json +65 -31
@@ -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,KAAK,KAAK,UAAU,CAAC,OAAS,GACvC,MAAM,KAAK,mBAAmB,EAAO,CAGhC,EAMT,MAAM,OAA2B,CAE/B,OADgB,MAAM,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,MAXC,GAAiB,OAAS,EAC1B,EAAiB,cAAc,CAG5B,GAED,EAAiB,iBAAiB,YAAY,CAAC,UAAY,GAE1D,CAGG,EAMT,UAAU,GAAG,EAAyB,CAKpC,OAJI,KAAK,SAAS,SAAW,GAAK,KAAK,SAAS,KAAO,MACrD,KAAK,SAAW,EAAE,EAEpB,KAAK,SAAS,KAAK,GAAG,EAAQ,CACvB,KAMT,KAAK,EAA2E,CAC9E,GAAI,OAAO,GAAc,SACvB,KAAK,UAAU,OAAmB,WACzB,MAAM,QAAQ,EAAU,CACjC,IAAK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AO,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,K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ototypeOf(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,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,IAAM,EAAS,IAAI,IAAI,EAAK,CAC5B,OAAO,IAAI,EAAmB,KAAK,OAAQ,GAAS,EAAO,IAAI,EAAK,QAAQ,CAAC,CAAC,CAAC,CAMjF,MAAM,KAAK,EAA6C,CAGtD,OAAO,KAMT,KAAK,EAA4D,CAK/D,OAJI,OAAO,GAAkB,WACpB,MAAM,KAAK,EAAc,CAG3B,MAAM,KAAM,GAAS,EAAK,QAAQ,GAAK,EAAc,CAM9D,SAAS,EAAsD,CAC7D,OAAO,KAAK,KAAK,EAAc,GAAK,IAAA,GAMtC,QAAQ,EAAc,EAAsC,CAC1D,IAAM,EAAW,IAAI,IAAI,EAAO,CAChC,OAAO,IAAI,EAAmB,MAAM,OAAQ,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
+ {"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,Q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AS,CAAC,EAAO,IAAI,EAAK,QAAQ,CAAC,CAAC,CAAC,CAMlF,KAAK,EAAoC,CACvC,IAAM,EAAS,IAAI,IAAI,EAAK,CAC5B,OAAO,IAAI,EAAmB,KAAK,OAAQ,GAAS,EAAO,IAAI,EAAK,QAAQ,CAAC,CAAC,CAAC,CAMjF,MAAM,KAAK,EAA6C,CAGtD,OAAO,KAMT,KAAK,EAA4D,CAK/D,OAJI,OAAO,GAAkB,WACpB,MAAM,KAAK,EAAc,CAG3B,MAAM,KAAM,GAAS,EAAK,QAAQ,GAAK,EAAc,CAM9D,SAAS,EAAsD,CAC7D,OAAO,KAAK,KAAK,EAAc,GAAK,IAAA,GAMtC,QAAQ,EAAc,EAAsC,CAC1D,IAAM,EAAW,IAAI,IAAI,EAAO,CAChC,OAAO,IAAI,EAAmB,MAAM,OAAQ,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,S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ACxB,OAAO,KAAK,aAMd,UAAU,EAAiC,CACzC,IAAM,EAAW,EAAQ,EAAM,aAAa,KAAK,SAAS,CAAG,KAU7D,OARA,KAAK,OAAO,aAAa,KAAK,WAAY,EAAS,CAE/C,EACF,KAAK,OAAO,YAAY,KAAK,aAAc,EAAM,CAEjD,KAAK,OAAO,cAAc,KAAK,aAAa,CAGvC,KAAK,OAMd,YAAsB,CAIpB,OAHA,KAAK,OAAO,aAAa,KAAK,WAAY,KAAK,CAC/C,KAAK,OAAO,YAAY,KAAK,aAAc,KAAK,CAEzC,KAAK,OAQd,MAAM,KAAgC,CACpC,OAAO,KAAK,YAAY,CAM1B,MAAM,OAAO,EAAkD,CAC7D,OAAO,KAAK,MAAM,OAAO,EAAW,CAMtC,0BAA6C,CAC3C,OAAO,KAAK,MAAM,KAAK,aAAa,CAAG,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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,KAAK,WAAY,EAAS,CAE/C,EACF,KAAK,OAAO,YAAY,KAAK,aAAc,EAAM,CAEjD,KAAK,OAAO,cAAc,KAAK,aAAa,CAGvC,KAAK,OAMd,YAAsB,CAIpB,OAHA,KAAK,OAAO,aAAa,KAAK,WAAY,KAAK,CAC/C,KAAK,OAAO,YAAY,KAAK,aAAc,KAAK,CAEzC,KAAK,OAQd,MAAM,KAAgC,CACpC,OAAO,KAAK,YAAY,CAM1B,MAAM,OAAO,EAAkD,CAC7D,OAAO,KAAK,MAAM,OAAO,EAAW,CAMtC,0BAA6C,CAC3C,OAAO,KAAK,MAAM,KAAK,aAAa,CAAG,IAAM,KAAK,QAAQ,YAAY,CAMxE,MAAgB,EAAuB,CACrC,OAAO,EACJ,QAAQ,WAAY,MAAM,CAC1B,aAAa,CACb,QAAQ,KAAM,GAAG"}
@@ -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
@@ -1 +1 @@
1
- {"version":3,"file":"BelongsToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/BelongsToMany.ts"],"sourcesContent":["/**\n * BelongsToMany Relationship\n *\n * Represents a many-to-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 BelongsToMany<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The intermediate table for the relation\n */\n protected table: string;\n\n /**\n * The foreign key of the parent model\n */\n protected foreignPivotKey: string;\n\n /**\n * The associated key of the relation\n */\n protected relatedPivotKey: string;\n\n /**\n * The parent key of the relationship\n */\n protected parentKey: string;\n\n /**\n * The related key of the relationship\n */\n protected relatedKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * The pivot table columns to retrieve\n */\n protected pivotColumns: string[] = [];\n\n /**\n * Any pivot table restrictions\n */\n protected pivotWheres: Array<{ column: string; operator?: string; value?: any; boolean: string }> = [];\n\n /**\n * The pivot table values to attach\n */\n protected pivotValues: Record<string, any>[] = [];\n\n /**\n * Whether we are using timestamps on the pivot table\n */\n protected usingTimestamps: boolean = false;\n\n /**\n * The custom pivot table model\n */\n protected using?: any;\n\n /**\n * The name of the \"created at\" column\n */\n protected pivotCreatedAt?: string;\n\n /**\n * The name of the \"updated at\" column\n */\n protected pivotUpdatedAt?: string;\n\n /**\n * The name of the accessor to use for the pivot relationship\n */\n protected accessor: string = 'pivot';\n\n /**\n * Create a new belongs to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string\n ) {\n super(query, parent);\n this.table = table;\n this.foreignPivotKey = foreignPivotKey;\n this.relatedPivotKey = relatedPivotKey;\n this.parentKey = parentKey;\n this.relatedKey = relatedKey;\n this.relationName = relationName || '';\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n this.performJoin();\n\n if (Relation['constraints']) {\n this.addWhereConstraints();\n }\n }\n\n /**\n * Set the join clause for the relation query\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table on the related key\n query.join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`);\n }\n\n /**\n * Set the where clause for the relation query\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\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.getKeys(models, this.parentKey);\n this.query.whereIn(this.getQualifiedForeignPivotKeyName(), 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, new EnsembleCollection<TRelated>());\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.parentKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign 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 pivotAttributes = this.migratePivotAttributes(result);\n const key = pivotAttributes[this.foreignPivotKey];\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return [];\n }\n\n return this.get();\n }\n\n /**\n * Execute the query and get the models\n */\n async get(): Promise<TRelated[]> {\n this.ensureConstraints();\n\n const builder = this.query.addSelect(...this.shouldSelect());\n\n const models = await builder.get();\n\n this.hydratePivotRelation(models);\n\n return models;\n }\n\n /**\n * Get the select columns for the relation query\n */\n protected shouldSelect(columns: string[] = ['*']): string[] {\n if (columns.length === 1 && columns[0] === '*') {\n columns = [`${this.related.getTable()}.*`];\n }\n\n return [...columns, ...this.aliasedPivotColumns()];\n }\n\n /**\n * Get the pivot columns for the relation\n */\n protected aliasedPivotColumns(): string[] {\n const defaults = [this.foreignPivotKey, this.relatedPivotKey];\n const columns = [...defaults, ...this.pivotColumns];\n\n return columns.map((column) => {\n return `${this.table}.${column} as pivot_${column}`;\n });\n }\n\n /**\n * Hydrate the pivot relationship on the models\n */\n protected hydratePivotRelation(models: TRelated[]): void {\n for (const model of models) {\n const pivot = this.migratePivotAttributes(model);\n model.setRelation(this.accessor, pivot);\n }\n }\n\n /**\n * Migrate the pivot attributes from the model to a pivot model\n */\n protected migratePivotAttributes(model: TRelated): Record<string, any> {\n const values: Record<string, any> = {};\n\n // Extract all pivot_* attributes\n const attributes = (model as any).attributes || {};\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) {\n const pivotKey = key.substring(6); // Remove 'pivot_' prefix\n values[pivotKey] = value;\n delete (model as any).attributes[key];\n }\n }\n\n return values;\n }\n\n /**\n * Get the fully qualified foreign key for the relation\n */\n protected getQualifiedForeignPivotKeyName(): string {\n return `${this.table}.${this.foreignPivotKey}`;\n }\n\n /**\n * Get the fully qualified \"related key\" for the relation\n */\n protected getQualifiedRelatedPivotKeyName(): string {\n return `${this.table}.${this.relatedPivotKey}`;\n }\n\n /**\n * Get the fully qualified parent key name\n */\n protected getQualifiedParentKeyName(): string {\n return `${this.parent.getTable()}.${this.parentKey}`;\n }\n\n /**\n * Get the fully qualified related key name\n */\n protected getQualifiedRelatedKeyName(): string {\n return `${this.related.getTable()}.${this.relatedKey}`;\n }\n\n /**\n * Specify the pivot table columns to retrieve\n */\n withPivot(...columns: string[]): this {\n this.pivotColumns = [...this.pivotColumns, ...columns];\n\n return this;\n }\n\n /**\n * Indicate that the pivot table has timestamps\n */\n withTimestamps(createdAt?: string, updatedAt?: string): this {\n this.usingTimestamps = true;\n\n this.pivotCreatedAt = createdAt || 'created_at';\n this.pivotUpdatedAt = updatedAt || 'updated_at';\n\n return this.withPivot(this.pivotCreatedAt, this.pivotUpdatedAt);\n }\n\n /**\n * Set a where clause for the pivot table\n */\n wherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n this.pivotWheres.push({\n column: `${this.table}.${column}`,\n operator,\n value,\n boolean: 'and',\n });\n\n return this.query.where(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Set a \"where in\" clause for the pivot table\n */\n wherePivotIn(column: string, values: any[]): this {\n return this.query.whereIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where not in\" clause for the pivot table\n */\n wherePivotNotIn(column: string, values: any[]): this {\n return this.query.whereNotIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where null\" clause for the pivot table\n */\n wherePivotNull(column: string): this {\n return this.query.whereNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set a \"where not null\" clause for the pivot table\n */\n wherePivotNotNull(column: string): this {\n return this.query.whereNotNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set an \"or where\" clause for the pivot table\n */\n orWherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n return this.query.orWhere(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Attach models to the parent\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}): Promise<void> {\n const records = this.formatAttachRecords(this.parseIds(ids), attributes);\n\n if (records.length === 0) {\n return;\n }\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent\n */\n async detach(ids?: any | any[]): Promise<number> {\n const connection = this.parent.getConnection();\n let query = connection.table(this.table).where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey));\n\n if (ids !== undefined) {\n const parsedIds = this.parseIds(ids);\n query = query.whereIn(this.relatedPivotKey, parsedIds);\n }\n\n return await query.delete();\n }\n\n /**\n * Sync the intermediate tables with a list of IDs\n */\n async sync(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n detached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n const detach = current.filter((id) => !records.some((record) => record.id === id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Sync without detaching\n */\n async syncWithoutDetaching(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Toggle models from the parent\n */\n async toggle(ids: any | any[]): Promise<{\n attached: any[];\n detached: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n };\n\n const parsedIds = this.parseIds(ids);\n const current = await this.getCurrentlyAttachedPivots();\n\n const detach = parsedIds.filter((id) => current.includes(id));\n const attach = parsedIds.filter((id) => !current.includes(id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n if (attach.length > 0) {\n await this.attach(attach);\n changes.attached = attach;\n }\n\n return changes;\n }\n\n /**\n * Update an existing pivot record on the table\n */\n async updateExistingPivot(id: any, attributes: Record<string, any>): Promise<number> {\n if (this.usingTimestamps && this.pivotUpdatedAt) {\n attributes[this.pivotUpdatedAt] = new Date();\n }\n\n const connection = this.parent.getConnection();\n return await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .where(this.relatedPivotKey, '=', id)\n .update(attributes);\n }\n\n /**\n * Get the currently attached pivot IDs\n */\n protected async getCurrentlyAttachedPivots(): Promise<any[]> {\n const connection = this.parent.getConnection();\n const results = await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .pluck(this.relatedPivotKey);\n\n return results;\n }\n\n /**\n * Attach new records\n */\n protected async attachNew(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const newRecords = records.filter((record) => !current.includes(record.id));\n\n if (newRecords.length === 0) {\n return [];\n }\n\n await this.attach(\n newRecords.map((r) => r.id),\n newRecords[0]?.attributes || {}\n );\n\n return newRecords.map((r) => r.id);\n }\n\n /**\n * Update existing records\n */\n protected async updateExisting(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const updated: any[] = [];\n\n for (const record of records) {\n if (current.includes(record.id) && Object.keys(record.attributes).length > 0) {\n await this.updateExistingPivot(record.id, record.attributes);\n updated.push(record.id);\n }\n }\n\n return updated;\n }\n\n /**\n * Format the records for attaching\n */\n protected formatAttachRecords(ids: any[], attributes: Record<string, any>): Record<string, any>[] {\n const records: Record<string, any>[] = [];\n const hasTimestamps = this.usingTimestamps;\n\n for (const id of ids) {\n const record: Record<string, any> = {\n [this.foreignPivotKey]: this.parent.getAttribute(this.parentKey),\n [this.relatedPivotKey]: id,\n ...attributes,\n };\n\n if (hasTimestamps) {\n const now = new Date();\n if (this.pivotCreatedAt) {\n record[this.pivotCreatedAt] = now;\n }\n if (this.pivotUpdatedAt) {\n record[this.pivotUpdatedAt] = now;\n }\n }\n\n records.push(record);\n }\n\n return records;\n }\n\n /**\n * Format the sync records\n */\n protected formatRecordsList(ids: any[]): Array<{ id: any; attributes: Record<string, any> }> {\n return ids.map((id) => {\n if (typeof id === 'object' && !Array.isArray(id)) {\n const { id: recordId, ...attributes } = id;\n return { id: recordId, attributes };\n }\n return { id, attributes: {} };\n });\n }\n\n /**\n * Parse the IDs from the given value\n */\n protected parseIds(value: any): any[] {\n if (value instanceof EnsembleCollection) {\n return value.modelKeys();\n }\n\n if (Array.isArray(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null) {\n // Handle {id: attributes} format\n return Object.keys(value).map((key) => {\n const id = isNaN(Number(key)) ? key : Number(key);\n return { id, ...value[key] };\n });\n }\n\n return [value];\n }\n\n /**\n * Get the name of the pivot accessor\n */\n getPivotAccessor(): string {\n return this.accessor;\n }\n\n /**\n * Set the name of the pivot accessor\n */\n as(accessor: string): this {\n this.accessor = accessor;\n return this;\n }\n\n /**\n * Get the pivot table name\n */\n getTable(): string {\n return this.table;\n }\n\n /**\n * Get the foreign pivot key name\n */\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey;\n }\n\n /**\n * Get the related pivot key name\n */\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey;\n }\n\n /**\n * Get the parent key name\n */\n getParentKeyName(): string {\n return this.parentKey;\n }\n\n /**\n * Get the related key name\n */\n getRelatedKeyName(): string {\n return this.relatedKey;\n }\n\n /**\n * Get the relationship name\n */\n getRelationName(): string {\n return this.relationName;\n }\n}\n"],"mappings":"+OAQ4E,IACtC,CAEzB,EAAb,cAAwF,CAA4B,CAIlH,MAKA,gBAKA,gBAKA,UAKA,WAKA,aAKA,aAAmC,EAAE,CAKrC,YAAoG,EAAE,CAKtG,YAA+C,EAAE,CAKjD,gBAAqC,GAKrC,MAKA,eAKA,eAKA,SAA6B,QAK7B,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,MAAQ,EACb,KAAK,gBAAkB,EACvB,KAAK,gBAAkB,EACvB,KAAK,UAAY,EACjB,KAAK,WAAa,EAClB,KAAK,aAAe,GAAgB,GACpC,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,KAAK,aAAa,CAEd,EAAS,aACX,KAAK,qBAAqB,CAO9B,YAAsB,EAAyC,CAC7D,IAAiB,KAAK,MAGtB,EAAM,KAAK,KAAK,MAAO,GAAG,KAAK,4BAA4B,GAAI,IAAK,GAAG,KAAK,iCAAiC,GAAG,CAMlH,qBAAsC,CACpC,IAAM,EAAiB,KAAK,OAAO,aAAa,KAAK,UAAU,CAG3D,GAAmB,MACrB,KAAK,MAAM,MAAM,KAAK,iCAAiC,CAAE,IAAK,EAAe,CAOjF,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,QAAQ,EAAQ,KAAK,UAAU,CACjD,KAAK,MAAM,QAAQ,KAAK,iCAAiC,CAAE,EAAK,CAMlE,aAAa,EAAmB,EAA6B,CAC3D,IAAK,IAAM,KAAS,EAClB,EAAM,YAAY,EAAU,IAAI,EAA+B,CAGjE,OAAO,EAMT,MAAM,EAAmB,EAAuC,EAA6B,CAC3F,IAAM,EAAa,KAAK,gBAAgB,EAAQ,CAEhD,IAAK,IAAM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CAMhB,kBAA2B,CACzB,OAAO,KAAK,SAMd,GAAG,EAAwB,CAEzB,MADA,MAAK,SAAW,EACT,KAMT,UAAmB,CACjB,OAAO,KAAK,MAMd,wBAAiC,CAC/B,OAAO,KAAK,gBAMd,wBAAiC,CAC/B,OAAO,KAAK,gBAMd,kBAA2B,CACzB,OAAO,KAAK,UAMd,mBAA4B,CAC1B,OAAO,KAAK,WAMd,iBAA0B,CACxB,OAAO,KAAK"}
1
+ {"version":3,"file":"BelongsToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/BelongsToMany.ts"],"sourcesContent":["/**\n * BelongsToMany Relationship\n *\n * Represents a many-to-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 BelongsToMany<TRelated extends Ensemble, TParent extends Ensemble> extends Relation<TRelated, TParent> {\n /**\n * The intermediate table for the relation\n */\n protected table: string;\n\n /**\n * The foreign key of the parent model\n */\n protected foreignPivotKey: string;\n\n /**\n * The associated key of the relation\n */\n protected relatedPivotKey: string;\n\n /**\n * The parent key of the relationship\n */\n protected parentKey: string;\n\n /**\n * The related key of the relationship\n */\n protected relatedKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * The pivot table columns to retrieve\n */\n protected pivotColumns: string[] = [];\n\n /**\n * Any pivot table restrictions\n */\n protected pivotWheres: Array<{ column: string; operator?: string; value?: any; boolean: string }> = [];\n\n /**\n * The pivot table values to attach\n */\n protected pivotValues: Record<string, any>[] = [];\n\n /**\n * Whether we are using timestamps on the pivot table\n */\n protected usingTimestamps: boolean = false;\n\n /**\n * The custom pivot table model\n */\n protected using?: any;\n\n /**\n * The name of the \"created at\" column\n */\n protected pivotCreatedAt?: string;\n\n /**\n * The name of the \"updated at\" column\n */\n protected pivotUpdatedAt?: string;\n\n /**\n * The name of the accessor to use for the pivot relationship\n */\n protected accessor: string = 'pivot';\n\n /**\n * Create a new belongs to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string\n ) {\n super(query, parent);\n this.table = table;\n this.foreignPivotKey = foreignPivotKey;\n this.relatedPivotKey = relatedPivotKey;\n this.parentKey = parentKey;\n this.relatedKey = relatedKey;\n this.relationName = relationName || '';\n this.initializeRelation();\n }\n\n /**\n * Set the base constraints on the relation query\n */\n addConstraints(): void {\n this.performJoin();\n\n if (Relation['constraints']) {\n this.addWhereConstraints();\n }\n }\n\n /**\n * Set the join clause for the relation query\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table on the related key\n query.join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`);\n }\n\n /**\n * Set the where clause for the relation query\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\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.getKeys(models, this.parentKey);\n this.query.whereIn(this.getQualifiedForeignPivotKeyName(), 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, new EnsembleCollection<TRelated>());\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.parentKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign 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 pivotAttributes = this.migratePivotAttributes(result);\n const key = pivotAttributes[this.foreignPivotKey];\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return [];\n }\n\n return this.get();\n }\n\n /**\n * Execute the query and get the models\n */\n async get(): Promise<TRelated[]> {\n this.ensureConstraints();\n\n const builder = this.query.addSelect(...this.shouldSelect());\n\n const models = await builder.get();\n\n this.hydratePivotRelation(models);\n\n return models;\n }\n\n /**\n * Get the select columns for the relation query\n */\n protected shouldSelect(columns: string[] = ['*']): string[] {\n if (columns.length === 1 && columns[0] === '*') {\n columns = [`${this.related.getTable()}.*`];\n }\n\n return [...columns, ...this.aliasedPivotColumns()];\n }\n\n /**\n * Get the pivot columns for the relation\n */\n protected aliasedPivotColumns(): string[] {\n const defaults = [this.foreignPivotKey, this.relatedPivotKey];\n const columns = [...defaults, ...this.pivotColumns];\n\n return columns.map((column) => {\n return `${this.table}.${column} as pivot_${column}`;\n });\n }\n\n /**\n * Hydrate the pivot relationship on the models\n */\n protected hydratePivotRelation(models: TRelated[]): void {\n for (const model of models) {\n const pivot = this.migratePivotAttributes(model);\n model.setRelation(this.accessor, pivot);\n }\n }\n\n /**\n * Migrate the pivot attributes from the model to a pivot model\n */\n protected migratePivotAttributes(model: TRelated): Record<string, any> {\n const values: Record<string, any> = {};\n\n // Extract all pivot_* attributes\n const attributes = (model as any).attributes || {};\n for (const [key, value] of Object.entries(attributes)) {\n if (key.startsWith('pivot_')) {\n const pivotKey = key.substring(6); // Remove 'pivot_' prefix\n values[pivotKey] = value;\n delete (model as any).attributes[key];\n }\n }\n\n return values;\n }\n\n /**\n * Get the fully qualified foreign key for the relation\n */\n protected getQualifiedForeignPivotKeyName(): string {\n return `${this.table}.${this.foreignPivotKey}`;\n }\n\n /**\n * Get the fully qualified \"related key\" for the relation\n */\n protected getQualifiedRelatedPivotKeyName(): string {\n return `${this.table}.${this.relatedPivotKey}`;\n }\n\n /**\n * Get the fully qualified parent key name\n */\n protected getQualifiedParentKeyName(): string {\n return `${this.parent.getTable()}.${this.parentKey}`;\n }\n\n /**\n * Get the fully qualified related key name\n */\n protected getQualifiedRelatedKeyName(): string {\n return `${this.related.getTable()}.${this.relatedKey}`;\n }\n\n /**\n * Specify the pivot table columns to retrieve\n */\n withPivot(...columns: string[]): this {\n this.pivotColumns = [...this.pivotColumns, ...columns];\n\n return this;\n }\n\n /**\n * Indicate that the pivot table has timestamps\n */\n withTimestamps(createdAt?: string, updatedAt?: string): this {\n this.usingTimestamps = true;\n\n this.pivotCreatedAt = createdAt || 'created_at';\n this.pivotUpdatedAt = updatedAt || 'updated_at';\n\n return this.withPivot(this.pivotCreatedAt, this.pivotUpdatedAt);\n }\n\n /**\n * Set a where clause for the pivot table\n */\n wherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n this.pivotWheres.push({\n column: `${this.table}.${column}`,\n operator,\n value,\n boolean: 'and',\n });\n\n return this.query.where(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Set a \"where in\" clause for the pivot table\n */\n wherePivotIn(column: string, values: any[]): this {\n return this.query.whereIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where not in\" clause for the pivot table\n */\n wherePivotNotIn(column: string, values: any[]): this {\n return this.query.whereNotIn(`${this.table}.${column}`, values) as any;\n }\n\n /**\n * Set a \"where null\" clause for the pivot table\n */\n wherePivotNull(column: string): this {\n return this.query.whereNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set a \"where not null\" clause for the pivot table\n */\n wherePivotNotNull(column: string): this {\n return this.query.whereNotNull(`${this.table}.${column}`) as any;\n }\n\n /**\n * Set an \"or where\" clause for the pivot table\n */\n orWherePivot(column: string, operator?: any, value?: any): this {\n if (arguments.length === 2) {\n value = operator;\n operator = '=';\n }\n\n return this.query.orWhere(`${this.table}.${column}`, operator, value) as any;\n }\n\n /**\n * Attach models to the parent\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}): Promise<void> {\n const records = this.formatAttachRecords(this.parseIds(ids), attributes);\n\n if (records.length === 0) {\n return;\n }\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent\n */\n async detach(ids?: any | any[]): Promise<number> {\n const connection = this.parent.getConnection();\n let query = connection.table(this.table).where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey));\n\n if (ids !== undefined) {\n const parsedIds = this.parseIds(ids);\n query = query.whereIn(this.relatedPivotKey, parsedIds);\n }\n\n return await query.delete();\n }\n\n /**\n * Sync the intermediate tables with a list of IDs\n */\n async sync(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n detached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n const detach = current.filter((id) => !records.some((record) => record.id === id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Sync without detaching\n */\n async syncWithoutDetaching(ids: any | any[] | Record<number | string, Record<string, any>>): Promise<{\n attached: any[];\n updated: any[];\n }> {\n const changes = {\n attached: [] as any[],\n updated: [] as any[],\n };\n\n const current = await this.getCurrentlyAttachedPivots();\n const records = this.formatRecordsList(this.parseIds(ids));\n\n changes.attached = await this.attachNew(records, current);\n changes.updated = await this.updateExisting(records, current);\n\n return changes;\n }\n\n /**\n * Toggle models from the parent\n */\n async toggle(ids: any | any[]): Promise<{\n attached: any[];\n detached: any[];\n }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n };\n\n const parsedIds = this.parseIds(ids);\n const current = await this.getCurrentlyAttachedPivots();\n\n const detach = parsedIds.filter((id) => current.includes(id));\n const attach = parsedIds.filter((id) => !current.includes(id));\n\n if (detach.length > 0) {\n await this.detach(detach);\n changes.detached = detach;\n }\n\n if (attach.length > 0) {\n await this.attach(attach);\n changes.attached = attach;\n }\n\n return changes;\n }\n\n /**\n * Update an existing pivot record on the table\n */\n async updateExistingPivot(id: any, attributes: Record<string, any>): Promise<number> {\n if (this.usingTimestamps && this.pivotUpdatedAt) {\n attributes[this.pivotUpdatedAt] = new Date();\n }\n\n const connection = this.parent.getConnection();\n return await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .where(this.relatedPivotKey, '=', id)\n .update(attributes);\n }\n\n /**\n * Get the currently attached pivot IDs\n */\n protected async getCurrentlyAttachedPivots(): Promise<any[]> {\n const connection = this.parent.getConnection();\n const results = await connection\n .table(this.table)\n .where(this.foreignPivotKey, '=', this.parent.getAttribute(this.parentKey))\n .pluck(this.relatedPivotKey);\n\n return results;\n }\n\n /**\n * Attach new records\n */\n protected async attachNew(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const newRecords = records.filter((record) => !current.includes(record.id));\n\n if (newRecords.length === 0) {\n return [];\n }\n\n await this.attach(\n newRecords.map((r) => r.id),\n newRecords[0]?.attributes || {}\n );\n\n return newRecords.map((r) => r.id);\n }\n\n /**\n * Update existing records\n */\n protected async updateExisting(\n records: Array<{ id: any; attributes: Record<string, any> }>,\n current: any[]\n ): Promise<any[]> {\n const updated: any[] = [];\n\n for (const record of records) {\n if (current.includes(record.id) && Object.keys(record.attributes).length > 0) {\n await this.updateExistingPivot(record.id, record.attributes);\n updated.push(record.id);\n }\n }\n\n return updated;\n }\n\n /**\n * Format the records for attaching\n */\n protected formatAttachRecords(ids: any[], attributes: Record<string, any>): Record<string, any>[] {\n const records: Record<string, any>[] = [];\n const hasTimestamps = this.usingTimestamps;\n\n for (const id of ids) {\n const record: Record<string, any> = {\n [this.foreignPivotKey]: this.parent.getAttribute(this.parentKey),\n [this.relatedPivotKey]: id,\n ...attributes,\n };\n\n if (hasTimestamps) {\n const now = new Date();\n if (this.pivotCreatedAt) {\n record[this.pivotCreatedAt] = now;\n }\n if (this.pivotUpdatedAt) {\n record[this.pivotUpdatedAt] = now;\n }\n }\n\n records.push(record);\n }\n\n return records;\n }\n\n /**\n * Format the sync records\n */\n protected formatRecordsList(ids: any[]): Array<{ id: any; attributes: Record<string, any> }> {\n return ids.map((id) => {\n if (typeof id === 'object' && !Array.isArray(id)) {\n const { id: recordId, ...attributes } = id;\n return { id: recordId, attributes };\n }\n return { id, attributes: {} };\n });\n }\n\n /**\n * Parse the IDs from the given value\n */\n protected parseIds(value: any): any[] {\n if (value instanceof EnsembleCollection) {\n return value.modelKeys();\n }\n\n if (Array.isArray(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null) {\n // Handle {id: attributes} format\n return Object.keys(value).map((key) => {\n const id = isNaN(Number(key)) ? key : Number(key);\n return { id, ...value[key] };\n });\n }\n\n return [value];\n }\n\n /**\n * Get the name of the pivot accessor\n */\n getPivotAccessor(): string {\n return this.accessor;\n }\n\n /**\n * Set the name of the pivot accessor\n */\n as(accessor: string): this {\n this.accessor = accessor;\n return this;\n }\n\n /**\n * Get the pivot table name\n */\n getTable(): string {\n return this.table;\n }\n\n /**\n * Get the foreign pivot key name\n */\n getForeignPivotKeyName(): string {\n return this.foreignPivotKey;\n }\n\n /**\n * Get the related pivot key name\n */\n getRelatedPivotKeyName(): string {\n return this.relatedPivotKey;\n }\n\n /**\n * Get the parent key name\n */\n getParentKeyName(): string {\n return this.parentKey;\n }\n\n /**\n * Get the related key name\n */\n getRelatedKeyName(): string {\n return this.relatedKey;\n }\n\n /**\n * Get the relationship name\n */\n getRelationName(): string {\n return this.relationName;\n }\n}\n"],"mappings":"+OAQ4E,IACtC,CAEzB,EAAb,cAAwF,CAA4B,CAIlH,MAKA,gBAKA,gBAKA,UAKA,WAKA,aAKA,aAAmC,EAAE,CAKrC,YAAoG,EAAE,CAKtG,YAA+C,EAAE,CAKjD,gBAAqC,GAKrC,MAKA,eAKA,eAKA,SAA6B,QAK7B,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,MAAQ,EACb,KAAK,gBAAkB,EACvB,KAAK,gBAAkB,EACvB,KAAK,UAAY,EACjB,KAAK,WAAa,EAClB,KAAK,aAAe,GAAgB,GACpC,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,KAAK,aAAa,CAEd,EAAS,aACX,KAAK,qBAAqB,CAO9B,YAAsB,EAAyC,CAC7D,IAAiB,KAAK,MAGtB,EAAM,KAAK,KAAK,MAAO,GAAG,KAAK,4BAA4B,GAAI,IAAK,GAAG,KAAK,iCAAiC,GAAG,CAMlH,qBAAsC,CACpC,IAAM,EAAiB,KAAK,OAAO,aAAa,KAAK,UAAU,CAG3D,GAAmB,MACrB,KAAK,MAAM,MAAM,KAAK,iCAAiC,CAAE,IAAK,EAAe,CAOjF,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,QAAQ,EAAQ,KAAK,UAAU,CACjD,KAAK,MAAM,QAAQ,KAAK,iCAAiC,CAAE,EAAK,CAMlE,aAAa,EAAmB,EAA6B,CAC3D,IAAK,IAAM,KAAS,EAClB,EAAM,YAAY,EAAU,IAAI,EAA+B,CAGjE,OAAO,EAMT,MAAM,EAAmB,EAAuC,EAA6B,CAC3F,IAAM,EAAa,KAAK,gBAAgB,EAAQ,CAEhD,IAAK,IAAM,KAAS,EAAQ,CAC1B,I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EzB,MADA,MAAK,SAAW,EACT,KAMT,UAAmB,CACjB,OAAO,KAAK,MAMd,wBAAiC,CAC/B,OAAO,KAAK,gBAMd,wBAAiC,CAC/B,OAAO,KAAK,gBAMd,kBAA2B,CACzB,OAAO,KAAK,UAMd,mBAA4B,CAC1B,OAAO,KAAK,WAMd,iBAA0B,CACxB,OAAO,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"HasMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/HasMany.ts"],"sourcesContent":["/**\n * HasMany Relationship\n *\n * Represents a one-to-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 HasMany<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 local key of the parent model\n */\n protected localKey: string;\n\n /**\n * Create a new has many relationship instance\n */\n constructor(query: EnsembleBuilder<TRelated>, parent: TParent, foreignKey: string, localKey: string) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.localKey = localKey;\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 parentKey = this.getParentKey();\n\n // Only add constraint if parent key exists\n if (parentKey !== null && parentKey !== undefined) {\n this.query.where(this.foreignKey, '=', parentKey);\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.getKeys(models, this.localKey);\n this.query.whereIn(this.foreignKey, 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, new EnsembleCollection<TRelated>());\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.localKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign 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.foreignKey);\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n if (!this.getParentKey()) {\n return [];\n }\n\n this.ensureConstraints();\n return this.query.get();\n }\n\n /**\n * Get the key value of the parent's local key\n */\n protected getParentKey(): any {\n return this.parent.getAttribute(this.localKey);\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 local key for the relationship\n */\n getLocalKeyName(): string {\n return this.localKey;\n }\n\n /**\n * Make a new related instance\n */\n make(attributes: Record<string, any> = {}): TRelated {\n return this.related.newInstance(attributes);\n }\n\n /**\n * Create a new instance of the related model\n */\n async create(attributes: Record<string, any> = {}): Promise<TRelated> {\n const instance = this.make(attributes);\n\n instance.setAttribute(this.foreignKey, this.getParentKey());\n\n await instance.save();\n\n return instance;\n }\n\n /**\n * Create an array of new instances of the related model\n */\n async createMany(records: Record<string, any>[]): Promise<TRelated[]> {\n const instances: TRelated[] = [];\n\n for (const record of records) {\n instances.push(await this.create(record));\n }\n\n return instances;\n }\n\n /**\n * Create a new instance and set the foreign key\n */\n async save(model: TRelated): Promise<TRelated> {\n model.setAttribute(this.foreignKey, this.getParentKey());\n\n await model.save();\n\n return model;\n }\n\n /**\n * Save multiple models with the foreign key set\n */\n async saveMany(models: TRelated[]): Promise<TRelated[]> {\n for (const model of models) {\n await this.save(model);\n }\n\n return models;\n }\n\n /**\n * Find a related model by its primary key\n */\n async find(id: any): Promise<TRelated | null> {\n return this.query.where(this.related.getKeyName(), '=', id).first();\n }\n\n /**\n * Find multiple related models by their primary keys\n */\n async findMany(ids: any[]): Promise<TRelated[]> {\n return this.query.whereIn(this.related.getKeyName(), ids).get();\n }\n\n /**\n * Find a related model by its primary key or throw an exception\n */\n async findOrFail(id: any): Promise<TRelated> {\n const result = await this.find(id);\n\n if (!result) {\n throw new Error(`Model not found with id: ${id}`);\n }\n\n return result;\n }\n\n /**\n * Get the first related model matching the attributes or create it\n */\n async firstOrCreate(attributes: Record<string, any>, values: Record<string, any> = {}): Promise<TRelated> {\n let query = this.query.clone();\n\n // Apply each attribute as a where clause\n for (const [key, value] of Object.entries(attributes)) {\n query = query.where(key, '=', value);\n }\n\n const instance = await query.first();\n\n if (instance) {\n return instance;\n }\n\n return this.create({ ...attributes, ...values });\n }\n\n /**\n * Update the parent model on the relationship\n */\n async update(attributes: Record<string, any>): Promise<number> {\n const updatedAtColumn = this.related.getUpdatedAtColumn();\n if (updatedAtColumn) {\n attributes[updatedAtColumn] = new Date();\n }\n\n return this.query.update(attributes);\n }\n}\n"],"mappings":"4JAQ4E,IACtC,CAEtC,IAAa,EAAb,cAAkF,CAA4B,CAI5G,WAKA,SAKA,YAAY,EAAkC,EAAiB,EAAoB,EAAkB,CACnG,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,SAAW,EAChB,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,GAAI,EAAS,YAAgB,CAC3B,IAAM,EAAY,KAAK,cAAc,CAGjC,GAAc,MAChB,KAAK,MAAM,MAAM,KAAK,WAAY,IAAK,EAAU,EAQvD,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,QAAQ,EAAQ,KAAK,SAAS,CAChD,KAAK,MAAM,QAAQ,KAAK,WAAY,EA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Ac,CAAC,CAExD,MAAM,EAAM,MAAM,CAEX,EAMT,MAAM,SAAS,EAAyC,CACtD,IAAK,IAAM,KAAS,EAClB,MAAM,KAAK,KAAK,EAAM,CAGxB,OAAO,EAMT,MAAM,KAAK,EAAmC,CAC5C,OAAO,KAAK,MAAM,MAAM,KAAK,QAAQ,YAAY,CAAE,IAAK,EAAG,CAAC,OAAO,CAMrE,MAAM,SAAS,EAAiC,CAC9C,OAAO,KAAK,MAAM,QAAQ,KAAK,QAAQ,YAAY,CAAE,EAAI,CAAC,KAAK,CAMjE,MAAM,WAAW,EAA4B,CAC3C,IAAM,EAAS,MAAM,KAAK,KAAK,EAAG,CAElC,GAAI,CAAC,EACH,MAAU,MAAM,4BAA4B,IAAK,CAGnD,OAAO,EAMT,MAAM,cAAc,EAAiC,EAA8B,EAAE,CAAqB,CACxG,IAAI,EAAQ,KAAK,MAAM,OAAO,CAG9B,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,EAAW,CACnD,EAAQ,EAAM,MAAM,EAAK,IAAK,EAAM,CAStC,OANiB,MAAM,EAAM,OAAO,EAM7B,KAAK,OAAO,CAAE,GAAG,EAAY,GAAG,EAAQ,CAAC,CAMlD,MAAM,OAAO,EAAkD,CAC7D,IAAM,EAAkB,KAAK,QAAQ,oBAAoB,CAKzD,OAJI,IACF,EAAW,GAAmB,IAAI,MAG7B,KAAK,MAAM,OAAO,EAAW"}
1
+ {"version":3,"file":"HasMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/HasMany.ts"],"sourcesContent":["/**\n * HasMany Relationship\n *\n * Represents a one-to-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 HasMany<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 local key of the parent model\n */\n protected localKey: string;\n\n /**\n * Create a new has many relationship instance\n */\n constructor(query: EnsembleBuilder<TRelated>, parent: TParent, foreignKey: string, localKey: string) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.localKey = localKey;\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 parentKey = this.getParentKey();\n\n // Only add constraint if parent key exists\n if (parentKey !== null && parentKey !== undefined) {\n this.query.where(this.foreignKey, '=', parentKey);\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.getKeys(models, this.localKey);\n this.query.whereIn(this.foreignKey, 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, new EnsembleCollection<TRelated>());\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.localKey);\n\n if (key !== null && key !== undefined && dictionary[key]) {\n model.setRelation(relation, new EnsembleCollection<TRelated>(dictionary[key]));\n }\n }\n\n return models;\n }\n\n /**\n * Build model dictionary keyed by the relation's foreign 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.foreignKey);\n\n if (key !== null && key !== undefined) {\n if (!dictionary[key]) {\n dictionary[key] = [];\n }\n dictionary[key].push(result);\n }\n }\n\n return dictionary;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<TRelated[]> {\n if (!this.getParentKey()) {\n return [];\n }\n\n this.ensureConstraints();\n return this.query.get();\n }\n\n /**\n * Get the key value of the parent's local key\n */\n protected getParentKey(): any {\n return this.parent.getAttribute(this.localKey);\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 local key for the relationship\n */\n getLocalKeyName(): string {\n return this.localKey;\n }\n\n /**\n * Make a new related instance\n */\n make(attributes: Record<string, any> = {}): TRelated {\n return this.related.newInstance(attributes);\n }\n\n /**\n * Create a new instance of the related model\n */\n async create(attributes: Record<string, any> = {}): Promise<TRelated> {\n const instance = this.make(attributes);\n\n instance.setAttribute(this.foreignKey, this.getParentKey());\n\n await instance.save();\n\n return instance;\n }\n\n /**\n * Create an array of new instances of the related model\n */\n async createMany(records: Record<string, any>[]): Promise<TRelated[]> {\n const instances: TRelated[] = [];\n\n for (const record of records) {\n instances.push(await this.create(record));\n }\n\n return instances;\n }\n\n /**\n * Create a new instance and set the foreign key\n */\n async save(model: TRelated): Promise<TRelated> {\n model.setAttribute(this.foreignKey, this.getParentKey());\n\n await model.save();\n\n return model;\n }\n\n /**\n * Save multiple models with the foreign key set\n */\n async saveMany(models: TRelated[]): Promise<TRelated[]> {\n for (const model of models) {\n await this.save(model);\n }\n\n return models;\n }\n\n /**\n * Find a related model by its primary key\n */\n async find(id: any): Promise<TRelated | null> {\n return this.query.where(this.related.getKeyName(), '=', id).first();\n }\n\n /**\n * Find multiple related models by their primary keys\n */\n async findMany(ids: any[]): Promise<TRelated[]> {\n return this.query.whereIn(this.related.getKeyName(), ids).get();\n }\n\n /**\n * Find a related model by its primary key or throw an exception\n */\n async findOrFail(id: any): Promise<TRelated> {\n const result = await this.find(id);\n\n if (!result) {\n throw new Error(`Model not found with id: ${id}`);\n }\n\n return result;\n }\n\n /**\n * Get the first related model matching the attributes or create it\n */\n async firstOrCreate(attributes: Record<string, any>, values: Record<string, any> = {}): Promise<TRelated> {\n let query = this.query.clone();\n\n // Apply each attribute as a where clause\n for (const [key, value] of Object.entries(attributes)) {\n query = query.where(key, '=', value);\n }\n\n const instance = await query.first();\n\n if (instance) {\n return instance;\n }\n\n return this.create({ ...attributes, ...values });\n }\n\n /**\n * Update the parent model on the relationship\n */\n async update(attributes: Record<string, any>): Promise<number> {\n const updatedAtColumn = this.related.getUpdatedAtColumn();\n if (updatedAtColumn) {\n attributes[updatedAtColumn] = new Date();\n }\n\n return this.query.update(attributes);\n }\n}\n"],"mappings":"4JAQ4E,IACtC,CAEtC,IAAa,EAAb,cAAkF,CAA4B,CAI5G,WAKA,SAKA,YAAY,EAAkC,EAAiB,EAAoB,EAAkB,CACnG,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,SAAW,EAChB,KAAK,oBAAoB,CAM3B,gBAAuB,CACrB,GAAI,EAAS,YAAgB,CAC3B,IAAM,EAAY,KAAK,cAAc,CAGjC,GAAc,MAChB,KAAK,MAAM,MAAM,KAAK,WAAY,IAAK,EAAU,EAQvD,oBAAoB,EAAyB,CAC3C,IAAM,EAAO,KAAK,QAAQ,EAAQ,KAAK,SAAS,CAChD,KAAK,MAAM,QAAQ,KAAK,WAAY,EAAK,CAM3C,aAAa,EAAmB,EAA6B,CAC3D,IAAK,IAAM,KAAS,EAClB,EAAM,YAAY,EAAU,IAAI,EAA+B,CAGjE,OAAO,EAMT,MAAM,EAAmB,EAAuC,EAA6B,CAC3F,IAAM,EAAa,KAAK,gBAAgB,EAAQ,CAEhD,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAM,EAAM,aAAa,KAAK,SAAS,CAEzC,GAAQ,MAA6B,EAAW,IAClD,EAAM,YAAY,EAAU,IAAI,EAA6B,EAAW,GAAK,CAAC,CAIlF,OAAO,EAMT,gBAA0B,EAAgE,CACxF,IAAM,EAAsC,EAAE,CAE9C,IAAK,IAAM,KAAU,EAAS,CAC5B,IAAM,EAAM,EAAO,aAAa,KAAK,WAAW,CAE5C,GAAQ,OACL,EAAW,KACd,EAAW,GAAO,EAAE,EAEtB,EAAW,GAAK,KAAK,EAAO,EAIhC,OAAO,EAMT,MAAM,YAAkC,CAMt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,OAAO,QAAQ,EAAW,CACnD,EAAQ,EAAM,MAAM,EAAK,IAAK,EAAM,CAStC,OAJI,MAFmB,EAAM,OAAO,EAM7B,KAAK,OAAO,CAAE,GAAG,EAAY,GAAG,EAAQ,CAAC,CAMlD,MAAM,OAAO,EAAkD,CAC7D,IAAM,EAAkB,KAAK,QAAQ,oBAAoB,CAKzD,OAJI,IACF,EAAW,GAAmB,IAAI,MAG7B,KAAK,MAAM,OAAO,EAAW"}
@@ -1 +1 @@
1
- {"version":3,"file":"MorphTo.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphTo.ts"],"sourcesContent":["/**\n * MorphTo Relationship\n *\n * Represents a polymorphic inverse relationship\n * Example: Comment belongs to Post or Video (commentable)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { MorphMap } from './MorphMap';\nimport { Relation } from './Relation';\n\nexport class MorphTo<TParent extends Ensemble> extends Relation<Ensemble, TParent> {\n /**\n * The foreign key of the parent model (e.g., 'commentable_id')\n */\n protected foreignKey: string;\n\n /**\n * The morph type column (e.g., 'commentable_type')\n */\n protected morphType: string;\n\n /**\n * The owner key on the related model\n */\n protected ownerKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * Dictionary of models grouped by type\n */\n protected dictionary: Map<string, Map<any, Ensemble>> = new Map();\n\n /**\n * Models loaded by type\n */\n protected models: Map<string, Ensemble[]> = new Map();\n\n /**\n * Create a new morph to relationship instance\n */\n constructor(\n query: EnsembleBuilder<Ensemble>,\n parent: TParent,\n foreignKey: string,\n morphType: string,\n ownerKey: string,\n relationName: string\n ) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.morphType = morphType;\n this.ownerKey = ownerKey;\n this.relationName = relationName;\n // Don't call initializeRelation() - MorphTo doesn't add constraints in constructor\n }\n\n /**\n * Set the base constraints on the relation query\n * MorphTo doesn't use base constraints - queries are built per type\n */\n addConstraints(): void {\n // MorphTo doesn't add constraints here\n // Constraints are added dynamically based on type\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n // Build dictionary grouped by type\n this.buildDictionary(models);\n }\n\n /**\n * Build dictionary of models grouped by morph type\n */\n protected buildDictionary(models: TParent[]): void {\n this.dictionary.clear();\n\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n continue;\n }\n\n if (!this.dictionary.has(type)) {\n this.dictionary.set(type, new Map());\n }\n\n const typeDict = this.dictionary.get(type)!;\n typeDict.set(id, null as any); // Placeholder, will be replaced in match\n }\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<Ensemble>, relation: string): TParent[] {\n // Match each model with its related parent\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n model.setRelation(relation, null);\n continue;\n }\n\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(id)) {\n const related = typeDict.get(id);\n model.setRelation(relation, related || null);\n } else {\n model.setRelation(relation, null);\n }\n }\n\n return models;\n }\n\n /**\n * Get the eager loading results\n */\n async getEager(): Promise<Ensemble[]> {\n const allResults: Ensemble[] = [];\n\n for (const [type, ids] of this.dictionary.entries()) {\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n continue;\n }\n\n const instance = new modelClass();\n const models = await instance.newQuery().whereIn(this.ownerKey, Array.from(ids.keys())).get();\n\n // Store in dictionary for matching\n for (const model of models) {\n const key = model.getAttribute(this.ownerKey);\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(key)) {\n typeDict.set(key, model);\n }\n }\n\n allResults.push(...models);\n }\n\n return allResults;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<Ensemble | null> {\n const type = this.parent.getAttribute(this.morphType);\n const id = this.parent.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n return null;\n }\n\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n return null;\n }\n\n const instance = new modelClass();\n return instance.newQuery().where(this.ownerKey, '=', id).first();\n }\n\n /**\n * Associate the model instance to the parent model\n */\n associate(model: Ensemble | null): this {\n if (model === null) {\n return this.dissociate();\n }\n\n this.parent.setAttribute(this.foreignKey, model.getAttribute(this.ownerKey));\n this.parent.setAttribute(this.morphType, MorphMap.getMorphedModel(model));\n this.parent.setRelation(this.relationName, model);\n\n return this;\n }\n\n /**\n * Dissociate the model from the parent\n */\n dissociate(): this {\n this.parent.setAttribute(this.foreignKey, null);\n this.parent.setAttribute(this.morphType, null);\n this.parent.setRelation(this.relationName, null);\n\n return this;\n }\n\n /**\n * Get the foreign key value\n */\n protected getForeignKeyValue(): any {\n return this.parent.getAttribute(this.foreignKey);\n }\n\n /**\n * Get the morph type value\n */\n protected getMorphTypeValue(): string | null {\n return this.parent.getAttribute(this.morphType);\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 morph type for the relationship\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the owner key for the relationship\n */\n getOwnerKeyName(): string {\n return this.ownerKey;\n }\n}\n"],"mappings":"sPAUsC,IACA,CAEzB,EAAb,cAAuD,CAA4B,CAIjF,WAKA,UAKA,SAKA,aAKA,WAAwD,IAAI,IAK5D,OAA4C,IAAI,IAKhD,YACE,EACA,EACA,EACA,EACA,EACA,EACA,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A0B,CACxB,OAAO,KAAK"}
1
+ {"version":3,"file":"MorphTo.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphTo.ts"],"sourcesContent":["/**\n * MorphTo Relationship\n *\n * Represents a polymorphic inverse relationship\n * Example: Comment belongs to Post or Video (commentable)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { EnsembleCollection } from '@/Database/Ensemble/EnsembleCollection';\nimport { MorphMap } from './MorphMap';\nimport { Relation } from './Relation';\n\nexport class MorphTo<TParent extends Ensemble> extends Relation<Ensemble, TParent> {\n /**\n * The foreign key of the parent model (e.g., 'commentable_id')\n */\n protected foreignKey: string;\n\n /**\n * The morph type column (e.g., 'commentable_type')\n */\n protected morphType: string;\n\n /**\n * The owner key on the related model\n */\n protected ownerKey: string;\n\n /**\n * The name of the relationship\n */\n protected relationName: string;\n\n /**\n * Dictionary of models grouped by type\n */\n protected dictionary: Map<string, Map<any, Ensemble>> = new Map();\n\n /**\n * Models loaded by type\n */\n protected models: Map<string, Ensemble[]> = new Map();\n\n /**\n * Create a new morph to relationship instance\n */\n constructor(\n query: EnsembleBuilder<Ensemble>,\n parent: TParent,\n foreignKey: string,\n morphType: string,\n ownerKey: string,\n relationName: string\n ) {\n super(query, parent);\n this.foreignKey = foreignKey;\n this.morphType = morphType;\n this.ownerKey = ownerKey;\n this.relationName = relationName;\n // Don't call initializeRelation() - MorphTo doesn't add constraints in constructor\n }\n\n /**\n * Set the base constraints on the relation query\n * MorphTo doesn't use base constraints - queries are built per type\n */\n addConstraints(): void {\n // MorphTo doesn't add constraints here\n // Constraints are added dynamically based on type\n }\n\n /**\n * Set the constraints for an eager load of the relation\n */\n addEagerConstraints(models: TParent[]): void {\n // Build dictionary grouped by type\n this.buildDictionary(models);\n }\n\n /**\n * Build dictionary of models grouped by morph type\n */\n protected buildDictionary(models: TParent[]): void {\n this.dictionary.clear();\n\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n continue;\n }\n\n if (!this.dictionary.has(type)) {\n this.dictionary.set(type, new Map());\n }\n\n const typeDict = this.dictionary.get(type)!;\n typeDict.set(id, null as any); // Placeholder, will be replaced in match\n }\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<Ensemble>, relation: string): TParent[] {\n // Match each model with its related parent\n for (const model of models) {\n const type = model.getAttribute(this.morphType);\n const id = model.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n model.setRelation(relation, null);\n continue;\n }\n\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(id)) {\n const related = typeDict.get(id);\n model.setRelation(relation, related || null);\n } else {\n model.setRelation(relation, null);\n }\n }\n\n return models;\n }\n\n /**\n * Get the eager loading results\n */\n async getEager(): Promise<Ensemble[]> {\n const allResults: Ensemble[] = [];\n\n for (const [type, ids] of this.dictionary.entries()) {\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n continue;\n }\n\n const instance = new modelClass();\n const models = await instance.newQuery().whereIn(this.ownerKey, Array.from(ids.keys())).get();\n\n // Store in dictionary for matching\n for (const model of models) {\n const key = model.getAttribute(this.ownerKey);\n const typeDict = this.dictionary.get(type);\n if (typeDict && typeDict.has(key)) {\n typeDict.set(key, model);\n }\n }\n\n allResults.push(...models);\n }\n\n return allResults;\n }\n\n /**\n * Get the results of the relationship\n */\n async getResults(): Promise<Ensemble | null> {\n const type = this.parent.getAttribute(this.morphType);\n const id = this.parent.getAttribute(this.foreignKey);\n\n if (!type || id === null || id === undefined) {\n return null;\n }\n\n const modelClass = MorphMap.getClass(type);\n\n if (!modelClass) {\n console.warn(`MorphTo: Unknown morph type \"${type}\". Did you forget to register it in MorphMap?`);\n return null;\n }\n\n const instance = new modelClass();\n return instance.newQuery().where(this.ownerKey, '=', id).first();\n }\n\n /**\n * Associate the model instance to the parent model\n */\n associate(model: Ensemble | null): this {\n if (model === null) {\n return this.dissociate();\n }\n\n this.parent.setAttribute(this.foreignKey, model.getAttribute(this.ownerKey));\n this.parent.setAttribute(this.morphType, MorphMap.getMorphedModel(model));\n this.parent.setRelation(this.relationName, model);\n\n return this;\n }\n\n /**\n * Dissociate the model from the parent\n */\n dissociate(): this {\n this.parent.setAttribute(this.foreignKey, null);\n this.parent.setAttribute(this.morphType, null);\n this.parent.setRelation(this.relationName, null);\n\n return this;\n }\n\n /**\n * Get the foreign key value\n */\n protected getForeignKeyValue(): any {\n return this.parent.getAttribute(this.foreignKey);\n }\n\n /**\n * Get the morph type value\n */\n protected getMorphTypeValue(): string | null {\n return this.parent.getAttribute(this.morphType);\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 morph type for the relationship\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the owner key for the relationship\n */\n getOwnerKeyName(): string {\n return this.ownerKey;\n }\n}\n"],"mappings":"sPAUsC,IACA,CAEzB,EAAb,cAAuD,CAA4B,CAIjF,WAKA,UAKA,SAKA,aAKA,WAAwD,IAAI,IAK5D,OAA4C,IAAI,IAKhD,YACE,EACA,EACA,EACA,EACA,EACA,EACA,CACA,MAAM,EAAO,EAAO,CACpB,KAAK,WAAa,EAClB,KAAK,UAAY,EACjB,KAAK,SAAW,EAChB,KAAK,aAAe,EAQtB,gBAAuB,EAQvB,oBAAoB,EAAyB,CAE3C,KAAK,gBAAgB,EAAO,CAM9B,gBAA0B,EAAyB,CACjD,KAAK,WAAW,OAAO,CAEvB,IAAK,IAAM,KAAS,EAAQ,CAC1B,IAAM,EAAO,EAAM,aAAa,KAAK,U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,EAAW,KAAK,GAAG,EAAO,CAG5B,OAAO,EAMT,MAAM,YAAuC,CAC3C,IAAM,EAAO,KAAK,OAAO,aAAa,KAAK,UAAU,CAC/C,EAAK,KAAK,OAAO,aAAa,KAAK,WAAW,CAEpD,GAAI,CAAC,GAAQ,GAAO,KAClB,OAAO,KAGT,IAAM,EAAa,EAAS,SAAS,EAAK,CAQ1C,OANK,EAME,IADc,GACN,CAAC,UAAU,CAAC,MAAM,KAAK,SAAU,IAAK,EAAG,CAAC,OAAO,EAL9D,QAAQ,KAAK,gCAAgC,EAAK,+CAA+C,CAC1F,MAUX,UAAU,EAA8B,CAStC,OARI,IAAU,KACL,KAAK,YAAY,EAG1B,KAAK,OAAO,aAAa,KAAK,WAAY,EAAM,aAAa,KAAK,SAAS,CAAC,CAC5E,KAAK,OAAO,aAAa,KAAK,UAAW,EAAS,gBAAgB,EAAM,CAAC,CACzE,KAAK,OAAO,YAAY,KAAK,aAAc,EAAM,CAE1C,MAMT,YAAmB,CAKjB,OAJA,KAAK,OAAO,aAAa,KAAK,WAAY,KAAK,CAC/C,KAAK,OAAO,aAAa,KAAK,UAAW,KAAK,CAC9C,KAAK,OAAO,YAAY,KAAK,aAAc,KAAK,CAEzC,KAMT,oBAAoC,CAClC,OAAO,KAAK,OAAO,aAAa,KAAK,WAAW,CAMlD,mBAA6C,CAC3C,OAAO,KAAK,OAAO,aAAa,KAAK,UAAU,CAMjD,mBAA4B,CAC1B,OAAO,KAAK,WAMd,cAAuB,CACrB,OAAO,KAAK,UAMd,iBAA0B,CACxB,OAAO,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"MorphToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphToMany.ts"],"sourcesContent":["/**\n * MorphToMany Relationship\n *\n * Represents a polymorphic many-to-many relationship from the parent side\n * Example: Post has many Tags (where Tag can belong to many types via taggables table)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { BelongsToMany } from './BelongsToMany';\nimport { MorphMap } from './MorphMap';\n\nexport class MorphToMany<TRelated extends Ensemble, TParent extends Ensemble> extends BelongsToMany<TRelated, TParent> {\n /**\n * The morph type column (e.g., 'taggable_type')\n */\n protected morphType: string;\n\n /**\n * The morph class name or alias\n */\n protected morphClass: string;\n\n /**\n * Whether this is the inverse of the relation\n */\n protected inverse: boolean;\n\n /**\n * Create a new morph to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n name: string,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n morphType: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string,\n inverse: boolean = false\n ) {\n super(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, relationName);\n\n this.morphType = morphType;\n this.morphClass = this.getMorphClass();\n this.inverse = inverse;\n }\n\n /**\n * Set the join clause for the relation query\n * Adds the morph type constraint\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table with morph type constraint\n query\n .join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`)\n .where(`${this.table}.${this.morphType}`, '=', this.morphClass);\n }\n\n /**\n * Set the where clause for eager loading\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\n }\n }\n\n /**\n * Get the morph class for the parent during initialization\n */\n protected getMorphClass(): string {\n if (this.inverse) {\n // For inverse relations, we don't set the morph class on parent\n // It will be set per attach/sync operation\n return '';\n }\n\n return MorphMap.getMorphedModel(this.parent);\n }\n\n /**\n * Get the morph type name\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the morph class value\n */\n getMorphClassValue(): string {\n return this.morphClass;\n }\n\n /**\n * Set the morph class (used for inverse relations)\n */\n setMorphClass(morphClass: string): this {\n this.morphClass = morphClass;\n return this;\n }\n\n /**\n * Attach models to the parent with morph type\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}, touch: boolean = true): Promise<void> {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n throw new Error('Parent key must be set before attaching');\n }\n\n const records = idsArray.map((id) => ({\n [this.foreignPivotKey]: parentKey,\n [this.relatedPivotKey]: id,\n [this.morphType]: this.morphClass,\n ...attributes,\n }));\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent with morph type constraint\n */\n async detach(ids?: any | any[]): Promise<number> {\n const query = this.newPivotQuery();\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return 0;\n }\n\n query.where(this.foreignPivotKey, '=', parentKey).where(this.morphType, '=', this.morphClass);\n\n if (ids) {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n query.whereIn(this.relatedPivotKey, idsArray);\n }\n\n return query.delete();\n }\n\n /**\n * Sync the intermediate tables with morph type\n */\n async sync(ids: any[], detaching: boolean = true): Promise<{ attached: any[]; detached: any[]; updated: any[] }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const parentKey = this.parent.getAttribute(this.parentKey);\n if (!parentKey) {\n return changes;\n }\n\n // Get current IDs\n const current = await this.newPivotQuery()\n .where(this.foreignPivotKey, '=', parentKey)\n .where(this.morphType, '=', this.morphClass)\n .select(this.relatedPivotKey)\n .get();\n\n const currentIds = current.map((record: any) => record[this.relatedPivotKey]);\n const idsToAttach = ids.filter((id) => !currentIds.includes(id));\n const idsToDetach = detaching ? currentIds.filter((id: any) => !ids.includes(id)) : [];\n\n // Detach old records\n if (idsToDetach.length > 0) {\n await this.detach(idsToDetach);\n changes.detached = idsToDetach;\n }\n\n // Attach new records\n if (idsToAttach.length > 0) {\n await this.attach(idsToAttach);\n changes.attached = idsToAttach;\n }\n\n return changes;\n }\n\n /**\n * Create a new pivot query\n */\n protected newPivotQuery(): EnsembleBuilder<any> {\n const connection = this.parent.getConnection();\n return connection.table(this.table) as any;\n }\n}\n"],"mappings":"yQASgD,IACV,CAEzB,EAAb,cAAsF,CAAiC,CAIrH,UAKA,WAKA,QAKA,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAAmB,GACnB,CACA,MAAM,EAAO,EAAQ,EAAO,EAAiB,EAAiB,EAAW,EAAY,EAAa,CAElG,KAAK,UAAY,EACjB,KAAK,WAAa,KAAK,eAAe,CACtC,KAAK,QAAU,EAOjB,YAAsB,EAAyC,CAC7D,IAAiB,KAAK,MAGtB,EACG,KAAK,KAAK,MAAO,GAAG,KAAK,4BAA4B,GAAI,IAAK,GAAG,KAAK,iCAAiC,GAAG,CAC1G,MAAM,GAAG,KAAK,MAAM,GAAG,KAAK,YAAa,IAAK,KAAK,WAAW,CAMnE,qBAAsC,CACpC,IAAM,EAAiB,KAAK,OAAO,aAAa,KAAK,UAAU,CAG3D,GAAmB,MACrB,KAAK,MAAM,MAAM,KAAK,iCAAiC,CAAE,IAAK,EAAe,CAOjF,eAAkC,CAOhC,OANI,KAAK,QAGA,GAGF,EAAS,gBAAgB,KAAK,OAAO,CAM9C,cAAuB,CACrB,OAAO,KAAK,UAMd,oBAA6B,CAC3B,OAAO,KAAK,WAMd,cAAc,EAA0B,CAEtC,MADA,MAAK,WAAa,EACX,KAMT,MAAM,OAAO,EAAkB,EAAkC,EAAE,CAAE,EAAiB,GAAqB,CACzG,IAAM,EAAW,MAAM,QAAQ,EAAI,CAAG,EAAM,CAAC,EAAI,CAC3C,EAAY,KAAK,OAAO,aAAa,KAAK,UAAU,CAE1D,GAAI,CAAC,EACH,MAAU,MAAM,0CAA0C,CAG5D,IAAM,EAAU,EAAS,IAAK,IAAQ,EACnC,KAAK,iBAAkB,GACvB,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,MAAM,KAAK,MAAM"}
1
+ {"version":3,"file":"MorphToMany.mjs","names":[],"sources":["../../../../src/Database/Ensemble/Relations/MorphToMany.ts"],"sourcesContent":["/**\n * MorphToMany Relationship\n *\n * Represents a polymorphic many-to-many relationship from the parent side\n * Example: Post has many Tags (where Tag can belong to many types via taggables table)\n */\n\nimport { Ensemble } from '@/Database/Ensemble/Ensemble';\nimport { EnsembleBuilder } from '@/Database/Ensemble/EnsembleBuilder';\nimport { BelongsToMany } from './BelongsToMany';\nimport { MorphMap } from './MorphMap';\n\nexport class MorphToMany<TRelated extends Ensemble, TParent extends Ensemble> extends BelongsToMany<TRelated, TParent> {\n /**\n * The morph type column (e.g., 'taggable_type')\n */\n protected morphType: string;\n\n /**\n * The morph class name or alias\n */\n protected morphClass: string;\n\n /**\n * Whether this is the inverse of the relation\n */\n protected inverse: boolean;\n\n /**\n * Create a new morph to many relationship instance\n */\n constructor(\n query: EnsembleBuilder<TRelated>,\n parent: TParent,\n name: string,\n table: string,\n foreignPivotKey: string,\n relatedPivotKey: string,\n morphType: string,\n parentKey: string,\n relatedKey: string,\n relationName?: string,\n inverse: boolean = false\n ) {\n super(query, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, relationName);\n\n this.morphType = morphType;\n this.morphClass = this.getMorphClass();\n this.inverse = inverse;\n }\n\n /**\n * Set the join clause for the relation query\n * Adds the morph type constraint\n */\n protected performJoin(query?: EnsembleBuilder<TRelated>): void {\n query = query || this.query;\n\n // Join the pivot table with morph type constraint\n query\n .join(this.table, `${this.getQualifiedRelatedKeyName()}`, '=', `${this.getQualifiedRelatedPivotKeyName()}`)\n .where(`${this.table}.${this.morphType}`, '=', this.morphClass);\n }\n\n /**\n * Set the where clause for eager loading\n */\n protected addWhereConstraints(): void {\n const parentKeyValue = this.parent.getAttribute(this.parentKey);\n\n // Only add constraint if parent key value exists\n if (parentKeyValue !== null && parentKeyValue !== undefined) {\n this.query.where(this.getQualifiedForeignPivotKeyName(), '=', parentKeyValue);\n }\n }\n\n /**\n * Get the morph class for the parent during initialization\n */\n protected getMorphClass(): string {\n if (this.inverse) {\n // For inverse relations, we don't set the morph class on parent\n // It will be set per attach/sync operation\n return '';\n }\n\n return MorphMap.getMorphedModel(this.parent);\n }\n\n /**\n * Get the morph type name\n */\n getMorphType(): string {\n return this.morphType;\n }\n\n /**\n * Get the morph class value\n */\n getMorphClassValue(): string {\n return this.morphClass;\n }\n\n /**\n * Set the morph class (used for inverse relations)\n */\n setMorphClass(morphClass: string): this {\n this.morphClass = morphClass;\n return this;\n }\n\n /**\n * Attach models to the parent with morph type\n */\n async attach(ids: any | any[], attributes: Record<string, any> = {}, touch: boolean = true): Promise<void> {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n throw new Error('Parent key must be set before attaching');\n }\n\n const records = idsArray.map((id) => ({\n [this.foreignPivotKey]: parentKey,\n [this.relatedPivotKey]: id,\n [this.morphType]: this.morphClass,\n ...attributes,\n }));\n\n const connection = this.parent.getConnection();\n await connection.table(this.table).insert(records);\n }\n\n /**\n * Detach models from the parent with morph type constraint\n */\n async detach(ids?: any | any[]): Promise<number> {\n const query = this.newPivotQuery();\n const parentKey = this.parent.getAttribute(this.parentKey);\n\n if (!parentKey) {\n return 0;\n }\n\n query.where(this.foreignPivotKey, '=', parentKey).where(this.morphType, '=', this.morphClass);\n\n if (ids) {\n const idsArray = Array.isArray(ids) ? ids : [ids];\n query.whereIn(this.relatedPivotKey, idsArray);\n }\n\n return query.delete();\n }\n\n /**\n * Sync the intermediate tables with morph type\n */\n async sync(ids: any[], detaching: boolean = true): Promise<{ attached: any[]; detached: any[]; updated: any[] }> {\n const changes = {\n attached: [] as any[],\n detached: [] as any[],\n updated: [] as any[],\n };\n\n const parentKey = this.parent.getAttribute(this.parentKey);\n if (!parentKey) {\n return changes;\n }\n\n // Get current IDs\n const current = await this.newPivotQuery()\n .where(this.foreignPivotKey, '=', parentKey)\n .where(this.morphType, '=', this.morphClass)\n .select(this.relatedPivotKey)\n .get();\n\n const currentIds = current.map((record: any) => record[this.relatedPivotKey]);\n const idsToAttach = ids.filter((id) => !currentIds.includes(id));\n const idsToDetach = detaching ? currentIds.filter((id: any) => !ids.includes(id)) : [];\n\n // Detach old records\n if (idsToDetach.length > 0) {\n await this.detach(idsToDetach);\n changes.detached = idsToDetach;\n }\n\n // Attach new records\n if (idsToAttach.length > 0) {\n await this.attach(idsToAttach);\n changes.attached = idsToAttach;\n }\n\n return changes;\n }\n\n /**\n * Create a new pivot query\n */\n protected newPivotQuery(): EnsembleBuilder<any> {\n const connection = this.parent.getConnection();\n return connection.table(this.table) as any;\n }\n}\n"],"mappings":"yQASgD,IACV,CAEzB,EAAb,cAAsF,CAAiC,CAIrH,UAKA,WAKA,QAKA,YACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAAmB,GACnB,CACA,MAAM,EAAO,EAAQ,EAAO,EAAiB,EAAiB,EAAW,EAAY,EAAa,CAElG,KAAK,UAAY,EACjB,KAAK,WAAa,KAAK,eAAe,CACtC,KAAK,QAAU,EAOjB,YAAsB,EAAyC,CAC7D,IAAiB,KAAK,MAGtB,EACG,KAAK,KAAK,MAAO,GAAG,KAAK,4BAA4B,GAAI,IAAK,GAAG,KAAK,iCAAiC,GAAG,CAC1G,MAAM,GAAG,KAAK,MAAM,GAAG,KAAK,YAAa,IAAK,KAAK,WAAW,CAMnE,qBAAsC,CACpC,IAAM,EAAiB,KAAK,OAAO,aAAa,KAAK,UAAU,CAG3D,GAAmB,MACrB,KAAK,MAAM,MAAM,KAAK,iCAAiC,CAAE,IAAK,EAAe,CAOjF,eAAkC,CAOhC,OANI,KAAK,QAGA,GAGF,EAAS,gBAAgB,KAAK,OAAO,CAM9C,cAAuB,CACrB,OAAO,KAAK,UAMd,oBAA6B,CAC3B,OAAO,KAAK,WAMd,cAAc,EAA0B,CAEtC,MADA,MAAK,WAAa,EACX,KAMT,MA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,EAAW,OAAQ,GAAY,CAAC,EAAI,SAAS,EAAG,CAAC,CAAG,EAAE,CActF,OAXI,EAAY,OAAS,IACvB,MAAM,KAAK,OAAO,EAAY,CAC9B,EAAQ,SAAW,GAIjB,EAAY,OAAS,IACvB,MAAM,KAAK,OAAO,EAAY,CAC9B,EAAQ,SAAW,GAGd,EAMT,eAAgD,CAE9C,OADmB,KAAK,OAAO,eACd,CAAC,MAAM,KAAK,MAAM"}
@@ -1 +1 @@
1
- require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./ColumnDefinition.cjs`),t=require(`./ForeignKeyDefinition.cjs`);var n=class{columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e.ColumnDefinition(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e.ColumnDefinition(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e.ColumnDefinition(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e.ColumnDefinition(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e.ColumnDefinition(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e.ColumnDefinition(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e.ColumnDefinition(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e.ColumnDefinition(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e.ColumnDefinition(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e.ColumnDefinition(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e.ColumnDefinition(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e.ColumnDefinition(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e.ColumnDefinition(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e.ColumnDefinition(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e.ColumnDefinition(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e.ColumnDefinition(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e.ColumnDefinition(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e.ColumnDefinition(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e.ColumnDefinition(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e.ColumnDefinition(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e.ColumnDefinition(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t.ForeignKeyDefinition(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};exports.Blueprint=n;
1
+ require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`./ColumnDefinition.cjs`),t=require(`./ForeignKeyDefinition.cjs`);var n=class{table;columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e.ColumnDefinition(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e.ColumnDefinition(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e.ColumnDefinition(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e.ColumnDefinition(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e.ColumnDefinition(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e.ColumnDefinition(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e.ColumnDefinition(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e.ColumnDefinition(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e.ColumnDefinition(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e.ColumnDefinition(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e.ColumnDefinition(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e.ColumnDefinition(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e.ColumnDefinition(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e.ColumnDefinition(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e.ColumnDefinition(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e.ColumnDefinition(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e.ColumnDefinition(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e.ColumnDefinition(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e.ColumnDefinition(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e.ColumnDefinition(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e.ColumnDefinition(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e.ColumnDefinition(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t.ForeignKeyDefinition(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};exports.Blueprint=n;
@@ -1,2 +1,2 @@
1
- import{ColumnDefinition as e}from"./ColumnDefinition.mjs";import{ForeignKeyDefinition as t}from"./ForeignKeyDefinition.mjs";var n=class{columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};export{n as Blueprint};
1
+ import{ColumnDefinition as e}from"./ColumnDefinition.mjs";import{ForeignKeyDefinition as t}from"./ForeignKeyDefinition.mjs";var n=class{table;columns=[];indexes=[];foreignKeys=[];commands=[];isCreate=!1;constructor(e){this.table=e}id(t=`id`){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isPrimary=!0,n.isUnsigned=!0,this.columns.push(n),n}bigIncrements(t){let n=new e(t,`bigIncrements`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}increments(t){let n=new e(t,`increments`);return n.isAutoIncrement=!0,n.isUnsigned=!0,this.columns.push(n),n}uuid(t){let n=new e(t,`uuid`);return n.length=36,this.columns.push(n),n}string(t,n=255){let r=new e(t,`string`);return r.length=n,this.columns.push(r),r}text(t){let n=new e(t,`text`);return this.columns.push(n),n}mediumText(t){let n=new e(t,`mediumText`);return this.columns.push(n),n}longText(t){let n=new e(t,`longText`);return this.columns.push(n),n}integer(t){let n=new e(t,`integer`);return this.columns.push(n),n}bigInteger(t){let n=new e(t,`bigInteger`);return this.columns.push(n),n}smallInteger(t){let n=new e(t,`smallInteger`);return this.columns.push(n),n}tinyInteger(t){let n=new e(t,`tinyInteger`);return this.columns.push(n),n}decimal(t,n=8,r=2){let i=new e(t,`decimal`);return i.precision=n,i.scale=r,this.columns.push(i),i}float(t,n,r){let i=new e(t,`float`);return i.precision=n,i.scale=r,this.columns.push(i),i}double(t,n,r){let i=new e(t,`double`);return i.precision=n,i.scale=r,this.columns.push(i),i}boolean(t){let n=new e(t,`boolean`);return this.columns.push(n),n}date(t){let n=new e(t,`date`);return this.columns.push(n),n}datetime(t,n){let r=new e(t,`datetime`);return r.precision=n,this.columns.push(r),r}timestamp(t,n){let r=new e(t,`timestamp`);return r.precision=n,this.columns.push(r),r}timestamps(e){this.timestamp(`created_at`,e).nullable(),this.timestamp(`updated_at`,e).nullable()}json(t){let n=new e(t,`json`);return this.columns.push(n),n}jsonb(t){let n=new e(t,`jsonb`);return this.columns.push(n),n}binary(t){let n=new e(t,`binary`);return this.columns.push(n),n}enum(t,n){let r=new e(t,`enum`);return r.enumValues=n,this.columns.push(r),r}rememberToken(){return this.string(`remember_token`,100).nullable()}softDeletes(e=`deleted_at`){return this.timestamp(e).nullable()}index(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`index`})}unique(e,t){this.indexes.push({columns:Array.isArray(e)?e:[e],name:t,type:`unique`})}primary(e){this.indexes.push({columns:Array.isArray(e)?e:[e],type:`primary`})}foreign(e,n){let r=new t(e,n);return this.foreignKeys.push(r),r}dropColumn(e){this.commands.push({type:`dropColumn`,columns:Array.isArray(e)?e:[e]})}dropIndex(e){this.commands.push({type:`dropIndex`,name:e})}dropForeign(e){this.commands.push({type:`dropForeign`,name:e})}renameColumn(e,t){this.commands.push({type:`renameColumn`,from:e,to:t})}};export{n as Blueprint};
2
2
  //# sourceMappingURL=Blueprint.mjs.map