@ahoo-wang/wow-client 10.0.0-beta.1 → 10.0.0-beta.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 (233) hide show
  1. package/README.md +4 -2
  2. package/README.zh-CN.md +1 -1
  3. package/dist/commands.cjs +1 -1
  4. package/dist/commands.cjs.map +1 -1
  5. package/dist/commands.d.cts +1 -8
  6. package/dist/commands.d.ts +1 -8
  7. package/dist/commands.es.js +45 -51
  8. package/dist/commands.es.js.map +1 -1
  9. package/dist/dsl/aggregation/admit.cjs +1 -1
  10. package/dist/dsl/aggregation/admit.cjs.map +1 -1
  11. package/dist/dsl/aggregation/admit.es.js +73 -69
  12. package/dist/dsl/aggregation/admit.es.js.map +1 -1
  13. package/dist/dsl/aggregation/aliases.cjs +2 -0
  14. package/dist/dsl/aggregation/aliases.cjs.map +1 -0
  15. package/dist/dsl/aggregation/aliases.d.cts +2 -0
  16. package/dist/dsl/aggregation/aliases.d.ts +2 -0
  17. package/dist/dsl/aggregation/aliases.es.js +13 -0
  18. package/dist/dsl/aggregation/aliases.es.js.map +1 -0
  19. package/dist/dsl/aggregation/builders.cjs +1 -1
  20. package/dist/dsl/aggregation/builders.cjs.map +1 -1
  21. package/dist/dsl/aggregation/builders.d.cts +17 -243
  22. package/dist/dsl/aggregation/builders.d.ts +17 -243
  23. package/dist/dsl/aggregation/builders.es.js +36 -171
  24. package/dist/dsl/aggregation/builders.es.js.map +1 -1
  25. package/dist/dsl/aggregation/derived.cjs +1 -1
  26. package/dist/dsl/aggregation/derived.cjs.map +1 -1
  27. package/dist/dsl/aggregation/derived.d.cts +123 -1
  28. package/dist/dsl/aggregation/derived.d.ts +123 -1
  29. package/dist/dsl/aggregation/derived.es.js +43 -28
  30. package/dist/dsl/aggregation/derived.es.js.map +1 -1
  31. package/dist/dsl/aggregation/groups.cjs +2 -0
  32. package/dist/dsl/aggregation/groups.cjs.map +1 -0
  33. package/dist/dsl/aggregation/groups.d.cts +325 -0
  34. package/dist/dsl/aggregation/groups.d.ts +325 -0
  35. package/dist/dsl/aggregation/groups.es.js +80 -0
  36. package/dist/dsl/aggregation/groups.es.js.map +1 -0
  37. package/dist/dsl/aggregation/having.cjs +1 -1
  38. package/dist/dsl/aggregation/having.cjs.map +1 -1
  39. package/dist/dsl/aggregation/having.d.cts +63 -1
  40. package/dist/dsl/aggregation/having.d.ts +63 -1
  41. package/dist/dsl/aggregation/having.es.js +33 -30
  42. package/dist/dsl/aggregation/having.es.js.map +1 -1
  43. package/dist/dsl/aggregation/index.d.cts +4 -2
  44. package/dist/dsl/aggregation/index.d.ts +4 -2
  45. package/dist/dsl/aggregation/metrics.cjs +2 -0
  46. package/dist/dsl/aggregation/metrics.cjs.map +1 -0
  47. package/dist/dsl/aggregation/metrics.d.cts +279 -0
  48. package/dist/dsl/aggregation/metrics.d.ts +279 -0
  49. package/dist/dsl/aggregation/metrics.es.js +75 -0
  50. package/dist/dsl/aggregation/metrics.es.js.map +1 -0
  51. package/dist/dsl/aggregation/types.cjs +1 -1
  52. package/dist/dsl/aggregation/types.cjs.map +1 -1
  53. package/dist/dsl/aggregation/types.d.cts +4 -524
  54. package/dist/dsl/aggregation/types.d.ts +4 -524
  55. package/dist/dsl/aggregation/types.es.js +5 -25
  56. package/dist/dsl/aggregation/types.es.js.map +1 -1
  57. package/dist/dsl/cursorQuery.cjs +1 -1
  58. package/dist/dsl/cursorQuery.cjs.map +1 -1
  59. package/dist/dsl/cursorQuery.d.cts +18 -7
  60. package/dist/dsl/cursorQuery.d.ts +18 -7
  61. package/dist/dsl/cursorQuery.es.js +13 -12
  62. package/dist/dsl/cursorQuery.es.js.map +1 -1
  63. package/dist/dsl/descriptor.cjs +1 -1
  64. package/dist/dsl/descriptor.cjs.map +1 -1
  65. package/dist/dsl/descriptor.d.cts +17 -379
  66. package/dist/dsl/descriptor.d.ts +17 -379
  67. package/dist/dsl/descriptor.es.js +4 -31
  68. package/dist/dsl/descriptor.es.js.map +1 -1
  69. package/dist/dsl/fieldDescriptor.cjs +2 -0
  70. package/dist/dsl/fieldDescriptor.cjs.map +1 -0
  71. package/dist/dsl/fieldDescriptor.d.cts +246 -0
  72. package/dist/dsl/fieldDescriptor.d.ts +246 -0
  73. package/dist/dsl/fieldDescriptor.es.js +24 -0
  74. package/dist/dsl/fieldDescriptor.es.js.map +1 -0
  75. package/dist/dsl/filter/builders.cjs +1 -1
  76. package/dist/dsl/filter/builders.cjs.map +1 -1
  77. package/dist/dsl/filter/builders.d.cts +7 -949
  78. package/dist/dsl/filter/builders.d.ts +7 -949
  79. package/dist/dsl/filter/builders.es.js +14 -285
  80. package/dist/dsl/filter/builders.es.js.map +1 -1
  81. package/dist/dsl/filter/expressionFilter.cjs +2 -0
  82. package/dist/dsl/filter/expressionFilter.cjs.map +1 -0
  83. package/dist/dsl/filter/expressionFilter.d.cts +35 -0
  84. package/dist/dsl/filter/expressionFilter.d.ts +35 -0
  85. package/dist/dsl/filter/expressionFilter.es.js +18 -0
  86. package/dist/dsl/filter/expressionFilter.es.js.map +1 -0
  87. package/dist/dsl/filter/fieldFilters.cjs +2 -0
  88. package/dist/dsl/filter/fieldFilters.cjs.map +1 -0
  89. package/dist/dsl/filter/fieldFilters.d.cts +297 -0
  90. package/dist/dsl/filter/fieldFilters.d.ts +297 -0
  91. package/dist/dsl/filter/fieldFilters.es.js +110 -0
  92. package/dist/dsl/filter/fieldFilters.es.js.map +1 -0
  93. package/dist/dsl/filter/index.d.cts +2 -1
  94. package/dist/dsl/filter/index.d.ts +2 -1
  95. package/dist/dsl/filter/logicalFilters.cjs +2 -0
  96. package/dist/dsl/filter/logicalFilters.cjs.map +1 -0
  97. package/dist/dsl/filter/logicalFilters.d.cts +109 -0
  98. package/dist/dsl/filter/logicalFilters.d.ts +109 -0
  99. package/dist/dsl/filter/logicalFilters.es.js +36 -0
  100. package/dist/dsl/filter/logicalFilters.es.js.map +1 -0
  101. package/dist/dsl/filter/metadataFilters.cjs +2 -0
  102. package/dist/dsl/filter/metadataFilters.cjs.map +1 -0
  103. package/dist/dsl/filter/metadataFilters.d.cts +132 -0
  104. package/dist/dsl/filter/metadataFilters.d.ts +132 -0
  105. package/dist/dsl/filter/metadataFilters.es.js +56 -0
  106. package/dist/dsl/filter/metadataFilters.es.js.map +1 -0
  107. package/dist/dsl/filter/operator.cjs +1 -1
  108. package/dist/dsl/filter/operator.cjs.map +1 -1
  109. package/dist/dsl/filter/operator.d.cts +11 -9
  110. package/dist/dsl/filter/operator.d.ts +11 -9
  111. package/dist/dsl/filter/operator.es.js +1 -1
  112. package/dist/dsl/filter/operator.es.js.map +1 -1
  113. package/dist/dsl/filter/searchFilter.cjs +2 -0
  114. package/dist/dsl/filter/searchFilter.cjs.map +1 -0
  115. package/dist/dsl/filter/searchFilter.d.cts +39 -0
  116. package/dist/dsl/filter/searchFilter.d.ts +39 -0
  117. package/dist/dsl/filter/searchFilter.es.js +19 -0
  118. package/dist/dsl/filter/searchFilter.es.js.map +1 -0
  119. package/dist/dsl/filter/timeFilters.cjs +2 -0
  120. package/dist/dsl/filter/timeFilters.cjs.map +1 -0
  121. package/dist/dsl/filter/timeFilters.d.cts +290 -0
  122. package/dist/dsl/filter/timeFilters.d.ts +290 -0
  123. package/dist/dsl/filter/timeFilters.es.js +89 -0
  124. package/dist/dsl/filter/timeFilters.es.js.map +1 -0
  125. package/dist/dsl/filter/types.d.cts +4 -14
  126. package/dist/dsl/filter/types.d.ts +4 -14
  127. package/dist/dsl/filter/validate.cjs +1 -1
  128. package/dist/dsl/filter/validate.cjs.map +1 -1
  129. package/dist/dsl/filter/validate.d.cts +2 -4
  130. package/dist/dsl/filter/validate.d.ts +2 -4
  131. package/dist/dsl/filter/validate.es.js +25 -31
  132. package/dist/dsl/filter/validate.es.js.map +1 -1
  133. package/dist/dsl/queryErrorCodes.cjs +1 -1
  134. package/dist/dsl/queryErrorCodes.cjs.map +1 -1
  135. package/dist/dsl/queryErrorCodes.d.cts +0 -2
  136. package/dist/dsl/queryErrorCodes.d.ts +0 -2
  137. package/dist/dsl/queryErrorCodes.es.js +0 -1
  138. package/dist/dsl/queryErrorCodes.es.js.map +1 -1
  139. package/dist/dsl/queryFilter.cjs +2 -0
  140. package/dist/dsl/queryFilter.cjs.map +1 -0
  141. package/dist/dsl/queryFilter.d.cts +3 -0
  142. package/dist/dsl/queryFilter.d.ts +3 -0
  143. package/dist/dsl/queryFilter.es.js +9 -0
  144. package/dist/dsl/queryFilter.es.js.map +1 -0
  145. package/dist/dsl/queryable.cjs +1 -1
  146. package/dist/dsl/queryable.cjs.map +1 -1
  147. package/dist/dsl/queryable.es.js +12 -16
  148. package/dist/dsl/queryable.es.js.map +1 -1
  149. package/dist/dsl/semanticTypes.cjs +2 -0
  150. package/dist/dsl/semanticTypes.cjs.map +1 -0
  151. package/dist/dsl/semanticTypes.d.cts +128 -0
  152. package/dist/dsl/semanticTypes.d.ts +128 -0
  153. package/dist/dsl/semanticTypes.es.js +13 -0
  154. package/dist/dsl/semanticTypes.es.js.map +1 -0
  155. package/dist/dsl.cjs +1 -1
  156. package/dist/dsl.d.cts +2 -0
  157. package/dist/dsl.d.ts +2 -0
  158. package/dist/dsl.es.js +14 -8
  159. package/dist/exactJson.cjs +2 -2
  160. package/dist/exactJson.cjs.map +1 -1
  161. package/dist/exactJson.d.cts +41 -16
  162. package/dist/exactJson.d.ts +41 -16
  163. package/dist/exactJson.es.js +104 -102
  164. package/dist/exactJson.es.js.map +1 -1
  165. package/dist/frameworkErrors.cjs.map +1 -1
  166. package/dist/frameworkErrors.d.cts +4 -4
  167. package/dist/frameworkErrors.d.ts +4 -4
  168. package/dist/frameworkErrors.es.js.map +1 -1
  169. package/dist/http.cjs +1 -1
  170. package/dist/http.cjs.map +1 -1
  171. package/dist/http.d.cts +29 -9
  172. package/dist/http.d.ts +29 -9
  173. package/dist/http.es.js +24 -19
  174. package/dist/http.es.js.map +1 -1
  175. package/dist/index.cjs +1 -1
  176. package/dist/index.d.cts +3 -3
  177. package/dist/index.d.ts +3 -3
  178. package/dist/index.es.js +12 -12
  179. package/dist/manifest.cjs +1 -1
  180. package/dist/manifest.cjs.map +1 -1
  181. package/dist/manifest.d.cts +24 -0
  182. package/dist/manifest.d.ts +24 -0
  183. package/dist/manifest.es.js +34 -6
  184. package/dist/manifest.es.js.map +1 -1
  185. package/dist/manifestTypes.d.cts +16 -1
  186. package/dist/manifestTypes.d.ts +16 -1
  187. package/dist/queries.cjs +1 -1
  188. package/dist/queries.cjs.map +1 -1
  189. package/dist/queries.d.cts +18 -8
  190. package/dist/queries.d.ts +18 -8
  191. package/dist/queries.es.js +46 -35
  192. package/dist/queries.es.js.map +1 -1
  193. package/dist/routes.cjs +1 -1
  194. package/dist/routes.cjs.map +1 -1
  195. package/dist/routes.d.cts +16 -3
  196. package/dist/routes.d.ts +16 -3
  197. package/dist/routes.es.js +24 -25
  198. package/dist/routes.es.js.map +1 -1
  199. package/dist/state.cjs +1 -1
  200. package/dist/state.cjs.map +1 -1
  201. package/dist/state.d.cts +21 -19
  202. package/dist/state.d.ts +21 -19
  203. package/dist/state.es.js +27 -22
  204. package/dist/state.es.js.map +1 -1
  205. package/dist/streams.cjs +1 -1
  206. package/dist/streams.cjs.map +1 -1
  207. package/dist/streams.d.cts +14 -7
  208. package/dist/streams.d.ts +14 -7
  209. package/dist/streams.es.js +65 -50
  210. package/dist/streams.es.js.map +1 -1
  211. package/dist/testing/wire.cjs +1 -1
  212. package/dist/testing/wire.cjs.map +1 -1
  213. package/dist/testing/wire.es.js +1 -1
  214. package/dist/testing/wire.es.js.map +1 -1
  215. package/dist/wait.cjs +1 -1
  216. package/dist/wait.cjs.map +1 -1
  217. package/dist/wait.d.cts +17 -4
  218. package/dist/wait.d.ts +17 -4
  219. package/dist/wait.es.js +36 -34
  220. package/dist/wait.es.js.map +1 -1
  221. package/dist/wire.cjs +1 -1
  222. package/dist/wire.cjs.map +1 -1
  223. package/dist/wire.d.cts +75 -31
  224. package/dist/wire.d.ts +75 -31
  225. package/dist/wire.es.js +1 -3
  226. package/dist/wire.es.js.map +1 -1
  227. package/package.json +5 -5
  228. package/dist/dsl/filter/datePattern.cjs +0 -2
  229. package/dist/dsl/filter/datePattern.cjs.map +0 -1
  230. package/dist/dsl/filter/datePattern.d.cts +0 -8
  231. package/dist/dsl/filter/datePattern.d.ts +0 -8
  232. package/dist/dsl/filter/datePattern.es.js +0 -96
  233. package/dist/dsl/filter/datePattern.es.js.map +0 -1
