@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,592 @@
1
+ // @vitest-environment happy-dom
2
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
3
+ import { cleanup, render, screen, waitFor, fireEvent } from "@testing-library/react";
4
+ import { registerUIPlugin, resetRegistry, I18nProvider } from "@octarq/plugin-sdk";
5
+ import linksPlugin from "../index";
6
+ import { LinkEditorForm } from "./LinkEditorForm";
7
+ import { Link } from "../api";
8
+
9
+ function jsonResponse(body: unknown, status = 200) {
10
+ return {
11
+ ok: status >= 200 && status < 300,
12
+ status,
13
+ json: async () => body,
14
+ headers: { get: (name: string) => (name === "content-type" ? "application/json" : null) },
15
+ };
16
+ }
17
+
18
+ const existingMockLink: Link = {
19
+ id: 101,
20
+ host: "link.acme.com",
21
+ slug: "spring-promo",
22
+ title: "Spring Promo 2026",
23
+ tags: "promo, spring, sale",
24
+ target: "https://acme.com/spring-sale",
25
+ note: "Internal spring sale campaign note",
26
+ expiresAt: "2026-12-31T23:59:00.000Z",
27
+ expiredUrl: "https://acme.com/expired-sale",
28
+ clickLimit: 500,
29
+ archived: false,
30
+ enabled: true,
31
+ clicks: 42,
32
+ hasPassword: true,
33
+ routingRules: [
34
+ { type: "device", match: "mobile", target: "https://acme.com/mobile-sale" },
35
+ { type: "split", weight: 50, target: "https://acme.com/spring-b" },
36
+ ],
37
+ createdAt: "2026-03-01T00:00:00Z",
38
+ };
39
+
40
+ describe("LinkEditorForm", () => {
41
+ let fetchMock: ReturnType<typeof vi.fn>;
42
+
43
+ beforeEach(() => {
44
+ cleanup();
45
+ resetRegistry();
46
+ registerUIPlugin(linksPlugin);
47
+
48
+ fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
49
+ const method = (init?.method ?? "GET").toUpperCase();
50
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
51
+ const urlObj = new URL(rawUrl, "http://localhost");
52
+ const path = urlObj.pathname;
53
+
54
+ if (method === "GET" && path === "/api/ai/assist/status") {
55
+ return jsonResponse({ configured: true, provider: "openai" });
56
+ }
57
+ if (method === "POST" && path === "/api/ai/assist/suggest-slug") {
58
+ return jsonResponse({ slugs: ["ai-suggest-1", "ai-suggest-2"] });
59
+ }
60
+ if (method === "GET" && path === "/api/links/metadata") {
61
+ return jsonResponse({ title: "Fetched Page Title", description: "Desc", favicon: "" });
62
+ }
63
+ if (method === "GET" && path === "/api/links/capabilities") {
64
+ return jsonResponse({ geoReady: false, mode: "unavailable" });
65
+ }
66
+ if (method === "POST" && path === "/api/links") {
67
+ const body = init?.body ? JSON.parse(init.body as string) : {};
68
+ return jsonResponse({ id: 200, ...body, clicks: 0, hasPassword: !!body.password, createdAt: new Date().toISOString() });
69
+ }
70
+ if (method === "PUT" && path === "/api/links/101") {
71
+ const body = init?.body ? JSON.parse(init.body as string) : {};
72
+ return jsonResponse({ ...existingMockLink, ...body });
73
+ }
74
+
75
+ throw new Error(`Unhandled fetch in test: ${method} ${rawUrl}`);
76
+ });
77
+ vi.stubGlobal("fetch", fetchMock);
78
+ });
79
+
80
+ afterEach(() => {
81
+ cleanup();
82
+ vi.restoreAllMocks();
83
+ });
84
+
85
+ it("renders new link form with initial state and required target validation", async () => {
86
+ const onCancel = vi.fn();
87
+ const onSaved = vi.fn();
88
+
89
+ render(
90
+ <I18nProvider>
91
+ <LinkEditorForm link={null} hosts={["link.acme.com", "go.acme.com"]} onCancel={onCancel} onSaved={onSaved} />
92
+ </I18nProvider>
93
+ );
94
+
95
+ // Verify fields are rendered
96
+ const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz");
97
+ expect(targetInput).toBeDefined();
98
+
99
+ const slugInput = screen.getByPlaceholderText("e.g. promo2026");
100
+ expect(slugInput).toBeDefined();
101
+
102
+ // Save button should be disabled when target is empty
103
+ const saveBtn = screen.getByRole("button", { name: "Save link" });
104
+ expect((saveBtn as HTMLButtonElement).disabled).toBe(true);
105
+
106
+ // Cancel button works
107
+ const cancelBtn = screen.getByRole("button", { name: "Cancel" });
108
+ fireEvent.click(cancelBtn);
109
+ expect(onCancel).toHaveBeenCalledTimes(1);
110
+
111
+ // Typing target enables save button
112
+ fireEvent.change(targetInput, { target: { value: "https://acme.com/new-product" } });
113
+ expect((saveBtn as HTMLButtonElement).disabled).toBe(false);
114
+ });
115
+
116
+ it("handles AI slug suggestions and populates slug input", async () => {
117
+ render(
118
+ <I18nProvider>
119
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
120
+ </I18nProvider>
121
+ );
122
+
123
+ // Wait for AI assist status to load
124
+ await waitFor(() => {
125
+ expect(screen.getByRole("button", { name: "AI suggest" })).toBeDefined();
126
+ });
127
+
128
+ const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz");
129
+ fireEvent.change(targetInput, { target: { value: "https://acme.com/awesome-tool" } });
130
+
131
+ const aiBtn = screen.getByRole("button", { name: "AI suggest" });
132
+ fireEvent.click(aiBtn);
133
+
134
+ await waitFor(() => {
135
+ expect(screen.getByText("ai-suggest-1")).toBeDefined();
136
+ expect(screen.getByText("ai-suggest-2")).toBeDefined();
137
+ });
138
+
139
+ // Clicking a suggestion chip sets the slug
140
+ fireEvent.click(screen.getByText("ai-suggest-1"));
141
+ const slugInput = screen.getByPlaceholderText("e.g. promo2026") as HTMLInputElement;
142
+ expect(slugInput.value).toBe("ai-suggest-1");
143
+ });
144
+
145
+ it("handles AI suggest error gracefully", async () => {
146
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
147
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
148
+ const urlObj = new URL(rawUrl, "http://localhost");
149
+ if (urlObj.pathname === "/api/ai/assist/status") {
150
+ return jsonResponse({ configured: true, provider: "openai" });
151
+ }
152
+ if (urlObj.pathname === "/api/ai/assist/suggest-slug") {
153
+ return jsonResponse({ message: "AI rate limit" }, 500);
154
+ }
155
+ throw new Error(`Unhandled fetch: ${rawUrl}`);
156
+ });
157
+
158
+ render(
159
+ <I18nProvider>
160
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
161
+ </I18nProvider>
162
+ );
163
+
164
+ await waitFor(() => {
165
+ expect(screen.getByRole("button", { name: "AI suggest" })).toBeDefined();
166
+ });
167
+
168
+ const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz");
169
+ fireEvent.change(targetInput, { target: { value: "https://acme.com/awesome-tool" } });
170
+
171
+ const aiBtn = screen.getByRole("button", { name: "AI suggest" });
172
+ fireEvent.click(aiBtn);
173
+
174
+ await waitFor(() => {
175
+ expect(screen.getByText("Could not generate AI suggestion. Try again.")).toBeDefined();
176
+ });
177
+ });
178
+
179
+ it("fetches page title metadata into title field", async () => {
180
+ render(
181
+ <I18nProvider>
182
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
183
+ </I18nProvider>
184
+ );
185
+
186
+ const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz");
187
+ fireEvent.change(targetInput, { target: { value: "https://acme.com/awesome-article" } });
188
+
189
+ const fetchBtn = screen.getByRole("button", { name: "Fetch" });
190
+ fireEvent.click(fetchBtn);
191
+
192
+ await waitFor(() => {
193
+ const titleInput = screen.getByPlaceholderText("Auto-populated title for page previews") as HTMLInputElement;
194
+ expect(titleInput.value).toBe("Fetched Page Title");
195
+ });
196
+ });
197
+
198
+ it("expands UTM builder and applies query parameters to destination URL", async () => {
199
+ render(
200
+ <I18nProvider>
201
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
202
+ </I18nProvider>
203
+ );
204
+
205
+ const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz") as HTMLTextAreaElement;
206
+ fireEvent.change(targetInput, { target: { value: "https://acme.com/landing" } });
207
+
208
+ // Open UTM builder
209
+ const utmBtn = screen.getByRole("button", { name: "UTM" });
210
+ fireEvent.click(utmBtn);
211
+
212
+ expect(screen.getByPlaceholderText("utm_source")).toBeDefined();
213
+ expect(screen.getByPlaceholderText("utm_medium")).toBeDefined();
214
+ expect(screen.getByPlaceholderText("utm_campaign")).toBeDefined();
215
+
216
+ fireEvent.change(screen.getByPlaceholderText("utm_source"), { target: { value: "newsletter" } });
217
+ fireEvent.change(screen.getByPlaceholderText("utm_medium"), { target: { value: "email" } });
218
+ fireEvent.change(screen.getByPlaceholderText("utm_campaign"), { target: { value: "fall2026" } });
219
+ fireEvent.change(screen.getByPlaceholderText("utm_term"), { target: { value: "discount" } });
220
+ fireEvent.change(screen.getByPlaceholderText("utm_content"), { target: { value: "header-link" } });
221
+
222
+ // Apply UTM
223
+ const applyBtn = screen.getByRole("button", { name: "Apply UTM parameters" });
224
+ fireEvent.click(applyBtn);
225
+
226
+ expect(targetInput.value).toBe(
227
+ "https://acme.com/landing?utm_source=newsletter&utm_medium=email&utm_campaign=fall2026&utm_term=discount&utm_content=header-link"
228
+ );
229
+ });
230
+
231
+ it("manages routing rules with add, type selection, match, target, and delete", async () => {
232
+ render(
233
+ <I18nProvider>
234
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
235
+ </I18nProvider>
236
+ );
237
+
238
+ // Add rule
239
+ const addRuleBtn = screen.getByRole("button", { name: "Add rule" });
240
+ fireEvent.click(addRuleBtn);
241
+
242
+ // Initial added rule is split with weight 50
243
+ expect(screen.getByPlaceholderText("Target URL")).toBeDefined();
244
+ expect(screen.getByText(/Remaining to control: 50%/)).toBeDefined();
245
+
246
+ const ruleTarget = screen.getByPlaceholderText("Target URL");
247
+ fireEvent.change(ruleTarget, { target: { value: "https://acme.com/split-target" } });
248
+
249
+ // Add a second rule
250
+ fireEvent.click(addRuleBtn);
251
+ const ruleTargets = screen.getAllByPlaceholderText("Target URL");
252
+ expect(ruleTargets.length).toBe(2);
253
+
254
+ // Delete first rule
255
+ const deleteButtons = screen.getAllByRole("button").filter(b => b.querySelector("svg.lucide-trash-2"));
256
+ expect(deleteButtons.length).toBe(2);
257
+ fireEvent.click(deleteButtons[0]);
258
+
259
+ // Only one rule remains
260
+ expect(screen.getAllByPlaceholderText("Target URL").length).toBe(1);
261
+ });
262
+
263
+ it("submits a new link with full configuration and invokes onSaved", async () => {
264
+ let capturedPayload: any = null;
265
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
266
+ const method = (init?.method ?? "GET").toUpperCase();
267
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
268
+ const urlObj = new URL(rawUrl, "http://localhost");
269
+
270
+ if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
271
+ return jsonResponse({ configured: false, provider: "" });
272
+ }
273
+ if (method === "POST" && urlObj.pathname === "/api/links") {
274
+ capturedPayload = JSON.parse(init?.body as string);
275
+ return jsonResponse({ id: 55, ...capturedPayload });
276
+ }
277
+ throw new Error(`Unexpected request: ${method} ${rawUrl}`);
278
+ });
279
+
280
+ const onSaved = vi.fn();
281
+
282
+ render(
283
+ <I18nProvider>
284
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={onSaved} />
285
+ </I18nProvider>
286
+ );
287
+
288
+ // Fill target
289
+ fireEvent.change(screen.getByPlaceholderText("https://example.com/blog-post-xyz"), {
290
+ target: { value: "https://acme.com/special-promo" },
291
+ });
292
+
293
+ // Fill slug
294
+ fireEvent.change(screen.getByPlaceholderText("e.g. promo2026"), {
295
+ target: { value: "special-slug" },
296
+ });
297
+
298
+ // Fill title
299
+ fireEvent.change(screen.getByPlaceholderText("Auto-populated title for page previews"), {
300
+ target: { value: "Special Title" },
301
+ });
302
+
303
+ // Fill tags
304
+ fireEvent.change(screen.getByPlaceholderText("e.g. q3-ads, product-hunt"), {
305
+ target: { value: "vip, promo" },
306
+ });
307
+
308
+ // Fill note
309
+ fireEvent.change(screen.getByPlaceholderText("Notes visible only to team members"), {
310
+ target: { value: "Campaign Q4" },
311
+ });
312
+
313
+ // Fill password
314
+ fireEvent.change(screen.getByPlaceholderText("e.g. 123456"), {
315
+ target: { value: "supersecret" },
316
+ });
317
+
318
+ // Fill redirectUrl after expiry
319
+ fireEvent.change(screen.getByPlaceholderText("e.g. https://my-site.com/expired"), {
320
+ target: { value: "https://acme.com/expired" },
321
+ });
322
+
323
+ // Submit
324
+ const saveBtn = screen.getByRole("button", { name: "Save link" });
325
+ fireEvent.click(saveBtn);
326
+
327
+ await waitFor(() => {
328
+ expect(onSaved).toHaveBeenCalledTimes(1);
329
+ });
330
+
331
+ expect(capturedPayload).toMatchObject({
332
+ target: "https://acme.com/special-promo",
333
+ slug: "special-slug",
334
+ host: "link.acme.com",
335
+ title: "Special Title",
336
+ tags: "vip, promo",
337
+ note: "Campaign Q4",
338
+ password: "supersecret",
339
+ expiredUrl: "https://acme.com/expired",
340
+ enabled: true,
341
+ });
342
+ });
343
+
344
+ it("pre-populates existing link data in edit mode and sends PUT request", async () => {
345
+ let putPayload: any = null;
346
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
347
+ const method = (init?.method ?? "GET").toUpperCase();
348
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
349
+ const urlObj = new URL(rawUrl, "http://localhost");
350
+
351
+ if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
352
+ return jsonResponse({ configured: false, provider: "" });
353
+ }
354
+ if (method === "PUT" && urlObj.pathname === "/api/links/101") {
355
+ putPayload = JSON.parse(init?.body as string);
356
+ return jsonResponse({ ...existingMockLink, ...putPayload });
357
+ }
358
+ throw new Error(`Unexpected request: ${method} ${rawUrl}`);
359
+ });
360
+
361
+ const onSaved = vi.fn();
362
+
363
+ render(
364
+ <I18nProvider>
365
+ <LinkEditorForm
366
+ link={existingMockLink}
367
+ hosts={["link.acme.com", "other.acme.com"]}
368
+ onCancel={vi.fn()}
369
+ onSaved={onSaved}
370
+ />
371
+ </I18nProvider>
372
+ );
373
+
374
+ // Verify existing fields are filled
375
+ const targetInput = screen.getByPlaceholderText("https://example.com/blog-post-xyz") as HTMLTextAreaElement;
376
+ expect(targetInput.value).toBe("https://acme.com/spring-sale");
377
+
378
+ const slugInput = screen.getByPlaceholderText("e.g. promo2026") as HTMLInputElement;
379
+ expect(slugInput.value).toBe("spring-promo");
380
+
381
+ const titleInput = screen.getByPlaceholderText("Auto-populated title for page previews") as HTMLInputElement;
382
+ expect(titleInput.value).toBe("Spring Promo 2026");
383
+
384
+ const tagsInput = screen.getByPlaceholderText("e.g. q3-ads, product-hunt") as HTMLInputElement;
385
+ expect(tagsInput.value).toBe("promo, spring, sale");
386
+
387
+ expect(screen.getByPlaceholderText("e.g. 123456")).toBeDefined();
388
+ expect(screen.getByText("Optional password check")).toBeDefined();
389
+
390
+ // Modify title and submit
391
+ fireEvent.change(titleInput, { target: { value: "Updated Spring Promo 2026" } });
392
+ const saveBtn = screen.getByRole("button", { name: "Save link" });
393
+ fireEvent.click(saveBtn);
394
+
395
+ await waitFor(() => {
396
+ expect(onSaved).toHaveBeenCalledTimes(1);
397
+ });
398
+
399
+ expect(putPayload.title).toBe("Updated Spring Promo 2026");
400
+ expect(putPayload.slug).toBe("spring-promo");
401
+ expect(putPayload.host).toBe("link.acme.com");
402
+ });
403
+
404
+ it("handles 400 host is required error with localized message", async () => {
405
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
406
+ const method = (init?.method ?? "GET").toUpperCase();
407
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
408
+ const urlObj = new URL(rawUrl, "http://localhost");
409
+
410
+ if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
411
+ return jsonResponse({ configured: false, provider: "" });
412
+ }
413
+ if (method === "POST" && urlObj.pathname === "/api/links") {
414
+ return jsonResponse({ message: "host is required on multi-tenant instance" }, 400);
415
+ }
416
+ throw new Error(`Unexpected request: ${method} ${rawUrl}`);
417
+ });
418
+
419
+ render(
420
+ <I18nProvider>
421
+ <LinkEditorForm link={null} hosts={[]} onCancel={vi.fn()} onSaved={vi.fn()} />
422
+ </I18nProvider>
423
+ );
424
+
425
+ fireEvent.change(screen.getByPlaceholderText("https://example.com/blog-post-xyz"), {
426
+ target: { value: "https://acme.com/test" },
427
+ });
428
+
429
+ fireEvent.click(screen.getByRole("button", { name: "Save link" }));
430
+
431
+ await waitFor(() => {
432
+ expect(screen.getByText("Host is required: pick a link host for this short link (this instance is multi-tenant)")).toBeDefined();
433
+ });
434
+ });
435
+
436
+ it("handles general API errors with FormError display", async () => {
437
+ fetchMock.mockImplementation(async (input: RequestInfo | URL, init?: RequestInit) => {
438
+ const method = (init?.method ?? "GET").toUpperCase();
439
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
440
+ const urlObj = new URL(rawUrl, "http://localhost");
441
+
442
+ if (method === "GET" && urlObj.pathname === "/api/ai/assist/status") {
443
+ return jsonResponse({ configured: false, provider: "" });
444
+ }
445
+ if (method === "POST" && urlObj.pathname === "/api/links") {
446
+ return jsonResponse({ message: "Slug 'custom' is already in use by another link" }, 409);
447
+ }
448
+ throw new Error(`Unexpected request: ${method} ${rawUrl}`);
449
+ });
450
+
451
+ render(
452
+ <I18nProvider>
453
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
454
+ </I18nProvider>
455
+ );
456
+
457
+ fireEvent.change(screen.getByPlaceholderText("https://example.com/blog-post-xyz"), {
458
+ target: { value: "https://acme.com/test" },
459
+ });
460
+
461
+ fireEvent.click(screen.getByRole("button", { name: "Save link" }));
462
+
463
+ await waitFor(() => {
464
+ expect(screen.getByText("Slug 'custom' is already in use by another link")).toBeDefined();
465
+ });
466
+ });
467
+
468
+ it("displays domain guidance alert when no custom domain configured and supports cancel navigation", async () => {
469
+ const onCancel = vi.fn();
470
+ render(
471
+ <I18nProvider>
472
+ <LinkEditorForm link={null} hosts={[]} onCancel={onCancel} onSaved={vi.fn()} />
473
+ </I18nProvider>
474
+ );
475
+
476
+ expect(screen.getByText("No custom domain configured.")).toBeDefined();
477
+ expect(
478
+ screen.getByText("Short links require a configured domain on this instance.")
479
+ ).toBeDefined();
480
+
481
+ const configBtn = screen.getByRole("button", { name: /Configure Domains/i });
482
+ expect(configBtn).toBeDefined();
483
+ fireEvent.click(configBtn);
484
+ expect(onCancel).toHaveBeenCalled();
485
+ });
486
+
487
+ it("does not display domain guidance alert when hosts are configured", () => {
488
+ render(
489
+ <I18nProvider>
490
+ <LinkEditorForm link={null} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
491
+ </I18nProvider>
492
+ );
493
+
494
+ expect(screen.queryByText("No custom domain configured.")).toBeNull();
495
+ });
496
+
497
+ it("displays GeoIP Active badge when geo rule exists and geoReady is true", async () => {
498
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
499
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
500
+ const urlObj = new URL(rawUrl, "http://localhost");
501
+ if (urlObj.pathname === "/api/links/capabilities") {
502
+ return jsonResponse({ geoReady: true, mode: "configured" });
503
+ }
504
+ if (urlObj.pathname === "/api/ai/assist/status") {
505
+ return jsonResponse({ configured: false });
506
+ }
507
+ return jsonResponse({});
508
+ });
509
+
510
+ const geoLink: Link = {
511
+ ...existingMockLink,
512
+ routingRules: [{ type: "geo", match: "US", target: "https://us.acme.com" }],
513
+ };
514
+
515
+ render(
516
+ <I18nProvider>
517
+ <LinkEditorForm link={geoLink} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
518
+ </I18nProvider>
519
+ );
520
+
521
+ await waitFor(() => {
522
+ expect(screen.getByText("GeoIP Active")).toBeDefined();
523
+ });
524
+ });
525
+
526
+ it("displays GeoIP Unavailable badge when geoReady is false", async () => {
527
+ fetchMock.mockImplementation(async (input: RequestInfo | URL) => {
528
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : (input as Request).url;
529
+ const urlObj = new URL(rawUrl, "http://localhost");
530
+ if (urlObj.pathname === "/api/links/capabilities") {
531
+ return jsonResponse({ geoReady: false, mode: "unavailable" });
532
+ }
533
+ if (urlObj.pathname === "/api/ai/assist/status") {
534
+ return jsonResponse({ configured: false });
535
+ }
536
+ return jsonResponse({});
537
+ });
538
+
539
+ const geoLink: Link = {
540
+ ...existingMockLink,
541
+ routingRules: [{ type: "geo", match: "US", target: "https://us.acme.com" }],
542
+ };
543
+
544
+ render(
545
+ <I18nProvider>
546
+ <LinkEditorForm link={geoLink} hosts={["link.acme.com"]} onCancel={vi.fn()} onSaved={vi.fn()} />
547
+ </I18nProvider>
548
+ );
549
+
550
+ await waitFor(() => {
551
+ expect(screen.getByText("GeoIP Unavailable (bypassed)")).toBeDefined();
552
+ });
553
+ });
554
+
555
+ it("defensively handles undefined hosts without crashing and renders domain guidance", () => {
556
+ render(
557
+ <I18nProvider>
558
+ <LinkEditorForm link={null} hosts={undefined as any} onCancel={vi.fn()} onSaved={vi.fn()} />
559
+ </I18nProvider>
560
+ );
561
+
562
+ expect(screen.getByText("No custom domain configured.")).toBeDefined();
563
+ });
564
+
565
+ it("navigates to /admin/domains on fallback when rendered outside a router", () => {
566
+ const originalLocation = window.location;
567
+ const locationMock = { href: "" };
568
+ Object.defineProperty(window, "location", {
569
+ value: locationMock,
570
+ writable: true,
571
+ configurable: true,
572
+ });
573
+ try {
574
+ const onCancel = vi.fn();
575
+ render(
576
+ <I18nProvider>
577
+ <LinkEditorForm link={null} hosts={[]} onCancel={onCancel} onSaved={vi.fn()} />
578
+ </I18nProvider>
579
+ );
580
+ const configBtn = screen.getByRole("button", { name: /Configure Domains/i });
581
+ fireEvent.click(configBtn);
582
+ expect(onCancel).toHaveBeenCalled();
583
+ expect(locationMock.href).toBe("/admin/domains");
584
+ } finally {
585
+ Object.defineProperty(window, "location", {
586
+ value: originalLocation,
587
+ writable: true,
588
+ configurable: true,
589
+ });
590
+ }
591
+ });
592
+ });