lagrange-library 0.3.2

A WASI-rendered Markdown static site facility — multilingual out of the box
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// @vitest-environment happy-dom
// Desktop shape of the docs search: async path, dismissal routes, clear
// affordance. MUT anchors name the mutation each pin survives.
// The component is mounted UNMOCKED here (no breakpoint stub): the phone
// shape lives in docsSearchBox.mobile.

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { nextTick } from "vue";
import { mount } from "../testUtils";
import { DocsSearchBox } from "../DocsSearchBox";
import type { DocsSiteMeta } from "../types";

// HkPopover is replaced by a stub that renders its slot and records how
// the real one reports dismissal (Escape / backdrop / ✕ all emit
// `update:modelValue(false)`). happy-dom never mounts the real popover,
// so this is the only way to drive the component's half of that contract.
// MUT: M6 (round 6 — `onSheetUpdate` made a no-op) left the suite green.
const modalState = vi.hoisted(() => ({ dismiss: null as (() => void) | null }));
vi.mock("@celestia-island/hikari", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@celestia-island/hikari")>();
  const { defineComponent, h, Teleport } = await import("vue");
  return {
    ...actual,
    HkModal: defineComponent({
      name: "HkModal",
      props: {
        modelValue: Boolean,
        "onUpdate:modelValue": Function,
      },
      setup(props, { slots }) {
        modalState.dismiss = () => props["onUpdate:modelValue"]?.(false);
        // Teleported like the real popover, so "nothing lands in the
        // header root" stays the contract under test.
        return () =>
          props.modelValue
            ? h(Teleport, { to: "body" }, [h("div", { class: "stub-modal" }, slots.default?.())])
            : null;
      },
    }),
  };
});
const modalDismiss = () => modalState.dismiss;

const site: DocsSiteMeta = {
  title: "Lagrange",
  description: "d",
  logo: null,
  base: "",
  defaultLang: "en",
  langs: [{ code: "en", label: "English" }],
  buildStamp: "s",
};

/** Answer every fetch with the same shard/lead-in payload. */
function stubFetch(handler?: (url: string) => unknown): void {
  vi.stubGlobal(
    "fetch",
    vi.fn(async (url: string) => {
      const body = handler ? handler(url) : defaultBody(url);
      if (body === "REJECT") throw new Error("network down");
      return { ok: true, json: async () => body };
    }),
  );
}

function defaultBody(url: string): unknown {
  if (url.endsWith("search_meta.json")) {
    return {
      docs: [
        {
          id: 0,
          lang: "en",
          title: "Architecture",
          url: "/guides/architecture.html",
          document_id: "d",
          chunks: [{ heading_path: ["Architecture"], anchor: "a", snippet: "pipeline" }],
        },
      ],
      shards: ["search_i_00.json"],
    };
  }
  // "lagrange" starts with 'l' (108 % 16 = 12), but any shard contents
  // work for this test — the postings point at doc 0.
  // Any token the tests type resolves to the same posting set.
  // Bare postings map — the shape the build writes.
  return { pipeline: [[0, 0]], pipeline2: [[0, 0]] };
}

/** Open the trigger's popup if it is not already open (clicking an OPEN
 * trigger toggles the panel shut). */
async function openPanel(): Promise<void> {
  if (document.querySelector(".lagrange-docs-search-input")) return;
  const trigger = document.querySelector<HTMLButtonElement>(
    ".lagrange-docs-search button[aria-haspopup='dialog']",
  )!;
  trigger.click();
  await nextTick();
}
async function typeInto(_root: ParentNode, value: string): Promise<void> {
  // Trigger-first (2026-11-24): the field lives inside the trigger's popup.
  // Open it only when not already open — clicking an OPEN trigger toggles
  // the panel shut — then type wherever the popover stub rendered the field.
  // MUT:mut-openpanel-toggle (an open-panel trigger click closes the panel,
  // which is exactly what this helper must not do).
  await openPanel();
  const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
  input.value = value;
  input.dispatchEvent(new Event("input"));
  await nextTick();
  await new Promise((r) => setTimeout(r, 30));
  await nextTick();
}