package/README.md CHANGED
@@ -95,13 +95,15 @@ const result = await commands.wait({
95
95
  sent by its route as the service's Manifest lists it: the Manifest the client
96
96
  is given (`new CommandClient(options, { manifest })`, a whole Manifest or a
97
97
  generated client's `manifest.ts`, its routes alone), else the service's,
98
- fetched once (`GET /wow/manifest`). A command that
98
+ fetched once (`GET /wow/manifest`) for every command waiting on it; a
99
+ command's `signal` ends its own wait, and a failed fetch rejects each command
100
+ with an error of its own, carrying its request id. A command that
99
101
  may create its aggregate leaves `id` out and goes by the route without one. As with Kotlin's `CommandClient`,
100
102
  `send` answers once the command is accepted, `wait` with the result its plan
101
103
  ends with (the server's default plan when there is none), and `stream` one
102
104
  `CommandResult` per hop. `wait` is a `WaitPlan`, as Kotlin's:
103
105
  `WaitPlan.ACCEPTED`, `COMMITTED`, `SNAPSHOT`, or `WaitPlan.of(...hops)` of the
104
- `wait` hops (`accepted`, `committed`, `snapshot`, or a subscription's
106
+ `wait` hops (`accepted`, `committed`, `snapshot`, `queryable`, or a subscription's
105
107
  `handled`, also across a saga's derived commands), `.within(ms)` its timeout;
106
108
  `timeout` is in milliseconds and overrides it. `parseWaitPlan` and
107
109
  `formatWaitPlan` read and write the `Wow-Wait` header. `targetTenant` and `targetScope`
package/README.zh-CN.md CHANGED
@@ -91,7 +91,7 @@ const result = await commands.wait({
91
91
  与 Kotlin 的 `CommandClient` 一样,`send` 在命令被接受后应答,`wait` 以等待计划最后
92
92
  一跳的结果应答(没有计划时用服务端的默认计划),`stream` 每到一跳应答一个
93
93
  `CommandResult`。`wait` 是与 Kotlin 一致的 `WaitPlan`:`WaitPlan.ACCEPTED`、`COMMITTED`、
94
- `SNAPSHOT`,或由 `wait` 各跳(`accepted`、`committed`、`snapshot`,或某个订阅的 `handled`,
94
+ `SNAPSHOT`,或由 `wait` 各跳(`accepted`、`committed`、`snapshot`、`queryable`,或某个订阅的 `handled`,
95
95
  也可以跨过 Saga 派生的命令)组成的 `WaitPlan.of(...hops)`,`.within(ms)` 给它超时;
96
96
  `timeout` 以毫秒计并覆盖计划的超时。`parseWaitPlan` 和 `formatWaitPlan` 读写 `Wow-Wait` 头。`targetTenant` 和
97
97
  `targetScope`(`{ ownerId?, spaceId? }`)在另一个租户、所有者或空间中操作。
package/dist/commands.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./frameworkErrors.cjs"),t=require("./wire.cjs"),n=require("./problem.cjs"),r=require("./http.cjs"),i=require("./manifest.cjs"),a=require("./streams.cjs"),o=require("./wait.cjs");var s={DELETE_AGGREGATE:`wow.lifecycle.DeleteAggregate`,RESTORE_AGGREGATE:`wow.lifecycle.RestoreAggregate`,TRANSFER_OWNER:`wow.lifecycle.TransferOwner`,TRANSFER_SPACE:`wow.lifecycle.TransferSpace`,APPLY_TAGS:`wow.lifecycle.ApplyTags`};function c(){let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return[n.slice(0,4),n.slice(4,6),n.slice(6,8),n.slice(8,10),n.slice(10,16)].map(e=>e.join(``)).join(`-`)}async function l(e,t){try{return await t()}catch(t){throw n.rememberRequestId(t,e),t}}var u=`wow.`,d=`{id}`;function f(e){return e.hops.length===1&&e.hops[0].stage===t.Stage.ACCEPTED}function p(e){return e.timeout===void 0?e.wait:(e.wait??o.WaitPlan.DEFAULT).within(e.timeout)}function m(e,t,n){let r=t.find(e=>e.path.includes(d)===(n!==void 0));if(r===void 0)throw TypeError(n===void 0?`${e.command} has no route without an aggregate id: set the request's id.`:`${e.command} has no route to an aggregate by its id: send it without an id.`);if(n===``)throw TypeError(`The path ${r.path} of ${e.command} needs id.`);let i=r.method;if(i!==`POST`&&i!==`DELETE`)throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);return{method:i,path:n===void 0?r.path:r.path.replace(d,encodeURIComponent(n))}}function h(e,t){let n=e.body??{},r=e.id;if(t===void 0||r===void 0)return n;let i=n[t];if(i==null)return{...n,[t]:r};if(i!==r)throw TypeError(`The request names the aggregate ${r}, but the body of ${e.command} names ${String(i)}: send it without an id.`);return n}function g(e){let t=e.split(`.`);if(t.length<3||t.some(e=>e===``))throw TypeError(`${e} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`);return{context:t[0],name:t[1]}}function _(e,t,n,i){return{[r.WowHeaders.REQUEST_ID]:n,[r.WowHeaders.WAIT]:t===void 0||t.isDefault?void 0:o.formatWaitPlan(t),[r.WowHeaders.WAIT_TIMEOUT]:t!==void 0&&(e.timeout!==void 0||t.timeout!==o.WaitPlan.DEFAULT_TIMEOUT)?o.formatWaitTimeout(t.timeout):void 0,[r.WowHeaders.IF_MATCH]:e.expectedVersion===void 0?void 0:`"${e.expectedVersion}"`,Accept:i}}function v(e){if(e.targetTenant!==void 0||e.targetScope!==void 0)return{tenantId:e.targetTenant,...e.targetScope}}var y=class{constructor(e={},t={}){this.client=e,this.manifest=t.manifest===void 0?void 0:Promise.resolve(i.checkManifest(t.manifest)),this.bodyNumbers=t.bodyNumbers??{}}async send(e){let t=p(e);if(t!==void 0&&!t.isDefault&&!f(t))throw TypeError(`send answers on acceptance: use wait() for the plan ${o.formatWaitPlan(t)}.`);return this.exchange(e,o.WaitPlan.ACCEPTED.within(e.timeout??o.WaitPlan.DEFAULT_TIMEOUT))}wait(e){return this.exchange(e,p(e))}async stream(e){let t=e.requestId??c();return l(t,async()=>a.commandResults(await this.post(e,p(e),t,`text/event-stream`)))}async exchange(e,i){let a=e.requestId??c();return l(a,async()=>{let o;try{o=await r.json(await this.post(e,i,a))}catch(e){throw e instanceof n.WowProblemError&&e.result?.status===t.CommandResultStatus.REJECTED?new n.CommandRejectedError(e.result,{problem:e.problem,cause:e}):e}return b(o)})}async post(e,t,n,i){let a=await this.commandOf(e),o=a.idProperty,s=m(e,a.routes,o===void 0?e.id:void 0),c=v(e),l=this.bodyNumbers[e.command];return r.send(this.client,{method:s.method,path:s.path,headers:_(e,t,n,i),...s.method===`DELETE`?{}:{body:h(e,o)},...l===void 0?{}:{bodyNumbers:l},options:{...c===void 0?{}:{scope:c},...e.space===void 0?{}:{space:e.space},...e.headers===void 0?{}:{headers:e.headers},...e.signal===void 0?{}:{signal:e.signal}}})}async commandOf(e){let t=e.command,n=t.startsWith(u),r=e.type??(n?void 0:g(t));if(r===void 0)throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);let i=`${r.context}.${r.name}.`,a=t.startsWith(i)?t.slice(i.length):t,o=(await this.manifestOf()).contexts.find(e=>e.name===r.context),s=o?.aggregates?.find(e=>e.name===r.name)?.commands?.find(e=>e.name===a||e.aliases?.includes(a)===!0)??(n?o?.commands?.find(e=>e.name===a):void 0);if(s?.routes===void 0)throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);return s}manifestOf(){return this.manifest??=i.fetchManifest(this.client).catch(e=>{throw this.manifest=void 0,e}),this.manifest}};function b(r){if(r.status===t.CommandResultStatus.REJECTED)throw new n.CommandRejectedError(r);if(!x.has(r.status))throw new n.WowProblemError({type:`urn:wow:error:${e.FrameworkErrorCodes.COMMAND_FAILED}`,title:`Unknown command status`,status:200,code:e.FrameworkErrorCodes.COMMAND_FAILED,detail:`The command was answered with the status ${r.status}, which this client does not know: the service is newer than this client, so upgrade it.`,result:r});return r}var x=new Set(Object.values(t.CommandResultStatus));exports.CommandClient=y,exports.LifecycleCommands=s,exports.newRequestId=c;
1
+ const e=require("./frameworkErrors.cjs"),t=require("./wire.cjs"),n=require("./problem.cjs"),r=require("./http.cjs"),i=require("./manifest.cjs"),a=require("./streams.cjs"),o=require("./wait.cjs");var s={DELETE_AGGREGATE:`wow.lifecycle.DeleteAggregate`,RESTORE_AGGREGATE:`wow.lifecycle.RestoreAggregate`,TRANSFER_OWNER:`wow.lifecycle.TransferOwner`,TRANSFER_SPACE:`wow.lifecycle.TransferSpace`};function c(){let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return[n.slice(0,4),n.slice(4,6),n.slice(6,8),n.slice(8,10),n.slice(10,16)].map(e=>e.join(``)).join(`-`)}async function l(e,t){try{return await t()}catch(t){throw n.rememberRequestId(t,e),t}}var u=`wow.`,d=`{id}`;function f(e){return e.hops.length===1&&e.hops[0].stage===t.Stage.ACCEPTED}function p(e){return e.timeout===void 0?e.wait:(e.wait??o.WaitPlan.DEFAULT).within(e.timeout)}function m(e,t,n){let r=t.find(e=>e.path.includes(d)===(n!==void 0));if(r===void 0)throw TypeError(n===void 0?`${e.command} has no route without an aggregate id: set the request's id.`:`${e.command} has no route to an aggregate by its id: send it without an id.`);if(n===``)throw TypeError(`The path ${r.path} of ${e.command} needs id.`);let i=r.method;if(i!==`POST`&&i!==`DELETE`)throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);return{method:i,path:n===void 0?r.path:r.path.replace(d,encodeURIComponent(n))}}function h(e,t){let n=e.body??{},r=e.id;if(t===void 0||r===void 0)return n;let i=n[t];if(i==null)return{...n,[t]:r};if(i!==r)throw TypeError(`The request names the aggregate ${r}, but the body of ${e.command} names ${String(i)}: send it without an id.`);return n}function g(e){let t=e.split(`.`);if(t.length<3||t.some(e=>e===``))throw TypeError(`${e} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`);return{context:t[0],name:t[1]}}function _(e,t,n,i){return{[r.WowHeaders.REQUEST_ID]:n,[r.WowHeaders.WAIT]:t===void 0||t.isDefault?void 0:o.formatWaitPlan(t),[r.WowHeaders.WAIT_TIMEOUT]:t!==void 0&&(e.timeout!==void 0||t.timeout!==o.WaitPlan.DEFAULT_TIMEOUT)?o.formatWaitTimeout(t.timeout):void 0,[r.WowHeaders.IF_MATCH]:e.expectedVersion===void 0?void 0:`"${e.expectedVersion}"`,Accept:i}}function v(e){if(e.targetTenant!==void 0||e.targetScope!==void 0)return{tenantId:e.targetTenant,...e.targetScope}}var y=class{constructor(e={},t={}){this.client=e,this.manifest=new i.ManifestSource(e,t.manifest),this.bodyNumbers=t.bodyNumbers??{}}async send(e){let t=p(e);if(t!==void 0&&!t.isDefault&&!f(t))throw TypeError(`send answers on acceptance: use wait() for the plan ${o.formatWaitPlan(t)}.`);return this.exchange(e,o.WaitPlan.ACCEPTED.within(e.timeout??o.WaitPlan.DEFAULT_TIMEOUT))}wait(e){return this.exchange(e,p(e))}async stream(e){let t=e.requestId??c();return l(t,async()=>a.commandResults(await this.post(e,p(e),t,`text/event-stream`),t))}async exchange(e,r){let i=e.requestId??c();return l(i,async()=>{let a;try{a=await(await this.post(e,r,i)).json()}catch(e){throw e instanceof n.WowProblemError&&e.result?.status===t.CommandResultStatus.REJECTED?new n.CommandRejectedError(e.result,{problem:e.problem,cause:e}):e}return b(a)})}async post(e,t,n,i){let a=await this.commandOf(e),o=a.idProperty,s=m(e,a.routes,o===void 0?e.id:void 0),c=v(e),l=this.bodyNumbers[e.command];return r.send(this.client,{method:s.method,path:s.path,headers:_(e,t,n,i),...s.method===`DELETE`?{}:{body:h(e,o)},numbers:{body:l},options:{...c===void 0?{}:{scope:c},...e.space===void 0?{}:{space:e.space},...e.headers===void 0?{}:{headers:e.headers},...e.signal===void 0?{}:{signal:e.signal}}})}async commandOf(e){let t=e.command,n=t.startsWith(u),r=e.type??(n?void 0:g(t));if(r===void 0)throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);let i=`${r.context}.${r.name}.`,a=t.startsWith(i)?t.slice(i.length):t,o=(await this.manifest.read(e.signal)).contexts.find(e=>e.name===r.context),s=o?.aggregates?.find(e=>e.name===r.name)?.commands?.find(e=>e.name===a||e.aliases?.includes(a)===!0)??(n?o?.commands?.find(e=>e.name===a):void 0);if(s?.routes===void 0)throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);return s}};function b(r){if(r.status===t.CommandResultStatus.REJECTED)throw new n.CommandRejectedError(r);if(!x.has(r.status))throw new n.WowProblemError({type:`urn:wow:error:${e.FrameworkErrorCodes.COMMAND_FAILED}`,title:`Unknown command status`,status:200,code:e.FrameworkErrorCodes.COMMAND_FAILED,detail:`The command was answered with the status ${r.status}, which this client does not know: the service is newer than this client, so upgrade it.`,result:r});return r}var x=new Set(Object.values(t.CommandResultStatus));exports.CommandClient=y,exports.LifecycleCommands=s,exports.newRequestId=c;
2
2
  //# sourceMappingURL=commands.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands.cjs","names":["Stage","WaitPlan","WowHeaders","formatWaitPlan","formatWaitTimeout","checkManifest","commandResults","json","WowProblemError","CommandResultStatus","CommandRejectedError","send","fetchManifest","FrameworkErrorCodes","require_frameworkErrors","require_wire","require_problem","require_http","require_manifest","require_streams","require_wait","LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","planOf","request","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","accept","targetOf","CommandClient","client","options","result","settled","declared","scope","bodyNumbers","system","type","prefix","name","context","aggregate","KNOWN_STATUSES"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n json,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n checkManifest,\n fetchManifest,\n type RouteManifest,\n type RoutingCommand,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it. A command whose body names its aggregate (the\n * Manifest's `idProperty`) goes by that route too, whether `id` is given or\n * not: a given one is the one its body names, or is written into a body\n * that names none.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/**\n * The route of `request` among `routes`, by `id` (the request's, none for a\n * command whose body names its aggregate): its method and path, the id in it.\n * An empty id is refused before anything is sent: it would leave the path's\n * segment empty (`/<context>/<aggregate>//…`), a route no service has.\n */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n id: string | undefined,\n): { method: 'POST' | 'DELETE'; path: string } {\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n if (id === '') {\n throw new TypeError(\n `The path ${route.path} of ${request.command} needs id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/**\n * The body `request` sends, `{}` when it has none. Of a command whose body\n * names its aggregate in `idProperty`, the route has no id: the request's id,\n * when it names one, is the body's too, written into a body that names none.\n *\n * @throws TypeError when the body names another aggregate than the request\n */\nfunction bodyOf(\n request: CommandRequest,\n idProperty: string | undefined,\n): object {\n const body = request.body ?? {};\n const id = request.id;\n if (idProperty === undefined || id === undefined) return body;\n const named: unknown = (body as Record<string, unknown>)[idProperty];\n if (named === undefined || named === null) {\n return { ...body, [idProperty]: id };\n }\n if (named !== id) {\n throw new TypeError(\n `The request names the aggregate ${id}, but the body of ${request.command} names ${String(named)}: send it without an id.`,\n );\n }\n return body;\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private manifest: Promise<RoutingManifest> | undefined;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await json<CommandResult<R>>(\n await this.post(request, plan, requestId),\n );\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n const declared = await this.commandOf(request);\n const idProperty = declared.idProperty;\n const route = routeOf(\n request,\n declared.routes,\n idProperty === undefined ? request.id : undefined,\n );\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE'\n ? {}\n : { body: bodyOf(request, idProperty) }),\n ...(bodyNumbers === undefined ? {} : { bodyNumbers }),\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * `request`'s command as the Manifest lists it, with its routes: a domain\n * command among its aggregate's commands, by name or former name; a system\n * command among its type's, else among its context's (a job's).\n */\n private async commandOf(request: CommandRequest): Promise<RoutingCommand> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifestOf()).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared;\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":"A,mMAsJA,IAAaqB,EAAoB,CAC/B,iBAAkB,gCAClB,kBAAmB,iCACnB,eAAgB,8BAChB,eAAgB,8BAChB,WAAY,yBACd,EA0BA,SAAgBC,GAAuB,CACrC,IAAMC,EAAS,WAAW,OAC1B,GAAI,OAAOA,GAAQ,YAAe,WAAY,OAAOA,EAAO,WAAW,EAEvE,IAAMC,EAAQ,IAAI,WAAW,EAAE,EAC/B,GAAI,OAAOD,GAAQ,iBAAoB,WACrCA,EAAO,gBAAgBC,CAAK,OAE5B,IAAK,IAAIC,EAAQ,EAAGA,EAAQD,EAAM,OAAQ,IACxC,EAAMC,GAAS,KAAK,MAAM,KAAK,OAAO,EAAI,GAAG,EAGjD,EAAM,GAAMD,EAAM,GAAK,GAAQ,GAC/B,EAAM,GAAMA,EAAM,GAAK,GAAQ,IAC/B,IAAME,EAAM,MAAM,KAAKF,EAAO,GAAQG,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,EACxE,MAAO,CACLD,EAAI,MAAM,EAAG,CAAC,EACdA,EAAI,MAAM,EAAG,CAAC,EACdA,EAAI,MAAM,EAAG,CAAC,EACdA,EAAI,MAAM,EAAG,EAAE,EACfA,EAAI,MAAM,GAAI,EAAE,CAClB,CAAC,CACE,IAAI,GAASE,EAAM,KAAK,EAAE,CAAC,CAAC,CAC5B,KAAK,GAAG,CACb,CAGA,eAAeC,EACb,EAC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AClD,IAAA,IACN,GAAIN,GAAU,SAAW,IAAA,GACvB,MAAU,UACR,iCAAiCM,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE,EAEF,OAAOJ,CACT,CAGA,YAA+C,CAK7C,MAJA,MAAK,WAAajD,EAAAA,cAAc,KAAK,MAAM,CAAC,CAAC,MAAO,GAAmB,CAErE,KADA,MAAK,SAAW,IAAA,GACVmB,CACR,CAAC,EACM,KAAK,QACd,CACF,EAQA,SAAS6B,EAAW,EAA4C,CAC9D,GAAID,EAAO,SAAWlD,EAAAA,oBAAoB,SACxC,MAAM,IAAIC,EAAAA,qBAAqBiD,CAAuB,EAExD,GAAI,CAACW,EAAe,IAAIX,EAAO,MAAM,EACnC,MAAM,IAAInD,EAAAA,gBAAgB,CACxB,KAAM,iBAAiBK,EAAAA,oBAAoB,iBAC3C,MAAO,yBACP,OAAQ,IACR,KAAMA,EAAAA,oBAAoB,eAC1B,OAAQ,4CAA4C8C,EAAO,OAAO,0FAC1D,QACV,CAAC,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAO7D,EAAAA,mBAAmB,CACnC,E"}
1
+ {"version":3,"file":"commands.cjs","names":["Stage","WaitPlan","WowHeaders","formatWaitPlan","formatWaitTimeout","ManifestSource","commandResults","WowProblemError","CommandResultStatus","CommandRejectedError","send","FrameworkErrorCodes","require_frameworkErrors","require_wire","require_problem","require_http","require_manifest","require_streams","require_wait","LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","planOf","request","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","accept","targetOf","CommandClient","client","options","result","settled","declared","scope","bodyNumbers","system","type","prefix","name","context","aggregate","KNOWN_STATUSES"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n type Answer,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n ManifestSource,\n type RouteManifest,\n type RoutingCommand,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it. A command whose body names its aggregate (the\n * Manifest's `idProperty`) goes by that route too, whether `id` is given or\n * not: a given one is the one its body names, or is written into a body\n * that names none.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/**\n * The route of `request` among `routes`, by `id` (the request's, none for a\n * command whose body names its aggregate): its method and path, the id in it.\n * An empty id is refused before anything is sent: it would leave the path's\n * segment empty (`/<context>/<aggregate>//…`), a route no service has.\n */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n id: string | undefined,\n): { method: 'POST' | 'DELETE'; path: string } {\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n if (id === '') {\n throw new TypeError(\n `The path ${route.path} of ${request.command} needs id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/**\n * The body `request` sends, `{}` when it has none. Of a command whose body\n * names its aggregate in `idProperty`, the route has no id: the request's id,\n * when it names one, is the body's too, written into a body that names none.\n *\n * @throws TypeError when the body names another aggregate than the request\n */\nfunction bodyOf(\n request: CommandRequest,\n idProperty: string | undefined,\n): object {\n const body = request.body ?? {};\n const id = request.id;\n if (idProperty === undefined || id === undefined) return body;\n const named: unknown = (body as Record<string, unknown>)[idProperty];\n if (named === undefined || named === null) {\n return { ...body, [idProperty]: id };\n }\n if (named !== id) {\n throw new TypeError(\n `The request names the aggregate ${id}, but the body of ${request.command} names ${String(named)}: send it without an id.`,\n );\n }\n return body;\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private readonly manifest: ManifestSource;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest = new ManifestSource(client, options.manifest);\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n requestId,\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Answer> {\n const declared = await this.commandOf(request);\n const idProperty = declared.idProperty;\n const route = routeOf(\n request,\n declared.routes,\n idProperty === undefined ? request.id : undefined,\n );\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE'\n ? {}\n : { body: bodyOf(request, idProperty) }),\n // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: bodyNumbers },\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * `request`'s command as the Manifest lists it, with its routes: a domain\n * command among its aggregate's commands, by name or former name; a system\n * command among its type's, else among its context's (a job's).\n */\n private async commandOf(request: CommandRequest): Promise<RoutingCommand> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifest.read(request.signal)).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedRes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lD,EAAAA,gBAAgB,CACxB,KAAM,iBAAiBI,EAAAA,oBAAoB,iBAC3C,MAAO,yBACP,OAAQ,IACR,KAAMA,EAAAA,oBAAoB,eAC1B,OAAQ,4CAA4C8C,EAAO,OAAO,0FAC1D,QACV,CAAC,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAO5D,EAAAA,mBAAmB,CACnC,E"}
@@ -107,7 +107,6 @@ export declare const LifecycleCommands: {
107
107
  readonly RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate";
108
108
  readonly TRANSFER_OWNER: "wow.lifecycle.TransferOwner";
109
109
  readonly TRANSFER_SPACE: "wow.lifecycle.TransferSpace";
110
- readonly APPLY_TAGS: "wow.lifecycle.ApplyTags";
111
110
  };
112
111
  /** A {@link LifecycleCommands} value. */
113
112
  export type LifecycleCommand = (typeof LifecycleCommands)[keyof typeof LifecycleCommands];
@@ -119,10 +118,6 @@ export interface TransferOwner {
119
118
  export interface TransferSpace {
120
119
  readonly spaceId: string;
121
120
  }
122
- /** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */
123
- export interface ApplyTags {
124
- readonly tags: Readonly<Record<string, readonly string[]>>;
125
- }
126
121
  /**
127
122
  * A new request id (`Wow-Request-Id`): a random UUID. The client generates
128
123
  * one for a command sent without; generate it first to retry with it however
@@ -149,7 +144,7 @@ export declare function newRequestId(): string;
149
144
  */
150
145
  export declare class CommandClient {
151
146
  readonly client: WowClientOptions;
152
- private manifest;
147
+ private readonly manifest;
153
148
  private readonly bodyNumbers;
154
149
  /**
155
150
  * @param client - How the service is reached
@@ -191,6 +186,4 @@ export declare class CommandClient {
191
186
  * command among its type's, else among its context's (a job's).
192
187
  */
193
188
  private commandOf;
194
- /** The Manifest given, or the service's, fetched once (again after a failure). */
195
- private manifestOf;
196
189
  }
@@ -107,7 +107,6 @@ export declare const LifecycleCommands: {
107
107
  readonly RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate";
108
108
  readonly TRANSFER_OWNER: "wow.lifecycle.TransferOwner";
109
109
  readonly TRANSFER_SPACE: "wow.lifecycle.TransferSpace";
110
- readonly APPLY_TAGS: "wow.lifecycle.ApplyTags";
111
110
  };
112
111
  /** A {@link LifecycleCommands} value. */
113
112
  export type LifecycleCommand = (typeof LifecycleCommands)[keyof typeof LifecycleCommands];
@@ -119,10 +118,6 @@ export interface TransferOwner {
119
118
  export interface TransferSpace {
120
119
  readonly spaceId: string;
121
120
  }
122
- /** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */
123
- export interface ApplyTags {
124
- readonly tags: Readonly<Record<string, readonly string[]>>;
125
- }
126
121
  /**
127
122
  * A new request id (`Wow-Request-Id`): a random UUID. The client generates
128
123
  * one for a command sent without; generate it first to retry with it however
@@ -149,7 +144,7 @@ export declare function newRequestId(): string;
149
144
  */
150
145
  export declare class CommandClient {
151
146
  readonly client: WowClientOptions;
152
- private manifest;
147
+ private readonly manifest;
153
148
  private readonly bodyNumbers;
154
149
  /**
155
150
  * @param client - How the service is reached
@@ -191,6 +186,4 @@ export declare class CommandClient {
191
186
  * command among its type's, else among its context's (a job's).
192
187
  */
193
188
  private commandOf;
194
- /** The Manifest given, or the service's, fetched once (again after a failure). */
195
- private manifestOf;
196
189
  }
@@ -1,19 +1,18 @@
1
1
  import { FrameworkErrorCodes as e } from "./frameworkErrors.es.js";
2
2
  import { CommandResultStatus as t, Stage as n } from "./wire.es.js";
3
3
  import { CommandRejectedError as r, WowProblemError as i, rememberRequestId as a } from "./problem.es.js";
4
- import { WowHeaders as o, json as s, send as c } from "./http.es.js";
5
- import { checkManifest as l, fetchManifest as u } from "./manifest.es.js";
6
- import { commandResults as d } from "./streams.es.js";
7
- import { WaitPlan as f, formatWaitPlan as p, formatWaitTimeout as m } from "./wait.es.js";
4
+ import { WowHeaders as o, send as s } from "./http.es.js";
5
+ import { ManifestSource as c } from "./manifest.es.js";
6
+ import { commandResults as l } from "./streams.es.js";
7
+ import { WaitPlan as u, formatWaitPlan as d, formatWaitTimeout as f } from "./wait.es.js";
8
8
  // src/commands.ts
9
- var h = {
9
+ var p = {
10
10
  DELETE_AGGREGATE: "wow.lifecycle.DeleteAggregate",
11
11
  RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate",
12
12
  TRANSFER_OWNER: "wow.lifecycle.TransferOwner",
13
- TRANSFER_SPACE: "wow.lifecycle.TransferSpace",
14
- APPLY_TAGS: "wow.lifecycle.ApplyTags"
13
+ TRANSFER_SPACE: "wow.lifecycle.TransferSpace"
15
14
  };
16
- function g() {
15
+ function m() {
17
16
  let e = globalThis.crypto;
18
17
  if (typeof e?.randomUUID == "function") return e.randomUUID();
19
18
  let t = /* @__PURE__ */ new Uint8Array(16);
@@ -29,32 +28,32 @@ function g() {
29
28
  n.slice(10, 16)
30
29
  ].map((e) => e.join("")).join("-");
31
30
  }
32
- async function _(e, t) {
31
+ async function h(e, t) {
33
32
  try {
34
33
  return await t();
35
34
  } catch (t) {
36
35
  throw a(t, e), t;
37
36
  }
38
37
  }
39
- var v = "wow.", y = "{id}";
40
- function b(e) {
38
+ var g = "wow.", _ = "{id}";
39
+ function v(e) {
41
40
  return e.hops.length === 1 && e.hops[0].stage === n.ACCEPTED;
42
41
  }
43
- function x(e) {
44
- return e.timeout === void 0 ? e.wait : (e.wait ?? f.DEFAULT).within(e.timeout);
42
+ function y(e) {
43
+ return e.timeout === void 0 ? e.wait : (e.wait ?? u.DEFAULT).within(e.timeout);
45
44
  }
46
- function S(e, t, n) {
47
- let r = t.find((e) => e.path.includes(y) === (n !== void 0));
45
+ function b(e, t, n) {
46
+ let r = t.find((e) => e.path.includes(_) === (n !== void 0));
48
47
  if (r === void 0) throw TypeError(n === void 0 ? `${e.command} has no route without an aggregate id: set the request's id.` : `${e.command} has no route to an aggregate by its id: send it without an id.`);
49
48
  if (n === "") throw TypeError(`The path ${r.path} of ${e.command} needs id.`);
50
49
  let i = r.method;
51
50
  if (i !== "POST" && i !== "DELETE") throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);
52
51
  return {
53
52
  method: i,
54
- path: n === void 0 ? r.path : r.path.replace(y, encodeURIComponent(n))
53
+ path: n === void 0 ? r.path : r.path.replace(_, encodeURIComponent(n))
55
54
  };
56
55
  }
57
- function C(e, t) {
56
+ function x(e, t) {
58
57
  let n = e.body ?? {}, r = e.id;
59
58
  if (t === void 0 || r === void 0) return n;
60
59
  let i = n[t];
@@ -65,7 +64,7 @@ function C(e, t) {
65
64
  if (i !== r) throw TypeError(`The request names the aggregate ${r}, but the body of ${e.command} names ${String(i)}: send it without an id.`);
66
65
  return n;
67
66
  }
68
- function w(e) {
67
+ function S(e) {
69
68
  let t = e.split(".");
70
69
  if (t.length < 3 || t.some((e) => e === "")) throw TypeError(`${e} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`);
71
70
  return {
@@ -73,62 +72,62 @@ function w(e) {
73
72
  name: t[1]
74
73
  };
75
74
  }
76
- function T(e, t, n, r) {
75
+ function C(e, t, n, r) {
77
76
  return {
78
77
  [o.REQUEST_ID]: n,
79
- [o.WAIT]: t === void 0 || t.isDefault ? void 0 : p(t),
80
- [o.WAIT_TIMEOUT]: t !== void 0 && (e.timeout !== void 0 || t.timeout !== f.DEFAULT_TIMEOUT) ? m(t.timeout) : void 0,
78
+ [o.WAIT]: t === void 0 || t.isDefault ? void 0 : d(t),
79
+ [o.WAIT_TIMEOUT]: t !== void 0 && (e.timeout !== void 0 || t.timeout !== u.DEFAULT_TIMEOUT) ? f(t.timeout) : void 0,
81
80
  [o.IF_MATCH]: e.expectedVersion === void 0 ? void 0 : `"${e.expectedVersion}"`,
82
81
  Accept: r
83
82
  };
84
83
  }
85
- function E(e) {
84
+ function w(e) {
86
85
  if (e.targetTenant !== void 0 || e.targetScope !== void 0) return {
87
86
  tenantId: e.targetTenant,
88
87
  ...e.targetScope
89
88
  };
90
89
  }
91
- var D = class {
90
+ var T = class {
92
91
  constructor(e = {}, t = {}) {
93
- this.client = e, this.manifest = t.manifest === void 0 ? void 0 : Promise.resolve(l(t.manifest)), this.bodyNumbers = t.bodyNumbers ?? {};
92
+ this.client = e, this.manifest = new c(e, t.manifest), this.bodyNumbers = t.bodyNumbers ?? {};
94
93
  }
95
94
  async send(e) {
96
- let t = x(e);
97
- if (t !== void 0 && !t.isDefault && !b(t)) throw TypeError(`send answers on acceptance: use wait() for the plan ${p(t)}.`);
98
- return this.exchange(e, f.ACCEPTED.within(e.timeout ?? f.DEFAULT_TIMEOUT));
95
+ let t = y(e);
96
+ if (t !== void 0 && !t.isDefault && !v(t)) throw TypeError(`send answers on acceptance: use wait() for the plan ${d(t)}.`);
97
+ return this.exchange(e, u.ACCEPTED.within(e.timeout ?? u.DEFAULT_TIMEOUT));
99
98
  }
100
99
  wait(e) {
101
- return this.exchange(e, x(e));
100
+ return this.exchange(e, y(e));
102
101
  }
103
102
  async stream(e) {
104
- let t = e.requestId ?? g();
105
- return _(t, async () => d(await this.post(e, x(e), t, "text/event-stream")));
103
+ let t = e.requestId ?? m();
104
+ return h(t, async () => l(await this.post(e, y(e), t, "text/event-stream"), t));
106
105
  }
107
106
  async exchange(e, n) {
108
- let a = e.requestId ?? g();
109
- return _(a, async () => {
107
+ let a = e.requestId ?? m();
108
+ return h(a, async () => {
110
109
  let o;
111
110
  try {
112
- o = await s(await this.post(e, n, a));
111
+ o = await (await this.post(e, n, a)).json();
113
112
  } catch (e) {
114
113
  throw e instanceof i && e.result?.status === t.REJECTED ? new r(e.result, {
115
114
  problem: e.problem,
116
115
  cause: e
117
116
  }) : e;
118
117
  }
119
- return O(o);
118
+ return E(o);
120
119
  });
121
120
  }
122
121
  async post(e, t, n, r) {
123
- let i = await this.commandOf(e), a = i.idProperty, o = S(e, i.routes, a === void 0 ? e.id : void 0), s = E(e), l = this.bodyNumbers[e.command];
124
- return c(this.client, {
122
+ let i = await this.commandOf(e), a = i.idProperty, o = b(e, i.routes, a === void 0 ? e.id : void 0), c = w(e), l = this.bodyNumbers[e.command];
123
+ return s(this.client, {
125
124
  method: o.method,
126
125
  path: o.path,
127
- headers: T(e, t, n, r),
128
- ...o.method === "DELETE" ? {} : { body: C(e, a) },
129
- ...l === void 0 ? {} : { bodyNumbers: l },
126
+ headers: C(e, t, n, r),
127
+ ...o.method === "DELETE" ? {} : { body: x(e, a) },
128
+ numbers: { body: l },
130
129
  options: {
131
- ...s === void 0 ? {} : { scope: s },
130
+ ...c === void 0 ? {} : { scope: c },
132
131
  ...e.space === void 0 ? {} : { space: e.space },
133
132
  ...e.headers === void 0 ? {} : { headers: e.headers },
134
133
  ...e.signal === void 0 ? {} : { signal: e.signal }
@@ -136,21 +135,16 @@ var D = class {
136
135
  });
137
136
  }
138
137
  async commandOf(e) {
139
- let t = e.command, n = t.startsWith(v), r = e.type ?? (n ? void 0 : w(t));
138
+ let t = e.command, n = t.startsWith(g), r = e.type ?? (n ? void 0 : S(t));
140
139
  if (r === void 0) throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);
141
- let i = `${r.context}.${r.name}.`, a = t.startsWith(i) ? t.slice(i.length) : t, o = (await this.manifestOf()).contexts.find((e) => e.name === r.context), s = o?.aggregates?.find((e) => e.name === r.name)?.commands?.find((e) => e.name === a || e.aliases?.includes(a) === !0) ?? (n ? o?.commands?.find((e) => e.name === a) : void 0);
140
+ let i = `${r.context}.${r.name}.`, a = t.startsWith(i) ? t.slice(i.length) : t, o = (await this.manifest.read(e.signal)).contexts.find((e) => e.name === r.context), s = o?.aggregates?.find((e) => e.name === r.name)?.commands?.find((e) => e.name === a || e.aliases?.includes(a) === !0) ?? (n ? o?.commands?.find((e) => e.name === a) : void 0);
142
141
  if (s?.routes === void 0) throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);
143
142
  return s;
144
143
  }
145
- manifestOf() {
146
- return this.manifest ??= u(this.client).catch((e) => {
147
- throw this.manifest = void 0, e;
148
- }), this.manifest;
149
- }
150
144
  };
151
- function O(n) {
145
+ function E(n) {
152
146
  if (n.status === t.REJECTED) throw new r(n);
153
- if (!k.has(n.status)) throw new i({
147
+ if (!D.has(n.status)) throw new i({
154
148
  type: `urn:wow:error:${e.COMMAND_FAILED}`,
155
149
  title: "Unknown command status",
156
150
  status: 200,
@@ -160,7 +154,7 @@ function O(n) {
160
154
  });
161
155
  return n;
162
156
  }
163
- var k = new Set(Object.values(t));
164
- export { D as CommandClient, h as LifecycleCommands, g as newRequestId };
157
+ var D = new Set(Object.values(t));
158
+ export { T as CommandClient, p as LifecycleCommands, m as newRequestId };
165
159
 
166
160
  //# sourceMappingURL=commands.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands.es.js","names":["LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","rememberRequestId","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","Stage","planOf","request","WaitPlan","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","options","checkManifest","commandResults","result","json","WowProblemError","CommandResultStatus","CommandRejectedError","settled","declared","scope","bodyNumbers","send","system","type","prefix","name","context","aggregate","fetchManifest","KNOWN_STATUSES","FrameworkErrorCodes"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n json,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n checkManifest,\n fetchManifest,\n type RouteManifest,\n type RoutingCommand,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it. A command whose body names its aggregate (the\n * Manifest's `idProperty`) goes by that route too, whether `id` is given or\n * not: a given one is the one its body names, or is written into a body\n * that names none.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/**\n * The route of `request` among `routes`, by `id` (the request's, none for a\n * command whose body names its aggregate): its method and path, the id in it.\n * An empty id is refused before anything is sent: it would leave the path's\n * segment empty (`/<context>/<aggregate>//…`), a route no service has.\n */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n id: string | undefined,\n): { method: 'POST' | 'DELETE'; path: string } {\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n if (id === '') {\n throw new TypeError(\n `The path ${route.path} of ${request.command} needs id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/**\n * The body `request` sends, `{}` when it has none. Of a command whose body\n * names its aggregate in `idProperty`, the route has no id: the request's id,\n * when it names one, is the body's too, written into a body that names none.\n *\n * @throws TypeError when the body names another aggregate than the request\n */\nfunction bodyOf(\n request: CommandRequest,\n idProperty: string | undefined,\n): object {\n const body = request.body ?? {};\n const id = request.id;\n if (idProperty === undefined || id === undefined) return body;\n const named: unknown = (body as Record<string, unknown>)[idProperty];\n if (named === undefined || named === null) {\n return { ...body, [idProperty]: id };\n }\n if (named !== id) {\n throw new TypeError(\n `The request names the aggregate ${id}, but the body of ${request.command} names ${String(named)}: send it without an id.`,\n );\n }\n return body;\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private manifest: Promise<RoutingManifest> | undefined;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await json<CommandResult<R>>(\n await this.post(request, plan, requestId),\n );\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n const declared = await this.commandOf(request);\n const idProperty = declared.idProperty;\n const route = routeOf(\n request,\n declared.routes,\n idProperty === undefined ? request.id : undefined,\n );\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE'\n ? {}\n : { body: bodyOf(request, idProperty) }),\n ...(bodyNumbers === undefined ? {} : { bodyNumbers }),\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * `request`'s command as the Manifest lists it, with its routes: a domain\n * command among its aggregate's commands, by name or former name; a system\n * command among its type's, else among its context's (a job's).\n */\n private async commandOf(request: CommandRequest): Promise<RoutingCommand> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifestOf()).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared;\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":";;;;;;;;AAsJA,IAAaA,IAAoB;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AAoB;EAC1B,QAAQ,4CAA4ClB,EAAO,OAAO;EAC1D;CACV,CAAC;CAEH,OAAOA;AACT;AAEA,IAAMiB,IAAsC,IAAI,IAC9C,OAAO,OAAOd,CAAmB,CACnC"}
1
+ {"version":3,"file":"commands.es.js","names":["LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","rememberRequestId","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","Stage","planOf","request","WaitPlan","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","ManifestSource","options","commandResults","result","WowProblemError","CommandResultStatus","CommandRejectedError","settled","declared","scope","bodyNumbers","send","system","type","prefix","name","context","aggregate","KNOWN_STATUSES","FrameworkErrorCodes"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n type Answer,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n ManifestSource,\n type RouteManifest,\n type RoutingCommand,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it. A command whose body names its aggregate (the\n * Manifest's `idProperty`) goes by that route too, whether `id` is given or\n * not: a given one is the one its body names, or is written into a body\n * that names none.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/**\n * The route of `request` among `routes`, by `id` (the request's, none for a\n * command whose body names its aggregate): its method and path, the id in it.\n * An empty id is refused before anything is sent: it would leave the path's\n * segment empty (`/<context>/<aggregate>//…`), a route no service has.\n */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n id: string | undefined,\n): { method: 'POST' | 'DELETE'; path: string } {\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n if (id === '') {\n throw new TypeError(\n `The path ${route.path} of ${request.command} needs id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/**\n * The body `request` sends, `{}` when it has none. Of a command whose body\n * names its aggregate in `idProperty`, the route has no id: the request's id,\n * when it names one, is the body's too, written into a body that names none.\n *\n * @throws TypeError when the body names another aggregate than the request\n */\nfunction bodyOf(\n request: CommandRequest,\n idProperty: string | undefined,\n): object {\n const body = request.body ?? {};\n const id = request.id;\n if (idProperty === undefined || id === undefined) return body;\n const named: unknown = (body as Record<string, unknown>)[idProperty];\n if (named === undefined || named === null) {\n return { ...body, [idProperty]: id };\n }\n if (named !== id) {\n throw new TypeError(\n `The request names the aggregate ${id}, but the body of ${request.command} names ${String(named)}: send it without an id.`,\n );\n }\n return body;\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private readonly manifest: ManifestSource;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest = new ManifestSource(client, options.manifest);\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n requestId,\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Answer> {\n const declared = await this.commandOf(request);\n const idProperty = declared.idProperty;\n const route = routeOf(\n request,\n declared.routes,\n idProperty === undefined ? request.id : undefined,\n );\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE'\n ? {}\n : { body: bodyOf(request, idProperty) }),\n // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: bodyNumbers },\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * `request`'s command as the Manifest lists it, with its routes: a domain\n * command among its aggregate's commands, by name or former name; a system\n * command among its type's, else among its context's (a job's).\n */\n private async commandOf(request: CommandRequest): Promise<RoutingCommand> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifest.read(request.signal)).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":";;;;;;;;AAqJA,IAAaA,IAAoB;CAC/B,kBAAkB;CAClB,mBAAmB;CACnB,gBAAgB;CAChB,gBAAgB;AAClB;AAqBA,SAAgBC,IAAuB;CACrC,IAAMC,IAAS,WAAW;CAC1B,IAAI,OAAOA,GAAQ,cAAe,YAAY,OAAOA,EAAO,WAAW;CAEvE,IAAMC,oBAAQ,IAAI,WAAW,EAAE;CAC/B,IAAI,OAAOD,GAAQ,mBAAoB,YACrC,EAAO,gBAAgBC,CAAK;MAE5B,KAAK,IAAIC,IAAQ,GAAGA,IAAQD,EAAM,QAAQ,KACxC,EAAMC,KAAS,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;CAIjD,AADA,EAAM,KAAMD,EAAM,KAAK,KAAQ,IAC/B,EAAM,KAAMA,EAAM,KAAK,KAAQ;CAC/B,IAAME,IAAM,MAAM,KAAKF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