@ahoo-wang/wow-client 10.0.0-alpha.7 → 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 CHANGED
@@ -126,9 +126,10 @@ aggregate or at admission, rejects with a `CommandRejectedError` (its `code`,
126
126
  its `result`, and the `problem` when the service answered one); anything
127
127
  else with a `WowProblemError`: the RFC 9457 `problem` as written, its
128
128
  `status`, its Wow `code`, its `violations`, and the `result` when the
129
- service sent one. `stream` emits every result, whatever its status. A
130
- stream that fails midway errors with the same error, so a `for await`
131
- throws it.
129
+ service sent one. `stream` emits every result after admission, whatever
130
+ its status; a command refused at admission rejects the `stream` call itself
131
+ with a `WowProblemError` whose `result.status` is `rejected`. A stream that
132
+ fails midway errors with the same error, so a `for await` throws it.
132
133
 
133
134
  ```ts
134
135
  import { FrameworkErrorCodes, WowProblemError } from '@ahoo-wang/wow-client';
package/README.zh-CN.md CHANGED
@@ -111,8 +111,9 @@ Manifest(`GET /wow/manifest`)。
111
111
  `CommandClient` 一致:被拒绝的命令(聚合拒绝或在准入时拒绝)以 `CommandRejectedError`
112
112
  reject(它的 `code`、`result`,服务回答了问题时还有 `problem`);其他情况以
113
113
  `WowProblemError` reject:原样的 RFC 9457 `problem`、`status`、Wow 的 `code`、
114
- `violations`,服务发送了结果时还有 `result`。`stream` 发出每个结果,不论状态。
115
- 中途失败的流以同一个错误结束,`for await` 会抛出它。
114
+ `violations`,服务发送了结果时还有 `result`。`stream` 发出准入之后的每个结果,不论
115
+ 状态;在准入时被拒绝的命令,让 `stream` 调用本身以 `result.status` 为 `rejected` 的
116
+ `WowProblemError` reject。中途失败的流以同一个错误结束,`for await` 会抛出它。
116
117
 
117
118
  ```ts
118
119
  import { FrameworkErrorCodes, WowProblemError } from '@ahoo-wang/wow-client';
