Skip to content

feat(widget): split the embed into a smart loader and an element bundle #149

Closed

Description

@Ardnived

Summary

Split the embed into a small loader that every host pastes and an element bundle it fetches
on demand, move all configuration onto the loader's own script URL, and have the loader report what
it found about the page it landed on.

Three problems this solves at once:

  • A host pays ~370 KiB gz eagerly today for a widget that may be far below the fold. That lands
    on the host page's LCP and INP, which are ranking signals for the pages the wider program is
    trying to get indexed. A ~3 KiB loader plus an IntersectionObserver gate makes the cost
    proportional to whether anyone actually sees the widget.
  • Configuration currently rides on HTML attributes, which is fragile on exactly the platforms we
    need. WordPress wp_kses strips a <script> for anyone below Administrator; Wix's Custom Element
    supplies a bare Server URL and its own attribute panel. Putting every parameter on the script URL
    gives one mechanism that works identically everywhere, and makes attribute stripping stop being a
    category of failure.
  • We do not know how our own embeds are installed. client.legacyConfig.embed_type records
    sahajayoga.at as script; it actually serves <iframe src="https://atlas.sydevelopers.com/map?key=…">.
    Hand-maintained integration metadata is wrong in the field, so the loader should observe and
    report instead.

Part of the white-label/SEO program — full context, evidence and staging in
.claude/reports/whitelabel-seo-program.md. Depends on #148 (until the embed origin is
consolidated, no client receives current code at all).

Proposed changes

Three build entries

Entry What Who loads it
auto.js the smart loader, ~3 KiB, unhashed at the dist root every host
embed.js the custom element definition (ESM) the loader, dynamically
embed.classic.js ~100 bytes: import('./embed.js') Wix's Custom Element, and any host that cannot serve type="module"

⚠ embed.js is being reused for a different artifact than it names today. Today it is the entry
a host loads directly; here it is an internal bundle only auto.js fetches. No back-compat is
required, but docs/embedding.md and CHANGELOG.md must call the rename out explicitly — #93/#144
exist because the README named a file the build never emitted, and a name that silently changes
meaning is the same failure with better spelling.

The classic shim exists because Wix does not document what script type it injects for a Custom
Element. Rather than resolve that, the shim makes it irrelevant: dynamic import() from a classic
script is Chrome 63 / Safari 11.1, far below this bundle's Chrome 111 / Safari 16.4 floor.
(ElevenLabs' convai-widget-embed, the canonical real-world Wix custom element, ships as a classic
IIFE — so classic is at minimum known to work there.)

One configuration surface

<script src="https://<origin>/auto.js?key=…&map=false&locale=fr&routing=path&mount=/map"></script>

Every parameter on the URL; no HTML attributes at all. embed.js reads its own
document.currentScript / import.meta.url, which is why Wix needs no attribute panel and why
nothing depends on markup surviving a sanitizer.

Parameters: key (required) · map · locale · routing (query|path) · mount (path routing
only) · analytics · geolocation · error-reporting · compact · name.

Keep the existing spelling rule from attributeEnabled (src/config/privacy.ts:61): only the exact
strings false and 0 disable something, so a typo can never silently switch off a flow a host is
relying on. compact is three-valued (auto|always|never) so it cannot use that helper, but it
keeps the principle — an unrecognised value falls back to auto, never to the destructive
option.

⚠ document.currentScript is null under async/defer. Read it at module top level and stash
it; fall back to document.querySelector('script[src*="auto.js"]') and document that async is
unsupported.

Detection

Runs locally on every load and acts immediately. The stored metadata is a record, never the
decision — a server round trip before render would add latency, and a stale value would produce a
broken embed.

Signal How
topLevel window.self === window.top — false inside a platform sandbox, which means no SEO regardless of mode
urlWritable history.replaceState(history.state, '', location.href) in a try — a no-op that throws in a sandboxed or file:// document
paramPersisted write a param, read it back after a frame — catches a host router reverting it
mode component when topLevel; iframe otherwise

⚠ Report on idle, not at mount: paramPersisted needs the host router to have settled. Measured on
two live Wix sites, the param survives replaceState, two animation frames, 2.5s of runtime boot,
and a cold deep-link load — but that is a measurement of Wix, not a guarantee about every host,
which is the whole reason to detect rather than assume.

Reporting

POST /api/clients/report, only when the detected fingerprint differs from what /clients/me
returned
. Steady state is zero writes; a client redesigning their site self-corrects on the next
visit, with no cron and no revalidation schedule.

  • The report carries origin + pathname only — never the host's query string or fragment. Same
    rule hostPageUrl() (src/lib/report.ts) already enforces for Sentry, for the same reason: a
    host's query can carry a reset token or an email address. This is the third time this repo has
    ruled that way; keep it consistent.
  • Server-side, Origin is validated against the client's allowedDomains. A report from an unknown
    origin is refused.
  • The receiving field is added by the SahajCloud half of this program (Clients embedMetadata,
    keyed by origin+path). This ticket can ship without it — detection and the console diagnostics
    are useful on their own; gate the POST behind the endpoint existing.

Console diagnostics

