@ahoo-wang/wow-client 10.0.0-alpha.6 → 10.0.0-alpha.7

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 (198) hide show
  1. package/README.md +76 -23
  2. package/README.zh-CN.md +66 -19
  3. package/dist/commands.cjs +1 -1
  4. package/dist/commands.cjs.map +1 -1
  5. package/dist/commands.d.cts +131 -61
  6. package/dist/commands.d.ts +131 -61
  7. package/dist/commands.es.js +117 -59
  8. package/dist/commands.es.js.map +1 -1
  9. package/dist/developmentCaller.cjs +2 -0
  10. package/dist/developmentCaller.cjs.map +1 -0
  11. package/dist/developmentCaller.d.cts +61 -0
  12. package/dist/developmentCaller.d.ts +61 -0
  13. package/dist/developmentCaller.es.js +26 -0
  14. package/dist/developmentCaller.es.js.map +1 -0
  15. package/dist/dsl/aggregation/admit.cjs +1 -1
  16. package/dist/dsl/aggregation/admit.cjs.map +1 -1
  17. package/dist/dsl/aggregation/admit.es.js +93 -93
  18. package/dist/dsl/aggregation/admit.es.js.map +1 -1
  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 +20 -20
  22. package/dist/dsl/aggregation/builders.d.ts +20 -20
  23. package/dist/dsl/aggregation/builders.es.js +88 -88
  24. package/dist/dsl/aggregation/builders.es.js.map +1 -1
  25. package/dist/dsl/aggregation/derived.cjs.map +1 -1
  26. package/dist/dsl/aggregation/derived.d.cts +8 -8
  27. package/dist/dsl/aggregation/derived.d.ts +8 -8
  28. package/dist/dsl/aggregation/derived.es.js +1 -2
  29. package/dist/dsl/aggregation/derived.es.js.map +1 -1
  30. package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
  31. package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
  32. package/dist/dsl/aggregation/having.cjs +1 -1
  33. package/dist/dsl/aggregation/having.cjs.map +1 -1
  34. package/dist/dsl/aggregation/having.d.cts +12 -12
  35. package/dist/dsl/aggregation/having.d.ts +12 -12
  36. package/dist/dsl/aggregation/having.es.js +33 -33
  37. package/dist/dsl/aggregation/having.es.js.map +1 -1
  38. package/dist/dsl/aggregation/sort.cjs.map +1 -1
  39. package/dist/dsl/aggregation/sort.es.js +1 -2
  40. package/dist/dsl/aggregation/types.cjs +1 -1
  41. package/dist/dsl/aggregation/types.cjs.map +1 -1
  42. package/dist/dsl/aggregation/types.d.cts +69 -69
  43. package/dist/dsl/aggregation/types.d.ts +69 -69
  44. package/dist/dsl/aggregation/types.es.js +15 -16
  45. package/dist/dsl/aggregation/types.es.js.map +1 -1
  46. package/dist/dsl/constantName.cjs +2 -0
  47. package/dist/dsl/constantName.cjs.map +1 -0
  48. package/dist/dsl/constantName.d.cts +9 -0
  49. package/dist/dsl/constantName.d.ts +9 -0
  50. package/dist/dsl/constantName.es.js +7 -0
  51. package/dist/dsl/constantName.es.js.map +1 -0
  52. package/dist/dsl/cursorQuery.cjs.map +1 -1
  53. package/dist/dsl/cursorQuery.es.js +1 -2
  54. package/dist/dsl/deletionState.cjs +1 -1
  55. package/dist/dsl/deletionState.cjs.map +1 -1
  56. package/dist/dsl/deletionState.d.cts +3 -3
  57. package/dist/dsl/deletionState.d.ts +3 -3
  58. package/dist/dsl/deletionState.es.js +2 -3
  59. package/dist/dsl/deletionState.es.js.map +1 -1
  60. package/dist/dsl/descriptor.cjs +1 -1
  61. package/dist/dsl/descriptor.cjs.map +1 -1
  62. package/dist/dsl/descriptor.d.cts +92 -42
  63. package/dist/dsl/descriptor.d.ts +92 -42
  64. package/dist/dsl/descriptor.es.js +36 -29
  65. package/dist/dsl/descriptor.es.js.map +1 -1
  66. package/dist/dsl/field.cjs.map +1 -1
  67. package/dist/dsl/field.es.js +1 -2
  68. package/dist/dsl/filter/builders.cjs +1 -1
  69. package/dist/dsl/filter/builders.cjs.map +1 -1
  70. package/dist/dsl/filter/builders.d.cts +53 -53
  71. package/dist/dsl/filter/builders.d.ts +53 -53
  72. package/dist/dsl/filter/builders.es.js +111 -111
  73. package/dist/dsl/filter/builders.es.js.map +1 -1
  74. package/dist/dsl/filter/datePattern.cjs.map +1 -1
  75. package/dist/dsl/filter/datePattern.es.js +1 -2
  76. package/dist/dsl/filter/operator.cjs +1 -1
  77. package/dist/dsl/filter/operator.cjs.map +1 -1
  78. package/dist/dsl/filter/operator.d.cts +57 -57
  79. package/dist/dsl/filter/operator.d.ts +57 -57
  80. package/dist/dsl/filter/operator.es.js +4 -5
  81. package/dist/dsl/filter/operator.es.js.map +1 -1
  82. package/dist/dsl/filter/scope.cjs +1 -1
  83. package/dist/dsl/filter/scope.cjs.map +1 -1
  84. package/dist/dsl/filter/scope.es.js +12 -12
  85. package/dist/dsl/filter/scope.es.js.map +1 -1
  86. package/dist/dsl/filter/validate.cjs +1 -1
  87. package/dist/dsl/filter/validate.cjs.map +1 -1
  88. package/dist/dsl/filter/validate.es.js +23 -23
  89. package/dist/dsl/filter/validate.es.js.map +1 -1
  90. package/dist/dsl/pagination.cjs.map +1 -1
  91. package/dist/dsl/pagination.es.js +1 -2
  92. package/dist/dsl/projection.cjs.map +1 -1
  93. package/dist/dsl/projection.d.cts +1 -1
  94. package/dist/dsl/projection.d.ts +1 -1
  95. package/dist/dsl/projection.es.js +1 -2
  96. package/dist/dsl/projection.es.js.map +1 -1
  97. package/dist/dsl/queryErrorCodes.cjs +1 -1
  98. package/dist/dsl/queryErrorCodes.cjs.map +1 -1
  99. package/dist/dsl/queryErrorCodes.d.cts +59 -48
  100. package/dist/dsl/queryErrorCodes.d.ts +59 -48
  101. package/dist/dsl/queryErrorCodes.es.js +51 -50
  102. package/dist/dsl/queryErrorCodes.es.js.map +1 -1
  103. package/dist/dsl/queryable.cjs +1 -1
  104. package/dist/dsl/queryable.cjs.map +1 -1
  105. package/dist/dsl/queryable.d.cts +25 -21
  106. package/dist/dsl/queryable.d.ts +25 -21
  107. package/dist/dsl/queryable.es.js +5 -5
  108. package/dist/dsl/queryable.es.js.map +1 -1
  109. package/dist/dsl/sort.cjs +1 -1
  110. package/dist/dsl/sort.cjs.map +1 -1
  111. package/dist/dsl/sort.d.cts +2 -2
  112. package/dist/dsl/sort.d.ts +2 -2
  113. package/dist/dsl/sort.es.js +4 -5
  114. package/dist/dsl/sort.es.js.map +1 -1
  115. package/dist/dsl.cjs +1 -1
  116. package/dist/dsl.es.js +3 -3
  117. package/dist/exactJson.cjs.map +1 -1
  118. package/dist/exactJson.d.cts +4 -4
  119. package/dist/exactJson.d.ts +4 -4
  120. package/dist/exactJson.es.js +1 -2
  121. package/dist/exactJson.es.js.map +1 -1
  122. package/dist/frameworkErrors.cjs +2 -0
  123. package/dist/frameworkErrors.cjs.map +1 -0
  124. package/dist/frameworkErrors.d.cts +121 -0
  125. package/dist/frameworkErrors.d.ts +121 -0
  126. package/dist/frameworkErrors.es.js +95 -0
  127. package/dist/frameworkErrors.es.js.map +1 -0
  128. package/dist/http.cjs +1 -1
  129. package/dist/http.cjs.map +1 -1
  130. package/dist/http.d.cts +4 -7
  131. package/dist/http.d.ts +4 -7
  132. package/dist/http.es.js +12 -20
  133. package/dist/http.es.js.map +1 -1
  134. package/dist/index.cjs +1 -1
  135. package/dist/index.d.cts +9 -7
  136. package/dist/index.d.ts +9 -7
  137. package/dist/index.es.js +11 -9
  138. package/dist/manifest.cjs +1 -1
  139. package/dist/manifest.cjs.map +1 -1
  140. package/dist/manifest.d.cts +33 -95
  141. package/dist/manifest.d.ts +33 -95
  142. package/dist/manifest.es.js +12 -7
  143. package/dist/manifest.es.js.map +1 -1
  144. package/dist/manifestTypes.d.cts +193 -0
  145. package/dist/manifestTypes.d.ts +193 -0
  146. package/dist/problem.cjs +1 -1
  147. package/dist/problem.cjs.map +1 -1
  148. package/dist/problem.d.cts +76 -115
  149. package/dist/problem.d.ts +76 -115
  150. package/dist/problem.es.js +45 -80
  151. package/dist/problem.es.js.map +1 -1
  152. package/dist/queries.cjs +1 -1
  153. package/dist/queries.cjs.map +1 -1
  154. package/dist/queries.d.cts +28 -51
  155. package/dist/queries.d.ts +28 -51
  156. package/dist/queries.es.js +49 -40
  157. package/dist/queries.es.js.map +1 -1
  158. package/dist/routes.cjs +2 -0
  159. package/dist/routes.cjs.map +1 -0
  160. package/dist/routes.d.cts +49 -0
  161. package/dist/routes.d.ts +49 -0
  162. package/dist/routes.es.js +33 -0
  163. package/dist/routes.es.js.map +1 -0
  164. package/dist/state.cjs +1 -1
  165. package/dist/state.cjs.map +1 -1
  166. package/dist/state.d.cts +56 -11
  167. package/dist/state.d.ts +56 -11
  168. package/dist/state.es.js +56 -21
  169. package/dist/state.es.js.map +1 -1
  170. package/dist/streams.cjs +1 -1
  171. package/dist/streams.cjs.map +1 -1
  172. package/dist/streams.d.cts +17 -13
  173. package/dist/streams.d.ts +17 -13
  174. package/dist/streams.es.js +50 -50
  175. package/dist/streams.es.js.map +1 -1
  176. package/dist/testing/wire.cjs +2 -0
  177. package/dist/testing/wire.cjs.map +1 -0
  178. package/dist/testing/wire.d.cts +29 -0
  179. package/dist/testing/wire.d.ts +29 -0
  180. package/dist/testing/wire.es.js +88 -0
  181. package/dist/testing/wire.es.js.map +1 -0
  182. package/dist/testing.cjs +1 -0
  183. package/dist/testing.d.cts +12 -0
  184. package/dist/testing.d.ts +12 -0
  185. package/dist/testing.es.js +3 -0
  186. package/dist/wait.cjs +1 -1
  187. package/dist/wait.cjs.map +1 -1
  188. package/dist/wait.d.cts +67 -18
  189. package/dist/wait.d.ts +67 -18
  190. package/dist/wait.es.js +59 -12
  191. package/dist/wait.es.js.map +1 -1
  192. package/dist/wire.cjs +1 -1
  193. package/dist/wire.cjs.map +1 -1
  194. package/dist/wire.d.cts +100 -50
  195. package/dist/wire.d.ts +100 -50
  196. package/dist/wire.es.js +17 -6
  197. package/dist/wire.es.js.map +1 -1
  198. package/package.json +23 -3