package/dist/commands.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./frameworkErrors.cjs"),t=require("./wire.cjs"),n=require("./problem.cjs"),r=require("./http.cjs"),i=require("./manifest.cjs"),a=require("./streams.cjs"),o=require("./wait.cjs");var s={DELETE_AGGREGATE:`wow.lifecycle.DeleteAggregate`,RESTORE_AGGREGATE:`wow.lifecycle.RestoreAggregate`,TRANSFER_OWNER:`wow.lifecycle.TransferOwner`,TRANSFER_SPACE:`wow.lifecycle.TransferSpace`,APPLY_TAGS:`wow.lifecycle.ApplyTags`};function c(){let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return[n.slice(0,4),n.slice(4,6),n.slice(6,8),n.slice(8,10),n.slice(10,16)].map(e=>e.join(``)).join(`-`)}async function l(e,t){try{return await t()}catch(t){throw n.rememberRequestId(t,e),t}}var u=`wow.`,d=`{id}`;function f(e){return e.hops.length===1&&e.hops[0].stage===t.Stage.ACCEPTED}function p(e){return e.timeout===void 0?e.wait:(e.wait??o.WaitPlan.DEFAULT).within(e.timeout)}function m(e,t){let n=e.id,r=t.find(e=>e.path.includes(d)===(n!==void 0));if(r===void 0)throw TypeError(n===void 0?`${e.command} has no route without an aggregate id: set the request's id.`:`${e.command} has no route to an aggregate by its id: send it without an id.`);let i=r.method;if(i!==`POST`&&i!==`DELETE`)throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);return{method:i,path:n===void 0?r.path:r.path.replace(d,encodeURIComponent(n))}}function h(e){let t=e.split(`.`);if(t.length<3||t.some(e=>e===``))throw TypeError(`${e} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`);return{context:t[0],name:t[1]}}function g(e,t,n,i){return{[r.WowHeaders.REQUEST_ID]:n,[r.WowHeaders.WAIT]:t===void 0||t.isDefault?void 0:o.formatWaitPlan(t),[r.WowHeaders.WAIT_TIMEOUT]:t!==void 0&&(e.timeout!==void 0||t.timeout!==o.WaitPlan.DEFAULT_TIMEOUT)?o.formatWaitTimeout(t.timeout):void 0,[r.WowHeaders.IF_MATCH]:e.expectedVersion===void 0?void 0:`"${e.expectedVersion}"`,Accept:i}}function _(e){if(e.targetTenant!==void 0||e.targetScope!==void 0)return{tenantId:e.targetTenant,...e.targetScope}}var v=class{constructor(e={},t={}){this.client=e,this.manifest=t.manifest===void 0?void 0:Promise.resolve(i.checkManifest(t.manifest)),this.bodyNumbers=t.bodyNumbers??{}}async send(e){let t=p(e);if(t!==void 0&&!t.isDefault&&!f(t))throw TypeError(`send answers on acceptance: use wait() for the plan ${o.formatWaitPlan(t)}.`);return this.exchange(e,o.WaitPlan.ACCEPTED.within(e.timeout??o.WaitPlan.DEFAULT_TIMEOUT))}wait(e){return this.exchange(e,p(e))}async stream(e){let t=e.requestId??c();return l(t,async()=>a.commandResults(await this.post(e,p(e),t,`text/event-stream`)))}async exchange(e,i){let a=e.requestId??c();return l(a,async()=>{let o;try{o=await r.json(await this.post(e,i,a))}catch(e){throw e instanceof n.WowProblemError&&e.result?.status===t.CommandResultStatus.REJECTED?new n.CommandRejectedError(e.result,{problem:e.problem,cause:e}):e}return y(o)})}async post(e,t,n,i){let a=m(e,await this.routesOf(e)),o=_(e),s=this.bodyNumbers[e.command];return r.send(this.client,{method:a.method,path:a.path,headers:g(e,t,n,i),...a.method===`DELETE`?{}:{body:e.body??{}},...s===void 0?{}:{bodyNumbers:s},options:{...o===void 0?{}:{scope:o},...e.space===void 0?{}:{space:e.space},...e.headers===void 0?{}:{headers:e.headers},...e.signal===void 0?{}:{signal:e.signal}}})}async routesOf(e){let t=e.command,n=t.startsWith(u),r=e.type??(n?void 0:h(t));if(r===void 0)throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);let i=`${r.context}.${r.name}.`,a=t.startsWith(i)?t.slice(i.length):t,o=(await this.manifestOf()).contexts.find(e=>e.name===r.context),s=o?.aggregates?.find(e=>e.name===r.name)?.commands?.find(e=>e.name===a||e.aliases?.includes(a)===!0)??(n?o?.commands?.find(e=>e.name===a):void 0);if(s?.routes===void 0)throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);return s.routes}manifestOf(){return this.manifest??=i.fetchManifest(this.client).catch(e=>{throw this.manifest=void 0,e}),this.manifest}};function y(r){if(r.status===t.CommandResultStatus.REJECTED)throw new n.CommandRejectedError(r);if(!b.has(r.status))throw new n.WowProblemError({type:`urn:wow:error:${e.FrameworkErrorCodes.COMMAND_FAILED}`,title:`Unknown command status`,status:200,code:e.FrameworkErrorCodes.COMMAND_FAILED,detail:`The command was answered with the status ${r.status}, which this client does not know: the service is newer than this client, so upgrade it.`,result:r});return r}var b=new Set(Object.values(t.CommandResultStatus));exports.CommandClient=v,exports.LifecycleCommands=s,exports.newRequestId=c;
1
+ const e=require("./frameworkErrors.cjs"),t=require("./wire.cjs"),n=require("./problem.cjs"),r=require("./http.cjs"),i=require("./manifest.cjs"),a=require("./streams.cjs"),o=require("./wait.cjs");var s={DELETE_AGGREGATE:`wow.lifecycle.DeleteAggregate`,RESTORE_AGGREGATE:`wow.lifecycle.RestoreAggregate`,TRANSFER_OWNER:`wow.lifecycle.TransferOwner`,TRANSFER_SPACE:`wow.lifecycle.TransferSpace`,APPLY_TAGS:`wow.lifecycle.ApplyTags`};function c(){let e=globalThis.crypto;if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);if(typeof e?.getRandomValues==`function`)e.getRandomValues(t);else for(let e=0;e<t.length;e++)t[e]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=Array.from(t,e=>e.toString(16).padStart(2,`0`));return[n.slice(0,4),n.slice(4,6),n.slice(6,8),n.slice(8,10),n.slice(10,16)].map(e=>e.join(``)).join(`-`)}async function l(e,t){try{return await t()}catch(t){throw n.rememberRequestId(t,e),t}}var u=`wow.`,d=`{id}`;function f(e){return e.hops.length===1&&e.hops[0].stage===t.Stage.ACCEPTED}function p(e){return e.timeout===void 0?e.wait:(e.wait??o.WaitPlan.DEFAULT).within(e.timeout)}function m(e,t,n){let r=t.find(e=>e.path.includes(d)===(n!==void 0));if(r===void 0)throw TypeError(n===void 0?`${e.command} has no route without an aggregate id: set the request's id.`:`${e.command} has no route to an aggregate by its id: send it without an id.`);if(n===``)throw TypeError(`The path ${r.path} of ${e.command} needs id.`);let i=r.method;if(i!==`POST`&&i!==`DELETE`)throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);return{method:i,path:n===void 0?r.path:r.path.replace(d,encodeURIComponent(n))}}function h(e,t){let n=e.body??{},r=e.id;if(t===void 0||r===void 0)return n;let i=n[t];if(i==null)return{...n,[t]:r};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.`);return n}function g(e){let t=e.split(`.`);if(t.length<3||t.some(e=>e===``))throw TypeError(`${e} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`);return{context:t[0],name:t[1]}}function _(e,t,n,i){return{[r.WowHeaders.REQUEST_ID]:n,[r.WowHeaders.WAIT]:t===void 0||t.isDefault?void 0:o.formatWaitPlan(t),[r.WowHeaders.WAIT_TIMEOUT]:t!==void 0&&(e.timeout!==void 0||t.timeout!==o.WaitPlan.DEFAULT_TIMEOUT)?o.formatWaitTimeout(t.timeout):void 0,[r.WowHeaders.IF_MATCH]:e.expectedVersion===void 0?void 0:`"${e.expectedVersion}"`,Accept:i}}function v(e){if(e.targetTenant!==void 0||e.targetScope!==void 0)return{tenantId:e.targetTenant,...e.targetScope}}var y=class{constructor(e={},t={}){this.client=e,this.manifest=t.manifest===void 0?void 0:Promise.resolve(i.checkManifest(t.manifest)),this.bodyNumbers=t.bodyNumbers??{}}async send(e){let t=p(e);if(t!==void 0&&!t.isDefault&&!f(t))throw TypeError(`send answers on acceptance: use wait() for the plan ${o.formatWaitPlan(t)}.`);return this.exchange(e,o.WaitPlan.ACCEPTED.within(e.timeout??o.WaitPlan.DEFAULT_TIMEOUT))}wait(e){return this.exchange(e,p(e))}async stream(e){let t=e.requestId??c();return l(t,async()=>a.commandResults(await this.post(e,p(e),t,`text/event-stream`)))}async exchange(e,i){let a=e.requestId??c();return l(a,async()=>{let o;try{o=await r.json(await this.post(e,i,a))}catch(e){throw e instanceof n.WowProblemError&&e.result?.status===t.CommandResultStatus.REJECTED?new n.CommandRejectedError(e.result,{problem:e.problem,cause:e}):e}return b(o)})}async post(e,t,n,i){let a=await this.commandOf(e),o=a.idProperty,s=m(e,a.routes,o===void 0?e.id:void 0),c=v(e),l=this.bodyNumbers[e.command];return r.send(this.client,{method:s.method,path:s.path,headers:_(e,t,n,i),...s.method===`DELETE`?{}:{body:h(e,o)},...l===void 0?{}:{bodyNumbers:l},options:{...c===void 0?{}:{scope:c},...e.space===void 0?{}:{space:e.space},...e.headers===void 0?{}:{headers:e.headers},...e.signal===void 0?{}:{signal:e.signal}}})}async commandOf(e){let t=e.command,n=t.startsWith(u),r=e.type??(n?void 0:g(t));if(r===void 0)throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);let i=`${r.context}.${r.name}.`,a=t.startsWith(i)?t.slice(i.length):t,o=(await this.manifestOf()).contexts.find(e=>e.name===r.context),s=o?.aggregates?.find(e=>e.name===r.name)?.commands?.find(e=>e.name===a||e.aliases?.includes(a)===!0)??(n?o?.commands?.find(e=>e.name===a):void 0);if(s?.routes===void 0)throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);return s}manifestOf(){return this.manifest??=i.fetchManifest(this.client).catch(e=>{throw this.manifest=void 0,e}),this.manifest}};function b(r){if(r.status===t.CommandResultStatus.REJECTED)throw new n.CommandRejectedError(r);if(!x.has(r.status))throw new n.WowProblemError({type:`urn:wow:error:${e.FrameworkErrorCodes.COMMAND_FAILED}`,title:`Unknown command status`,status:200,code:e.FrameworkErrorCodes.COMMAND_FAILED,detail:`The command was answered with the status ${r.status}, which this client does not know: the service is newer than this client, so upgrade it.`,result:r});return r}var x=new Set(Object.values(t.CommandResultStatus));exports.CommandClient=y,exports.LifecycleCommands=s,exports.newRequestId=c;
2
2
  //# sourceMappingURL=commands.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands.cjs","names":["Stage","WaitPlan","WowHeaders","formatWaitPlan","formatWaitTimeout","checkManifest","commandResults","json","WowProblemError","CommandResultStatus","CommandRejectedError","send","fetchManifest","FrameworkErrorCodes","require_frameworkErrors","require_wire","require_problem","require_http","require_manifest","require_streams","require_wait","LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","planOf","request","routeOf","id","route","routes","item","method","typeNamed","parts","command","part","commandHeaders","accept","targetOf","CommandClient","client","options","result","settled","scope","bodyNumbers","system","type","prefix","name","context","declared","aggregate","KNOWN_STATUSES"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n json,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n checkManifest,\n fetchManifest,\n type RouteManifest,\n type RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/** The route of `request` among `routes`: its method and path, the id in it. */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n): { method: 'POST' | 'DELETE'; path: string } {\n const id = request.id;\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private manifest: Promise<RoutingManifest> | undefined;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await json<CommandResult<R>>(\n await this.post(request, plan, requestId),\n );\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n const route = routeOf(request, await this.routesOf(request));\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE' ? {} : { body: request.body ?? {} }),\n ...(bodyNumbers === undefined ? {} : { bodyNumbers }),\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * The routes of `request`'s command in the Manifest: a domain command's\n * among its aggregate's commands, by name or former name; a system\n * command's among its type's, else among its context's (a job's).\n */\n private async routesOf(\n request: CommandRequest,\n ): Promise<readonly RouteManifest[]> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifestOf()).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared.routes;\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":"A,mMAkJA,IAAaqB,EAAoB,CAC/B,iBAAkB,gCAClB,kBAAmB,iCACnB,eAAgB,8BAChB,eAAgB,8BAChB,WAAY,yBACd,EA0BA,SAAgBC,GAAuB,CACrC,IAAMC,EAAS,WAAW,OAC1B,GAAI,OAAOA,GAAQ,YAAe,WAAY,OAAOA,EAAO,WAAW,EAEvE,IAAMC,EAAQ,IAAI,WAAW,EAAE,EAC/B,GAAI,OAAOD,GAAQ,iBAAoB,WACrCA,EAAO,gBAAgBC,CAAK,OAE5B,IAAK,IAAIC,EAAQ,EAAGA,EAAQD,EAAM,OAAQ,IACxC,EAAMC,GAAS,KAAK,MAAM,KAAK,OAAO,EAAI,GAAG,EAGjD,EAAM,GAAMD,EAAM,GAAK,GAAQ,GAC/B,EAAM,GAAMA,EAAM,GAAK,GAAQ,IAC/B,IAAME,EAAM,MAAM,KAAKF,EAAO,GAAQG,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAAG,CAAC,EACxE,MAAO,CACLD,EAAI,MAAM,EAAG,CAAC,EACdA,EAAI,MAAM,EAAG,CAAC,EACdA,EAAI,MAAM,EAAG,CAAC,EACdA,EAAI,MAAM,EAAG,EAAE,EACfA,EAAI,MAAM,GAAI,EAAE,CAClB,CAAC,CACE,IAAI,GAASE,EAAM,KAAK,EAAE,CAAC,CAAC,CAC5B,KAAK,GAAG,CACb,CAGA,eAAeC,EACb,EACA,EACY,CACZ,GAAI,CACF,OAAO,MAAMC,EAAQ,CACvB,OAASC,EAAO,CAEd,MADAf,EAAA,kBAAkBe,EAAOC,CAAS,EAC5BD,CAC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C,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAOzD,EAAAA,mBAAmB,CACnC,E"}
1
+ {"version":3,"file":"commands.cjs","names":["Stage","WaitPlan","WowHeaders","formatWaitPlan","formatWaitTimeout","checkManifest","commandResults","json","WowProblemError","CommandResultStatus","CommandRejectedError","send","fetchManifest","FrameworkErrorCodes","require_frameworkErrors","require_wire","require_problem","require_http","require_manifest","require_streams","require_wait","LifecycleCommands","newRequestId","crypto","bytes","index","hex","byte","group","withRequestId","sending","error","requestId","SYSTEM_PREFIX","ID","acceptedOnly","plan","planOf","request","routeOf","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","accept","targetOf","CommandClient","client","options","result","settled","declared","scope","bodyNumbers","system","type","prefix","name","context","aggregate","KNOWN_STATUSES"],"sources":["../src/commands.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { TextNumbers } from './exactJson.js';\nimport {\n json,\n type RequestOptions,\n send,\n type TargetScope,\n type WowClientOptions,\n WowHeaders,\n} from './http.js';\nimport {\n type AggregateType,\n type CommandResult,\n CommandResultStatus,\n type RefusedResult,\n Stage,\n} from './wire.js';\nimport {\n checkManifest,\n fetchManifest,\n type RouteManifest,\n type 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":"A,mMAsJA,IAAaqB,EAAoB,CAC/B,iBAAkB,gCAClB,kBAAmB,iCACnB,eAAgB,8BAChB,eAAgB,8BAChB,WAAY,yBACd,EA0BA,SAAgBC,GAAuB,CACrC,IAAMC,EAAS,WAAW,OAC1B,GAAI,OAAOA,GAAQ,YAAe,WAAY,OAAOA,EAAO,WAAW,EAEvE,IAAMC,EAAQ,IAAI,WAAW,EAAE,EAC/B,GAA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AC1D,QACV,CAAC,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAO7D,EAAAA,mBAAmB,CACnC,E"}
@@ -18,7 +18,10 @@ import { WaitPlan } from './wait.cjs';
18
18
  * a creation, whose id the server assigns, an `@Unaddressed` command, or
19
19
  * any command of an aggregate whose id is its owner's (the Manifest's
20
20
  * `idSource: "owner"`), which goes to the caller's own; the route without
21
- * `{id}` then sends it.
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.
22
25
  * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to
23
26
  * act across scopes acts in (`Wow-Scope`); the caller's own when absent.
24
27
  * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds
@@ -183,11 +186,11 @@ export declare class CommandClient {
183
186
  private exchange;
184
187
  private post;
185
188
  /**
186
- * The routes of `request`'s command in the Manifest: a domain command's
187
- * among its aggregate's commands, by name or former name; a system
188
- * command's among its type's, else among its context's (a job's).
189
+ * `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).
189
192
  */
