@bieberkit/plugin-redirects 0.0.1 → 0.6.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/CHANGELOG.md ADDED
@@ -0,0 +1,55 @@
1
+ <!--
2
+ BieberKit
3
+
4
+ @file plugins/redirects/CHANGELOG.md
5
+ @description Release history generated from changesets for @bieberkit/plugin-redirects.
6
+ @author Bieber Kieu <kieutrongthien@gmail.com>
7
+ @generated pnpm changeset version (license header normalized)
8
+ @copyright Copyright (c) 2026 Bieber Kieu
9
+ @license Apache-2.0
10
+
11
+ Licensed under the Apache License, Version 2.0 (the "License");
12
+ you may not use this file except in compliance with the License.
13
+ You may obtain a copy of the License at
14
+
15
+ http://www.apache.org/licenses/LICENSE-2.0
16
+
17
+ Unless required by applicable law or agreed to in writing, software
18
+ distributed under the License is distributed on an "AS IS" BASIS,
19
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ See the License for the specific language governing permissions and
21
+ limitations under the License.
22
+
23
+ SPDX-License-Identifier: Apache-2.0
24
+ -->
25
+
26
+ # @bieberkit/plugin-redirects
27
+
28
+ ## 0.6.0
29
+
30
+ ### Minor Changes
31
+
32
+ - 41d3311: Publish localized pages and articles from the admin. Draft changes stay private until published, and a signed preview link can open a draft. New site projects include publication snapshots, distinct localized slugs, permanent redirects on renames and per-type sitemap listings.
33
+
34
+ - d45cc96: Manage public redirects and retired paths from the admin. The generated site applies each rule before rendering, and rule changes invalidate shared HTML. New projects made with `--site` include the redirects plugin.
35
+
36
+ ### Patch Changes
37
+
38
+ - Updated dependencies [b87af44]
39
+ - Updated dependencies [2b2bd1c]
40
+ - Updated dependencies [b27ba2d]
41
+ - Updated dependencies [d69343e]
42
+ - Updated dependencies [f8dcdec]
43
+ - Updated dependencies [4958f26]
44
+ - Updated dependencies [6bf1a53]
45
+ - Updated dependencies [594f5db]
46
+ - Updated dependencies [ab624de]
47
+ - Updated dependencies [f1811d7]
48
+ - Updated dependencies [a9ecbb2]
49
+ - Updated dependencies [9ee9a18]
50
+ - Updated dependencies [8b309a4]
51
+ - @bieberkit/admin-antd@0.6.0
52
+ - @bieberkit/admin-core@0.6.0
53
+ - @bieberkit/http@0.6.0
54
+ - @bieberkit/core@0.6.0
55
+ - @bieberkit/data@0.6.0
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # @bieberkit/plugin-redirects
1
+ <!--
2
+ BieberKit
2
3
 
