@ahoo-wang/wow-client 10.0.0-alpha.5 → 10.0.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -23
- package/README.zh-CN.md +66 -19
- package/dist/commands.cjs +1 -1
- package/dist/commands.cjs.map +1 -1
- package/dist/commands.d.cts +131 -61
- package/dist/commands.d.ts +131 -61
- package/dist/commands.es.js +117 -59
- package/dist/commands.es.js.map +1 -1
- package/dist/developmentCaller.cjs +2 -0
- package/dist/developmentCaller.cjs.map +1 -0
- package/dist/developmentCaller.d.cts +61 -0
- package/dist/developmentCaller.d.ts +61 -0
- package/dist/developmentCaller.es.js +26 -0
- package/dist/developmentCaller.es.js.map +1 -0
- package/dist/dsl/aggregation/admit.cjs +1 -1
- package/dist/dsl/aggregation/admit.cjs.map +1 -1
- package/dist/dsl/aggregation/admit.es.js +93 -93
- package/dist/dsl/aggregation/admit.es.js.map +1 -1
- package/dist/dsl/aggregation/builders.cjs +1 -1
- package/dist/dsl/aggregation/builders.cjs.map +1 -1
- package/dist/dsl/aggregation/builders.d.cts +20 -20
- package/dist/dsl/aggregation/builders.d.ts +20 -20
- package/dist/dsl/aggregation/builders.es.js +88 -88
- package/dist/dsl/aggregation/builders.es.js.map +1 -1
- package/dist/dsl/aggregation/derived.cjs.map +1 -1
- package/dist/dsl/aggregation/derived.d.cts +8 -8
- package/dist/dsl/aggregation/derived.d.ts +8 -8
- package/dist/dsl/aggregation/derived.es.js +1 -2
- package/dist/dsl/aggregation/derived.es.js.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.cjs.map +1 -1
- package/dist/dsl/aggregation/expressionTrees.es.js +1 -2
- package/dist/dsl/aggregation/having.cjs +1 -1
- package/dist/dsl/aggregation/having.cjs.map +1 -1
- package/dist/dsl/aggregation/having.d.cts +12 -12
- package/dist/dsl/aggregation/having.d.ts +12 -12
- package/dist/dsl/aggregation/having.es.js +33 -33
- package/dist/dsl/aggregation/having.es.js.map +1 -1
- package/dist/dsl/aggregation/sort.cjs.map +1 -1
- package/dist/dsl/aggregation/sort.es.js +1 -2
- package/dist/dsl/aggregation/types.cjs +1 -1
- package/dist/dsl/aggregation/types.cjs.map +1 -1
- package/dist/dsl/aggregation/types.d.cts +69 -69
- package/dist/dsl/aggregation/types.d.ts +69 -69
- package/dist/dsl/aggregation/types.es.js +15 -16
- package/dist/dsl/aggregation/types.es.js.map +1 -1
- package/dist/dsl/constantName.cjs +2 -0
- package/dist/dsl/constantName.cjs.map +1 -0
- package/dist/dsl/constantName.d.cts +9 -0
- package/dist/dsl/constantName.d.ts +9 -0
- package/dist/dsl/constantName.es.js +7 -0
- package/dist/dsl/constantName.es.js.map +1 -0
- package/dist/dsl/cursorQuery.cjs.map +1 -1
- package/dist/dsl/cursorQuery.es.js +1 -2
- package/dist/dsl/deletionState.cjs +1 -1
- package/dist/dsl/deletionState.cjs.map +1 -1
- package/dist/dsl/deletionState.d.cts +3 -3
- package/dist/dsl/deletionState.d.ts +3 -3
- package/dist/dsl/deletionState.es.js +2 -3
- package/dist/dsl/deletionState.es.js.map +1 -1
- package/dist/dsl/descriptor.cjs +1 -1
- package/dist/dsl/descriptor.cjs.map +1 -1
- package/dist/dsl/descriptor.d.cts +92 -42
- package/dist/dsl/descriptor.d.ts +92 -42
- package/dist/dsl/descriptor.es.js +36 -29
- package/dist/dsl/descriptor.es.js.map +1 -1
- package/dist/dsl/field.cjs.map +1 -1
- package/dist/dsl/field.es.js +1 -2
- package/dist/dsl/filter/builders.cjs +1 -1
- package/dist/dsl/filter/builders.cjs.map +1 -1
- package/dist/dsl/filter/builders.d.cts +53 -53
- package/dist/dsl/filter/builders.d.ts +53 -53
- package/dist/dsl/filter/builders.es.js +111 -111
- package/dist/dsl/filter/builders.es.js.map +1 -1
- package/dist/dsl/filter/datePattern.cjs.map +1 -1
- package/dist/dsl/filter/datePattern.es.js +1 -2
- package/dist/dsl/filter/operator.cjs +1 -1
- package/dist/dsl/filter/operator.cjs.map +1 -1
- package/dist/dsl/filter/operator.d.cts +57 -57
- package/dist/dsl/filter/operator.d.ts +57 -57
- package/dist/dsl/filter/operator.es.js +4 -5
- package/dist/dsl/filter/operator.es.js.map +1 -1
- package/dist/dsl/filter/scope.cjs +1 -1
- package/dist/dsl/filter/scope.cjs.map +1 -1
- package/dist/dsl/filter/scope.es.js +12 -12
- package/dist/dsl/filter/scope.es.js.map +1 -1
- package/dist/dsl/filter/validate.cjs +1 -1
- package/dist/dsl/filter/validate.cjs.map +1 -1
- package/dist/dsl/filter/validate.es.js +23 -23
- package/dist/dsl/filter/validate.es.js.map +1 -1
- package/dist/dsl/pagination.cjs.map +1 -1
- package/dist/dsl/pagination.es.js +1 -2
- package/dist/dsl/projection.cjs.map +1 -1
- package/dist/dsl/projection.d.cts +1 -1
- package/dist/dsl/projection.d.ts +1 -1
- package/dist/dsl/projection.es.js +1 -2
- package/dist/dsl/projection.es.js.map +1 -1
- package/dist/dsl/queryErrorCodes.cjs +1 -1
- package/dist/dsl/queryErrorCodes.cjs.map +1 -1
- package/dist/dsl/queryErrorCodes.d.cts +59 -48
- package/dist/dsl/queryErrorCodes.d.ts +59 -48
- package/dist/dsl/queryErrorCodes.es.js +51 -50
- package/dist/dsl/queryErrorCodes.es.js.map +1 -1
- package/dist/dsl/queryable.cjs +1 -1
- package/dist/dsl/queryable.cjs.map +1 -1
- package/dist/dsl/queryable.d.cts +25 -21
- package/dist/dsl/queryable.d.ts +25 -21
- package/dist/dsl/queryable.es.js +5 -5
- package/dist/dsl/queryable.es.js.map +1 -1
- package/dist/dsl/sort.cjs +1 -1
- package/dist/dsl/sort.cjs.map +1 -1
- package/dist/dsl/sort.d.cts +2 -2
- package/dist/dsl/sort.d.ts +2 -2
- package/dist/dsl/sort.es.js +4 -5
- package/dist/dsl/sort.es.js.map +1 -1
- package/dist/dsl.cjs +1 -1
- package/dist/dsl.es.js +3 -3
- package/dist/exactJson.cjs.map +1 -1
- package/dist/exactJson.d.cts +4 -4
- package/dist/exactJson.d.ts +4 -4
- package/dist/exactJson.es.js +1 -2
- package/dist/exactJson.es.js.map +1 -1
- package/dist/frameworkErrors.cjs +2 -0
- package/dist/frameworkErrors.cjs.map +1 -0
- package/dist/frameworkErrors.d.cts +121 -0
- package/dist/frameworkErrors.d.ts +121 -0
- package/dist/frameworkErrors.es.js +95 -0
- package/dist/frameworkErrors.es.js.map +1 -0
- package/dist/http.cjs +1 -1
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +4 -7
- package/dist/http.d.ts +4 -7
- package/dist/http.es.js +12 -20
- package/dist/http.es.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -7
- package/dist/index.d.ts +9 -7
- package/dist/index.es.js +11 -9
- package/dist/manifest.cjs +1 -1
- package/dist/manifest.cjs.map +1 -1
- package/dist/manifest.d.cts +33 -95
- package/dist/manifest.d.ts +33 -95
- package/dist/manifest.es.js +12 -7
- package/dist/manifest.es.js.map +1 -1
- package/dist/manifestTypes.d.cts +193 -0
- package/dist/manifestTypes.d.ts +193 -0
- package/dist/problem.cjs +1 -1
- package/dist/problem.cjs.map +1 -1
- package/dist/problem.d.cts +76 -111
- package/dist/problem.d.ts +76 -111
- package/dist/problem.es.js +45 -78
- package/dist/problem.es.js.map +1 -1
- package/dist/queries.cjs +1 -1
- package/dist/queries.cjs.map +1 -1
- package/dist/queries.d.cts +28 -51
- package/dist/queries.d.ts +28 -51
- package/dist/queries.es.js +49 -40
- package/dist/queries.es.js.map +1 -1
- package/dist/routes.cjs +2 -0
- package/dist/routes.cjs.map +1 -0
- package/dist/routes.d.cts +49 -0
- package/dist/routes.d.ts +49 -0
- package/dist/routes.es.js +33 -0
- package/dist/routes.es.js.map +1 -0
- package/dist/state.cjs +1 -1
- package/dist/state.cjs.map +1 -1
- package/dist/state.d.cts +56 -11
- package/dist/state.d.ts +56 -11
- package/dist/state.es.js +56 -21
- package/dist/state.es.js.map +1 -1
- package/dist/streams.cjs +1 -1
- package/dist/streams.cjs.map +1 -1
- package/dist/streams.d.cts +17 -13
- package/dist/streams.d.ts +17 -13
- package/dist/streams.es.js +50 -50
- package/dist/streams.es.js.map +1 -1
- package/dist/testing/wire.cjs +2 -0
- package/dist/testing/wire.cjs.map +1 -0
- package/dist/testing/wire.d.cts +29 -0
- package/dist/testing/wire.d.ts +29 -0
- package/dist/testing/wire.es.js +88 -0
- package/dist/testing/wire.es.js.map +1 -0
- package/dist/testing.cjs +1 -0
- package/dist/testing.d.cts +12 -0
- package/dist/testing.d.ts +12 -0
- package/dist/testing.es.js +3 -0
- package/dist/wait.cjs +1 -1
- package/dist/wait.cjs.map +1 -1
- package/dist/wait.d.cts +67 -18
- package/dist/wait.d.ts +67 -18
- package/dist/wait.es.js +59 -12
- package/dist/wait.es.js.map +1 -1
- package/dist/wire.cjs +1 -1
- package/dist/wire.cjs.map +1 -1
- package/dist/wire.d.cts +100 -50
- package/dist/wire.d.ts +100 -50
- package/dist/wire.es.js +17 -6
- package/dist/wire.es.js.map +1 -1
- package/package.json +26 -7
package/dist/streams.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.cjs","names":["toJsonServerSentEventStream","toServerSentEventStream","WowProblemError","isProblem","marksNothing","parseJson","require_exactJson","require_problem","_ahoo_wang_fetcher_eventstream","ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","response","controller","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","data","resumableQueryRows","options","numbers","events","from","row","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended (decision D253): `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One record of a streamed list, with its position. */\nexport interface StreamedRow<T> {\n /** The record. */\n readonly record: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes (decision D253). A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link StreamedRow.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; 5 by default, 0 never\n * resumes.\n */\n readonly maxRetries?: number;\n /** The wait before the first such retry, doubled for each next; 200 ms by default. */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; 10 s by default. */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list (decision D253), read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<StreamedRow<T>> {\n const {\n maxRetries = 5,\n initialDelayMs = 200,\n maxDelayMs = 10_000,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && !error.retry.retryable)\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retry?.afterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<StreamedRow<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id\n ? { record: data as T, position: id }\n : { record: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (!error.retry.retryable) throw error;\n stop = error;\n delayMs = error.retry.afterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":"8GAwBA,IAAMS,EAAY,MAGZC,EAAc,QAGdC,EAAY,MAGZC,EAAgB,UAYtB,SAAgBC,EAAkB,EAA4C,CAC5E,OAAA,EAAOb,EAAAA,4BAAAA,EAAAA,EACLC,EAAAA,wBAAAA,CAAwBa,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,CACA,UAAU,EAAO,EAAY,CAC3BC,EAAW,QAAQC,EAAM,IAAI,CAC/B,CACF,CAAC,CACH,CACF,CAqDA,IAAMC,EAAgC,eAChCC,EAA4B,WAGlC,SAASC,EAAM,EAAY,EAAqC,CAC9D,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAMC,MAAc,CAClB,aAAaC,CAAK,EAClBC,EAAOC,GAAQ,MAAM,CACvB,EACMF,EAAQ,eAAiB,CAC7BE,GAAQ,oBAAoB,QAASH,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AMN,CAAO,EAAI,CAClC5B,EAAW,MAAM,EACjB,MACF,CACF,CACF,EACA,OAAO,EAAQ,CAEb,MADA,GAAY,GACLmB,EAAO,OAAOkB,CAAM,CAC7B,CACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"streams.cjs","names":["toJsonServerSentEventStream","toServerSentEventStream","WowProblemError","isProblem","DEFAULT_RETRY","marksNothing","parseJson","require_exactJson","require_frameworkErrors","require_problem","_ahoo_wang_fetcher_eventstream","ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","response","controller","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","data","resumableQueryRows","options","numbers","events","from","row","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":"A,iJAyBA,IAAMW,EAAY,MAGZC,EAAc,QAGdC,EAAY,MAGZC,EAAgB,UAYtB,SAAgBC,EAAkB,EAA4C,CAC5E,OAAA,EAAOf,EAAAA,4BAAAA,EAAAA,EACLC,EAAAA,wBAAAA,CAAwBe,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,CACA,UAAU,EAAO,EAAY,CAC3BC,EAAW,QAAQC,EAAM,IAAI,CAC/B,CACF,CAAC,CACH,CACF,CAyDA,IAAMC,EAAgC,eAChCC,EAA4B,WAGlC,SAASC,EAAM,EAAY,EAAqC,CAC9D,OAAO,IAAI,SAAS,EAAS,IAAW,CACtC,IAAMC,MAAc,CAClB,aAAaC,CAAK,EAClBC,EAAOC,GAAQ,MAAM,CACvB,EACMF,EAAQ,eAAiB,CAC7BE,GAAQ,oBAAoB,QAASH,CAAK,EAC1CI,EAAQ,CACV,EAAGC,CAAE,EACLF,GAAQ,iBAAiB,QAASH,CAAK,CACzC,CAAC,CACH,CAEA,SAASM,EAAU,EAAgC,CACjD,OAAO,IAAI1B,EAAAA,gBACTC,EAAAA,UAAU0B,CAAI,EACVA,EACA,CAAE,KAAM,cAAe,MAAO,eAAgB,OAAQ,GAAI,CAChE,CACF,CAeA,SAAgBC,EACd,EACA,EAIA,EAII,CAAC,EAC0B,CAC/B,GAAM,CACJ,aAAa1B,EAAAA,cAAc,SAAW,EACtC,iBAAiBA,EA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K,EAC/B,GAAIY,EAAK,KAEP,EAAW,UAAU,+BAA+B,MAC/C,CACL,GAAM,CAAE,QAAO,KAAI,QAASA,EAAK,MACjC,GAAI9B,IAAUP,GAAaO,IAAUJ,EAAe,CAC9CsC,IAAI,EAAcA,GACtB,IACA,EAAW,EACXnC,EAAW,QACTmC,EAAK,CAAE,IAAKvB,EAAW,SAAUuB,CAAG,EAAI,CAAE,IAAKvB,CAAU,CAC3D,EACA,MACF,CACA,GAAIX,IAAUL,EAAW,CACvB,IAAMwC,EAAMxB,EACZ,GAAIwB,EAAI,SAAWjC,EAAU,CAC3BH,EAAW,MAAM,EACjB,MACF,CAEA,GADA,EAAW,UAAU,2BAA2BoC,EAAI,OAAO,EAAE,EACzD,CAACA,EAAI,UAAW,MAAMF,EACtBE,EAAI,SAAWlC,IAAc,EAAU,EAC7C,MAAO,GAAID,IAAUN,EAAa,CAChC,IAAMsC,EAAQtB,EAAUC,CAAI,EAC5B,GAAIqB,EAAM,QAAU,OAAQ,MAAMA,EAClC,EAAOA,EACP,EAAUA,EAAM,YAClB,MACE,QAEJ,CACF,OAASA,EAAO,CACd,GAAIA,IAAUC,GAAQD,aAAiBhD,EAAAA,gBAAiB,MAAMgD,EAC9D,EAAOA,CACT,CACA,GAAIV,EAAW,OAEf,GAAIf,GAAQ,QAAS,MAAMA,EAAO,OAClC,GAAIY,IAAgB,IAAA,IAAaC,EAAW,EAAG,MAAMa,EACrD,GAAI,CAAE,MAAMV,EAAOU,EAAMN,CAAO,EAAI,CAClC5B,EAAW,MAAM,EACjB,MACF,CACF,CACF,EACA,OAAO,EAAQ,CAEb,MADA,GAAY,GACLmB,EAAO,OAAOkB,CAAM,CAC7B,CACF,CAAC,CACH,C"}
|
package/dist/streams.d.cts
CHANGED
|
@@ -9,7 +9,7 @@ export type CommandResultStream<R = Record<string, unknown>> = ReadableStream<Co
|
|
|
9
9
|
/** The data of each event of `response`'s server-sent event stream. */
|
|
10
10
|
export declare function commandResults<R>(response: Response): CommandResultStream<R>;
|
|
11
11
|
/**
|
|
12
|
-
* Why a resumable streamed list ended
|
|
12
|
+
* Why a resumable streamed list ended: `complete` once every
|
|
13
13
|
* record was sent; the others are the server's, and resumable: the stream ran
|
|
14
14
|
* for its hold time, its store had no query permit for its next chunk, or
|
|
15
15
|
* the node is stopping.
|
|
@@ -22,10 +22,10 @@ export interface StreamEnd {
|
|
|
22
22
|
/** Whether asking again with `Last-Event-ID` goes on where it ended. */
|
|
23
23
|
readonly resumable: boolean;
|
|
24
24
|
}
|
|
25
|
-
/** One
|
|
26
|
-
export interface
|
|
27
|
-
/** The
|
|
28
|
-
readonly
|
|
25
|
+
/** One row of a streamed list, with its position. Kotlin's `Positioned`. */
|
|
26
|
+
export interface Positioned<T> {
|
|
27
|
+
/** The row. */
|
|
28
|
+
readonly row: T;
|
|
29
29
|
/**
|
|
30
30
|
* The record's position, its event's `id`: an opaque cursor token to
|
|
31
31
|
* resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a
|
|
@@ -34,28 +34,32 @@ export interface StreamedRow<T> {
|
|
|
34
34
|
readonly position?: string;
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
|
-
* How a streamed list resumes
|
|
37
|
+
* How a streamed list resumes. A stream the server ends with
|
|
38
38
|
* a resumable `end`, one cut off before its `end`, and one that fails with a
|
|
39
39
|
* retryable problem (a 429 after its `Retry-After`) are asked for again with
|
|
40
40
|
* `Last-Event-ID`, the position of the last record read, and go on strictly
|
|
41
41
|
* after it.
|
|
42
42
|
*/
|
|
43
43
|
export interface StreamResumeOptions {
|
|
44
|
-
/** Starts after this position: a {@link
|
|
44
|
+
/** Starts after this position: a {@link Positioned.position} read before. */
|
|
45
45
|
readonly lastEventId?: string;
|
|
46
46
|
/**
|
|
47
47
|
* How many times in a row the stream may be resumed without a record in
|
|
48
|
-
* between before it fails with what stopped it;
|
|
49
|
-
*
|
|
48
|
+
* between before it fails with what stopped it; by default one fewer than
|
|
49
|
+
* the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0
|
|
50
|
+
* never resumes.
|
|
50
51
|
*/
|
|
51
52
|
readonly maxRetries?: number;
|
|
52
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* The wait before the first such retry, doubled for each next; the
|
|
55
|
+
* catalog's backoff by default ({@link DEFAULT_RETRY}).
|
|
56
|
+
*/
|
|
53
57
|
readonly initialDelayMs?: number;
|
|
54
|
-
/** The longest wait between retries;
|
|
58
|
+
/** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */
|
|
55
59
|
readonly maxDelayMs?: number;
|
|
56
60
|
}
|
|
57
61
|
/**
|
|
58
|
-
* The records of a resumable streamed list
|
|
62
|
+
* The records of a resumable streamed list, read from
|
|
59
63
|
* `response` and, each time the stream is to be resumed, from what `reopen`
|
|
60
64
|
* answers for the position of the last record read (none before the first),
|
|
61
65
|
* with how many records were read so far: `undefined` when no more are
|
|
@@ -71,4 +75,4 @@ export declare function resumableQueryRows<T>(response: Response, reopen: (lastE
|
|
|
71
75
|
readonly signal?: AbortSignal;
|
|
72
76
|
/** The numbers of each record read as their exact text (review R4-Q, Q-9). */
|
|
73
77
|
readonly numbers?: TextNumbers;
|
|
74
|
-
}): ReadableStream<
|
|
78
|
+
}): ReadableStream<Positioned<T>>;
|
package/dist/streams.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export type CommandResultStream<R = Record<string, unknown>> = ReadableStream<Co
|
|
|
9
9
|
/** The data of each event of `response`'s server-sent event stream. */
|
|
10
10
|
export declare function commandResults<R>(response: Response): CommandResultStream<R>;
|
|
11
11
|
/**
|
|
12
|
-
* Why a resumable streamed list ended
|
|
12
|
+
* Why a resumable streamed list ended: `complete` once every
|
|
13
13
|
* record was sent; the others are the server's, and resumable: the stream ran
|
|
14
14
|
* for its hold time, its store had no query permit for its next chunk, or
|
|
15
15
|
* the node is stopping.
|
|
@@ -22,10 +22,10 @@ export interface StreamEnd {
|
|
|
22
22
|
/** Whether asking again with `Last-Event-ID` goes on where it ended. */
|
|
23
23
|
readonly resumable: boolean;
|
|
24
24
|
}
|
|
25
|
-
/** One
|
|
26
|
-
export interface
|
|
27
|
-
/** The
|
|
28
|
-
readonly
|
|
25
|
+
/** One row of a streamed list, with its position. Kotlin's `Positioned`. */
|
|
26
|
+
export interface Positioned<T> {
|
|
27
|
+
/** The row. */
|
|
28
|
+
readonly row: T;
|
|
29
29
|
/**
|
|
30
30
|
* The record's position, its event's `id`: an opaque cursor token to
|
|
31
31
|
* resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a
|
|
@@ -34,28 +34,32 @@ export interface StreamedRow<T> {
|
|
|
34
34
|
readonly position?: string;
|
|
35
35
|
}
|
|
36
36
|
/**
|
|
37
|
-
* How a streamed list resumes
|
|
37
|
+
* How a streamed list resumes. A stream the server ends with
|
|
38
38
|
* a resumable `end`, one cut off before its `end`, and one that fails with a
|
|
39
39
|
* retryable problem (a 429 after its `Retry-After`) are asked for again with
|
|
40
40
|
* `Last-Event-ID`, the position of the last record read, and go on strictly
|
|
41
41
|
* after it.
|
|
42
42
|
*/
|
|
43
43
|
export interface StreamResumeOptions {
|
|
44
|
-
/** Starts after this position: a {@link
|
|
44
|
+
/** Starts after this position: a {@link Positioned.position} read before. */
|
|
45
45
|
readonly lastEventId?: string;
|
|
46
46
|
/**
|
|
47
47
|
* How many times in a row the stream may be resumed without a record in
|
|
48
|
-
* between before it fails with what stopped it;
|
|
49
|
-
*
|
|
48
|
+
* between before it fails with what stopped it; by default one fewer than
|
|
49
|
+
* the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0
|
|
50
|
+
* never resumes.
|
|
50
51
|
*/
|
|
51
52
|
readonly maxRetries?: number;
|
|
52
|
-
/**
|
|
53
|
+
/**
|
|
54
|
+
* The wait before the first such retry, doubled for each next; the
|
|
55
|
+
* catalog's backoff by default ({@link DEFAULT_RETRY}).
|
|
56
|
+
*/
|
|
53
57
|
readonly initialDelayMs?: number;
|
|
54
|
-
/** The longest wait between retries;
|
|
58
|
+
/** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */
|
|
55
59
|
readonly maxDelayMs?: number;
|
|
56
60
|
}
|
|
57
61
|
/**
|
|
58
|
-
* The records of a resumable streamed list
|
|
62
|
+
* The records of a resumable streamed list, read from
|
|
59
63
|
* `response` and, each time the stream is to be resumed, from what `reopen`
|
|
60
64
|
* answers for the position of the last record read (none before the first),
|
|
61
65
|
* with how many records were read so far: `undefined` when no more are
|
|
@@ -71,4 +75,4 @@ export declare function resumableQueryRows<T>(response: Response, reopen: (lastE
|
|
|
71
75
|
readonly signal?: AbortSignal;
|
|
72
76
|
/** The numbers of each record read as their exact text (review R4-Q, Q-9). */
|
|
73
77
|
readonly numbers?: TextNumbers;
|
|
74
|
-
}): ReadableStream<
|
|
78
|
+
}): ReadableStream<Positioned<T>>;
|
package/dist/streams.es.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { marksNothing as e, parseJson as t } from "./exactJson.es.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
import { DEFAULT_RETRY as n } from "./frameworkErrors.es.js";
|
|
3
|
+
import { WowProblemError as r, isProblem as i } from "./problem.es.js";
|
|
4
|
+
import { toJsonServerSentEventStream as a, toServerSentEventStream as o } from "@ahoo-wang/fetcher-eventstream";
|
|
5
|
+
// src/streams.ts
|
|
6
|
+
var s = "row", c = "error", l = "end", u = "message";
|
|
7
|
+
function d(e) {
|
|
8
|
+
return a(o(e)).pipeThrough(new TransformStream({ transform(e, t) {
|
|
8
9
|
t.enqueue(e.data);
|
|
9
10
|
} }));
|
|
10
11
|
}
|
|
11
|
-
var
|
|
12
|
-
function
|
|
12
|
+
var f = "hold-expired", p = "complete";
|
|
13
|
+
function m(e, t) {
|
|
13
14
|
return new Promise((n, r) => {
|
|
14
15
|
let i = () => {
|
|
15
16
|
clearTimeout(a), r(t?.reason);
|
|
@@ -19,85 +20,84 @@ function p(e, t) {
|
|
|
19
20
|
t?.addEventListener("abort", i);
|
|
20
21
|
});
|
|
21
22
|
}
|
|
22
|
-
function
|
|
23
|
-
return new
|
|
23
|
+
function h(e) {
|
|
24
|
+
return new r(i(e) ? e : {
|
|
24
25
|
type: "about:blank",
|
|
25
26
|
title: "Query failed",
|
|
26
27
|
status: 500
|
|
27
28
|
});
|
|
28
29
|
}
|
|
29
|
-
function
|
|
30
|
-
let { maxRetries:
|
|
31
|
-
let r = e.event ===
|
|
30
|
+
function g(i, d, g = {}) {
|
|
31
|
+
let { maxRetries: _ = n.attempts - 1, initialDelayMs: v = n.backoffMs, maxDelayMs: y = n.maxWaitMs, signal: b } = g, x = g.numbers, S = (n) => (e(x) ? a(o(n)) : o(n).pipeThrough(new TransformStream({ transform(e, n) {
|
|
32
|
+
let r = e.event === s || e.event === u;
|
|
32
33
|
n.enqueue({
|
|
33
34
|
...e,
|
|
34
|
-
data: t(e.data, r ?
|
|
35
|
+
data: t(e.data, r ? x : void 0)
|
|
35
36
|
});
|
|
36
|
-
} }))).getReader(),
|
|
37
|
-
async function
|
|
37
|
+
} }))).getReader(), C = S(i), w = g.lastEventId, T = 0, E = 0, D = !1;
|
|
38
|
+
async function O(e, t) {
|
|
38
39
|
for (;;) {
|
|
39
|
-
if (
|
|
40
|
-
if (
|
|
41
|
-
let
|
|
42
|
-
|
|
40
|
+
if (b?.aborted) throw b.reason;
|
|
41
|
+
if (E++ >= _) throw e;
|
|
42
|
+
let n = t ?? Math.min(y, v * 2 ** (E - 1));
|
|
43
|
+
n > 0 && await m(n, b);
|
|
43
44
|
try {
|
|
44
|
-
let e = await
|
|
45
|
-
return e && (
|
|
46
|
-
} catch (
|
|
47
|
-
if (
|
|
48
|
-
t =
|
|
45
|
+
let e = await d(w, T);
|
|
46
|
+
return e && (C = S(e)), e !== void 0;
|
|
47
|
+
} catch (n) {
|
|
48
|
+
if (b?.aborted || n instanceof r && n.retry === "none") throw n;
|
|
49
|
+
t = n.retryAfterMs, e = n;
|
|
49
50
|
}
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
return new ReadableStream({
|
|
53
54
|
async pull(e) {
|
|
54
55
|
for (;;) {
|
|
55
|
-
let t,
|
|
56
|
+
let t, n;
|
|
56
57
|
try {
|
|
57
|
-
let
|
|
58
|
-
if (
|
|
58
|
+
let r = await C.read();
|
|
59
|
+
if (r.done) t = /* @__PURE__ */ TypeError("The query stream was cut off.");
|
|
59
60
|
else {
|
|
60
|
-
let { event: i, id: a, data:
|
|
61
|
-
if (i ===
|
|
62
|
-
a && (
|
|
63
|
-
|
|
61
|
+
let { event: i, id: a, data: o } = r.value;
|
|
62
|
+
if (i === s || i === u) {
|
|
63
|
+
a && (w = a), T++, E = 0, e.enqueue(a ? {
|
|
64
|
+
row: o,
|
|
64
65
|
position: a
|
|
65
|
-
} : {
|
|
66
|
+
} : { row: o });
|
|
66
67
|
return;
|
|
67
68
|
}
|
|
68
|
-
if (i ===
|
|
69
|
-
let
|
|
70
|
-
if (
|
|
69
|
+
if (i === l) {
|
|
70
|
+
let r = o;
|
|
71
|
+
if (r.reason === p) {
|
|
71
72
|
e.close();
|
|
72
73
|
return;
|
|
73
74
|
}
|
|
74
|
-
if (t = /* @__PURE__ */ TypeError(`The query stream ended: ${
|
|
75
|
-
|
|
76
|
-
} else if (i ===
|
|
77
|
-
let e =
|
|
78
|
-
if (
|
|
79
|
-
t = e,
|
|
75
|
+
if (t = /* @__PURE__ */ TypeError(`The query stream ended: ${r.reason}.`), !r.resumable) throw t;
|
|
76
|
+
r.reason === f && (n = 0);
|
|
77
|
+
} else if (i === c) {
|
|
78
|
+
let e = h(o);
|
|
79
|
+
if (e.retry === "none") throw e;
|
|
80
|
+
t = e, n = e.retryAfterMs;
|
|
80
81
|
} else continue;
|
|
81
82
|
}
|
|
82
83
|
} catch (e) {
|
|
83
|
-
if (e === t || e instanceof
|
|
84
|
+
if (e === t || e instanceof r) throw e;
|
|
84
85
|
t = e;
|
|
85
86
|
}
|
|
86
|
-
if (
|
|
87
|
-
if (
|
|
88
|
-
if (
|
|
89
|
-
if (!await
|
|
87
|
+
if (D) return;
|
|
88
|
+
if (b?.aborted) throw b.reason;
|
|
89
|
+
if (w === void 0 && T > 0) throw t;
|
|
90
|
+
if (!await O(t, n)) {
|
|
90
91
|
e.close();
|
|
91
92
|
return;
|
|
92
93
|
}
|
|
93
94
|
}
|
|
94
95
|
},
|
|
95
96
|
cancel(e) {
|
|
96
|
-
return
|
|
97
|
+
return D = !0, C.cancel(e);
|
|
97
98
|
}
|
|
98
99
|
});
|
|
99
100
|
}
|
|
100
|
-
|
|
101
|
-
export { u as commandResults, h as resumableQueryRows };
|
|
101
|
+
export { d as commandResults, g as resumableQueryRows };
|
|
102
102
|
|
|
103
103
|
//# sourceMappingURL=streams.es.js.map
|
package/dist/streams.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.es.js","names":["ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","toJsonServerSentEventStream","toServerSentEventStream","response","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","WowProblemError","isProblem","data","resumableQueryRows","options","numbers","events","marksNothing","from","row","parseJson","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","controller","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended (decision D253): `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One record of a streamed list, with its position. */\nexport interface StreamedRow<T> {\n /** The record. */\n readonly record: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes (decision D253). A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link StreamedRow.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; 5 by default, 0 never\n * resumes.\n */\n readonly maxRetries?: number;\n /** The wait before the first such retry, doubled for each next; 200 ms by default. */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; 10 s by default. */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list (decision D253), read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<StreamedRow<T>> {\n const {\n maxRetries = 5,\n initialDelayMs = 200,\n maxDelayMs = 10_000,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && !error.retry.retryable)\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retry?.afterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<StreamedRow<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id\n ? { record: data as T, position: id }\n : { record: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (!error.retry.retryable) throw error;\n stop = error;\n delayMs = error.retry.afterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return reader.cancel(reason);\n },\n });\n}\n"],"mappings":";;;;AAwBA,IAAMA,IAAY,OAGZC,IAAc,SAGdC,IAAY,OAGZC,IAAgB;AAYtB,SAAgBC,EAAkB,GAA4C;CAC5E,OAAOC,EACLC,EAAwBC,CAAQ,CAClC,CAAC,CAAC,YACA,IAAI,gBAGF,EACA,UAAU,GAAO,GAAY;EAC3B,EAAW,QAAQC,EAAM,IAAI;CAC/B,EACF,CAAC,CACH;AACF;AAqDA,IAAMC,IAAgC,gBAChCC,IAA4B;AAGlC,SAASC,EAAM,GAAY,GAAqC;CAC9D,OAAO,IAAI,SAAS,GAAS,MAAW;EACtC,IAAMC,UAAc;GAElB,AADA,aAAaC,CAAK,GAClBC,EAAOC,GAAQ,MAAM;EACvB,GACMF,IAAQ,iBAAiB;GAE7B,AADAE,GAAQ,oBAAoB,SAASH,CAAK,GAC1CI,EAAQ;EACV,GAAGC,CAAE;EACL,GAAQ,iBAAiB,SAASL,CAAK;CACzC,CAAC;AACH;AAEA,SAASM,EAAU,GAAgC;CACjD,OAAO,IAAIC,EACTC,EAAUC,CAAI,IACVA,IACA;EAAE,MAAM;EAAe,OAAO;EAAgB,QAAQ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Z,EAAO,KAAK;KAC/B,IAAIY,EAAK,MAEP,IAAO,gBAAI,UAAU,+BAA+B;UAC/C;MACL,IAAM,EAAE,UAAO,OAAI,YAASA,EAAK;MACjC,IAAIlC,MAAUR,KAAaQ,MAAUL,GAAe;OAIlD,AAHI2C,MAAI,IAAcA,IACtB,KACA,IAAW,GACXC,EAAW,QACTD,IACI;QAAE,QAAQzB;QAAW,UAAUyB;OAAG,IAClC,EAAE,QAAQzB,EAAU,CAC1B;OACA;MACF;MACA,IAAIb,MAAUN,GAAW;OACvB,IAAM8C,IAAM3B;OACZ,IAAI2B,EAAI,WAAWtC,GAAU;QAC3B,EAAW,MAAM;QACjB;OACF;OAEA,IADA,IAAO,gBAAI,UAAU,2BAA2BsC,EAAI,OAAO,EAAE,GACzD,CAACA,EAAI,WAAW,MAAMH;OAC1B,AAAIG,EAAI,WAAWvC,MAAc,IAAU;MAC7C,OAAO,IAAID,MAAUP,GAAa;OAChC,IAAM2C,IAAQ1B,EAAUG,CAAI;OAC5B,IAAI,CAACuB,EAAM,MAAM,WAAW,MAAMA;OAElC,AADA,IAAOA,GACP,IAAUA,EAAM,MAAM;MACxB,OACE;KAEJ;IACF,SAASA,GAAO;KACd,IAAIA,MAAUC,KAAQD,aAAiBzB,GAAiB,MAAMyB;KAC9D,IAAOA;IACT;IACA,IAAIV,GAAW;IAEf,IAAInB,GAAQ,SAAS,MAAMA,EAAO;IAClC,IAAIgB,MAAgB,KAAA,KAAaC,IAAW,GAAG,MAAMa;IACrD,IAAI,CAAE,MAAMV,EAAOU,GAAMN,CAAO,GAAI;KAClC,EAAW,MAAM;KACjB;IACF;GACF;EACF;EACA,OAAO,GAAQ;GAEb,OADA,IAAY,IACLT,EAAO,OAAOmB,CAAM;EAC7B;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"streams.es.js","names":["ROW_EVENT","ERROR_EVENT","END_EVENT","UNNAMED_EVENT","commandResults","toJsonServerSentEventStream","toServerSentEventStream","response","event","HOLD_EXPIRED","COMPLETE","sleep","abort","timer","reject","signal","resolve","ms","problemOf","WowProblemError","isProblem","data","resumableQueryRows","DEFAULT_RETRY","options","numbers","events","marksNothing","from","row","parseJson","reader","lastEventId","received","failures","cancelled","resume","maxRetries","cause","wait","delayMs","maxDelayMs","initialDelayMs","next","reopen","error","stop","id","controller","end","reason"],"sources":["../src/streams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n type JsonServerSentEvent,\n type ServerSentEvent,\n toJsonServerSentEventStream,\n toServerSentEventStream,\n} from '@ahoo-wang/fetcher-eventstream';\nimport { marksNothing, parseJson, type TextNumbers } from './exactJson.js';\nimport type { CommandResult } from './wire.js';\nimport { DEFAULT_RETRY } from './frameworkErrors.js';\nimport { isProblem, WowProblemError } from './problem.js';\n\n/** The event of each record of a streamed query list. */\nconst ROW_EVENT = 'row';\n\n/** The event that ends a streamed query list that failed: the problem. */\nconst ERROR_EVENT = 'error';\n\n/** The event that ends a resumable streamed query list (decision D253). */\nconst END_EVENT = 'end';\n\n/** The name an event without one is read under. */\nconst UNNAMED_EVENT = 'message';\n\n/**\n * The results of a command's event stream (`Accept: text/event-stream`), one\n * per hop, each event named by its stage. A rejection or a failure after\n * admission is the stream's last result, not an error.\n */\nexport type CommandResultStream<R = Record<string, unknown>> = ReadableStream<\n CommandResult<R>\n>;\n\n/** The data of each event of `response`'s server-sent event stream. */\nexport function commandResults<R>(response: Response): CommandResultStream<R> {\n return toJsonServerSentEventStream<CommandResult<R>>(\n toServerSentEventStream(response),\n ).pipeThrough(\n new TransformStream<\n JsonServerSentEvent<CommandResult<R>>,\n CommandResult<R>\n >({\n transform(event, controller) {\n controller.enqueue(event.data);\n },\n }),\n );\n}\n\n/**\n * Why a resumable streamed list ended: `complete` once every\n * record was sent; the others are the server's, and resumable: the stream ran\n * for its hold time, its store had no query permit for its next chunk, or\n * the node is stopping.\n */\nexport type StreamEndReason =\n 'complete' | 'hold-expired' | 'permit-reclaimed' | 'node-stopping';\n\n/** The data of the `end` event that ends a resumable streamed list. */\nexport interface StreamEnd {\n /** Why it ended. */\n readonly reason: StreamEndReason | (string & {});\n /** Whether asking again with `Last-Event-ID` goes on where it ended. */\n readonly resumable: boolean;\n}\n\n/** One row of a streamed list, with its position. Kotlin's `Positioned`. */\nexport interface Positioned<T> {\n /** The row. */\n readonly row: T;\n /**\n * The record's position, its event's `id`: an opaque cursor token to\n * resume after it ({@link StreamResumeOptions.lastEventId}). Absent from a\n * list whose sort cannot order a cursor, which cannot be resumed.\n */\n readonly position?: string;\n}\n\n/**\n * How a streamed list resumes. A stream the server ends with\n * a resumable `end`, one cut off before its `end`, and one that fails with a\n * retryable problem (a 429 after its `Retry-After`) are asked for again with\n * `Last-Event-ID`, the position of the last record read, and go on strictly\n * after it.\n */\nexport interface StreamResumeOptions {\n /** Starts after this position: a {@link Positioned.position} read before. */\n readonly lastEventId?: string;\n /**\n * How many times in a row the stream may be resumed without a record in\n * between before it fails with what stopped it; by default one fewer than\n * the catalog's attempts ({@link DEFAULT_RETRY}, as the Kotlin client), 0\n * never resumes.\n */\n readonly maxRetries?: number;\n /**\n * The wait before the first such retry, doubled for each next; the\n * catalog's backoff by default ({@link DEFAULT_RETRY}).\n */\n readonly initialDelayMs?: number;\n /** The longest wait between retries; the catalog's by default ({@link DEFAULT_RETRY}). */\n readonly maxDelayMs?: number;\n}\n\nconst HOLD_EXPIRED: StreamEndReason = 'hold-expired';\nconst COMPLETE: StreamEndReason = 'complete';\n\n/** Waits `ms`, or rejects once `signal` aborts. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n const abort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', abort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', abort);\n });\n}\n\nfunction problemOf(data: unknown): WowProblemError {\n return new WowProblemError(\n isProblem(data)\n ? data\n : { type: 'about:blank', title: 'Query failed', status: 500 },\n );\n}\n\n/**\n * The records of a resumable streamed list, read from\n * `response` and, each time the stream is to be resumed, from what `reopen`\n * answers for the position of the last record read (none before the first),\n * with how many records were read so far: `undefined` when no more are\n * wanted. Each record comes with its position. An `error` event that is not\n * retryable, a failure `reopen` cannot get past, and an abort of `signal`\n * error the stream.\n *\n * @param response - The first response\n * @param reopen - Asks for the stream again after a position\n * @param options - How the stream resumes, and what cancels it\n */\nexport function resumableQueryRows<T>(\n response: Response,\n reopen: (\n lastEventId: string | undefined,\n received: number,\n ) => Promise<Response | undefined>,\n options: StreamResumeOptions & {\n readonly signal?: AbortSignal;\n /** The numbers of each record read as their exact text (review R4-Q, Q-9). */\n readonly numbers?: TextNumbers;\n } = {},\n): ReadableStream<Positioned<T>> {\n const {\n maxRetries = DEFAULT_RETRY.attempts - 1,\n initialDelayMs = DEFAULT_RETRY.backoffMs,\n maxDelayMs = DEFAULT_RETRY.maxWaitMs,\n signal,\n } = options;\n const numbers = options.numbers;\n const events = (from: Response) =>\n (marksNothing(numbers)\n ? toJsonServerSentEventStream<unknown>(toServerSentEventStream(from))\n : toServerSentEventStream(from).pipeThrough(\n new TransformStream<ServerSentEvent, JsonServerSentEvent<unknown>>({\n transform(event, controller) {\n const row =\n event.event === ROW_EVENT || event.event === UNNAMED_EVENT;\n controller.enqueue({\n ...event,\n data: parseJson(event.data, row ? numbers : undefined),\n });\n },\n }),\n )\n ).getReader();\n let reader = events(response);\n let lastEventId = options.lastEventId;\n let received = 0;\n let failures = 0;\n // Set once the reader cancels: a read in flight then ends, and must not be\n // taken for a cut-off stream to ask for again.\n let cancelled = false;\n\n /** Asks for the stream again, or throws `cause` once out of retries. */\n async function resume(cause: unknown, delayMs?: number): Promise<boolean> {\n for (;;) {\n if (signal?.aborted) throw signal.reason;\n if (failures++ >= maxRetries) throw cause;\n const wait =\n delayMs ?? Math.min(maxDelayMs, initialDelayMs * 2 ** (failures - 1));\n if (wait > 0) await sleep(wait, signal);\n try {\n const next = await reopen(lastEventId, received);\n if (next) reader = events(next);\n return next !== undefined;\n } catch (error) {\n if (\n signal?.aborted ||\n (error instanceof WowProblemError && error.retry === 'none')\n ) {\n throw error;\n }\n delayMs = (error as WowProblemError).retryAfterMs;\n cause = error;\n }\n }\n }\n\n return new ReadableStream<Positioned<T>>({\n async pull(controller) {\n for (;;) {\n let stop: unknown;\n let delayMs: number | undefined;\n try {\n const next = await reader.read();\n if (next.done) {\n // Every stream ends with `end`: one without was cut off.\n stop = new TypeError('The query stream was cut off.');\n } else {\n const { event, id, data } = next.value;\n if (event === ROW_EVENT || event === UNNAMED_EVENT) {\n if (id) lastEventId = id;\n received++;\n failures = 0;\n controller.enqueue(\n id ? { row: data as T, position: id } : { row: data as T },\n );\n return;\n }\n if (event === END_EVENT) {\n const end = data as StreamEnd;\n if (end.reason === COMPLETE) {\n controller.close();\n return;\n }\n stop = new TypeError(`The query stream ended: ${end.reason}.`);\n if (!end.resumable) throw stop;\n if (end.reason === HOLD_EXPIRED) delayMs = 0;\n } else if (event === ERROR_EVENT) {\n const error = problemOf(data);\n if (error.retry === 'none') throw error;\n stop = error;\n delayMs = error.retryAfterMs;\n } else {\n continue;\n }\n }\n } catch (error) {\n if (error === stop || error instanceof WowProblemError) throw error;\n stop = error;\n }\n if (cancelled) return;\n // Only a stream read from the start, or whose records have positions, can be asked for again.\n if (signal?.aborted) throw signal.reason;\n if (lastEventId === undefined && received > 0) throw stop;\n if (!(await resume(stop, delayMs))) {\n controller.close();\n return;\n }\n }\n },\n cancel(reason) {\n cancelled = true;\n return re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,CAACA,EAAI,WAAW,MAAMH;OAC1B,AAAIG,EAAI,WAAWxC,MAAc,IAAU;MAC7C,OAAO,IAAID,MAAUP,GAAa;OAChC,IAAM4C,IAAQ3B,EAAUG,CAAI;OAC5B,IAAIwB,EAAM,UAAU,QAAQ,MAAMA;OAElC,AADA,IAAOA,GACP,IAAUA,EAAM;MAClB,OACE;KAEJ;IACF,SAASA,GAAO;KACd,IAAIA,MAAUC,KAAQD,aAAiB1B,GAAiB,MAAM0B;KAC9D,IAAOA;IACT;IACA,IAAIV,GAAW;IAEf,IAAIpB,GAAQ,SAAS,MAAMA,EAAO;IAClC,IAAIiB,MAAgB,KAAA,KAAaC,IAAW,GAAG,MAAMa;IACrD,IAAI,CAAE,MAAMV,EAAOU,GAAMN,CAAO,GAAI;KAClC,EAAW,MAAM;KACjB;IACF;GACF;EACF;EACA,OAAO,GAAQ;GAEb,OADA,IAAY,IACLT,EAAO,OAAOmB,CAAM;EAC7B;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../frameworkErrors.cjs"),t=require("../wire.cjs");function n(n,r={}){let{context:i,name:a}=n.type,o=r.status??t.CommandResultStatus.SUCCEEDED,s=r.commandId??`command-1`;return{format:1,commandId:s,requestId:`request-1`,correlationId:s,ref:n,hop:{stage:t.Stage.COMMITTED,context:i},function:{kind:t.FunctionKind.COMMAND,context:i,processor:a,name:`Command`},status:o,version:1,duplicate:!1,error:o===t.CommandResultStatus.SUCCEEDED?null:{code:o===t.CommandResultStatus.REJECTED?e.FrameworkErrorCodes.COMMAND_REFUSED:e.FrameworkErrorCodes.COMMAND_FAILED,message:`The command was ${o.toLowerCase()}.`},results:{},derived:[],signalTime:0,...r}}var r={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,409:`Conflict`,410:`Gone`,412:`Precondition Failed`,429:`Too Many Requests`,500:`Internal Server Error`,503:`Service Unavailable`,504:`Gateway Timeout`};function i(e,t,n={}){return{type:t===void 0?`about:blank`:`urn:wow:error:${t}`,title:r[e]??`HTTP ${e}`,status:e,...t===void 0?{}:{code:t},...n}}function a(e,t={}){let{extensions:n,...r}=e,i=new Headers(t.headers);return i.set(`Content-Type`,`application/problem+json`),new Response(JSON.stringify({...n,...r}),{...t,status:e.status,headers:i})}function o(e,t,n={}){return{tenantId:e.tenantId,aggregateId:e.id,version:1,ownerId:null,spaceId:null,deleted:!1,tags:{},firstEventTime:0,lastEventTime:0,operator:null,firstOperator:null,schedules:{},state:t,...n}}exports.commandResultOf=n,exports.problemOf=i,exports.problemResponse=a,exports.snapshotOf=o;
|
|
2
|
+
//# sourceMappingURL=wire.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wire.cjs","names":["CommandResultStatus","Stage","FunctionKind","FrameworkErrorCodes","require_frameworkErrors","require_wire","commandResultOf","ref","status","overrides","commandId","name","TITLES","problemOf","code","problemResponse","members","problem","headers","init","extensions","snapshotOf"],"sources":["../../src/testing/wire.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FrameworkErrorCodes, type Problem } from '../problem.js';\nimport {\n type AggregateRef,\n type CommandResult,\n CommandResultStatus,\n FunctionKind,\n Stage,\n type Snapshot,\n} from '../wire.js';\n\n/**\n * A command's result as a service answers it, for a test's fake: the command\n * `ref` names, committed (`succeeded` at `committed`, version 1) unless\n * `overrides` says otherwise. A `rejected` or `failed` one without an `error`\n * carries `wow.command.refused` or `wow.command.failed`.\n */\nexport function commandResultOf<R = Record<string, unknown>>(\n ref: AggregateRef,\n overrides: Partial<CommandResult<R>> = {},\n): CommandResult<R> {\n const { context, name } = ref.type;\n const status = overrides.status ?? CommandResultStatus.SUCCEEDED;\n const commandId = overrides.commandId ?? 'command-1';\n return {\n format: 1,\n commandId,\n requestId: 'request-1',\n correlationId: commandId,\n ref,\n hop: { stage: Stage.COMMITTED, context },\n function: {\n kind: FunctionKind.COMMAND,\n context,\n processor: name,\n name: 'Command',\n },\n status,\n version: 1,\n duplicate: false,\n error:\n status === CommandResultStatus.SUCCEEDED\n ? null\n : {\n code:\n status === CommandResultStatus.REJECTED\n ? FrameworkErrorCodes.COMMAND_REFUSED\n : FrameworkErrorCodes.COMMAND_FAILED,\n message: `The command was ${status.toLowerCase()}.`,\n },\n results: {} as R,\n derived: [],\n signalTime: 0,\n ...overrides,\n };\n}\n\n/** The reason phrases of the statuses a Wow service answers a problem with. */\nconst TITLES: Readonly<Record<number, string>> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * An RFC 9457 problem as a service answers it, of `status` and the Wow `code`\n * (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or\n * an expected error. Its title is the status's reason phrase unless\n * `overrides` says otherwise.\n */\nexport function problemOf(\n status: number,\n code?: string,\n overrides: Partial<Problem> = {},\n): Problem {\n return {\n type: code === undefined ? 'about:blank' : `urn:wow:error:${code}`,\n title: TITLES[status] ?? `HTTP ${status}`,\n status,\n ...(code === undefined ? {} : { code }),\n ...overrides,\n };\n}\n\n/**\n * The response a service answers `problem` with: `application/problem+json`,\n * its extension members written as members of their own, as the wire carries\n * them.\n */\nexport function problemResponse(\n problem: Problem,\n init: ResponseInit = {},\n): Response {\n const { extensions, ...members } = problem;\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/problem+json');\n return new Response(JSON.stringify({ ...extensions, ...members }), {\n ...init,\n status: problem.status,\n headers,\n });\n}\n\n/**\n * An aggregate's snapshot as a state read and a snapshot query answer it, for\n * a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous\n * caller, of no owner or space, not deleted, untagged and keeping no\n * schedules unless `overrides` says otherwise.\n */\nexport function snapshotOf<S>(\n ref: AggregateRef,\n state: S,\n overrides: Partial<\n Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>\n > = {},\n): Snapshot<S> {\n return {\n tenantId: ref.tenantId,\n aggregateId: ref.id,\n version: 1,\n ownerId: null,\n spaceId: null,\n deleted: false,\n tags: {},\n firstEventTime: 0,\n lastEventTime: 0,\n operator: null,\n firstOperator: null,\n schedules: {},\n state,\n ...overrides,\n };\n}\n"],"mappings":"A,mEA6BA,SAAgBM,EACd,EACA,EAAuC,CAAC,EACtB,CAClB,GAAM,CAAE,UAAS,QAASC,EAAI,KACxBC,EAASC,EAAU,QAAUT,EAAAA,oBAAoB,UACjDU,EAAYD,EAAU,WAAa,YACzC,MAAO,CACL,OAAQ,EACR,YACA,UAAW,YACX,cAAeC,EACf,MACA,IAAK,CAAE,MAAOT,EAAAA,MAAM,UAAW,SAAQ,EACvC,SAAU,CACR,KAAMC,EAAAA,aAAa,QACnB,UACA,UAAWS,EACX,KAAM,SACR,EACA,SACA,QAAS,EACT,UAAW,GACX,MACEH,IAAWR,EAAAA,oBAAoB,UAC3B,KACA,CACE,KACEQ,IAAWR,EAAAA,oBAAoB,SAC3BG,EAAAA,oBAAoB,gBACpBA,EAAAA,oBAAoB,eAC1B,QAAS,mBAAmBK,EAAO,YAAY,EAAE,EACnD,EACN,QAAS,CAAC,EACV,QAAS,CAAC,EACV,WAAY,EACZ,GAAGC,CACL,CACF,CAGA,IAAMG,EAA2C,CAC/C,IAAK,cACL,IAAK,eACL,IAAK,YACL,IAAK,YACL,IAAK,WACL,IAAK,OACL,IAAK,sBACL,IAAK,oBACL,IAAK,wBACL,IAAK,sBACL,IAAK,iBACP,EAQA,SAAgBC,EACd,EACA,EACA,EAA8B,CAAC,EACtB,CACT,MAAO,CACL,KAAMC,IAAS,IAAA,GAAY,cAAgB,iBAAiBA,IAC5D,MAAOF,EAAOJ,IAAW,QAAQA,IACjC,SACA,GAAIM,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,MAAK,EACrC,GAAGL,CACL,CACF,CAOA,SAAgBM,EACd,EACA,EAAqB,CAAC,EACZ,CACV,GAAM,CAAE,aAAY,GAAGC,GAAYC,EAC7BC,EAAU,IAAI,QAAQC,EAAK,OAAO,EAExC,OADAD,EAAQ,IAAI,eAAgB,0BAA0B,EAC/C,IAAI,SAAS,KAAK,UAAU,CAAE,GAAGE,EAAY,GAAGJ,CAAQ,CAAC,EAAG,CACjE,GAAGG,EACH,OAAQF,EAAQ,OAChB,SACF,CAAC,CACH,CAQA,SAAgBI,EACd,EACA,EACA,EAEI,CAAC,EACQ,CACb,MAAO,CACL,SAAUd,EAAI,SACd,YAAaA,EAAI,GACjB,QAAS,EACT,QAAS,KACT,QAAS,KACT,QAAS,GACT,KAAM,CAAC,EACP,eAAgB,EAChB,cAAe,EACf,SAAU,KACV,cAAe,KACf,UAAW,CAAC,EACZ,QACA,GAAGE,CACL,CACF,C"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Problem } from '../problem.cjs';
|
|
2
|
+
import { AggregateRef, CommandResult, Snapshot } from '../wire.cjs';
|
|
3
|
+
/**
|
|
4
|
+
* A command's result as a service answers it, for a test's fake: the command
|
|
5
|
+
* `ref` names, committed (`succeeded` at `committed`, version 1) unless
|
|
6
|
+
* `overrides` says otherwise. A `rejected` or `failed` one without an `error`
|
|
7
|
+
* carries `wow.command.refused` or `wow.command.failed`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function commandResultOf<R = Record<string, unknown>>(ref: AggregateRef, overrides?: Partial<CommandResult<R>>): CommandResult<R>;
|
|
10
|
+
/**
|
|
11
|
+
* An RFC 9457 problem as a service answers it, of `status` and the Wow `code`
|
|
12
|
+
* (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or
|
|
13
|
+
* an expected error. Its title is the status's reason phrase unless
|
|
14
|
+
* `overrides` says otherwise.
|
|
15
|
+
*/
|
|
16
|
+
export declare function problemOf(status: number, code?: string, overrides?: Partial<Problem>): Problem;
|
|
17
|
+
/**
|
|
18
|
+
* The response a service answers `problem` with: `application/problem+json`,
|
|
19
|
+
* its extension members written as members of their own, as the wire carries
|
|
20
|
+
* them.
|
|
21
|
+
*/
|
|
22
|
+
export declare function problemResponse(problem: Problem, init?: ResponseInit): Response;
|
|
23
|
+
/**
|
|
24
|
+
* An aggregate's snapshot as a state read and a snapshot query answer it, for
|
|
25
|
+
* a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous
|
|
26
|
+
* caller, of no owner or space, not deleted, untagged and keeping no
|
|
27
|
+
* schedules unless `overrides` says otherwise.
|
|
28
|
+
*/
|
|
29
|
+
export declare function snapshotOf<S>(ref: AggregateRef, state: S, overrides?: Partial<Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>>): Snapshot<S>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Problem } from '../problem.js';
|
|
2
|
+
import { AggregateRef, CommandResult, Snapshot } from '../wire.js';
|
|
3
|
+
/**
|
|
4
|
+
* A command's result as a service answers it, for a test's fake: the command
|
|
5
|
+
* `ref` names, committed (`succeeded` at `committed`, version 1) unless
|
|
6
|
+
* `overrides` says otherwise. A `rejected` or `failed` one without an `error`
|
|
7
|
+
* carries `wow.command.refused` or `wow.command.failed`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function commandResultOf<R = Record<string, unknown>>(ref: AggregateRef, overrides?: Partial<CommandResult<R>>): CommandResult<R>;
|
|
10
|
+
/**
|
|
11
|
+
* An RFC 9457 problem as a service answers it, of `status` and the Wow `code`
|
|
12
|
+
* (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or
|
|
13
|
+
* an expected error. Its title is the status's reason phrase unless
|
|
14
|
+
* `overrides` says otherwise.
|
|
15
|
+
*/
|
|
16
|
+
export declare function problemOf(status: number, code?: string, overrides?: Partial<Problem>): Problem;
|
|
17
|
+
/**
|
|
18
|
+
* The response a service answers `problem` with: `application/problem+json`,
|
|
19
|
+
* its extension members written as members of their own, as the wire carries
|
|
20
|
+
* them.
|
|
21
|
+
*/
|
|
22
|
+
export declare function problemResponse(problem: Problem, init?: ResponseInit): Response;
|
|
23
|
+
/**
|
|
24
|
+
* An aggregate's snapshot as a state read and a snapshot query answer it, for
|
|
25
|
+
* a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous
|
|
26
|
+
* caller, of no owner or space, not deleted, untagged and keeping no
|
|
27
|
+
* schedules unless `overrides` says otherwise.
|
|
28
|
+
*/
|
|
29
|
+
export declare function snapshotOf<S>(ref: AggregateRef, state: S, overrides?: Partial<Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>>): Snapshot<S>;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { FrameworkErrorCodes as e } from "../frameworkErrors.es.js";
|
|
2
|
+
import { CommandResultStatus as t, FunctionKind as n, Stage as r } from "../wire.es.js";
|
|
3
|
+
// src/testing/wire.ts
|
|
4
|
+
function i(i, a = {}) {
|
|
5
|
+
let { context: o, name: s } = i.type, c = a.status ?? t.SUCCEEDED, l = a.commandId ?? "command-1";
|
|
6
|
+
return {
|
|
7
|
+
format: 1,
|
|
8
|
+
commandId: l,
|
|
9
|
+
requestId: "request-1",
|
|
10
|
+
correlationId: l,
|
|
11
|
+
ref: i,
|
|
12
|
+
hop: {
|
|
13
|
+
stage: r.COMMITTED,
|
|
14
|
+
context: o
|
|
15
|
+
},
|
|
16
|
+
function: {
|
|
17
|
+
kind: n.COMMAND,
|
|
18
|
+
context: o,
|
|
19
|
+
processor: s,
|
|
20
|
+
name: "Command"
|
|
21
|
+
},
|
|
22
|
+
status: c,
|
|
23
|
+
version: 1,
|
|
24
|
+
duplicate: !1,
|
|
25
|
+
error: c === t.SUCCEEDED ? null : {
|
|
26
|
+
code: c === t.REJECTED ? e.COMMAND_REFUSED : e.COMMAND_FAILED,
|
|
27
|
+
message: `The command was ${c.toLowerCase()}.`
|
|
28
|
+
},
|
|
29
|
+
results: {},
|
|
30
|
+
derived: [],
|
|
31
|
+
signalTime: 0,
|
|
32
|
+
...a
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
var a = {
|
|
36
|
+
400: "Bad Request",
|
|
37
|
+
401: "Unauthorized",
|
|
38
|
+
403: "Forbidden",
|
|
39
|
+
404: "Not Found",
|
|
40
|
+
409: "Conflict",
|
|
41
|
+
410: "Gone",
|
|
42
|
+
412: "Precondition Failed",
|
|
43
|
+
429: "Too Many Requests",
|
|
44
|
+
500: "Internal Server Error",
|
|
45
|
+
503: "Service Unavailable",
|
|
46
|
+
504: "Gateway Timeout"
|
|
47
|
+
};
|
|
48
|
+
function o(e, t, n = {}) {
|
|
49
|
+
return {
|
|
50
|
+
type: t === void 0 ? "about:blank" : `urn:wow:error:${t}`,
|
|
51
|
+
title: a[e] ?? `HTTP ${e}`,
|
|
52
|
+
status: e,
|
|
53
|
+
...t === void 0 ? {} : { code: t },
|
|
54
|
+
...n
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function s(e, t = {}) {
|
|
58
|
+
let { extensions: n, ...r } = e, i = new Headers(t.headers);
|
|
59
|
+
return i.set("Content-Type", "application/problem+json"), new Response(JSON.stringify({
|
|
60
|
+
...n,
|
|
61
|
+
...r
|
|
62
|
+
}), {
|
|
63
|
+
...t,
|
|
64
|
+
status: e.status,
|
|
65
|
+
headers: i
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function c(e, t, n = {}) {
|
|
69
|
+
return {
|
|
70
|
+
tenantId: e.tenantId,
|
|
71
|
+
aggregateId: e.id,
|
|
72
|
+
version: 1,
|
|
73
|
+
ownerId: null,
|
|
74
|
+
spaceId: null,
|
|
75
|
+
deleted: !1,
|
|
76
|
+
tags: {},
|
|
77
|
+
firstEventTime: 0,
|
|
78
|
+
lastEventTime: 0,
|
|
79
|
+
operator: null,
|
|
80
|
+
firstOperator: null,
|
|
81
|
+
schedules: {},
|
|
82
|
+
state: t,
|
|
83
|
+
...n
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export { i as commandResultOf, o as problemOf, s as problemResponse, c as snapshotOf };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=wire.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wire.es.js","names":["commandResultOf","ref","status","overrides","CommandResultStatus","commandId","Stage","FunctionKind","name","FrameworkErrorCodes","TITLES","problemOf","code","problemResponse","members","problem","headers","init","extensions","snapshotOf"],"sources":["../../src/testing/wire.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FrameworkErrorCodes, type Problem } from '../problem.js';\nimport {\n type AggregateRef,\n type CommandResult,\n CommandResultStatus,\n FunctionKind,\n Stage,\n type Snapshot,\n} from '../wire.js';\n\n/**\n * A command's result as a service answers it, for a test's fake: the command\n * `ref` names, committed (`succeeded` at `committed`, version 1) unless\n * `overrides` says otherwise. A `rejected` or `failed` one without an `error`\n * carries `wow.command.refused` or `wow.command.failed`.\n */\nexport function commandResultOf<R = Record<string, unknown>>(\n ref: AggregateRef,\n overrides: Partial<CommandResult<R>> = {},\n): CommandResult<R> {\n const { context, name } = ref.type;\n const status = overrides.status ?? CommandResultStatus.SUCCEEDED;\n const commandId = overrides.commandId ?? 'command-1';\n return {\n format: 1,\n commandId,\n requestId: 'request-1',\n correlationId: commandId,\n ref,\n hop: { stage: Stage.COMMITTED, context },\n function: {\n kind: FunctionKind.COMMAND,\n context,\n processor: name,\n name: 'Command',\n },\n status,\n version: 1,\n duplicate: false,\n error:\n status === CommandResultStatus.SUCCEEDED\n ? null\n : {\n code:\n status === CommandResultStatus.REJECTED\n ? FrameworkErrorCodes.COMMAND_REFUSED\n : FrameworkErrorCodes.COMMAND_FAILED,\n message: `The command was ${status.toLowerCase()}.`,\n },\n results: {} as R,\n derived: [],\n signalTime: 0,\n ...overrides,\n };\n}\n\n/** The reason phrases of the statuses a Wow service answers a problem with. */\nconst TITLES: Readonly<Record<number, string>> = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 410: 'Gone',\n 412: 'Precondition Failed',\n 429: 'Too Many Requests',\n 500: 'Internal Server Error',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * An RFC 9457 problem as a service answers it, of `status` and the Wow `code`\n * (`urn:wow:error:<code>`; `about:blank` without one), for a test's fake or\n * an expected error. Its title is the status's reason phrase unless\n * `overrides` says otherwise.\n */\nexport function problemOf(\n status: number,\n code?: string,\n overrides: Partial<Problem> = {},\n): Problem {\n return {\n type: code === undefined ? 'about:blank' : `urn:wow:error:${code}`,\n title: TITLES[status] ?? `HTTP ${status}`,\n status,\n ...(code === undefined ? {} : { code }),\n ...overrides,\n };\n}\n\n/**\n * The response a service answers `problem` with: `application/problem+json`,\n * its extension members written as members of their own, as the wire carries\n * them.\n */\nexport function problemResponse(\n problem: Problem,\n init: ResponseInit = {},\n): Response {\n const { extensions, ...members } = problem;\n const headers = new Headers(init.headers);\n headers.set('Content-Type', 'application/problem+json');\n return new Response(JSON.stringify({ ...extensions, ...members }), {\n ...init,\n status: problem.status,\n headers,\n });\n}\n\n/**\n * An aggregate's snapshot as a state read and a snapshot query answer it, for\n * a test's fake: `ref`'s `state` at version 1, committed at 0 by an anonymous\n * caller, of no owner or space, not deleted, untagged and keeping no\n * schedules unless `overrides` says otherwise.\n */\nexport function snapshotOf<S>(\n ref: AggregateRef,\n state: S,\n overrides: Partial<\n Omit<Snapshot<S>, 'tenantId' | 'aggregateId' | 'state'>\n > = {},\n): Snapshot<S> {\n return {\n tenantId: ref.tenantId,\n aggregateId: ref.id,\n version: 1,\n ownerId: null,\n spaceId: null,\n deleted: false,\n tags: {},\n firstEventTime: 0,\n lastEventTime: 0,\n operator: null,\n firstOperator: null,\n schedules: {},\n state,\n ...overrides,\n };\n}\n"],"mappings":";;;AA6BA,SAAgBA,EACd,GACA,IAAuC,CAAC,GACtB;CAClB,IAAM,EAAE,YAAS,YAASC,EAAI,MACxBC,IAASC,EAAU,UAAUC,EAAoB,WACjDC,IAAYF,EAAU,aAAa;CACzC,OAAO;EACL,QAAQ;EACR;EACA,WAAW;EACX,eAAeE;EACf;EACA,KAAK;GAAE,OAAOC,EAAM;GAAW;EAAQ;EACvC,UAAU;GACR,MAAMC,EAAa;GACnB;GACA,WAAWC;GACX,MAAM;EACR;EACA;EACA,SAAS;EACT,WAAW;EACX,OACEN,MAAWE,EAAoB,YAC3B,OACA;GACE,MACEF,MAAWE,EAAoB,WAC3BK,EAAoB,kBACpBA,EAAoB;GAC1B,SAAS,mBAAmBP,EAAO,YAAY,EAAE;EACnD;EACN,SAAS,CAAC;EACV,SAAS,CAAC;EACV,YAAY;EACZ,GAAGC;CACL;AACF;AAGA,IAAMO,IAA2C;CAC/C,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;AACP;AAQA,SAAgBC,EACd,GACA,GACA,IAA8B,CAAC,GACtB;CACT,OAAO;EACL,MAAMC,MAAS,KAAA,IAAY,gBAAgB,iBAAiBA;EAC5D,OAAOF,EAAOR,MAAW,QAAQA;EACjC;EACA,GAAIU,MAAS,KAAA,IAAY,CAAC,IAAI,EAAE,QAAK;EACrC,GAAGT;CACL;AACF;AAOA,SAAgBU,EACd,GACA,IAAqB,CAAC,GACZ;CACV,IAAM,EAAE,eAAY,GAAGC,MAAYC,GAC7BC,IAAU,IAAI,QAAQC,EAAK,OAAO;CAExC,OADAD,EAAQ,IAAI,gBAAgB,0BAA0B,GAC/C,IAAI,SAAS,KAAK,UAAU;EAAE,GAAGE;EAAY,GAAGJ;CAAQ,CAAC,GAAG;EACjE,GAAGG;EACH,QAAQF,EAAQ;EAChB;CACF,CAAC;AACH;AAQA,SAAgBI,EACd,GACA,GACA,IAEI,CAAC,GACQ;CACb,OAAO;EACL,UAAUlB,EAAI;EACd,aAAaA,EAAI;EACjB,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,MAAM,CAAC;EACP,gBAAgB;EAChB,eAAe;EACf,UAAU;EACV,eAAe;EACf,WAAW,CAAC;EACZ;EACA,GAAGE;CACL;AACF"}
|
package/dist/testing.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./developmentCaller.cjs"),t=require("./testing/wire.cjs");exports.DevelopmentCallerHeaders=e.DevelopmentCallerHeaders,exports.commandResultOf=t.commandResultOf,exports.developmentCaller=e.developmentCaller,exports.developmentCallerHeaders=e.developmentCallerHeaders,exports.problemOf=t.problemOf,exports.problemResponse=t.problemResponse,exports.snapshotOf=t.snapshotOf;
|