190
- private routesOf;
193
+ private commandOf;
191
194
  /** The Manifest given, or the service's, fetched once (again after a failure). */
192
195
  private manifestOf;
193
196
  }
@@ -18,7 +18,10 @@ import { WaitPlan } from './wait.js';
18
18
  * a creation, whose id the server assigns, an `@Unaddressed` command, or
19
19
  * any command of an aggregate whose id is its owner's (the Manifest's
20
20
  * `idSource: "owner"`), which goes to the caller's own; the route without
21
- * `{id}` then sends it.
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.
22
25
  * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to
23
26
  * act across scopes acts in (`Wow-Scope`); the caller's own when absent.
24
27
  * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds
@@ -183,11 +186,11 @@ export declare class CommandClient {
183
186
  private exchange;
184
187
  private post;
185
188
  /**
186
- * The routes of `request`'s command in the Manifest: a domain command's
187
- * among its aggregate's commands, by name or former name; a system
188
- * command's among its type's, else among its context's (a job's).
189
+ * `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).
189
192
  */
190
- private routesOf;
193
+ private commandOf;
191
194
  /** The Manifest given, or the service's, fetched once (again after a failure). */
192
195
  private manifestOf;
193
196
  }
@@ -43,9 +43,10 @@ function b(e) {
43
43
  function x(e) {
44
44
  return e.timeout === void 0 ? e.wait : (e.wait ?? f.DEFAULT).within(e.timeout);
45
45
  }
46
- function S(e, t) {
47
- let n = e.id, r = t.find((e) => e.path.includes(y) === (n !== void 0));
46
+ function S(e, t, n) {
47
+ let r = t.find((e) => e.path.includes(y) === (n !== void 0));
48
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.`);
49
50
  let i = r.method;
50
51
  if (i !== "POST" && i !== "DELETE") throw TypeError(`${e.command} is routed by ${i}: a command is sent by POST or DELETE.`);
51
52
  return {
@@ -53,7 +54,18 @@ function S(e, t) {
53
54
  path: n === void 0 ? r.path : r.path.replace(y, encodeURIComponent(n))
54
55
  };
55
56
  }
56
- function C(e) {
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) {
57
69
  let t = e.split(".");
58
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.`);
59
71
  return {
@@ -61,7 +73,7 @@ function C(e) {
61
73
  name: t[1]
62
74
  };
63
75
  }
64
- function w(e, t, n, r) {
76
+ function T(e, t, n, r) {
65
77
  return {
66
78
  [o.REQUEST_ID]: n,
67
79
  [o.WAIT]: t === void 0 || t.isDefault ? void 0 : p(t),
@@ -70,13 +82,13 @@ function w(e, t, n, r) {
70
82
  Accept: r
71
83
  };
72
84
  }
73
- function T(e) {
85
+ function E(e) {
74
86
  if (e.targetTenant !== void 0 || e.targetScope !== void 0) return {
75
87
  tenantId: e.targetTenant,
76
88
  ...e.targetScope
77
89
  };
78
90
  }
79
- var E = class {
91
+ var D = class {
80
92
  constructor(e = {}, t = {}) {
81
93
  this.client = e, this.manifest = t.manifest === void 0 ? void 0 : Promise.resolve(l(t.manifest)), this.bodyNumbers = t.bodyNumbers ?? {};
82
94
  }
@@ -104,31 +116,31 @@ var E = class {
104
116
  cause: e
105
117
  }) : e;
106
118
  }
107
- return D(o);
119
+ return O(o);
108
120
  });
109
121
  }
110
122
  async post(e, t, n, r) {
111
- let i = S(e, await this.routesOf(e)), a = T(e), o = this.bodyNumbers[e.command];
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];
112
124
  return c(this.client, {
113
- method: i.method,
114
- path: i.path,
115
- headers: w(e, t, n, r),
116
- ...i.method === "DELETE" ? {} : { body: e.body ?? {} },
117
- ...o === void 0 ? {} : { bodyNumbers: o },
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 },
118
130
  options: {
119
- ...a === void 0 ? {} : { scope: a },
131
+ ...s === void 0 ? {} : { scope: s },
120
132
  ...e.space === void 0 ? {} : { space: e.space },
121
133
  ...e.headers === void 0 ? {} : { headers: e.headers },
122
134
  ...e.signal === void 0 ? {} : { signal: e.signal }
123
135
  }
124
136
  });
125
137
  }
