alepha 0.13.0 → 0.13.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 (461) hide show
  1. package/README.md +1 -1
  2. package/dist/api-files/index.d.ts +28 -91
  3. package/dist/api-files/index.js +10 -755
  4. package/dist/api-files/index.js.map +1 -1
  5. package/dist/api-jobs/index.d.ts +67 -67
  6. package/dist/api-jobs/index.js +13 -13
  7. package/dist/api-jobs/index.js.map +1 -1
  8. package/dist/api-notifications/index.d.ts +129 -146
  9. package/dist/api-notifications/index.js +17 -39
  10. package/dist/api-notifications/index.js.map +1 -1
  11. package/dist/api-parameters/index.d.ts +21 -22
  12. package/dist/api-parameters/index.js +22 -22
  13. package/dist/api-parameters/index.js.map +1 -1
  14. package/dist/api-users/index.d.ts +224 -2001
  15. package/dist/api-users/index.js +914 -4787
  16. package/dist/api-users/index.js.map +1 -1
  17. package/dist/api-verifications/index.d.ts +96 -96
  18. package/dist/batch/index.d.ts +13 -13
  19. package/dist/batch/index.js +8 -8
  20. package/dist/batch/index.js.map +1 -1
  21. package/dist/bucket/index.d.ts +14 -14
  22. package/dist/bucket/index.js +12 -12
  23. package/dist/bucket/index.js.map +1 -1
  24. package/dist/cache/index.d.ts +11 -11
  25. package/dist/cache/index.js +9 -9
  26. package/dist/cache/index.js.map +1 -1
  27. package/dist/cli/{dist-Sz2EXvQX.cjs → dist-Dl9Vl7Ur.js} +17 -13
  28. package/dist/cli/{dist-BBPjuQ56.js.map → dist-Dl9Vl7Ur.js.map} +1 -1
  29. package/dist/cli/index.d.ts +31 -37
  30. package/dist/cli/index.js +152 -83
  31. package/dist/cli/index.js.map +1 -1
  32. package/dist/command/index.d.ts +19 -19
  33. package/dist/command/index.js +25 -25
  34. package/dist/command/index.js.map +1 -1
  35. package/dist/core/index.browser.js +218 -218
  36. package/dist/core/index.browser.js.map +1 -1
  37. package/dist/core/index.d.ts +232 -232
  38. package/dist/core/index.js +218 -218
  39. package/dist/core/index.js.map +1 -1
  40. package/dist/core/{index.cjs → index.native.js} +304 -455
  41. package/dist/core/index.native.js.map +1 -0
  42. package/dist/datetime/index.d.ts +9 -9
  43. package/dist/datetime/index.js +7 -7
  44. package/dist/datetime/index.js.map +1 -1
  45. package/dist/email/index.d.ts +16 -16
  46. package/dist/email/index.js +80 -82
  47. package/dist/email/index.js.map +1 -1
  48. package/dist/file/index.js +1 -1
  49. package/dist/file/index.js.map +1 -1
  50. package/dist/lock/index.d.ts +9 -9
  51. package/dist/lock/index.js +8 -8
  52. package/dist/lock/index.js.map +1 -1
  53. package/dist/lock-redis/index.js +3 -66
  54. package/dist/lock-redis/index.js.map +1 -1
  55. package/dist/logger/index.d.ts +5 -5
  56. package/dist/logger/index.js +8 -8
  57. package/dist/logger/index.js.map +1 -1
  58. package/dist/orm/index.browser.js +114 -114
  59. package/dist/orm/index.browser.js.map +1 -1
  60. package/dist/orm/index.d.ts +219 -219
  61. package/dist/orm/index.js +46 -46
  62. package/dist/orm/index.js.map +1 -1
  63. package/dist/queue/index.d.ts +25 -25
  64. package/dist/queue/index.js +20 -20
  65. package/dist/queue/index.js.map +1 -1
  66. package/dist/queue-redis/index.d.ts +2 -2
  67. package/dist/redis/index.d.ts +10 -10
  68. package/dist/retry/index.d.ts +20 -20
  69. package/dist/retry/index.js +9 -9
  70. package/dist/retry/index.js.map +1 -1
  71. package/dist/scheduler/index.d.ts +12 -12
  72. package/dist/scheduler/index.js +9 -9
  73. package/dist/scheduler/index.js.map +1 -1
  74. package/dist/security/index.d.ts +53 -53
  75. package/dist/security/index.js +32 -32
  76. package/dist/security/index.js.map +1 -1
  77. package/dist/server/index.browser.js +1 -1
  78. package/dist/server/index.browser.js.map +1 -1
  79. package/dist/server/index.d.ts +101 -101
  80. package/dist/server/index.js +17 -17
  81. package/dist/server/index.js.map +1 -1
  82. package/dist/server-auth/index.browser.js +4 -982
  83. package/dist/server-auth/index.browser.js.map +1 -1
  84. package/dist/server-auth/index.d.ts +204 -785
  85. package/dist/server-auth/index.js +47 -1239
  86. package/dist/server-auth/index.js.map +1 -1
  87. package/dist/server-cache/index.d.ts +10 -10
  88. package/dist/server-cache/index.js +2 -2
  89. package/dist/server-cache/index.js.map +1 -1
  90. package/dist/server-compress/index.d.ts +4 -4
  91. package/dist/server-compress/index.js +1 -1
  92. package/dist/server-compress/index.js.map +1 -1
  93. package/dist/server-cookies/index.browser.js +8 -8
  94. package/dist/server-cookies/index.browser.js.map +1 -1
  95. package/dist/server-cookies/index.d.ts +17 -17
  96. package/dist/server-cookies/index.js +10 -10
  97. package/dist/server-cookies/index.js.map +1 -1
  98. package/dist/server-cors/index.d.ts +17 -17
  99. package/dist/server-cors/index.js +9 -9
  100. package/dist/server-cors/index.js.map +1 -1
  101. package/dist/server-health/index.d.ts +2 -2
  102. package/dist/server-helmet/index.d.ts +1 -1
  103. package/dist/server-links/index.browser.js +12 -12
  104. package/dist/server-links/index.browser.js.map +1 -1
  105. package/dist/server-links/index.d.ts +59 -251
  106. package/dist/server-links/index.js +23 -502
  107. package/dist/server-links/index.js.map +1 -1
  108. package/dist/server-metrics/index.d.ts +4 -4
  109. package/dist/server-metrics/index.js +170 -174
  110. package/dist/server-metrics/index.js.map +1 -1
  111. package/dist/server-multipart/index.d.ts +2 -2
  112. package/dist/server-proxy/index.d.ts +12 -12
  113. package/dist/server-proxy/index.js +10 -10
  114. package/dist/server-proxy/index.js.map +1 -1
  115. package/dist/server-rate-limit/index.d.ts +22 -22
  116. package/dist/server-rate-limit/index.js +12 -12
  117. package/dist/server-rate-limit/index.js.map +1 -1
  118. package/dist/server-security/index.d.ts +24 -24
  119. package/dist/server-security/index.js +15 -15
  120. package/dist/server-security/index.js.map +1 -1
  121. package/dist/server-static/index.d.ts +14 -14
  122. package/dist/server-static/index.js +8 -8
  123. package/dist/server-static/index.js.map +1 -1
  124. package/dist/server-swagger/index.d.ts +25 -184
  125. package/dist/server-swagger/index.js +21 -724
  126. package/dist/server-swagger/index.js.map +1 -1
  127. package/dist/sms/index.d.ts +14 -14
  128. package/dist/sms/index.js +9 -9
  129. package/dist/sms/index.js.map +1 -1
  130. package/dist/thread/index.d.ts +11 -11
  131. package/dist/thread/index.js +17 -17
  132. package/dist/thread/index.js.map +1 -1
  133. package/dist/topic/index.d.ts +26 -26
  134. package/dist/topic/index.js +16 -16
  135. package/dist/topic/index.js.map +1 -1
  136. package/dist/topic-redis/index.d.ts +1 -1
  137. package/dist/vite/index.d.ts +3 -3
  138. package/dist/vite/index.js +12 -13
  139. package/dist/vite/index.js.map +1 -1
  140. package/dist/websocket/index.browser.js +11 -11
  141. package/dist/websocket/index.browser.js.map +1 -1
  142. package/dist/websocket/index.d.ts +51 -51
  143. package/dist/websocket/index.js +13 -13
  144. package/dist/websocket/index.js.map +1 -1
  145. package/package.json +62 -52
  146. package/src/api-files/services/FileService.ts +5 -7
  147. package/src/api-jobs/index.ts +1 -1
  148. package/src/api-jobs/{descriptors → primitives}/$job.ts +8 -8
  149. package/src/api-jobs/providers/JobProvider.ts +9 -9
  150. package/src/api-jobs/services/JobService.ts +5 -5
  151. package/src/api-notifications/index.ts +5 -15
  152. package/src/api-notifications/{descriptors → primitives}/$notification.ts +10 -10
  153. package/src/api-notifications/services/NotificationSenderService.ts +3 -3
  154. package/src/api-parameters/index.ts +1 -1
  155. package/src/api-parameters/{descriptors → primitives}/$config.ts +7 -12
  156. package/src/api-users/index.ts +1 -1
  157. package/src/api-users/{descriptors → primitives}/$userRealm.ts +8 -8
  158. package/src/api-users/providers/UserRealmProvider.ts +1 -1
  159. package/src/batch/index.ts +3 -3
  160. package/src/batch/{descriptors → primitives}/$batch.ts +13 -16
  161. package/src/bucket/index.ts +8 -8
  162. package/src/bucket/{descriptors → primitives}/$bucket.ts +8 -8
  163. package/src/bucket/providers/LocalFileStorageProvider.ts +3 -3
  164. package/src/cache/index.ts +4 -4
  165. package/src/cache/{descriptors → primitives}/$cache.ts +15 -15
  166. package/src/cli/apps/AlephaPackageBuilderCli.ts +30 -3
  167. package/src/cli/assets/appRouterTs.ts +9 -0
  168. package/src/cli/assets/indexHtml.ts +2 -1
  169. package/src/cli/assets/mainBrowserTs.ts +10 -0
  170. package/src/cli/commands/CoreCommands.ts +6 -5
  171. package/src/cli/commands/DrizzleCommands.ts +69 -61
  172. package/src/cli/commands/VerifyCommands.ts +2 -2
  173. package/src/cli/commands/ViteCommands.ts +6 -1
  174. package/src/cli/services/ProjectUtils.ts +78 -41
  175. package/src/command/index.ts +5 -5
  176. package/src/command/{descriptors → primitives}/$command.ts +9 -12
  177. package/src/command/providers/CliProvider.ts +10 -10
  178. package/src/core/Alepha.ts +30 -33
  179. package/src/core/constants/KIND.ts +1 -1
  180. package/src/core/constants/OPTIONS.ts +1 -1
  181. package/src/core/helpers/{descriptor.ts → primitive.ts} +18 -18
  182. package/src/core/helpers/ref.ts +1 -1
  183. package/src/core/index.shared.ts +8 -8
  184. package/src/core/{descriptors → primitives}/$context.ts +5 -5
  185. package/src/core/{descriptors → primitives}/$hook.ts +4 -4
  186. package/src/core/{descriptors → primitives}/$inject.ts +2 -2
  187. package/src/core/{descriptors → primitives}/$module.ts +9 -9
  188. package/src/core/{descriptors → primitives}/$use.ts +2 -2
  189. package/src/core/providers/CodecManager.ts +1 -1
  190. package/src/core/providers/JsonSchemaCodec.ts +1 -1
  191. package/src/core/providers/StateManager.ts +2 -2
  192. package/src/datetime/index.ts +3 -3
  193. package/src/datetime/{descriptors → primitives}/$interval.ts +6 -6
  194. package/src/email/index.ts +4 -4
  195. package/src/email/{descriptors → primitives}/$email.ts +8 -8
  196. package/src/file/index.ts +1 -1
  197. package/src/lock/index.ts +3 -3
  198. package/src/lock/{descriptors → primitives}/$lock.ts +10 -10
  199. package/src/logger/index.ts +8 -8
  200. package/src/logger/{descriptors → primitives}/$logger.ts +2 -2
  201. package/src/logger/services/Logger.ts +1 -1
  202. package/src/orm/constants/PG_SYMBOLS.ts +2 -2
  203. package/src/orm/index.browser.ts +2 -2
  204. package/src/orm/index.ts +8 -8
  205. package/src/orm/{descriptors → primitives}/$entity.ts +11 -11
  206. package/src/orm/{descriptors → primitives}/$repository.ts +2 -2
  207. package/src/orm/{descriptors → primitives}/$sequence.ts +8 -8
  208. package/src/orm/{descriptors → primitives}/$transaction.ts +4 -4
  209. package/src/orm/providers/DrizzleKitProvider.ts +1 -1
  210. package/src/orm/providers/PostgresTypeProvider.ts +3 -3
  211. package/src/orm/providers/RepositoryProvider.ts +4 -4
  212. package/src/orm/providers/drivers/DatabaseProvider.ts +7 -7
  213. package/src/orm/services/ModelBuilder.ts +9 -9
  214. package/src/orm/services/PgRelationManager.ts +2 -2
  215. package/src/orm/services/PostgresModelBuilder.ts +5 -5
  216. package/src/orm/services/Repository.ts +7 -7
  217. package/src/orm/services/SqliteModelBuilder.ts +5 -5
  218. package/src/queue/index.ts +7 -7
  219. package/src/queue/{descriptors → primitives}/$consumer.ts +15 -15
  220. package/src/queue/{descriptors → primitives}/$queue.ts +12 -12
  221. package/src/queue/providers/WorkerProvider.ts +7 -7
  222. package/src/retry/index.ts +3 -3
  223. package/src/retry/{descriptors → primitives}/$retry.ts +19 -17
  224. package/src/scheduler/index.ts +3 -3
  225. package/src/scheduler/{descriptors → primitives}/$scheduler.ts +9 -9
  226. package/src/scheduler/providers/CronProvider.ts +1 -1
  227. package/src/security/index.ts +9 -9
  228. package/src/security/{descriptors → primitives}/$permission.ts +7 -7
  229. package/src/security/{descriptors → primitives}/$realm.ts +6 -12
  230. package/src/security/{descriptors → primitives}/$role.ts +12 -12
  231. package/src/security/{descriptors → primitives}/$serviceAccount.ts +8 -8
  232. package/src/server/index.browser.ts +1 -1
  233. package/src/server/index.ts +14 -14
  234. package/src/server/{descriptors → primitives}/$action.ts +13 -13
  235. package/src/server/{descriptors → primitives}/$route.ts +9 -9
  236. package/src/server/providers/NodeHttpServerProvider.ts +2 -2
  237. package/src/server/services/HttpClient.ts +1 -1
  238. package/src/server-auth/index.browser.ts +1 -1
  239. package/src/server-auth/index.ts +6 -6
  240. package/src/server-auth/{descriptors → primitives}/$auth.ts +10 -10
  241. package/src/server-auth/{descriptors → primitives}/$authCredentials.ts +4 -4
  242. package/src/server-auth/{descriptors → primitives}/$authGithub.ts +4 -4
  243. package/src/server-auth/{descriptors → primitives}/$authGoogle.ts +4 -4
  244. package/src/server-auth/providers/ServerAuthProvider.ts +4 -4
  245. package/src/server-cache/providers/ServerCacheProvider.ts +7 -7
  246. package/src/server-compress/providers/ServerCompressProvider.ts +3 -3
  247. package/src/server-cookies/index.browser.ts +2 -2
  248. package/src/server-cookies/index.ts +5 -5
  249. package/src/server-cookies/{descriptors → primitives}/$cookie.browser.ts +12 -12
  250. package/src/server-cookies/{descriptors → primitives}/$cookie.ts +13 -13
  251. package/src/server-cookies/providers/ServerCookiesProvider.ts +4 -4
  252. package/src/server-cookies/services/CookieParser.ts +1 -1
  253. package/src/server-cors/index.ts +3 -3
  254. package/src/server-cors/{descriptors → primitives}/$cors.ts +11 -13
  255. package/src/server-cors/providers/ServerCorsProvider.ts +5 -5
  256. package/src/server-links/index.browser.ts +5 -5
  257. package/src/server-links/index.ts +9 -9
  258. package/src/server-links/{descriptors → primitives}/$remote.ts +11 -11
  259. package/src/server-links/providers/LinkProvider.ts +7 -7
  260. package/src/server-links/providers/{RemoteDescriptorProvider.ts → RemotePrimitiveProvider.ts} +6 -6
  261. package/src/server-links/providers/ServerLinksProvider.ts +3 -3
  262. package/src/server-proxy/index.ts +3 -3
  263. package/src/server-proxy/{descriptors → primitives}/$proxy.ts +8 -8
  264. package/src/server-proxy/providers/ServerProxyProvider.ts +4 -4
  265. package/src/server-rate-limit/index.ts +6 -6
  266. package/src/server-rate-limit/{descriptors → primitives}/$rateLimit.ts +13 -13
  267. package/src/server-rate-limit/providers/ServerRateLimitProvider.ts +5 -5
  268. package/src/server-security/index.ts +3 -3
  269. package/src/server-security/{descriptors → primitives}/$basicAuth.ts +13 -13
  270. package/src/server-security/providers/ServerBasicAuthProvider.ts +5 -5
  271. package/src/server-security/providers/ServerSecurityProvider.ts +4 -4
  272. package/src/server-static/index.ts +3 -3
  273. package/src/server-static/{descriptors → primitives}/$serve.ts +8 -10
  274. package/src/server-static/providers/ServerStaticProvider.ts +6 -6
  275. package/src/server-swagger/index.ts +5 -5
  276. package/src/server-swagger/{descriptors → primitives}/$swagger.ts +9 -9
  277. package/src/server-swagger/providers/ServerSwaggerProvider.ts +11 -10
  278. package/src/sms/index.ts +4 -4
  279. package/src/sms/{descriptors → primitives}/$sms.ts +8 -8
  280. package/src/thread/index.ts +3 -3
  281. package/src/thread/{descriptors → primitives}/$thread.ts +13 -13
  282. package/src/thread/providers/ThreadProvider.ts +7 -9
  283. package/src/topic/index.ts +5 -5
  284. package/src/topic/{descriptors → primitives}/$subscriber.ts +14 -14
  285. package/src/topic/{descriptors → primitives}/$topic.ts +10 -10
  286. package/src/topic/providers/TopicProvider.ts +4 -4
  287. package/src/vite/helpers/boot.ts +3 -3
  288. package/src/vite/tasks/copyAssets.ts +1 -1
  289. package/src/vite/tasks/generateSitemap.ts +3 -3
  290. package/src/vite/tasks/prerenderPages.ts +2 -2
  291. package/src/vite/tasks/runAlepha.ts +2 -2
  292. package/src/websocket/index.browser.ts +3 -3
  293. package/src/websocket/index.shared.ts +2 -2
  294. package/src/websocket/index.ts +4 -4
  295. package/src/websocket/interfaces/WebSocketInterfaces.ts +3 -3
  296. package/src/websocket/{descriptors → primitives}/$channel.ts +10 -10
  297. package/src/websocket/{descriptors → primitives}/$websocket.ts +8 -8
  298. package/src/websocket/providers/NodeWebSocketServerProvider.ts +7 -7
  299. package/src/websocket/providers/WebSocketServerProvider.ts +3 -3
  300. package/src/websocket/services/WebSocketClient.ts +5 -5
  301. package/dist/api-files/index.cjs +0 -1293
  302. package/dist/api-files/index.cjs.map +0 -1
  303. package/dist/api-files/index.d.cts +0 -829
  304. package/dist/api-jobs/index.cjs +0 -274
  305. package/dist/api-jobs/index.cjs.map +0 -1
  306. package/dist/api-jobs/index.d.cts +0 -654
  307. package/dist/api-notifications/index.cjs +0 -380
  308. package/dist/api-notifications/index.cjs.map +0 -1
  309. package/dist/api-notifications/index.d.cts +0 -289
  310. package/dist/api-parameters/index.cjs +0 -66
  311. package/dist/api-parameters/index.cjs.map +0 -1
  312. package/dist/api-parameters/index.d.cts +0 -84
  313. package/dist/api-users/index.cjs +0 -6009
  314. package/dist/api-users/index.cjs.map +0 -1
  315. package/dist/api-users/index.d.cts +0 -4740
  316. package/dist/api-verifications/index.cjs +0 -407
  317. package/dist/api-verifications/index.cjs.map +0 -1
  318. package/dist/api-verifications/index.d.cts +0 -207
  319. package/dist/batch/index.cjs +0 -408
  320. package/dist/batch/index.cjs.map +0 -1
  321. package/dist/batch/index.d.cts +0 -330
  322. package/dist/bin/index.cjs +0 -17
  323. package/dist/bin/index.cjs.map +0 -1
  324. package/dist/bin/index.d.cts +0 -1
  325. package/dist/bucket/index.cjs +0 -303
  326. package/dist/bucket/index.cjs.map +0 -1
  327. package/dist/bucket/index.d.cts +0 -355
  328. package/dist/cache/index.cjs +0 -241
  329. package/dist/cache/index.cjs.map +0 -1
  330. package/dist/cache/index.d.cts +0 -202
  331. package/dist/cache-redis/index.cjs +0 -84
  332. package/dist/cache-redis/index.cjs.map +0 -1
  333. package/dist/cache-redis/index.d.cts +0 -40
  334. package/dist/cli/chunk-DSlc6foC.cjs +0 -43
  335. package/dist/cli/dist-BBPjuQ56.js +0 -2778
  336. package/dist/cli/dist-Sz2EXvQX.cjs.map +0 -1
  337. package/dist/cli/index.cjs +0 -1241
  338. package/dist/cli/index.cjs.map +0 -1
  339. package/dist/cli/index.d.cts +0 -422
  340. package/dist/command/index.cjs +0 -693
  341. package/dist/command/index.cjs.map +0 -1
  342. package/dist/command/index.d.cts +0 -340
  343. package/dist/core/index.cjs.map +0 -1
  344. package/dist/core/index.d.cts +0 -1927
  345. package/dist/datetime/index.cjs +0 -318
  346. package/dist/datetime/index.cjs.map +0 -1
  347. package/dist/datetime/index.d.cts +0 -145
  348. package/dist/email/index.cjs +0 -10874
  349. package/dist/email/index.cjs.map +0 -1
  350. package/dist/email/index.d.cts +0 -186
  351. package/dist/fake/index.cjs +0 -34641
  352. package/dist/fake/index.cjs.map +0 -1
  353. package/dist/fake/index.d.cts +0 -74
  354. package/dist/file/index.cjs +0 -1212
  355. package/dist/file/index.cjs.map +0 -1
  356. package/dist/file/index.d.cts +0 -698
  357. package/dist/lock/index.cjs +0 -226
  358. package/dist/lock/index.cjs.map +0 -1
  359. package/dist/lock/index.d.cts +0 -361
  360. package/dist/lock-redis/index.cjs +0 -113
  361. package/dist/lock-redis/index.cjs.map +0 -1
  362. package/dist/lock-redis/index.d.cts +0 -24
  363. package/dist/logger/index.cjs +0 -521
  364. package/dist/logger/index.cjs.map +0 -1
  365. package/dist/logger/index.d.cts +0 -281
  366. package/dist/orm/index.cjs +0 -2986
  367. package/dist/orm/index.cjs.map +0 -1
  368. package/dist/orm/index.d.cts +0 -2213
  369. package/dist/queue/index.cjs +0 -1044
  370. package/dist/queue/index.cjs.map +0 -1
  371. package/dist/queue/index.d.cts +0 -1265
  372. package/dist/queue-redis/index.cjs +0 -873
  373. package/dist/queue-redis/index.cjs.map +0 -1
  374. package/dist/queue-redis/index.d.cts +0 -82
  375. package/dist/redis/index.cjs +0 -153
  376. package/dist/redis/index.cjs.map +0 -1
  377. package/dist/redis/index.d.cts +0 -82
  378. package/dist/retry/index.cjs +0 -146
  379. package/dist/retry/index.cjs.map +0 -1
  380. package/dist/retry/index.d.cts +0 -172
  381. package/dist/router/index.cjs +0 -111
  382. package/dist/router/index.cjs.map +0 -1
  383. package/dist/router/index.d.cts +0 -46
  384. package/dist/scheduler/index.cjs +0 -576
  385. package/dist/scheduler/index.cjs.map +0 -1
  386. package/dist/scheduler/index.d.cts +0 -145
  387. package/dist/security/index.cjs +0 -2402
  388. package/dist/security/index.cjs.map +0 -1
  389. package/dist/security/index.d.cts +0 -598
  390. package/dist/server/index.cjs +0 -1680
  391. package/dist/server/index.cjs.map +0 -1
  392. package/dist/server/index.d.cts +0 -810
  393. package/dist/server-auth/index.cjs +0 -3146
  394. package/dist/server-auth/index.cjs.map +0 -1
  395. package/dist/server-auth/index.d.cts +0 -1164
  396. package/dist/server-cache/index.cjs +0 -252
  397. package/dist/server-cache/index.cjs.map +0 -1
  398. package/dist/server-cache/index.d.cts +0 -164
  399. package/dist/server-compress/index.cjs +0 -141
  400. package/dist/server-compress/index.cjs.map +0 -1
  401. package/dist/server-compress/index.d.cts +0 -38
  402. package/dist/server-cookies/index.cjs +0 -234
  403. package/dist/server-cookies/index.cjs.map +0 -1
  404. package/dist/server-cookies/index.d.cts +0 -144
  405. package/dist/server-cors/index.cjs +0 -201
  406. package/dist/server-cors/index.cjs.map +0 -1
  407. package/dist/server-cors/index.d.cts +0 -140
  408. package/dist/server-health/index.cjs +0 -62
  409. package/dist/server-health/index.cjs.map +0 -1
  410. package/dist/server-health/index.d.cts +0 -58
  411. package/dist/server-helmet/index.cjs +0 -131
  412. package/dist/server-helmet/index.cjs.map +0 -1
  413. package/dist/server-helmet/index.d.cts +0 -97
  414. package/dist/server-links/index.cjs +0 -992
  415. package/dist/server-links/index.cjs.map +0 -1
  416. package/dist/server-links/index.d.cts +0 -513
  417. package/dist/server-metrics/index.cjs +0 -4535
  418. package/dist/server-metrics/index.cjs.map +0 -1
  419. package/dist/server-metrics/index.d.cts +0 -35
  420. package/dist/server-multipart/index.cjs +0 -237
  421. package/dist/server-multipart/index.cjs.map +0 -1
  422. package/dist/server-multipart/index.d.cts +0 -50
  423. package/dist/server-proxy/index.cjs +0 -186
  424. package/dist/server-proxy/index.cjs.map +0 -1
  425. package/dist/server-proxy/index.d.cts +0 -234
  426. package/dist/server-rate-limit/index.cjs +0 -241
  427. package/dist/server-rate-limit/index.cjs.map +0 -1
  428. package/dist/server-rate-limit/index.d.cts +0 -183
  429. package/dist/server-security/index.cjs +0 -316
  430. package/dist/server-security/index.cjs.map +0 -1
  431. package/dist/server-security/index.d.cts +0 -173
  432. package/dist/server-static/index.cjs +0 -170
  433. package/dist/server-static/index.cjs.map +0 -1
  434. package/dist/server-static/index.d.cts +0 -121
  435. package/dist/server-swagger/index.cjs +0 -1021
  436. package/dist/server-swagger/index.cjs.map +0 -1
  437. package/dist/server-swagger/index.d.cts +0 -382
  438. package/dist/sms/index.cjs +0 -221
  439. package/dist/sms/index.cjs.map +0 -1
  440. package/dist/sms/index.d.cts +0 -130
  441. package/dist/thread/index.cjs +0 -350
  442. package/dist/thread/index.cjs.map +0 -1
  443. package/dist/thread/index.d.cts +0 -260
  444. package/dist/topic/index.cjs +0 -282
  445. package/dist/topic/index.cjs.map +0 -1
  446. package/dist/topic/index.d.cts +0 -523
  447. package/dist/topic-redis/index.cjs +0 -71
  448. package/dist/topic-redis/index.cjs.map +0 -1
  449. package/dist/topic-redis/index.d.cts +0 -42
  450. package/dist/vite/index.cjs +0 -1077
  451. package/dist/vite/index.cjs.map +0 -1
  452. package/dist/vite/index.d.cts +0 -542
  453. package/dist/websocket/index.cjs +0 -1117
  454. package/dist/websocket/index.cjs.map +0 -1
  455. package/dist/websocket/index.d.cts +0 -861
  456. package/src/api-notifications/providers/MemorySmsProvider.ts +0 -20
  457. package/src/api-notifications/providers/SmsProvider.ts +0 -8
  458. /package/src/core/{descriptors → primitives}/$atom.ts +0 -0
  459. /package/src/core/{descriptors → primitives}/$env.ts +0 -0
  460. /package/src/server-auth/{descriptors → primitives}/$authApple.ts +0 -0
  461. /package/src/server-links/{descriptors → primitives}/$client.ts +0 -0
