@octarq/plugin-links 0.0.0-stage → 0.1.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.
@@ -0,0 +1,462 @@
1
+ import {
2
+ Alert,
3
+ Badge,
4
+ Empty,
5
+ ScreenWrap,
6
+ PageHeader,
7
+ Panel,
8
+ GlassCard,
9
+ Button,
10
+ Input,
11
+ Table,
12
+ THead,
13
+ TBody,
14
+ TR,
15
+ TH,
16
+ TabBar,
17
+ TableError,
18
+ confirmDialog,
19
+ toast,
20
+ useTranslation,
21
+ roleSatisfies,
22
+ useCurrentRole,
23
+ usePluginGate,
24
+ ListSkeleton,
25
+ } from "@octarq/plugin-sdk";
26
+ import { useEffect, useMemo, useState } from "react";
27
+ import { useSearchParams, NavLink } from "react-router-dom";
28
+ import { api, linksApi, Link, Domain, effectiveLinkHosts } from "../api";
29
+ import { AlertCircle, Link2, Search, Settings, Plus, Activity, ShieldCheck, AlertTriangle, Blocks } from "lucide-react";
30
+ import { parseLinksFilter, buildLinksFilterQuery } from "../filters";
31
+ import { LinkTableRow } from "./LinkTableRow";
32
+ import { LinkModals } from "./LinkModals";
33
+
34
+ export const SYSTEM_RESERVED_SLUGS = [
35
+ "admin",
36
+ "api",
37
+ "app",
38
+ "assets",
39
+ "auth",
40
+ "dashboard",
41
+ "docs",
42
+ "healthz",
43
+ "help",
44
+ "instance",
45
+ "login",
46
+ "logout",
47
+ "portal",
48
+ "settings",
49
+ "static",
50
+ "status",
51
+ "webhook",
52
+ ];
53
+
54
+ export default function LinksPage() {
55
+ const { role, isInstanceAdmin } = useCurrentRole();
56
+ const canDeleteLink = roleSatisfies("admin", role, isInstanceAdmin);
57
+ const [links, setLinks] = useState<Link[]>([]);
58
+ const [domains, setDomains] = useState<Domain[]>([]);
59
+ const [tab, setTab] = useState<"links" | "anomalies" | "reserved">("links");
60
+
61
+ const [searchParams, setSearchParams] = useSearchParams();
62
+ const { q, archived } = useMemo(() => parseLinksFilter(searchParams), [searchParams]);
63
+ const [searchInput, setSearchInput] = useState(q);
64
+
65
+ useEffect(() => {
66
+ setSearchInput(q);
67
+ }, [q]);
68
+
69
+ useEffect(() => {
70
+ const timer = setTimeout(() => {
71
+ if (searchInput !== q) {
72
+ setSearchParams(
73
+ (prev) => buildLinksFilterQuery({ q: searchInput, archived }, prev),
74
+ { replace: true },
75
+ );
76
+ }
77
+ }, 250);
78
+ return () => clearTimeout(timer);
79
+ }, [searchInput, archived, q, setSearchParams]);
80
+
81
+ const [createOpen, setCreateOpen] = useState(false);
82
+ const [editingLink, setEditingLink] = useState<Link | null>(null);
83
+ const [analyticsLink, setAnalyticsLink] = useState<Link | null>(null);
84
+ const [qrLink, setQrLink] = useState<Link | null>(null);
85
+
86
+ const [page, setPage] = useState(0);
87
+ const [hasMore, setHasMore] = useState(true);
88
+ const [loading, setLoading] = useState(false);
89
+ const [error, setError] = useState<{ detail?: string } | null>(null);
90
+ const [copiedId, setCopiedId] = useState<number | null>(null);
91
+ const { t } = useTranslation();
92
+ const pluginGate = usePluginGate();
93
+
94
+ useEffect(() => {
95
+ if (searchParams.get("create") === "1") {
96
+ setCreateOpen(true);
97
+ setSearchParams(
98
+ (prev) => {
99
+ const next = new URLSearchParams(prev);
100
+ next.delete("create");
101
+ return next;
102
+ },
103
+ { replace: true },
104
+ );
105
+ }
106
+ }, [searchParams, setSearchParams]);
107
+
108
+ const linkHostOptions = Array.from(new Set(domains.flatMap(effectiveLinkHosts)));
109
+
110
+ async function loadMore(reset = false) {
111
+ if (loading || (!hasMore && !reset)) return;
112
+ setLoading(true);
113
+ if (reset) setError(null);
114
+ try {
115
+ const limit = 50;
116
+ const offset = reset ? 0 : page * limit;
117
+ const res = await linksApi.links({ q, archived, limit, offset });
118
+ if (res.length < limit) setHasMore(false);
119
+ else setHasMore(true);
120
+
121
+ setLinks((prev) => (reset ? res : [...prev, ...res]));
122
+ setPage(reset ? 1 : page + 1);
123
+ setError(null);
124
+ } catch (e: unknown) {
125
+ const err = e as { status?: number; message?: string };
126
+ if (err.status === 404 || err.status === 402) {
127
+ pluginGate.degrade(err.status);
128
+ return;
129
+ }
130
+ // Everything else used to be swallowed: the first page rendered the
131
+ // "no links yet" empty state over a 500, and a failed next page looked
132
+ // like the end of the list.
133
+ setError({ detail: err.status ? `HTTP ${err.status}` : err.message });
134
+ } finally {
135
+ setLoading(false);
136
+ }
137
+ }
138
+
139
+ useEffect(() => {
140
+ loadMore(true);
141
+ }, [q, archived]);
142
+
143
+ useEffect(() => {
144
+ api.domains().then(setDomains).catch(() => {});
145
+ }, []);
146
+
147
+ const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
148
+ const bottom =
149
+ e.currentTarget.scrollHeight - e.currentTarget.scrollTop <=
150
+ e.currentTarget.clientHeight + 100;
151
+ if (bottom) loadMore();
152
+ };
153
+
154
+ function linkURL(l: Link) {
155
+ return l.host ? `https://${l.host}/${l.slug}` : `${location.origin}/${l.slug}`;
156
+ }
157
+
158
+ const copy = (l: Link) => {
159
+ navigator.clipboard.writeText(linkURL(l));
160
+ setCopiedId(l.id);
161
+ setTimeout(() => setCopiedId(null), 2000);
162
+ };
163
+
164
+ const toggleArchive = async (l: Link) => {
165
+ try {
166
+ await linksApi.updateLink(l.id, { archived: !l.archived });
167
+ loadMore(true);
168
+ } catch {
169
+ // A rejected mutation used to bubble out of the click handler as an
170
+ // unhandled rejection, leaving the row unchanged with no feedback.
171
+ toast.error(t("links.actionFailed"));
172
+ }
173
+ };
174
+
175
+ const handleDelete = async (l: Link) => {
176
+ if (!(await confirmDialog(t("links.confirmDelete", { slug: l.slug })))) return;
177
+ try {
178
+ await linksApi.deleteLink(l.id);
179
+ loadMore(true);
180
+ } catch {
181
+ toast.error(t("links.actionFailed"));
182
+ }
183
+ };
184
+
185
+ // The empty state below carries the same action. Two primary buttons that do
186
+ // the same thing on one screen split attention, so the header keeps it only
187
+ // when the empty state cannot show it: another tab, a load failure, a search
188
+ // with no hits, or a list still loading.
189
+ const emptyStateOwnsCreate = tab === "links" && !error && !loading && links.length === 0 && !q;
190
+
191
+ return (
192
+ <ScreenWrap>
193
+ <PageHeader
194
+ title={t("links.pageTitle")}
195
+ description={t("links.pageDescription")}
196
+ action={
197
+ emptyStateOwnsCreate ? undefined : (
198
+ <Button variant="primary" size="sm" onClick={() => setCreateOpen(true)}>
199
+ <Plus className="h-3.5 w-3.5" />
200
+ {t("links.newLink")}
201
+ </Button>
202
+ )
203
+ }
204
+ />
205
+
206
+ <TabBar
207
+ className="mb-6"
208
+ value={tab}
209
+ onValueChange={(v) => setTab(v as "links" | "anomalies" | "reserved")}
210
+ items={[
211
+ { value: "links", label: t("links.tabLinks", "Links"), testId: "tab-links" },
212
+ { value: "anomalies", label: t("links.tabAnomalies", "Anomaly Monitoring"), testId: "tab-anomalies" },
213
+ { value: "reserved", label: t("links.tabReserved", "Reserved Words"), testId: "tab-reserved" },
214
+ ]}
215
+ />
216
+
217
+ {tab === "links" && (
218
+ <div className="space-y-4" data-testid="links-projection-view">
219
+ {/* Search, Filter Tabs & Batch Toolbar */}
220
+ <div className="flex flex-wrap items-center justify-between gap-3">
221
+ <div className="flex max-w-sm flex-1 items-center gap-2">
222
+ <div className="relative w-full">
223
+ <Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
224
+ <Input
225
+ className="!pl-10"
226
+ aria-label={t("links.searchPlaceholder")}
227
+ placeholder={t("links.searchPlaceholder")}
228
+ value={searchInput}
229
+ onChange={(e) => setSearchInput(e.target.value)}
230
+ />
231
+ </div>
232
+ {searchInput && (
233
+ <Button variant="ghost" size="sm" onClick={() => setSearchInput("")}>
234
+ {t("links.emptyFilteredAction")}
235
+ </Button>
236
+ )}
237
+ </div>
238
+
239
+ <div className="flex items-center gap-2">
240
+ <TabBar
241
+ size="sm"
242
+ value={archived ? "archived" : "active"}
243
+ onValueChange={(v) =>
244
+ setSearchParams((prev) => buildLinksFilterQuery({ q, archived: v === "archived" }, prev), { replace: true })
245
+ }
246
+ items={[
247
+ { value: "active", label: t("links.active") },
248
+ { value: "archived", label: t("links.archived") },
249
+ ]}
250
+ />
251
+ </div>
252
+ </div>
253
+
254
+ {/* Links Data Table / Empty Views */}
255
+ {error && links.length === 0 ? (
256
+ <TableError errorText={error.detail} onRetry={() => loadMore(true)} />
257
+ ) : loading && links.length === 0 ? (
258
+ <ListSkeleton rows={8} ariaLabel={t("links.loading")} />
259
+ ) : links.length === 0 ? (
260
+ q ? (
261
+ <GlassCard className="flex flex-col items-center gap-3 px-4 py-12 text-center">
262
+ <p className="text-sm text-muted-foreground">
263
+ {t("links.emptyFilteredReason")} <span className="font-mono text-foreground">{`“${q}”`}</span>
264
+ </p>
265
+ <Button
266
+ variant="ghost"
267
+ className="text-xs py-1.5"
268
+ onClick={() => setSearchParams((prev) => buildLinksFilterQuery({ q: "", archived: false }, prev), { replace: true })}
269
+ >
270
+ {t("links.emptyFilteredAction")}
271
+ </Button>
272
+ </GlassCard>
273
+ ) : (
274
+ <Empty
275
+ reason={t("links.emptyNoLinksReason")}
276
+ detail={
277
+ linkHostOptions.length > 0 ? (
278
+ <>
279
+ {t("links.emptyNoLinksDetailPre")} <span className="font-mono">{`“${linkHostOptions.join(", ")}”`}</span>
280
+ </>
281
+ ) : (
282
+ <>
283
+ {t("links.emptyNoHostDetailPre")} <span className="font-mono">{`“${window.location.origin}”`}</span>
284
+ </>
285
+ )
286
+ }
287
+ action={
288
+ <Button variant="primary" className="mt-1 text-xs py-1.5" onClick={() => setCreateOpen(true)}>
289
+ {t("links.newLink")}
290
+ </Button>
291
+ }
292
+ >
293
+ <Link2 className="h-8 w-8 text-muted-foreground mb-1" />
294
+ </Empty>
295
+ )
296
+ ) : (
297
+ <>
298
+ <GlassCard className="overflow-hidden border border-border">
299
+ <div className="overflow-x-auto max-h-[700px] overflow-y-auto" onScroll={handleScroll}>
300
+ <Table>
301
+ <THead className="border-b border-border bg-well">
302
+ <TR>
303
+ <TH className="min-w-[200px]">{t("links.pageTitle")}</TH>
304
+ <TH className="min-w-[240px]">{t("links.targetDestination")}</TH>
305
+ <TH className="w-24 text-center">{t("links.totalClicks")}</TH>
306
+ <TH className="w-24 text-center">{t("links.active")}</TH>
307
+ <TH className="text-right w-44" />
308
+ </TR>
309
+ </THead>
310
+ <TBody className="divide-y divide-border">
311
+ {links.map((l) => (
312
+ <LinkTableRow
313
+ key={l.id}
314
+ link={l}
315
+ isCopied={copiedId === l.id}
316
+ canDeleteLink={canDeleteLink}
317
+ onCopy={copy}
318
+ onAnalytics={setAnalyticsLink}
319
+ onQr={setQrLink}
320
+ onEdit={setEditingLink}
321
+ onToggleArchive={toggleArchive}
322
+ onDelete={handleDelete}
323
+ linkURL={linkURL}
324
+ />
325
+ ))}
326
+ </TBody>
327
+ </Table>
328
+ {loading && <div className="p-3 text-center text-xs text-muted-foreground">{t("links.loading")}</div>}
329
+ </div>
330
+ </GlassCard>
331
+ {error && (
332
+ <Alert
333
+ variant="danger"
334
+ icon={<AlertCircle className="h-4 w-4" />}
335
+ actions={
336
+ <Button variant="outline" size="sm" onClick={() => loadMore()}>
337
+ {t("proTable.retry")}
338
+ </Button>
339
+ }
340
+ >
341
+ {t("proTable.errorTitle")}
342
+ {error.detail ? ` (${error.detail})` : ""}
343
+ </Alert>
344
+ )}
345
+ </>
346
+ )}
347
+ </div>
348
+ )}
349
+
350
+ {tab === "anomalies" && (
351
+ <div className="space-y-6" data-testid="anomalies-projection-view">
352
+ {/* Overview Stat Cards */}
353
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
354
+ <GlassCard className="p-4 space-y-1.5">
355
+ <div className="flex items-center justify-between">
356
+ <span className="text-xs text-muted-foreground">{t("links.anomalyTraffic", "Traffic Anomalies")}</span>
357
+ <Activity className="h-4 w-4 text-success-fg" />
358
+ </div>
359
+ <div className="text-xl font-semibold text-foreground">0</div>
360
+ <div className="text-[11px] text-success-fg font-medium">{t("links.anomalyHealthySpikes", "Healthy · No spikes")}</div>
361
+ </GlassCard>
362
+
363
+ <GlassCard className="p-4 space-y-1.5">
364
+ <div className="flex items-center justify-between">
365
+ <span className="text-xs text-muted-foreground">{t("links.anomalyBot", "Bot Filtering")}</span>
366
+ <ShieldCheck className="h-4 w-4 text-accent-fg" />
367
+ </div>
368
+ <div className="text-xl font-semibold text-foreground">{t("links.anomalyActive", "Active")}</div>
369
+ <div className="text-[11px] text-muted-foreground">{t("links.anomalyRateLimitActive", "Rate limiting active")}</div>
370
+ </GlassCard>
371
+
372
+ <GlassCard className="p-4 space-y-1.5">
373
+ <div className="flex items-center justify-between">
374
+ <span className="text-xs text-muted-foreground">{t("links.anomalyLatency", "Redirect Latency")}</span>
375
+ <Activity className="h-4 w-4 text-info-fg" />
376
+ </div>
377
+ <div className="text-xl font-semibold text-foreground">{t("links.anomalyLatencyValue", "< 35ms")}</div>
378
+ <div className="text-[11px] text-success-fg font-medium">{t("links.anomalyP99Latency", "p99 edge redirect")}</div>
379
+ </GlassCard>
380
+
381
+ <GlassCard className="p-4 space-y-1.5">
382
+ <div className="flex items-center justify-between">
383
+ <span className="text-xs text-muted-foreground">{t("links.anomalyLoops", "Redirect Loops")}</span>
384
+ <AlertTriangle className="h-4 w-4 text-warning-fg" />
385
+ </div>
386
+ <div className="text-xl font-semibold text-foreground">0</div>
387
+ <div className="text-[11px] text-muted-foreground">{t("links.anomalyLoopClear", "Loop detector clear")}</div>
388
+ </GlassCard>
389
+ </div>
390
+
391
+ {/* Anomaly Real-Time Monitor Card */}
392
+ <Panel
393
+ title={t("links.tabAnomalies", "Anomaly Monitoring")}
394
+ description={t("links.anomalyDesc", "Real-time monitors track 404 floods, redirect loops, and abnormal traffic spikes.")}
395
+ action={<Badge variant="success" className="text-xs">{t("links.anomalyOperational", "Operational")}</Badge>}
396
+ >
397
+
398
+ <div className="py-8 text-center space-y-2">
399
+ <ShieldCheck className="h-10 w-10 text-success-fg mx-auto opacity-80" />
400
+ <h4 className="text-sm font-medium text-foreground">{t("links.anomalyClean", "No anomalies detected across short links in the last 24 hours.")}</h4>
401
+ <p className="text-xs text-muted-foreground max-w-md mx-auto">
402
+ {t("links.anomalyDesc", "Real-time monitors track 404 floods, redirect loops, and abnormal traffic spikes.")}
403
+ </p>
404
+ </div>
405
+ </Panel>
406
+ </div>
407
+ )}
408
+
409
+ {tab === "reserved" && (
410
+ <div className="space-y-6" data-testid="reserved-projection-view">
411
+ {/* Guidance Banner */}
412
+ <div className="flex items-center justify-between p-3 rounded-lg border border-primary/20 bg-accent-soft text-xs text-foreground">
413
+ <div className="flex items-center gap-2">
414
+ <Blocks className="h-4 w-4 text-accent-fg shrink-0" />
415
+ <span>{t("links.reservedInstanceNotice", "Configure custom instance-level reserved slugs in Instance Settings.")}</span>
416
+ </div>
417
+ <NavLink
418
+ to="/instance/settings"
419
+ className="text-accent-fg hover:underline font-medium text-xs whitespace-nowrap ml-3"
420
+ >
421
+ {t("links.reservedInstanceAction", "Configure Instance Settings →")}
422
+ </NavLink>
423
+ </div>
424
+
425
+ {/* Reserved Words GlassCard */}
426
+ <Panel
427
+ title={t("links.reservedTitle", "System Reserved Words")}
428
+ description={t("links.reservedDesc", "Reserved words prevent short links from colliding with system routes and administrative endpoints.")}
429
+ >
430
+
431
+ <div className="flex flex-wrap gap-2 pt-2">
432
+ {SYSTEM_RESERVED_SLUGS.map((slug) => (
433
+ <span
434
+ key={slug}
435
+ className="inline-flex items-center px-2.5 py-1 rounded-md text-xs font-mono bg-well border border-border text-foreground"
436
+ >
437
+ /{slug}
438
+ </span>
439
+ ))}
440
+ </div>
441
+ </Panel>
442
+ </div>
443
+ )}
444
+
445
+ <LinkModals
446
+ createOpen={createOpen}
447
+ editingLink={editingLink}
448
+ analyticsLink={analyticsLink}
449
+ qrLink={qrLink}
450
+ linkHostOptions={linkHostOptions}
451
+ copiedId={copiedId}
452
+ onCloseCreate={() => setCreateOpen(false)}
453
+ onCloseEdit={() => setEditingLink(null)}
454
+ onCloseAnalytics={() => setAnalyticsLink(null)}
455
+ onCloseQr={() => setQrLink(null)}
456
+ onRefreshLinks={() => loadMore(true)}
457
+ onCopyQrLink={copy}
458
+ linkURL={linkURL}
459
+ />
460
+ </ScreenWrap>
461
+ );
462
+ }
@@ -0,0 +1,102 @@
1
+ // @vitest-environment happy-dom
2
+ import { describe, it, expect, vi, beforeEach } from "vitest";
3
+ import { cleanup, render, screen, waitFor, fireEvent } from "@testing-library/react";
4
+ import { MemoryRouter } from "react-router-dom";
5
+ import { registerUIPlugin, resetRegistry, I18nProvider } from "@octarq/plugin-sdk";
6
+ import linksPlugin from "../index";
7
+ import LinksPage from "./index";
8
+ import { Link } from "../api";
9
+
10
+ const mockLinksWithPassword: Link[] = [
11
+ {
12
+ id: 1,
13
+ host: "link.acme.com",
14
+ slug: "pass-protected",
15
+ title: "Protected Link",
16
+ tags: "secret",
17
+ target: "https://acme.com/secret",
18
+ note: "",
19
+ expiresAt: null,
20
+ expiredUrl: "",
21
+ clickLimit: 0,
22
+ archived: false,
23
+ enabled: true,
24
+ clicks: 5,
25
+ password: "SecretCode123",
26
+ hasPassword: true,
27
+ routingRules: [],
28
+ createdAt: "2026-06-01T00:00:00Z",
29
+ },
30
+ ];
31
+
32
+ function jsonResponse(body: unknown, status = 200) {
33
+ return {
34
+ ok: status >= 200 && status < 300,
35
+ status,
36
+ json: async () => body,
37
+ headers: { get: (name: string) => (name === "content-type" ? "application/json" : null) },
38
+ };
39
+ }
40
+
41
+ describe("Link password plaintext display and edit form", () => {
42
+ let updatedPayload: any = null;
43
+
44
+ beforeEach(() => {
45
+ cleanup();
46
+ resetRegistry();
47
+ registerUIPlugin(linksPlugin);
48
+ updatedPayload = null;
49
+
50
+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
51
+ const method = (init?.method ?? "GET").toUpperCase();
52
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
53
+ const urlObj = new URL(rawUrl, "http://localhost");
54
+ const path = urlObj.pathname;
55
+ if (method === "GET" && path === "/api/links") return jsonResponse(mockLinksWithPassword);
56
+ if (method === "GET" && path === "/api/domains") return jsonResponse([]);
57
+ if (method === "PUT" && path === "/api/links/1") {
58
+ updatedPayload = JSON.parse((init?.body as string) || "{}");
59
+ return jsonResponse({ ...mockLinksWithPassword[0], ...updatedPayload });
60
+ }
61
+ throw new Error(`unexpected request in test: ${method} ${rawUrl}`);
62
+ });
63
+ vi.stubGlobal("fetch", fetchMock);
64
+ });
65
+
66
+ it("displays password in plaintext on the link badge and pre-fills the plaintext input in edit form", async () => {
67
+ render(
68
+ <MemoryRouter initialEntries={["/links"]}>
69
+ <I18nProvider>
70
+ <LinksPage />
71
+ </I18nProvider>
72
+ </MemoryRouter>
73
+ );
74
+
75
+ // 1. Password should be visible in plain text on the badge in the list
76
+ await waitFor(() => {
77
+ expect(screen.getByText("SecretCode123")).toBeDefined();
78
+ });
79
+
80
+ // 2. Click Edit Link to open the editor modal
81
+ const editBtn = screen.getByTitle("Edit link");
82
+ fireEvent.click(editBtn);
83
+
84
+ await waitFor(() => {
85
+ expect(screen.getByText("Edit link — Protected Link")).toBeDefined();
86
+ });
87
+
88
+ // 3. The password input field should be type="text" and contain "SecretCode123"
89
+ const passwordInput = screen.getByDisplayValue("SecretCode123") as HTMLInputElement;
90
+ expect(passwordInput).toBeDefined();
91
+ expect(passwordInput.type).toBe("text");
92
+
93
+ // 4. Save without touching password -> payload should retain the password and not silently clear it
94
+ const saveBtn = screen.getByText("Save link");
95
+ fireEvent.click(saveBtn);
96
+
97
+ await waitFor(() => {
98
+ expect(updatedPayload).not.toBeNull();
99
+ });
100
+ expect(updatedPayload.password).toBe("SecretCode123");
101
+ });
102
+ });