@ahoo-wang/wow-client 10.0.0-alpha.5 → 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 -111
  149. package/dist/problem.d.ts +76 -111
  150. package/dist/problem.es.js +45 -78
  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 +26 -7
@@ -0,0 +1,193 @@
1
+ /** A service's Manifest, or a module's fragment (without service), format 1. */
2
+ export interface Manifest {
3
+ /** The format of the Manifest. */
4
+ readonly format: number;
5
+ /** The markers a reader must understand to read the Manifest. */
6
+ readonly requires?: readonly string[];
7
+ readonly service?: ServiceManifest;
8
+ readonly contexts: readonly ContextManifest[];
9
+ /** The framework's error codes and their HTTP statuses. */
10
+ readonly errors: readonly ErrorManifest[];
11
+ /** The JSON Schema 2020-12 of every payload, by key. */
12
+ readonly $defs: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
13
+ }
14
+ /** The service a merged Manifest describes; a fragment has none. */
15
+ export interface ServiceManifest {
16
+ readonly name: string;
17
+ readonly version?: string;
18
+ }
19
+ /** A bounded context: its aggregates, subscriptions, published streams, error codes and job commands. */
20
+ export interface ContextManifest {
21
+ /** The bounded context's name: lower case words joined by hyphens. */
22
+ readonly name: string;
23
+ readonly description?: string;
24
+ readonly aggregates: readonly AggregateManifest[];
25
+ readonly subscriptions: readonly SubscriptionManifest[];
26
+ readonly published: readonly PublishedManifest[];
27
+ /** The context's own error codes. */
28
+ readonly errors: readonly ErrorManifest[];
29
+ /** The context's own system commands: its job commands. */
30
+ readonly commands?: readonly CommandManifest[];
31
+ /** The context's service routes, whose handlers are its own code. */
32
+ readonly routes?: readonly ServiceRouteManifest[];
33
+ }
34
+ /** A service route: a route whose handler is the service's own code, its parameters and schemas. */
35
+ export interface ServiceRouteManifest {
36
+ /** The route's name in its context: its identity and its client's method. */
37
+ readonly name: string;
38
+ readonly route: RouteManifest;
39
+ readonly parameters?: readonly RouteParameterManifest[];
40
+ /** An inline JSON Schema: a $ref into $defs, or an array of one. */
41
+ readonly request?: unknown;
42
+ /** An inline JSON Schema: a $ref into $defs, or an array of one. */
43
+ readonly response?: unknown;
44
+ /** The codes the route refuses with, entries of the context's errors. */
45
+ readonly errors?: readonly string[];
46
+ readonly description?: string;
47
+ readonly deprecated?: boolean;
48
+ }
49
+ /** A path variable or query parameter of a service route, and its scalar schema. */
50
+ export interface RouteParameterManifest {
51
+ readonly name: string;
52
+ /** Where the parameter is read from. */
53
+ readonly in: 'path' | 'query' | (string & {});
54
+ /** An inline JSON Schema of a scalar. */
55
+ readonly schema: unknown;
56
+ readonly required: boolean;
57
+ }
58
+ /** An aggregate type: its state, snapshots, commands, events and query models. */
59
+ export interface AggregateManifest {
60
+ readonly name: string;
61
+ readonly description?: string;
62
+ readonly state: StateManifest;
63
+ readonly snapshot: SnapshotManifest;
64
+ readonly commands: readonly CommandManifest[];
65
+ readonly events: readonly EventManifest[];
66
+ readonly queries: readonly QueryManifest[];
67
+ /** The commands the aggregate schedules. */
68
+ readonly schedules?: readonly string[];
69
+ /** Who owns an aggregate; owner when absent. */
70
+ readonly ownership?: 'owner' | 'tenant' | (string & {});
71
+ /** The events the aggregate no longer produces. */
72
+ readonly retired?: readonly string[];
73
+ /** Where an aggregate's id comes from; assigned when absent. */
74
+ readonly idSource?: 'assigned' | 'owner' | (string & {});
75
+ }
76
+ /** An aggregate's state: its schema, the fingerprint of its shape and, in a contract, its view. */
77
+ export interface StateManifest {
78
+ /** #/$defs/<key> */
79
+ readonly schema: string;
80
+ readonly fingerprint?: string;
81
+ readonly view?: string;
82
+ }
83
+ /** Whether an aggregate keeps snapshots, and the revision of their state. */
84
+ export interface SnapshotManifest {
85
+ readonly enabled: boolean;
86
+ readonly stateRevision?: number;
87
+ }
88
+ /** A query model of an aggregate (snapshot, events) and its routes. */
89
+ export interface QueryManifest {
90
+ readonly model: string;
91
+ readonly routes: readonly RouteManifest[];
92
+ }
93
+ /** A command of an aggregate or a context, and the routes that send it. */
94
+ export interface CommandManifest {
95
+ readonly name: string;
96
+ /** The command's former names. */
97
+ readonly aliases: readonly string[];
98
+ /** #/$defs/<key> */
99
+ readonly schema: string;
100
+ /** Whether the command creates its aggregate. */
101
+ readonly creation: 'none' | 'required' | 'allowed' | (string & {});
102
+ /** The events the command produces, when the module says. */
103
+ readonly produces?: readonly string[];
104
+ readonly routes: readonly RouteManifest[];
105
+ readonly mounted?: boolean;
106
+ /** A system command (wow.*): a lifecycle command, a rebuild or a job command. */
107
+ readonly system?: boolean;
108
+ readonly transformsTo?: readonly string[];
109
+ readonly description?: string;
110
+ }
111
+ /** An event of an aggregate and its revision. */
112
+ export interface EventManifest {
113
+ readonly name: string;
114
+ /** The event's former names. */
115
+ readonly aliases: readonly string[];
116
+ readonly revision: number;
117
+ /** #/$defs/<key> */
118
+ readonly schema: string;
119
+ readonly description?: string;
120
+ }
121
+ /** A route of the edge: a method and a path, {id} the aggregate id. */
122
+ export interface RouteManifest {
123
+ readonly method: string;
124
+ readonly path: string;
125
+ }
126
+ /** An error code, the HTTP status it is answered with, and what a retry may do. */
127
+ export interface ErrorManifest {
128
+ readonly code: string;
129
+ readonly status: number;
130
+ readonly description?: string;
131
+ /** What a retry may do, as a problem of the code says: none when left out. */
132
+ readonly retry?: 'none' | 'same-request' | 'new-request' | (string & {});
133
+ /** The seconds to wait before a retry, the problem's Retry-After; given with retry. */
134
+ readonly retryAfter?: number;
135
+ }
136
+ /** A stream a context publishes of an aggregate's events, and its topic. */
137
+ export interface PublishedManifest {
138
+ readonly aggregate: string;
139
+ readonly topic: string;
140
+ readonly includeState: boolean;
141
+ }
142
+ /** A subscription of a bounded context: what it reads and what its handler derives. */
143
+ export interface SubscriptionManifest {
144
+ /** processor.function */
145
+ readonly name: string;
146
+ readonly kind: 'projection' | 'reactor' | 'saga' | (string & {});
147
+ readonly source: SourceManifest;
148
+ readonly function: FunctionManifest;
149
+ readonly derives?: readonly string[];
150
+ readonly rejected?: readonly string[];
151
+ readonly committed?: readonly string[];
152
+ readonly calls?: readonly string[];
153
+ readonly start?: 'beginning' | 'end' | (string & {});
154
+ readonly schedules?: readonly string[];
155
+ readonly retry?: RetryManifest;
156
+ readonly job?: JobManifest;
157
+ }
158
+ /** What a subscription reads: a context, aggregate types and events. */
159
+ export interface SourceManifest {
160
+ readonly context?: string;
161
+ readonly aggregates: readonly string[];
162
+ readonly events: readonly string[];
163
+ readonly eventSchemas?: readonly string[];
164
+ readonly nullableState?: boolean;
165
+ }
166
+ /** The handler function of a subscription. */
167
+ export interface FunctionManifest {
168
+ readonly kind: 'command' | 'project' | 'react' | 'saga' | (string & {});
169
+ readonly context: string;
170
+ readonly processor: string;
171
+ readonly name: string;
172
+ }
173
+ /** A subscription's retry budget. */
174
+ export interface RetryManifest {
175
+ readonly maxAttempts?: number;
176
+ readonly initialBackoff?: string;
177
+ readonly maxBackoff?: string;
178
+ readonly timeout?: string;
179
+ readonly recoverable?: readonly string[];
180
+ readonly unrecoverable?: readonly string[];
181
+ readonly multiplier?: number;
182
+ }
183
+ /** The scheduled job a subscription runs. */
184
+ export interface JobManifest {
185
+ readonly name: string;
186
+ readonly cron: string;
187
+ readonly zone: string;
188
+ /** Who the job runs for. */
189
+ readonly scope: 'system' | 'tenant' | (string & {});
190
+ readonly sharded: boolean;
191
+ /** What the job does with the slots it missed. */
192
+ readonly misfire: 'coalesce' | 'catch-up' | (string & {});
193
+ }
package/dist/problem.cjs CHANGED
@@ -1,2 +1,2 @@
1
- var e={AUTH_UNAUTHENTICATED:`wow.auth.unauthenticated`,AUTH_FORBIDDEN:`wow.auth.forbidden`,AGGREGATE_FORBIDDEN:`wow.aggregate.forbidden`,COMMAND_MALFORMED:`wow.command.malformed`,COMMAND_INVALID:`wow.command.invalid`,WAIT_INVALID:`wow.wait.invalid`,COMMAND_UNHANDLED:`wow.command.unhandled`,AGGREGATE_NOT_FOUND:`wow.aggregate.not-found`,AGGREGATE_EXISTS:`wow.aggregate.exists`,AGGREGATE_VERSION_MISMATCH:`wow.aggregate.version-mismatch`,COMMAND_REQUEST_ID_REUSED:`wow.command.request-id-reused`,COMMAND_CONTENDED:`wow.command.contended`,AGGREGATE_DELETED:`wow.aggregate.deleted`,COMMAND_BUSY:`wow.command.busy`,COMMAND_UNKNOWN:`wow.command.unknown`,COMMAND_FAILED:`wow.command.failed`,NODE_CLOSING:`wow.node.closing`,NODE_STANDBY:`wow.node.standby`,STORAGE_UNAVAILABLE:`wow.storage.unavailable`,SCHEDULE_NOT_DUE:`wow.schedule.not-due`,SCHEDULE_JOB_INVALID:`wow.schedule.job-invalid`,SUBSCRIPTION_PARKED:`wow.subscription.parked`,WAIT_TIMEOUT:`wow.wait.timeout`,QUERY_MALFORMED:`wow.query.malformed`,QUERY_INVALID:`wow.query.invalid`,QUERY_FAILED:`wow.query.failed`,QUERY_TIMEOUT:`wow.query.timeout`,QUERY_BUSY:`wow.query.busy`,QUERY_NOT_FOUND:`wow.query.not-found`,QUERY_DATASET_NOT_FOUND:`wow.query.dataset-not-found`,QUERY_MIN_VERSION_NOT_REACHED:`wow.query.min-version-not-reached`,QUERY_DATASET_UNAVAILABLE:`wow.query.dataset-unavailable`,CALL_COMMAND_FORBIDDEN:`wow.call.command-forbidden`},t=`wow.`,n=`urn:wow:error:`,r=new Set([`type`,`title`,`status`,`detail`,`instance`,`code`,`violations`,`result`,`extensions`]);function i(e){if(e.extensions!==void 0)return e;let t=Object.fromEntries(Object.entries(e).filter(([e])=>!r.has(e)));return Object.keys(t).length===0?e:{...e,extensions:t}}var a=new Map([[e.COMMAND_UNKNOWN,!0],[e.NODE_CLOSING,!0],[e.NODE_STANDBY,!0],[e.STORAGE_UNAVAILABLE,!0],[e.SCHEDULE_NOT_DUE,!0],[e.COMMAND_BUSY,!0],[e.QUERY_BUSY,!1],[e.QUERY_MIN_VERSION_NOT_REACHED,!1],[e.COMMAND_CONTENDED,!0],[e.WAIT_TIMEOUT,!0]]);function o(e,t,n){let r=e===void 0?void 0:a.get(e),i=r!==void 0||e===void 0&&t===503;return{retryable:i,sameRequestId:r??i,...n===void 0?{}:{afterMs:n}}}var s=class extends Error{get requestId(){return this.result?.requestId??c.get(this)}constructor(e,t={}){super(e.code?`[${e.code}] ${e.detail??e.title}`:`${e.status} ${e.detail??e.title}`),this.name=`WowProblemError`,this.problem=i(e),this.status=e.status,e.code!==void 0&&(this.code=e.code),this.violations=e.violations??[],e.result!==void 0&&(this.result=e.result),this.retry=o(e.code,e.status,t.retryAfterMs),t.cause!==void 0&&(this.cause=t.cause)}get isFramework(){return this.code?.startsWith(`wow.`)??!1}},c=new WeakMap;function l(e,t){(typeof e==`object`&&e||typeof e==`function`)&&(c.has(e)||c.set(e,t))}function u(e){return e instanceof s?e.requestId:typeof e==`object`&&e||typeof e==`function`?c.get(e):void 0}function d(e){return typeof e==`object`&&!!e&&typeof e.status==`number`}function f(e,t=Date.now()){if(!e)return;let n=e.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}async function p(e){let t;try{t=await e.clone().json()}catch{}if(d(t)){let n=t.code??(t.type?.startsWith(`urn:wow:error:`)?t.type.slice(14):void 0);return i({...t,type:t.type??`about:blank`,title:t.title??e.statusText,...n===void 0?{}:{code:n}})}return{type:`about:blank`,title:e.statusText,status:e.status}}async function m(e){if(e instanceof s)return e;if(typeof e!=`object`||!e)return;let{exchange:t,cause:n}=e;if(n instanceof s)return n;let r=t?.response;if(!r||r.ok)return;let i=await p(r),a=f(r.headers.get(`Retry-After`));return new s(i,{cause:e,...a===void 0?{}:{retryAfterMs:a}})}exports.FRAMEWORK_ERROR_PREFIX=t,exports.FrameworkErrorCodes=e,exports.PROBLEM_TYPE_PREFIX=n,exports.WowProblemError=s,exports.isProblem=d,exports.parseRetryAfter=f,exports.readProblem=p,exports.rememberRequestId=l,exports.requestIdOf=u,exports.retryHintOf=o,exports.toWowProblemError=m;
1
+ const e=require("./frameworkErrors.cjs"),t=require("./wire.cjs");var n=`wow.`,r=`urn:wow:error:`,i=new Set([`type`,`title`,`status`,`detail`,`instance`,`code`,`retry`,`violations`,`result`,`extensions`]);function a(e){if(e.extensions!==void 0)return e;let t=Object.fromEntries(Object.entries(e).filter(([e])=>!i.has(e)));return Object.keys(t).length===0?e:{...e,extensions:t}}function o(t){if(t.retry!==void 0)return t.retry;let n=t.code===void 0?void 0:e.FRAMEWORK_RETRIES.get(t.code);return n?n.retry:t.code===void 0&&(t.status===503||t.status===429)?`same-request`:`none`}var s=class extends Error{get requestId(){return this.result?.requestId??l.get(this)}constructor(t,n={}){super(t.code?`[${t.code}] ${t.detail??t.title}`:`${t.status} ${t.detail??t.title}`),this.name=`WowProblemError`,this.problem=a(t),this.status=t.status,t.code!==void 0&&(this.code=t.code),this.violations=t.violations??[],t.result!==void 0&&(this.result=t.result),this.retry=o(t);let r=n.retryAfterMs??(t.code===void 0?void 0:e.FRAMEWORK_RETRIES.get(t.code)?.retryAfterMs);this.retry!==`none`&&r!==void 0&&(this.retryAfterMs=r),n.cause!==void 0&&(this.cause=n.cause)}get isFramework(){return this.code?.startsWith(`wow.`)??!1}},c=class extends Error{constructor(e,n={}){let r=[e.error?.code,e.error?.message].filter(Boolean).join(` `);if(super(`${e.ref.type.context}.${e.ref.type.name}/${e.ref.id??`(no id)`} rejected the command`+(r?`: ${r}`:`.`)),this.name=`CommandRejectedError`,e.status!==t.CommandResultStatus.REJECTED)throw TypeError(`A rejection has a rejected result, not ${e.status}.`);this.result=e,n.problem!==void 0&&(this.problem=n.problem),n.cause!==void 0&&(this.cause=n.cause)}get code(){return this.result.error?.code??``}get requestId(){return this.result.requestId}},l=new WeakMap;function u(e,t){(typeof e==`object`&&e||typeof e==`function`)&&(l.has(e)||l.set(e,t))}function d(e){return e instanceof s?e.requestId:typeof e==`object`&&e||typeof e==`function`?l.get(e):void 0}function f(e){return typeof e==`object`&&!!e&&typeof e.status==`number`}function p(e,t=Date.now()){if(!e)return;let n=e.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}async function m(e){let t;try{t=await e.clone().json()}catch{}if(f(t)){let n=t.code??(t.type?.startsWith(`urn:wow:error:`)?t.type.slice(14):void 0);return a({...t,type:t.type??`about:blank`,title:t.title??e.statusText,...n===void 0?{}:{code:n}})}return{type:`about:blank`,title:e.statusText,status:e.status}}async function h(e){if(e instanceof s)return e;if(typeof e!=`object`||!e)return;let{exchange:t,cause:n}=e;if(n instanceof s)return n;let r=t?.response;if(!r||r.ok)return;let i=await m(r),a=p(r.headers.get(`Retry-After`));return new s(i,{cause:e,...a===void 0?{}:{retryAfterMs:a}})}exports.CommandRejectedError=c,exports.DEFAULT_RETRY=e.DEFAULT_RETRY,exports.FRAMEWORK_ERROR_PREFIX=n,exports.FRAMEWORK_RETRIES=e.FRAMEWORK_RETRIES,exports.FrameworkErrorCodes=e.FrameworkErrorCodes,exports.PROBLEM_TYPE_PREFIX=r,exports.WowProblemError=s,exports.isProblem=f,exports.parseRetryAfter=p,exports.readProblem=m,exports.rememberRequestId=u,exports.requestIdOf=d,exports.retryOf=o,exports.toWowProblemError=h;
2
2
  //# sourceMappingURL=problem.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"problem.cjs","names":["FrameworkErrorCodes","FRAMEWORK_ERROR_PREFIX","PROBLEM_TYPE_PREFIX","PROBLEM_MEMBERS","withExtensions","problem","extensions","name","RETRYABLE","retryHintOf","sameRequestId","code","retryable","status","afterMs","WowProblemError","SENT_REQUEST_IDS","options","rememberRequestId","error","requestId","requestIdOf","isProblem","value","parseRetryAfter","trimmed","date","now","readProblem","body","response","toWowProblemError","cause","exchange","retryAfterMs"],"sources":["../src/problem.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 { CommandResult, Violation } from './wire.js';\n\n/**\n * The framework's error codes (design 05 §3, decisions D102, D103, D130),\n * each answered with the status of the Manifest's `errors` table. A domain\n * rejection has a code of its own, answered with 422 unless the service\n * configures another status.\n */\nexport const FrameworkErrorCodes = {\n /** 401: the request carries no valid credentials. */\n AUTH_UNAUTHENTICATED: 'wow.auth.unauthenticated',\n /** 403: the caller may not send this command. */\n AUTH_FORBIDDEN: 'wow.auth.forbidden',\n /** 403: the aggregate is outside the caller's scope. */\n AGGREGATE_FORBIDDEN: 'wow.aggregate.forbidden',\n /** 400: the command body cannot be read as the command type. */\n COMMAND_MALFORMED: 'wow.command.malformed',\n /** 400: the command failed validation; the problem lists the violations. */\n COMMAND_INVALID: 'wow.command.invalid',\n /** 400: the wait is not a chain the runtime can follow. */\n WAIT_INVALID: 'wow.wait.invalid',\n /** 400: the aggregate does not handle this command. */\n COMMAND_UNHANDLED: 'wow.command.unhandled',\n /** 404: the aggregate does not exist. */\n AGGREGATE_NOT_FOUND: 'wow.aggregate.not-found',\n /** 409: the aggregate already exists. */\n AGGREGATE_EXISTS: 'wow.aggregate.exists',\n /** 409, or 412 with `If-Match`: the aggregate is not at the expected version. */\n AGGREGATE_VERSION_MISMATCH: 'wow.aggregate.version-mismatch',\n /** 409: the request id was used by another command. */\n COMMAND_REQUEST_ID_REUSED: 'wow.command.request-id-reused',\n /** 409: concurrent writers kept winning; retrying with the same request id is safe. */\n COMMAND_CONTENDED: 'wow.command.contended',\n /** 410: the aggregate is deleted; only RestoreAggregate applies. */\n AGGREGATE_DELETED: 'wow.aggregate.deleted',\n /** 429: the command was not taken, its aggregate or the node being busy; retry later. */\n COMMAND_BUSY: 'wow.command.busy',\n /** 503: whether the command committed is unknown; retrying with the same request id is safe. */\n COMMAND_UNKNOWN: 'wow.command.unknown',\n /** 500: the command's handling failed with an unexpected error; it committed nothing, and a retry fails alike. */\n COMMAND_FAILED: 'wow.command.failed',\n /** 503: the node is shutting down; retry on another node. */\n NODE_CLOSING: 'wow.node.closing',\n /** 503: the node is on standby until a migration's cut-over; it serves reads only. */\n NODE_STANDBY: 'wow.node.standby',\n /** 503, with `Retry-After`: a store could not be reached in time; retry later. */\n STORAGE_UNAVAILABLE: 'wow.storage.unavailable',\n /** 503: a scheduled command arrived too long before its due time; it is sent again later. */\n SCHEDULE_NOT_DUE: 'wow.schedule.not-due',\n /** 400: the job command does not fit its job or instance (decision D198). */\n SCHEDULE_JOB_INVALID: 'wow.schedule.job-invalid',\n /** 500: a subscription on the wait chain parked the aggregate. */\n SUBSCRIPTION_PARKED: 'wow.subscription.parked',\n /** 504: the wait ran out of time; the command may have committed. */\n WAIT_TIMEOUT: 'wow.wait.timeout',\n /** 400: the query body cannot be read as a query. */\n QUERY_MALFORMED: 'wow.query.malformed',\n /** 400: the query failed admission; each violation has its code. */\n QUERY_INVALID: 'wow.query.invalid',\n /** 500: the query backend failed to run the query. */\n QUERY_FAILED: 'wow.query.failed',\n /** 504: the query ran longer than its budget allows; not retried (decision D254 ③). */\n QUERY_TIMEOUT: 'wow.query.timeout',\n /** 429, with `Retry-After`: the query's store runs as many queries as it allows; retry later. */\n QUERY_BUSY: 'wow.query.busy',\n /**\n * 404: a `single` query matched no record, whatever its model (review R4-Q,\n * Q-4); a state read by id that finds none is `wow.aggregate.not-found`.\n */\n QUERY_NOT_FOUND: 'wow.query.not-found',\n /** 404: no dataset of that name is served to the caller. */\n QUERY_DATASET_NOT_FOUND: 'wow.query.dataset-not-found',\n /**\n * 409, with `Retry-After`: a state read asked for a version (`minVersion`) the\n * aggregate has not reached within the wait; the problem's `version` is its\n * current one (review R4-Q, Q-13).\n */\n QUERY_MIN_VERSION_NOT_REACHED: 'wow.query.min-version-not-reached',\n /** 409: the dataset is served but cannot be queried now (it needs revision, decision D259). */\n QUERY_DATASET_UNAVAILABLE: 'wow.query.dataset-unavailable',\n /** 403: the calling service may not call this command (a synchronous call on the internal port, decision D226). */\n CALL_COMMAND_FORBIDDEN: 'wow.call.command-forbidden',\n} as const;\n\n/** A {@link FrameworkErrorCodes} value. */\nexport type FrameworkErrorCode =\n (typeof FrameworkErrorCodes)[keyof typeof FrameworkErrorCodes];\n\n/** The prefix of every framework code, and of no domain code. */\nexport const FRAMEWORK_ERROR_PREFIX = 'wow.';\n\n/** The prefix of a problem's `type` that carries a Wow code. */\nexport const PROBLEM_TYPE_PREFIX = 'urn:wow:error:';\n\n/**\n * An RFC 9457 problem as a Wow service writes it (decisions D101, D102):\n * `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is\n * only HTTP's (a missing route, 406, 415).\n */\nexport interface Problem {\n readonly type: string;\n readonly title: string;\n readonly status: number;\n readonly detail?: string;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n readonly violations?: readonly Violation[];\n /** The whole result of a command that has a ref. */\n readonly result?: CommandResult;\n /**\n * The problem's extension members (RFC 9457): every member the server\n * wrote besides the ones above and `instance`, such as a rejection's\n * structured data (decision D211). Absent when it wrote none.\n */\n readonly extensions?: Readonly<Record<string, unknown>>;\n}\n\n/** The members of a problem that are not extension members. */\nconst PROBLEM_MEMBERS: ReadonlySet<string> = new Set([\n 'type',\n 'title',\n 'status',\n 'detail',\n 'instance',\n 'code',\n 'violations',\n 'result',\n 'extensions',\n]);\n\n/**\n * `problem` with its extension members gathered as `extensions` (internal):\n * a problem read from the wire carries them as top-level members.\n */\nfunction withExtensions(problem: Problem): Problem {\n if (problem.extensions !== undefined) return problem;\n const extensions = Object.fromEntries(\n Object.entries(problem).filter(([name]) => !PROBLEM_MEMBERS.has(name)),\n );\n return Object.keys(extensions).length === 0\n ? problem\n : { ...problem, extensions };\n}\n\n/**\n * What a client may do about a failed request: whether retrying can succeed,\n * whether to keep the request id (`Wow-Request-Id`) so the server\n * deduplicates a command that did commit, and how long to wait first.\n */\nexport interface RetryHint {\n readonly retryable: boolean;\n /** Retry with the same `Wow-Request-Id`: a commit is then answered as a duplicate. */\n readonly sameRequestId: boolean;\n /** The server's `Retry-After`, in milliseconds. */\n readonly afterMs?: number;\n}\n\n/**\n * The codes a retry may get past, each with whether to keep the request id:\n * the 503s (`wow.command.unknown`, `wow.node.closing`, `wow.node.standby`,\n * `wow.storage.unavailable`, `wow.schedule.not-due`),\n * the 429s `wow.command.busy` and `wow.query.busy`, the 409s `wow.command.contended` and\n * `wow.query.min-version-not-reached` (once the command commits), and the 504\n * `wow.wait.timeout`, whose command may have committed.\n */\nconst RETRYABLE: ReadonlyMap<string, boolean> = new Map([\n [FrameworkErrorCodes.COMMAND_UNKNOWN, true],\n [FrameworkErrorCodes.NODE_CLOSING, true],\n [FrameworkErrorCodes.NODE_STANDBY, true],\n [FrameworkErrorCodes.STORAGE_UNAVAILABLE, true],\n [FrameworkErrorCodes.SCHEDULE_NOT_DUE, true],\n [FrameworkErrorCodes.COMMAND_BUSY, true],\n [FrameworkErrorCodes.QUERY_BUSY, false],\n [FrameworkErrorCodes.QUERY_MIN_VERSION_NOT_REACHED, false],\n [FrameworkErrorCodes.COMMAND_CONTENDED, true],\n [FrameworkErrorCodes.WAIT_TIMEOUT, true],\n]);\n\n/**\n * The retry hint of a problem with `code` and `status`: a code of the\n * retryable table, or a 503 without a code (a proxy's), may be retried.\n *\n * @param code - The problem's Wow code, if any\n * @param status - The HTTP status\n * @param afterMs - The `Retry-After` the response carried, in milliseconds\n */\nexport function retryHintOf(\n code: string | undefined,\n status: number,\n afterMs?: number,\n): RetryHint {\n const sameRequestId = code === undefined ? undefined : RETRYABLE.get(code);\n const retryable =\n sameRequestId !== undefined || (code === undefined && status === 503);\n return {\n retryable,\n sameRequestId: sameRequestId ?? retryable,\n ...(afterMs === undefined ? {} : { afterMs }),\n };\n}\n\n/**\n * A request a Wow service answered with a problem: a non-2xx response, a\n * command result that did not succeed, or the `error` event that ends a\n * streamed query.\n */\nexport class WowProblemError extends Error {\n override readonly name = 'WowProblemError';\n /** The problem as the server wrote it. */\n readonly problem: Problem;\n /** The HTTP status. */\n readonly status: number;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n readonly violations: readonly Violation[];\n /** The command's result, when the command had a ref. */\n readonly result?: CommandResult;\n /** What a client may do about it. */\n readonly retry: RetryHint;\n /** The error this one explains: the fetcher's, or the stream's. */\n readonly cause?: unknown;\n\n /**\n * The request id (`Wow-Request-Id`) of the command this answers: its\n * result's, else the one the client sent. Retry with it when\n * {@link RetryHint.sameRequestId} says so.\n */\n get requestId(): string | undefined {\n return this.result?.requestId ?? SENT_REQUEST_IDS.get(this);\n }\n\n /**\n * @param problem - The problem the server answered with\n * @param options - The response's `Retry-After` in milliseconds, and the\n * error this one explains\n */\n constructor(\n problem: Problem,\n options: { retryAfterMs?: number; cause?: unknown } = {},\n ) {\n super(\n problem.code\n ? `[${problem.code}] ${problem.detail ?? problem.title}`\n : `${problem.status} ${problem.detail ?? problem.title}`,\n );\n this.problem = withExtensions(problem);\n this.status = problem.status;\n if (problem.code !== undefined) this.code = problem.code;\n this.violations = problem.violations ?? [];\n if (problem.result !== undefined) this.result = problem.result;\n this.retry = retryHintOf(\n problem.code,\n problem.status,\n options.retryAfterMs,\n );\n if (options.cause !== undefined) this.cause = options.cause;\n }\n\n /** Whether the code is a framework one (`wow.*`) rather than the domain's. */\n get isFramework(): boolean {\n return this.code?.startsWith(FRAMEWORK_ERROR_PREFIX) ?? false;\n }\n}\n\n/** The request ids the client sent, by the errors the requests failed with. */\nconst SENT_REQUEST_IDS = new WeakMap<object, string>();\n\n/**\n * Remembers that the request that failed with `error` was sent with\n * `requestId` (internal): {@link requestIdOf} answers it.\n *\n * @param error - What the request failed with\n * @param requestId - The `Wow-Request-Id` it was sent with\n */\nexport function rememberRequestId(error: unknown, requestId: string): void {\n if (\n (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ) {\n if (!SENT_REQUEST_IDS.has(error)) SENT_REQUEST_IDS.set(error, requestId);\n }\n}\n\n/**\n * The request id (`Wow-Request-Id`) a command that failed with `error` was\n * sent with: also after a failure no server answered (the network, a proxy,\n * an abort), so the command can be retried with the same id and the service\n * answers a commit that did happen as a duplicate (decision D223).\n * Undefined for an error of no command the client sent.\n *\n * @param error - What a command rejected with\n */\nexport function requestIdOf(error: unknown): string | undefined {\n if (error instanceof WowProblemError) return error.requestId;\n return (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ? SENT_REQUEST_IDS.get(error)\n : undefined;\n}\n\n/** Whether `value` reads as a problem: an object with a numeric `status`. */\nexport function isProblem(value: unknown): value is Problem {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { status?: unknown }).status === 'number'\n );\n}\n\n/**\n * The milliseconds of a `Retry-After` header: delay seconds or an HTTP date.\n *\n * @param value - The header's value\n * @param now - The current time, in epoch milliseconds\n */\nexport function parseRetryAfter(\n value: string | null | undefined,\n now: number = Date.now(),\n): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000;\n const date = Date.parse(trimmed);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/**\n * The problem a response that did not succeed carries: its body when it is\n * a problem (or a code the `type` names), else one made of its status.\n *\n * @param response - A response that is not 2xx\n */\nexport async function readProblem(response: Response): Promise<Problem> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n // Not JSON, or already read: the status is all there is.\n }\n if (isProblem(body)) {\n const code =\n body.code ??\n (body.type?.startsWith(PROBLEM_TYPE_PREFIX)\n ? body.type.slice(PROBLEM_TYPE_PREFIX.length)\n : undefined);\n return withExtensions({\n ...body,\n type: body.type ?? 'about:blank',\n title: body.title ?? response.statusText,\n ...(code === undefined ? {} : { code }),\n });\n }\n return {\n type: 'about:blank',\n title: response.statusText,\n status: response.status,\n };\n}\n\ninterface ExchangeLike {\n exchange?: { response?: Response };\n cause?: unknown;\n}\n\n/**\n * The {@link WowProblemError} of an error a request rejected with: the\n * fetcher's `ExchangeError` of a response that is not 2xx, read as a problem.\n * Undefined for a failure no server answered (a network error, an abort).\n *\n * @param error - What the request rejected with\n */\nexport async function toWowProblemError(\n error: unknown,\n): Promise<WowProblemError | undefined> {\n if (error instanceof WowProblemError) return error;\n if (typeof error !== 'object' || error === null) return undefined;\n const { exchange, cause } = error as ExchangeLike;\n if (cause instanceof WowProblemError) return cause;\n const response = exchange?.response;\n if (!response || response.ok) return undefined;\n const problem = await readProblem(response);\n const retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n return new WowProblemError(problem, {\n cause: error,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n}\n"],"mappings":"AAqBA,IAAaA,EAAsB,CAEjC,qBAAsB,2BAEtB,eAAgB,qBAEhB,oBAAqB,0BAErB,kBAAmB,wBAEnB,gBAAiB,sBAEjB,aAAc,mBAEd,kBAAmB,wBAEnB,oBAAqB,0BAErB,iBAAkB,uBAElB,2BAA4B,iCAE5B,0BAA2B,gCAE3B,kBAAmB,wBAEnB,kBAAmB,wBAEnB,aAAc,mBAEd,gBAAiB,sBAEjB,eAAgB,qBAEhB,aAAc,mBAEd,aAAc,mBAEd,oBAAqB,0BAErB,iBAAkB,uBAElB,qBAAsB,2BAEtB,oBAAqB,0BAErB,aAAc,mBAEd,gBAAiB,sBAEjB,cAAe,oBAEf,aAAc,mBAEd,cAAe,oBAEf,WAAY,iBAKZ,gBAAiB,sBAEjB,wBAAyB,8BAMzB,8BAA+B,oCAE/B,0BAA2B,gCAE3B,uBAAwB,4BAC1B,EAOaC,EAAyB,OAGzBC,EAAsB,iBA0B7BC,EAAuC,IAAI,IAAI,CACnD,OACA,QACA,SACA,SACA,WACA,OACA,aACA,SACA,YACF,CAAC,EAMD,SAASC,EAAe,EAA2B,CACjD,GAAIC,EAAQ,aAAe,IAAA,GAAW,OAAOA,EAC7C,IAAMC,EAAa,OAAO,YACxB,OAAO,QAAQD,CAAO,CAAC,CAAC,QAAQ,CAACE,KAAU,CAACJ,EAAgB,IAAII,CAAI,CAAC,CACvE,EACA,OAAO,OAAO,KAAKD,CAAU,CAAC,CAAC,SAAW,EACtCD,EACA,CAAE,GAAGA,EAAS,YAAW,CAC/B,CAuBA,IAAMG,EAA0C,IAAI,IAAI,CACtD,CAACR,EAAoB,gBAAiB,EAAI,EAC1C,CAACA,EAAoB,aAAc,EAAI,EACvC,CAACA,EAAoB,aAAc,EAAI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AAIZ,aAAiBJ,EAAiB,OAAOI,EAC7C,GAAI,OAAOA,GAAU,WAAYA,EAAgB,OACjD,GAAM,CAAE,WAAU,SAAUA,EAC5B,GAAIa,aAAiBjB,EAAiB,OAAOiB,EAC7C,IAAMF,EAAWG,GAAU,SAC3B,GAAI,CAACH,GAAYA,EAAS,GAAI,OAC9B,IAAMzB,EAAU,MAAMuB,EAAYE,CAAQ,EACpCI,EAAeV,EAAgBM,EAAS,QAAQ,IAAI,aAAa,CAAC,EACxE,OAAO,IAAIf,EAAgBV,EAAS,CAClC,MAAOc,EACP,GAAIe,IAAiB,IAAA,GAAY,CAAC,EAAI,CAAE,cAAa,CACvD,CAAC,CACH"}