126
- async routesOf(e) {
127
- let t = e.command, n = t.startsWith(v), r = e.type ?? (n ? void 0 : C(t));
138
+ async commandOf(e) {
139
+ let t = e.command, n = t.startsWith(v), r = e.type ?? (n ? void 0 : w(t));
128
140
  if (r === void 0) throw TypeError(`${t} is a system command every aggregate takes: set the request's type.`);
129
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);
130
142
  if (s?.routes === void 0) throw TypeError(`The Manifest lists no command ${a} of ${r.context}.${r.name}.`);
131
- return s.routes;
143
+ return s;
132
144
  }
133
145
  manifestOf() {
134
146
  return this.manifest ??= u(this.client).catch((e) => {
@@ -136,9 +148,9 @@ var E = class {
136
148
  }), this.manifest;
137
149
  }
138
150
  };
139
- function D(n) {
151
+ function O(n) {
140
152
  if (n.status === t.REJECTED) throw new r(n);
141
- if (!O.has(n.status)) throw new i({
153
+ if (!k.has(n.status)) throw new i({
142
154
  type: `urn:wow:error:${e.COMMAND_FAILED}`,
143
155
  title: "Unknown command status",
144
156
  status: 200,
@@ -148,7 +160,7 @@ function D(n) {
148
160
  });
149
161
  return n;
150
162
  }
151
- var O = new Set(Object.values(t));
152
- export { E as CommandClient, h as LifecycleCommands, g as newRequestId };
163
+ var k = new Set(Object.values(t));
164
+ export { D as CommandClient, h as LifecycleCommands, g as newRequestId };
153
165
 
154
166
  //# sourceMappingURL=commands.es.js.map
@@ -1 +1 @@
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","id","route","routes","item","method","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","options","checkManifest","commandResults","result","json","WowProblemError","CommandResultStatus","CommandRejectedError","settled","scope","bodyNumbers","send","system","type","prefix","name","context","declared","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 RoutingManifest,\n} from './manifest.js';\nimport {\n CommandRejectedError,\n FrameworkErrorCodes,\n rememberRequestId,\n WowProblemError,\n} from './problem.js';\nimport { commandResults, type CommandResultStream } from './streams.js';\nimport { formatWaitPlan, formatWaitTimeout, WaitPlan } from './wait.js';\n\n/**\n * One command a {@link CommandClient} sends, and how: the TypeScript\n * `CommandRequest` of Kotlin's `me.ahoo.wow.api.client`, with the same\n * fields. Kotlin's `command` is the command object, whose class names it;\n * here `command` is the command's name and `body` its payload, as the wire\n * carries them.\n *\n * - `command`: the full type name, `context.aggregate.Command`, which names\n * the aggregate type too; or a system command (`wow.*`, a lifecycle command\n * of {@link LifecycleCommands} among them), which needs `type`.\n * - `id`: the aggregate's id. Absent when the command names no aggregate id:\n * a creation, whose id the server assigns, an `@Unaddressed` command, or\n * any command of an aggregate whose id is its owner's (the Manifest's\n * `idSource: \"owner\"`), which goes to the caller's own; the route without\n * `{id}` then sends it.\n * - `targetTenant`, `targetScope`: the tenant and scope a caller allowed to\n * act across scopes acts in (`Wow-Scope`); the caller's own when absent.\n * - `wait` (`Wow-Wait`), a {@link WaitPlan}, and `timeout` in milliseconds\n * (`Wow-Wait-Timeout`), which overrides the plan's: the plan the command\n * waits with is `wait` within `timeout`, the server's default plan when\n * only a timeout is given, and the server's default without either.\n * - `requestId` (`Wow-Request-Id`) and `expectedVersion` (`If-Match`).\n */\nexport interface CommandRequest extends Omit<RequestOptions, 'scope'> {\n /** The command's full type name, or a system command's. */\n readonly command: string;\n /** The command's body; `{}` when absent. */\n readonly body?: object;\n /**\n * The aggregate's id; absent for a creation, an unaddressed command or the\n * caller's own aggregate of one whose id is its owner's.\n */\n readonly id?: string;\n /**\n * The aggregate type, which `command` names unless it is a system command:\n * then it is required.\n */\n readonly type?: AggregateType;\n /** The tenant to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetTenant?: string;\n /** The owner and space to act in, for a caller allowed to (`Wow-Scope`). */\n readonly targetScope?: Omit<TargetScope, 'tenantId'>;\n /**\n * Not a command's: a query's `Wow-Scope`. A command names the scope it acts\n * in with `targetTenant` and `targetScope`, so a query's options spread into\n * a command's fail to compile rather than drop their scope.\n */\n readonly scope?: never;\n /** How far to wait for the command (`Wow-Wait`). */\n readonly wait?: WaitPlan;\n /** How long to wait, in milliseconds, over the plan's own timeout. */\n readonly timeout?: number;\n /**\n * The request id (`Wow-Request-Id`): a retry with the same one is\n * deduplicated, answered as the first commit's duplicate. When absent, the\n * client generates one ({@link newRequestId}), which a failure carries\n * ({@link requestIdOf}). A request sent again without one is another\n * request: for an application-level retry, set it (or keep the one the\n * failure or the first result carries) and send that request again.\n */\n readonly requestId?: string;\n /** The version the aggregate must be at (`If-Match`). */\n readonly expectedVersion?: number;\n}\n\n/** How a {@link CommandClient} sends, beside how it reaches the service. */\nexport interface CommandClientOptions {\n /**\n * The Manifest whose routes send each command: a whole Manifest, or the\n * routing part a generated client carries (`manifest.ts`). Without it the\n * client fetches the service's once, when it first sends\n * (`GET /wow/manifest`), and again after a failed fetch.\n */\n readonly manifest?: RoutingManifest;\n /**\n * The body numbers each command writes as their exact text, unquoted JSON\n * numbers (decision D122), by the command's full type name: a generated\n * client sets them for commands with `int64`, `bigint` or `decimal` fields,\n * which it types as `string`.\n */\n readonly bodyNumbers?: Readonly<Record<string, TextNumbers>>;\n}\n\n/**\n * The options of a generated client's command method: a {@link CommandRequest}\n * without what the method fixes, its command, body and type.\n */\nexport type CommandOptions = Omit<\n CommandRequest,\n 'command' | 'body' | 'type' | 'id'\n>;\n\n/** The options of a command that may create its aggregate, with its id or not. */\nexport interface CreateCommandOptions extends CommandOptions {\n /**\n * The id of the aggregate to create (decision D176); the service generates\n * one when absent.\n */\n readonly id?: string;\n}\n\n/** The lifecycle commands an aggregate may list. */\nexport const LifecycleCommands = {\n DELETE_AGGREGATE: 'wow.lifecycle.DeleteAggregate',\n RESTORE_AGGREGATE: 'wow.lifecycle.RestoreAggregate',\n TRANSFER_OWNER: 'wow.lifecycle.TransferOwner',\n TRANSFER_SPACE: 'wow.lifecycle.TransferSpace',\n APPLY_TAGS: 'wow.lifecycle.ApplyTags',\n} as const;\n\n/** A {@link LifecycleCommands} value. */\nexport type LifecycleCommand =\n (typeof LifecycleCommands)[keyof typeof LifecycleCommands];\n\n/** The body of `wow.lifecycle.TransferOwner`. */\nexport interface TransferOwner {\n readonly ownerId: string;\n}\n\n/** The body of `wow.lifecycle.TransferSpace`. */\nexport interface TransferSpace {\n readonly spaceId: string;\n}\n\n/** The body of `wow.lifecycle.ApplyTags`: the tags, names to values. */\nexport interface ApplyTags {\n readonly tags: Readonly<Record<string, readonly string[]>>;\n}\n\n/**\n * A new request id (`Wow-Request-Id`): a random UUID. The client generates\n * one for a command sent without; generate it first to retry with it however\n * the request fails.\n */\nexport function newRequestId(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID();\n // An insecure browser context has no randomUUID: a version 4 UUID by hand.\n const bytes = new Uint8Array(16);\n if (typeof crypto?.getRandomValues === 'function') {\n crypto.getRandomValues(bytes);\n } else {\n for (let index = 0; index < bytes.length; index++) {\n bytes[index] = Math.floor(Math.random() * 256);\n }\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map(group => group.join(''))\n .join('-');\n}\n\n/** Sends with the request id `requestId`, which a failure carries. */\nasync function withRequestId<T>(\n requestId: string,\n sending: () => Promise<T>,\n): Promise<T> {\n try {\n return await sending();\n } catch (error) {\n rememberRequestId(error, requestId);\n throw error;\n }\n}\n\n/** The prefix of the system commands' names, the lifecycle commands' among them. */\nconst SYSTEM_PREFIX = 'wow.';\n\n/** The aggregate id of a route's path. */\nconst ID = '{id}';\n\n/** Whether `plan` waits for acceptance alone. */\nfunction acceptedOnly(plan: WaitPlan): boolean {\n return plan.hops.length === 1 && plan.hops[0].stage === Stage.ACCEPTED;\n}\n\n/**\n * The plan `request` waits with, as Kotlin's `CommandRequest.plan`: its\n * `wait` within its `timeout`, the default plan when only a timeout is given.\n */\nfunction planOf(request: CommandRequest): WaitPlan | undefined {\n if (request.timeout === undefined) return request.wait;\n return (request.wait ?? WaitPlan.DEFAULT).within(request.timeout);\n}\n\n/** The route of `request` among `routes`: its method and path, the id in it. */\nfunction routeOf(\n request: CommandRequest,\n routes: readonly RouteManifest[],\n): { method: 'POST' | 'DELETE'; path: string } {\n const id = request.id;\n const route = routes.find(\n item => item.path.includes(ID) === (id !== undefined),\n );\n if (route === undefined) {\n throw new TypeError(\n id === undefined\n ? `${request.command} has no route without an aggregate id: set the request's id.`\n : `${request.command} has no route to an aggregate by its id: send it without an id.`,\n );\n }\n const method = route.method;\n if (method !== 'POST' && method !== 'DELETE') {\n throw new TypeError(\n `${request.command} is routed by ${method}: a command is sent by POST or DELETE.`,\n );\n }\n return {\n method,\n path:\n id === undefined\n ? route.path\n : route.path.replace(ID, encodeURIComponent(id)),\n };\n}\n\n/** The aggregate type a full type name `context.aggregate.Command` names. */\nfunction typeNamed(command: string): AggregateType {\n const parts = command.split('.');\n if (parts.length < 3 || parts.some(part => part === '')) {\n throw new TypeError(\n `${command} is not a full type name, context.aggregate.Command: name it so, or set the request's type.`,\n );\n }\n return { context: parts[0], name: parts[1] };\n}\n\nfunction commandHeaders(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n): Record<string, string | undefined> {\n return {\n [WowHeaders.REQUEST_ID]: requestId,\n // The default plan is the service's to pick: it sends no plan.\n [WowHeaders.WAIT]:\n plan === undefined || plan.isDefault ? undefined : formatWaitPlan(plan),\n // A plan's own timeout, or the request's; the service's default otherwise.\n [WowHeaders.WAIT_TIMEOUT]:\n plan !== undefined &&\n (request.timeout !== undefined ||\n plan.timeout !== WaitPlan.DEFAULT_TIMEOUT)\n ? formatWaitTimeout(plan.timeout)\n : undefined,\n [WowHeaders.IF_MATCH]:\n request.expectedVersion === undefined\n ? undefined\n : `\"${request.expectedVersion}\"`,\n Accept: accept,\n };\n}\n\n/** The `Wow-Scope` a request targets, when it targets one. */\nfunction targetOf(request: CommandRequest): TargetScope | undefined {\n if (request.targetTenant === undefined && request.targetScope === undefined) {\n return undefined;\n }\n return { tenantId: request.targetTenant, ...request.targetScope };\n}\n\n/**\n * Sends commands to the command routes of a Wow service as its Manifest lists\n * them (`POST /{context}/{aggregate}/{id}/{command}`, the route without\n * `{id}` for a request that names none, `DELETE /{context}/{aggregate}/{id}`\n * for `DeleteAggregate`): the Manifest the client is given, else the\n * service's, fetched once (`GET /wow/manifest`). The TypeScript\n * `CommandClient` of Kotlin's `me.ahoo.wow.api.client`: {@link send} answers\n * once the command is accepted, {@link wait} with the result its wait plan\n * ends with, {@link stream} with one result per hop. Generated aggregate\n * clients build on it.\n *\n * `send` and `wait` resolve only a result that succeeded. A rejected one,\n * by the aggregate or at admission, rejects with a\n * {@link CommandRejectedError}; anything else that did not succeed with a\n * {@link WowProblemError} (the table on {@link CommandRejectedError} says\n * which). Every command carries a request id, the request's or a generated\n * one, and whatever it rejects with carries that id ({@link requestIdOf}).\n */\nexport class CommandClient {\n private manifest: Promise<RoutingManifest> | undefined;\n private readonly bodyNumbers: Readonly<Record<string, TextNumbers>>;\n\n /**\n * @param client - How the service is reached\n * @param options - The service's Manifest, and the commands' exact numbers\n */\n constructor(\n readonly client: WowClientOptions = {},\n options: CommandClientOptions = {},\n ) {\n this.manifest =\n options.manifest === undefined\n ? undefined\n : Promise.resolve(checkManifest(options.manifest));\n this.bodyNumbers = options.bodyNumbers ?? {};\n }\n\n /**\n * Sends a command and answers once it is accepted (202), within the\n * request's timeout (10 seconds without one), as Kotlin's\n * `CommandClient.send`. A request whose `wait` waits for more rejects with a\n * `TypeError` before it is sent: {@link wait} answers with that plan's result.\n *\n * @param request - The command and how to send it\n */\n async send<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n const plan = planOf(request);\n if (plan !== undefined && !plan.isDefault && !acceptedOnly(plan)) {\n throw new TypeError(\n `send answers on acceptance: use wait() for the plan ${formatWaitPlan(plan)}.`,\n );\n }\n return this.exchange<R>(\n request,\n WaitPlan.ACCEPTED.within(request.timeout ?? WaitPlan.DEFAULT_TIMEOUT),\n );\n }\n\n /**\n * Sends a command and answers the result its wait plan ends with: 200, or\n * 202 for a plan that ends at `accepted`. Without a plan, the server's\n * default: the snapshot, or the commit where the aggregate keeps no\n * snapshot (decision D69).\n *\n * @param request - The command and how to send it\n */\n wait<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResult<R>> {\n return this.exchange<R>(request, planOf(request));\n }\n\n /**\n * Sends a command with `Accept: text/event-stream` and answers one result\n * per hop as the wait advances, whatever its status. An admission refusal\n * rejects with its problem; a rejection after admission is the stream's\n * last result.\n *\n * @param request - The command and how to send it\n */\n async stream<R = Record<string, unknown>>(\n request: CommandRequest,\n ): Promise<CommandResultStream<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () =>\n commandResults<R>(\n await this.post(\n request,\n planOf(request),\n requestId,\n 'text/event-stream',\n ),\n ),\n );\n }\n\n private async exchange<R>(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n ): Promise<CommandResult<R>> {\n const requestId = request.requestId ?? newRequestId();\n return withRequestId(requestId, async () => {\n let result: CommandResult<R>;\n try {\n result = await json<CommandResult<R>>(\n await this.post(request, plan, requestId),\n );\n } catch (error) {\n if (\n error instanceof WowProblemError &&\n error.result?.status === CommandResultStatus.REJECTED\n ) {\n throw new CommandRejectedError(error.result, {\n problem: error.problem,\n cause: error,\n });\n }\n throw error;\n }\n return settled(result);\n });\n }\n\n private async post(\n request: CommandRequest,\n plan: WaitPlan | undefined,\n requestId: string,\n accept?: string,\n ): Promise<Response> {\n const route = routeOf(request, await this.routesOf(request));\n const scope = targetOf(request);\n const bodyNumbers = this.bodyNumbers[request.command];\n return send(this.client, {\n method: route.method,\n path: route.path,\n headers: commandHeaders(request, plan, requestId, accept),\n ...(route.method === 'DELETE' ? {} : { body: request.body ?? {} }),\n ...(bodyNumbers === undefined ? {} : { bodyNumbers }),\n options: {\n ...(scope === undefined ? {} : { scope }),\n ...(request.space === undefined ? {} : { space: request.space }),\n ...(request.headers === undefined ? {} : { headers: request.headers }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n },\n });\n }\n\n /**\n * The routes of `request`'s command in the Manifest: a domain command's\n * among its aggregate's commands, by name or former name; a system\n * command's among its type's, else among its context's (a job's).\n */\n private async routesOf(\n request: CommandRequest,\n ): Promise<readonly RouteManifest[]> {\n const command = request.command;\n const system = command.startsWith(SYSTEM_PREFIX);\n const type = request.type ?? (system ? undefined : typeNamed(command));\n if (type === undefined) {\n throw new TypeError(\n `${command} is a system command every aggregate takes: set the request's type.`,\n );\n }\n const prefix = `${type.context}.${type.name}.`;\n const name = command.startsWith(prefix)\n ? command.slice(prefix.length)\n : command;\n const context = (await this.manifestOf()).contexts.find(\n item => item.name === type.context,\n );\n const declared =\n context?.aggregates\n ?.find(aggregate => aggregate.name === type.name)\n ?.commands?.find(\n item => item.name === name || item.aliases?.includes(name) === true,\n ) ??\n (system\n ? context?.commands?.find(item => item.name === name)\n : undefined);\n if (declared?.routes === undefined) {\n throw new TypeError(\n `The Manifest lists no command ${name} of ${type.context}.${type.name}.`,\n );\n }\n return declared.routes;\n }\n\n /** The Manifest given, or the service's, fetched once (again after a failure). */\n private manifestOf(): Promise<RoutingManifest> {\n this.manifest ??= fetchManifest(this.client).catch((error: unknown) => {\n this.manifest = undefined;\n throw error;\n });\n return this.manifest;\n }\n}\n\n/**\n * The result a command was answered with, when it succeeded; else the error\n * that says why it did not, as Kotlin's `HttpCommandClient` settles one: a\n * rejected result rejects with a {@link CommandRejectedError}, a status this\n * client does not know (a newer service's) with a {@link WowProblemError}.\n */\nfunction settled<R>(result: CommandResult<R>): CommandResult<R> {\n if (result.status === CommandResultStatus.REJECTED) {\n throw new CommandRejectedError(result as RefusedResult);\n }\n if (!KNOWN_STATUSES.has(result.status)) {\n throw new WowProblemError({\n type: `urn:wow:error:${FrameworkErrorCodes.COMMAND_FAILED}`,\n title: 'Unknown command status',\n status: 200,\n code: FrameworkErrorCodes.COMMAND_FAILED,\n detail: `The command was answered with the status ${result.status}, which this client does not know: the service is newer than this client, so upgrade it.`,\n result: result as RefusedResult,\n });\n }\n return result;\n}\n\nconst KNOWN_STATUSES: ReadonlySet<string> = new Set(\n Object.values(CommandResultStatus),\n);\n"],"mappings":";;;;;;;;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,GACMI,IACJD,GAAS,YACL,MAAK,MAAaE,EAAU,SAASL,EAAK,IAAI,CAAC,EAC/C,UAAU,MACV,MAAQ3B,EAAK,SAAS6B,KAAQ7B,EAAK,SAAS,SAAS6B,CAAI,MAAM,EACjE,MACDH,IACGI,GAAS,UAAU,MAAK,MAAQ9B,EAAK,SAAS6B,CAAI,IAClD,KAAA;EACN,IAAIE,GAAU,WAAW,KAAA,GACvB,MAAU,UACR,iCAAiCF,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE;EAEF,OAAOI,EAAS;CAClB;CAGA,aAA+C;EAK7C,OAJA,KAAK,aAAaE,EAAc,KAAK,MAAM,CAAC,CAAC,OAAO,MAAmB;GAErE,MADA,KAAK,WAAW,KAAA,GACVhD;EACR,CAAC,GACM,KAAK;CACd;AACF;AAQA,SAASqC,EAAW,GAA4C;CAC9D,IAAIL,EAAO,WAAWG,EAAoB,UACxC,MAAM,IAAIC,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"}
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,G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,IAClD,KAAA;EACN,IAAIP,GAAU,WAAW,KAAA,GACvB,MAAU,UACR,iCAAiCO,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE;EAEF,OAAOL;CACT;CAGA,aAA+C;EAK7C,OAJA,KAAK,aAAaU,EAAc,KAAK,MAAM,CAAC,CAAC,OAAO,MAAmB;GAErE,MADA,KAAK,WAAW,KAAA,GACVpD;EACR,CAAC,GACM,KAAK;CACd;AACF;AAQA,SAASyC,EAAW,GAA4C;CAC9D,IAAIL,EAAO,WAAWG,EAAoB,UACxC,MAAM,IAAIC,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"}
@@ -1,2 +1,2 @@
1
- var e=Object.freeze({SNAPSHOT:`snapshot`,EVENT_STREAM:`events`,DATASET:`dataset`}),t=Object.freeze({STRING:`string`,INTEGER:`integer`,DECIMAL:`decimal`,BOOLEAN:`boolean`,OBJECT:`object`}),n=function(e){return e.UNKNOWN=`unknown`,e.NULL=`null`,e.SCALAR=`scalar`,e.OBJECT=`object`,e.ARRAY=`array`,e.UNION=`union`,e}({}),r=function(e){return e.LIST=`list`,e.PAGED=`paged`,e.CURSOR=`cursor`,e}({}),i=Object.freeze({IDENTITY:`identity`,AGGREGATE_ID:`aggregate-id`,TENANT_ID:`tenant-id`,OWNER_ID:`owner-id`,SPACE_ID:`space-id`,DELETED:`deleted`,EVENT_TIME:`event-time`,FIRST_EVENT_TIME:`first-event-time`}),a=Object.freeze({CURSOR_UNIQUE_SORT:`cursor-unique-sort`,COUNT_REQUIRES_FILTER:`count-requires-filter`,STARTS_WITH_REQUIRES_PREFIX:`starts-with-requires-prefix`,PARALLEL_ARRAY_SORT:`parallel-array-sort`,NULL_OR_EMPTY_AS_MISSING:`null-or-empty-as-missing`,ARRAY_EQUALITY:`array-equality`}),o=Object.freeze({TEMPORAL_DATE:`temporal-date`,TEMPORAL_EPOCH:`temporal-epoch`,TEMPORAL_FORMATTED:`temporal-formatted`,DECIMAL:`decimal`,MONEY:`money`,DURATION:`duration`,REFERENCE:`reference`}),s=function(e){return e.DISPLAY=`display`,e.CONFIDENTIAL=`confidential`,e}({});exports.PagingMode=r,exports.QueryConstraintTypes=a,exports.QueryFieldRoles=i,exports.QueryModels=e,exports.QuerySemanticTypes=o,exports.QueryValueKind=n,exports.QueryValueTypes=t,exports.SensitivityLevel=s;
1
+ var e=Object.freeze({SNAPSHOT:`snapshot`,EVENT_STREAM:`events`,DATASET:`dataset`}),t=Object.freeze({STRING:`string`,INTEGER:`integer`,DECIMAL:`decimal`,BOOLEAN:`boolean`,OBJECT:`object`}),n=function(e){return e.UNKNOWN=`unknown`,e.NULL=`null`,e.SCALAR=`scalar`,e.OBJECT=`object`,e.ARRAY=`array`,e.UNION=`union`,e}({}),r=function(e){return e.LIST=`list`,e.PAGED=`paged`,e.CURSOR=`cursor`,e}({}),i=Object.freeze({IDENTITY:`identity`,AGGREGATE_ID:`aggregate-id`,TENANT_ID:`tenant-id`,OWNER_ID:`owner-id`,SPACE_ID:`space-id`,DELETED:`deleted`,EVENT_TIME:`event-time`,FIRST_EVENT_TIME:`first-event-time`}),a=Object.freeze({CURSOR_UNIQUE_SORT:`cursor-unique-sort`,COUNT_REQUIRES_FILTER:`count-requires-filter`,STARTS_WITH_REQUIRES_PREFIX:`starts-with-requires-prefix`,PARALLEL_ARRAY_SORT:`parallel-array-sort`,NULL_OR_EMPTY_AS_MISSING:`null-or-empty-as-missing`,ARRAY_EQUALITY:`array-equality`,AGGREGATE_REQUIRED:`aggregate-required`}),o=Object.freeze({TEMPORAL_DATE:`temporal-date`,TEMPORAL_EPOCH:`temporal-epoch`,TEMPORAL_FORMATTED:`temporal-formatted`,DECIMAL:`decimal`,MONEY:`money`,DURATION:`duration`,REFERENCE:`reference`}),s=function(e){return e.DISPLAY=`display`,e.CONFIDENTIAL=`confidential`,e}({});exports.PagingMode=r,exports.QueryConstraintTypes=a,exports.QueryFieldRoles=i,exports.QueryModels=e,exports.QuerySemanticTypes=o,exports.QueryValueKind=n,exports.QueryValueTypes=t,exports.SensitivityLevel=s;
2
2
  //# sourceMappingURL=descriptor.cjs.map