package/README.md CHANGED
@@ -50,7 +50,7 @@ const active = await carts.list(
50
50
  ```
51
51
 
52
52
  `single`, `list`, `paged`, `cursor`, `count` and `aggregate` each answer one
53
- operation; `listStream` reads a list as server-sent events and resumes a
53
+ operation; `stream` reads a list as server-sent events and resumes a
54
54
  stream the service cut off where it stopped. `describe(version?)` reads the
55
55
  query model's capability descriptor (`GET` on the same route): the fields
56
56
  with the operators, sorts and aggregation each admits, and the limits;
@@ -79,37 +79,56 @@ declare const fetcher: Fetcher;
79
79
  -->
80
80
 
81
81
  ```ts
82
- import { CommandGateway, wait } from '@ahoo-wang/wow-client';
83
-
84
- const commands = new CommandGateway({ fetcher });
85
- const result = await commands.send(
86
- '/shop/cart/{id}/add-cart-item',
87
- { productId: 'p-1', quantity: 1 },
88
- { id: 'cart-42', wait: { plan: [wait.snapshot()], timeout: 10_000 } },
89
- );
82
+ import { CommandClient, WaitPlan } from '@ahoo-wang/wow-client';
83
+
84
+ const commands = new CommandClient({ fetcher });
85
+ const result = await commands.wait({
86
+ command: 'shop.cart.AddCartItem',
87
+ body: { productId: 'p-1', quantity: 1 },
88
+ id: 'cart-42',
89
+ wait: WaitPlan.SNAPSHOT,
90
+ timeout: 10_000,
91
+ });
90
92
  ```
91
93
 
92
- The route is `POST /{context}/{aggregate}/{id}/{command}`; a command that may
93
- create its aggregate leaves `{id}` out. `wait` says how far the command
94
- goes before the call answers (`accepted`, `committed`, `snapshot`, or a
95
- subscription's `handled`, also across a saga's derived commands); `stream`
96
- answers one `CommandResult` per hop. Every command carries a request id
94
+ `command` is the full type name, `context.aggregate.Command`. The command is
95
+ sent by its route as the service's Manifest lists it: the Manifest the client
96
+ is given (`new CommandClient(options, { manifest })`, a whole Manifest or a
97
+ generated client's `manifest.ts`, its routes alone), else the service's,
98
+ fetched once (`GET /wow/manifest`). A command that
99
+ may create its aggregate leaves `id` out and goes by the route without one. As with Kotlin's `CommandClient`,
100
+ `send` answers once the command is accepted, `wait` with the result its plan
101
+ ends with (the server's default plan when there is none), and `stream` one
102
+ `CommandResult` per hop. `wait` is a `WaitPlan`, as Kotlin's:
103
+ `WaitPlan.ACCEPTED`, `COMMITTED`, `SNAPSHOT`, or `WaitPlan.of(...hops)` of the
104
+ `wait` hops (`accepted`, `committed`, `snapshot`, or a subscription's
105
+ `handled`, also across a saga's derived commands), `.within(ms)` its timeout;
106
+ `timeout` is in milliseconds and overrides it. `parseWaitPlan` and
107
+ `formatWaitPlan` read and write the `Wow-Wait` header. `targetTenant` and `targetScope`
108
+ (`{ ownerId?, spaceId? }`) act in another tenant, owner or space. Every command carries a request id
97
109
  (`Wow-Request-Id`), given or generated: a retry with the same one is answered
98
110
  as the first commit's duplicate, and `requestIdOf(error)` hands back the one
99
- a failure was sent with. `lifecycle` sends the lifecycle commands an
100
- aggregate lists (delete, restore, transfer, tags).
111
+ a failure was sent with. A system command, such as a lifecycle
112
+ command an aggregate lists (`LifecycleCommands.DELETE_AGGREGATE`, …), also
113
+ names the aggregate's `type: { context, name }`, and a lifecycle command its
114
+ `id`.
101
115
 
102
116
  `StateClient` reads an aggregate's state, at a version or a time, and its
103
- trace; `fetchManifest` reads the service's Manifest (`GET /wow/manifest`).
117
+ trace; `find(id, options?)` answers `undefined` for an aggregate that does
118
+ not exist (404 `wow.aggregate.not-found`), where `get` and `read` reject, and
119
+ any other 404 still rejects; `fetchManifest` reads the service's Manifest (`GET /wow/manifest`).
104
120
 
105
121
  ## Errors
106
122
 
107
- The service answers a refusal with an RFC 9457 problem, and the call rejects
108
- with a `WowProblemError`: the `problem` as written, its `status`, its Wow
109
- `code` and its `violations`. A command that did not succeed carries its
110
- `CommandResult` too, and `resolveRejected: true` resolves that result
111
- instead. A stream that fails midway errors with the same error, so a
112
- `for await` throws it.
123
+ `send` and `wait` resolve only a result that succeeded, and map the rest by
124
+ the result's status, as Kotlin's `CommandClient`: a rejected command, by its
125
+ aggregate or at admission, rejects with a `CommandRejectedError` (its `code`,
126
+ its `result`, and the `problem` when the service answered one); anything
127
+ else with a `WowProblemError`: the RFC 9457 `problem` as written, its
128
+ `status`, its Wow `code`, its `violations`, and the `result` when the
129
+ service sent one. `stream` emits every result, whatever its status. A
130
+ stream that fails midway errors with the same error, so a `for await`
131
+ throws it.
113
132
 
114
133
  ```ts
115
134
  import { FrameworkErrorCodes, WowProblemError } from '@ahoo-wang/wow-client';
@@ -138,6 +157,40 @@ without the clients: no Fetcher, and none of the stream patches
138
157
  `aggregation.query()` admits a whole aggregation against the rules Wow
139
158
  enforces on arrival, so a bad query fails where it was built.
140
159
 
160
+ ## Test against a service: `@ahoo-wang/wow-client/testing`
161
+
162
+ A development run of a Wow service reads its caller from headers
163
+ (`DevelopmentCallerHeaders`); `developmentCaller` sends them on every request
164
+ of a fetcher. `commandResultOf`, `problemOf`, `problemResponse` and
165
+ `snapshotOf` build the service's answers for a fake. The entry loads no test
166
+ runner.
167
+
168
+ ```ts
169
+ import { Fetcher } from '@ahoo-wang/fetcher';
170
+ import {
171
+ commandResultOf,
172
+ developmentCaller,
173
+ problemOf,
174
+ problemResponse,
175
+ } from '@ahoo-wang/wow-client/testing';
176
+
177
+ const fetcher = new Fetcher({ baseURL: 'http://localhost:8080' });
178
+ fetcher.interceptors.request.use(
179
+ developmentCaller({ user: 'alice', owner: 'alice', tenant: 'acme' }),
180
+ );
181
+
182
+ const mug = {
183
+ type: { context: 'eshop-catalog', name: 'product' },
184
+ tenantId: 'acme',
185
+ id: 'mug',
186
+ };
187
+ const refused = problemResponse(
188
+ problemOf(409, 'wow.command.refused', {
189
+ result: commandResultOf(mug, { status: 'rejected' }),
190
+ }),
191
+ );
192
+ ```
193
+
141
194
  ## Documentation
142
195
 
143
196
  - [TypeScript guide](https://wow.ahoo.me/typescript/)
package/README.zh-CN.md CHANGED
@@ -47,7 +47,7 @@ const active = await carts.list(
47
47
  ```
48
48
 
49
49
  `single`、`list`、`paged`、`cursor`、`count`、`aggregate` 各对应一种操作;
50
- `listStream` 以服务端推送事件读列表,服务中断的流从中断处续读。`describe(version?)`
50
+ `stream` 以服务端推送事件读列表,服务中断的流从中断处续读。`describe(version?)`
51
51
  读查询模型的能力描述(同一路由的 `GET`):每个字段可用的运算符、排序与聚合,以及
52
52
  各项上限;传入已持有的版本,304 时返回 `{ notModified: true, version }`。
53
53
  `EventQueryClient` 以同样方式查询聚合的事件流,`QueryModelClient` 查询任意查询路由,
@@ -73,32 +73,46 @@ declare const fetcher: Fetcher;
73
73
  -->
74
74
 
75
75
  ```ts
76
- import { CommandGateway, wait } from '@ahoo-wang/wow-client';
77
-
78
- const commands = new CommandGateway({ fetcher });
79
- const result = await commands.send(
80
- '/shop/cart/{id}/add-cart-item',
81
- { productId: 'p-1', quantity: 1 },
82
- { id: 'cart-42', wait: { plan: [wait.snapshot()], timeout: 10_000 } },
83
- );
76
+ import { CommandClient, WaitPlan } from '@ahoo-wang/wow-client';
77
+
78
+ const commands = new CommandClient({ fetcher });
79
+ const result = await commands.wait({
80
+ command: 'shop.cart.AddCartItem',
81
+ body: { productId: 'p-1', quantity: 1 },
82
+ id: 'cart-42',
83
+ wait: WaitPlan.SNAPSHOT,
84
+ timeout: 10_000,
85
+ });
84
86
  ```
85
87
 
86
- 路由是 `POST /{context}/{aggregate}/{id}/{command}`;可以创建聚合的命令不带 `{id}`。
87
- `wait` 说明命令走到哪一步才应答(`accepted`、`committed`、`snapshot`,或某个订阅的
88
- `handled`,也可以跨过 Saga 派生的命令);`stream` 每到一跳应答一个 `CommandResult`。
88
+ `command` 是完整类型名 `context.aggregate.Command`。命令按服务 Manifest 列出的路由发送:
89
+ 交给客户端的 Manifest(`new CommandClient(options, { manifest })`,完整的 Manifest,或生成的客户端的
90
+ `manifest.ts`,只有路由),否则取服务的 Manifest(`GET /wow/manifest`,只取一次)。可以创建聚合的命令不带 `id`,走不带 id 的路由。
91
+ 与 Kotlin 的 `CommandClient` 一样,`send` 在命令被接受后应答,`wait` 以等待计划最后
92
+ 一跳的结果应答(没有计划时用服务端的默认计划),`stream` 每到一跳应答一个
93
+ `CommandResult`。`wait` 是与 Kotlin 一致的 `WaitPlan`:`WaitPlan.ACCEPTED`、`COMMITTED`、
94
+ `SNAPSHOT`,或由 `wait` 各跳(`accepted`、`committed`、`snapshot`,或某个订阅的 `handled`,
95
+ 也可以跨过 Saga 派生的命令)组成的 `WaitPlan.of(...hops)`,`.within(ms)` 给它超时;
96
+ `timeout` 以毫秒计并覆盖计划的超时。`parseWaitPlan` 和 `formatWaitPlan` 读写 `Wow-Wait` 头。`targetTenant` 和
97
+ `targetScope`(`{ ownerId?, spaceId? }`)在另一个租户、所有者或空间中操作。
89
98
  每条命令都带请求 id(`Wow-Request-Id`),传入的或生成的:用同一个 id 重试,应答的是
90
- 第一次提交的重复结果;`requestIdOf(error)` 取回失败请求所用的 id。`lifecycle` 发送
91
- 聚合列出的生命周期命令(删除、恢复、转移、标签)。
99
+ 第一次提交的重复结果;`requestIdOf(error)` 取回失败请求所用的 id。系统命令(例如聚合列出的生命周期命令
100
+ `LifecycleCommands.DELETE_AGGREGATE` 等)还要指明聚合的 `type: { context, name }`,
101
+ 生命周期命令还要指明 `id`。
92
102
 
93
- `StateClient` 按版本或时间读取聚合的状态及其轨迹;`fetchManifest` 读取服务的
103
+ `StateClient` 按版本或时间读取聚合的状态及其轨迹;聚合不存在时(404
104
+ `wow.aggregate.not-found`)`get` 和 `read` 拒绝,`find(id, options?)` 则返回
105
+ `undefined`,其他 404 仍然拒绝;`fetchManifest` 读取服务的
94
106
  Manifest(`GET /wow/manifest`)。
95
107
 
96
108
  ## 错误
97
109
 
98
- 服务以 RFC 9457 问题拒绝请求,调用以 `WowProblemError` 拒绝:原样的 `problem`、
99
- `status`、Wow 的 `code` 和 `violations`。未成功的命令还带着它的 `CommandResult`,
100
- `resolveRejected: true` 时改为返回该结果。中途失败的流以同一个错误结束,`for await`
101
- 会抛出它。
110
+ `send` 和 `wait` 只以成功的结果 resolve,其余按结果的状态区分,与 Kotlin 的
111
+ `CommandClient` 一致:被拒绝的命令(聚合拒绝或在准入时拒绝)以 `CommandRejectedError`
112
+ reject(它的 `code`、`result`,服务回答了问题时还有 `problem`);其他情况以
113
+ `WowProblemError` reject:原样的 RFC 9457 `problem`、`status`、Wow 的 `code`、
114
+ `violations`,服务发送了结果时还有 `result`。`stream` 发出每个结果,不论状态。
115
+ 中途失败的流以同一个错误结束,`for await` 会抛出它。
102
116
 
103
117
  ```ts
104
118
  import { FrameworkErrorCodes, WowProblemError } from '@ahoo-wang/wow-client';
@@ -124,6 +138,39 @@ if (
124
138
  补丁。只构建查询的包用它。`aggregation.query()` 按 Wow 收到聚合时执行的规则校验整个
125
139
  聚合,错误的查询在构建处就失败。
126
140
 
141
+ ## 对着服务测试:`@ahoo-wang/wow-client/testing`
142
+
143
+ Wow 服务的开发模式从请求头读取调用者(`DevelopmentCallerHeaders`);
144
+ `developmentCaller` 在一个 fetcher 的每个请求上发送它们。`commandResultOf`、
145
+ `problemOf`、`problemResponse` 和 `snapshotOf` 为假服务构造服务的应答。这个入口不加载
146
+ 任何测试运行器。
147
+
148
+ ```ts
149
+ import { Fetcher } from '@ahoo-wang/fetcher';
150
+ import {
151
+ commandResultOf,
152
+ developmentCaller,
153
+ problemOf,
154
+ problemResponse,
155
+ } from '@ahoo-wang/wow-client/testing';
156
+
157
+ const fetcher = new Fetcher({ baseURL: 'http://localhost:8080' });
158
+ fetcher.interceptors.request.use(
159
+ developmentCaller({ user: 'alice', owner: 'alice', tenant: 'acme' }),
160
+ );
161
+
162
+ const mug = {
163
+ type: { context: 'eshop-catalog', name: 'product' },
164
+ tenantId: 'acme',
165
+ id: 'mug',
166
+ };
167
+ const refused = problemResponse(
168
+ problemOf(409, 'wow.command.refused', {
169
+ result: commandResultOf(mug, { status: 'rejected' }),
170
+ }),
171
+ );
172
+ ```
173
+
127
174
  ## 文档
128
175
 
129
176
  - [TypeScript 指南](https://wow.ahoo.me/zh/typescript/)
package/dist/commands.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./problem.cjs"),t=require("./http.cjs"),n=require("./streams.cjs"),r=require("./wait.cjs");var i={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 a(e){return e.replace(/([A-Z]+)([A-Z][a-z])/g,`$1-$2`).replace(/([a-z0-9])([A-Z])/g,`$1-$2`).replace(/[_\s]+/g,`-`).toLowerCase()}function o(){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 s(t,n){try{return await n()}catch(n){throw e.rememberRequestId(n,t),n}}function c(e,n,i){let a=e.wait;return{[t.WowHeaders.REQUEST_ID]:n,[t.WowHeaders.WAIT]:a?.plan===void 0?void 0:r.formatWaitPlan(a.plan),[t.WowHeaders.WAIT_TIMEOUT]:a?.timeout===void 0?void 0:r.formatWaitTimeout(a.timeout),[t.WowHeaders.IF_MATCH]:e.expectedVersion===void 0?void 0:`"${e.expectedVersion}"`,Accept:i}}var l=class{constructor(e={}){this.client=e}async send(n,r,i={}){let a=i.requestId??o();try{return await s(a,async()=>t.json(await this.post(n,r,i,a)))}catch(t){if(i.resolveRejected&&t instanceof e.WowProblemError&&t.result!==void 0)return t.result;throw t}}async stream(e,t,r={}){let i=r.requestId??o();return s(i,async()=>n.commandResults(await this.post(e,t,r,i,`text/event-stream`)))}async lifecycle(e,n,r,l,u={}){let d=`${e}/${encodeURIComponent(n)}`;if(r===i.DELETE_AGGREGATE){let e=u.requestId??o();return s(e,async()=>{let n=await t.send(this.client,{method:`DELETE`,path:d,headers:c(u,e),options:u});return t.json(n)})}return this.send(`${d}/${a(r)}`,l??{},u)}post(e,n,r,i,a){return t.send(this.client,{method:`POST`,path:e.includes(`{id}`)?t.expandPath(e,{id:r.id??``}):e,headers:c(r,i,a),body:n??{},...r.bodyNumbers===void 0?{}:{bodyNumbers:r.bodyNumbers},options:r})}};exports.CommandGateway=l,exports.LifecycleCommands=i,exports.commandSegment=a,exports.newRequestId=o;
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){let n=e.id,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.`);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){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 g(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 _(e){if(e.targetTenant!==void 0||e.targetScope!==void 0)return{tenantId:e.targetTenant,...e.targetScope}}var v=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 y(o)})}async post(e,t,n,i){let a=m(e,await this.routesOf(e)),o=_(e),s=this.bodyNumbers[e.command];return r.send(this.client,{method:a.method,path:a.path,headers:g(e,t,n,i),...a.method===`DELETE`?{}:{body:e.body??{}},...s===void 0?{}:{bodyNumbers:s},options:{...o===void 0?{}:{scope:o},...e.space===void 0?{}:{space:e.space},...e.headers===void 0?{}:{headers:e.headers},...e.signal===void 0?{}:{signal:e.signal}}})}async routesOf(e){let t=e.command,n=t.startsWith(u),r=e.type??(n?void 0:h(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.routes}manifestOf(){return this.manifest??=i.fetchManifest(this.client).catch(e=>{throw this.manifest=void 0,e}),this.manifest}};function y(r){if(r.status===t.CommandResultStatus.REJECTED)throw new n.CommandRejectedError(r);if(!b.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 b=new Set(Object.values(t.CommandResultStatus));exports.CommandClient=v,exports.LifecycleCommands=s,exports.newRequestId=c;
2
2
  //# sourceMappingURL=commands.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands.cjs","names":["WowHeaders","formatWaitPlan","formatWaitTimeout","json","WowProblemError","commandResults","send","expandPath","require_problem","require_http","require_streams","require_wait","LifecycleCommands","commandSegment","name","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","requestId","commandHeaders","wait","options","accept","CommandGateway","client","path","body","base","aggregatePath","id","command","response"],"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 expandPath,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport type { CommandResult } from './wire.js';\nimport { rememberRequestId, WowProblemError } from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, type WaitOptions } from './wait.js';\n\n/** What a command request carries beside its body (decisions D95–D99). */\nexport interface CommandOptions extends RequestOptions {\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 * gateway generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}): retry with it, not with a new one.\n */\n readonly requestId?: string;\n /** What to wait for, and for how long. */\n readonly wait?: WaitOptions;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n /**\n * The body's numbers written as their exact text, unquoted JSON numbers\n * (review R4-Q, Q-9; decision D122): a generated client sets it for a\n * command with `int64`, `bigint` or `decimal` fields, which it types as\n * `string`.\n */\n readonly bodyNumbers?: TextNumbers;\n /**\n * Resolve a result that did not succeed instead of rejecting with its\n * {@link WowProblemError}; `false` by default.\n */\n readonly resolveRejected?: boolean;\n}\n\n/** The options of a command whose route may name the aggregate 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 (decision D113). */\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 * The route segment of a command name, as the server derives it: kebab case,\n * dots kept (`AddCartItem` → `add-cart-item`,\n * `wow.lifecycle.RestoreAggregate` → `wow.lifecycle.restore-aggregate`).\n *\n * @param name - The command's name\n */\nexport function commandSegment(name: string): string {\n return name\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[_\\s]+/g, '-')\n .toLowerCase();\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The gateway 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\nfunction commandHeaders(\n options: CommandOptions,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n const wait = options.wait;\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n [WowHeaders.WAIT]:\n wait?.plan === undefined ? undefined : formatWaitPlan(wait.plan),\n [WowHeaders.WAIT_TIMEOUT]:\n wait?.timeout === undefined ? undefined : formatWaitTimeout(wait.timeout),\n [WowHeaders.IF_MATCH]:\n options.expectedVersion === undefined\n ? undefined\n : `\"${options.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/**\n * Sends commands to the command routes of a Wow service\n * (`POST /{context}/{aggregate}/{id}/{command}`, and without `{id}` for a\n * command that may create its aggregate). Generated aggregate clients build\n * on it; it serves any route too.\n *\n * A command that did not succeed rejects with a {@link WowProblemError}\n * holding its result, unless the options resolve it. Every command carries a\n * request id, the options' or a generated one, and whatever it rejects with\n * carries that id ({@link requestIdOf}).\n */\nexport class CommandGateway {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /**\n * Sends a command and answers the result its wait ends with: 200, or 202\n * for a plan that ends at `accepted`.\n *\n * @param path - The route, `{id}` filled from `id`\n * @param body - The command's body; `{}` when absent\n * @param options - Headers, wait and the aggregate id\n */\n async send<R = Record<string, unknown>>(\n path: string,\n body?: object,\n options: CreateCommandOptions = {},\n ): Promise<CommandResult<R>> {\n const requestId = options.requestId ?? newRequestId();\n try {\n return await withRequestId(requestId, async () =>\n json<CommandResult<R>>(await this.post(path, body, options, requestId)),\n );\n } catch (error) {\n if (\n options.resolveRejected &&\n error instanceof WowProblemError &&\n error.result !== undefined\n ) {\n return error.result as CommandResult<R>;\n }\n throw error;\n }\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances. An admission refusal rejects with its\n * problem; a rejection after admission is the stream's last result.\n *\n * @param path - The route, `{id}` filled from `id`\n * @param body - The command's body; `{}` when absent\n * @param options - Headers, wait and the aggregate id\n */\n async stream<R = Record<string, unknown>>(\n path: string,\n body?: object,\n options: CreateCommandOptions = {},\n ): Promise<CommandResultStream<R>> {\n const requestId = options.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(path, body, options, requestId, 'text/event-stream'),\n ),\n );\n }\n\n /**\n * Sends a lifecycle command an aggregate lists: `DELETE\n * /{context}/{aggregate}/{id}` for `DeleteAggregate`, `POST\n * …/{id}/wow.lifecycle.<kebab>` for the others.\n *\n * @param aggregatePath - `/{context}/{aggregate}`\n * @param id - The aggregate's id\n * @param command - The lifecycle command\n * @param body - Its body, for the commands that have one\n * @param options - Headers and wait\n */\n async lifecycle<R = Record<string, unknown>>(\n aggregatePath: string,\n id: string,\n command: LifecycleCommand,\n body?: TransferOwner | TransferSpace | ApplyTags,\n options: CommandOptions = {},\n ): Promise<CommandResult<R>> {\n const base = `${aggregatePath}/${encodeURIComponent(id)}`;\n if (command === LifecycleCommands.DELETE_AGGREGATE) {\n const requestId = options.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n const response = await send(this.client, {\n method: 'DELETE',\n path: base,\n headers: commandHeaders(options, requestId),\n options,\n });\n return json<CommandResult<R>>(response);\n });\n }\n return this.send<R>(\n `${base}/${commandSegment(command)}`,\n body ?? {},\n options,\n );\n }\n\n private post(\n path: string,\n body: object | undefined,\n options: CreateCommandOptions,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: path.includes('{id}')\n ? expandPath(path, { id: options.id ?? '' })\n : path,\n headers: commandHeaders(options, requestId, accept),\n body: body ?? {},\n ...(options.bodyNumbers === undefined\n ? {}\n : { bodyNumbers: options.bodyNumbers }),\n options,\n });\n }\n}\n"],"mappings":"4GAgEA,IAAaY,EAAoB,CAC/B,iB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QAASR,EAAeE,EAASH,CAAS,EAC1C,SACF,CAAC,EACD,OAAOtB,EAAAA,KAAuBmC,CAAQ,CACxC,CAAC,CACH,CACA,OAAO,KAAK,KACV,GAAGJ,EAAK,GAAGrB,EAAewB,CAAO,IACjCJ,GAAQ,CAAC,EACTL,CACF,CACF,CAEA,KACE,EACA,EACA,EACA,EACA,EACmB,CACnB,OAAOtB,EAAAA,KAAK,KAAK,OAAQ,CACvB,OAAQ,OACR,KAAM0B,EAAK,SAAS,MAAM,EACtBzB,EAAAA,WAAWyB,EAAM,CAAE,GAAIJ,EAAQ,IAAM,EAAG,CAAC,EACzCI,EACJ,QAASN,EAAeE,EAASH,EAAWI,CAAM,EAClD,KAAMI,GAAQ,CAAC,EACf,GAAIL,EAAQ,cAAgB,IAAA,GACxB,CAAC,EACD,CAAE,YAAaA,EAAQ,WAAY,EACvC,SACF,CAAC,CACH,CACF"}
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","id","route","routes","item","method","typeNamed","parts","command","part","commandHeaders","accept","targetOf","CommandClient","client","options","result","settled","scope","bodyNumbers","system","type","prefix","name","context","declared","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 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.\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/** The route of `request` among `routes`: its method and path, the id in it. */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n): { method: 'POST' | 'DELETE'; path: string } {\n const id = request.id;\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 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/** 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 route = routeOf(request, await this.routesOf(request));\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' ? {} : { body: request.body ?? {} }),\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 * The routes of `request`'s command in the Manifest: a domain command's\n * among its aggregate's commands, by name or former name; a system\n * command's among its type's, else among its context's (a job's).\n */\n private async routesOf(\n request: CommandRequest,\n ): Promise<readonly RouteManifest[]> {\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.routes;\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,mMAkJA,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,EAA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AAK,MAAM,CAAC,CAAC,MAAO,GAAmB,CAErE,KADA,MAAK,SAAW,IAAA,GACVmB,CACR,CAAC,EACM,KAAK,QACd,CACF,EAQA,SAASyB,EAAW,EAA4C,CAC9D,GAAID,EAAO,SAAW9C,EAAAA,oBAAoB,SACxC,MAAM,IAAIC,EAAAA,qBAAqB6C,CAAuB,EAExD,GAAI,CAACW,EAAe,IAAIX,EAAO,MAAM,EACnC,MAAM,IAAI/C,EAAAA,gBAAgB,CACxB,KAAM,iBAAiBK,EAAAA,oBAAoB,iBAC3C,MAAO,yBACP,OAAQ,IACR,KAAMA,EAAAA,oBAAoB,eAC1B,OAAQ,4CAA4C0C,EAAO,OAAO,0FAC1D,QACV,CAAC,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAOzD,EAAAA,mBAAmB,CACnC,E"}
@@ -1,35 +1,96 @@
1
1
  import { TextNumbers } from './exactJson.cjs';
2
- import { RequestOptions, WowClientOptions } from './http.cjs';
3
- import { CommandResult } from './wire.cjs';
2
+ import { RequestOptions, TargetScope, WowClientOptions } from './http.cjs';
3
+ import { AggregateType, CommandResult } from './wire.cjs';
4
+ import { RoutingManifest } from './manifest.cjs';
4
5
  import { CommandResultStream } from './streams.cjs';
5
- import { WaitOptions } from './wait.cjs';
6
- /** What a command request carries beside its body (decisions D95–D99). */
7
- export interface CommandOptions extends RequestOptions {
6
+ import { WaitPlan } from './wait.cjs';
7
+ /**
8
+ * One command a {@link CommandClient} sends, and how: the TypeScript
9
+ * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same
10
+ * fields. Kotlin's `command` is the command object, whose class names it;
11
+ * here `command` is the command's name and `body` its payload, as the wire
12
+ * carries them.
13
+ *
14
+ * - `command`: the full type name, `context.aggregate.Command`, which names
15
+ * the aggregate type too; or a system command (`wow.*`, a lifecycle command
16
+ * of {@link LifecycleCommands} among them), which needs `type`.
17
+ * - `id`: the aggregate's id. Absent when the command names no aggregate id:
18
+ * a creation, whose id the server assigns, an `@Unaddressed` command, or
19
+ * any command of an aggregate whose id is its owner's (the Manifest's
20
+ * `idSource: "owner"`), which goes to the caller's own; the route without
21
+ * `{id}` then sends it.
22
+ * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to
23
+ * act across scopes acts in (`Wow-Scope`); the caller's own when absent.
24
+ * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds
25
+ * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command
26
+ * waits with is `wait` within `timeout`, the server's default plan when
27
+ * only a timeout is given, and the server's default without either.
28
+ * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).
29
+ */
30
+ export interface CommandRequest extends Omit<RequestOptions, 'scope'> {
31
+ /** The command's full type name, or a system command's. */
32
+ readonly command: string;
33
+ /** The command's body; `{}` when absent. */
34
+ readonly body?: object;
35
+ /**
36
+ * The aggregate's id; absent for a creation, an unaddressed command or the
37
+ * caller's own aggregate of one whose id is its owner's.
38
+ */
39
+ readonly id?: string;
40
+ /**
41
+ * The aggregate type, which `command` names unless it is a system command:
42
+ * then it is required.
43
+ */
44
+ readonly type?: AggregateType;
45
+ /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */
46
+ readonly targetTenant?: string;
47
+ /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */
48
+ readonly targetScope?: Omit<TargetScope, 'tenantId'>;
49
+ /**
50
+ * Not a command's: a query's `Wow-Scope`. A command names the scope it acts
51
+ * in with `targetTenant` and `targetScope`, so a query's options spread into
52
+ * a command's fail to compile rather than drop their scope.
53
+ */
54
+ readonly scope?: never;
55
+ /** How far to wait for the command (`Wow-Wait`). */
56
+ readonly wait?: WaitPlan;
57
+ /** How long to wait, in milliseconds, over the plan's own timeout. */
58
+ readonly timeout?: number;
8
59
  /**
9
60
  * The request id (`Wow-Request-Id`): a retry with the same one is
10
61
  * deduplicated, answered as the first commit's duplicate. When absent, the
11
- * gateway generates one ({@link newRequestId}), which a failure carries
12
- * ({@link requestIdOf}): retry with it, not with a new one.
62
+ * client generates one ({@link newRequestId}), which a failure carries
63
+ * ({@link requestIdOf}). A request sent again without one is another
64
+ * request: for an application-level retry, set it (or keep the one the
65
+ * failure or the first result carries) and send that request again.
13
66
  */
14
67
  readonly requestId?: string;
15
- /** What to wait for, and for how long. */
16
- readonly wait?: WaitOptions;
17
68
  /** The version the aggregate must be at (`If-Match`). */
18
69
  readonly expectedVersion?: number;
70
+ }
71
+ /** How a {@link CommandClient} sends, beside how it reaches the service. */
72
+ export interface CommandClientOptions {
19
73
  /**
20
- * The body's numbers written as their exact text, unquoted JSON numbers
21
- * (review R4-Q, Q-9; decision D122): a generated client sets it for a
22
- * command with `int64`, `bigint` or `decimal` fields, which it types as
23
- * `string`.
74
+ * The Manifest whose routes send each command: a whole Manifest, or the
75
+ * routing part a generated client carries (`manifest.ts`). Without it the
76
+ * client fetches the service's once, when it first sends
77
+ * (`GET /wow/manifest`), and again after a failed fetch.
24
78
  */
25
- readonly bodyNumbers?: TextNumbers;
79
+ readonly manifest?: RoutingManifest;
26
80
  /**
27
- * Resolve a result that did not succeed instead of rejecting with its
28
- * {@link WowProblemError}; `false` by default.
81
+ * The body numbers each command writes as their exact text, unquoted JSON
82
+ * numbers (decision D122), by the command's full type name: a generated
83
+ * client sets them for commands with `int64`, `bigint` or `decimal` fields,
84
+ * which it types as `string`.
29
85
  */
30
- readonly resolveRejected?: boolean;
86
+ readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;
31
87
  }
32
- /** The options of a command whose route may name the aggregate id or not. */
88
+ /**
89
+ * The options of a generated client's command method: a {@link CommandRequest}
90
+ * without what the method fixes, its command, body and type.
91
+ */
92
+ export type CommandOptions = Omit<CommandRequest, 'command' | 'body' | 'type' | 'id'>;
93
+ /** The options of a command that may create its aggregate, with its id or not. */
33
94
  export interface CreateCommandOptions extends CommandOptions {
34
95
  /**
35
96
  * The id of the aggregate to create (decision D176); the service generates
@@ -37,7 +98,7 @@ export interface CreateCommandOptions extends CommandOptions {
37
98
  */
38
99
  readonly id?: string;
39
100
  }
40
- /** The lifecycle commands an aggregate may list (decision D113). */
101
+ /** The lifecycle commands an aggregate may list. */
41
102
  export declare const LifecycleCommands: {
42
103
  readonly DELETE_AGGREGATE: "wow.lifecycle.DeleteAggregate";
43
104
  readonly RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate";
@@ -60,64 +121,73 @@ export interface ApplyTags {
60
121
  readonly tags: Readonly<Record<string, readonly string[]>>;
61
122
  }
62
123
  /**
63
- * The route segment of a command name, as the server derives it: kebab case,
64
- * dots kept (`AddCartItem` → `add-cart-item`,
65
- * `wow.lifecycle.RestoreAggregate` → `wow.lifecycle.restore-aggregate`).
66
- *
67
- * @param name - The command's name
68
- */
69
- export declare function commandSegment(name: string): string;
70
- /**
71
- * A new request id (`Wow-Request-Id`): a random UUID. The gateway generates
124
+ * A new request id (`Wow-Request-Id`): a random UUID. The client generates
72
125
  * one for a command sent without; generate it first to retry with it however
73
126
  * the request fails.
74
127
  */
75
128
  export declare function newRequestId(): string;
76
129
  /**
77
- * Sends commands to the command routes of a Wow service
78
- * (`POST /{context}/{aggregate}/{id}/{command}`, and without `{id}` for a
79
- * command that may create its aggregate). Generated aggregate clients build
80
- * on it; it serves any route too.
130
+ * Sends commands to the command routes of a Wow service as its Manifest lists
131
+ * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without
132
+ * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`
133
+ * for `DeleteAggregate`): the Manifest the client is given, else the
134
+ * service's, fetched once (`GET /wow/manifest`). The TypeScript
135
+ * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers
136
+ * once the command is accepted, {@link wait} with the result its wait plan
137
+ * ends with, {@link stream} with one result per hop. Generated aggregate
138
+ * clients build on it.
81
139
  *
82
- * A command that did not succeed rejects with a {@link WowProblemError}
83
- * holding its result, unless the options resolve it. Every command carries a
84
- * request id, the options' or a generated one, and whatever it rejects with
85
- * carries that id ({@link requestIdOf}).
140
+ * `send` and `wait` resolve only a result that succeeded. A rejected one,
141
+ * by the aggregate or at admission, rejects with a
142
+ * {@link CommandRejectedError}; anything else that did not succeed with a
143
+ * {@link WowProblemError} (the table on {@link CommandRejectedError} says
144
+ * which). Every command carries a request id, the request's or a generated
145
+ * one, and whatever it rejects with carries that id ({@link requestIdOf}).
86
146
  */
87
- export declare class CommandGateway {
147
+ export declare class CommandClient {
88
148
  readonly client: WowClientOptions;
89
- /** @param client - How the service is reached */
90
- constructor(client?: WowClientOptions);
149
+ private manifest;
150
+ private readonly bodyNumbers;
91
151
  /**
92
- * Sends a command and answers the result its wait ends with: 200, or 202
93
- * for a plan that ends at `accepted`.
152
+ * @param client - How the service is reached
153
+ * @param options - The service's Manifest, and the commands' exact numbers
154
+ */
155
+ constructor(client?: WowClientOptions, options?: CommandClientOptions);
156
+ /**
157
+ * Sends a command and answers once it is accepted (202), within the
158
+ * request's timeout (10 seconds without one), as Kotlin's
159
+ * `CommandClient.send`. A request whose `wait` waits for more rejects with a
160
+ * `TypeError` before it is sent: {@link wait} answers with that plan's result.
94
161
  *
95
- * @param path - The route, `{id}` filled from `id`
96
- * @param body - The command's body; `{}` when absent
97
- * @param options - Headers, wait and the aggregate id
162
+ * @param request - The command and how to send it
98
163
  */
99
- send<R = Record<string, unknown>>(path: string, body?: object, options?: CreateCommandOptions): Promise<CommandResult<R>>;
164
+ send<R = Record<string, unknown>>(request: CommandRequest): Promise<CommandResult<R>>;
100
165
  /**
101
- * Sends a command with `Accept: text/event-stream` and answers one result
102
- * per hop as the wait advances. An admission refusal rejects with its
103
- * problem; a rejection after admission is the stream's last result.
166
+ * Sends a command and answers the result its wait plan ends with: 200, or
167
+ * 202 for a plan that ends at `accepted`. Without a plan, the server's
168
+ * default: the snapshot, or the commit where the aggregate keeps no
169
+ * snapshot (decision D69).
104
170
  *
105
- * @param path - The route, `{id}` filled from `id`
106
- * @param body - The command's body; `{}` when absent
107
- * @param options - Headers, wait and the aggregate id
171
+ * @param request - The command and how to send it
108
172
  */
109
- stream<R = Record<string, unknown>>(path: string, body?: object, options?: CreateCommandOptions): Promise<CommandResultStream<R>>;
173
+ wait<R = Record<string, unknown>>(request: CommandRequest): Promise<CommandResult<R>>;
110
174
  /**
111
- * Sends a lifecycle command an aggregate lists: `DELETE
112
- * /{context}/{aggregate}/{id}` for `DeleteAggregate`, `POST
113
- * …/{id}/wow.lifecycle.<kebab>` for the others.
175
+ * Sends a command with `Accept: text/event-stream` and answers one result
176
+ * per hop as the wait advances, whatever its status. An admission refusal
177
+ * rejects with its problem; a rejection after admission is the stream's
178
+ * last result.
114
179
  *
115
- * @param aggregatePath - `/{context}/{aggregate}`
116
- * @param id - The aggregate's id
117
- * @param command - The lifecycle command
118
- * @param body - Its body, for the commands that have one
119
- * @param options - Headers and wait
180
+ * @param request - The command and how to send it
120
181
  */
121
- lifecycle<R = Record<string, unknown>>(aggregatePath: string, id: string, command: LifecycleCommand, body?: TransferOwner | TransferSpace | ApplyTags, options?: CommandOptions): Promise<CommandResult<R>>;
182
+ stream<R = Record<string, unknown>>(request: CommandRequest): Promise<CommandResultStream<R>>;
183
+ private exchange;
122
184
  private post;
185
+ /**
186
+ * The routes of `request`'s command in the Manifest: a domain command's
187
+ * among its aggregate's commands, by name or former name; a system
188
+ * command's among its type's, else among its context's (a job's).
189
+ */
190
+ private routesOf;
191
+ /** The Manifest given, or the service's, fetched once (again after a failure). */
192
+ private manifestOf;
123
193
  }