3
- Reserved for the first BieberKit release of this package. The release will be available under `beta`.
4
+ @file plugins/redirects/README.md
5
+ @description Explains how to manage public site redirects.
6
+ @author Bieber Kieu <kieutrongthien@gmail.com>
7
+ @copyright Copyright (c) 2026 Bieber Kieu
8
+ @license Apache-2.0
9
+
10
+ Licensed under the Apache License, Version 2.0 (the "License");
11
+ you may not use this file except in compliance with the License.
12
+ You may obtain a copy of the License at
13
+
14
+ http://www.apache.org/licenses/LICENSE-2.0
15
+
16
+ Unless required by applicable law or agreed to in writing, software
17
+ distributed under the License is distributed on an "AS IS" BASIS,
18
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ See the License for the specific language governing permissions and
20
+ limitations under the License.
21
+
22
+ SPDX-License-Identifier: Apache-2.0
23
+ -->
24
+
25
+ # Public site redirects
26
+
27
+ In the admin, open **Redirects** and enter a public source path, including its locale prefix. Select an HTTP status and supply an internal path or HTTP URL as the destination. To retire a path, select 410 and leave the destination empty.
28
+
29
+ Projects made with `--site` include this plugin. The generated site looks up rules before rendering and uses the policy cache tag to invalidate cached HTML when a rule changes. See ADR 0052.
@@ -0,0 +1,26 @@
1
+ /**
2
+ * BieberKit
3
+ *
4
+ * @file plugins/redirects/src/admin/index.ts
5
+ * @description Publishes the redirect management screen to the admin shell.
6
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
7
+ * @copyright Copyright (c) 2026 Bieber Kieu
8
+ * @license Apache-2.0
9
+ *
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * http://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ *
22
+ * SPDX-License-Identifier: Apache-2.0
23
+ */
24
+ import { AdminPart, AdminView } from "@bieberkit/admin-core";
25
+ declare const part: AdminPart<AdminView>;
26
+ export { part as default };
@@ -0,0 +1,45 @@
1
+ import { defineAdminPlugin } from "@bieberkit/admin-core";
2
+ // src/admin/index.ts
3
+ /**
4
+ * BieberKit
5
+ *
6
+ * @file plugins/redirects/src/admin/index.ts
7
+ * @description Publishes the redirect management screen to the admin shell.
8
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
9
+ * @copyright Copyright (c) 2026 Bieber Kieu
10
+ * @license Apache-2.0
11
+ *
12
+ * Licensed under the Apache License, Version 2.0 (the "License");
13
+ * you may not use this file except in compliance with the License.
14
+ * You may obtain a copy of the License at
15
+ *
16
+ * http://www.apache.org/licenses/LICENSE-2.0
17
+ *
18
+ * Unless required by applicable law or agreed to in writing, software
19
+ * distributed under the License is distributed on an "AS IS" BASIS,
20
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ * See the License for the specific language governing permissions and
22
+ * limitations under the License.
23
+ *
24
+ * SPDX-License-Identifier: Apache-2.0
25
+ */
26
+ const part = defineAdminPlugin({
27
+ name: "@bieberkit/plugin-redirects",
28
+ menu: [{
29
+ page: "/site-redirects",
30
+ group: "content",
31
+ permission: "redirects.read"
32
+ }],
33
+ pages: [{
34
+ path: "/site-redirects",
35
+ title: "redirects.title",
36
+ permission: "redirects.read",
37
+ load: () => import("./pages/RedirectsPage.js")
38
+ }],
39
+ messages: {
40
+ en: async () => ({ default: (await import("./messages/en.js")).en }),
41
+ vi: async () => ({ default: (await import("./messages/vi.js")).vi }),
42
+ zh: async () => ({ default: (await import("./messages/zh.js")).zh })
43
+ }
44
+ });
45
+ export { part as default };
@@ -0,0 +1,47 @@
1
+ // src/admin/messages/en.ts
2
+ /**
3
+ * BieberKit
4
+ *
5
+ * @file plugins/redirects/src/admin/messages/en.ts
6
+ * @description Labels for the redirects admin screen in en.
7
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
8
+ * @copyright Copyright (c) 2026 Bieber Kieu
9
+ * @license Apache-2.0
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ *
23
+ * SPDX-License-Identifier: Apache-2.0
24
+ */
25
+ const en = {
26
+ "redirects.title": "Redirects",
27
+ "redirects.source": "Source path",
28
+ "redirects.target": "Destination",
29
+ "redirects.status": "Status",
30
+ "redirects.save": "Save rule",
31
+ "redirects.clear": "Clear form",
32
+ "redirects.edit": "Edit",
33
+ "redirects.remove": "Remove",
34
+ "redirects.confirm": "Remove this redirect?",
35
+ "redirects.empty": "No redirect rules",
36
+ "redirects.retry": "Try again",
37
+ "redirects.actions": "Actions",
38
+ "redirects.targetRequired": "Change the destination",
39
+ "redirects.410": "Page removed (410)",
40
+ "redirects.301": "Permanent redirect (301)",
41
+ "redirects.302": "Found (302)",
42
+ "redirects.307": "Temporary redirect (307)",
43
+ "redirects.308": "Permanent redirect (308)",
44
+ "redirects.codes.permission.redirects.manage": "Manage public redirects",
45
+ "redirects.codes.permission.redirects.read": "Read public redirects"
46
+ };
47
+ export { en };
@@ -0,0 +1,47 @@
1
+ // src/admin/messages/vi.ts
2
+ /**
3
+ * BieberKit
4
+ *
5
+ * @file plugins/redirects/src/admin/messages/vi.ts
6
+ * @description Labels for the redirects admin screen in vi.
7
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
8
+ * @copyright Copyright (c) 2026 Bieber Kieu
9
+ * @license Apache-2.0
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ *
23
+ * SPDX-License-Identifier: Apache-2.0
24
+ */
25
+ const vi = {
26
+ "redirects.title": "Chuyển hướng",
27
+ "redirects.source": "Đường dẫn nguồn",
28
+ "redirects.target": "Đích chuyển hướng",
29
+ "redirects.status": "Trạng thái",
30
+ "redirects.save": "Lưu quy tắc",
31
+ "redirects.clear": "Xóa nội dung biểu mẫu",
32
+ "redirects.edit": "Sửa",
33
+ "redirects.remove": "Xóa",
34
+ "redirects.confirm": "Xóa quy tắc chuyển hướng này?",
35
+ "redirects.empty": "Chưa có quy tắc chuyển hướng",
36
+ "redirects.retry": "Thử lại",
37
+ "redirects.actions": "Thao tác",
38
+ "redirects.targetRequired": "Đổi đích chuyển hướng",
39
+ "redirects.410": "Trang đã bị gỡ (410)",
40
+ "redirects.301": "Chuyển hướng vĩnh viễn (301)",
41
+ "redirects.302": "Chuyển hướng tạm thời (302)",
42
+ "redirects.307": "Chuyển hướng tạm thời (307)",
43
+ "redirects.308": "Chuyển hướng vĩnh viễn (308)",
44
+ "redirects.codes.permission.redirects.manage": "Quản lý chuyển hướng công khai",
45
+ "redirects.codes.permission.redirects.read": "Xem chuyển hướng công khai"
46
+ };
47
+ export { vi };
@@ -0,0 +1,47 @@
1
+ // src/admin/messages/zh.ts
2
+ /**
3
+ * BieberKit
4
+ *
5
+ * @file plugins/redirects/src/admin/messages/zh.ts
6
+ * @description Labels for the redirects admin screen in zh.
7
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
8
+ * @copyright Copyright (c) 2026 Bieber Kieu
9
+ * @license Apache-2.0
10
+ *
11
+ * Licensed under the Apache License, Version 2.0 (the "License");
12
+ * you may not use this file except in compliance with the License.
13
+ * You may obtain a copy of the License at
14
+ *
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ *
17
+ * Unless required by applicable law or agreed to in writing, software
18
+ * distributed under the License is distributed on an "AS IS" BASIS,
19
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ * See the License for the specific language governing permissions and
21
+ * limitations under the License.
22
+ *
23
+ * SPDX-License-Identifier: Apache-2.0
24
+ */
25
+ const zh = {
26
+ "redirects.title": "重定向",
27
+ "redirects.source": "来源路径",
28
+ "redirects.target": "目标地址",
29
+ "redirects.status": "状态",
30
+ "redirects.save": "保存规则",
31
+ "redirects.clear": "清空表单",
32
+ "redirects.edit": "编辑",
33
+ "redirects.remove": "删除",
34
+ "redirects.confirm": "是否删除此重定向?",
35
+ "redirects.empty": "暂无重定向规则",
36
+ "redirects.retry": "重试",
37
+ "redirects.actions": "操作",
38
+ "redirects.targetRequired": "更改目标地址",
39
+ "redirects.410": "页面已删除 (410)",
40
+ "redirects.301": "永久重定向 (301)",
41
+ "redirects.302": "临时重定向 (302)",
42
+ "redirects.307": "临时重定向 (307)",
43
+ "redirects.308": "永久重定向 (308)",
44
+ "redirects.codes.permission.redirects.manage": "管理公开重定向",
45
+ "redirects.codes.permission.redirects.read": "查看公开重定向"
46
+ };
47
+ export { zh };
@@ -0,0 +1,219 @@
1
+ import { useAdminClient, useCan, useText } from "@bieberkit/admin-antd";
2
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3
+ import { Alert, Button, Form, Input, Popconfirm, Select, Space, Table } from "antd";
4
+ import { useState } from "react";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ // src/admin/pages/RedirectsPage.tsx
7
+ /**
8
+ * BieberKit
9
+ *
10
+ * @file plugins/redirects/src/admin/pages/RedirectsPage.tsx
11
+ * @description Lists and edits the public site redirect rules.
12
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
13
+ * @copyright Copyright (c) 2026 Bieber Kieu
14
+ * @license Apache-2.0
15
+ *
16
+ * Licensed under the Apache License, Version 2.0 (the "License");
17
+ * you may not use this file except in compliance with the License.
18
+ * You may obtain a copy of the License at
19
+ *
20
+ * http://www.apache.org/licenses/LICENSE-2.0
21
+ *
22
+ * Unless required by applicable law or agreed to in writing, software
23
+ * distributed under the License is distributed on an "AS IS" BASIS,
24
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25
+ * See the License for the specific language governing permissions and
26
+ * limitations under the License.
27
+ *
28
+ * SPDX-License-Identifier: Apache-2.0
29
+ */
30
+ const API = "/api/v1/redirects/rules";
31
+ const KEY = ["site-redirects"];
32
+ const statuses = [
33
+ 301,
34
+ 302,
35
+ 307,
36
+ 308,
37
+ 410
38
+ ];
39
+ function readList(input) {
40
+ if (typeof input !== "object" || input === null || !("data" in input) || !Array.isArray(input.data)) return {
41
+ data: [],
42
+ total: 0
43
+ };
44
+ const data = input.data.flatMap((candidate) => {
45
+ if (typeof candidate !== "object" || candidate === null || !("source" in candidate) || typeof candidate.source !== "string" || !("status" in candidate) || typeof candidate.status !== "number") return [];
46
+ const { source, status } = candidate;
47
+ const target = "target" in candidate && typeof candidate.target === "string" ? candidate.target : void 0;
48
+ return [target === void 0 ? {
49
+ source,
50
+ status
51
+ } : {
52
+ source,
53
+ status,
54
+ target
55
+ }];
56
+ });
57
+ return {
58
+ data,
59
+ total: "total" in input && typeof input.total === "number" ? input.total : data.length
60
+ };
61
+ }
62
+ function RedirectsPage() {
63
+ const text = useText();
64
+ const client = useAdminClient();
65
+ const canManage = useCan("redirects.manage");
66
+ const cache = useQueryClient();
67
+ const [page, setPage] = useState(1);
68
+ const [editing, setEditing] = useState(false);
69
+ const [form] = Form.useForm();
70
+ const status = Form.useWatch("status", form);
71
+ const list = useQuery({
72
+ queryKey: [...KEY, page],
73
+ queryFn: async () => readList(await client.request("GET", API + "?page=" + String(page)))
74
+ });
75
+ const clear = () => {
76
+ form.resetFields();
77
+ setEditing(false);
78
+ };
79
+ const save = useMutation({
80
+ mutationFn: (draft) => client.request("PUT", API, { body: draft.status === 410 ? {
81
+ source: draft.source,
82
+ status: draft.status
83
+ } : draft }),
84
+ onSuccess: async () => {
85
+ clear();
86
+ await cache.invalidateQueries({ queryKey: KEY });
87
+ }
88
+ });
89
+ const remove = useMutation({
90
+ mutationFn: (source) => client.request("DELETE", API + "?" + new URLSearchParams({ source })),
91
+ onSuccess: async (_response, source) => {
92
+ if (form.getFieldValue("source") === source) clear();
93
+ if ((list.data?.data.length ?? 0) === 1 && page > 1) setPage(page - 1);
94
+ await cache.invalidateQueries({ queryKey: KEY });
95
+ }
96
+ });
97
+ const error = save.error ?? remove.error ?? list.error;
98
+ const pending = save.isPending || remove.isPending;
99
+ return /* @__PURE__ */ jsxs(Space, {
100
+ orientation: "vertical",
101
+ size: "large",
102
+ style: { width: "100%" },
103
+ children: [
104
+ error && /* @__PURE__ */ jsx(Alert, {
105
+ type: "error",
106
+ showIcon: true,
107
+ title: error.message,
108
+ action: list.isError && /* @__PURE__ */ jsx(Button, {
109
+ type: "link",
110
+ onClick: () => void list.refetch(),
111
+ children: text("redirects.retry")
112
+ })
113
+ }),
114
+ canManage && /* @__PURE__ */ jsxs(Form, {
115
+ form,
116
+ layout: "vertical",
117
+ initialValues: { status: 301 },
118
+ disabled: pending,
119
+ onFinish: (draft) => save.mutate(draft),
120
+ children: [
121
+ /* @__PURE__ */ jsx(Form.Item, {
122
+ name: "source",
123
+ label: text("redirects.source"),
124
+ rules: [{ required: true }],
125
+ children: /* @__PURE__ */ jsx(Input, {
126
+ readOnly: editing,
127
+ maxLength: 2048
128
+ })
129
+ }),
130
+ /* @__PURE__ */ jsx(Form.Item, {
131
+ name: "status",
132
+ label: text("redirects.status"),
133
+ rules: [{ required: true }],
134
+ children: /* @__PURE__ */ jsx(Select, {
135
+ virtual: false,
136
+ options: statuses.map((value) => ({
137
+ value,
138
+ label: text("redirects." + String(value))
139
+ }))
140
+ })
141
+ }),
142
+ status !== 410 && /* @__PURE__ */ jsx(Form.Item, {
143
+ name: "target",
144
+ label: text("redirects.target"),
145
+ rules: [{
146
+ required: true,
147
+ message: text("redirects.targetRequired")
148
+ }],
149
+ children: /* @__PURE__ */ jsx(Input, { maxLength: 2048 })
150
+ }),
151
+ /* @__PURE__ */ jsxs(Space, { children: [/* @__PURE__ */ jsx(Button, {
152
+ type: "primary",
153
+ htmlType: "submit",
154
+ loading: save.isPending,
155
+ children: text("redirects.save")
156
+ }), /* @__PURE__ */ jsx(Button, {
157
+ onClick: clear,
158
+ children: text("redirects.clear")
159
+ })] })
160
+ ]
161
+ }),
162
+ /* @__PURE__ */ jsx(Table, {
163
+ rowKey: "source",
164
+ loading: list.isPending,
165
+ dataSource: list.data?.data ?? [],
166
+ locale: { emptyText: text("redirects.empty") },
167
+ pagination: {
168
+ current: page,
169
+ total: list.data?.total ?? 0,
170
+ pageSize: 50,
171
+ showSizeChanger: false,
172
+ onChange: setPage
173
+ },
174
+ columns: [
175
+ {
176
+ key: "source",
177
+ dataIndex: "source",
178
+ title: text("redirects.source")
179
+ },
180
+ {
181
+ key: "target",
182
+ dataIndex: "target",
183
+ title: text("redirects.target")
184
+ },
185
+ {
186
+ key: "status",
187
+ title: text("redirects.status"),
188
+ render: (_, rule) => text("redirects." + String(rule.status))
189
+ },
190
+ ...canManage ? [{
191
+ key: "actions",
192
+ title: text("redirects.actions"),
193
+ render: (_, rule) => /* @__PURE__ */ jsxs(Space, { children: [/* @__PURE__ */ jsx(Button, {
194
+ disabled: pending,
195
+ onClick: () => {
196
+ form.setFieldsValue({
197
+ ...rule,
198
+ target: rule.target ?? ""
199
+ });
200
+ setEditing(true);
201
+ },
202
+ children: text("redirects.edit")
203
+ }), /* @__PURE__ */ jsx(Popconfirm, {
204
+ disabled: pending,
205
+ title: text("redirects.confirm"),
206
+ onConfirm: () => remove.mutate(rule.source),
207
+ children: /* @__PURE__ */ jsx(Button, {
208
+ danger: true,
209
+ disabled: pending,
210
+ children: text("redirects.remove")
211
+ })
212
+ })] })
213
+ }] : []
214
+ ]
215
+ })
216
+ ]
217
+ });
218
+ }
219
+ export { RedirectsPage as default };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * BieberKit
3
+ *
4
+ * @file plugins/redirects/src/index.ts
5
+ * @description Declares the redirects plugin and its public lookup.
6
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
7
+ * @copyright Copyright (c) 2026 Bieber Kieu
8
+ * @license Apache-2.0
9
+ *
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * http://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ *
22
+ * SPDX-License-Identifier: Apache-2.0
23
+ */
24
+ import { PluginDef } from "@bieberkit/core";
25
+ import "@bieberkit/data/orm";
26
+ interface PublicationRedirects {
27
+ isReserved(path: string): Promise<boolean>;
28
+ recordMove(previous: string, current: string): Promise<void>;
29
+ }
30
+ declare module "@bieberkit/core" {
31
+ interface ServiceRegistry {
32
+ publicationRedirects: PublicationRedirects;
33
+ }
34
+ }
35
+ declare const plugin: PluginDef;
36
+ export { type PublicationRedirects, plugin as default };
package/dist/index.js ADDED
@@ -0,0 +1,442 @@
1
+ import { BkError, definePlugin } from "@bieberkit/core";
2
+ import { defineEntity, f } from "@bieberkit/data";
3
+ import { DEFAULT_TENANT, currentEntityManager, runInTransaction, runInUnitOfWork } from "@bieberkit/data/orm";
4
+ import { HttpError, defineRoute, purgeSite } from "@bieberkit/http";
5
+ import { createHash } from "node:crypto";
6
+ // package.json
7
+ var version = "0.6.0";
8
+ // src/entities/redirect.ts
9
+ /**
10
+ * BieberKit
11
+ *
12
+ * @file plugins/redirects/src/entities/redirect.ts
13
+ * @description Defines an exact-path public site redirect rule.
14
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
15
+ * @copyright Copyright (c) 2026 Bieber Kieu
16
+ * @license Apache-2.0
17
+ *
18
+ * Licensed under the Apache License, Version 2.0 (the "License");
19
+ * you may not use this file except in compliance with the License.
20
+ * You may obtain a copy of the License at
21
+ *
22
+ * http://www.apache.org/licenses/LICENSE-2.0
23
+ *
24
+ * Unless required by applicable law or agreed to in writing, software
25
+ * distributed under the License is distributed on an "AS IS" BASIS,
26
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27
+ * See the License for the specific language governing permissions and
28
+ * limitations under the License.
29
+ *
30
+ * SPDX-License-Identifier: Apache-2.0
31
+ */
32
+ const Redirect = defineEntity({
33
+ name: "redirects.Redirect",
34
+ table: "bk_site_redirects",
35
+ fields: {
36
+ id: f.id(),
37
+ sourceKey: f.string({
38
+ min: 64,
39
+ max: 64
40
+ }).unique(),
41
+ source: f.string({
42
+ min: 1,
43
+ max: 2048
44
+ }),
45
+ target: f.string({
46
+ min: 1,
47
+ max: 2048
48
+ }).optional(),
49
+ status: f.int({
50
+ min: 301,
51
+ max: 410
52
+ }),
53
+ createdAt: f.createdAt(),
54
+ updatedAt: f.updatedAt()
55
+ }
56
+ });
57
+ // src/services/redirects.ts
58
+ /**
59
+ * BieberKit
60
+ *
61
+ * @file plugins/redirects/src/services/redirects.ts
62
+ * @description Validates, stores and resolves public site redirect rules.
63
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
64
+ * @copyright Copyright (c) 2026 Bieber Kieu
65
+ * @license Apache-2.0
66
+ *
67
+ * Licensed under the Apache License, Version 2.0 (the "License");
68
+ * you may not use this file except in compliance with the License.
69
+ * You may obtain a copy of the License at
70
+ *
71
+ * http://www.apache.org/licenses/LICENSE-2.0
72
+ *
73
+ * Unless required by applicable law or agreed to in writing, software
74
+ * distributed under the License is distributed on an "AS IS" BASIS,
75
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
76
+ * See the License for the specific language governing permissions and
77
+ * limitations under the License.
78
+ *
79
+ * SPDX-License-Identifier: Apache-2.0
80
+ */
81
+ const REDIRECT_STATUSES = [
82
+ 301,
83
+ 302,
84
+ 307,
85
+ 308,
86
+ 410
87
+ ];
88
+ const SITE_ORIGIN = "https://redirects.invalid";
89
+ const PAGE_SIZE = 50;
90
+ const POLICY_TAG = ["site:policy"];
91
+ const tableOf = (em) => em.getMetadata().getByClassName(Redirect.name).class;
92
+ const keyOf = (source) => createHash("sha256").update(source).digest("hex");
93
+ const withinLimit = (value) => value.length > 0 && value.length <= 2048;
94
+ const unsafe = /[\p{Cc}\\\s]/u;
95
+ function normalizedPath(value) {
96
+ if (!withinLimit(value) || !value.startsWith("/") || value.startsWith("//") || unsafe.test(value)) return void 0;
97
+ try {
98
+ const segments = value.split("/").map((segment) => decodeURIComponent(segment).normalize("NFC"));
99
+ if (segments.some((segment) => segment === "." || segment === ".." || /[\p{Cc}/\\]/u.test(segment))) return void 0;
100
+ const path = segments.map((segment) => encodeURIComponent(segment)).join("/");
101
+ return withinLimit(path) ? path : void 0;
102
+ } catch {
103
+ return;
104
+ }
105
+ }
106
+ function sourceOf(value) {
107
+ if (typeof value !== "string" || value.includes("?") || value.includes("#")) return void 0;
108
+ const path = normalizedPath(value);
109
+ if (path === void 0 || /^\/(?:api|health|assets|sitemap|admin)(?:\/|$)/.test(path) || path === "/robots.txt" || path === "/sitemap.xml") return void 0;
110
+ return path;
111
+ }
112
+ function targetOf(value) {
113
+ if (typeof value !== "string" || !withinLimit(value) || unsafe.test(value) || value.startsWith("//")) return void 0;
114
+ const relative = value.startsWith("/");
115
+ const url = relative ? URL.parse(value, SITE_ORIGIN) : URL.parse(value);
116
+ if (url === null || url.protocol !== "http:" && url.protocol !== "https:" || url.username !== "" || url.password !== "") return void 0;
117
+ if (!relative) return withinLimit(url.href) ? url.href : void 0;
118
+ const path = normalizedPath(url.pathname);
119
+ const target = path === void 0 || url.origin !== SITE_ORIGIN ? void 0 : path + url.search + url.hash;
120
+ return target !== void 0 && withinLimit(target) ? target : void 0;
121
+ }
122
+ function invalid(message) {
123
+ throw new HttpError("REDIRECT_INVALID", 400, message, "Check the source, destination and HTTP status.");
124
+ }
125
+ function readRule(row) {
126
+ if (typeof row !== "object" || row === null) return void 0;
127
+ const source = Reflect.get(row, "source");
128
+ const status = Reflect.get(row, "status");
129
+ if (typeof source !== "string" || typeof status !== "number" || !REDIRECT_STATUSES.includes(status)) return void 0;
130
+ if (status === 410) return {
131
+ source,
132
+ status
133
+ };
134
+ const target = targetOf(Reflect.get(row, "target"));
135
+ return target === void 0 ? void 0 : {
136
+ source,
137
+ status,
138
+ target
139
+ };
140
+ }
141
+ const pathOfTarget = (target) => target?.startsWith("/") === true ? URL.parse(target, SITE_ORIGIN)?.pathname : void 0;
142
+ async function bySource(em, source) {
143
+ return readRule(await em.findOne(tableOf(em), { sourceKey: keyOf(source) }));
144
+ }
145
+ async function nextEditCreatesLoop(em, source, target) {
146
+ const visited = /* @__PURE__ */ new Set([source]);
147
+ let next = pathOfTarget(target);
148
+ while (next !== void 0) {
149
+ if (visited.has(next) || visited.size === 32) return true;
150
+ visited.add(next);
151
+ next = pathOfTarget((await bySource(em, next))?.target);
152
+ }
153
+ return false;
154
+ }
155
+ async function lookupRedirect(db, path) {
156
+ const source = sourceOf(path);
157
+ if (source === void 0) return null;
158
+ return runInUnitOfWork(db, async (em) => {
159
+ const rule = await bySource(em, source);
160
+ if (rule === void 0 || await nextEditCreatesLoop(em, source, rule.target)) return null;
161
+ return rule.target === void 0 ? { status: rule.status } : {
162
+ status: rule.status,
163
+ target: rule.target
164
+ };
165
+ });
166
+ }
167
+ async function listRedirects(db, page) {
168
+ return runInUnitOfWork(db, async (em) => {
169
+ const [rows, total] = await em.findAndCount(tableOf(em), {}, {
170
+ orderBy: {
171
+ source: "asc",
172
+ id: "asc"
173
+ },
174
+ offset: (page - 1) * PAGE_SIZE,
175
+ limit: PAGE_SIZE
176
+ });
177
+ return {
178
+ data: rows.flatMap((row) => {
179
+ const rule = readRule(row);
180
+ return rule === void 0 ? [] : [rule];
181
+ }),
182
+ total
183
+ };
184
+ });
185
+ }
186
+ function normalizedRule(input) {
187
+ if (typeof input !== "object" || input === null) return invalid("Send a redirect rule.");
188
+ const source = sourceOf(Reflect.get(input, "source"));
189
+ const status = Reflect.get(input, "status");
190
+ const destination = Reflect.get(input, "target");
191
+ const target = targetOf(destination);
192
+ if (source === void 0) return invalid("The source must be a public site path.");
193
+ if (typeof status !== "number" || !REDIRECT_STATUSES.includes(status)) return invalid("Choose a supported HTTP status.");
194
+ if (status === 410 ? destination !== void 0 : target === void 0) return invalid("Check the destination for this status.");
195
+ return target === void 0 ? {
196
+ source,
197
+ status
198
+ } : {
199
+ source,
200
+ status,
201
+ target
202
+ };
203
+ }
204
+ async function storeRedirect(em, rule) {
205
+ const { source, status, target } = rule;
206
+ if (await nextEditCreatesLoop(em, source, target)) return invalid("This rule would create a redirect loop.");
207
+ const entity = tableOf(em);
208
+ const sourceKey = keyOf(source);
209
+ const existing = await em.findOne(entity, { sourceKey });
210
+ if (typeof existing === "object" && existing !== null) {
211
+ const previous = readRule(existing);
212
+ if (previous?.status === status && previous.target === target) return rule;
213
+ Reflect.set(existing, "status", status);
214
+ Reflect.set(existing, "target", target ?? null);
215
+ } else em.create(entity, {
216
+ ...rule,
217
+ sourceKey
218
+ });
219
+ purgeSite(em, POLICY_TAG);
220
+ await em.flush();
221
+ return rule;
222
+ }
223
+ async function saveRedirect(db, input) {
224
+ const rule = normalizedRule(input);
225
+ return runInTransaction(db, (em) => storeRedirect(em, rule));
226
+ }
227
+ function publicationTransaction() {
228
+ const em = currentEntityManager();
229
+ if (em?.isInTransaction() !== true) throw new BkError("Update publication paths inside the publishing transaction.", { code: "REDIRECT_TRANSACTION" });
230
+ return em;
231
+ }
232
+ const publicationRedirects = {
233
+ async isReserved(path) {
234
+ const source = sourceOf(path);
235
+ if (source === void 0) return invalid("The path must be a public site path.");
236
+ const em = publicationTransaction();
237
+ return await em.count(tableOf(em), { sourceKey: keyOf(source) }) > 0;
238
+ },
239
+ async recordMove(previous, current) {
240
+ await storeRedirect(publicationTransaction(), normalizedRule({
241
+ source: previous,
242
+ status: 301,
243
+ target: current
244
+ }));
245
+ }
246
+ };
247
+ async function deleteRedirect(db, input) {
248
+ const source = sourceOf(input);
249
+ if (source === void 0) return invalid("The source must be a public site path.");
250
+ await runInTransaction(db, async (em) => {
251
+ if (await em.nativeDelete(tableOf(em), { sourceKey: keyOf(source) }) > 0) {
252
+ purgeSite(em, POLICY_TAG);
253
+ await em.flush();
254
+ }
255
+ });
256
+ }
257
+ // src/routes/index.ts
258
+ /**
259
+ * BieberKit
260
+ *
261
+ * @file plugins/redirects/src/routes/index.ts
262
+ * @description Declares redirect management and public lookup routes.
263
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
264
+ * @copyright Copyright (c) 2026 Bieber Kieu
265
+ * @license Apache-2.0
266
+ *
267
+ * Licensed under the Apache License, Version 2.0 (the "License");
268
+ * you may not use this file except in compliance with the License.
269
+ * You may obtain a copy of the License at
270
+ *
271
+ * http://www.apache.org/licenses/LICENSE-2.0
272
+ *
273
+ * Unless required by applicable law or agreed to in writing, software
274
+ * distributed under the License is distributed on an "AS IS" BASIS,
275
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
276
+ * See the License for the specific language governing permissions and
277
+ * limitations under the License.
278
+ *
279
+ * SPDX-License-Identifier: Apache-2.0
280
+ */
281
+ const rules = "/api/v1/redirects/rules";
282
+ const address = {
283
+ type: "string",
284
+ minLength: 1,
285
+ maxLength: 2048
286
+ };
287
+ const action = {
288
+ type: "object",
289
+ properties: {
290
+ status: {
291
+ type: "integer",
292
+ enum: REDIRECT_STATUSES
293
+ },
294
+ target: address
295
+ },
296
+ required: ["status"]
297
+ };
298
+ const rule = {
299
+ ...action,
300
+ additionalProperties: false,
301
+ properties: {
302
+ ...action.properties,
303
+ source: address
304
+ },
305
+ required: ["source", "status"]
306
+ };
307
+ function siteScope(ctx) {
308
+ if (ctx.tenantId !== void 0 && ctx.tenantId !== DEFAULT_TENANT) throw new HttpError("REDIRECT_SCOPE", 403, "Redirect rules are shared by the whole public site.", "Manage rules outside a tenant.");
309
+ ctx.header("cache-control", "private, no-store");
310
+ }
311
+ const routes = [
312
+ defineRoute({
313
+ method: "GET",
314
+ url: "/api/v1/redirects/lookup",
315
+ public: true,
316
+ schema: {
317
+ query: {
318
+ type: "object",
319
+ properties: { path: address },
320
+ required: ["path"]
321
+ },
322
+ response: { 200: {
323
+ type: "object",
324
+ properties: { data: { anyOf: [action, { type: "null" }] } },
325
+ required: ["data"]
326
+ } }
327
+ },
328
+ handler: async (ctx) => {
329
+ ctx.header("cache-control", "private, no-store");
330
+ return { data: await lookupRedirect(ctx.services.database, ctx.query["path"]) };
331
+ }
332
+ }),
333
+ defineRoute({
334
+ method: "GET",
335
+ url: rules,
336
+ permission: "redirects.read",
337
+ schema: {
338
+ query: {
339
+ type: "object",
340
+ properties: { page: {
341
+ type: "integer",
342
+ minimum: 1,
343
+ maximum: 1e6
344
+ } }
345
+ },
346
+ response: { 200: {
347
+ type: "object",
348
+ properties: {
349
+ data: {
350
+ type: "array",
351
+ items: rule
352
+ },
353
+ total: { type: "integer" }
354
+ },
355
+ required: ["data", "total"]
356
+ } }
357
+ },
358
+ handler: (ctx) => {
359
+ siteScope(ctx);
360
+ const page = ctx.query["page"];
361
+ return listRedirects(ctx.services.database, typeof page === "number" ? page : 1);
362
+ }
363
+ }),
364
+ defineRoute({
365
+ method: "PUT",
366
+ url: rules,
367
+ permission: "redirects.manage",
368
+ schema: {
369
+ body: rule,
370
+ response: { 200: {
371
+ type: "object",
372
+ properties: { data: rule },
373
+ required: ["data"]
374
+ } }
375
+ },
376
+ handler: async (ctx) => {
377
+ siteScope(ctx);
378
+ return { data: await saveRedirect(ctx.services.database, ctx.body) };
379
+ }
380
+ }),
381
+ defineRoute({
382
+ method: "DELETE",
383
+ url: rules,
384
+ permission: "redirects.manage",
385
+ schema: {
386
+ query: {
387
+ type: "object",
388
+ properties: { source: address },
389
+ required: ["source"]
390
+ },
391
+ response: { 204: { type: "null" } }
392
+ },
393
+ handler: async (ctx) => {
394
+ siteScope(ctx);
395
+ await deleteRedirect(ctx.services.database, ctx.query["source"]);
396
+ ctx.status(204);
397
+ return null;
398
+ }
399
+ })
400
+ ];
401
+ // src/index.ts
402
+ /**
403
+ * BieberKit
404
+ *
405
+ * @file plugins/redirects/src/index.ts
406
+ * @description Declares the redirects plugin and its public lookup.
407
+ * @author Bieber Kieu <kieutrongthien@gmail.com>
408
+ * @copyright Copyright (c) 2026 Bieber Kieu
409
+ * @license Apache-2.0
410
+ *
411
+ * Licensed under the Apache License, Version 2.0 (the "License");
412
+ * you may not use this file except in compliance with the License.
413
+ * You may obtain a copy of the License at
414
+ *
415
+ * http://www.apache.org/licenses/LICENSE-2.0
416
+ *
417
+ * Unless required by applicable law or agreed to in writing, software
418
+ * distributed under the License is distributed on an "AS IS" BASIS,
419
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
420
+ * See the License for the specific language governing permissions and
421
+ * limitations under the License.
422
+ *
423
+ * SPDX-License-Identifier: Apache-2.0
424
+ */
425
+ const plugin = definePlugin({
426
+ name: "@bieberkit/plugin-redirects",
427
+ version,
428
+ core: "*",
429
+ dialects: [
430
+ "postgres",
431
+ "mysql",
432
+ "sqlite"
433
+ ],
434
+ permissions: ["redirects.read", "redirects.manage"],
435
+ entities: [Redirect],
436
+ routes,
437
+ services: { publicationRedirects: {
438
+ scope: "singleton",
439
+ create: () => publicationRedirects
440
+ } }
441
+ });
442
+ export { plugin as default };
package/package.json CHANGED
@@ -1,19 +1,112 @@
1
1
  {
2
2
  "name": "@bieberkit/plugin-redirects",
3
- "version": "0.0.1",
4
- "description": "Reserved for the first BieberKit release of this package.",
3
+ "version": "0.6.0",
4
+ "description": "Manages public site redirects and retired routes.",
5
+ "keywords": [
6
+ "bieberkit",
7
+ "bieberkit-plugin"
8
+ ],
9
+ "homepage": "https://github.com/kieutrongthien/bieberkit#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/kieutrongthien/bieberkit/issues"
12
+ },
5
13
  "license": "Apache-2.0",
