@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.
- package/README.md +77 -23
- package/README.zh-CN.md +67 -19
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +134 -61
- package/dist/commands.d.ts +134 -61
- package/dist/commands.es.js +129 -59
- package/dist/commands.es.js.map +1 -1
- package/dist/developmentCaller.cjs +2 -0
- package/dist/developmentCaller.cjs.map +1 -0
- package/dist/developmentCaller.d.cts +61 -0
- package/dist/developmentCaller.d.ts +61 -0
- package/dist/developmentCaller.es.js +26 -0
- package/dist/developmentCaller.es.js.map +1 -0
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +93 -93
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +20 -20
- package/dist/dsl/aggregation/builders.d.ts +20 -20
- package/dist/dsl/aggregation/builders.es.js +88 -88
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +8 -8
- package/dist/dsl/aggregation/derived.d.ts +8 -8
- package/dist/dsl/aggregation/derived.es.js +1 -2
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +12 -12
- package/dist/dsl/aggregation/having.d.ts +12 -12
- package/dist/dsl/aggregation/having.es.js +33 -33
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/sort.cjs.map +1 -1
- package/dist/dsl/aggregation/sort.es.js +1 -2
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +69 -69
- package/dist/dsl/aggregation/types.d.ts +69 -69
- package/dist/dsl/aggregation/types.es.js +15 -16
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/constantName.cjs +2 -0
- package/dist/dsl/constantName.cjs.map +1 -0
- package/dist/dsl/constantName.d.cts +9 -0
- package/dist/dsl/constantName.d.ts +9 -0
- package/dist/dsl/constantName.es.js +7 -0
- package/dist/dsl/constantName.es.js.map +1 -0
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.es.js +1 -2
- package/dist/dsl/deletionState.cjs +1 -1
- package/dist/dsl/deletionState.cjs.map +1 -1
- package/dist/dsl/deletionState.d.cts +3 -3
- package/dist/dsl/deletionState.d.ts +3 -3
- package/dist/dsl/deletionState.es.js +2 -3
- package/dist/dsl/deletionState.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 +99 -42
- package/dist/dsl/descriptor.d.ts +99 -42
- package/dist/dsl/descriptor.es.js +37 -29
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/field.cjs.map +1 -1
- package/dist/dsl/field.es.js +1 -2
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +53 -53
- package/dist/dsl/filter/builders.d.ts +53 -53
- package/dist/dsl/filter/builders.es.js +111 -111
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/datePattern.cjs.map +1 -1
- package/dist/dsl/filter/datePattern.es.js +1 -2
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +57 -57
- package/dist/dsl/filter/operator.d.ts +57 -57
- package/dist/dsl/filter/operator.es.js +4 -5
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/scope.cjs +1 -1
- package/dist/dsl/filter/scope.cjs.map +1 -1
- package/dist/dsl/filter/scope.es.js +12 -12
- package/dist/dsl/filter/scope.es.js.map +1 -1
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.es.js +23 -23
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/pagination.cjs.map +1 -1
- package/dist/dsl/pagination.es.js +1 -2
- package/dist/dsl/projection.cjs.map +1 -1
- package/dist/dsl/projection.d.cts +1 -1
- package/dist/dsl/projection.d.ts +1 -1
- package/dist/dsl/projection.es.js +1 -2
- package/dist/dsl/projection.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 +59 -48
- package/dist/dsl/queryErrorCodes.d.ts +59 -48
- package/dist/dsl/queryErrorCodes.es.js +51 -50
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.d.cts +25 -21
- package/dist/dsl/queryable.d.ts +25 -21
- package/dist/dsl/queryable.es.js +5 -5
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/sort.cjs +1 -1
- package/dist/dsl/sort.cjs.map +1 -1
- package/dist/dsl/sort.d.cts +2 -2
- package/dist/dsl/sort.d.ts +2 -2
- package/dist/dsl/sort.es.js +4 -5
- package/dist/dsl/sort.es.js.map +1 -1
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.es.js +3 -3
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +4 -4
- package/dist/exactJson.d.ts +4 -4
- package/dist/exactJson.es.js +1 -2
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs +2 -0
- package/dist/frameworkErrors.cjs.map +1 -0
- package/dist/frameworkErrors.d.cts +121 -0
- package/dist/frameworkErrors.d.ts +121 -0
- package/dist/frameworkErrors.es.js +95 -0
- package/dist/frameworkErrors.es.js.map +1 -0
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +4 -7
- package/dist/http.d.ts +4 -7
- package/dist/http.es.js +12 -20
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -7
- package/dist/index.d.ts +9 -7
- package/dist/index.es.js +11 -9
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +37 -95
- package/dist/manifest.d.ts +37 -95
- package/dist/manifest.es.js +12 -7
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +195 -0
- package/dist/manifestTypes.d.ts +195 -0
- package/dist/problem.cjs +1 -1
- package/dist/problem.cjs.map +1 -1
- package/dist/problem.d.cts +76 -115
- package/dist/problem.d.ts +76 -115
- package/dist/problem.es.js +45 -80
- package/dist/problem.es.js.map +1 -1
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +28 -51
- package/dist/queries.d.ts +28 -51
- package/dist/queries.es.js +49 -40
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +2 -0
- package/dist/routes.cjs.map +1 -0
- package/dist/routes.d.cts +49 -0
- package/dist/routes.d.ts +49 -0
- package/dist/routes.es.js +33 -0
- package/dist/routes.es.js.map +1 -0
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +56 -11
- package/dist/state.d.ts +56 -11
- package/dist/state.es.js +56 -21
- 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 +17 -13
- package/dist/streams.d.ts +17 -13
- package/dist/streams.es.js +50 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +2 -0
- package/dist/testing/wire.cjs.map +1 -0
- package/dist/testing/wire.d.cts +29 -0
- package/dist/testing/wire.d.ts +29 -0
- package/dist/testing/wire.es.js +88 -0
- package/dist/testing/wire.es.js.map +1 -0
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +12 -0
- package/dist/testing.d.ts +12 -0
- package/dist/testing.es.js +3 -0
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +68 -19
- package/dist/wait.d.ts +68 -19
- package/dist/wait.es.js +61 -14
- 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 +101 -50
- package/dist/wire.d.ts +101 -50
- package/dist/wire.es.js +17 -6
- package/dist/wire.es.js.map +1 -1
- package/package.json +23 -3
package/dist/commands.d.ts
CHANGED
|
@@ -1,35 +1,99 @@
|
|
|
1
1
|
import { TextNumbers } from './exactJson.js';
|
|
2
|
-
import { RequestOptions, WowClientOptions } from './http.js';
|
|
3
|
-
import { CommandResult } from './wire.js';
|
|
2
|
+
import { RequestOptions, TargetScope, WowClientOptions } from './http.js';
|
|
3
|
+
import { AggregateType, CommandResult } from './wire.js';
|
|
4
|
+
import { RoutingManifest } from './manifest.js';
|
|
4
5
|
import { CommandResultStream } from './streams.js';
|
|
5
|
-
import {
|
|
6
|
-
/**
|
|
7
|
-
|
|
6
|
+
import { WaitPlan } from './wait.js';
|
|
7
|
+
/**
|
|
8
|
+
* One command a {@link CommandClient} sends, and how: the TypeScript
|
|
9
|
+
* `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same
|
|
10
|
+
* fields. Kotlin's `command` is the command object, whose class names it;
|
|
11
|
+
* here `command` is the command's name and `body` its payload, as the wire
|
|
12
|
+
* carries them.
|
|
13
|
+
*
|
|
14
|
+
* - `command`: the full type name, `context.aggregate.Command`, which names
|
|
15
|
+
* the aggregate type too; or a system command (`wow.*`, a lifecycle command
|
|
16
|
+
* of {@link LifecycleCommands} among them), which needs `type`.
|
|
17
|
+
* - `id`: the aggregate's id. Absent when the command names no aggregate id:
|
|
18
|
+
* a creation, whose id the server assigns, an `@Unaddressed` command, or
|
|
19
|
+
* any command of an aggregate whose id is its owner's (the Manifest's
|
|
20
|
+
* `idSource: "owner"`), which goes to the caller's own; the route without
|
|
21
|
+
* `{id}` then sends it. A command whose body names its aggregate (the
|
|
22
|
+
* Manifest's `idProperty`) goes by that route too, whether `id` is given or
|
|
23
|
+
* not: a given one is the one its body names, or is written into a body
|
|
24
|
+
* that names none.
|
|
25
|
+
* - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to
|
|
26
|
+
* act across scopes acts in (`Wow-Scope`); the caller's own when absent.
|
|
27
|
+
* - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds
|
|
28
|
+
* (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command
|
|
29
|
+
* waits with is `wait` within `timeout`, the server's default plan when
|
|
30
|
+
* only a timeout is given, and the server's default without either.
|
|
31
|
+
* - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).
|
|
32
|
+
*/
|
|
33
|
+
export interface CommandRequest extends Omit<RequestOptions, 'scope'> {
|
|
34
|
+
/** The command's full type name, or a system command's. */
|
|
35
|
+
readonly command: string;
|
|
36
|
+
/** The command's body; `{}` when absent. */
|
|
37
|
+
readonly body?: object;
|
|
38
|
+
/**
|
|
39
|
+
* The aggregate's id; absent for a creation, an unaddressed command or the
|
|
40
|
+
* caller's own aggregate of one whose id is its owner's.
|
|
41
|
+
*/
|
|
42
|
+
readonly id?: string;
|
|
43
|
+
/**
|
|
44
|
+
* The aggregate type, which `command` names unless it is a system command:
|
|
45
|
+
* then it is required.
|
|
46
|
+
*/
|
|
47
|
+
readonly type?: AggregateType;
|
|
48
|
+
/** The tenant to act in, for a caller allowed to (`Wow-Scope`). */
|
|
49
|
+
readonly targetTenant?: string;
|
|
50
|
+
/** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */
|
|
51
|
+
readonly targetScope?: Omit<TargetScope, 'tenantId'>;
|
|
52
|
+
/**
|
|
53
|
+
* Not a command's: a query's `Wow-Scope`. A command names the scope it acts
|
|
54
|
+
* in with `targetTenant` and `targetScope`, so a query's options spread into
|
|
55
|
+
* a command's fail to compile rather than drop their scope.
|
|
56
|
+
*/
|
|
57
|
+
readonly scope?: never;
|
|
58
|
+
/** How far to wait for the command (`Wow-Wait`). */
|
|
59
|
+
readonly wait?: WaitPlan;
|
|
60
|
+
/** How long to wait, in milliseconds, over the plan's own timeout. */
|
|
61
|
+
readonly timeout?: number;
|
|
8
62
|
/**
|
|
9
63
|
* The request id (`Wow-Request-Id`): a retry with the same one is
|
|
10
64
|
* deduplicated, answered as the first commit's duplicate. When absent, the
|
|
11
|
-
*
|
|
12
|
-
* ({@link requestIdOf})
|
|
65
|
+
* client generates one ({@link newRequestId}), which a failure carries
|
|
66
|
+
* ({@link requestIdOf}). A request sent again without one is another
|
|
67
|
+
* request: for an application-level retry, set it (or keep the one the
|
|
68
|
+
* failure or the first result carries) and send that request again.
|
|
13
69
|
*/
|
|
14
70
|
readonly requestId?: string;
|
|
15
|
-
/** What to wait for, and for how long. */
|
|
16
|
-
readonly wait?: WaitOptions;
|
|
17
71
|
/** The version the aggregate must be at (`If-Match`). */
|
|
18
72
|
readonly expectedVersion?: number;
|
|
73
|
+
}
|
|
74
|
+
/** How a {@link CommandClient} sends, beside how it reaches the service. */
|
|
75
|
+
export interface CommandClientOptions {
|
|
19
76
|
/**
|
|
20
|
-
* The
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* `
|
|
77
|
+
* The Manifest whose routes send each command: a whole Manifest, or the
|
|
78
|
+
* routing part a generated client carries (`manifest.ts`). Without it the
|
|
79
|
+
* client fetches the service's once, when it first sends
|
|
80
|
+
* (`GET /wow/manifest`), and again after a failed fetch.
|
|
24
81
|
*/
|
|
25
|
-
readonly
|
|
82
|
+
readonly manifest?: RoutingManifest;
|
|
26
83
|
/**
|
|
27
|
-
*
|
|
28
|
-
*
|
|
84
|
+
* The body numbers each command writes as their exact text, unquoted JSON
|
|
85
|
+
* numbers (decision D122), by the command's full type name: a generated
|
|
86
|
+
* client sets them for commands with `int64`, `bigint` or `decimal` fields,
|
|
87
|
+
* which it types as `string`.
|
|
29
88
|
*/
|
|
30
|
-
readonly
|
|
89
|
+
readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;
|
|
31
90
|
}
|
|
32
|
-
/**
|
|
91
|
+
/**
|
|
92
|
+
* The options of a generated client's command method: a {@link CommandRequest}
|
|
93
|
+
* without what the method fixes, its command, body and type.
|
|
94
|
+
*/
|
|
95
|
+
export type CommandOptions = Omit<CommandRequest, 'command' | 'body' | 'type' | 'id'>;
|
|
96
|
+
/** The options of a command that may create its aggregate, with its id or not. */
|
|
33
97
|
export interface CreateCommandOptions extends CommandOptions {
|
|
34
98
|
/**
|
|
35
99
|
* The id of the aggregate to create (decision D176); the service generates
|
|
@@ -37,7 +101,7 @@ export interface CreateCommandOptions extends CommandOptions {
|
|
|
37
101
|
*/
|
|
38
102
|
readonly id?: string;
|
|
39
103
|
}
|
|
40
|
-
/** The lifecycle commands an aggregate may list
|
|
104
|
+
/** The lifecycle commands an aggregate may list. */
|
|
41
105
|
export declare const LifecycleCommands: {
|
|
42
106
|
readonly DELETE_AGGREGATE: "wow.lifecycle.DeleteAggregate";
|
|
43
107
|
readonly RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate";
|
|
@@ -60,64 +124,73 @@ export interface ApplyTags {
|
|
|
60
124
|
readonly tags: Readonly<Record<string, readonly string[]>>;
|
|
61
125
|
}
|
|
62
126
|
/**
|
|
63
|
-
*
|
|
64
|
-
* dots kept (`AddCartItem` → `add-cart-item`,
|
|
65
|
-
* `wow.lifecycle.RestoreAggregate` → `wow.lifecycle.restore-aggregate`).
|
|
66
|
-
*
|
|
67
|
-
* @param name - The command's name
|
|
68
|
-
*/
|
|
69
|
-
export declare function commandSegment(name: string): string;
|
|
70
|
-
/**
|
|
71
|
-
* A new request id (`Wow-Request-Id`): a random UUID. The gateway generates
|
|
127
|
+
* A new request id (`Wow-Request-Id`): a random UUID. The client generates
|
|
72
128
|
* one for a command sent without; generate it first to retry with it however
|
|
73
129
|
* the request fails.
|
|
74
130
|
*/
|
|
75
131
|
export declare function newRequestId(): string;
|
|
76
132
|
/**
|
|
77
|
-
* Sends commands to the command routes of a Wow service
|
|
78
|
-
* (`POST /{context}/{aggregate}/{id}/{command}`,
|
|
79
|
-
*
|
|
80
|
-
*
|
|
133
|
+
* Sends commands to the command routes of a Wow service as its Manifest lists
|
|
134
|
+
* them (`POST /{context}/{aggregate}/{id}/{command}`, the route without
|
|
135
|
+
* `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`
|
|
136
|
+
* for `DeleteAggregate`): the Manifest the client is given, else the
|
|
137
|
+
* service's, fetched once (`GET /wow/manifest`). The TypeScript
|
|
138
|
+
* `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers
|
|
139
|
+
* once the command is accepted, {@link wait} with the result its wait plan
|
|
140
|
+
* ends with, {@link stream} with one result per hop. Generated aggregate
|
|
141
|
+
* clients build on it.
|
|
81
142
|
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
143
|
+
* `send` and `wait` resolve only a result that succeeded. A rejected one,
|
|
144
|
+
* by the aggregate or at admission, rejects with a
|
|
145
|
+
* {@link CommandRejectedError}; anything else that did not succeed with a
|
|
146
|
+
* {@link WowProblemError} (the table on {@link CommandRejectedError} says
|
|
147
|
+
* which). Every command carries a request id, the request's or a generated
|
|
148
|
+
* one, and whatever it rejects with carries that id ({@link requestIdOf}).
|
|
86
149
|
*/
|
|
87
|
-
export declare class
|
|
150
|
+
export declare class CommandClient {
|
|
88
151
|
readonly client: WowClientOptions;
|
|
89
|
-
|
|
90
|
-
|
|
152
|
+
private manifest;
|
|
153
|
+
private readonly bodyNumbers;
|
|
91
154
|
/**
|
|
92
|
-
*
|
|
93
|
-
*
|
|
155
|
+
* @param client - How the service is reached
|
|
156
|
+
* @param options - The service's Manifest, and the commands' exact numbers
|
|
157
|
+
*/
|
|
158
|
+
constructor(client?: WowClientOptions, options?: CommandClientOptions);
|
|
159
|
+
/**
|
|
160
|
+
* Sends a command and answers once it is accepted (202), within the
|
|
161
|
+
* request's timeout (10 seconds without one), as Kotlin's
|
|
162
|
+
* `CommandClient.send`. A request whose `wait` waits for more rejects with a
|
|
163
|
+
* `TypeError` before it is sent: {@link wait} answers with that plan's result.
|
|
94
164
|
*
|
|
95
|
-
* @param
|
|
96
|
-
* @param body - The command's body; `{}` when absent
|
|
97
|
-
* @param options - Headers, wait and the aggregate id
|
|
165
|
+
* @param request - The command and how to send it
|
|
98
166
|
*/
|
|
99
|
-
send<R = Record<string, unknown>>(
|
|
167
|
+
send<R = Record<string, unknown>>(request: CommandRequest): Promise<CommandResult<R>>;
|
|
100
168
|
/**
|
|
101
|
-
* Sends a command
|
|
102
|
-
*
|
|
103
|
-
*
|
|
169
|
+
* Sends a command and answers the result its wait plan ends with: 200, or
|
|
170
|
+
* 202 for a plan that ends at `accepted`. Without a plan, the server's
|
|
171
|
+
* default: the snapshot, or the commit where the aggregate keeps no
|
|
172
|
+
* snapshot (decision D69).
|
|
104
173
|
*
|
|
105
|
-
* @param
|
|
106
|
-
* @param body - The command's body; `{}` when absent
|
|
107
|
-
* @param options - Headers, wait and the aggregate id
|
|
174
|
+
* @param request - The command and how to send it
|
|
108
175
|
*/
|
|
109
|
-
|
|
176
|
+
wait<R = Record<string, unknown>>(request: CommandRequest): Promise<CommandResult<R>>;
|
|
110
177
|
/**
|
|
111
|
-
* Sends a
|
|
112
|
-
*
|
|
113
|
-
*
|
|
178
|
+
* Sends a command with `Accept: text/event-stream` and answers one result
|
|
179
|
+
* per hop as the wait advances, whatever its status. An admission refusal
|
|
180
|
+
* rejects with its problem; a rejection after admission is the stream's
|
|
181
|
+
* last result.
|
|
114
182
|
*
|
|
115
|
-
* @param
|
|
116
|
-
* @param id - The aggregate's id
|
|
117
|
-
* @param command - The lifecycle command
|
|
118
|
-
* @param body - Its body, for the commands that have one
|
|
119
|
-
* @param options - Headers and wait
|
|
183
|
+
* @param request - The command and how to send it
|
|
120
184
|
*/
|
|
121
|
-
|
|
185
|
+
stream<R = Record<string, unknown>>(request: CommandRequest): Promise<CommandResultStream<R>>;
|
|
186
|
+
private exchange;
|
|
122
187
|
private post;
|
|
188
|
+
/**
|
|
189
|
+
* `request`'s command as the Manifest lists it, with its routes: a domain
|
|
190
|
+
* command among its aggregate's commands, by name or former name; a system
|
|
191
|
+
* command among its type's, else among its context's (a job's).
|
|
192
|
+
*/
|
|
193
|
+
private commandOf;
|
|
194
|
+
/** The Manifest given, or the service's, fetched once (again after a failure). */
|
|
195
|
+
private manifestOf;
|
|
123
196
|
}
|
package/dist/commands.es.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import { FrameworkErrorCodes as e } from "./frameworkErrors.es.js";
|
|
2
|
+
import { CommandResultStatus as t, Stage as n } from "./wire.es.js";
|
|
3
|
+
import { CommandRejectedError as r, WowProblemError as i, rememberRequestId as a } from "./problem.es.js";
|
|
4
|
+
import { WowHeaders as o, json as s, send as c } from "./http.es.js";
|
|
5
|
+
import { checkManifest as l, fetchManifest as u } from "./manifest.es.js";
|
|
6
|
+
import { commandResults as d } from "./streams.es.js";
|
|
7
|
+
import { WaitPlan as f, formatWaitPlan as p, formatWaitTimeout as m } from "./wait.es.js";
|
|
8
|
+
// src/commands.ts
|
|
9
|
+
var h = {
|
|
7
10
|
DELETE_AGGREGATE: "wow.lifecycle.DeleteAggregate",
|
|
8
11
|
RESTORE_AGGREGATE: "wow.lifecycle.RestoreAggregate",
|
|
9
12
|
TRANSFER_OWNER: "wow.lifecycle.TransferOwner",
|
|
10
13
|
TRANSFER_SPACE: "wow.lifecycle.TransferSpace",
|
|
11
14
|
APPLY_TAGS: "wow.lifecycle.ApplyTags"
|
|
12
15
|
};
|
|
13
|
-
function
|
|
14
|
-
return e.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase();
|
|
15
|
-
}
|
|
16
|
-
function d() {
|
|
16
|
+
function g() {
|
|
17
17
|
let e = globalThis.crypto;
|
|
18
18
|
if (typeof e?.randomUUID == "function") return e.randomUUID();
|
|
19
19
|
let t = /* @__PURE__ */ new Uint8Array(16);
|
|
@@ -29,68 +29,138 @@ function d() {
|
|
|
29
29
|
n.slice(10, 16)
|
|
30
30
|
].map((e) => e.join("")).join("-");
|
|
31
31
|
}
|
|
32
|
-
async function
|
|
32
|
+
async function _(e, t) {
|
|
33
33
|
try {
|
|
34
|
-
return await
|
|
35
|
-
} catch (
|
|
36
|
-
throw t
|
|
34
|
+
return await t();
|
|
35
|
+
} catch (t) {
|
|
36
|
+
throw a(t, e), t;
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
var v = "wow.", y = "{id}";
|
|
40
|
+
function b(e) {
|
|
41
|
+
return e.hops.length === 1 && e.hops[0].stage === n.ACCEPTED;
|
|
42
|
+
}
|
|
43
|
+
function x(e) {
|
|
44
|
+
return e.timeout === void 0 ? e.wait : (e.wait ?? f.DEFAULT).within(e.timeout);
|
|
45
|
+
}
|
|
46
|
+
function S(e, t, n) {
|
|
47
|
+
let r = t.find((e) => e.path.includes(y) === (n !== void 0));
|
|
48
|
+
if (r === void 0) throw TypeError(n === void 0 ? `${e.command} has no route without an aggregate id: set the request's id.` : `${e.command} has no route to an aggregate by its id: send it without an id.`);
|
|
49
|
+
if (n === "") throw TypeError(`The path ${r.path} of ${e.command} needs id.`);
|
|
50
|
+
let i = r.method;
|
|
51
|
+
if (i !== "POST" && i !== "DELETE") throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);
|
|
52
|
+
return {
|
|
53
|
+
method: i,
|
|
54
|
+
path: n === void 0 ? r.path : r.path.replace(y, encodeURIComponent(n))
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function C(e, t) {
|
|
58
|
+
let n = e.body ?? {}, r = e.id;
|
|
59
|
+
if (t === void 0 || r === void 0) return n;
|
|
60
|
+
let i = n[t];
|
|
61
|
+
if (i == null) return {
|
|
62
|
+
...n,
|
|
63
|
+
[t]: r
|
|
64
|
+
};
|
|
65
|
+
if (i !== r) throw TypeError(`The request names the aggregate ${r}, but the body of ${e.command} names ${String(i)}: send it without an id.`);
|
|
66
|
+
return n;
|
|
67
|
+
}
|
|
68
|
+
function w(e) {
|
|
69
|
+
let t = e.split(".");
|
|
70
|
+
if (t.length < 3 || t.some((e) => e === "")) throw TypeError(`${e} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`);
|
|
71
|
+
return {
|
|
72
|
+
context: t[0],
|
|
73
|
+
name: t[1]
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function T(e, t, n, r) {
|
|
41
77
|
return {
|
|
42
|
-
[
|
|
43
|
-
[
|
|
44
|
-
[
|
|
45
|
-
[
|
|
78
|
+
[o.REQUEST_ID]: n,
|
|
79
|
+
[o.WAIT]: t === void 0 || t.isDefault ? void 0 : p(t),
|
|
80
|
+
[o.WAIT_TIMEOUT]: t !== void 0 && (e.timeout !== void 0 || t.timeout !== f.DEFAULT_TIMEOUT) ? m(t.timeout) : void 0,
|
|
81
|
+
[o.IF_MATCH]: e.expectedVersion === void 0 ? void 0 : `"${e.expectedVersion}"`,
|
|
46
82
|
Accept: r
|
|
47
83
|
};
|
|
48
84
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
85
|
+
function E(e) {
|
|
86
|
+
if (e.targetTenant !== void 0 || e.targetScope !== void 0) return {
|
|
87
|
+
tenantId: e.targetTenant,
|
|
88
|
+
...e.targetScope
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
var D = class {
|
|
92
|
+
constructor(e = {}, t = {}) {
|
|
93
|
+
this.client = e, this.manifest = t.manifest === void 0 ? void 0 : Promise.resolve(l(t.manifest)), this.bodyNumbers = t.bodyNumbers ?? {};
|
|
52
94
|
}
|
|
53
|
-
async send(
|
|
54
|
-
let
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
} catch (t) {
|
|
58
|
-
if (r.resolveRejected && t instanceof e && t.result !== void 0) return t.result;
|
|
59
|
-
throw t;
|
|
60
|
-
}
|
|
95
|
+
async send(e) {
|
|
96
|
+
let t = x(e);
|
|
97
|
+
if (t !== void 0 && !t.isDefault && !b(t)) throw TypeError(`send answers on acceptance: use wait() for the plan ${p(t)}.`);
|
|
98
|
+
return this.exchange(e, f.ACCEPTED.within(e.timeout ?? f.DEFAULT_TIMEOUT));
|
|
61
99
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return f(r, async () => o(await this.post(e, t, n, r, "text/event-stream")));
|
|
100
|
+
wait(e) {
|
|
101
|
+
return this.exchange(e, x(e));
|
|
65
102
|
}
|
|
66
|
-
async
|
|
67
|
-
let
|
|
68
|
-
|
|
69
|
-
let e = o.requestId ?? d();
|
|
70
|
-
return f(e, async () => {
|
|
71
|
-
let t = await a(this.client, {
|
|
72
|
-
method: "DELETE",
|
|
73
|
-
path: s,
|
|
74
|
-
headers: p(o, e),
|
|
75
|
-
options: o
|
|
76
|
-
});
|
|
77
|
-
return i(t);
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
return this.send(`${s}/${u(n)}`, r ?? {}, o);
|
|
103
|
+
async stream(e) {
|
|
104
|
+
let t = e.requestId ?? g();
|
|
105
|
+
return _(t, async () => d(await this.post(e, x(e), t, "text/event-stream")));
|
|
81
106
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
107
|
+
async exchange(e, n) {
|
|
108
|
+
let a = e.requestId ?? g();
|
|
109
|
+
return _(a, async () => {
|
|
110
|
+
let o;
|
|
111
|
+
try {
|
|
112
|
+
o = await s(await this.post(e, n, a));
|
|
113
|
+
} catch (e) {
|
|
114
|
+
throw e instanceof i && e.result?.status === t.REJECTED ? new r(e.result, {
|
|
115
|
+
problem: e.problem,
|
|
116
|
+
cause: e
|
|
117
|
+
}) : e;
|
|
118
|
+
}
|
|
119
|
+
return O(o);
|
|
90
120
|
});
|
|
91
121
|
}
|
|
122
|
+
async post(e, t, n, r) {
|
|
123
|
+
let i = await this.commandOf(e), a = i.idProperty, o = S(e, i.routes, a === void 0 ? e.id : void 0), s = E(e), l = this.bodyNumbers[e.command];
|
|
124
|
+
return c(this.client, {
|
|
125
|
+
method: o.method,
|
|
126
|
+
path: o.path,
|
|
127
|
+
headers: T(e, t, n, r),
|
|
128
|
+
...o.method === "DELETE" ? {} : { body: C(e, a) },
|
|
129
|
+
...l === void 0 ? {} : { bodyNumbers: l },
|
|
130
|
+
options: {
|
|
131
|
+
...s === void 0 ? {} : { scope: s },
|
|
132
|
+
...e.space === void 0 ? {} : { space: e.space },
|
|
133
|
+
...e.headers === void 0 ? {} : { headers: e.headers },
|
|
134
|
+
...e.signal === void 0 ? {} : { signal: e.signal }
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
async commandOf(e) {
|
|
139
|
+
let t = e.command, n = t.startsWith(v), r = e.type ?? (n ? void 0 : w(t));
|
|
140
|
+
if (r === void 0) throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);
|
|
141
|
+
let i = `${r.context}.${r.name}.`, a = t.startsWith(i) ? t.slice(i.length) : t, o = (await this.manifestOf()).contexts.find((e) => e.name === r.context), s = o?.aggregates?.find((e) => e.name === r.name)?.commands?.find((e) => e.name === a || e.aliases?.includes(a) === !0) ?? (n ? o?.commands?.find((e) => e.name === a) : void 0);
|
|
142
|
+
if (s?.routes === void 0) throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);
|
|
143
|
+
return s;
|
|
144
|
+
}
|
|
145
|
+
manifestOf() {
|
|
146
|
+
return this.manifest ??= u(this.client).catch((e) => {
|
|
147
|
+
throw this.manifest = void 0, e;
|
|
148
|
+
}), this.manifest;
|
|
149
|
+
}
|
|
92
150
|
};
|
|
93
|
-
|
|
94
|
-
|
|
151
|
+
function O(n) {
|
|
152
|
+
if (n.status === t.REJECTED) throw new r(n);
|
|
153
|
+
if (!k.has(n.status)) throw new i({
|
|
154
|
+
type: `urn:wow:error:${e.COMMAND_FAILED}`,
|
|
155
|
+
title: "Unknown command status",
|
|
156
|
+
status: 200,
|
|
157
|
+
code: e.COMMAND_FAILED,
|
|
158
|
+
detail: `The command was answered with the status ${n.status}, which this client does not know: the service is newer than this client, so upgrade it.`,
|
|
159
|
+
result: n
|
|
160
|
+
});
|
|
161
|
+
return n;
|
|
162
|
+
}
|
|
163
|
+
var k = new Set(Object.values(t));
|
|
164
|
+
export { D as CommandClient, h as LifecycleCommands, g as newRequestId };
|
|
95
165
|
|
|
96
166
|
//# sourceMappingURL=commands.es.js.map
|
package/dist/commands.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.es.js","names":["LifecycleCommands","commandSegment","name","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","rememberRequestId","requestId","commandHeaders","wait","options","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","CommandGateway","client","json","path","body","WowProblemError","commandResults","base","aggregatePath","id","command","response","send","expandPath"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n expandPath,\n json,\n type RequestOptions,\n send,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport type { CommandResult } from './wire.js';\nimport { rememberRequestId, WowProblemError } from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, type WaitOptions } from './wait.js';\n\n/** What a command request carries beside its body (decisions D95–D99). */\nexport interface CommandOptions extends RequestOptions {\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * gateway generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}): retry with it, not with a new one.\n */\n readonly requestId?: string;\n /** What to wait for, and for how long. */\n readonly wait?: WaitOptions;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n /**\n * The body's numbers written as their exact text, unquoted JSON numbers\n * (review R4-Q, Q-9; decision D122): a generated client sets it for a\n * command with `int64`, `bigint` or `decimal` fields, which it types as\n * `string`.\n */\n readonly bodyNumbers?: TextNumbers;\n /**\n * Resolve a result that did not succeed instead of rejecting with its\n * {@link WowProblemError}; `false` by default.\n */\n readonly resolveRejected?: boolean;\n}\n\n/** The options of a command whose route may name the aggregate id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list (decision D113). */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * The route segment of a command name, as the server derives it: kebab case,\n * dots kept (`AddCartItem` → `add-cart-item`,\n * `wow.lifecycle.RestoreAggregate` → `wow.lifecycle.restore-aggregate`).\n *\n * @param name - The command's name\n */\nexport function commandSegment(name: string): string {\n return name\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/[_\\s]+/g, '-')\n .toLowerCase();\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The gateway generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\nfunction commandHeaders(\n options: CommandOptions,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n const wait = options.wait;\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n [WowHeaders.WAIT]:\n wait?.plan === undefined ? undefined : formatWaitPlan(wait.plan),\n [WowHeaders.WAIT_TIMEOUT]:\n wait?.timeout === undefined ? undefined : formatWaitTimeout(wait.timeout),\n [WowHeaders.IF_MATCH]:\n options.expectedVersion === undefined\n ? undefined\n : `\"${options.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/**\n * Sends commands to the command routes of a Wow service\n * (`POST /{context}/{aggregate}/{id}/{command}`, and without `{id}` for a\n * command that may create its aggregate). Generated aggregate clients build\n * on it; it serves any route too.\n *\n * A command that did not succeed rejects with a {@link WowProblemError}\n * holding its result, unless the options resolve it. Every command carries a\n * request id, the options' or a generated one, and whatever it rejects with\n * carries that id ({@link requestIdOf}).\n */\nexport class CommandGateway {\n /** @param client - How the service is reached */\n constructor(readonly client: WowClientOptions = {}) {}\n\n /**\n * Sends a command and answers the result its wait ends with: 200, or 202\n * for a plan that ends at `accepted`.\n *\n * @param path - The route, `{id}` filled from `id`\n * @param body - The command's body; `{}` when absent\n * @param options - Headers, wait and the aggregate id\n */\n async send<R = Record<string, unknown>>(\n path: string,\n body?: object,\n options: CreateCommandOptions = {},\n ): Promise<CommandResult<R>> {\n const requestId = options.requestId ?? newRequestId();\n try {\n return await withRequestId(requestId, async () =>\n json<CommandResult<R>>(await this.post(path, body, options, requestId)),\n );\n } catch (error) {\n if (\n options.resolveRejected &&\n error instanceof WowProblemError &&\n error.result !== undefined\n ) {\n return error.result as CommandResult<R>;\n }\n throw error;\n }\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances. An admission refusal rejects with its\n * problem; a rejection after admission is the stream's last result.\n *\n * @param path - The route, `{id}` filled from `id`\n * @param body - The command's body; `{}` when absent\n * @param options - Headers, wait and the aggregate id\n */\n async stream<R = Record<string, unknown>>(\n path: string,\n body?: object,\n options: CreateCommandOptions = {},\n ): Promise<CommandResultStream<R>> {\n const requestId = options.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(path, body, options, requestId, 'text/event-stream'),\n ),\n );\n }\n\n /**\n * Sends a lifecycle command an aggregate lists: `DELETE\n * /{context}/{aggregate}/{id}` for `DeleteAggregate`, `POST\n * …/{id}/wow.lifecycle.<kebab>` for the others.\n *\n * @param aggregatePath - `/{context}/{aggregate}`\n * @param id - The aggregate's id\n * @param command - The lifecycle command\n * @param body - Its body, for the commands that have one\n * @param options - Headers and wait\n */\n async lifecycle<R = Record<string, unknown>>(\n aggregatePath: string,\n id: string,\n command: LifecycleCommand,\n body?: TransferOwner | TransferSpace | ApplyTags,\n options: CommandOptions = {},\n ): Promise<CommandResult<R>> {\n const base = `${aggregatePath}/${encodeURIComponent(id)}`;\n if (command === LifecycleCommands.DELETE_AGGREGATE) {\n const requestId = options.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n const response = await send(this.client, {\n method: 'DELETE',\n path: base,\n headers: commandHeaders(options, requestId),\n options,\n });\n return json<CommandResult<R>>(response);\n });\n }\n return this.send<R>(\n `${base}/${commandSegment(command)}`,\n body ?? {},\n options,\n );\n }\n\n private post(\n path: string,\n body: object | undefined,\n options: CreateCommandOptions,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n return send(this.client, {\n method: 'POST',\n path: path.includes('{id}')\n ? expandPath(path, { id: options.id ?? '' })\n : path,\n headers: commandHeaders(options, requestId, accept),\n body: body ?? {},\n ...(options.bodyNumbers === undefined\n ? {}\n : { b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H,CAAS;KAC1C;IACF,CAAC;IACD,OAAOU,EAAuBS,CAAQ;GACxC,CAAC;EACH;EACA,OAAO,KAAK,KACV,GAAGJ,EAAK,GAAG5B,EAAe+B,CAAO,KACjCN,KAAQ,CAAC,GACTT,CACF;CACF;CAEA,KACE,GACA,GACA,GACA,GACA,GACmB;EACnB,OAAOiB,EAAK,KAAK,QAAQ;GACvB,QAAQ;GACR,MAAMT,EAAK,SAAS,MAAM,IACtBU,EAAWV,GAAM,EAAE,IAAIR,EAAQ,MAAM,GAAG,CAAC,IACzCQ;GACJ,SAASV,EAAeE,GAASH,GAAWO,CAAM;GAClD,MAAMK,KAAQ,CAAC;GACf,GAAIT,EAAQ,gBAAgB,KAAA,IACxB,CAAC,IACD,EAAE,aAAaA,EAAQ,YAAY;GACvC;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"commands.es.js","names":["LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","rememberRequestId","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","Stage","planOf","request","WaitPlan","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","options","checkManifest","commandResults","result","json","WowProblemError","CommandResultStatus","CommandRejectedError","settled","declared","scope","bodyNumbers","send","system","type","prefix","name","context","aggregate","fetchManifest","KNOWN_STATUSES","FrameworkErrorCodes"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n json,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n checkManifest,\n fetchManifest,\n type RouteManifest,\n type RoutingCommand,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it. A command whose body names its aggregate (the\n * Manifest's `idProperty`) goes by that route too, whether `id` is given or\n * not: a given one is the one its body names, or is written into a body\n * that names none.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/**\n * The route of `request` among `routes`, by `id` (the request's, none for a\n * command whose body names its aggregate): its method and path, the id in it.\n * An empty id is refused before anything is sent: it would leave the path's\n * segment empty (`/<context>/<aggregate>//…`), a route no service has.\n */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n id: string | undefined,\n): { method: 'POST' | 'DELETE'; path: string } {\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n if (id === '') {\n throw new TypeError(\n `The path ${route.path} of ${request.command} needs id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/**\n * The body `request` sends, `{}` when it has none. Of a command whose body\n * names its aggregate in `idProperty`, the route has no id: the request's id,\n * when it names one, is the body's too, written into a body that names none.\n *\n * @throws TypeError when the body names another aggregate than the request\n */\nfunction bodyOf(\n request: CommandRequest,\n idProperty: string | undefined,\n): object {\n const body = request.body ?? {};\n const id = request.id;\n if (idProperty === undefined || id === undefined) return body;\n const named: unknown = (body as Record<string, unknown>)[idProperty];\n if (named === undefined || named === null) {\n return { ...body, [idProperty]: id };\n }\n if (named !== id) {\n throw new TypeError(\n `The request names the aggregate ${id}, but the body of ${request.command} names ${String(named)}: send it without an id.`,\n );\n }\n return body;\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private manifest: Promise<RoutingManifest> | undefined;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await json<CommandResult<R>>(\n await this.post(request, plan, requestId),\n );\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n const declared = await this.commandOf(request);\n const idProperty = declared.idProperty;\n const route = routeOf(\n request,\n declared.routes,\n idProperty === undefined ? request.id : undefined,\n );\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE'\n ? {}\n : { body: bodyOf(request, idProperty) }),\n ...(bodyNumbers === undefined ? {} : { bodyNumbers }),\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * `request`'s command as the Manifest lists it, with its routes: a domain\n * command among its aggregate's commands, by name or former name; a system\n * command among its type's, else among its context's (a job's).\n */\n private async commandOf(request: CommandRequest): Promise<RoutingCommand> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifestOf()).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared;\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":";;;;;;;;AAsJA,IAAaA,IAAoB;CAC/B,kBAAkB;CAClB,mBAAmB;CACnB,gBAAgB;CAChB,gBAAgB;CAChB,YAAY;AACd;AA0BA,SAAgBC,IAAuB;CACrC,IAAMC,IAAS,WAAW;CAC1B,IAAI,OAAOA,GAAQ,cAAe,YAAY,OAAOA,EAAO,WAAW;CAEvE,IAAMC,oBAAQ,IAAI,WAAW,EAAE;CAC/B,IAAI,OAAOD,GAAQ,mBAAoB,YACrC,EAAO,gBAAgBC,CAAK;MAE5B,KAAK,IAAIC,IAAQ,GAAGA,IAAQD,EAAM,QAAQ,KACxC,EAAMC,KAAS,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;CAIjD,AADA,EAAM,KAAMD,EAAM,KAAK,KAAQ,IAC/B,EAAM,KAAMA,EAAM,KAAK,KAAQ;CAC/B,IAAME,IAAM,MAAM,KAAKF,IAAO,MAAQG,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC;CACxE,OAAO;EACLD,EAAI,MAAM,GAAG,CAAC;EACdA,EAAI,MAAM,GAAG,CAAC;EACdA,EAAI,MAAM,GAAG,CAAC;EACdA,EAAI,MAAM,GAAG,EAAE;EACfA,EAAI,MAAM,IAAI,EAAE;CAClB,CAAC,CACE,KAAI,MAASE,EAAM,KAAK,EAAE,CAAC,CAAC,CAC5B,KAAK,GAAG;AACb;AAGA,eAAeC,EACb,GACA,GACY;CACZ,IAAI;EACF,OAAO,MAAMC,EAAQ;CACvB,SAASC,GAAO;EAEd,MADAC,EAAkBD,GAAOE,CAAS,GAC5BF;CACR;AACF;AAGA,IAAMG,IAAgB,QAGhBC,IAAK;AAGX,SAASC,EAAa,GAAyB;CAC7C,OAAOC,EAAK,KAAK,WAAW,KAAKA,EAAK,KAAK,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EAAqBJ,CAAuB;CAExD,IAAI,CAACiB,EAAe,IAAIjB,EAAO,MAAM,GACnC,MAAM,IAAIE,EAAgB;EACxB,MAAM,iBAAiBgB,EAAoB;EAC3C,OAAO;EACP,QAAQ;EACR,MAAMA,EAAoB;EAC1B,QAAQ,4CAA4ClB,EAAO,OAAO;EAC1D;CACV,CAAC;CAEH,OAAOA;AACT;AAEA,IAAMiB,IAAsC,IAAI,IAC9C,OAAO,OAAOd,CAAmB,CACnC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e={USER:`Wow-User`,OWNER:`Wow-Owner`,TENANT:`Wow-Tenant`,ROLES:`Wow-Roles`,APP:`Wow-App`};function t(t){let n={[e.USER]:t.user};return t.owner!==void 0&&(n[e.OWNER]=t.owner),t.tenant!==void 0&&(n[e.TENANT]=t.tenant),t.roles?.length&&(n[e.ROLES]=t.roles.join(`,`)),t.app!==void 0&&(n[e.APP]=t.app),n}function n(e){let n=typeof e==`function`?e:()=>e;return{name:`DevelopmentCaller`,order:0,intercept(e){let r=n();r&&Object.assign(e.ensureRequestHeaders(),t(r))}}}exports.DevelopmentCallerHeaders=e,exports.developmentCaller=n,exports.developmentCallerHeaders=t;
|
|
2
|
+
//# sourceMappingURL=developmentCaller.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"developmentCaller.cjs","names":["DevelopmentCallerHeaders","developmentCallerHeaders","headers","caller","developmentCaller","current","asking","exchange"],"sources":["../src/developmentCaller.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 { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The identity headers a development run of a Wow service reads the caller\n * from (the host's development callers, in a profile of `wow.dev-profiles`,\n * when CoSec is off): any client can set them, so a deployment never reads\n * them. Without {@link DevelopmentCallerHeaders.USER} the request is the\n * anonymous caller of the default tenant, and only\n * {@link DevelopmentCallerHeaders.APP} is kept.\n *\n * A console that offers a local run's caller, and a test, send them with\n * {@link developmentCaller}; `@ahoo-wang/wow-client/testing` exports it\n * too.\n */\nexport const DevelopmentCallerHeaders = {\n /** The caller's subject. */\n USER: 'Wow-User',\n /** The owner of its scope: an owner-level caller; a tenant-level one without it. */\n OWNER: 'Wow-Owner',\n /** Its tenant; the service's default tenant without it. */\n TENANT: 'Wow-Tenant',\n /** Its roles, comma-separated. */\n ROLES: 'Wow-Roles',\n /** The application it calls in, which each command records as its `app_id`. */\n APP: 'Wow-App',\n} as const;\n\n/**\n * Who a request comes from, as a development run of a Wow service reads it\n * ({@link DevelopmentCallerHeaders}).\n */\nexport interface DevelopmentCaller {\n /** The caller's subject. */\n readonly user: string;\n /**\n * The owner of its scope, for an owner-level caller; a tenant-level caller\n * without it. The owner is never the user unless it says so.\n */\n readonly owner?: string;\n /** Its tenant; the service's default tenant (`wow.tenant.default`) without it. */\n readonly tenant?: string;\n /** Its roles. */\n readonly roles?: readonly string[];\n /** The application it calls in. */\n readonly app?: string;\n}\n\n/** The headers that name `caller` to a development run: only those it sets. */\nexport function developmentCallerHeaders(\n caller: DevelopmentCaller,\n): Record<string, string> {\n const headers: Record<string, string> = {\n [DevelopmentCallerHeaders.USER]: caller.user,\n };\n if (caller.owner !== undefined)\n headers[DevelopmentCallerHeaders.OWNER] = caller.owner;\n if (caller.tenant !== undefined)\n headers[DevelopmentCallerHeaders.TENANT] = caller.tenant;\n if (caller.roles?.length)\n headers[DevelopmentCallerHeaders.ROLES] = caller.roles.join(',');\n if (caller.app !== undefined)\n headers[DevelopmentCallerHeaders.APP] = caller.app;\n return headers;\n}\n\n/**\n * A request interceptor that sends every request as `caller`, by the headers\n * a development run reads ({@link developmentCallerHeaders}): a fetcher that\n * uses it asks as that caller, as a host's CoSec interceptors send its token.\n * Given a function, it sends the caller the function answers at each request,\n * and nothing when it answers none.\n *\n * ```ts\n * const fetcher = new Fetcher({ baseURL });\n * fetcher.interceptors.request.use(\n * developmentCaller({ user: 'alice', owner: 'alice', tenant: 'acme' }),\n * );\n * ```\n */\nexport function developmentCaller(\n caller: DevelopmentCaller | (() => DevelopmentCaller | null | undefined),\n): RequestInterceptor {\n const current = typeof caller === 'function' ? caller : () => caller;\n return {\n name: 'DevelopmentCaller',\n order: 0,\n intercept(exchange: FetchExchange): void {\n const asking = current();\n if (!asking) return;\n Object.assign(\n exchange.ensureRequestHeaders(),\n developmentCallerHeaders(asking),\n );\n },\n };\n}\n"],"mappings":"AA2BA,IAAaA,EAA2B,CAEtC,KAAM,WAEN,MAAO,YAEP,OAAQ,aAER,MAAO,YAEP,IAAK,SACP,EAuBA,SAAgBC,EACd,EACwB,CACxB,IAAMC,EAAkC,EACrCF,EAAyB,MAAOG,EAAO,IAC1C,EASA,OARIA,EAAO,QAAU,IAAA,KACnB,EAAQH,EAAyB,OAASG,EAAO,OAC/CA,EAAO,SAAW,IAAA,KACpB,EAAQH,EAAyB,QAAUG,EAAO,QAChDA,EAAO,OAAO,SAChB,EAAQH,EAAyB,OAASG,EAAO,MAAM,KAAK,GAAG,GAC7DA,EAAO,MAAQ,IAAA,KACjB,EAAQH,EAAyB,KAAOG,EAAO,KAC1CD,CACT,CAgBA,SAAgBE,EACd,EACoB,CACpB,IAAMC,EAAU,OAAOF,GAAW,WAAaA,MAAeA,EAC9D,MAAO,CACL,KAAM,oBACN,MAAO,EACP,UAAU,EAA+B,CACvC,IAAMG,EAASD,EAAQ,EAClBC,GACL,OAAO,OACLC,EAAS,qBAAqB,EAC9BN,EAAyBK,CAAM,CACjC,CACF,CACF,CACF,C"}
|