@@ -1,350 +0,0 @@
1
- let alepha = require("alepha");
2
- let node_os = require("node:os");
3
- let node_worker_threads = require("node:worker_threads");
4
- let alepha_logger = require("alepha/logger");
5
-
6
- //#region src/thread/descriptors/$thread.ts
7
- /**
8
- * Creates a worker thread descriptor for offloading CPU-intensive tasks to separate threads.
9
- *
10
- * This descriptor enables you to run JavaScript code in Node.js worker threads, allowing you to
11
- * leverage multiple CPU cores and avoid blocking the main event loop. It provides a pool-based
12
- * approach with intelligent thread reuse and automatic lifecycle management.
13
- *
14
- * **Key Features**
15
- *
16
- * - **Thread Pool Management**: Automatically manages a pool of worker threads with configurable limits
17
- * - **Thread Reuse**: Reuses existing threads to avoid expensive initialization overhead
18
- * - **Idle Cleanup**: Automatically terminates unused threads after a configurable timeout
19
- * - **Type-Safe Communication**: Optional TypeBox schema validation for data passed to threads
20
- * - **CPU-Aware Defaults**: Pool size defaults to CPU count × 2 for optimal performance
21
- * - **Error Handling**: Proper error propagation and thread cleanup on failures
22
- *
23
- * **Use Cases**
24
- *
25
- * Perfect for CPU-intensive tasks that would otherwise block the main thread:
26
- * - Image/video processing
27
- * - Data transformation and analysis
28
- * - Cryptographic operations
29
- * - Heavy computations and algorithms
30
- * - Background data processing
31
- *
32
- * @example
33
- * **Basic thread usage:**
34
- * ```ts
35
- * import { $thread } from "alepha/thread";
36
- *
37
- * class DataProcessor {
38
- * heavyComputation = $thread({
39
- * name: "compute",
40
- * handler: async () => {
41
- * // This runs in a separate worker thread
42
- * let result = 0;
43
- * for (let i = 0; i < 1000000; i++) {
44
- * result += Math.sqrt(i);
45
- * }
46
- * return { result, timestamp: Date.now() };
47
- * }
48
- * });
49
- *
50
- * async processData() {
51
- * // Execute in worker thread without blocking main thread
52
- * const result = await this.heavyComputation.execute();
53
- * console.log(`Computation result: ${result.result}`);
54
- * }
55
- * }
56
- * ```
57
- *
58
- * @example
59
- * **Configured thread pool with custom settings:**
60
- * ```ts
61
- * class ImageProcessor {
62
- * imageProcessor = $thread({
63
- * name: "image-processing",
64
- * maxPoolSize: 4, // Limit to 4 concurrent threads
65
- * idleTimeout: 30000, // Clean up idle threads after 30 seconds
66
- * handler: async () => {
67
- * // CPU-intensive image processing logic
68
- * return await processImageData();
69
- * }
70
- * });
71
- * }
72
- * ```
73
- *
74
- * @example
75
- * **Thread with data validation:**
76
- * ```ts
77
- * import { t } from "alepha";
78
- *
79
- * class CryptoService {
80
- * encrypt = $thread({
81
- * name: "encryption",
82
- * handler: async () => {
83
- * // Perform encryption operations
84
- * return await encryptData();
85
- * }
86
- * });
87
- *
88
- * async encryptSensitiveData(data: { text: string; key: string }) {
89
- * // Validate input data before sending to thread
90
- * const schema = t.object({
91
- * text: t.text(),
92
- * key: t.text()
93
- * });
94
- *
95
- * return await this.encrypt.execute(data, schema);
96
- * }
97
- * }
98
- * ```
99
- *
100
- * @example
101
- * **Parallel processing with multiple threads:**
102
- * ```ts
103
- * class BatchProcessor {
104
- * processor = $thread({
105
- * name: "batch-worker",
106
- * maxPoolSize: 8, // Allow up to 8 concurrent workers
107
- * handler: async () => {
108
- * return await processBatchItem();
109
- * }
110
- * });
111
- *
112
- * async processBatch(items: any[]) {
113
- * // Process multiple items in parallel across different threads
114
- * const promises = items.map(() => this.processor.execute());
115
- * const results = await Promise.all(promises);
116
- * return results;
117
- * }
118
- * }
119
- * ```
120
- */
121
- const $thread = (options) => {
122
- return (0, alepha.createDescriptor)(ThreadDescriptor, options);
123
- };
124
- var ThreadDescriptor = class ThreadDescriptor extends alepha.Descriptor {
125
- script = process.argv[1];
126
- static globalPool = /* @__PURE__ */ new Map();
127
- get name() {
128
- return this.options.name || this.config.propertyKey;
129
- }
130
- get maxPoolSize() {
131
- return this.options.maxPoolSize || (0, node_os.cpus)().length * 2;
132
- }
133
- get idleTimeout() {
134
- return this.options.idleTimeout || 6e4;
135
- }
136
- getPool() {
137
- if (!ThreadDescriptor.globalPool.has(this.name)) ThreadDescriptor.globalPool.set(this.name, new ThreadPool(this.name, this.maxPoolSize, this.idleTimeout, this.script));
138
- return ThreadDescriptor.globalPool.get(this.name);
139
- }
140
- async execute(data, schema) {
141
- if (schema && data) try {
142
- alepha.TypeBoxValue.Decode(schema, data);
143
- } catch (error) {
144
- throw new Error(`Invalid data: ${error instanceof Error ? error.message : error}`);
145
- }
146
- return await this.getPool().execute(data);
147
- }
148
- async create() {
149
- await this.getPool().warmUp();
150
- }
151
- async terminate() {
152
- await this.getPool().terminate();
153
- ThreadDescriptor.globalPool.delete(this.name);
154
- }
155
- };
156
- $thread[alepha.KIND] = ThreadDescriptor;
157
- var ThreadPool = class {
158
- instances = [];
159
- queue = [];
160
- idleTimer;
161
- constructor(name, maxPoolSize, idleTimeout, script) {
162
- this.name = name;
163
- this.maxPoolSize = maxPoolSize;
164
- this.idleTimeout = idleTimeout;
165
- this.script = script;
166
- }
167
- async warmUp() {
168
- if (this.instances.length === 0) await this.createInstance();
169
- }
170
- async createInstance() {
171
- const { port1, port2 } = new node_worker_threads.MessageChannel();
172
- const worker = new node_worker_threads.Worker(this.script, {
173
- env: {
174
- ...process.env,
175
- ALEPHA_WORKER: this.name,
176
- APP_NAME: "WORKER"
177
- },
178
- workerData: { port: port2 },
179
- transferList: [port2]
180
- });
181
- const instance = {
182
- worker,
183
- port: port1,
184
- busy: false,
185
- lastUsed: Date.now(),
186
- pendingMessages: /* @__PURE__ */ new Map()
187
- };
188
- instance.port.on("message", (message) => {
189
- if (message.type === "response" || message.type === "error") {
190
- const pending = instance.pendingMessages.get(message.id);
191
- if (pending) {
192
- instance.pendingMessages.delete(message.id);
193
- instance.busy = false;
194
- instance.lastUsed = Date.now();
195
- if (message.type === "error") pending.reject(new Error(message.error));
196
- else pending.resolve(message.data);
197
- this.processQueue();
198
- }
199
- }
200
- });
201
- await new Promise((resolve, reject) => {
202
- const timeout = setTimeout(() => reject(/* @__PURE__ */ new Error("Thread initialization timeout")), 5e3);
203
- worker.once("online", () => {
204
- clearTimeout(timeout);
205
- resolve();
206
- });
207
- worker.once("error", (error) => {
208
- clearTimeout(timeout);
209
- reject(error);
210
- });
211
- });
212
- this.instances.push(instance);
213
- this.resetIdleTimer();
214
- return instance;
215
- }
216
- async execute(data) {
217
- return new Promise((resolve, reject) => {
218
- this.queue.push({
219
- data,
220
- resolve,
221
- reject
222
- });
223
- this.processQueue();
224
- });
225
- }
226
- async processQueue() {
227
- if (this.queue.length === 0) return;
228
- let instance = this.instances.find((i) => !i.busy);
229
- if (!instance && this.instances.length < this.maxPoolSize) try {
230
- instance = await this.createInstance();
231
- } catch (error) {
232
- const { reject: reject$1 } = this.queue.shift();
233
- reject$1(error instanceof Error ? error : /* @__PURE__ */ new Error("Failed to create thread instance"));
234
- return;
235
- }
236
- if (!instance) return;
237
- const { data, resolve, reject } = this.queue.shift();
238
- const messageId = `${Date.now()}-${Math.random()}`;
239
- instance.busy = true;
240
- instance.pendingMessages.set(messageId, {
241
- resolve,
242
- reject
243
- });
244
- const message = {
245
- id: messageId,
246
- type: "execute",
247
- data
248
- };
249
- instance.port.postMessage(message);
250
- }
251
- resetIdleTimer() {
252
- if (this.idleTimer) clearTimeout(this.idleTimer);
253
- this.idleTimer = setTimeout(() => {
254
- this.cleanupIdleInstances();
255
- }, this.idleTimeout);
256
- }
257
- cleanupIdleInstances() {
258
- const now = Date.now();
259
- const instancesToRemove = this.instances.filter((instance) => !instance.busy && now - instance.lastUsed > this.idleTimeout);
260
- for (const instance of instancesToRemove) {
261
- const index = this.instances.indexOf(instance);
262
- if (index > -1) {
263
- this.instances.splice(index, 1);
264
- instance.port.close();
265
- instance.worker.terminate();
266
- }
267
- }
268
- if (this.instances.length > 0) this.resetIdleTimer();
269
- }
270
- async terminate() {
271
- if (this.idleTimer) clearTimeout(this.idleTimer);
272
- await Promise.all(this.instances.map(async (instance) => {
273
- instance.port.close();
274
- await instance.worker.terminate();
275
- }));
276
- this.instances = [];
277
- this.queue = [];
278
- }
279
- };
280
-
281
- //#endregion
282
- //#region src/thread/providers/ThreadProvider.ts
283
- var ThreadProvider = class {
284
- log = (0, alepha_logger.$logger)();
285
- env = (0, alepha.$env)(alepha.t.object({ ALEPHA_WORKER: alepha.t.optional(alepha.t.text()) }));
286
- ready = (0, alepha.$hook)({
287
- on: "ready",
288
- handler: async (alepha$1) => {
289
- const worker = this.env.ALEPHA_WORKER;
290
- if (!worker) return;
291
- const threadDescriptor = alepha$1.descriptors($thread).find((thread) => thread.name === worker);
292
- if (!threadDescriptor) {
293
- this.log.error(`Thread not found: ${worker}`);
294
- return;
295
- }
296
- this.log.info(`Thread ready: ${threadDescriptor.name}`);
297
- const communicationPort = node_worker_threads.workerData?.port || node_worker_threads.parentPort;
298
- if (!communicationPort) {
299
- this.log.error("No communication port available");
300
- return;
301
- }
302
- communicationPort.on("message", async (message) => {
303
- if (message.type === "execute") try {
304
- this.log.debug(`Executing thread handler: ${threadDescriptor.name}`);
305
- const result = await threadDescriptor.options.handler();
306
- communicationPort.postMessage({
307
- id: message.id,
308
- type: "response",
309
- data: result
310
- });
311
- } catch (error) {
312
- this.log.error(`Thread execution error: ${error}`);
313
- communicationPort.postMessage({
314
- id: message.id,
315
- type: "error",
316
- error: error instanceof Error ? error.message : String(error)
317
- });
318
- }
319
- });
320
- communicationPort.postMessage({ type: "ready" });
321
- }
322
- });
323
- static async cleanup() {
324
- if (node_worker_threads.parentPort) node_worker_threads.parentPort.removeAllListeners();
325
- }
326
- };
327
-
328
- //#endregion
329
- //#region src/thread/index.ts
330
- alepha.Alepha.prototype.isWorkerThread = function() {
331
- return !!this.env.ALEPHA_WORKER;
332
- };
333
- /**
334
- * Simple interface for managing worker threads in Alepha.
335
- *
336
- * @see {@link $thread}
337
- * @module alepha.thread
338
- */
339
- const AlephaThread = (0, alepha.$module)({
340
- name: "alepha.thread",
341
- descriptors: [$thread],
342
- services: [ThreadProvider]
343
- });
344
-
345
- //#endregion
346
- exports.$thread = $thread;
347
- exports.AlephaThread = AlephaThread;
348
- exports.ThreadDescriptor = ThreadDescriptor;
349
- exports.ThreadProvider = ThreadProvider;
350
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","names":["Descriptor","KIND","name: string","maxPoolSize: number","idleTimeout: number","script: string","MessageChannel","Worker","instance: ThreadInstance","message: ThreadMessage","t","alepha","workerData","parentPort"],"sources":["../../src/thread/descriptors/$thread.ts","../../src/thread/providers/ThreadProvider.ts","../../src/thread/index.ts"],"sourcesContent":["import { cpus } from \"node:os\";\nimport { MessageChannel, type MessagePort, Worker } from \"node:worker_threads\";\nimport type { TSchema } from \"alepha\";\nimport { createDescriptor, Descriptor, KIND, TypeBoxValue } from \"alepha\";\n\n/**\n * Creates a worker thread descriptor for offloading CPU-intensive tasks to separate threads.\n *\n * This descriptor enables you to run JavaScript code in Node.js worker threads, allowing you to\n * leverage multiple CPU cores and avoid blocking the main event loop. It provides a pool-based\n * approach with intelligent thread reuse and automatic lifecycle management.\n *\n * **Key Features**\n *\n * - **Thread Pool Management**: Automatically manages a pool of worker threads with configurable limits\n * - **Thread Reuse**: Reuses existing threads to avoid expensive initialization overhead\n * - **Idle Cleanup**: Automatically terminates unused threads after a configurable timeout\n * - **Type-Safe Communication**: Optional TypeBox schema validation for data passed to threads\n * - **CPU-Aware Defaults**: Pool size defaults to CPU count × 2 for optimal performance\n * - **Error Handling**: Proper error propagation and thread cleanup on failures\n *\n * **Use Cases**\n *\n * Perfect for CPU-intensive tasks that would otherwise block the main thread:\n * - Image/video processing\n * - Data transformation and analysis\n * - Cryptographic operations\n * - Heavy computations and algorithms\n * - Background data processing\n *\n * @example\n * **Basic thread usage:**\n * ```ts\n * import { $thread } from \"alepha/thread\";\n *\n * class DataProcessor {\n * heavyComputation = $thread({\n * name: \"compute\",\n * handler: async () => {\n * // This runs in a separate worker thread\n * let result = 0;\n * for (let i = 0; i < 1000000; i++) {\n * result += Math.sqrt(i);\n * }\n * return { result, timestamp: Date.now() };\n * }\n * });\n *\n * async processData() {\n * // Execute in worker thread without blocking main thread\n * const result = await this.heavyComputation.execute();\n * console.log(`Computation result: ${result.result}`);\n * }\n * }\n * ```\n *\n * @example\n * **Configured thread pool with custom settings:**\n * ```ts\n * class ImageProcessor {\n * imageProcessor = $thread({\n * name: \"image-processing\",\n * maxPoolSize: 4, // Limit to 4 concurrent threads\n * idleTimeout: 30000, // Clean up idle threads after 30 seconds\n * handler: async () => {\n * // CPU-intensive image processing logic\n * return await processImageData();\n * }\n * });\n * }\n * ```\n *\n * @example\n * **Thread with data validation:**\n * ```ts\n * import { t } from \"alepha\";\n *\n * class CryptoService {\n * encrypt = $thread({\n * name: \"encryption\",\n * handler: async () => {\n * // Perform encryption operations\n * return await encryptData();\n * }\n * });\n *\n * async encryptSensitiveData(data: { text: string; key: string }) {\n * // Validate input data before sending to thread\n * const schema = t.object({\n * text: t.text(),\n * key: t.text()\n * });\n *\n * return await this.encrypt.execute(data, schema);\n * }\n * }\n * ```\n *\n * @example\n * **Parallel processing with multiple threads:**\n * ```ts\n * class BatchProcessor {\n * processor = $thread({\n * name: \"batch-worker\",\n * maxPoolSize: 8, // Allow up to 8 concurrent workers\n * handler: async () => {\n * return await processBatchItem();\n * }\n * });\n *\n * async processBatch(items: any[]) {\n * // Process multiple items in parallel across different threads\n * const promises = items.map(() => this.processor.execute());\n * const results = await Promise.all(promises);\n * return results;\n * }\n * }\n * ```\n */\nexport const $thread = (options: ThreadDescriptorOptions): ThreadDescriptor => {\n return createDescriptor(ThreadDescriptor, options);\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport interface ThreadDescriptorOptions {\n /**\n * Unique name for this thread worker.\n *\n * Used for:\n * - Thread pool identification (threads with same name share the same pool)\n * - Logging and debugging\n * - Error messages and stack traces\n *\n * If not provided, defaults to the property key of the descriptor.\n *\n * @example \"image-processor\"\n * @example \"crypto-worker\"\n * @example \"data-analysis\"\n */\n name?: string;\n\n /**\n * The function to execute in the worker thread.\n *\n * This function:\n * - Runs in a separate Node.js worker thread\n * - Should contain the CPU-intensive logic\n * - Can be async and return any serializable data\n * - Has access to standard Node.js APIs and modules\n * - Cannot directly access the main thread's memory or variables\n *\n * **Important**: The handler function is serialized and sent to the worker thread,\n * so it cannot reference variables from the parent scope (closures won't work).\n * All required data must be passed via the `execute()` method.\n *\n * @example\n * ```ts\n * handler: async () => {\n * // CPU-intensive work here\n * const result = performComplexCalculation();\n * return { result, completed: Date.now() };\n * }\n * ```\n */\n handler: () => any | Promise<any>;\n\n /**\n * Maximum number of worker threads in the pool.\n *\n * Controls how many threads can run concurrently for this named thread worker.\n * When all threads are busy, additional `execute()` calls will queue until a thread becomes available.\n *\n * **Default**: `cpus().length * 2` (number of CPU cores × 2)\n *\n * **Guidelines**:\n * - For CPU-bound tasks: Set to number of CPU cores\n * - For I/O-bound tasks in workers: Can be higher (2x CPU cores)\n * - For memory-intensive tasks: Set lower to avoid memory pressure\n * - For short-lived tasks: Can be higher for better throughput\n *\n * @default cpus().length * 2\n * @example 4 // Limit to 4 concurrent threads\n * @example 1 // Single worker thread (sequential processing)\n * @example 16 // High concurrency for lightweight tasks\n */\n maxPoolSize?: number;\n\n /**\n * Time in milliseconds before idle worker threads are terminated.\n *\n * When a worker thread has been idle (not executing any tasks) for this duration,\n * it will be automatically terminated to free up system resources. New threads\n * will be created as needed when new tasks are submitted.\n *\n * **Default**: 60000 (60 seconds)\n *\n * **Considerations**:\n * - Shorter timeouts: Save memory but increase thread creation overhead\n * - Longer timeouts: Keep threads ready but consume more memory\n * - Very short timeouts may cause constant thread creation/destruction\n *\n * @default 60000\n * @example 30000 // 30 seconds\n * @example 120000 // 2 minutes\n * @example 5000 // 5 seconds (for very memory-constrained environments)\n */\n idleTimeout?: number;\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport class ThreadDescriptor extends Descriptor<ThreadDescriptorOptions> {\n protected readonly script = process.argv[1];\n static readonly globalPool = new Map<string, ThreadPool>();\n\n public get name(): string {\n return this.options.name || this.config.propertyKey;\n }\n\n public get maxPoolSize(): number {\n return this.options.maxPoolSize || cpus().length * 2;\n }\n\n public get idleTimeout(): number {\n return this.options.idleTimeout || 60000; // 1 minute default\n }\n\n private getPool(): ThreadPool {\n if (!ThreadDescriptor.globalPool.has(this.name)) {\n ThreadDescriptor.globalPool.set(\n this.name,\n new ThreadPool(\n this.name,\n this.maxPoolSize,\n this.idleTimeout,\n this.script,\n ),\n );\n }\n return ThreadDescriptor.globalPool.get(this.name)!;\n }\n\n public async execute<T = any>(data?: any, schema?: TSchema): Promise<T> {\n if (schema && data) {\n try {\n TypeBoxValue.Decode(schema, data);\n } catch (error) {\n throw new Error(\n `Invalid data: ${error instanceof Error ? error.message : error}`,\n );\n }\n }\n\n const pool = this.getPool();\n return await pool.execute<T>(data);\n }\n\n public async create(): Promise<void> {\n const pool = this.getPool();\n await pool.warmUp();\n }\n\n public async terminate(): Promise<void> {\n const pool = this.getPool();\n await pool.terminate();\n ThreadDescriptor.globalPool.delete(this.name);\n }\n}\n\n$thread[KIND] = ThreadDescriptor;\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ninterface ThreadMessage<T = any> {\n id: string;\n type: \"execute\" | \"response\" | \"error\";\n data?: T;\n error?: string;\n}\n\ninterface ThreadInstance {\n worker: Worker;\n port: MessagePort;\n busy: boolean;\n lastUsed: number;\n pendingMessages: Map<\n string,\n { resolve: (value: any) => void; reject: (error: Error) => void }\n >;\n}\n\nclass ThreadPool {\n private instances: ThreadInstance[] = [];\n private queue: Array<{\n data: any;\n resolve: (value: any) => void;\n reject: (error: Error) => void;\n }> = [];\n private idleTimer?: NodeJS.Timeout;\n\n constructor(\n private readonly name: string,\n private readonly maxPoolSize: number,\n private readonly idleTimeout: number,\n private readonly script: string,\n ) {}\n\n async warmUp(): Promise<void> {\n if (this.instances.length === 0) {\n await this.createInstance();\n }\n }\n\n private async createInstance(): Promise<ThreadInstance> {\n const { port1, port2 } = new MessageChannel();\n\n const worker = new Worker(this.script, {\n env: {\n ...process.env,\n ALEPHA_WORKER: this.name,\n APP_NAME: \"WORKER\",\n },\n workerData: { port: port2 },\n transferList: [port2],\n });\n\n const instance: ThreadInstance = {\n worker,\n port: port1,\n busy: false,\n lastUsed: Date.now(),\n pendingMessages: new Map(),\n };\n\n instance.port.on(\"message\", (message: ThreadMessage) => {\n if (message.type === \"response\" || message.type === \"error\") {\n const pending = instance.pendingMessages.get(message.id);\n if (pending) {\n instance.pendingMessages.delete(message.id);\n instance.busy = false;\n instance.lastUsed = Date.now();\n\n if (message.type === \"error\") {\n pending.reject(new Error(message.error));\n } else {\n pending.resolve(message.data);\n }\n\n this.processQueue();\n }\n }\n });\n\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(\n () => reject(new Error(\"Thread initialization timeout\")),\n 5000,\n );\n\n worker.once(\"online\", () => {\n clearTimeout(timeout);\n resolve();\n });\n\n worker.once(\"error\", (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n });\n\n this.instances.push(instance);\n this.resetIdleTimer();\n\n return instance;\n }\n\n async execute<T = any>(data?: any): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.queue.push({ data, resolve, reject });\n this.processQueue();\n });\n }\n\n private async processQueue(): Promise<void> {\n if (this.queue.length === 0) {\n return;\n }\n\n let instance = this.instances.find((i) => !i.busy);\n\n if (!instance && this.instances.length < this.maxPoolSize) {\n try {\n instance = await this.createInstance();\n } catch (error) {\n const { reject } = this.queue.shift()!;\n reject(\n error instanceof Error\n ? error\n : new Error(\"Failed to create thread instance\"),\n );\n return;\n }\n }\n\n if (!instance) {\n return; // Wait for an instance to become available\n }\n\n const { data, resolve, reject } = this.queue.shift()!;\n const messageId = `${Date.now()}-${Math.random()}`;\n\n instance.busy = true;\n instance.pendingMessages.set(messageId, { resolve, reject });\n\n const message: ThreadMessage = {\n id: messageId,\n type: \"execute\",\n data,\n };\n\n instance.port.postMessage(message);\n }\n\n private resetIdleTimer(): void {\n if (this.idleTimer) {\n clearTimeout(this.idleTimer);\n }\n\n this.idleTimer = setTimeout(() => {\n this.cleanupIdleInstances();\n }, this.idleTimeout);\n }\n\n private cleanupIdleInstances(): void {\n const now = Date.now();\n const instancesToRemove = this.instances.filter(\n (instance) =>\n !instance.busy && now - instance.lastUsed > this.idleTimeout,\n );\n\n for (const instance of instancesToRemove) {\n const index = this.instances.indexOf(instance);\n if (index > -1) {\n this.instances.splice(index, 1);\n instance.port.close();\n void instance.worker.terminate();\n }\n }\n\n if (this.instances.length > 0) {\n this.resetIdleTimer();\n }\n }\n\n async terminate(): Promise<void> {\n if (this.idleTimer) {\n clearTimeout(this.idleTimer);\n }\n\n await Promise.all(\n this.instances.map(async (instance) => {\n instance.port.close();\n await instance.worker.terminate();\n }),\n );\n\n this.instances = [];\n this.queue = [];\n }\n}\n\n// ---------------------------------------------------------------------------------------------------------------------\n","import { parentPort, workerData } from \"node:worker_threads\";\nimport { $env, $hook, t } from \"alepha\";\nimport { $logger } from \"alepha/logger\";\nimport { $thread } from \"../descriptors/$thread.ts\";\n\ninterface ThreadMessage<T = any> {\n id: string;\n type: \"execute\" | \"response\" | \"error\" | \"ready\";\n data?: T;\n error?: string;\n}\n\nexport class ThreadProvider {\n protected readonly log = $logger();\n protected readonly env = $env(\n t.object({\n ALEPHA_WORKER: t.optional(t.text()),\n }),\n );\n\n protected readonly ready = $hook({\n on: \"ready\",\n handler: async (alepha) => {\n const worker = this.env.ALEPHA_WORKER;\n if (!worker) {\n return;\n }\n\n const threads = alepha.descriptors($thread);\n const threadDescriptor = threads.find((thread) => thread.name === worker);\n\n if (!threadDescriptor) {\n this.log.error(`Thread not found: ${worker}`);\n return;\n }\n\n this.log.info(`Thread ready: ${threadDescriptor.name}`);\n\n // Use the message channel port from worker data if available, fallback to parentPort\n const communicationPort = workerData?.port || parentPort;\n\n if (!communicationPort) {\n this.log.error(\"No communication port available\");\n return;\n }\n\n // Set up message handling\n communicationPort.on(\"message\", async (message: ThreadMessage) => {\n if (message.type === \"execute\") {\n try {\n this.log.debug(\n `Executing thread handler: ${threadDescriptor.name}`,\n );\n const result = await threadDescriptor.options.handler();\n\n communicationPort.postMessage({\n id: message.id,\n type: \"response\",\n data: result,\n } as ThreadMessage);\n } catch (error) {\n this.log.error(`Thread execution error: ${error}`);\n\n communicationPort.postMessage({\n id: message.id,\n type: \"error\",\n error: error instanceof Error ? error.message : String(error),\n } as ThreadMessage);\n }\n }\n });\n\n // Signal that the worker is ready\n communicationPort.postMessage({ type: \"ready\" } as ThreadMessage);\n },\n });\n\n public static async cleanup(): Promise<void> {\n if (parentPort) {\n parentPort.removeAllListeners();\n }\n }\n}\n","import { $module, Alepha } from \"alepha\";\nimport { $thread } from \"./descriptors/$thread.ts\";\nimport { ThreadProvider } from \"./providers/ThreadProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./descriptors/$thread.ts\";\nexport * from \"./providers/ThreadProvider.ts\";\n\n// ---------------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n interface Alepha {\n isWorkerThread(): boolean;\n }\n}\n\nAlepha.prototype.isWorkerThread = function (this: Alepha): boolean {\n return !!this.env.ALEPHA_WORKER;\n};\n\n// ---------------------------------------------------------------------------------------------------------------------\n\n/**\n * Simple interface for managing worker threads in Alepha.\n *\n * @see {@link $thread}\n * @module alepha.thread\n */\nexport const AlephaThread = $module({\n name: \"alepha.thread\",\n descriptors: [$thread],\n services: [ThreadProvider],\n});\n"],"mappings":"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"}
@@ -1,260 +0,0 @@
1
- import * as alepha1 from "alepha";
2
- import { Descriptor, KIND, TSchema } from "alepha";
3
- import * as alepha_logger0 from "alepha/logger";
4
-
5
- //#region src/thread/descriptors/$thread.d.ts
6
-
7
- /**
8
- * Creates a worker thread descriptor for offloading CPU-intensive tasks to separate threads.
9
- *
10
- * This descriptor enables you to run JavaScript code in Node.js worker threads, allowing you to
11
- * leverage multiple CPU cores and avoid blocking the main event loop. It provides a pool-based
12
- * approach with intelligent thread reuse and automatic lifecycle management.
13
- *
14
- * **Key Features**
15
- *
16
- * - **Thread Pool Management**: Automatically manages a pool of worker threads with configurable limits
17
- * - **Thread Reuse**: Reuses existing threads to avoid expensive initialization overhead
18
- * - **Idle Cleanup**: Automatically terminates unused threads after a configurable timeout
19
- * - **Type-Safe Communication**: Optional TypeBox schema validation for data passed to threads
20
- * - **CPU-Aware Defaults**: Pool size defaults to CPU count × 2 for optimal performance
21
- * - **Error Handling**: Proper error propagation and thread cleanup on failures
22
- *
23
- * **Use Cases**
24
- *
25
- * Perfect for CPU-intensive tasks that would otherwise block the main thread:
26
- * - Image/video processing
27
- * - Data transformation and analysis
28
- * - Cryptographic operations
29
- * - Heavy computations and algorithms
30
- * - Background data processing
31
- *
32
- * @example
33
- * **Basic thread usage:**
34
- * ```ts
35
- * import { $thread } from "alepha/thread";
36
- *
37
- * class DataProcessor {
38
- * heavyComputation = $thread({
39
- * name: "compute",
40
- * handler: async () => {
41
- * // This runs in a separate worker thread
42
- * let result = 0;
43
- * for (let i = 0; i < 1000000; i++) {
44
- * result += Math.sqrt(i);
45
- * }
46
- * return { result, timestamp: Date.now() };
47
- * }
48
- * });
49
- *
50
- * async processData() {
51
- * // Execute in worker thread without blocking main thread
52
- * const result = await this.heavyComputation.execute();
53
- * console.log(`Computation result: ${result.result}`);
54
- * }
55
- * }
56
- * ```
57
- *
58
- * @example
59
- * **Configured thread pool with custom settings:**
60
- * ```ts
61
- * class ImageProcessor {
62
- * imageProcessor = $thread({
63
- * name: "image-processing",
64
- * maxPoolSize: 4, // Limit to 4 concurrent threads
65
- * idleTimeout: 30000, // Clean up idle threads after 30 seconds
66
- * handler: async () => {
67
- * // CPU-intensive image processing logic
68
- * return await processImageData();
69
- * }
70
- * });
71
- * }
72
- * ```
73
- *
74
- * @example
75
- * **Thread with data validation:**
76
- * ```ts
77
- * import { t } from "alepha";
78
- *
79
- * class CryptoService {
80
- * encrypt = $thread({
81
- * name: "encryption",
82
- * handler: async () => {
83
- * // Perform encryption operations
84
- * return await encryptData();
85
- * }
86
- * });
87
- *
88
- * async encryptSensitiveData(data: { text: string; key: string }) {
89
- * // Validate input data before sending to thread
90
- * const schema = t.object({
91
- * text: t.text(),
92
- * key: t.text()
93
- * });
94
- *
95
- * return await this.encrypt.execute(data, schema);
96
- * }
97
- * }
98
- * ```
99
- *
100
- * @example
101
- * **Parallel processing with multiple threads:**
102
- * ```ts
103
- * class BatchProcessor {
104
- * processor = $thread({
105
- * name: "batch-worker",
106
- * maxPoolSize: 8, // Allow up to 8 concurrent workers
107
- * handler: async () => {
108
- * return await processBatchItem();
109
- * }
110
- * });
111
- *
112
- * async processBatch(items: any[]) {
113
- * // Process multiple items in parallel across different threads
114
- * const promises = items.map(() => this.processor.execute());
115
- * const results = await Promise.all(promises);
116
- * return results;
117
- * }
118
- * }
119
- * ```
120
- */
121
- declare const $thread: {
122
- (options: ThreadDescriptorOptions): ThreadDescriptor;
123
- [KIND]: typeof ThreadDescriptor;
124
- };
125
- interface ThreadDescriptorOptions {
126
- /**
127
- * Unique name for this thread worker.
128
- *
129
- * Used for:
130
- * - Thread pool identification (threads with same name share the same pool)
131
- * - Logging and debugging
132
- * - Error messages and stack traces
133
- *
134
- * If not provided, defaults to the property key of the descriptor.
135
- *
136
- * @example "image-processor"
137
- * @example "crypto-worker"
138
- * @example "data-analysis"
139
- */
140
- name?: string;
141
- /**
142
- * The function to execute in the worker thread.
143
- *
144
- * This function:
145
- * - Runs in a separate Node.js worker thread
146
- * - Should contain the CPU-intensive logic
147
- * - Can be async and return any serializable data
148
- * - Has access to standard Node.js APIs and modules
149
- * - Cannot directly access the main thread's memory or variables
150
- *
151
- * **Important**: The handler function is serialized and sent to the worker thread,
152
- * so it cannot reference variables from the parent scope (closures won't work).
153
- * All required data must be passed via the `execute()` method.
154
- *
155
- * @example
156
- * ```ts
157
- * handler: async () => {
158
- * // CPU-intensive work here
159
- * const result = performComplexCalculation();
160
- * return { result, completed: Date.now() };
161
- * }
162
- * ```
163
- */
164
- handler: () => any | Promise<any>;
165
- /**
166
- * Maximum number of worker threads in the pool.
167
- *
168
- * Controls how many threads can run concurrently for this named thread worker.
169
- * When all threads are busy, additional `execute()` calls will queue until a thread becomes available.
170
- *
171
- * **Default**: `cpus().length * 2` (number of CPU cores × 2)
172
- *
173
- * **Guidelines**:
174
- * - For CPU-bound tasks: Set to number of CPU cores
175
- * - For I/O-bound tasks in workers: Can be higher (2x CPU cores)
176
- * - For memory-intensive tasks: Set lower to avoid memory pressure
177
- * - For short-lived tasks: Can be higher for better throughput
178
- *
179
- * @default cpus().length * 2
180
- * @example 4 // Limit to 4 concurrent threads
181
- * @example 1 // Single worker thread (sequential processing)
182
- * @example 16 // High concurrency for lightweight tasks
183
- */
184
- maxPoolSize?: number;
185
- /**
186
- * Time in milliseconds before idle worker threads are terminated.
187
- *
188
- * When a worker thread has been idle (not executing any tasks) for this duration,
189
- * it will be automatically terminated to free up system resources. New threads
190
- * will be created as needed when new tasks are submitted.
191
- *
192
- * **Default**: 60000 (60 seconds)
193
- *
194
- * **Considerations**:
195
- * - Shorter timeouts: Save memory but increase thread creation overhead
196
- * - Longer timeouts: Keep threads ready but consume more memory
197
- * - Very short timeouts may cause constant thread creation/destruction
198
- *
199
- * @default 60000
200
- * @example 30000 // 30 seconds
201
- * @example 120000 // 2 minutes
202
- * @example 5000 // 5 seconds (for very memory-constrained environments)
203
- */
204
- idleTimeout?: number;
205
- }
206
- declare class ThreadDescriptor extends Descriptor<ThreadDescriptorOptions> {
207
- protected readonly script: string;
208
- static readonly globalPool: Map<string, ThreadPool>;
209
- get name(): string;
210
- get maxPoolSize(): number;
211
- get idleTimeout(): number;
212
- private getPool;
213
- execute<T = any>(data?: any, schema?: TSchema): Promise<T>;
214
- create(): Promise<void>;
215
- terminate(): Promise<void>;
216
- }
217
- declare class ThreadPool {
218
- private readonly name;
219
- private readonly maxPoolSize;
220
- private readonly idleTimeout;
221
- private readonly script;
222
- private instances;
223
- private queue;
224
- private idleTimer?;
225
- constructor(name: string, maxPoolSize: number, idleTimeout: number, script: string);
226
- warmUp(): Promise<void>;
227
- private createInstance;
228
- execute<T = any>(data?: any): Promise<T>;
229
- private processQueue;
230
- private resetIdleTimer;
231
- private cleanupIdleInstances;
232
- terminate(): Promise<void>;
233
- }
234
- //#endregion
235
- //#region src/thread/providers/ThreadProvider.d.ts
236
- declare class ThreadProvider {
237
- protected readonly log: alepha_logger0.Logger;
238
- protected readonly env: {
239
- ALEPHA_WORKER?: string | undefined;
240
- };
241
- protected readonly ready: alepha1.HookDescriptor<"ready">;
242
- static cleanup(): Promise<void>;
243
- }
244
- //#endregion
245
- //#region src/thread/index.d.ts
246
- declare module "alepha" {
247
- interface Alepha {
248
- isWorkerThread(): boolean;
249
- }
250
- }
251
- /**
252
- * Simple interface for managing worker threads in Alepha.
253
- *
254
- * @see {@link $thread}
255
- * @module alepha.thread
256
- */
257
- declare const AlephaThread: alepha1.Service<alepha1.Module>;
258
- //#endregion
259
- export { $thread, AlephaThread, ThreadDescriptor, ThreadDescriptorOptions, ThreadProvider };
260
- //# sourceMappingURL=index.d.cts.map