The loader runs in someone else's page, so its console output is the only channel an integrator has.
Both go through reportIntegrationWarning (src/lib/report.ts), which already prefixes and
rate-limits:

  • allowedDomains refusal → a console error, naming the origin that was refused and pointing
    at the client record. Without it the widget simply does nothing and the integrator has no thread
    to pull.
  • Compact-card mode → a console warning explaining why, with the measured slot size and the
    threshold that triggered it. A host who wanted the full interface needs to know they got the small
    one and what to change. (The compact card itself is a later ticket; this is the diagnostic
    contract it will use.)

Lazy mount

IntersectionObserver around the dynamic import('./embed.js'). Skip the gate entirely when the
element is already intersecting at load, so an above-the-fold embed loses nothing.

Surviving a host that moves the element

⚠ Moving a node in the DOM fires disconnectedCallback() then connectedCallback(), and
Elementor's "Optimized Markup" does exactly that. Today disconnectedCallback
(src/Widget.tsx:341-363) releases the API key and calls queryClient.clear(), so a page builder
relocating the element wipes an hour of warm cache mid-session and re-fetches the whole feed.

Element.moveBefore() does not help — unsupported in Safari, and the host would have to call it.
So: make connectedCallback idempotent and cheap, and defer teardown behind a short timer that a
reconnect cancels. The reason those teardowns exist still holds — an element re-added with a
different key must not authenticate as the first — so the timer must not simply remove them.

Bundle gates

⚠ scripts/check-bundle-size.mjs:221 exits 1 on graph.length < 2 with "Import walker found no
chunks". A single-file loader trips it. Needs:

  • an explicit single-file exemption;
  • a auto.js graph with a hard ceiling (~3 KiB gz) and an embed.classic.js graph;
  • a closure-disjointness assertion — auto.js's import closure must not intersect embed.js's.
    The budget alone would catch a regression (3 KiB vs ~370), but the disjointness message names the
    actual mistake.

The loader imports nothing from src/ at runtime (types only, which erase). Shared string literals
are duplicated and pinned by a spec importing both copies — the pattern src/lib/scope.ts and
scripts/postcss-scope-widget.test.ts already use for WIDGET_SCOPE.

Acceptance criteria

  • pnpm build emits auto.js, embed.js and embed.classic.js; auto.js and
    embed.classic.js are unhashed at the dist root.
  • pnpm size reports three graphs, auto.js is under its ceiling, and its closure is asserted
    disjoint from embed.js's. The graph.length < 2 exemption is explicit, not incidental.
  • A page loading only auto.js with an off-screen element fetches no widget chunk until the
    element is scrolled near the viewport; an element already on screen fetches immediately.
  • Every parameter listed above is read from the script URL, and no HTML attribute is read.
    The false/0 rule holds, and an unrecognised compact value resolves to auto.
  • document.currentScript being null under async degrades to the fallback lookup rather than
    failing to configure.
  • Detection produces the four signals and reports on idle. With no report endpoint deployed, the
    loader still renders and still logs — the POST is gated, not assumed.
  • A report never contains the host's query string or fragment. Asserted in the node lane.
  • An allowedDomains refusal logs a console error naming the origin; the widget does not
    silently do nothing.
  • Removing and re-inserting the element in the DOM within the grace window does not clear the
    query cache or release the API key; re-inserting with a different key still re-authenticates.
  • docs/embedding.md and CHANGELOG.md document the new snippet, the parameter list, and the
    embed.js rename explicitly.
  • pnpm lint && pnpm typecheck && pnpm test:run && pnpm build && pnpm size && pnpm ladle:build pass.
  • Write an implementation report to .claude/reports/<issue-number>-<short-slug>.md.

Test strategy

Node lane (per .claude/rules/tests.md, this carries the bulk):

  • the script-URL parameter parser: every parameter, the false/0 rule, compact's
    fallback-to-auto, an absent key, and a hostile mount refused by safePath
  • the detection predicate as a pure function over injected signals — no DOM needed
  • the report payload: origin+pathname only, and the differs-from-/clients/me gate
  • the literal-duplication pin between the loader's copy and src/'s

Browser (Playwright MCP) — the lazy-mount gate actually firing on scroll, and the
disconnect/reconnect grace window. Neither is expressible in the node lane, and per this repo's own
lesson (.claude/rules/tests.md, the hash.router.test.tsx cautionary tale) a pure spec cannot
attest an agreement with a foreign runtime.

Smoke lane — auto.js and embed.classic.js are served, with the right content type. Assert
on the body, never the status
: _redirects answers 200 text/html for any path, so a status check
passes against a missing file. embed.smoke.test.ts learned this the hard way.

Files affected

  • src/loader/ (new) — the loader entry and its duplicated literals
  • src/Widget.tsx — configuration read from the script URL; the connect/disconnect grace window
  • src/config/privacy.ts → likely src/config/attributes.ts — attributeEnabled plus a tri-state reader
  • vite.config.ts — two new inputs and their entryFileNames
  • scripts/check-bundle-size.mjs — third/fourth graph, single-file exemption, disjointness assertion
  • src/lib/report.ts — the two console diagnostics
  • docs/embedding.md, CHANGELOG.md, README.md, demo.html
  • tests/smoke/ — a spec for the new entries

References

Activity

  1. added 6 commits that reference this issue on Aug 18, 2026
    8e6c4ce
    698d11d
    38a7683
    6108cb8
    73bf3fb
    7ef11b2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Hold Until

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions