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

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 +77 -23
  2. package/README.zh-CN.md +67 -19
  3. package/dist/commands.cjs +1 -1
  4. package/dist/commands.cjs.map +1 -1
  5. package/dist/commands.d.cts +134 -61
  6. package/dist/commands.d.ts +134 -61
  7. package/dist/commands.es.js +129 -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 +99 -42
  63. package/dist/dsl/descriptor.d.ts +99 -42
  64. package/dist/dsl/descriptor.es.js +37 -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 +37 -95
  141. package/dist/manifest.d.ts +37 -95
  142. package/dist/manifest.es.js +12 -7
  143. package/dist/manifest.es.js.map +1 -1
  144. package/dist/manifestTypes.d.cts +195 -0
  145. package/dist/manifestTypes.d.ts +195 -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 +68 -19
  189. package/dist/wait.d.ts +68 -19
  190. package/dist/wait.es.js +61 -14
  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 +101 -50
  195. package/dist/wire.d.ts +101 -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/dist/problem.d.ts CHANGED
@@ -1,97 +1,12 @@
1
- import { CommandResult, Violation } from './wire.js';
2
- /**
3
- * The framework's error codes (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
- /** 409: the aggregate's current state refuses the command (a check of its decide function); the message says why. */
42
- readonly COMMAND_REFUSED: "wow.command.refused";
43
- /** 503: the node is shutting down; retry on another node. */
44
- readonly NODE_CLOSING: "wow.node.closing";
45
- /** 503: the node is on standby until a migration's cut-over; it serves reads only. */
46
- readonly NODE_STANDBY: "wow.node.standby";
47
- /** 503, with `Retry-After`: a store could not be reached in time; retry later. */
48
- readonly STORAGE_UNAVAILABLE: "wow.storage.unavailable";
49
- /** 503: a scheduled command arrived too long before its due time; it is sent again later. */
50
- readonly SCHEDULE_NOT_DUE: "wow.schedule.not-due";
51
- /** 400: the job command does not fit its job or instance (decision D198). */
52
- readonly SCHEDULE_JOB_INVALID: "wow.schedule.job-invalid";
53
- /** 500: a subscription on the wait chain parked the aggregate. */
54
- readonly SUBSCRIPTION_PARKED: "wow.subscription.parked";
55
- /** 409: a ledger action names a parking the entry no longer is; read it again. */
56
- readonly LEDGER_STALE: "wow.ledger.stale";
57
- /** 504: the wait ran out of time; the command may have committed. */
58
- readonly WAIT_TIMEOUT: "wow.wait.timeout";
59
- /** 400: the query body cannot be read as a query. */
60
- readonly QUERY_MALFORMED: "wow.query.malformed";
61
- /** 400: the query failed admission; each violation has its code. */
62
- readonly QUERY_INVALID: "wow.query.invalid";
63
- /** 500: the query backend failed to run the query. */
64
- readonly QUERY_FAILED: "wow.query.failed";
65
- /** 504: the query ran longer than its budget allows; not retried (decision D254 ③). */
66
- readonly QUERY_TIMEOUT: "wow.query.timeout";
67
- /** 429, with `Retry-After`: the query's store runs as many queries as it allows; retry later. */
68
- readonly QUERY_BUSY: "wow.query.busy";
69
- /**
70
- * 404: a `single` query matched no record, whatever its model (review R4-Q,
71
- * Q-4); a state read by id that finds none is `wow.aggregate.not-found`.
72
- */
73
- readonly QUERY_NOT_FOUND: "wow.query.not-found";
74
- /** 404: no dataset of that name is served to the caller. */
75
- readonly QUERY_DATASET_NOT_FOUND: "wow.query.dataset-not-found";
76
- /**
77
- * 409, with `Retry-After`: a state read asked for a version (`minVersion`) the
78
- * aggregate has not reached within the wait; the problem's `version` is its
79
- * current one (review R4-Q, Q-13).
80
- */
81
- readonly QUERY_MIN_VERSION_NOT_REACHED: "wow.query.min-version-not-reached";
82
- /** 409: the dataset is served but cannot be queried now (it needs revision, decision D259). */
83
- readonly QUERY_DATASET_UNAVAILABLE: "wow.query.dataset-unavailable";
84
- /** 403: the calling service may not call this command (a synchronous call on the internal port, decision D226). */
85
- readonly CALL_COMMAND_FORBIDDEN: "wow.call.command-forbidden";
86
- };
87
- /** A {@link FrameworkErrorCodes} value. */
88
- export type FrameworkErrorCode = (typeof FrameworkErrorCodes)[keyof typeof FrameworkErrorCodes];
1
+ import { Retry } from './frameworkErrors.js';
2
+ import { RefusedResult, Violation } from './wire.js';
3
+ export { DEFAULT_RETRY, FRAMEWORK_RETRIES, type FrameworkRetry, type FrameworkErrorCode, FrameworkErrorCodes, type Retry, } from './frameworkErrors.js';
89
4
  /** The prefix of every framework code, and of no domain code. */