6
14
  "author": "Bieber Kieu <kieutrongthien@gmail.com>",
7
- "homepage": "https://github.com/kieutrongthien/bieberkit#readme",
8
15
  "repository": {
9
16
  "type": "git",
10
17
  "url": "git+https://github.com/kieutrongthien/bieberkit.git",
11
18
  "directory": "plugins/redirects"
12
19
  },
13
20
  "files": [
14
- "NOTICE"
21
+ "dist",
22
+ "NOTICE",
23
+ "CHANGELOG.md"
15
24
  ],
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./admin": {
33
+ "types": "./dist/admin/index.d.ts",
34
+ "default": "./dist/admin/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
16
38
  "publishConfig": {
17
- "registry": "https://registry.npmjs.org/"
39
+ "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "@bieberkit/core": "0.6.0",
43
+ "@bieberkit/data": "0.6.0",
44
+ "@bieberkit/http": "0.6.0"
45
+ },
46
+ "devDependencies": {
47
+ "@bieberkit/admin-antd": "0.6.0",
48
+ "@bieberkit/admin-core": "0.6.0",
49
+ "@bieberkit/testing": "0.6.0",
50
+ "@tanstack/react-query": "5.108.0",
51
+ "@types/react": "19.3.0",
52
+ "antd": "6.7.1",
53
+ "react": "19.3.1",
54
+ "react-dom": "19.3.1"
55
+ },
56
+ "peerDependencies": {
57
+ "@bieberkit/admin-antd": "^0.6.0",
58
+ "@bieberkit/admin-core": "^0.6.0",
59
+ "@tanstack/react-query": "^5.108.0",
60
+ "antd": "^6.0.0",
61
+ "react": "^19.0.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "@bieberkit/admin-antd": {
65
+ "optional": true
66
+ },
67
+ "@bieberkit/admin-core": {
68
+ "optional": true
69
+ },
70
+ "@tanstack/react-query": {
71
+ "optional": true
72
+ },
73
+ "antd": {
74
+ "optional": true
75
+ },
76
+ "react": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "engines": {
81
+ "node": ">=24.12"
82
+ },
83
+ "bieberkit": {
84
+ "core": "*",
85
+ "dialects": [
86
+ "mysql",
87
+ "postgres",
88
+ "sqlite"
89
+ ],
90
+ "requires": {},
91
+ "conflicts": [],
92
+ "env": [],
93
+ "tables": [
94
+ "bk_site_redirects"
95
+ ],
96
+ "routes": [
97
+ "DELETE /api/v1/redirects/rules",
98
+ "GET /api/v1/redirects/lookup",
99
+ "GET /api/v1/redirects/rules",
100
+ "PUT /api/v1/redirects/rules"
101
+ ],
102
+ "permissions": [
103
+ "redirects.manage",
104
+ "redirects.read"
105
+ ],
106
+ "admin": []
107
+ },
108
+ "scripts": {
109
+ "build": "tsdown && tsdown -c tsdown.admin.config.ts && node --conditions=@bieberkit/source ../../tools/plugin-manifests.ts --write --plugin .",
110
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p src/admin/tsconfig.json"
18
111
  }
19
112
  }