@ahoo-wang/wow-client 10.0.0-beta.2 → 10.0.0-beta.4
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/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +15 -3
- package/dist/commands.d.ts +15 -3
- package/dist/commands.es.js +46 -46
- package/dist/commands.es.js.map +1 -1
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +96 -96
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.es.js +32 -32
- package/dist/dsl/aggregation/derived.cjs +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.es.js +11 -11
- package/dist/dsl/aggregation/groups.cjs +1 -1
- package/dist/dsl/aggregation/groups.cjs.map +1 -1
- package/dist/dsl/aggregation/groups.es.js +22 -22
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.es.js +11 -11
- package/dist/dsl/filter/expressionFilter.cjs +1 -1
- package/dist/dsl/filter/expressionFilter.cjs.map +1 -1
- package/dist/dsl/filter/expressionFilter.es.js +7 -7
- package/dist/dsl/filter/fieldFilters.cjs +1 -1
- package/dist/dsl/filter/fieldFilters.cjs.map +1 -1
- package/dist/dsl/filter/fieldFilters.es.js +61 -61
- package/dist/dsl/filter/logicalFilters.cjs +1 -1
- package/dist/dsl/filter/logicalFilters.cjs.map +1 -1
- package/dist/dsl/filter/logicalFilters.es.js +19 -19
- package/dist/dsl/filter/metadataFilters.cjs +1 -1
- package/dist/dsl/filter/metadataFilters.cjs.map +1 -1
- package/dist/dsl/filter/metadataFilters.es.js +31 -31
- package/dist/dsl/filter/scope.cjs +1 -1
- package/dist/dsl/filter/scope.cjs.map +1 -1
- package/dist/dsl/filter/scope.es.js +18 -18
- package/dist/dsl/filter/searchFilter.cjs +1 -1
- package/dist/dsl/filter/searchFilter.cjs.map +1 -1
- package/dist/dsl/filter/searchFilter.es.js +6 -6
- package/dist/dsl/filter/timeFilters.cjs +1 -1
- package/dist/dsl/filter/timeFilters.cjs.map +1 -1
- package/dist/dsl/filter/timeFilters.es.js +47 -47
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.es.js +8 -8
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.es.js +8 -8
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.es.js +12 -12
- package/dist/index.cjs +1 -1
- package/dist/index.es.js +12 -12
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.es.js +11 -11
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.es.js +22 -22
- package/package.json +4 -4
package/dist/commands.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./frameworkErrors.cjs"),t=require("./
|
|
1
|
+
const e=require("./frameworkErrors.cjs"),t=require("./http.cjs"),n=require("./wire.cjs"),r=require("./manifest.cjs"),i=require("./problem.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`};function c(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)t.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);let n=Date.now();for(let t=5;t>=0;t--)e[t]=n%256,n=Math.floor(n/256);e[6]=e[6]&15|112,e[8]=e[8]&63|128;let r=Array.from(e,e=>e.toString(16).padStart(2,`0`));return[r.slice(0,4),r.slice(4,6),r.slice(6,8),r.slice(8,10),r.slice(10,16)].map(e=>e.join(``)).join(`-`)}async function l(e,t){try{return await t()}catch(t){throw i.rememberRequestId(t,e),t}}var u=`wow.`,d=`{id}`;function f(e){return e.hops.length===1&&e.hops[0].stage===n.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,n,r,i){return{[t.WowHeaders.REQUEST_ID]:r,[t.WowHeaders.WAIT]:n===void 0||n.isDefault?void 0:o.formatWaitPlan(n),[t.WowHeaders.WAIT_TIMEOUT]:n!==void 0&&(e.timeout!==void 0||n.timeout!==o.WaitPlan.DEFAULT_TIMEOUT)?o.formatWaitTimeout(n.timeout):void 0,[t.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=new r.ManifestSource(e,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`),t))}async exchange(e,t){let r=e.requestId??c();return l(r,async()=>{let a;try{a=await(await this.post(e,t,r)).json()}catch(e){throw e instanceof i.WowProblemError&&e.result?.status===n.CommandResultStatus.REJECTED?new i.CommandRejectedError(e.result,{problem:e.problem,cause:e}):e}return b(a)})}async post(e,n,r,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 t.send(this.client,{method:s.method,path:s.path,headers:_(e,n,r,i),...s.method===`DELETE`?{}:{body:h(e,o)},numbers:{body: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.manifest.read(e.signal)).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}};function b(t){if(t.status===n.CommandResultStatus.REJECTED)throw new i.CommandRejectedError(t);if(!x.has(t.status))throw new i.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 ${t.status}, which this client does not know: the service is newer than this client, so upgrade it.`,result:t});return t}var x=new Set(Object.values(n.CommandResultStatus));exports.CommandClient=y,exports.LifecycleCommands=s,exports.newRequestId=c;
|
|
2
2
|
//# sourceMappingURL=commands.cjs.map
|
package/dist/commands.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.cjs","names":["Stage","WaitPlan","WowHeaders","formatWaitPlan","formatWaitTimeout","ManifestSource","commandResults","WowProblemError","CommandResultStatus","CommandRejectedError","send","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 type Answer,\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 ManifestSource,\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} 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/**\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 readonly manifest: ManifestSource;\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 = new ManifestSource(client, 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 requestId,\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 (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\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<Answer> {\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 // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: 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.manifest.read(request.signal)).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\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,mMAqJA,IAAamB,EAAoB,CAC/B,iBAAkB,gCAClB,kBAAmB,iCACnB,eAAgB,8BAChB,eAAgB,6BAClB,EAqBA,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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GAAGd,EAAQ,oEACb,EAEF,IAAMe,EAAS,GAAGD,EAAK,QAAQ,GAAGA,EAAK,KAAK,GACtCE,EAAOhB,EAAQ,WAAWe,CAAM,EAClCf,EAAQ,MAAMe,EAAO,MAAM,EAC3Bf,EACEiB,GAAW,MAAM,KAAK,SAAS,KAAK9B,EAAQ,MAAM,EAAA,CAAG,SAAS,KAClE,GAAQI,EAAK,OAASuB,EAAK,OAC7B,EACMJ,EACJO,GAAS,YACL,KAAK,GAAaC,EAAU,OAASJ,EAAK,IAAI,CAAC,EAC/C,UAAU,KACV,GAAQvB,EAAK,OAASyB,GAAQzB,EAAK,SAAS,SAASyB,CAAI,IAAM,EACjE,IACDH,EACGI,GAAS,UAAU,KAAK,GAAQ1B,EAAK,OAASyB,CAAI,EAClD,IAAA,IACN,GAAIN,GAAU,SAAW,IAAA,GACvB,MAAU,UACR,iCAAiCM,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE,EAEF,OAAOJ,CACT,CACF,EAQA,SAASD,EAAW,EAA4C,CAC9D,GAAID,EAAO,SAAWjD,EAAAA,oBAAoB,SACxC,MAAM,IAAIC,EAAAA,qBAAqBgD,CAAuB,EAExD,GAAI,CAACW,EAAe,IAAIX,EAAO,MAAM,EACnC,MAAM,IAAIlD,EAAAA,gBAAgB,CACxB,KAAM,iBAAiBI,EAAAA,oBAAoB,iBAC3C,MAAO,yBACP,OAAQ,IACR,KAAMA,EAAAA,oBAAoB,eAC1B,OAAQ,4CAA4C8C,EAAO,OAAO,0FAC1D,QACV,CAAC,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAO5D,EAAAA,mBAAmB,CACnC,E"}
|
|
1
|
+
{"version":3,"file":"commands.cjs","names":["Stage","WaitPlan","WowHeaders","formatWaitPlan","formatWaitTimeout","ManifestSource","commandResults","WowProblemError","CommandResultStatus","CommandRejectedError","send","FrameworkErrorCodes","require_frameworkErrors","require_http","require_wire","require_manifest","require_problem","require_streams","require_wait","LifecycleCommands","newRequestId","bytes","crypto","index","time","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 type Answer,\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 ManifestSource,\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} 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/**\n * A new request id (`Wow-Request-Id`): a UUIDv7 (RFC 9562), the Unix\n * milliseconds it was made in, then random bits. The client generates one\n * for a command sent without; generate it first to retry with it however the\n * request fails.\n *\n * The time comes first so that ids sort by when they were made, as the\n * Kotlin client's do: the service keeps a unique index on the request id,\n * and ids that arrive in order insert at its end rather than at a random\n * page. Ids made within one millisecond share its prefix and order among\n * themselves at random, which keeps them on the same page without a counter\n * shared across calls.\n *\n * The random bits come from `crypto.getRandomValues`, which a page served\n * over plain HTTP has too (it lacks only `randomUUID`), else from\n * `Math.random`.\n */\nexport function newRequestId(): string {\n const bytes = new Uint8Array(16);\n const crypto = globalThis.crypto;\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 // The 48-bit timestamp, big-endian, in the first six bytes.\n let time = Date.now();\n for (let index = 5; index >= 0; index--) {\n bytes[index] = time % 256;\n time = Math.floor(time / 256);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\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 readonly manifest: ManifestSource;\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 = new ManifestSource(client, 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 requestId,\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 (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\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<Answer> {\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 // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: 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.manifest.read(request.signal)).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\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,mMAqJA,IAAamB,EAAoB,CAC/B,iBAAkB,gCAClB,kBAAmB,iCACnB,eAAgB,8BAChB,eAAgB,6BAClB,EAiCA,SAAgBC,GAAuB,CACrC,IAAMC,EAAQ,IAAI,WAAW,EAAE,EACzBC,EAAS,WAAW,OAC1B,GAAI,OAAOA,GAAQ,iBAAoB,WACrCA,EAAO,gBAAgBD,CAAK,OAE5B,IAAK,IAAIE,EAAQ,EAAGA,EAAQF,EAAM,OAAQ,IACxC,EAAME,GAAS,KAAK,MAAM,KAAK,OAAO,EAAI,GAAG,EAIjD,IAAIC,EAAO,KAAK,IAAI,EACpB,IAAK,IAAID,EAAQ,EAAGA,GAAS,EAAG,IAC9B,EAAMA,GAASC,EAAO,IACtB,EAAO,KAAK,MAAMA,EAAO,GAAG,EAE9B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,EAAOhB,EAAQ,WAAWe,CAAM,EAClCf,EAAQ,MAAMe,EAAO,MAAM,EAC3Bf,EACEiB,GAAW,MAAM,KAAK,SAAS,KAAK9B,EAAQ,MAAM,EAAA,CAAG,SAAS,KAClE,GAAQI,EAAK,OAASuB,EAAK,OAC7B,EACMJ,EACJO,GAAS,YACL,KAAK,GAAaC,EAAU,OAASJ,EAAK,IAAI,CAAC,EAC/C,UAAU,KACV,GAAQvB,EAAK,OAASyB,GAAQzB,EAAK,SAAS,SAASyB,CAAI,IAAM,EACjE,IACDH,EACGI,GAAS,UAAU,KAAK,GAAQ1B,EAAK,OAASyB,CAAI,EAClD,IAAA,IACN,GAAIN,GAAU,SAAW,IAAA,GACvB,MAAU,UACR,iCAAiCM,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE,EAEF,OAAOJ,CACT,CACF,EAQA,SAASD,EAAW,EAA4C,CAC9D,GAAID,EAAO,SAAWlD,EAAAA,oBAAoB,SACxC,MAAM,IAAIC,EAAAA,qBAAqBiD,CAAuB,EAExD,GAAI,CAACW,EAAe,IAAIX,EAAO,MAAM,EACnC,MAAM,IAAInD,EAAAA,gBAAgB,CACxB,KAAM,iBAAiBI,EAAAA,oBAAoB,iBAC3C,MAAO,yBACP,OAAQ,IACR,KAAMA,EAAAA,oBAAoB,eAC1B,OAAQ,4CAA4C+C,EAAO,OAAO,0FAC1D,QACV,CAAC,EAEH,OAAOA,CACT,CAEA,IAAMW,EAAsC,IAAI,IAC9C,OAAO,OAAO7D,EAAAA,mBAAmB,CACnC,E"}
|
package/dist/commands.d.cts
CHANGED
|
@@ -119,9 +119,21 @@ export interface TransferSpace {
|
|
|
119
119
|
readonly spaceId: string;
|
|
120
120
|
}
|
|
121
121
|
/**
|
|
122
|
-
* A new request id (`Wow-Request-Id`): a
|
|
123
|
-
*
|
|
124
|
-
*
|
|
122
|
+
* A new request id (`Wow-Request-Id`): a UUIDv7 (RFC 9562), the Unix
|
|
123
|
+
* milliseconds it was made in, then random bits. The client generates one
|
|
124
|
+
* for a command sent without; generate it first to retry with it however the
|
|
125
|
+
* request fails.
|
|
126
|
+
*
|
|
127
|
+
* The time comes first so that ids sort by when they were made, as the
|
|
128
|
+
* Kotlin client's do: the service keeps a unique index on the request id,
|
|
129
|
+
* and ids that arrive in order insert at its end rather than at a random
|
|
130
|
+
* page. Ids made within one millisecond share its prefix and order among
|
|
131
|
+
* themselves at random, which keeps them on the same page without a counter
|
|
132
|
+
* shared across calls.
|
|
133
|
+
*
|
|
134
|
+
* The random bits come from `crypto.getRandomValues`, which a page served
|
|
135
|
+
* over plain HTTP has too (it lacks only `randomUUID`), else from
|
|
136
|
+
* `Math.random`.
|
|
125
137
|
*/
|
|
126
138
|
export declare function newRequestId(): string;
|
|
127
139
|
/**
|
package/dist/commands.d.ts
CHANGED
|
@@ -119,9 +119,21 @@ export interface TransferSpace {
|
|
|
119
119
|
readonly spaceId: string;
|
|
120
120
|
}
|
|
121
121
|
/**
|
|
122
|
-
* A new request id (`Wow-Request-Id`): a
|
|
123
|
-
*
|
|
124
|
-
*
|
|
122
|
+
* A new request id (`Wow-Request-Id`): a UUIDv7 (RFC 9562), the Unix
|
|
123
|
+
* milliseconds it was made in, then random bits. The client generates one
|
|
124
|
+
* for a command sent without; generate it first to retry with it however the
|
|
125
|
+
* request fails.
|
|
126
|
+
*
|
|
127
|
+
* The time comes first so that ids sort by when they were made, as the
|
|
128
|
+
* Kotlin client's do: the service keeps a unique index on the request id,
|
|
129
|
+
* and ids that arrive in order insert at its end rather than at a random
|
|
130
|
+
* page. Ids made within one millisecond share its prefix and order among
|
|
131
|
+
* themselves at random, which keeps them on the same page without a counter
|
|
132
|
+
* shared across calls.
|
|
133
|
+
*
|
|
134
|
+
* The random bits come from `crypto.getRandomValues`, which a page served
|
|
135
|
+
* over plain HTTP has too (it lacks only `randomUUID`), else from
|
|
136
|
+
* `Math.random`.
|
|
125
137
|
*/
|
|
126
138
|
export declare function newRequestId(): string;
|
|
127
139
|
/**
|
package/dist/commands.es.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { FrameworkErrorCodes as e } from "./frameworkErrors.es.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
2
|
+
import { WowHeaders as t, send as n } from "./http.es.js";
|
|
3
|
+
import { CommandResultStatus as r, Stage as i } from "./wire.es.js";
|
|
4
|
+
import { ManifestSource as a } from "./manifest.es.js";
|
|
5
|
+
import { CommandRejectedError as o, WowProblemError as s, rememberRequestId as c } from "./problem.es.js";
|
|
6
6
|
import { commandResults as l } from "./streams.es.js";
|
|
7
7
|
import { WaitPlan as u, formatWaitPlan as d, formatWaitTimeout as f } from "./wait.es.js";
|
|
8
8
|
// src/commands.ts
|
|
@@ -13,31 +13,31 @@ var p = {
|
|
|
13
13
|
TRANSFER_SPACE: "wow.lifecycle.TransferSpace"
|
|
14
14
|
};
|
|
15
15
|
function m() {
|
|
16
|
-
let e = globalThis.crypto;
|
|
17
|
-
if (typeof
|
|
18
|
-
let t =
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
let
|
|
16
|
+
let e = /* @__PURE__ */ new Uint8Array(16), t = globalThis.crypto;
|
|
17
|
+
if (typeof t?.getRandomValues == "function") t.getRandomValues(e);
|
|
18
|
+
else for (let t = 0; t < e.length; t++) e[t] = Math.floor(Math.random() * 256);
|
|
19
|
+
let n = Date.now();
|
|
20
|
+
for (let t = 5; t >= 0; t--) e[t] = n % 256, n = Math.floor(n / 256);
|
|
21
|
+
e[6] = e[6] & 15 | 112, e[8] = e[8] & 63 | 128;
|
|
22
|
+
let r = Array.from(e, (e) => e.toString(16).padStart(2, "0"));
|
|
23
23
|
return [
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
24
|
+
r.slice(0, 4),
|
|
25
|
+
r.slice(4, 6),
|
|
26
|
+
r.slice(6, 8),
|
|
27
|
+
r.slice(8, 10),
|
|
28
|
+
r.slice(10, 16)
|
|
29
29
|
].map((e) => e.join("")).join("-");
|
|
30
30
|
}
|
|
31
31
|
async function h(e, t) {
|
|
32
32
|
try {
|
|
33
33
|
return await t();
|
|
34
34
|
} catch (t) {
|
|
35
|
-
throw
|
|
35
|
+
throw c(t, e), t;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
38
|
var g = "wow.", _ = "{id}";
|
|
39
39
|
function v(e) {
|
|
40
|
-
return e.hops.length === 1 && e.hops[0].stage ===
|
|
40
|
+
return e.hops.length === 1 && e.hops[0].stage === i.ACCEPTED;
|
|
41
41
|
}
|
|
42
42
|
function y(e) {
|
|
43
43
|
return e.timeout === void 0 ? e.wait : (e.wait ?? u.DEFAULT).within(e.timeout);
|
|
@@ -72,13 +72,13 @@ function S(e) {
|
|
|
72
72
|
name: t[1]
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
|
-
function C(e,
|
|
75
|
+
function C(e, n, r, i) {
|
|
76
76
|
return {
|
|
77
|
-
[
|
|
78
|
-
[
|
|
79
|
-
[
|
|
80
|
-
[
|
|
81
|
-
Accept:
|
|
77
|
+
[t.REQUEST_ID]: r,
|
|
78
|
+
[t.WAIT]: n === void 0 || n.isDefault ? void 0 : d(n),
|
|
79
|
+
[t.WAIT_TIMEOUT]: n !== void 0 && (e.timeout !== void 0 || n.timeout !== u.DEFAULT_TIMEOUT) ? f(n.timeout) : void 0,
|
|
80
|
+
[t.IF_MATCH]: e.expectedVersion === void 0 ? void 0 : `"${e.expectedVersion}"`,
|
|
81
|
+
Accept: i
|
|
82
82
|
};
|
|
83
83
|
}
|
|
84
84
|
function w(e) {
|
|
@@ -89,7 +89,7 @@ function w(e) {
|
|
|
89
89
|
}
|
|
90
90
|
var T = class {
|
|
91
91
|
constructor(e = {}, t = {}) {
|
|
92
|
-
this.client = e, this.manifest = new
|
|
92
|
+
this.client = e, this.manifest = new a(e, t.manifest), this.bodyNumbers = t.bodyNumbers ?? {};
|
|
93
93
|
}
|
|
94
94
|
async send(e) {
|
|
95
95
|
let t = y(e);
|
|
@@ -103,28 +103,28 @@ var T = class {
|
|
|
103
103
|
let t = e.requestId ?? m();
|
|
104
104
|
return h(t, async () => l(await this.post(e, y(e), t, "text/event-stream"), t));
|
|
105
105
|
}
|
|
106
|
-
async exchange(e,
|
|
107
|
-
let
|
|
108
|
-
return h(
|
|
109
|
-
let
|
|
106
|
+
async exchange(e, t) {
|
|
107
|
+
let n = e.requestId ?? m();
|
|
108
|
+
return h(n, async () => {
|
|
109
|
+
let i;
|
|
110
110
|
try {
|
|
111
|
-
|
|
111
|
+
i = await (await this.post(e, t, n)).json();
|
|
112
112
|
} catch (e) {
|
|
113
|
-
throw e instanceof
|
|
113
|
+
throw e instanceof s && e.result?.status === r.REJECTED ? new o(e.result, {
|
|
114
114
|
problem: e.problem,
|
|
115
115
|
cause: e
|
|
116
116
|
}) : e;
|
|
117
117
|
}
|
|
118
|
-
return E(
|
|
118
|
+
return E(i);
|
|
119
119
|
});
|
|
120
120
|
}
|
|
121
|
-
async post(e, t,
|
|
122
|
-
let
|
|
123
|
-
return
|
|
124
|
-
method:
|
|
125
|
-
path:
|
|
126
|
-
headers: C(e, t,
|
|
127
|
-
...
|
|
121
|
+
async post(e, t, r, i) {
|
|
122
|
+
let a = await this.commandOf(e), o = a.idProperty, s = b(e, a.routes, o === void 0 ? e.id : void 0), c = w(e), l = this.bodyNumbers[e.command];
|
|
123
|
+
return n(this.client, {
|
|
124
|
+
method: s.method,
|
|
125
|
+
path: s.path,
|
|
126
|
+
headers: C(e, t, r, i),
|
|
127
|
+
...s.method === "DELETE" ? {} : { body: x(e, o) },
|
|
128
128
|
numbers: { body: l },
|
|
129
129
|
options: {
|
|
130
130
|
...c === void 0 ? {} : { scope: c },
|
|
@@ -142,19 +142,19 @@ var T = class {
|
|
|
142
142
|
return s;
|
|
143
143
|
}
|
|
144
144
|
};
|
|
145
|
-
function E(
|
|
146
|
-
if (
|
|
147
|
-
if (!D.has(
|
|
145
|
+
function E(t) {
|
|
146
|
+
if (t.status === r.REJECTED) throw new o(t);
|
|
147
|
+
if (!D.has(t.status)) throw new s({
|
|
148
148
|
type: `urn:wow:error:${e.COMMAND_FAILED}`,
|
|
149
149
|
title: "Unknown command status",
|
|
150
150
|
status: 200,
|
|
151
151
|
code: e.COMMAND_FAILED,
|
|
152
|
-
detail: `The command was answered with the status ${
|
|
153
|
-
result:
|
|
152
|
+
detail: `The command was answered with the status ${t.status}, which this client does not know: the service is newer than this client, so upgrade it.`,
|
|
153
|
+
result: t
|
|
154
154
|
});
|
|
155
|
-
return
|
|
155
|
+
return t;
|
|
156
156
|
}
|
|
157
|
-
var D = new Set(Object.values(
|
|
157
|
+
var D = new Set(Object.values(r));
|
|
158
158
|
export { T as CommandClient, p as LifecycleCommands, m as newRequestId };
|
|
159
159
|
|
|
160
160
|
//# sourceMappingURL=commands.es.js.map
|
package/dist/commands.es.js.map
CHANGED
|
@@ -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","route","routes","item","id","method","bodyOf","body","idProperty","named","typeNamed","parts","command","part","commandHeaders","WowHeaders","formatWaitPlan","formatWaitTimeout","accept","targetOf","CommandClient","client","ManifestSource","options","commandResults","result","WowProblemError","CommandResultStatus","CommandRejectedError","settled","declared","scope","bodyNumbers","send","system","type","prefix","name","context","aggregate","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 type Answer,\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 ManifestSource,\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} 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/**\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 readonly manifest: ManifestSource;\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 = new ManifestSource(client, 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 requestId,\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 (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\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<Answer> {\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 // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: 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.manifest.read(request.signal)).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\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":";;;;;;;;AAqJA,IAAaA,IAAoB;CAC/B,kBAAkB;CAClB,mBAAmB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EAAQ,SAClBoC,IAAStB,EAAQ,WAAWpB,CAAa,GACzC2C,IAAOrC,EAAQ,SAASoC,IAAS,KAAA,IAAYxB,EAAUE,CAAO;EACpE,IAAIuB,MAAS,KAAA,GACX,MAAU,UACR,GAAGvB,EAAQ,oEACb;EAEF,IAAMwB,IAAS,GAAGD,EAAK,QAAQ,GAAGA,EAAK,KAAK,IACtCE,IAAOzB,EAAQ,WAAWwB,CAAM,IAClCxB,EAAQ,MAAMwB,EAAO,MAAM,IAC3BxB,GACE0B,KAAW,MAAM,KAAK,SAAS,KAAKxC,EAAQ,MAAM,EAAA,CAAG,SAAS,MAClE,MAAQK,EAAK,SAASgC,EAAK,OAC7B,GACML,IACJQ,GAAS,YACL,MAAK,MAAaC,EAAU,SAASJ,EAAK,IAAI,CAAC,EAC/C,UAAU,MACV,MAAQhC,EAAK,SAASkC,KAAQlC,EAAK,SAAS,SAASkC,CAAI,MAAM,EACjE,MACDH,IACGI,GAAS,UAAU,MAAK,MAAQnC,EAAK,SAASkC,CAAI,IAClD,KAAA;EACN,IAAIP,GAAU,WAAW,KAAA,GACvB,MAAU,UACR,iCAAiCO,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE;EAEF,OAAOL;CACT;AACF;AAQA,SAASD,EAAW,GAA4C;CAC9D,IAAIJ,EAAO,WAAWE,EAAoB,UACxC,MAAM,IAAIC,EAAqBH,CAAuB;CAExD,IAAI,CAACe,EAAe,IAAIf,EAAO,MAAM,GACnC,MAAM,IAAIC,EAAgB;EACxB,MAAM,iBAAiBe,EAAoB;EAC3C,OAAO;EACP,QAAQ;EACR,MAAMA,EAAoB;EAC1B,QAAQ,4CAA4ChB,EAAO,OAAO;EAC1D;CACV,CAAC;CAEH,OAAOA;AACT;AAEA,IAAMe,IAAsC,IAAI,IAC9C,OAAO,OAAOb,CAAmB,CACnC"}
|
|
1
|
+
{"version":3,"file":"commands.es.js","names":["LifecycleCommands","newRequestId","bytes","crypto","index","time","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","ManifestSource","options","commandResults","result","WowProblemError","CommandResultStatus","CommandRejectedError","settled","declared","scope","bodyNumbers","send","system","type","prefix","name","context","aggregate","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 type Answer,\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 ManifestSource,\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} 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/**\n * A new request id (`Wow-Request-Id`): a UUIDv7 (RFC 9562), the Unix\n * milliseconds it was made in, then random bits. The client generates one\n * for a command sent without; generate it first to retry with it however the\n * request fails.\n *\n * The time comes first so that ids sort by when they were made, as the\n * Kotlin client's do: the service keeps a unique index on the request id,\n * and ids that arrive in order insert at its end rather than at a random\n * page. Ids made within one millisecond share its prefix and order among\n * themselves at random, which keeps them on the same page without a counter\n * shared across calls.\n *\n * The random bits come from `crypto.getRandomValues`, which a page served\n * over plain HTTP has too (it lacks only `randomUUID`), else from\n * `Math.random`.\n */\nexport function newRequestId(): string {\n const bytes = new Uint8Array(16);\n const crypto = globalThis.crypto;\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 // The 48-bit timestamp, big-endian, in the first six bytes.\n let time = Date.now();\n for (let index = 5; index >= 0; index--) {\n bytes[index] = time % 256;\n time = Math.floor(time / 256);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\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 readonly manifest: ManifestSource;\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 = new ManifestSource(client, 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 requestId,\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 (\n await this.post(request, plan, requestId)\n ).json<CommandResult<R>>();\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<Answer> {\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 // A result's numbers are the framework's; its `results` are the\n // service's own, which the Manifest gives no schema.\n numbers: { body: 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.manifest.read(request.signal)).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\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":";;;;;;;;AAqJA,IAAaA,IAAoB;CAC/B,kBAAkB;CAClB,mBAAmB;CACnB,gBAAgB;CAChB,gBAAgB;AAClB;AAiCA,SAAgBC,IAAuB;CACrC,IAAMC,oBAAQ,IAAI,WAAW,EAAE,GACzBC,IAAS,WAAW;CAC1B,IAAI,OAAOA,GAAQ,mBAAoB,YACrC,EAAO,gBAAgBD,CAAK;MAE5B,KAAK,IAAIE,IAAQ,GAAGA,IAAQF,EAAM,QAAQ,KACxC,EAAME,KAAS,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;CAIjD,IAAIC,IAAO,KAAK,IAAI;CACpB,KAAK,IAAID,IAAQ,GAAGA,KAAS,GAAG,KAE9B,AADA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AAO,MAAM,IAC3BxB,GACE0B,KAAW,MAAM,KAAK,SAAS,KAAKxC,EAAQ,MAAM,EAAA,CAAG,SAAS,MAClE,MAAQK,EAAK,SAASgC,EAAK,OAC7B,GACML,IACJQ,GAAS,YACL,MAAK,MAAaC,EAAU,SAASJ,EAAK,IAAI,CAAC,EAC/C,UAAU,MACV,MAAQhC,EAAK,SAASkC,KAAQlC,EAAK,SAAS,SAASkC,CAAI,MAAM,EACjE,MACDH,IACGI,GAAS,UAAU,MAAK,MAAQnC,EAAK,SAASkC,CAAI,IAClD,KAAA;EACN,IAAIP,GAAU,WAAW,KAAA,GACvB,MAAU,UACR,iCAAiCO,EAAK,MAAMF,EAAK,QAAQ,GAAGA,EAAK,KAAK,EACxE;EAEF,OAAOL;CACT;AACF;AAQA,SAASD,EAAW,GAA4C;CAC9D,IAAIJ,EAAO,WAAWE,EAAoB,UACxC,MAAM,IAAIC,EAAqBH,CAAuB;CAExD,IAAI,CAACe,EAAe,IAAIf,EAAO,MAAM,GACnC,MAAM,IAAIC,EAAgB;EACxB,MAAM,iBAAiBe,EAAoB;EAC3C,OAAO;EACP,QAAQ;EACR,MAAMA,EAAoB;EAC1B,QAAQ,4CAA4ChB,EAAO,OAAO;EAC1D;CACV,CAAC;CAEH,OAAOA;AACT;AAEA,IAAMe,IAAsC,IAAI,IAC9C,OAAO,OAAOb,CAAmB,CACnC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../
|
|
1
|
+
const e=require("../constantName.cjs"),t=require("../filter/operator.cjs"),n=require("./expressionTrees.cjs"),r=require("./sort.cjs"),i=require("./derived.cjs"),a=require("./groups.cjs"),o=require("./having.cjs"),s=require("./metrics.cjs"),c=require("./types.cjs");function l(e,t,n,r){if(n.length>r)throw TypeError(`${e} must contain at most ${r} ${t}.`)}function u(e){switch(e.op){case t.FilterOperator.SEARCH:throw TypeError(`Aggregation metric filters do not support search filters.`);case t.FilterOperator.ELEMENT_MATCH:throw TypeError(`Aggregation metric filters do not support [ELEMENT_MATCH].`);case t.FilterOperator.AND:case t.FilterOperator.OR:case t.FilterOperator.NOR:e.operands.forEach(u)}}function d(t,r){n.requireValidExpressionTrees(t.flatMap(e=>e.type===s.AggregationMetricType.NUMERIC||e.type===s.AggregationMetricType.DISTINCT_COUNT||e.type===s.AggregationMetricType.PERCENTILE?[e.expression]:[])),r.forEach(t=>{if(t.type===a.AggregationGroupType.TERMS||t.type===a.AggregationGroupType.HISTOGRAM){if(t.field===void 0==(t.expression===void 0))throw TypeError(`${e.constantName(t.type)} group requires exactly one of field and expression.`);if(t.expression&&n.requireValidExpressionTrees([t.expression]),t.type===a.AggregationGroupType.TERMS&&t.missingKey!==void 0&&t.expression)throw TypeError(`terms missingKey requires a field input.`);if(t.scope===a.AggregationGroupScope.ROOT&&t.expression)throw TypeError(`${e.constantName(t.type)} with a ROOT scope requires a field input.`)}})}var f=new Set([s.AggregationMetricType.ANY,s.AggregationMetricType.FIRST,s.AggregationMetricType.LAST]);function p(e){let t=new Map,n=new Set,r={nodes:0,windows:0};e.forEach(e=>{e.type===s.AggregationMetricType.DERIVED&&(m(e,t,n,r),n.add(e.alias)),t.set(e.alias,f.has(e.type)?e.type:void 0)})}function m(t,n,r,a){let o=[{expression:t.expression,depth:1}];for(;o.length>0;){let{expression:s,depth:l}=o.pop();if(l>c.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH)throw TypeError(`derived expression depth must be at most ${c.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`);if(a.nodes++,a.nodes>c.AGGREGATION_LIMITS.MAX_EXPRESSION_NODES)throw TypeError(`derived expressions must contain at most ${c.AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`);switch(s.type){case i.DerivedExpressionType.METRIC_REF:{let r=s.metric;if(!n.has(r))throw TypeError(`derived metric [${t.alias}] must reference a metric declared before it, but was [${r}].`);let i=n.get(r);if(i!==void 0)throw TypeError(`derived metric [${t.alias}] cannot reference ${e.constantName(i)} metric [${r}].`);break}case i.DerivedExpressionType.CONSTANT:if(!Number.isFinite(s.value))throw TypeError(`derived constant must be finite.`);break;case i.DerivedExpressionType.BINARY:o.push({expression:s.left,depth:l+1}),o.push({expression:s.right,depth:l+1});break;case i.DerivedExpressionType.TOTAL:case i.DerivedExpressionType.RUNNING:case i.DerivedExpressionType.PREVIOUS:case i.DerivedExpressionType.RANK:if(a.windows++,a.windows>c.AGGREGATION_LIMITS.MAX_WINDOWS)throw TypeError(`an aggregation must compute at most ${c.AGGREGATION_LIMITS.MAX_WINDOWS} windows.`);h(t.alias,s,n,r);break;default:throw TypeError(`Unsupported derived expression: ${String(s.type)}.`)}}}function h(t,n,r,i){let a=n.metric;if(!r.has(a))throw TypeError(`${e.constantName(n.type)} window of derived metric [${t}] must read a metric declared before it, but was [${a}].`);if(r.get(a)!==void 0||i.has(a))throw TypeError(`${e.constantName(n.type)} window of derived metric [${t}] must read a non-derived numeric metric, but was [${a}].`)}function g(e,t,n,r){if(!t.has(e))throw TypeError(`having condition [${e}] must reference a declared metric alias.`);if(n.has(e))throw TypeError(`having condition [${e}] cannot reference ANY metric.`);if(r.has(e))throw TypeError(`having condition [${e}] cannot reference FIRST or LAST metric.`)}function _(t,n,r){if(t===void 0)return;if(n.length===0)throw TypeError(`having requires at least one groupBy.`);let i=new Set(r.map(e=>e.alias)),a=new Set(r.filter(e=>e.type===s.AggregationMetricType.ANY).map(e=>e.alias)),l=new Set(r.filter(e=>e.type===s.AggregationMetricType.FIRST||e.type===s.AggregationMetricType.LAST).map(e=>e.alias)),u=[{expression:t,depth:1}];for(;u.length>0;){let{expression:t,depth:n}=u.pop();if(n>c.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH)throw TypeError(`having expression depth must be at most ${c.AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`);switch(t.type){case o.HavingExpressionType.CONDITION:if(g(t.metric,i,a,l),!Number.isFinite(t.value))throw TypeError(`having condition [${t.metric}] value must be finite.`);break;case o.HavingExpressionType.BETWEEN:if(g(t.metric,i,a,l),!Number.isFinite(t.lower)||!Number.isFinite(t.upper))throw TypeError(`having between [${t.metric}] bounds must be finite.`);if(t.lower>t.upper)throw TypeError(`having between [${t.metric}] lower bound must not exceed upper bound.`);break;case o.HavingExpressionType.IN:if(g(t.metric,i,a,l),t.values.length===0)throw TypeError(`having in [${t.metric}] values must not be empty.`);if(!t.values.every(Number.isFinite))throw TypeError(`having in [${t.metric}] values must be finite.`);break;case o.HavingExpressionType.IS_NULL:g(t.metric,i,a,l);break;case o.HavingExpressionType.AND:case o.HavingExpressionType.OR:if(t.operands.length===0)throw TypeError(`having ${e.constantName(t.type)} operands must not be empty.`);t.operands.forEach(e=>u.push({expression:e,depth:n+1}));break;default:throw TypeError(`Unsupported having expression: ${String(t.type)}.`)}}}function v(e,t,n){if(l(`sort`,`fields`,e,c.AGGREGATION_LIMITS.MAX_SORT_FIELDS),t.length===0&&e.length>0)throw TypeError(`sort requires at least one groupBy.`);let i=e.map(e=>e.field);if(new Set(i).size!==i.length)throw TypeError(`sort fields must be unique.`);if(!i.every(e=>n.includes(e)))throw TypeError(`sort fields must reference aggregation aliases.`);l(`effective sort`,`fields`,r.effectiveSort({groupBy:[...t],sort:[...e]}),c.AGGREGATION_LIMITS.MAX_SORT_FIELDS)}function y(e){let t=new Map((e.groupBy??[]).map(e=>[e.alias,e.scope===a.AggregationGroupScope.ROOT])),n=r.effectiveSort(e).flatMap(e=>t.has(e.field)?[t.get(e.field)]:[]),i=n.indexOf(!1);if(i>=0&&n.slice(i).includes(!0))throw TypeError(`groups with a ROOT scope must sort before the element groups.`)}function b(t){let n=t.elements??[],r=t.groupBy??[],i=t.metrics,o=t.sort??[];if(l(`elements`,`paths`,n,c.AGGREGATION_LIMITS.MAX_ELEMENTS),l(`groupBy`,`dimensions`,r,c.AGGREGATION_LIMITS.MAX_GROUPS),!Array.isArray(i)||i.length===0)throw TypeError(`metrics must not be empty.`);if(l(`metrics`,`entries`,i,c.AGGREGATION_LIMITS.MAX_METRICS),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1||t.limit>c.AGGREGATION_LIMITS.MAX_LIMIT))throw TypeError(`limit must be between 1 and ${c.AGGREGATION_LIMITS.MAX_LIMIT}.`);d(i,r),p(i),_(t.having,r,i),i.forEach(e=>{`filter`in e&&e.filter&&u(e.filter)}),r.forEach(t=>{if((t.type===a.AggregationGroupType.DATE_HISTOGRAM||t.type===a.AggregationGroupType.DATE_PART)&&t.dense===!0&&r.length!==1)throw TypeError(`dense requires ${e.constantName(t.type)} to be the only groupBy.`)});let s=[...r.map(e=>e.alias),...i.map(e=>e.alias)];if(new Set(s).size!==s.length)throw TypeError(`aggregation aliases must be unique.`);return v(o,r,s),n.length>0&&y(t),{...t,metrics:[...i]}}exports.admitAggregationQuery=b;
|
|
2
2
|
//# sourceMappingURL=admit.cjs.map
|