@ahoo-wang/wow-client 10.0.0-beta.1 → 10.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/README.zh-CN.md +1 -1
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +1 -8
- package/dist/commands.d.ts +1 -8
- package/dist/commands.es.js +45 -51
- package/dist/commands.es.js.map +1 -1
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +73 -69
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/aliases.cjs +2 -0
- package/dist/dsl/aggregation/aliases.cjs.map +1 -0
- package/dist/dsl/aggregation/aliases.d.cts +2 -0
- package/dist/dsl/aggregation/aliases.d.ts +2 -0
- package/dist/dsl/aggregation/aliases.es.js +13 -0
- package/dist/dsl/aggregation/aliases.es.js.map +1 -0
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +17 -243
- package/dist/dsl/aggregation/builders.d.ts +17 -243
- package/dist/dsl/aggregation/builders.es.js +36 -171
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +123 -1
- package/dist/dsl/aggregation/derived.d.ts +123 -1
- package/dist/dsl/aggregation/derived.es.js +43 -28
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/groups.cjs +2 -0
- package/dist/dsl/aggregation/groups.cjs.map +1 -0
- package/dist/dsl/aggregation/groups.d.cts +325 -0
- package/dist/dsl/aggregation/groups.d.ts +325 -0
- package/dist/dsl/aggregation/groups.es.js +80 -0
- package/dist/dsl/aggregation/groups.es.js.map +1 -0
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +63 -1
- package/dist/dsl/aggregation/having.d.ts +63 -1
- package/dist/dsl/aggregation/having.es.js +33 -30
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/index.d.cts +4 -2
- package/dist/dsl/aggregation/index.d.ts +4 -2
- package/dist/dsl/aggregation/metrics.cjs +2 -0
- package/dist/dsl/aggregation/metrics.cjs.map +1 -0
- package/dist/dsl/aggregation/metrics.d.cts +279 -0
- package/dist/dsl/aggregation/metrics.d.ts +279 -0
- package/dist/dsl/aggregation/metrics.es.js +75 -0
- package/dist/dsl/aggregation/metrics.es.js.map +1 -0
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +4 -524
- package/dist/dsl/aggregation/types.d.ts +4 -524
- package/dist/dsl/aggregation/types.es.js +5 -25
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/cursorQuery.cjs +1 -1
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.d.cts +18 -7
- package/dist/dsl/cursorQuery.d.ts +18 -7
- package/dist/dsl/cursorQuery.es.js +13 -12
- package/dist/dsl/cursorQuery.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +17 -379
- package/dist/dsl/descriptor.d.ts +17 -379
- package/dist/dsl/descriptor.es.js +4 -31
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/fieldDescriptor.cjs +2 -0
- package/dist/dsl/fieldDescriptor.cjs.map +1 -0
- package/dist/dsl/fieldDescriptor.d.cts +246 -0
- package/dist/dsl/fieldDescriptor.d.ts +246 -0
- package/dist/dsl/fieldDescriptor.es.js +24 -0
- package/dist/dsl/fieldDescriptor.es.js.map +1 -0
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +7 -949
- package/dist/dsl/filter/builders.d.ts +7 -949
- package/dist/dsl/filter/builders.es.js +14 -285
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/expressionFilter.cjs +2 -0
- package/dist/dsl/filter/expressionFilter.cjs.map +1 -0
- package/dist/dsl/filter/expressionFilter.d.cts +35 -0
- package/dist/dsl/filter/expressionFilter.d.ts +35 -0
- package/dist/dsl/filter/expressionFilter.es.js +18 -0
- package/dist/dsl/filter/expressionFilter.es.js.map +1 -0
- package/dist/dsl/filter/fieldFilters.cjs +2 -0
- package/dist/dsl/filter/fieldFilters.cjs.map +1 -0
- package/dist/dsl/filter/fieldFilters.d.cts +297 -0
- package/dist/dsl/filter/fieldFilters.d.ts +297 -0
- package/dist/dsl/filter/fieldFilters.es.js +110 -0
- package/dist/dsl/filter/fieldFilters.es.js.map +1 -0
- package/dist/dsl/filter/index.d.cts +2 -1
- package/dist/dsl/filter/index.d.ts +2 -1
- package/dist/dsl/filter/logicalFilters.cjs +2 -0
- package/dist/dsl/filter/logicalFilters.cjs.map +1 -0
- package/dist/dsl/filter/logicalFilters.d.cts +109 -0
- package/dist/dsl/filter/logicalFilters.d.ts +109 -0
- package/dist/dsl/filter/logicalFilters.es.js +36 -0
- package/dist/dsl/filter/logicalFilters.es.js.map +1 -0
- package/dist/dsl/filter/metadataFilters.cjs +2 -0
- package/dist/dsl/filter/metadataFilters.cjs.map +1 -0
- package/dist/dsl/filter/metadataFilters.d.cts +132 -0
- package/dist/dsl/filter/metadataFilters.d.ts +132 -0
- package/dist/dsl/filter/metadataFilters.es.js +56 -0
- package/dist/dsl/filter/metadataFilters.es.js.map +1 -0
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +11 -9
- package/dist/dsl/filter/operator.d.ts +11 -9
- package/dist/dsl/filter/operator.es.js +1 -1
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/searchFilter.cjs +2 -0
- package/dist/dsl/filter/searchFilter.cjs.map +1 -0
- package/dist/dsl/filter/searchFilter.d.cts +39 -0
- package/dist/dsl/filter/searchFilter.d.ts +39 -0
- package/dist/dsl/filter/searchFilter.es.js +19 -0
- package/dist/dsl/filter/searchFilter.es.js.map +1 -0
- package/dist/dsl/filter/timeFilters.cjs +2 -0
- package/dist/dsl/filter/timeFilters.cjs.map +1 -0
- package/dist/dsl/filter/timeFilters.d.cts +290 -0
- package/dist/dsl/filter/timeFilters.d.ts +290 -0
- package/dist/dsl/filter/timeFilters.es.js +89 -0
- package/dist/dsl/filter/timeFilters.es.js.map +1 -0
- package/dist/dsl/filter/types.d.cts +4 -14
- package/dist/dsl/filter/types.d.ts +4 -14
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.d.cts +2 -4
- package/dist/dsl/filter/validate.d.ts +2 -4
- package/dist/dsl/filter/validate.es.js +25 -31
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/queryErrorCodes.cjs +1 -1
- package/dist/dsl/queryErrorCodes.cjs.map +1 -1
- package/dist/dsl/queryErrorCodes.d.cts +0 -2
- package/dist/dsl/queryErrorCodes.d.ts +0 -2
- package/dist/dsl/queryErrorCodes.es.js +0 -1
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryFilter.cjs +2 -0
- package/dist/dsl/queryFilter.cjs.map +1 -0
- package/dist/dsl/queryFilter.d.cts +3 -0
- package/dist/dsl/queryFilter.d.ts +3 -0
- package/dist/dsl/queryFilter.es.js +9 -0
- package/dist/dsl/queryFilter.es.js.map +1 -0
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.es.js +12 -16
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/semanticTypes.cjs +2 -0
- package/dist/dsl/semanticTypes.cjs.map +1 -0
- package/dist/dsl/semanticTypes.d.cts +128 -0
- package/dist/dsl/semanticTypes.d.ts +128 -0
- package/dist/dsl/semanticTypes.es.js +13 -0
- package/dist/dsl/semanticTypes.es.js.map +1 -0
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.d.cts +2 -0
- package/dist/dsl.d.ts +2 -0
- package/dist/dsl.es.js +14 -8
- package/dist/exactJson.cjs +2 -2
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +41 -16
- package/dist/exactJson.d.ts +41 -16
- package/dist/exactJson.es.js +104 -102
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs.map +1 -1
- package/dist/frameworkErrors.d.cts +4 -4
- package/dist/frameworkErrors.d.ts +4 -4
- package/dist/frameworkErrors.es.js.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +29 -9
- package/dist/http.d.ts +29 -9
- package/dist/http.es.js +24 -19
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.es.js +12 -12
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +24 -0
- package/dist/manifest.d.ts +24 -0
- package/dist/manifest.es.js +34 -6
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +16 -1
- package/dist/manifestTypes.d.ts +16 -1
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +18 -8
- package/dist/queries.d.ts +18 -8
- package/dist/queries.es.js +46 -35
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +1 -1
- package/dist/routes.cjs.map +1 -1
- package/dist/routes.d.cts +16 -3
- package/dist/routes.d.ts +16 -3
- package/dist/routes.es.js +24 -25
- package/dist/routes.es.js.map +1 -1
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +21 -19
- package/dist/state.d.ts +21 -19
- package/dist/state.es.js +27 -22
- package/dist/state.es.js.map +1 -1
- package/dist/streams.cjs +1 -1
- package/dist/streams.cjs.map +1 -1
- package/dist/streams.d.cts +14 -7
- package/dist/streams.d.ts +14 -7
- package/dist/streams.es.js +65 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +1 -1
- package/dist/testing/wire.cjs.map +1 -1
- package/dist/testing/wire.es.js +1 -1
- package/dist/testing/wire.es.js.map +1 -1
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +17 -4
- package/dist/wait.d.ts +17 -4
- package/dist/wait.es.js +36 -34
- package/dist/wait.es.js.map +1 -1
- package/dist/wire.cjs +1 -1
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +75 -31
- package/dist/wire.d.ts +75 -31
- package/dist/wire.es.js +1 -3
- package/dist/wire.es.js.map +1 -1
- package/package.json +5 -5
- package/dist/dsl/filter/datePattern.cjs +0 -2
- package/dist/dsl/filter/datePattern.cjs.map +0 -1
- package/dist/dsl/filter/datePattern.d.cts +0 -8
- package/dist/dsl/filter/datePattern.d.ts +0 -8
- package/dist/dsl/filter/datePattern.es.js +0 -96
- package/dist/dsl/filter/datePattern.es.js.map +0 -1
package/dist/streams.es.js
CHANGED
|
@@ -1,13 +1,33 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { DEFAULT_RETRY as
|
|
3
|
-
import { WowProblemError as
|
|
4
|
-
import {
|
|
1
|
+
import { parseJson as e } from "./exactJson.es.js";
|
|
2
|
+
import { DEFAULT_RETRY as t } from "./frameworkErrors.es.js";
|
|
3
|
+
import { WowProblemError as n, isProblem as r, rememberRequestId as i } from "./problem.es.js";
|
|
4
|
+
import { toServerSentEventStream as a } from "@ahoo-wang/fetcher-eventstream";
|
|
5
5
|
// src/streams.ts
|
|
6
|
-
var
|
|
7
|
-
function
|
|
8
|
-
return a(
|
|
9
|
-
|
|
10
|
-
|
|
6
|
+
var o = "row", s = "error", c = "end", l = "message";
|
|
7
|
+
function u(t, n) {
|
|
8
|
+
return a(t.response).pipeThrough(new TransformStream({ transform(r, i) {
|
|
9
|
+
i.enqueue({
|
|
10
|
+
...r,
|
|
11
|
+
data: e(r.data, n(r.event) ? t.numbers : void 0)
|
|
12
|
+
});
|
|
13
|
+
} })).getReader();
|
|
14
|
+
}
|
|
15
|
+
function d(e, t) {
|
|
16
|
+
let n = u(e, () => !0);
|
|
17
|
+
return new ReadableStream({
|
|
18
|
+
async pull(e) {
|
|
19
|
+
let r;
|
|
20
|
+
try {
|
|
21
|
+
r = await n.read();
|
|
22
|
+
} catch (e) {
|
|
23
|
+
throw i(e, t), e;
|
|
24
|
+
}
|
|
25
|
+
r.done ? e.close() : e.enqueue(r.value.data);
|
|
26
|
+
},
|
|
27
|
+
cancel(e) {
|
|
28
|
+
return n.cancel(e);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
11
31
|
}
|
|
12
32
|
var f = "hold-expired", p = "complete";
|
|
13
33
|
function m(e, t) {
|
|
@@ -21,80 +41,75 @@ function m(e, t) {
|
|
|
21
41
|
});
|
|
22
42
|
}
|
|
23
43
|
function h(e) {
|
|
24
|
-
return new r(
|
|
44
|
+
return new n(r(e) ? e : {
|
|
25
45
|
type: "about:blank",
|
|
26
46
|
title: "Query failed",
|
|
27
47
|
status: 500
|
|
28
48
|
});
|
|
29
49
|
}
|
|
30
|
-
function g(
|
|
31
|
-
let { maxRetries:
|
|
32
|
-
|
|
33
|
-
n.enqueue({
|
|
34
|
-
...e,
|
|
35
|
-
data: t(e.data, r ? x : void 0)
|
|
36
|
-
});
|
|
37
|
-
} }))).getReader(), C = S(i), w = g.lastEventId, T = 0, E = 0, D = !1;
|
|
38
|
-
async function O(e, t) {
|
|
50
|
+
function g(e, r, i = {}) {
|
|
51
|
+
let { maxRetries: a = t.attempts - 1, initialDelayMs: d = t.backoffMs, maxDelayMs: g = t.maxWaitMs, signal: _ } = i, v = (e) => u(e, (e) => e === o || e === l), y = v(e), b = i.lastEventId, x = 0, S = 0, C = new AbortController(), w = _ === void 0 ? C.signal : AbortSignal.any([_, C.signal]);
|
|
52
|
+
async function T(e, t) {
|
|
39
53
|
for (;;) {
|
|
40
|
-
if (
|
|
41
|
-
if (
|
|
42
|
-
let
|
|
43
|
-
|
|
54
|
+
if (w.aborted) throw w.reason;
|
|
55
|
+
if (S++ >= a) throw e;
|
|
56
|
+
let i = t ?? Math.min(g, d * 2 ** (S - 1));
|
|
57
|
+
i > 0 && await m(i, w);
|
|
44
58
|
try {
|
|
45
|
-
let e = await
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
59
|
+
let e = await r(b, x, w);
|
|
60
|
+
if (w.aborted) throw await e?.response.body?.cancel(w.reason), w.reason;
|
|
61
|
+
return e && (y = v(e)), e !== void 0;
|
|
62
|
+
} catch (r) {
|
|
63
|
+
if (w.aborted || r instanceof n && r.retry === "none") throw r;
|
|
64
|
+
t = r.retryAfterMs, e = r;
|
|
50
65
|
}
|
|
51
66
|
}
|
|
52
67
|
}
|
|
53
68
|
return new ReadableStream({
|
|
54
69
|
async pull(e) {
|
|
55
70
|
for (;;) {
|
|
56
|
-
let t,
|
|
71
|
+
let t, r;
|
|
57
72
|
try {
|
|
58
|
-
let
|
|
59
|
-
if (
|
|
73
|
+
let n = await y.read();
|
|
74
|
+
if (n.done) t = /* @__PURE__ */ TypeError("The query stream was cut off.");
|
|
60
75
|
else {
|
|
61
|
-
let { event: i, id: a, data:
|
|
62
|
-
if (i ===
|
|
63
|
-
a && (
|
|
64
|
-
row:
|
|
76
|
+
let { event: i, id: a, data: u } = n.value;
|
|
77
|
+
if (i === o || i === l) {
|
|
78
|
+
a && (b = a), x++, S = 0, e.enqueue(a ? {
|
|
79
|
+
row: u,
|
|
65
80
|
position: a
|
|
66
|
-
} : { row:
|
|
81
|
+
} : { row: u });
|
|
67
82
|
return;
|
|
68
83
|
}
|
|
69
|
-
if (i ===
|
|
70
|
-
let
|
|
71
|
-
if (
|
|
84
|
+
if (i === c) {
|
|
85
|
+
let n = u;
|
|
86
|
+
if (n.reason === p) {
|
|
72
87
|
e.close();
|
|
73
88
|
return;
|
|
74
89
|
}
|
|
75
|
-
if (t = /* @__PURE__ */ TypeError(`The query stream ended: ${
|
|
76
|
-
|
|
77
|
-
} else if (i ===
|
|
78
|
-
let e = h(
|
|
90
|
+
if (t = /* @__PURE__ */ TypeError(`The query stream ended: ${n.reason}.`), !n.resumable) throw t;
|
|
91
|
+
n.reason === f && (r = 0);
|
|
92
|
+
} else if (i === s) {
|
|
93
|
+
let e = h(u);
|
|
79
94
|
if (e.retry === "none") throw e;
|
|
80
|
-
t = e,
|
|
95
|
+
t = e, r = e.retryAfterMs;
|
|
81
96
|
} else continue;
|
|
82
97
|
}
|
|
83
98
|
} catch (e) {
|
|
84
|
-
if (e === t || e instanceof
|
|
99
|
+
if (e === t || e instanceof n) throw e;
|
|
85
100
|
t = e;
|
|
86
101
|
}
|
|
87
|
-
if (
|
|
88
|
-
if (
|
|
89
|
-
if (
|
|
90
|
-
if (!await
|
|
102
|
+
if (C.signal.aborted) return;
|
|
103
|
+
if (_?.aborted) throw _.reason;
|
|
104
|
+
if (b === void 0 && x > 0) throw t;
|
|
105
|
+
if (!await T(t, r)) {
|
|
91
106
|
e.close();
|
|
92
107
|
return;
|
|
93
108
|
}
|
|
94
109
|
}
|
|
95
110
|
},
|
|
96
111
|
cancel(e) {
|
|
97
|
-
return
|
|
112
|
+
return C.abort(e), y.cancel(e);
|
|
98
113
|
}
|
|
99
114
|
});
|
|
100
115
|
}
|
package/dist/streams.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.es.js","names":["ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","toJsonServerSentEventStream","toServerSentEventStream","response","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","WowProblemError","isProblem","data","resumableQueryRows","DEFAULT_RETRY","options","numbers","events","marksNothing","from","row","parseJson","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","controller","end","reason"],"sources":["../src/streams.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 {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;AAyBA,IAAMA,IAAY,OAGZC,IAAc,SAGdC,IAAY,OAGZC,IAAgB;AAYtB,SAAgBC,EAAkB,GAA4C;CAC5E,OAAOC,EACLC,EAAwBC,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,EACA,UAAU,GAAO,GAAY;EAC3B,EAAW,QAAQC,EAAM,IAAI;CAC/B,EACF,CAAC,CACH;AACF;AAyDA,IAAMC,IAAgC,gBAChCC,IAA4B;AAGlC,SAASC,EAAM,GAAY,GAAqC;CAC9D,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,UAAc;GAElB,AADA,aAAaC,CAAK,GAClBC,EAAOC,GAAQ,MAAM;EACvB,GACMF,IAAQ,iBAAiB;GAE7B,AADAE,GAAQ,oBAAoB,SAASH,CAAK,GAC1CI,EAAQ;EACV,GAAGC,CAAE;EACL,GAAQ,iBAAiB,SAASL,CAAK;CACzC,CAAC;AACH;AAEA,SAASM,EAAU,GAAgC;CACjD,OAAO,IAAIC,EACTC,EAAUC,CAAI,IACVA,IACA;EAAE,MAAM;EAAe,OAAO;EAAgB,QAAQ;CAAI,CAChE;AACF;AAeA,SAAgBC,EACd,GACA,GAIA,IAII,CAAC,GAC0B;CAC/B,IAAM,EACJ,gBAAaC,EAAc,WAAW,GACtC,oBAAiBA,EAAc,WAC/B,gBAAaA,EAAc,WAC3B,cACEC,GACEC,IAAUD,EAAQ,SAClBE,KAAU,OACbC,EAAaF,CAAO,IACjBpB,EAAqCC,EAAwBsB,CAAI,CAAC,IAClEtB,EAAwBsB,CAAI,CAAC,CAAC,YAC5B,IAAI,gBAA+D,EACjE,UAAU,GAAO,GAAY;EAC3B,IAAMC,IACJrB,EAAM,UAAUR,KAAaQ,EAAM,UAAUL;EAC/C,EAAW,QAAQ;GACjB,GAAGK;GACH,MAAM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;OACF;OAEA,IADA,IAAO,gBAAI,UAAU,2BAA2BuC,EAAI,OAAO,EAAE,GACzD,CAACA,EAAI,WAAW,MAAMH;OAC1B,AAAIG,EAAI,WAAWxC,MAAc,IAAU;MAC7C,OAAO,IAAID,MAAUP,GAAa;OAChC,IAAM4C,IAAQ3B,EAAUG,CAAI;OAC5B,IAAIwB,EAAM,UAAU,QAAQ,MAAMA;OAElC,AADA,IAAOA,GACP,IAAUA,EAAM;MAClB,OACE;KAEJ;IACF,SAASA,GAAO;KACd,IAAIA,MAAUC,KAAQD,aAAiB1B,GAAiB,MAAM0B;KAC9D,IAAOA;IACT;IACA,IAAIV,GAAW;IAEf,IAAIpB,GAAQ,SAAS,MAAMA,EAAO;IAClC,IAAIiB,MAAgB,KAAA,KAAaC,IAAW,GAAG,MAAMa;IACrD,IAAI,CAAE,MAAMV,EAAOU,GAAMN,CAAO,GAAI;KAClC,EAAW,MAAM;KACjB;IACF;GACF;EACF;EACA,OAAO,GAAQ;GAEb,OADA,IAAY,IACLT,EAAO,OAAOmB,CAAM;EAC7B;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"streams.es.js","names":["ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","eventsOf","toServerSentEventStream","answer","event","parseJson","marked","commandResults","reader","next","error","rememberRequestId","requestId","controller","reason","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","WowProblemError","isProblem","data","resumableQueryRows","DEFAULT_RETRY","options","events","from","lastEventId","received","failures","cancelling","halted","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","reopen","stop","id","end"],"sources":["../src/streams.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 {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { parseJson } from './exactJson.js';\nimport type { Answer } from './http.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, rememberRequestId, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/**\n * The events of `answer`'s server-sent event stream, each event's data read\n * as JSON: with the answer's exact numbers for an event `marked` names.\n */\nfunction eventsOf(\n answer: Answer,\n marked: (event: string | undefined) => boolean,\n): ReadableStreamDefaultReader<JsonServerSentEvent<unknown>> {\n return toServerSentEventStream(answer.response)\n .pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n controller.enqueue({\n ...event,\n data: parseJson(\n event.data,\n marked(event.event) ? answer.numbers : undefined,\n ),\n });\n },\n }),\n )\n .getReader();\n}\n\n/**\n * The data of each event of `answer`'s server-sent event stream, the\n * results of the command sent with `requestId`. A read that fails, such as a\n * connection lost after the response began, fails with an error that carries\n * `requestId` (`requestIdOf`): the command may have been committed, and\n * a retry with the same id is answered as its duplicate.\n */\nexport function commandResults<R>(\n answer: Answer,\n requestId: string,\n): CommandResultStream<R> {\n const reader = eventsOf(answer, () => true);\n return new ReadableStream<CommandResult<R>>({\n async pull(controller) {\n let next: ReadableStreamReadResult<JsonServerSentEvent<unknown>>;\n try {\n next = await reader.read();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n if (next.done) controller.close();\n else controller.enqueue(next.value.data as CommandResult<R>);\n },\n cancel(reason) {\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream. The signal `reopen` is given aborts once `signal` does or\n * the stream's reader cancels it: a cancel during a wait to resume, or while\n * the stream is asked for again, sends nothing more and leaves no response\n * open.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n answer: Answer,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n signal: AbortSignal,\n ) => Promise<Answer | undefined>,\n options: StreamResumeOptions & { readonly signal?: AbortSignal } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n // A record's exact numbers are its answer's (review R4-Q, Q-9).\n const events = (from: Answer) =>\n eventsOf(from, event => event === ROW_EVENT || event === UNNAMED_EVENT);\n let reader = events(answer);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Aborted once the reader cancels: a read in flight then ends, and must not\n // be taken for a cut-off stream to ask for again. `halted` aborts with it or\n // with `signal`, and a wait to resume, or a request to, ends with `halted`\n // (`AbortSignal.any`: Node 20.3, Chrome 116, Firefox 124, Safari 17.4, all\n // within the runtimes the compatibility page states).\n const cancelling = new AbortController();\n const halted =\n signal === undefined\n ? cancelling.signal\n : AbortSignal.any([signal, cancelling.signal]);\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (halted.aborted) throw halted.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, halted);\n try {\n const next = await reopen(lastEventId, received, halted);\n if (halted.aborted) {\n // Answered as it was cancelled: nothing reads this response.\n await next?.response.body?.cancel(halted.reason);\n throw halted.reason;\n }\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n halted.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelling.signal.aborted) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelling.abort(reason);\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;;AAyBA,IAAMA,IAAY,OAGZC,IAAc,SAGdC,IAAY,OAGZC,IAAgB;AAetB,SAASC,EACP,GACA,GAC2D;CAC3D,OAAOC,EAAwBC,EAAO,QAAQ,CAAC,CAC5C,YACC,IAAI,gBAA+D,EACjE,UAAU,GAAO,GAAY;EAC3B,EAAW,QAAQ;GACjB,GAAGC;GACH,MAAMC,EACJD,EAAM,MACNE,EAAOF,EAAM,KAAK,IAAID,EAAO,UAAU,KAAA,CACzC;EACF,CAAC;CACH,EACF,CAAC,CACH,CAAC,CACA,UAAU;AACf;AASA,SAAgBI,EACd,GACA,GACwB;CACxB,IAAMC,IAASP,EAASE,SAAc,EAAI;CAC1C,OAAO,IAAI,eAAiC;EAC1C,MAAM,KAAK,GAAY;GACrB,IAAIM;GACJ,IAAI;IACF,IAAO,MAAMD,EAAO,KAAK;GAC3B,SAASE,GAAO;IAEd,MADAC,EAAkBD,GAAOE,CAAS,GAC5BF;GACR;GACA,AAAID,EAAK,OAAMI,EAAW,MAAM,IAC3BA,EAAW,QAAQJ,EAAK,MAAM,IAAwB;EAC7D;EACA,OAAO,GAAQ;GACb,OAAOD,EAAO,OAAOM,CAAM;EAC7B;CACF,CAAC;AACH;AAyDA,IAAMC,IAAgC,gBAChCC,IAA4B;AAGlC,SAASC,EAAM,GAAY,GAAqC;CAC9D,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,UAAc;GAElB,AADA,aAAaC,CAAK,GAClBC,EAAOC,G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;GAEb,OADAN,EAAW,MAAMtB,CAAM,GAChBN,EAAO,OAAOM,CAAM;EAC7B;CACF,CAAC;AACH"}
|
package/dist/testing/wire.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../frameworkErrors.cjs"),t=require("../wire.cjs");function n(n,r={}){let{context:i,name:a}=n.type,o=r.status??t.CommandResultStatus.SUCCEEDED,s=r.commandId??`command-1`;return{format:1,commandId:s,requestId:`request-1`,correlationId:s,ref:n,hop:{stage:t.Stage.COMMITTED,context:i},function:{kind:t.FunctionKind.COMMAND,context:i,processor:a,name:`Command`},status:o,version:1,duplicate:!1,error:o===t.CommandResultStatus.SUCCEEDED?null:{code:o===t.CommandResultStatus.REJECTED?e.FrameworkErrorCodes.COMMAND_REFUSED:e.FrameworkErrorCodes.COMMAND_FAILED,message:`The command was ${o.toLowerCase()}.`},results:{},derived:[],signalTime:0,...r}}var r={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,409:`Conflict`,410:`Gone`,412:`Precondition Failed`,429:`Too Many Requests`,500:`Internal Server Error`,503:`Service Unavailable`,504:`Gateway Timeout`};function i(e,t,n={}){return{type:t===void 0?`about:blank`:`urn:wow:error:${t}`,title:r[e]??`HTTP ${e}`,status:e,...t===void 0?{}:{code:t},...n}}function a(e,t={}){let{extensions:n,...r}=e,i=new Headers(t.headers);return i.set(`Content-Type`,`application/problem+json`),new Response(JSON.stringify({...n,...r}),{...t,status:e.status,headers:i})}function o(e,t,n={}){return{tenantId:e.tenantId,aggregateId:e.id,version:1,ownerId:null,spaceId:null,deleted:!1,
|
|
1
|
+
const e=require("../frameworkErrors.cjs"),t=require("../wire.cjs");function n(n,r={}){let{context:i,name:a}=n.type,o=r.status??t.CommandResultStatus.SUCCEEDED,s=r.commandId??`command-1`;return{format:1,commandId:s,requestId:`request-1`,correlationId:s,ref:n,hop:{stage:t.Stage.COMMITTED,context:i},function:{kind:t.FunctionKind.COMMAND,context:i,processor:a,name:`Command`},status:o,version:1,duplicate:!1,error:o===t.CommandResultStatus.SUCCEEDED?null:{code:o===t.CommandResultStatus.REJECTED?e.FrameworkErrorCodes.COMMAND_REFUSED:e.FrameworkErrorCodes.COMMAND_FAILED,message:`The command was ${o.toLowerCase()}.`},results:{},derived:[],signalTime:0,...r}}var r={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,409:`Conflict`,410:`Gone`,412:`Precondition Failed`,429:`Too Many Requests`,500:`Internal Server Error`,503:`Service Unavailable`,504:`Gateway Timeout`};function i(e,t,n={}){return{type:t===void 0?`about:blank`:`urn:wow:error:${t}`,title:r[e]??`HTTP ${e}`,status:e,...t===void 0?{}:{code:t},...n}}function a(e,t={}){let{extensions:n,...r}=e,i=new Headers(t.headers);return i.set(`Content-Type`,`application/problem+json`),new Response(JSON.stringify({...n,...r}),{...t,status:e.status,headers:i})}function o(e,t,n={}){return{tenantId:e.tenantId,aggregateId:e.id,version:1,ownerId:null,spaceId:null,deleted:!1,access:{},firstEventTime:0,lastEventTime:0,operator:null,firstOperator:null,schedules:{},state:t,...n}}exports.commandResultOf=n,exports.problemOf=i,exports.problemResponse=a,exports.snapshotOf=o;
|
|
2
2
|
//# sourceMappingURL=wire.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wire.cjs","names":["CommandResultStatus","Stage","FunctionKind","FrameworkErrorCodes","require_frameworkErrors","require_wire","commandResultOf","ref","status","overrides","commandId","name","TITLES","problemOf","code","problemResponse","members","problem","headers","init","extensions","snapshotOf"],"sources":["../../src/testing/wire.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 { FrameworkErrorCodes, type Problem } from '../problem.js';\nimport {\n type AggregateRef,\n type CommandResult,\n CommandResultStatus,\n FunctionKind,\n Stage,\n type Snapshot,\n} from '../wire.js';\n\n/**\n * A command's result as a service answers it, for a test's fake: the command\n * `ref` names, committed (`succeeded` at `committed`, version 1) unless\n * `overrides` says otherwise. A `rejected` or `failed` one without an `error`\n * carries `wow.command.refused` or `wow.command.failed`.\n */\nexport function commandResultOf<R = Record<string, unknown>>(\n ref: AggregateRef,\n overrides: Partial<CommandResult<R>> = {},\n): CommandResult<R> {\n const { context, name } = ref.type;\n const status = overrides.status ?? CommandResultStatus.SUCCEEDED;\n const commandId = overrides.commandId ?? 'command-1';\n return {\n format: 1,\n commandId,\n requestId: 'request-1',\n correlationId: commandId,\n ref,\n hop: { stage: Stage.COMMITTED, context },\n function: {\n kind: FunctionKind.COMMAND,\n context,\n processor: name,\n name: 'Command',\n },\n status,\n version: 1,\n duplicate: false,\n error:\n status === CommandResultStatus.SUCCEEDED\n ? null\n : {\n code:\n status === CommandResultStatus.REJECTED\n ? FrameworkErrorCodes.COMMAND_REFUSED\n : FrameworkErrorCodes.COMMAND_FAILED,\n message: `The command was ${status.toLowerCase()}.`,\n },\n results: {} as R,\n derived: [],\n signalTime: 0,\n ...overrides,\n };\n}\n\n/** The reason phrases of the statuses a Wow service answers a problem with. */\nconst TITLES: Readonly<Record<number, string>> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * An RFC 9457 problem as a service answers it, of `status` and the Wow `code`\n * (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or\n * an expected error. Its title is the status's reason phrase unless\n * `overrides` says otherwise.\n */\nexport function problemOf(\n status: number,\n code?: string,\n overrides: Partial<Problem> = {},\n): Problem {\n return {\n type: code === undefined ? 'about:blank' : `urn:wow:error:${code}`,\n title: TITLES[status] ?? `HTTP ${status}`,\n status,\n ...(code === undefined ? {} : { code }),\n ...overrides,\n };\n}\n\n/**\n * The response a service answers `problem` with: `application/problem+json`,\n * its extension members written as members of their own, as the wire carries\n * them.\n */\nexport function problemResponse(\n problem: Problem,\n init: ResponseInit = {},\n): Response {\n const { extensions, ...members } = problem;\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/problem+json');\n return new Response(JSON.stringify({ ...extensions, ...members }), {\n ...init,\n status: problem.status,\n headers,\n });\n}\n\n/**\n * An aggregate's snapshot as a state read and a snapshot query answer it, for\n * a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous\n * caller, of no owner or space, not deleted, untagged and keeping no\n * schedules unless `overrides` says otherwise.\n */\nexport function snapshotOf<S>(\n ref: AggregateRef,\n state: S,\n overrides: Partial<\n Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>\n > = {},\n): Snapshot<S> {\n return {\n tenantId: ref.tenantId,\n aggregateId: ref.id,\n version: 1,\n ownerId: null,\n spaceId: null,\n deleted: false,\n
|
|
1
|
+
{"version":3,"file":"wire.cjs","names":["CommandResultStatus","Stage","FunctionKind","FrameworkErrorCodes","require_frameworkErrors","require_wire","commandResultOf","ref","status","overrides","commandId","name","TITLES","problemOf","code","problemResponse","members","problem","headers","init","extensions","snapshotOf"],"sources":["../../src/testing/wire.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 { FrameworkErrorCodes, type Problem } from '../problem.js';\nimport {\n type AggregateRef,\n type CommandResult,\n CommandResultStatus,\n FunctionKind,\n Stage,\n type Snapshot,\n} from '../wire.js';\n\n/**\n * A command's result as a service answers it, for a test's fake: the command\n * `ref` names, committed (`succeeded` at `committed`, version 1) unless\n * `overrides` says otherwise. A `rejected` or `failed` one without an `error`\n * carries `wow.command.refused` or `wow.command.failed`.\n */\nexport function commandResultOf<R = Record<string, unknown>>(\n ref: AggregateRef,\n overrides: Partial<CommandResult<R>> = {},\n): CommandResult<R> {\n const { context, name } = ref.type;\n const status = overrides.status ?? CommandResultStatus.SUCCEEDED;\n const commandId = overrides.commandId ?? 'command-1';\n return {\n format: 1,\n commandId,\n requestId: 'request-1',\n correlationId: commandId,\n ref,\n hop: { stage: Stage.COMMITTED, context },\n function: {\n kind: FunctionKind.COMMAND,\n context,\n processor: name,\n name: 'Command',\n },\n status,\n version: 1,\n duplicate: false,\n error:\n status === CommandResultStatus.SUCCEEDED\n ? null\n : {\n code:\n status === CommandResultStatus.REJECTED\n ? FrameworkErrorCodes.COMMAND_REFUSED\n : FrameworkErrorCodes.COMMAND_FAILED,\n message: `The command was ${status.toLowerCase()}.`,\n },\n results: {} as R,\n derived: [],\n signalTime: 0,\n ...overrides,\n };\n}\n\n/** The reason phrases of the statuses a Wow service answers a problem with. */\nconst TITLES: Readonly<Record<number, string>> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * An RFC 9457 problem as a service answers it, of `status` and the Wow `code`\n * (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or\n * an expected error. Its title is the status's reason phrase unless\n * `overrides` says otherwise.\n */\nexport function problemOf(\n status: number,\n code?: string,\n overrides: Partial<Problem> = {},\n): Problem {\n return {\n type: code === undefined ? 'about:blank' : `urn:wow:error:${code}`,\n title: TITLES[status] ?? `HTTP ${status}`,\n status,\n ...(code === undefined ? {} : { code }),\n ...overrides,\n };\n}\n\n/**\n * The response a service answers `problem` with: `application/problem+json`,\n * its extension members written as members of their own, as the wire carries\n * them.\n */\nexport function problemResponse(\n problem: Problem,\n init: ResponseInit = {},\n): Response {\n const { extensions, ...members } = problem;\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/problem+json');\n return new Response(JSON.stringify({ ...extensions, ...members }), {\n ...init,\n status: problem.status,\n headers,\n });\n}\n\n/**\n * An aggregate's snapshot as a state read and a snapshot query answer it, for\n * a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous\n * caller, of no owner or space, not deleted, untagged and keeping no\n * schedules unless `overrides` says otherwise.\n */\nexport function snapshotOf<S>(\n ref: AggregateRef,\n state: S,\n overrides: Partial<\n Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>\n > = {},\n): Snapshot<S> {\n return {\n tenantId: ref.tenantId,\n aggregateId: ref.id,\n version: 1,\n ownerId: null,\n spaceId: null,\n deleted: false,\n access: {},\n firstEventTime: 0,\n lastEventTime: 0,\n operator: null,\n firstOperator: null,\n schedules: {},\n state,\n ...overrides,\n };\n}\n"],"mappings":"A,mEA6BA,SAAgBM,EACd,EACA,EAAuC,CAAC,EACtB,CAClB,GAAM,CAAE,UAAS,QAASC,EAAI,KACxBC,EAASC,EAAU,QAAUT,EAAAA,oBAAoB,UACjDU,EAAYD,EAAU,WAAa,YACzC,MAAO,CACL,OAAQ,EACR,YACA,UAAW,YACX,cAAeC,EACf,MACA,IAAK,CAAE,MAAOT,EAAAA,MAAM,UAAW,SAAQ,EACvC,SAAU,CACR,KAAMC,EAAAA,aAAa,QACnB,UACA,UAAWS,EACX,KAAM,SACR,EACA,SACA,QAAS,E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-
{"version":3,"file":"wire.es.js","names":["commandResultOf","ref","status","overrides","CommandResultStatus","commandId","Stage","FunctionKind","name","FrameworkErrorCodes","TITLES","problemOf","code","problemResponse","members","problem","headers","init","extensions","snapshotOf"],"sources":["../../src/testing/wire.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 { FrameworkErrorCodes, type Problem } from '../problem.js';\nimport {\n type AggregateRef,\n type CommandResult,\n CommandResultStatus,\n FunctionKind,\n Stage,\n type Snapshot,\n} from '../wire.js';\n\n/**\n * A command's result as a service answers it, for a test's fake: the command\n * `ref` names, committed (`succeeded` at `committed`, version 1) unless\n * `overrides` says otherwise. A `rejected` or `failed` one without an `error`\n * carries `wow.command.refused` or `wow.command.failed`.\n */\nexport function commandResultOf<R = Record<string, unknown>>(\n ref: AggregateRef,\n overrides: Partial<CommandResult<R>> = {},\n): CommandResult<R> {\n const { context, name } = ref.type;\n const status = overrides.status ?? CommandResultStatus.SUCCEEDED;\n const commandId = overrides.commandId ?? 'command-1';\n return {\n format: 1,\n commandId,\n requestId: 'request-1',\n correlationId: commandId,\n ref,\n hop: { stage: Stage.COMMITTED, context },\n function: {\n kind: FunctionKind.COMMAND,\n context,\n processor: name,\n name: 'Command',\n },\n status,\n version: 1,\n duplicate: false,\n error:\n status === CommandResultStatus.SUCCEEDED\n ? null\n : {\n code:\n status === CommandResultStatus.REJECTED\n ? FrameworkErrorCodes.COMMAND_REFUSED\n : FrameworkErrorCodes.COMMAND_FAILED,\n message: `The command was ${status.toLowerCase()}.`,\n },\n results: {} as R,\n derived: [],\n signalTime: 0,\n ...overrides,\n };\n}\n\n/** The reason phrases of the statuses a Wow service answers a problem with. */\nconst TITLES: Readonly<Record<number, string>> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * An RFC 9457 problem as a service answers it, of `status` and the Wow `code`\n * (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or\n * an expected error. Its title is the status's reason phrase unless\n * `overrides` says otherwise.\n */\nexport function problemOf(\n status: number,\n code?: string,\n overrides: Partial<Problem> = {},\n): Problem {\n return {\n type: code === undefined ? 'about:blank' : `urn:wow:error:${code}`,\n title: TITLES[status] ?? `HTTP ${status}`,\n status,\n ...(code === undefined ? {} : { code }),\n ...overrides,\n };\n}\n\n/**\n * The response a service answers `problem` with: `application/problem+json`,\n * its extension members written as members of their own, as the wire carries\n * them.\n */\nexport function problemResponse(\n problem: Problem,\n init: ResponseInit = {},\n): Response {\n const { extensions, ...members } = problem;\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/problem+json');\n return new Response(JSON.stringify({ ...extensions, ...members }), {\n ...init,\n status: problem.status,\n headers,\n });\n}\n\n/**\n * An aggregate's snapshot as a state read and a snapshot query answer it, for\n * a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous\n * caller, of no owner or space, not deleted, untagged and keeping no\n * schedules unless `overrides` says otherwise.\n */\nexport function snapshotOf<S>(\n ref: AggregateRef,\n state: S,\n overrides: Partial<\n Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>\n > = {},\n): Snapshot<S> {\n return {\n tenantId: ref.tenantId,\n aggregateId: ref.id,\n version: 1,\n ownerId: null,\n spaceId: null,\n deleted: false,\n
|
|
1
|
+
{"version":3,"file":"wire.es.js","names":["commandResultOf","ref","status","overrides","CommandResultStatus","commandId","Stage","FunctionKind","name","FrameworkErrorCodes","TITLES","problemOf","code","problemResponse","members","problem","headers","init","extensions","snapshotOf"],"sources":["../../src/testing/wire.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 { FrameworkErrorCodes, type Problem } from '../problem.js';\nimport {\n type AggregateRef,\n type CommandResult,\n CommandResultStatus,\n FunctionKind,\n Stage,\n type Snapshot,\n} from '../wire.js';\n\n/**\n * A command's result as a service answers it, for a test's fake: the command\n * `ref` names, committed (`succeeded` at `committed`, version 1) unless\n * `overrides` says otherwise. A `rejected` or `failed` one without an `error`\n * carries `wow.command.refused` or `wow.command.failed`.\n */\nexport function commandResultOf<R = Record<string, unknown>>(\n ref: AggregateRef,\n overrides: Partial<CommandResult<R>> = {},\n): CommandResult<R> {\n const { context, name } = ref.type;\n const status = overrides.status ?? CommandResultStatus.SUCCEEDED;\n const commandId = overrides.commandId ?? 'command-1';\n return {\n format: 1,\n commandId,\n requestId: 'request-1',\n correlationId: commandId,\n ref,\n hop: { stage: Stage.COMMITTED, context },\n function: {\n kind: FunctionKind.COMMAND,\n context,\n processor: name,\n name: 'Command',\n },\n status,\n version: 1,\n duplicate: false,\n error:\n status === CommandResultStatus.SUCCEEDED\n ? null\n : {\n code:\n status === CommandResultStatus.REJECTED\n ? FrameworkErrorCodes.COMMAND_REFUSED\n : FrameworkErrorCodes.COMMAND_FAILED,\n message: `The command was ${status.toLowerCase()}.`,\n },\n results: {} as R,\n derived: [],\n signalTime: 0,\n ...overrides,\n };\n}\n\n/** The reason phrases of the statuses a Wow service answers a problem with. */\nconst TITLES: Readonly<Record<number, string>> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * An RFC 9457 problem as a service answers it, of `status` and the Wow `code`\n * (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or\n * an expected error. Its title is the status's reason phrase unless\n * `overrides` says otherwise.\n */\nexport function problemOf(\n status: number,\n code?: string,\n overrides: Partial<Problem> = {},\n): Problem {\n return {\n type: code === undefined ? 'about:blank' : `urn:wow:error:${code}`,\n title: TITLES[status] ?? `HTTP ${status}`,\n status,\n ...(code === undefined ? {} : { code }),\n ...overrides,\n };\n}\n\n/**\n * The response a service answers `problem` with: `application/problem+json`,\n * its extension members written as members of their own, as the wire carries\n * them.\n */\nexport function problemResponse(\n problem: Problem,\n init: ResponseInit = {},\n): Response {\n const { extensions, ...members } = problem;\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/problem+json');\n return new Response(JSON.stringify({ ...extensions, ...members }), {\n ...init,\n status: problem.status,\n headers,\n });\n}\n\n/**\n * An aggregate's snapshot as a state read and a snapshot query answer it, for\n * a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous\n * caller, of no owner or space, not deleted, untagged and keeping no\n * schedules unless `overrides` says otherwise.\n */\nexport function snapshotOf<S>(\n ref: AggregateRef,\n state: S,\n overrides: Partial<\n Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>\n > = {},\n): Snapshot<S> {\n return {\n tenantId: ref.tenantId,\n aggregateId: ref.id,\n version: 1,\n ownerId: null,\n spaceId: null,\n deleted: false,\n access: {},\n firstEventTime: 0,\n lastEventTime: 0,\n operator: null,\n firstOperator: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EAChB;CACF,CAAC;AACH;AAQA,SAAgBI,EACd,GACA,GACA,IAEI,CAAC,GACQ;CACb,OAAO;EACL,UAAUlB,EAAI;EACd,aAAaA,EAAI;EACjB,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,QAAQ,CAAC;EACT,gBAAgB;EAChB,eAAe;EACf,UAAU;EACV,eAAe;EACf,WAAW,CAAC;EACZ;EACA,GAAGE;CACL;AACF"}
|
package/dist/wait.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./wire.cjs");var t=`wow.snapshot`,n=/^[A-Za-z0-9_.-]+$/;function
|
|
1
|
+
const e=require("./wire.cjs");var t=`wow.snapshot`,n=`wow.queryable`,r=/^[A-Za-z0-9_.-]+$/;function i(e,t){if(!r.test(t))throw TypeError(`Not a ${e} name: '${t}'.`);return t}function a(e,t,n){return{stage:e,...t===void 0?{}:{context:i(`context`,t)},...n===void 0?{}:{subscription:i(`subscription`,n)}}}var o={accepted:t=>a(e.Stage.ACCEPTED,t),committed:t=>a(e.Stage.COMMITTED,t),snapshot:n=>a(e.Stage.HANDLED,n,t),queryable:t=>a(e.Stage.HANDLED,t,n),handled:(t,n)=>a(e.Stage.HANDLED,n,t)};function s(t){let n=t.context??void 0,r=t.subscription??void 0;if(t.stage===e.Stage.HANDLED){if(r===void 0)throw TypeError(`A handled hop names its subscription.`);return r===`wow.snapshot`?n===void 0?`snapshot`:`snapshot(${n})`:r===`wow.queryable`?n===void 0?`queryable`:`queryable(${n})`:n===void 0?`handled(${r})`:`handled(${n}/${r})`}if(r!==void 0)throw TypeError(`Only a handled hop names a subscription.`);let i=t.stage.toLowerCase();return n===void 0?i:`${i}(${n})`}var c=class e{static{this.DEFAULT_TIMEOUT=1e4}static{this.DEFAULT=new e([o.snapshot()],void 0,!0)}static{this.SNAPSHOT=new e([o.snapshot()])}static{this.COMMITTED=new e([o.committed()])}static{this.ACCEPTED=new e([o.accepted()])}static of(...t){return new e(t)}constructor(t,n=e.DEFAULT_TIMEOUT,r=!1){if(t.length===0)throw TypeError(`A wait plan has at least one hop.`);m(n),this.hops=Object.freeze([...t]),this.timeout=n,this.isDefault=r,Object.freeze(this)}within(t){return new e(this.hops,t,this.isDefault)}};function l(e){return e.hops.map(s).join(` > `)}var u=/^([A-Za-z]+)\s*(?:\(\s*([^()]*?)\s*\))?$/;function d(e){if(e.trim()===``)throw TypeError(`A wait plan has at least one hop.`);return c.of(...e.split(`>`).map(e=>f(e.trim())))}function f(e){let t=u.exec(e);if(t===null)throw TypeError(`Not a hop: '${e}'.`);let n=t[1].toLowerCase(),r=t[2];switch(n){case`accepted`:return o.accepted(r);case`committed`:return o.committed(r);case`snapshot`:return o.snapshot(r);case`queryable`:return o.queryable(r);case`handled`:{if(r===void 0)throw TypeError(`A handled hop names its subscription: '${e}'.`);let t=r.split(`/`);if(t.length>2)throw TypeError(`A handled hop is (subscription) or (context/subscription): '${r}'.`);return t.length===1?o.handled(t[0]):o.handled(t[1].trim(),t[0].trim())}default:throw TypeError(`Not a stage: '${n}'.`)}}function p(e){return m(e),e%1e3==0?`${e/1e3}s`:`${e}ms`}function m(e){if(!Number.isInteger(e)||e<=0)throw TypeError(`A wait timeout is a positive whole number of milliseconds: ${e}.`)}exports.QUERYABLE_SUBSCRIPTION=n,exports.SNAPSHOT_SUBSCRIPTION=t,exports.WaitPlan=c,exports.formatHop=s,exports.formatWaitPlan=l,exports.formatWaitTimeout=p,exports.parseHop=f,exports.parseWaitPlan=d,exports.wait=o;
|
|
2
2
|
//# sourceMappingURL=wait.cjs.map
|
package/dist/wait.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wait.cjs","names":["Stage","require_wire","SNAPSHOT_SUBSCRIPTION","NAME","checkName","value","kind","hop","context","subscription","wait","formatHop","keyword","WaitPlan","hops","checkTimeout","timeout","isDefault","formatWaitPlan","plan","HOP","parseWaitPlan","parseHop","part","match","argument","parts","formatWaitTimeout"],"sources":["../src/wait.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 Hop, Stage } from './wire.js';\n\n/** The name of the built-in subscription that writes snapshots. */\nexport const SNAPSHOT_SUBSCRIPTION = 'wow.snapshot';\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\nfunction checkName(kind: string, value: string): string {\n if (!NAME.test(value)) {\n throw new TypeError(`Not a ${kind} name: '${value}'.`);\n }\n return value;\n}\n\nfunction hop(stage: Stage, context?: string, subscription?: string): Hop {\n return {\n stage,\n ...(context === undefined\n ? {}\n : { context: checkName('context', context) }),\n ...(subscription === undefined\n ? {}\n : { subscription: checkName('subscription', subscription) }),\n };\n}\n\n/**\n * Builds the hops of a wait chain. A context left out is\n * the command's own. A saga's `handled` hop may be followed by hops of the\n * commands it derived, in their contexts:\n *\n * @example\n * ```typescript\n * const plan = [\n * wait.committed(),\n * wait.handled('BasketCheckoutSaga.onBasketCheckedOut', 'eshop-basket'),\n * wait.committed('eshop-ordering'),\n * ];\n * ```\n */\nexport const wait = {\n /** Until the command passed admission; the route answers 202. */\n accepted: (context?: string): Hop => hop(Stage.ACCEPTED, context),\n /** Until the command's events are appended to the log. */\n committed: (context?: string): Hop => hop(Stage.COMMITTED, context),\n /** Until the snapshot holds the commit: the caller reads its own write. */\n snapshot: (context?: string): Hop =>\n hop(Stage.HANDLED, context, SNAPSHOT_SUBSCRIPTION),\n /** Until the subscription named `processor.function` handled the commit. */\n handled: (subscription: string, context?: string): Hop =>\n hop(Stage.HANDLED, context, subscription),\n} as const;\n\n/**\n * A hop as `Wow-Wait` spells it: `accepted`, `committed`, `snapshot` and\n * `handled(subscription)`, each with its context when it has one:\n * `committed(ctx)`, `snapshot(ctx)`, `handled(ctx/subscription)`.\n *\n * @param value - The hop\n */\nexport function formatHop(value: Hop): string {\n const context = value.context ?? undefined;\n const subscription = value.subscription ?? undefined;\n if (value.stage === Stage.HANDLED) {\n if (subscription === undefined) {\n throw new TypeError('A handled hop names its subscription.');\n }\n if (subscription === SNAPSHOT_SUBSCRIPTION) {\n return context === undefined ? 'snapshot' : `snapshot(${context})`;\n }\n return context === undefined\n ? `handled(${subscription})`\n : `handled(${context}/${subscription})`;\n }\n if (subscription !== undefined) {\n throw new TypeError(`Only a handled hop names a subscription.`);\n }\n const keyword = value.stage.toLowerCase();\n return context === undefined ? keyword : `${keyword}(${context})`;\n}\n\n/**\n * How far a command is waited for, and for how long: the hops, in order, and\n * a timeout in milliseconds. Kotlin's `me.ahoo.wow.api.result.WaitPlan`,\n * with its constants and constructors: {@link WaitPlan.of} the hops a\n * {@link wait} builder makes, {@link WaitPlan.within} another timeout.\n *\n * @example\n * ```typescript\n * const plan = WaitPlan.of(\n * wait.committed(),\n * wait.handled('BasketCheckoutSaga.onBasketCheckedOut', 'eshop-basket'),\n * ).within(30_000);\n * ```\n */\nexport class WaitPlan {\n /** The timeout of a wait whose caller gives none: 10 seconds. */\n static readonly DEFAULT_TIMEOUT = 10_000;\n\n /**\n * The plan of a caller that asked for none: until the snapshot holds the\n * commit, so the caller reads its own write; until `committed` for an\n * aggregate without a snapshot subscription. A request with it sends no\n * `Wow-Wait`, so the service picks.\n */\n static readonly DEFAULT = new WaitPlan([wait.snapshot()], undefined, true);\n\n /**\n * Until the snapshot holds the commit, asked for explicitly: rejected at\n * admission for an aggregate without a snapshot subscription.\n */\n static readonly SNAPSHOT = new WaitPlan([wait.snapshot()]);\n\n /** Until the events are appended. */\n static readonly COMMITTED = new WaitPlan([wait.committed()]);\n\n /** Until the command passed admission. */\n static readonly ACCEPTED = new WaitPlan([wait.accepted()]);\n\n /** Until `hops` are reached, in order. */\n static of(...hops: Hop[]): WaitPlan {\n return new WaitPlan(hops);\n }\n\n /** The hops to reach, in order; at least one. */\n readonly hops: readonly Hop[];\n /** How long to wait, in milliseconds. */\n readonly timeout: number;\n /** Whether this is {@link WaitPlan.DEFAULT}, the service's choice. */\n readonly isDefault: boolean;\n\n private constructor(\n hops: readonly Hop[],\n timeout: number = WaitPlan.DEFAULT_TIMEOUT,\n isDefault = false,\n ) {\n if (hops.length === 0) {\n throw new TypeError('A wait plan has at least one hop.');\n }\n checkTimeout(timeout);\n this.hops = Object.freeze([...hops]);\n this.timeout = timeout;\n this.isDefault = isDefault;\n Object.freeze(this);\n }\n\n /** This plan, waiting `timeout` milliseconds. */\n within(timeout: number): WaitPlan {\n return new WaitPlan(this.hops, timeout, this.isDefault);\n }\n}\n\n/**\n * A wait plan as the `Wow-Wait` header spells it: its hops, in order,\n * separated by `>`; the inverse of {@link parseWaitPlan}.\n *\n * @param plan - The plan\n */\nexport function formatWaitPlan(plan: WaitPlan): string {\n return plan.hops.map(formatHop).join(' > ');\n}\n\nconst HOP = /^([A-Za-z]+)\\s*(?:\\(\\s*([^()]*?)\\s*\\))?$/;\n\n/**\n * The plan a `Wow-Wait` value spells, as the service reads it: hops\n * separated by `>`, each `accepted`, `committed`, `snapshot` or\n * `handled(subscription)`, with its context in parentheses\n * (`committed(ctx)`, `handled(ctx/subscription)`); the inverse of\n * {@link formatWaitPlan}. Throws a `TypeError` for anything else.\n *\n * @param value - The header's value\n */\nexport function parseWaitPlan(value: string): WaitPlan {\n if (value.trim() === '') {\n throw new TypeError('A wait plan has at least one hop.');\n }\n return WaitPlan.of(...value.split('>').map(part => parseHop(part.trim())));\n}\n\n/**\n * The hop one part of a `Wow-Wait` value spells; see {@link parseWaitPlan}.\n *\n * @param value - The part, such as `committed(ctx)`\n */\nexport function parseHop(value: string): Hop {\n const match = HOP.exec(value);\n if (match === null) throw new TypeError(`Not a hop: '${value}'.`);\n const keyword = match[1].toLowerCase();\n const argument = match[2];\n switch (keyword) {\n case 'accepted':\n return wait.accepted(argument);\n case 'committed':\n return wait.committed(argument);\n case 'snapshot':\n return wait.snapshot(argument);\n case 'handled': {\n if (argument === undefined) {\n throw new TypeError(\n `A handled hop names its subscription: '${value}'.`,\n );\n }\n const parts = argument.split('/');\n if (parts.length > 2) {\n throw new TypeError(\n `A handled hop is (subscription) or (context/subscription): '${argument}'.`,\n );\n }\n return parts.length === 1\n ? wait.handled(parts[0])\n : wait.handled(parts[1].trim(), parts[0].trim());\n }\n default:\n throw new TypeError(`Not a stage: '${keyword}'.`);\n }\n}\n\n/**\n * A wait timeout as the `Wow-Wait-Timeout` header spells it: milliseconds\n * as `<n>s` when whole seconds, else `<n>ms`.\n *\n * @param timeout - Milliseconds\n */\nexport function formatWaitTimeout(timeout: number): string {\n checkTimeout(timeout);\n return timeout % 1000 === 0 ? `${timeout / 1000}s` : `${timeout}ms`;\n}\n\nfunction checkTimeout(timeout: number): void {\n if (!Number.isInteger(timeout) || timeout <= 0) {\n throw new TypeError(\n `A wait timeout is a positive whole number of milliseconds: ${timeout}.`,\n );\n }\n}\n"],"mappings":"A,8BAgBA,IAAaE,EAAwB,eAE/BC,EAAO,oBAEb,SAASC,EAAU,EAAc,EAAuB,CACtD,GAAI,CAACD,EAAK,KAAKE,CAAK,EAClB,MAAU,UAAU,SAASC,EAAK,UAAUD,EAAM,GAAG,EAEvD,OAAOA,CACT,CAEA,SAASE,EAAI,EAAc,EAAkB,EAA4B,CACvE,MAAO,CACL,QACA,GAAIC,IAAY,IAAA,GACZ,CAAC,EACD,CAAE,QAASJ,EAAU,UAAWI,CAAO,CAAE,EAC7C,GAAIC,IAAiB,IAAA,GACjB,CAAC,EACD,CAAE,aAAcL,EAAU,eAAgBK,CAAY,CAAE,CAC9D,CACF,CAgBA,IAAaC,EAAO,CAElB,SAAW,GAA0BH,EAAIP,EAAAA,MAAM,SAAUQ,CAAO,EAEhE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,iBAAiBd,EAAQ,GAAG,CACpD,CACF,CAQA,SAAgBe,EAAkB,EAAyB,CAEzD,OADAZ,EAAaC,CAAO,EACbA,EAAU,KAAS,EAAI,GAAGA,EAAU,IAAK,GAAK,GAAGA,EAAQ,GAClE,CAEA,SAASD,EAAa,EAAuB,CAC3C,GAAI,CAAC,OAAO,UAAUC,CAAO,GAAKA,GAAW,EAC3C,MAAU,UACR,8DAA8DA,EAAQ,EACxE,CAEJ,C"}
|
|
1
|
+
{"version":3,"file":"wait.cjs","names":["Stage","require_wire","SNAPSHOT_SUBSCRIPTION","QUERYABLE_SUBSCRIPTION","NAME","checkName","value","kind","hop","context","subscription","wait","formatHop","keyword","WaitPlan","hops","checkTimeout","timeout","isDefault","formatWaitPlan","plan","HOP","parseWaitPlan","parseHop","part","match","argument","parts","formatWaitTimeout"],"sources":["../src/wait.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 Hop, Stage } from './wire.js';\n\n/** The name of the built-in subscription that writes snapshots. */\nexport const SNAPSHOT_SUBSCRIPTION = 'wow.snapshot';\n\n/**\n * The name a `queryable` hop gives the snapshot subscription of the store an\n * aggregate type's snapshot queries read: its copy's where it has one, else\n * its own store's, as `snapshot` is.\n */\nexport const QUERYABLE_SUBSCRIPTION = 'wow.queryable';\n\nconst NAME = /^[A-Za-z0-9_.-]+$/;\n\nfunction checkName(kind: string, value: string): string {\n if (!NAME.test(value)) {\n throw new TypeError(`Not a ${kind} name: '${value}'.`);\n }\n return value;\n}\n\nfunction hop(stage: Stage, context?: string, subscription?: string): Hop {\n return {\n stage,\n ...(context === undefined\n ? {}\n : { context: checkName('context', context) }),\n ...(subscription === undefined\n ? {}\n : { subscription: checkName('subscription', subscription) }),\n };\n}\n\n/**\n * Builds the hops of a wait chain. A context left out is\n * the command's own. A saga's `handled` hop may be followed by hops of the\n * commands it derived, in their contexts:\n *\n * @example\n * ```typescript\n * const plan = [\n * wait.committed(),\n * wait.handled('BasketCheckoutSaga.onBasketCheckedOut', 'eshop-basket'),\n * wait.committed('eshop-ordering'),\n * ];\n * ```\n */\nexport const wait = {\n /** Until the command passed admission; the route answers 202. */\n accepted: (context?: string): Hop => hop(Stage.ACCEPTED, context),\n /** Until the command's events are appended to the log. */\n committed: (context?: string): Hop => hop(Stage.COMMITTED, context),\n /** Until the snapshot holds the commit: the caller reads its own write. */\n snapshot: (context?: string): Hop =>\n hop(Stage.HANDLED, context, SNAPSHOT_SUBSCRIPTION),\n /**\n * Until the store the aggregate type's snapshot queries read holds the\n * commit: a list or a count the caller runs next sees it. The same as\n * `snapshot` for a type whose queries read its own store.\n */\n queryable: (context?: string): Hop =>\n hop(Stage.HANDLED, context, QUERYABLE_SUBSCRIPTION),\n /** Until the subscription named `processor.function` handled the commit. */\n handled: (subscription: string, context?: string): Hop =>\n hop(Stage.HANDLED, context, subscription),\n} as const;\n\n/**\n * A hop as `Wow-Wait` spells it: `accepted`, `committed`, `snapshot`,\n * `queryable` and `handled(subscription)`, each with its context when it has\n * one: `committed(ctx)`, `snapshot(ctx)`, `queryable(ctx)`,\n * `handled(ctx/subscription)`.\n *\n * @param value - The hop\n */\nexport function formatHop(value: Hop): string {\n const context = value.context ?? undefined;\n const subscription = value.subscription ?? undefined;\n if (value.stage === Stage.HANDLED) {\n if (subscription === undefined) {\n throw new TypeError('A handled hop names its subscription.');\n }\n if (subscription === SNAPSHOT_SUBSCRIPTION) {\n return context === undefined ? 'snapshot' : `snapshot(${context})`;\n }\n if (subscription === QUERYABLE_SUBSCRIPTION) {\n return context === undefined ? 'queryable' : `queryable(${context})`;\n }\n return context === undefined\n ? `handled(${subscription})`\n : `handled(${context}/${subscription})`;\n }\n if (subscription !== undefined) {\n throw new TypeError(`Only a handled hop names a subscription.`);\n }\n const keyword = value.stage.toLowerCase();\n return context === undefined ? keyword : `${keyword}(${context})`;\n}\n\n/**\n * How far a command is waited for, and for how long: the hops, in order, and\n * a timeout in milliseconds. Kotlin's `me.ahoo.wow.api.result.WaitPlan`,\n * with its constants and constructors: {@link WaitPlan.of} the hops a\n * {@link wait} builder makes, {@link WaitPlan.within} another timeout.\n *\n * @example\n * ```typescript\n * const plan = WaitPlan.of(\n * wait.committed(),\n * wait.handled('BasketCheckoutSaga.onBasketCheckedOut', 'eshop-basket'),\n * ).within(30_000);\n * ```\n */\nexport class WaitPlan {\n /** The timeout of a wait whose caller gives none: 10 seconds. */\n static readonly DEFAULT_TIMEOUT = 10_000;\n\n /**\n * The plan of a caller that asked for none: until the snapshot holds the\n * commit, so the caller reads its own write; until `committed` for an\n * aggregate without a snapshot subscription. A request with it sends no\n * `Wow-Wait`, so the service picks.\n */\n static readonly DEFAULT = new WaitPlan([wait.snapshot()], undefined, true);\n\n /**\n * Until the snapshot holds the commit, asked for explicitly: rejected at\n * admission for an aggregate without a snapshot subscription.\n */\n static readonly SNAPSHOT = new WaitPlan([wait.snapshot()]);\n\n /** Until the events are appended. */\n static readonly COMMITTED = new WaitPlan([wait.committed()]);\n\n /** Until the command passed admission. */\n static readonly ACCEPTED = new WaitPlan([wait.accepted()]);\n\n /** Until `hops` are reached, in order. */\n static of(...hops: Hop[]): WaitPlan {\n return new WaitPlan(hops);\n }\n\n /** The hops to reach, in order; at least one. */\n readonly hops: readonly Hop[];\n /** How long to wait, in milliseconds. */\n readonly timeout: number;\n /** Whether this is {@link WaitPlan.DEFAULT}, the service's choice. */\n readonly isDefault: boolean;\n\n private constructor(\n hops: readonly Hop[],\n timeout: number = WaitPlan.DEFAULT_TIMEOUT,\n isDefault = false,\n ) {\n if (hops.length === 0) {\n throw new TypeError('A wait plan has at least one hop.');\n }\n checkTimeout(timeout);\n this.hops = Object.freeze([...hops]);\n this.timeout = timeout;\n this.isDefault = isDefault;\n Object.freeze(this);\n }\n\n /** This plan, waiting `timeout` milliseconds. */\n within(timeout: number): WaitPlan {\n return new WaitPlan(this.hops, timeout, this.isDefault);\n }\n}\n\n/**\n * A wait plan as the `Wow-Wait` header spells it: its hops, in order,\n * separated by `>`; the inverse of {@link parseWaitPlan}.\n *\n * @param plan - The plan\n */\nexport function formatWaitPlan(plan: WaitPlan): string {\n return plan.hops.map(formatHop).join(' > ');\n}\n\nconst HOP = /^([A-Za-z]+)\\s*(?:\\(\\s*([^()]*?)\\s*\\))?$/;\n\n/**\n * The plan a `Wow-Wait` value spells, as the service reads it: hops\n * separated by `>`, each `accepted`, `committed`, `snapshot`, `queryable` or\n * `handled(subscription)`, with its context in parentheses\n * (`committed(ctx)`, `handled(ctx/subscription)`); the inverse of\n * {@link formatWaitPlan}. Throws a `TypeError` for anything else.\n *\n * @param value - The header's value\n */\nexport function parseWaitPlan(value: string): WaitPlan {\n if (value.trim() === '') {\n throw new TypeError('A wait plan has at least one hop.');\n }\n return WaitPlan.of(...value.split('>').map(part => parseHop(part.trim())));\n}\n\n/**\n * The hop one part of a `Wow-Wait` value spells; see {@link parseWaitPlan}.\n *\n * @param value - The part, such as `committed(ctx)`\n */\nexport function parseHop(value: string): Hop {\n const match = HOP.exec(value);\n if (match === null) throw new TypeError(`Not a hop: '${value}'.`);\n const keyword = match[1].toLowerCase();\n const argument = match[2];\n switch (keyword) {\n case 'accepted':\n return wait.accepted(argument);\n case 'committed':\n return wait.committed(argument);\n case 'snapshot':\n return wait.snapshot(argument);\n case 'queryable':\n return wait.queryable(argument);\n case 'handled': {\n if (argument === undefined) {\n throw new TypeError(\n `A handled hop names its subscription: '${value}'.`,\n );\n }\n const parts = argument.split('/');\n if (parts.length > 2) {\n throw new TypeError(\n `A handled hop is (subscription) or (context/subscription): '${argument}'.`,\n );\n }\n return parts.length === 1\n ? wait.handled(parts[0])\n : wait.handled(parts[1].trim(), parts[0].trim());\n }\n default:\n throw new TypeError(`Not a stage: '${keyword}'.`);\n }\n}\n\n/**\n * A wait timeout as the `Wow-Wait-Timeout` header spells it: milliseconds\n * as `<n>s` when whole seconds, else `<n>ms`.\n *\n * @param timeout - Milliseconds\n */\nexport function formatWaitTimeout(timeout: number): string {\n checkTimeout(timeout);\n return timeout % 1000 === 0 ? `${timeout / 1000}s` : `${timeout}ms`;\n}\n\nfunction checkTimeout(timeout: number): void {\n if (!Number.isInteger(timeout) || timeout <= 0) {\n throw new TypeError(\n `A wait timeout is a positive whole number of milliseconds: ${timeout}.`,\n );\n }\n}\n"],"mappings":"A,8BAgBA,IAAaE,EAAwB,eAOxBC,EAAyB,gBAEhCC,EAAO,oBAEb,SAASC,EAAU,EAAc,EAAuB,CACtD,GAAI,CAACD,EAAK,KAAKE,CAAK,EAClB,MAAU,UAAU,SAASC,EAAK,UAAUD,EAAM,GAAG,EAEvD,OAAOA,CACT,CAEA,SAASE,EAAI,EAAc,EAAkB,EAA4B,CACvE,MAAO,CACL,QACA,GAAIC,IAAY,IAAA,GACZ,CAAC,EACD,CAAE,QAASJ,EAAU,UAAWI,CAAO,CAAE,EAC7C,GAAIC,IAAiB,IAAA,GACjB,CAAC,EACD,CAAE,aAAcL,EAAU,eAAgBK,CAAY,CAAE,CAC9D,CACF,CAgBA,IAAaC,EAAO,CAElB,SAAW,GAA0BH,EAAIR,EAAAA,MAAM,SAAUS,CAAO,EAEhE,UAAY,GAA0BD,EAAIR,EAAAA,MAAM,UAAWS,CAAO,EAElE,SAAW,GACTD,EAAIR,EAAAA,MAAM,QAASS,EAASP,CAAqB,EAMnD,UAAY,GACVM,EAAIR,EAAAA,MAAM,QAASS,EAASN,CAAsB,EAEpD,SAAU,EAAsB,IAC9BK,EAAIR,EAAAA,MAAM,QAASS,EAASC,CAAY,CAC5C,EAUA,SAAgBE,EAAU,EAAoB,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S,EAAI,GAAGA,EAAU,IAAK,GAAK,GAAGA,EAAQ,GAClE,CAEA,SAASD,EAAa,EAAuB,CAC3C,GAAI,CAAC,OAAO,UAAUC,CAAO,GAAKA,GAAW,EAC3C,MAAU,UACR,8DAA8DA,EAAQ,EACxE,CAEJ,C"}
|
package/dist/wait.d.cts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { Hop } from './wire.cjs';
|
|
2
2
|
/** The name of the built-in subscription that writes snapshots. */
|
|
3
3
|
export declare const SNAPSHOT_SUBSCRIPTION = "wow.snapshot";
|
|
4
|
+
/**
|
|
5
|
+
* The name a `queryable` hop gives the snapshot subscription of the store an
|
|
6
|
+
* aggregate type's snapshot queries read: its copy's where it has one, else
|
|
7
|
+
* its own store's, as `snapshot` is.
|
|
8
|
+
*/
|
|
9
|
+
export declare const QUERYABLE_SUBSCRIPTION = "wow.queryable";
|
|
4
10
|
/**
|
|
5
11
|
* Builds the hops of a wait chain. A context left out is
|
|
6
12
|
* the command's own. A saga's `handled` hop may be followed by hops of the
|
|
@@ -22,13 +28,20 @@ export declare const wait: {
|
|
|
22
28
|
readonly committed: (context?: string) => Hop;
|
|
23
29
|
/** Until the snapshot holds the commit: the caller reads its own write. */
|
|
24
30
|
readonly snapshot: (context?: string) => Hop;
|
|
31
|
+
/**
|
|
32
|
+
* Until the store the aggregate type's snapshot queries read holds the
|
|
33
|
+
* commit: a list or a count the caller runs next sees it. The same as
|
|
34
|
+
* `snapshot` for a type whose queries read its own store.
|
|
35
|
+
*/
|
|
36
|
+
readonly queryable: (context?: string) => Hop;
|
|
25
37
|
/** Until the subscription named `processor.function` handled the commit. */
|
|
26
38
|
readonly handled: (subscription: string, context?: string) => Hop;
|
|
27
39
|
};
|
|
28
40
|
/**
|
|
29
|
-
* A hop as `Wow-Wait` spells it: `accepted`, `committed`, `snapshot
|
|
30
|
-
* `handled(subscription)`, each with its context when it has
|
|
31
|
-
* `committed(ctx)`, `snapshot(ctx)`, `
|
|
41
|
+
* A hop as `Wow-Wait` spells it: `accepted`, `committed`, `snapshot`,
|
|
42
|
+
* `queryable` and `handled(subscription)`, each with its context when it has
|
|
43
|
+
* one: `committed(ctx)`, `snapshot(ctx)`, `queryable(ctx)`,
|
|
44
|
+
* `handled(ctx/subscription)`.
|
|
32
45
|
*
|
|
33
46
|
* @param value - The hop
|
|
34
47
|
*/
|
|
@@ -87,7 +100,7 @@ export declare class WaitPlan {
|
|
|
87
100
|
export declare function formatWaitPlan(plan: WaitPlan): string;
|
|
88
101
|
/**
|
|
89
102
|
* The plan a `Wow-Wait` value spells, as the service reads it: hops
|
|
90
|
-
* separated by `>`, each `accepted`, `committed`, `snapshot` or
|
|
103
|
+
* separated by `>`, each `accepted`, `committed`, `snapshot`, `queryable` or
|
|
91
104
|
* `handled(subscription)`, with its context in parentheses
|
|
92
105
|
* (`committed(ctx)`, `handled(ctx/subscription)`); the inverse of
|
|
93
106
|
* {@link formatWaitPlan}. Throws a `TypeError` for anything else.
|
package/dist/wait.d.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { Hop } from './wire.js';
|
|
2
2
|
/** The name of the built-in subscription that writes snapshots. */
|
|
3
3
|
export declare const SNAPSHOT_SUBSCRIPTION = "wow.snapshot";
|
|
4
|
+
/**
|
|
5
|
+
* The name a `queryable` hop gives the snapshot subscription of the store an
|
|
6
|
+
* aggregate type's snapshot queries read: its copy's where it has one, else
|
|
7
|
+
* its own store's, as `snapshot` is.
|
|
8
|
+
*/
|
|
9
|
+
export declare const QUERYABLE_SUBSCRIPTION = "wow.queryable";
|
|
4
10
|
/**
|
|
5
11
|
* Builds the hops of a wait chain. A context left out is
|
|
6
12
|
* the command's own. A saga's `handled` hop may be followed by hops of the
|
|
@@ -22,13 +28,20 @@ export declare const wait: {
|
|
|
22
28
|
readonly committed: (context?: string) => Hop;
|
|
23
29
|
/** Until the snapshot holds the commit: the caller reads its own write. */
|
|
24
30
|
readonly snapshot: (context?: string) => Hop;
|
|
31
|
+
/**
|
|
32
|
+
* Until the store the aggregate type's snapshot queries read holds the
|
|
33
|
+
* commit: a list or a count the caller runs next sees it. The same as
|
|
34
|
+
* `snapshot` for a type whose queries read its own store.
|
|
35
|
+
*/
|
|
36
|
+
readonly queryable: (context?: string) => Hop;
|
|
25
37
|
/** Until the subscription named `processor.function` handled the commit. */
|
|
26
38
|
readonly handled: (subscription: string, context?: string) => Hop;
|
|
27
39
|
};
|
|
28
40
|
/**
|
|
29
|
-
* A hop as `Wow-Wait` spells it: `accepted`, `committed`, `snapshot
|
|
30
|
-
* `handled(subscription)`, each with its context when it has
|
|
31
|
-
* `committed(ctx)`, `snapshot(ctx)`, `
|
|
41
|
+
* A hop as `Wow-Wait` spells it: `accepted`, `committed`, `snapshot`,
|
|
42
|
+
* `queryable` and `handled(subscription)`, each with its context when it has
|
|
43
|
+
* one: `committed(ctx)`, `snapshot(ctx)`, `queryable(ctx)`,
|
|
44
|
+
* `handled(ctx/subscription)`.
|
|
32
45
|
*
|
|
33
46
|
* @param value - The hop
|
|
34
47
|
*/
|
|
@@ -87,7 +100,7 @@ export declare class WaitPlan {
|
|
|
87
100
|
export declare function formatWaitPlan(plan: WaitPlan): string;
|
|
88
101
|
/**
|
|
89
102
|
* The plan a `Wow-Wait` value spells, as the service reads it: hops
|
|
90
|
-
* separated by `>`, each `accepted`, `committed`, `snapshot` or
|
|
103
|
+
* separated by `>`, each `accepted`, `committed`, `snapshot`, `queryable` or
|
|
91
104
|
* `handled(subscription)`, with its context in parentheses
|
|
92
105
|
* (`committed(ctx)`, `handled(ctx/subscription)`); the inverse of
|
|
93
106
|
* {@link formatWaitPlan}. Throws a `TypeError` for anything else.
|