/**
 * `stubFetch`, but the way a REAL browser hands it out: a Window method
 * invoked with the wrong `this` throws "Illegal invocation". happy-dom's
 * own fetch never checks the receiver, which is exactly how a detached
 * `fetch` passed into `DocsSearch` shipped green tests and a dead search.
 * MUT: M1 (bare `fetch`) — this stub is the only oracle that catches it.
 */
function strictFetch(): void {
  const impl = async (input: string | URL | Request): Promise<Response> =>
    ({ ok: true, json: async () => defaultBody(String(input)) } as unknown as Response);
  // A REAL browser's rule, so the stub enforces it: a Window method
  // invoked off the Window throws. (`window === globalThis` holds in Chrome
  // too, so binding to either is fine; what kills the search is the BARE
  // `fetch` stored on an instance and called as a method — measured.)
  // MUT: M9 (round 8's M1) — reverting to the bare `fetch` makes this throw.
  const strict = function fetch(this: unknown, input: string | URL | Request): Promise<Response> {
    if (this !== window) {
      throw new TypeError("Failed to execute 'fetch' on 'Window': Illegal invocation");
    }
    return impl(input);
  };
  vi.stubGlobal("fetch", strict);
}

let cleanup: (() => void) | null = null;
beforeEach(() => stubFetch());
afterEach(() => {
  cleanup?.();
  cleanup = null;
  vi.unstubAllGlobals();
  document.body.innerHTML = "";
});