1
+ {"version":3,"file":"problem.cjs","names":["FRAMEWORK_RETRIES","CommandResultStatus","require_frameworkErrors","require_wire","FRAMEWORK_ERROR_PREFIX","PROBLEM_TYPE_PREFIX","PROBLEM_MEMBERS","withExtensions","problem","extensions","name","retryOf","known","WowProblemError","SENT_REQUEST_IDS","retryAfterMs","options","CommandRejectedError","said","result","rememberRequestId","error","requestId","requestIdOf","isProblem","value","parseRetryAfter","trimmed","date","now","readProblem","body","response","code","toWowProblemError","cause","exchange"],"sources":["../src/problem.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 { FRAMEWORK_RETRIES, type Retry } from './frameworkErrors.js';\nimport {\n CommandResultStatus,\n type RefusedResult,\n type Violation,\n} from './wire.js';\n\nexport {\n DEFAULT_RETRY,\n FRAMEWORK_RETRIES,\n type FrameworkRetry,\n type FrameworkErrorCode,\n FrameworkErrorCodes,\n type Retry,\n} from './frameworkErrors.js';\n\n/** The prefix of every framework code, and of no domain code. */\nexport const FRAMEWORK_ERROR_PREFIX = 'wow.';\n\n/** The prefix of a problem's `type` that carries a Wow code. */\nexport const PROBLEM_TYPE_PREFIX = 'urn:wow:error:';\n\n/**\n * An RFC 9457 problem as a Wow service writes it:\n * `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is\n * only HTTP's (a missing route, 406, 415).\n */\nexport interface Problem {\n readonly type: string;\n readonly title: string;\n readonly status: number;\n readonly detail?: string;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n /**\n * What a retry may do, as the error catalog declares it for the code: every\n * problem a Wow service writes carries it.\n */\n readonly retry?: Retry;\n readonly violations?: readonly Violation[];\n /**\n * The whole result of a command that has a ref; its id is null when\n * admission refused a creation before choosing one.\n */\n readonly result?: RefusedResult;\n /**\n * The problem's extension members (RFC 9457): every member the server\n * wrote besides the ones above and `instance`, such as a rejection's\n * structured data (decision D211). Absent when it wrote none.\n */\n readonly extensions?: Readonly<Record<string, unknown>>;\n}\n\n/** The members of a problem that are not extension members. */\nconst PROBLEM_MEMBERS: ReadonlySet<string> = new Set([\n 'type',\n 'title',\n 'status',\n 'detail',\n 'instance',\n 'code',\n 'retry',\n 'violations',\n 'result',\n 'extensions',\n]);\n\n/**\n * `problem` with its extension members gathered as `extensions` (internal):\n * a problem read from the wire carries them as top-level members.\n */\nfunction withExtensions(problem: Problem): Problem {\n if (problem.extensions !== undefined) return problem;\n const extensions = Object.fromEntries(\n Object.entries(problem).filter(([name]) => !PROBLEM_MEMBERS.has(name)),\n );\n return Object.keys(extensions).length === 0\n ? problem\n : { ...problem, extensions };\n}\n\n/**\n * What a retry of `problem` may do: its `retry` member, which every problem a\n * Wow service writes carries; else the error catalog's for its code; else, for\n * a body that is no Wow problem (a proxy's 503 or 429), `same-request`.\n *\n * @param problem - The problem a request was answered with\n */\nexport function retryOf(problem: Problem): Retry {\n if (problem.retry !== undefined) return problem.retry;\n const known =\n problem.code === undefined\n ? undefined\n : FRAMEWORK_RETRIES.get(problem.code);\n if (known) return known.retry;\n return problem.code === undefined &&\n (problem.status === 503 || problem.status === 429)\n ? 'same-request'\n : 'none';\n}\n\n/**\n * A request a Wow service answered with a problem: a non-2xx response, a\n * command result that did not succeed, or the `error` event that ends a\n * streamed query.\n */\nexport class WowProblemError extends Error {\n override readonly name = 'WowProblemError';\n /** The problem as the server wrote it. */\n readonly problem: Problem;\n /** The HTTP status. */\n readonly status: number;\n /** The Wow code; absent for an error that is only HTTP's. */\n readonly code?: string;\n readonly violations: readonly Violation[];\n /** The command's result, when the command had a ref ({@link RefusedResult}). */\n readonly result?: RefusedResult;\n /** What a retry may do ({@link retryOf}). */\n readonly retry: Retry;\n /**\n * How long to wait before a retry, in milliseconds: the response's\n * `Retry-After`, else the error catalog's for its code; none when no retry\n * may get past it.\n */\n readonly retryAfterMs?: number;\n /** The error this one explains: the fetcher's, or the stream's. */\n readonly cause?: unknown;\n\n /**\n * The request id (`Wow-Request-Id`) of the command this answers: its\n * result's, else the one the client sent. Retry with it when\n * {@link WowProblemError.retry} is `same-request`.\n */\n get requestId(): string | undefined {\n return this.result?.requestId ?? SENT_REQUEST_IDS.get(this);\n }\n\n /**\n * @param problem - The problem the server answered with\n * @param options - The response's `Retry-After` in milliseconds, and the\n * error this one explains\n */\n constructor(\n problem: Problem,\n options: { retryAfterMs?: number; cause?: unknown } = {},\n ) {\n super(\n problem.code\n ? `[${problem.code}] ${problem.detail ?? problem.title}`\n : `${problem.status} ${problem.detail ?? problem.title}`,\n );\n this.problem = withExtensions(problem);\n this.status = problem.status;\n if (problem.code !== undefined) this.code = problem.code;\n this.violations = problem.violations ?? [];\n if (problem.result !== undefined) this.result = problem.result;\n this.retry = retryOf(problem);\n const retryAfterMs =\n options.retryAfterMs ??\n (problem.code === undefined\n ? undefined\n : FRAMEWORK_RETRIES.get(problem.code)?.retryAfterMs);\n if (this.retry !== 'none' && retryAfterMs !== undefined) {\n this.retryAfterMs = retryAfterMs;\n }\n if (options.cause !== undefined) this.cause = options.cause;\n }\n\n /** Whether the code is a framework one (`wow.*`) rather than the domain's. */\n get isFramework(): boolean {\n return this.code?.startsWith(FRAMEWORK_ERROR_PREFIX) ?? false;\n }\n}\n\n/**\n * The command was rejected: its result's status is `rejected`, decided by\n * its aggregate (a business outcome with the domain's code) or at admission\n * (an unknown command, an invalid one, a caller the authorizer forbids).\n * Sending it again with the same request id is rejected again. As Kotlin's\n * `CommandRejectedException`. `send` and `wait` map what a command is\n * answered by the result's status, not by where it was refused (Kotlin's\n * `CommandClient` maps it the same way):\n *\n * - a result that succeeded: resolved;\n * - a rejected result: a {@link CommandRejectedError};\n * - a problem whose result is rejected, an admission refusal (an unknown\n * command, an invalid one, a forbidden caller): a\n * {@link CommandRejectedError}, its `problem` set;\n * - a result of a status this client does not know, a newer service's: a\n * {@link WowProblemError} `wow.command.failed`, not retryable;\n * - any other problem, refused before admission (a body that does not\n * parse), a technical failure (a busy or closing node, a store or a broker\n * that is down, a wait that timed out) or a failed result: a\n * {@link WowProblemError}, with its result when the service sent one, and\n * what a retry may do ({@link WowProblemError.retry}).\n *\n * `stream` emits every result, whatever its status.\n */\nexport class CommandRejectedError extends Error {\n override readonly name = 'CommandRejectedError';\n /** The rejected result; its ref names no aggregate id when none was decided. */\n readonly result: RefusedResult;\n /** The problem the service answered with, when it answered one. */\n readonly problem?: Problem;\n /** The error this one explains. */\n readonly cause?: unknown;\n\n /**\n * @param result - The rejected result\n * @param options - The problem it came in, and the error this one explains\n */\n constructor(\n result: RefusedResult,\n options: { problem?: Problem; cause?: unknown } = {},\n ) {\n const said = [result.error?.code, result.error?.message]\n .filter(Boolean)\n .join(' ');\n super(\n `${result.ref.type.context}.${result.ref.type.name}/${result.ref.id ?? '(no id)'} rejected the command` +\n (said ? `: ${said}` : '.'),\n );\n if (result.status !== CommandResultStatus.REJECTED) {\n throw new TypeError(\n `A rejection has a rejected result, not ${result.status}.`,\n );\n }\n this.result = result;\n if (options.problem !== undefined) this.problem = options.problem;\n if (options.cause !== undefined) this.cause = options.cause;\n }\n\n /** The rejection's error code. */\n get code(): string {\n return this.result.error?.code ?? '';\n }\n\n /** The request id (`Wow-Request-Id`) of the rejected command. */\n get requestId(): string {\n return this.result.requestId;\n }\n}\n\n/** The request ids the client sent, by the errors the requests failed with. */\nconst SENT_REQUEST_IDS = new WeakMap<object, string>();\n\n/**\n * Remembers that the request that failed with `error` was sent with\n * `requestId` (internal): {@link requestIdOf} answers it.\n *\n * @param error - What the request failed with\n * @param requestId - The `Wow-Request-Id` it was sent with\n */\nexport function rememberRequestId(error: unknown, requestId: string): void {\n if (\n (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ) {\n if (!SENT_REQUEST_IDS.has(error)) SENT_REQUEST_IDS.set(error, requestId);\n }\n}\n\n/**\n * The request id (`Wow-Request-Id`) a command that failed with `error` was\n * sent with: also after a failure no server answered (the network, a proxy,\n * an abort), so the command can be retried with the same id and the service\n * answers a commit that did happen as a duplicate.\n * Undefined for an error of no command the client sent.\n *\n * @param error - What a command rejected with\n */\nexport function requestIdOf(error: unknown): string | undefined {\n if (error instanceof WowProblemError) return error.requestId;\n return (typeof error === 'object' && error !== null) ||\n typeof error === 'function'\n ? SENT_REQUEST_IDS.get(error)\n : undefined;\n}\n\n/** Whether `value` reads as a problem: an object with a numeric `status`. */\nexport function isProblem(value: unknown): value is Problem {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { status?: unknown }).status === 'number'\n );\n}\n\n/**\n * The milliseconds of a `Retry-After` header: delay seconds or an HTTP date.\n *\n * @param value - The header's value\n * @param now - The current time, in epoch milliseconds\n */\nexport function parseRetryAfter(\n value: string | null | undefined,\n now: number = Date.now(),\n): number | undefined {\n if (!value) return undefined;\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed) * 1000;\n const date = Date.parse(trimmed);\n return Number.isNaN(date) ? undefined : Math.max(0, date - now);\n}\n\n/**\n * The problem a response that did not succeed carries: its body when it is\n * a problem (or a code the `type` names), else one made of its status.\n *\n * @param response - A response that is not 2xx\n */\nexport async function readProblem(response: Response): Promise<Problem> {\n let body: unknown;\n try {\n body = await response.clone().json();\n } catch {\n // Not JSON, or already read: the status is all there is.\n }\n if (isProblem(body)) {\n const code =\n body.code ??\n (body.type?.startsWith(PROBLEM_TYPE_PREFIX)\n ? body.type.slice(PROBLEM_TYPE_PREFIX.length)\n : undefined);\n return withExtensions({\n ...body,\n type: body.type ?? 'about:blank',\n title: body.title ?? response.statusText,\n ...(code === undefined ? {} : { code }),\n });\n }\n return {\n type: 'about:blank',\n title: response.statusText,\n status: response.status,\n };\n}\n\ninterface ExchangeLike {\n exchange?: { response?: Response };\n cause?: unknown;\n}\n\n/**\n * The {@link WowProblemError} of an error a request rejected with: the\n * fetcher's `ExchangeError` of a response that is not 2xx, read as a problem.\n * Undefined for a failure no server answered (a network error, an abort).\n *\n * @param error - What the request rejected with\n */\nexport async function toWowProblemError(\n error: unknown,\n): Promise<WowProblemError | undefined> {\n if (error instanceof WowProblemError) return error;\n if (typeof error !== 'object' || error === null) return undefined;\n const { exchange, cause } = error as ExchangeLike;\n if (cause instanceof WowProblemError) return cause;\n const response = exchange?.response;\n if (!response || response.ok) return undefined;\n const problem = await readProblem(response);\n const retryAfterMs = parseRetryAfter(response.headers.get('Retry-After'));\n return new WowProblemError(problem, {\n cause: error,\n ...(retryAfterMs === undefined ? {} : { retryAfterMs }),\n });\n}\n"],"mappings":"A,iEA8BA,IAAaI,EAAyB,OAGzBC,EAAsB,iBAkC7BC,EAAuC,IAAI,IAAI,CACnD,OACA,QACA,SACA,SACA,WACA,OACA,QACA,aACA,SACA,YACF,CAAC,EAMD,SAASC,EAAe,EAA2B,CACjD,GAAIC,EAAQ,aAAe,IAAA,GAAW,OAAOA,EAC7C,IAAMC,EAAa,OAAO,YACxB,OAAO,QAAQD,CAAO,CAAC,CAAC,QAAQ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es (design 05 §3, decisions D102, D103, D130),
4
- * each answered with the status of the Manifest's `errors` table. A domain
5
- * rejection has a code of its own, answered with 422 unless the service
6
- * configures another status.
7
- */
8
- export declare const FrameworkErrorCodes: {
9
- /** 401: the request carries no valid credentials. */
10
- readonly AUTH_UNAUTHENTICATED: "wow.auth.unauthenticated";
11
- /** 403: the caller may not send this command. */
12
- readonly AUTH_FORBIDDEN: "wow.auth.forbidden";
13
- /** 403: the aggregate is outside the caller's scope. */
14
- readonly AGGREGATE_FORBIDDEN: "wow.aggregate.forbidden";
15
- /** 400: the command body cannot be read as the command type. */
16
- readonly COMMAND_MALFORMED: "wow.command.malformed";
17
- /** 400: the command failed validation; the problem lists the violations. */
18
- readonly COMMAND_INVALID: "wow.command.invalid";
19
- /** 400: the wait is not a chain the runtime can follow. */
20
- readonly WAIT_INVALID: "wow.wait.invalid";
21
- /** 400: the aggregate does not handle this command. */
22
- readonly COMMAND_UNHANDLED: "wow.command.unhandled";
23
- /** 404: the aggregate does not exist. */
24
- readonly AGGREGATE_NOT_FOUND: "wow.aggregate.not-found";
25
- /** 409: the aggregate already exists. */
26
- readonly AGGREGATE_EXISTS: "wow.aggregate.exists";
27
- /** 409, or 412 with `If-Match`: the aggregate is not at the expected version. */
28
- readonly AGGREGATE_VERSION_MISMATCH: "wow.aggregate.version-mismatch";
29
- /** 409: the request id was used by another command. */
30
- readonly COMMAND_REQUEST_ID_REUSED: "wow.command.request-id-reused";
31
- /** 409: concurrent writers kept winning; retrying with the same request id is safe. */
32
- readonly COMMAND_CONTENDED: "wow.command.contended";
33
- /** 410: the aggregate is deleted; only RestoreAggregate applies. */
34
- readonly AGGREGATE_DELETED: "wow.aggregate.deleted";
35
- /** 429: the command was not taken, its aggregate or the node being busy; retry later. */
36
- readonly COMMAND_BUSY: "wow.command.busy";
37
- /** 503: whether the command committed is unknown; retrying with the same request id is safe. */
38
- readonly COMMAND_UNKNOWN: "wow.command.unknown";
39
- /** 500: the command's handling failed with an unexpected error; it committed nothing, and a retry fails alike. */
40
- readonly COMMAND_FAILED: "wow.command.failed";
41
- /** 503: the node is shutting down; retry on another node. */
42
- readonly NODE_CLOSING: "wow.node.closing";
43
- /** 503: the node is on standby until a migration's cut-over; it serves reads only. */
44
- readonly NODE_STANDBY: "wow.node.standby";
45
- /** 503, with `Retry-After`: a store could not be reached in time; retry later. */
46
- readonly STORAGE_UNAVAILABLE: "wow.storage.unavailable";
47
- /** 503: a scheduled command arrived too long before its due time; it is sent again later. */
48
- readonly SCHEDULE_NOT_DUE: "wow.schedule.not-due";
49
- /** 400: the job command does not fit its job or instance (decision D198). */
50
- readonly SCHEDULE_JOB_INVALID: "wow.schedule.job-invalid";
51
- /** 500: a subscription on the wait chain parked the aggregate. */
52
- readonly SUBSCRIPTION_PARKED: "wow.subscription.parked";
53
- /** 504: the wait ran out of time; the command may have committed. */
54
- readonly WAIT_TIMEOUT: "wow.wait.timeout";
55
- /** 400: the query body cannot be read as a query. */
56
- readonly QUERY_MALFORMED: "wow.query.malformed";
57
- /** 400: the query failed admission; each violation has its code. */
58
- readonly QUERY_INVALID: "wow.query.invalid";
59
- /** 500: the query backend failed to run the query. */
60
- readonly QUERY_FAILED: "wow.query.failed";
61
- /** 504: the query ran longer than its budget allows; not retried (decision D254 ③). */
62
- readonly QUERY_TIMEOUT: "wow.query.timeout";
63
- /** 429, with `Retry-After`: the query's store runs as many queries as it allows; retry later. */
64
- readonly QUERY_BUSY: "wow.query.busy";
65
- /**
66
- * 404: a `single` query matched no record, whatever its model (review R4-Q,
67
- * Q-4); a state read by id that finds none is `wow.aggregate.not-found`.
68
- */
69
- readonly QUERY_NOT_FOUND: "wow.query.not-found";
70
- /** 404: no dataset of that name is served to the caller. */
71
- readonly QUERY_DATASET_NOT_FOUND: "wow.query.dataset-not-found";
72
- /**
73
- * 409, with `Retry-After`: a state read asked for a version (`minVersion`) the
74
- * aggregate has not reached within the wait; the problem's `version` is its
75
- * current one (review R4-Q, Q-13).
76
- */
77
- readonly QUERY_MIN_VERSION_NOT_REACHED: "wow.query.min-version-not-reached";
78
- /** 409: the dataset is served but cannot be queried now (it needs revision, decision D259). */
79
- readonly QUERY_DATASET_UNAVAILABLE: "wow.query.dataset-unavailable";
80
- /** 403: the calling service may not call this command (a synchronous call on the internal port, decision D226). */
81
- readonly CALL_COMMAND_FORBIDDEN: "wow.call.command-forbidden";
82
- };
83
- /** A {@link FrameworkErrorCodes} value. */
84
- export type FrameworkErrorCode = (typeof FrameworkErrorCodes)[keyof typeof FrameworkErrorCodes];
1
+ import { Retry } from './frameworkErrors.cjs';
2
+ import { RefusedResult, Violation } from './wire.cjs';
3
+ export { DEFAULT_RETRY, FRAMEWORK_RETRIES, type FrameworkRetry, type FrameworkErrorCode, FrameworkErrorCodes, type Retry, } from './frameworkErrors.cjs';
85
4
  /** The prefix of every framework code, and of no domain code. */
86
5
  export declare const FRAMEWORK_ERROR_PREFIX = "wow.";
87
6
  /** The prefix of a problem's `type` that carries a Wow code. */
88
7
  export declare const PROBLEM_TYPE_PREFIX = "urn:wow:error:";
89
8
  /**
90
- * An RFC 9457 problem as a Wow service writes it (decisions D101, D102):
9
+ * An RFC 9457 problem as a Wow service writes it:
91
10
  * `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is
92
11
  * only HTTP's (a missing route, 406, 415).
93
12
  */
@@ -98,9 +17,17 @@ export interface Problem {
98
17
  readonly detail?: string;
99
18
  /** The Wow code; absent for an error that is only HTTP's. */
100
19
  readonly code?: string;
20
+ /**
21
+ * What a retry may do, as the error catalog declares it for the code: every
22
+ * problem a Wow service writes carries it.
23
+ */
24
+ readonly retry?: Retry;
101
25
  readonly violations?: readonly Violation[];
102
- /** The whole result of a command that has a ref. */
103
- readonly result?: CommandResult;
26
+ /**
27
+ * The whole result of a command that has a ref; its id is null when
28
+ * admission refused a creation before choosing one.
29
+ */
30
+ readonly result?: RefusedResult;
104
31
  /**
105
32
  * The problem's extension members (RFC 9457): every member the server
106
33
  * wrote besides the ones above and `instance`, such as a rejection's
@@ -109,26 +36,13 @@ export interface Problem {
109
36
  readonly extensions?: Readonly<Record<string, unknown>>;
110
37
  }
111
38
  /**
112
- * What a client may do about a failed request: whether retrying can succeed,
113
- * whether to keep the request id (`Wow-Request-Id`) so the server
114
- * deduplicates a command that did commit, and how long to wait first.
115
- */
116
- export interface RetryHint {
117
- readonly retryable: boolean;
118
- /** Retry with the same `Wow-Request-Id`: a commit is then answered as a duplicate. */
119
- readonly sameRequestId: boolean;
120
- /** The server's `Retry-After`, in milliseconds. */
121
- readonly afterMs?: number;
122
- }
123
- /**
124
- * The retry hint of a problem with `code` and `status`: a code of the
125
- * retryable table, or a 503 without a code (a proxy's), may be retried.
39
+ * What a retry of `problem` may do: its `retry` member, which every problem a
40
+ * Wow service writes carries; else the error catalog's for its code; else, for
41
+ * a body that is no Wow problem (a proxy's 503 or 429), `same-request`.
126
42
  *
127
- * @param code - The problem's Wow code, if any
128
- * @param status - The HTTP status
129
- * @param afterMs - The `Retry-After` the response carried, in milliseconds
43
+ * @param problem - The problem a request was answered with
130
44
  */
131
- export declare function retryHintOf(code: string | undefined, status: number, afterMs?: number): RetryHint;
45
+ export declare function retryOf(problem: Problem): Retry;
132
46
  /**
133
47
  * A request a Wow service answered with a problem: a non-2xx response, a
134
48
  * command result that did not succeed, or the `error` event that ends a
@@ -143,16 +57,22 @@ export declare class WowProblemError extends Error {
143
57
  /** The Wow code; absent for an error that is only HTTP's. */
144
58
  readonly code?: string;
145
59
  readonly violations: readonly Violation[];
146
- /** The command's result, when the command had a ref. */
147
- readonly result?: CommandResult;
148
- /** What a client may do about it. */
149
- readonly retry: RetryHint;
60
+ /** The command's result, when the command had a ref ({@link RefusedResult}). */
61
+ readonly result?: RefusedResult;
62
+ /** What a retry may do ({@link retryOf}). */
63
+ readonly retry: Retry;
64
+ /**
65
+ * How long to wait before a retry, in milliseconds: the response's
66
+ * `Retry-After`, else the error catalog's for its code; none when no retry
67
+ * may get past it.
68
+ */
69
+ readonly retryAfterMs?: number;
150
70
  /** The error this one explains: the fetcher's, or the stream's. */
151
71
  readonly cause?: unknown;
152
72
  /**
153
73
  * The request id (`Wow-Request-Id`) of the command this answers: its
154
74
  * result's, else the one the client sent. Retry with it when
155
- * {@link RetryHint.sameRequestId} says so.
75
+ * {@link WowProblemError.retry} is `same-request`.
156
76
  */
157
77
  get requestId(): string | undefined;
158
78
  /**
@@ -167,6 +87,51 @@ export declare class WowProblemError extends Error {
167
87
  /** Whether the code is a framework one (`wow.*`) rather than the domain's. */
168
88
  get isFramework(): boolean;
169
89
  }
90
+ /**
91
+ * The command was rejected: its result's status is `rejected`, decided by
92
+ * its aggregate (a business outcome with the domain's code) or at admission
93
+ * (an unknown command, an invalid one, a caller the authorizer forbids).
94
+ * Sending it again with the same request id is rejected again. As Kotlin's
95
+ * `CommandRejectedException`. `send` and `wait` map what a command is
96
+ * answered by the result's status, not by where it was refused (Kotlin's
97
+ * `CommandClient` maps it the same way):
98
+ *
99
+ * - a result that succeeded: resolved;
100
+ * - a rejected result: a {@link CommandRejectedError};
101
+ * - a problem whose result is rejected, an admission refusal (an unknown
102
+ * command, an invalid one, a forbidden caller): a
103
+ * {@link CommandRejectedError}, its `problem` set;
104
+ * - a result of a status this client does not know, a newer service's: a
105
+ * {@link WowProblemError} `wow.command.failed`, not retryable;
106
+ * - any other problem, refused before admission (a body that does not
107
+ * parse), a technical failure (a busy or closing node, a store or a broker
108
+ * that is down, a wait that timed out) or a failed result: a
109
+ * {@link WowProblemError}, with its result when the service sent one, and
110
+ * what a retry may do ({@link WowProblemError.retry}).
111
+ *
112
+ * `stream` emits every result, whatever its status.
113
+ */
114
+ export declare class CommandRejectedError extends Error {
115
+ readonly name = "CommandRejectedError";
116
+ /** The rejected result; its ref names no aggregate id when none was decided. */
117
+ readonly result: RefusedResult;
118
+ /** The problem the service answered with, when it answered one. */
119
+ readonly problem?: Problem;
120
+ /** The error this one explains. */
121
+ readonly cause?: unknown;
122
+ /**
123
+ * @param result - The rejected result
124
+ * @param options - The problem it came in, and the error this one explains
125
+ */
126
+ constructor(result: RefusedResult, options?: {
127
+ problem?: Problem;
128
+ cause?: unknown;
129
+ });
130
+ /** The rejection's error code. */
131
+ get code(): string;
132
+ /** The request id (`Wow-Request-Id`) of the rejected command. */
133
+ get requestId(): string;
134
+ }
170
135
  /**
171
136
  * Remembers that the request that failed with `error` was sent with
172
137
  * `requestId` (internal): {@link requestIdOf} answers it.
@@ -179,7 +144,7 @@ export declare function rememberRequestId(error: unknown, requestId: string): vo
179
144
  * The request id (`Wow-Request-Id`) a command that failed with `error` was
180
145
  * sent with: also after a failure no server answered (the network, a proxy,
181
146
  * an abort), so the command can be retried with the same id and the service
182
- * answers a commit that did happen as a duplicate (decision D223).
147
+ * answers a commit that did happen as a duplicate.
183
148
  * Undefined for an error of no command the client sent.
184
149
  *
185
150
  * @param error - What a command rejected with