@ahoo-wang/wow-view-store 9.9.0 → 10.0.0-alpha.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/README.md +84 -82
- package/README.zh-CN.md +61 -66
- package/dist/datasetWordings.d.ts +24 -25
- package/dist/errors.d.ts +54 -73
- package/dist/generated/index.d.ts +1 -0
- package/dist/generated/view-store/boundedContext.d.ts +36 -0
- package/dist/generated/view-store/dataset_wording/aggregate.d.ts +17 -0
- package/dist/generated/view-store/dataset_wording/commandClient.d.ts +32 -0
- package/dist/generated/view-store/dataset_wording/index.d.ts +3 -0
- package/dist/generated/view-store/dataset_wording/queryClient.d.ts +18 -0
- package/dist/generated/view-store/index.d.ts +5 -0
- package/dist/generated/view-store/types.d.ts +175 -0
- package/dist/generated/view-store/view/aggregate.d.ts +17 -0
- package/dist/generated/view-store/view/commandClient.d.ts +65 -0
- package/dist/generated/view-store/view/index.d.ts +3 -0
- package/dist/generated/view-store/view/queryClient.d.ts +18 -0
- package/dist/generated/view-store/view_preferences/aggregate.d.ts +17 -0
- package/dist/generated/view-store/view_preferences/commandClient.d.ts +22 -0
- package/dist/generated/view-store/view_preferences/index.d.ts +3 -0
- package/dist/generated/view-store/view_preferences/queryClient.d.ts +18 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.es.js +567 -490
- package/dist/index.es.js.map +1 -1
- package/dist/paths.d.ts +0 -32
- package/dist/remembered.d.ts +9 -0
- package/dist/source.d.ts +47 -0
- package/dist/systemViews.d.ts +21 -0
- package/dist/views.d.ts +49 -0
- package/dist/wire.d.ts +20 -73
- package/dist/wowViewStore.d.ts +111 -159
- package/package.json +7 -7
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":["LIST_LIMIT","WowViewStoreErrorCodes","REFERENCED_BY_SHARED_DASHBOARD","CODES","ErrorCodes","cause","wow","status","at","depth","message","found","UNFILLED","unfilled","ViewStoreError","code","failure","known","errorCode","toWowError","error","name","SHARED_OWNER_ID","SYSTEM_OWNER_ID","SYSTEM_TENANT_ID","SCOPE","PATHS","place","variables","view","SUMMARY_FIELDS","version","snapshot","aggregateId","state","body","preferences","order","defaultInstanceId","autoRun","lastTabs","a","b","tabs","x","y","LIST_LIMIT$1","REMEMBERED_WRITES","NOT_REPLAYED","REMEMBERED_SYSTEM_VIEWS","options","query","listQuery","filter","definitionId","LIST_ORDER","personal","shared","system","thrown","seen","summary","AUDIENCE_RANK","id","signal","input","context","requestId","made","write","result","revision","audience","answered","retry","answer","current","remembered","relocated","plan","expected","stored","replayed","read","places","index","response","strict","boards","titles","board","isSystemInstanceId","first","instance","NO_VIEW_STORE","singleQuery","method","url","request","path","ResultExtractors","CommandHeaders","CommandStage","asc","run","isViewStoreError","limit","key","value","LIST_LIMIT","ROUTES","snapshots","wording","dataset"],"sources":["../src/errors.ts","../src/paths.ts","../src/wire.ts","../src/wowViewStore.ts","../src/datasetWordings.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 ErrorCodes,\n toWowError,\n type BindingError,\n type WowError,\n} from '@ahoo-wang/wow-client';\nimport {\n ViewStoreError,\n type ViewStoreErrorCode,\n} from '@ahoo-wang/wow-view-engine';\n\n/**\n * The view store's own error codes, beside Wow's (`ErrorCodes` of\n * `@ahoo-wang/wow-client`).\n *\n * Named apart from the engine's `ViewStoreErrorCode` (the port's six codes): these\n * are the server's `errorCode` strings, which a `ViewStoreError` carries as\n * `detail.code`. Mirrors `ViewStoreErrorCodes` in\n * `view-store/wow-view-store-api/src/main/kotlin/me/ahoo/wow/viewstore/api/ViewStoreErrorCodes.kt`.\n */\nexport const WowViewStoreErrorCodes = Object.freeze({\n /** A write that is not a valid view or preferences write (HTTP 400). */\n VIEW_INVALID: 'ViewInvalid',\n /** The request carries no `CoSec-App-Id` (HTTP 400). */\n VIEW_APP_REQUIRED: 'ViewAppRequired',\n /** A system view is read-only (HTTP 403). */\n SYSTEM_VIEW_READ_ONLY: 'SystemViewReadOnly',\n /** The path's tenant or owner is missing, blank or invisible (HTTP 400). */\n VIEW_SCOPE_REQUIRED: 'ViewScopeRequired',\n /** The view store's event streams are closed to HTTP queries (HTTP 403). */\n VIEW_EVENT_STREAM_CLOSED: 'ViewEventStreamClosed',\n} as const);\n\n/**\n * The binding error code a claim refusal names each shared dashboard with\n * (`View.REFERENCED_BY_SHARED_DASHBOARD`): the board's id as `name`, its\n * title as `msg`.\n */\nexport const REFERENCED_BY_SHARED_DASHBOARD = 'referenced-by-shared-dashboard';\n\n/** The port's error code of each error code the server answers with. */\nconst CODES: Readonly<Record<string, ViewStoreErrorCode>> = {\n [ErrorCodes.COMMAND_EXPECT_VERSION_CONFLICT]: 'CONFLICT',\n [ErrorCodes.EVENT_VERSION_CONFLICT]: 'CONFLICT',\n [ErrorCodes.SOURCING_VERSION_CONFLICT]: 'CONFLICT',\n [ErrorCodes.NOT_FOUND]: 'NOT_FOUND',\n [ErrorCodes.ILLEGAL_ACCESS_DELETED_AGGREGATE]: 'NOT_FOUND',\n [ErrorCodes.ILLEGAL_ACCESS_OWNER_AGGREGATE]: 'FORBIDDEN',\n [ErrorCodes.ILLEGAL_ACCESS_SPACE_AGGREGATE]: 'FORBIDDEN',\n [ErrorCodes.ILLEGAL_ACCESS_QUERY_SCOPE]: 'FORBIDDEN',\n [WowViewStoreErrorCodes.SYSTEM_VIEW_READ_ONLY]: 'FORBIDDEN',\n [WowViewStoreErrorCodes.VIEW_EVENT_STREAM_CLOSED]: 'FORBIDDEN',\n [WowViewStoreErrorCodes.VIEW_INVALID]: 'INVALID',\n [WowViewStoreErrorCodes.VIEW_APP_REQUIRED]: 'INVALID',\n [WowViewStoreErrorCodes.VIEW_SCOPE_REQUIRED]: 'INVALID',\n [ErrorCodes.BAD_REQUEST]: 'INVALID',\n [ErrorCodes.ILLEGAL_ARGUMENT]: 'INVALID',\n // The server's own state, not the request: what a retry may get past.\n [ErrorCodes.ILLEGAL_STATE]: 'UNAVAILABLE',\n [ErrorCodes.COMMAND_VALIDATION]: 'INVALID',\n [ErrorCodes.DUPLICATE_AGGREGATE_ID]: 'INVALID',\n [ErrorCodes.QUERY_SCHEMA_VALIDATION]: 'INVALID',\n [ErrorCodes.REQUEST_TIMEOUT]: 'UNAVAILABLE',\n [ErrorCodes.TOO_MANY_REQUESTS]: 'UNAVAILABLE',\n [ErrorCodes.INTERNAL_SERVER_ERROR]: 'UNAVAILABLE',\n [ErrorCodes.QUERY_SCHEMA_UNAVAILABLE]: 'UNAVAILABLE',\n [ErrorCodes.QUERY_SCHEMA_CONFLICT]: 'UNAVAILABLE',\n};\n\n/**\n * A request that did not succeed, as the store reads it: the server's error,\n * when the server answered with one, and the HTTP status, when a response\n * came back at all.\n */\nexport class Failure {\n constructor(\n /** What the request threw. */\n readonly cause: unknown,\n /** The server's error, read from the failed response. */\n readonly wow?: WowError,\n /** The status of the failed response; absent when none came back. */\n readonly status?: number,\n ) {}\n\n /** The server's error code, if it answered with one. */\n get errorCode(): string | undefined {\n return this.wow?.errorCode;\n }\n\n get bindingErrors(): readonly BindingError[] {\n return this.wow?.bindingErrors ?? [];\n }\n\n /**\n * The path variable the fetcher's interceptors never filled, when that is\n * why the request was never sent: the host's set-up is wrong, not the\n * network.\n */\n get unfilled(): string | undefined {\n if (this.wow || this.status !== undefined) return undefined;\n for (let at: unknown = this.cause, depth = 0; at && depth < 4; depth++) {\n const message = (at as { message?: unknown }).message;\n const found = typeof message === 'string' ? UNFILLED.exec(message) : null;\n if (found) return found[1];\n at = (at as { cause?: unknown }).cause;\n }\n return undefined;\n }\n\n /**\n * The port's code for it (see {@link portCodeOf}). A path variable the\n * interceptors never filled is `INVALID`, as the server's own\n * `ViewScopeRequired` is: the request is wrong as built and a retry sends\n * the same — not `UNAVAILABLE`, which would offer one.\n */\n get code(): ViewStoreErrorCode {\n if (this.unfilled !== undefined) return 'INVALID';\n return portCodeOf(this.errorCode, this.status);\n }\n\n /**\n * Whether the server (or something in front of it) answered at all: a\n * response came back. An `UNAVAILABLE` that was answered is the server's\n * own error — a 5xx, a timeout it reported — and not the network.\n */\n get reached(): boolean {\n return this.wow !== undefined || this.status !== undefined;\n }\n\n get message(): string {\n if (this.wow) return this.wow.message;\n const unfilled = this.unfilled;\n if (unfilled !== undefined)\n return `The fetcher's interceptors did not fill the path variable {${unfilled}}`;\n if (this.status !== undefined)\n return `The view store answered HTTP ${this.status}`;\n return `The view store could not be reached: ${reasonOf(this.cause)}`;\n }\n\n /**\n * The port's error, holding what it was read from: the request's own\n * failure as `cause`, the server's error code as `detail` (a host tells\n * `ViewAppRequired` from `ViewInvalid` by it), and for `UNAVAILABLE`\n * whether the server answered (`reachable`).\n */\n toStoreError(): ViewStoreError {\n return new ViewStoreError(this.code, this.message, this.held());\n }\n\n /** {@link toStoreError} with another code: the same failure, read further. */\n held(): {\n cause: unknown;\n detail?: { code: string };\n reachable?: true;\n } {\n const code = this.errorCode;\n return {\n cause: this.cause,\n ...(code === undefined ? {} : { detail: { code } }),\n ...(this.code === 'UNAVAILABLE' && this.reached\n ? { reachable: true as const }\n : {}),\n };\n }\n}\n\n/** The fetcher's refusal of a route whose path variable has no value. */\nconst UNFILLED = /^Missing required path parameter: (\\S+)/;\n\n/** Whether the request id of a write was used before. */\nexport function isDuplicateRequest(failure: Failure): boolean {\n return failure.errorCode === ErrorCodes.DUPLICATE_REQUEST_ID;\n}\n\n/**\n * The port's code for a server's answer, **by Wow's error code first**: the\n * code says what the server decided, where one HTTP status carries several\n * decisions (a `400` is a stale version on no server, but a bad title and a\n * missing application alike). Only an answer without a code the store knows\n * — a gateway's own page, a proxy, a code a later server adds — falls back to\n * the status, and no answer at all (a network failure, a timeout, an abort)\n * is `UNAVAILABLE`: the outcome is unknown, and a retry under the same\n * `requestId` is what the port expects.\n */\nexport function portCodeOf(\n errorCode: string | undefined,\n status: number | undefined,\n): ViewStoreErrorCode {\n const known = errorCode === undefined ? undefined : CODES[errorCode];\n if (known) return known;\n switch (status) {\n case 400:\n case 422:\n return 'INVALID';\n case 401:\n case 403:\n return 'FORBIDDEN';\n case 404:\n case 410:\n return 'NOT_FOUND';\n case 409:\n case 412:\n return 'CONFLICT';\n default:\n return 'UNAVAILABLE';\n }\n}\n\n/** What a failed request threw, read as a {@link Failure}. */\nexport async function failureOf(error: unknown): Promise<Failure> {\n const wow = await toWowError(error);\n const status = wow?.status ?? statusOf(error);\n return new Failure(error, wow, status);\n}\n\n/** The status of a fetcher error's response, when it carries one. */\nfunction statusOf(error: unknown): number | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const response = (error as { exchange?: { response?: Response } }).exchange\n ?.response;\n return response?.status;\n}\n\n/** What a refusal said; a `DOMException` is an `Error` only in some realms. */\nfunction reasonOf(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (typeof message === 'string')\n return typeof name === 'string' ? `${name}: ${message}` : message;\n }\n return String(error);\n}\n","/*\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\n/**\n * The reserved owner of shared views and shared preferences\n * (`ViewStoreService.SHARED_OWNER_ID` on the server). The parentheses keep it\n * apart from every user id, so a path whose owner segment is `(shared)` is the\n * shared audience's.\n *\n * A host nobody signs in to fills `{ownerId}` with it by default (its own\n * request interceptor), and then has shared views and shared preferences\n * only.\n */\nexport const SHARED_OWNER_ID = '(shared)';\n\n/**\n * The reserved owner of stored system views\n * (`ViewStoreService.SYSTEM_OWNER_ID` on the server).\n */\nexport const SYSTEM_OWNER_ID = '(system)';\n\n/**\n * The one tenant stored system views live under\n * (`ViewStoreService.SYSTEM_TENANT_ID`): the value of CoSec's platform\n * tenant, not the default tenant `(0)`. System views are global, so the\n * store writes them on `tenant/(platform)/owner/(system)` whatever the\n * caller's own tenant, and the security gateway decides who may, by that\n * path.\n */\nexport const SYSTEM_TENANT_ID = '(platform)';\n\n/**\n * Where a view lives on the server: the owner segment of its path. `personal`\n * leaves `{ownerId}` to the fetcher's interceptors (fetcher-cosec's resource\n * attribution fills it from the token's `sub`); `shared` names\n * {@link SHARED_OWNER_ID}, which the interceptors never replace; `system`\n * names both the tenant and the owner of stored system views,\n * {@link SYSTEM_TENANT_ID} and {@link SYSTEM_OWNER_ID}.\n */\nexport type Place = 'personal' | 'shared' | 'system';\n\n/** Every route starts here; the tenant and owner are path variables. */\nexport const SCOPE = '/view-store/tenant/{tenantId}/owner/{ownerId}';\n\n/** The view store's routes, relative to the fetcher's base URL. */\nexport const PATHS = {\n /** `POST`: create (the server generates the id). */\n views: `${SCOPE}/view`,\n /** `DELETE`: Wow's delete of the aggregate. */\n view: `${SCOPE}/view/{id}`,\n save: `${SCOPE}/view/{id}/save`,\n rename: `${SCOPE}/view/{id}/rename`,\n /** Sent to the view's personal path; moves it to `(shared)`. */\n share: `${SCOPE}/view/{id}/share`,\n /** Sent to the caller's own path; moves a shared view to the caller. */\n claim: `${SCOPE}/view/{id}/claim`,\n single: `${SCOPE}/view/snapshot/single`,\n list: `${SCOPE}/view/snapshot/list`,\n /** The view as the write with this request id left it; `204` for a delete. */\n replay: `${SCOPE}/view/requests/{requestId}`,\n /**\n * Served under `(shared)` only: the configured system views of the\n * caller's tenant and the stored ones, global.\n */\n systemViews: `${SCOPE}/system-views`,\n systemView: `${SCOPE}/system-views/{id}`,\n preferences: `${SCOPE}/definitions/{definitionId}/preferences`,\n} as const;\n\n/**\n * The path variables of a request at `place`. The tenant is the\n * interceptors' but on the system path; the owner is theirs for a personal\n * path.\n */\nexport function pathAt(\n place: Place,\n variables: Record<string, string> = {},\n): Record<string, string> {\n switch (place) {\n case 'shared':\n return { ...variables, ownerId: SHARED_OWNER_ID };\n case 'system':\n return {\n ...variables,\n tenantId: SYSTEM_TENANT_ID,\n ownerId: SYSTEM_OWNER_ID,\n };\n default:\n return { ...variables };\n }\n}\n","/*\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\n/*\n * The server's shapes, as far as the store reads them, and their reading as\n * the port's. The server stores the engine's `ViewConfig` whole and never\n * reads its meaning, so a config comes back exactly as it was saved.\n */\n\nimport type {\n ViewAudience,\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n ViewKind,\n ViewPreferences,\n} from '@ahoo-wang/wow-view-engine';\n\n/** The state of a `view` aggregate (`ViewState`); tenant and owner are Wow's. */\nexport interface ViewStateBody {\n definitionId: string;\n title: string;\n /** Follows the owner: `(shared)` is `shared`, any user is `personal`. */\n audience: ViewAudience;\n config: ViewConfig;\n}\n\n/**\n * A view's snapshot as a snapshot query or the replay route answers it. A\n * list projects it down to the summary's fields, `state.config.kind` among\n * them.\n */\nexport interface ViewSnapshotBody {\n aggregateId: string;\n version: number;\n state: ViewStateBody;\n}\n\n/** A system view the server serves (`SystemView`); `scope` is always `system`. */\nexport interface SystemViewBody {\n id: string;\n definitionId: string;\n title: string;\n kind: ViewKind;\n /** A hash of its content, whatever its source. */\n revision: string;\n config: ViewConfig;\n /**\n * `configured` (read-only) or `stored` (a view of `tenant/(platform)/owner/(system)`,\n * written through the view routes); absent from a server before it,\n * which served configured views only.\n */\n source?: 'configured' | 'stored';\n /** A stored view's aggregate version, which its writes expect. */\n version?: number | null;\n}\n\n/**\n * Whether the server stores `view` (else it configures it). A stored one\n * carries the port's `stored: true` (D81), the views an `editSystem`\n * permission may write; configured and code system views carry none.\n */\nexport function isStored(view: SystemViewBody): boolean {\n return view.source === 'stored' && typeof view.version === 'number';\n}\n\n/** One owner's preferences in one definition (`ViewPreferencesView`). */\nexport interface PreferencesBody {\n definitionId: string;\n order?: string[] | null;\n defaultInstanceId?: string | null;\n autoRun?: boolean | null;\n lastTabs?: Record<string, string> | null;\n /** `0` for preferences never written. */\n version: number;\n}\n\n/** The part of a command's answer (`CommandResult`) the store reads. */\nexport interface CommandResultBody {\n aggregateId: string;\n aggregateVersion?: number | null;\n}\n\n/** The fields a list reads, and nothing of the config but its `kind`. */\nexport const SUMMARY_FIELDS = [\n 'aggregateId',\n 'version',\n 'state.definitionId',\n 'state.title',\n 'state.audience',\n 'state.config.kind',\n];\n\n/** A snapshot's revision: the aggregate's version, compared as a string. */\nexport function revisionOf(version: number): string {\n return String(version);\n}\n\nexport function toInstance(snapshot: ViewSnapshotBody): ViewInstance {\n const { aggregateId, version, state } = snapshot;\n return {\n id: aggregateId,\n definitionId: state.definitionId,\n title: state.title,\n scope: state.audience,\n revision: revisionOf(version),\n config: state.config,\n };\n}\n\nexport function toSummary(snapshot: ViewSnapshotBody): ViewInstanceSummary {\n const { aggregateId, version, state } = snapshot;\n return {\n id: aggregateId,\n definitionId: state.definitionId,\n title: state.title,\n scope: state.audience,\n kind: state.config.kind,\n revision: revisionOf(version),\n };\n}\n\nexport function systemInstance(view: SystemViewBody): ViewInstance {\n return {\n id: view.id,\n definitionId: view.definitionId,\n title: view.title,\n scope: 'system',\n revision: view.revision,\n config: view.config,\n ...(isStored(view) ? { stored: true as const } : {}),\n };\n}\n\nexport function systemSummary(view: SystemViewBody): ViewInstanceSummary {\n return {\n id: view.id,\n definitionId: view.definitionId,\n title: view.title,\n scope: 'system',\n kind: view.kind,\n revision: view.revision,\n ...(isStored(view) ? { stored: true as const } : {}),\n };\n}\n\n/**\n * The port's preferences. A member the server holds as `null` is one never\n * set: `defaultInstanceId` reads as `null`, and `autoRun` and `lastTabs` are\n * left out, as the port's own `emptyPreferences()` leaves them.\n */\nexport function toPreferences(body: PreferencesBody): ViewPreferences {\n return preferencesAt(\n {\n order: body.order ?? [],\n defaultInstanceId: body.defaultInstanceId ?? null,\n autoRun: body.autoRun ?? undefined,\n lastTabs: body.lastTabs ?? undefined,\n },\n body.version,\n );\n}\n\n/** What a preferences write sends: everything but the revision. */\nexport function preferencesInput(\n preferences: Omit<ViewPreferences, 'revision'>,\n): Omit<ViewPreferences, 'revision'> {\n const { order, defaultInstanceId, autoRun, lastTabs } = preferences;\n return {\n order: [...order],\n defaultInstanceId: defaultInstanceId ?? null,\n ...(autoRun === undefined ? {} : { autoRun }),\n ...(lastTabs === undefined ? {} : { lastTabs: { ...lastTabs } }),\n };\n}\n\n/** `preferences` as written at `version`, in the port's shape. */\nexport function preferencesAt(\n preferences: Omit<ViewPreferences, 'revision'>,\n version: number,\n): ViewPreferences {\n return { ...preferencesInput(preferences), revision: revisionOf(version) };\n}\n\n/** Whether two preferences say the same, whatever their revisions. */\nexport function samePreferences(\n a: Omit<ViewPreferences, 'revision'>,\n b: Omit<ViewPreferences, 'revision'>,\n): boolean {\n return canonical(a) === canonical(b);\n}\n\n/** One spelling of what preferences say, the tabs in key order. */\nfunction canonical(preferences: Omit<ViewPreferences, 'revision'>): string {\n const { order, defaultInstanceId, autoRun, lastTabs } =\n preferencesInput(preferences);\n const tabs =\n lastTabs &&\n Object.entries(lastTabs).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0));\n return JSON.stringify([\n order,\n defaultInstanceId,\n autoRun ?? null,\n tabs ?? null,\n ]);\n}\n","/*\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 { ResultExtractors, type Fetcher } from '@ahoo-wang/fetcher';\nimport {\n asc,\n CommandHeaders,\n CommandStage,\n filter,\n listQuery,\n singleQuery,\n type BindingError,\n} from '@ahoo-wang/wow-client';\nimport {\n isSystemInstanceId,\n isViewStoreError,\n ViewStoreError,\n type ViewAudience,\n type ViewConfig,\n type ViewInstance,\n type ViewInstanceSummary,\n type ViewPermissions,\n type ViewPreferences,\n type ViewStore,\n type WriteContext,\n} from '@ahoo-wang/wow-view-engine';\nimport {\n failureOf,\n Failure,\n isDuplicateRequest,\n REFERENCED_BY_SHARED_DASHBOARD,\n} from './errors.js';\nimport { PATHS, pathAt, type Place } from './paths.js';\nimport {\n isStored,\n preferencesAt,\n preferencesInput,\n revisionOf,\n samePreferences,\n SUMMARY_FIELDS,\n systemInstance,\n systemSummary,\n toInstance,\n toPreferences,\n toSummary,\n type CommandResultBody,\n type PreferencesBody,\n type SystemViewBody,\n type ViewSnapshotBody,\n} from './wire.js';\n\n/** How a {@link WowViewStore} reaches the view store. */\nexport interface WowViewStoreOptions {\n /**\n * The fetcher every request goes through, on the base URL that serves\n * `/view-store/…` (the CoSec gateway in front of the view store server, or\n * the service that embeds the starter).\n *\n * Its interceptors carry who is asking; the store never does. They must\n * fill the path variables `{tenantId}` and, on a personal path,\n * `{ownerId}` where the store leaves them out — fetcher-cosec's\n * `ResourceAttributionRequestInterceptor` fills them from the token's\n * `tenantId` and `sub` — and send `CoSec-App-Id` (fetcher-cosec's\n * `CoSecRequestInterceptor`), and the space and the authorization with it.\n * A host nobody signs in to adds an interceptor of its own that fills the\n * same defaults (the owner `(shared)`, {@link SHARED_OWNER_ID}).\n */\n fetcher: Fetcher;\n /**\n * Which buttons are enabled for one definition's views. The server does\n * not authorize, the CoSec gateway does; a host answers this by the roles\n * it holds there — `changeAudience` by the role that may write\n * `owner/(shared)`, which claiming a view needs. Left out, everything is\n * allowed, as the port reads a store without `permissions`.\n */\n permissions?: (definitionId: string) => ViewPermissions;\n}\n\n/**\n * The largest list the server answers (its query budget); a definition with\n * more views of one audience lists the first this many.\n */\nconst LIST_LIMIT = 1000;\n\n/** How many preference writes the store remembers the outcome of. */\nconst REMEMBERED_WRITES = 256;\n\n/** What a stored system view's writes expect: its version at a revision. */\ninterface StoredAt {\n /** The content hash the engine holds as the view's revision. */\n revision: string;\n version: number;\n}\n\n/** One instance write, as sent from the place the view is at. */\ninterface InstanceWrite {\n method: 'POST' | 'PUT' | 'DELETE';\n url: string;\n /** The path it is sent to, and so replayed on. */\n sentTo: Place;\n body?: unknown;\n /** Where the view is once it lands; `null` for a delete. */\n landsAt: Place | null;\n}\n\n/** The replay route found nothing this write can be answered with. */\nconst NOT_REPLAYED = Symbol('not replayed');\n\n/**\n * The view engine's `ViewStore` over the Wow view store (`view-store/` in the\n * Wow repository): saved views and preferences as two Wow aggregates, served\n * under `/view-store/tenant/{tenantId}/owner/{ownerId}/…`.\n *\n * **The owner segment is the audience.** A personal view lives on the\n * caller's own path (`{ownerId}` filled by the fetcher's interceptors), a\n * shared one on `owner/(shared)`; the CoSec gateway decides who may use\n * which. The port names a view by id alone, so the store remembers where it\n * last saw each one (a list, a read, a write) and looks an unknown id up on\n * the personal path, the shared path and the server's system views, in that\n * order. Setting a view shared or personal moves it between the two paths,\n * id kept.\n *\n * **Writes** carry the port's `requestId` as `Command-Request-Id`, its\n * `revision` as `Command-Aggregate-Version`, and wait for the snapshot; the\n * answer is the view read back at the version the write left. A write the\n * server refuses as a stale version or a repeated request id is first looked\n * up by its request id (the replay route): a retry answers what the first\n * attempt wrote. Otherwise a stale version is `CONFLICT` carrying the view as\n * it is now, and a view that turns out to be gone is `NOT_FOUND`.\n *\n * **Errors** are read by Wow's error code onto the port's five codes, by the\n * HTTP status only for an answer without a code the store knows; a request\n * that got no answer is `UNAVAILABLE`, and a retry under the same\n * `requestId` is safe.\n *\n * **Creating is not idempotent on the server**, which generates the id. A\n * store remembers the request ids of its own creates (bounded), and a retry\n * of one first asks the replay route whether it landed; a retry sent by\n * another store — another tab, a reload — makes a second view.\n */\nexport class WowViewStore implements ViewStore {\n /**\n * The most of one audience a list answers (`LIST_LIMIT`): an audience\n * listed this full was cut there, which the workbench then says (R2-26).\n */\n readonly listLimit = LIST_LIMIT;\n private readonly fetcher: Fetcher;\n /**\n * Where each view was last seen, by id. Kept after a delete, for its retry.\n * A `system` view is read through the server's system views (configured\n * and stored) and written, when stored, on the system path.\n */\n private readonly places = new Map<string, Place>();\n /**\n * The preferences have no replay route, so the store keeps what each of\n * its own writes answered, and which ones it sent: a retry answers the\n * first outcome, and a retry whose first answer was lost is recognised.\n */\n private readonly preferenceOutcomes = new Remembered<ViewPreferences>();\n private readonly preferenceAttempts = new Remembered<true>();\n /** The request ids of the creates this store sent, for their retries. */\n private readonly createAttempts = new Remembered<true>();\n /**\n * The system views as last read, by id: a stored one's version at its\n * revision (a hash of its content, while a write expects the version), or\n * `null` for a configured one, which is read-only.\n */\n private readonly storedVersions = new Remembered<StoredAt | null>(\n REMEMBERED_SYSTEM_VIEWS,\n );\n /** The host's {@link WowViewStoreOptions.permissions}, when it gave any. */\n readonly permissions?: (definitionId: string) => ViewPermissions;\n\n constructor(options: WowViewStoreOptions) {\n this.fetcher = options.fetcher;\n // Left undefined when the host declared none, which the port reads as\n // \"everything is allowed\".\n if (options.permissions) this.permissions = options.permissions;\n }\n\n /**\n * The caller's personal views, the shared views and the server's system\n * views of the definition: three requests, sent together, answered in the\n * port's order — system, shared, personal, each oldest first (the server\n * sorts each audience by the time its first event was written).\n *\n * A server with no view store at all (one released before it) answers\n * every route `404`, where a list on one that has it never does: that is\n * `UNSUPPORTED`, not a missing view.\n */\n list(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewInstanceSummary[]> {\n return guard(async () => {\n const query = listQuery({\n filter: filter.eq('state.definitionId', definitionId),\n projection: { include: SUMMARY_FIELDS },\n sort: LIST_ORDER,\n limit: LIST_LIMIT,\n });\n const [personal, shared, system] = await Promise.all([\n this.json<ViewSnapshotBody[]>('POST', PATHS.list, 'personal', {\n body: query,\n signal,\n }),\n this.json<ViewSnapshotBody[]>('POST', PATHS.list, 'shared', {\n body: query,\n signal,\n }),\n this.json<SystemViewBody[]>('GET', PATHS.systemViews, 'shared', {\n query: { definitionId },\n signal,\n }),\n ]).catch((thrown: unknown) => {\n throw thrown instanceof Failure && thrown.code === 'NOT_FOUND'\n ? unsupported(thrown)\n : thrown;\n });\n for (const view of system) this.rememberSystem(view);\n const seen = new Map<string, ViewInstanceSummary>();\n for (const summary of [\n ...personal.map(toSummary),\n ...shared.map(toSummary),\n ...system.map(systemSummary),\n ]) {\n if (seen.has(summary.id)) continue;\n seen.set(summary.id, summary);\n this.places.set(summary.id, summary.scope);\n }\n // Sorted stably: within an audience, the server's order stands.\n return [...seen.values()].sort(\n (a, b) => AUDIENCE_RANK[a.scope] - AUDIENCE_RANK[b.scope],\n );\n });\n }\n\n /** View `id` wherever it is: the caller's, shared, or the server's system view. */\n get(id: string, signal?: AbortSignal): Promise<ViewInstance> {\n return guard(async () => (await this.find(id, signal)).instance);\n }\n\n /**\n * Posts the view to the path of its `scope`; the server generates the id.\n * A retry of a create this store sent asks the replay route on that path\n * first, and answers the view the first attempt made when it landed; the\n * server itself does not deduplicate, so a retry from another store makes\n * a second view.\n */\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return guard(async () => {\n // A system view is created on the system path, global (the gateway\n // decides who may); configured and code system views stay read-only.\n const place: Place = input.scope;\n const { requestId } = context;\n if (this.createAttempts.has(requestId)) {\n const made = await this.probe(place, context, true);\n const snapshot =\n made?.status === 200\n ? ((await made.json()) as ViewSnapshotBody | null)\n : null;\n if (snapshot?.aggregateId) {\n this.places.set(snapshot.aggregateId, place);\n // A system view's revision is its content hash, which the\n // snapshot does not carry: it is read from the system views.\n return place === 'system'\n ? this.readAt('system', snapshot.aggregateId, context.signal)\n : toInstance(snapshot);\n }\n }\n this.createAttempts.set(requestId, true);\n const { definitionId, title, config } = input;\n const write: InstanceWrite = {\n method: 'POST',\n url: PATHS.views,\n sentTo: place,\n body: { definitionId, title, config },\n landsAt: place,\n };\n const result = await this.json<CommandResultBody>(\n write.method,\n write.url,\n place,\n {\n body: write.body,\n headers: writeHeaders(context),\n signal: context.signal,\n },\n ).catch(async (thrown: unknown) => {\n throw await this.unsupportedOr(thrown, context.signal);\n });\n const landed = await this.landed(\n result.aggregateId,\n write,\n result,\n context,\n );\n return landed!;\n });\n }\n\n /** Replaces the view's config, at the expected `revision`. */\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.write(id, revision, context, place => ({\n method: 'PUT',\n url: PATHS.save,\n sentTo: place,\n body: { config },\n landsAt: place,\n })) as Promise<ViewInstance>;\n }\n\n /** Renames the view (the server trims the title), at the expected `revision`. */\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.write(id, revision, context, place => ({\n method: 'PUT',\n url: PATHS.rename,\n sentTo: place,\n body: { title },\n landsAt: place,\n })) as Promise<ViewInstance>;\n }\n\n /**\n * 设为共享 sends `share` to the path the view is at; 设为个人 sends `claim`\n * to the caller's own path, which the gateway admits only with the role\n * that may write `owner/(shared)`. Either answers a view that already has\n * the audience as it is, revision unmoved.\n *\n * A shared view a shared dashboard shows stays shared: the server refuses\n * the claim and names the boards, and the refusal carries them by\n * **title** in `boards`, as they are stored — a title written as a key\n * stays one, and is said where the engine shows the refusal.\n */\n changeAudience(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.write(id, revision, context, place =>\n place === 'system'\n ? readOnly('A system view never moves audience')\n : audience === 'shared'\n ? {\n method: 'PUT',\n url: PATHS.share,\n sentTo: place,\n body: {},\n landsAt: 'shared',\n }\n : {\n method: 'PUT',\n url: PATHS.claim,\n sentTo: 'personal',\n landsAt: 'personal',\n },\n ) as Promise<ViewInstance>;\n }\n\n /** Deletes the view, at the expected `revision`; a board showing it keeps a broken panel. */\n async delete(\n id: string,\n revision: string,\n context: WriteContext,\n ): Promise<void> {\n await this.write(id, revision, context, place => ({\n method: 'DELETE',\n url: PATHS.view,\n sentTo: place,\n body: {},\n landsAt: null,\n }));\n }\n\n /** The caller's own, or `(shared)`'s where the host fills that owner. */\n getPreferences(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewPreferences> {\n return guard(async () =>\n toPreferences(\n await this.json<PreferencesBody>('GET', PATHS.preferences, 'personal', {\n path: { definitionId },\n signal,\n }).catch(async (thrown: unknown) => {\n throw await this.unsupportedOr(thrown, signal);\n }),\n ),\n );\n }\n\n /**\n * Writes the preferences at the expected `revision` (`'0'` for ones never\n * written). The server has no replay route for them, so a retry answers\n * what this store's first attempt answered, or — its answer lost — what is\n * stored when that is what it wrote.\n */\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences> {\n return guard(async () => {\n const { requestId, signal } = context;\n const answered = this.preferenceOutcomes.get(requestId);\n if (answered) return structuredClone(answered);\n const retry = this.preferenceAttempts.has(requestId);\n this.preferenceAttempts.set(requestId, true);\n let answer: ViewPreferences;\n try {\n const result = await this.json<CommandResultBody>(\n 'PUT',\n PATHS.preferences,\n 'personal',\n {\n path: { definitionId },\n body: preferencesInput(preferences),\n headers: writeHeaders(context, preferences.revision),\n signal,\n },\n );\n answer =\n typeof result.aggregateVersion === 'number'\n ? preferencesAt(preferences, result.aggregateVersion)\n : await this.getPreferences(definitionId, signal);\n } catch (thrown) {\n if (\n !(thrown instanceof Failure) ||\n (thrown.code !== 'CONFLICT' && !isDuplicateRequest(thrown))\n )\n throw await this.unsupportedOr(thrown, signal);\n const current = await this.getPreferences(definitionId, signal);\n // A retry the server refuses because its first attempt landed: what\n // is stored says what it wrote, unless another writer moved it on.\n if (\n (retry || isDuplicateRequest(thrown)) &&\n samePreferences(current, preferences)\n )\n answer = current;\n else\n throw new ViewStoreError('CONFLICT', thrown.message, {\n ...thrown.held(),\n preferences: current,\n });\n }\n this.preferenceOutcomes.set(requestId, answer);\n return structuredClone(answer);\n });\n }\n\n /**\n * One instance write: to the place the view is at, then the answer read\n * back. A view remembered at a place it has since left (another tab shared\n * it) is looked up again and the write sent once more to where it is.\n */\n private write(\n id: string,\n revision: string,\n context: WriteContext,\n plan: (place: Place) => InstanceWrite,\n ): Promise<ViewInstance | undefined> {\n return guard(async () => {\n const { signal } = context;\n const remembered = this.places.get(id);\n let place = remembered ?? (await this.find(id, signal)).place;\n let relocated = remembered === undefined;\n for (;;) {\n const write = plan(place);\n let expected = revision;\n if (place === 'system') {\n const stored = await this.storedVersion(id, revision, write, context);\n if ('answer' in stored) return stored.answer;\n expected = stored.version;\n }\n let result: CommandResultBody;\n try {\n result = await this.json<CommandResultBody>(\n write.method,\n write.url,\n write.sentTo,\n {\n path: { id },\n body: write.body,\n headers: writeHeaders(context, expected),\n signal,\n },\n );\n } catch (thrown) {\n if (!(thrown instanceof Failure)) throw thrown;\n const replayed = await this.replayed(id, write, context, thrown);\n if (replayed !== NOT_REPLAYED) return replayed;\n if (\n !relocated &&\n (thrown.code === 'NOT_FOUND' || thrown.code === 'FORBIDDEN')\n ) {\n relocated = true;\n const found = (await this.find(id, signal, null)).place;\n // Only where the write would go elsewhere: a claim goes to the\n // caller's own path wherever the view is.\n if (found !== place && plan(found).sentTo !== write.sentTo) {\n place = found;\n continue;\n }\n }\n if (thrown.code === 'CONFLICT' || isDuplicateRequest(thrown))\n throw await this.conflict(id, thrown, signal);\n throw await this.refusal(thrown, signal);\n }\n // Landed: what goes wrong reading it back is never a reason to send\n // it again.\n return this.landed(id, write, result, context);\n }\n });\n }\n\n /** A landed write's answer: the view read back at the version it left. */\n private async landed(\n id: string,\n write: InstanceWrite,\n result: CommandResultBody,\n context: WriteContext,\n ): Promise<ViewInstance | undefined> {\n if (write.landsAt === null) return undefined;\n this.places.set(id, write.landsAt);\n const version = result.aggregateVersion;\n let read: ViewInstance | undefined;\n let failure: unknown;\n try {\n read = await this.readAt(write.landsAt, id, context.signal);\n if (typeof version !== 'number' || read.revision === revisionOf(version))\n return read;\n // A system view's revision is its content hash: the version it was\n // read at says whether it is this write's.\n if (write.landsAt === 'system') {\n if (this.storedVersions.get(id)?.version === version) return read;\n }\n } catch (thrown) {\n failure = thrown;\n }\n // Another writer moved it on between the write and the read: the replay\n // route answers it as this write left it. The write landed, so a probe\n // that fails is no reason to report it otherwise: what was read stands.\n const replayed = await this.replay(id, write, context, false);\n if (replayed !== NOT_REPLAYED && replayed !== undefined) return replayed;\n if (read) return read;\n throw failure;\n }\n\n /**\n * The answer of a write the server refused as a stale version, a repeated\n * request id or a missing view, when the refusal is that of a retry: the\n * replay route finds the first attempt by its request id.\n */\n private async replayed(\n id: string,\n write: InstanceWrite,\n context: WriteContext,\n failure: Failure,\n ): Promise<ViewInstance | undefined | typeof NOT_REPLAYED> {\n const retryable =\n failure.code === 'CONFLICT' ||\n failure.code === 'NOT_FOUND' ||\n isDuplicateRequest(failure);\n return retryable ? this.replay(id, write, context, true) : NOT_REPLAYED;\n }\n\n /**\n * What the write with the context's request id left of view `id`, from the\n * replay route: the view at that version, or `undefined` for a delete.\n *\n * The route finds a write only on the path of the owner who wrote it, and\n * a retry may be sent elsewhere than its first attempt — a share goes to\n * the personal path the view has left by the time it is retried — so the\n * path this attempt went to is asked first and the other one next.\n *\n * A probe that fails other than as \"not found\" is no answer on its path.\n * With `strict` — a refused write, whose own path is asked first — that\n * path's failure is passed on: whether the first attempt landed is\n * unknown, and a retry under the same request id is safe. The other path\n * (a caller without the shared role is refused there), and every probe of\n * a write that landed, count it as not replayed, and the caller keeps what\n * it knows: the refusal, or the view it read back.\n */\n private async replay(\n id: string,\n write: InstanceWrite,\n context: WriteContext,\n strict: boolean,\n ): Promise<ViewInstance | undefined | typeof NOT_REPLAYED> {\n const places: Place[] =\n write.sentTo === 'system'\n ? ['system']\n : write.sentTo === 'personal'\n ? ['personal', 'shared']\n : ['shared', 'personal'];\n for (const [index, place] of places.entries()) {\n const response = await this.probe(place, context, strict && index === 0);\n if (!response) continue;\n if (response.status === 204)\n return write.landsAt === null ? undefined : NOT_REPLAYED;\n const snapshot = (await response.json()) as ViewSnapshotBody;\n if (write.landsAt === null || snapshot?.aggregateId !== id)\n return NOT_REPLAYED;\n // The replay route answers a snapshot, whose revision would be its\n // version; a system view's is its content hash, which only the server\n // computes: the view is answered as it is now.\n if (write.landsAt === 'system')\n return this.readAt('system', id, context.signal);\n return toInstance(snapshot);\n }\n return NOT_REPLAYED;\n }\n\n /**\n * The replay route at `place` for the context's request id; `undefined`\n * when it knows none, or — not `strict` — when it could not be asked.\n */\n private async probe(\n place: Place,\n context: WriteContext,\n strict: boolean,\n ): Promise<Response | undefined> {\n try {\n return await this.send('GET', PATHS.replay, place, {\n path: { requestId: context.requestId },\n signal: context.signal,\n });\n } catch (thrown) {\n if (thrown instanceof Failure && (thrown.code === 'NOT_FOUND' || !strict))\n return undefined;\n throw thrown;\n }\n }\n\n /** A stale write's refusal, carrying the view as it is now. */\n private async conflict(\n id: string,\n failure: Failure,\n signal: AbortSignal | undefined,\n ): Promise<ViewStoreError> {\n const { instance } = await this.find(id, signal, null);\n return new ViewStoreError('CONFLICT', failure.message, {\n ...failure.held(),\n instance,\n });\n }\n\n /**\n * The port's refusal of a write. A claim the server refuses because shared\n * dashboards show the view carries those boards' titles (`boards`), which\n * the server gives beside each board's id (a board it gives no title for\n * is read for one); the engine says the refusal around them.\n */\n private async refusal(\n failure: Failure,\n signal: AbortSignal | undefined,\n ): Promise<ViewStoreError> {\n const boards = failure.bindingErrors.filter(\n error => error.code === REFERENCED_BY_SHARED_DASHBOARD,\n );\n if (failure.code !== 'INVALID' || boards.length === 0)\n return failure.toStoreError();\n const titles = await Promise.all(\n boards.map(board => this.boardTitle(board, signal)),\n );\n return new ViewStoreError('INVALID', failure.message, {\n ...failure.held(),\n boards: titles,\n });\n }\n\n private async boardTitle(\n board: BindingError,\n signal: AbortSignal | undefined,\n ): Promise<string> {\n if (typeof board.msg === 'string' && board.msg.trim() !== '')\n return board.msg;\n try {\n return (await this.readAt('shared', board.name, signal)).title;\n } catch {\n return board.name;\n }\n }\n\n /**\n * View `id` and where it is: first where it was last seen (`first`, `null`\n * to ignore that), then the personal path, the shared path and the\n * server's system views.\n */\n private async find(\n id: string,\n signal: AbortSignal | undefined,\n first: Place | null | undefined = this.places.get(id),\n ): Promise<{ place: Place; instance: ViewInstance }> {\n // Ids in `system:` are the views a host declares in code; the server\n // never issues or serves one.\n if (!isSystemInstanceId(id)) {\n const order: Place[] = ['personal', 'shared', 'system'];\n if (first)\n order.sort((a, b) => Number(b === first) - Number(a === first));\n for (const place of order) {\n try {\n const instance = await this.readAt(place, id, signal);\n this.places.set(id, place);\n return { place, instance };\n } catch (thrown) {\n if (thrown instanceof Failure && thrown.code === 'NOT_FOUND')\n continue;\n throw thrown;\n }\n }\n // Every place answered `404`: a view that is not there, or no view\n // store there at all (a server released before it) — the one\n // question the server's system views tell apart.\n if (!(await this.served(signal)))\n throw new ViewStoreError('UNSUPPORTED', NO_VIEW_STORE);\n }\n throw new ViewStoreError('NOT_FOUND', `No such view: ${id}`);\n }\n\n /**\n * Whether the server has a view store at all: its system views answer\n * on one that has (an empty list included), and `404` on one released\n * before it. Any other failure is no answer to that, and reads as served.\n */\n private async served(signal: AbortSignal | undefined): Promise<boolean> {\n try {\n await this.send('GET', PATHS.systemViews, 'shared', { signal });\n return true;\n } catch (thrown) {\n return !(thrown instanceof Failure && thrown.code === 'NOT_FOUND');\n }\n }\n\n /** A `404` from a server with no view store is `UNSUPPORTED`; else as it was. */\n private async unsupportedOr(\n thrown: unknown,\n signal: AbortSignal | undefined,\n ): Promise<unknown> {\n return thrown instanceof Failure &&\n thrown.code === 'NOT_FOUND' &&\n !(await this.served(signal))\n ? unsupported(thrown)\n : thrown;\n }\n\n /** Keeps what a stored system view's writes expect; forgets a configured one. */\n private rememberSystem(view: SystemViewBody): SystemViewBody {\n this.storedVersions.set(\n view.id,\n isStored(view)\n ? { revision: view.revision, version: view.version! }\n : null,\n );\n return view;\n }\n\n /**\n * The version a write of stored system view `id` at `revision` (its\n * content hash) expects: as last read, else read now. A configured system\n * view is read-only (`FORBIDDEN`; a code one is never found here). A\n * revision other than the view's is stale — unless this write is a retry\n * whose first attempt moved it on, which the replay route answers — and is\n * then `CONFLICT`, carrying the view as it is.\n */\n private async storedVersion(\n id: string,\n revision: string,\n write: InstanceWrite,\n context: WriteContext,\n ): Promise<{ version: string } | { answer: ViewInstance | undefined }> {\n let known = this.storedVersions.get(id);\n if (known === null) readOnly('Configured system views are read-only');\n if (known?.revision !== revision) {\n const instance = await this.readAt('system', id, context.signal);\n known = this.storedVersions.get(id);\n if (known && known.revision !== revision) {\n const replayed = await this.replay(id, write, context, false);\n if (replayed !== NOT_REPLAYED) return { answer: replayed };\n throw new ViewStoreError(\n 'CONFLICT',\n `System view ${id} has moved on from revision ${revision}`,\n { instance },\n );\n }\n }\n if (!known) readOnly('Configured system views are read-only');\n return { version: String(known.version) };\n }\n\n private async readAt(\n place: Place,\n id: string,\n signal: AbortSignal | undefined,\n ): Promise<ViewInstance> {\n if (place === 'system')\n return systemInstance(\n this.rememberSystem(\n await this.json<SystemViewBody>('GET', PATHS.systemView, 'shared', {\n path: { id },\n signal,\n }),\n ),\n );\n return toInstance(\n await this.json<ViewSnapshotBody>('POST', PATHS.single, place, {\n body: singleQuery({ filter: filter.id(id) }),\n signal,\n }),\n );\n }\n\n private async json<R>(\n method: string,\n url: string,\n place: Place,\n request: Request,\n ): Promise<R> {\n const response = await this.send(method, url, place, request);\n return (await response.json()) as R;\n }\n\n /**\n * The one place a request leaves the store, and so the one place what it\n * threw becomes a {@link Failure}.\n */\n private async send(\n method: string,\n url: string,\n place: Place,\n { path, query, body, headers, signal }: Request,\n ): Promise<Response> {\n try {\n return await this.fetcher.request<Response>(\n {\n url,\n method,\n urlParams: { path: pathAt(place, path), query },\n body: body as Record<string, unknown> | undefined,\n headers,\n signal,\n },\n { resultExtractor: ResultExtractors.Response },\n );\n } catch (error) {\n throw await failureOf(error);\n }\n }\n}\n\n/** One request's parts beside its method, route and place. */\ninterface Request {\n path?: Record<string, string>;\n query?: Record<string, string>;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n/** The headers of a write: its request id, its expected version, the wait. */\nexport function writeHeaders(\n context: WriteContext,\n revision?: string,\n): Record<string, string> {\n return {\n [CommandHeaders.REQUEST_ID]: context.requestId,\n [CommandHeaders.WAIT_STAGE]: CommandStage.SNAPSHOT,\n ...(revision === undefined\n ? {}\n : { [CommandHeaders.AGGREGATE_VERSION]: revision }),\n };\n}\n\n/** What a server without a view store is told as. */\nconst NO_VIEW_STORE = 'This server has no view store';\n\nfunction unsupported(failure: Failure): ViewStoreError {\n return new ViewStoreError('UNSUPPORTED', NO_VIEW_STORE, failure.held());\n}\n\n/**\n * The port's list order, asked of the server per audience: oldest first, by\n * the time a view's first event was written, its id breaking a tie.\n */\nconst LIST_ORDER = [asc('firstEventTime'), asc('aggregateId')];\n\n/** System views first, then shared, then personal: the port's list order. */\nconst AUDIENCE_RANK: Readonly<Record<ViewInstanceSummary['scope'], number>> = {\n system: 0,\n shared: 1,\n personal: 2,\n};\n\n/** Refuses a write to a system view the server or the code declares. */\nfunction readOnly(message: string): never {\n throw new ViewStoreError('FORBIDDEN', message);\n}\n\n/**\n * Runs one of the port's methods, so that everything it rejects with is a\n * `ViewStoreError`: a failed request as its code says, anything else — a\n * body that did not parse — as `UNAVAILABLE`, the outcome unknown.\n */\nexport async function guard<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (thrown) {\n if (thrown instanceof Failure) throw thrown.toStoreError();\n if (isViewStoreError(thrown)) throw thrown;\n // A body that did not parse came back from something — a login wall's\n // page, a proxy's: answered, so not \"could not be reached\".\n throw new ViewStoreError(\n 'UNAVAILABLE',\n thrown instanceof Error ? thrown.message : String(thrown),\n {\n cause: thrown,\n ...(thrown instanceof SyntaxError ? { reachable: true as const } : {}),\n },\n );\n }\n}\n\n/**\n * How many system views the store remembers the version of; one it forgot\n * is read again before its write.\n */\nconst REMEMBERED_SYSTEM_VIEWS = 1024;\n\n/** A bounded memory by key: the oldest entry goes first. */\nclass Remembered<T> {\n private readonly entries = new Map<string, T>();\n\n constructor(private readonly limit = REMEMBERED_WRITES) {}\n\n get(key: string): T | undefined {\n return this.entries.get(key);\n }\n\n has(key: string): boolean {\n return this.entries.has(key);\n }\n\n set(key: string, value: T): void {\n this.entries.delete(key);\n this.entries.set(key, value);\n if (this.entries.size > this.limit)\n this.entries.delete(this.entries.keys().next().value!);\n }\n}\n","/*\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 { ResultExtractors, type Fetcher } from '@ahoo-wang/fetcher';\nimport { listQuery, filter } from '@ahoo-wang/wow-client';\nimport type {\n DatasetOverrides,\n DatasetWordingStore,\n StoredDatasetWording,\n WriteContext,\n} from '@ahoo-wang/wow-view-engine';\nimport { failureOf } from './errors.js';\nimport { pathAt, SCOPE } from './paths.js';\nimport { revisionOf, type CommandResultBody } from './wire.js';\nimport { guard, writeHeaders } from './wowViewStore.js';\n\n/** How a {@link WowDatasetWordings} reaches the view store: as a `WowViewStore` does. */\nexport interface WowDatasetWordingsOptions {\n /**\n * The fetcher every request goes through, as {@link WowViewStoreOptions.fetcher}:\n * its interceptors fill `{tenantId}` and send `CoSec-App-Id`. The\n * wording is the tenant's, so the store always names the owner `(shared)`.\n */\n fetcher: Fetcher;\n}\n\n/** The most datasets one application's wording is read for at once. */\nconst LIST_LIMIT = 1000;\n\nconst ROUTES = {\n /** `PUT` sets, `DELETE` clears; under `(shared)` only. */\n wording: `${SCOPE}/datasets/{dataset}/wording`,\n list: `${SCOPE}/dataset_wording/snapshot/list`,\n} as const;\n\n/** A wording's snapshot as the list answers it. */\ninterface WordingSnapshotBody {\n version: number;\n state: {\n dataset: string;\n title?: string | null;\n recordNoun?: string | null;\n fields?: DatasetOverrides['fields'] | null;\n };\n}\n\n/**\n * The wording a tenant's administrators keep over its datasets in the Wow\n * view store (view engine D86): one per dataset of the caller's tenant and\n * application, under `owner/(shared)`. The gateway decides who may write it.\n *\n * A host hands it to the datasets it registers as their store of wording\n * (`DatasetCatalog.wordings`, D91): `DatasetResources` reads it before each\n * refresh, registers each dataset in its stored words, and gives the view\n * manager an editor of them. The key is the dataset's definition id,\n * `{context}.{dataset}`.\n *\n * ```ts\n * const resources = new DatasetResources(engine, {\n * list: () => directory.list(),\n * source: entry => directory.source(entry),\n * wordings: new WowDatasetWordings({ fetcher }),\n * });\n * ```\n *\n * Every rejection is a `ViewStoreError`, read as a `WowViewStore`'s are.\n */\nexport class WowDatasetWordings implements DatasetWordingStore {\n private readonly fetcher: Fetcher;\n\n constructor(options: WowDatasetWordingsOptions) {\n this.fetcher = options.fetcher;\n }\n\n /** Every dataset's wording of the caller's tenant and application, by dataset. */\n list(\n signal?: AbortSignal,\n ): Promise<ReadonlyMap<string, StoredDatasetWording>> {\n return guard(async () => {\n const response = await this.send('POST', ROUTES.list, {\n body: listQuery({ filter: filter.matchAll(), limit: LIST_LIMIT }),\n signal,\n });\n const snapshots = (await response.json()) as WordingSnapshotBody[];\n return new Map(\n snapshots.map(({ version, state }) => [\n state.dataset,\n { wording: wordingOf(state), revision: revisionOf(version) },\n ]),\n );\n });\n }\n\n /**\n * Writes a dataset's wording at the expected `revision` (`'0'` for one never\n * written), whole: what it leaves out is no longer said. Answers the new\n * revision.\n */\n set(\n dataset: string,\n wording: DatasetOverrides,\n revision: string,\n context: WriteContext,\n ): Promise<string> {\n return guard(async () => {\n const response = await this.send('PUT', ROUTES.wording, {\n dataset,\n body: {\n ...(wording.title === undefined ? {} : { title: wording.title }),\n ...(wording.recordNoun === undefined\n ? {}\n : { recordNoun: wording.recordNoun }),\n ...(wording.fields === undefined ? {} : { fields: wording.fields }),\n },\n headers: writeHeaders(context, revision),\n signal: context.signal,\n });\n const result = (await response.json()) as CommandResultBody;\n return revisionOf(result.aggregateVersion ?? Number(revision) + 1);\n });\n }\n\n /** Clears a dataset's wording at the expected `revision`: its derived words stand again. */\n clear(\n dataset: string,\n revision: string,\n context: WriteContext,\n ): Promise<void> {\n return guard(async () => {\n await this.send('DELETE', ROUTES.wording, {\n dataset,\n body: {},\n headers: writeHeaders(context, revision),\n signal: context.signal,\n });\n });\n }\n\n private async send(\n method: string,\n url: string,\n {\n dataset,\n body,\n headers,\n signal,\n }: {\n dataset?: string;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n },\n ): Promise<Response> {\n try {\n return await this.fetcher.request<Response>(\n {\n url,\n method,\n urlParams: {\n path: pathAt('shared', dataset === undefined ? {} : { dataset }),\n },\n body: body as Record<string, unknown> | undefined,\n headers,\n signal,\n },\n { resultExtractor: ResultExtractors.Response },\n );\n } catch (error) {\n throw await failureOf(error);\n }\n }\n}\n\n/** The engine's overrides from a stored wording: what is stored, nothing more. */\nfunction wordingOf(state: WordingSnapshotBody['state']): DatasetOverrides {\n return {\n ...(state.title == null ? {} : { title: state.title }),\n ...(state.recordNoun == null ? {} : { recordNoun: state.recordNoun }),\n ...(state.fields == null ? {} : { fields: state.fields }),\n };\n}\n"],"mappings":";;;;IAiCaC,IAAyB,OAAO,OAAO;CAElD,cAAc;CAEd,mBAAmB;CAEnB,uBAAuB;CAEvB,qBAAqB;CAErB,0BAA0B;AAC5B,CAAU,GAOGC,IAAiC,kCAGxCC,IAAsD;EACzDC,EAAW,kCAAkC;EAC7CA,EAAW,yBAAyB;EACpCA,EAAW,4BAA4B;EACvCA,EAAW,YAAY;EACvBA,EAAW,mCAAmC;EAC9CA,EAAW,iCAAiC;EAC5CA,EAAW,iCAAiC;EAC5CA,EAAW,6BAA6B;EACxCH,EAAuB,wBAAwB;EAC/CA,EAAuB,2BAA2B;EAClDA,EAAuB,eAAe;EACtCA,EAAuB,oBAAoB;EAC3CA,EAAuB,sBAAsB;EAC7CG,EAAW,cAAc;EACzBA,EAAW,mBAAmB;EAE9BA,EAAW,gBAAgB;EAC3BA,EAAW,qBAAqB;EAChCA,EAAW,yBAAyB;EACpCA,EAAW,0BAA0B;EACrCA,EAAW,kBAAkB;EAC7BA,EAAW,oBAAoB;EAC/BA,EAAW,wBAAwB;EACnCA,EAAW,2BAA2B;EACtCA,EAAW,wBAAwB;AACtC,GAOa,UAAb,MAAqB;CACnB,YAEE,GAEA,GAEA,GACA;EADS,AAJA,KAAA,QAAAC,GAEA,KAAA,MAAAC,GAEA,KAAA,SAAAC;CACR;CAGH,IAAI,YAAgC;EAClC,OAAO,KAAK,KAAK;CACnB;CAEA,IAAI,gBAAyC;EAC3C,OAAO,KAAK,KAAK,iBAAiB,CAAC;CACrC;CAOA,IAAI,WAA+B;EACjC,IAAI,OAAK,OAAO,KAAK,WAAW,KA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AYA,EAAQ,WAAW;IACrC,GAAIA,EAAQ,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQA,EAAQ,OAAO;GACnE;GACA,SAAS,aAAa9C,GAASK,CAAQ;GACvC,QAAQL,EAAQ;EAClB,CAAC,EAAA,CAC8B,KAAK,EAClB,CAAO,oBAAoB,OAAOK,CAAQ,IAAI,CAAC,CAClE;CACH;CAGA,MACE,GACA,GACA,GACe;EACf,OAAO,MAAM,YAAY;GACvB,MAAM,KAAK,KAAK,UAAUuC,EAAO,SAAS;IACxC;IACA,MAAM,CAAC;IACP,SAAS,aAAa5C,GAASK,CAAQ;IACvC,QAAQL,EAAQ;GAClB,CAAC;EACH,CAAC;CACH;CAEA,MAAc,KACZ,GACA,GACA,EACE,YACA,SACA,YACA,aAOiB;EACnB,IAAI;GACF,OAAO,MAAM,KAAK,QAAQ,QACxB;IACE;IACA;IACA,WAAW,EACT,MAAM,OAAO,UAAU+C,MAAY,KAAA,IAAY,CAAC,IAAI,EAAE,WAAQ,CAAC,EACjE;IACM;IACN;IACA;GACF,GACA,EAAE,iBAAiBb,EAAiB,SAAS,CAC/C;EACF,SAAShF,GAAO;GACd,MAAM,MAAM,UAAUA,CAAK;EAC7B;CACF;AACF;AAGA,SAAS,UAAU,GAAuD;CACxE,OAAO;EACL,GAAIc,EAAM,SAAS,OAAO,CAAC,IAAI,EAAE,OAAOA,EAAM,MAAM;EACpD,GAAIA,EAAM,cAAc,OAAO,CAAC,IAAI,EAAE,YAAYA,EAAM,WAAW;EACnE,GAAIA,EAAM,UAAU,OAAO,CAAC,IAAI,EAAE,QAAQA,EAAM,OAAO;CACzD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.es.js","names":["LIST_LIMIT","optionsOf","__defProp","target","SHARED_OWNER_ID","SYSTEM_OWNER_ID","SYSTEM_TENANT_ID","REMEMBERED_WRITES","limit","key","value","view","version","body","preferences","order","defaultInstanceId","autoRun","lastTabs","VIEW_STORE_BOUNDED_CONTEXT","ViewStoreErrorCodes","viewStoreWait","wait","subscription","ViewAggregate","ViewCommandPaths","CommandGateway","options","id","LifecycleCommands","SnapshotQueryClient","StateClient","ViewPreferencesCommandPaths","ViewPreferencesAggregate","WowViewStoreErrorCodes","CODES","FrameworkErrorCodes","cause","problem","code","known","ViewStoreError","error","toWowProblemError","boards","extensions","board","title","run","thrown","isViewStoreError","message","name","SYSTEM_VIEWS_PATH","fetcher","definitionId","signal","url","SHARED_SCOPE","SYSTEM_SCOPE","place","SUMMARY_FIELDS","state","LIST_LIMIT$1","REMEMBERED_SYSTEM_REVISIONS","AUDIENCE_WAIT","client","query","listQuery","filter","asc","personal","shared","system","seen","summary","record","AUDIENCE_RANK","a","b","input","write","config","result","context","revision","audience","singleQuery","emptyPreferences","remembered","relocated","plan","found","landsAt","read","instance","failure","isSystemInstanceId","first","more","scope","ownerId","DatasetWordingCommandPaths","DatasetWordingAggregate","LIST_LIMIT","snapshots","wording","page","abort","previous","entry","LISTED"],"sources":["../src/paths.ts","../src/remembered.ts","../src/views.ts","../src/generated/view-store/boundedContext.ts","../src/generated/view-store/view/aggregate.ts","../src/generated/view-store/view/commandClient.ts","../src/generated/view-store/view/queryClient.ts","../src/generated/view-store/view_preferences/commandClient.ts","../src/generated/view-store/view_preferences/aggregate.ts","../src/generated/view-store/view_preferences/queryClient.ts","../src/errors.ts","../src/systemViews.ts","../src/wire.ts","../src/wowViewStore.ts","../src/generated/view-store/dataset_wording/commandClient.ts","../src/generated/view-store/dataset_wording/aggregate.ts","../src/generated/view-store/dataset_wording/queryClient.ts","../src/datasetWordings.ts","../src/source.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\n/**\n * The reserved owner of shared views and shared preferences\n * (`ViewStoreService.SHARED_OWNER_ID` on the server). The parentheses keep it\n * apart from every user id, so a path whose owner segment is `(shared)` is the\n * shared audience's.\n *\n * A host nobody signs in to fills `{ownerId}` with it by default (its own\n * request interceptor), and then has shared views and shared preferences\n * only.\n */\nexport const SHARED_OWNER_ID = '(shared)';\n\n/**\n * The reserved owner of stored system views\n * (`ViewStoreService.SYSTEM_OWNER_ID` on the server).\n */\nexport const SYSTEM_OWNER_ID = '(system)';\n\n/**\n * The one tenant stored system views live under\n * (`ViewStoreService.SYSTEM_TENANT_ID`): the value of CoSec's platform\n * tenant, not the default tenant `(0)`. System views are global, so the\n * store writes them on `tenant/(platform)/owner/(system)` whatever the\n * caller's own tenant, and the security gateway decides who may, by that\n * path.\n */\nexport const SYSTEM_TENANT_ID = '(platform)';\n\n/**\n * Where a view lives on the server: the owner segment of its path. `personal`\n * leaves `{ownerId}` to the fetcher's interceptors (fetcher-cosec's resource\n * attribution fills it from the token's `sub`); `shared` names\n * {@link SHARED_OWNER_ID}, which the interceptors never replace; `system`\n * names both the tenant and the owner of stored system views,\n * {@link SYSTEM_TENANT_ID} and {@link SYSTEM_OWNER_ID}.\n */\nexport type Place = 'personal' | 'shared' | 'system';\n","/*\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\n/** How many writes a store remembers the outcome of, unless told otherwise. */\nconst REMEMBERED_WRITES = 256;\n\n/** A bounded memory by key: the oldest entry goes first. */\nexport class Remembered<T> {\n private readonly entries = new Map<string, T>();\n\n constructor(private readonly limit = REMEMBERED_WRITES) {}\n\n get(key: string): T | undefined {\n return this.entries.get(key);\n }\n\n has(key: string): boolean {\n return this.entries.has(key);\n }\n\n set(key: string, value: T): void {\n this.entries.delete(key);\n this.entries.set(key, value);\n if (this.entries.size > this.limit)\n this.entries.delete(this.entries.keys().next().value!);\n }\n}\n","/*\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\n/*\n * The server's shapes, as far as the store reads them, and their reading as\n * the port's. The server stores the engine's `ViewConfig` whole and never\n * reads its meaning, so a config comes back exactly as it was saved.\n */\n\nimport type {\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n ViewKind,\n ViewPreferences,\n} from '@ahoo-wang/wow-view-engine';\n\n/** A system view the server serves (`SystemView`); `scope` is always `system`. */\nexport interface SystemViewBody {\n id: string;\n definitionId: string;\n title: string;\n kind: ViewKind;\n /** A hash of its content, whatever its source. */\n revision: string;\n config: ViewConfig;\n /**\n * `configured` (read-only) or `stored` (a view of `tenant/(platform)/owner/(system)`,\n * written through the view routes); absent from a server before it,\n * which served configured views only.\n */\n source?: 'configured' | 'stored';\n /** A stored view's aggregate version, which its writes expect. */\n version?: number | null;\n}\n\n/**\n * Whether the server stores `view` (else it configures it). A stored one\n * carries the port's `stored: true` (D81), the views an `editSystem`\n * permission may write; configured and code system views carry none.\n */\nexport function isStored(view: SystemViewBody): boolean {\n return view.source === 'stored' && typeof view.version === 'number';\n}\n\n/** One owner's preferences in one definition (`ViewPreferencesView`). */\nexport interface PreferencesBody {\n definitionId: string;\n order?: string[] | null;\n defaultInstanceId?: string | null;\n autoRun?: boolean | null;\n lastTabs?: Record<string, string> | null;\n /** `0` for preferences never written. */\n version: number;\n}\n\n/** A snapshot's revision: the aggregate's version, compared as a string. */\nexport function revisionOf(version: number): string {\n return String(version);\n}\n\nexport function systemInstance(view: SystemViewBody): ViewInstance {\n return {\n id: view.id,\n definitionId: view.definitionId,\n title: view.title,\n scope: 'system',\n revision: view.revision,\n config: view.config,\n ...(isStored(view) ? { stored: true as const } : {}),\n };\n}\n\nexport function systemSummary(view: SystemViewBody): ViewInstanceSummary {\n return {\n id: view.id,\n definitionId: view.definitionId,\n title: view.title,\n scope: 'system',\n kind: view.kind,\n revision: view.revision,\n ...(isStored(view) ? { stored: true as const } : {}),\n };\n}\n\n/**\n * The port's preferences. A member the server holds as `null` is one never\n * set: `defaultInstanceId` reads as `null`, and `autoRun` and `lastTabs` are\n * left out, as the port's own `emptyPreferences()` leaves them.\n */\nexport function toPreferences(body: PreferencesBody): ViewPreferences {\n return preferencesAt(\n {\n order: body.order ?? [],\n defaultInstanceId: body.defaultInstanceId ?? null,\n autoRun: body.autoRun ?? undefined,\n lastTabs: body.lastTabs ?? undefined,\n },\n body.version,\n );\n}\n\n/** What a preferences write sends: everything but the revision. */\nexport function preferencesInput(\n preferences: Omit<ViewPreferences, 'revision'>,\n): Omit<ViewPreferences, 'revision'> {\n const { order, defaultInstanceId, autoRun, lastTabs } = preferences;\n return {\n order: [...order],\n defaultInstanceId: defaultInstanceId ?? null,\n ...(autoRun === undefined ? {} : { autoRun }),\n ...(lastTabs === undefined ? {} : { lastTabs: { ...lastTabs } }),\n };\n}\n\n/** `preferences` as written at `version`, in the port's shape. */\nexport function preferencesAt(\n preferences: Omit<ViewPreferences, 'revision'>,\n version: number,\n): ViewPreferences {\n return { ...preferencesInput(preferences), revision: revisionOf(version) };\n}\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { type Hop, wait } from '@ahoo-wang/wow-client';\n\n/**\n * The bounded context `view-store`.\n * The view engine's saved views, view preferences and dataset wording\n */\nexport const VIEW_STORE_BOUNDED_CONTEXT = 'view-store';\n\n/** The domain error codes of `view-store`, each a problem's `code` with the status the Manifest gives it. */\nexport const ViewStoreErrorCodes = {\n /** 400: The request carries no CoSec-App-Id. */\n APP_REQUIRED: 'view-store.app-required',\n /** 400: The request is not a valid write: its config, title, preferences or wording. */\n INVALID: 'view-store.invalid',\n /** 404: The aggregate belongs to another application, which reads as none. */\n NOT_FOUND: 'view-store.not-found',\n /** 400: A view is saved by an owner: a user, (shared), or (system) under (platform). */\n OWNER_REQUIRED: 'view-store.owner-required',\n /** 409: A shared dashboard shows the view, which stays shared. */\n REFERENCED_BY_SHARED_DASHBOARD: 'view-store.referenced-by-shared-dashboard',\n /** 403: A system view never moves audience: it is neither shared nor claimed. */\n SYSTEM_VIEW_READ_ONLY: 'view-store.system-view-read-only',\n} as const;\n\n/** A {@link ViewStoreErrorCodes} value. */\nexport type ViewStoreErrorCode = (typeof ViewStoreErrorCodes)[keyof typeof ViewStoreErrorCodes];\n\n/** The subscriptions of `view-store` a `handled` hop names. */\nexport type ViewStoreSubscription = 'ViewAudienceSaga.onAudienceChanged';\n\n/** The hops of a wait chain (`Wow-Wait`) in `view-store`. */\nexport const viewStoreWait = {\n /** Until a command of `view-store` passed admission. */\n accepted: (): Hop => wait.accepted(VIEW_STORE_BOUNDED_CONTEXT),\n /** Until a command's events are appended to the log of `view-store`. */\n committed: (): Hop => wait.committed(VIEW_STORE_BOUNDED_CONTEXT),\n /** Until the snapshot of `view-store` holds the commit. */\n snapshot: (): Hop => wait.snapshot(VIEW_STORE_BOUNDED_CONTEXT),\n /** Until a subscription of `view-store` handled the commit. */\n handled: (subscription: ViewStoreSubscription): Hop => wait.handled(subscription, VIEW_STORE_BOUNDED_CONTEXT),\n} as const;\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport type { EventView, SystemEvent } from '@ahoo-wang/wow-client';\nimport type { ViewAudienceChanged, ViewClaimed, ViewCreated, ViewRenamed, ViewSaved, ViewShared } from '../types.js';\n\n/**\n * The aggregate `view-store.view`.\n * A saved view of the view engine: a record view, an analysis view or a dashboard\n */\nexport const ViewAggregate = {\n context: 'view-store',\n name: 'view',\n path: '/view-store/view',\n ownership: 'OWNER',\n snapshot: true,\n} as const;\n\n/** The `state.*` paths of `view`'s snapshots a query filters, sorts and projects on. */\nexport type ViewStateField = 'state.appId' | 'state.audience' | 'state.config' | 'state.definitionId' | 'state.kind' | 'state.title';\n\n/** The events of `view`, named as the server sends them, `view-store.view.<Event>` at its current revision (the `events` query upgrades older records), and the system events every aggregate has. */\nexport type ViewEvent = EventView<'view-store.view.ViewAudienceChanged', ViewAudienceChanged> | EventView<'view-store.view.ViewClaimed', ViewClaimed> | EventView<'view-store.view.ViewCreated', ViewCreated> | EventView<'view-store.view.ViewRenamed', ViewRenamed> | EventView<'view-store.view.ViewSaved', ViewSaved> | EventView<'view-store.view.ViewShared', ViewShared> | SystemEvent;\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { CommandGateway, type CommandOptions, type CommandResult, type CommandResultStream, type CreateCommandOptions, LifecycleCommands, type WowClientOptions } from '@ahoo-wang/wow-client';\nimport type { ClaimView, CreateView, RenameView, SaveView, ShareView, WowLifecycleTransferOwner } from '../types.js';\nimport { ViewAggregate } from './aggregate.js';\n\n/** The command routes of `view-store.view`. */\nexport const ViewCommandPaths = {\n CLAIM_VIEW: '/view-store/view/{id}/claim-view',\n CREATE_VIEW: '/view-store/view/{id}/create-view',\n CREATE_VIEW_WITHOUT_ID: '/view-store/view/create-view',\n RENAME_VIEW: '/view-store/view/{id}/rename-view',\n SAVE_VIEW: '/view-store/view/{id}/save-view',\n SHARE_VIEW: '/view-store/view/{id}/share-view',\n} as const;\n\n/** Sends the commands of `view-store.view`; a command that did not succeed rejects with a `WowProblemError` holding its result. */\nexport class ViewCommandClient {\n readonly gateway: CommandGateway;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.gateway = new CommandGateway(options);\n }\n\n /**\n * Make a shared view personal\n * `ClaimView`: `POST /view-store/view/{id}/claim-view`.\n * Produces `ViewClaimed`.\n */\n claimView(id: string, body: ClaimView = {}, options?: CommandOptions): Promise<CommandResult> {\n return this.gateway.send(ViewCommandPaths.CLAIM_VIEW, body, { ...options, id });\n }\n\n /** `ClaimView`, answered as one result per hop of its wait (`text/event-stream`). */\n claimViewStream(id: string, body: ClaimView = {}, options?: CommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(ViewCommandPaths.CLAIM_VIEW, body, { ...options, id });\n }\n\n /**\n * Create a view\n * `CreateView`: `POST /view-store/view/{id}/create-view`, `POST /view-store/view/create-view`.\n * Creates the aggregate.\n * Produces `ViewCreated`.\n */\n createView(body: CreateView, options?: CreateCommandOptions): Promise<CommandResult> {\n return this.gateway.send(options?.id === undefined ? ViewCommandPaths.CREATE_VIEW_WITHOUT_ID : ViewCommandPaths.CREATE_VIEW, body, options);\n }\n\n /** `CreateView`, answered as one result per hop of its wait (`text/event-stream`). */\n createViewStream(body: CreateView, options?: CreateCommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(options?.id === undefined ? ViewCommandPaths.CREATE_VIEW_WITHOUT_ID : ViewCommandPaths.CREATE_VIEW, body, options);\n }\n\n /**\n * Rename a view\n * `RenameView`: `POST /view-store/view/{id}/rename-view`.\n * Produces `ViewRenamed`.\n */\n renameView(id: string, body: RenameView, options?: CommandOptions): Promise<CommandResult> {\n return this.gateway.send(ViewCommandPaths.RENAME_VIEW, body, { ...options, id });\n }\n\n /** `RenameView`, answered as one result per hop of its wait (`text/event-stream`). */\n renameViewStream(id: string, body: RenameView, options?: CommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(ViewCommandPaths.RENAME_VIEW, body, { ...options, id });\n }\n\n /**\n * Save a view's config\n * `SaveView`: `POST /view-store/view/{id}/save-view`.\n * Produces `ViewSaved`.\n */\n saveView(id: string, body: SaveView, options?: CommandOptions): Promise<CommandResult> {\n return this.gateway.send(ViewCommandPaths.SAVE_VIEW, body, { ...options, id });\n }\n\n /** `SaveView`, answered as one result per hop of its wait (`text/event-stream`). */\n saveViewStream(id: string, body: SaveView, options?: CommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(ViewCommandPaths.SAVE_VIEW, body, { ...options, id });\n }\n\n /**\n * Make a view shared\n * `ShareView`: `POST /view-store/view/{id}/share-view`.\n * Produces `ViewShared`.\n */\n shareView(id: string, body: ShareView = {}, options?: CommandOptions): Promise<CommandResult> {\n return this.gateway.send(ViewCommandPaths.SHARE_VIEW, body, { ...options, id });\n }\n\n /** `ShareView`, answered as one result per hop of its wait (`text/event-stream`). */\n shareViewStream(id: string, body: ShareView = {}, options?: CommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(ViewCommandPaths.SHARE_VIEW, body, { ...options, id });\n }\n\n /**\n * Marks the aggregate deleted; its events stay in the log.\n * The lifecycle command `wow.lifecycle.DeleteAggregate`.\n */\n deleteAggregate(id: string, options?: CommandOptions): Promise<CommandResult> {\n return this.gateway.lifecycle(ViewAggregate.path, id, LifecycleCommands.DELETE_AGGREGATE, undefined, options);\n }\n\n /** The lifecycle command `wow.lifecycle.TransferOwner`. */\n transferOwner(id: string, body: WowLifecycleTransferOwner, options?: CommandOptions): Promise<CommandResult> {\n return this.gateway.lifecycle(ViewAggregate.path, id, LifecycleCommands.TRANSFER_OWNER, body, options);\n }\n}\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { EventQueryClient, SnapshotQueryClient, StateClient, type WowClientOptions } from '@ahoo-wang/wow-client';\nimport type { ViewState } from '../types.js';\nimport { ViewAggregate, type ViewEvent, type ViewStateField } from './aggregate.js';\n\n/** Queries the snapshots of `view-store.view`: `POST /view-store/view/snapshot/query`. */\nexport class ViewSnapshotQueryClient extends SnapshotQueryClient<ViewState, ViewStateField> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(ViewAggregate, options);\n }\n}\n\n\n/** Queries the event streams of `view-store.view`, one record per commit: `POST /view-store/view/events/query`. */\nexport class ViewEventQueryClient extends EventQueryClient<ViewEvent> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(ViewAggregate, options);\n }\n}\n\n\n/** Reads the states of `view-store.view`, at a version or a time, and their traces: `GET /view-store/view/{id}/state`. */\nexport class ViewStateClient extends StateClient<ViewState, ViewEvent> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(ViewAggregate, options);\n }\n}\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { CommandGateway, type CommandResult, type CommandResultStream, type CreateCommandOptions, type WowClientOptions } from '@ahoo-wang/wow-client';\nimport type { SetViewPreferences } from '../types.js';\n\n/** The command routes of `view-store.view_preferences`. */\nexport const ViewPreferencesCommandPaths = {\n SET_VIEW_PREFERENCES: '/view-store/view_preferences/{id}/set-view-preferences',\n SET_VIEW_PREFERENCES_WITHOUT_ID: '/view-store/view_preferences/set-view-preferences',\n} as const;\n\n/** Sends the commands of `view-store.view_preferences`; a command that did not succeed rejects with a `WowProblemError` holding its result. */\nexport class ViewPreferencesCommandClient {\n readonly gateway: CommandGateway;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.gateway = new CommandGateway(options);\n }\n\n /**\n * Set the view preferences of a definition\n * `SetViewPreferences`: `POST /view-store/view_preferences/{id}/set-view-preferences`, `POST /view-store/view_preferences/set-view-preferences`.\n * Creates the aggregate, or acts on the one that exists.\n * Produces `ViewPreferencesSet`.\n */\n setViewPreferences(body: SetViewPreferences, options?: CreateCommandOptions): Promise<CommandResult> {\n return this.gateway.send(options?.id === undefined ? ViewPreferencesCommandPaths.SET_VIEW_PREFERENCES_WITHOUT_ID : ViewPreferencesCommandPaths.SET_VIEW_PREFERENCES, body, options);\n }\n\n /** `SetViewPreferences`, answered as one result per hop of its wait (`text/event-stream`). */\n setViewPreferencesStream(body: SetViewPreferences, options?: CreateCommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(options?.id === undefined ? ViewPreferencesCommandPaths.SET_VIEW_PREFERENCES_WITHOUT_ID : ViewPreferencesCommandPaths.SET_VIEW_PREFERENCES, body, options);\n }\n}\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport type { EventView, SystemEvent } from '@ahoo-wang/wow-client';\nimport type { ViewPreferencesSet } from '../types.js';\n\n/**\n * The aggregate `view-store.view_preferences`.\n * One owner's view preferences for one definition in one application\n */\nexport const ViewPreferencesAggregate = {\n context: 'view-store',\n name: 'view_preferences',\n path: '/view-store/view_preferences',\n ownership: 'OWNER',\n snapshot: true,\n} as const;\n\n/** The `state.*` paths of `view_preferences`'s snapshots a query filters, sorts and projects on. */\nexport type ViewPreferencesStateField = 'state.appId' | 'state.autoRun' | 'state.defaultInstanceId' | 'state.definitionId' | 'state.lastTabs' | 'state.order';\n\n/** The events of `view_preferences`, named as the server sends them, `view-store.view_preferences.<Event>` at its current revision (the `events` query upgrades older records), and the system events every aggregate has. */\nexport type ViewPreferencesEvent = EventView<'view-store.view_preferences.ViewPreferencesSet', ViewPreferencesSet> | SystemEvent;\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { EventQueryClient, SnapshotQueryClient, StateClient, type WowClientOptions } from '@ahoo-wang/wow-client';\nimport type { ViewPreferencesState } from '../types.js';\nimport { ViewPreferencesAggregate, type ViewPreferencesEvent, type ViewPreferencesStateField } from './aggregate.js';\n\n/** Queries the snapshots of `view-store.view_preferences`: `POST /view-store/view_preferences/snapshot/query`. */\nexport class ViewPreferencesSnapshotQueryClient extends SnapshotQueryClient<ViewPreferencesState, ViewPreferencesStateField> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(ViewPreferencesAggregate, options);\n }\n}\n\n\n/** Queries the event streams of `view-store.view_preferences`, one record per commit: `POST /view-store/view_preferences/events/query`. */\nexport class ViewPreferencesEventQueryClient extends EventQueryClient<ViewPreferencesEvent> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(ViewPreferencesAggregate, options);\n }\n}\n\n\n/** Reads the states of `view-store.view_preferences`, at a version or a time, and their traces: `GET /view-store/view_preferences/{id}/state`. */\nexport class ViewPreferencesStateClient extends StateClient<ViewPreferencesState, ViewPreferencesEvent> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(ViewPreferencesAggregate, options);\n }\n}\n","/*\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 FrameworkErrorCodes,\n toWowProblemError,\n type WowProblemError,\n} from '@ahoo-wang/wow-client';\nimport {\n isViewStoreError,\n ViewStoreError,\n type ViewStoreErrorCode,\n} from '@ahoo-wang/wow-view-engine';\nimport { ViewStoreErrorCodes } from './generated/view-store/boundedContext.js';\n\n/**\n * The V10 view store's own problem codes (`ViewStoreRejections` of\n * `platform/view-store`), beside the framework's (`FrameworkErrorCodes` of\n * `@ahoo-wang/wow-client`): generated from the service's Manifest.\n *\n * Named apart from the engine's `ViewStoreErrorCode` (the port's codes):\n * these are the `code` of the server's problems, which a `ViewStoreError`\n * carries as `detail.code`.\n */\nexport const WowViewStoreErrorCodes = ViewStoreErrorCodes;\n\n/** The port's code of each problem code the server answers with. */\nconst CODES: Readonly<Record<string, ViewStoreErrorCode>> = {\n [FrameworkErrorCodes.AGGREGATE_VERSION_MISMATCH]: 'CONFLICT',\n // A request id another command already used: the write cannot be told\n // from that one, so it is refused as the stale write it most likely is.\n [FrameworkErrorCodes.COMMAND_REQUEST_ID_REUSED]: 'CONFLICT',\n [FrameworkErrorCodes.AGGREGATE_NOT_FOUND]: 'NOT_FOUND',\n [FrameworkErrorCodes.QUERY_NOT_FOUND]: 'NOT_FOUND',\n [FrameworkErrorCodes.AGGREGATE_DELETED]: 'NOT_FOUND',\n [ViewStoreErrorCodes.NOT_FOUND]: 'NOT_FOUND',\n [FrameworkErrorCodes.AUTH_UNAUTHENTICATED]: 'FORBIDDEN',\n [FrameworkErrorCodes.AUTH_FORBIDDEN]: 'FORBIDDEN',\n [FrameworkErrorCodes.AGGREGATE_FORBIDDEN]: 'FORBIDDEN',\n [ViewStoreErrorCodes.SYSTEM_VIEW_READ_ONLY]: 'FORBIDDEN',\n [ViewStoreErrorCodes.INVALID]: 'INVALID',\n [ViewStoreErrorCodes.APP_REQUIRED]: 'INVALID',\n [ViewStoreErrorCodes.OWNER_REQUIRED]: 'INVALID',\n [ViewStoreErrorCodes.REFERENCED_BY_SHARED_DASHBOARD]: 'INVALID',\n [FrameworkErrorCodes.AGGREGATE_EXISTS]: 'INVALID',\n [FrameworkErrorCodes.COMMAND_MALFORMED]: 'INVALID',\n [FrameworkErrorCodes.COMMAND_INVALID]: 'INVALID',\n [FrameworkErrorCodes.COMMAND_UNHANDLED]: 'INVALID',\n [FrameworkErrorCodes.WAIT_INVALID]: 'INVALID',\n [FrameworkErrorCodes.QUERY_MALFORMED]: 'INVALID',\n [FrameworkErrorCodes.QUERY_INVALID]: 'INVALID',\n};\n\n/**\n * A request that did not succeed, as the store reads it: the server's\n * problem when it answered with one, else what the request threw.\n */\nexport class Failure {\n constructor(\n /** What the request threw. */\n readonly cause: unknown,\n /** The server's problem, when a response came back. */\n readonly problem?: WowProblemError,\n ) {}\n\n /** The problem's code: a framework code (`wow.*`) or the view store's. */\n get problemCode(): string | undefined {\n return this.problem?.code;\n }\n\n /**\n * The port's code, **by the problem's code first**: one HTTP status\n * carries several decisions (a `400` is a bad title and a missing\n * application alike). Only an answer without a code the store knows — a\n * gateway's own page, a proxy, a code a later server adds — falls back to\n * the status; a problem the service says a retry may get past is\n * `UNAVAILABLE` whatever its status. A `404` without a code is a route the server does not serve:\n * no view store there (or, on the memory backend, no snapshot query), so\n * `UNSUPPORTED`. No answer at all is `UNAVAILABLE`: the outcome is\n * unknown, and a retry under the same request id is safe, since the\n * server deduplicates it.\n */\n get code(): ViewStoreErrorCode {\n const code = this.problemCode;\n const known = code === undefined ? undefined : CODES[code];\n if (known) return known;\n // What a retry may get past (a busy or closing node, a store out of\n // reach, contended writers, a wait that ran out): the outcome is unknown.\n if (this.problem?.retry.retryable) return 'UNAVAILABLE';\n switch (this.problem?.status) {\n case 400:\n case 422:\n return 'INVALID';\n case 401:\n case 403:\n return 'FORBIDDEN';\n case 404:\n return code === undefined ? 'UNSUPPORTED' : 'NOT_FOUND';\n case 410:\n return 'NOT_FOUND';\n case 409:\n case 412:\n return 'CONFLICT';\n default:\n return 'UNAVAILABLE';\n }\n }\n\n /** Whether the server (or something in front of it) answered at all. */\n get reached(): boolean {\n return this.problem !== undefined;\n }\n\n get message(): string {\n if (this.problem) return this.problem.message;\n return `The view store could not be reached: ${reasonOf(this.cause)}`;\n }\n\n /** The port's error, holding what it was read from. */\n toStoreError(): ViewStoreError {\n return new ViewStoreError(this.code, this.message, this.held());\n }\n\n /**\n * What {@link toStoreError} holds, for an error of another code: the\n * request's own failure as `cause`, the problem's code as `detail` (a\n * host tells `view-store.app-required` from `view-store.invalid` by it),\n * and for `UNAVAILABLE` whether the server answered (`reachable`).\n */\n held(): {\n cause: unknown;\n detail?: { code: string };\n reachable?: true;\n } {\n const code = this.problemCode;\n return {\n cause: this.cause,\n ...(code === undefined ? {} : { detail: { code } }),\n ...(this.code === 'UNAVAILABLE' && this.reached\n ? { reachable: true as const }\n : {}),\n };\n }\n}\n\n/** What a failed request threw, read as a {@link Failure}. */\nexport async function failureOf(error: unknown): Promise<Failure> {\n if (error instanceof Failure) return error;\n return new Failure(error, await toWowProblemError(error));\n}\n\n/**\n * The titles of the shared dashboards a claim refusal names: the problem's\n * `boards` extension member, a list of `{ id, title }` (decision D211). A\n * board without a title is named by its id; anything else is skipped.\n */\nexport function boardTitles(\n extensions: Readonly<Record<string, unknown>> | undefined,\n): string[] {\n const boards = extensions?.boards;\n if (!Array.isArray(boards)) return [];\n return boards.flatMap((board: unknown) => {\n if (typeof board !== 'object' || board === null) return [];\n const { id, title } = board as { id?: unknown; title?: unknown };\n if (typeof title === 'string' && title.trim() !== '') return [title];\n return typeof id === 'string' ? [id] : [];\n });\n}\n\n/**\n * Runs one of the port's methods, so that everything it rejects with is a\n * `ViewStoreError`: a failed request as its code says, anything else — a\n * body that did not parse — as `UNAVAILABLE`, the outcome unknown.\n */\nexport async function guard<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (thrown) {\n if (thrown instanceof Failure) throw thrown.toStoreError();\n if (isViewStoreError(thrown)) throw thrown;\n // A body that did not parse came back from something — a login wall's\n // page, a proxy's: answered, so not \"could not be reached\".\n throw new ViewStoreError(\n 'UNAVAILABLE',\n thrown instanceof Error ? thrown.message : String(thrown),\n {\n cause: thrown,\n ...(thrown instanceof SyntaxError ? { reachable: true as const } : {}),\n },\n );\n }\n}\n\n/** Runs one request, so that what it throws is a {@link Failure}. */\nexport async function request<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n // A body that did not parse is no failed request: `guard` reads it.\n if (error instanceof SyntaxError) throw error;\n throw await failureOf(error);\n }\n}\n\n/** What a refusal said; a `DOMException` is an `Error` only in some realms. */\nfunction reasonOf(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (typeof message === 'string')\n return typeof name === 'string' ? `${name}: ${message}` : message;\n }\n return String(error);\n}\n","/*\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 { Fetcher } from '@ahoo-wang/fetcher';\nimport type { SystemViewBody } from './views.js';\nimport { request } from './errors.js';\n\n/**\n * The system views route, `GET /view-store/system-views[/{id}]`: the\n * service's own route, ordered before Wow's and outside the Manifest, so no\n * client is generated for it. It answers the configured system views of the\n * caller's tenant and application and the stored ones, in the 9.x\n * `SystemView` shape; the tenant is the principal's, the application the\n * request's `CoSec-App-Id`.\n */\nexport const SYSTEM_VIEWS_PATH = '/view-store/system-views';\n\n/** The system views route, through the store's fetcher. */\nexport class SystemViewsClient {\n constructor(private readonly fetcher: Fetcher) {}\n\n /** The definition's system views: the configured ones first, in their order. */\n list(definitionId: string, signal?: AbortSignal): Promise<SystemViewBody[]> {\n return this.get(\n `${SYSTEM_VIEWS_PATH}?definitionId=${encodeURIComponent(definitionId)}`,\n signal,\n );\n }\n\n /** One system view; `404 view-store.not-found` for none. */\n one(id: string, signal?: AbortSignal): Promise<SystemViewBody> {\n return this.get(`${SYSTEM_VIEWS_PATH}/${encodeURIComponent(id)}`, signal);\n }\n\n private get<T>(url: string, signal: AbortSignal | undefined): Promise<T> {\n return request(async () => {\n const response = await this.fetcher.fetch(url, {\n method: 'GET',\n ...(signal === undefined ? {} : { signal }),\n });\n return (await response.json()) as T;\n });\n }\n}\n","/*\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\n/*\n * The V10 view store's shapes, as far as the store reads them, and their\n * reading as the port's. The server stores the engine's `ViewConfig` whole\n * and never reads its meaning; it keeps the config's `kind` beside it, as\n * `state.kind`, which a list projects and filters on.\n */\n\nimport type { TargetScope } from '@ahoo-wang/wow-client';\nimport type {\n DatasetOverrides,\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n} from '@ahoo-wang/wow-view-engine';\nimport { revisionOf } from './views.js';\nimport {\n SHARED_OWNER_ID,\n SYSTEM_OWNER_ID,\n SYSTEM_TENANT_ID,\n type Place,\n} from './paths.js';\nimport type {\n DatasetWordingState,\n ViewState,\n} from './generated/view-store/types.js';\n\n/** The `Wow-Scope` of the shared views: the reserved owner `(shared)`. */\nexport const SHARED_SCOPE: TargetScope = Object.freeze({\n ownerId: SHARED_OWNER_ID,\n});\n\n/** The `Wow-Scope` of the stored system views: `(system)` of `(platform)`. */\nexport const SYSTEM_SCOPE: TargetScope = Object.freeze({\n tenantId: SYSTEM_TENANT_ID,\n ownerId: SYSTEM_OWNER_ID,\n});\n\n/**\n * The `Wow-Scope` a request at `place` carries: none for the caller's own\n * views, whose owner the server takes from the principal.\n */\nexport function scopeAt(place: Place): TargetScope | undefined {\n switch (place) {\n case 'shared':\n return SHARED_SCOPE;\n case 'system':\n return SYSTEM_SCOPE;\n default:\n return undefined;\n }\n}\n\n/** A view's snapshot or state as the store reads it: its id, version and state. */\nexport interface ViewRecord {\n id: string;\n version: number;\n state: Pick<ViewState, 'definitionId' | 'title' | 'audience'> &\n Partial<Pick<ViewState, 'kind' | 'config'>>;\n}\n\n/** The fields a list reads, and of the config only its `kind`, kept apart. */\nexport const SUMMARY_FIELDS = [\n 'aggregateId',\n 'version',\n 'state.definitionId',\n 'state.title',\n 'state.audience',\n 'state.kind',\n] as const;\n\nexport function toInstance({ id, version, state }: ViewRecord): ViewInstance {\n return {\n id,\n definitionId: state.definitionId,\n title: state.title,\n scope: state.audience,\n revision: revisionOf(version),\n config: state.config as unknown as ViewConfig,\n };\n}\n\nexport function toSummary({\n id,\n version,\n state,\n}: ViewRecord): ViewInstanceSummary {\n return {\n id,\n definitionId: state.definitionId,\n title: state.title,\n scope: state.audience,\n kind: state.kind!,\n revision: revisionOf(version),\n };\n}\n\n/** The engine's overrides from a stored wording: what is stored, nothing more. */\nexport function wordingOf(\n state: Pick<DatasetWordingState, 'title' | 'recordNoun' | 'fields'>,\n): DatasetOverrides {\n return {\n ...(state.title == null ? {} : { title: state.title }),\n ...(state.recordNoun == null ? {} : { recordNoun: state.recordNoun }),\n ...(state.fields == null\n ? {}\n : { fields: state.fields as DatasetOverrides['fields'] }),\n };\n}\n","/*\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 { Fetcher } from '@ahoo-wang/fetcher';\nimport { asc, filter, listQuery, singleQuery } from '@ahoo-wang/wow-client/dsl';\nimport {\n FrameworkErrorCodes,\n type CommandOptions,\n type CommandResult,\n type WowClientOptions,\n} from '@ahoo-wang/wow-client';\nimport {\n emptyPreferences,\n isSystemInstanceId,\n ViewStoreError,\n type ViewAudience,\n type ViewConfig,\n type ViewInstance,\n type ViewInstanceSummary,\n type ViewPermissions,\n type ViewPreferences,\n type ViewStore,\n type WriteContext,\n} from '@ahoo-wang/wow-view-engine';\nimport { SHARED_OWNER_ID, SYSTEM_OWNER_ID, type Place } from './paths.js';\nimport { Remembered } from './remembered.js';\nimport {\n isStored,\n preferencesAt,\n preferencesInput,\n systemInstance,\n systemSummary,\n toPreferences,\n type SystemViewBody,\n} from './views.js';\nimport {\n ViewStoreErrorCodes,\n viewStoreWait,\n} from './generated/view-store/boundedContext.js';\nimport { ViewCommandClient } from './generated/view-store/view/commandClient.js';\nimport {\n ViewSnapshotQueryClient,\n ViewStateClient,\n} from './generated/view-store/view/queryClient.js';\nimport { ViewPreferencesCommandClient } from './generated/view-store/view_preferences/commandClient.js';\nimport { ViewPreferencesSnapshotQueryClient } from './generated/view-store/view_preferences/queryClient.js';\nimport type { ViewState } from './generated/view-store/types.js';\nimport { boardTitles, Failure, guard, request } from './errors.js';\nimport { SystemViewsClient } from './systemViews.js';\nimport {\n scopeAt,\n SUMMARY_FIELDS,\n toInstance,\n toSummary,\n type ViewRecord,\n} from './wire.js';\n\n/** How a V10 {@link WowViewStore} reaches the view store service. */\nexport interface WowViewStoreOptions {\n /**\n * The fetcher every request goes through, on the base URL that serves\n * `/view-store/…` (the V10 view store service, or a gateway in front of\n * it).\n *\n * Its interceptors carry who is asking; the store never does. The V10\n * service takes the tenant and the owner from the principal, so no path\n * names them: the interceptors send the authorization (CoSec's token, or\n * the headers the service's own caller resolver reads) and `CoSec-App-Id`,\n * the application every view, preference and wording is kept in. The\n * store adds `Wow-Scope` itself where it acts as a reserved owner: the\n * shared views' `(shared)`, and `(system)` of `(platform)` for stored\n * system views.\n */\n fetcher: Fetcher;\n /**\n * Which buttons are enabled for one definition's views. The service\n * authorizes each write; a host answers this by the roles it holds there —\n * `changeAudience` and the shared views' writes by the role that writes\n * the owner `(shared)` (`view-store.shared-writer` on the service as\n * shipped), `editSystem` by the one that writes `(system)`. Left out,\n * everything is allowed, as the port reads a store without `permissions`.\n */\n permissions?: (definitionId: string) => ViewPermissions;\n}\n\n/**\n * The largest list the server answers (its query budget); a definition with\n * more views of one audience lists the first this many.\n */\nconst LIST_LIMIT = 1000;\n\n/** How many system views' revisions the store remembers the version of. */\nconst REMEMBERED_SYSTEM_REVISIONS = 1024;\n\n/**\n * What a share or a claim waits for: the saga that moves the view to its\n * new owner, then that move's snapshot. The view's own commit changes its\n * audience; the owner, which reads and writes go by, changes one version\n * later (`ViewAudienceSaga`).\n */\nconst AUDIENCE_WAIT = [\n viewStoreWait.handled('ViewAudienceSaga.onAudienceChanged'),\n viewStoreWait.snapshot(),\n];\n\n/** One instance write, as sent from the place the view is at. */\ninterface InstanceWrite {\n /** Sends it with the options the store fills. */\n send(options: CommandOptions): Promise<CommandResult>;\n /** The place whose `Wow-Scope` it is sent with. */\n sentFrom: Place;\n /** Where the view is once it lands; `null` for a delete. */\n landsAt: Place | null;\n /** A share or a claim: it moves the view, waiting for the move. */\n moves?: boolean;\n}\n\n/**\n * The view engine's `ViewStore` over the **V10** view store service\n * (`platform/view-store` in the Wow repository): saved views and preferences\n * as two Wow V10 aggregates, reached through the clients generated from the\n * service's Manifest (`@ahoo-wang/wow-client`), and the system views\n * through the service's own route.\n *\n * **The owner is the audience.** A personal view is the caller's own; a\n * shared one belongs to the reserved owner `(shared)`, which the store acts\n * as with `Wow-Scope: owner=\"(shared)\"`; a stored system view to `(system)`\n * of the tenant `(platform)`. The port names a view by id alone, so the\n * store remembers where it last saw each one and looks an unknown id up as\n * the caller, as `(shared)` and among the system views, in that order.\n * Sharing and claiming move a view to the other owner in place, id kept:\n * the store waits for the service's `ViewAudienceSaga` to move it.\n *\n * **Writes** carry the port's `requestId` as `Wow-Request-Id` and its\n * `revision` as `If-Match`, and wait for the snapshot. The service\n * deduplicates a request id, creates included, so a retry is answered with\n * the first attempt's outcome; the store answers the view read back at the\n * version that write left (`GET …/{id}/state?version=`). A stale revision\n * is `CONFLICT` carrying the view as it is now.\n *\n * **Errors** are read by the problem's code onto the port's codes, by the\n * HTTP status only for an answer without a code the store knows; a `404`\n * without a code is a route the service does not serve (`UNSUPPORTED`), and\n * a request that got no answer is `UNAVAILABLE`.\n */\nexport class WowViewStore implements ViewStore {\n /**\n * The most of one audience a list answers (`LIST_LIMIT`): an audience\n * listed this full was cut there, which the workbench then says (R2-26).\n */\n readonly listLimit = LIST_LIMIT;\n /** The host's {@link WowViewStoreOptions.permissions}, when it gave any. */\n readonly permissions?: (definitionId: string) => ViewPermissions;\n private readonly commands: ViewCommandClient;\n private readonly snapshots: ViewSnapshotQueryClient;\n private readonly states: ViewStateClient;\n private readonly preferenceCommands: ViewPreferencesCommandClient;\n private readonly preferenceSnapshots: ViewPreferencesSnapshotQueryClient;\n private readonly systemViews: SystemViewsClient;\n /** Where each view was last seen, by id. */\n private readonly places = new Map<string, Place>();\n /**\n * The version of each stored system view at each revision the store has\n * seen it at (a hash of its content, while a write expects the version),\n * by `id` and revision; `null` for a configured one, which is read-only.\n * Keeping the old revisions too lets a retry send the version its first\n * attempt expected, which the service then answers as a duplicate.\n */\n private readonly systemVersions = new Remembered<number | null>(\n REMEMBERED_SYSTEM_REVISIONS,\n );\n\n constructor(options: WowViewStoreOptions) {\n const client: WowClientOptions = { fetcher: options.fetcher };\n this.commands = new ViewCommandClient(client);\n this.snapshots = new ViewSnapshotQueryClient(client);\n this.states = new ViewStateClient(client);\n this.preferenceCommands = new ViewPreferencesCommandClient(client);\n this.preferenceSnapshots = new ViewPreferencesSnapshotQueryClient(client);\n this.systemViews = new SystemViewsClient(options.fetcher);\n // Left undefined when the host declared none, which the port reads as\n // \"everything is allowed\".\n if (options.permissions) this.permissions = options.permissions;\n }\n\n /**\n * The caller's personal views, the shared views and the service's system\n * views of the definition: three requests, sent together, answered in the\n * port's order — system, shared, personal, each oldest first (the service\n * sorts each audience by the time its first event was written).\n */\n list(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewInstanceSummary[]> {\n return guard(async () => {\n const query = listQuery({\n filter: filter.eq('state.definitionId', definitionId),\n projection: { include: [...SUMMARY_FIELDS] },\n sort: [asc('firstEventTime'), asc('aggregateId')],\n limit: LIST_LIMIT,\n });\n const [personal, shared, system] = await Promise.all([\n request(() => this.snapshots.list(query, { signal })),\n request(() =>\n this.snapshots.list(query, { scope: scopeAt('shared'), signal }),\n ),\n this.systemViews.list(definitionId, signal),\n ]);\n for (const view of system) this.rememberSystem(view);\n const seen = new Map<string, ViewInstanceSummary>();\n for (const summary of [\n ...personal.map(record => toSummary(recordOf(record))),\n ...shared.map(record => toSummary(recordOf(record))),\n ...system.map(systemSummary),\n ]) {\n if (seen.has(summary.id)) continue;\n seen.set(summary.id, summary);\n this.places.set(summary.id, summary.scope);\n }\n // Sorted stably: within an audience, the service's order stands.\n return [...seen.values()].sort(\n (a, b) => AUDIENCE_RANK[a.scope] - AUDIENCE_RANK[b.scope],\n );\n });\n }\n\n /** View `id` wherever it is: the caller's, shared, or a system view. */\n get(id: string, signal?: AbortSignal): Promise<ViewInstance> {\n return guard(async () => (await this.find(id, signal)).instance);\n }\n\n /**\n * Creates the view as the owner of its `scope`; the service generates the\n * id. A retry under the same request id is answered with the first\n * attempt's view, whichever store sends it: the service deduplicates it.\n */\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return guard(async () => {\n const place: Place = input.scope;\n const { definitionId, title, config } = input;\n const write: InstanceWrite = {\n send: options =>\n this.commands.createView(\n { definitionId, title, config: bodyOf(config) },\n options,\n ),\n sentFrom: place,\n landsAt: place,\n };\n const result = await request(() =>\n write.send(this.commandOptions(place, context)),\n );\n return (await this.landed(result.ref.id, write, result, context))!;\n });\n }\n\n /** Replaces the view's config, at the expected `revision`. */\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.write(id, revision, context, place => ({\n send: options =>\n this.commands.saveView(id, { config: bodyOf(config) }, options),\n sentFrom: place,\n landsAt: place,\n })) as Promise<ViewInstance>;\n }\n\n /** Renames the view (the service trims the title), at the expected `revision`. */\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.write(id, revision, context, place => ({\n send: options => this.commands.renameView(id, { title }, options),\n sentFrom: place,\n landsAt: place,\n })) as Promise<ViewInstance>;\n }\n\n /**\n * 设为共享 sends `share-view` as the caller, the view's owner; 设为个人\n * sends `claim-view` as `(shared)`, which the service admits only with\n * the role that writes the owner `(shared)`, and which makes the caller\n * the owner. Either waits for the move (`ViewAudienceSaga`). Each is sent\n * from the same owner whether or not the view has moved, so a retry is\n * answered as its first attempt's duplicate even after the move.\n *\n * Asked for the audience the view already has, the service refuses the\n * command as outside that owner's scope; the store then answers the view\n * as it is, revision unmoved, once the revision matches.\n *\n * A shared view a shared dashboard shows stays shared: the service\n * refuses the claim and names the boards, and the refusal carries them by\n * **title** in `boards`, as they are stored.\n */\n changeAudience(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.write(id, revision, context, place => {\n if (place === 'system') readOnly('A system view never moves audience');\n return audience === 'shared'\n ? {\n send: options => this.commands.shareView(id, {}, options),\n sentFrom: 'personal',\n landsAt: 'shared',\n moves: true,\n }\n : {\n send: options => this.commands.claimView(id, {}, options),\n sentFrom: 'shared',\n landsAt: 'personal',\n moves: true,\n };\n }) as Promise<ViewInstance>;\n }\n\n /** Deletes the view, at the expected `revision`; a board showing it keeps a broken panel. */\n async delete(\n id: string,\n revision: string,\n context: WriteContext,\n ): Promise<void> {\n await this.write(id, revision, context, place => ({\n send: options => this.commands.deleteAggregate(id, options),\n sentFrom: place,\n landsAt: null,\n }));\n }\n\n /**\n * The caller's preferences of the definition, in the request's\n * application: the service derives their id from the owner, the\n * application and the definition. None written yet reads as the port's\n * empty preferences, at revision `'0'`.\n */\n getPreferences(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewPreferences> {\n return guard(async () => {\n try {\n const record = await request(() =>\n this.preferenceSnapshots.single(\n singleQuery({\n filter: filter.eq('state.definitionId', definitionId),\n }),\n { signal },\n ),\n );\n return toPreferences({ ...record.state, version: record.version });\n } catch (thrown) {\n if (\n thrown instanceof Failure &&\n thrown.problemCode === FrameworkErrorCodes.QUERY_NOT_FOUND\n )\n return emptyPreferences();\n throw thrown;\n }\n });\n }\n\n /**\n * Writes the preferences at the expected `revision` (`'0'` for ones never\n * written, which `If-Match: \"0\"` says). A retry under the same request id\n * is answered as the first attempt's duplicate, at its version.\n */\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences> {\n return guard(async () => {\n const { requestId, signal } = context;\n try {\n const result = await request(() =>\n this.preferenceCommands.setViewPreferences(\n { definitionId, ...preferencesInput(preferences) },\n {\n requestId,\n expectedVersion: versionOf(preferences.revision),\n ...(signal === undefined ? {} : { signal }),\n },\n ),\n );\n return typeof result.version === 'number'\n ? preferencesAt(preferences, result.version)\n : await this.getPreferences(definitionId, signal);\n } catch (thrown) {\n if (!(thrown instanceof Failure) || thrown.code !== 'CONFLICT')\n throw thrown;\n throw new ViewStoreError('CONFLICT', thrown.message, {\n ...thrown.held(),\n preferences: await this.getPreferences(definitionId, signal),\n });\n }\n });\n }\n\n /**\n * One instance write: to the place the view is at, then the answer read\n * back. A view remembered at a place it has since left (another tab shared\n * it) is looked up again and the write sent once more from where it is.\n * A move refused because the view already has the audience it asks for\n * changes nothing: the view is answered as it is, once its revision\n * matches.\n */\n private write(\n id: string,\n revision: string,\n context: WriteContext,\n plan: (place: Place) => InstanceWrite,\n ): Promise<ViewInstance | undefined> {\n return guard(async () => {\n const { signal } = context;\n const remembered = this.places.get(id);\n let place = remembered ?? (await this.find(id, signal)).place;\n let relocated = remembered === undefined;\n for (;;) {\n const write = plan(place);\n const options = this.commandOptions(write.sentFrom, context, {\n expectedVersion:\n place === 'system'\n ? await this.systemVersion(id, revision, signal)\n : versionOf(revision),\n ...(write.moves ? { wait: { plan: AUDIENCE_WAIT } } : {}),\n });\n let result: CommandResult;\n try {\n result = await request(() => write.send(options));\n } catch (thrown) {\n if (!(thrown instanceof Failure)) throw thrown;\n if (\n write.moves &&\n place === write.landsAt &&\n thrown.code === 'FORBIDDEN'\n )\n return this.unchanged(id, revision, place, signal);\n if (\n !relocated &&\n (thrown.code === 'NOT_FOUND' || thrown.code === 'FORBIDDEN')\n ) {\n relocated = true;\n const found = (await this.find(id, signal, null)).place;\n if (found !== place) {\n place = found;\n continue;\n }\n }\n if (thrown.code === 'CONFLICT')\n throw await this.conflict(id, thrown, signal);\n throw refusal(thrown);\n }\n // Landed: what goes wrong reading it back is never a reason to send\n // it again.\n return this.landed(id, write, result, context);\n }\n });\n }\n\n /**\n * A landed write's answer: the view read back at the version it left\n * (`GET …/{id}/state?version=`). A system view's revision is its content\n * hash, so it is read from its route as it is now.\n *\n * A move is two commits: the view's own (its audience), then the saga's\n * (its owner). Waited for, the result's version is the second; a\n * duplicate answers the first, so the move is read one version later,\n * where the owner it names must be the one it moved to. Anything else\n * (another writer between the two) answers the view as it is now.\n */\n private async landed(\n id: string,\n write: InstanceWrite,\n result: CommandResult,\n context: WriteContext,\n ): Promise<ViewInstance | undefined> {\n const { landsAt } = write;\n if (landsAt === null) return undefined;\n this.places.set(id, landsAt);\n const { signal } = context;\n const read = typeof result.version === 'number' ? result.version : null;\n if (landsAt !== 'system' && read !== null)\n try {\n const version = write.moves && result.duplicate ? read + 1 : read;\n const view = await request(() =>\n this.states.get(id, {\n version,\n ...optionsAt(landsAt),\n ...(signal === undefined ? {} : { signal }),\n }),\n );\n if (!write.moves || ownedAt(view.scope.ownerId) === landsAt)\n return toInstance({ id, version: view.version, state: view.state });\n } catch {\n // Moved on since (another tab moved it): answered as it is.\n }\n return (await this.find(id, signal, landsAt)).instance;\n }\n\n /** A move to where the view already is: the view as it is, at `revision`. */\n private async unchanged(\n id: string,\n revision: string,\n place: Place,\n signal: AbortSignal | undefined,\n ): Promise<ViewInstance> {\n const { instance } = await this.find(id, signal, place);\n if (instance.revision !== revision)\n throw new ViewStoreError(\n 'CONFLICT',\n `View ${id} has moved on from revision ${revision}`,\n { instance },\n );\n return instance;\n }\n\n /** A stale write's refusal, carrying the view as it is now. */\n private async conflict(\n id: string,\n failure: Failure,\n signal: AbortSignal | undefined,\n ): Promise<ViewStoreError> {\n const { instance } = await this.find(id, signal, null);\n return new ViewStoreError('CONFLICT', failure.message, {\n ...failure.held(),\n instance,\n });\n }\n\n /**\n * View `id` and where it is: first where it was last seen (`first`, `null`\n * to ignore that), then as the caller, as `(shared)` and among the system\n * views.\n */\n private async find(\n id: string,\n signal: AbortSignal | undefined,\n first: Place | null | undefined = this.places.get(id),\n ): Promise<{ place: Place; instance: ViewInstance }> {\n // Ids in `system:` are the views a host declares in code; the service\n // never issues or serves one.\n if (!isSystemInstanceId(id)) {\n const order: Place[] = ['personal', 'shared', 'system'];\n if (first)\n order.sort((a, b) => Number(b === first) - Number(a === first));\n for (const place of order) {\n try {\n const instance = await this.readAt(place, id, signal);\n this.places.set(id, place);\n return { place, instance };\n } catch (thrown) {\n if (thrown instanceof Failure && thrown.code === 'NOT_FOUND')\n continue;\n throw thrown;\n }\n }\n }\n throw new ViewStoreError('NOT_FOUND', `No such view: ${id}`);\n }\n\n /** The view as it is now at `place`; a `NOT_FOUND` failure when it is not there. */\n private async readAt(\n place: Place,\n id: string,\n signal: AbortSignal | undefined,\n ): Promise<ViewInstance> {\n if (place === 'system')\n return systemInstance(\n this.rememberSystem(await this.systemViews.one(id, signal)),\n );\n const record = await request(() =>\n this.snapshots.single(singleQuery({ filter: filter.id(id) }), {\n ...optionsAt(place),\n ...(signal === undefined ? {} : { signal }),\n }),\n );\n return toInstance(recordOf(record));\n }\n\n /** Keeps the version of a stored system view at its revision; a configured one as read-only. */\n private rememberSystem(view: SystemViewBody): SystemViewBody {\n this.systemVersions.set(\n revisionKey(view.id, view.revision),\n isStored(view) ? view.version! : null,\n );\n return view;\n }\n\n /**\n * The version a write of stored system view `id` at `revision` (its\n * content hash) expects: as seen at that revision, else as read now. A\n * configured system view is read-only (`FORBIDDEN`; a code one is never\n * found here); a revision other than the view's is `CONFLICT`, carrying\n * the view as it is.\n */\n private async systemVersion(\n id: string,\n revision: string,\n signal: AbortSignal | undefined,\n ): Promise<number> {\n const key = revisionKey(id, revision);\n if (!this.systemVersions.has(key)) {\n const instance = await this.readAt('system', id, signal);\n if (instance.revision !== revision && instance.stored)\n throw new ViewStoreError(\n 'CONFLICT',\n `System view ${id} has moved on from revision ${revision}`,\n { instance },\n );\n }\n const version = this.systemVersions.get(key);\n if (typeof version !== 'number')\n readOnly('Configured system views are read-only');\n return version;\n }\n\n /** The options of a command sent from `place`: its scope, request id and signal. */\n private commandOptions(\n place: Place,\n { requestId, signal }: WriteContext,\n more: Partial<CommandOptions> = {},\n ): CommandOptions {\n return {\n ...optionsAt(place),\n requestId,\n ...(signal === undefined ? {} : { signal }),\n ...more,\n };\n }\n}\n\n/** The port's list order: system views first, then shared, then personal. */\nconst AUDIENCE_RANK: Readonly<Record<ViewInstanceSummary['scope'], number>> = {\n system: 0,\n shared: 1,\n personal: 2,\n};\n\n/** The request options of `place`: its `Wow-Scope`, when it has one. */\nfunction optionsAt(place: Place): { scope?: ReturnType<typeof scopeAt> } {\n const scope = scopeAt(place);\n return scope === undefined ? {} : { scope };\n}\n\n/** The place of a view its owner says: a reserved owner, or a user's own. */\nfunction ownedAt(ownerId: string | null | undefined): Place {\n return ownerId === SHARED_OWNER_ID\n ? 'shared'\n : ownerId === SYSTEM_OWNER_ID\n ? 'system'\n : 'personal';\n}\n\n/** A snapshot record as the store reads it. */\nfunction recordOf(record: {\n aggregateId: string;\n version: number;\n state: unknown;\n}): ViewRecord {\n return {\n id: record.aggregateId,\n version: record.version,\n state: record.state as ViewState,\n };\n}\n\n/** A config as a command body holds it: free-form, the service stores it whole. */\nfunction bodyOf(config: ViewConfig): Record<string, unknown> {\n return config as unknown as Record<string, unknown>;\n}\n\n/** The aggregate version a revision of this store names. */\nfunction versionOf(revision: string): number {\n const version = Number(revision);\n if (!Number.isInteger(version) || version < 0)\n throw new ViewStoreError(\n 'CONFLICT',\n `Not a revision of this store: ${revision}`,\n );\n return version;\n}\n\nfunction revisionKey(id: string, revision: string): string {\n return `${id}\\u0000${revision}`;\n}\n\n/** Refuses a write to a system view the server or the code declares. */\nfunction readOnly(message: string): never {\n throw new ViewStoreError('FORBIDDEN', message);\n}\n\n/**\n * The port's refusal of a write. A claim the service refuses because shared\n * dashboards show the view carries those boards' titles (`boards`), read\n * from the problem's `boards` extension member; the engine says the refusal\n * around them.\n */\nfunction refusal(failure: Failure): ViewStoreError {\n if (\n failure.problemCode !== ViewStoreErrorCodes.REFERENCED_BY_SHARED_DASHBOARD\n )\n return failure.toStoreError();\n return new ViewStoreError('INVALID', failure.message, {\n ...failure.held(),\n boards: boardTitles(failure.problem?.problem.extensions),\n });\n}\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { CommandGateway, type CommandResult, type CommandResultStream, type CreateCommandOptions, type WowClientOptions } from '@ahoo-wang/wow-client';\nimport type { ClearDatasetWording, SetDatasetWording } from '../types.js';\n\n/** The command routes of `view-store.dataset_wording`. */\nexport const DatasetWordingCommandPaths = {\n CLEAR_DATASET_WORDING: '/view-store/dataset_wording/{id}/clear-dataset-wording',\n CLEAR_DATASET_WORDING_WITHOUT_ID: '/view-store/dataset_wording/clear-dataset-wording',\n SET_DATASET_WORDING: '/view-store/dataset_wording/{id}/set-dataset-wording',\n SET_DATASET_WORDING_WITHOUT_ID: '/view-store/dataset_wording/set-dataset-wording',\n} as const;\n\n/** Sends the commands of `view-store.dataset_wording`; a command that did not succeed rejects with a `WowProblemError` holding its result. */\nexport class DatasetWordingCommandClient {\n readonly gateway: CommandGateway;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.gateway = new CommandGateway(options);\n }\n\n /**\n * Clear the wording of a dataset\n * `ClearDatasetWording`: `POST /view-store/dataset_wording/{id}/clear-dataset-wording`, `POST /view-store/dataset_wording/clear-dataset-wording`.\n * Produces `DatasetWordingCleared`.\n */\n clearDatasetWording(body: ClearDatasetWording, options?: CreateCommandOptions): Promise<CommandResult> {\n return this.gateway.send(options?.id === undefined ? DatasetWordingCommandPaths.CLEAR_DATASET_WORDING_WITHOUT_ID : DatasetWordingCommandPaths.CLEAR_DATASET_WORDING, body, options);\n }\n\n /** `ClearDatasetWording`, answered as one result per hop of its wait (`text/event-stream`). */\n clearDatasetWordingStream(body: ClearDatasetWording, options?: CreateCommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(options?.id === undefined ? DatasetWordingCommandPaths.CLEAR_DATASET_WORDING_WITHOUT_ID : DatasetWordingCommandPaths.CLEAR_DATASET_WORDING, body, options);\n }\n\n /**\n * Set the wording of a dataset\n * `SetDatasetWording`: `POST /view-store/dataset_wording/{id}/set-dataset-wording`, `POST /view-store/dataset_wording/set-dataset-wording`.\n * Creates the aggregate, or acts on the one that exists.\n * Produces `DatasetWordingSet`.\n */\n setDatasetWording(body: SetDatasetWording, options?: CreateCommandOptions): Promise<CommandResult> {\n return this.gateway.send(options?.id === undefined ? DatasetWordingCommandPaths.SET_DATASET_WORDING_WITHOUT_ID : DatasetWordingCommandPaths.SET_DATASET_WORDING, body, options);\n }\n\n /** `SetDatasetWording`, answered as one result per hop of its wait (`text/event-stream`). */\n setDatasetWordingStream(body: SetDatasetWording, options?: CreateCommandOptions): Promise<CommandResultStream> {\n return this.gateway.stream(options?.id === undefined ? DatasetWordingCommandPaths.SET_DATASET_WORDING_WITHOUT_ID : DatasetWordingCommandPaths.SET_DATASET_WORDING, body, options);\n }\n}\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport type { EventView, SystemEvent } from '@ahoo-wang/wow-client';\nimport type { DatasetWordingCleared, DatasetWordingSet } from '../types.js';\n\n/**\n * The aggregate `view-store.dataset_wording`.\n * A tenant's wording over one dataset in one application\n */\nexport const DatasetWordingAggregate = {\n context: 'view-store',\n name: 'dataset_wording',\n path: '/view-store/dataset_wording',\n ownership: 'TENANT',\n snapshot: true,\n} as const;\n\n/** The `state.*` paths of `dataset_wording`'s snapshots a query filters, sorts and projects on. */\nexport type DatasetWordingStateField = 'state.appId' | 'state.dataset' | 'state.fields' | 'state.recordNoun' | 'state.title';\n\n/** The events of `dataset_wording`, named as the server sends them, `view-store.dataset_wording.<Event>` at its current revision (the `events` query upgrades older records), and the system events every aggregate has. */\nexport type DatasetWordingEvent = EventView<'view-store.dataset_wording.DatasetWordingCleared', DatasetWordingCleared> | EventView<'view-store.dataset_wording.DatasetWordingSet', DatasetWordingSet> | SystemEvent;\n","// Code generated by wow-generator. DO NOT EDIT.\n\nimport { EventQueryClient, SnapshotQueryClient, StateClient, type WowClientOptions } from '@ahoo-wang/wow-client';\nimport type { DatasetWordingState } from '../types.js';\nimport { DatasetWordingAggregate, type DatasetWordingEvent, type DatasetWordingStateField } from './aggregate.js';\n\n/** Queries the snapshots of `view-store.dataset_wording`: `POST /view-store/dataset_wording/snapshot/query`. */\nexport class DatasetWordingSnapshotQueryClient extends SnapshotQueryClient<DatasetWordingState, DatasetWordingStateField> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(DatasetWordingAggregate, options);\n }\n}\n\n\n/** Queries the event streams of `view-store.dataset_wording`, one record per commit: `POST /view-store/dataset_wording/events/query`. */\nexport class DatasetWordingEventQueryClient extends EventQueryClient<DatasetWordingEvent> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(DatasetWordingAggregate, options);\n }\n}\n\n\n/** Reads the states of `view-store.dataset_wording`, at a version or a time, and their traces: `GET /view-store/dataset_wording/{id}/state`. */\nexport class DatasetWordingStateClient extends StateClient<DatasetWordingState, DatasetWordingEvent> {\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(DatasetWordingAggregate, options);\n }\n}\n","/*\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 { Fetcher } from '@ahoo-wang/fetcher';\nimport { filter, listQuery } from '@ahoo-wang/wow-client/dsl';\nimport type { CommandOptions, CommandResult } from '@ahoo-wang/wow-client';\nimport type {\n DatasetOverrides,\n DatasetWordingStore,\n StoredDatasetWording,\n WriteContext,\n} from '@ahoo-wang/wow-view-engine';\nimport { revisionOf } from './views.js';\nimport { DatasetWordingCommandClient } from './generated/view-store/dataset_wording/commandClient.js';\nimport { DatasetWordingSnapshotQueryClient } from './generated/view-store/dataset_wording/queryClient.js';\nimport { guard, request } from './errors.js';\nimport { wordingOf } from './wire.js';\n\n/** How a V10 {@link WowDatasetWordings} reaches the view store service: as a V10 `WowViewStore` does. */\nexport interface WowDatasetWordingsOptions {\n /**\n * The fetcher every request goes through, as the V10\n * `WowViewStoreOptions.fetcher`: its interceptors carry the caller and\n * `CoSec-App-Id`. The wording is the tenant's (an aggregate of the tenant,\n * not of an owner), so no request names a scope.\n */\n fetcher: Fetcher;\n}\n\n/** The most datasets one application's wording is read for at once. */\nconst LIST_LIMIT = 1000;\n\n/**\n * The wording a tenant's administrators keep over its datasets in the V10\n * view store (view engine D86): one per dataset of the caller's tenant and\n * application, the id derived by the service from the two. Every reader of\n * the tenant reads it; the service decides who writes it (the role that\n * writes the owner `(shared)`, `view-store.shared-writer` as shipped).\n *\n * A host hands it to the datasets it registers as their store of wording\n * (`DatasetCatalog.wordings`, D91). The key is the dataset's definition id,\n * `{context}.{dataset}`. Every rejection is a `ViewStoreError`, read as a\n * V10 `WowViewStore`'s are.\n */\nexport class WowDatasetWordings implements DatasetWordingStore {\n private readonly commands: DatasetWordingCommandClient;\n private readonly snapshots: DatasetWordingSnapshotQueryClient;\n\n constructor(options: WowDatasetWordingsOptions) {\n const client = { fetcher: options.fetcher };\n this.commands = new DatasetWordingCommandClient(client);\n this.snapshots = new DatasetWordingSnapshotQueryClient(client);\n }\n\n /**\n * Every dataset's wording of the caller's tenant and application, by\n * dataset. A cleared one is listed too, saying nothing: its revision is\n * what the next write expects.\n */\n list(\n signal?: AbortSignal,\n ): Promise<ReadonlyMap<string, StoredDatasetWording>> {\n return guard(async () => {\n const snapshots = await request(() =>\n this.snapshots.list(\n listQuery({ filter: filter.matchAll(), limit: LIST_LIMIT }),\n signal === undefined ? {} : { signal },\n ),\n );\n return new Map(\n snapshots.map(({ version, state }) => [\n state.dataset,\n { wording: wordingOf(state), revision: revisionOf(version) },\n ]),\n );\n });\n }\n\n /**\n * Writes a dataset's wording at the expected `revision` (`'0'` for one never\n * written), whole: what it leaves out is no longer said. Answers the new\n * revision.\n */\n set(\n dataset: string,\n wording: DatasetOverrides,\n revision: string,\n context: WriteContext,\n ): Promise<string> {\n return guard(async () => {\n const result = await request(() =>\n this.commands.setDatasetWording(\n {\n dataset,\n ...(wording.title === undefined ? {} : { title: wording.title }),\n ...(wording.recordNoun === undefined\n ? {}\n : { recordNoun: wording.recordNoun }),\n ...(wording.fields === undefined\n ? {}\n : {\n fields: wording.fields as unknown as Record<string, unknown>,\n }),\n },\n optionsOf(revision, context),\n ),\n );\n return versionAfter(result, revision);\n });\n }\n\n /**\n * Clears a dataset's wording at the expected `revision`: its derived words\n * stand again. Answers the new revision.\n */\n clear(\n dataset: string,\n revision: string,\n context: WriteContext,\n ): Promise<string> {\n return guard(async () => {\n const result = await request(() =>\n this.commands.clearDatasetWording(\n { dataset },\n optionsOf(revision, context),\n ),\n );\n return versionAfter(result, revision);\n });\n }\n}\n\nfunction optionsOf(\n revision: string,\n { requestId, signal }: WriteContext,\n): CommandOptions {\n return {\n requestId,\n expectedVersion: Number(revision),\n ...(signal === undefined ? {} : { signal }),\n };\n}\n\n/** The revision a write left: its version, or the one it expected moved on. */\nfunction versionAfter(result: CommandResult, revision: string): string {\n return revisionOf(result.version ?? Number(revision) + 1);\n}\n","/*\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 {\n DatasetClient,\n PagedQuery,\n QueryModelClient,\n RequestOptions,\n} from '@ahoo-wang/wow-client';\nimport type {\n AggregationQuery,\n CursorQuery,\n FilterPagedQuery,\n} from '@ahoo-wang/wow-client/dsl';\nimport type {\n DatasetCatalog,\n DatasetDirectoryEntry,\n RecordData,\n ViewSource,\n} from '@ahoo-wang/wow-view-engine';\n\n/**\n * The view engine's `ViewSource` over one query route of a Wow **V10**\n * service: a generated `…SnapshotQueryClient`, a `QueryModelClient`, or a\n * dataset's (`DatasetClient.dataset(…)`). The engine's port takes an\n * `AbortController` rather than request options, reads the total as a plain\n * count, and wants the descriptor's version with every read. This is the\n * whole adapter.\n *\n * A page counts its total as the service does by default, `BOUNDED`\n * (D150): exact up to the budget's limit, and the limit itself past it. A\n * V10 service refuses an exact total over HTTP, so the engine, which reads\n * the total as the count of matches, shows a count past the limit as the\n * limit (an engine follow-up: say \"at least\"). The engine's `attributes`\n * have no counterpart on a V10 request and are not sent.\n *\n * ```ts\n * const engine = new ViewEngine({\n * store: new WowViewStore({ fetcher }),\n * resources: [\n * { definition: orders, source: viewSourceOf(new OrderSnapshotQueryClient({ fetcher })) },\n * ],\n * });\n * ```\n */\nexport function viewSourceOf<F extends string>(\n client: QueryModelClient<object, F>,\n): ViewSource {\n return {\n async paged(query, _attributes, abort) {\n const page = await client.paged(\n query as FilterPagedQuery<F> as PagedQuery<F>,\n optionsOf(abort),\n );\n return {\n total: page.total ?? page.list.length,\n list: [...page.list] as RecordData[],\n };\n },\n async cursor(query, _attributes, abort) {\n const page = await client.cursor(\n query as CursorQuery<F>,\n optionsOf(abort),\n );\n return { list: page.list as RecordData[], nextCursor: page.nextCursor };\n },\n aggregate(query, _attributes, abort) {\n return client.aggregate<RecordData>(\n query as AggregationQuery<F, string>,\n optionsOf(abort),\n );\n },\n async describe(previous, _attributes, abort) {\n const read = await client.describe(previous, optionsOf(abort));\n if (read.notModified) return read;\n return {\n notModified: false,\n descriptor: read.descriptor,\n version: read.version ?? read.descriptor.version,\n };\n },\n };\n}\n\n/**\n * What a `DatasetCatalog` reads of a Wow **V10** service's datasets: the\n * directory (`GET /wow/dataset`) and each dataset's query route as a\n * `ViewSource` ({@link viewSourceOf}). A host spreads it into the catalog it\n * hands `DatasetResources`, beside its own `overrides` and `wordings`:\n *\n * ```ts\n * const datasets = new DatasetClient({ fetcher });\n * new DatasetResources(engine, {\n * ...datasetCatalogOf(datasets),\n * wordings: new WowDatasetWordings({ fetcher }),\n * });\n * ```\n *\n * A V10 directory entry names no version, and lists only datasets it serves:\n * each is given `LISTED`, so `DatasetResources` (which reads `null` as a\n * dataset not servable) registers it, and a dataset is told changed by its\n * descriptor's version, which the engine checks on its own schedule.\n */\nexport function datasetCatalogOf(\n client: DatasetClient,\n): Pick<DatasetCatalog, 'list' | 'source'> {\n return {\n async list(): Promise<DatasetDirectoryEntry[]> {\n return (await client.list()).map(entry => ({\n contextName: entry.context,\n name: entry.dataset,\n title: entry.title ?? null,\n version: LISTED,\n }));\n },\n source: entry =>\n viewSourceOf(client.dataset(entry.contextName, entry.name)),\n };\n}\n\n/** The version every dataset a V10 directory lists is given (`datasetCatalogOf`). */\nconst LISTED = 'listed';\n\n/** A V10 request's options from the engine's controller. */\nfunction optionsOf(abort: AbortController | undefined): RequestOptions {\n return abort === undefined ? {} : { signal: abort.signal };\n}\n"],"mappings":";;;;;;;IAuBaI,IAAkB,YAMlBC,IAAkB,YAUlBC,IAAmB,cCzB1BC,IAAoB,KAGb,aAAb,MAA2B;CAGzB,YAAY,IAAyBA,GAAmB;EAF7B,AAEE,KAAA,QAAAC,GAFF,KAAA,0BAAA,IAAI,IAAe;CAEW;CAEzD,IA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EAAM,OAAO;AAC3D"}
|
package/dist/paths.d.ts
CHANGED
|
@@ -32,35 +32,3 @@ export declare const SYSTEM_TENANT_ID = "(platform)";
|
|
|
32
32
|
* {@link SYSTEM_TENANT_ID} and {@link SYSTEM_OWNER_ID}.
|
|
33
33
|
*/
|
|
34
34
|
export type Place = 'personal' | 'shared' | 'system';
|
|
35
|
-
/** Every route starts here; the tenant and owner are path variables. */
|
|
36
|
-
export declare const SCOPE = "/view-store/tenant/{tenantId}/owner/{ownerId}";
|
|
37
|
-
/** The view store's routes, relative to the fetcher's base URL. */
|
|
38
|
-
export declare const PATHS: {
|
|
39
|
-
/** `POST`: create (the server generates the id). */
|
|
40
|
-
readonly views: "/view-store/tenant/{tenantId}/owner/{ownerId}/view";
|
|
41
|
-
/** `DELETE`: Wow's delete of the aggregate. */
|
|
42
|
-
readonly view: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/{id}";
|
|
43
|
-
readonly save: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/{id}/save";
|
|
44
|
-
readonly rename: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/{id}/rename";
|
|
45
|
-
/** Sent to the view's personal path; moves it to `(shared)`. */
|
|
46
|
-
readonly share: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/{id}/share";
|
|
47
|
-
/** Sent to the caller's own path; moves a shared view to the caller. */
|
|
48
|
-
readonly claim: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/{id}/claim";
|
|
49
|
-
readonly single: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/snapshot/single";
|
|
50
|
-
readonly list: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/snapshot/list";
|
|
51
|
-
/** The view as the write with this request id left it; `204` for a delete. */
|
|
52
|
-
readonly replay: "/view-store/tenant/{tenantId}/owner/{ownerId}/view/requests/{requestId}";
|
|
53
|
-
/**
|
|
54
|
-
* Served under `(shared)` only: the configured system views of the
|
|
55
|
-
* caller's tenant and the stored ones, global.
|
|
56
|
-
*/
|
|
57
|
-
readonly systemViews: "/view-store/tenant/{tenantId}/owner/{ownerId}/system-views";
|
|
58
|
-
readonly systemView: "/view-store/tenant/{tenantId}/owner/{ownerId}/system-views/{id}";
|
|
59
|
-
readonly preferences: "/view-store/tenant/{tenantId}/owner/{ownerId}/definitions/{definitionId}/preferences";
|
|
60
|
-
};
|
|
61
|
-
/**
|
|
62
|
-
* The path variables of a request at `place`. The tenant is the
|
|
63
|
-
* interceptors' but on the system path; the owner is theirs for a personal
|
|
64
|
-
* path.
|
|
65
|
-
*/
|
|
66
|
-
export declare function pathAt(place: Place, variables?: Record<string, string>): Record<string, string>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** A bounded memory by key: the oldest entry goes first. */
|
|
2
|
+
export declare class Remembered<T> {
|
|
3
|
+
private readonly limit;
|
|
4
|
+
private readonly entries;
|
|
5
|
+
constructor(limit?: number);
|
|
6
|
+
get(key: string): T | undefined;
|
|
7
|
+
has(key: string): boolean;
|
|
8
|
+
set(key: string, value: T): void;
|
|
9
|
+
}
|
package/dist/source.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { DatasetClient, QueryModelClient } from '@ahoo-wang/wow-client';
|
|
2
|
+
import { DatasetCatalog, ViewSource } from '@ahoo-wang/wow-view-engine';
|
|
3
|
+
/**
|
|
4
|
+
* The view engine's `ViewSource` over one query route of a Wow **V10**
|
|
5
|
+
* service: a generated `…SnapshotQueryClient`, a `QueryModelClient`, or a
|
|
6
|
+
* dataset's (`DatasetClient.dataset(…)`). The engine's port takes an
|
|
7
|
+
* `AbortController` rather than request options, reads the total as a plain
|
|
8
|
+
* count, and wants the descriptor's version with every read. This is the
|
|
9
|
+
* whole adapter.
|
|
10
|
+
*
|
|
11
|
+
* A page counts its total as the service does by default, `BOUNDED`
|
|
12
|
+
* (D150): exact up to the budget's limit, and the limit itself past it. A
|
|
13
|
+
* V10 service refuses an exact total over HTTP, so the engine, which reads
|
|
14
|
+
* the total as the count of matches, shows a count past the limit as the
|
|
15
|
+
* limit (an engine follow-up: say "at least"). The engine's `attributes`
|
|
16
|
+
* have no counterpart on a V10 request and are not sent.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* const engine = new ViewEngine({
|
|
20
|
+
* store: new WowViewStore({ fetcher }),
|
|
21
|
+
* resources: [
|
|
22
|
+
* { definition: orders, source: viewSourceOf(new OrderSnapshotQueryClient({ fetcher })) },
|
|
23
|
+
* ],
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function viewSourceOf<F extends string>(client: QueryModelClient<object, F>): ViewSource;
|
|
28
|
+
/**
|
|
29
|
+
* What a `DatasetCatalog` reads of a Wow **V10** service's datasets: the
|
|
30
|
+
* directory (`GET /wow/dataset`) and each dataset's query route as a
|
|
31
|
+
* `ViewSource` ({@link viewSourceOf}). A host spreads it into the catalog it
|
|
32
|
+
* hands `DatasetResources`, beside its own `overrides` and `wordings`:
|
|
33
|
+
*
|
|
34
|
+
* ```ts
|
|
35
|
+
* const datasets = new DatasetClient({ fetcher });
|
|
36
|
+
* new DatasetResources(engine, {
|
|
37
|
+
* ...datasetCatalogOf(datasets),
|
|
38
|
+
* wordings: new WowDatasetWordings({ fetcher }),
|
|
39
|
+
* });
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* A V10 directory entry names no version, and lists only datasets it serves:
|
|
43
|
+
* each is given `LISTED`, so `DatasetResources` (which reads `null` as a
|
|
44
|
+
* dataset not servable) registers it, and a dataset is told changed by its
|
|
45
|
+
* descriptor's version, which the engine checks on its own schedule.
|
|
46
|
+
*/
|
|
47
|
+
export declare function datasetCatalogOf(client: DatasetClient): Pick<DatasetCatalog, 'list' | 'source'>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
2
|
+
import { SystemViewBody } from './views.js';
|
|
3
|
+
/**
|
|
4
|
+
* The system views route, `GET /view-store/system-views[/{id}]`: the
|
|
5
|
+
* service's own route, ordered before Wow's and outside the Manifest, so no
|
|
6
|
+
* client is generated for it. It answers the configured system views of the
|
|
7
|
+
* caller's tenant and application and the stored ones, in the 9.x
|
|
8
|
+
* `SystemView` shape; the tenant is the principal's, the application the
|
|
9
|
+
* request's `CoSec-App-Id`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const SYSTEM_VIEWS_PATH = "/view-store/system-views";
|
|
12
|
+
/** The system views route, through the store's fetcher. */
|
|
13
|
+
export declare class SystemViewsClient {
|
|
14
|
+
private readonly fetcher;
|
|
15
|
+
constructor(fetcher: Fetcher);
|
|
16
|
+
/** The definition's system views: the configured ones first, in their order. */
|
|
17
|
+
list(definitionId: string, signal?: AbortSignal): Promise<SystemViewBody[]>;
|
|
18
|
+
/** One system view; `404 view-store.not-found` for none. */
|
|
19
|
+
one(id: string, signal?: AbortSignal): Promise<SystemViewBody>;
|
|
20
|
+
private get;
|
|
21
|
+
}
|