@harrylabsj/kiwi-merchant-cloud 0.12.30 → 0.12.32

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 (336) hide show
  1. package/app/a2a/node.d.ts +1 -0
  2. package/app/a2a/node.js +170 -2
  3. package/app/a2a/node.js.map +1 -1
  4. package/app/a2a/reception/agent-runtime.d.ts +32 -1
  5. package/app/a2a/reception/agent-runtime.js +420 -11
  6. package/app/a2a/reception/agent-runtime.js.map +1 -1
  7. package/app/a2a/reception/customer-memory-tools.d.ts +73 -0
  8. package/app/a2a/reception/customer-memory-tools.js +17 -0
  9. package/app/a2a/reception/customer-memory-tools.js.map +1 -0
  10. package/app/a2a/reception/engine.d.ts +12 -0
  11. package/app/a2a/reception/engine.js +42 -1
  12. package/app/a2a/reception/engine.js.map +1 -1
  13. package/app/a2a/reception/publish.d.ts +14 -1
  14. package/app/a2a/reception/publish.js +62 -1
  15. package/app/a2a/reception/publish.js.map +1 -1
  16. package/app/a2a/reception/question-spec.d.ts +91 -0
  17. package/app/a2a/reception/question-spec.js +260 -0
  18. package/app/a2a/reception/question-spec.js.map +1 -0
  19. package/app/a2a/reception/reply-outbox.d.ts +6 -0
  20. package/app/a2a/reception/reply-outbox.js +44 -0
  21. package/app/a2a/reception/reply-outbox.js.map +1 -1
  22. package/app/a2a/reception/responder.d.ts +13 -1
  23. package/app/a2a/reception/responder.js +26 -3
  24. package/app/a2a/reception/responder.js.map +1 -1
  25. package/app/a2a/reception/skill-catalog.d.ts +72 -0
  26. package/app/a2a/reception/skill-catalog.js +85 -0
  27. package/app/a2a/reception/skill-catalog.js.map +1 -0
  28. package/app/a2a/reception/skill-contract.d.ts +70 -0
  29. package/app/a2a/reception/skill-contract.js +183 -0
  30. package/app/a2a/reception/skill-contract.js.map +1 -0
  31. package/app/a2a/reception/types.d.ts +12 -0
  32. package/app/a2a/server/customer-identity-gateway.d.ts +111 -0
  33. package/app/a2a/server/customer-identity-gateway.js +441 -0
  34. package/app/a2a/server/customer-identity-gateway.js.map +1 -0
  35. package/app/a2a/server/merchant-handler.d.ts +56 -1
  36. package/app/a2a/server/merchant-handler.js +659 -44
  37. package/app/a2a/server/merchant-handler.js.map +1 -1
  38. package/app/a2a/server/pipeline.js +74 -29
  39. package/app/a2a/server/pipeline.js.map +1 -1
  40. package/app/a2a/server/types.d.ts +2 -0
  41. package/app/a2a/unit-alias.d.ts +3 -3
  42. package/app/a2a/unit-alias.js +9 -5
  43. package/app/a2a/unit-alias.js.map +1 -1
  44. package/app/agent/buyer/buyer-tools.js +1 -2
  45. package/app/agent/buyer/buyer-tools.js.map +1 -1
  46. package/app/agent/buyer/search-loop.js +0 -1
  47. package/app/agent/buyer/search-loop.js.map +1 -1
  48. package/app/auth/merchant-sessions.d.ts +3 -0
  49. package/app/auth/merchant-sessions.js +21 -5
  50. package/app/auth/merchant-sessions.js.map +1 -1
  51. package/app/buyer-core/a2a-knp.d.ts +4 -2
  52. package/app/buyer-core/a2a-knp.js +5 -2
  53. package/app/buyer-core/a2a-knp.js.map +1 -1
  54. package/app/buyer-core/a2a-negotiator.d.ts +1 -0
  55. package/app/buyer-core/a2a-negotiator.js +18 -11
  56. package/app/buyer-core/a2a-negotiator.js.map +1 -1
  57. package/app/buyer-core/a2a-quote-fetcher.d.ts +25 -0
  58. package/app/buyer-core/a2a-quote-fetcher.js +82 -4
  59. package/app/buyer-core/a2a-quote-fetcher.js.map +1 -1
  60. package/app/buyer-core/a2a-quote-history.d.ts +94 -0
  61. package/app/buyer-core/a2a-quote-history.js +149 -0
  62. package/app/buyer-core/a2a-quote-history.js.map +1 -0
  63. package/app/buyer-core/build-service.d.ts +19 -0
  64. package/app/buyer-core/build-service.js +30 -1
  65. package/app/buyer-core/build-service.js.map +1 -1
  66. package/app/buyer-core/errors.d.ts +1 -1
  67. package/app/buyer-core/errors.js +1 -0
  68. package/app/buyer-core/errors.js.map +1 -1
  69. package/app/buyer-core/merchant-index.js +0 -1
  70. package/app/buyer-core/merchant-index.js.map +1 -1
  71. package/app/buyer-core/open-inquiry-signer.d.ts +1 -0
  72. package/app/buyer-core/open-inquiry-signer.js +5 -2
  73. package/app/buyer-core/open-inquiry-signer.js.map +1 -1
  74. package/app/buyer-core/protocol-recovery.d.ts +2 -1
  75. package/app/buyer-core/protocol-recovery.js +14 -4
  76. package/app/buyer-core/protocol-recovery.js.map +1 -1
  77. package/app/buyer-core/service.d.ts +58 -5
  78. package/app/buyer-core/service.js +279 -53
  79. package/app/buyer-core/service.js.map +1 -1
  80. package/app/buyer-core/store.d.ts +8 -0
  81. package/app/buyer-core/store.js +37 -7
  82. package/app/buyer-core/store.js.map +1 -1
  83. package/app/cli.js +136 -34
  84. package/app/cli.js.map +1 -1
  85. package/app/cloud/bootstrap.d.ts +1 -1
  86. package/app/cloud/bootstrap.js +162 -35
  87. package/app/cloud/bootstrap.js.map +1 -1
  88. package/app/cloud/product-import-tabular.js +13 -5
  89. package/app/cloud/product-import-tabular.js.map +1 -1
  90. package/app/cloud/trade-platforms-client.d.ts +30 -0
  91. package/app/cloud/trade-platforms-client.js +34 -1
  92. package/app/cloud/trade-platforms-client.js.map +1 -1
  93. package/app/cloud-sample/products.json +3 -3
  94. package/app/commerce/receipt/dispatcher.d.ts +42 -0
  95. package/app/commerce/receipt/dispatcher.js +68 -0
  96. package/app/commerce/receipt/dispatcher.js.map +1 -0
  97. package/app/commerce/receipt/receipts.d.ts +140 -0
  98. package/app/commerce/receipt/receipts.js +247 -0
  99. package/app/commerce/receipt/receipts.js.map +1 -0
  100. package/app/config/profile.d.ts +2 -2
  101. package/app/handoff/order-receipts.d.ts +62 -0
  102. package/app/handoff/order-receipts.js +71 -0
  103. package/app/handoff/order-receipts.js.map +1 -0
  104. package/app/handoff/trade-platform-rules.js +5 -2
  105. package/app/handoff/trade-platform-rules.js.map +1 -1
  106. package/app/handoff/ucp-checkout/cart-channel.d.ts +2 -1
  107. package/app/handoff/ucp-checkout/cart-channel.js +1 -0
  108. package/app/handoff/ucp-checkout/cart-channel.js.map +1 -1
  109. package/app/handoff/ucp-checkout/channel.d.ts +6 -0
  110. package/app/handoff/ucp-checkout/channel.js +44 -0
  111. package/app/handoff/ucp-checkout/channel.js.map +1 -1
  112. package/app/http/cli.js +6 -0
  113. package/app/http/cli.js.map +1 -1
  114. package/app/http/merchant-management/api.d.ts +11 -1
  115. package/app/http/merchant-management/api.js +471 -3
  116. package/app/http/merchant-management/api.js.map +1 -1
  117. package/app/http/merchant-management/draft-store.js +8 -6
  118. package/app/http/merchant-management/draft-store.js.map +1 -1
  119. package/app/http/merchant-management/page.js +83 -22
  120. package/app/http/merchant-management/page.js.map +1 -1
  121. package/app/mcp/cli.js +6 -0
  122. package/app/mcp/cli.js.map +1 -1
  123. package/app/mcp/merchant-runtime-assembly.d.ts +20 -0
  124. package/app/mcp/merchant-runtime-assembly.js +93 -3
  125. package/app/mcp/merchant-runtime-assembly.js.map +1 -1
  126. package/app/mcp/merchant-server.d.ts +5 -0
  127. package/app/mcp/merchant-server.js +12 -0
  128. package/app/mcp/merchant-server.js.map +1 -1
  129. package/app/mcp/tools.js +12 -3
  130. package/app/mcp/tools.js.map +1 -1
  131. package/app/merchant/application/actor.d.ts +1 -1
  132. package/app/merchant/application/actor.js +15 -0
  133. package/app/merchant/application/actor.js.map +1 -1
  134. package/app/merchant/workbench-server.d.ts +38 -0
  135. package/app/merchant/workbench-server.js +428 -0
  136. package/app/merchant/workbench-server.js.map +1 -0
  137. package/app/merchant-core/budget/background-budget.d.ts +132 -0
  138. package/app/merchant-core/budget/background-budget.js +308 -0
  139. package/app/merchant-core/budget/background-budget.js.map +1 -0
  140. package/app/merchant-core/context-governance/actor-context.d.ts +56 -0
  141. package/app/merchant-core/context-governance/actor-context.js +76 -0
  142. package/app/merchant-core/context-governance/actor-context.js.map +1 -0
  143. package/app/merchant-core/context-governance/authority.d.ts +39 -0
  144. package/app/merchant-core/context-governance/authority.js +28 -0
  145. package/app/merchant-core/context-governance/authority.js.map +1 -0
  146. package/app/merchant-core/context-governance/context-guard.d.ts +104 -0
  147. package/app/merchant-core/context-governance/context-guard.js +194 -0
  148. package/app/merchant-core/context-governance/context-guard.js.map +1 -0
  149. package/app/merchant-core/context-governance/data-use-grant.d.ts +91 -0
  150. package/app/merchant-core/context-governance/data-use-grant.js +211 -0
  151. package/app/merchant-core/context-governance/data-use-grant.js.map +1 -0
  152. package/app/merchant-core/context-governance/feature-flags.d.ts +32 -0
  153. package/app/merchant-core/context-governance/feature-flags.js +83 -0
  154. package/app/merchant-core/context-governance/feature-flags.js.map +1 -0
  155. package/app/merchant-core/context-governance/pilot-readiness.d.ts +39 -0
  156. package/app/merchant-core/context-governance/pilot-readiness.js +141 -0
  157. package/app/merchant-core/context-governance/pilot-readiness.js.map +1 -0
  158. package/app/merchant-core/context-governance/source-governance.d.ts +157 -0
  159. package/app/merchant-core/context-governance/source-governance.js +492 -0
  160. package/app/merchant-core/context-governance/source-governance.js.map +1 -0
  161. package/app/merchant-core/context-governance/types.d.ts +62 -0
  162. package/app/merchant-core/context-governance/types.js +92 -0
  163. package/app/merchant-core/context-governance/types.js.map +1 -0
  164. package/app/merchant-core/customer-delivery/binding.d.ts +55 -0
  165. package/app/merchant-core/customer-delivery/binding.js +121 -0
  166. package/app/merchant-core/customer-delivery/binding.js.map +1 -0
  167. package/app/merchant-core/customer-delivery/channel.d.ts +75 -0
  168. package/app/merchant-core/customer-delivery/channel.js +157 -0
  169. package/app/merchant-core/customer-delivery/channel.js.map +1 -0
  170. package/app/merchant-core/customer-delivery/consent-repository.d.ts +50 -0
  171. package/app/merchant-core/customer-delivery/consent-repository.js +160 -0
  172. package/app/merchant-core/customer-delivery/consent-repository.js.map +1 -0
  173. package/app/merchant-core/customer-delivery/dispatcher-loop.d.ts +68 -0
  174. package/app/merchant-core/customer-delivery/dispatcher-loop.js +132 -0
  175. package/app/merchant-core/customer-delivery/dispatcher-loop.js.map +1 -0
  176. package/app/merchant-core/customer-delivery/dispatcher.d.ts +118 -0
  177. package/app/merchant-core/customer-delivery/dispatcher.js +166 -0
  178. package/app/merchant-core/customer-delivery/dispatcher.js.map +1 -0
  179. package/app/merchant-core/customer-delivery/email-adapter.d.ts +31 -0
  180. package/app/merchant-core/customer-delivery/email-adapter.js +90 -0
  181. package/app/merchant-core/customer-delivery/email-adapter.js.map +1 -0
  182. package/app/merchant-core/customer-delivery/gate.d.ts +37 -0
  183. package/app/merchant-core/customer-delivery/gate.js +196 -0
  184. package/app/merchant-core/customer-delivery/gate.js.map +1 -0
  185. package/app/merchant-core/customer-delivery/reconciliation.d.ts +13 -0
  186. package/app/merchant-core/customer-delivery/reconciliation.js +70 -0
  187. package/app/merchant-core/customer-delivery/reconciliation.js.map +1 -0
  188. package/app/merchant-core/customer-delivery/repository.d.ts +55 -0
  189. package/app/merchant-core/customer-delivery/repository.js +235 -0
  190. package/app/merchant-core/customer-delivery/repository.js.map +1 -0
  191. package/app/merchant-core/customer-delivery/smtp-adapter.d.ts +30 -0
  192. package/app/merchant-core/customer-delivery/smtp-adapter.js +183 -0
  193. package/app/merchant-core/customer-delivery/smtp-adapter.js.map +1 -0
  194. package/app/merchant-core/customer-delivery/stream-gate.d.ts +45 -0
  195. package/app/merchant-core/customer-delivery/stream-gate.js +123 -0
  196. package/app/merchant-core/customer-delivery/stream-gate.js.map +1 -0
  197. package/app/merchant-core/customer-delivery/types.d.ts +103 -0
  198. package/app/merchant-core/customer-delivery/types.js +32 -0
  199. package/app/merchant-core/customer-delivery/types.js.map +1 -0
  200. package/app/merchant-core/customer-delivery/weixin-adapter.d.ts +35 -0
  201. package/app/merchant-core/customer-delivery/weixin-adapter.js +56 -0
  202. package/app/merchant-core/customer-delivery/weixin-adapter.js.map +1 -0
  203. package/app/merchant-core/customer-memory/auto-identity.d.ts +43 -0
  204. package/app/merchant-core/customer-memory/auto-identity.js +163 -0
  205. package/app/merchant-core/customer-memory/auto-identity.js.map +1 -0
  206. package/app/merchant-core/customer-memory/grants.d.ts +72 -0
  207. package/app/merchant-core/customer-memory/grants.js +224 -0
  208. package/app/merchant-core/customer-memory/grants.js.map +1 -0
  209. package/app/merchant-core/customer-memory/history.d.ts +51 -0
  210. package/app/merchant-core/customer-memory/history.js +252 -0
  211. package/app/merchant-core/customer-memory/history.js.map +1 -0
  212. package/app/merchant-core/customer-memory/identity.d.ts +66 -0
  213. package/app/merchant-core/customer-memory/identity.js +249 -0
  214. package/app/merchant-core/customer-memory/identity.js.map +1 -0
  215. package/app/merchant-core/customer-memory/maintenance.d.ts +51 -0
  216. package/app/merchant-core/customer-memory/maintenance.js +67 -0
  217. package/app/merchant-core/customer-memory/maintenance.js.map +1 -0
  218. package/app/merchant-core/customer-memory/memory.d.ts +119 -0
  219. package/app/merchant-core/customer-memory/memory.js +502 -0
  220. package/app/merchant-core/customer-memory/memory.js.map +1 -0
  221. package/app/merchant-core/customer-memory/private-transport.d.ts +10 -0
  222. package/app/merchant-core/customer-memory/private-transport.js +108 -0
  223. package/app/merchant-core/customer-memory/private-transport.js.map +1 -0
  224. package/app/merchant-core/customer-memory/quote-history.d.ts +160 -0
  225. package/app/merchant-core/customer-memory/quote-history.js +392 -0
  226. package/app/merchant-core/customer-memory/quote-history.js.map +1 -0
  227. package/app/merchant-core/customer-memory/reception-provider.d.ts +69 -0
  228. package/app/merchant-core/customer-memory/reception-provider.js +250 -0
  229. package/app/merchant-core/customer-memory/reception-provider.js.map +1 -0
  230. package/app/merchant-core/customer-memory/reception-writer.d.ts +19 -0
  231. package/app/merchant-core/customer-memory/reception-writer.js +32 -0
  232. package/app/merchant-core/customer-memory/reception-writer.js.map +1 -0
  233. package/app/merchant-core/customer-memory/types.d.ts +111 -0
  234. package/app/merchant-core/customer-memory/types.js +58 -0
  235. package/app/merchant-core/customer-memory/types.js.map +1 -0
  236. package/app/merchant-core/followup/repository.d.ts +2 -1
  237. package/app/merchant-core/followup/repository.js +29 -23
  238. package/app/merchant-core/followup/repository.js.map +1 -1
  239. package/app/merchant-core/learning/evaluation-fixtures.d.ts +38 -0
  240. package/app/merchant-core/learning/evaluation-fixtures.js +83 -0
  241. package/app/merchant-core/learning/evaluation-fixtures.js.map +1 -0
  242. package/app/merchant-core/learning/evaluation-suite-v1.d.ts +56 -0
  243. package/app/merchant-core/learning/evaluation-suite-v1.js +129 -0
  244. package/app/merchant-core/learning/evaluation-suite-v1.js.map +1 -0
  245. package/app/merchant-core/learning/evaluation.d.ts +84 -0
  246. package/app/merchant-core/learning/evaluation.js +581 -0
  247. package/app/merchant-core/learning/evaluation.js.map +1 -0
  248. package/app/merchant-core/learning/initial-skills.d.ts +36 -0
  249. package/app/merchant-core/learning/initial-skills.js +67 -0
  250. package/app/merchant-core/learning/initial-skills.js.map +1 -0
  251. package/app/merchant-core/learning/precheck.d.ts +33 -0
  252. package/app/merchant-core/learning/precheck.js +56 -0
  253. package/app/merchant-core/learning/precheck.js.map +1 -0
  254. package/app/merchant-core/learning/real-evaluation-runner.d.ts +52 -0
  255. package/app/merchant-core/learning/real-evaluation-runner.js +167 -0
  256. package/app/merchant-core/learning/real-evaluation-runner.js.map +1 -0
  257. package/app/merchant-core/learning/reception-skill-catalog.d.ts +39 -0
  258. package/app/merchant-core/learning/reception-skill-catalog.js +145 -0
  259. package/app/merchant-core/learning/reception-skill-catalog.js.map +1 -0
  260. package/app/merchant-core/learning/recovery-gateway.d.ts +27 -0
  261. package/app/merchant-core/learning/recovery-gateway.js +106 -0
  262. package/app/merchant-core/learning/recovery-gateway.js.map +1 -0
  263. package/app/merchant-core/learning/repository.d.ts +130 -0
  264. package/app/merchant-core/learning/repository.js +588 -0
  265. package/app/merchant-core/learning/repository.js.map +1 -0
  266. package/app/merchant-core/learning/service.d.ts +262 -0
  267. package/app/merchant-core/learning/service.js +1498 -0
  268. package/app/merchant-core/learning/service.js.map +1 -0
  269. package/app/merchant-core/learning/test-dispatch-gateway.d.ts +43 -0
  270. package/app/merchant-core/learning/test-dispatch-gateway.js +145 -0
  271. package/app/merchant-core/learning/test-dispatch-gateway.js.map +1 -0
  272. package/app/merchant-core/learning/types.d.ts +217 -0
  273. package/app/merchant-core/learning/types.js +52 -0
  274. package/app/merchant-core/learning/types.js.map +1 -0
  275. package/app/merchant-core/migrations/ledgers.d.ts +40 -0
  276. package/app/merchant-core/migrations/ledgers.js +824 -0
  277. package/app/merchant-core/migrations/ledgers.js.map +1 -0
  278. package/app/merchant-core/migrations/runner.d.ts +55 -0
  279. package/app/merchant-core/migrations/runner.js +114 -0
  280. package/app/merchant-core/migrations/runner.js.map +1 -0
  281. package/app/merchant-core/operations-jobs/advice-runner.d.ts +63 -0
  282. package/app/merchant-core/operations-jobs/advice-runner.js +199 -0
  283. package/app/merchant-core/operations-jobs/advice-runner.js.map +1 -0
  284. package/app/merchant-core/operations-jobs/pilot-evidence.d.ts +64 -0
  285. package/app/merchant-core/operations-jobs/pilot-evidence.js +109 -0
  286. package/app/merchant-core/operations-jobs/pilot-evidence.js.map +1 -0
  287. package/app/merchant-core/operations-jobs/pilot-metrics.d.ts +70 -0
  288. package/app/merchant-core/operations-jobs/pilot-metrics.js +98 -0
  289. package/app/merchant-core/operations-jobs/pilot-metrics.js.map +1 -0
  290. package/app/merchant-core/operations-jobs/projection.d.ts +41 -0
  291. package/app/merchant-core/operations-jobs/projection.js +158 -0
  292. package/app/merchant-core/operations-jobs/projection.js.map +1 -0
  293. package/app/merchant-core/operations-jobs/scheduler.d.ts +68 -0
  294. package/app/merchant-core/operations-jobs/scheduler.js +233 -0
  295. package/app/merchant-core/operations-jobs/scheduler.js.map +1 -0
  296. package/app/merchant-core/operations-jobs/service.d.ts +260 -0
  297. package/app/merchant-core/operations-jobs/service.js +922 -0
  298. package/app/merchant-core/operations-jobs/service.js.map +1 -0
  299. package/app/merchant-core/ops/facade.d.ts +10 -0
  300. package/app/merchant-core/ops/facade.js +52 -0
  301. package/app/merchant-core/ops/facade.js.map +1 -1
  302. package/app/merchant-core/ops/schema.d.ts +1 -1
  303. package/app/merchant-core/ops/schema.js +119 -2
  304. package/app/merchant-core/ops/schema.js.map +1 -1
  305. package/app/merchant-core/ops/surface.d.ts +37 -0
  306. package/app/merchant-core/ops/surface.js +240 -0
  307. package/app/merchant-core/ops/surface.js.map +1 -1
  308. package/app/merchant-core/ownership/instance-ownership.d.ts +122 -0
  309. package/app/merchant-core/ownership/instance-ownership.js +236 -0
  310. package/app/merchant-core/ownership/instance-ownership.js.map +1 -0
  311. package/app/merchant-core/ownership/runtime.d.ts +175 -0
  312. package/app/merchant-core/ownership/runtime.js +422 -0
  313. package/app/merchant-core/ownership/runtime.js.map +1 -0
  314. package/app/merchant-core/storage/transaction.d.ts +102 -7
  315. package/app/merchant-core/storage/transaction.js +274 -3
  316. package/app/merchant-core/storage/transaction.js.map +1 -1
  317. package/app/merchant-credential-rotation.d.ts +4 -1
  318. package/app/merchant-credential-rotation.js +12 -8
  319. package/app/merchant-credential-rotation.js.map +1 -1
  320. package/app/merchant-gateway/catalog-tools.js +4 -2
  321. package/app/merchant-gateway/catalog-tools.js.map +1 -1
  322. package/app/merchant-runtime/manager.d.ts +2 -0
  323. package/app/merchant-runtime/manager.js +5 -0
  324. package/app/merchant-runtime/manager.js.map +1 -1
  325. package/app/product-buyer.d.ts +1 -0
  326. package/app/product-buyer.js +0 -1
  327. package/app/product-buyer.js.map +1 -1
  328. package/app/product-cli.js +11 -1
  329. package/app/product-cli.js.map +1 -1
  330. package/build-manifest.json +1255 -280
  331. package/deployment-lock.json +2 -2
  332. package/package.json +1 -1
  333. package/prepare.mjs +5 -1
  334. package/runtime-package.json +1 -1
  335. package/shipping-sbom.cdx.json +6 -6
  336. package/shipping-source.json +12 -12
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * P1 客户通知的持久化(设计 §16.3 / M6-2)。
18
+ *
19
+ * 唯一发送真相是 `followup_outbox`:本模块只把已冻结的 DeliveryRecord 映射
20
+ * 到该表,不另建第二份队列表。领取/回执通过 `inImmediateTransaction` 与
21
+ * dispatcher 组合,保证同一 stream 的单流在途约束。
22
+ */
23
+ import { deliveryAttemptDigest } from "./reconciliation.js";
24
+ import { inImmediateTransaction } from "../storage/transaction.js";
25
+ import { DeliveryGateError } from "./types.js";
26
+ function rowToRecord(row) {
27
+ // 旧 followup_outbox 行没有 M6 扩展字段;它们不是 P1 通知,忽略。
28
+ if (row.stream_key === null ||
29
+ row.binding_id === null ||
30
+ row.binding_epoch === null ||
31
+ row.subscription_id === null ||
32
+ row.subscription_epoch === null ||
33
+ row.purpose === null ||
34
+ row.channel === null ||
35
+ row.payload_digest === null ||
36
+ row.valid_until === null ||
37
+ row.seq === null) {
38
+ return undefined;
39
+ }
40
+ return {
41
+ delivery_id: row.outbox_id,
42
+ merchant_id: row.merchant_id,
43
+ stream_key: row.stream_key,
44
+ binding_id: row.binding_id,
45
+ binding_epoch: row.binding_epoch,
46
+ channel: row.channel,
47
+ purpose: row.purpose,
48
+ payload: JSON.parse(row.payload_json),
49
+ payload_digest: row.payload_digest,
50
+ seq: row.seq,
51
+ valid_until: row.valid_until,
52
+ subscription_id: row.subscription_id,
53
+ subscription_epoch: row.subscription_epoch,
54
+ source_grants: row.source_grants_json === null ? [] : JSON.parse(row.source_grants_json),
55
+ created_at: row.created_at,
56
+ status: row.status,
57
+ ...(row.lease_owner !== null ? { lease_owner: row.lease_owner } : {}),
58
+ ...(row.lease_expires_at !== null ? { lease_expires_at: row.lease_expires_at } : {}),
59
+ ...(row.started_at !== null ? { started_at: row.started_at } : {}),
60
+ attempts: row.attempts,
61
+ ...(row.next_attempt_at !== null ? { next_attempt_at: row.next_attempt_at } : {}),
62
+ ...(row.provider_request_id !== null ? { provider_request_id: row.provider_request_id } : {}),
63
+ ...(row.receipt_json !== null
64
+ ? { receipt: JSON.parse(row.receipt_json) }
65
+ : {}),
66
+ ...(row.accepted_at !== null ? { accepted_at: row.accepted_at } : {}),
67
+ ...(row.read_at !== null ? { read_at: row.read_at } : {}),
68
+ ...(row.read_evidence_ref !== null ? { read_evidence_ref: row.read_evidence_ref } : {}),
69
+ ...(row.blocked_reason !== null ? { blocked_reason: row.blocked_reason } : {}),
70
+ };
71
+ }
72
+ const DELIVERY_AUDIT_SCHEMA = `
73
+ CREATE TABLE IF NOT EXISTS customer_delivery_reconciliation_audit (
74
+ id INTEGER PRIMARY KEY,
75
+ merchant_id TEXT NOT NULL,
76
+ delivery_id TEXT NOT NULL,
77
+ attempt_digest TEXT NOT NULL,
78
+ outcome TEXT NOT NULL,
79
+ actor_id TEXT NOT NULL,
80
+ evidence_ref TEXT NOT NULL,
81
+ reconciled_at TEXT NOT NULL,
82
+ UNIQUE (merchant_id, delivery_id, attempt_digest)
83
+ );
84
+ `;
85
+ export class CustomerDeliveryRepository {
86
+ db;
87
+ now;
88
+ constructor(options) {
89
+ this.db = options.db;
90
+ this.now = options.now;
91
+ }
92
+ /** 插入已冻结的 PENDING 通知;delivery_id 即 outbox_id。 */
93
+ insert(record, taskId) {
94
+ if (record.status !== "PENDING") {
95
+ throw new DeliveryGateError("invalid_transition", "只有 PENDING 通知可以入队");
96
+ }
97
+ this.db
98
+ .prepare(`INSERT INTO followup_outbox
99
+ (outbox_id, task_id, merchant_id, payload_json, status, created_at, updated_at,
100
+ stream_key, seq, payload_digest, valid_until, binding_id, binding_epoch,
101
+ subscription_id, subscription_epoch, purpose, channel, source_grants_json,
102
+ lease_owner, lease_expires_at, started_at, accepted_at, read_at,
103
+ read_evidence_ref, blocked_reason, provider_request_id, receipt_json,
104
+ attempts, next_attempt_at)
105
+ VALUES (?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
106
+ .run(record.delivery_id, taskId, record.merchant_id, JSON.stringify(record.payload), record.created_at, this.now(), record.stream_key, record.seq, record.payload_digest, record.valid_until, record.binding_id, record.binding_epoch, record.subscription_id, record.subscription_epoch, record.purpose, record.channel, JSON.stringify(record.source_grants), record.lease_owner ?? null, record.lease_expires_at ?? null, record.started_at ?? null, record.accepted_at ?? null, record.read_at ?? null, record.read_evidence_ref ?? null, record.blocked_reason ?? null, record.provider_request_id ?? null, record.receipt !== undefined ? JSON.stringify(record.receipt) : null, record.attempts ?? 0, record.next_attempt_at ?? null);
107
+ }
108
+ get(merchantId, deliveryId) {
109
+ const row = this.db
110
+ .prepare("SELECT * FROM followup_outbox WHERE merchant_id = ? AND outbox_id = ?")
111
+ .get(merchantId, deliveryId);
112
+ return row === undefined ? undefined : rowToRecord(row);
113
+ }
114
+ findBlocking(merchantId, streamKey, deliveryId) {
115
+ const rows = this.db
116
+ .prepare(`SELECT * FROM followup_outbox
117
+ WHERE merchant_id = ? AND stream_key = ? AND outbox_id != ?
118
+ AND (status = 'UNKNOWN' OR (status = 'PENDING' AND started_at IS NOT NULL))`)
119
+ .all(merchantId, streamKey, deliveryId);
120
+ for (const row of rows) {
121
+ const record = rowToRecord(row);
122
+ if (record !== undefined)
123
+ return record;
124
+ }
125
+ return undefined;
126
+ }
127
+ save(record) {
128
+ const result = this.db
129
+ .prepare(`UPDATE followup_outbox SET
130
+ status = ?, payload_json = ?, payload_digest = ?, valid_until = ?,
131
+ lease_owner = ?, lease_expires_at = ?, started_at = ?, accepted_at = ?,
132
+ read_at = ?, read_evidence_ref = ?, blocked_reason = ?,
133
+ provider_request_id = ?, receipt_json = ?, attempts = ?,
134
+ next_attempt_at = ?, updated_at = ?
135
+ WHERE merchant_id = ? AND outbox_id = ?`)
136
+ .run(record.status, JSON.stringify(record.payload), record.payload_digest, record.valid_until, record.lease_owner ?? null, record.lease_expires_at ?? null, record.started_at ?? null, record.accepted_at ?? null, record.read_at ?? null, record.read_evidence_ref ?? null, record.blocked_reason ?? null, record.provider_request_id ?? null, record.receipt !== undefined ? JSON.stringify(record.receipt) : null, record.attempts ?? 0, record.next_attempt_at ?? null, this.now(), record.merchant_id, record.delivery_id);
137
+ if (Number(result.changes) !== 1) {
138
+ throw new DeliveryGateError("invalid_transition", "通知不存在或已删除");
139
+ }
140
+ }
141
+ /** A vanished worker may have reached the channel before recording the result. */
142
+ recoverExpiredClaims(merchantId, now) {
143
+ const result = this.db
144
+ .prepare(`UPDATE followup_outbox
145
+ SET status = 'UNKNOWN', lease_owner = NULL, lease_expires_at = NULL,
146
+ blocked_reason = 'send_lease_expired', updated_at = ?
147
+ WHERE merchant_id = ? AND status = 'PENDING' AND stream_key IS NOT NULL
148
+ AND (started_at IS NOT NULL OR lease_owner IS NOT NULL)
149
+ AND (lease_expires_at IS NULL OR lease_expires_at <= ?)`)
150
+ .run(now, merchantId, now);
151
+ return Number(result.changes);
152
+ }
153
+ /** Settle only the exact attempt inspected by the trusted evidence source. */
154
+ reconcileUnknown(snapshot, evidence) {
155
+ return this.inTransaction(() => {
156
+ const current = this.get(snapshot.merchant_id, snapshot.delivery_id);
157
+ const digest = deliveryAttemptDigest(snapshot);
158
+ if (current?.status !== "UNKNOWN" || current.started_at === undefined ||
159
+ deliveryAttemptDigest(current) !== digest ||
160
+ !/^[A-Za-z0-9_.:/-]{1,180}$/.test(evidence.evidence_ref))
161
+ return false;
162
+ const now = this.now();
163
+ if (evidence.outcome === "accepted" &&
164
+ !(Date.parse(evidence.accepted_at) >= Date.parse(current.started_at) &&
165
+ Date.parse(evidence.accepted_at) <= Date.parse(now)))
166
+ return false;
167
+ if (evidence.outcome === "not_sent" && evidence.future_execution_blocked !== true)
168
+ return false;
169
+ this.db.exec(DELIVERY_AUDIT_SCHEMA);
170
+ this.db.prepare(`INSERT INTO customer_delivery_reconciliation_audit
171
+ (merchant_id, delivery_id, attempt_digest, outcome, actor_id, evidence_ref, reconciled_at)
172
+ VALUES (?, ?, ?, ?, ?, ?, ?)`).run(current.merchant_id, current.delivery_id, digest, evidence.outcome, "service:delivery-evidence", evidence.evidence_ref, now);
173
+ this.save({
174
+ ...current,
175
+ lease_owner: undefined, lease_expires_at: undefined,
176
+ ...(evidence.outcome === "accepted"
177
+ ? { status: "SENT", accepted_at: evidence.accepted_at, blocked_reason: undefined }
178
+ // PENDING is a legacy storage enum; the deadline makes this row permanently ineligible.
179
+ : { status: "PENDING", started_at: undefined, next_attempt_at: current.valid_until,
180
+ blocked_reason: "reconciled_not_sent_no_retry" }),
181
+ });
182
+ return true;
183
+ });
184
+ }
185
+ listReconciliationAudit(merchantId) {
186
+ if (this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'customer_delivery_reconciliation_audit'").get() === undefined)
187
+ return [];
188
+ return this.db.prepare(`SELECT delivery_id, attempt_digest, outcome, actor_id, evidence_ref, reconciled_at
189
+ FROM customer_delivery_reconciliation_audit WHERE merchant_id = ? ORDER BY id DESC LIMIT 100`).all(merchantId);
190
+ }
191
+ /** dispatcher 扫描:PENDING、未过期、尚未领取、已过重试退避。 */
192
+ listDue(merchantId, now, limit = 20) {
193
+ const rows = this.db
194
+ .prepare(`SELECT * FROM followup_outbox
195
+ WHERE merchant_id = ? AND status = 'PENDING' AND valid_until > ?
196
+ AND started_at IS NULL AND lease_owner IS NULL
197
+ AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
198
+ ORDER BY seq ASC, created_at ASC
199
+ LIMIT ?`)
200
+ .all(merchantId, now, now, limit);
201
+ return rows.map((row) => rowToRecord(row)).filter((row) => row !== undefined);
202
+ }
203
+ /** 当日(UTC 日)同一订阅已 accepted 的发送数;频控复核用。 */
204
+ countSentToday(merchantId, subscriptionId, now) {
205
+ const dayStart = `${now.slice(0, 10)}T00:00:00.000Z`;
206
+ const row = this.db
207
+ .prepare(`SELECT COUNT(*) AS n FROM followup_outbox
208
+ WHERE merchant_id = ? AND subscription_id = ? AND status = 'SENT'
209
+ AND accepted_at >= ?`)
210
+ .get(merchantId, subscriptionId, dayStart);
211
+ return Number(row.n);
212
+ }
213
+ countUnknown(merchantId) {
214
+ const row = this.db.prepare("SELECT COUNT(*) AS n FROM followup_outbox WHERE merchant_id = ? AND status = 'UNKNOWN' AND stream_key IS NOT NULL").get(merchantId);
215
+ return row.n;
216
+ }
217
+ /** 运营核对:列出指定状态的投递记录(默认 UNKNOWN)。 */
218
+ listByStatus(merchantId, status, limit = 50, offset = 0) {
219
+ const rows = this.db
220
+ .prepare(`SELECT * FROM followup_outbox
221
+ WHERE merchant_id = ? AND status = ? AND stream_key IS NOT NULL
222
+ ORDER BY created_at ASC, outbox_id ASC LIMIT ? OFFSET ?`)
223
+ .all(merchantId, status, limit, offset);
224
+ return rows.map((row) => rowToRecord(row)).filter((row) => row !== undefined);
225
+ }
226
+ /** 在 IMMEDIATE 事务内执行领取/回执组合,确保单流约束与写入原子。 */
227
+ inTransaction(fn) {
228
+ return inImmediateTransaction(this.db, fn);
229
+ }
230
+ /** DeliveryStore.transaction:dispatcher 在领取时使用。 */
231
+ transaction(fn) {
232
+ return this.inTransaction(fn);
233
+ }
234
+ }
235
+ //# sourceMappingURL=repository.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repository.js","sourceRoot":"","sources":["../../../src/merchant-core/customer-delivery/repository.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;GAMG;AAEH,OAAO,EAAE,qBAAqB,EAAyB,MAAM,qBAAqB,CAAC;AAGnF,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAuB,MAAM,YAAY,CAAC;AAmCpE,SAAS,WAAW,CAAC,GAAc;IACjC,+CAA+C;IAC/C,IACE,GAAG,CAAC,UAAU,KAAK,IAAI;QACvB,GAAG,CAAC,U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iCAEyB,CAC1B;aACA,GAAG,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAkB,CAAC;QAC9D,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACvB,CAAC;IAED,YAAY,CAAC,UAAkB;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC,OAAO,CACzB,mHAAmH,CACpH,CAAC,GAAG,CAAC,UAAU,CAAkB,CAAC;QACnC,OAAO,GAAG,CAAC,CAAC,CAAC;IACf,CAAC;IAED,oCAAoC;IACpC,YAAY,CAAC,UAAkB,EAAE,MAAsB,EAAE,KAAK,GAAG,EAAE,EAAE,MAAM,GAAG,CAAC;QAC7E,MAAM,IAAI,GAAG,IAAI,CAAC,EAAE;aACjB,OAAO,CACN;;kEAE0D,CAC3D;aACA,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAA2B,CAAC;QACpE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAyB,EAAE,CAAC,GAAG,KAAK,SAAS,CAAC,CAAC;IACvG,CAAC;IAED,4CAA4C;IAC5C,aAAa,CAAI,EAAW;QAC1B,OAAO,sBAAsB,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;IAC7C,CAAC;IAED,mDAAmD;IACnD,WAAW,CAAI,EAAW;QACxB,OAAO,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IAChC,CAAC;CACF"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { DeliveryChannelAdapter } from "./channel.js";
17
+ export interface SmtpChannelAdapterOptions {
18
+ readonly host: string;
19
+ readonly port: number;
20
+ readonly secure?: boolean;
21
+ readonly user?: string;
22
+ readonly password?: string;
23
+ /** 缺省 true;测试/内网明文可显式关闭。 */
24
+ readonly starttls?: boolean;
25
+ readonly from: string;
26
+ /** 仅测试注入;生产必须由调用方按授权绑定传入 recipient。 */
27
+ readonly to?: string;
28
+ readonly timeout_ms?: number;
29
+ }
30
+ export declare function createSmtpChannelAdapter(options: SmtpChannelAdapterOptions): DeliveryChannelAdapter;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * SMTP 发送适配器(M6-6;465 隐式 TLS 或 587 STARTTLS)。
18
+ *
19
+ * 零运行时依赖:node:net/node:tls。2xx 最终 DATA 响应视为平台接受;
20
+ * 4xx/5xx 在 DATA 前可证明未发送;超时/连接中断为 UNKNOWN。
21
+ */
22
+ import { connect as netConnect } from "node:net";
23
+ import { connect as tlsConnect } from "node:tls";
24
+ /** 每条命令的响应 deadline(P1-3):服务器停在任意阶段都会销毁 socket
25
+ * 并归为 UNKNOWN,不让 tick 永久挂起。 */
26
+ function readResponse(socket, timeoutMs) {
27
+ return new Promise((resolve, reject) => {
28
+ let buffer = "";
29
+ const finish = (fn) => {
30
+ clearTimeout(timer);
31
+ socket.off("data", onData);
32
+ socket.off("error", onError);
33
+ socket.off("close", onClose);
34
+ fn();
35
+ };
36
+ const onData = (chunk) => {
37
+ buffer += chunk.toString("utf8");
38
+ const lines = buffer.split(/\r?\n/);
39
+ // 多行响应以 "250-" 继续,最后一行 "250 "。
40
+ const last = lines.filter((line) => /^\d{3}[ ]/.test(line)).pop();
41
+ if (last !== undefined)
42
+ finish(() => resolve(buffer));
43
+ };
44
+ const onError = (err) => finish(() => reject(err));
45
+ const onClose = () => finish(() => reject(new Error("smtp_closed")));
46
+ const timer = setTimeout(() => {
47
+ finish(() => reject(new Error("smtp_timeout")));
48
+ socket.destroy();
49
+ }, timeoutMs);
50
+ socket.on("data", onData);
51
+ socket.once("error", onError);
52
+ socket.once("close", onClose);
53
+ });
54
+ }
55
+ async function command(socket, line, timeoutMs) {
56
+ socket.write(`${line}\r\n`);
57
+ return readResponse(socket, timeoutMs);
58
+ }
59
+ function statusCode(response) {
60
+ const match = /^(\d{3})/m.exec(response.trim());
61
+ return match === null ? 0 : Number(match[1]);
62
+ }
63
+ function validEnvelopeAddress(value) {
64
+ return value.trim() !== "" && !/[<>]/.test(value) && Array.from(value).every((character) => {
65
+ const code = character.charCodeAt(0);
66
+ return code >= 32 && code !== 127;
67
+ });
68
+ }
69
+ function escapeData(text) {
70
+ return text
71
+ .replace(/\r\n|\r|\n/g, "\r\n")
72
+ .split("\r\n")
73
+ .map((line) => (line.startsWith(".") ? `.${line}` : line))
74
+ .join("\r\n");
75
+ }
76
+ async function connectSmtp(options) {
77
+ const timeout = options.timeout_ms ?? 20_000;
78
+ if (options.secure === true || options.port === 465) {
79
+ return new Promise((resolve, reject) => {
80
+ const socket = tlsConnect({ host: options.host, port: options.port, servername: options.host, timeout }, () => resolve(socket));
81
+ socket.once("error", reject);
82
+ socket.once("timeout", () => reject(new Error("smtp_timeout")));
83
+ });
84
+ }
85
+ return new Promise((resolve, reject) => {
86
+ const socket = netConnect({ host: options.host, port: options.port, timeout }, () => resolve(socket));
87
+ socket.once("error", reject);
88
+ socket.once("timeout", () => reject(new Error("smtp_timeout")));
89
+ });
90
+ }
91
+ async function upgradeTls(socket, host, timeoutMs) {
92
+ return new Promise((resolve, reject) => {
93
+ const secure = tlsConnect({ socket, servername: host, timeout: timeoutMs }, () => resolve(secure));
94
+ secure.once("error", reject);
95
+ secure.once("timeout", () => reject(new Error("smtp_timeout")));
96
+ });
97
+ }
98
+ export function createSmtpChannelAdapter(options) {
99
+ return {
100
+ async send({ delivery, recipient, timeout_ms }) {
101
+ if (delivery.channel !== "email")
102
+ return { outcome: "not_sent", reason: "channel_mismatch" };
103
+ const to = recipient ?? options.to;
104
+ if (to === undefined || to.trim() === "") {
105
+ return { outcome: "not_sent", reason: "recipient_unresolved" };
106
+ }
107
+ if (!validEnvelopeAddress(options.from) || !validEnvelopeAddress(to)) {
108
+ return { outcome: "not_sent", reason: "invalid_envelope_address" };
109
+ }
110
+ const timeoutMs = Math.max(1, Math.min(timeout_ms, options.timeout_ms ?? timeout_ms));
111
+ const subject = typeof delivery.payload.title === "string" ? delivery.payload.title : "通知";
112
+ const body = typeof delivery.payload.body === "string" ? delivery.payload.body : "";
113
+ if (body.trim() === "")
114
+ return { outcome: "not_sent", reason: "payload_empty" };
115
+ let socket;
116
+ try {
117
+ socket = await connectSmtp({ ...options, timeout_ms: timeoutMs });
118
+ const greeting = await readResponse(socket, timeoutMs);
119
+ if (statusCode(greeting) !== 220)
120
+ return { outcome: "not_sent", reason: "smtp_greeting" };
121
+ let ehlo = await command(socket, "EHLO kiwi.local", timeoutMs);
122
+ if (statusCode(ehlo) !== 250)
123
+ return { outcome: "not_sent", reason: "smtp_ehlo" };
124
+ if (options.starttls !== false && !(options.secure === true || options.port === 465)) {
125
+ const starttls = await command(socket, "STARTTLS", timeoutMs);
126
+ if (statusCode(starttls) !== 220)
127
+ return { outcome: "not_sent", reason: "smtp_starttls" };
128
+ socket = await upgradeTls(socket, options.host, timeoutMs);
129
+ ehlo = await command(socket, "EHLO kiwi.local", timeoutMs);
130
+ if (statusCode(ehlo) !== 250)
131
+ return { outcome: "not_sent", reason: "smtp_ehlo_tls" };
132
+ }
133
+ if (options.user !== undefined && options.password !== undefined) {
134
+ const auth = await command(socket, "AUTH LOGIN", timeoutMs);
135
+ if (statusCode(auth) !== 334)
136
+ return { outcome: "not_sent", reason: "smtp_auth" };
137
+ const user = await command(socket, Buffer.from(options.user).toString("base64"), timeoutMs);
138
+ if (statusCode(user) !== 334)
139
+ return { outcome: "not_sent", reason: "smtp_auth_user" };
140
+ const pass = await command(socket, Buffer.from(options.password).toString("base64"), timeoutMs);
141
+ if (statusCode(pass) !== 235)
142
+ return { outcome: "not_sent", reason: "smtp_auth_password" };
143
+ }
144
+ const mailFrom = await command(socket, `MAIL FROM:<${options.from}>`, timeoutMs);
145
+ if (statusCode(mailFrom) !== 250)
146
+ return { outcome: "not_sent", reason: "smtp_mail_from" };
147
+ const rcpt = await command(socket, `RCPT TO:<${to}>`, timeoutMs);
148
+ if (statusCode(rcpt) !== 250 && statusCode(rcpt) !== 251) {
149
+ return { outcome: "not_sent", reason: "smtp_rcpt" };
150
+ }
151
+ const data = await command(socket, "DATA", timeoutMs);
152
+ if (statusCode(data) !== 354)
153
+ return { outcome: "not_sent", reason: "smtp_data" };
154
+ // P2-12:同一 delivery_id 必须映射同一 Message-ID,重发才能被下游关联/去重。
155
+ const messageId = `<${delivery.delivery_id}@kiwi.local>`;
156
+ const payload = [
157
+ `From: ${options.from}`,
158
+ `To: ${to}`,
159
+ `Subject: ${subject.replace(/[\r\n]/g, " ")}`,
160
+ `Message-ID: ${messageId}`,
161
+ "MIME-Version: 1.0",
162
+ 'Content-Type: text/plain; charset="utf-8"',
163
+ "",
164
+ escapeData(body),
165
+ ".",
166
+ ].join("\r\n");
167
+ socket.write(`${payload}\r\n`);
168
+ const accepted = await readResponse(socket, timeoutMs);
169
+ if (statusCode(accepted) !== 250)
170
+ return { outcome: "unknown", receipt: { status: statusCode(accepted) } };
171
+ await command(socket, "QUIT", timeoutMs).catch(() => undefined);
172
+ return { outcome: "accepted", provider_request_id: messageId, receipt: { accepted: true } };
173
+ }
174
+ catch {
175
+ return { outcome: "unknown" };
176
+ }
177
+ finally {
178
+ socket?.destroy();
179
+ }
180
+ },
181
+ };
182
+ }
183
+ //# sourceMappingURL=smtp-adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smtp-adapter.js","sourceRoot":"","sources":["../../../src/merchant-core/customer-delivery/smtp-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,IAAI,UAAU,EAAe,MAAM,UAAU,CAAC;AAC9D,OAAO,EAAE,OAAO,IAAI,UAAU,EAAkB,MAAM,UAAU,CAAC;AAoBjE;+BAC+B;AAC/B,SAAS,YAAY,CAAC,MAAkB,EAAE,SAAiB;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,MAAM,GAAG,EAAE,CAAC;QAChB,MAAM,MAAM,GAAG,CAAC,EAAc,EAAQ,EAAE;YACtC,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YAC3B,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC7B,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC7B,EAAE,EAAE,CAAC;QACP,CAAC,CAAC;QACF,MAAM,MAAM,GAAG,CAAC,KAAa,EAAQ,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;YACjC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACpC,+BAA+B;YAC/B,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM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ChE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,SAAS,EAAE,OAAO,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC;YAC9F,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;YAChC,CAAC;oBAAS,CAAC;gBACT,MAAM,EAAE,OAAO,EAAE,CAAC;YACpB,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { DatabaseSync } from "node:sqlite";
17
+ export type StreamGateErrorCode = "stream_busy";
18
+ export declare class StreamGateError extends Error {
19
+ readonly code: StreamGateErrorCode;
20
+ readonly streamKey: string;
21
+ constructor(streamKey: string);
22
+ }
23
+ export declare class StreamGate {
24
+ private readonly db?;
25
+ private readonly holders;
26
+ constructor(db?: DatabaseSync | undefined);
27
+ static forDataDir(dataDir: string): StreamGate;
28
+ close(): void;
29
+ /** 申请进入发送流;已有未过期 holder 时拒绝。 */
30
+ enter(input: {
31
+ stream_key: string;
32
+ holder_id: string;
33
+ lease_ms: number;
34
+ now: string;
35
+ }): void;
36
+ /** 结果确定(SENT/not_sent)后释放;UNKNOWN 不释放。 */
37
+ leave(stream_key: string, holder_id: string): void;
38
+ isHeld(stream_key: string, now: string): boolean;
39
+ }
40
+ /** 接待与经营通知共用的 stream key 约定。 */
41
+ export declare function streamKey(input: {
42
+ merchant_id: string;
43
+ channel: string;
44
+ scope: string;
45
+ }): string;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * P1 发送流协调门(设计 §16.3 / M6-5)。
18
+ *
19
+ * 接待回复与经营通知共用同一 stream_key(merchant + 渠道 + 会话/收件范围),
20
+ * 同一时刻只允许一条在途。UNKNOWN 未核对前保持占用;结果确认后才释放。
21
+ * 持久实例使用共享 SQLite 租约;投递结果仍以各自 outbox 为准。
22
+ */
23
+ import { constants, fchmodSync, fstatSync, openSync, closeSync } from "node:fs";
24
+ import path from "node:path";
25
+ import { DatabaseSync } from "node:sqlite";
26
+ export class StreamGateError extends Error {
27
+ code;
28
+ streamKey;
29
+ constructor(streamKey) {
30
+ super(`发送流 ${streamKey} 已有在途通知`);
31
+ this.name = "StreamGateError";
32
+ this.code = "stream_busy";
33
+ this.streamKey = streamKey;
34
+ }
35
+ }
36
+ export class StreamGate {
37
+ db;
38
+ holders = new Map();
39
+ constructor(db) {
40
+ this.db = db;
41
+ db?.exec(`
42
+ CREATE TABLE IF NOT EXISTS delivery_stream_leases (
43
+ stream_key TEXT PRIMARY KEY, holder_id TEXT NOT NULL, lease_expires_at TEXT NOT NULL
44
+ )
45
+ `);
46
+ }
47
+ static forDataDir(dataDir) {
48
+ const file = path.join(dataDir, "delivery-streams.sqlite");
49
+ const fd = openSync(file, constants.O_CREAT | constants.O_NOFOLLOW | constants.O_RDWR, 0o600);
50
+ try {
51
+ const stat = fstatSync(fd);
52
+ if (!stat.isFile() || stat.nlink !== 1)
53
+ throw new Error("Invalid delivery stream database");
54
+ fchmodSync(fd, 0o600);
55
+ }
56
+ finally {
57
+ closeSync(fd);
58
+ }
59
+ const db = new DatabaseSync(file);
60
+ try {
61
+ db.exec("PRAGMA busy_timeout = 3000");
62
+ return new StreamGate(db);
63
+ }
64
+ catch (error) {
65
+ db.close();
66
+ throw error;
67
+ }
68
+ }
69
+ close() {
70
+ this.db?.close();
71
+ }
72
+ /** 申请进入发送流;已有未过期 holder 时拒绝。 */
73
+ enter(input) {
74
+ if (!Number.isSafeInteger(input.lease_ms) || input.lease_ms <= 0) {
75
+ throw new Error("lease_ms must be a positive integer");
76
+ }
77
+ const expiresAt = new Date(Date.parse(input.now) + input.lease_ms).toISOString();
78
+ if (this.db !== undefined) {
79
+ const result = this.db.prepare(`INSERT INTO delivery_stream_leases (stream_key, holder_id, lease_expires_at)
80
+ VALUES (?, ?, ?) ON CONFLICT(stream_key) DO UPDATE SET
81
+ holder_id = excluded.holder_id, lease_expires_at = excluded.lease_expires_at
82
+ WHERE delivery_stream_leases.lease_expires_at <= ?
83
+ OR delivery_stream_leases.holder_id = excluded.holder_id`).run(input.stream_key, input.holder_id, expiresAt, input.now);
84
+ if (result.changes === 0)
85
+ throw new StreamGateError(input.stream_key);
86
+ return;
87
+ }
88
+ const current = this.holders.get(input.stream_key);
89
+ if (current !== undefined &&
90
+ Date.parse(current.lease_expires_at) > Date.parse(input.now) &&
91
+ current.holder_id !== input.holder_id) {
92
+ throw new StreamGateError(input.stream_key);
93
+ }
94
+ this.holders.set(input.stream_key, {
95
+ holder_id: input.holder_id,
96
+ lease_expires_at: expiresAt,
97
+ });
98
+ }
99
+ /** 结果确定(SENT/not_sent)后释放;UNKNOWN 不释放。 */
100
+ leave(stream_key, holder_id) {
101
+ if (this.db !== undefined) {
102
+ this.db.prepare("DELETE FROM delivery_stream_leases WHERE stream_key = ? AND holder_id = ?")
103
+ .run(stream_key, holder_id);
104
+ return;
105
+ }
106
+ const current = this.holders.get(stream_key);
107
+ if (current?.holder_id === holder_id)
108
+ this.holders.delete(stream_key);
109
+ }
110
+ isHeld(stream_key, now) {
111
+ if (this.db !== undefined) {
112
+ return this.db.prepare("SELECT 1 FROM delivery_stream_leases WHERE stream_key = ? AND lease_expires_at > ?")
113
+ .get(stream_key, now) !== undefined;
114
+ }
115
+ const current = this.holders.get(stream_key);
116
+ return current !== undefined && Date.parse(current.lease_expires_at) > Date.parse(now);
117
+ }
118
+ }
119
+ /** 接待与经营通知共用的 stream key 约定。 */
120
+ export function streamKey(input) {
121
+ return `${input.merchant_id}:${input.channel}:${input.scope}`;
122
+ }
123
+ //# sourceMappingURL=stream-gate.js.map