90
5
  export declare const FRAMEWORK_ERROR_PREFIX = "wow.";
91
6
  /** The prefix of a problem's `type` that carries a Wow code. */
92
7
  export declare const PROBLEM_TYPE_PREFIX = "urn:wow:error:";
93
8
  /**
94
- * An RFC 9457 problem as a Wow service writes it (decisions D101, D102):
9
+ * An RFC 9457 problem as a Wow service writes it:
95
10
  * `type` is `urn:wow:error:<code>`, or `about:blank` for an error that is
96
11
  * only HTTP's (a missing route, 406, 415).
97
12
  */
@@ -102,9 +17,17 @@ export interface Problem {
102
17
  readonly detail?: string;
103
18
  /** The Wow code; absent for an error that is only HTTP's. */
104
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;
105
25
  readonly violations?: readonly Violation[];
106
- /** The whole result of a command that has a ref. */
107
- 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;
108
31
  /**
109
32
  * The problem's extension members (RFC 9457): every member the server
110
33
  * wrote besides the ones above and `instance`, such as a rejection's
@@ -113,26 +36,13 @@ export interface Problem {
113
36
  readonly extensions?: Readonly<Record<string, unknown>>;
114
37
  }
115
38
  /**
116
- * What a client may do about a failed request: whether retrying can succeed,
117
- * whether to keep the request id (`Wow-Request-Id`) so the server
118
- * deduplicates a command that did commit, and how long to wait first.
119
- */
120
- export interface RetryHint {
121
- readonly retryable: boolean;
122
- /** Retry with the same `Wow-Request-Id`: a commit is then answered as a duplicate. */
123
- readonly sameRequestId: boolean;
124
- /** The server's `Retry-After`, in milliseconds. */
125
- readonly afterMs?: number;
126
- }
127
- /**
128
- * The retry hint of a problem with `code` and `status`: a code of the
129
- * 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`.
130
42
  *
131
- * @param code - The problem's Wow code, if any
132
- * @param status - The HTTP status
133
- * @param afterMs - The `Retry-After` the response carried, in milliseconds
43
+ * @param problem - The problem a request was answered with
134
44
  */
135
- export declare function retryHintOf(code: string | undefined, status: number, afterMs?: number): RetryHint;
45
+ export declare function retryOf(problem: Problem): Retry;
136
46
  /**
137
47
  * A request a Wow service answered with a problem: a non-2xx response, a
138
48
  * command result that did not succeed, or the `error` event that ends a
@@ -147,16 +57,22 @@ export declare class WowProblemError extends Error {
147
57
  /** The Wow code; absent for an error that is only HTTP's. */
148
58
  readonly code?: string;
149
59
  readonly violations: readonly Violation[];
150
- /** The command's result, when the command had a ref. */
151
- readonly result?: CommandResult;
152
- /** What a client may do about it. */
153
- 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;
154
70
  /** The error this one explains: the fetcher's, or the stream's. */
155
71
  readonly cause?: unknown;
156
72
  /**
157
73
  * The request id (`Wow-Request-Id`) of the command this answers: its
158
74
  * result's, else the one the client sent. Retry with it when
159
- * {@link RetryHint.sameRequestId} says so.
75
+ * {@link WowProblemError.retry} is `same-request`.
160
76
  */
161
77
  get requestId(): string | undefined;
162
78
  /**
@@ -171,6 +87,51 @@ export declare class WowProblemError extends Error {
171
87
  /** Whether the code is a framework one (`wow.*`) rather than the domain's. */
172
88
  get isFramework(): boolean;
173
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
+ }
174
135
  /**
175
136
  * Remembers that the request that failed with `error` was sent with
176
137
  * `requestId` (internal): {@link requestIdOf} answers it.
@@ -183,7 +144,7 @@ export declare function rememberRequestId(error: unknown, requestId: string): vo
183
144
  * The request id (`Wow-Request-Id`) a command that failed with `error` was
184
145
  * sent with: also after a failure no server answered (the network, a proxy,
185
146
  * an abort), so the command can be retried with the same id and the service
186
- * answers a commit that did happen as a duplicate (decision D223).
147
+ * answers a commit that did happen as a duplicate.
187
148
  * Undefined for an error of no command the client sent.
188
149
  *
189
150
  * @param error - What a command rejected with
@@ -1,114 +1,80 @@
1
- //#region src/problem.ts
2
- var e = {
3
- AUTH_UNAUTHENTICATED: "wow.auth.unauthenticated",
4
- AUTH_FORBIDDEN: "wow.auth.forbidden",
5
- AGGREGATE_FORBIDDEN: "wow.aggregate.forbidden",
6
- COMMAND_MALFORMED: "wow.command.malformed",
7
- COMMAND_INVALID: "wow.command.invalid",
8
- WAIT_INVALID: "wow.wait.invalid",
9
- COMMAND_UNHANDLED: "wow.command.unhandled",
10
- AGGREGATE_NOT_FOUND: "wow.aggregate.not-found",
11
- AGGREGATE_EXISTS: "wow.aggregate.exists",
12
- AGGREGATE_VERSION_MISMATCH: "wow.aggregate.version-mismatch",
13
- COMMAND_REQUEST_ID_REUSED: "wow.command.request-id-reused",
14
- COMMAND_CONTENDED: "wow.command.contended",
15
- AGGREGATE_DELETED: "wow.aggregate.deleted",
16
- COMMAND_BUSY: "wow.command.busy",
17
- COMMAND_UNKNOWN: "wow.command.unknown",
18
- COMMAND_FAILED: "wow.command.failed",
19
- COMMAND_REFUSED: "wow.command.refused",
20
- NODE_CLOSING: "wow.node.closing",
21
- NODE_STANDBY: "wow.node.standby",
22
- STORAGE_UNAVAILABLE: "wow.storage.unavailable",
23
- SCHEDULE_NOT_DUE: "wow.schedule.not-due",
24
- SCHEDULE_JOB_INVALID: "wow.schedule.job-invalid",
25
- SUBSCRIPTION_PARKED: "wow.subscription.parked",
26
- LEDGER_STALE: "wow.ledger.stale",
27
- WAIT_TIMEOUT: "wow.wait.timeout",
28
- QUERY_MALFORMED: "wow.query.malformed",
29
- QUERY_INVALID: "wow.query.invalid",
30
- QUERY_FAILED: "wow.query.failed",
31
- QUERY_TIMEOUT: "wow.query.timeout",
32
- QUERY_BUSY: "wow.query.busy",
33
- QUERY_NOT_FOUND: "wow.query.not-found",
34
- QUERY_DATASET_NOT_FOUND: "wow.query.dataset-not-found",
35
- QUERY_MIN_VERSION_NOT_REACHED: "wow.query.min-version-not-reached",
36
- QUERY_DATASET_UNAVAILABLE: "wow.query.dataset-unavailable",
37
- CALL_COMMAND_FORBIDDEN: "wow.call.command-forbidden"
38
- }, t = "wow.", n = "urn:wow:error:", r = /* @__PURE__ */ new Set([
1
+ import { DEFAULT_RETRY as e, FRAMEWORK_RETRIES as t, FrameworkErrorCodes as n } from "./frameworkErrors.es.js";
2
+ import { CommandResultStatus as r } from "./wire.es.js";
3
+ // src/problem.ts
4
+ var i = "wow.", a = "urn:wow:error:", o = /* @__PURE__ */ new Set([
39
5
  "type",
40
6
  "title",
41
7
  "status",
42
8
  "detail",
43
9
  "instance",
44
10
  "code",
11
+ "retry",
45
12
  "violations",
46
13
  "result",
47
14
  "extensions"
48
15
  ]);
49
- function i(e) {
16
+ function s(e) {
50
17
  if (e.extensions !== void 0) return e;
51
- let t = Object.fromEntries(Object.entries(e).filter(([e]) => !r.has(e)));
18
+ let t = Object.fromEntries(Object.entries(e).filter(([e]) => !o.has(e)));
52
19
  return Object.keys(t).length === 0 ? e : {
53
20
  ...e,
54
21
  extensions: t
55
22
  };
56
23
  }
57
- var a = /* @__PURE__ */ new Map([
58
- [e.COMMAND_UNKNOWN, !0],
59
- [e.NODE_CLOSING, !0],
60
- [e.NODE_STANDBY, !0],
61
- [e.STORAGE_UNAVAILABLE, !0],
62
- [e.SCHEDULE_NOT_DUE, !0],
63
- [e.COMMAND_BUSY, !0],
64
- [e.QUERY_BUSY, !1],
65
- [e.QUERY_MIN_VERSION_NOT_REACHED, !1],
66
- [e.COMMAND_CONTENDED, !0],
67
- [e.WAIT_TIMEOUT, !0]
68
- ]);
69
- function o(e, t, n) {
70
- let r = e === void 0 ? void 0 : a.get(e), i = r !== void 0 || e === void 0 && t === 503;
71
- return {
72
- retryable: i,
73
- sameRequestId: r ?? i,
74
- ...n === void 0 ? {} : { afterMs: n }
75
- };
24
+ function c(e) {
25
+ if (e.retry !== void 0) return e.retry;
26
+ let n = e.code === void 0 ? void 0 : t.get(e.code);
27
+ return n ? n.retry : e.code === void 0 && (e.status === 503 || e.status === 429) ? "same-request" : "none";
76
28
  }
77
- var s = class extends Error {
29
+ var l = class extends Error {
78
30
  get requestId() {
79
- return this.result?.requestId ?? c.get(this);
31
+ return this.result?.requestId ?? d.get(this);
80
32
  }
81
- constructor(e, t = {}) {
82
- 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);
33
+ constructor(e, n = {}) {
34
+ super(e.code ? `[${e.code}] ${e.detail ?? e.title}` : `${e.status} ${e.detail ?? e.title}`), this.name = "WowProblemError", this.problem = s(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 = c(e);
35
+ let r = n.retryAfterMs ?? (e.code === void 0 ? void 0 : t.get(e.code)?.retryAfterMs);
36
+ this.retry !== "none" && r !== void 0 && (this.retryAfterMs = r), n.cause !== void 0 && (this.cause = n.cause);
83
37
  }
84
38
  get isFramework() {
85
39
  return this.code?.startsWith("wow.") ?? !1;
86
40
  }
87
- }, c = /* @__PURE__ */ new WeakMap();
88
- function l(e, t) {
89
- (typeof e == "object" && e || typeof e == "function") && (c.has(e) || c.set(e, t));
41
+ }, u = class extends Error {
42
+ constructor(e, t = {}) {
43
+ let n = [e.error?.code, e.error?.message].filter(Boolean).join(" ");
44
+ if (super(`${e.ref.type.context}.${e.ref.type.name}/${e.ref.id ?? "(no id)"} rejected the command` + (n ? `: ${n}` : ".")), this.name = "CommandRejectedError", e.status !== r.REJECTED) throw TypeError(`A rejection has a rejected result, not ${e.status}.`);
45
+ this.result = e, t.problem !== void 0 && (this.problem = t.problem), t.cause !== void 0 && (this.cause = t.cause);
46
+ }
47
+ get code() {
48
+ return this.result.error?.code ?? "";
49
+ }
50
+ get requestId() {
51
+ return this.result.requestId;
52
+ }
53
+ }, d = /* @__PURE__ */ new WeakMap();
54
+ function f(e, t) {
55
+ (typeof e == "object" && e || typeof e == "function") && (d.has(e) || d.set(e, t));
90
56
  }
91
- function u(e) {
92
- return e instanceof s ? e.requestId : typeof e == "object" && e || typeof e == "function" ? c.get(e) : void 0;
57
+ function p(e) {
58
+ return e instanceof l ? e.requestId : typeof e == "object" && e || typeof e == "function" ? d.get(e) : void 0;
93
59
  }
94
- function d(e) {
60
+ function m(e) {
95
61
  return typeof e == "object" && !!e && typeof e.status == "number";
96
62
  }
97
- function f(e, t = Date.now()) {
63
+ function h(e, t = Date.now()) {
98
64
  if (!e) return;
99
65
  let n = e.trim();
100
66
  if (/^\d+$/.test(n)) return Number(n) * 1e3;
101
67
  let r = Date.parse(n);
102
68
  return Number.isNaN(r) ? void 0 : Math.max(0, r - t);
103
69
  }
104
- async function p(e) {
70
+ async function g(e) {
105
71
  let t;
106
72
  try {
107
73
  t = await e.clone().json();
108
74
  } catch {}
109
- if (d(t)) {
75
+ if (m(t)) {
110
76
  let n = t.code ?? (t.type?.startsWith("urn:wow:error:") ? t.type.slice(14) : void 0);
111
- return i({
77
+ return s({
112
78
  ...t,
113
79
  type: t.type ?? "about:blank",
114
80
  title: t.title ?? e.statusText,
@@ -121,20 +87,19 @@ async function p(e) {
121
87
  status: e.status
122
88
  };
123
89
  }
124
- async function m(e) {
125
- if (e instanceof s) return e;
90
+ async function _(e) {
91
+ if (e instanceof l) return e;
126
92
  if (typeof e != "object" || !e) return;
127
93
  let { exchange: t, cause: n } = e;
128
- if (n instanceof s) return n;
94
+ if (n instanceof l) return n;
129
95
  let r = t?.response;
130
96
  if (!r || r.ok) return;
131
- let i = await p(r), a = f(r.headers.get("Retry-After"));
132
- return new s(i, {
97
+ let i = await g(r), a = h(r.headers.get("Retry-After"));
98
+ return new l(i, {
133
99
  cause: e,
134
100
  ...a === void 0 ? {} : { retryAfterMs: a }
135
101
  });
136
102
  }
137
- //#endregion
138
- export { t as FRAMEWORK_ERROR_PREFIX, e as FrameworkErrorCodes, n as PROBLEM_TYPE_PREFIX, s as WowProblemError, d as isProblem, f as parseRetryAfter, p as readProblem, l as rememberRequestId, u as requestIdOf, o as retryHintOf, m as toWowProblemError };
103
+ export { u as CommandRejectedError, e as DEFAULT_RETRY, i as FRAMEWORK_ERROR_PREFIX, t as FRAMEWORK_RETRIES, n as FrameworkErrorCodes, a as PROBLEM_TYPE_PREFIX, l as WowProblemError, m as isProblem, h as parseRetryAfter, g as readProblem, f as rememberRequestId, p as requestIdOf, c as retryOf, _ as toWowProblemError };
139
104
 
140
105
  //# sourceMappingURL=problem.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"problem.es.js","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 /** 409: the aggregate's current state refuses the command (a check of its decide function); the message says why. */\n COMMAND_REFUSED: 'wow.command.refused',\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 /** 409: a ledger action names a parking the entry no longer is; read it again. */\n LEDGER_STALE: 'wow.ledger.stale',\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,IAAsB;CAEjC,sBAAsB;CAEtB,gBAAgB;CAEhB,qBAAqB;CAErB,mBAAmB;CAEnB,iBAAiB;CAEjB,cAAc;CAEd,mBAAmB;CAEnB,qBAAqB;CAErB,kBAAkB;CAElB,4BAA4B;CAE5B,2BAA2B;CAE3B,mBAAmB;CAEnB,mBAAmB;CAEnB,cAAc;CAEd,iBAAiB;CAEjB,gBAAgB;CAEhB,iBAAiB;CAEjB,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}
1
+ {"version":3,"file":"problem.es.js","names":["FRAMEWORK_ERROR_PREFIX","PROBLEM_TYPE_PREFIX","PROBLEM_MEMBERS","withExtensions","problem","extensions","name","retryOf","known","FRAMEWORK_RETRIES","WowProblemError","SENT_REQUEST_IDS","retryAfterMs","options","CommandRejectedError","said","result","CommandResultStatus","rememberRequestId","error","requestId","requestIdOf","isProblem","value","parseRetryAfter","trimmed","date","now","readProblem","body","response","code","toWowProblemError","cause","exchange","DEFAULT_RETRY","FrameworkErrorCodes"],"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":";;;AA8BA,IAAaA,IAAyB,QAGzBC,IAAsB,kBAkC7BC,oBAAuC,IAAI,IAAI;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAMD,SAASC,EAAe,GAA2B;CACjD,IAAIC,EAAQ,eAAe,KAAA,GAAW,OAAOA;CAC7C,IAAMC,IAAa,OAAO,YACxB,OAAO,QAAQD,CAAO,CAAC,CAAC,QAAQ,CAACE,OAAU,CAACJ,EAAgB,IAAII,CAAI,CAAC,CACvE;CACA,OAAO,OAAO,KAAKD,CAAU,CAAC,CAAC,WAAW,IACtCD,IACA;EAAE,GAAGA;EAAS;CAAW;AAC/B;AASA,SAAgBG,EAAQ,GAAyB;CAC/C,IAAIH,EAAQ,UAAU,KAAA,GAAW,OAAOA,EAAQ;CAChD,IAAMI,IACJJ,EAAQ,SAAS,KAAA,IACb,KAAA,IACAK,EAAkB,IAAIL,EAAQ,IAAI;CAExC,OADII,IAAcA,EAAM,QACjBJ,EAAQ,SAAS,KAAA,MACrBA,EAAQ,WAAW,OAAOA,EAAQ,WAAW,OAC5C,iBACA;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A,gBAA8B,IACtCA,EAAK,KAAK,MAAM,EAA0B,IAC1C,KAAA;EACN,OAAO1B,EAAe;GACpB,GAAG0B;GACH,MAAMA,EAAK,QAAQ;GACnB,OAAOA,EAAK,SAASC,EAAS;GAC9B,GAAIC,MAAS,KAAA,IAAY,CAAC,IAAI,EAAE,QAAK;EACvC,CAAC;CACH;CACA,OAAO;EACL,MAAM;EACN,OAAOD,EAAS;EAChB,QAAQA,EAAS;CACnB;AACF;AAcA,eAAsBE,EACpB,GACsC;CACtC,IAAIb,aAAiBT,GAAiB,OAAOS;CAC7C,IAAI,OAAOA,KAAU,aAAYA,GAAgB;CACjD,IAAM,EAAE,aAAU,aAAUA;CAC5B,IAAIc,aAAiBvB,GAAiB,OAAOuB;CAC7C,IAAMH,IAAWI,GAAU;CAC3B,IAAI,CAACJ,KAAYA,EAAS,IAAI;CAC9B,IAAM1B,IAAU,MAAMwB,EAAYE,CAAQ,GACpClB,IAAeY,EAAgBM,EAAS,QAAQ,IAAI,aAAa,CAAC;CACxE,OAAO,IAAIpB,EAAgBN,GAAS;EAClC,OAAOe;EACP,GAAIP,MAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAa;CACvD,CAAC;AACH"}
package/dist/queries.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./exactJson.cjs"),t=require("./http.cjs"),n=require("./streams.cjs");var r=class{constructor(e,t={},n){this.path=e,this.client=t,this.numbers=n}get listNumbers(){return this.numbers===void 0?void 0:{"*":this.numbers}}get pageNumbers(){return this.numbers===void 0?void 0:{list:{"*":this.numbers}}}async list(e,n){return t.json(await this.post(`list`,e,n),this.listNumbers)}async listStream(e,t){return(await this.listStreamRows(e,t)).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e.record)}}))}async listStreamRows(e,t={}){let r=t.resume===!1?{maxRetries:0}:t.resume,i=e.limit??0,a=(n,r)=>this.post(`list`,i>0?{...e,limit:i-r}:e,t,`text/event-stream`,n),o=await a(r?.lastEventId,0);return n.resumableQueryRows(o,(e,t)=>i>0&&t>=i?Promise.resolve(void 0):a(e,t),{...r,...t.signal===void 0?{}:{signal:t.signal},...this.numbers===void 0?{}:{numbers:this.numbers}})}async paged(e,n){return t.json(await this.post(`paged`,e,n),this.pageNumbers)}async cursor(e,n){return t.json(await this.post(`cursor`,e,n),this.pageNumbers)}async single(e,n){return t.json(await this.post(`single`,e,n),this.numbers)}async count(e,n){return t.json(await this.post(`count`,e,n))}async aggregate(e,n){return t.json(await this.post(`aggregate`,e,n))}async describe(e,n){let r=await t.send(this.client,{method:`GET`,path:this.path,headers:{[t.WowHeaders.IF_NONE_MATCH]:e===void 0?void 0:`"${e}"`},options:n,notModified:!0}),i=t.entityTag(r);return r.status===304?{notModified:!0,version:i??e??``}:{notModified:!1,...i===void 0?{}:{version:i},descriptor:await t.json(r)}}post(e,n,r,i,a){return t.send(this.client,{method:`POST`,path:this.path,headers:{Accept:i,[t.WowHeaders.LAST_EVENT_ID]:a},body:{...n,kind:e},options:r})}};function i(e,t){return`/${e.context}/${e.name}/${t}/query`}var a=class extends r{constructor(e,t){super(i(e,`snapshot`),t,e.textNumbers?.state===void 0?void 0:{state:e.textNumbers.state}),this.type=e}},o=class extends r{constructor(t,n){let r=e.eventNumbers(t);super(i(t,`events`),n,r===void 0?void 0:{events:{"*":r}}),this.type=t}},s=class{constructor(e={}){this.client=e}async list(e){return t.json(await t.send(this.client,{method:`GET`,path:`/wow/dataset`,options:e}))}dataset(e,t){return new r(`/wow/dataset/${encodeURIComponent(e)}/${encodeURIComponent(t)}/query`,this.client)}};exports.DatasetClient=s,exports.EventQueryClient=o,exports.QueryModelClient=r,exports.SnapshotQueryClient=a,exports.queryPath=i;
1
+ const e=require("./exactJson.cjs"),t=require("./frameworkErrors.cjs"),n=require("./problem.cjs"),r=require("./http.cjs"),i=require("./streams.cjs");var a=class{constructor(e,t={},n){this.path=e,this.client=t,this.numbers=n}get listNumbers(){return this.numbers===void 0?void 0:{"*":this.numbers}}get pageNumbers(){return this.numbers===void 0?void 0:{list:{"*":this.numbers}}}async list(e,t){return r.json(await this.post(`list`,e,t),this.listNumbers)}async stream(e,t){return(await this.streamRows(e,t)).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e.row)}}))}async streamRows(e,t={}){let n=t.resume===!1?{maxRetries:0}:t.resume,r=e.limit,a=(n,i)=>this.post(`list`,r===void 0?e:{...e,limit:r-i},t,`text/event-stream`,n),o=await a(n?.lastEventId,0);return i.resumableQueryRows(o,(e,t)=>r!==void 0&&t>=r?Promise.resolve(void 0):a(e,t),{...n,...t.signal===void 0?{}:{signal:t.signal},...this.numbers===void 0?{}:{numbers:this.numbers}})}async paged(e,t){return r.json(await this.post(`paged`,e,t),this.pageNumbers)}async cursor(e,t){return r.json(await this.post(`cursor`,e,t),this.pageNumbers)}async single(e,t){try{return r.json(await this.post(`single`,e,t),this.numbers)}catch(e){if(o(e))return;throw e}}async count(e,t){return r.json(await this.post(`count`,e,t))}async aggregate(e,t){return r.json(await this.post(`aggregate`,e,t))}async describe(e,t){let n=await r.send(this.client,{method:`GET`,path:this.path,headers:{[r.WowHeaders.IF_NONE_MATCH]:e===void 0?void 0:`"${e}"`},options:t,notModified:!0}),i=r.entityTag(n);return n.status===304?{notModified:!0,version:i??e??``}:{notModified:!1,...i===void 0?{}:{version:i},descriptor:await r.json(n)}}post(e,t,n,i,a){return r.send(this.client,{method:`POST`,path:this.path,headers:{Accept:i,[r.WowHeaders.LAST_EVENT_ID]:a},body:{...t,kind:e},options:n})}};function o(e){return e instanceof n.WowProblemError&&e.status===404&&(e.code===t.FrameworkErrorCodes.QUERY_NOT_FOUND||e.code===t.FrameworkErrorCodes.AGGREGATE_NOT_FOUND)}function s(e,t){return`/${e.context}/${e.name}/${t}/query`}var c=class extends a{constructor(e,t){super(s(e,`snapshot`),t,e.textNumbers?.state===void 0?void 0:{state:e.textNumbers.state}),this.type=e}},l=class extends a{constructor(t,n){let r=e.eventNumbers(t);super(s(t,`events`),n,r===void 0?void 0:{events:{"*":r}}),this.type=t}},u=class{constructor(e={}){this.client=e}async list(e){return r.json(await r.send(this.client,{method:`GET`,path:`/wow/dataset`,options:e}))}dataset(e,t){return new a(`/wow/dataset/${encodeURIComponent(e)}/${encodeURIComponent(t)}/query`,this.client)}};exports.DatasetClient=u,exports.EventQueryClient=l,exports.QueryModelClient=a,exports.SnapshotQueryClient=c,exports.queryPath=s;
2
2
  //# sourceMappingURL=queries.cjs.map