Repository navigation
Description
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 anIntersectionObservergate 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. WordPresswp_ksesstrips 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_typerecords
sahajayoga.atasscript; 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
rulehostPageUrl()(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,
Originis validated against the client'sallowedDomains. 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:
allowedDomainsrefusal → 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.jsgraph with a hard ceiling (~3 KiB gz) and anembed.classic.jsgraph; - a closure-disjointness assertion —
auto.js's import closure must not intersectembed.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 buildemitsauto.js,embed.jsandembed.classic.js;auto.jsand
embed.classic.jsare unhashed at the dist root. -
pnpm sizereports three graphs,auto.jsis under its ceiling, and its closure is asserted
disjoint fromembed.js's. Thegraph.length < 2exemption is explicit, not incidental. - A page loading only
auto.jswith 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.
Thefalse/0rule holds, and an unrecognisedcompactvalue resolves toauto. -
document.currentScriptbeing null underasyncdegrades 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
allowedDomainsrefusal 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 differentkeystill re-authenticates. -
docs/embedding.mdandCHANGELOG.mddocument the new snippet, the parameter list, and the
embed.jsrename explicitly. -
pnpm lint && pnpm typecheck && pnpm test:run && pnpm build && pnpm size && pnpm ladle:buildpass. - 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/0rule,compact's
fallback-to-auto, an absentkey, and a hostilemountrefused bysafePath - the detection predicate as a pure function over injected signals — no DOM needed
- the report payload: origin+pathname only, and the differs-from-
/clients/megate - 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 literalssrc/Widget.tsx— configuration read from the script URL; the connect/disconnect grace windowsrc/config/privacy.ts→ likelysrc/config/attributes.ts—attributeEnabledplus a tri-state readervite.config.ts— two new inputs and theirentryFileNamesscripts/check-bundle-size.mjs— third/fourth graph, single-file exemption, disjointness assertionsrc/lib/report.ts— the two console diagnosticsdocs/embedding.md,CHANGELOG.md,README.md,demo.htmltests/smoke/— a spec for the new entries
References
.claude/reports/whitelabel-seo-program.md— the program this is Stage 1 of- chore(build): stop the sahajatlas.com zone overriding the loader's Cache-Control #148 — embed-origin consolidation, a hard prerequisite
docs/embedding.md§"Sizing the element", §"Updates and caching".claude/rules/tests.md— the two lanes, the jsdom exception list, and the status-is-not-a-result invariant
Metadata
Metadata
Assignees
Labels
Type
Fields
Hold Until
Activity
refactor(widget): narrow the embed config to six parameters
refactor(build): make the classic shim an ordinary build entry
fix(build): pin the entry files to revalidate instead of going stale (#…
feat(widget): send the embed report and publish a readiness marker (#159
docs(embedding): describe the compact form and what a host must avoid
docs(embedding): describe the compact form and what a host must avoid
docs(embedding): describe the compact form and what a host must avoid
feat(widget): one slot question, and a compact card that works in an …
fix(i18n): three test names still name a dead attribute
fix(docs): the components guide names a renamed table