describe("DocsSearchBox", () => {
  // 2026-11-24: `new DocsSearch(site, fetch)` stored the bare Window
  // method on an instance and called it as a method; Chrome rejected the
  // receiver and every query died as "unavailable" on every docs site.
  it("calls fetch with the Window as its receiver, as a real browser requires", async () => {
    strictFetch();
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    // MUT: M6 (back to the bare `fetch`) — the strict stub throws, the
    // box shows its error state instead of hits.
    expect(document.querySelector(".lagrange-docs-search-error")).toBeNull();
    const results = document.querySelector(".lagrange-docs-search-results");
    expect(results, "the index must be readable when fetch is bound").toBeTruthy();
    expect(results?.textContent).toContain("Architecture");
  });

  // The guard above rests on the stub's receiver check; this one reads the
  // receiver identity off the function the component ACTUALLY calls, so a
  // stub that silently stopped checking (round 4, M3b) cannot pass it.
  it("hands DocsSearch a fetch whose receiver is the Window itself", async () => {
    let seen: unknown = "never called";
    const orig = window.fetch.bind(window);
    const spy = function fetch(this: unknown, input: string | URL | Request): Promise<Response> {
      seen = this;
      return orig(input);
    };
    vi.stubGlobal("fetch", spy);
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(document, "pipeline");
    // MUT: M1 (back to the bare `fetch`) — the receiver is then the
    // DocsSearch instance, not the Window.
    expect(seen).toBe(window);
  });

  it("renders hits for a query in the page language", async () => {
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    const results = document.querySelector(".lagrange-docs-search-results");
    expect(results).toBeTruthy();
    expect(results?.textContent).toContain("Architecture");
    expect(document.querySelector<HTMLAnchorElement>(".lagrange-docs-search-hit")?.getAttribute("href"))
      .toBe("/en/guides/architecture.html#a");
  });

  // M18: the empty-query path must reset BOTH the hits and the panel.
  it("clears the hits when the query is emptied, and keeps the modal open", async () => {
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    expect(document.querySelector(".lagrange-docs-search-results")).toBeTruthy();

    await typeInto(m.root, "");
    // The results fold; the SURFACE does not. 2026-11-24: the search is a
    // second-level window now, and a modal that closes the moment the field
    // empties would strand the user (round 7 of #124's rule — no invisible
    // backdrop to fold away — now applies on every viewport).
    expect(document.querySelector(".lagrange-docs-search-results")).toBeNull();
    expect(
      document.querySelector(".stub-modal"),
      "the modal itself stays up so the user can keep typing",
    ).toBeTruthy();
    // …and the stale-hit guard does not repopulate it afterwards.
    // MUT: M18 (removing the empty-query reset turns this test RED).
    await new Promise((r) => setTimeout(r, 40));
    expect(document.querySelector(".lagrange-docs-search-results")).toBeNull();
  });

  it("shows the no-results state for a query with no postings", async () => {
    stubFetch((url) => (url.endsWith("search_meta.json") ? defaultBody("search_meta.json") : {}));
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "zzzz");
    expect(document.querySelector(".lagrange-docs-search-empty")).toBeTruthy();
  });

  // Round 5: a rejected fetch must not surface as an unhandled rejection
  // or leave the panel frozen on stale results.
  it("shows an error state when the index cannot be read", async () => {
    stubFetch(() => "REJECT");
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    const err = document.querySelector(".lagrange-docs-search-error");
    expect(err, "the error state must render").toBeTruthy();
    expect(err?.getAttribute("role")).toBe("status");
  });

  // Dismissal is HkPopover's (Escape, outside click, the sheet's backdrop
  // and ✕). happy-dom mounts no popover, so the contract under test is the
  // component's half of it: a `false` from the popover closes the panel.
  // MUT: M6 (round 6 — `onSheetUpdate` made a no-op) left the whole suite
  // green: the sheet's own dismiss had no guard at all.
  it("closes when the popover reports its own dismissal", async () => {
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    const box = document.querySelector(".lagrange-docs-search")!;
    expect(box.getAttribute("data-open")).toBe("true");
    expect(modalDismiss(), "the modal must be mounted once the panel has content").not.toBeNull();
    modalDismiss()!();
    await nextTick();
    // MUT: M6 (round 6 — `onSheetUpdate` made a no-op) left the whole suite
    // green: the popover's own dismissal had no guard at all.
    expect(box.getAttribute("data-open")).toBe("false");
  });

  // Round 7: the field's ✕ is the one dismiss route that bypasses both
  // `run()` and HkPopover. It reset `busy` but not `open`, so an invisible
  // 10×10 popover host and a full-viewport transparent backdrop stayed up
  // and swallowed the next header click (the language menu would not open).
  it("folds the panel when the field is cleared with the ✕ button", async () => {
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    const box = document.querySelector(".lagrange-docs-search")!;
    expect(box.getAttribute("data-open")).toBe("true");
    document.querySelector<HTMLButtonElement>(".lagrange-docs-search-clear")!.click();
    await nextTick();
    // MUT: M3 (round 7 — `clear()` leaving `open` set). The RESULT list and
    // the busy flag are what `clear()` must reset; the modal's own state is
    // HkModal's (2026-11-24 — a modal stays up while the user is in it),
    // and THAT is pinned too: a `clear()` that folded the whole window
    // would strand the user mid-typing.
    expect(box.getAttribute("data-busy")).toBe("false");
    expect(document.querySelector(".lagrange-docs-search-results")).toBeNull();
    expect(
      document.querySelector(".stub-modal"),
      "clear() must fold the results, never the window",
    ).toBeTruthy();
    // …and mid-flight too (round 8 M3: the reset in `clear()` was unguarded).
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string) => {
        await new Promise((r) => setTimeout(r, 60));
        return { ok: true, json: async () => defaultBody(url) };
      }),
    );
    await openPanel();
    const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
    input.value = "pipeline";
    input.dispatchEvent(new Event("input"));
    await nextTick();
    expect(box.getAttribute("data-busy")).toBe("true");
    document.querySelector<HTMLButtonElement>(".lagrange-docs-search-clear")!.click();
    await nextTick();
    expect(box.getAttribute("data-busy")).toBe("false");
    await new Promise((r) => setTimeout(r, 120));
    expect(box.getAttribute("data-busy")).toBe("false");
  });

  // Round 5: emptying the field while a query is in flight used to leave
  // `busy` true forever (the superseded run's `finally` skips the reset),
  // pinning an empty popover on screen.
  it("does not leave the panel pinned when the field is emptied mid-flight", async () => {
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string) => {
        await new Promise((r) => setTimeout(r, 60));
        return { ok: true, json: async () => defaultBody(url) };
      }),
    );
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await openPanel();
    const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
    input.value = "pipeline";
    input.dispatchEvent(new Event("input"));
    await nextTick();
    expect(document.querySelector(".lagrange-docs-search")?.getAttribute("data-busy")).toBe("true");
    input.value = "";
    input.dispatchEvent(new Event("input"));
    await nextTick();
    // MUT: M7 (round 5 — dropping the `busy` reset in `run()`/`clear()`).
    expect(document.querySelector(".lagrange-docs-search")?.getAttribute("data-busy")).toBe("false");
    await new Promise((r) => setTimeout(r, 120));
    expect(document.querySelector(".lagrange-docs-search")?.getAttribute("data-busy")).toBe("false");
    expect(document.querySelector(".lagrange-docs-search-results")).toBeNull();
  });

  it("keeps the panel when focus moves onto a hit", async () => {
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await typeInto(m.root, "pipeline");
    await openPanel();
    const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
    const hit = document.querySelector<HTMLAnchorElement>(".lagrange-docs-search-hit")!;
    input.dispatchEvent(new FocusEvent("focusout", { bubbles: true, relatedTarget: hit }));
    await nextTick();
    expect(document.querySelector(".lagrange-docs-search-results")).toBeTruthy();
    expect(document.querySelector(".lagrange-docs-search")?.getAttribute("data-open")).toBe("true");
  });

  // Round 6 M25: a slow answer for an OLD query must not overwrite the
  // newer one (the token guard).
  it("ignores a stale answer that resolves after a newer query", async () => {
    const slow = new Map<string, number>([
      ["pipeline", 80],
      ["architecture", 0],
    ]);
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string) => {
        const body = defaultBody(url);
        // Both queries hit the same shard URL, so key the delay off the
        // shard request order instead: first call is slow.
        const isFirst = !seen;
        seen = true;
        await new Promise((r) => setTimeout(r, isFirst ? 80 : 0));
        return { ok: true, json: async () => body };
      }),
    );
    let seen = false;
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    // Fire the slow query, then immediately the fast one.
    await openPanel();
    const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
    input.value = "pipeline";
    input.dispatchEvent(new Event("input"));
    await nextTick();
    input.value = "architecture";
    input.dispatchEvent(new Event("input"));
    await new Promise((r) => setTimeout(r, 150));
    await nextTick();
    // The panel stays consistent (one result set, not a torn write).
    const results = document.querySelector(".lagrange-docs-search-results");
    expect(results).toBeTruthy();
    expect(document.querySelectorAll(".lagrange-docs-search-hit").length).toBeLessThanOrEqual(1);
    void slow;
  });

  // Round 6 M26: the panel opens only AFTER the answer lands — opening
  // it before the await shows an empty "no results" flash.
  it("does not open an empty panel before the first answer arrives", async () => {
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string) => {
        await new Promise((r) => setTimeout(r, 40));
        return { ok: true, json: async () => defaultBody(url) };
      }),
    );
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await openPanel();
    const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
    input.value = "pipeline";
    input.dispatchEvent(new Event("input"));
    await nextTick();
    // Still in flight: no panel, no "No results" flash.
    expect(document.querySelector(".lagrange-docs-search-results")).toBeNull();
    await new Promise((r) => setTimeout(r, 90));
    await nextTick();
    expect(document.querySelector(".lagrange-docs-search-results")).toBeTruthy();
  });

  // Round 8 M35: `busy` was written and never read — dead state no test
  // could catch. It now drives the in-flight row and the data-busy flag.
  // MUT: M35 (hiding data-busy turns this test RED).
  it("shows the in-flight state while a query resolves", async () => {
    vi.stubGlobal(
      "fetch",
      vi.fn(async (url: string) => {
        await new Promise((r) => setTimeout(r, 40));
        return { ok: true, json: async () => defaultBody(url) };
      }),
    );
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    await openPanel();
    const input = document.querySelector<HTMLInputElement>(".lagrange-docs-search-input")!;
    input.value = "pipeline";
    input.dispatchEvent(new Event("input"));
    await nextTick();
    expect(document.querySelector(".lagrange-docs-search")?.getAttribute("data-busy")).toBe("true");
    // The in-flight row rides the popover, which is teleported to the
    // overlay root — and the popover now mounts on the busy state itself,
    // so the row is visible from the first keystroke rather than only
    // once an answer has landed.
    expect(document.querySelector('[role="status"]')?.textContent).toContain("Searching");
    await new Promise((r) => setTimeout(r, 90));
    await nextTick();
    expect(document.querySelector(".lagrange-docs-search")?.getAttribute("data-busy")).toBe("false");
  });

  it("hides the clear affordance on an empty field", async () => {
    const m = await mount(DocsSearchBox, { site, lang: "en" });
    cleanup = m.unmount;
    expect(document.querySelector(".lagrange-docs-search-clear")).toBeNull();
  });
});