@ahoo-wang/wow-view-store 9.7.0 → 9.9.0
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 +39 -138
- package/README.zh-CN.md +33 -101
- package/dist/datasetWordings.d.ts +47 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +67 -2
- package/dist/index.es.js.map +1 -1
- package/dist/paths.d.ts +2 -0
- package/dist/wowViewStore.d.ts +13 -0
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ of [`@ahoo-wang/wow-view-engine`](../wow-view-engine/README.md), kept by the
|
|
|
8
8
|
standalone `wow-view-store-server` or by any Wow service that embeds
|
|
9
9
|
`wow-view-store-starter`.
|
|
10
10
|
|
|
11
|
-
Released with Wow
|
|
11
|
+
Released with Wow, from the same tag and with the same version, together
|
|
12
12
|
with the view engine and the view store's server modules.
|
|
13
13
|
|
|
14
14
|
> **Compatibility.** From 9.2.0 on, a patch release never breaks the public
|
|
@@ -72,149 +72,50 @@ one all need it. Left out, everything is allowed — but the engine's
|
|
|
72
72
|
off unless the host's answer says `true`: give it by the role the gateway
|
|
73
73
|
admits to `tenant/(platform)/owner/(system)` (`view-store/README.md`, 「System views」).
|
|
74
74
|
|
|
75
|
-
###
|
|
75
|
+
### Dataset wording
|
|
76
76
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
`
|
|
77
|
+
`WowDatasetWordings` keeps a tenant's wording over its datasets (the view
|
|
78
|
+
engine's dataset overrides: title, record noun, field labels, order and
|
|
79
|
+
narrowing) under `owner/(shared)`, one per dataset and application, keyed by
|
|
80
|
+
the dataset's definition id. Hand it to the datasets as their store of
|
|
81
|
+
wording: `DatasetResources` reads it before each refresh, registers each
|
|
82
|
+
dataset in its stored words, and gives the view manager its wording tab
|
|
83
|
+
where the host grants `editDatasetWording`:
|
|
82
84
|
|
|
83
|
-
|
|
84
|
-
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
85
|
+
```ts
|
|
86
|
+
import type { Fetcher } from '@ahoo-wang/fetcher';
|
|
87
|
+
import {
|
|
88
|
+
DatasetDirectoryClient,
|
|
89
|
+
DatasetQueryClient,
|
|
90
|
+
} from '@ahoo-wang/wow-client';
|
|
91
|
+
import { DatasetResources, type ViewEngine } from '@ahoo-wang/wow-view-engine';
|
|
92
|
+
import { WowDatasetWordings } from '@ahoo-wang/wow-view-store';
|
|
93
|
+
|
|
94
|
+
declare const engine: ViewEngine;
|
|
85
95
|
declare const fetcher: Fetcher;
|
|
86
|
-
-->
|
|
87
96
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
intercept(exchange: FetchExchange): void {
|
|
97
|
-
const path = exchange.ensureRequestUrlParams().path;
|
|
98
|
-
path.tenantId ??= '(0)';
|
|
99
|
-
path.ownerId ??= SHARED_OWNER_ID;
|
|
100
|
-
exchange.ensureRequestHeaders()['CoSec-App-Id'] = 'console';
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
fetcher.interceptors.request.use(new ConsoleDefaults());
|
|
97
|
+
const directory = new DatasetDirectoryClient();
|
|
98
|
+
const datasets = new DatasetResources(engine, {
|
|
99
|
+
list: () => directory.list(),
|
|
100
|
+
source: entry =>
|
|
101
|
+
new DatasetQueryClient({ context: entry.contextName, dataset: entry.name }),
|
|
102
|
+
wordings: new WowDatasetWordings({ fetcher }),
|
|
103
|
+
});
|
|
104
|
+
await datasets.refresh();
|
|
105
105
|
```
|
|
106
106
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
owner
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
|
115
|
-
|
|
|
116
|
-
|
|
|
117
|
-
|
|
|
118
|
-
|
|
|
119
|
-
| `changeAudience('shared')` | `PUT …/view/{id}/share` on the view's path |
|
|
120
|
-
| `changeAudience('personal')` | `PUT …/view/{id}/claim` on the caller's own path |
|
|
121
|
-
| `getPreferences`, `setPreferences` | `GET`, `PUT …/definitions/{definitionId}/preferences` on the caller's path |
|
|
122
|
-
|
|
123
|
-
A list answers in the port's order — the system views, then the shared views,
|
|
124
|
-
then the caller's, each audience oldest first (the server sorts it by
|
|
125
|
-
`firstEventTime`) — and reads at most 1,000 views of each audience, the server's
|
|
126
|
-
query budget: the oldest 1,000. A view past the cut is still read by its id, and
|
|
127
|
-
the workbench asks for one an address names before it sets it aside.
|
|
128
|
-
|
|
129
|
-
**Writes** send the port's `requestId` as `Command-Request-Id`, the `revision`
|
|
130
|
-
as `Command-Aggregate-Version` (`'0'` for preferences never written), and wait
|
|
131
|
-
for the snapshot. The answer is the view read back at the version the write
|
|
132
|
-
left. `share` and `delete` send `{}`, `claim` no body.
|
|
133
|
-
|
|
134
|
-
**A retry answers the first outcome.** A write the server refuses as a stale
|
|
135
|
-
version or a repeated request id is looked up by its request id first
|
|
136
|
-
(`GET …/view/requests/{requestId}`, on the path it was sent to and then the
|
|
137
|
-
other one): if the first attempt landed, its outcome is the answer. Only then is
|
|
138
|
-
a stale version `CONFLICT`, carrying the view as it is now — or `NOT_FOUND`,
|
|
139
|
-
when the view is gone. A lookup the server fails is no answer: on the path the
|
|
140
|
-
write went to, the outcome is unknown (`UNAVAILABLE`, and a retry is safe); on the
|
|
141
|
-
other path — `(shared)` refuses a caller without the shared role — the write is
|
|
142
|
-
taken as not replayed, and the refusal stands. A write that landed and was moved
|
|
143
|
-
on by another writer before the read back answers the view as the replay route
|
|
144
|
-
gives it, or, if that route cannot be asked, as it was read. Preferences have no such route: the store answers a retry
|
|
145
|
-
with what its own first attempt answered, and a retry whose first answer was
|
|
146
|
-
lost with what is stored, when that is what it wrote.
|
|
147
|
-
|
|
148
|
-
**Creating is not idempotent on the server**, which generates the id. The store
|
|
149
|
-
remembers the request ids of its own creates (the last 256), and a retry of one
|
|
150
|
-
first asks the replay route on the path of its `scope`: if the first attempt
|
|
151
|
-
landed, that view is the answer, and nothing is posted again. A retry from
|
|
152
|
-
another store instance — another tab, a reload — makes a second view.
|
|
153
|
-
|
|
154
|
-
**A view that moved.** When another tab shared a view this store remembers as
|
|
155
|
-
personal (or the other way round), the write is refused on the old path; the
|
|
156
|
-
store looks the view up again and sends the write once more to where it is.
|
|
157
|
-
|
|
158
|
-
**System views.** The server's system views (`GET (shared)/system-views`) are
|
|
159
|
-
configured ones, read-only, and stored ones (`source: 'stored'`), which
|
|
160
|
-
`WowViewStore` lists and reads with `stored: true` on the summary and the
|
|
161
|
-
instance. A stored one is written on `tenant/(platform)/owner/(system)`
|
|
162
|
-
(`SYSTEM_TENANT_ID`, `SYSTEM_OWNER_ID`) whatever the caller's tenant: they are
|
|
163
|
-
global. `create({ scope: 'system', … })` publishes one (a copy: the source
|
|
164
|
-
view stays), `save`, `rename` and `delete` edit and unpublish it;
|
|
165
|
-
`changeAudience` and any write to a configured or code system view are
|
|
166
|
-
`FORBIDDEN` before anything is sent.
|
|
167
|
-
|
|
168
|
-
A system view's `revision` is a hash of its content, as the engine needs for
|
|
169
|
-
its dirty baseline, while a write expects the aggregate version: the store
|
|
170
|
-
remembers the `version` each read of a stored view gave beside its revision,
|
|
171
|
-
sends that version, and when the engine holds a revision it has no version
|
|
172
|
-
for, reads the view again first — a revision other than the view's is
|
|
173
|
-
`CONFLICT` with the view as it is, and nothing is sent. The answer of a write
|
|
174
|
-
is read back from the system-views route at the version it left. A retry the
|
|
175
|
-
server refuses as a repeated request is found by the replay route on the
|
|
176
|
-
system path, but that route answers a snapshot, whose content hash only the
|
|
177
|
-
server computes: the store answers it with the system view **as it is now**,
|
|
178
|
-
which is the retried write's outcome unless another admin wrote in between.
|
|
179
|
-
A retry whose first attempt moved the view on (so the revision it holds is no
|
|
180
|
-
longer the view's) asks the replay route before it is refused as `CONFLICT`,
|
|
181
|
-
and a retried create of a system view answers the view from the system
|
|
182
|
-
views, flagged and at its hash.
|
|
183
|
-
|
|
184
|
-
## Errors
|
|
185
|
-
|
|
186
|
-
Every rejection is the engine's `ViewStoreError`, read by Wow's error code — the
|
|
187
|
-
HTTP status only when an answer carries no code the store knows:
|
|
188
|
-
|
|
189
|
-
| Server | Port |
|
|
190
|
-
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
|
|
191
|
-
| `CommandExpectVersionConflict`, `EventVersionConflict`, `SourcingVersionConflict`; without a known code, 409 and 412 | `CONFLICT` |
|
|
192
|
-
| `NotFound` (also a view of another application), `IllegalAccessDeletedAggregate`; without a known code, 404 and 410 | `NOT_FOUND` |
|
|
193
|
-
| `IllegalAccessOwnerAggregate`, `IllegalAccessSpaceAggregate`, `IllegalAccessQueryScope`, `SystemViewReadOnly`, `ViewEventStreamClosed`; without a known code, 401 and 403 | `FORBIDDEN` |
|
|
194
|
-
| `ViewInvalid`, `ViewAppRequired`, `ViewScopeRequired`, `BadRequest`, `CommandValidation`, `IllegalArgument`, `DuplicateAggregateId`, `QuerySchemaValidation`; without a known code, 400 and 422; a path variable the fetcher's interceptors never filled (nothing is sent) | `INVALID` |
|
|
195
|
-
| `IllegalState`, `RequestTimeout`, `TooManyRequests`, `InternalServerError`, `QuerySchemaUnavailable`, `QuerySchemaConflict`; without a known code, any other status; no answer at all | `UNAVAILABLE` |
|
|
196
|
-
| `404` from a server with no view store at all (one released before it): a list, or a read whose every place is `404` while the server's system views are too | `UNSUPPORTED` |
|
|
197
|
-
|
|
198
|
-
Every `ViewStoreError` keeps what it was read from: the request's failure as
|
|
199
|
-
`cause`, the server's `errorCode` as `detail.code` (so a host tells
|
|
200
|
-
`ViewAppRequired` from `ViewInvalid`, both `INVALID`), and on an `UNAVAILABLE`
|
|
201
|
-
the server answered — a 5xx, a timeout it reported, a page that is not JSON —
|
|
202
|
-
`reachable: true`, which the engine says as 「服务端暂时无法处理」 rather than
|
|
203
|
-
「无法连接服务端」.
|
|
204
|
-
|
|
205
|
-
A repeated request id (`DuplicateRequestId`) is not an error of its own: the
|
|
206
|
-
store looks the first attempt up (above). A path variable left unfilled is the
|
|
207
|
-
host's set-up — its interceptors do not fill `{tenantId}`, or `{ownerId}` on a
|
|
208
|
-
personal path — so it is `INVALID`, as the server's own `ViewScopeRequired` is:
|
|
209
|
-
the request is wrong as built, and a retry would send it the same.
|
|
210
|
-
|
|
211
|
-
A claim the server refuses because shared dashboards show the view carries those
|
|
212
|
-
boards' **titles** in the error's `boards`, as stored, and the view engine says
|
|
213
|
-
the refusal in its own words around them: a title written as a key stays a key,
|
|
214
|
-
said where the refusal is shown. The `message` keeps the server's words, for
|
|
215
|
-
logs.
|
|
216
|
-
|
|
217
|
-
`WowViewStoreErrorCodes` names the view store's own codes.
|
|
107
|
+
`set(dataset, wording, revision, { requestId })` writes one whole at the
|
|
108
|
+
expected revision (`'0'` for one never written) and `clear` removes it; the
|
|
109
|
+
gateway decides who may, by the role it admits to
|
|
110
|
+
`…/owner/(shared)/datasets/{dataset}/wording`.
|
|
111
|
+
|
|
112
|
+
## Documentation
|
|
113
|
+
|
|
114
|
+
| To | Read |
|
|
115
|
+
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
116
|
+
| Choose where views live, wire `WowViewStore`, give permissions, serve a host nobody signs in to | [Where views live](https://wow.ahoo.me/guide/typescript/view-engine-storage#wowviewstore-views-on-a-wow-service) |
|
|
117
|
+
| The exports, the contract, every request the port sends and how server errors map to the port | [wow-view-store reference](https://wow.ahoo.me/reference/typescript/wow-view-store/) |
|
|
118
|
+
| Run the view store server, its configuration and the gateway rules | [View store](https://wow.ahoo.me/guide/extensions/view-store) |
|
|
218
119
|
|
|
219
120
|
## Testing
|
|
220
121
|
|
package/README.zh-CN.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
保存的视图与偏好,由[视图存储](../../view-store/README.md)保管——两个 Wow 聚合,由独立的
|
|
7
7
|
`wow-view-store-server` 提供,或由任何引入了 `wow-view-store-starter` 的 Wow 服务提供。
|
|
8
8
|
|
|
9
|
-
随 Wow
|
|
9
|
+
随 Wow 发布,与 Wow 同一个 tag、同一个版本号,与视图引擎和视图存储的服务端模块一起发布。
|
|
10
10
|
|
|
11
11
|
> **兼容性。** 从 9.2.0 起,补丁版本不破坏公开面(入口的导出与错误码);次版本可以破坏,它的发布说明
|
|
12
12
|
> 逐条列出每个破坏与迁移步骤。Wow 包请停在同一个次版本上,见[版本范围](https://wow.ahoo.me/zh/guide/typescript/compatibility#版本范围)。
|
|
@@ -58,112 +58,44 @@ const engine = new ViewEngine({
|
|
|
58
58
|
但引擎的 `editSystem`(发布、编辑、取消发布存储的系统视图)只在宿主明确答 `true` 时打开:按网关放行
|
|
59
59
|
`tenant/(platform)/owner/(system)` 的角色给(`view-store/README.md`「System views」)。
|
|
60
60
|
|
|
61
|
-
###
|
|
61
|
+
### 数据集措辞
|
|
62
62
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
`
|
|
63
|
+
`WowDatasetWordings` 在 `owner/(shared)` 下存租户给数据集写的措辞(视图引擎的数据集覆盖:标题、名词、字段的
|
|
64
|
+
口径、次序与收窄),每个应用、每个数据集一份,按数据集的定义 id 存。把它交给数据集作措辞存储:`DatasetResources`
|
|
65
|
+
每次刷新前读它,按存着的措辞登记每个数据集,并在宿主给了 `editDatasetWording` 时给视图管理器一个「措辞」页签:
|
|
66
66
|
|
|
67
|
-
|
|
68
|
-
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
67
|
+
```ts
|
|
68
|
+
import type { Fetcher } from '@ahoo-wang/fetcher';
|
|
69
|
+
import {
|
|
70
|
+
DatasetDirectoryClient,
|
|
71
|
+
DatasetQueryClient,
|
|
72
|
+
} from '@ahoo-wang/wow-client';
|
|
73
|
+
import { DatasetResources, type ViewEngine } from '@ahoo-wang/wow-view-engine';
|
|
74
|
+
import { WowDatasetWordings } from '@ahoo-wang/wow-view-store';
|
|
75
|
+
|
|
76
|
+
declare const engine: ViewEngine;
|
|
69
77
|
declare const fetcher: Fetcher;
|
|
70
|
-
-->
|
|
71
78
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
intercept(exchange: FetchExchange): void {
|
|
81
|
-
const path = exchange.ensureRequestUrlParams().path;
|
|
82
|
-
path.tenantId ??= '(0)';
|
|
83
|
-
path.ownerId ??= SHARED_OWNER_ID;
|
|
84
|
-
exchange.ensureRequestHeaders()['CoSec-App-Id'] = 'console';
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
fetcher.interceptors.request.use(new ConsoleDefaults());
|
|
79
|
+
const directory = new DatasetDirectoryClient();
|
|
80
|
+
const datasets = new DatasetResources(engine, {
|
|
81
|
+
list: () => directory.list(),
|
|
82
|
+
source: entry =>
|
|
83
|
+
new DatasetQueryClient({ context: entry.contextName, dataset: entry.name }),
|
|
84
|
+
wordings: new WowDatasetWordings({ fetcher }),
|
|
85
|
+
});
|
|
86
|
+
await datasets.refresh();
|
|
89
87
|
```
|
|
90
88
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
|
97
|
-
|
|
|
98
|
-
| `
|
|
99
|
-
|
|
|
100
|
-
|
|
|
101
|
-
| `save`、`rename`、`delete` | 在视图所在路径上 `PUT …/view/{id}/save`、`/rename`,`DELETE …/view/{id}` |
|
|
102
|
-
| `changeAudience('shared')` | 在视图所在路径上 `PUT …/view/{id}/share` |
|
|
103
|
-
| `changeAudience('personal')` | 在调用者自己的路径上 `PUT …/view/{id}/claim` |
|
|
104
|
-
| `getPreferences`、`setPreferences` | 调用者路径上的 `GET`、`PUT …/definitions/{definitionId}/preferences` |
|
|
105
|
-
|
|
106
|
-
列表按端口规定的顺序作答——系统视图、共享视图、调用者的个人视图,每种受众按创建先后(服务端按 `firstEventTime`
|
|
107
|
-
排序)——每种受众最多读 1000 个,即服务端的查询上限:最早的 1000 个。截断之外的视图仍可按 id 读到,地址里点名的
|
|
108
|
-
视图工作台会先按 id 问一次,再决定是不是别的定义的。
|
|
109
|
-
|
|
110
|
-
**写入**把端口的 `requestId` 作为 `Command-Request-Id`、`revision` 作为 `Command-Aggregate-Version`
|
|
111
|
-
(从没写过的偏好是 `'0'`)发送,并等到快照落地。作答的是按这次写入留下的版本读回的视图。`share` 与 `delete`
|
|
112
|
-
发送 `{}`,`claim` 不带请求体。
|
|
113
|
-
|
|
114
|
-
**重试答第一次的结果。** 服务端以过期版本或重复的请求 id 拒绝一次写入时,先按请求 id 查一次
|
|
115
|
-
(`GET …/view/requests/{requestId}`,先在这次发往的路径上,再在另一条上):第一次已经落地,就以它的结果作答。
|
|
116
|
-
之后过期版本才是 `CONFLICT`,带上视图现在的样子——视图已经不在了则是 `NOT_FOUND`。服务端答不上来的查询不算回答:
|
|
117
|
-
在这次发往的路径上,结局未知(`UNAVAILABLE`,重试安全);在另一条路径上——没有共享角色的调用者在 `(shared)`
|
|
118
|
-
会被拒——就当没有重放,原来的拒绝照旧。已经落地、读回前又被别人推过的写入,以重放路由给的那一版作答;
|
|
119
|
-
那条路由问不了时,以读回的作答。偏好没有这样的路由:
|
|
120
|
-
store 以自己第一次得到的结果回答重试;第一次的回答丢了的重试,在存着的正是它写的内容时,以存着的作答。
|
|
121
|
-
|
|
122
|
-
**创建在服务端不是幂等的**,id 由服务端生成。store 记着自己发出的创建的请求 id(最近 256 个),
|
|
123
|
-
重试其中一个时先在其 `scope` 的路径上问重放路由:第一次已经落地,就以那个视图作答,不再发一次。
|
|
124
|
-
从另一个 store 实例发出的重试——另一个标签页、刷新之后——会再建一个视图。
|
|
125
|
-
|
|
126
|
-
**挪了地方的视图。** 另一个标签页把这个 store 记作个人的视图设为了共享(或反过来),写入在旧路径上被拒;
|
|
127
|
-
store 重新找到视图,把写入再发一次到它现在所在的地方。
|
|
128
|
-
|
|
129
|
-
**系统视图。** 服务端的系统视图(`GET (shared)/system-views`)有配置的,只读;也有存储的(`source: 'stored'`),
|
|
130
|
-
`WowViewStore` 列出、读取它们时在摘要与实例上带 `stored: true`。存储的系统视图是全局的,不管调用者在哪个租户,
|
|
131
|
-
都写在 `tenant/(platform)/owner/(system)`(`SYSTEM_TENANT_ID`、`SYSTEM_OWNER_ID`)上。`create({ scope: 'system', … })`
|
|
132
|
-
发布一个(是复制,源视图不变),`save`、`rename`、`delete` 编辑与取消发布;`changeAudience`,以及对配置的或
|
|
133
|
-
代码声明的系统视图的任何写入,都在发出请求之前就是 `FORBIDDEN`。
|
|
134
|
-
|
|
135
|
-
系统视图的 `revision` 是内容的散列,引擎的「已改动」基线靠它;而写入要的是聚合版本:store 记着每次读到的存储视图
|
|
136
|
-
在那个 revision 上的 `version`,写入时发这个版本;引擎拿着一个 store 没有版本的 revision 时,先重读一次——
|
|
137
|
-
与视图当前不符的 revision 是 `CONFLICT`,带上视图现在的样子,什么都不发。写入的答复按它留下的版本从系统视图路由
|
|
138
|
-
读回。服务端以重复请求拒绝的重试,会在系统路径上的重放路由里找到,但那条路由答的是快照,内容散列只有服务端算得出:
|
|
139
|
-
store 以系统视图**现在的样子**作答——除非这期间另一位管理员写过,那就是这次重试的结果。第一次已经把视图推过、手里的 revision 已不是视图当前的那个的重试,
|
|
140
|
-
先问重放路由,再以 `CONFLICT` 拒绝;重试的系统视图创建,从系统视图路由读回作答,带标记、用内容散列。
|
|
141
|
-
|
|
142
|
-
## 错误
|
|
143
|
-
|
|
144
|
-
所有拒绝都是引擎的 `ViewStoreError`,按 Wow 的错误码读——只有回答里没有 store 认得的错误码时才看 HTTP 状态:
|
|
145
|
-
|
|
146
|
-
| 服务端 | 端口 |
|
|
147
|
-
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
|
|
148
|
-
| `CommandExpectVersionConflict`、`EventVersionConflict`、`SourcingVersionConflict`;没有认得的错误码时 409、412 | `CONFLICT` |
|
|
149
|
-
| `NotFound`(别的应用的视图也是)、`IllegalAccessDeletedAggregate`;没有认得的错误码时 404、410 | `NOT_FOUND` |
|
|
150
|
-
| `IllegalAccessOwnerAggregate`、`IllegalAccessSpaceAggregate`、`IllegalAccessQueryScope`、`SystemViewReadOnly`、`ViewEventStreamClosed`;没有认得的错误码时 401、403 | `FORBIDDEN` |
|
|
151
|
-
| `ViewInvalid`、`ViewAppRequired`、`ViewScopeRequired`、`BadRequest`、`CommandValidation`、`IllegalArgument`、`DuplicateAggregateId`、`QuerySchemaValidation`;没有认得的错误码时 400、422;fetcher 的拦截器没填的路径变量(什么都没发) | `INVALID` |
|
|
152
|
-
| `IllegalState`、`RequestTimeout`、`TooManyRequests`、`InternalServerError`、`QuerySchemaUnavailable`、`QuerySchemaConflict`;没有认得的错误码时其余状态;根本没有回答 | `UNAVAILABLE` |
|
|
153
|
-
| 没有视图存储的服务端(早于它发布的)答的 `404`:列表,或每处都 `404` 且服务端的系统视图也 `404` 的读写 | `UNSUPPORTED` |
|
|
154
|
-
|
|
155
|
-
每个 `ViewStoreError` 都留着它的来处:请求本身的失败是 `cause`,服务端的 `errorCode` 是 `detail.code`(宿主据此分辨同为
|
|
156
|
-
`INVALID` 的 `ViewAppRequired` 与 `ViewInvalid`);服务端答了话的 `UNAVAILABLE`——5xx、它报的超时、不是 JSON 的页面——带
|
|
157
|
-
`reachable: true`,引擎据此说「服务端暂时无法处理」,而不是「无法连接服务端」。
|
|
158
|
-
|
|
159
|
-
重复的请求 id(`DuplicateRequestId`)本身不是错误:store 去查第一次的结果(见上)。没填的路径变量是宿主的配置问题——
|
|
160
|
-
拦截器没填 `{tenantId}`,或个人路径上的 `{ownerId}`——所以与服务端自己的 `ViewScopeRequired` 一样是 `INVALID`:
|
|
161
|
-
请求一构造就是错的,重试发出的还是同一个。
|
|
162
|
-
|
|
163
|
-
服务端因为有共享仪表盘显示着视图而拒绝收为个人时,错误的 `boards` 原样带上那几块看板的**标题**,由视图引擎用自己的话
|
|
164
|
-
说出这次拒绝:以键写的标题仍是键,在显示拒绝的地方说成话。`message` 保留服务端的原话,供日志。
|
|
165
|
-
|
|
166
|
-
`WowViewStoreErrorCodes` 列出视图存储自己的错误码。
|
|
89
|
+
`set(dataset, wording, revision, { requestId })` 按期望版本整份写入(从没写过的是 `'0'`),`clear` 清掉;谁能写由网关
|
|
90
|
+
按放行 `…/owner/(shared)/datasets/{dataset}/wording` 的角色决定。
|
|
91
|
+
|
|
92
|
+
## 文档
|
|
93
|
+
|
|
94
|
+
| 想做的事 | 读 |
|
|
95
|
+
| ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
|
|
96
|
+
| 选择视图放在哪里、接入 `WowViewStore`、给出权限、服务不登录的宿主 | [视图存放在哪里](https://wow.ahoo.me/zh/guide/typescript/view-engine-storage#wowviewstore-视图存在-wow-服务上) |
|
|
97
|
+
| 导出、合同、端口发出的每个请求,以及服务端错误怎样映射到端口 | [wow-view-store 参考](https://wow.ahoo.me/zh/reference/typescript/wow-view-store/) |
|
|
98
|
+
| 运行视图存储服务端、它的配置与网关规则 | [视图存储](https://wow.ahoo.me/zh/guide/extensions/view-store) |
|
|
167
99
|
|
|
168
100
|
## 测试
|
|
169
101
|
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
2
|
+
import { DatasetOverrides, DatasetWordingStore, StoredDatasetWording, WriteContext } from '@ahoo-wang/wow-view-engine';
|
|
3
|
+
/** How a {@link WowDatasetWordings} reaches the view store: as a `WowViewStore` does. */
|
|
4
|
+
export interface WowDatasetWordingsOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The fetcher every request goes through, as {@link WowViewStoreOptions.fetcher}:
|
|
7
|
+
* its interceptors fill `{tenantId}` and send `CoSec-App-Id`. The
|
|
8
|
+
* wording is the tenant's, so the store always names the owner `(shared)`.
|
|
9
|
+
*/
|
|
10
|
+
fetcher: Fetcher;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The wording a tenant's administrators keep over its datasets in the Wow
|
|
14
|
+
* view store (view engine D86): one per dataset of the caller's tenant and
|
|
15
|
+
* application, under `owner/(shared)`. The gateway decides who may write it.
|
|
16
|
+
*
|
|
17
|
+
* A host hands it to the datasets it registers as their store of wording
|
|
18
|
+
* (`DatasetCatalog.wordings`, D91): `DatasetResources` reads it before each
|
|
19
|
+
* refresh, registers each dataset in its stored words, and gives the view
|
|
20
|
+
* manager an editor of them. The key is the dataset's definition id,
|
|
21
|
+
* `{context}.{dataset}`.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* const resources = new DatasetResources(engine, {
|
|
25
|
+
* list: () => directory.list(),
|
|
26
|
+
* source: entry => directory.source(entry),
|
|
27
|
+
* wordings: new WowDatasetWordings({ fetcher }),
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* Every rejection is a `ViewStoreError`, read as a `WowViewStore`'s are.
|
|
32
|
+
*/
|
|
33
|
+
export declare class WowDatasetWordings implements DatasetWordingStore {
|
|
34
|
+
private readonly fetcher;
|
|
35
|
+
constructor(options: WowDatasetWordingsOptions);
|
|
36
|
+
/** Every dataset's wording of the caller's tenant and application, by dataset. */
|
|
37
|
+
list(signal?: AbortSignal): Promise<ReadonlyMap<string, StoredDatasetWording>>;
|
|
38
|
+
/**
|
|
39
|
+
* Writes a dataset's wording at the expected `revision` (`'0'` for one never
|
|
40
|
+
* written), whole: what it leaves out is no longer said. Answers the new
|
|
41
|
+
* revision.
|
|
42
|
+
*/
|
|
43
|
+
set(dataset: string, wording: DatasetOverrides, revision: string, context: WriteContext): Promise<string>;
|
|
44
|
+
/** Clears a dataset's wording at the expected `revision`: its derived words stand again. */
|
|
45
|
+
clear(dataset: string, revision: string, context: WriteContext): Promise<void>;
|
|
46
|
+
private send;
|
|
47
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { WowViewStore, type WowViewStoreOptions } from './wowViewStore.js';
|
|
2
2
|
export { SHARED_OWNER_ID, SYSTEM_OWNER_ID, SYSTEM_TENANT_ID } from './paths.js';
|
|
3
3
|
export { WowViewStoreErrorCodes } from './errors.js';
|
|
4
|
+
export { WowDatasetWordings, type WowDatasetWordingsOptions, } from './datasetWordings.js';
|
package/dist/index.es.js
CHANGED
|
@@ -234,7 +234,7 @@ function canonical(e) {
|
|
|
234
234
|
//#region src/wowViewStore.ts
|
|
235
235
|
var S = 1e3, C = 256, w = Symbol("not replayed"), WowViewStore = class {
|
|
236
236
|
constructor(e) {
|
|
237
|
-
this.places = /* @__PURE__ */ new Map(), this.preferenceOutcomes = new Remembered(), this.preferenceAttempts = new Remembered(), this.createAttempts = new Remembered(), this.storedVersions = new Remembered(O), this.fetcher = e.fetcher, e.permissions && (this.permissions = e.permissions);
|
|
237
|
+
this.listLimit = S, this.places = /* @__PURE__ */ new Map(), this.preferenceOutcomes = new Remembered(), this.preferenceAttempts = new Remembered(), this.createAttempts = new Remembered(), this.storedVersions = new Remembered(O), this.fetcher = e.fetcher, e.permissions && (this.permissions = e.permissions);
|
|
238
238
|
}
|
|
239
239
|
list(e, t) {
|
|
240
240
|
return guard(async () => {
|
|
@@ -597,8 +597,73 @@ var O = 1024, Remembered = class {
|
|
|
597
597
|
set(e, t) {
|
|
598
598
|
this.entries.delete(e), this.entries.set(e, t), this.entries.size > this.limit && this.entries.delete(this.entries.keys().next().value);
|
|
599
599
|
}
|
|
600
|
+
}, k = 1e3, A = {
|
|
601
|
+
wording: `${y}/datasets/{dataset}/wording`,
|
|
602
|
+
list: `${y}/dataset_wording/snapshot/list`
|
|
603
|
+
}, WowDatasetWordings = class {
|
|
604
|
+
constructor(e) {
|
|
605
|
+
this.fetcher = e.fetcher;
|
|
606
|
+
}
|
|
607
|
+
list(e) {
|
|
608
|
+
return guard(async () => {
|
|
609
|
+
let t = await (await this.send("POST", A.list, {
|
|
610
|
+
body: o({
|
|
611
|
+
filter: a.matchAll(),
|
|
612
|
+
limit: k
|
|
613
|
+
}),
|
|
614
|
+
signal: e
|
|
615
|
+
})).json();
|
|
616
|
+
return new Map(t.map(({ version: e, state: t }) => [t.dataset, {
|
|
617
|
+
wording: wordingOf(t),
|
|
618
|
+
revision: revisionOf(e)
|
|
619
|
+
}]));
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
set(e, t, n, r) {
|
|
623
|
+
return guard(async () => revisionOf((await (await this.send("PUT", A.wording, {
|
|
624
|
+
dataset: e,
|
|
625
|
+
body: {
|
|
626
|
+
...t.title === void 0 ? {} : { title: t.title },
|
|
627
|
+
...t.recordNoun === void 0 ? {} : { recordNoun: t.recordNoun },
|
|
628
|
+
...t.fields === void 0 ? {} : { fields: t.fields }
|
|
629
|
+
},
|
|
630
|
+
headers: writeHeaders(r, n),
|
|
631
|
+
signal: r.signal
|
|
632
|
+
})).json()).aggregateVersion ?? Number(n) + 1));
|
|
633
|
+
}
|
|
634
|
+
clear(e, t, n) {
|
|
635
|
+
return guard(async () => {
|
|
636
|
+
await this.send("DELETE", A.wording, {
|
|
637
|
+
dataset: e,
|
|
638
|
+
body: {},
|
|
639
|
+
headers: writeHeaders(n, t),
|
|
640
|
+
signal: n.signal
|
|
641
|
+
});
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
async send(t, n, { dataset: r, body: i, headers: a, signal: o }) {
|
|
645
|
+
try {
|
|
646
|
+
return await this.fetcher.request({
|
|
647
|
+
url: n,
|
|
648
|
+
method: t,
|
|
649
|
+
urlParams: { path: pathAt("shared", r === void 0 ? {} : { dataset: r }) },
|
|
650
|
+
body: i,
|
|
651
|
+
headers: a,
|
|
652
|
+
signal: o
|
|
653
|
+
}, { resultExtractor: e.Response });
|
|
654
|
+
} catch (e) {
|
|
655
|
+
throw await failureOf(e);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
600
658
|
};
|
|
659
|
+
function wordingOf(e) {
|
|
660
|
+
return {
|
|
661
|
+
...e.title == null ? {} : { title: e.title },
|
|
662
|
+
...e.recordNoun == null ? {} : { recordNoun: e.recordNoun },
|
|
663
|
+
...e.fields == null ? {} : { fields: e.fields }
|
|
664
|
+
};
|
|
665
|
+
}
|
|
601
666
|
//#endregion
|
|
602
|
-
export { g as SHARED_OWNER_ID, _ as SYSTEM_OWNER_ID, v as SYSTEM_TENANT_ID, WowViewStore, f as WowViewStoreErrorCodes };
|
|
667
|
+
export { g as SHARED_OWNER_ID, _ as SYSTEM_OWNER_ID, v as SYSTEM_TENANT_ID, WowDatasetWordings, WowViewStore, f as WowViewStoreErrorCodes };
|
|
603
668
|
|
|
604
669
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":["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","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"],"sources":["../src/errors.ts","../src/paths.ts","../src/wire.ts","../src/wowViewStore.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. */\nconst 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 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. */\nfunction 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 */\nasync 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"],"mappings":";;;;IAiCaA,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,KAAA,IAChC,KAAK,IAAIC,IAAc,KAAK,OAAOC,IAAQ,GAAGD,KAAMC,IAAQ,GAAG,KAAS;GACtE,IAAMC,IAAWF,EAA6B,SACxCG,IAAQ,OAAOD,KAAY,WAAWE,EAAS,KAA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,IAAIA,CAAG;CAC7B;CAEA,IAAI,GAAa,GAAgB;EAG/B,AAFA,KAAK,QAAQ,OAAOA,CAAG,GACvB,KAAK,QAAQ,IAAIA,GAAKC,CAAK,GACvB,KAAK,QAAQ,OAAO,KAAK,SAC3B,KAAK,QAAQ,OAAO,KAAK,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;CACzD;AACF"}
|
|
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,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,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"}
|
package/dist/paths.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ 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}";
|
|
35
37
|
/** The view store's routes, relative to the fetcher's base URL. */
|
|
36
38
|
export declare const PATHS: {
|
|
37
39
|
/** `POST`: create (the server generates the id). */
|
package/dist/wowViewStore.d.ts
CHANGED
|
@@ -59,6 +59,11 @@ export interface WowViewStoreOptions {
|
|
|
59
59
|
* another store — another tab, a reload — makes a second view.
|
|
60
60
|
*/
|
|
61
61
|
export declare class WowViewStore implements ViewStore {
|
|
62
|
+
/**
|
|
63
|
+
* The most of one audience a list answers (`LIST_LIMIT`): an audience
|
|
64
|
+
* listed this full was cut there, which the workbench then says (R2-26).
|
|
65
|
+
*/
|
|
66
|
+
readonly listLimit = 1000;
|
|
62
67
|
private readonly fetcher;
|
|
63
68
|
/**
|
|
64
69
|
* Where each view was last seen, by id. Kept after a delete, for its retry.
|
|
@@ -212,3 +217,11 @@ export declare class WowViewStore implements ViewStore {
|
|
|
212
217
|
*/
|
|
213
218
|
private send;
|
|
214
219
|
}
|
|
220
|
+
/** The headers of a write: its request id, its expected version, the wait. */
|
|
221
|
+
export declare function writeHeaders(context: WriteContext, revision?: string): Record<string, string>;
|
|
222
|
+
/**
|
|
223
|
+
* Runs one of the port's methods, so that everything it rejects with is a
|
|
224
|
+
* `ViewStoreError`: a failed request as its code says, anything else — a
|
|
225
|
+
* body that did not parse — as `UNAVAILABLE`, the outcome unknown.
|
|
226
|
+
*/
|
|
227
|
+
export declare function guard<T>(run: () => Promise<T>): Promise<T>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/wow-view-store",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.9.0",
|
|
4
4
|
"description": "The Wow view store as the view engine's ViewStore: saved views and preferences of @ahoo-wang/wow-view-engine on a Wow server (https://github.com/Ahoo-Wang/Wow).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"wow",
|
|
@@ -43,8 +43,8 @@
|
|
|
43
43
|
"sideEffects": false,
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@ahoo-wang/fetcher": "^5.1.5 || ^6.0.0",
|
|
46
|
-
"@ahoo-wang/wow-client": "~9.
|
|
47
|
-
"@ahoo-wang/wow-view-engine": "~9.
|
|
46
|
+
"@ahoo-wang/wow-client": "~9.9.0",
|
|
47
|
+
"@ahoo-wang/wow-view-engine": "~9.9.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
50
|
"@ahoo-wang/fetcher": "^6.0.1",
|
|
@@ -52,17 +52,17 @@
|
|
|
52
52
|
"@ahoo-wang/fetcher-eventstream": "^6.0.1",
|
|
53
53
|
"@eslint/js": "^10.0.1",
|
|
54
54
|
"@microsoft/api-extractor": "^7.59.4",
|
|
55
|
-
"@types/node": "^26.6.
|
|
55
|
+
"@types/node": "^26.6.5",
|
|
56
56
|
"@vitest/coverage-v8": "4.1.11",
|
|
57
57
|
"eslint": "^10.12.0",
|
|
58
58
|
"globals": "^17.13.0",
|
|
59
59
|
"typescript": "~6.0.3",
|
|
60
60
|
"typescript-eslint": "^8.71.1",
|
|
61
61
|
"unplugin-dts": "1.1.2",
|
|
62
|
-
"vite": "8.3.
|
|
62
|
+
"vite": "8.3.4",
|
|
63
63
|
"vitest": "^4.1.11",
|
|
64
|
-
"@ahoo-wang/wow-
|
|
65
|
-
"@ahoo-wang/wow-
|
|
64
|
+
"@ahoo-wang/wow-view-engine": "~9.9.0",
|
|
65
|
+
"@ahoo-wang/wow-client": "~9.9.0"
|
|
66
66
|
},
|
|
67
67
|
"scripts": {
|
|
68
68
|
"build": "vite build && pnpm test:package",
|