diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 0000000000..96551bd897 --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,20 @@ +{ + "name": "studio", + "interface": { + "displayName": "studio" + }, + "plugins": [ + { + "name": "data-liberation", + "source": { + "source": "local", + "path": "./packages/data-liberation-agent" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Coding" + } + ] +} \ No newline at end of file diff --git a/.agents/skills/codex.marketplace.json b/.agents/skills/codex.marketplace.json new file mode 120000 index 0000000000..68dd22cea9 --- /dev/null +++ b/.agents/skills/codex.marketplace.json @@ -0,0 +1 @@ +../plugins/marketplace.json \ No newline at end of file diff --git a/.agents/skills/marketplace.json b/.agents/skills/marketplace.json new file mode 120000 index 0000000000..68dd22cea9 --- /dev/null +++ b/.agents/skills/marketplace.json @@ -0,0 +1 @@ +../plugins/marketplace.json \ No newline at end of file diff --git a/.buildkite/commands/run-lint.sh b/.buildkite/commands/run-lint.sh index b391398c23..4f366b3463 100755 --- a/.buildkite/commands/run-lint.sh +++ b/.buildkite/commands/run-lint.sh @@ -14,3 +14,16 @@ npm run lint echo '--- :typescript: Typecheck' npm run typecheck + +# The data-liberation plugin ships its MCP server as a committed esbuild +# bundle (the plugin installer copies the package from git verbatim — no +# npm install, no build). Rebuild it and fail if the committed artifact +# doesn't match src/, so the two can never drift. The build is +# byte-deterministic for a given lockfile, so a clean tree means fresh. +echo '--- :package: Verify data-liberation MCP bundle is fresh' +npm -w data-liberation run build:mcp-bundle +if ! git diff --exit-code -- packages/data-liberation-agent/dist/mcp-server.bundle.mjs; then + echo "^^^ +++" + echo "The committed data-liberation MCP bundle is stale. Run 'npm -w data-liberation run build:mcp-bundle' and commit the updated bundle." + exit 1 +fi diff --git a/packages/data-liberation-agent/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json similarity index 83% rename from packages/data-liberation-agent/.claude-plugin/marketplace.json rename to .claude-plugin/marketplace.json index 7b7f8c1751..56d18c798b 100644 --- a/packages/data-liberation-agent/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,12 +1,12 @@ { - "name": "data-liberation", + "name": "studio", "owner": { "name": "Automattic" }, "plugins": [ { "name": "data-liberation", - "source": "./", + "source": "./packages/data-liberation-agent", "description": "Extract content from closed web platforms (GoDaddy Websites & Marketing, Hostinger, HubSpot, Shopify, Squarespace, Webflow, Weebly, Wix) into WordPress-compatible WXR files. Inspect, extract, QA, and import to WordPress." } ] diff --git a/.gitignore b/.gitignore index c47aadf3cc..38246bc530 100644 --- a/.gitignore +++ b/.gitignore @@ -114,6 +114,10 @@ cli/vendor/ dist dist-hosted dist-local +# …except the data-liberation plugin's committed MCP server bundle (the plugin +# installer copies the package without running npm install or a build). The +# package-level .gitignore keeps everything else in its dist/ ignored. +!packages/data-liberation-agent/dist # Playwright traces test-results diff --git a/package-lock.json b/package-lock.json index 8666bca93d..7bef9d37a3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -33133,6 +33133,7 @@ "@types/pixelmatch": "^5.2.6", "@types/pngjs": "^6.0.5", "@types/react": "^19.2.14", + "esbuild": "^0.28.0", "jsdom": "^26.1.0", "single-file-cli": "^2.0.83", "tsx": "^4.19.0", diff --git a/packages/data-liberation-agent/.claude-plugin/plugin.json b/packages/data-liberation-agent/.claude-plugin/plugin.json index f754ebde89..439f7a47f8 100644 --- a/packages/data-liberation-agent/.claude-plugin/plugin.json +++ b/packages/data-liberation-agent/.claude-plugin/plugin.json @@ -1,12 +1,12 @@ { "name": "data-liberation", "description": "Extract content from closed web platforms (GoDaddy Websites & Marketing, Hostinger, HubSpot, Shopify, Squarespace, Webflow, Weebly, Wix) into WordPress-compatible WXR files. Inspect, extract, QA, and import to WordPress.", - "version": "0.2.2", + "version": "1.0.0", "author": { "name": "Automattic" }, - "homepage": "https://github.com/Automattic/data-liberation-agent", - "repository": "https://github.com/Automattic/data-liberation-agent", + "homepage": "https://github.com/Automattic/studio", + "repository": "https://github.com/Automattic/studio", "license": "GPL-2.0-or-later", "keywords": [ "content-extraction", @@ -23,8 +23,5 @@ "wordpress", "wxr" ], - "mcp": { - "command": "npx", - "args": ["tsx", "src/mcp-server.ts"] - } + "mcpServers": "./.mcp.json" } diff --git a/packages/data-liberation-agent/.codex-plugin/plugin.json b/packages/data-liberation-agent/.codex-plugin/plugin.json index d769b11fc4..99a0c9c410 100644 --- a/packages/data-liberation-agent/.codex-plugin/plugin.json +++ b/packages/data-liberation-agent/.codex-plugin/plugin.json @@ -1,14 +1,14 @@ { "name": "data-liberation", "description": "Extract content from closed web platforms (GoDaddy Websites & Marketing, Hostinger, HubSpot, Shopify, Squarespace, Webflow, Weebly, Wix) into WordPress-compatible WXR files. Inspect, extract, QA, and import to WordPress.", - "version": "0.2.2", + "version": "1.0.0", "author": { "name": "Automattic" }, - "homepage": "https://github.com/Automattic/data-liberation-agent", + "homepage": "https://github.com/Automattic/studio", "license": "GPL-2.0-or-later", "skills": "./skills/", - "mcpServers": "./.mcp.json", + "mcpServers": "./.mcp.codex.json", "interface": { "displayName": "Data Liberation", "shortDescription": "Extract closed-platform sites into WordPress-compatible exports", @@ -20,7 +20,7 @@ "Read", "Write" ], - "websiteURL": "https://github.com/Automattic/data-liberation-agent", + "websiteURL": "https://github.com/Automattic/studio", "defaultPrompt": [ "Inspect a site for liberation", "Extract this site into WordPress-compatible WXR", diff --git a/packages/data-liberation-agent/.gitignore b/packages/data-liberation-agent/.gitignore index 14c416ed8c..b0df77f796 100644 --- a/packages/data-liberation-agent/.gitignore +++ b/packages/data-liberation-agent/.gitignore @@ -4,7 +4,11 @@ skills/replicate-workspace/ node_modules/ .DS_Store *.log -dist/ +# dist/ is build output, EXCEPT the committed plugin bundle: the Claude/Codex +# plugin installer copies this package verbatim (no npm install, no build), so +# the self-contained MCP server bundle must live in git. +dist/* +!dist/mcp-server.bundle.mjs docs/plans/ docs/superpowers/ qa-screenshots/ @@ -15,6 +19,8 @@ qa-screenshots/ .worktrees/ .tmp-test/ TODOS.md +# Local discovery log — see CONTRIBUTING.md; intentionally not committed +DISCOVERIES.md # Streaming compose-then-install scratch dir .tmp-compose/ diff --git a/packages/data-liberation-agent/.mcp.codex.json b/packages/data-liberation-agent/.mcp.codex.json new file mode 100644 index 0000000000..89fded61ad --- /dev/null +++ b/packages/data-liberation-agent/.mcp.codex.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "data-liberation": { + "command": "node", + "args": ["./scripts/mcp-launcher.mjs"], + "cwd": "." + } + } +} diff --git a/packages/data-liberation-agent/.mcp.json b/packages/data-liberation-agent/.mcp.json index 5b0c593718..5f7278ba45 100644 --- a/packages/data-liberation-agent/.mcp.json +++ b/packages/data-liberation-agent/.mcp.json @@ -1,9 +1,9 @@ { "mcpServers": { "data-liberation": { - "command": "npx", - "args": ["tsx", "${CLAUDE_PLUGIN_ROOT:-.}/src/mcp-server.ts"], - "cwd": "${CLAUDE_PLUGIN_ROOT:-.}" + "command": "node", + "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/mcp-launcher.mjs"], + "cwd": "${CLAUDE_PLUGIN_ROOT}" } } } diff --git a/packages/data-liberation-agent/AGENTS.md b/packages/data-liberation-agent/AGENTS.md index f69a22ce81..a3d59429e9 100644 --- a/packages/data-liberation-agent/AGENTS.md +++ b/packages/data-liberation-agent/AGENTS.md @@ -50,6 +50,7 @@ When `adminToken` is present, `shopifyAdapter.extract` fetches products via the ## Non-obvious Details - **MCP server runs `tsx src/mcp-server.ts` as ONE long-lived process — editing `src/` does NOT hot-reload it.** ESM modules are cached per process, so a re-called `liberate_*` tool keeps running the code that was loaded at server start. After editing handler/lib source, either restart the MCP server (so all callers pick it up) or, for a quick one-off re-run, drive the handler from a fresh `tsx` process (import the handler, pass a minimal `HandlerContext` with `textResult`/`errorResult`). Unit tests (`vitest`) always use the on-disk source, so they reflect edits immediately — the staleness is only the running MCP server. +- **`.mcp.json` starts the MCP server through `scripts/mcp-launcher.mjs`: dev checkouts run `src/` via tsx; plugin installs run the COMMITTED bundle `dist/mcp-server.bundle.mjs`.** The launcher only uses the bundle when the package's dependencies don't resolve, so a dev environment never runs a stale dist. The bundle must be committed because plugin installs are plain git copies: Claude's installer restores npm deps only when a per-package `package-lock.json` exists (this workspace package has none), and Codex's installer NEVER restores deps — so `claude/codex plugin marketplace add Automattic/studio` only works with a prebuilt self-contained artifact in the tree. After changing `src/` or dependencies, regenerate with `npm run build:mcp-bundle` and commit the result — CI (Buildkite Lint) rebuilds it and fails on drift. `playwright` and `single-file-cli` stay external to the bundle (guarded dynamic imports that degrade with install guidance). See `scripts/build-mcp-bundle.mjs` for the import.meta.url asset-resolution seam. - DLA consumes `@automattic/blocks-engine` through the local pre-publish override `"file:../blocks-engine/packages/blocks-engine"`; standalone `npm install` therefore needs the sibling `blocks-engine` checkout until the package is published. On publish, flip the dependency to the authorized semver range (for example `"^0.x.y"`). Publishing itself remains gated on explicit user authorization. - **`tsx scripts/*.ts` that call `page.evaluate` must create the page via `newShimmedPage` from `scripts/_pw.ts`** — tsx's esbuild keepNames rewrites named functions to `__name(...)`, which is undefined in the browser context Playwright serializes into (`ReferenceError: __name is not defined`). The shim installs a `__name` identity via `addInitScript`. vitest-run code is unaffected (its transform doesn't keepNames). - WXR builder targets WXR 1.2 spec compliance diff --git a/packages/data-liberation-agent/CONTRIBUTING.md b/packages/data-liberation-agent/CONTRIBUTING.md index bea13e04bd..2c767eee78 100644 --- a/packages/data-liberation-agent/CONTRIBUTING.md +++ b/packages/data-liberation-agent/CONTRIBUTING.md @@ -54,7 +54,7 @@ If you can't test against a real site, note that in the PR and explain what you ### 3. Add to DISCOVERIES.md -This is required. Add a new entry at the top of [DISCOVERIES.md](./DISCOVERIES.md) in this format: +This is required. DISCOVERIES.md is a local, untracked log (gitignored — it is not committed to the repo); create it at the package root if it doesn't exist yet. Add a new entry at the top in this format: ```markdown ## YYYY-MM-DD — Short title diff --git a/packages/data-liberation-agent/DISCOVERIES.md b/packages/data-liberation-agent/DISCOVERIES.md deleted file mode 100644 index 00e60a0aba..0000000000 --- a/packages/data-liberation-agent/DISCOVERIES.md +++ /dev/null @@ -1,1002 +0,0 @@ -# Discoveries - -A living log of findings from real migrations. Newest entries at the top. - -AI agents: when you contribute an improvement, add an entry here. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the required format. - ---- - -## 2026-06-04 — getsnooz.com (Shopify) carry run: capture 429s, carry-path media-install timeout, carry-tool schema gap - -**Found by:** Claude + Matt -**During:** A `/liberate` → theme-replication (carry-and-scope) pass on getsnooz.com (Shopify, ~99 URLs, 436 media). -**Type:** capture reliability + install-path bug + fix + MCP schema fix - -### 1. CDP beats Shopify's 403, but capture concurrency 6 trips a 429 rate-limit -Memory said "Shopify capture needs CDP (headless 403s)" — true: a real Chrome over `--remote-debugging-port` captured cleanly where headless got 403s. But the *first* run still failed **168 capture ops** with `HTTP 429 Too Many Requests`, all clustered ~2 min in: the **default screenshot concurrency (6) × 2 viewports** hammered the origin fast enough that Shopify's edge throttled every subsequent `goto`. The capture loop does `attempt: 1` with **no 429 retry/backoff**, so once throttled the rest of the run cascaded into manifest stubs (slug+capturedAt, no PNG). **Workaround:** resume `liberate_screenshot` at `concurrency: 2` → 90 captured, **0 failed**. **Open fix:** add 429-aware retry/backoff (honor `Retry-After`) to `screenshotter.ts`, and/or lower the default capture concurrency for Shopify origins. (Extends the prior "default to CDP for Shopify" note.) - -### 2. Carry-path media install hit the SAME Studio 120s timeout that import-wxr.php already fixed -`liberate_reconstruct_pages_carry` returned `mediaInstalled: 0` with every entry erroring `install-media.php failed: … No activity for 120s`. Root cause is identical to the 2026-05-27 `import-wxr.php` finding below: `install-media.php` calls `wp_generate_attachment_metadata()` (thumbnail regen) per file and **emits no output until after the loop**, so a large media set (here the run's full 992-file map installed on the first page) runs silently past Studio's 120s IPC-silence kill — leaving carried `` on the source CDN (carry's "self-hosted media" promise broken). **Fix (applied, uncommitted):** mirror `import-wxr.php` in `src/lib/preview/scripts/install-media.php` — `add_filter('intermediate_image_sizes_advanced','__return_empty_array')` + a `WP_CLI::log` heartbeat inside the loop (printed before the `DLA_INSTALL_MEDIA_JSON_BEGIN` sentinel, so `media-install.ts`'s marker-delimited slice ignores it). Result after fix: **mediaInstalled 992, 0 errors**; homepage island went from all-CDN to 88 local `/wp-content/uploads/` refs (7 CDN left = known CSS-`url()` limit). Lesson: the thumbnail-skip + heartbeat pattern belongs in **every** vendored WP-CLI script that loops over media, not just `import-wxr.php`. - -### 3. `liberate_reconstruct_pages_carry` MCP schema under-declared `htmlSlug` + `postType` -The handler reads `p.htmlSlug` (cached-HTML stem: `html/.html`) and `p.postType` (`page`|`post`), but the tool's `inputSchema.pages.items` only declared `slug`/`sourceUrl`/`title`/`isHome`. The server happens to pass args raw (no strip), so it worked — but the schema lied about the contract, and without `htmlSlug` every page (e.g. `about` whose file is `pages--about.html`) would silently fall back to a live fetch of `sourceUrl`. **Fix (applied):** added `postType` (enum page/post) + `htmlSlug` to the schema in `src/mcp-server.ts` so it matches the handler. - ---- - -## 2026-05-28 — corneliusholmes.com (Wix) re-run: content-width band layers + verify `__name` tooling bug - -**Found by:** Claude + Matt -**During:** A second `/liberate` pass on corneliusholmes.com. After the prior fixes, content pages STILL rendered flat-white and every captured section `backgroundColor` was `rgb(255,255,255)`. -**Type:** reconstruction fidelity + tooling bug - -### 1. Section bands missed because the colored layer is content-width, not full-bleed -The descendant bg-layer scan in `section-extract.ts` (`pickEffectiveBg`) required the colored child to span **≥90% width AND ≥90% height**. A live DOM probe showed Wix paints each band's tint on an **~810px-of-1440 (~56%) inner column** beside a photo (peach `#fadcd6`, blue `#b6d1d9`, sage `#d5e1ca`, warm-grey `#f0eded`), so the ≥90%-width gate skipped them and the section recorded white. **Fix:** accept a *content-width band* — `width ≥ 50%` when it still spans `height ≥ 90%` of the section (full-height ⇒ it's the band, not a small card); largest-area still wins. 40/40 `section-extract.test.ts` pass. Re-extracting with `refresh:true` restored the pastel bands across all content pages. (Extends fix #5 below.) - -### 2. `liberate_replicate_verify` section-metrics crash: `__name is not defined` -Every desktop capture's `measureReplicaSectionsInBrowser` `page.evaluate` threw `ReferenceError: __name is not defined` — esbuild/tsx's `keepNames` helper (`__name`) is referenced inside the function body but isn't defined in the page context. This silently disables the automated `SectionParity` live-DOM metrics, forcing QA onto the vision+pngjs fallback. **Still open** — the browser-evaluated function needs to be self-contained (no bundler-injected helpers). Screenshots themselves capture fine. - -### 3. Card-grid flatten (prior "still open") — hand-fixed per-page for the homepage -The 3-card numbered service row and the two-tone My-Approach/About-Me blocks still flatten (geometry classifier reads them as `static`, no `cells[]`). For this run they were rebuilt as an R2 per-page `post_content` patch (3 peach cards in a columns row; peach+coral two-tone cards), and the homepage hero was rebuilt as a `wp:cover` (the captured hero `` src came back empty, so the structured render fell back to a black band with an invisible black-on-black title). The underlying **card-grid / cover-hero classifier** gap remains the right systemic fix. - ---- - -## 2026-05-28 — Visual-parity fixes from the corneliusholmes.com (Wix) rebuild: gapless sections, exact captured colors, fluid-off, suffix-tolerant font match, QA sampling - -**Found by:** Claude + Matt -**During:** A long parity pass on the corneliusholmes.com homepage where the block reconstruction looked significantly different from the source (muddy/dark hero, saturated-wrong card colors, flattened tiles, white gaps between sections). Root retro → 5 systemic fixes. -**Type:** reconstruction fidelity + scaffold defaults + QA workflow - -### What was wrong (and the meta-lesson) -Core-block reconstruction re-derives a bespoke design with generic blocks and *inferred* values, and the agent compounded that by **guessing colors/sizes and declaring "parity" before measuring**. Almost every fix came from MEASURING the source (sampling screenshot pixels, reading the SectionSpec) instead of eyeballing. Treat that as the default: sample, don't guess; lead with the differences. - -### Fixes shipped -1. **Suffix-tolerant captured-font matching** (`font-capture.ts` `matchCapturedFamily`). The capture pipeline derives a suffix-free family (`futura-lt-w01`) while the computed style carries a weight/style suffix or builder hash (`futura-lt-w01-book`, `avenir-lt-w01_35-light1475496`). The old EXACT match failed, so the substitution path wrongly fired and replaced the real self-hosted source font with Inter. Now falls back to comparing weight/style/hash-stripped base names. Also reordered `theme-scaffold.ts buildFontFamilies` so a real captured family beats the free substitute. -2. **Fluid typography OFF for replicas** (`theme-scaffold.ts`). `settings.typography.fluid:true` silently rewrote the reconstruction's exact px sizes into shrinking `clamp()`s (a captured 36px heading rendered ~22px). Faithful px wins over fluid scaling. -3. **Gapless full-bleed section stacking** (`page-reconstruct.ts wrapSection`). White gaps between sections came from WP's default top-level block-gap. Every section now zeroes its top/bottom margin so bands butt edge-to-edge; all vertical rhythm comes from each section's own captured padding (`padTopPx`/`padBottomPx`, which the spec already carried). -4. **Paint the exact captured band color** (`page-reconstruct.ts`). A band now renders its real captured tint (e.g. pale-blue `#e8eff1`) instead of the generic `surface-raised` grey approximation. Guarded: near-white and low-alpha (<0.6) and near-neutral-grey tints fall back to the token (don't over-saturate). -5. **Capture the band's real background from a full-span DESCENDANT layer** (`section-extract.ts` `pickEffectiveBg`). Page builders (Wix) paint a section's color on a full-span child (`colorUnderlay`/bgLayers) div, not the `
` or its ancestors — so the own→ancestor→sibling walk reported the page white and missed the real band color. Added a geometry-based descendant scan (≥90% width AND height of the section) when own+ancestors give no color or near-white. -6. **design-qa now samples + gates per-section** (`skills/design-qa/SKILL.md`). The skill must sample source-vs-replica pixels per band (colors, inter-section gaps, heading/body sizes), report a per-section delta table, and treat a high structural delta as disqualifying — not declare "matches" from vision alone. - -### Still open (next) -- **Card-grid DETECTION.** The 3-card service row flattened to stacked text because the geometry classifier read it as flat `static` (so no `cells[]` were captured → no card bgs). The cell-bg walk already handles descendants; the gap is detecting the grid in the first place. Needs a stronger card-grid/​hero-cover/​pill-row/​testimonial-grid classifier + `section-mapping` templates. -- **Set the html-first expectation up front.** Core-block reconstruction can't pixel-match a bespoke Wix design (absolute positioning, full-bleed image backgrounds, container-query scaling). The skill should say so early and offer the carried-CSS html-first path when the user prioritizes pixel fidelity over editable blocks. - -### Verification -`font-capture` / `theme-scaffold` / `font-substitution` (82), `page-reconstruct` / `validate-block-markup` / `compose-instantiate` (71), `section-extract` (40) unit suites pass, incl. new cases (suffix-tolerant match, gapless margins, exact-tint paint, grey-skip). Browser-eval (`pickEffectiveBg` descendant scan) needs a live re-extract to exercise; the MCP server must be restarted to pick up `src/` changes. - ---- - -## 2026-05-28 — Wix `/liberate`: scaffold drops valid captured fonts to Inter; updating post_content in a Studio site needs the VFS path - -**Found by:** Claude + Matt -**During:** Migrating https://www.corneliusholmes.com/ (Wix therapy practice — 18 pages, 32 posts). -**Type:** theme-scaffold behavior + Studio CLI operational gotcha - -### Finding 1 — `liberate_theme_scaffold` substituted self-hostable source fonts with a generic -The source uses commercial Wix faces — **Futura LT** (display) and **Avenir LT** (body). The scaffold's font pipeline successfully downloaded BOTH as valid woff2 into `theme/assets/fonts/` (verified `file` → "Web Open Font Format (Version 2), TrueType"), yet `theme.json` bound the `body` AND `display` families to **Inter** via `fontSubstitutions` (`arial→Inter`, `futura-lt-w01-book→Inter`). Net effect: the source's geometric-display / humanist-body contrast collapses into one neutral face. The design-foundation's intended substitutes (Jost/Mulish) were also ignored. - -**Workaround this run:** hand-rebound `theme.json` `body`→`avenir-lt-w01_35-light1475496` and `display`→`futura-lt-w01` (the real captured woff2, with Jost/Mulish kept as fallback in the stack). Worth tightening the substitution logic: when a captured woff2 is present and valid, prefer self-hosting the real face (or the foundation's chosen substitute) over a generic Inter fallback. Note licensing — Futura/Avenir are commercial; fine for a local benchmark replica, flag for publication. - -### Finding 2 — `studio wp post update ` can only read files via the `/wordpress` VFS path -QA edits to a page's `post_content` (re-carding the homepage service row) failed two ways before working: -- `post update 208 /abs/host/path.html` → `Error: Unable to read content from '...'` (Studio's PHP sandbox can't see arbitrary host paths). -- `post update 208 - < file.html` (STDIN) → reports `Success` but silently sets `post_content` to **empty** (the proxy doesn't forward stdin). - -**Working method:** copy the content file INTO the site dir (`~/Studio//`) and reference it by its VFS path — Studio mounts the site at `/wordpress`, so `studio wp --path post update /wordpress/`. This mirrors how `studio.ts` drives WXR import (`toVfsPath` + `eval-file`). Always verify with a follow-up `post get --field=post_content | wc -c` — the STDIN path's false success is the dangerous one. - -### Why it matters -Both bite any agent-driven Wix replica: Finding 1 silently flattens type identity on sites whose fonts ARE capturable; Finding 2 can blank a reconstructed page during QA touch-ups while reporting success. - ---- - -## 2026-05-22 — `liberate_extract_one` clobbered the WXR (same bug as the 2026-04-30 resume fix, second site of) - -**Found by:** Claude + Matt -**During:** Migrating https://www.swiftlumber.com/ — first full extract produced 6 pages; retrying the single failed `/projects` URL via `liberate_extract_one` left the WXR with only that one (failed) page, destroying the other 6. -**Type:** extraction infrastructure bug - -### What I found -The 2026-04-30 fix only patched the resume path of `liberate_extract` (`handlers/extract.ts`). `handlers/extract-one.ts` — the agent-first single-URL tool — has the *same* shape: it constructs a fresh `WxrBuilder`, extracts one URL into it, and calls `wxr.serialize(wxrPath)`, atomically overwriting whatever multi-page WXR was already there. Its own comment even flagged the limitation ("v1 extract-one writes a per-call WXR that the watch CLI is expected to merge if needed"), but when the tool is driven directly (not through the watch CLI's shared in-memory builder), nothing merges — so every `extract_one` against an existing extraction truncates it to one item. - -### How it's fixed -Extracted the rehydrate-before-serialize logic into a shared helper `src/lib/extraction/wxr-rehydrate.ts` (`rehydrateBuilderFromWxr(wxr, wxrPath)`): reads the prior WXR, copies authors/categories/tags/terms/comments/redirects + non-`nav_menu_item` items onto the fresh builder, and reseeds `_nextId` past the largest retained id. `nav_menu_items` are dropped because the extraction loop regenerates them deterministically each run. Missing prior WXR → no-op; corrupt prior WXR → treated as a fresh start (builder untouched). - -- `extract.ts` now calls the helper on `args.resume` (replacing its inline block). -- `extract-one.ts` calls it unconditionally — every `extract_one` is an append to an existing extraction. - -Covered by `wxr-rehydrate.test.ts` (merge/nav-drop/id-reseed, missing-file no-op, corrupt-file no-op) and `extract-one.test.ts` (prior pages survive a single-URL append). The latter reproduces the swiftlumber data loss: red before the fix (only `['new']` survived), green after (`['about','contact','home','new']`). - -### Why it matters -`extract_one` is the agent-first streaming primitive — the orchestrator calls it repeatedly, once per URL. Pre-fix, any multi-call agent run kept only the *last* URL's item in the WXR. The bug was masked in the watch CLI (shared builder via `processOneUrl`) but active for every direct MCP/agent caller. - ---- - -## 2026-05-22 — Wix Pro Gallery pages fail extraction with "Execution context was destroyed" - -**Found by:** Claude + Matt -**During:** Migrating https://www.swiftlumber.com/ — the `/projects` page (a "GALLERY" nav item) failed both in the full extract and on single-URL retry, identically: `page.evaluate: Execution context was destroyed, most likely because of a navigation`. -**Type:** Wix adapter limitation - -### What I found -`/projects` returns HTTP 200 (no server redirect) and is a Wix **Pro Gallery** page — `pro-gallery` appears ~876× in the served HTML, with `ProGallery` widgets and inline `window.location` / `location.href` handlers. During hydration the gallery fires a client-side navigation (route/lightbox state), which invalidates the JS execution context just as the adapter's in-page `page.evaluate` extraction script runs. Result: deterministic failure, no HTML capture, no screenshot, no content for that page. All other pages on the site extracted at high quality. - -### How it's fixed (2026-05-23) -Layered defense in `src/adapters/wix.ts` so the page survives the navigation-destroys-context race instead of erroring out. All four layers were shipped because the failure is **intermittent and timing-dependent** (under concurrent load the gallery's deferred navigation lands mid-evaluate; in isolation it often doesn't fire at all) — no single layer is reliable on its own: - -1. **Route pinning before navigation.** `addInitScript(ROUTE_PIN_INIT_SCRIPT)` no-ops `history.pushState`/`replaceState` and swallows `location.assign`/`replace` writes for the page's lifetime, so the gallery can't navigate away during extraction. Best-effort (the native `location` setter can't always be overridden), installed inside try/catch. -2. **Settle before evaluate.** `goto('domcontentloaded')` → bounded `waitForLoadState('networkidle')` (6s, best-effort — Wix telemetry never truly idles) → fixed 4s delay → a lazy-load scroll pass (so below-the-fold gallery thumbnails enter the DOM) → re-settle. This lets the gallery finish hydrating *before* we read it. -3. **Retry once on destroyed context.** Every in-page `page.evaluate` (globals/JSON-LD/meta, rendered content, blog-archive probe) goes through `evaluateWithRetry`, which on a `isExecutionContextDestroyed(err)` match re-settles and re-runs the evaluate exactly once. The globals read — historically the *unguarded* call that crashed the whole URL — now degrades to an empty shell on a second failure instead of throwing. -4. **Served-HTML fallback.** When the live path fails (or `page.content()` is unreadable), we plain-GET the URL (`fetchHtml`) and run `extractGalleryFromHtml`, which recovers the title, an og:description/heading content shell, and the gallery image URLs from full `static.wixstatic.com/media/...` links *and* the bare `~mv2.` media tokens in the `wix-warmup-data` JSON (promoted to canonical CDN URLs). This runs on every page (folding any token-derived URLs the live scan missed into `mediaUrls`), so a Pro Gallery page is never dropped entirely. - -New exported, unit-tested helpers: `isExecutionContextDestroyed`, `extractGalleryFromHtml`, `ROUTE_PIN_INIT_SCRIPT`. Covered by `test/adapters/wix-pro-gallery.test.ts` (12 tests, fixture `test/fixtures/wix-pro-gallery.html`): error-classification (matches Playwright + bare CDP phrasings, rejects unrelated errors), gallery image recovery (img src / background-image / og:image / warmup tokens, all normalized to absolute CDN URLs, de-duped), title-suffix stripping, content-shell assembly, and no-false-positives on plain markup. - -### Verified live (2026-05-23) -Ran the real `wixAdapter.extract` against just `https://www.swiftlumber.com/projects`: -- **No "execution context destroyed" error escaped** (`thrown: null`); URL logged as `processed` with `qualityScore: high`. -- `pagesExtracted: 1, failed: 0`; WXR item `type: page`, `title: "GALLERY"`, content length 6419 with **25 `` tags** (descriptive alt text) plus heading/body text. -- **72 media collected / 70 image files downloaded** (the gallery photos). -- The served-HTML fallback, exercised in isolation against the live 1 MB markup with **zero JS execution**, independently recovered the title, a content shell, and **33 absolute gallery image URLs** — so even in the worst case (context destroyed, `page.content()` unreadable) the page still yields content + images. - -### Honest reliability assessment -**Best-effort, not a guarantee — but the page is no longer dropped.** The live `page.evaluate` path now succeeds on the runs I observed (the destroyed-context error did not reproduce in isolation at the time of the fix; the site may hydrate faster now, or the race only triggers under the concurrent load of a full multi-page + screenshot run). Layers 1–3 widen the window where the live read succeeds; layer 4 guarantees that *if* the live read still fails, the page is salvaged from the served HTML (title + content shell + gallery image URLs) rather than failing the whole URL. The remaining gap vs. a clean live extract is **layout fidelity in the worst case**: the HTML fallback yields the images and a thin content shell, not the full rendered gallery markup. The images themselves — the gallery's actual value — are recovered in every path. - ---- - -## 2026-04-30 — `--resume` overwrites the existing WXR with only newly-extracted items - -**Found by:** Claude + James -**During:** Migrating https://www.corneliusholmes.com/ — first run extracted 16 pages, the resume run for 2 remaining failures left only those 2 pages in the final WXR -**Type:** extraction infrastructure bug - -### What I found -The `liberate_extract` MCP handler in `src/mcp-server.ts` constructs a fresh `WxrBuilder` on every invocation and calls `wxr.serialize(wxrPath)` at the end, which `writeFileSync`s the WXR (overwriting whatever's there). The `runExtractionLoop` correctly filters URLs already in `extraction-log.jsonl` on `--resume`, so the in-memory builder ends each resume run with *only the newly-extracted items*. Serialize then atomically replaces the prior multi-item WXR with whatever was extracted this run. - -Concretely on the test site: -- Run 1 (fresh): extracted 16 pages → `output.wxr` contains 16 pages. -- Run 2 (`--resume`, retrying 2 previously-failed URLs): builder sees 2 new pages → `output.wxr` rewritten with 2 pages, the prior 16 destroyed. - -This makes resume worse than useless — it actively damages the prior output. The user thought they were extending the extraction; they were truncating it. - -### How it works -On resume, rehydrate the `WxrBuilder` from the existing `output.wxr` *before* calling `adapter.extract`. The repo already has `readWxr` (`src/lib/extraction/wxr-reader.ts`) which produces typed `WxrItem[]` / `Author[]` / etc. matching the builder's public fields. Direct field assignment + reseed `_nextId` past the max existing ID. - -`nav_menu_item`s are dropped on load because the extraction loop regenerates them deterministically from the current inventory's navigation each run; keeping the prior ones would produce duplicates. - -```ts -if (typedArgs.resume && existsSync(wxrPath)) { - try { - const prior = readWxr(wxrPath); - wxr.authors = prior.authors; - wxr.categories = prior.categories; - wxr.tags = prior.tags; - wxr.terms = prior.terms; - wxr.comments = prior.comments; - wxr.redirects = prior.redirects; - wxr.items = prior.items.filter((i) => i.type !== 'nav_menu_item'); - - let maxId = 0; - for (const it of wxr.items) maxId = Math.max(maxId, it.id); - // ...same for authors/categories/tags/terms/comments - wxr._nextId = maxId + 1; - } catch { - // Corrupt prior WXR: fall through and treat as a fresh run. - } -} -``` - -### Why it's better than the previous approach -Before: `--resume` was destructive — every resume run shrank the WXR to whatever was extracted in that single invocation, even though the underlying log correctly recorded all prior URLs as processed. Users who hit per-page failures and re-ran lost the bulk of their extraction silently. -After: resume is genuinely incremental — prior items survive, only new URLs are added, the WXR grows monotonically until extraction is complete. - - -## 2026-04-28 — Wix authenticated content endpoints — catalogue - -**Found by:** Claude + human contributor -**During:** Mapping Wix's authenticated traffic during a parallel Wix -migration project; needed a reference for the *content* endpoints (vs. -the dashboard infrastructure endpoints already documented) -**Type:** API endpoint | content type - -### What I found -The 2026-03-31 *Wix Dashboard API reverse engineering via CDP* entry -covers auth (cookie + XSRF + per-app JWT), window globals, and the -infrastructure endpoints a Wix dashboard hits at load (account, -premium-status, feature-flag, alerts, etc.). What it does not -catalogue is the ten *content* endpoints a logged-in editor or -dashboard hits to read the data the public renderer doesn't expose: -CMS Data Collections including drafts, contacts, members, full-variant -products, form submissions, bookings, blog drafts with Ricos -`richContent` source, full-resolution media originals, and hidden / -password-protected pages. - -### How it works -Added a new reference doc at `docs/wix-content-endpoints.md` listing -the ten endpoints with URL, response shape, what public scraping -misses, and per-endpoint gotchas (e.g. CMS items needing -`SANDBOX_PREFERRED` + `includeDraftItems: true` for drafts; signed -media URLs expiring in ~10 minutes; Stores `manageVariants` true/false -branching; three distinct forms-product variants). Linked from -`README.md`. - -### Why it's better than the previous approach -Today's adapter relies entirely on rendered HTML + JSON-LD + -opportunistic API capture from public navigation. The reference doc -gives future contributors a baseline of "here's what exists behind -auth, here's what each endpoint returns, here are the traps" — so -subsequent authenticated-mode work doesn't restart from scratch. - -## 2026-04-28 — Wix splits hosted media across three CDN hosts - -**Found by:** Claude + human contributor -**During:** Migrating Wix sites; noticed platform assets (icons, -decorative imagery) weren't being downloaded -**Type:** platform quirk - -### What I found -All Wix-hosted media uses one of three CDN hostnames: - -- `static.wixstatic.com` — images, documents (the well-known one) -- `static.parastorage.com` — platform assets: icons, decorative - imagery, pattern fills used by Wix templates -- `video.wixstatic.com` — video content (already covered by the - existing `wixstatic.com` term) - -The image-CDN regex in `extractImageUrls()` only matched -`wixstatic.com` / `wixmp.com`. `parastorage.com` was silently dropped -during the "only keep image-looking URLs" filter, so platform -decorative assets never made it into the media-download set. - -### How it works -Add `parastorage\.com` to the `imageCdns` regex inside -`extractImageUrls()` in `src/adapters/wix.ts`. Comment documents all -three hosts so the next reader doesn't have to re-discover them. - -### Why it's better than the previous approach -Before: any URL on `static.parastorage.com` was filtered out unless it -also passed the file-extension check, missing extension-less or -query-param-styled CDN URLs. After: all three Wix CDN hosts are -recognised consistently. - -## 2026-04-28 — Wix appends " Main" to every site name - -**Found by:** Claude + human contributor -**During:** Migrating multiple Wix sites; noticed every WordPress import -ended up with a site title like "My Studio Main" -**Type:** platform quirk - -### What I found -Wix's editor appends a literal " Main" suffix to every site's name. It -shows up in two places: - -- `` content ends in " Main" (e.g. - "Gilded Carat Main") -- `document.title` follows the pattern `Page Title | Site Name Main` - -The suffix is a Wix internal label (probably the default page-set -name, "Main"). It is never part of the agency's actual site name. - -### How it works -At the homepage `siteTitle` extraction site in `discover()`, take the -substring after the last ` | ` and strip a trailing ` Main`: - -```js -const t = document.title; -const pipeIdx = t.lastIndexOf(' | '); -const sitePart = pipeIdx > 0 ? t.slice(pipeIdx + 3).trim() : t; -return sitePart.replace(/ Main$/, '').trim(); -``` - -The per-page title stripping in `runExtractionLoop` (slice everything -after ` | `) already handles per-page titles correctly — the trailing -" Main" suffix goes with the site-name half. The bug was site-level -only. - -### Why it's better than the previous approach -Before: WordPress imports landed with site titles like -"Home | Gilded Carat Main". After: clean "Gilded Carat". - -## 2026-04-28 — Wix product pages expose stable `data-hook` selectors - -**Found by:** Claude + human contributor -**During:** Migrating Wix Stores sites where JSON-LD was malformed or -missing AND the products API call hadn't been captured during navigation -**Type:** platform quirk | content type - -### What I found -Wix product pages tag key elements with `data-hook="..."` attributes -that have been stable across every Wix Stores site we've tested. When -JSON-LD is missing or malformed *and* the products API call hasn't -been captured, the rendered DOM is still extractable via these hooks — -no need to give up on the product. - -| Element | Selector | -|---|---| -| Product title | `[data-hook="product-title"]` | -| Product price (clean) | `[data-hook="formatted-primary-price"]` | -| Product price (wrapper, includes SR "Price") | `[data-hook="product-price"]` | -| Product gallery root | `[data-hook="product-gallery-root"]` | -| Main product image | `[data-hook="main-media-image-wrapper"] img` | -| Thumbnail images | `[data-hook="thumbnail-image"] img` | -| Product description | `[data-hook="product-description"]` | -| Product options | `[data-hook="product-options"]` | - -The `[data-hook="product-price"]` wrapper contains a screen-reader span -(`[data-hook="sr-formatted-primary-price"]`) with the literal word -"Price" — use `[data-hook="formatted-primary-price"]` for the clean -value. - -### How it works -Added a third fallback path in `extractWixProduct()` after the -JSON-LD and captured-API paths. When both upstream paths fail, parse -the rendered HTML using the hooks above. Required adding an optional -`pageHtml` field to `PageData` so the raw HTML (already captured for -media-URL extraction) is available to the product extractor. - -### Why it's better than the previous approach -Before: `extractWixProduct()` returned `null` whenever JSON-LD was -missing AND the product API call wasn't captured (e.g. cached -navigation, slow hydration, throttled requests). After: name, price, -description, and gallery images recover from the rendered DOM — -typically the worst-case path that still yields a usable product -record. - - -## 2026-04-28 — Wix's `networkidle` never resolves; use `domcontentloaded` + delay - -**Found by:** Claude + human contributor -**During:** Building a Wix → WordPress.com migration tool against ~12 live Wix sites -**Type:** platform quirk | bug fix - -### What I found -Using `page.goto(url, { waitUntil: 'networkidle' })` against Wix sites -times out on roughly half of product pages. Wix's analytics, chat -widgets, and tracking pixels keep firing requests indefinitely, so the -network never goes idle inside the 30s budget. - -### How it works -Switch the wait strategy from `networkidle` to `domcontentloaded` and -add a fixed `await p.waitForTimeout(4000)` afterwards. The 4s delay -covers Wix's client-side hydration of lazy content (Thunderbolt -rendering engine). Applied at all three navigation sites in the Wix -adapter (page extraction, homepage crawl fallback, navigation -extraction). - -### Why it's better than the previous approach -Validated empirically across multiple live Wix sites: with -`networkidle`, ~50% of product pages timed out and emitted partial or -empty extractions. With `domcontentloaded` + 4s delay, the same pages -extract reliably and the 30s budget is no longer exhausted by -background telemetry. - -## 2026-04-17 — Dedupe Wix URLs across child sitemaps - -**Found by:** Claude + human contributor -**During:** Testing the Wix adapter against a range of live Wix sites -**Type:** bug fix - -### What I found - -`fetchSitemapPw()` pushed every non-XML URL found in each sitemap child into a flat `sitemapUrls` array with no deduplication. Wix sites commonly list the same URL in multiple child sitemaps — most often `/blog` appears in both `pages-sitemap.xml` (as a regular site page) and `blog-categories-sitemap.xml` (as the blog category index). The URL then gets processed twice, and the WXR ends up with two items sharing the same slug, which breaks WordPress import (the importer either rejects the second or silently appends a suffix, leaving inconsistent URLs). - -Observed on roughly 24% of tested sites — always the same `/blog` duplication pattern. - -### How it works - -Added two dedupe Sets in `discover()`: - -```ts -const seenUrls = new Set(); -const seenSitemaps = new Set(); - -async function fetchSitemapPw(sitemapUrl, depth = 0) { - if (depth > 3) return; - if (seenSitemaps.has(sitemapUrl)) return; - seenSitemaps.add(sitemapUrl); - // …existing fetch / parse… - for (const loc of locs) { - if (loc.endsWith('.xml')) { - await fetchSitemapPw(loc, depth + 1); - } else if (!seenUrls.has(loc)) { - seenUrls.add(loc); - sitemapUrls.push(loc); - } - } -} -``` - -`seenUrls` rejects identical URLs across sibling sitemaps. `seenSitemaps` prevents re-fetching a sitemap index file if it appears more than once (defensive — not observed during testing but cheap to add). - -### Why it's better than the previous approach - -Tested on an affected site after the fix: the WXR no longer contains two items with `slug=blog`. Content coverage unchanged — the URL is still extracted, just once. - ---- - -## 2026-04-17 — Dedupe Wix URLs across child sitemaps - -**Found by:** Claude + human contributor -**During:** Testing the Wix adapter against a range of live Wix sites -**Type:** bug fix - -### What I found - -`runExtractionLoop()` in `src/adapters/shared.ts` had a type-promotion fallback: if `classifyUrl()` returned `page` or `homepage`, it would re-check via a regex `/@type.*BlogPosting|NewsArticle|Article|SocialMediaPosting/` run across the full `pageData.content` string. Any occurrence anywhere in the HTML promoted the item to `post`. - -The problem: blog *listing* pages (`/blog--categories--X`, `/blog`) commonly embed `BlogPosting` JSON-LD cards for each post they display in their index. The regex happily matched those embedded cards and promoted the listing page to `post` — producing authorless "posts" in the WXR whose content was a list of links to other posts. Observed on multiple tested sites: one jewellery ecommerce site had 6 of 15 "posts" misclassified; an interior-design blog had 11 of 96; a furniture store had 2 of 7. - -### How it works - -Replaced the raw-content regex with a structured check using `pageData.jsonLd` (the array of already-parsed JSON-LD objects the adapter returned): - -```ts -const BLOG_TYPES = new Set(['BlogPosting', 'NewsArticle', 'Article', 'SocialMediaPosting']); -const isRealBlogPost = Array.isArray(pageData.jsonLd) && pageData.jsonLd.some((ld) => { - if (!ld || typeof ld !== 'object') return false; - const obj = ld as Record; - const atType = obj['@type']; - if (typeof atType !== 'string' || !BLOG_TYPES.has(atType)) return false; - const mep = obj.mainEntityOfPage; - if (mep && typeof mep === 'object') { - const mepRec = mep as Record; - const mepUrl = typeof mepRec.url === 'string' ? mepRec.url : - typeof mepRec['@id'] === 'string' ? mepRec['@id'] as string : null; - if (mepUrl && mepUrl !== url) return false; - } - return true; -}); -``` - -Two tightenings: (1) `@type` must be at the top level of a JSON-LD object, not anywhere in the raw HTML; (2) when `mainEntityOfPage` is present, its URL must match the current page URL — so embedded-card JSON-LD (whose `mainEntityOfPage` points to *other* posts) can't promote the current page. - -Also added `jsonLd?: unknown[]` to the `ExtractedPage` interface and piped `pageData.jsonLd` through the Wix adapter's `extractPage` callback so the shared loop has the parsed objects available. - -### Why it's better than the previous approach - -Tested on a food-blog site alongside the sibling URL-classifier fix that stops bare `/blog` from classifying as `post`: the `/blog` listing page is now correctly a `page` with its listing content, and no longer promoted to a post by its embedded BlogPosting cards for indexed posts. - -## 2026-04-17 — Wix sitemap discovery silently loses child sitemaps under CDN pressure - -**Found by:** Claude + human contributor -**During:** Testing the Wix adapter against multiple live sites in parallel -**Type:** bug fix - -### What I found - -`fetchSitemapPw()` in the Wix adapter's `discover()` wrapped `p.goto(sitemapUrl)` in `try { … } catch { /* sitemap fetch failed */ }` with a silent early-return on `!resp.ok()`. When Playwright timed out or the Wix CDN returned a transient error on a child sitemap (e.g. `pages-sitemap.xml`, `blog-posts-sitemap.xml`), the failure was swallowed — no log, no retry, no end-of-discovery warning. The extraction proceeded with whatever URLs happened to arrive before the failure, producing a WXR with (often) zero real pages. - -Observed on roughly 20% of sites during parallel-worker testing: several produced zero-content WXRs outright (media downloaded, pages empty), while others had `pages-sitemap.xml` children silently skipped while other sitemaps (store-products, blog-posts) went through. - -Re-running the affected sites sequentially (outside the parallel run) extracted them cleanly — confirming the failures were transient, not deterministic, and the old code gave the user no way to know they'd lost data. - -### How it works - -Wrapped the `p.goto` call in an up-to-3-attempt retry loop with exponential backoff (500ms × attempt number): - -```ts -const RETRIES = 3; -for (let attempt = 1; attempt <= RETRIES; attempt++) { - try { - const resp = await p.goto(sitemapUrl, { timeout: 15000 }); - if (!resp || !resp.ok()) { - lastErr = resp ? 'HTTP status-not-ok' : 'no response'; - if (attempt < RETRIES) { await sleep(500 * attempt); continue; } - console.warn(`[wix:discover] sitemap fetch failed after ${RETRIES} attempts: ${sitemapUrl} (${lastErr})`); - sitemapFailures.push({ url: sitemapUrl, reason: lastErr }); - return; - } - // …parse and recurse as before, then `return` on success - } catch (err) { - // …same retry pattern on thrown errors - } -} -``` - -On final failure the URL + reason is logged via `console.warn` and appended to a `sitemapFailures` array. After the recursive discovery completes, an end-of-phase summary warns if any fetches failed — so the operator sees that inventory may be incomplete rather than silently getting partial data. - -### Why it's better than the previous approach - -Tested on a small Wix business site with a dry run (clean discovery, no retries needed). The previous silent-failure behavior turned transient network blips or CDN rate-limits into silent data loss; now the same blips are retried and — if persistent — surfaced as visible warnings. - - - -## 2026-04-17 — Site-level JSON-LD leaks into Wix category-page content - -**Found by:** Claude + human contributor -**During:** Testing the Wix adapter against a range of live Wix sites -**Type:** bug fix - -### What I found - -`deriveContent()` step 3 accepted `description` from *any* JSON-LD object on the page. Wix ecommerce templates commonly include a site-level JSON-LD block — `@type: "FurnitureStore"`, `"Organization"`, `"LocalBusiness"`, `"Restaurant"`, etc. — whose `description` field is a generic store tagline written once by the site owner. Every page that falls through to step 3 (Wix category archives whose product grids are JS-rendered, for example) ends up with the same site-wide tagline as its body content. - -Observed on a tested furniture-store site: 49 of 58 pages (84%) had the identical 266-character site-tagline as `` — because each `/category/…` page has no static content (the product grid is rendered client-side) so derivation fell through API → DOM → and grabbed the `FurnitureStore` JSON-LD description. When imported to WordPress, the category pages are indistinguishable. - -### How it works - -Two changes to `deriveContent()`: - -1. **`@type` allow-list for JSON-LD description**: introduced `CONTENT_LD_TYPES = {Article, BlogPosting, NewsArticle, SocialMediaPosting, Product, ItemPage, Event, Recipe, Course, Book, Movie}`. The JSON-LD `description` fallback now only accepts a match whose top-level `@type` is in the allow-list. `articleBody` remains universally accepted (it's inherently content-level). - -2. **`og:description` fallback** (new step 4): when steps 1–3 fail, use `pageData.meta.ogDescription || pageData.meta.description` if ≥ 50 chars. `og:description` is per-page (written by the site owner for sharing), so pages that share the old site-level fallback now carry their own per-page description instead. - -The accessibility-tree fallback moves from step 4 to step 5; empty from 5 to 6. - -### Why it's better than the previous approach - -Tested on two category pages from the affected site: both now derive content from `og:description` instead of the shared `FurnitureStore` block, so the category pages produce distinct content rather than identical boilerplate. - ---- - -## 2026-04-17 — Wix API responses leak ``/`` tags as page content - -**Found by:** Claude + human contributor -**During:** Testing the Wix adapter against a range of live Wix sites -**Type:** bug fix - -### What I found - -`deriveContent()` in the Wix adapter tries API-call responses first, using `findHtmlContent()` to walk JSON bodies for keys named `html`/`richText`/`body`/`content`/`text`/`plainText` containing HTML-like strings. The existing validator (after the earlier tag-manager fix) strips ``:null}var tu=3,Mvt=30,Pvt=/\b(\d{4}-\d{2}-\d{2}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+\d{1,2},?\s*\d{4}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+\d{1,2})\b/i,Lvt="html,body,main,section";function NR(e,t){let r=e(t).children().toArray().map(n=>n.tagName?.toLowerCase()).filter(n=>!!n).sort();return`${t.tagName.toLowerCase()}>${r.join(",")}`}function Fvt(e,t){let r=[],n=i=>{for(let s of e(i).children().toArray())r.push(s),n(s)};return n(t),r}function MR(e,t){let r=e.parent;for(;r;){if(r===t)return!0;r=r.parent}return!1}function Ovt(e,t){let r=i=>{let s=[],o=i;for(;o&&o.type==="tag";)s.push(o),o=o.parent;return s},n=new Set(r(e));for(let i of r(t))if(n.has(i))return i;return null}function Uvt(e,t){let r=new Map;for(let a of t){let c=a.parent;if(!c||c.type!=="tag")continue;let u=r.get(c)??[];u.push(a),r.set(c,u)}let n=[],i=[];for(let[a,c]of r)c.length>=tu?n.push({cards:[...c],container:a}):i.push(...c);if(n.length===0)return t.length>=tu?[t]:[];for(let a of i){let c=null;for(let u of n){let l=Ovt(a,u.container);l&&(!c||MR(l,c.ancestor))&&(c={grid:u,ancestor:l})}c&&(c.grid.cards.push(a),c.grid.container=c.ancestor)}let s=e("*").toArray(),o=new Map(s.map((a,c)=>[a,c]));return n.map(a=>a.cards.sort((c,u)=>(o.get(c)??0)-(o.get(u)??0)))}function $vt(e,t){let r=e(t).attr("id");if(r&&e(`#${Hvt(r)}`).length===1)return`#${r}`;let n=[],i=t;for(;i&&i.type==="tag";){let s=e(i).attr("id");if(s){n.unshift(`#${s}`);break}let o=i.tagName.toLowerCase(),a=e(i).prevAll(o).length+1;n.unshift(`${o}:nth-of-type(${a})`),i=i.parent}return n.join(" > ")}function Hvt(e){return e.replace(/[^a-zA-Z0-9_-]/g,t=>`\\${t}`)}function CV(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function pxe(e,t){let r=e(t),n=r.find("h1,h2,h3,h4,h5,h6").length>0||r.find('[class*="title" i],[class*="headline" i]').length>0,i=r.find("img[src],source[srcset]").length>0||!!r.find('[style*="background-image" i]').attr("style"),s=r.find("a[href]").toArray().some(a=>e(a).text().trim().length>0),o=r.text().replace(/\s+/g," ").trim().length;return n&&(i||s)&&o>=20}function DR(e){let t=e.find("h1,h2,h3,h4,h5,h6").first();return t.length&&t.text().trim()?t.text().replace(/\s+/g," ").trim():e.find('[class*="title" i],[class*="headline" i]').first().text().replace(/\s+/g," ").trim()}function jvt(e,t){return e(t).children("h1,h2,h3,h4,h5,h6").first().text().replace(/\s+/g," ").trim()}function qvt(e){let t=e.find("img[src]").first().attr("src");if(t)return t;let n=(e.find('[style*="background-image" i]').first().attr("style")??"").match(/url\(\s*['"]?([^'")]+)['"]?\s*\)/i);return n?n[1]:""}function zvt(e,t){let r=e(t);return r.is('[class*="cat" i],[class*="tag" i]')||r.closest('[class*="cat" i],[class*="tag" i]').length>0?1:0}function RR(e,t,r){let n=e(t),i=DR(n),s=n.find("h1,h2,h3,h4,h5,h6").first().find("a[href]").first().attr("href"),o=n.find("a[href]").toArray().map(A=>e(A).attr("href")).find(Boolean),a=s??o??"",c=qvt(n),u=n.find("p").first().text().replace(/\s+/g," ").trim(),d=(n.find("time").first().text().trim()||(n.text().match(Pvt)?.[0]??"")).trim(),p=n.find("a[href]").toArray().map((A,g)=>({href:e(A).attr("href")??"",text:e(A).text().replace(/\s+/g," ").trim(),order:g,score:zvt(e,A)})).filter(A=>A.text&&A.text!==i&&A.href!==a&&A.text.length<=Mvt).sort((A,g)=>g.score-A.score||A.order-g.order)[0]?.text??"";return{id:CV(i)||CV(a.replace(/\.[a-z]+$/i,""))||`card-${r+1}`,title:i,excerpt:u,image:c,category:p,date:d,link:a,meta:{}}}function IV(e,t,r){let n=le(e.html(t),void 0,!1),i=n.root().children().first();if(r.title){let o=i.find("h1,h2,h3,h4,h5,h6").first(),a=o.find("a[href]").first().length?o.find("a[href]").first():o;a.length&&a.attr("data-dla-text","title").text("")}if(r.excerpt){let o=i.find("p").toArray().find(a=>n(a).text().replace(/\s+/g," ").trim()===r.excerpt);o&&n(o).attr("data-dla-text","content").text("")}if(r.category){let o=i.find("a[href]").toArray().find(a=>n(a).text().replace(/\s+/g," ").trim()===r.category);o&&n(o).attr("data-dla-text","cat.label").text("")}if(r.date){let o=i.find("time").first();if(o.length)o.attr("data-dla-text","meta.date").text("");else{let a=i.find("span").toArray().find(c=>n(c).text().replace(/\s+/g," ").trim()===r.date);a&&n(a).attr("data-dla-text","meta.date").text("")}}if(r.image){let o=i.find("img[src]").first();o.length&&o.attr("data-dla-attr","src:meta.image").removeAttr("src")}let s=(o,a)=>{let c=o.attr("data-dla-attr");o.attr("data-dla-attr",c?`${c},${a}`:a)};if(r.link&&i.find("a[href]").toArray().forEach(o=>{(n(o).attr("href")??"")===r.link&&s(n(o),"href:permalink")}),r.category){let o=i.find('[data-dla-text="cat.label"]').first();o.length&&o.is("a[href]")&&s(o,"href:cat.url")}return(n.html(i)??"").trim()}function Vvt(e,t,r){let n=r.filter(l=>l.parent===t),i=r.filter(l=>l.parent!==t),s=new Map;for(let l of i){let d=l.parent;if(!d||d.type!=="tag")continue;let f=s.get(d)??[];f.push(l),s.set(d,f)}if(n.length<1||s.size!==1)return;let[[o,a]]=[...s.entries()];if(a.length<2||n.length+a.length!==r.length||!MR(o,t)||r.includes(o))return;let c=[...n,...a].map(l=>CV(RR(e,l,0).category)).filter(Boolean),u=c.length>0&&c.every(l=>l===c[0])?c[0]:void 0;return{leadCount:n.length,columnWrapperClass:(e(o).attr("class")??"").trim(),leadTemplate:IV(e,n[0],RR(e,n[0],0)),rowTemplate:IV(e,a[0],RR(e,a[0],0)),...u?{termSlug:u}:{}}}function Gvt(e,t,r,n){let i=Zvt(e,t),s=$vt(e,i),o=(e(i).attr("class")??"").trim(),a=t.filter(g=>pxe(e,g));if(a.lengthRR(e,g,m)),u=c.map(g=>{let m={id:g.id,title:g.title,link:g.link,excerpt:g.excerpt};g.image&&(m.image=g.image),g.category&&(m.category=g.category),g.date&&(m.date=g.date);for(let[b,E]of Object.entries(g.meta))m[`meta_${b}`]=E;return m}),l=new Map;for(let g of c)g.link&&l.set(g.link,(l.get(g.link)??0)+1);for(let g=0;g1:!1,E=c[g].excerpt;if(n.resolvePage&&m&&!b)try{let C=n.resolvePage(m);if(C){let I=QR(C);I&&I.trim()&&(E=I)}}catch{}u[g].content=E}let d=[...l.entries()].filter(([,g])=>g>1).map(([g])=>g),f=d.length?` shared-target(single-template)=${d.join(",")}`:"",p=c.every(g=>g.title),h=IV(e,a[0],c[0]),A=Vvt(e,i,a);return{containerSelector:s,containerClass:o,records:u,cardTemplate:h,...A?{featured:A}:{},confidence:p&&h?"high":"low",evidence:`signature=${r} cards=${a.length} roles=title,excerpt,image,category,date,link${f}`}}function Wvt(e){let t=new Map;for(let r of e){let n=t.get(r.sig)??{sig:r.sig,candidates:[],richCards:[]};n.candidates.push(r);for(let i of r.richCards)n.richCards.includes(i)||n.richCards.push(i);t.set(r.sig,n)}return[...t.values()]}function fxe(e,t){return e.map(r=>t.filter(n=>MR(n,r)).length)}function Yvt(e,t,r){let n=0,i=!1;for(let s of t){let o=r.filter(u=>MR(u,s));if(o.length===0)continue;if(o.length!==1)return"none";let a=DR(e(s)),c=DR(e(o[0]));a&&c&&a!==c&&(i=!0),n+=1}return nc>=tu)&&r.add(s)}for(let s of i)for(let o of i){if(s===o||fxe(s.richCards,o.richCards).reduce((l,d)=>l+d,0)!==o.richCards.length)continue;let u=Yvt(e,s.richCards,o.richCards);u==="part"?n.add(o.sig):u==="wrapper"&&s.candidates.forEach(l=>r.add(l))}return t.filter(s=>!r.has(s)&&!n.has(s.sig))}function Zvt(e,t){let r=t[0].parent;return r&&r.type==="tag"&&!e(r).is(Lvt)?r:Kvt(e,t)?t[0]:r??t[0]}function Kvt(e,t){if(t.lengthn.parent).filter(n=>!!n))];return r.lengthn.tagName?.toLowerCase()!=="section")||r.some(n=>t.filter(i=>i.parent===n).length!==1)?!1:t.some(n=>{let i=jvt(e,n.parent),s=DR(e(n));return!!(i&&s&&i!==s)})}function wV(e,t={}){let r=le(e),n=r("body")[0],i=n?Fvt(r,n):[],s=new Map;for(let l of i){if(r(l).children().length===0)continue;let d=NR(r,l),f=s.get(d)??[];f.push(l),s.set(d,f)}let o=[];for(let[l,d]of s)if(!(d.length=tu&&o.push({cards:f,sig:l});let a=o.map(l=>({...l,richCards:l.cards.filter(d=>pxe(r,d))})).filter(l=>l.richCards.length>=tu),c=Jvt(r,a),u=[];for(let{cards:l,sig:d}of c){let f=Gvt(r,l,d,t);f.records.length>0&&u.push(f)}return u}var Xvt=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],bxe=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],ext="\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65",Exe="\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC",SV={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},vV="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",txt={5:vV,"5module":vV+" export import",6:vV+" const class extends export import super"},Cxe=/^in(stanceof)?$/,rxt=new RegExp("["+Exe+"]"),nxt=new RegExp("["+Exe+ext+"]");function BV(e,t){for(var r=65536,n=0;ne)return!1;if(r+=t[n+1],r>=e)return!0}return!1}function ru(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&rxt.test(String.fromCharCode(e)):t===!1?!1:BV(e,bxe)}function Zd(e,t){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&nxt.test(String.fromCharCode(e)):t===!1?!1:BV(e,bxe)||BV(e,Xvt)}var Sr=function(t,r){r===void 0&&(r={}),this.label=t,this.keyword=r.keyword,this.beforeExpr=!!r.beforeExpr,this.startsExpr=!!r.startsExpr,this.isLoop=!!r.isLoop,this.isAssign=!!r.isAssign,this.prefix=!!r.prefix,this.postfix=!!r.postfix,this.binop=r.binop||null,this.updateContext=null};function ma(e,t){return new Sr(e,{beforeExpr:!0,binop:t})}var ya={beforeExpr:!0},ro={startsExpr:!0},QV={};function Ar(e,t){return t===void 0&&(t={}),t.keyword=e,QV[e]=new Sr(e,t)}var x={num:new Sr("num",ro),regexp:new Sr("regexp",ro),string:new Sr("string",ro),name:new Sr("name",ro),privateId:new Sr("privateId",ro),eof:new Sr("eof"),bracketL:new Sr("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new Sr("]"),braceL:new Sr("{",{beforeExpr:!0,startsExpr:!0}),braceR:new Sr("}"),parenL:new Sr("(",{beforeExpr:!0,startsExpr:!0}),parenR:new Sr(")"),comma:new Sr(",",ya),semi:new Sr(";",ya),colon:new Sr(":",ya),dot:new Sr("."),question:new Sr("?",ya),questionDot:new Sr("?."),arrow:new Sr("=>",ya),template:new Sr("template"),invalidTemplate:new Sr("invalidTemplate"),ellipsis:new Sr("...",ya),backQuote:new Sr("`",ro),dollarBraceL:new Sr("${",{beforeExpr:!0,startsExpr:!0}),eq:new Sr("=",{beforeExpr:!0,isAssign:!0}),assign:new Sr("_=",{beforeExpr:!0,isAssign:!0}),incDec:new Sr("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Sr("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:ma("||",1),logicalAND:ma("&&",2),bitwiseOR:ma("|",3),bitwiseXOR:ma("^",4),bitwiseAND:ma("&",5),equality:ma("==/!=/===/!==",6),relational:ma("/<=/>=",7),bitShift:ma("<>/>>>",8),plusMin:new Sr("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:ma("%",10),star:ma("*",10),slash:ma("/",10),starstar:new Sr("**",{beforeExpr:!0}),coalesce:ma("??",1),_break:Ar("break"),_case:Ar("case",ya),_catch:Ar("catch"),_continue:Ar("continue"),_debugger:Ar("debugger"),_default:Ar("default",ya),_do:Ar("do",{isLoop:!0,beforeExpr:!0}),_else:Ar("else",ya),_finally:Ar("finally"),_for:Ar("for",{isLoop:!0}),_function:Ar("function",ro),_if:Ar("if"),_return:Ar("return",ya),_switch:Ar("switch"),_throw:Ar("throw",ya),_try:Ar("try"),_var:Ar("var"),_const:Ar("const"),_while:Ar("while",{isLoop:!0}),_with:Ar("with"),_new:Ar("new",{beforeExpr:!0,startsExpr:!0}),_this:Ar("this",ro),_super:Ar("super",ro),_class:Ar("class",ro),_extends:Ar("extends",ya),_export:Ar("export"),_import:Ar("import",ro),_null:Ar("null",ro),_true:Ar("true",ro),_false:Ar("false",ro),_in:Ar("in",{beforeExpr:!0,binop:7}),_instanceof:Ar("instanceof",{beforeExpr:!0,binop:7}),_typeof:Ar("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Ar("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Ar("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},no=/\r\n?|\n|\u2028|\u2029/,ixt=new RegExp(no.source,"g");function b0(e){return e===10||e===13||e===8232||e===8233}function Ixe(e,t,r){r===void 0&&(r=e.length);for(var n=t;n>10)+55296,(e&1023)+56320))}var axt=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,ww=function(t,r){this.line=t,this.column=r};ww.prototype.offset=function(t){return new ww(this.line,this.column+t)};var $R=function(t,r,n){this.start=r,this.end=n,t.sourceFile!==null&&(this.source=t.sourceFile)};function vxe(e,t){for(var r=1,n=0;;){var i=Ixe(e,n,t);if(i<0)return new ww(r,t-n);++r,n=i}}var kV={ecmaVersion:null,sourceType:"script",strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},gxe=!1;function cxt(e){var t={};for(var r in kV)t[r]=e&&E0(e,r)?e[r]:kV[r];if(t.ecmaVersion==="latest"?t.ecmaVersion=1e8:t.ecmaVersion==null?(!gxe&&typeof console=="object"&&console.warn&&(gxe=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required. +Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),t.allowReserved==null&&(t.allowReserved=t.ecmaVersion<5),(!e||e.allowHashBang==null)&&(t.allowHashBang=t.ecmaVersion>=14),hxe(t.onToken)){var n=t.onToken;t.onToken=function(i){return n.push(i)}}if(hxe(t.onComment)&&(t.onComment=uxt(t,t.onComment)),t.sourceType==="commonjs"&&t.allowAwaitOutsideFunction)throw new Error("Cannot use allowAwaitOutsideFunction with sourceType: commonjs");return t}function uxt(e,t){return function(r,n,i,s,o,a){var c={type:r?"Block":"Line",value:n,start:i,end:s};e.locations&&(c.loc=new $R(this,o,a)),e.ranges&&(c.range=[i,s]),t.push(c)}}var kh=1,_h=2,RV=4,xxe=8,DV=16,Bxe=32,HR=64,kxe=128,Th=256,Sw=512,_xe=1024,jR=kh|_h|Th;function NV(e,t){return _h|(e?RV:0)|(t?xxe:0)}var LR=0,MV=1,ol=2,Txe=3,Qxe=4,Rxe=5,Kn=function(t,r,n){this.options=t=cxt(t),this.sourceFile=t.sourceFile,this.keywords=Jd(txt[t.ecmaVersion>=6?6:t.sourceType==="module"?"5module":5]);var i="";t.allowReserved!==!0&&(i=SV[t.ecmaVersion>=6?6:t.ecmaVersion===5?5:3],t.sourceType==="module"&&(i+=" await")),this.reservedWords=Jd(i);var s=(i?i+" ":"")+SV.strict;this.reservedWordsStrict=Jd(s),this.reservedWordsStrictBind=Jd(s+" "+SV.strictBind),this.input=String(r),this.containsEsc=!1,n?(this.pos=n,this.lineStart=this.input.lastIndexOf(` +`,n-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(no).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=x.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=t.sourceType==="module",this.strict=this.inModule||t.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&t.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType==="commonjs"?_h:kh),this.regexpState=null,this.privateNameStack=[]},Ea={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};Kn.prototype.parse=function(){var t=this,r=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return t.parseTopLevel(r)})};Ea.inFunction.get=function(){return(this.currentVarScope().flags&_h)>0};Ea.inGenerator.get=function(){return(this.currentVarScope().flags&xxe)>0};Ea.inAsync.get=function(){return(this.currentVarScope().flags&RV)>0};Ea.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e],r=t.flags;if(r&(Th|Sw))return!1;if(r&_h)return(r&RV)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};Ea.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&kh)};Ea.allowSuper.get=function(){var e=this.currentThisScope(),t=e.flags;return(t&HR)>0||this.options.allowSuperOutsideMethod};Ea.allowDirectSuper.get=function(){return(this.currentThisScope().flags&kxe)>0};Ea.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Ea.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e],r=t.flags;if(r&(Th|Sw)||r&_h&&!(r&DV))return!0}return!1};Ea.allowUsing.get=function(){var e=this.currentScope(),t=e.flags;return!(t&_xe||!this.inModule&&t&kh)};Ea.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&Th)>0};Kn.extend=function(){for(var t=[],r=arguments.length;r--;)t[r]=arguments[r];for(var n=this,i=0;i=,?^&]/.test(i)||i==="!"&&this.input.charAt(n+1)==="=")}e+=t[0].length,gi.lastIndex=e,e+=gi.exec(this.input)[0].length,this.input[e]===";"&&e++}};is.eat=function(e){return this.type===e?(this.next(),!0):!1};is.isContextual=function(e){return this.type===x.name&&this.value===e&&!this.containsEsc};is.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1};is.catchStackOverflow=function(e){try{return e()}catch(t){if(t instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(t.message)||/\btoo much recursion\b/i.test(t.message)))this.raise(this.start,"Not enough stack space to parse input");else throw t}};is.expectContextual=function(e){this.eatContextual(e)||this.unexpected()};is.canInsertSemicolon=function(){return this.type===x.eof||this.type===x.braceR||no.test(this.input.slice(this.lastTokEnd,this.start))};is.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};is.semicolon=function(){!this.eat(x.semi)&&!this.insertSemicolon()&&this.unexpected()};is.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0};is.expect=function(e){this.eat(e)||this.unexpected()};is.unexpected=function(e){this.raise(e??this.start,"Unexpected token")};var qR=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};is.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var r=t?e.parenthesizedAssign:e.parenthesizedBind;r>-1&&this.raiseRecoverable(r,t?"Assigning to rvalue":"Parenthesized pattern")}};is.checkExpressionErrors=function(e,t){if(!e)return!1;var r=e.shorthandAssign,n=e.doubleProto;if(!t)return r>=0||n>=0;r>=0&&this.raise(r,"Shorthand property assignments are valid only in destructuring patterns"),n>=0&&this.raiseRecoverable(n,"Redefinition of __proto__ property")};is.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case x._class:return e&&this.unexpected(),this.parseClass(i,!0);case x._if:return this.parseIfStatement(i);case x._return:return this.parseReturnStatement(i);case x._switch:return this.parseSwitchStatement(i);case x._throw:return this.parseThrowStatement(i);case x._try:return this.parseTryStatement(i);case x._const:case x._var:return s=s||this.value,e&&s!=="var"&&this.unexpected(),this.parseVarStatement(i,s);case x._while:return this.parseWhileStatement(i);case x._with:return this.parseWithStatement(i);case x.braceL:return this.parseBlock(!0,i);case x.semi:return this.parseEmptyStatement(i);case x._export:case x._import:if(this.options.ecmaVersion>10&&n===x._import){gi.lastIndex=this.pos;var o=gi.exec(this.input),a=this.pos+o[0].length,c=this.input.charCodeAt(a);if(c===40||c===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===x._import?this.parseImport(i):this.parseExport(i,r);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var u=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(u)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),e&&this.raise(this.start,"Using declaration is not allowed in single-statement positions"),u==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(i,!1,u),this.semicolon(),this.finishNode(i,"VariableDeclaration");var l=this.value,d=this.parseExpression();return n===x.name&&d.type==="Identifier"&&this.eat(x.colon)?this.parseLabeledStatement(i,l,d,e):this.parseExpressionStatement(i,d)}};nt.parseBreakContinueStatement=function(e,t){var r=t==="break";this.next(),this.eat(x.semi)||this.insertSemicolon()?e.label=null:this.type!==x.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var n=0;n=6?this.eat(x.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")};nt.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(PV),this.enterScope(0),this.expect(x.parenL),this.type===x.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var r=this.isLet();if(this.type===x._var||this.type===x._const||r){var n=this.startNode(),i=r?"let":this.value;return this.next(),this.parseVar(n,!0,i),this.finishNode(n,"VariableDeclaration"),this.parseForAfterInit(e,n,t)}var s=this.isContextual("let"),o=!1,a=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(a){var c=this.startNode();return this.next(),a==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.parseVar(c,!0,a),this.finishNode(c,"VariableDeclaration"),this.parseForAfterInit(e,c,t)}var u=this.containsEsc,l=new qR,d=this.start,f=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===x._in||(o=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===x._in&&this.unexpected(t),e.await=!0):o&&this.options.ecmaVersion>=8&&(f.start===d&&!u&&f.type==="Identifier"&&f.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(e.await=!1)),s&&o&&this.raise(f.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(f,!1,l),this.checkLValPattern(f),this.parseForIn(e,f)):(this.checkExpressionErrors(l,!0),t>-1&&this.unexpected(t),this.parseFor(e,f))};nt.parseForAfterInit=function(e,t,r){return(this.type===x._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&t.declarations.length===1?(this.type===x._in?((t.kind==="using"||t.kind==="await using")&&!t.declarations[0].init&&this.raise(this.start,"Using declaration is not allowed in for-in loops"),this.options.ecmaVersion>=9&&r>-1&&this.unexpected(r)):this.options.ecmaVersion>=9&&(e.await=r>-1),this.parseForIn(e,t)):(r>-1&&this.unexpected(r),this.parseFor(e,t))};nt.parseFunctionStatement=function(e,t,r){return this.next(),this.parseFunction(e,Iw|(r?0:_V),!1,t)};nt.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(x._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")};nt.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(x.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")};nt.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(x.braceL),this.labels.push(dxt),this.enterScope(_xe);for(var t,r=!1;this.type!==x.braceR;)if(this.type===x._case||this.type===x._default){var n=this.type===x._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),n?t.test=this.parseExpression():(r&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),r=!0,t.test=null),this.expect(x.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")};nt.parseThrowStatement=function(e){return this.next(),no.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var fxt=[];nt.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type==="Identifier";return this.enterScope(t?Bxe:0),this.checkLValPattern(e,t?Qxe:ol),this.expect(x.parenR),e};nt.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===x._catch){var t=this.startNode();this.next(),this.eat(x.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(x._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")};nt.parseVarStatement=function(e,t,r){return this.next(),this.parseVar(e,!1,t,r),this.semicolon(),this.finishNode(e,"VariableDeclaration")};nt.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(PV),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")};nt.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")};nt.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")};nt.parseLabeledStatement=function(e,t,r,n){for(var i=0,s=this.labels;i=0;c--){var u=this.labels[c];if(u.statementStart===e.start)u.statementStart=this.start,u.kind=a;else break}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(n?n.indexOf("label")===-1?n+"label":n:"label"),this.labels.pop(),e.label=r,this.finishNode(e,"LabeledStatement")};nt.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")};nt.parseBlock=function(e,t,r){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(x.braceL),e&&this.enterScope(0);this.type!==x.braceR;){var n=this.parseStatement(null);t.body.push(n)}return r&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")};nt.parseFor=function(e,t){return e.init=t,this.expect(x.semi),e.test=this.type===x.semi?null:this.parseExpression(),this.expect(x.semi),e.update=this.type===x.parenR?null:this.parseExpression(),this.expect(x.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")};nt.parseForIn=function(e,t){var r=this.type===x._in;return this.next(),t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!r||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")&&this.raise(t.start,(r?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=r?this.parseExpression():this.parseMaybeAssign(),this.expect(x.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,r?"ForInStatement":"ForOfStatement")};nt.parseVar=function(e,t,r,n){for(e.declarations=[],e.kind=r;;){var i=this.startNode();if(this.parseVarId(i,r),this.eat(x.eq)?i.init=this.parseMaybeAssign(t):!n&&r==="const"&&!(this.type===x._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!n&&(r==="using"||r==="await using")&&this.options.ecmaVersion>=17&&this.type!==x._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+r+" declaration"):!n&&i.id.type!=="Identifier"&&!(t&&(this.type===x._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):i.init=null,e.declarations.push(this.finishNode(i,"VariableDeclarator")),!this.eat(x.comma))break}return e};nt.parseVarId=function(e,t){e.id=t==="using"||t==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t==="var"?MV:ol,!1)};var Iw=1,_V=2,Dxe=4;nt.parseFunction=function(e,t,r,n,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!n)&&(this.type===x.star&&t&_V&&this.unexpected(),e.generator=this.eat(x.star)),this.options.ecmaVersion>=8&&(e.async=!!n),t&Iw&&(e.id=t&Dxe&&this.type!==x.name?null:this.parseIdent(),e.id&&!(t&_V)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?MV:ol:Txe));var s=this.yieldPos,o=this.awaitPos,a=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(NV(e.async,e.generator)),t&Iw||(e.id=this.type===x.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,r,!1,i),this.yieldPos=s,this.awaitPos=o,this.awaitIdentPos=a,this.finishNode(e,t&Iw?"FunctionDeclaration":"FunctionExpression")};nt.parseFunctionParams=function(e){this.expect(x.parenL),e.params=this.parseBindingList(x.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};nt.parseClass=function(e,t){this.next();var r=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var n=this.enterClassBody(),i=this.startNode(),s=!1;for(i.body=[],this.expect(x.braceL);this.type!==x.braceR;){var o=this.parseClassElement(e.superClass!==null);o&&(i.body.push(o),o.type==="MethodDefinition"&&o.kind==="constructor"?(s&&this.raiseRecoverable(o.start,"Duplicate constructor in the same class"),s=!0):o.key&&o.key.type==="PrivateIdentifier"&&pxt(n,o)&&this.raiseRecoverable(o.key.start,"Identifier '#"+o.key.name+"' has already been declared"))}return this.strict=r,this.next(),e.body=this.finishNode(i,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};nt.parseClassElement=function(e){if(this.eat(x.semi))return null;var t=this.options.ecmaVersion,r=this.startNode(),n="",i=!1,s=!1,o="method",a=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(x.braceL))return this.parseClassStaticBlock(r),r;this.isClassElementNameStart()||this.type===x.star?a=!0:n="static"}if(r.static=a,!n&&t>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===x.star)&&!this.canInsertSemicolon()?s=!0:n="async"),!n&&(t>=9||!s)&&this.eat(x.star)&&(i=!0),!n&&!s&&!i){var c=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?o=c:n=c)}if(n?(r.computed=!1,r.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),r.key.name=n,this.finishNode(r.key,"Identifier")):this.parseClassElementName(r),t<13||this.type===x.parenL||o!=="method"||i||s){var u=!r.static&&FR(r,"constructor"),l=u&&e;u&&o!=="method"&&this.raise(r.key.start,"Constructor can't have get/set modifier"),r.kind=u?"constructor":o,this.parseClassMethod(r,i,s,l)}else this.parseClassField(r);return r};nt.isClassElementNameStart=function(){return this.type===x.name||this.type===x.privateId||this.type===x.num||this.type===x.string||this.type===x.bracketL||this.type.keyword};nt.parseClassElementName=function(e){this.type===x.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)};nt.parseClassMethod=function(e,t,r,n){var i=e.key;e.kind==="constructor"?(t&&this.raise(i.start,"Constructor can't be a generator"),r&&this.raise(i.start,"Constructor can't be an async method")):e.static&&FR(e,"prototype")&&this.raise(i.start,"Classes may not have a static property named prototype");var s=e.value=this.parseMethod(t,r,n);return e.kind==="get"&&s.params.length!==0&&this.raiseRecoverable(s.start,"getter should have no params"),e.kind==="set"&&s.params.length!==1&&this.raiseRecoverable(s.start,"setter should have exactly one param"),e.kind==="set"&&s.params[0].type==="RestElement"&&this.raiseRecoverable(s.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")};nt.parseClassField=function(e){return FR(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&FR(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(x.eq)?(this.enterScope(Sw|HR),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,"PropertyDefinition")};nt.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(Th|HR);this.type!==x.braceR;){var r=this.parseStatement(null);e.body.push(r)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")};nt.parseClassId=function(e,t){this.type===x.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,ol,!1)):(t===!0&&this.unexpected(),e.id=null)};nt.parseClassSuper=function(e){e.superClass=this.eat(x._extends)?this.parseExprSubscripts(null,!1):null};nt.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared};nt.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,r=e.used;if(this.options.checkPrivateFields)for(var n=this.privateNameStack.length,i=n===0?null:this.privateNameStack[n-1],s=0;s=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==x.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")};nt.parseExport=function(e,t){if(this.next(),this.eat(x.star))return this.parseExportAllDeclaration(e,t);if(this.eat(x._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),e.declaration.type==="VariableDeclaration"?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==x.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var r=0,n=e.specifiers;r=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,"ExportNamedDeclaration")};nt.parseExportDeclaration=function(e){return this.parseStatement(null)};nt.parseExportDefaultDeclaration=function(){var e;if(this.type===x._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,Iw|Dxe,!1,e)}else if(this.type===x._class){var r=this.startNode();return this.parseClass(r,"nullableID")}else{var n=this.parseMaybeAssign();return this.semicolon(),n}};nt.checkExport=function(e,t,r){e&&(typeof t!="string"&&(t=t.type==="Identifier"?t.name:t.value),E0(e,t)&&this.raiseRecoverable(r,"Duplicate export '"+t+"'"),e[t]=!0)};nt.checkPatternExport=function(e,t){var r=t.type;if(r==="Identifier")this.checkExport(e,t,t.start);else if(r==="ObjectPattern")for(var n=0,i=t.properties;n=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")};nt.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,ol),this.finishNode(e,"ImportSpecifier")};nt.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,ol),this.finishNode(e,"ImportDefaultSpecifier")};nt.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,ol),this.finishNode(e,"ImportNamespaceSpecifier")};nt.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===x.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(x.comma)))return e;if(this.type===x.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(x.braceL);!this.eat(x.braceR);){if(t)t=!1;else if(this.expect(x.comma),this.afterTrailingComma(x.braceR))break;e.push(this.parseImportSpecifier())}return e};nt.parseWithClause=function(){var e=[];if(!this.eat(x._with))return e;this.expect(x.braceL);for(var t={},r=!0;!this.eat(x.braceR);){if(r)r=!1;else if(this.expect(x.comma),this.afterTrailingComma(x.braceR))break;var n=this.parseImportAttribute(),i=n.key.type==="Identifier"?n.key.name:n.key.value;E0(t,i)&&this.raiseRecoverable(n.key.start,"Duplicate attribute key '"+i+"'"),t[i]=!0,e.push(n)}return e};nt.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===x.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(x.colon),this.type!==x.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")};nt.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===x.string){var e=this.parseLiteral(this.value);return axt.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)};nt.adaptDirectivePrologue=function(e){for(var t=0;t=5&&e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&typeof e.expression.value=="string"&&(this.input[e.start]==='"'||this.input[e.start]==="'")};var Ca=Kn.prototype;Ca.toAssignable=function(e,t,r){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&e.name==="await"&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",r&&this.checkPatternErrors(r,!0);for(var n=0,i=e.properties;n=8&&!a&&c.name==="async"&&!this.canInsertSemicolon()&&this.eat(x._function))return this.overrideContext(In.f_expr),this.parseFunction(this.startNodeAt(s,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(x.arrow))return this.parseArrowExpression(this.startNodeAt(s,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name==="async"&&this.type===x.name&&!a&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(x.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,o),[c],!0,t)}return c;case x.regexp:var u=this.value;return n=this.parseLiteral(u.value),n.regex={pattern:u.pattern,flags:u.flags},n;case x.num:case x.string:return this.parseLiteral(this.value);case x._null:case x._true:case x._false:return n=this.startNode(),n.value=this.type===x._null?null:this.type===x._true,n.raw=this.type.keyword,this.next(),this.finishNode(n,"Literal");case x.parenL:var l=this.start,d=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)&&(e.parenthesizedAssign=l),e.parenthesizedBind<0&&(e.parenthesizedBind=l)),d;case x.bracketL:return n=this.startNode(),this.next(),n.elements=this.parseExprList(x.bracketR,!0,!0,e),this.finishNode(n,"ArrayExpression");case x.braceL:return this.overrideContext(In.b_expr),this.parseObj(!1,e);case x._function:return n=this.startNode(),this.next(),this.parseFunction(n,0);case x._class:return this.parseClass(this.startNode(),!1);case x._new:return this.parseNew();case x.backQuote:return this.parseTemplate();case x._import:return this.options.ecmaVersion>=11?this.parseExprImport(r):this.unexpected();default:return this.parseExprAtomDefault()}};Tt.parseExprAtomDefault=function(){this.unexpected()};Tt.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===x.parenL&&!e)return this.parseDynamicImport(t);if(this.type===x.dot){var r=this.startNodeAt(t.start,t.loc&&t.loc.start);return r.name="import",t.meta=this.finishNode(r,"Identifier"),this.parseImportMeta(t)}else this.unexpected()};Tt.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(x.parenR)?e.options=null:(this.expect(x.comma),this.afterTrailingComma(x.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(x.parenR)||(this.expect(x.comma),this.afterTrailingComma(x.parenR)||this.unexpected())));else if(!this.eat(x.parenR)){var t=this.start;this.eat(x.comma)&&this.eat(x.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")};Tt.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!=="meta"&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")};Tt.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),t.raw.charCodeAt(t.raw.length-1)===110&&(t.bigint=t.value!=null?t.value.toString():t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")};Tt.parseParenExpression=function(){this.expect(x.parenL);var e=this.parseExpression();return this.expect(x.parenR),e};Tt.shouldParseArrow=function(e){return!this.canInsertSemicolon()};Tt.parseParenAndDistinguishExpression=function(e,t){var r=this.start,n=this.startLoc,i,s=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,a=this.startLoc,c=[],u=!0,l=!1,d=new qR,f=this.yieldPos,p=this.awaitPos,h;for(this.yieldPos=0,this.awaitPos=0;this.type!==x.parenR;)if(u?u=!1:this.expect(x.comma),s&&this.afterTrailingComma(x.parenR,!0)){l=!0;break}else if(this.type===x.ellipsis){h=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===x.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else c.push(this.parseMaybeAssign(!1,d,this.parseParenItem));var A=this.lastTokEnd,g=this.lastTokEndLoc;if(this.expect(x.parenR),e&&this.shouldParseArrow(c)&&this.eat(x.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=p,this.parseParenArrowList(r,n,c,t);(!c.length||l)&&this.unexpected(this.lastTokStart),h&&this.unexpected(h),this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,c.length>1?(i=this.startNodeAt(o,a),i.expressions=c,this.finishNodeAt(i,"SequenceExpression",A,g)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var m=this.startNodeAt(r,n);return m.expression=i,this.finishNode(m,"ParenthesizedExpression")}else return i};Tt.parseParenItem=function(e){return e};Tt.parseParenArrowList=function(e,t,r,n){return this.parseArrowExpression(this.startNodeAt(e,t),r,!1,n)};var hxt=[];Tt.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===x.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var r=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!=="target"&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),r&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var n=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),n,i,!0,!1),e.callee.type==="Super"&&this.raiseRecoverable(n,"Invalid use of 'super'"),this.eat(x.parenL)?e.arguments=this.parseExprList(x.parenR,this.options.ecmaVersion>=8,!1):e.arguments=hxt,this.finishNode(e,"NewExpression")};Tt.parseTemplateElement=function(e){var t=e.isTagged,r=this.startNode();return this.type===x.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),r.value={raw:this.value.replace(/\r\n?/g,` +`),cooked:null}):r.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,` +`),cooked:this.value},this.next(),r.tail=this.type===x.backQuote,this.finishNode(r,"TemplateElement")};Tt.parseTemplate=function(e){e===void 0&&(e={});var t=e.isTagged;t===void 0&&(t=!1);var r=this.startNode();this.next(),r.expressions=[];var n=this.parseTemplateElement({isTagged:t});for(r.quasis=[n];!n.tail;)this.type===x.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(x.dollarBraceL),r.expressions.push(this.parseExpression()),this.expect(x.braceR),r.quasis.push(n=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(r,"TemplateLiteral")};Tt.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===x.name||this.type===x.num||this.type===x.string||this.type===x.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===x.star)&&!no.test(this.input.slice(this.lastTokEnd,this.start))};Tt.parseObj=function(e,t){var r=this.startNode(),n=!0,i={};for(r.properties=[],this.next();!this.eat(x.braceR);){if(n)n=!1;else if(this.expect(x.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(x.braceR))break;var s=this.parseProperty(e,t);e||this.checkPropClash(s,i,t),r.properties.push(s)}return this.finishNode(r,e?"ObjectPattern":"ObjectExpression")};Tt.parseProperty=function(e,t){var r=this.startNode(),n,i,s,o;if(this.options.ecmaVersion>=9&&this.eat(x.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===x.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(r,"RestElement")):(r.argument=this.parseMaybeAssign(!1,t),this.type===x.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(r,"SpreadElement"));this.options.ecmaVersion>=6&&(r.method=!1,r.shorthand=!1,(e||t)&&(s=this.start,o=this.startLoc),e||(n=this.eat(x.star)));var a=this.containsEsc;return this.parsePropertyName(r),!e&&!a&&this.options.ecmaVersion>=8&&!n&&this.isAsyncProp(r)?(i=!0,n=this.options.ecmaVersion>=9&&this.eat(x.star),this.parsePropertyName(r)):i=!1,this.parsePropertyValue(r,e,n,i,s,o,t,a),this.finishNode(r,"Property")};Tt.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var r=e.kind==="get"?0:1;if(e.value.params.length!==r){var n=e.value.start;e.kind==="get"?this.raiseRecoverable(n,"getter should have no params"):this.raiseRecoverable(n,"setter should have exactly one param")}else e.kind==="set"&&e.value.params[0].type==="RestElement"&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")};Tt.parsePropertyValue=function(e,t,r,n,i,s,o,a){(r||n)&&this.type===x.colon&&this.unexpected(),this.eat(x.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind="init"):this.options.ecmaVersion>=6&&this.type===x.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(r,n),e.kind="init"):!t&&!a&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&this.type!==x.comma&&this.type!==x.braceR&&this.type!==x.eq?((r||n)&&this.unexpected(),this.parseGetterSetter(e)):this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"?((r||n)&&this.unexpected(),this.checkUnreserved(e.key),e.key.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=i),t?e.value=this.parseMaybeDefault(i,s,this.copyNode(e.key)):this.type===x.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,s,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind="init",e.shorthand=!0):this.unexpected()};Tt.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(x.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(x.bracketR),e.key;e.computed=!1}return e.key=this.type===x.num||this.type===x.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};Tt.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)};Tt.parseMethod=function(e,t,r){var n=this.startNode(),i=this.yieldPos,s=this.awaitPos,o=this.awaitIdentPos;return this.initFunction(n),this.options.ecmaVersion>=6&&(n.generator=e),this.options.ecmaVersion>=8&&(n.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(NV(t,n.generator)|HR|(r?kxe:0)),this.expect(x.parenL),n.params=this.parseBindingList(x.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(n,!1,!0,!1),this.yieldPos=i,this.awaitPos=s,this.awaitIdentPos=o,this.finishNode(n,"FunctionExpression")};Tt.parseArrowExpression=function(e,t,r,n){var i=this.yieldPos,s=this.awaitPos,o=this.awaitIdentPos;return this.enterScope(NV(r,!1)|DV),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!r),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,n),this.yieldPos=i,this.awaitPos=s,this.awaitIdentPos=o,this.finishNode(e,"ArrowFunctionExpression")};Tt.parseFunctionBody=function(e,t,r,n){var i=t&&this.type!==x.braceL,s=this.strict,o=!1;if(i)e.body=this.parseMaybeAssign(n),e.expression=!0,this.checkParams(e,!1);else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!s||a)&&(o=this.strictDirective(this.end),o&&a&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list"));var c=this.labels;this.labels=[],o&&(this.strict=!0),this.checkParams(e,!s&&!o&&!t&&!r&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,Rxe),e.body=this.parseBlock(!1,void 0,o&&!s),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()};Tt.isSimpleParamList=function(e){for(var t=0,r=e;t-1||i.functions.indexOf(e)>-1||i.var.indexOf(e)>-1,i.lexical.push(e),this.inModule&&i.flags&kh&&delete this.undefinedExports[e]}else if(t===Qxe){var s=this.currentScope();s.lexical.push(e)}else if(t===Txe){var o=this.currentScope();this.treatFunctionsAsVar?n=o.lexical.indexOf(e)>-1:n=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1,o.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var c=this.scopeStack[a];if(c.lexical.indexOf(e)>-1&&!(c.flags&Bxe&&c.lexical[0]===e)||!this.treatFunctionsAsVarInScope(c)&&c.functions.indexOf(e)>-1){n=!0;break}if(c.var.push(e),this.inModule&&c.flags&kh&&delete this.undefinedExports[e],c.flags&jR)break}n&&this.raiseRecoverable(r,"Identifier '"+e+"' has already been declared")};Kd.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)};Kd.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};Kd.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(jR|Sw|Th))return t}};Kd.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(jR|Sw|Th)&&!(t.flags&DV))return t}};var zR=function(t,r,n){this.type="",this.start=r,this.end=0,t.options.locations&&(this.loc=new $R(t,n)),t.options.directSourceFile&&(this.sourceFile=t.options.directSourceFile),t.options.ranges&&(this.range=[r,0])},vw=Kn.prototype;vw.startNode=function(){return new zR(this,this.start,this.startLoc)};vw.startNodeAt=function(e,t){return new zR(this,e,t)};function Mxe(e,t,r,n){return e.type=t,e.end=r,this.options.locations&&(e.loc.end=n),this.options.ranges&&(e.range[1]=r),e}vw.finishNode=function(e,t){return Mxe.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};vw.finishNodeAt=function(e,t,r,n){return Mxe.call(this,e,t,r,n)};vw.copyNode=function(e){var t=new zR(this,e.start,this.startLoc);for(var r in e)t[r]=e[r];return t};var gxt="Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz",Pxe="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",Lxe=Pxe+" Extended_Pictographic",Fxe=Lxe,Oxe=Fxe+" EBase EComp EMod EPres ExtPict",Uxe=Oxe,mxt=Uxe,yxt={9:Pxe,10:Lxe,11:Fxe,12:Oxe,13:Uxe,14:mxt},bxt="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",Ext={9:"",10:"",11:"",12:"",13:"",14:bxt},mxe="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",$xe="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",Hxe=$xe+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",jxe=Hxe+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",qxe=jxe+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",zxe=qxe+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",Cxt=zxe+" "+gxt,Ixt={9:$xe,10:Hxe,11:jxe,12:qxe,13:zxe,14:Cxt},Vxe={};function wxt(e){var t=Vxe[e]={binary:Jd(yxt[e]+" "+mxe),binaryOfStrings:Jd(Ext[e]),nonBinary:{General_Category:Jd(mxe),Script:Jd(Ixt[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(PR=0,xV=[9,10,11,12,13,14];PR=6?"uy":"")+(t.options.ecmaVersion>=9?"s":"")+(t.options.ecmaVersion>=13?"d":"")+(t.options.ecmaVersion>=15?"v":""),this.unicodeProperties=Vxe[t.options.ecmaVersion>=14?14:t.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};nu.prototype.reset=function(t,r,n){var i=n.indexOf("v")!==-1,s=n.indexOf("u")!==-1;this.start=t|0,this.source=r+"",this.flags=n,i&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=s&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=s&&this.parser.options.ecmaVersion>=9)};nu.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)};nu.prototype.at=function(t,r){r===void 0&&(r=!1);var n=this.source,i=n.length;if(t>=i)return-1;var s=n.charCodeAt(t);if(!(r||this.switchU)||s<=55295||s>=57344||t+1>=i)return s;var o=n.charCodeAt(t+1);return o>=56320&&o<=57343?(s<<10)+o-56613888:s};nu.prototype.nextIndex=function(t,r){r===void 0&&(r=!1);var n=this.source,i=n.length;if(t>=i)return i;var s=n.charCodeAt(t),o;return!(r||this.switchU)||s<=55295||s>=57344||t+1>=i||(o=n.charCodeAt(t+1))<56320||o>57343?t+1:t+2};nu.prototype.current=function(t){return t===void 0&&(t=!1),this.at(this.pos,t)};nu.prototype.lookahead=function(t){return t===void 0&&(t=!1),this.at(this.nextIndex(this.pos,t),t)};nu.prototype.advance=function(t){t===void 0&&(t=!1),this.pos=this.nextIndex(this.pos,t)};nu.prototype.eat=function(t,r){return r===void 0&&(r=!1),this.current(r)===t?(this.advance(r),!0):!1};nu.prototype.eatChars=function(t,r){r===void 0&&(r=!1);for(var n=this.pos,i=0,s=t;i-1&&this.raise(e.start,"Duplicate regular expression flag"),o==="u"&&(n=!0),o==="v"&&(i=!0)}this.options.ecmaVersion>=15&&n&&i&&this.raise(e.start,"Invalid regular expression flag")};function Sxt(e){for(var t in e)return!0;return!1}tt.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&Sxt(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))};tt.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,r=e.backReferenceNames;t=16;for(t&&(e.branchID=new UR(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")};tt.regexp_alternative=function(e){for(;e.pos=9&&(r=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!r,!0}return e.pos=t,!1};tt.regexp_eatQuantifier=function(e,t){return t===void 0&&(t=!1),this.regexp_eatQuantifierPrefix(e,t)?(e.eat(63),!0):!1};tt.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};tt.regexp_eatBracedQuantifier=function(e,t){var r=e.pos;if(e.eat(123)){var n=0,i=-1;if(this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue),e.eat(125)))return i!==-1&&i=16){var r=this.regexp_eatModifiers(e),n=e.eat(45);if(r||n){for(var i=0;i-1&&e.raise("Duplicate regular expression modifiers")}if(n){var o=this.regexp_eatModifiers(e);!r&&!o&&e.current()===58&&e.raise("Invalid regular expression modifiers");for(var a=0;a-1||r.indexOf(c)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1};tt.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):e.current()===63&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1};tt.regexp_eatModifiers=function(e){for(var t="",r=0;(r=e.current())!==-1&&vxt(r);)t+=il(r),e.advance();return t};function vxt(e){return e===105||e===109||e===115}tt.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};tt.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1};tt.regexp_eatSyntaxCharacter=function(e){var t=e.current();return Gxe(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Gxe(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}tt.regexp_eatPatternCharacters=function(e){for(var t=e.pos,r=0;(r=e.current())!==-1&&!Gxe(r);)e.advance();return e.pos!==t};tt.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124?(e.advance(),!0):!1};tt.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,r=e.groupNames[e.lastStringValue];if(r)if(t)for(var n=0,i=r;n=11,n=e.current(r);return e.advance(r),n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(n=e.lastIntValue),xxt(n)?(e.lastIntValue=n,!0):(e.pos=t,!1)};function xxt(e){return ru(e,!0)||e===36||e===95}tt.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,r=this.options.ecmaVersion>=11,n=e.current(r);return e.advance(r),n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,r)&&(n=e.lastIntValue),Bxt(n)?(e.lastIntValue=n,!0):(e.pos=t,!1)};function Bxt(e){return Zd(e,!0)||e===36||e===95||e===8204||e===8205}tt.regexp_eatAtomEscape=function(e){return this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)?!0:(e.switchU&&(e.current()===99&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)};tt.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var r=e.lastIntValue;if(e.switchU)return r>e.maxBackReference&&(e.maxBackReference=r),!0;if(r<=e.numCapturingParens)return!0;e.pos=t}return!1};tt.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1};tt.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};tt.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1};tt.regexp_eatZero=function(e){return e.current()===48&&!VR(e.lookahead())?(e.lastIntValue=0,e.advance(),!0):!1};tt.regexp_eatControlEscape=function(e){var t=e.current();return t===116?(e.lastIntValue=9,e.advance(),!0):t===110?(e.lastIntValue=10,e.advance(),!0):t===118?(e.lastIntValue=11,e.advance(),!0):t===102?(e.lastIntValue=12,e.advance(),!0):t===114?(e.lastIntValue=13,e.advance(),!0):!1};tt.regexp_eatControlLetter=function(e){var t=e.current();return Wxe(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function Wxe(e){return e>=65&&e<=90||e>=97&&e<=122}tt.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){t===void 0&&(t=!1);var r=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var s=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=(i-55296)*1024+(o-56320)+65536,!0}e.pos=s,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&kxt(e.lastIntValue))return!0;n&&e.raise("Invalid unicode escape"),e.pos=r}return!1};function kxt(e){return e>=0&&e<=1114111}tt.regexp_eatIdentityEscape=function(e){if(e.switchU)return this.regexp_eatSyntaxCharacter(e)?!0:e.eat(47)?(e.lastIntValue=47,!0):!1;var t=e.current();return t!==99&&(!e.switchN||t!==107)?(e.lastIntValue=t,e.advance(),!0):!1};tt.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do e.lastIntValue=10*e.lastIntValue+(t-48),e.advance();while((t=e.current())>=48&&t<=57);return!0}return!1};var Yxe=0,sl=1,ba=2;tt.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(_xt(t))return e.lastIntValue=-1,e.advance(),sl;var r=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((r=t===80)||t===112)){e.lastIntValue=-1,e.advance();var n;if(e.eat(123)&&(n=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return r&&n===ba&&e.raise("Invalid property name"),n;e.raise("Invalid property name")}return Yxe};function _xt(e){return e===100||e===68||e===115||e===83||e===119||e===87}tt.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var r=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,r,n),sl}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return Yxe};tt.regexp_validateUnicodePropertyNameAndValue=function(e,t,r){E0(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(r)||e.raise("Invalid property value")};tt.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(e.unicodeProperties.binary.test(t))return sl;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return ba;e.raise("Invalid property name")};tt.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";Jxe(t=e.current());)e.lastStringValue+=il(t),e.advance();return e.lastStringValue!==""};function Jxe(e){return Wxe(e)||e===95}tt.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Txt(t=e.current());)e.lastStringValue+=il(t),e.advance();return e.lastStringValue!==""};function Txt(e){return Jxe(e)||VR(e)}tt.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};tt.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),r=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&r===ba&&e.raise("Negated character class may contain strings"),!0}return!1};tt.regexp_classContents=function(e){return e.current()===93?sl:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),sl)};tt.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var r=e.lastIntValue;e.switchU&&(t===-1||r===-1)&&e.raise("Invalid character class"),t!==-1&&r!==-1&&t>r&&e.raise("Range out of order in character class")}}};tt.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var r=e.current();(r===99||Xxe(r))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var n=e.current();return n!==93?(e.lastIntValue=n,e.advance(),!0):!1};tt.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};tt.regexp_classSetExpression=function(e){var t=sl,r;if(!this.regexp_eatClassSetRange(e))if(r=this.regexp_eatClassSetOperand(e)){r===ba&&(t=ba);for(var n=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(r=this.regexp_eatClassSetOperand(e))){r!==ba&&(t=sl);continue}e.raise("Invalid character in character class")}if(n!==e.pos)return t;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(n!==e.pos)return t}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(r=this.regexp_eatClassSetOperand(e),!r)return t;r===ba&&(t=ba)}};tt.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var n=e.lastIntValue;return r!==-1&&n!==-1&&r>n&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1};tt.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?sl:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)};tt.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var r=e.eat(94),n=this.regexp_classContents(e);if(e.eat(93))return r&&n===ba&&e.raise("Negated character class may contain strings"),n;e.pos=t}if(e.eat(92)){var i=this.regexp_eatCharacterClassEscape(e);if(i)return i;e.pos=t}return null};tt.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var r=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return r}else e.raise("Invalid escape");e.pos=t}return null};tt.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===ba&&(t=ba);return t};tt.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?sl:ba};tt.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return this.regexp_eatCharacterEscape(e)||this.regexp_eatClassSetReservedPunctuator(e)?!0:e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1);var r=e.current();return r<0||r===e.lookahead()&&Qxt(r)||Rxt(r)?!1:(e.advance(),e.lastIntValue=r,!0)};function Qxt(e){return e===33||e>=35&&e<=38||e>=42&&e<=44||e===46||e>=58&&e<=64||e===94||e===96||e===126}function Rxt(e){return e===40||e===41||e===45||e===47||e>=91&&e<=93||e>=123&&e<=125}tt.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return Dxt(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Dxt(e){return e===33||e===35||e===37||e===38||e===44||e===45||e>=58&&e<=62||e===64||e===96||e===126}tt.regexp_eatClassControlLetter=function(e){var t=e.current();return VR(t)||t===95?(e.lastIntValue=t%32,e.advance(),!0):!1};tt.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1};tt.regexp_eatDecimalDigits=function(e){var t=e.pos,r=0;for(e.lastIntValue=0;VR(r=e.current());)e.lastIntValue=10*e.lastIntValue+(r-48),e.advance();return e.pos!==t};function VR(e){return e>=48&&e<=57}tt.regexp_eatHexDigits=function(e){var t=e.pos,r=0;for(e.lastIntValue=0;Zxe(r=e.current());)e.lastIntValue=16*e.lastIntValue+Kxe(r),e.advance();return e.pos!==t};function Zxe(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Kxe(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}tt.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var r=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=t*64+r*8+e.lastIntValue:e.lastIntValue=t*8+r}else e.lastIntValue=t;return!0}return!1};tt.regexp_eatOctalDigit=function(e){var t=e.current();return Xxe(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function Xxe(e){return e>=48&&e<=55}tt.regexp_eatFixedHexDigits=function(e,t){var r=e.pos;e.lastIntValue=0;for(var n=0;n=this.input.length)return this.finishToken(x.eof);if(e.override)return e.override(this);this.readToken(this.fullCharCodeAtPos())};sr.readToken=function(e){return ru(e,this.options.ecmaVersion>=6)||e===92?this.readWord():this.getTokenFromCode(e)};sr.fullCharCodeAt=function(e){var t=this.input.charCodeAt(e);if(t<=55295||t>=56320)return t;var r=this.input.charCodeAt(e+1);return r<=56319||r>=57344?t:(t<<10)+r-56613888};sr.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)};sr.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,r=this.input.indexOf("*/",this.pos+=2);if(r===-1&&this.raise(this.pos-2,"Unterminated comment"),this.pos=r+2,this.options.locations)for(var n=void 0,i=t;(n=Ixe(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=n;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,r),t,this.pos,e,this.curPosition())};sr.skipLineComment=function(e){for(var t=this.pos,r=this.options.onComment&&this.curPosition(),n=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&wxe.test(String.fromCharCode(e)))++this.pos;else break e}}};sr.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var r=this.type;this.type=e,this.value=t,this.updateContext(r)};sr.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&e===46&&t===46?(this.pos+=3,this.finishToken(x.ellipsis)):(++this.pos,this.finishToken(x.dot))};sr.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):e===61?this.finishOp(x.assign,2):this.finishOp(x.slash,1)};sr.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),r=1,n=e===42?x.star:x.modulo;return this.options.ecmaVersion>=7&&e===42&&t===42&&(++r,n=x.starstar,t=this.input.charCodeAt(this.pos+2)),t===61?this.finishOp(x.assign,r+1):this.finishOp(n,r)};sr.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var r=this.input.charCodeAt(this.pos+2);if(r===61)return this.finishOp(x.assign,3)}return this.finishOp(e===124?x.logicalOR:x.logicalAND,2)}return t===61?this.finishOp(x.assign,2):this.finishOp(e===124?x.bitwiseOR:x.bitwiseAND,1)};sr.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);return e===61?this.finishOp(x.assign,2):this.finishOp(x.bitwiseXOR,1)};sr.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||no.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(x.incDec,2):t===61?this.finishOp(x.assign,2):this.finishOp(x.plusMin,1)};sr.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),r=1;return t===e?(r=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+r)===61?this.finishOp(x.assign,r+1):this.finishOp(x.bitShift,r)):t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(t===61&&(r=2),this.finishOp(x.relational,r))};sr.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(x.equality,this.input.charCodeAt(this.pos+2)===61?3:2):e===61&&t===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(x.arrow)):this.finishOp(e===61?x.eq:x.prefix,1)};sr.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var r=this.input.charCodeAt(this.pos+2);if(r<48||r>57)return this.finishOp(x.questionDot,2)}if(t===63){if(e>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61)return this.finishOp(x.assign,3)}return this.finishOp(x.coalesce,2)}}return this.finishOp(x.question,1)};sr.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,t=this.fullCharCodeAtPos(),ru(t,!0)||t===92))return this.finishToken(x.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+il(t)+"'")};sr.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(x.parenL);case 41:return++this.pos,this.finishToken(x.parenR);case 59:return++this.pos,this.finishToken(x.semi);case 44:return++this.pos,this.finishToken(x.comma);case 91:return++this.pos,this.finishToken(x.bracketL);case 93:return++this.pos,this.finishToken(x.bracketR);case 123:return++this.pos,this.finishToken(x.braceL);case 125:return++this.pos,this.finishToken(x.braceR);case 58:return++this.pos,this.finishToken(x.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(x.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(t===111||t===79)return this.readRadixNumber(8);if(t===98||t===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(x.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+il(e)+"'")};sr.finishOp=function(e,t){var r=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,r)};sr.readRegexp=function(){for(var e,t,r=this.pos;;){this.pos>=this.input.length&&this.raise(r,"Unterminated regular expression");var n=this.input.charAt(this.pos);if(no.test(n)&&this.raise(r,"Unterminated regular expression"),e)e=!1;else{if(n==="[")t=!0;else if(n==="]"&&t)t=!1;else if(n==="/"&&!t)break;e=n==="\\"}++this.pos}var i=this.input.slice(r,this.pos);++this.pos;var s=this.pos,o=this.readWord1();this.containsEsc&&this.unexpected(s);var a=this.regexpState||(this.regexpState=new nu(this));a.reset(r,i,o),this.validateRegExpFlags(a),this.validateRegExpPattern(a);var c=null;try{c=new RegExp(i,o)}catch{}return this.finishToken(x.regexp,{pattern:i,flags:o,value:c})};sr.readInt=function(e,t,r){for(var n=this.options.ecmaVersion>=12&&t===void 0,i=r&&this.input.charCodeAt(this.pos)===48,s=this.pos,o=0,a=0,c=0,u=t??1/0;c=97?d=l-97+10:l>=65?d=l-65+10:l>=48&&l<=57?d=l-48:d=1/0,d>=e)break;a=l,o=o*e+d}return n&&a===95&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===s||t!=null&&this.pos-s!==t?null:o};function Nxt(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,""))}function eBe(e){return typeof BigInt!="function"?null:BigInt(e.replace(/_/g,""))}sr.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var r=this.readInt(e);return r==null&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(r=eBe(this.input.slice(t,this.pos)),++this.pos):ru(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(x.num,r)};sr.readNumber=function(e){var t=this.pos;!e&&this.readInt(10,void 0,!0)===null&&this.raise(t,"Invalid number");var r=this.pos-t>=2&&this.input.charCodeAt(t)===48;r&&this.strict&&this.raise(t,"Invalid number");var n=this.input.charCodeAt(this.pos);if(!r&&!e&&this.options.ecmaVersion>=11&&n===110){var i=eBe(this.input.slice(t,this.pos));return++this.pos,ru(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(x.num,i)}r&&/[89]/.test(this.input.slice(t,this.pos))&&(r=!1),n===46&&!r&&(++this.pos,this.readInt(10),n=this.input.charCodeAt(this.pos)),(n===69||n===101)&&!r&&(n=this.input.charCodeAt(++this.pos),(n===43||n===45)&&++this.pos,this.readInt(10)===null&&this.raise(t,"Invalid number")),ru(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var s=Nxt(this.input.slice(t,this.pos),r);return this.finishToken(x.num,s)};sr.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){this.options.ecmaVersion<6&&this.unexpected();var r=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,t>1114111&&this.invalidStringToken(r,"Code point out of bounds")}else t=this.readHexChar(4);return t};sr.readString=function(e){for(var t="",r=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var n=this.input.charCodeAt(this.pos);if(n===e)break;n===92?(t+=this.input.slice(r,this.pos),t+=this.readEscapedChar(!1),r=this.pos):n===8232||n===8233?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(b0(n)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(r,this.pos++),this.finishToken(x.string,t)};var tBe={};sr.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===tBe)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1};sr.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw tBe;this.raise(e,t)};sr.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var r=this.input.charCodeAt(this.pos);if(r===96||r===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===x.template||this.type===x.invalidTemplate)?r===36?(this.pos+=2,this.finishToken(x.dollarBraceL)):(++this.pos,this.finishToken(x.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(x.template,e));if(r===92)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(b0(r)){switch(e+=this.input.slice(t,this.pos),++this.pos,r){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:e+=` +`;break;default:e+=String.fromCharCode(r);break}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}};sr.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var n=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(n,8);return i>255&&(n=n.slice(0,-1),i=parseInt(n,8)),this.pos+=n.length-1,t=this.input.charCodeAt(this.pos),(n!=="0"||t===56||t===57)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-n.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(i)}return b0(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}};sr.readHexChar=function(e){var t=this.pos,r=this.readInt(16,e);return r===null&&this.invalidStringToken(t,"Bad character escape sequence"),r};sr.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,r=this.pos,n=this.options.ecmaVersion>=6;this.posnBe?`${r.slice(0,nBe)}...`:r}function Uxt(e){return!e||e.type!=="ArrayExpression"||e.elements.length===0?!1:e.elements.every(t=>!t||t.type!=="ObjectExpression"?!1:(t.properties??[]).some(r=>{let n=r.key?.name??r.key?.value;return n==="id"||n==="slug"||typeof n=="string"&&/id$/i.test(n)}))}function xw(e){return e?e.type==="Literal"?!0:e.type==="ArrayExpression"?(e.elements??[]).every(t=>t===null||xw(t)):e.type==="ObjectExpression"?(e.properties??[]).every(t=>!t||t.type!=="Property"||t.kind!=="init"||t.method||t.shorthand||t.computed&&!xw(t.key)?!1:xw(t.value)):e.type==="UnaryExpression"&&["-","+","!","~"].includes(e.operator)?xw(e.argument):e.type==="TemplateLiteral"?(e.expressions??[]).length===0:!1:!1}function $xt(e,t){let r=e.slice(t.start,t.end),n=Oxt(e,t);if(r.length>Lxt)return{confidence:"low",evidence:`literal too large (${r.length} chars) :: ${n}`};if(!xw(t))return{confidence:"low",evidence:n};try{let i=Pxt(`(${r})`,Object.create(null),{timeout:1e3});return!Array.isArray(i)||i.length>Fxt?{confidence:"low",evidence:n}:{records:i,confidence:"high",evidence:n}}catch(i){return{confidence:"low",evidence:`${i.message} :: ${n}`}}}function Hxt(e){return e??"(anonymous)"}function iBe(e){let t=Rh(e);if(!t)return[];let r=[],n=new Set,i=(s,o)=>{!Uxt(s)||n.has(s.start)||(n.add(s.start),r.push({name:Hxt(o),...$xt(e,s)}))};return Qh(t,s=>{if(s.type==="VariableDeclarator"&&s.id?.type==="Identifier"&&i(s.init,s.id.name),s.type==="AssignmentExpression"){let o=s.left,a=o?.type==="Identifier"?o.name:o?.property?.name;i(s.right,a)}s.type==="Property"&&i(s.value,s.key?.name??s.key?.value),s.type==="ReturnStatement"&&i(s.argument,void 0)}),r}var jxt=/^(#[\w-]+|\.[\w-]+|\[[\w-]+(=("[^"]*"|'[^']*'|[\w-]+))?\])$/;function qxt(e){for(let t of e.arguments??[])if(t.type==="Literal"&&typeof t.value=="number")return t.value;for(let t of e.arguments??[])if(t.type==="CallExpression"){let r=(t.arguments??[]).find(n=>n.type==="Literal"&&typeof n.value=="number");if(r)return r.value}}function sBe(e,t){let r=le(e),n=Rh(t),i=new Map;n&&Qh(n,a=>{if(a.type!=="CallExpression")return;let c=(a.arguments??[]).filter(u=>u.type==="Literal"&&typeof u.value=="string").map(u=>String(u.value)).find(u=>jxt.test(u));c&&!i.has(c)&&i.set(c,{source:t.slice(a.start,a.end),perPage:qxt(a)})});let s=[],o=new Set;for(let[a,c]of i){let u=r(a).first();u.length!==0&&(o.add(a),s.push({selector:a,wrapperClass:u.attr("class")||void 0,sourceCall:c.source,perPageHint:c.perPage,confidence:"high",evidence:c.source}))}return r("[id]").each((a,c)=>{let l=`#${r(c).attr("id")}`;o.has(l)||r(c).children().length>0||s.push({selector:l,wrapperClass:r(c).attr("class")||void 0,confidence:"low",evidence:`empty container ${l} has no matching JS call`})}),s}function oBe(e){let t=Rh(e);if(!t)return[];let r=new Set,n=i=>i?.type==="MemberExpression"&&i.property?.name==="id";return Qh(t,i=>{if(i.type==="CallExpression"&&i.callee?.type==="MemberExpression"&&i.callee.property?.name==="find"&&i.callee.object?.type==="Identifier"){let s=i.arguments?.[0]?.body;s?.type==="BinaryExpression"&&/^===?$/.test(s.operator)&&(n(s.left)||n(s.right))&&r.add(i.callee.object.name)}}),[...r]}var zxt=["title","name","label","heading"],Vxt=["content","story","description","body","excerpt"],Gxt=["category","cat","kind","type","collection","group"],Wxt=["images","gallery","photos","media"];var Yxt=e=>[...new Set(e.flatMap(t=>Object.keys(t)))],Xd=(e,t)=>e.map(r=>r[t]).filter(r=>r!==void 0),Jxt=e=>e.length>0&&e.every(t=>typeof t=="string"||typeof t=="number"),FV=e=>e.length>0&&e.every(t=>typeof t=="string"),Zxt=e=>new Set(e).size===e.length,I0=(e,t)=>e.find(r=>t.includes(r.toLowerCase()));function OV(e,t){let r=Xd(e,t).filter(n=>typeof n=="string");return r.length?r.reduce((n,i)=>n+i.length,0)/r.length:0}function Kxt(e){return Array.isArray(e)&&e.every(t=>typeof t=="string"||!!(t&&typeof t=="object"&&("caption"in t||"url"in t)))}function Xxt(e){return e.every(t=>typeof t=="boolean")?"boolean":e.every(t=>typeof t=="number")?e.every(t=>Number.isInteger(t))?"integer":"number":"string"}function eBt(e){let t=e.filter(r=>typeof r=="string");if(t.length!==0){if(t.every(r=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(r)))return"email";if(t.every(r=>/^https?:\/\//.test(r)))return"url";if(t.every(r=>/^\d{4}-\d{2}-\d{2}/.test(r)))return"date";if(t.some(r=>r.length>=60))return"textarea"}}function tBt(e,t){let r=Xd(e,t),n=Xxt(r),i=n==="string"?eBt(r):void 0;return i?{key:t,type:n,format:i}:{key:t,type:n}}function aBe(e){let t=Yxt(e),r=I0(t,["id","slug"])??t[0]??"id",n="low";I0(t,["id","slug"])&&Jxt(Xd(e,r))&&Zxt(Xd(e,r))&&(n="high");let i=I0(t,zxt),s=i?"high":"low";i||(i=t.filter(f=>f!==r&&FV(Xd(e,f))).sort((f,p)=>OV(e,f)-OV(e,p))[0]??r);let o=I0(t,Vxt)??t.find(f=>f!==i&&FV(Xd(e,f))&&OV(e,f)>=60),a=I0(t,Gxt),c=a?"high":"low";a||(a=t.find(f=>{let p=Xd(e,f);return f!==r&&f!==i&&FV(p)&&new Set(p).size<=Math.max(1,Math.floor(p.length/2))}),a&&(c="low"));let u=I0(t,Wxt)??t.find(f=>{let p=Xd(e,f);return p.length>0&&p.every(Kxt)}),l=new Set;n==="high"&&l.add(r),s==="high"&&l.add(i),o&&l.add(o),a&&c==="high"&&l.add(a),u&&l.add(u);let d=t.filter(f=>!l.has(f)).map(f=>tBt(e,f));return{idKey:r,titleKey:i,contentKey:o,termKey:a,galleryKey:u,fields:d,confidence:{id:n,title:s,terms:c}}}function cBe(e,t){let r=`${e}::${t}`,n=2166136261;for(let i=0;i>>0).toString(36)}`}var nBt=2e5,iBt=5e3,UV=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),sBt=e=>e.replace(/s$/i,""),$V=e=>e.replace(/[-_]+/g," ").replace(/\b\w/g,t=>t.toUpperCase()).trim(),uBe=e=>["string","number","boolean"].includes(typeof e),oBt=["newest","recent","latest"],fBe=(e,t)=>e?"category":`${t}_cat`;function pBe(e){let t=[],r=mBt(e.js),n=oBe(e.js),i=sBe(e.html,e.js),o={arrays:r.map(d=>({name:d.name,confidence:d.confidence,recordCount:d.records?.length,reason:d.confidence==="low"?d.evidence.slice(0,120):void 0})),skippedFiles:e.skippedFiles??[],unmatchedContainers:i.filter(d=>d.confidence==="low"||!d.sourceCall).map(d=>d.selector)},a=dBt(r,n,i);if(a?.records)return lBe({records:a.records,typeName:a.name,mounts:i,idLookupNames:n,source:"js-array",cardTemplateTodoEvidence:IBt(e.js),deterministicCard:void 0,discovered:o,todos:t});let c=e.htmlFiles?.length?e.htmlFiles.flatMap(d=>wV(d.text,{resolvePage:e.resolvePage}).map((f,p)=>({grid:f,disambiguator:`${d.name}:${p}`,sourcePage:d.name}))):wV(e.html,{resolvePage:e.resolvePage}).map((d,f)=>({grid:d,disambiguator:String(f),sourcePage:void 0})),u=c.filter(({grid:d})=>d.records.length>=1);if(u.length>0){let d=aBt(u.flatMap(({grid:A})=>A.records)),f=u.find(({grid:A})=>A.featured),p=fBe(!0,"post"),h=u.map(({grid:A,disambiguator:g,sourcePage:m})=>({selector:`#${cBe(A.containerSelector,g)}`,sourceSelector:A.containerSelector,...m?{sourcePage:m}:{},sourceCall:`html-cards:${A.containerSelector}`,...A.containerClass?{wrapperClass:A.containerClass}:{},perPageHint:A.records.length,...A.featured?{featured:{columnWrapperClass:A.featured.columnWrapperClass,leadPerPage:A.featured.leadCount,columnPerPage:A.records.length-A.featured.leadCount,variant:"row",...A.featured.termSlug?{termSlug:A.featured.termSlug,taxonomy:p}:{}}}:{},confidence:"high",evidence:A.evidence}));return lBe({records:d,coreType:"post",mounts:h,idLookupNames:[],source:"html-cards",cardTemplateTodoEvidence:void 0,deterministicCard:u[0].grid.cardTemplate,deterministicCardVariants:f?.grid.featured?{row:f.grid.featured.rowTemplate}:void 0,discovered:{...o,unmatchedContainers:c.filter(({grid:A})=>A.records.length===0).map(({grid:A})=>A.containerSelector)},todos:t})}let l=gBt();return t.push({path:"items",instruction:"No static data array literal and no repeated content-card grid were found. Author items[] and the model by hand from the source.",evidence:r[0]?.evidence??"(no array-like declarations or card grids found)"}),{model:l,skillTodos:t,discovered:{...o,source:"none"},validation:Cw(l)}}function lBe(e){let{records:t,todos:r}=e,n=e.coreType==="post",i=aBe(t),s=n&&t.some(h=>Object.prototype.hasOwnProperty.call(h,"content"))?{...i,contentKey:"content",fields:cBt(t,i).filter(h=>h.key!=="content")}:i,o=e.typeName??"item",a=sBt(o==="(anonymous)"?"item":o).toLowerCase(),c=n?"post":UV(a)||"item",u=fBe(n,c),l=new Map;if(s.termKey)for(let h of t){let A=h[s.termKey];typeof A=="string"&&l.set(UV(A),$V(A))}let d=t.map(h=>{let A={};for(let C of s.fields){let I=h[C.key];uBe(I)&&(A[C.key]=I)}let g=s.galleryKey?h[s.galleryKey]:void 0,m=Array.isArray(g)?g.map(C=>{if(typeof C=="string")return{caption:C};let I=C;return{caption:String(I.caption??""),url:I.url}}):[],b=s.termKey?h[s.termKey]:void 0,E=h[s.idKey];return{id:uBe(E)?String(E):"",title:String(h[s.titleKey]??""),terms:typeof b=="string"?[UV(b)]:[],meta:A,gallery:m,content:s.contentKey?String(h[s.contentKey]??""):void 0}}),f=[];for(let h of e.mounts){if(h.confidence!=="high"||!h.sourceCall)continue;let A=f.length,g=h.perPageHint??-1,m=pBt(h,g);m.confidence==="low"&&r.push({path:`mounts[${A}].query.order`,instruction:`Confirm ordering/perPage for ${h.selector}; source call: "${h.sourceCall}". Default applied: date/DESC. Adjust to match the source's selection semantics.`,evidence:h.evidence}),f.push({selector:h.selector,sourceCall:h.sourceCall,query:{postType:c,perPage:g,orderBy:"date",order:m.order},wrapperClass:h.wrapperClass,...h.sourceSelector?{sourceSelector:h.sourceSelector}:{},...h.sourcePage?{sourcePage:h.sourcePage}:{},...h.featured?{featured:h.featured}:{}})}e.cardTemplateTodoEvidence&&r.unshift({path:"card.template",instruction:"Author card.template: rewrite the source per-item card function into a single-root skeleton with data-dla-* bindings (data-dla-text/attr/class/if), preserving the source classes. Reference: id, title, content, cat.slug, cat.label, meta., gallery..caption, map... Add any value-keyed lookups to card.maps.",evidence:e.cardTemplateTodoEvidence}),s.confidence.id==="low"&&r.push({path:"items[].id",instruction:`The id field was guessed ('${s.idKey}') and may be non-unique or non-scalar; confirm/choose the stable per-item id (it is the idempotency key for inserts).`,evidence:`record keys: ${Object.keys(t[0]??{}).join(", ")}`}),s.confidence.title==="low"&&r.push({path:"items[].title",instruction:`Title was guessed ('${s.titleKey}') with no name match; confirm it is the human title.`,evidence:`record keys: ${Object.keys(t[0]??{}).join(", ")}`}),s.confidence.terms==="low"&&s.termKey&&r.push({path:"taxonomy",instruction:`Taxonomy column was guessed ('${s.termKey}') by low cardinality; confirm it is a content category.`,evidence:`distinct: ${[...l.keys()].join(", ")}`});let p={cpt:n?{slug:"post",singular:"Post",plural:"Posts",public:!0,supports:["title","editor","thumbnail","custom-fields"]}:{slug:c,singular:$V(a),plural:$V((o==="(anonymous)"?"items":o).toLowerCase()),public:!0,supports:["title","editor","custom-fields"]},taxonomy:{slug:u,label:"Categories",hierarchical:!0,terms:[...l].map(([h,A])=>({slug:h,label:A}))},fields:s.fields,items:d,mounts:f,card:{template:e.deterministicCard??"",maps:{},...e.deterministicCardVariants?{variants:e.deterministicCardVariants}:{}},sourceArrays:n?[]:[...new Set([...e.idLookupNames,o].filter(h=>h&&h!=="(anonymous)"))],schema:3};return{model:p,skillTodos:r,discovered:{...e.discovered,source:e.source},validation:Cw(p)}}function aBt(e){let t=new Map,r=[];for(let n of e){let i=n.id;if(typeof i=="string"&&i){let s=t.get(i);if(s){let o=dBe(s),a=dBe(n);o!==a&&console.warn(`[local-data] dropping duplicate card id "${i}" (title "${a}") - shared id/idempotency key`);continue}t.set(i,n)}r.push(n)}return r}function dBe(e){let t=e.title;return t==null?"":String(t)}function cBt(e,t){let r=[...t.fields];t.contentKey&&t.contentKey!=="content"&&!r.some(i=>i.key===t.contentKey)&&r.push(lBt(e,t.contentKey));let n=new Map(uBt(e).map((i,s)=>[i,s]));return r.sort((i,s)=>(n.get(i.key)??Number.MAX_SAFE_INTEGER)-(n.get(s.key)??Number.MAX_SAFE_INTEGER))}function uBt(e){return[...new Set(e.flatMap(t=>Object.keys(t)))]}function lBt(e,t){let r=e.map(i=>i[t]).filter(i=>i!==void 0);if(r.length>0&&r.every(i=>typeof i=="boolean"))return{key:t,type:"boolean"};if(r.length>0&&r.every(i=>typeof i=="number"))return{key:t,type:r.every(i=>Number.isInteger(i))?"integer":"number"};let n=r.filter(i=>typeof i=="string");return n.length>0&&n.every(i=>/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(i))?{key:t,type:"string",format:"email"}:n.length>0&&n.every(i=>/^https?:\/\//.test(i))?{key:t,type:"string",format:"url"}:n.length>0&&n.every(i=>/^\d{4}-\d{2}-\d{2}/.test(i))?{key:t,type:"string",format:"date"}:n.some(i=>i.length>=60)?{key:t,type:"string",format:"textarea"}:{key:t,type:"string"}}function dBt(e,t,r){let n=e.filter(c=>c.records?.length);if(n.length===0)return;let i=new Set(t),s=n.find(c=>i.has(c.name));if(s)return s;let o=r.map(c=>c.sourceCall).filter(c=>!!c),a=n.find(c=>o.some(u=>fBt(u,c.name)));return a||n.reduce((c,u)=>(u.records?.length??0)>(c.records?.length??0)?u:c)}function fBt(e,t){if(!/^[A-Za-z_$][\w$]*$/.test(t))return!1;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_$])${r}($|[^A-Za-z0-9_$])`).test(e)}function pBt(e,t){return e.sourceCall?.startsWith("html-cards:")?{order:"ASC",confidence:"high"}:e.perPageHint===void 0||t===-1?{order:"ASC",confidence:"high"}:hBt(e.sourceCall??"")?{order:"DESC",confidence:"high"}:{order:"DESC",confidence:"low"}}function hBt(e){return(e.match(/[A-Za-z][A-Za-z0-9_$]*/g)??[]).some(r=>oBt.some(n=>ABt(r,n)))}function ABt(e,t){let r=e.toLowerCase();if(r===t)return!0;if(!r.startsWith(t))return!1;let n=e[t.length];return!!(n&&/[A-Z0-9_$]/.test(n))}function gBt(){return{cpt:{slug:"item",singular:"Item",plural:"Items",public:!0,supports:["title","editor","custom-fields"]},taxonomy:{slug:"item_cat",label:"Categories",hierarchical:!0,terms:[]},fields:[],items:[],mounts:[],card:{template:"",maps:{}},sourceArrays:[],schema:3}}function mBt(e){let t=iBe(e);return t.some(r=>r.records?.length)?t:[...t,...yBt(e,t)]}function yBt(e,t){let r=Rh(e);if(!r)return[];let n=new Set(t.map(a=>a.evidence)),i=[],s=new Set,o=(a,c)=>{if(!bBt(a)||s.has(a.start))return;s.add(a.start);let u=CBt(e,a);if(n.has(u))return;let l=EBt(e,a,u);i.push({name:c,...l})};return Qh(r,a=>{if(a.type==="VariableDeclarator"&&a.id?.type==="Identifier"&&o(a.init,a.id.name),a.type==="AssignmentExpression"){let c=a.left,u=c?.type==="Identifier"?c.name:c?.property?.name;o(a.right,u??"(anonymous)")}a.type==="Property"&&o(a.value,String(a.key?.name??a.key?.value??"(anonymous)"))}),i}function bBt(e){return!!(e?.type==="ArrayExpression"&&e.elements?.length>0&&e.elements.every(t=>t?.type==="ObjectExpression"))}function Bw(e){return e?e.type==="Literal"?!0:e.type==="ArrayExpression"?(e.elements??[]).every(t=>t===null||Bw(t)):e.type==="ObjectExpression"?(e.properties??[]).every(t=>!t||t.type!=="Property"||t.kind!=="init"||t.method||t.shorthand||t.computed&&!Bw(t.key)?!1:Bw(t.value)):e.type==="UnaryExpression"&&["-","+","!","~"].includes(e.operator)?Bw(e.argument):e.type==="TemplateLiteral"?(e.expressions??[]).length===0:!1:!1}function EBt(e,t,r){let n=e.slice(t.start,t.end);if(n.length>nBt)return{confidence:"low",evidence:`literal too large (${n.length} chars) :: ${r}`};if(!Bw(t))return{confidence:"low",evidence:r};try{let i=rBt(`(${n})`,Object.create(null),{timeout:1e3});return!Array.isArray(i)||i.length>iBt?{confidence:"low",evidence:r}:{records:i,confidence:"high",evidence:r}}catch(i){return{confidence:"low",evidence:`${i.message} :: ${r}`}}}function CBt(e,t){let r=e.slice(t.start,t.end);return r.length>400?`${r.slice(0,400)}...`:r}function IBt(e){let t=e.match(/function\s+\w*[Cc]ard\s*\([^)]*\)\s*\{[\s\S]*?\}/);return t?t[0].length>600?`${t[0].slice(0,600)}...`:t[0]:"(no *Card function found; author from the rendered card markup)"}var _Bt=256*1024;function HV(e,t){if(!gBe(e))return[];let r=[];for(let n of wBt(e))if(t.includes(xBt(n).toLowerCase()))try{r.push({name:n,text:mBe(GR(e,n),"utf8")})}catch{}return r}function TBt(e){let t=[];for(let r of e)try{let n=le(r.text);n("script").each((i,s)=>{if(n(s).attr("src")!==void 0)return;let o=n(s).text();o.trim()&&t.push(o)})}catch{}return t}function QBt(e){return t=>{if(!t||/^(https?:|mailto:|tel:|#|javascript:)/i.test(t))return null;let r=decodeURIComponent(t.split(/[?#]/)[0]);if(!r||ABe(r))return null;let n=hBe(kBt(e)),i=hBe(GR(n,r));if(!i.startsWith(n))return null;let s=BBt(n,i);if(s.startsWith("..")||ABe(s)||!/\.html?$/i.test(i))return null;try{return gBe(i)?mBe(i,"utf8"):null}catch{return null}}}var yBe=async(e,t)=>{let r=e.dir,n=e.outputDir??r;if(!r)return t.errorResult("dir is required");if(!n)return t.errorResult("outputDir is required");let i=Date.now();try{let s=HV(r,[".html",".htm"]),o=s.map(f=>f.text).join(` +`),a=[...HV(GR(r,"assets"),[".js"]),...HV(r,[".js"])],c=TBt(s),u=[],l=[];for(let f of a){if(f.text.length>_Bt||Rh(f.text)===null){u.push(f.name);continue}l.push(f.text)}let d=pBe({html:o,htmlFiles:s,js:[...l,...c].join(` +`),skippedFiles:u,resolvePage:QBt(r)});return vBt(n,{recursive:!0}),SBt(GR(n,"data-model.draft.json"),JSON.stringify(d.model,null,2),"utf8"),console.error(`[data-model] ${JSON.stringify({tool:"scaffold",dir:r,ok:!0,source:d.discovered.source,items:d.model.items.length,todos:d.skillTodos.length,arrays:d.discovered.arrays,skipped:u,durationMs:Date.now()-i})}`),t.textResult(d)}catch(s){return console.error(`[data-model] ${JSON.stringify({tool:"scaffold",dir:r,ok:!1,durationMs:Date.now()-i})}`),t.errorResult(s.message)}};var bBe=async(e,t)=>{let r=e.outputDir,n=e.origin,i=Date.now();try{let{scaffoldDesignFoundation:s}=await Promise.resolve().then(()=>(wj(),Ube)),o=s(r,{origin:n});return console.error(`[design-foundation] ${JSON.stringify({tool:"scaffold",outputDir:r,ok:!0,durationMs:Date.now()-i})}`),t.textResult(o)}catch(s){return console.error(`[design-foundation] ${JSON.stringify({tool:"scaffold",outputDir:r,ok:!1,durationMs:Date.now()-i})}`),t.errorResult(s.message)}};function EBe(e,t){let r=t.split("."),n=e;for(let c of r){if(!n||typeof n!="object")return!1;n=n[c]}if(!n||typeof n!="object")return!1;let i=n,s=Array.isArray(i.evidence)&&i.evidence.length>0,o=typeof i.value=="string"&&i.value.length>0&&i.value!=="TODO"||typeof i.css=="string"&&i.css.length>0&&i.css!=="TODO",a=typeof i.role=="string"&&i.role.length>0&&i.role!=="TODO";return s&&o&&a}var vBe=async(e,t)=>{let r=e.foundation,n=Date.now(),{DesignFoundationSchema:i}=await Promise.resolve().then(()=>(zV(),SBe)),s=i.safeParse(r),o={ok:s.success};if(s.success||(o.errors=s.error.issues),s.success){let a=s.data,c=[];for(let u of a.skillTodos)EBe(a,u)||c.push(u);c.length>0&&(o.ok=!1,o.errors=c.map(u=>({code:"skill_todo_unfilled",path:u.split("."),message:`skillTodos entry "${u}" is still empty or TODO`})))}return console.error(`[design-foundation] ${JSON.stringify({tool:"validate",ok:o.ok,durationMs:Date.now()-n,errorCount:o.errors?.length??0})}`),t.textResult(o)};var NBe=async(e,t)=>{let r=e.outputDir,n=e.foundation,i=!!e.force,s=Date.now(),{saveDesignFoundation:o}=await Promise.resolve().then(()=>(DBe(),RBe));try{let a=o(r,n,{force:i});return console.error(`[design-foundation] ${JSON.stringify({tool:"save",outputDir:r,ok:a.ok,durationMs:Date.now()-s,...a.ok?{unchanged:a.unchanged}:{errorCount:a.errors.length}})}`),t.textResult(a)}catch(a){return console.error(`[design-foundation] ${JSON.stringify({tool:"save",outputDir:r,ok:!1,durationMs:Date.now()-s})}`),t.errorResult(a.message)}};var UBe=async(e,t)=>{let r=e.outputDir,n=Date.now();try{let{inventoryReplica:i}=await Promise.resolve().then(()=>(OBe(),FBe)),s=i(r);return console.error(`[replicate] ${JSON.stringify({tool:"inventory",outputDir:r,ok:!0,durationMs:Date.now()-n,archetypes:Object.fromEntries(Object.entries(s.archetypes).map(([o,a])=>[o,a.count]))})}`),t.textResult(s)}catch(i){return console.error(`[replicate] ${JSON.stringify({tool:"inventory",outputDir:r,ok:!1,durationMs:Date.now()-n})}`),t.errorResult(i.message)}};var GBe=async(e,t)=>{let r=e.outputDir,n=e.replicaBaseUrl,i=e.urls??[],s=Date.now();try{let{verifyReplica:o}=await Promise.resolve().then(()=>(VBe(),zBe)),a=await o({outputDir:r,replicaBaseUrl:n,urls:i,viewports:e.viewports,outputSubdir:e.outputSubdir,cdpPort:e.cdpPort,concurrency:e.concurrency});return console.error(`[replicate] ${JSON.stringify({tool:"verify",outputDir:r,replicaBaseUrl:n,urlCount:i.length,ok:a.ok,durationMs:Date.now()-s})}`),t.textResult(a)}catch(o){return console.error(`[replicate] ${JSON.stringify({tool:"verify",outputDir:r,replicaBaseUrl:n,ok:!1,durationMs:Date.now()-s})}`),t.errorResult(o.message)}};import{writeFileSync as wkt,renameSync as Skt}from"node:fs";import{join as vkt}from"node:path";var cke=async(e,t)=>{let r=e.originDir,n=e.replicaDir;if(!r||!n)return t.errorResult("liberate_compare requires originDir + replicaDir");let i=Date.now();try{let{compareScreenshotDirs:s,buildRepairTasks:o,DEFAULT_MAX_HEIGHT_DELTA:a}=await Promise.resolve().then(()=>(eD(),ake)),c=e.maxHeightDelta??a,u=e.floor??.99,l=await s({originDir:r,replicaDir:n,viewports:e.viewports,diffOutputDir:e.diffOutputDir,maxHeightDelta:c}),d=o(l.results,{floor:u}),f=vkt(n,"repair-tasks.json"),p=`${f}.tmp.${process.pid}`;return wkt(p,JSON.stringify({schema:1,floor:u,maxHeightDelta:c,tasks:d},null,2)+` +`),Skt(p,f),console.error(`[compare] ${JSON.stringify({tool:"compare",originDir:r,replicaDir:n,count:l.results.length,repairTasks:d.length,durationMs:Date.now()-i})}`),t.textResult({...l,heightGate:{maxHeightDelta:c,perPage:l.results.map(h=>({pathname:h.pathname,desktop:h.desktop.heightDelta??null,mobile:h.mobile.heightDelta??null}))},repairTasks:{count:d.length,path:f}})}catch(s){return console.error(`[compare] ${JSON.stringify({tool:"compare",originDir:r,replicaDir:n,ok:!1,durationMs:Date.now()-i})}`),t.errorResult(s.message)}};function uke(e){return e.sections.map(t=>{let r=[t.columns!=null?`c${t.columns}`:"",t.mediaPosition?`m${t.mediaPosition[0]}`:"",t.imageBucket?`i${t.imageBucket[0]}`:""].filter(Boolean).join(",");return r?`${t.type}{${r}}`:t.type}).join("|")}function lke(e){let t=new Map;for(let n of e){let i=uke(n),s=t.get(i);s?s.push(n):t.set(i,[n])}let r=[];for(let[n,i]of t){let s=i.reduce((o,a)=>a.htmlBytes>o.htmlBytes?a:o);r.push({key:n,members:i.map(o=>o.url),representative:s.url,signature:s})}return{clusters:r}}var dke=async(e,t)=>{let r=e.signatures;return Array.isArray(r)?t.textResult(lke(r)):t.errorResult("signatures[] is required")};E2();var fke=async(e,t)=>{let r=e.url,n=e.detail;if(!r||!n)return t.errorResult("url and detail are required");if(n==="signature"){let i=e.html;return i?t.textResult(xme(r,i,i.length)):t.errorResult("html is required for detail=signature")}if(n==="full"){let i=e.mediaMap??{},s=typeof e.cdpPort=="number"?e.cdpPort:void 0;try{let{specs:o}=await b2(r,i,{cdpPort:s});return t.textResult(o)}catch(o){return t.errorResult(`section_extract detail=full failed for ${r}: ${o instanceof Error?o.message:String(o)}`)}}return t.errorResult(`unknown detail: ${n} (expected 'signature' or 'full')`)};function tD(e,t,r){let n=[],i=[];for(let c of e.sections){let u=``;for(let l of c.slots){let d=t[l];d==null||d===""?n.push(l):u+=` +${String(d)}`}i.push(u)}let o=Number(t.__extraSections??0)>0,a=n.length>0||o;return{postContent:i.join(` +`),misfit:a,sanity:{unfilledSlots:n,sectionCountMismatch:o}}}var pke=async(e,t)=>{let r=e.skeleton,n=e.pageContent;return!r||!n?t.errorResult("skeleton and pageContent are required"):t.textResult(tD(r,n,e.mediaMap??{}))};eE();import{mkdirSync as U_t,renameSync as qke,unlinkSync as zke,writeFileSync as c7}from"node:fs";import{join as Vke}from"node:path";St();import{readdirSync as xkt,readFileSync as Bkt,lstatSync as kkt}from"node:fs";import{join as _kt,relative as Tkt,sep as Qkt}from"node:path";function Rkt(e){let t=[],r=n=>{for(let i of xkt(n)){if(i.startsWith(".")||i==="node_modules")continue;let s=_kt(n,i),o=kkt(s);o.isSymbolicLink()||(o.isDirectory()?r(s):(i.toLowerCase().endsWith(".html")||i.toLowerCase().endsWith(".htm"))&&t.push(s))}};return r(e),t}function Dkt(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function hke(e){return e.map(Dkt).filter(Boolean).join("-")}function t7(e){let r=e.replace(/\.html?$/i,"").split(Qkt).filter(Boolean);return r.length===0?"home":r[r.length-1].toLowerCase()==="index"?r.length===1?"home":hke(r.slice(0,-1))||"home":hke(r)||"home"}function rD(e){let t=Rkt(e);if(t.length===0)throw new Error(`no html pages found under ${e}`);let r=t.map(i=>{let s=Bkt(i,"utf8"),o=le(s),a=Tkt(e,i),c={},u=o("body").attr()??{};for(let[l,d]of Object.entries(u))l.startsWith("data-")&&(c[l.slice(5)]=d);return{relPath:a,slug:t7(a),html:s,title:o("title").first().text().trim(),...Object.keys(c).length>0?{bodyData:c}:{}}});r.sort((i,s)=>i.slug.localeCompare(s.slug));let n=new Set;for(let i of r){if(n.has(i.slug))throw new Error(`slug collision: "${i.slug}" from "${i.relPath}"`);n.add(i.slug)}return{root:e,pages:r}}pi();St();function Ake(e){return e==="home"?"/":`/${e}/`}function nD(e,t){let r=le(e),n=new Set(t);return r("a[href]").each((i,s)=>{let o=r(s).attr("href")??"";if(!o||/^[a-z]+:/i.test(o)||o.startsWith("//")||o.startsWith("#"))return;let a=o.split(/[?#]/)[0];try{a=decodeURIComponent(a)}catch{}let c=t7(a.replace(/^\.\//,"").replace(/^\//,""));n.has(c)&&r(s).attr("href",Ake(c))}),r("body").html()??e}function gke(e,t){let r=t.flatMap(i=>{let s=Ake(i.slug);return[i.relPath,`./${i.relPath}`,`/${i.relPath}`].map(o=>({raw:o,url:s}))}).sort((i,s)=>s.raw.length-i.raw.length),n=e;for(let{raw:i,url:s}of r){let o=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`(['"])${o}\\1`,"g"),(a,c)=>`${c}${s}${c}`)}return n}St();En();import{createHash as Nkt}from"node:crypto";function Mkt(e){return e.split(";").map(t=>t.trim().replace(/\s+/g," ")).filter(Boolean).map(t=>{let r=t.indexOf(":");return r<0?t:`${t.slice(0,r).trim()}:${t.slice(r+1).trim()}`}).join(";")}var S0=class{rules=new Map;classFor(t){let r=Mkt(t??"");if(!r)return null;let n=`lib-i${Nkt("sha1").update(r).digest("hex").slice(0,10)}`;return this.rules.set(n,r),n}get size(){return this.rules.size}toCss(){return[...this.rules.entries()].sort((t,r)=>t[0]r[0]?1:0).map(([t,r])=>`.${t}{${r}}`).join(` +`)}};function mke(...e){let t=new Set;for(let r of e)for(let n of(r??"").split(` +`)){let i=n.trim();i&&t.add(i)}return[...t].sort().join(` +`)}En();function n7(e,t,r,n={}){let i=Okt(e,t);if(!i)return null;let s=$kt(e,i);if(s.unsupported)return null;let o=[],a=0,c=new Set,u=Hkt(e,i);for(let l of s.fields){let d=l.tagName.toLowerCase(),f=e(l);if(d==="textarea"){o.push(r7("jetpack/field-textarea",iD(e,i,l,f.attr("placeholder")),{inputType:"textarea"})),a+=1;continue}if(d==="select"){let A=Wkt(e,l);if(A.length===0)return null;o.push(r7("jetpack/field-select",iD(e,i,l,Ykt(e,l),A),{inputType:"dropdown"})),a+=1;continue}if(d!=="input")return null;let p=Tw(f);if(p==="radio"){let A=(f.attr("name")??"").trim(),g=A?`name:${A}`:`node:${s.fields.indexOf(l)}`;if(c.has(g))continue;let m=Vkt(e,i,l);if(!m)return null;c.add(g),o.push(Zkt("jetpack/field-radio",m,"radio")),a+=1;continue}if(p==="checkbox"){let A=iD(e,i,l),g=e_t(e,l,A.label)?"jetpack/field-consent":"jetpack/field-checkbox";o.push(Kkt(g,A)),a+=1;continue}let h=zkt(e,l);if(!h)return null;o.push(r7(h,iD(e,i,l,f.attr("placeholder")),{inputBlockName:h==="jetpack/field-telephone"?"jetpack/phone-input":"jetpack/input",inputType:h==="jetpack/field-telephone"?void 0:p})),a+=1}return a===0?null:(u&&o.push(Jkt(e,u)),{markup:` +
+${o.join(` +`)} +
+`,fieldCount:a})}var Pkt="input, select, textarea",Lkt="button, input, select, textarea",Fkt=new Set(["hidden"]);function Okt(e,t){if((t.tagName?.toLowerCase()??"")==="form")return t;let n=e(t).find("form").toArray();if(n.length!==1)return null;let[i]=n;return Ukt(e,t,i)?e(t).find(Lkt).toArray().some(o=>!Ike(e,o,i))?null:i:null}function Ukt(e,t,r){if(yke(t))return!1;let n=e(t).clone();return n.find("form").remove(),xs(n.text())?!1:n.find("*").toArray().every(i=>{let s=e(i),o=i.tagName?.toLowerCase()??"",a=i.attribs??{};return o==="img"||o==="picture"||o==="svg"||o==="video"||o==="canvas"||yke(i)||a.src||a.href||a.role||a["aria-label"]?!1:s.children().length===0&&!xs(s.text())})}function yke(e){return Object.keys(e.attribs??{}).some(t=>t!=="data-astro-cid")}function $kt(e,t){let r=[],n=new Map,i=!1;for(let s of e(t).find(Pkt).toArray()){if(!ve(s))continue;let o=s,a=o.tagName.toLowerCase(),c=e(o);if(a==="input"){let u=Tw(c);if(Fkt.has(u)||jkt(u))continue;if(u==="checkbox"){let l=(c.attr("name")??"").trim();l&&n.set(l,(n.get(l)??0)+1)}if(!qkt(u)){i=!0;continue}}r.push(o)}for(let s of r){let o=e(s);if(s.tagName.toLowerCase()==="input"&&Tw(o)==="checkbox"){let a=(o.attr("name")??"").trim();a&&(n.get(a)??0)>1&&(i=!0)}}for(let s of e(t).find("button").toArray())ve(s)&&(e(s).attr("type")??"submit").trim().toLowerCase()!=="submit"&&(i=!0);return{fields:r,unsupported:i}}function Hkt(e,t){for(let r of e(t).find("button, input").toArray()){if(!ve(r))continue;let n=r,i=n.tagName.toLowerCase(),s=e(n);if(i==="button"&&(s.attr("type")??"submit").toLowerCase()==="submit"||i==="input"&&Tw(s)==="submit")return n}return null}function Tw(e){return(e.attr("type")??"text").trim().toLowerCase()}function jkt(e){return e==="submit"}function qkt(e){return["text","email","tel","url","checkbox","radio"].includes(e)}function zkt(e,t){let r=e(t);switch(Tw(r)){case"text":return Xkt(e,t)?"jetpack/field-name":"jetpack/field-text";case"email":return"jetpack/field-email";case"tel":return"jetpack/field-telephone";case"url":return"jetpack/field-url";default:return null}}function iD(e,t,r,n,i){let s={},o=oD(e,t,r);o&&(s.label=o),i7(e,r)&&(s.required=!0);let a=xs(n??"");return a&&(s.placeholder=a),i&&i.length>0&&(s.options=i),s}function Vkt(e,t,r){let i=(e(r).attr("name")??"").trim(),s=i?t_t(e(t).find('input[type="radio"]').toArray(),e,"name",i):[r],o=s.filter(u=>!e(u).attr("disabled")).map(u=>oD(e,t,u)||xs(e(u).attr("value")??"")).filter(Boolean);if(o.length===0)return null;let a={options:o},c=Gkt(e,t,s)||r_t(i);return c&&(a.label=c),s.some(u=>i7(e,u))&&(a.required=!0),a}function Gkt(e,t,r){let n=e(r[0]).closest("fieldset").get(0);if(n&&r.every(i=>Ike(e,i,n))){let i=xs(e(n).children("legend").first().text());if(i)return i}return oD(e,t,r[0])}function Wkt(e,t){return e(t).children("option").toArray().filter((r,n)=>!Eke(e,r,n)).map(r=>xs(e(r).text())||xs(e(r).attr("value")??"")).filter(Boolean)}function Ykt(e,t){let r=e(t).children("option").first().get(0);return r&&Eke(e,r,0)?xs(e(r).text()):""}function Eke(e,t,r){let n=e(t);if(n.attr("disabled")===void 0)return!1;let i=xs(n.attr("value")??"");return r===0||i===""||n.attr("selected")!==void 0}function Jkt(e,t){let r=e(t),n=t.tagName.toLowerCase(),i=xs(n==="input"?r.attr("value")??r.attr("aria-label")??"Submit":r.text()||r.attr("aria-label")||"Submit");return Qw("jetpack/button",{element:"button",text:i||"Submit"})}function r7(e,t,r){let n=sD(t),i=r.inputBlockName??(r.inputType?"jetpack/input":void 0),s=[Cke(t),i?Qw(i,{placeholder:t.placeholder,type:r.inputType}):""].filter(Boolean).join(` +`);return` +
+${s} +
+`}function Zkt(e,t,r){let n=sD(t),i=(t.options??[]).map(o=>Qw("jetpack/option",{label:o})).join(` +`),s=[Cke(t),` +
    +${i} +
+`].filter(Boolean).join(` +`);return` +
+${s} +
+`}function Kkt(e,t){let r=e==="jetpack/field-consent"?{...t,consentType:"explicit",explicitConsentMessage:t.label}:t,n=sD(r),i={label:t.label},s=e==="jetpack/field-consent"?{...i,hideInput:!1,isStandalone:!0}:{...i,isStandalone:!0};return` +
+${Qw("jetpack/option",s)} +
+`}function Cke(e){return e.label?Qw("jetpack/label",{label:e.label,requiredText:e.required?"*":void 0}):""}function Qw(e,t){let r=sD(t);return``}function sD(e){let t={};return e.label&&(t.label=e.label),e.required&&(t.required=!0),e.placeholder&&(t.placeholder=e.placeholder),e.options&&e.options.length>0&&(t.options=e.options),e.consentType&&(t.consentType=e.consentType),e.explicitConsentMessage&&(t.explicitConsentMessage=e.explicitConsentMessage),e.element&&(t.element=e.element),e.text&&(t.text=e.text),"type"in e&&typeof e.type=="string"&&e.type&&(t.type=e.type),"requiredText"in e&&typeof e.requiredText=="string"&&e.requiredText&&(t.requiredText=e.requiredText),"isStandalone"in e&&typeof e.isStandalone=="boolean"&&(t.isStandalone=e.isStandalone),"hideInput"in e&&typeof e.hideInput=="boolean"&&(t.hideInput=e.hideInput),Object.keys(t).length===0?"":` ${JSON.stringify(t).replace(/--/g,"\\u002d\\u002d")}`}function oD(e,t,r){let n=e(r),i=(n.attr("id")??"").trim();if(i){let c=e(t).find("label").toArray().find(l=>(e(l).attr("for")??"")===i),u=c?bke(e,c):"";if(u)return u}let s=n.closest("label").get(0);if(s){let c=bke(e,s);if(c)return c}let o=n.prevAll("label").first();if(o.length>0){let c=xs(o.text());if(c)return c}let a=xs(n.attr("aria-label")??"");return a||""}function bke(e,t){let r=e(t).clone();return r.find("input, select, textarea, button").remove(),xs(r.text())}function i7(e,t){let r=e(t);return r.attr("required")!==void 0||(r.attr("aria-required")??"").toLowerCase()==="true"}function Xkt(e,t){let r=e(t),n=[r.attr("autocomplete")??"",r.attr("id")??"",r.attr("name")??"",oD(e,e(t).closest("form").get(0),t)].join(" ").toLowerCase();return/(^|[^a-z0-9])(given-name|family-name|additional-name|honorific-prefix|honorific-suffix|name)([^a-z0-9]|$)/.test(n)}function e_t(e,t,r){if(!i7(e,t))return!1;let n=e(t),i=[r??"",n.attr("id")??"",n.attr("name")??""].join(" ").toLowerCase();return/\b(consent|terms?|privacy|agree|agreement|permission)\b/.test(i)}function Ike(e,t,r){return t===r||e(t).parents().toArray().includes(r)}function t_t(e,t,r,n){return e.filter(i=>(t(i).attr(r)??"")===n)}function r_t(e){return xs(e.replace(/[_-]+/g," "))}function xs(e){return e.replace(/\s+/g," ").trim()}function al(e){return JSON.stringify(e).replace(/--/g,"\\u002d\\u002d")}function vke(e){return(e.attr("class")??"").split(/\s+/).filter(Boolean).join(" ")}function Bo(e,t){let r=t?[...e,`"className":${al(t)}`]:e;return r.length?` {${r.join(",")}}`:""}function ef(e,t){let r=vke(e),n=t.classFor(e.attr("style"));return[r,n].filter(Boolean).join(" ")}function Rw(e){return e?` +${e} +`:""}var n_t=/^h([1-6])$/,s7=new Set(["a","strong","em","b","i","br","span"]);function tf(e,t){let r="";for(let n of e(t).contents().get())if(en(n))r+=kt(n.data);else if(ve(n)){let i=n.tagName?.toLowerCase()??"";if(i==="br"){r+="
";continue}let s=(e(n).attr("class")??"").trim(),o=(e(n).attr("style")??"").trim();if(s7.has(i)){let a=tf(e,n),c=s?` class="${kt(s)}"`:"";if(i==="a"){let u=kt(e(n).attr("href")??"");r+=`${a}`}else{let u=o?` style="${kt(o)}"`:"";r+=`<${i}${c}${u}>${a}`}}else r+=tf(e,n)}return r}function wke(e,t,r){let n=kt(e(t).attr("src")??""),i=kt(e(t).attr("alt")??""),s=ef(e(t),r),o=Bo([],s),a=["wp-block-image",s].filter(Boolean).join(" ");return` +
${i}
+`}function Dw(e){return` +

${e}

+`}function i_t(e,t,r){let n=e(t),i=ef(n,r),s=Bo([],i),o=i?` class="${kt(i)}"`:"",a=n.children("ul, ol").toArray();if(a.length===0)return` +${tf(e,t).trim()} +`;let c=n.clone();c.children("ul, ol").remove(),c.find("button svg").remove();let u=c.get(0),l=u&&ve(u)?tf(e,u).trim():"",d=a.map(p=>xke(e,p,r)).join(` +`),f=[l,d].filter(Boolean).join(` +`);return` +${f} +`}function xke(e,t,r){let n=t.tagName?.toLowerCase()??"",i=e(t),s=i.children("li").map((d,f)=>i_t(e,f,r)).get().join(` +`),o=ef(i,r),c=Bo(n==="ol"?['"ordered":true']:[],o),u=n==="ol"?"ol":"ul",l=["wp-block-list",o].filter(Boolean).join(" ");return` +<${u} class="${kt(l)}">${s} +`}var s_t=new Set(["button","input","select","textarea","svg"]);function o_t(e,t){let r=t.tagName?.toLowerCase()??"";return s_t.has(r)?!0:e(t).find("button, input, select, textarea, svg").length>0}var a_t=/\b(button|btn)\b/i;function Ske(e,t){return(t.tagName??"").toLowerCase()!=="a"?!1:a_t.test(e(t).attr("class")??"")}function c_t(e,t){let r=e(t);return r.attr("id")||!(r.attr("class")??"").trim()?!1:r.children().length===0&&!r.text().trim()}function u_t(e,t){return e(t).find("[id]").toArray().some(r=>{let n=e(r);return n.children().length===0&&!n.text().trim()})}function l_t(e,t,r){return(t.tagName??"").toLowerCase()==="form"?!1:e(t).find("form").toArray().some(n=>n7(e,n,r)!==null)}function Bke(e,t,r,n={}){let i=t.tagName?.toLowerCase()??"",s=e(t);if(n.jetpackForms){let p=n7(e,t,r);if(p)return n.onJetpackForm?.(p.fieldCount),{markup:p.markup,clean:!0}}let o=n.jetpackForms&&l_t(e,t,r);if(n.verbatimInteractive&&!o&&!u_t(e,t)&&(o_t(e,t)||c_t(e,t)))return{markup:Rw((e.html(t)??"").trim()),clean:!0};let a=n_t.exec(i);if(a){let p=Number(a[1]),h=ef(s,r),A=Bo(p===2?[]:[`"level":${p}`],h),g=["wp-block-heading",h].filter(Boolean).join(" "),m=tf(e,t).trim();return{markup:` +${m} +`,clean:!0}}if(i==="p"){let p=ef(s,r),h=Bo([],p),A=tf(e,t).trim(),m=``;return{markup:` +${m}${A}

+`,clean:!0}}if(i==="img")return{markup:wke(e,t,r),clean:!0};if(i==="a"&&Ske(e,t)){let p=kt(s.attr("href")??""),h=kt(s.text().trim()),A=ef(s,r),g=[A,"lib-cta"].filter(Boolean).join(" "),m=Bo([],g),b=["wp-block-button",g].filter(Boolean).join(" "),E=["wp-block-button__link","wp-element-button",A].filter(Boolean).join(" ");return{markup:` +
+ +
+`,clean:!0}}if(i==="ul"||i==="ol")return{markup:xke(e,t,r),clean:!0};if(i==="table"){let p=vke(s),h=k=>`${e(k).children("th, td").map((_,v)=>{let N=v.tagName?.toLowerCase()==="th"?"th":"td";return`<${N}>${kt(e(v).text().trim())}`}).get().join("")}`,A=s.find("thead tr").map((k,D)=>h(D)).get(),g=s.find("tbody tr").toArray();if(g.length===0&&(g=s.find("tr").toArray()),A.length===0&&g.length>0){let k=g[0];e(k).children("td").length===0&&e(k).children("th").length>0&&(A.push(h(k)),g=g.slice(1))}let m=g.map(k=>h(k)),b=Bo([],p),E=p,C=E?` class="${kt(E)}"`:"",I=A.length?`${A.join("")}`:"",T=`${m.join("")}`;return{markup:` +${I}${T}
+`,clean:!0}}let c=s.attr("id"),u=s.children().toArray();if(c||u.length>0){let p=k=>{let D=(k.tagName??"").toLowerCase();return s7.has(D)?e(k).find("*").toArray().every(_=>s7.has((_.tagName??"").toLowerCase())):!1},h=u.length>0&&u.every(k=>p(k)),A=u.length>0&&u.every(k=>Ske(e,k)),g,m;if(h&&!A)g=Rw(tf(e,t).trim()),m=!0;else{let k=u.map(N=>Bke(e,N,r,n)),D=k.map(N=>N.markup).filter(Boolean).join(` +`),_=s.clone().children().remove().end().text().trim(),v=_&&k.length===0?Dw(kt(_)):"";g=[D,v].filter(Boolean).join(` +`),m=k.every(N=>N.clean)&&!(_&&k.length>0)}let b=ef(s,r),E=['"tagName":"div"'];c&&E.unshift(`"anchor":${al(c)}`);let C=Bo(E,b),I=["wp-block-group",b].filter(Boolean).join(" "),T=c?` id="${kt(c)}"`:"";return{markup:` +${g?` +${g} +`:""} +`,clean:m}}let l=s.find("img");if(l.length>0){let p=l.map((g,m)=>wke(e,m,r)).get().join(` +`),h=kt(s.text().trim()),A=h?` +${Dw(h)}`:"";return{markup:p+A,clean:!1}}let d=s.text().trim();if(i==="div"||i==="span"){if(d){let h=ef(s,r),A=Bo([],h),g=h?` class="${kt(h)}"`:"";return{markup:` +${tf(e,t).trim()}

+`,clean:!0}}let p=(s.attr("class")??"").trim()?(e.html(t)??"").trim():"";return p?{markup:Rw(p),clean:!0}:{markup:Dw(kt(d)),clean:!1}}let f=(e.html(t)??"").trim();return f?{markup:Rw(f),clean:!0}:{markup:Dw(kt(d)),clean:!1}}function d_t(e){return e.replace(//g,"")}function f_t(e,t,r){let n=(e.classes??[]).join(" "),i=[`"anchor":${al(e.id)}`],s=[];(t.kind==="tabs"||t.kind==="slider")&&(i.push(`"activeClass":${al(t.activeClass)}`),s.push(`"activeClass":${al(t.activeClass)}`),t.kind==="slider"&&t.intervalMs&&(i.push(`"intervalMs":${JSON.stringify(t.intervalMs)}`),s.push(`"intervalMs":${JSON.stringify(t.intervalMs)}`)));let o=Bo(i,n),a=s.length?`{${s.join(",")}}`.replace(/'/g,"\\u0027"):"",c=a?` data-wp-context='${a}'`:"",u=[`wp-block-dla-${t.kind}`,n].filter(Boolean).join(" ");return` +
${r}
+`}function kke(e,t={}){let r=t.instanceStyles??new S0,n=le(e.html),i=0,s=n("section, article, main, div").first(),o=s.length?s:n("body");if(e.behavior&&e.behavior.kind!=="reveal"){let k=d_t(o.html()??"");if((t.behaviorWrapper??"dla")==="group"){let D=(e.classes??[]).join(" "),_=Bo([`"anchor":${al(e.id)}`,'"tagName":"section"'],D),v=["wp-block-group",D].filter(Boolean).join(" "),N=Rw(k);return{markup:` +
${N?` +${N} +`:""}
+`,confidence:1,instanceStyles:r,formsConverted:i}}return{markup:f_t(e,e.behavior,k),confidence:1,instanceStyles:r,formsConverted:i}}let a={verbatimInteractive:t.verbatimInteractive??!1,jetpackForms:t.jetpackForms??!1,onJetpackForm:()=>{i+=1}},c=[],u=0,l=0;for(let k of o.contents().get())if(ve(k)){l+=1;let D=Bke(n,k,r,a);D.clean||(u+=1),c.push(D.markup)}else if(en(k)){let D=k.data.trim();if(!D)continue;l+=1,c.push(Dw(kt(D)))}let d=c.join(` +`),f=(e.classes??[]).join(" "),p=l===0?0:1-u/l;if(e.behavior?.kind==="reveal"){let k=e.behavior,D=[`"anchor":${al(e.id)}`,`"threshold":${JSON.stringify(k.threshold)}`,`"translateY":${al(k.translateY)}`,`"durationMs":${JSON.stringify(k.durationMs)}`],_=Bo(D,f),v=`{"visible":false,"threshold":${JSON.stringify(k.threshold)}}`.replace(/--/g,"\\u002d\\u002d"),N=["wp-block-dla-reveal",f].filter(Boolean).join(" ");return{markup:` +
${d}
+`,confidence:p,instanceStyles:r,formsConverted:i}}let h=`"anchor":${al(e.id)}`,A='"tagName":"section"',g=t.wrapper??"section",m=r.classFor(o.attr("style")),b=[f,m].filter(Boolean).join(" "),C=Bo(g==="section"?[h,A]:[h],b),I=["wp-block-group",b].filter(Boolean).join(" ");return{markup:` +<${g} id="${kt(e.id)}" class="${kt(I)}">${d} +`,confidence:p,instanceStyles:r,formsConverted:i}}St();var p_t=new Set(["script","style","template","noscript"]),h_t=/"className"\s*:\s*"([^"]*)"/g;function _ke(e){let t=new Set,r=le(e);r("[class]").each((n,i)=>{let s=i;if(!p_t.has(s.tagName?.toLowerCase()??""))for(let o of(r(s).attr("class")??"").split(/\s+/))o&&t.add(o)});for(let n of e.matchAll(h_t))for(let i of n[1].split(/\s+/))i&&t.add(i);return t}function Tke(e,t){let r=_ke(t),n=new Set;for(let i of _ke(e))r.has(i)||n.add(i);return[...n].sort()}function Qke(e,t={}){let r=t.native===!0,n=t.pageSlugs?.length?nD(e.html,t.pageSlugs):e.html,i=Vu(n).filter(p=>p.role==="body").map(p=>{let h=t.detectSection?.(p);return h?{...p,behavior:h}:t.reveal?{...p,behavior:t.reveal}:p});if(i.length===0)return{postContent:"",report:[],formsConverted:0,contractIssues:[],stylingDrops:[]};let s={sections:[]},o={},a=[],c=[],u=0;for(let p of i){let{markup:h,confidence:A,formsConverted:g}=kke(p,{behaviorWrapper:r?"dla":"group",instanceStyles:t.instanceStyles,verbatimInteractive:t.verbatimInteractive,jetpackForms:t.jetpackForms});u+=g;let m=g>0?[]:Tke(p.html,h);m.length>0&&c.push({sectionId:p.id,droppedClasses:m}),s.sections.push({type:"content",slots:[p.id]}),o[p.id]=h;let b=p.behavior&&(r||p.behavior.kind==="reveal")?`dla/${p.behavior.kind}`:"group";a.push({sectionId:p.id,blockType:b,confidence:A})}let l=tD(s,o,{});if(l.misfit)throw new Error(`compose mismatch for "${e.slug}": ${JSON.stringify(l.sanity)}`);let d=l.postContent.split(` +`).filter(p=>!/^ +
+ +
+`}function cD(e,t=0){let r=v0(e.selector);if(e.featured){let s={};r&&(s.anchor=r),s.tagName="div",e.wrapperClass&&(s.className=e.wrapperClass);let o=r?` id="${r}"`:"",a=h_e(e.wrapperClass),c={};e.featured.columnWrapperClass&&(c.className=e.featured.columnWrapperClass);let u=h_e(e.featured.columnWrapperClass),l=e.featured.termSlug&&e.featured.taxonomy?{dlaTermSlug:e.featured.termSlug,dlaTaxonomy:e.featured.taxonomy}:{},d=E7({perPage:e.featured.leadPerPage,offset:0,postType:e.query.postType,order:e.query.order,orderBy:e.query.orderBy,queryId:t,...l}),f=E7({perPage:e.featured.columnPerPage,offset:e.featured.leadPerPage,postType:e.query.postType,order:e.query.order,orderBy:e.query.orderBy,queryId:t+zTt,variant:e.featured.variant,...l}),p=` +${d} + +
${f}
+ +`,h=r?`#${r} .wp-block-query, +#${r} .wp-block-post-template{display:contents} +#${r} .wp-block-post-template > li{display:contents}`:"";return{markup:p,css:h}}let n=E7({anchor:r,perPage:e.query.perPage,offset:0,postType:e.query.postType,order:e.query.order,orderBy:e.query.orderBy,queryId:t,postTemplateClassName:e.wrapperClass}),i=r?`#${r} .wp-block-post-template > li{display:contents}`:"";return{markup:n,css:i}}function A_e(e,t){let r=e,n=[],i=[],s=[];return t.forEach((o,a)=>{let c=v0(o.selector);if(!c){i.push(o.selector);return}let u=new RegExp(`\\s*
]*>\\s*
\\s*`);if(!u.test(r)){i.push(c);return}let l=cD(o,a);r=r.replace(u,()=>l.markup),n.push(c),l.css&&s.push(l.css)}),{markup:r,injected:n,missing:i,css:s.join(` +`)}}function g_e(e,t){let r=e,n=0;for(let i of t){let s=new RegExp(`(?(n+=1,`/* data-mount neutralized (WordPress-driven): ${i} */`))}return{js:r,removed:n}}var m_e=`/* dla: read a WordPress-driven card record from its DOM data island */ +window.dlaItem = function (id) { + var sel = '.dla-item[data-id="' + (window.CSS && CSS.escape ? CSS.escape(id) : id) + '"]'; + var el = document.querySelector(sel); + if (!el) { return null; } + try { + var d = JSON.parse(el.textContent); + if (d && d.meta && typeof d.meta === 'object') { + for (var k in d.meta) { if (!(k in d)) { d[k] = d.meta[k]; } } + } + return d; + } catch (e) { return null; } +};`;function y_e(e,t){let r=e,n=0;for(let i of t){let s=new RegExp(`${Nh(i)}\\.find\\(\\s*([\\w$]+)\\s*=>\\s*\\1\\.id\\s*===?\\s*((?:[^()]|\\([^()]*\\))+?)\\s*\\)`,"g");r=r.replace(s,(o,a,c)=>(n+=1,`window.dlaItem(${c.trim()})`))}return{js:r,rewritten:n}}rc();import{mkdirSync as GTt,writeFileSync as WTt,existsSync as YTt}from"node:fs";import{join as b_e}from"node:path";var E_e="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",JTt=new Set(["woff2","woff","ttf","otf","eot"]);function uD(e,t){let n=new RegExp(`${t}\\s*:\\s*([^;]+)`,"i").exec(e);return n?n[1].trim():null}function ZTt(e){let t=e.split("?")[0].split("#")[0],r=t.lastIndexOf(".");if(r<0)return null;let n=t.slice(r+1).toLowerCase();return JTt.has(n)?n:null}function KTt(e){let t=/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,r=[],n;for(;(n=t.exec(e))!==null;){let i=n[2].trim(),s=ZTt(i);s&&r.push({url:i,format:s})}return r.length===0?null:(r.sort((i,s)=>{let o=a=>a.format==="woff2"?0:a.format==="woff"?1:2;return o(i)-o(s)}),r[0])}function XTt(e){let t=e.trim().toLowerCase();if(t==="normal")return"400";if(t==="bold")return"700";let r=/\d{3}/.exec(t);return r?r[0]:"400"}function e2t(e){let t=(e??"").trim().toLowerCase();return t==="italic"?"italic":t.startsWith("oblique")?"oblique":"normal"}function t2t(e){let t=[],r=new Set,n=/@font-face\s*\{([^}]*)\}/gi,i;for(;(i=n.exec(e))!==null;){let s=i[1],o=uD(s,"font-family");if(!o)continue;let a=o.replace(/^["']|["']$/g,"").trim();if(!a)continue;let c=uD(s,"src");if(!c)continue;let u=KTt(c);if(!u)continue;let l=XTt(uD(s,"font-weight")??"400"),d=e2t(uD(s,"font-style")),f=`${a.toLowerCase()}|${l}|${d}|${u.url}`;r.has(f)||(r.add(f),t.push({family:a,src:u.url,format:u.format,weight:l,style:d}))}return t}function r2t(e){let r=(e.src.split("?")[0].split("#")[0].split("/").pop()??"").replace(/[^A-Za-z0-9._-]+/g,"");if(r&&/\.[a-z0-9]+$/i.test(r))return r;let n=e.family.replace(/[^A-Za-z0-9]+/g,""),i=e.style==="italic"?"-italic":"",s=e.format==="woff"?"woff":"woff2";return`${n}-${e.weight}${i}.${s}`}async function C_e(e,t){let r=t.fetchImpl??fetch,n=t.fontsSubdir??"assets/fonts",i=b_e(t.themeDir,n),s=[],o=[],a=[],c=new Map;for(let u of e){let l;try{let f=await r(u,{headers:{"User-Agent":E_e},signal:AbortSignal.timeout(t.timeoutMs??3e4)});if(!f.ok)throw new Error(`HTTP ${f.status}`);l=await f.text()}catch(f){o.push({url:u,error:`css fetch failed: ${f.message}`});continue}let d=l;for(let f of t2t(l))try{let p=c.get(f.src);if(!p){Wu(f.src);let A=r2t(f);p=`${n}/${A}`;let g=b_e(i,A);if(!YTt(g)){let m=await r(f.src,{headers:{"User-Agent":E_e},signal:AbortSignal.timeout(t.timeoutMs??3e4)});if(!m.ok)throw new Error(`HTTP ${m.status}`);GTt(i,{recursive:!0}),WTt(g,Buffer.from(await m.arrayBuffer()))}c.set(f.src,p),s.push({...f,localPath:p})}let h=p.replace(/^assets\//,"../");d=d.split(f.src).join(h)}catch(p){o.push({url:f.src,error:p.message})}a.push(d)}return{faces:s,localizedCss:a.join(` + +`),errors:o}}pi();var Mh=Tr(pw(),1),I_e=[".wp-block-jetpack-contact-form",".jetpack-contact-form-container"],wa=".contact-form.commentsblock.jetpack-contact-form__form",n2t=new Set(["display","visibility","position","opacity","transform","float","clip","clip-path","z-index"]),i2t=[...I_e,...Pw([wa])],s2t=Pw([`${wa} [class*="grunion-field-"][class*="-wrap"]`,`${wa} .contact-form__inset-label-wrap`,`${wa} .contact-form__select-wrapper`]),o2t=Pw([`${wa} input.grunion-field:not([type=checkbox]):not([type=radio]):not([type=hidden])`,`${wa} textarea.grunion-field`,`${wa} .grunion-field-url-wrap input.grunion-field[type=text]`,`${wa} .contact-form__select-wrapper select`]),a2t=Pw([`${wa} .grunion-field-label`]),c2t=Pw([`${wa} .wp-block-jetpack-button .wp-block-button__link`,".wp-block-jetpack-button .wp-block-button__link",`${wa} .contact-submit button[type=submit]`,`${wa} button.pushbutton-wide`]),u2t=new Set([":active",":checked",":disabled",":enabled",":hover",":invalid",":optional",":placeholder-shown",":required",":valid",":visited"]);function w_e(e){if(e.formsConverted<=0||e.sourceCss.trim()==="")return{css:""};let t;try{t=Wd.parse(e.sourceCss)}catch{return{css:""}}let r=[];return t.walkRules(n=>{if(v2t(n))return;let i=p2t(n);if(i.length!==0)for(let s of i){let[o,a]=s.split(":"),c=l2t(n,o);if(c.length===0)continue;let u=I2t(o,a);r.push(x2t(u,c,S2t(n)))}}),{css:r.join(` +`)}}function Pw(e){return I_e.flatMap(t=>e.map(r=>`${t} ${r}`))}function l2t(e,t){let r=[];for(let n of e.nodes??[]){if(n.type!=="decl")continue;let i=n,s=i.prop.trim().toLowerCase(),o=i.value.trim();!s||!o||!d2t(s,t)||r.push({prop:s,value:o,important:i.important})}return r}function d2t(e,t){return n2t.has(e)?!1:!!(e==="color"||e==="height"||e==="line-height"||e==="letter-spacing"||e==="min-height"||e==="min-width"||e==="background"||e==="background-color"||e==="box-shadow"||e==="width"||e==="max-width"||e.startsWith("border")||e.startsWith("outline")||e.startsWith("padding")||e.startsWith("font")||(t==="form"||t==="field")&&f2t(e)||(t==="label"||t==="submit")&&(e==="display"||e.startsWith("margin"))||t==="submit"&&(e==="text-decoration"||e==="text-transform"))}function f2t(e){return e==="display"||e==="gap"||e==="row-gap"||e==="column-gap"||e==="align-items"||e==="justify-items"||e==="justify-content"||e==="flex-direction"||e==="flex-wrap"||e==="grid-template-columns"||e==="grid-template-rows"||e.startsWith("margin")}function p2t(e){let t=new Set;for(let r of e.selectors){let n=h2t(r);if(!n)continue;let i=n.focus?"focus":"base";for(let s of n.kinds)t.add(`${s}:${i}`)}return[...t]}function h2t(e){let t;try{t=(0,Mh.default)().astSync(e,{lossless:!1})}catch{return null}let r=new Set,n=!1,i=!1;for(let s of t.nodes){let o=A2t(s);o.unsupportedState&&(i=!0),o.focus&&(n=!0);let a=o.tags.includes("button")||o.hasTypeSubmit&&o.tags.includes("input"),c=o.tags.some(f=>f==="select"||f==="textarea")||o.tags.includes("input")&&!a,u=o.tags.includes("label")||o.classes.some(E2t),l=o.classes.some(b2t),d=o.tags.includes("form")||o.classes.some(S_e)||o.ids.some(y2t);(c||o.classes.some(m2t))&&r.add("control"),u&&r.add("label"),(a||o.classes.some(C2t))&&r.add("submit"),l&&!c&&!u&&!a&&r.add("field"),d&&r.size===0&&r.add("form")}return i||r.size===0?null:{kinds:r,focus:n}}function A2t(e){let t=[],r=[],n=[],i=!1,s=!1,o=!1;return e.walk(a=>{if(!g2t(a)){if(Mh.default.isTag(a)){t.push(a.value.toLowerCase());return}if(Mh.default.isClassName(a)){r.push(a.value.toLowerCase());return}if(a.type==="id"){let c=a.value;c&&n.push(c.toLowerCase());return}if(Mh.default.isAttribute(a)){let c=a.attribute.toLowerCase(),u=(a.value??"").toLowerCase();c==="type"&&a.operator==="="&&u==="submit"&&(i=!0);return}if(Mh.default.isPseudo(a)){let c=a.value.toLowerCase();if(c===":focus"||c===":focus-visible"){s=!0;return}u2t.has(c)&&(o=!0)}}}),{tags:t,classes:r,ids:n,hasTypeSubmit:i,focus:s,unsupportedState:o}}function g2t(e){let t=e.parent;for(;t;){if(Mh.default.isPseudo(t))return!0;t=t.parent}return!1}function m2t(e){return!!(["form-control","form-input","form-select","form-textarea"].includes(e)||/^(?:input|select|textarea)(?:[-_](?:field|control))?$/.test(e)||/^(?:field|control)[-_](?:input|select|textarea)$/.test(e)||/(?:^|[-_])form[-_](?:control|field|input|select|textarea)(?:$|[-_])/.test(e)||/(?:^|[-_])(?:input|select|textarea)(?:$|[-_])/.test(e)&&/(?:form|field|control|contact|email|message|name|phone)/.test(e)||/(?:^|[-_])(?:field|control)(?:$|[-_])/.test(e)&&/(?:form|contact|input|select|textarea)/.test(e))}function S_e(e){return e==="form"?!0:/(?:^|[-_])form(?:$|[-_])/.test(e)?!/(?:input|select|textarea|label|submit|button|btn|control|field|check|checkbox|radio)/.test(e):!1}function y2t(e){return S_e(e)}function b2t(e){return["field","form-field","form-group","form-row","form-check","input-group"].includes(e)?!0:/(?:^|[-_])(?:form|contact)[-_](?:field|group|row|check)(?:$|[-_])/.test(e)||/(?:^|[-_])(?:field|group|row|check)[-_](?:form|contact)(?:$|[-_])/.test(e)}function E2t(e){return e==="label"||e==="form-label"?!0:/(?:^|[-_])(?:form|field|contact)[-_]label(?:$|[-_])/.test(e)}function C2t(e){return e==="submit"||e==="form-submit"?!0:/(?:^|[-_])(?:form|contact)[-_]submit(?:$|[-_])/.test(e)||/(?:^|[-_])submit[-_](?:button|btn)(?:$|[-_])/.test(e)}function I2t(e,t){let r=e==="form"?i2t:e==="field"?s2t:e==="control"?o2t:e==="label"?a2t:c2t;return t==="focus"?r.map(w2t):r}function w2t(e){return`${e}:focus`}function S2t(e){let t=[],r=e.parent;for(;r;){if(r.type==="atrule"){let n=r;t.unshift({name:n.name,params:n.params})}r=r.parent}return t}function v2t(e){let t=e.parent;for(;t;){if(t.type==="atrule"&&/keyframes$/i.test(t.name))return!0;t=t.parent}return!1}function x2t(e,t,r){let n=`${e.join(",")}{${t.map(B2t).join(";")}}`;for(let i=r.length-1;i>=0;i-=1){let s=r[i];n=`@${s.name}${s.params?` ${s.params}`:""}{${n}}`}return n}function B2t(e){return`${e.prop}:${e.value}${e.important?"!important":""}`}function v_e(e){return w_e(e)}var Ph={themeRelativePath:"assets/css/jetpack-form-parity.css",outputFileName:"jetpack-form-parity.css",frontendHandleSuffix:"jetpack-form-parity",editorStylePath:"assets/css/jetpack-form-parity.css"};St();g2();pi();var x_e=24;function B_e(e){return e.replace(/\s+/g," ").trim()}function k2t(e){let t=e("body").children().first().get(0);return t||(e.root().children().first().get(0)??null)}function _2t(e,t,r){let n=r.tagName?.toLowerCase()??"",i=(t(r).attr("role")??"").trim().toLowerCase();return n==="header"||n==="nav"||n==="footer"||n==="aside"?n:i==="navigation"?"nav":i==="complementary"?"complementary":i?"region":e.role==="header"||e.role==="nav"||e.role==="footer"?e.role:"body"}function T2t(e){return e.role!=="body"}function Q2t(e){return T2t(e)||e.linkCount>=2||e.text.length>=x_e}function R2t(e){let t=le(e.html),r=k2t(t),n=r?.tagName?.toLowerCase()||"section",i=t(r||"body"),s=(i.attr("id")??"").trim()||null,o=(e.classes?.length?e.classes:(i.attr("class")??"").split(/\s+/)).filter(Boolean);return{selector:Fp({tag:n,id:s,classes:o,nthOfType:1}),role:r?_2t(e,t,r):e.role,sectionId:e.id,html:e.html,text:B_e(i.text()),linkCount:i.find("a[href]").length+(n==="a"&&i.attr("href")?1:0),classes:o}}function D2t(e){return Vu(e).map(R2t).filter(Q2t)}function N2t(e){let t=new Set;return e("[id]").each((r,n)=>{let i=e(n).attr("id");i&&t.add(i)}),t}function M2t(e,t){return e.includes(`"anchor":${JSON.stringify(t)}`)}function P2t(e,t,r,n){let i=N2t(r);if(i.has(e.sectionId)||M2t(t,e.sectionId))return!0;let s=/#([A-Za-z0-9_-]+)/.exec(e.selector)?.[1];return!!(s&&i.has(s)||e.role==="body"&&e.text.length>=x_e&&n.includes(e.text))}function k_e(e){let t=[e.postContent,...e.partMarkup??[]].filter(Boolean).join(` +`),r=le(t),n=B_e(r.text());return D2t(e.sourceHtml).filter(i=>!P2t(i,t,r,n)).map(i=>({selector:i.selector,role:i.role,pageSlug:e.pageSlug,reason:"actionable_region_unplaced"}))}g2();var L2t="dla-interactivity",F2t=` array( '@wordpress/interactivity' ), 'version' => '1.0.0' ); +`,Fw=` array( 'wp-blocks', 'wp-block-editor', 'wp-element' ), 'version' => '1.0.0' ); +`;function lD(e){return{type:"string",source:"html",selector:e}}function Ow(e){let t=`dla/${e}`,r=`wp-block-dla-${e}`;return`( function ( blocks, blockEditor, element ) { + var el = element.createElement; + var RawHTML = element.RawHTML; + var blockName = '${t}'; + var baseClass = '${r}'; + var tagName = '${e==="sticky"?"div":"section"}'; + + function joinClasses() { + return Array.prototype.slice.call( arguments ).filter( Boolean ).join( ' ' ); + } + + function safeJson( value ) { + return JSON.stringify( value ).replace( /--/g, '\\\\u002d\\\\u002d' ).replace( /'/g, '\\\\u0027' ); + } + + function content( attributes ) { + if ( ! attributes.content ) return null; + // pointer-events:none in EDIT only \u2014 save() never calls this wrapper. + return el( 'div', { style: { pointerEvents: 'none' } }, el( RawHTML, { children: attributes.content } ) ); + } + + function savedContent( attributes ) { + return attributes.content ? el( RawHTML, { children: attributes.content } ) : null; + } + + function numberOr( value, fallback ) { + // NOT ||: threshold 0 / offset 0 / durationMs 0 are legitimate source + // values \u2014 a || fallback would drift save() from the emitted markup and + // invalidate the block. + return typeof value === 'number' ? value : fallback; + } + + function wrapperProps( attributes ) { + var props = { + className: joinClasses( baseClass, attributes.className ), + }; + if ( attributes.anchor ) props.id = attributes.anchor; + if ( blockName === 'dla/reveal' ) { + props.style = { + '--dla-reveal-y': attributes.translateY || '18px', + '--dla-reveal-ms': numberOr( attributes.durationMs, 600 ) + 'ms', + }; + props[ 'data-wp-interactive' ] = 'dla/reveal'; + props[ 'data-wp-context' ] = safeJson( { + visible: false, + threshold: numberOr( attributes.threshold, 0.12 ), + } ); + props[ 'data-wp-init' ] = 'callbacks.init'; + props[ 'data-wp-class--is-visible' ] = 'context.visible'; + } else if ( blockName === 'dla/sticky' ) { + props.style = { display: 'none' }; + props[ 'data-wp-interactive' ] = 'dla/sticky'; + props[ 'data-wp-context' ] = safeJson( { + toggleClass: attributes.toggleClass || 'is-scrolled', + offset: numberOr( attributes.offset, 8 ), + } ); + props[ 'data-wp-init' ] = 'callbacks.init'; + } else if ( blockName === 'dla/tabs' ) { + props[ 'data-wp-interactive' ] = 'dla/tabs'; + props[ 'data-wp-context' ] = safeJson( { + activeClass: attributes.activeClass || 'is-active', + } ); + props[ 'data-wp-init' ] = 'callbacks.init'; + } else if ( blockName === 'dla/slider' ) { + var ctx = { activeClass: attributes.activeClass || 'is-current' }; + if ( attributes.intervalMs ) ctx.intervalMs = attributes.intervalMs; + props[ 'data-wp-interactive' ] = 'dla/slider'; + props[ 'data-wp-context' ] = safeJson( ctx ); + props[ 'data-wp-init' ] = 'callbacks.init'; + } else if ( blockName === 'dla/modal' ) { + props[ 'data-wp-interactive' ] = 'dla/modal'; + props[ 'data-wp-init' ] = 'callbacks.init'; + } + return props; + } + + var isReveal = blockName === 'dla/reveal'; + + blocks.registerBlockType( '${t}', { + edit: function ( props ) { + var attributes = props.attributes; + var blockProps = blockEditor.useBlockProps( wrapperProps( attributes ) ); + if ( isReveal ) { + return el( tagName, blockProps, el( blockEditor.InnerBlocks ) ); + } + return el( tagName, blockProps, content( attributes ) ); + }, + save: function ( props ) { + var attributes = props.attributes; + if ( isReveal ) { + return el( tagName, wrapperProps( attributes ), el( blockEditor.InnerBlocks.Content ) ); + } + return el( tagName, wrapperProps( attributes ), savedContent( attributes ) ); + }, + } ); +} )( window.wp.blocks, window.wp.blockEditor, window.wp.element ); +`}var O2t=JSON.stringify({$schema:"https://schemas.wp.org/trunk/block.json",apiVersion:3,name:"dla/reveal",title:"Reveal Section",category:"design",description:"Scroll-reveal section (IntersectionObserver via the Interactivity API).",supports:{interactivity:!0,html:!1},attributes:{anchor:{type:"string"},className:{type:"string"},threshold:{type:"number",default:.12},translateY:{type:"string",default:"18px"},durationMs:{type:"number",default:600}},editorScript:"file:./editor.js",viewScriptModule:"file:./view.js",style:"file:./style.css"},null," ")+` +`,U2t=`import { store, getContext, getElement } from '@wordpress/interactivity'; + +document.documentElement.classList.add( 'dla-reveal-js' ); + +store( 'dla/reveal', { + callbacks: { + init() { + const ctx = getContext(); + const { ref } = getElement(); + if ( window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches ) { + ctx.visible = true; + return; + } + const obs = new IntersectionObserver( + ( entries ) => { + entries.forEach( ( e ) => { + if ( e.isIntersecting ) { + ctx.visible = true; + obs.unobserve( e.target ); + } + } ); + }, + { threshold: ctx.threshold ?? 0.12 } + ); + obs.observe( ref ); + }, + }, +} ); +`,$2t=`.dla-reveal-js .wp-block-dla-reveal:not(.is-visible) { + opacity: 0; + transform: translateY( var( --dla-reveal-y, 18px ) ); +} +.dla-reveal-js .wp-block-dla-reveal.is-visible { + transition: opacity var( --dla-reveal-ms, 600ms ) ease, transform var( --dla-reveal-ms, 600ms ) ease; +} +@media (prefers-reduced-motion: reduce) { + .dla-reveal-js .wp-block-dla-reveal:not(.is-visible) { + opacity: 1; + transform: none; + } + .dla-reveal-js .wp-block-dla-reveal.is-visible { + transition: none; + } +} +`,H2t=JSON.stringify({$schema:"https://schemas.wp.org/trunk/block.json",apiVersion:3,name:"dla/sticky",title:"Sticky Header State",category:"design",description:"Scroll-reactive header state (toggles the source-authored class past an offset).",supports:{interactivity:!0,html:!1},attributes:{className:{type:"string"},toggleClass:{type:"string",default:"is-scrolled"},offset:{type:"number",default:8},content:lD(".wp-block-dla-sticky")},editorScript:"file:./editor.js",viewScriptModule:"file:./view.js"},null," ")+` +`,j2t=`import { store, getContext, getElement } from '@wordpress/interactivity'; + +store( 'dla/sticky', { + callbacks: { + init() { + const ctx = getContext(); + const { ref } = getElement(); + const target = ref.closest( 'header' ) ?? ref; + const toggleClass = ctx.toggleClass ?? 'is-scrolled'; + const offset = ctx.offset ?? 8; + const apply = () => target.classList.toggle( toggleClass, window.scrollY > offset ); + apply(); + window.addEventListener( 'scroll', apply, { passive: true } ); + }, + }, +} ); +`,q2t=JSON.stringify({$schema:"https://schemas.wp.org/trunk/block.json",apiVersion:3,name:"dla/tabs",title:"Tabs Section",category:"design",description:"Tabbed section (verbatim source markup; toggles the source-authored active class).",supports:{interactivity:!0,html:!1},attributes:{anchor:{type:"string"},className:{type:"string"},activeClass:{type:"string",default:"is-active"},content:lD(".wp-block-dla-tabs")},editorScript:"file:./editor.js",viewScriptModule:"file:./view.js"},null," ")+` +`,z2t=`import { store, getContext, getElement } from '@wordpress/interactivity'; + +store( 'dla/tabs', { + callbacks: { + init() { + const ctx = getContext(); + const { ref } = getElement(); + const activeClass = ctx.activeClass ?? 'is-active'; + const tabs = Array.from( ref.querySelectorAll( '[role="tab"]' ) ); + const panels = Array.from( ref.querySelectorAll( '[role="tabpanel"]' ) ); + const panelFor = ( tab, i ) => { + const id = tab.getAttribute( 'aria-controls' ); + return ( id && ref.querySelector( '#' + CSS.escape( id ) ) ) || panels[ i ] || null; + }; + const select = ( idx ) => { + tabs.forEach( ( t, i ) => { + const on = i === idx; + t.classList.toggle( activeClass, on ); + t.setAttribute( 'aria-selected', on ? 'true' : 'false' ); + t.tabIndex = on ? 0 : -1; + const p = panelFor( t, i ); + if ( p ) p.hidden = ! on; + } ); + }; + tabs.forEach( ( t, i ) => { + t.addEventListener( 'click', () => select( i ) ); + t.addEventListener( 'keydown', ( e ) => { + if ( e.key !== 'ArrowRight' && e.key !== 'ArrowLeft' ) return; + const next = ( i + ( e.key === 'ArrowRight' ? 1 : tabs.length - 1 ) ) % tabs.length; + select( next ); + tabs[ next ].focus(); + } ); + } ); + // Source markup is the initial state; normalize roving tabindex from it. + const initial = tabs.findIndex( ( t ) => t.getAttribute( 'aria-selected' ) === 'true' ); + select( initial >= 0 ? initial : 0 ); + }, + }, +} ); +`,V2t=JSON.stringify({$schema:"https://schemas.wp.org/trunk/block.json",apiVersion:3,name:"dla/slider",title:"Slider Section",category:"design",description:"Carousel section (verbatim source markup; moves the source-authored active class).",supports:{interactivity:!0,html:!1},attributes:{anchor:{type:"string"},className:{type:"string"},activeClass:{type:"string",default:"is-current"},intervalMs:{type:"number"},content:lD(".wp-block-dla-slider")},editorScript:"file:./editor.js",viewScriptModule:"file:./view.js"},null," ")+` +`,G2t=`import { store, getContext, getElement } from '@wordpress/interactivity'; + +store( 'dla/slider', { + callbacks: { + init() { + const ctx = getContext(); + const { ref } = getElement(); + const activeClass = ctx.activeClass ?? 'is-current'; + const current = ref.querySelector( '.' + CSS.escape( activeClass ) ); + const list = current ? Array.from( current.parentElement.children ) : []; + if ( list.length < 2 ) return; + let idx = list.indexOf( current ); + const go = ( n ) => { + list[ idx ].classList.remove( activeClass ); + idx = ( n + list.length ) % list.length; + list[ idx ].classList.add( activeClass ); + }; + ref.querySelector( '.next, [data-next]' )?.addEventListener( 'click', () => go( idx + 1 ) ); + ref.querySelector( '.prev, [data-prev]' )?.addEventListener( 'click', () => go( idx - 1 ) ); + // Keyboard: arrows operate the slider whenever focus is inside it (the + // prev/next buttons are already focusable; no tabindex injection \u2014 the + // verbatim inner markup must stay untouched). + ref.addEventListener( 'keydown', ( e ) => { + if ( e.key === 'ArrowRight' ) go( idx + 1 ); + else if ( e.key === 'ArrowLeft' ) go( idx - 1 ); + } ); + const reduced = window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches; + if ( ctx.intervalMs && ! reduced ) { + let timer = setInterval( () => go( idx + 1 ), ctx.intervalMs ); + ref.addEventListener( 'pointerenter', () => clearInterval( timer ) ); + ref.addEventListener( 'pointerleave', () => { timer = setInterval( () => go( idx + 1 ), ctx.intervalMs ); } ); + } + }, + }, +} ); +`,W2t=JSON.stringify({$schema:"https://schemas.wp.org/trunk/block.json",apiVersion:3,name:"dla/modal",title:"Modal Section",category:"design",description:"Section with a native dialog modal (verbatim source markup; showModal/close wiring).",supports:{interactivity:!0,html:!1},attributes:{anchor:{type:"string"},className:{type:"string"},content:lD(".wp-block-dla-modal")},editorScript:"file:./editor.js",viewScriptModule:"file:./view.js"},null," ")+` +`,Y2t=`import { store, getElement, withSyncEvent } from '@wordpress/interactivity'; + +store( 'dla/modal', { + callbacks: { + init() { + const { ref } = getElement(); + const dialog = ref.querySelector( 'dialog' ); + if ( ! dialog ) return; + // Trigger: first button OUTSIDE the dialog within the section. + const trigger = Array.from( ref.querySelectorAll( 'button' ) ).find( ( b ) => ! dialog.contains( b ) ); + trigger?.addEventListener( 'click', () => dialog.showModal() ); + // Close: any [data-close]/.close button inside; backdrop click closes. + dialog.querySelectorAll( '[data-close], .close' ).forEach( ( b ) => + b.addEventListener( 'click', () => dialog.close() ) + ); + dialog.addEventListener( 'click', withSyncEvent( ( e ) => { + if ( e.target === dialog ) dialog.close(); // backdrop \u2014 Esc is native + } ) ); + }, + }, +} ); +`;function __e(){return{slug:L2t,files:[{relativePath:"plugin.php",content:F2t},{relativePath:"blocks/reveal/block.json",content:O2t},{relativePath:"blocks/reveal/editor.js",content:Ow("reveal")},{relativePath:"blocks/reveal/editor.asset.php",content:Fw},{relativePath:"blocks/reveal/view.js",content:U2t},{relativePath:"blocks/reveal/view.asset.php",content:Lw},{relativePath:"blocks/reveal/style.css",content:$2t},{relativePath:"blocks/sticky/block.json",content:H2t},{relativePath:"blocks/sticky/editor.js",content:Ow("sticky")},{relativePath:"blocks/sticky/editor.asset.php",content:Fw},{relativePath:"blocks/sticky/view.js",content:j2t},{relativePath:"blocks/sticky/view.asset.php",content:Lw},{relativePath:"blocks/tabs/block.json",content:q2t},{relativePath:"blocks/tabs/editor.js",content:Ow("tabs")},{relativePath:"blocks/tabs/editor.asset.php",content:Fw},{relativePath:"blocks/tabs/view.js",content:z2t},{relativePath:"blocks/tabs/view.asset.php",content:Lw},{relativePath:"blocks/slider/block.json",content:V2t},{relativePath:"blocks/slider/editor.js",content:Ow("slider")},{relativePath:"blocks/slider/editor.asset.php",content:Fw},{relativePath:"blocks/slider/view.js",content:G2t},{relativePath:"blocks/slider/view.asset.php",content:Lw},{relativePath:"blocks/modal/block.json",content:W2t},{relativePath:"blocks/modal/editor.js",content:Ow("modal")},{relativePath:"blocks/modal/editor.asset.php",content:Fw},{relativePath:"blocks/modal/view.js",content:Y2t},{relativePath:"blocks/modal/view.asset.php",content:Lw}]}}rc();pi();import{normalize as eQt}from"node:path";var J2t={color:{surface:{base:{value:"#ffffff"}},text:{default:{value:"#111111"}},accent:{primary:{value:"#0066cc"}}},typography:{families:{body:{value:"system-ui, sans-serif"}}}};function T_e(e,t,r){let n=e?``:"",i=t?.partSlug?` + +`:"",s=r?{tagName:"main",className:r}:{tagName:"main"},o=["wp-block-group",r].filter(Boolean).join(" "),a=` +
+${n} +
+ + +`,c=` + +`,u=` +`,l=t?.layoutWrapperTag?.trim();if(t&&i&&l){let d=(t.layoutWrapperClasses??[]).filter(Boolean).join(" ").trim(),f=d?{tagName:l,className:d}:{tagName:l},p=["wp-block-group",d].filter(Boolean).join(" "),h=t.layoutWrapperRailPosition==="afterMain"?a+i:i+a,A=kt(p);return c+` +<${l} class="${A}"> +`+h+` + + +`+u}return c+i+a+` +`}function Z2t(e,t,r,n=!1){let i=t?` +// Source reveal scripts gate on html.js (no-JS visitors keep content visible). +add_action( 'wp_head', function () { + echo ""; +}, 0 ); +`:"",s=r&&Object.keys(r).length>0?` +// JS-rendered source: replay body data-* attributes per pathname. +add_action( 'wp_body_open', function () { + echo ''; +} ); +`:"",o=Ph.themeRelativePath,a=`${e}-${Ph.frontendHandleSuffix}`,c=n?` + $jetpack_form = get_theme_file_path( '${o}' ); + $jetpack_form_mtime = @filemtime( $jetpack_form ); + if ( false !== $jetpack_form_mtime ) { + if ( false !== $inst_mtime ) { + $jetpack_deps = array( '${e}-instance' ); + } elseif ( false !== $css_mtime ) { + $jetpack_deps = array( '${e}-source' ); + } else { + $jetpack_deps = array( '${e}-style' ); + } + wp_enqueue_style( '${a}', get_theme_file_uri( '${o}' ), $jetpack_deps, (string) $jetpack_form_mtime ); + } +`:"",u=n?` if ( false !== $jetpack_form_mtime ) { + $deps = array( '${a}' ); + } elseif ( false !== $inst_mtime ) { + $deps = array( '${e}-instance' ); + } elseif ( false !== $css_mtime ) { + $deps = array( '${e}-source' ); + } else { + $deps = array( '${e}-style' ); + }`:` if ( false !== $inst_mtime ) { + $deps = array( '${e}-instance' ); + } elseif ( false !== $css_mtime ) { + $deps = array( '${e}-source' ); + } else { + $deps = array( '${e}-style' ); + }`,l=["assets/css/source.css","assets/css/instance-styles.css",...n?[Ph.editorStylePath]:[],"assets/css/parity-patch.css","assets/css/editor-reveal-reset.css"];return` +// Stage 1d carry: the source site's own CSS/JS, adapted for the block DOM. +// Enqueued at priority 20 so it lands AFTER global styles + theme style. +// Guards are @filemtime (not file_exists): PHP's realpath cache keeps +// file_exists() TRUE for up to 120s after a deletion while the stat fails, +// and the bare filemtime() printed a warning INTO the served page. One +// suppressed stat is the truthful existence check AND the enqueue version. +// +// Cascade order is load-bearing: theme style \u2192 source.css \u2192 instance-styles.css +// (per-instance lib-i rules override class defaults; equal specificity, later +${n?`// wins) \u2192 jetpack-form-parity.css (form-specific carried CSS bridge) \u2192 +// parity-patch.css (final deterministic fixes).`:"// wins) \u2192 parity-patch.css (final deterministic fixes)."} +add_action( 'wp_enqueue_scripts', function () { + $css = get_theme_file_path( 'assets/css/source.css' ); + $css_mtime = @filemtime( $css ); + if ( false !== $css_mtime ) { + wp_enqueue_style( '${e}-source', get_theme_file_uri( 'assets/css/source.css' ), array( '${e}-style' ), (string) $css_mtime ); + } + $js = get_theme_file_path( 'assets/js/source.js' ); + $js_mtime = @filemtime( $js ); + if ( false !== $js_mtime ) { + wp_enqueue_script( '${e}-source', get_theme_file_uri( 'assets/js/source.js' ), array(), (string) $js_mtime, true ); + } + $inst = get_theme_file_path( 'assets/css/instance-styles.css' ); + $inst_mtime = @filemtime( $inst ); + if ( false !== $inst_mtime ) { + $inst_deps = false !== $css_mtime ? array( '${e}-source' ) : array( '${e}-style' ); + wp_enqueue_style( '${e}-instance', get_theme_file_uri( 'assets/css/instance-styles.css' ), $inst_deps, (string) $inst_mtime ); + } +${c} + $patch = get_theme_file_path( 'assets/css/parity-patch.css' ); + $patch_mtime = @filemtime( $patch ); + if ( false !== $patch_mtime ) { +${u} + wp_enqueue_style( '${e}-parity-patch', get_theme_file_uri( 'assets/css/parity-patch.css' ), $deps, (string) $patch_mtime ); + } +}, 20 ); +// Editor parity: load the SAME carried frontend CSS into the block-editor +// canvas iframe so blocks render styled in the editor (matching the frontend), +// not as unstyled defaults. add_editor_style takes theme-relative paths in +// cascade order; file_exists guards keep it safe when an asset is absent. +add_action( 'after_setup_theme', function () { + add_theme_support( 'editor-styles' ); + foreach ( array( ${l.map(f=>`'${f}'`).join(", ")} ) as $rel ) { + if ( file_exists( get_theme_file_path( $rel ) ) ) { + add_editor_style( $rel ); + } + } +} ); +${i}${s}`}var K2t=`/* editor-reveal-reset.css \u2014 add_editor_style ONLY; never a front-end style. */ +.reveal, +[class*="reveal"], +[class*="fade-in"], +[class*="fadein"], +[class*="animate"], +[class*="aos-"], +[data-aos] { + opacity: 1 !important; + transform: none !important; + visibility: visible !important; + animation: none !important; + transition: none !important; +} +`;function I7(e){let n=LQ({foundation:e.foundation??J2t,themeSlug:e.themeSlug,siteTitle:e.siteTitle,capturedFonts:e.capturedFonts}).map(a=>a.relativePath==="parts/header.html"?{...a,content:e.headerPart}:a.relativePath==="parts/footer.html"?{...a,content:e.footerPart}:a).map(a=>{if(a.relativePath!=="theme.json")return a;let c=JSON.parse(a.content),u=[...c.customTemplates??[],{name:"page-local",title:"Local Page (no title)",postTypes:["page"]},...(e.interiorChromeTemplates??[]).map(l=>({name:l.templateName,title:l.templateTitle,postTypes:["page"]}))];return{...a,content:JSON.stringify({...c,customTemplates:u},null,2)+` +`}}),i=T_e(e.mainClass,void 0,e.mainWrapperClass);n.push({relativePath:"templates/page-local.html",content:i});for(let a of e.interiorChromeTemplates??[])n.push({relativePath:`parts/${a.partSlug}.html`,content:a.partMarkup}),n.push({relativePath:`templates/${a.templateName}.html`,content:T_e(e.mainClass,a,e.mainWrapperClass)});n.push({relativePath:"templates/front-page.html",content:i});let s=(e.jetpackFormParityCss??"").trim(),o=s.length>0;if(e.carrySourceAssets||o){let{css:a,js:c}=e.carrySourceAssets??{css:"",js:""},u=a.trim().length>0,l=c.trim().length>0;if(u){let p=n.findIndex(h=>h.relativePath==="theme.json");if(p>=0){let h=JSON.parse(n[p].content);delete h.styles,h.settings={...h.settings??{},spacing:{...h.settings?.spacing??{},blockGap:null}},n[p]={...n[p],content:JSON.stringify(h,null,2)+` +`}}}u&&(n.push({relativePath:"assets/css/source.css",content:a}),n.push({relativePath:"assets/css/editor-reveal-reset.css",content:K2t})),l&&n.push({relativePath:"assets/js/source.js",content:c}),o&&n.push({relativePath:Ph.themeRelativePath,content:s+` +`});let d=(e.instanceStylesCss??"").trim();u&&d.length>0&&n.push({relativePath:"assets/css/instance-styles.css",content:d+` +`});let f=n.findIndex(p=>p.relativePath==="functions.php");f>=0&&(n[f]={...n[f],content:n[f].content+Z2t(e.themeSlug,l,e.carrySourceAssets?e.bodyDataByPath:void 0,o)})}return n}function Q_e(e,t={}){let r=e.html;return t.pageSlugs?.length&&(r=nD(r,t.pageSlugs)),r.trim()}function R_e(e){let t=/^#?([0-9a-f]{6})$/i.exec(e.trim());if(!t)return null;let r=parseInt(t[1],16),n=(r>>16&255)/255,i=(r>>8&255)/255,s=(r&255)/255,o=Math.max(n,i,s),a=Math.min(n,i,s),c=(o+a)/2,u=o-a,l=u===0?0:u/(1-Math.abs(2*c-1)),d=0;return u!==0&&(o===n?d=(i-s)/u%6:o===i?d=(s-n)/u+2:d=(n-i)/u+4,d*=60,d<0&&(d+=360)),{h:d,s:l,l:c}}var X2t=.5;function D_e(e){let t=new Map,r=/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi;for(let n of e)for(let i of n.matchAll(r)){let s=i[1].toLowerCase(),o=s.length===3?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}`:`#${s}`;t.set(o,(t.get(o)??0)+1)}return[...t.entries()].map(([n,i])=>({hex:n,count:i})).sort((n,i)=>i.count-n.count)}function N_e(e,t){let{palette:r,typography:n,breakpoints:i}=e,s=Math.max(1,Math.ceil((r.sampledUrls||1)*X2t)),o=r.colors.map(_=>({..._,hsl:R_e(_.hex)})).filter(_=>_.urls>=s&&_.hsl!==null),a=[...o].sort((_,v)=>_.hsl.l-v.hsl.l),c=a[0]?.hex??"#111111",u=a[a.length-1]?.hex??"#ffffff",d=([...o].sort((_,v)=>v.count-_.count)[0]?.hsl.l??.5)<.4,f=d?c:u,p=d?u:c,h=_=>_.hsl.s>=.35&&_.hsl.l>=.25&&_.hsl.l<=.7&&_.hex.toLowerCase()!==c.toLowerCase()&&_.hex.toLowerCase()!==u.toLowerCase(),A=(t?.cssColors??[]).map(_=>({hex:_.hex,count:_.count,hsl:R_e(_.hex)})).filter(_=>_.hsl!==null),g=[...o.filter(h).sort((_,v)=>v.count-_.count),...A.filter(h).sort((_,v)=>v.count-_.count)][0]?.hex??p,m=_=>n.bySelector[_]?.slice().sort((v,N)=>N.urls-v.urls)[0]?.fontFamily,b=m("body")??"system-ui, sans-serif",E=m("h1")??m("h2")??b,C=[...new Set([...i.minWidth,...i.maxWidth])].sort((_,v)=>_-v),I=(_,v)=>`${C.filter(N=>N<=_).pop()??v}px`,T=I(768,768),k=I(1024,1024),D=`${C.filter(_=>_>1024).pop()??1280}px`;return{foundation:{color:{surface:{base:{value:f},inverse:{value:p}},text:{default:{value:p},inverse:{value:f}},accent:{primary:{value:g}}},typography:{families:{body:{value:b},display:{value:E}}},breakpoints:{md:T,lg:k,xl:D},components:{button:{background:g,text:f,radius:"999px"}}},footerBgToken:"surface-inverse",footerTextToken:"text-inverse"}}function L_e(e){let t=e.cssColors??(e.cssSources?D_e(e.cssSources):void 0),n=N_e({palette:e.palette??cQt(),typography:e.typography??uQt(),breakpoints:e.breakpoints??lQt()},t?{cssColors:t}:void 0).foundation,s={palette:[Uw("Surface Base",n.color?.surface?.base),Uw("Surface Inverse",n.color?.surface?.inverse),Uw("Text Default",n.color?.text?.default),Uw("Text Inverse",n.color?.text?.inverse),Uw("Accent Primary",n.color?.accent?.primary)].filter(o=>o!==null),typography:{...$w("body",n.typography?.families?.body?.value),...$w("display",n.typography?.families?.display?.value)},breakpoints:{...$w("md",n.breakpoints?.md),...$w("lg",n.breakpoints?.lg),...$w("xl",n.breakpoints?.xl)}};return{tokens:s,foundationAggregates:{palette:s.palette,typography:s.typography,breakpoints:s.breakpoints}}}function F_e(e){let t=I7({siteTitle:e.siteTitle,themeSlug:e.themeSlug,headerPart:"",footerPart:"",carrySourceAssets:e.carrySourceAssets,instanceStylesCss:e.instanceStylesCss,jetpackFormParityCss:e.jetpackFormParityCss,bodyDataByPath:e.bodyDataByPath}).find(r=>r.relativePath==="functions.php");if(!t)throw new Error("DLA theme assembly did not emit functions.php");return t.content}function O_e(e,t){let r=e.pages.map(i=>i.slug),n=new Map;for(let i of e.pages){if(i.slug===t)continue;let s=Vu(i.html).filter(u=>u.chromeSource==="layout-rail");if(s.length===0)continue;let o=i.slug.replace(/[^a-z0-9_-]+/gi,"-").replace(/^-+|-+$/g,"")||"page",a=s.map(u=>Q_e(u,{pageSlugs:r})).join(` +`),c=s.find(u=>u.layoutWrapperTag&&u.layoutWrapperRailPosition);n.set(i.slug,{templateName:`page-local-${o}-chrome`,templateTitle:`Local Page Chrome (${i.title||i.slug})`,partSlug:`interior-chrome-${o}`,partMarkup:a,...c?{layoutWrapperTag:c.layoutWrapperTag,layoutWrapperClasses:c.layoutWrapperClasses??[],layoutWrapperRailPosition:c.layoutWrapperRailPosition}:{}})}return n}function U_e(e){return Vu(e)}async function $_e(e,t){let r=q_e(t),n={...e.templates},i={...e.parts},s=e.themeJson;for(let o of r){if(o.relativePath==="theme.json"){let a=JSON.parse(o.content);s=iQt(s,a,t);continue}if(o.relativePath.startsWith("templates/")){let a=o.relativePath.slice(10);(a==="front-page.html"||a==="page-local.html"||/^page-local-.+-chrome\.html$/.test(a))&&(n[a]=o.content);continue}o.relativePath.startsWith("parts/interior-chrome-")&&(i[o.relativePath.slice(6)]=o.content)}return tQt({...e,themeJson:s,templates:n,parts:i},t)}function H_e(e){return q_e(e).filter(t=>t.relativePath.startsWith("assets/"))}function j_e(e,t){let r=aQt([{relativePath:"style.css",content:e.model.styleCss},{relativePath:"theme.json",content:JSON.stringify(e.model.themeJson,null,2)+` +`},...w7("templates",e.model.templates),...w7("parts",e.model.parts),...w7("patterns",e.model.patterns),...t.extraThemeFiles??[],{relativePath:"functions.php",content:t.functionsPhp}]),n=e.written.map(Hw),i=[...new Set(n.filter(s=>s.startsWith("assets/")))].sort();return{themeFiles:r,assetSourceDir:e.outDir,assetFiles:i,writtenThemeFiles:r.map(s=>s.relativePath)}}function q_e(e){return I7({siteTitle:e.siteTitle,themeSlug:e.themeSlug,headerPart:"",footerPart:"",mainClass:e.mainClass,mainWrapperClass:e.mainWrapperClass,interiorChromeTemplates:e.interiorChromeTemplates??[],carrySourceAssets:e.carrySourceAssets,instanceStylesCss:e.instanceStylesCss,jetpackFormParityCss:e.jetpackFormParityCss})}async function tQt(e,t){if(!t.site)return e;let r=t.site.pages.find(l=>l.slug==="home")??t.site.pages[0];if(!r)return e;let n=t.site.pages.map(l=>l.slug),i=Vu(r.html),s={...e.parts},o=(t.carrySourceAssets?.css??"").trim().length>0,a=t.allowSourceChromeMounts?ZH(r.html):{},c=i.find(l=>l.role==="header")??i.find(l=>l.role==="nav");c?s["header.html"]=await YH(o?rQt(c,i):c,{pageSlugs:n,convertPart:M_e,...t.sticky?{sticky:t.sticky}:{}}):a.header?s["header.html"]=eQ(a.header,t.sticky):s["header.html"]=WH(t.siteTitle,[],n,{plain:o,...t.sticky?{sticky:t.sticky}:{}});let u=i.find(l=>l.role==="footer")??null;return s["footer.html"]=a.footer?eQ(a.footer):await JH(u,t.siteTitle,{pageSlugs:n,convertPart:M_e}),{...e,parts:s}}function M_e(e){return e}function rQt(e,t){let r=t.filter(i=>i.chromeSource==="layout-rail"&&i!==e);if(r.length===0)return e;let n=e.html.replace(/^]*>)/i,"\s*$/i,"");return{...e,html:`
${[n,...r.map(i=>i.html)].join(` +`)}
`,classes:["dla-carried-header-chrome"]}}function Uw(e,t){let r=t?.value?.trim();return r?{name:e,color:r}:null}function $w(e,t){let r=t?.trim();return r?{[e]:r}:{}}function w7(e,t){return Object.entries(t).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>({relativePath:nQt(e,r),content:n}))}function nQt(e,t){let r=t.trim();if(r.startsWith(`${e}/`)||r.includes("/"))return Hw(r);let n=/\.[a-z0-9]+$/i.test(r)?r:`${r}.html`;return Hw(`${e}/${n}`)}function Hw(e){let t=e.replace(/\\/g,"/"),r=eQt(t).replace(/\\/g,"/");if(!r||r==="."||r===".."||r.startsWith("../")||t.startsWith("/"))throw new Error(`theme path must stay relative: ${e}`);return r}function iQt(e,t,r){let n={...e};return(r.carrySourceAssets?.css??"").trim().length>0&&(delete n.styles,n.settings=oQt(n.settings,t.settings)),sQt(n,t.customTemplates)}function sQt(e,t){if(!Array.isArray(t))return e;let r=Array.isArray(e.customTemplates)?e.customTemplates:[],n=new Set(t.map(s=>P_e(s)).filter(s=>!!s)),i=r.filter(s=>{let o=P_e(s);return!o||!n.has(o)});return{...e,customTemplates:[...i,...t]}}function P_e(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e.name;return typeof t=="string"&&t.trim()?t:void 0}function oQt(e,t){let r=dD(e),n=dD(t),i=dD(r.spacing),s=dD(n.spacing);return{...r,spacing:{...i,...s}}}function dD(e){return e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{}}function aQt(e){let t=new Map;for(let r of e)t.set(Hw(r.relativePath),{...r,relativePath:Hw(r.relativePath)});return[...t.values()]}function cQt(){return{version:1,sampledUrls:0,colors:[]}}function uQt(){return{version:1,sampledUrls:0,bySelector:{}}}function lQt(){return{version:1,sampledUrls:0,minWidth:[],maxWidth:[]}}var z_e="failOnConservationRailDrop",fD=["nav","complementary"];var V_e=["display","position","marginTop","marginBottom","marginLeft","marginRight","paddingTop","paddingBottom","paddingLeft","paddingRight","maxWidth","fontSize","fontFamily","fontWeight","lineHeight","letterSpacing","textTransform","color","backgroundColor","gap","justifyContent","flexWrap","borderBottomWidth"];function dQt(e,t,r,n){let i=new Map(t.map(a=>[a.match,a])),s=[],o=n!==void 0?{page:n}:{};for(let a of e){let c=i.get(a.match);if(!c){s.push({match:a.match,viewport:r,kind:"missing",prop:"element",source:"present",replica:"absent",replicaOnlyClasses:[],...o});continue}for(let u of V_e){let l=a.props[u],d=c.props[u];l!==void 0&&d!==void 0&&l!==d&&s.push({match:a.match,viewport:r,kind:"prop",prop:u,source:l,replica:d,replicaOnlyClasses:c.replicaOnlyClasses,...o})}for(let u of["top","left","width","height"])Math.abs(a.rect[u]-c.rect[u])>2&&s.push({match:a.match,viewport:r,kind:"rect",prop:u,source:String(a.rect[u]),replica:String(c.rect[u]),replicaOnlyClasses:c.replicaOnlyClasses,...o})}return s}var S7="*,*::before,*::after{transition:none!important;animation:none!important}html.js section{opacity:1!important;transform:none!important}.dla-reveal-js .wp-block-dla-reveal{opacity:1!important;transform:none!important}html{scroll-behavior:auto!important}",v7=`(() => { + const top = window.setInterval(() => {}, 9999); + for (let i = top; i >= 0; i--) window.clearInterval(i); +})()`,fQt=` + if (typeof globalThis.__name === 'undefined') { + globalThis.__name = function (fn) { return fn; }; + } +`,pQt=`(args) => { + const { regions, battery } = args; + const intersects = (r) => regions.some((g) => r.top <= g.bottom && r.bottom >= g.top); + const counters = new Map(); + const out = []; + for (const el of Array.from(document.querySelectorAll('[id], [class]'))) { + const rect = el.getBoundingClientRect(); + const abs = { top: rect.top + window.scrollY, bottom: rect.bottom + window.scrollY }; + if (rect.width === 0 && rect.height === 0) continue; + const tag = el.tagName.toLowerCase(); + if (tag === 'html' || tag === 'body') continue; + const id = el.getAttribute('id'); + // Identity classes: source-authored only \u2014 wp-*, is-*, has-* are WP-added. + const all = (el.getAttribute('class') || '').split(/\\s+/).filter(Boolean); + const own = all.filter((c) => !/^(wp-|is-|has-|alignfull|alignwide)/.test(c)); + if (!id && own.length === 0) continue; + const base = id ? '#' + id : tag + '.' + own.join('.'); + const n = counters.get(base) || 0; + counters.set(base, n + 1); + // Count EVERY qualifying element in document order, EMIT only the + // intersecting ones \u2014 counting global keeps occurrence indices stable + // across asymmetric region shapes on both sides. + if (!intersects(abs)) continue; + const cs = getComputedStyle(el); + const props = {}; + for (const p of battery) props[p] = cs[p]; + out.push({ + match: base + '[' + n + ']', + rect: { top: Math.round(abs.top), left: Math.round(rect.left), width: Math.round(rect.width), height: Math.round(rect.height) }, + props, + replicaOnlyClasses: all.filter((c) => /^(wp-|is-|has-)/.test(c) || c === 'alignfull' || c === 'alignwide'), + }); + } + return out; +}`;async function hQt(e,t){return await e.evaluate(`(${pQt})(${JSON.stringify({regions:t,battery:V_e})})`)}var AQt={desktop:{width:1440,height:900,mobile:!1},mobile:{width:390,height:844,mobile:!0}},gQt="Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1";async function G_e(e){let t=AQt[e.viewport],r=await e.browser.newContext({viewport:{width:t.width,height:t.height},...t.mobile?{isMobile:!0,hasTouch:!0,userAgent:gQt}:{}});await r.addInitScript(fQt);try{let n=await r.newPage(),i=async c=>(await n.goto(c,{waitUntil:"networkidle"}),await n.evaluate("document.fonts.ready"),await n.addStyleTag({content:S7}),await n.evaluate(v7),hQt(n,e.regions)),s=await i(e.sourceUrl),o=await i(e.replicaUrl),a=e.page;if(a===void 0)try{a=new URL(e.sourceUrl).pathname}catch{a=e.sourceUrl}return dQt(s,o,e.viewport,a)}finally{await r.close()}}var W_e=Tr(OI(),1);function mQt(e,t){return e[t]>200&&e[t+1]<100&&e[t+2]<100&&e[t+3]>0}function Y_e(e,t){let{scale:r}=t,n=t.gapTolerance??8,i=t.minPixels??6,s=W_e.PNG.sync.read(e),o=[];for(let l=0;l0&&o.push({y:l,x0:d,x1:f,count:p})}let a=[],c=null,u=()=>{c&&c.pixels>=i&&a.push({top:Math.round(c.top/r),bottom:Math.round(c.bottom/r),left:Math.round(c.left/r),right:Math.round(c.right/r),pixels:c.pixels}),c=null};for(let l of o)c&&l.y-c.bottom<=n?(c.bottom=l.y,c.left=Math.min(c.left,l.x0),c.right=Math.max(c.right,l.x1),c.pixels+=l.count):(u(),c={top:l.y,bottom:l.y,left:l.x0,right:l.x1,pixels:l.count});return u(),a}import{createHash as yQt}from"node:crypto";var bQt=new Set(["display","marginTop","marginBottom","marginLeft","marginRight","paddingTop","paddingBottom","paddingLeft","paddingRight","maxWidth","fontSize","fontWeight","lineHeight","letterSpacing","textTransform","color","backgroundColor","gap","justifyContent","flexWrap","borderBottomWidth"]),EQt={fontFamily:"font-authority"},CQt=e=>e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`);function IQt(e){let t=/^(.*)\[(\d+)\]$/.exec(e);return t?{selector:t[1],occurrence:Number(t[2])}:{selector:e,occurrence:0}}var wQt=/[:\[\]{}()"'\\]/;function SQt(e){return!(wQt.test(e)||e.startsWith("#")&&e.slice(1).includes("."))}function J_e(e){let t=new Map,r=[],n=[];for(let a of e){if(a.kind!=="prop"){r.push({...a,cause:"structural"});continue}let c=EQt[a.prop];if(c){r.push({...a,cause:c});continue}let{selector:u,occurrence:l}=IQt(a.match);if(!SQt(u)){r.push({...a,cause:"unsafe-selector"});continue}if(!bQt.has(a.prop)){r.push({...a,cause:"unpatchable-prop"});continue}if(l!==0){r.push({...a,cause:"occurrence-ambiguous"});continue}n.push({div:a,selector:u,occurrence:l})}let i=new Map;for(let a of n){let c=`${a.selector}|${a.occurrence}|${a.div.prop}|${a.div.viewport}`,u=i.get(c);u||(u=new Set,i.set(c,u)),u.add(a.div.source)}let s=new Set([...i.entries()].filter(([,a])=>a.size>1).map(([a])=>a));for(let a of n){let{div:c,selector:u,occurrence:l}=a,d=`${u}|${l}|${c.prop}|${c.viewport}`;if(s.has(d)){r.push({...c,cause:"page-conflict"});continue}let f=`${u}|${l}|${c.prop}|${c.source}`,p=t.get(f);p?p.viewports.includes(c.viewport)||p.viewports.push(c.viewport):t.set(f,{selector:u,occurrence:l,prop:CQt(c.prop),value:c.source,viewports:[c.viewport],cause:c.replicaOnlyClasses.length>0?"wp-interference":"cascade-divergence"})}let o=[...t.values()].sort((a,c)=>a.selector.localeCompare(c.selector)||a.prop.localeCompare(c.prop));for(let a of o)a.viewports.sort();return{overrides:o,unresolved:r}}var vQt=["desktop","mobile"];function Z_e(e){let t=new Map;for(let i of e){let s=`${i.selector}|${i.occurrence}|${i.prop}`,o=t.get(s);o?o.push(i):t.set(s,[i])}let r=[],n=[];for(let[,i]of t){let s=new Set;for(let o of vQt){let a=new Set;for(let c of i)c.viewports.includes(o)&&a.add(c.value);a.size>1&&(s.add(o),r.push({selector:i[0].selector,occurrence:i[0].occurrence,prop:i[0].prop,viewport:o,values:[...a].sort()}))}if(s.size===0){n.push(...i);continue}for(let o of i){let a=o.viewports.filter(c=>!s.has(c));a.length>0&&n.push({...o,viewports:a})}}return{overrides:n,conflicts:r}}var xQt="@media (max-width: 767px)",BQt="@media (min-width: 768px)";function K_e(e){if(e.overrides.length===0)return"";let t=[],r=[],n=[];for(let s of e.overrides){let o=`${s.selector} { ${s.prop}: ${s.value}; }`;s.viewports.length===2?t.push(o):s.viewports[0]==="mobile"?r.push(o):n.push(o)}let i=["/* parity-patch: generated deterministically by the repair loop \u2014 same"," divergence inputs produce identical bytes. Source-measured values"," restoring authorial intent over residual WP interference. */",...t];return n.length&&i.push(`${BQt} { + ${n.join(` + `)} +}`),r.length&&i.push(`${xQt} { + ${r.join(` + `)} +}`),i.join(` +`)+` +`}function X_e(e){let t=e.map(r=>`${r.match}|${r.viewport}|${r.kind}|${r.prop}|${r.source}|${r.replica}`).sort();return yQt("sha1").update(t.join(` +`)).digest("hex")}async function Fh(e,t){return(await Ur(e,[...t],{timeout:6e4,maxBuffer:10*1024*1024})).trim()}async function RQt(e,t){let r=MQt(t?.headers??NQt(e)),n=await tc(DQt(e),{...r?{headers:r}:{}});return new Response(Uint8Array.from(n.body).buffer,{status:n.status,headers:n.headers})}function DQt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function NQt(e){if(typeof Request<"u"&&e instanceof Request)return e.headers}function MQt(e){if(!e)return;let t=new Headers(e),r={};return t.forEach((n,i)=>{r[i]=n}),Object.keys(r).length>0?r:void 0}function pD(e,t){AD(T7(e),{recursive:!0});let r=`${e}.tmp.${process.pid}`;try{k0(r,t),jw(r,e)}catch(n){try{hD(r)}catch{}throw n}}function B7(e){return e.replace(/\s+/g," ").trim()}function tTe(e){let t=e("body").children().first().get(0)??e.root().children().first().get(0);return t&&ve(t)?t:null}function rTe(e){return e==="header"||e==="nav"||e==="footer"||e==="aside"||e==="complementary"}function PQt(e,t){let r=t.tagName.toLowerCase(),n=1;for(let s=t.prev;s;s=s.prev)ve(s)&&s.tagName?.toLowerCase()===r&&(n+=1);let i=e(t);return{tag:r,id:(i.attr("id")??"").trim()||null,classes:(i.attr("class")??"").split(/\s+/).filter(Boolean),nthOfType:n}}function LQt(e){let t=le(e),r=new Set;return n=>{let i=le(n),s=i("body").children().first().get(0)??i.root().children().first().get(0);if(!s||!ve(s))return Mm(n);let o=i.html(s),a=s.tagName.toLowerCase(),c=t(a).toArray().filter(u=>ve(u));for(let u of c)if(!r.has(u)&&t.html(u)===o)return r.add(u),Fp(PQt(t,u));return Mm(n)}}function k7(e,t,r=Mm){let n=W2(e.html);return{kind:t,selector:r(e.html),...rTe(n)?{role:n}:{}}}function FQt(e,t=Mm){let r=W2(e.html);return{kind:"page_body_section",selector:t(e.html),...rTe(r)?{role:r}:{}}}function OQt(e){let t=le(e),r=[],n=tTe(t);if(n){let i=(t(n).attr("id")??"").trim();i&&r.push(i)}return t("[id]").each((i,s)=>{let o=(t(s).attr("id")??"").trim();o&&!r.includes(o)&&r.push(o)}),r}function _7(e,t){if(!t.trim())return!1;let r=le(e.html),n=tTe(r),i=r(n||"body"),s=n?(r(n).attr("class")??"").split(/\s+/).filter(Boolean):[],o=le(t),a=B7(o.text()),c=new Set;o("[id]").each((p,h)=>{let A=(o(h).attr("id")??"").trim();A&&c.add(A)});let u=new Set;o("[class]").each((p,h)=>{for(let A of(o(h).attr("class")??"").split(/\s+/).filter(Boolean))u.add(A)});let l=OQt(e.html);if(l.some(p=>c.has(p)||t.includes(`"anchor":${JSON.stringify(p)}`))||t.includes(`"anchor":${JSON.stringify(e.id)}`)||s.some(p=>u.has(p)))return!0;if(l.length>0||s.length>0)return!1;let d=r("a[href]").toArray().map(p=>B7(r(p).text())).filter(Boolean);if(d.length>0&&d.every(p=>a.includes(p)))return!0;let f=B7(i.text());return f.length>=24&&a.includes(f)}function UQt(e,t){let r=t.filter(i=>i.kind==="page_body_section"),n=t.filter(i=>i.kind==="page_body_section"?!1:i.selector===e.selector?!0:i.selector===void 0&&(i.role===void 0||i.role===e.role));return[...r,...n]}function $Qt(e,t,r,n){let i=e.map(a=>Pm([a],UQt(a,t),r,n).assignments[0]),s={};for(let a of e)s[a.role]=(s[a.role]??0)+1;let o=i.filter(a=>a.kind==="unassigned").map(a=>a.landmark);return{page:r,entryUrl:n,assignments:i,unassignedRegions:o,counts:{sourceLandmarks:s,assigned:i.filter(a=>["page_body_section","header_part","footer_part"].includes(a.kind)).length,unassigned:o.length,nonActionable:i.filter(a=>a.kind==="non_actionable").length}}}var nTe=async(e,t)=>{let r=e.dir,n=e.studioSitePath,i=e.outputDir??r;if(!r)return t.errorResult("dir is required");if(!n)return t.errorResult("studioSitePath is required");if(!i)return t.errorResult("outputDir is required");let s=QQt(RI(n)),o=[],a=e.createSite===!0,c=Gc(s);if(!c&&a){let $=e.siteTitle??(TQt(s.replace(/\/+$/,""))||"Local Site");try{let Ae=await uCe({name:$,sitePath:s,adminUser:process.env.WP_ADMIN_USER,adminPassword:process.env.WP_ADMIN_PASS});c=Ae.wpRoot,Ae.created&&o.push(`created Studio site "${$}" at ${s}`)}catch(Ae){return t.errorResult(`failed to create Studio site at ${s}: ${Ae.message}`)}}if(!c)return t.errorResult(`no wp-content found under ${s} (or its wordpress/ subdir) \u2014 pass createSite:true to provision a fresh Studio site`);let u=e.skipDesign===!0,l=e.skipCompare===!0,d=e.editorSurface===!0,f=e.repair!==!1,p=Math.min(Math.max(Number(e.maxRepairRounds??2),0),5),h=e[z_e]===!0,A=e.carryCss!==!1,g=e.wpUrl?.replace(/\/$/,""),m=e.nativeBehaviors===!0,b=e.editableIslands!==!1;m&&e.carryJs===!0&&o.push("nativeBehaviors forces carryJs off (carried source JS would double-drive block behaviors)");let E=m?!1:e.carryJs!==!1,C;if(e.dataModel!==!1){for(let $ of[vr(i,"data-model.json"),vr(r,"data-model.json")])if(Lh($)){try{let Ae=JSON.parse(nf($,"utf8"));if(Ae&&Ae.cpt?.slug&&Array.isArray(Ae.mounts)){let et=Cw(Ae);try{let gt=vr(i,"reports");AD(gt,{recursive:!0}),k0(vr(gt,"data-model-validation.json"),JSON.stringify(et,null,2))}catch{}for(let gt of et.warnings)o.push(`data-model warning: ${gt}`);if(et.valid)C=Ae;else{for(let gt of et.errors)o.push(`data-model ERROR: ${gt}`);o.push(`data-model.json invalid (${et.errors.length} error(s)) \u2014 data path skipped; see reports/data-model-validation.json`)}}else o.push(`data-model.json at ${$} is missing cpt/mounts \u2014 ignored`)}catch(Ae){o.push(`data-model.json parse failed (${$}): ${Ae.message}`)}break}}let I=C?.mounts.filter($=>$.sourceSelector)??[],T=await aD({dir:r,outputDir:i,nativeBehaviors:m,editableIslands:b,cardMounts:I},t);if(T.isError)return T;let k=JSON.parse(T.content[0].text),D=k.formsConverted??0,_=k.islandsConverted??0,v={lowConfidence:k.lowConfidence,failedPageCount:k.failedPageCount,failedPagesList:k.failedPagesList,stylingDrops:k.stylingDrops??0},N={tabs:k.behaviors?.tabs??0,slider:k.behaviors?.slider??0,modal:k.behaviors?.modal??0},O=new Set;N.tabs>0&&O.add("tabs"),N.slider>0&&O.add("slider"),N.modal>0&&O.add("modal");let S=rD(r),w=e.siteTitle??S.pages.find($=>$.slug==="home")?.title??"Local Site",R=e.themeSlug??"local-site-theme",U,J="",X=!1,z=vr(i,"source"),W=async $=>{await $.addStyleTag({content:S7}),await $.evaluate(v7)};if(!u){let $;try{$=await h7(r);let Ae=S.pages.map(ut=>$.urlForPage(ut.relPath));await bI({urls:Ae,outputDir:z,primaryUrl:$.url,captureDesign:!0,concurrency:6,prepareCapture:W});let et=ut=>JSON.parse(nf(vr(z,ut),"utf8")),gt=S.pages.map(ut=>ut.html);for(let ut of _Qt(r))ut.endsWith(".css")&>.push(nf(vr(r,ut),"utf8"));U=L_e({palette:et("palette.json"),typography:et("typography.json"),breakpoints:et("breakpoints.json"),cssSources:gt});let ht=tj(gt);if(ht.length>0){let ut=await C_e(ht,{themeDir:vr(i,"theme")});J=ut.localizedCss;for(let Dt of ut.errors)o.push(`font self-host failed: ${Dt.url}: ${Dt.error}`)}X=!0}catch(Ae){o.push(`design capture failed (default styling used): ${Ae.message}`)}finally{await $?.close()}}let ce,ne,he={},q=0,Te=!1;if(A||E||m){let $=Fm(r,S.pages.map(Ae=>({relPath:Ae.relPath,html:Ae.html})));$.skippedUnlinked.length>0&&o.push(`unlinked top-level assets skipped (linked assets exist; stale-revision protection): ${$.skippedUnlinked.join(", ")}`),he=$.imgRewritesByPage;for(let Ae of $.imgAssets)try{let et=vr(i,"theme",Ae.themeRel);AD(T7(et),{recursive:!0}),eTe(Ae.srcAbs,et),q++,/\.svg$/i.test(Ae.themeRel)&&(Te=!0)}catch(et){o.push(`carry img ${Ae.themeRel}: ${et.message}`)}if(A||E){let Ae=J?$.css.replace(AI,AI+J+` + +`):$.css,et=E?gke($.js,S.pages):"";if(et&&C){let gt=g_e(et,C.mounts.map(ut=>ut.selector)),ht=y_e(gt.js,C.sourceArrays??[]);et=`${ht.js} +${m_e} +`,o.push(`data: neutralized ${gt.removed} mount call(s), rebound ${ht.rewritten} lookup(s)`)}if(ce={css:A?Ae:"",js:et},A)for(let gt of $.mediaAssets)try{let ht=vr(i,"theme",gt.themeRel);AD(T7(ht),{recursive:!0}),eTe(gt.srcAbs,ht)}catch(ht){o.push(`carry media ${gt.themeRel}: ${ht.message}`)}}ne=m?Nw({css:$.css,js:$.js},{sectionKinds:O}):void 0}if(ne){let $=vr(i,"behavior-gaps.json"),Ae=`${$}.tmp.${process.pid}`;try{k0(Ae,JSON.stringify({schema:1,site:r,gaps:ne.gaps},null,2)+` +`),jw(Ae,$)}catch(et){try{hD(Ae)}catch{}o.push(`behavior-gaps write failed: ${et.message}`)}}let Z=A&&(ce?.css??"").trim().length>0,Qe=E&&(ce?.js??"").trim().length>0,dt;if(D>=1){let Ae=v_e({sourceCss:ce?.css??"",formsConverted:D}).css.trim();Ae.length>0&&(dt=Ae)}let xe=S.pages.find($=>$.slug==="home")??S.pages[0],Ue=!!ne?.sticky&&Z;ne?.sticky&&!Ue&&o.push("sticky behavior detected but not emitted (requires carried chrome header)");let Se=O_e(S,xe.slug),Vt=C?C.mounts.map($=>cD($).css).filter(Boolean).join(` +`):"",Qt;{let $=[];if(Z){let et="";try{et=nf(AQ(i),"utf8")}catch{}$.push(et)}Vt&&$.push(Vt);let Ae=mke(...$);Qt=Ae.length>0?Ae:void 0}let Gt=(()=>{for(let $ of[xe,...S.pages]){let Ae=$?.html?.match(/]*\bclass="([^"]+)"/i);if(Ae)return Ae[1]}})(),Hr=j2(xe.html,ce?.css??""),H=Object.fromEntries(S.pages.filter($=>$.bodyData).map($=>[$.slug===xe.slug?"/":`/${$.slug}/`,$.bodyData])),de=[...Se.values()],oe,ie="",ue="";try{oe=await qH(r,{outDir:vr(i,"theme"),themeMeta:{slug:R,name:w},...U?{foundationAggregates:U.foundationAggregates}:{},fetchImpl:RQt,coverageFloor:0,carrySourceCss:!1,variationHoist:!1,hooks:{onFoundation:async $=>U?.tokens??$,onSection:async $=>$,onAssets:async $=>({keep:$.assets.map(Ae=>Ae.relPath),decoration:[]}),onRefine:async $=>$_e($,{site:S,siteTitle:w,themeSlug:R,mainClass:Gt,mainWrapperClass:Hr,interiorChromeTemplates:de,carrySourceAssets:ce,instanceStylesCss:Qt,jetpackFormParityCss:dt,allowSourceChromeMounts:Z&&Qe,...Ue?{sticky:ne.sticky}:{}})}}),ie=oe.model.parts["header.html"]??"",ue=oe.model.parts["footer.html"]??"";for(let $ of oe.warnings)o.push($)}catch($){return t.errorResult(`theme build failed: ${$.message}`)}let Be=0,Ce=[];try{let $=[...m?[__e()]:[],...b&&_>0?[t0()]:[]],Ae=F_e({siteTitle:w,themeSlug:R,carrySourceAssets:ce,instanceStylesCss:Qt,jetpackFormParityCss:dt,bodyDataByPath:H}),et=H_e({siteTitle:w,themeSlug:R,mainClass:Gt,mainWrapperClass:Hr,interiorChromeTemplates:de,carrySourceAssets:ce,instanceStylesCss:Qt,jetpackFormParityCss:dt});pD(vr(oe.outDir,"functions.php"),Ae);let gt=j_e(oe,{functionsPhp:Ae,extraThemeFiles:et}),ht=nc({wpRoot:c,themeSlug:R,themeFiles:gt.themeFiles,assetSourceDir:gt.assetSourceDir,...$.length>0?{blockPlugins:$}:{}});Be=ht.themeWritten,Ce=ht.pluginSlugs}catch($){return t.errorResult(`theme write failed: ${$.message}`)}if(dt)try{pD(vr(i,Ph.outputFileName),dt+` +`)}catch($){o.push(`jetpack form parity css mirror write failed: ${$.message}`)}{let $=vr(c,"wp-content","themes",R);try{if(!Qe){let Ae=vr($,"assets","js","source.js");Lh(Ae)&&hD(Ae)}if(!Z){let Ae=vr($,"assets","css","source.css");Lh(Ae)&&hD(Ae)}}catch(Ae){o.push(`stale carry asset cleanup failed: ${Ae.message}`)}}try{await Fh(s,["theme","activate",R])}catch($){o.push(`theme activate failed: ${$.message}`)}if(Gke(D))try{await Fh(s,rf.wpArgs);try{await Fh(s,Mw.wpArgs)}catch($){o.push(Yke($))}}catch($){o.push(Wke($))}for(let $ of Ce)try{await Fh(s,["plugin","activate",$])}catch(Ae){o.push(`plugin activate failed for ${$}: ${Ae.message}`)}let fe=!1;if(Te){let $=await Pd(s,"safe-svg",Fh);$.ok?fe=!0:o.push(`safe-svg install failed: ${$.error}`)}if(q>0&&o.push(`carried ${q} HTML asset(s) into the theme`+(Te?` (safe-svg ${fe?"ensured":"NOT installed"})`:"")),!g)try{g=(await Fh(s,["option","get","siteurl"])).trim().replace(/\/$/,"")}catch($){g="http://localhost:8889",o.push(`siteurl resolve failed, using ${g}: ${$.message}`)}for(let $ of PI())try{await Fh(s,$)}catch(Ae){o.push(`cache flush failed (${$.slice(0,2).join(" ")}): ${Ae.message}`)}if(C)try{let $=await p_e({model:C,studioSitePath:s,wpRoot:c,sourceDir:r}),Ae=($.skippedModified?`, ${$.skippedModified} skipped (edited in wp-admin)`:"")+($.collisions?`, ${$.collisions} slug-collision(s)`:"")+($.defaultsTrashed?`, ${$.defaultsTrashed} WP seed default(s) trashed`:"");for(let et of $.mediaErrors)o.push(`data media: ${et.sourceUrl}: ${et.error}`);o.push(`data: ${$.inserted} inserted, ${$.updated} updated, ${$.terms} term(s), ${$.mediaInstalled} media item(s) installed${Ae}; mu-plugins ${$.muPlugins.join(", ")}`)}catch($){o.push(`data install failed: ${$.message}`)}let Ze=Jke(S,i),We=Ze.items.filter($=>!$.content.trim()).map($=>$.slug),Oe=[];for(let $ of Ze.items){let Ae=S.pages.find(gt=>gt.slug===$.slug);if(!Ae)continue;let et=Se.get($.slug);Oe.push(...k_e({pageSlug:$.slug,sourceHtml:Ae.html,postContent:$.content,partMarkup:[ie,ue,...et?[et.partMarkup]:[]]}))}let Je=vr(i,"conservation-leaks.json");try{pD(Je,JSON.stringify({schema:1,site:r,leaks:Oe},null,2)+` +`)}catch($){o.push(`conservation leaks report write failed: ${$.message}`)}let It=vr(i,"region-audit.json"),Wt=()=>({ok:!0,status:"pass",unassignedRegions:0,hardFailRegions:0,artifact:It,railHardFail:{enabled:h,roles:fD,minLinks:2}}),se=Wt();try{let $=LQt(xe.html),Ae=Y2(xe.html),et=U_e(xe.html),gt=et.find(tr=>tr.role==="header")??et.find(tr=>tr.role==="nav")??null,ht=et.find(tr=>tr.role==="footer")??null,ut=[...et.filter(tr=>tr.role==="body"&&tr.chromeSource!=="layout-rail").map(tr=>FQt(tr,$))];gt&>.chromeSource!=="layout-rail"&&_7(gt,ie)&&ut.push(k7(gt,"header_part",$)),ht&&_7(ht,ue)&&ut.push(k7(ht,"footer_part",$));for(let tr of et.filter(yi=>yi.chromeSource==="layout-rail"))_7(tr,ie)&&ut.push(k7(tr,"header_part",$));let Dt=$Qt(Ae,ut,xe.slug,xe.relPath),kn=Dt.unassignedRegions.filter(tr=>fD.includes(tr.role)&&(tr.linkCount??0)>=2),Vn=h?kn:[];se={ok:Vn.length===0,status:Vn.length>0?"fail":Dt.counts.unassigned>0?"warn":"pass",unassignedRegions:Dt.counts.unassigned,hardFailRegions:Vn.length,artifact:It,railHardFail:{enabled:h,roles:fD,minLinks:2}};try{let tr={schema:1,site:r,pages:[Dt],unassignedRegions:Dt.counts.unassigned,hardFailRegions:Vn};pD(It,JSON.stringify(tr,null,2)+` +`)}catch(tr){o.push(`region audit write failed: ${tr.message}`)}}catch($){o.push(`region audit failed: ${$.message}`),se=Wt()}let ae=[],Fe=[];for(let $ of Ze.items)try{let Ae;if(C){let ut=A_e($.content,C.mounts);ut.injected.length>0&&(Ae=ut.markup,o.push(`data: ${$.slug} \u2192 query loop(s) for ${ut.injected.join(", ")}`))}let et=S.pages.find(ut=>ut.slug===$.slug),gt=et?he[et.relPath]:void 0;gt&>.length>0&&(Ae=HH(Ae??$.content,gt,R));let ht=await Kke({item:$,outputDir:i,studioSitePath:s,contentOverride:Ae});!ht||ht.action==="error"?Fe.push({slug:$.slug,error:ht?.error??"unsupported item"}):ae.push({slug:$.slug,postId:ht.postId})}catch(Ae){Fe.push({slug:$.slug,error:Ae.message})}let Xe=!1;{let $={};for(let[ht,ut]of kQ({title:w}))$[ht]=ut;let Ae=ae.filter(ht=>ht.postId!=null).map(ht=>({postId:ht.postId,slug:ht.slug,template:Se.get(ht.slug)?.templateName??"page-local"})),et=ae.find(ht=>ht.slug===Ze.homeSlug),gt=et?.postId!=null?et.postId:void 0;try{let ht=await e_e({payload:{options:$,templateAssigns:Ae,...gt!==void 0?{frontPageId:gt}:{}},studioSitePath:s});Xe=ht.applied.frontPage;for(let ut of ht.errors)ut.item.startsWith("option:")?o.push(`${ut.item.slice(7)} set failed: ${ut.error}`):ut.item.startsWith("template:")?o.push(`template assign failed for ${ut.item.slice(9)}: ${ut.error}`):ut.item==="frontPage"?o.push(`front page set failed: ${ut.error}`):o.push(`site finalize ${ut.item} failed: ${ut.error}`)}catch(ht){let ut=[...Object.keys($).map(Dt=>`option ${Dt}`),...Ae.map(Dt=>`template ${Dt.slug}`),...gt!==void 0?["front page"]:[]];o.push(`site finalize failed (attempted: ${ut.join(", ")}): ${ht.message}`)}}let Ye=.99,Re=vr(i,"replica"),Ht=ae.filter($=>$.postId!=null).map($=>$.slug===Ze.homeSlug?`${g}/`:`${g}/${$.slug}/`),ur;if(!u&&!l&&X)try{await bI({urls:Ht,outputDir:Re,primaryUrl:g,concurrency:6,prepareCapture:W});let $=await XR({originDir:vr(z,"screenshots"),replicaDir:vr(Re,"screenshots")}),Ae=Dt=>$.results.map(kn=>kn[Dt]?.score).filter(kn=>typeof kn=="number"),et=Dt=>Dt.length?Dt.reduce((kn,Vn)=>kn+Vn,0)/Dt.length:0,gt=$.results.map(Dt=>{let kn=Dt.desktop?.score??null,Vn=Dt.mobile?.score??null;return{pathname:Dt.pathname,desktop:kn,mobile:Vn,desktopHeightPass:Dt.desktop?.heightPass,mobileHeightPass:Dt.mobile?.heightPass,passes:kn!==null&&Vn!==null&&kn>=Ye&&Vn>=Ye&&Dt.desktop?.heightPass!==!1&&Dt.mobile?.heightPass!==!1}});ur={floor:Ye,allPass:gt.length>0&>.every(Dt=>Dt.passes),avgDesktop:et(Ae("desktop")),avgMobile:et(Ae("mobile")),pages:gt};let ht=vr(i,"parity-report.json"),ut=`${ht}.tmp.${process.pid}`;k0(ut,JSON.stringify({schema:1,comparison:$,parity:ur},null,2)+` +`),jw(ut,ht)}catch($){o.push(`compare failed: ${$.message}`)}if(f&&ur&&!ur.allPass&&p>0&&!Z&&o.push("repair skipped: requires carried source css (carryCss)"),f&&ur&&!ur.allPass&&p>0&&Z){let $=0,Ae,et=!1,gt=new Map,ht=[],ut=[],Dt=ur;for(;!Dt.allPass&&$!Nt.passes);ut=[];let Vn=new Map;try{let Nt=vr(Re,"screenshots","manifest.json");if(Lh(Nt)){let Nn=JSON.parse(nf(Nt,"utf8"));for(let[ss,Mn]of Object.entries(Nn.entries))try{Vn.set(new URL(ss).pathname,Mn.slug)}catch{}}}catch(Nt){o.push(`repair round ${$}: manifest read failed: ${Nt.message}`);break}let tr=[],yi,Sa,va=!0;try{yi=await h7(r),Sa=await Oa({});for(let Nt of kn){let Nn=Vn.get(Nt.pathname);if(!Nn)continue;let ss=S.pages.find(Mn=>{let wn=Mn.slug===Ze.homeSlug?`${g}/`:`${g}/${Mn.slug}/`;return new URL(wn).pathname===Nt.pathname});if(ss)for(let Mn of["desktop","mobile"]){let wn=Nt[Mn],io=Mn==="desktop"?Nt.desktopHeightPass:Nt.mobileHeightPass;if(wn!==null&&wn>=Ye){io===!1&&ut.push(`${Nt.pathname} ${Mn}`);continue}let ks=vr(Re,"screenshots","diff",`${Nn}.${Mn}.diff.png`);if(!Lh(ks))continue;let iu;try{iu=Y_e(nf(ks),{scale:Mn==="desktop"?RB:1})}catch{continue}if(iu.length===0)continue;let Yw=yi.urlForPage(ss.relPath),dl=ss.slug===Ze.homeSlug?`${g}/`:`${g}/${ss.slug}/`;try{let Q0=await G_e({browser:Sa,sourceUrl:Yw,replicaUrl:dl,viewport:Mn,regions:iu});tr.push(...Q0)}catch(Q0){o.push(`repair round ${$}: probe ${Nt.pathname} ${Mn}: ${Q0.message}`)}}}}catch(Nt){o.push(`repair round ${$}: probe setup failed: ${Nt.message}`),va=!1}finally{await Sa?.close(),await yi?.close()}if(!va)break;let xa=J_e(tr),ll=X_e(tr);if(ll===Ae){ht=xa.unresolved;break}Ae=ll;for(let Nt of xa.overrides){let Nn=`${Nt.selector}|${Nt.occurrence}|${Nt.prop}|${Nt.value}`,ss=gt.get(Nn);if(ss)for(let Mn of Nt.viewports)ss.viewports.includes(Mn)||ss.viewports.push(Mn);else gt.set(Nn,{...Nt,viewports:[...Nt.viewports]})}ht=xa.unresolved;let $h=Z_e([...gt.values()].sort((Nt,Nn)=>Nt.selector.localeCompare(Nn.selector)||Nt.prop.localeCompare(Nn.prop)));for(let Nt of $h.conflicts)o.push(`repair: page-conflict (unpatchable globally) ${Nt.selector} ${Nt.prop} ${Nt.viewport}: ${Nt.values.join(" vs ")}`);let Hh={overrides:$h.overrides,unresolved:ht};if(Hh.overrides.length===0){ut.length>0&&o.push(`repair: height-only failures (content lost below the crop; not deterministically patchable): ${ut.join(", ")}`);break}let sf=K_e(Hh);try{nc({wpRoot:c,themeSlug:R,themeFiles:[{relativePath:"assets/css/parity-patch.css",content:sf}]});let Nt=vr(i,"parity-patch.css"),Nn=`${Nt}.tmp.${process.pid}`;k0(Nn,sf),jw(Nn,Nt)}catch(Nt){o.push(`repair round ${$}: patch write failed: ${Nt.message}`);break}try{await bI({urls:Ht,outputDir:Re,primaryUrl:g,concurrency:6,prepareCapture:W,force:!0});let Nn=(await XR({originDir:vr(z,"screenshots"),replicaDir:vr(Re,"screenshots")})).results.map(wn=>{let io=wn.desktop?.score??null,ks=wn.mobile?.score??null;return{pathname:wn.pathname,desktop:io,mobile:ks,desktopHeightPass:wn.desktop?.heightPass,mobileHeightPass:wn.mobile?.heightPass,passes:io!==null&&ks!==null&&io>=Ye&&ks>=Ye&&wn.desktop?.heightPass!==!1&&wn.mobile?.heightPass!==!1}}),ss=wn=>Nn.map(io=>io[wn]).filter(io=>io!==null),Mn=wn=>wn.length?wn.reduce((io,ks)=>io+ks,0)/wn.length:0;Dt={...Dt,allPass:Nn.length>0&&Nn.every(wn=>wn.passes),avgDesktop:Mn(ss("desktop")),avgMobile:Mn(ss("mobile")),pages:Nn}}catch(Nt){o.push(`repair round ${$}: re-compare failed: ${Nt.message}`);break}if($++,Dt.allPass){et=!0;break}}ur={...Dt,repair:{rounds:$,overrides:gt.size,unresolved:ht,converged:et,...ut.length>0?{heightOnly:ut}:{}}}}let ti;if(d){let $=process.env.WP_ADMIN_PASS;if(!$)o.push("editorSurface skipped: set WP_ADMIN_PASS (editor login credential) in the environment");else if(!g)o.push("editorSurface skipped: replica wpUrl not resolved");else try{let Ae=new Map;try{let tr=vr(z,"screenshots","manifest.json");if(Lh(tr)){let yi=JSON.parse(nf(tr,"utf8"));for(let[Sa,va]of Object.entries(yi.entries??{}))try{Ae.set(new URL(Sa).pathname,va.slug)}catch{}}}catch{}let et=[];for(let tr of ae){let yi=S.pages.find($h=>$h.slug===tr.slug);if(!yi)continue;let Sa="";try{Sa=nf(jm(i,tr.slug),"utf8")}catch{continue}if(!Sa.trim())continue;let va=yi.slug===Ze.homeSlug?"/":`/${yi.slug}/`,xa=Ae.get(va),ll=xa?vr(z,"screenshots","desktop",`${xa}.png`):null;et.push({pathname:va,slug:tr.slug,markup:Sa,blocksPath:!1,sourceShotDesktop:ll&&Lh(ll)?ll:null})}let gt=await n_e({wpUrl:g,sitePath:s,username:process.env.WP_ADMIN_USER??"admin",password:$}),ht;try{ht=await i_e({session:gt,pages:et,floor:Ye,diffDir:vr(Re,"screenshots")})}finally{await gt.close()}let ut=ht.results.filter(tr=>tr.editorScore!==null),Dt=ut.length>0?ut.reduce((tr,yi)=>tr+(yi.editorScore??0),0)/ut.length:null;ti={scored:ut.length,skipped:ht.results.length-ut.length,avgEditorScore:Dt,repairTasks:ht.repairTasks.length};let kn=vr(i,"editor-report.json"),Vn=`${kn}.tmp.${process.pid}`;k0(Vn,JSON.stringify({schema:1,surface:"editor",results:ht.results,repairTasks:ht.repairTasks},null,2)+` +`),jw(Vn,kn)}catch(Ae){o.push(`editorSurface failed: ${Ae.message}`)}}let Dn=t.textResult({pages:Ze.items.length,installed:ae.length,...ti!==void 0?{editorSurface:ti}:{},failedInstalls:Fe,missingSidecars:Ze.missingSidecars,emptySidecars:We,ingest:v,...b?{islandsConverted:_}:{},themeSlug:R,themeWritten:Be,frontPageSet:Xe,designCaptured:X,carried:{css:Z,js:Qe},conservationLeaks:{count:Oe.length,artifact:Je},conservation:se,...ne!==void 0?{behaviors:{reveal:!!ne.reveal,sticky:Ue,tabs:N.tabs,slider:N.slider,modal:N.modal,gaps:ne.gaps.length}}:{},...ur!==void 0?{parity:ur}:{},warnings:o});return se.status==="fail"&&(Dn.isError=!0),Dn};var iTe=async(e,t)=>{let r=e.patterns;if(!Array.isArray(r))return t.errorResult("patterns[] is required");let n=MQ({patterns:r});return t.textResult(n)};import{existsSync as HQt,readdirSync as jQt,readFileSync as qQt}from"node:fs";import{join as oTe}from"node:path";function sTe(e){let t=[],r=0,n=0,i=0;return e.forEach((s,o)=>{let a=`section[${o}] (index ${typeof s?.index=="number"?s.index:"?"})`;if(typeof s!="object"||s===null||!Array.isArray(s.findings)||!Array.isArray(s.applied)||!Array.isArray(s.skipped)){t.push(`${a}: malformed report \u2014 findings/applied/skipped arrays are required`);return}let c=new Set;for(let d of s.findings){if(typeof d?.id!="string"||d.id===""){t.push(`${a}: finding with missing id`);continue}c.has(d.id)&&t.push(`${a}: duplicate finding id "${d.id}"`),c.add(d.id)}let u=new Set(s.applied.map(d=>d?.id).filter(d=>typeof d=="string")),l=new Set(s.skipped.map(d=>d?.id).filter(d=>typeof d=="string"));for(let d of c){let f=u.has(d),p=l.has(d);f&&p&&t.push(`${a}: finding "${d}" appears in both applied and skipped`),!f&&!p&&t.push(`${a}: finding "${d}" is UNACCOUNTED \u2014 add it to applied (with summary) or skipped (with reason)`)}for(let d of s.applied)d?.id&&!c.has(d.id)&&t.push(`${a}: applied id "${d.id}" has no matching finding`);for(let d of s.skipped)d?.id&&!c.has(d.id)&&t.push(`${a}: skipped id "${d.id}" has no matching finding`);r+=c.size,n+=s.applied.length,i+=s.skipped.length}),{ok:t.length===0,errors:t,sections:e.length,findings:r,applied:n,skipped:i}}var aTe=async(e,t)=>{let r=e.outputDir,n=e.slug;if(!r||!n)return t.errorResult("outputDir and slug are required");if(!/^[a-z0-9][a-z0-9._-]*$/i.test(n)||n.includes(".."))return t.errorResult(`Invalid slug "${n}" \u2014 expected a plain page slug (letters/digits/dot/dash/underscore).`);let i=oTe(r,"refine",n);if(!HQt(i))return t.errorResult(`No refine reports at ${i} \u2014 match-section must write refine//.json before validation.`);let s=[],o=[];for(let c of jQt(i).filter(u=>u.endsWith(".json")).sort())try{s.push(JSON.parse(qQt(oTe(i,c),"utf8")))}catch{o.push(c)}if(o.length>0)return t.errorResult(`Unparseable refine report file(s): ${o.join(", ")}`);if(s.length===0)return t.errorResult(`No section reports found in ${i}.`);let a=sTe(s);return a.ok?t.textResult({ok:!0,slug:n,sections:a.sections,findings:a.findings,applied:a.applied,skipped:a.skipped}):t.errorResult(`Refine coverage FAILED for ${n}: +- ${a.errors.join(` +- `)}`)};var cTe={liberate_cluster_pages:{description:"Cluster page signatures by exact layout signature; pick a representative per cluster.",inputSchema:{type:"object",properties:{signatures:{type:"array",description:"PageSignature[]"}},required:["signatures"]}},liberate_section_extract:{description:"Extract a page signature (off saved HTML) or full computed-style section specs (representatives).",inputSchema:{type:"object",properties:{url:{type:"string"},html:{type:"string"},detail:{type:"string",enum:["signature","full"]},mediaMap:{type:"object",description:"detail=full only: {sourceCdnUrl: uploadedWpUrl} rewrite map"},cdpPort:{type:"number",description:"detail=full only: connect to an existing Chromium over CDP instead of launching"}},required:["url","detail"]}},liberate_compose_instantiate:{description:"Deterministically fill a cluster layout skeleton with a page's content; flag misfits.",inputSchema:{type:"object",properties:{skeleton:{type:"object"},pageContent:{type:"object"}},required:["skeleton","pageContent"]}},liberate_validate_artifacts:{description:"Pre-install gate: drift + escaping/injection + provenance over generated patterns.",inputSchema:{type:"object",properties:{patterns:{type:"array",description:"ArtifactPattern[]"}},required:["patterns"]}}};ki();St();var Dr=/\.(jpg|jpeg|png|gif|svg|webp|avif|ico|bmp|tiff)/i;function De(e,t){let r=le(e);return r(`meta[property="${t}"]`).attr("content")||r(`meta[name="${t}"]`).attr("content")||""}function br(e){return le(e)("title").first().text().trim()}function Oh(e){let t=le(e),r=t("h1").first().text().trim();return r||t("title").first().text().trim()}function Bs(e,t){let r=le(e),n=[],i=new Set;return r("nav a[href]").each((s,o)=>{let a=r(o).attr("href")||"",c=r(o).text().trim();if(!c||i.has(a))return;i.add(a);let u=a;if(a.startsWith("/"))try{u=new URL(a,t).href}catch{u=a}n.push({text:c,href:u})}),n}var zQt="Mozilla/5.0 (compatible; DataLiberation/1.0)";async function uTe(e,t){let r=e.includes("://")?e:`https://${e}`,n="";try{let h=await fetch(r,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":zQt}});h.ok?n=await h.text():await h.body?.cancel()}catch{}let i=De(n,"og:title"),s=De(n,"og:description"),o=i||br(n)||"Imported Site",a=s||De(n,"description")||"",u=n.match(/]+lang=["']([^"']+)["']/i)?.[1]||"en-US",l=await ii(e),d=Bs(n,r),f={},p=[];for(let h of l){let A=cr(h);p.push({url:h,type:A}),f[A]=(f[A]||0)+1}return p.length===0&&(p.push({url:r,type:"homepage"}),f.homepage=1),{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:o,tagline:a,language:u},navigation:d,counts:f,urls:p}}St();ki();rc();Ls();var Xn={throughputEmaAlpha:.2,aimdDropRatio:.9,aimdDecreaseFactor:.7,errorDecreaseFactor:.5,errorBackoffRequests:3,pageDelayMin:50,pageDelayMax:1e4,pageDelayIncrease:50,mediaConcurrencyMin:1,mediaConcurrencyMax:12,mediaConcurrencyIncrease:1,mediaConcurrencyStart:6,mediaErrorMinCount:2,mediaErrorRatio:.5};function Q7(e){return typeof e=="number"&&Number.isFinite(e)}function lTe(e,t,r,n,i,s){let o={currentValue:t,throughputEma:null,errorBackoffRemaining:0,min:r,max:n,additiveIncrease:i,invertDirection:s};return e&&(Q7(e.currentValue)&&(o.currentValue=Math.max(r,Math.min(n,e.currentValue))),e.throughputEma===null?o.throughputEma=null:Q7(e.throughputEma)&&e.throughputEma>0&&(o.throughputEma=e.throughputEma),Q7(e.errorBackoffRemaining)&&(o.errorBackoffRemaining=Math.max(0,Math.min(Xn.errorBackoffRequests,Math.floor(e.errorBackoffRemaining))))),o}var gD=class{page;media;lastDebug=null;constructor(t,r){let n=t.config??{},i=n.pageDelayMin??Xn.pageDelayMin,s=n.pageDelayMax??Xn.pageDelayMax,o=n.pageDelayIncrease??Xn.pageDelayIncrease,a=n.mediaConcurrencyMin??Xn.mediaConcurrencyMin,c=n.mediaConcurrencyMax??Xn.mediaConcurrencyMax,u=n.mediaConcurrencyIncrease??Xn.mediaConcurrencyIncrease;this.page=lTe(r?.page,t.pageDelayStart,i,s,o,!0),this.media=lTe(r?.media,Xn.mediaConcurrencyStart,a,c,u,!1)}getPageDelay(){return Math.round(this.page.currentValue)}getMediaConcurrency(){return Math.round(this.media.currentValue)}getPageConcurrency(){let t=this.getPageDelay();return t<200?3:t<500?2:1}getState(){return{page:{currentValue:this.page.currentValue,throughputEma:this.page.throughputEma,errorBackoffRemaining:this.page.errorBackoffRemaining},media:{currentValue:this.media.currentValue,throughputEma:this.media.throughputEma,errorBackoffRemaining:this.media.errorBackoffRemaining}}}updateTrack(t,r,n,i){if(r<=0)return this.lastDebug={track:i,elapsed:r,workDone:n,throughput:0,ema:t.throughputEma,ratio:null,decision:"skip"},"skip";let s=n/r;if(t.throughputEma===null)return t.throughputEma=s,t.errorBackoffRemaining>0&&t.errorBackoffRemaining--,this.lastDebug={track:i,elapsed:r,workDone:n,throughput:s,ema:s,ratio:null,decision:"warmup"},"warmup";let o=s/t.throughputEma;if(t.throughputEma=t.throughputEma*(1-Xn.throughputEmaAlpha)+s*Xn.throughputEmaAlpha,t.errorBackoffRemaining>0)return t.errorBackoffRemaining--,this.lastDebug={track:i,elapsed:r,workDone:n,throughput:s,ema:t.throughputEma,ratio:o,decision:"error_backoff"},"error_backoff";let a;return osetTimeout(t,e))}function WQt(e,t){let r=le(e),n=[];r('script[type="application/ld+json"]').each((i,s)=>{n.push(r(s).html()||"")});for(let i of n)try{let s=JSON.parse(i);if(s["@type"]==="Product"&&s.name){let o=Array.isArray(s.offers)?s.offers:s.offers?[s.offers]:[],a=o[0]?.price?String(o[0].price):"",c=[];if(typeof s.image=="string")c.push(s.image);else if(Array.isArray(s.image))for(let u of s.image)typeof u=="string"?c.push(u):u?.url&&c.push(u.url);return{name:s.name,description:s.description||"",regularPrice:a,sku:s.sku||"",images:c,inStock:o[0]?.availability?.includes("InStock")??!0,sourceUrl:t}}}catch{}return null}function YQt(e,t,r){if(t<0)return[];if(e.length<=t)return e.slice();if(t===0)return[];let n=new Map;for(let u of e){let l=n.get(u.type);l?l.push(u):n.set(u.type,[u])}let i=[],s=new Set,o=n.get("homepage");if(o){for(let u of o){if(i.length>=t)break;i.push(u),s.add(u)}n.delete("homepage")}if(r&&r.size>0)for(let u of e){if(i.length>=t)break;s.has(u)||u.url&&r.has(u.url)&&(i.push(u),s.add(u))}let a=new Map;for(let u of n.keys())a.set(u,0);let c=!0;for(;i.length=t)break;let d=a.get(u);for(;d!q.has(Te.url))}let S=JQt(r,N),w=g??(a?3:void 0);w!==void 0&&w>=0&&(N=YQt(N,w,S));let R=N.map(q=>q.url);if(R.length===0)return{pagesExtracted:0,postsExtracted:0,productsExtracted:0,failed:0,mediaCollected:0};let U=0,J=0,X=0,z=0,W=new Set,ce=new Map,ne=q=>{try{l?.sendLoggingMessage?.({level:"info",data:q})}catch{}},he=0;for(;he{let Ue=Date.now();try{let Se=await p(xe);return{url:xe,pageData:Se,elapsedMs:Date.now()-Ue,error:null}}catch(Se){return{url:xe,pageData:null,elapsedMs:Date.now()-Ue,error:Se instanceof Error?Se.message:String(Se)}}}));if(Z.some(xe=>xe.error)&&(E.recordPageError(),u)){let xe=Z.filter(Ue=>Ue.error).length;ne(` [tuner] page delay: \u2192 ${E.getPageDelay()}ms (error backoff \u2014 ${xe}/${Z.length} failed)`)}for(let xe of Z)if(!xe.error){let Ue=xe.elapsedMs/1e3,Se=E.recordPageResult({elapsed:Ue});if(u&&E.lastDebug){let Vt=E.lastDebug;ne(` [tuner:debug] page: elapsed=${Vt.elapsed.toFixed(2)}s throughput=${Vt.throughput.toFixed(2)} ema=${Vt.ema?.toFixed(2)??"null"} ratio=${Vt.ratio?.toFixed(2)??"n/a"} \u2192 ${Vt.decision}`)}u&&(Se==="increase"||Se==="decrease")&&ne(` [tuner] page delay: \u2192 ${E.getPageDelay()}ms (${Se})`)}for(let xe=0;xeWt.url===Ue)?.type||cr(Ue),It=Je==="product"?"product":Je==="post"||Je==="blog-post"?"post":"page";f.bumpProgress(It,"failed"),f.save()}continue}let H;if(!a&&C){let We=E.getMediaConcurrency(),Oe=[];for(let Je of Se.mediaUrls)if(!k.has(Je)){if(Nj(Je)){k.add(Je);continue}if(D&&!D.shouldAttempt(Je)){k.add(Je);let It=D.get(Je);if(It?.status==="success"&&It.localPath){let Wt=_.get(It.localPath);Wt||(Wt=n.addMedia({url:Je,localPath:It.localPath,title:It.localPath.split("/").pop()||""}),_.set(It.localPath,Wt),n.isStreaming&&n.flushItem(n.items[n.items.length-1])),H||(H=Wt)}continue}k.add(Je),Oe.push(Je)}for(let Je=0;JeZp(Re,C,I,T,{svgRaster:!0}).then(Ht=>({mediaUrl:Re,...Ht})))),ae=(Date.now()-Wt)/1e3,Fe=se.reduce((Re,Ht)=>Re+(Ht.bytes??0),0),Xe=se.filter(Re=>Re.error).length,Ye=se.filter(Re=>!Re.error&&(Re.bytes??0)>0).length;if(Xe>=Xn.mediaErrorMinCount&&Xe>It.length*Xn.mediaErrorRatio)E.recordMediaError(),u&&ne(` [tuner] media concurrency: \u2192 ${E.getMediaConcurrency()} (error \u2014 ${Xe}/${It.length} failed)`);else if(Ye>0){let Re=E.recordMediaResult({elapsed:ae,bytesDownloaded:Fe});if(u&&E.lastDebug){let Ht=E.lastDebug;ne(` [tuner:debug] media: elapsed=${Ht.elapsed.toFixed(2)}s bytes=${Ht.workDone} throughput=${Ht.throughput.toFixed(0)} ema=${Ht.ema?.toFixed(0)??"null"} ratio=${Ht.ratio?.toFixed(2)??"n/a"} \u2192 ${Ht.decision}`)}u&&(Re==="increase"||Re==="decrease")&&ne(` [tuner] media concurrency: \u2192 ${E.getMediaConcurrency()} (${Re})`)}for(let Re of se){if(!Re.error&&Re.localPath){let Ht=_.get(Re.localPath);if(Ht)H||(H=Ht);else{let ur=n.addMedia({url:Re.mediaUrl,localPath:Re.localPath,title:Re.filename||""});_.set(Re.localPath,ur),n.isStreaming&&n.flushItem(n.items[n.items.length-1]),H||(H=ur)}}if(i.logMedia({url:Re.mediaUrl,localPath:Re.localPath,error:Re.error}),D){if(Re.error)D.markFailure(Re.mediaUrl,Re.error);else if(Re.localPath){let Ht=Re.svgRisky!==void 0||Re.rasterPath||Re.rasterError?{svgRisky:Re.svgRisky,rasterPath:Re.rasterPath,rasterError:Re.rasterError}:void 0;D.markSuccess(Re.mediaUrl,Re.localPath,Ht)}}}}}let de=t.find(We=>We.url===Ue),oe=Se.detectedType||de?.type||cr(Ue);if(oe==="page"||oe==="homepage"){let We=new Set(["BlogPosting","NewsArticle","Article","SocialMediaPosting"]);Array.isArray(Se.jsonLd)&&Se.jsonLd.some(Je=>{if(!Je||typeof Je!="object")return!1;let It=Je,Wt=It["@type"];if(typeof Wt!="string"||!We.has(Wt))return!1;let se=It.mainEntityOfPage;if(se&&typeof se=="object"){let ae=se,Fe=typeof ae.url=="string"?ae.url:typeof ae["@id"]=="string"?ae["@id"]:null;if(Fe&&Fe!==Ue)return!1}return!0})&&(oe="post")}let ie=oe==="post"||oe==="blog-post",ue=oe==="product";if(ue&&d&&!a){let We=h?.(Ue,Se.content)??WQt(Se.content,Ue);We&&(d.addProduct(We),X++)}let Be=VQt(Se.content),Ce=ue&&d?Se.slug:TB(_B(Ue),ce),fe;if(Se.author&&(fe=Se.author.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||void 0,fe&&!W.has(fe)&&(W.add(fe),n.addAuthor({login:fe,displayName:Se.author}))),ue&&d||(ie?(n.addPost({title:Se.title,slug:Ce,content:Be,excerpt:Se.excerpt,date:Se.date,seoTitle:Se.seoTitle,seoDescription:Se.seoDescription,sourceUrl:Ue,featuredMediaId:H,categories:Se.categories,tags:Se.tags,author:fe}),J++):(n.addPage({title:Se.title,slug:Ce,content:Be,excerpt:Se.excerpt,date:Se.date,seoTitle:Se.seoTitle,seoDescription:Se.seoDescription,sourceUrl:Ue}),U++)),!(ue&&d)){n.isStreaming&&n.flushItem(n.items[n.items.length-1]);try{let We=new URL(Ue).pathname,Oe=`/${Ce}/`;We&&We!=="/"&&We!==Oe&&n.addRedirect({from:We,to:Oe})}catch{}}let Ze=Date.now()-Gt;if(i.logProcessed({url:Ue,slug:Se.slug,durationMs:Ze,qualityScore:Se.qualityScore}),f){let We=ue?"product":ie?"post":"page";f.bumpProgress(We,"extracted"),(Qt+1)%10===0&&(f.setCursor("adaptive-tuner",E.getState()),f.save(),D?.flush())}if(u&&ne(` media: ${Se.mediaUrls.length}, quality: ${Se.qualityScore}, ${Ze}ms`),A){D?.flush();try{await A({url:Ue,slug:Se.slug,type:oe,items:n.items.slice(Hr),mediaUrls:Se.mediaUrls})}catch(We){ne(` [warn] onPageExtracted failed for ${Ue}: ${We.message}`)}}}f&&f.setCursor("adaptive-tuner",E.getState());let dt=E.getPageDelay();he+Te.length0&&await GQt(dt),he+=Te.length}for(let q=0;qt&&(t=r.attributes.length);return t}customMetaKeys(){let t=new Set;for(let r of this.products)if(r.meta)for(let n of Object.keys(r.meta))R7.includes(n)||t.add(n);return[...t].sort()}buildHeaders(t){let r=["id","type","sku","name","published","short_description","description","regular_price","sale_price","category_ids","tag_ids","images","weight","length","width","height","stock_status","stock_quantity"],n=this.maxAttributes();for(let i=1;i<=n;i++)r.push(`attributes:name${i}`),r.push(`attributes:value${i}`),r.push(`attributes:visible${i}`),r.push(`attributes:taxonomy${i}`);r.push("parent_id");for(let i of R7)r.push(`meta:${i}`);for(let i of t)r.push(`meta:${i}`);return r}static collapseNewlines(t){return t.replace(/\r?\n/g," ")}static metaValue(t,r){return r===gTe&&t.seoTitle?t.seoTitle:r===mTe&&t.seoDescription?t.seoDescription:r===yTe&&t.costOfGoods?t.costOfGoods:t.meta?.[r]||""}buildRow(t,r,n){let i=e.collapseNewlines,s=["",t.type||"simple",t.sku||"",i(t.name),t.published===!1?"0":"1",i(t.shortDescription||""),i(t.description||""),t.regularPrice||"",t.salePrice||"",t.categories?t.categories.join(" | "):"",t.tags?t.tags.join(" | "):"",t.images?t.images.join(", "):"",t.weight||"",t.length||"",t.width||"",t.height||"",t.inStock===!1?"outofstock":t.inStock===!0?"instock":"",t.stock!=null?String(t.stock):""];for(let o=0;othis.buildRow(a,i,r)),o=ATe.default.unparse({fields:n,data:s},{newline:`\r +`});fTe(t,o,"utf8")}_streamDir=null;_jsonlPath=null;_streaming=!1;get isStreaming(){return this._streaming}openStream(t,{resume:r=!1}={}){hTe(t,{recursive:!0}),this._streamDir=t,this._jsonlPath=pTe(t,"products.jsonl"),this._streaming=!0,r||fTe(this._jsonlPath,"","utf8")}flushProduct(t){if(!this._streaming||!this._jsonlPath)throw new Error("Cannot flushProduct: streaming is not active. Call openStream() first.");KQt(this._jsonlPath,JSON.stringify(t)+` +`,"utf8")}closeStream(){if(!this._streaming||!this._jsonlPath||!this._streamDir)throw new Error("Cannot closeStream: streaming is not active.");let t=pTe(this._streamDir,"products.csv"),r=rRt(this._jsonlPath);return r.length>0&&(this.products=r,this.serialize(t),this.products=[]),this._streaming=!1,t}};function rRt(e){if(!eRt(e))return[];let t=XQt(e,"utf8"),r=[];for(let n of t.split(` +`))if(n.trim())try{r.push(JSON.parse(n))}catch{}return r}St();function nRt(e,t){let r=(e??"").trim();if(!r||r.startsWith("data:"))return null;try{return new URL(r,t).toString()}catch{return null}}function bTe(e){return e.split(",").map(t=>t.trim().split(/\s+/)[0]).filter(Boolean)}function ETe(e,t){let r=le(e),n=new Set,i=s=>{let o=nRt(s,t);o&&n.add(o)};return r("img").each((s,o)=>{i(r(o).attr("src"));for(let a of bTe(r(o).attr("srcset")||""))i(a)}),r("source").each((s,o)=>{for(let a of bTe(r(o).attr("srcset")||""))i(a)}),i(r('meta[property="og:image"]').attr("content")),[...n]}var iRt="Mozilla/5.0 (compatible; DataLiberation/1.0)";async function sRt(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":iRt}});if(t.ok)return await t.text();await t.body?.cancel()}catch{}return""}async function oRt(e,t){let r=await e.newPage();try{return await r.goto(t,{waitUntil:"domcontentloaded",timeout:2e4}),await r.waitForTimeout(800).catch(()=>{}),await r.content()}catch{return""}finally{await r.close().catch(()=>{})}}function aRt(e,t){let r=De(e,"article:published_time");if(r)return r;let n=e.match(/]+datetime=["']([^"']+)["']/i)?.[1];if(n)return n;for(let i of t){let s=i.datePublished;if(typeof s=="string")return s}return""}function cRt(e,t){let r=De(e,"article:author");if(r)return r;for(let n of t){let i=n.author;if(typeof i=="string")return i;if(i&&typeof i=="object"){let s=i.name;if(typeof s=="string")return s}}}function uRt(e,t){let r=QR(t),n=cxe(t),i=lxe(n),s=Oh(t)||er(e),o=De(t,"og:description")||De(t,"description")||"",a=De(t,"og:title")||br(t)||s,c=ETe(t,e),u=dxe(n),l=u?r+` +`+u:r,d="low";return r.length>200?d="high":r.length>50&&(d="medium"),{title:s,slug:er(e),content:l,excerpt:o,date:aRt(t,n),seoTitle:a,seoDescription:o,mediaUrls:c,qualityScore:d,categories:[],tags:[],author:cRt(t,n),detectedType:i,jsonLd:n}}async function CTe(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"",c=s.render!==!1,u=new ei;a&&!s.dryRun&&u.openStream(a);let l=null,d=null;if(c)try{l=(await Ec({cdpPort:s.cdpPort})).browser,d=l.contexts()[0]||await l.newContext()}catch{l=null,d=null}try{let f=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:u,onPageExtracted:s.onPageExtracted,extractPage:async p=>{let h=d?await oRt(d,p):"";return h||(h=await sRt(p)),uRt(p,h)}});return f.productsExtracted>0&&a&&!s.dryRun&&(u.isStreaming?u.closeStream():u.serialize(a+"/products.csv")),f}finally{await l?.close().catch(()=>{})}}function lRt(e){return!1}var ITe={id:"default",detect:lRt,discover:uTe,extract:CTe};ki();async function dRt(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});return t.ok?await t.text():(await t.body?.cancel(),"")}catch{return""}}async function fRt(e){let t=e.includes("://")?e:`https://${e}`,r=new URL(t).origin,n=[],i=new Set,s=[{path:"/sitemap.website.xml",type:"page"},{path:"/sitemap.blog.xml",type:"post"}];for(let{path:o,type:a}of s){let c=await dRt(`${r}${o}`);if(!c)continue;let u=$b(c);for(let l of u){if(i.has(l))continue;i.add(l);let d=cr(l)==="homepage"?"homepage":a;n.push({url:l,type:d})}}return n}async function wTe(e,t){let r=e.includes("://")?e:`https://${e}`,n="";try{let h=await fetch(r,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});h.ok?n=await h.text():await h.body?.cancel()}catch{}let i=De(n,"og:title"),s=De(n,"og:description"),a=De(n,"og:site_name")||i||br(n)||"Imported Site",c=s||De(n,"description")||"",l=n.match(/]+lang=["']([^"']+)["']/i)?.[1]||"en-US",d=Bs(n,r),f=await fRt(r);f.length===0&&f.push({url:r,type:"homepage"});let p={};for(let h of f)p[h.type]=(p[h.type]||0)+1;return{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:a,tagline:c,language:l},navigation:d,counts:p,urls:f}}qi();St();function ul(e){if(!e)return e;let t=e.trim();if(t.startsWith("//")&&(t=`https:${t}`),!/^https?:\/\/img1\.wsimg\.com\/isteam\//i.test(t))return e;let[r]=t.split("/:/");return`${r}/:/rs=w:4000,cg:true`}function STe(e){let t=new Set,r=/https?:\/\/img1\.wsimg\.com\/isteam\/[^\s"'<>)]+/g,n=/\/\/img1\.wsimg\.com\/isteam\/[^\s"'<>)]+/g;for(let o of e.match(r)||[])t.add(o);for(let o of e.match(n)||[])t.add(`https:${o}`);let i=e.match(/]+src=["']([^"']+)["']/gi)||[];for(let o of i){let a=o.match(/src=["']([^"']+)["']/i);if(a?.[1]&&!a[1].startsWith("data:")){let c=a[1].startsWith("//")?`https:${a[1]}`:a[1];c.startsWith("http")&&t.add(c)}}let s=/\.(css|js|json|xml|txt|map|woff2?|ttf|eot|pdf)$/i;return[...t].map(ul).filter(o=>{try{let a=new URL(o);return/\/favicon\//i.test(a.pathname)?!1:/^img1\.wsimg\.com$/i.test(a.hostname)?!0:s.test(a.pathname)?!1:Dr.test(a.pathname)}catch{return!1}})}function qw(e){return e.replace(/&/g,"&").replace(/"/g,""")}function vTe(e){let t="window._BLOG_DATA=",r=e.indexOf(t);if(r<0)return null;let n=e.indexOf("",r);if(n<0)return null;let i=e.slice(r+t.length,n).trim().replace(/;$/,"");try{return JSON.parse(i)}catch{return null}}function xTe(e){let t=le(e);t("script, style, noscript, link, meta").remove(),t('section[data-aid="HEADER_SECTION"]').remove(),t('header[data-aid="HEADER_WIDGET"]').remove(),t('[data-aid^="FOOTER_"]').remove(),t("footer").remove(),t('[data-aid*="COOKIE"], [data-aid*="HAMBURGER"], [data-aid="NAV_MORE"]').remove(),t('[data-aid$="_SECTION_TITLE_RENDERED"]').first().remove(),t('[data-aid$="_IMAGE_RENDERED0"]').first().remove(),t("img, source").each((n,i)=>{let s=t(i),o=s.attr("src");o&&!o.startsWith("data:")&&s.attr("src",ul(o));let a=s.attr("data-srclazy");if(a){let c=ul(a);s.attr("data-srclazy",c),(!o||o.startsWith("data:"))&&s.attr("src",c)}s.removeAttr("srcset"),s.removeAttr("data-srcsetlazy")}),t("source").remove();let r=t("main").first();return r.length&&r.text().trim().length>50?r.html()?.trim()||"":t("body").html()?.trim()||""}function D7(e){let t=le(e),r=t('section[data-aid="HEADER_SECTION"]'),n=new Set(r.find("h1, h2").toArray()),i=t("h1").toArray().find(o=>!n.has(o));if(i){let o=t(i).text().trim();if(o)return o}let s=t("h2").toArray().find(o=>!n.has(o));if(s){let o=t(s).text().trim();if(o)return o}return De(e,"og:title")||br(e)}var BTe={BOLD:"strong",ITALIC:"em",UNDERLINE:"u",STRIKETHROUGH:"s",CODE:"code"};function kTe(e,t){let r=e.text||"";if(!r)return"";let n=e.inlineStyleRanges||[],i=e.entityRanges||[],s=[];for(let d=0;d=h.offset&&d=h.offset&&d{for(;a.length;){let d=a.pop(),f=BTe[d];f&&(o+=``)}if(c!=null){let d=t[String(c)];d&&d.type==="LINK"&&(o+=""),c=null}},l={styles:new Set,entity:null};for(let d=0;dl.styles.has(A)),h=f.entityKey===l.entity;if(!p||!h){if(u(),f.entityKey!=null){let A=t[String(f.entityKey)];if(A&&A.type==="LINK"){let g=qw(String(A.data?.href||"#")),m=A.data?.target?` target="${qw(String(A.data.target))}"`:"";o+=``,c=f.entityKey}}for(let A of f.styles){let g=BTe[A];g&&(o+=`<${g}>`,a.push(A))}l.styles=new Set(f.styles),l.entity=f.entityKey}o+=ws(f.char)}return u(),o}function pRt(e,t){let r=e.entityRanges||[];if(r.length===0)return"";let n=t[String(r[0].key)];if(!n||n.type!=="IMAGE")return"";let i=ul(String(n.data?.src||"")),s=qw(String(n.data?.alt||""));return`
${s}
`}function _Te(e){let t=e.blocks||[],r=e.entityMap||{},n=[],i=null,s=()=>{i&&(n.push(``),i=null)};for(let o of t){let a=o.type||"unstyled",c=a==="unordered-list-item";if(c||a==="ordered-list-item"){let d=c?"ul":"ol";i!==d&&(s(),n.push(`<${d}>`),i=d),n.push(`
  • ${kTe(o,r)}
  • `);continue}if(s(),a==="atomic"){let d=pRt(o,r);d&&n.push(d);continue}let l=kTe(o,r);if(a==="unstyled")l.trim()&&n.push(`

    ${l}

    `);else if(/^header-(one|two|three|four|five|six)$/.test(a)){let f={"header-one":1,"header-two":2,"header-three":3,"header-four":4,"header-five":5,"header-six":6}[a];n.push(`${l}`)}else a==="blockquote"?n.push(`
    ${l}
    `):a==="code-block"?n.push(`
    ${l}
    `):l.trim()&&n.push(`

    ${l}

    `)}return s(),n.join(` +`)}async function TTe(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"";return mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,onPageExtracted:s.onPageExtracted,extractPage:async c=>{let u="";try{let D=await fetch(c,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});D.ok?u=await D.text():await D.body?.cancel()}catch{}let d=vTe(u)?.post,f,p,h,A=[],g;if(d&&typeof d.fullContent=="string"){try{let D=JSON.parse(d.fullContent),_=d.featuredImage||"";if(_&&D.blocks?.length){let v=D.blocks[0];if(v.type==="atomic"&&(v.entityRanges?.length??0)>0){let N=D.entityMap?.[String(v.entityRanges[0].key)];if(N?.type==="IMAGE"){let O=String(N.data?.src||"");O.startsWith("//")&&(O=`https:${O}`);let S=w=>w.replace(/^https?:/,"").split("?")[0];S(O)===S(_)&&(D.blocks=D.blocks.slice(1))}}}f=_Te(D)}catch{f=d.content?`

    ${ws(d.content)}

    `:""}p=d.title||D7(u)||er(c),h=d.publishedDate||d.date||"",A=Array.isArray(d.categories)?d.categories:[],g="post"}else{f=xTe(u),p=D7(u)||er(c);let D=De(u,"article:published_time"),_=u.match(/]+datetime=["']([^"']+)["']/i)?.[1];h=D||_||""}let m=d?.content&&d.content.replace(/\.{3}$/,"").trim()||De(u,"og:description")||De(u,"description")||"",b=De(u,"og:title")||br(u)||p,E=m,C=De(u,"author")||void 0,I=STe(u);if(f){let D=f.match(/https?:\/\/img1\.wsimg\.com\/isteam\/[^\s"'<>)]+/g)||[];for(let _ of D)I.includes(_)||I.push(_)}if(d?.featuredImage){let D=ul(d.featuredImage);I.includes(D)||I.push(D)}let T=De(u,"og:image");if(T&&T.startsWith("http")){let D=ul(T);if(!I.includes(D))try{let _=new URL(D);(/^img1\.wsimg\.com$/i.test(_.hostname)||Dr.test(_.pathname))&&I.push(D)}catch{}}let k="low";return f.length>500?k="high":f.length>100&&(k="medium"),{title:p,slug:er(c),content:f,excerpt:m,date:h,seoTitle:b,seoDescription:E,mediaUrls:I,qualityScore:k,categories:A,tags:[],author:C,detectedType:g}}})}var QTe={id:"godaddy-wm",detect(e){return!1},discover:wTe,extract:TTe};ki();async function RTe(e,t){let r="";try{let h=e.includes("://")?e:`https://${e}`,A=await fetch(h,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});A.ok?r=await A.text():await A.body?.cancel()}catch{}let n=De(r,"og:title"),i=De(r,"og:description"),s=n||br(r)||"Imported Site",o=i||De(r,"description")||"",c=r.match(/]+lang=["']([^"']+)["']/i)?.[1]||"en-US",u=await ii(e),l=e.includes("://")?e:`https://${e}`,d=Bs(r,l),f={},p=[];for(let h of u){let A=cr(h);A==="page"&&/\/blog-post|\/blog\//.test(h)&&(A="post"),p.push({url:h,type:A}),f[A]=(f[A]||0)+1}return p.length===0&&(p.push({url:l,type:"homepage"}),f.homepage=1),{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:s,tagline:o,language:c},navigation:d,counts:f,urls:p}}qi();function DTe(e){let t=[],r=/]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi,n;for(;(n=r.exec(e))!==null;)try{let i=JSON.parse(n[1].trim());if(Array.isArray(i))for(let s of i)s&&typeof s=="object"&&t.push(s);else i&&typeof i=="object"&&t.push(i)}catch{}return t}function N7(e,t){for(let r of e){let n=r["@type"];if(typeof n=="string"&&t.test(n)||Array.isArray(n)&&n.some(i=>typeof i=="string"&&t.test(i)))return r}return null}function NTe(e,t){let r=typeof e.name=="string"?e.name:"";if(!r)return null;let i=(Array.isArray(e.offers)?e.offers:e.offers&&typeof e.offers=="object"?[e.offers]:[])[0],s=i?.price!=null?String(i.price):"",o=typeof i?.availability=="string"?i.availability:"",a=[];if(typeof e.image=="string")a.push(e.image);else if(Array.isArray(e.image))for(let c of e.image)typeof c=="string"?a.push(c):c&&typeof c=="object"&&typeof c.url=="string"&&a.push(c.url);return{name:r,type:"simple",description:typeof e.description=="string"?e.description:"",regularPrice:s,sku:typeof e.sku=="string"?e.sku:"",images:a,inStock:o?/InStock/i.test(o):!0,sourceUrl:t}}var MTe=/\b(block-sticky-bar|block-header|block--footer|block-header-cart|block-header-item|block-blog-header)\b/,hRt=/]*\bclass=["'][^"']*\b(block-sticky-bar|block-header|block--footer|block-blog-header)\b[^"']*["'][^>]*>[\s\S]*?<\/section>/gi,ARt=[/]*>[\s\S]*?<\/nav>/gi,/]*>[\s\S]*?<\/header>/gi,/]*>[\s\S]*?<\/footer>/gi];function M7(e){let t=e;for(let r of ARt)t=t.replace(r,"");return t.replace(hRt,"")}function PTe(e){let t=/]*\bclass=["']([^"']*)["'][^>]*>([\s\S]*?)<\/section>/gi,r=[],n;for(;(n=t.exec(e))!==null;){let a=n[1],c=n[2];/\bblock\b/.test(a)&&(MTe.test(a)||c.trim()&&r.push(c.trim()))}if(r.length>0)return r.join(` + +`);let i=e.match(/]*>([\s\S]*?)<\/article>/i);if(i?.[1]?.trim())return i[1].trim();let s=e.match(/]*>([\s\S]*?)<\/main>/i);if(s?.[1]?.trim())return M7(s[1]).trim();let o=e.match(/]*>([\s\S]*?)<\/body>/i);return o?.[1]?M7(o[1]).trim():""}function LTe(e){let t=e.match(/]*>([\s\S]*?)<\/h1>/i)?.[1]?.replace(/<[^>]*>/g,"").trim();if(t)return t;let r=De(e,"og:title");return r||br(e)}function FTe(e,t){if(!t)return e;let r=i=>i.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim().toLowerCase(),n=r(t);return n?e.replace(/]*>([\s\S]*?)<\/h1>/i,(i,s)=>r(s)===n?"":i):e}function OTe(e,t){let r;try{r=new URL(t.includes("://")?t:`https://${t}`).origin}catch{return e}return e.replace(/(src|href)=["'](\/[^"']+)["']/gi,(n,i,s)=>`${i}="${r}${s}"`)}function UTe(e){let t=new Set,r=/https?:\/\/[^\s"'<>)]*zyrosite\.com\/[^\s"'<>)]+/g,n=e.match(r)||[];for(let o of n){let a=o.replace(/(https?:\/\/[^/]+\/cdn-cgi\/image\/[^/]+\/)(.+)/,(c,u,l)=>`https://assets.zyrosite.com/${l}`);t.add(a)}let i=e.match(/]+src=["']([^"']+)["']/gi)||[];for(let o of i){let a=o.match(/src=["']([^"']+)["']/i);a?.[1]&&a[1].startsWith("http")&&t.add(a[1])}let s=/\.(css|js|json|xml|txt|map|woff2?|ttf|eot|pdf)$/i;return[...t].filter(o=>{try{let a=new URL(o);return s.test(a.pathname)?!1:/zyrosite\.com/i.test(a.hostname)?!0:Dr.test(a.pathname)}catch{return!1}})}async function $Te(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"",c=new ei;a&&!s.dryRun&&c.openStream(a);let u=new Map,l=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:c,onPageExtracted:s.onPageExtracted,extractPage:async d=>{let f=await fetch(d,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});if(!f.ok)throw await f.body?.cancel(),new Error(`HTTP ${f.status} ${f.statusText}`);let p=await f.text(),h=DTe(p),A=N7(h,/^(Article|BlogPosting|NewsArticle)$/),g=N7(h,/^Product$/),m=!!g||/class=["'][^"']*\bblock-product(?:-wrapper)?\b/.test(p);if(m&&g){let U=NTe(g,d);U&&u.set(d,U)}let b=A?.headline||LTe(p)||er(d),E=OTe(FTe(PTe(p),b),d),C=De(p,"og:description")||De(p,"description")||"",I=De(p,"og:title")||br(p)||b,T=C,k=A?.datePublished||"";if(k||(k=De(p,"article:published_time")||""),!k){let U=p.match(/]+datetime=["']([^"']+)["']/i)?.[1];U&&(k=U)}let D=[],_=A?.articleSection;typeof _=="string"?D=[_]:Array.isArray(_)&&(D=_.filter(U=>typeof U=="string"));let v,N=A?.author;if(N&&typeof N=="object")if(Array.isArray(N)){let U=N[0];U&&typeof U=="object"&&typeof U.name=="string"&&(v=U.name)}else typeof N.name=="string"&&(v=N.name);let O=UTe(p),S=De(p,"og:image");if(S&&S.startsWith("http")&&!O.includes(S))try{let U=new URL(S);(Dr.test(U.pathname)||/zyrosite\.com/i.test(U.hostname))&&O.push(S)}catch{}let w=E.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim(),R="low";return w.length>200?R="high":w.length>50&&(R="medium"),{title:b,slug:er(d),content:E,excerpt:C,date:k,seoTitle:I,seoDescription:T,mediaUrls:O,qualityScore:R,categories:D,tags:[],author:v,detectedType:m?"product":void 0}},extractProduct:d=>u.get(d)??null});return l.productsExtracted>0&&a&&!s.dryRun&&(c.isStreaming?c.closeStream():c.serialize(`${a}/products.csv`)),l}function gRt(e){return!1}var HTe={id:"hostinger",detect:gRt,discover:RTe,extract:$Te};St();ki();function _0(e){try{return new URL(e.includes("://")?e:`https://${e}`).origin}catch{return null}}function mD(e,t){return e?e.startsWith("http://")||e.startsWith("https://")?e:e.startsWith("//")?"https:"+e:e.startsWith("/")&&t?t+e:null:null}function yD(e){return!!(/\/(blog|news|insights|articles)\/[^/?#]+/i.test(e)||/\/(resources|updates)\/[^/?#]+\/[^/?#]+/i.test(e))}async function jTe(e,t){let r=e.includes("://")?e:`https://${e}`,n;try{n=await fetch(r,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}})}catch(A){throw new Error(`HubSpot discover(): fetch failed for ${r}: ${A.message}`)}if(!n.ok)throw await n.body?.cancel(),new Error(`HubSpot discover(): HTTP ${n.status} ${n.statusText} for ${r}`);let i;try{i=await n.text()}catch(A){throw await n.body?.cancel().catch(()=>{}),new Error(`HubSpot discover(): failed reading body of ${r}: ${A.message}`)}i.length>5242880&&(i=i.slice(0,5242880));let s=le(i),o=De(i,"og:title"),a=De(i,"og:description"),c=o||br(i)||"Imported Site",u=a||De(i,"description")||"",l=s("html").attr("lang")||"en-US",d=await ii(e),f=Bs(i,r),p={},h=[];for(let A of d){let g=cr(A);g==="page"&&yD(A)&&(g="post"),h.push({url:A,type:g}),p[g]=(p[g]||0)+1}return h.length===0&&(h.push({url:r,type:"homepage"}),p.homepage=1),{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:c,tagline:u,language:l},navigation:f,counts:p,urls:h}}St();qi();var P7=/\.(css|js|json|xml|txt|map|woff2?|ttf|eot|otf|pdf|zip|mp4|webm|mov)$/i;function mRt(e){let t=[],r=e.length,n=0;for(;n=r)break;let i=n;for(;n{let o=s.match(/(\d+(?:\.\d+)?)w/);if(o)return parseFloat(o[1]);let a=s.match(/(\d+(?:\.\d+)?)x/);return a?parseFloat(a[1]):0},n=t[t.length-1],i=r(n.descriptor);for(let s of t){let o=r(s.descriptor);o>i&&(n=s,i=o)}return n.url}function qTe(e,t){let r=new Set,n=_0(t),i=s=>{if(!s)return;let o=mD(s,n);o&&r.add(o)};return e("img").each((s,o)=>{let a=e(o);i(a.attr("src")),i(a.attr("data-src"));let c=a.attr("srcset");c&&i(bD(c))}),e("source[srcset]").each((s,o)=>{let a=e(o).attr("srcset")||"";i(bD(a))}),[...r].filter(s=>{try{let o=new URL(s);return P7.test(o.pathname)?!1:Dr.test(o.pathname)?!0:/hubspotusercontent/i.test(o.hostname)||/\/hubfs\//.test(o.pathname)}catch{return!1}})}function zTe(e){let t=[];return e('script[type="application/ld+json"]').each((r,n)=>{let i=e(n).text().trim().replace(/^$/,"").trim();if(!i)return;let s;try{s=JSON.parse(i)}catch{return}let o=Array.isArray(s)?s:[s];for(let a of o){if(!a||typeof a!="object")continue;let c=a,u=c["@graph"];if(Array.isArray(u))for(let l of u)l&&typeof l=="object"&&t.push(l);else t.push(c)}}),t}function VTe(e){let t=e["@type"],r=n=>n==="BlogPosting"||n==="Article"||n==="NewsArticle";return r(t)||Array.isArray(t)&&t.some(r)}function GTe(e,t){let r=e(".blog-post__timestamp").first().text().replace(/\s+/g," ").trim();if(r){let c=new Date(r);if(!isNaN(c.getTime()))return c.toISOString()}let n=e("time[datetime]").first().attr("datetime");if(n)return n;for(let c of zTe(e)){if(!VTe(c))continue;let u=c.datePublished;if(typeof u=="string"&&u)return u}let i=De(t,"article:published_time");if(i)return i;let a=(e(".post-body").first().text()||e("body").first().text()||"").slice(0,500).match(/\b(?:on|posted on|published on|by[^,\n]{1,80},\s*on)\s+([A-Z][a-z]{2,}\s+\d{1,2},\s+\d{4}(?:\s+\d{1,2}:\d{2}(?::\d{2})?\s*[AP]M)?)/);if(a?.[1]){let c=new Date(a[1]);if(!isNaN(c.getTime()))return c.toISOString()}return""}function WTe(e,t){let r=e(".blog-post__author").first().text().replace(/\s+/g," ").trim();if(r)return r;let n=e('a[href*="/author/"]').first().text().trim();if(n)return n;let i=zTe(e);for(let o of i){if(!VTe(o))continue;let a=o.author;if(!a)continue;let c=Array.isArray(a)?a[0]:a;if(c&&typeof c=="object"&&typeof c.name=="string")return c.name}for(let o of i)if(o["@type"]==="Person"&&typeof o.name=="string")return o.name;return De(t,"author")||void 0}function YTe(e){let t=[],r=new Set,n=s=>{let o=s.replace(/\s+/g," ").trim();if(!o)return;let a=o.toLowerCase();r.has(a)||(r.add(a),t.push(o))},i=e(".blog-post__tag-link");return i.length?(i.each((s,o)=>n(e(o).text())),t):(e('a[href*="/topic/"]').each((s,o)=>{let a=e(o).attr("href")||"";/\/topic\/[^/?#]+\/?(?:[?#]|$)/.test(a)&&n(e(o).text())}),t)}St();var yRt=[".hs-cta-wrapper",".hs-cta-node",".hs_cos_wrapper_type_form",".hs_cos_wrapper_type_blog_comments",".addthis_toolbox",".addthis_sharing_toolbox",".blog-post__preheader",".blog-post__summary",".blog-post__timestamp",".blog-post__author",".blog-post__social-sharing",".blog-post__tags",".blog-more",".blog-more-grid",".subscriber-form"].join(", ");function JTe(e){return e(".hs-blog-post").length>0}function ED(e){e.find(yRt).remove()}function ZTe(e){let t=e(".post-body").first();if(t.length){ED(t);let s=t.html();if(s)return s.trim()}let r=e(".body-container").first();if(r.length){r.find("nav, header, footer").remove(),ED(r);let s=r.html();if(s)return s.trim()}let n=e("main").first();if(n.length&&n.text().trim()){ED(n);let s=n.html();if(s)return s.trim()}let i=e("body").first();if(i.length){i.find("nav, header, footer").remove(),ED(i);let s=i.html();if(s)return s.trim()}return""}function KTe(e,t){let r=_0(t),n=r?s=>/^https?:\/\//i.test(s)?s:s.startsWith("//")?"https:"+s:s.startsWith("/")?r+s:s:s=>s,i=le(e,null,!1);return i("img[srcset]").each((s,o)=>{let a=i(o),c=a.attr("srcset")||"",u=bD(c);u&&a.attr("src",u)}),r&&i("[src], [href], [data-src]").each((s,o)=>{let a=i(o);for(let c of["src","href","data-src"]){let u=a.attr(c);u&&a.attr(c,n(u))}}),i("img").removeAttr("srcset").removeAttr("sizes"),i("picture source").remove(),i.html()}function XTe(e,t){if(!t)return;let r=t.replace(/\s+/g," ").trim().toLowerCase();if(!r)return;let n=e("h1").first();if(!n.length)return;n.text().replace(/\s+/g," ").trim().toLowerCase()===r&&n.remove()}async function e2e(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"",c=new ei;a&&!s.dryRun&&c.openStream(a);let u=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:c,onPageExtracted:s.onPageExtracted,extractPage:async l=>{let d=await fetch(l,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});if(!d.ok)throw await d.body?.cancel(),new Error(`HTTP ${d.status} ${d.statusText}`);let f=await d.text();f.length>5242880&&(f=f.slice(0,5242880));let p=le(f),h=JTe(p)||yD(l),A=Oh(f)||er(l),m=p(".blog-post__summary").first().text().replace(/\s+/g," ").trim()||De(f,"og:description")||De(f,"description")||"",b=h?GTe(p,f):"",E=h?WTe(p,f):void 0,C=h?YTe(p):[];XTe(p,A);let I=ZTe(p),T=KTe(I,l),k=De(f,"og:title")||br(f)||A,D=De(f,"og:description")||De(f,"description")||m,_=qTe(p,l),v=De(f,"og:image");if(v&&!_.includes(v)){let S=mD(v,_0(l));if(S)try{let w=new URL(S);!P7.test(w.pathname)&&(Dr.test(w.pathname)||/hubspotusercontent/i.test(w.hostname)||/\/hubfs\//.test(w.pathname))&&_.push(S)}catch{}}let N=T.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim(),O="low";return N.length>200?O="high":N.length>50&&(O="medium"),{title:A,slug:er(l),content:T,excerpt:m,date:b,seoTitle:k,seoDescription:D,mediaUrls:_,qualityScore:O,categories:C,tags:[],author:E,detectedType:h?"post":void 0}}});return u.productsExtracted>0&&a&&!s.dryRun&&(c.isStreaming?c.closeStream():c.serialize(`${a}/products.csv`)),u}function bRt(e){return!1}var t2e={id:"hubspot",detect:bRt,discover:jTe,extract:e2e};var r2e={removeSelectors:["#upCart","#upCartStickyButton",'[class*="kl-teaser"]']};ki();async function L7(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)",Accept:"application/json"}});return t.ok?await t.json():(await t.body?.cancel(),null)}catch{return null}}async function CD(e,t){let r=[],n=1,i=20;for(;n<=i;){let s=e.includes("?")?"&":"?",o=`${e}${s}limit=250&page=${n}`,a=await L7(o);if(!a||!a[t]||a[t].length===0||(r.push(...a[t]),a[t].length<250))break;n++}return r}function F7(e){let t=e.match(/Shopify\.shop\s*=\s*["']([^"']+\.myshopify\.com)["']/i);if(t?.[1])return t[1];let r=e.match(/shopId["']?\s*[:,]\s*\d+[^}]*shop["']?\s*[:,]\s*["']([^"']+\.myshopify\.com)["']/i);if(r?.[1])return r[1];let n=e.match(/"shop"\s*:\s*"([^"]+\.myshopify\.com)"/i);if(n?.[1])return n[1]}function O7(e){let t=0;return e.title.length>0&&(t+=20),e.content.length>200?t+=25:e.content.length>50&&(t+=10),e.images.length>0&&(t+=15),e.hasStructuredData&&(t+=10),e.hasPriceSku&&(t+=10),e.date.length>0&&(t+=10),t>=50?"high":t>=25?"medium":"low"}function i2e(e){let t=c=>c.replace(/<[^>]*>/g,"").trim().length,n=e.match(/]*id="replo-fullpage-element"[^>]*>([\s\S]*?)<\/main>/i);if(n?.[1]&&t(n[1])>=100)return n[1].trim();let i=e.match(/]*class="[^"]*\brte\b[^"]*"[^>]*>/i);if(i){let u=e.indexOf(i[0])+i[0].length,l=1,d=u;for(;d0;){let f=e.indexOf("",d);if(p===-1)break;if(f!==-1&&f=100)return h;break}d=p+6}}}let s=e.match(/]*class="[^"]*alchemy-rte[^"]*"[^>]*>([\s\S]*?)<\/div>/i);if(s?.[1]&&t(s[1])>=100)return s[1].trim();let o=e.match(/]*>([\s\S]*?)<\/article>/i);if(o?.[1]&&t(o[1])>=100)return o[1].trim();let a=e.match(/]*>([\s\S]*?)<\/main>/i);return a?.[1]?.trim()?a[1].trim():""}var ERt=/\.(css|js|mjs|json|xml|txt|map|woff2?|ttf|eot|otf|pdf|zip|mp4|webm|mov|m4v)(?:$|[?#])/i,n2e=/(google-analytics|googletagmanager|facebook\.com\/tr|doubleclick|hotjar|segment\.|cdn\.shopify\.com\/shopifycloud\/(?:web-pixels|consent))/i;function T0(e){let t=new Set,r=n=>{if(!n)return;let i=n.trim();/^https?:\/\//i.test(i)&&t.add(i)};for(let n of e.match(/https?:\/\/cdn\.shopify\.com\/s\/files\/[^\s"'<>)]+/g)||[])r(n);for(let n of e.match(/<(?:img|source)\b[^>]*>/gi)||[]){for(let i of["src","data-src","data-lazy-src","data-original","data-image"]){let s=n.match(new RegExp(`\\b${i}=["']([^"']+)["']`,"i"));r(s?.[1])}for(let i of["srcset","data-srcset"]){let s=n.match(new RegExp(`\\b${i}=["']([^"']+)["']`,"i"));if(s?.[1])for(let o of s[1].split(","))r(o.trim().split(/\s+/)[0])}}for(let n of e.matchAll(/background(?:-image)?\s*:\s*[^;"']*url\((['"]?)([^)'"]+)\1\)/gi))r(n[2]);return[...t].filter(n=>{try{let i=new URL(n);return n2e.test(i.host)||n2e.test(n)||ERt.test(i.pathname)?!1:(Dr.test(i.pathname),!0)}catch{return!1}})}function s2e(e){let t=e.match(/datePublished["']?\s*[:=]\s*["']([^"']+)["']/i)?.[1];if(t)return t;let r=e.match(/]+datetime=["']([^"']+)["']/i)?.[1];if(r)return r;let n=De(e,"article:published_time");return n||""}async function CRt(e,t){let{launchBrowser:r}=await Promise.resolve().then(()=>(zi(),MF)),{page:n,close:i}=await r({cdpPort:e}),s=[],o=new Set;try{let a=n;a.on("response",async c=>{let u=c.url();if(u.includes("admin.shopify.com/api/operations/")&&!(!u.includes("ProductIndex")&&!u.includes("ProductList")))try{let d=(await c.json()).data;if(!d)return;let p=d.filteredProducts?.edges||[];for(let h of p){let A=h.node?.handle;A&&!o.has(A)&&(o.add(A),s.push(A))}}catch{}});try{await a.goto(`${t}/admin/products`,{waitUntil:"networkidle",timeout:3e4})}catch{}for(let c=0;c<5&&(await a.evaluate(()=>window.scrollTo(0,document.body.scrollHeight)),await new Promise(u=>setTimeout(u,2e3)),!(s.length>200));c++);await new Promise(c=>setTimeout(c,1e3))}finally{await i()}return s}async function o2e(e,t){let r=e.includes("://")?e:`https://${e}`,n=new URL(r).origin,i=!1,s=await CD(`${n}/pages.json`,"pages");s.length>0&&(i=!0);let o="";try{let E=await fetch(r,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});E.ok?o=await E.text():await E.body?.cancel()}catch{}let a=De(o,"og:title"),c=De(o,"og:description"),u=a||br(o)||"Imported Site",l=c||De(o,"description")||"",f=o.match(/]+lang=["']([^"']+)["']/i)?.[1]||"en-US",p=Bs(o,n),h=[],A={};if(i){for(let C of s){let I=`${n}/pages/${C.handle}`;h.push({url:I,type:"page"}),A.page=(A.page||0)+1}let E=await CD(`${n}/blogs.json`,"blogs");for(let C of E){let I=await CD(`${n}/blogs/${C.handle}/articles.json`,"articles");for(let T of I){let k=`${n}/blogs/${C.handle}/${T.handle}`;h.push({url:k,type:"post"}),A.post=(A.post||0)+1}}}let g=await ii(r);for(let E of g){if(h.some(I=>I.url===E))continue;let C=cr(E);h.push({url:E,type:C}),A[C]=(A[C]||0)+1}for(let E of p){let C;try{C=new URL(E.href)}catch{continue}if(C.origin!==n)continue;let I=`${C.origin}${C.pathname.replace(/\/+$/,"")}`;if(I===n||I===`${n}/`||h.some(k=>k.url===I||k.url===E.href))continue;let T=cr(I);h.push({url:I,type:T}),A[T]=(A[T]||0)+1}let m=t;if(m.cdpPort)try{let E=await CRt(m.cdpPort,n);for(let C of E){let I=`${n}/products/${C}`;h.some(T=>T.url===I)||(h.push({url:I,type:"product"}),A.product=(A.product||0)+1)}}catch{}h.length===0&&(h.push({url:r,type:"homepage"}),A.homepage=1);let b=F7(o);if(!b){let E=new URL(r).hostname;E.endsWith(".myshopify.com")&&(b=E)}return{siteUrl:e,discoveredAt:new Date().toISOString(),shopDomain:b,siteMeta:{title:u,tagline:l,language:f},navigation:p,counts:A,urls:h,jsonApiAvailable:i}}Ls();var IRt="2025-04",ID=class{endpoint;accessToken;constructor({shopDomain:t,accessToken:r}){let n=t.replace(/^https?:\/\//,"").replace(/\/$/,"");this.endpoint=`https://${n}/admin/api/${IRt}/graphql.json`,this.accessToken=r}async request(t,r={}){let n=await fetch(this.endpoint,{method:"POST",signal:AbortSignal.timeout(3e4),headers:{"Content-Type":"application/json","X-Shopify-Access-Token":this.accessToken,Accept:"application/json"},body:JSON.stringify({query:t,variables:r})});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Shopify GraphQL HTTP ${n.status}: ${s.slice(0,200)}`)}let i=await n.json();if(i.errors&&i.errors.length>0){let s=i.errors.map(o=>o.message).join("; ");throw new Error(`Shopify GraphQL errors: ${s}`)}if(!i.data)throw new Error("Shopify GraphQL: empty data field");return i.data}},wRt=` + query GetShopifyProducts( + $first: Int!, + $after: String, + $query: String, + $variantsFirst: Int = 100 + ) { + products(first: $first, after: $after, query: $query) { + edges { + cursor + node { + id + title + handle + descriptionHtml + status + createdAt + vendor + tags + productType + onlineStoreUrl + options(first: 10) { id name position values } + featuredMedia { + ... on MediaImage { id image { url altText } } + } + media(first: 50) { + edges { node { ... on MediaImage { id image { url altText } } } } + } + variants(first: $variantsFirst) { + edges { + node { + id + sku + price + compareAtPrice + inventoryPolicy + inventoryQuantity + inventoryItem { + tracked + unitCost { amount currencyCode } + measurement { weight { value unit } } + } + media(first: 1) { + edges { node { ... on MediaImage { image { url } } } } + } + selectedOptions { name value } + } + } + } + collections(first: 20) { + edges { node { id handle title } } + } + metafields(first: 20, namespace: "global") { + edges { node { namespace key value } } + } + seo { title description } + } + } + pageInfo { hasNextPage endCursor } + } + } +`;async function a2e(e,{pageSize:t=50,filter:r,session:n,cursorKey:i="shopify:products:endCursor",onBatch:s}={}){let o=!s,a=[],c=n?.getCursor(i)??null,u=1e4,l=0;for(;;){if(++l>u)throw new Error(`Shopify GraphQL pagination exceeded ${u} pages \u2014 aborting`);let d=await e.request(wRt,{first:t,after:c,query:r??null}),p=d.products.edges.map(g=>g.node);o&&a.push(...p),s&&p.length>0&&await s(p);let{hasNextPage:h,endCursor:A}=d.products.pageInfo;if(n&&A&&n.setCursor(i,A),!h||!A)break;if(A===c)throw new Error("Shopify GraphQL pagination cursor did not advance \u2014 aborting");c=A}return n&&n.setCursor(i,null),a}qi();function Vw(e,t){if(e==null||e===0)return;let r=(t||"kg").toLowerCase(),n;switch(r){case"kg":n=e;break;case"g":n=e/1e3;break;case"lb":n=e*.453592;break;case"oz":n=e*.0283495;break;default:n=e}return Number(n.toFixed(4)).toString()}function wD(e,t){let r=e.variants||[],n=e.options||[],i=r.length>1||n.length>0&&n[0]?.name!=="Title",s=new Set;e.image?.src&&s.add(e.image.src);for(let C of e.images||[])s.add(C.src);let o=/src="(https?:\/\/[^"']+\.(jpg|jpeg|png|gif|webp)[^"']*)"/gi,a;for(;(a=o.exec(e.body_html||""))!==null;)s.add(a[1]);let c=[...s],u=r[0],l=e.tags?e.tags.split(",").map(C=>C.trim()).filter(Boolean):[],d=e.product_type?[e.product_type]:[],f=u?.price?Number(u.price):NaN,p=u?.compare_at_price?Number(u.compare_at_price):NaN,h=!i&&Number.isFinite(f)&&Number.isFinite(p)&&p>f,A={name:e.title,type:i?"variable":"simple",sku:i?e.handle||e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-"):u?.sku||"",published:!0,description:e.body_html||"",regularPrice:i?"":h?String(u.compare_at_price):u?.price||"",salePrice:h&&u?.price||void 0,categories:d,tags:l,images:c,inStock:u?.available!==!1,stock:u?.inventory_quantity!=null?u.inventory_quantity:void 0,sourceUrl:t};n.length>0&&(A.attributes=n.map(C=>({name:C.name,values:C.values,visible:!0,global:!1})));let g=Vw(u?.weight,u?.weight_unit);g&&(A.weight=g);let m=new Map,b=new Map;for(let C of e.images||[]){C.id&&m.set(C.id,C.src);for(let I of C.variant_ids||[])b.set(I,C.src)}let E=[];if(i)for(let C of r){let I=C.compare_at_price!=null&&C.compare_at_price!=="",T;C.featured_image?.src?T=C.featured_image.src:C.image_id&&m.has(C.image_id)?T=m.get(C.image_id):C.id&&b.has(C.id)&&(T=b.get(C.id));let k={name:e.title,type:"variation",sku:C.sku||"",parentSku:A.sku,published:!0,description:"",regularPrice:I?String(C.compare_at_price):C.price||"",salePrice:I&&C.price||void 0,inStock:C.available!==!1,stock:C.inventory_quantity!=null?C.inventory_quantity:void 0,...T?{images:[T]}:{}},D=Vw(C.weight,C.weight_unit);D&&(k.weight=D);let _=[];C.option1!=null&&n[0]&&_.push({name:n[0].name,values:[C.option1],visible:!0,global:!1}),C.option2!=null&&n[1]&&_.push({name:n[1].name,values:[C.option2],visible:!0,global:!1}),C.option3!=null&&n[2]&&_.push({name:n[2].name,values:[C.option3],visible:!0,global:!1}),_.length>0&&(k.attributes=_),E.push(k)}return{parent:A,variations:E}}function U7(e,t){let n=(e.variants?.edges||[]).map(_=>_.node),i=e.options||[],s=n.length>1||i.length>0&&i[0]?.name!=="Title",o=new Set;e.featuredMedia?.image?.url&&o.add(e.featuredMedia.image.url);for(let _ of e.media?.edges||[])_.node.image?.url&&o.add(_.node.image.url);let a=/src="(https?:\/\/[^"']+\.(jpg|jpeg|png|gif|webp)[^"']*)"/gi,c;for(;(c=a.exec(e.descriptionHtml||""))!==null;)o.add(c[1]);let u=[...o],l=n[0],d=e.tags||[],f=new Set;for(let _ of e.collections?.edges||[])_.node.title&&f.add(_.node.title);f.size===0&&e.productType&&f.add(e.productType);let p=[...f],h=_=>{let v=_.inventoryItem?.tracked,N=_.inventoryPolicy,O=_.inventoryQuantity;return v?O==null?{inStock:!0,stock:void 0}:O>0?{inStock:!0,stock:O}:{inStock:N==="CONTINUE",stock:O}:{inStock:!0}},A=l?h(l):{inStock:!0},g=l?.price?Number(l.price):NaN,m=l?.compareAtPrice?Number(l.compareAtPrice):NaN,b=!s&&Number.isFinite(g)&&Number.isFinite(m)&&m>g,E={name:e.title,type:s?"variable":"simple",sku:s?e.handle||e.title.toLowerCase().replace(/[^a-z0-9]+/g,"-"):l?.sku||"",published:e.status==="ACTIVE",description:e.descriptionHtml||"",regularPrice:s?"":b?String(l.compareAtPrice):l?.price||"",salePrice:b&&l?.price||void 0,categories:p,tags:d,images:u,inStock:A.inStock,stock:A.stock,sourceUrl:t},C=e.seo?.title||e.metafields?.edges?.find(_=>_.node.key==="title_tag")?.node.value||"",I=e.seo?.description||e.metafields?.edges?.find(_=>_.node.key==="description_tag")?.node.value||"";C&&(E.seoTitle=C),I&&(E.seoDescription=I);let T=l?.inventoryItem?.unitCost?.amount;T&&Number.isFinite(Number(T))&&(E.costOfGoods=T),i.length>0&&(E.attributes=i.map(_=>({name:_.name,values:_.values,visible:!0,global:!1})));let k=Vw(l?.inventoryItem?.measurement?.weight?.value,l?.inventoryItem?.measurement?.weight?.unit);k&&(E.weight=k);let D=[];if(s)for(let _ of n){let v=_.price?Number(_.price):NaN,N=_.compareAtPrice?Number(_.compareAtPrice):NaN,O=Number.isFinite(v)&&Number.isFinite(N)&&N>v,S=_.media?.edges?.[0]?.node?.image?.url,w=h(_),R={name:e.title,type:"variation",sku:_.sku||"",parentSku:E.sku,published:!0,description:"",regularPrice:O?String(_.compareAtPrice):_.price||"",salePrice:O&&_.price||void 0,inStock:w.inStock,stock:w.stock,...S?{images:[S]}:{}},U=Vw(_.inventoryItem?.measurement?.weight?.value,_.inventoryItem?.measurement?.weight?.unit);U&&(R.weight=U);let J=_.inventoryItem?.unitCost?.amount;J&&Number.isFinite(Number(J))&&(R.costOfGoods=J);let X=[];for(let z of _.selectedOptions||[])X.push({name:z.name,values:[z.value],visible:!0,global:!1});X.length>0&&(R.attributes=X),D.push(R)}return{parent:E,variations:D}}function SRt(e,t){let r=e.match(/]+type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)||[];for(let i of r){let s=i.replace(/]*>/i,"").replace(/<\/script>/i,"");try{let o=JSON.parse(s);if(o["@type"]==="Product"&&o.name){let a=Array.isArray(o.offers)?o.offers:o.offers?[o.offers]:[],c=a[0]?.price?String(a[0].price):"",u=[];if(typeof o.image=="string")u.push(o.image);else if(Array.isArray(o.image))for(let l of o.image)typeof l=="string"?u.push(l):l?.url&&u.push(l.url);return{name:o.name,description:o.description||"",regularPrice:c,sku:o.sku||"",images:u,inStock:a[0]?.availability?.includes("InStock")??!0,sourceUrl:t}}}catch{}}let n=e.match(/data-product-json[^>]*>([\s\S]*?)<\/script>/i);if(n?.[1])try{let i=JSON.parse(n[1]);if(i.title)return wD(i,t).parent}catch{}return null}async function c2e(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"",c=a?Uo.loadOrCreate(a,"shopify",s,{resume:!!s.resume}):void 0,u=new ei,l=!1;a&&!s.dryRun&&u.openStream(a,{resume:!!s.resume});let d=new Set;if(s.adminToken&&!s.dryRun){let g=s.shopDomain||i.shopDomain;if(g){if(!g.endsWith(".myshopify.com"))throw new Error(`shopDomain "${g}" must end in .myshopify.com`)}else{let E=new URL(i.siteUrl.includes("://")?i.siteUrl:`https://${i.siteUrl}`).hostname;if(E.endsWith(".myshopify.com"))g=E;else throw new Error(`Shopify GraphQL requires a *.myshopify.com host, but auto-detection failed and siteUrl "${E}" is a custom domain. Pass --shop-domain explicitly, or re-run discover() to refresh inventory.shopDomain.`)}let m=c?.getCursor("shopify:products:emittedHandles")??[];for(let E of m)d.add(E);let b;try{b=new URL(i.siteUrl.includes("://")?i.siteUrl:`https://${i.siteUrl}`).origin}catch{b=`https://${g}`}try{let E=new ID({shopDomain:g,accessToken:s.adminToken});await a2e(E,{session:c,onBatch:C=>{for(let I of C){if(I.handle&&d.has(I.handle))continue;let T=I.handle?`${b}/products/${I.handle}`:void 0,{parent:k,variations:D}=U7(I,T);u.addProduct(k);for(let _ of D)u.addProduct(_);l=!0,I.handle&&d.add(I.handle),c&&c.bumpProgress("product","extracted")}c&&(c.setCursor("shopify:products:emittedHandles",[...d]),c.save())}}),c&&c.setCursor("shopify:products:emittedHandles",null)}catch(E){let C=E instanceof Error?E.message:String(E);n.server?.sendLoggingMessage?.({level:"warning",data:`Shopify GraphQL fetch failed, falling back to JSON API: ${C}`})}}d.size>0&&(i.urls=i.urls.filter(g=>{if(g.type!=="product")return!0;let m=g.url.match(/\/products\/([^/?#]+)/)?.[1];return!m||!d.has(m)}));let f=new Set(i.urls.filter(g=>g.type==="product").map(g=>g.url)),p=null;async function h(){if(!p){let{launchBrowser:g}=await Promise.resolve().then(()=>(zi(),MF)),m=await g(s.cdpPort?{cdpPort:s.cdpPort}:{headed:!0});p={page:m.page,close:()=>m.close()}}return p.page}let A;try{return A=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:u,session:c,onPageExtracted:s.onPageExtracted,extractPage:async g=>{let m="",b="",E="",C="",I=[],T=[],k=[],D=!1,_=!1,v,N,O=f.has(g)||/\/products\//.test(g);try{let X=g.replace(/\/?$/,"")+".json",z=await L7(X);if(z){let W=z.article,ce=z.page,ne=z.product;if(ne?.title){v="product";let{parent:he,variations:q}=wD(ne,g);u.addProduct(he);for(let Te of q)u.addProduct(Te);l=!0,_=!0,m=ne.title,b=ne.body_html||"",I=ne.tags?ne.tags.split(",").map(Te=>Te.trim()).filter(Boolean):[],T=ne.product_type?[ne.product_type]:[],k=he.images?[...he.images]:[],k.push(...T0(b))}else W?.body_html?(m=W.title,b=W.body_html,E=W.summary_html||W.body_html.replace(/<[^>]*>/g,"").slice(0,200),C=W.published_at||"",N=W.author||void 0,I=W.tags?W.tags.split(",").map(he=>he.trim()).filter(Boolean):[],W.image?.src&&k.push(W.image.src),k.push(...T0(b)),D=!0):ce?.body_html&&(m=ce.title,b=ce.body_html,C=ce.published_at||"",N=ce.author||void 0,k.push(...T0(b)),D=!0);D&&b.replace(/<[^>]*>/g,"").trim().length<100&&(D=!1)}}catch{}let S=/\/blogs\//.test(g);if(!D||S){let X="",z=!1;try{let W=await fetch(g,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});W.ok?(X=await W.text(),X.includes("Just a moment...")&&X.includes("cf_chl_opt")&&(X="",z=!0)):(await W.body?.cancel(),W.status===403&&(z=!0))}catch{}if(z&&!X)try{let W=await h();await W.goto(g,{waitUntil:"networkidle",timeout:3e4}),X=await W.content()}catch{}if(!D){if(!_){let ne=SRt(X,g);ne&&(v="product",u.addProduct(ne),l=!0)}let W=i2e(X);W.replace(/<[^>]*>/g,"").trim().length>b.replace(/<[^>]*>/g,"").trim().length&&(b=W),m||(m=Oh(X)||""),E||(E=De(X,"og:description")||De(X,"description")||""),C||(C=s2e(X));let ce=T0(X);for(let ne of ce)k.includes(ne)||k.push(ne)}if(X){let W=De(X,"og:image");if(W&&W.startsWith("http")&&!k.includes(W))try{Dr.test(new URL(W).pathname)&&k.unshift(W)}catch{}}}m||(m=er(g));let R=m,U=E;k=[...new Set(k)];let J=O7({title:m,content:b,images:k,date:C,hasStructuredData:D,hasPriceSku:v==="product"});return{title:m,slug:er(g),content:b,excerpt:E,date:C,seoTitle:R,seoDescription:U,mediaUrls:k,qualityScore:J,categories:T,tags:I,detectedType:v,author:N}}}),l&&a&&!s.dryRun&&(u.isStreaming?u.closeStream():u.serialize(`${a}/products.csv`)),c&&c.complete(),A}catch(g){if(c)try{c.setStage("error",g instanceof Error?g.message:String(g))}catch{}throw g}finally{p&&await p.close()}}function vRt(e){return/myshopify\.com|shopify\.com/i.test(e)}var u2e={id:"shopify",capture:r2e,detect:vRt,discover:o2e,extract:c2e};ki();async function Gw(e){try{let t=e.includes("?")?"&":"?",r=`${e}${t}format=json`,n=await fetch(r,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});return n.ok?await n.json():null}catch{return null}}function $7(e,t){let r=new Set;t&&r.add(t);let n=/https?:\/\/images\.squarespace-cdn\.com\/content\/[^\s"'<>)]+/g,i=e.match(n)||[];for(let l of i)r.add(l);let s=/https?:\/\/static1?\.squarespace\.com\/static\/[^\s"'<>)]+/g,o=e.match(s)||[];for(let l of o)r.add(l);let a=e.match(/]+src=["']([^"']+)["']/gi)||[];for(let l of a){let d=l.match(/src=["']([^"']+)["']/i);d?.[1]&&d[1].startsWith("http")&&r.add(d[1])}let c=Dr,u=/squarespace-cdn\.com|squarespace\.com\/static/i;return[...r].filter(l=>{try{let d=new URL(l);return c.test(d.pathname)||u.test(d.hostname+d.pathname)}catch{return!1}})}function l2e(e){return e?new Date(e).toISOString():new Date().toISOString()}async function d2e(e,t){let r=e;await r.goto(t,{waitUntil:"domcontentloaded",timeout:45e3});try{await r.waitForLoadState("networkidle",{timeout:1e4})}catch{}let n=await r.title().catch(()=>""),i=await r.evaluate(()=>{let a=[...(document.querySelector("main")||document.querySelector('[role="main"]')||document.body).querySelectorAll("h1, h2, h3, h4, h5, h6, p, li, img, blockquote, figcaption")],c=[],u=[],l=new Set;for(let d of a.slice(0,250)){if(d.tagName==="IMG"){let h=d.src,A=d.alt||"";h&&h.startsWith("http")&&(u.push(h),l.has(h)||(l.add(h),c.push(`${A}`)));continue}let f=d.innerText?.trim();if(!f||l.has(f)||["Skip to Content","SKIP TO CONTENT"].includes(f))continue;l.add(f);let p=d.tagName.toLowerCase();p.startsWith("h")?c.push(`<${p}>${f}`):p==="li"?c.push(`
  • ${f}
  • `):p==="blockquote"?c.push(`
    ${f}
    `):p==="figcaption"?c.push(`
    ${f}
    `):c.push(`

    ${f}

    `)}return{blocks:c,mediaUrls:u}}),s=i.blocks.join(` +`);if(!s)try{let o=await r.context().newCDPSession(e),a=await o.send("Accessibility.getFullAXTree",{depth:10}),c=[];for(let u of a.nodes||[]){let l=u.role?.value||"",d=u.name?.value||"";d&&(l==="heading"?c.push(`

    ${d}

    `):["paragraph","StaticText"].includes(l)&&c.push(`

    ${d}

    `))}s=c.join(` +`),await o.detach()}catch{}return{content:s,mediaUrls:i.mediaUrls,title:n}}zi();var f2e={1:"index",2:"gallery",5:"album",6:"blog",7:"events",8:"product",10:"page",11:"portfolio"};function xRt(e,t){if(typeof e=="number"&&f2e[e])return f2e[e];if(typeof e=="string"){let n=e.toLowerCase();return n.startsWith("blog")?"post":n.startsWith("gallery")||n.startsWith("portfolio")?"gallery":n.startsWith("events")?"event":n.startsWith("products")?"product":n.startsWith("index")||n.startsWith("folder")?"page":n}let r=t.toLowerCase();return r.includes("/blog")||r.includes("/post")?"post":r.includes("/gallery")||r.includes("/portfolio")?"gallery":r.includes("/store")||r.includes("/product")?"product":r.includes("/event")?"event":r==="/"?"homepage":"page"}function BRt(e){if(e.assetUrl||e.scriptUrl||e.mimeType||e.contentType)return!1;let t=!!(e.fullUrl||e.publicUrl||e.pageUrl||e.path||e.url||e.href||e.slug),r=!!(e.title||e.navigationTitle||e.name),n=!!(e.id||e.pageId||e.collectionId);return t&&(r||n)}function p2e(e,t,r){let n=new Map,i=new WeakSet;function s(a){if(!a||typeof a!="string")return null;let c=a.trim();if(!c||c.includes("/config/pages"))return null;try{let u=new URL(c,t);return u.host!==r||/^\/(api|scripts|assets|styles|fonts|static)\//.test(u.pathname)||/\.(jpg|jpeg|png|gif|webp|svg|avif|ico|js|css|map|json|txt|xml|pdf|woff2?|ttf|eot)$/i.test(u.pathname)?null:(u.hash="",u.toString())}catch{return null}}function o(a){if(!a||typeof a!="object"||i.has(a))return;if(i.add(a),Array.isArray(a)){for(let u of a)o(u);return}let c=a;if(BRt(c)){let u=s(c.fullUrl||c.publicUrl||c.pageUrl||c.path||c.url||c.href||c.slug);if(u){let l=c.navigationTitle||c.title||c.name||new URL(u).pathname,d=c.pageId||c.collectionId||c.id,f=c.published===!1?"draft":c.showInNavigation===!1||c.navigationHidden||c.unlinked?"unlinked":c.passwordProtected?"password-protected":"published";n.set(u,{url:u,title:l,type:xRt(c.typeName||c.pageType||c.type||c.collectionType,new URL(u).pathname),visibility:f,adminPageId:d?String(d):null})}}for(let u of Object.values(c))o(u)}return o(e),[...n.values()]}async function h2e(e,t){let r=new URL(e).origin,n=new URL(e).host,s=await(await hs()).chromium.connectOverCDP(`http://127.0.0.1:${t}`);try{let o=s.contexts()[0]||await s.newContext(),c=o.pages().find(h=>h.url().includes("/config"));c||(c=await o.newPage());let u=[],l=async h=>{let A=h,g=A.url();if(!(!(A.headers()["content-type"]||"").includes("application/json")||!(g.includes("/api/")||g.includes("/api/content/")||g.includes("/api/commondata/"))))try{u.push({url:g,data:await A.json()})}catch{}};c.on("response",l);try{await c.goto(`${r}/config/pages`,{waitUntil:"domcontentloaded",timeout:45e3}),await new Promise(h=>setTimeout(h,3e3)),await c.waitForLoadState("networkidle",{timeout:1e4}).catch(()=>{}),await new Promise(h=>setTimeout(h,1e3))}catch{}c.off("response",l);let d=null;try{d=await c.evaluate(()=>window.__NEXT_DATA__||null)}catch{}let f=[...p2e(u.map(h=>h.data),r,n),...p2e(d,r,n)],p=new Map;for(let h of f)p.set(h.url,h);return[...p.values()]}finally{await s.close()}}function A2e(e,t){if(t.length===0)return e;let r=new Map;for(let a of e.urls)r.set(a.url,{...a});for(let a of t){let c=r.get(a.url);c?(a.type&&a.type!=="page"&&(c.type=a.type),c.visibility=a.visibility):r.set(a.url,{url:a.url,type:a.type||"page",visibility:a.visibility})}let n=new Set(e.navigation.map(a=>a.href)),i=[...e.navigation];for(let a of t)a.visibility!=="published"||n.has(a.url)||(i.push({text:a.title,href:a.url}),n.add(a.url));let s={},o=[];for(let a of r.values())o.push(a),s[a.type]=(s[a.type]||0)+1;return{...e,navigation:i,counts:s,urls:o}}async function g2e(e,t){let r=t,n=await Gw(e),i=n?.website?.siteTitle||n?.websiteSettings?.siteTitle||"Imported Site",s=n?.website?.siteTagLine||n?.websiteSettings?.siteTagLine||n?.website?.siteDescription||"",o=n?.website?.language||"en-US",a=await ii(e),c=[],u={},l=[];for(let f of a){let p=cr(f);l.push({url:f,type:p}),u[p]=(u[p]||0)+1}if(l.length===0&&n?.items){let f=new URL(e).origin;for(let p of n.items)if(p.fullUrl){let h=p.fullUrl.startsWith("http")?p.fullUrl:`${f}${p.fullUrl}`,A=cr(h);l.push({url:h,type:A}),u[A]=(u[A]||0)+1}}l.length===0&&(l.push({url:e,type:"homepage"}),u.homepage=1);let d={siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:i,tagline:s,language:o},navigation:c,counts:u,urls:l};if(r.cdpPort)try{let f=await h2e(e,r.cdpPort);f.length>0&&(d=A2e(d,f))}catch(f){let p=f instanceof Error?f.message:String(f);d.adminWarning=`Squarespace admin discovery failed: ${p}. Drafts, unlisted pages, and password-protected content may be missing. Make sure you are logged in to Squarespace admin in the Chrome window connected via CDP.`}return d}ki();qi();zi();async function kRt(e){let r=(await Gw(e))?.item;if(!r)return null;let n=r.structuredContent;if(!n)return null;let i=n.priceMoney,s=n.salePriceMoney,o=n.onSale,a=n.variants||[],c=[],u=r.items;if(u)for(let A of u)A.assetUrl&&c.push(A.assetUrl);r.assetUrl&&!c.includes(r.assetUrl)&&c.unshift(r.assetUrl);let l=a.length>1,d=i?.value||"",f=o&&s?.value&&s.value!=="0.00"?s.value:void 0,p={name:r.title||"",type:l?"variable":"simple",sku:l?"":a[0]?.sku||"",published:!0,description:r.body||"",regularPrice:l?"":d,salePrice:l?void 0:f,images:c,categories:r.categories||[],tags:r.tags||[],sourceUrl:e},h=n.variantOptionOrdering||[];if(h.length>0&&l){let A=new Map;for(let g of h)A.set(g,new Set);for(let g of a)for(let m of g.optionValues||[])m.optionName&&m.value&&A.get(m.optionName)?.add(m.value);p.attributes=h.map(g=>({name:g,values:[...A.get(g)||[]],visible:!0,global:!1}))}return p}async function m2e(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=null;async function c(){if(!a){let d=await Ec({cdpPort:s.cdpPort});a={page:d.page,close:()=>d.close()}}return a.page}let u=s.outputDir||"",l=new ei;u&&!s.dryRun&&l.openStream(u);try{let d=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:u,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:l,onPageExtracted:s.onPageExtracted,extractPage:async p=>{let h=await Gw(p),A=h?.item,g=h?.collection,m=A?.body||g?.mainContent||"",b=A?.title||g?.title||er(p),E=A?.excerpt||g?.description||"",C=l2e(A?.publishOn||A?.addedOn),I=A?.seoData?.seoTitle||b,T=A?.seoData?.seoDescription||E,k=A?.categories||[],D=A?.tags||[],_=$7(m,A?.assetUrl),v=m.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();if(!m||m.includes("columns-12 empty")||v.length<50)try{let R=await c(),U=await d2e(R,p);U.content&&(m=U.content,_=[..._,...$7(U.content),...U.mediaUrls],_=[...new Set(_)]),U.title&&b===er(p)&&(b=U.title)}catch{}let O=m.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim(),S="low";O.length>200?S="high":O.length>50&&(S="medium");let w=A?.author?.displayName||void 0;return{title:b,slug:er(p),content:m,excerpt:E,date:C,seoTitle:I,seoDescription:T,mediaUrls:_,qualityScore:S,categories:k,tags:D,author:w}},extractProduct:(p,h)=>null}),f=i.urls.filter(p=>cr(p.url)==="product");for(let p of f){if(s.dryRun)break;try{let h=await kRt(p.url);h&&h.name&&(l.addProduct(h),d.productsExtracted++)}catch{}}return d.productsExtracted>0&&u&&!s.dryRun&&(l.isStreaming?l.closeStream():l.serialize(`${u}/products.csv`)),d}finally{a&&await a.close()}}St();pi();Yp();var _Rt=/\bsqs-block\b/;function TRt(e,t){if(!e||!_Rt.test(e))return null;let r=le(e,null,!1),n=[];return r(".sqs-block").each((i,s)=>{let o=r(s);if(o.parents(".sqs-block").length>0)return;let a=QRt(r,o);a&&n.push(a)}),n.length===0?null:n.join(` + +`)}function QRt(e,t){let r=t.attr("class")||"";return/\bimage-block\b/.test(r)?DRt(e,t):/\bgallery-block\b/.test(r)?NRt(e,t):/\b(?:embed-block|video-block)\b/.test(r)?MRt(e,t):/\bquote-block\b/.test(r)?PRt(e,t):/\b(?:horizontal-rule-block|line-block)\b/.test(r)?` +
    +`:/\bspacer-block\b/.test(r)?null:/\bhtml-block\b/.test(r)?LRt(e,t):FRt(e,t)}function RRt(e){let t=e.find("img").first();if(t.length===0)return null;let r=t.attr("data-image")||t.attr("data-src")||"",n=/^https?:\/\//.test(r)?r:t.attr("src")||"";if(!n)return null;let i=(t.attr("alt")||"").trim(),s=e.find("figcaption, .image-caption-wrapper").first(),o=s.length?s.text().trim():"";return{src:n,alt:i,caption:o}}function DRt(e,t){let r=RRt(t);return r?` +${r.caption?`
    ${Uh(r.alt)}
    ${ts(r.caption)}
    `:`
    ${Uh(r.alt)}
    `} +`:null}function NRt(e,t){let r=[];if(t.find("img").each((i,s)=>{let o=e(s),a=o.attr("data-image")||o.attr("data-src")||"",c=/^https?:\/\//.test(a)?a:o.attr("src")||"";c&&r.push({src:c,alt:(o.attr("alt")||"").trim()})}),r.length===0)return null;let n=[];for(let i of r)n.push(` +
    ${Uh(i.alt)}
    +`);return` + +`}function MRt(e,t){let n=t.find("iframe").first().attr("src")||t.find("a[href]").first().attr("href")||"";return/^https?:\/\//.test(n)?jQ(n):null}function PRt(e,t){let r=t.find("blockquote, .quote-content, p").first().text().trim();if(!r)return null;let n=t.find("cite, .source").first().text().trim();return` +${n?`

    ${ts(r)}

    ${ts(n)}
    `:`

    ${ts(r)}

    `} +`}function LRt(e,t){let r=t.find(".html-block-html").first().length?t.find(".html-block-html").first():t,n=[];if(r.children().each((i,s)=>{let o=(s.tagName||"").toLowerCase(),a=e(s);if(/^h[1-6]$/.test(o)){let c=parseInt(o.slice(1),10),u=a.html()||"";n.push(` +<${o}>${u} +`)}else if(o==="ul"||o==="ol"){let c=o==="ol",u=[];a.children("li").each((f,p)=>{u.push(` +
  • ${e(p).html()||""}
  • +`)});let l=c?"
      ":"
        ",d=c?"
    ":"";n.push(` +${l} +${u.join(` +`)} +${d} +`)}else if(o==="blockquote")n.push(` +
    ${a.html()||""}
    +`);else if(o==="hr")n.push(` +
    +`);else if(o==="p"){let c=(a.html()||"").trim();c&&n.push(` +

    ${c}

    +`)}else n.push(`${Wp} +${da(e.html(s))} +`)}),n.length===0){let i=r.text().trim();i&&n.push(` +

    ${ts(i)}

    +`)}return n.length?n.join(` + +`):null}function FRt(e,t){let r=e.html(t);return r.trim()?`${Wp} +${da(r)} +`:null}function Uh(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}var y2e={htmlToBlocks:TRt};function ORt(e){return/squarespace\.com/i.test(e)}var b2e={id:"squarespace",detect:ORt,discover:g2e,extract:m2e,blocks:y2e};ki();async function E2e(e,t){let r="";try{let h=e.includes("://")?e:`https://${e}`,A=await fetch(h,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});A.ok?r=await A.text():await A.body?.cancel()}catch{}let n=De(r,"og:title"),i=De(r,"og:description"),s=n||br(r)||"Imported Site",o=i||De(r,"description")||"",c=r.match(/]+lang=["']([^"']+)["']/i)?.[1]||"en-US",u=await ii(e),l=e.includes("://")?e:`https://${e}`,d=Bs(r,l),f={},p=[];for(let h of u){let A=cr(h);p.push({url:h,type:A}),f[A]=(f[A]||0)+1}return p.length===0&&(p.push({url:l,type:"homepage"}),f.homepage=1),{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:s,tagline:o,language:c},navigation:d,counts:f,urls:p}}qi();function URt(e){let t=e.match(/]*class="[^"]*w-richtext[^"]*"[^>]*>/i);if(t){let s=e.indexOf(t[0])+t[0].length,o=1,a=s;for(;a0;){let c=e.indexOf("",a);if(u===-1)break;if(c!==-1&&c]*>([\s\S]*?)<\/article>/i);if(r?.[1]?.trim())return r[1].trim();let n=e.match(/]*>([\s\S]*?)<\/main>/i);return n?.[1]?.trim()?n[1].trim():""}function $Rt(e){let t=e.match(/]*>([\s\S]*?)<\/h1>/i)?.[1]?.replace(/<[^>]*>/g,"").trim();if(t)return t;let r=e.match(/]*>([\s\S]*?)<\/h2>/i)?.[1]?.replace(/<[^>]*>/g,"").trim();return r||br(e)}function HRt(e){let t=new Set,r=/https?:\/\/cdn\.prod\.website-files\.com\/[^\s"'<>)]+/g,n=e.match(r)||[];for(let u of n)t.add(u);let i=/https?:\/\/[^\s"'<>)]*website-files\.com\/[^\s"'<>)]+/g,s=e.match(i)||[];for(let u of s)t.add(u);let o=e.match(/]+src=["']([^"']+)["']/gi)||[];for(let u of o){let l=u.match(/src=["']([^"']+)["']/i);l?.[1]&&l[1].startsWith("http")&&t.add(l[1])}let a=Dr,c=/\.(css|js|json|xml|txt|map|woff2?|ttf|eot|pdf)$/i;return[...t].filter(u=>{try{let l=new URL(u);return c.test(l.pathname)?!1:a.test(l.pathname)}catch{return!1}})}async function C2e(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"",c=new ei;a&&!s.dryRun&&c.openStream(a);let u=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:c,onPageExtracted:s.onPageExtracted,extractPage:async l=>{let d="";try{let D=await fetch(l,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});D.ok?d=await D.text():await D.body?.cancel()}catch{}let f=URt(d),p=$Rt(d)||er(l),h=De(d,"og:description")||De(d,"description")||"",A=De(d,"og:title")||br(d)||p,g=h,m=De(d,"article:published_time"),b=d.match(/]+datetime=["']([^"']+)["']/i)?.[1],E=m||b||"",C=HRt(d),I=De(d,"og:image");if(I&&I.startsWith("http")&&!C.includes(I)){let D=Dr;try{D.test(new URL(I).pathname)&&C.push(I)}catch{}}let T=De(d,"article:author")||void 0;if(!T){let D=d.match(/"author"\s*:\s*\{\s*"@type"\s*:\s*"Person"\s*,\s*"name"\s*:\s*"([^"]+)"/);D&&(T=D[1])}if(!T){let D=d.match(/"author"\s*:\s*"([^"]+)"/);D&&(T=D[1])}let k="low";return f.length>200?k="high":f.length>50&&(k="medium"),{title:p,slug:er(l),content:f,excerpt:h,date:E,seoTitle:A,seoDescription:g,mediaUrls:C,qualityScore:k,categories:[],tags:[],author:T}}});return u.productsExtracted>0&&a&&!s.dryRun&&(c.isStreaming?c.closeStream():c.serialize(`${a}/products.csv`)),u}function jRt(e){return/webflow\.io|webflow\.com/i.test(e)}var I2e={id:"webflow",detect:jRt,discover:E2e,extract:C2e};ki();function w2e(e,t){let r=[],n=new Set,i=/]+class=["'][^"']*wsite-menu-item[^"']*["'][^>]*>([\s\S]*?)<\/a>/gi,s;for(;(s=i.exec(e))!==null;){let o=s[0],a=s[1].replace(/<[^>]*>/g,"").trim(),c=o.match(/href=["']([^"']+)["']/i);if(!a||!c)continue;let u=c[1];if(!n.has(u)){if(n.add(u),u.startsWith("//"))u="https:"+u;else if(u.startsWith("/"))try{u=new URL(u,t).href}catch{}r.push({text:a,href:u})}}return r.length===0?Bs(e,t):r}function S2e(e){let t=new Set,r=/https?:\/\/[^\s"'<>)]*editmysite\.com\/[^\s"'<>)]+/g,n=e.match(r)||[];for(let l of n)t.add(l);let i=/https?:\/\/[^\s"'<>)]*weeblycloud\.com\/[^\s"'<>)]+/g,s=e.match(i)||[];for(let l of s)t.add(l);let o=/https?:\/\/[^\s"'<>)]*\/uploads\/[^\s"'<>)]+/g,a=e.match(o)||[];for(let l of a)t.add(l);let c=e.match(/]+src=["']([^"']+)["']/gi)||[];for(let l of c){let d=l.match(/src=["']([^"']+)["']/i);d?.[1]&&d[1].startsWith("http")&&t.add(d[1])}let u=/\.(css|js|json|xml|txt|map|woff2?|ttf|eot|pdf)$/i;return[...t].filter(l=>{try{let d=new URL(l);return u.test(d.pathname)?!1:Dr.test(d.pathname)}catch{return!1}})}async function v2e(e,t){let r="";try{let h=e.includes("://")?e:`https://${e}`,A=await fetch(h,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});A.ok?r=await A.text():await A.body?.cancel()}catch{}let n=De(r,"og:title"),i=De(r,"og:description"),s=n||br(r)||"Imported Site",o=i||De(r,"description")||"",c=r.match(/]+lang=["']([^"']+)["']/i)?.[1]||"en-US",u=await ii(e),l=e.includes("://")?e:`https://${e}`,d=w2e(r,l),f={},p=[];for(let h of u){let A=cr(h);A==="page"&&/\/blog\//.test(h)&&!/\/blog\/category\//.test(h)&&(A="post"),p.push({url:h,type:A}),f[A]=(f[A]||0)+1}return p.length===0&&(p.push({url:l,type:"homepage"}),f.homepage=1),{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:s,tagline:o,language:c},navigation:d,counts:f,urls:p}}qi();function x2e(e,t,r="div"){let n=e.match(t);if(!n)return"";let s=e.indexOf(n[0])+n[0].length,o=1,a=s,c=`<${r}`,u=``;for(;a0;){let l=e.indexOf(c,a),d=e.indexOf(u,a);if(d===-1)break;if(l!==-1&&l]*\sid=["']wsite-content["'][^>]*>/i);if(t)return t;let r=e.match(/]*>([\s\S]*?)<\/main>/i);if(r?.[1]?.trim())return r[1].trim();let n=e.match(/]*>([\s\S]*?)<\/article>/i);return n?.[1]?.trim()?n[1].trim():""}function k2e(e){let t=e.match(/]*>([\s\S]*?)<\/h1>/i)?.[1]?.replace(/<[^>]*>/g,"").trim();if(t)return t;let r=De(e,"og:title");return r||br(e)}function _2e(e){let t=De(e,"article:published_time");if(t)return t;let r=e.match(/class=["'][^"']*date-text[^"']*["'][^>]*>([^<]+)]+datetime=["']([^"']+)["']/i)?.[1];if(n)return n;let i=x2e(e,/]*\sid=["']wsite-content["'][^>]*>/i)||e,s=/(\d{1,2}\/\d{1,2}\/\d{4})/,o=i.match(s);if(o?.[1]){let a=new Date(o[1]);if(!isNaN(a.getTime()))return a.toISOString()}return""}function T2e(e){let t=[],r=new Set,n=/href=["'][^"']*\/blog\/category\/([^"']+)["'][^>]*>([^<]+)/gi,i;for(;(i=n.exec(e))!==null;){let s=i[2].trim();s&&!r.has(s.toLowerCase())&&(r.add(s.toLowerCase()),t.push(s))}return t}function Q2e(e,t){let r;try{r=new URL(t.includes("://")?t:`https://${t}`).origin}catch{return e}return e.replace(/(src|href)=["'](\/(?!\/)[^"']+)["']/gi,(n,i,s)=>`${i}="${r}${s}"`)}function R2e(e,t){if(!t)return null;let n=t.match(/]*>([\s\S]*?)<\/h2>/i)?.[1]?.replace(/<[^>]*>/g,"").trim();if(!n)return null;let i=/\$\s*(\d+(?:\.\d{2})?)/,o=t.match(i)?.[1]||"",c=t.match(/class=["'][^"']*(?:sale|original)[^"']*["'][^>]*>\s*\$\s*(\d+(?:\.\d{2})?)/i)?.[1]||void 0,u=[];function l(m){return!(m.length<15||/^\$\d/.test(m)||/^SKU:/i.test(m)||/^(Add to Cart|Unavailable|Out of Stock|per item|Have questions|Items handcrafted)/i.test(m))}let d=t.match(/]*>([\s\S]*?)<\/p>/gi)||[];for(let m of d){let b=m.replace(/<[^>]*>/g,"").trim();l(b)&&u.push(b)}if(u.length===0){let m=t.match(/]+class=["'][^"']*paragraph[^"']*["'][^>]*>([\s\S]*?)<\/div>/gi)||[];for(let b of m){let E=b.replace(/<[^>]*>/g,"").trim();l(E)&&u.push(E)}}let f=u.join(` + +`),p=[],h=/]+src=["']([^"']*\/uploads\/[^"']+)["']/gi,A;for(;(A=h.exec(t))!==null;){let m=A[1];if(m.startsWith("/"))try{m=new URL(e).origin+m}catch{}m=m.replace(/\?width=\d+/,""),p.includes(m)||p.push(m)}let g=/]+src=["'](https?:\/\/[^"']*editmysite\.com\/[^"']+)["']/gi;for(;(A=g.exec(t))!==null;){let m=A[1];Dr.test(m)&&!p.includes(m)&&p.push(m)}return{name:n,type:"simple",description:f,regularPrice:o,salePrice:c,images:p,inStock:!0,sourceUrl:e}}async function D2e(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:300,a=s.outputDir||"",c=new ei;a&&!s.dryRun&&c.openStream(a);let u=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:c,onPageExtracted:s.onPageExtracted,extractPage:async l=>{let d=await fetch(l,{signal:AbortSignal.timeout(15e3),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});if(!d.ok)throw await d.body?.cancel(),new Error(`HTTP ${d.status} ${d.statusText}`);let f=await d.text(),p=Q2e(B2e(f),l),h=k2e(f)||er(l),A=De(f,"og:description")||De(f,"description")||"",g=De(f,"og:title")||br(f)||h,m=A,b=_2e(f),E=S2e(f),C=De(f,"og:image");if(C&&C.startsWith("http")&&!E.includes(C))try{Dr.test(new URL(C).pathname)&&E.push(C)}catch{}let I=T2e(f),T=p.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim(),k="low";return T.length>200?k="high":T.length>50&&(k="medium"),{title:h,slug:er(l),content:p,excerpt:A,date:b,seoTitle:g,seoDescription:m,mediaUrls:E,qualityScore:k,categories:I,tags:[]}},extractProduct:R2e});return u.productsExtracted>0&&a&&!s.dryRun&&(c.isStreaming?c.closeStream():c.serialize(`${a}/products.csv`)),u}function qRt(e){return/weebly\.com/i.test(e)}var N2e={id:"weebly",detect:qRt,discover:v2e,extract:D2e};ki();qi();zi();async function M2e(e,t){let r=t;e=kB(e);let{browser:n,page:i,close:s}=await Ec({cdpPort:r.cdpPort});try{let o=i,a=(()=>{let b=new URL(e);return b.origin+b.pathname.replace(/\/$/,"")})(),c=[],u=new Set,l=new Set,d=[];async function f(b,E=0,C=!1){if(E>3||l.has(b))return;l.add(b);let I=D=>{if(C){r.verbose&&console.warn(`[wix:discover] optional sub-sitemap not present: ${b} (${D})`);return}console.warn(`[wix:discover] sitemap fetch failed after ${T} attempts: ${b} (${D})`),d.push({url:b,reason:D})},T=3,k=null;for(let D=1;D<=T;D++)try{let _=await o.goto(b,{timeout:15e3});if(!_||!_.ok()){if(k=_?`HTTP ${_.ok()?"ok=false":"status-not-ok"}`:"no response",DsetTimeout(O,500*D));continue}I(k??"unknown");return}let v=await o.content(),N=$b(v);for(let O of N)O.endsWith(".xml")?await f(O,E+1):u.has(O)||(u.add(O),c.push(O));return}catch(_){if(k=_ instanceof Error?_.message:String(_),DsetTimeout(v,500*D));continue}I(k??"unknown")}}await f(`${a}/sitemap.xml`),d.length>0&&console.warn(`[wix:discover] ${d.length} sitemap fetch(es) failed \u2014 inventory may be incomplete`);for(let b of["blog-posts-sitemap.xml","store-products-sitemap.xml","forum-posts-sitemap.xml"])await f(`${a}/${b}`,0,!0);let p=c;if(p.length===0)try{await o.goto(e,{waitUntil:"domcontentloaded",timeout:3e4}),await o.waitForTimeout(4e3);let b=new URL(e).origin;p=await o.evaluate(E=>{let C=E;return[...new Set([...document.querySelectorAll("a[href]")].map(I=>I.href).filter(I=>I.startsWith(C)&&!I.includes("#")))]},b)}catch{}let h=[];try{await o.goto(e,{waitUntil:"domcontentloaded",timeout:3e4}).catch(()=>{}),await o.waitForTimeout(4e3),h=await o.evaluate(()=>{let b=[];return document.querySelectorAll('nav a, header a, [role="navigation"] a').forEach(E=>{let C=E,I=C.textContent?.trim()||"",T=C.href;I&&T&&!T.includes("#")&&!b.find(k=>k.href===T)&&b.push({text:I,href:T})}),b})}catch{}let A="";try{A=await o.evaluate(()=>{let b=document.title,E=b.lastIndexOf(" | ");return(E>0?b.slice(E+3).trim():b).replace(/ Main$/,"").trim()})}catch{}let g={},m=[];for(let b of p){let E=cr(b);m.push({url:b,type:E}),g[E]=(g[E]||0)+1}return{siteUrl:e,discoveredAt:new Date().toISOString(),siteMeta:{title:A||"Imported Site",tagline:"",language:"en-US"},navigation:h,counts:g,urls:m}}finally{await s()}}zi();function H7(e){let t=e instanceof Error?e.message:String(e??"");return/execution context was destroyed|context was destroyed|because of (?:a )?navigation/i.test(t)}var j7=` +(function () { + try { + var noop = function () { return undefined; }; + if (window.history) { + try { window.history.pushState = noop; } catch (e) {} + try { window.history.replaceState = noop; } catch (e) {} + } + try { + var loc = window.location; + if (loc) { + try { loc.assign = noop; } catch (e) {} + try { loc.replace = noop; } catch (e) {} + } + } catch (e) {} + } catch (e) {} +})(); +`;function P2e(){return{title:"",description:"",ogTitle:"",ogDescription:"",ogImage:"",canonical:""}}function L2e(e){let t=new Set,n=JSON.stringify({apiCalls:e.apiCalls,globals:e.globals,jsonLd:e.jsonLd}).match(/https?:\/\/[^"'\s]*(?:wixstatic\.com|wixmp\.com)[^"'\s]*/g)||[];for(let o of n)t.add(o);for(let o of e.jsonLd){let a=o;if(typeof a.image=="string"&&t.add(a.image),Array.isArray(a.image))for(let c of a.image)typeof c=="string"&&t.add(c),typeof c=="object"&&c&&typeof c.url=="string"&&t.add(c.url);typeof a.thumbnailUrl=="string"&&t.add(a.thumbnailUrl)}if(e.meta.ogImage&&t.add(e.meta.ogImage),e.pageHtml){let o=e.pageHtml.match(/]+src=["']([^"']+)["']/gi)||[];for(let c of o){let u=c.match(/src=["']([^"']+)["']/i);u?.[1]&&u[1].startsWith("http")&&t.add(u[1])}let a=e.pageHtml.match(/url\(["']?(https?:\/\/[^"')]+)["']?\)/gi)||[];for(let c of a){let u=c.match(/url\(["']?(https?:\/\/[^"')]+)["']?\)/i);u?.[1]&&t.add(u[1])}}let i=Dr,s=/wixstatic\.com|wixmp\.com|parastorage\.com|images\.unsplash\.com|cdn\.shopify\.com/i;return[...t].filter(o=>{try{let a=new URL(o);return i.test(a.pathname)||s.test(a.hostname)}catch{return!1}})}function F2e(e){for(let t of e){let r=t,n=r["@type"];if(!(n==="BlogPosting"||n==="Article"||n==="NewsArticle"||Array.isArray(n)&&n.some(o=>o==="BlogPosting"||o==="Article"||o==="NewsArticle")))continue;let s=r.image;if(typeof s=="string")return s;if(s&&typeof s=="object"&&!Array.isArray(s)){let o=s.url;if(typeof o=="string")return o}if(Array.isArray(s))for(let o of s){if(typeof o=="string")return o;if(o&&typeof o=="object"){let a=o.url;if(typeof a=="string")return a}}}return null}function q7(e,t=0){if(t>8||e==null||typeof e=="string"||typeof e!="object")return null;let r=e,n=["html","richText","body","content","text","plainText"];for(let i of n){let s=r[i];if(typeof s=="string"&&s.length>50&&s.includes("<"))return s}if(Array.isArray(e))for(let i of e){let s=q7(i,t+1);if(s)return s}else for(let i of Object.values(r)){let s=q7(i,t+1);if(s)return s}return null}function O2e(e){for(let n of e.apiCalls){let i=q7(n.data);if(i&&i.length>50){let s=i.replace(//gi,"").replace(//gi,"").replace(//gi,"").replace(/]*\/?>/gi,"").replace(/]*\/?>/gi,"").trim();if(s.length>50&&/<[a-z][\s\S]*>/i.test(s))return{content:i,qualityScore:"high"}}}if(e.renderedContent&&e.renderedContent.length>30)return{content:e.renderedContent,qualityScore:"high"};let t=new Set(["Article","BlogPosting","NewsArticle","SocialMediaPosting","Product","ItemPage","Event","Recipe","Course","Book","Movie"]);for(let n of e.jsonLd){let i=n;if(typeof i.articleBody=="string"&&i.articleBody.length>50)return{content:`

    ${i.articleBody}

    `,qualityScore:"medium"};let s=i["@type"];if(typeof s=="string"&&t.has(s)&&typeof i.description=="string"&&i.description.length>50)return{content:`

    ${i.description}

    `,qualityScore:"medium"}}let r=e.meta.ogDescription||e.meta.description||"";if(r.length>50)return{content:`

    ${r}

    `,qualityScore:"medium"};if(e.accessibility&&e.accessibility.length>0){let n=[];for(let i of e.accessibility)i.role==="heading"?n.push(`

    ${i.name}

    `):i.name&&n.push(`

    ${i.name}

    `);if(n.length>0)return{content:n.join(` +`),qualityScore:"low"}}return{content:"",qualityScore:"low"}}function z7(e){let t=new Set,r=/https?:\/\/[a-z0-9.-]*(?:wixstatic\.com|wixmp\.com)\/media\/[^\s"'()<>\\]+/gi;for(let h of e.match(r)||[])t.add(h);let n=/[a-z0-9]{4,}_[a-f0-9]{32}~mv2\.(?:jpe?g|png|gif|webp|avif)/gi;for(let h of e.match(n)||[])t.add(`https://static.wixstatic.com/media/${h}`);let i=new Map;for(let h of t){let A=h.match(/\/media\/([a-z0-9]{4,}_[a-f0-9]{32}~mv2\.[a-z0-9]+)/i)?.[1],g=A??h;i.get(g)?A&&h.endsWith(A)&&i.set(g,`https://static.wixstatic.com/media/${A}`):i.set(g,h)}let s=[...i.values()],o=e.match(/]+property=["']og:title["'][^>]+content=["']([^"']+)["']/i)?.[1],a=e.match(/]*>([\s\S]*?)<\/title>/i)?.[1]?.trim(),c=(o||a||"").trim(),u=c.lastIndexOf(" | "),l=u>0?c.slice(0,u).trim():c,d=[],f=e.match(/]+property=["']og:description["'][^>]+content=["']([^"']*)["']/i)?.[1]?.trim();for(let h of e.match(/]*>([\s\S]*?)<\/h[1-3]>/gi)||[]){let A=h.replace(/<[^>]+>/g,"").trim(),g=h.match(/<(h[1-3])/i)?.[1]?.toLowerCase()||"h2";if(A&&A.length<200&&d.push(`<${g}>${A}`),d.length>=12)break}f&&f.length>0&&d.unshift(`

    ${f}

    `);let p=d.join(` +`);return{title:l,content:p,mediaUrls:s}}qi();async function U2e(e){try{let t=await fetch(e,{signal:AbortSignal.timeout(2e4),headers:{"User-Agent":"Mozilla/5.0 (compatible; DataLiberation/1.0)"}});return t.ok?await t.text():(await t.body?.cancel(),"")}catch{return""}}async function $2e(e,t){let r=e,n=async(m,b)=>{try{await r.waitForLoadState("networkidle",{timeout:m})}catch{}await r.waitForTimeout(b)},i=async m=>{try{return await r.evaluate(m)}catch(b){if(!H7(b))throw b;return await n(8e3,1500),await r.evaluate(m)}},s={apiCalls:[]},o=async m=>{let b=m,E=b.url();if(!(!(b.headers()["content-type"]||"").includes("application/json")||!(E.includes("/_api/")||E.includes("wixapis.com")||E.includes("wix.com/_api"))))try{let T=await b.json();s.apiCalls.push({url:E,data:T})}catch{}};r.on("response",o);try{await r.addInitScript(j7)}catch{}try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:3e4}),await n(6e3,4e3);try{await r.evaluate(async()=>{let b=document.documentElement.scrollHeight;for(let E=0;EsetTimeout(C,120));window.scrollTo(0,0)}),await n(3e3,500)}catch{}}catch{}r.off("response",o);let a=!1,c;try{c=await i(()=>{let m={},b=["__WIX_DATA__","__SITE_DATA__","wixBiSession","__wixInjectedPageData"],E=window;for(let T of b)E[T]&&(m[T]=E[T]);for(let T of Object.keys(window))if((T.startsWith("__WIX")||T.startsWith("_wix"))&&!m[T])try{m[T]=E[T]}catch{}let C=Array.from(document.querySelectorAll('script[type="application/ld+json"]')).map(T=>{try{return JSON.parse(T.textContent||"")}catch{return null}}).filter(Boolean),I={title:document.title,description:document.querySelector('meta[name="description"]')?.content||"",ogTitle:document.querySelector('meta[property="og:title"]')?.content||"",ogDescription:document.querySelector('meta[property="og:description"]')?.content||"",ogImage:document.querySelector('meta[property="og:image"]')?.content||"",canonical:document.querySelector('link[rel="canonical"]')?.href||""};return{globals:m,jsonLd:C,meta:I}})}catch{c={globals:{},jsonLd:[],meta:P2e()},a=!0}let u=null;try{u=await i(()=>{let m=document.querySelector("main")||document.querySelector("#PAGES_CONTAINER")||document.querySelector("#SITE_PAGES");if(!m)return null;let b=m.querySelectorAll('[data-testid="richTextElement"]');if(b.length===0)return null;let E=[],C=new Set;return b.forEach(T=>{let k=T.querySelectorAll("h1, h2, h3, h4, h5, h6, p, ul, ol, blockquote");if(k.length>0)k.forEach(D=>{let _=D.innerText?.trim();if(!_||C.has(_))return;C.add(_);let v=D.tagName.toLowerCase();v.startsWith("h")?E.push(`<${v}>${_}`):v==="ul"||v==="ol"?E.push(D.outerHTML):v==="blockquote"?E.push(`
    ${_}
    `):E.push(`

    ${_}

    `)});else{let D=T.innerText?.trim();D&&!C.has(D)&&(C.add(D),E.push(`

    ${D}

    `))}}),m.querySelectorAll('img[src*="wixstatic"], img[src*="wixmp"], [data-testid="image"] img').forEach(T=>{let k=T.src,D=T.alt||"";k&&!C.has(k)&&(C.add(k),E.push(`${D}`))}),E.length>0?E.join(` +`):null})}catch{}let l=null;try{await i(()=>!!document.querySelector('[data-hook="feed-page-root"]'))&&(l="blog_archive")}catch{}let d=null;try{let m=await r.context().newCDPSession(e);d=((await m.send("Accessibility.getFullAXTree",{depth:10})).nodes||[]).filter(C=>["heading","paragraph","StaticText","link","img","list","listitem","article","main","section"].includes(C.role?.value||"")).map(C=>({role:C.role?.value||"",name:C.name?.value||"",description:C.description?.value})).filter(C=>C.name),await m.detach()}catch{}let f="";try{f=await r.content()}catch{f=await U2e(t)||""}a&&f.length<2e3&&(f=await U2e(t)||f);let p=L2e({apiCalls:s.apiCalls,globals:c.globals,jsonLd:c.jsonLd,meta:c.meta,accessibility:d,pageHtml:f}),{content:h,qualityScore:A}=O2e({apiCalls:s.apiCalls,jsonLd:c.jsonLd,renderedContent:u,accessibility:d,meta:c.meta});if(f){let m=z7(f);if(p.length===0&&m.mediaUrls.length>0)p.push(...m.mediaUrls);else{let b=new Set(p);for(let E of m.mediaUrls)b.has(E)||p.push(E)}(!h||h.length<30)&&m.content&&(h=m.content,A="low"),!c.meta.title&&!c.meta.ogTitle&&m.title&&(c.meta.ogTitle=m.title)}let g=F2e(c.jsonLd);return{sourceUrl:t,slug:er(t),extractedAt:new Date().toISOString(),apiCalls:s.apiCalls,globals:c.globals,jsonLd:c.jsonLd,meta:c.meta,accessibility:d,mediaUrls:p,content:h,qualityScore:A,pageHtml:f,...l?{pageType:l}:{},...g?{featuredImage:g}:{}}}function H2e(e){for(let t of e.jsonLd){let r=t;if(r["@type"]==="Product"&&typeof r.name=="string"){let n=r.offers||r.Offers,s=(Array.isArray(n)?n:n?[n]:[])[0]||{},o=s.price?String(s.price):"",a=[];if(typeof r.image=="string")a.push(r.image);else if(Array.isArray(r.image)){for(let u of r.image)if(typeof u=="string")a.push(u);else if(typeof u=="object"&&u){let l=u.url||u.contentUrl;typeof l=="string"&&a.push(l)}}let c=s.availability||s.Availability;return{name:r.name,description:typeof r.description=="string"?r.description:"",regularPrice:o,sku:typeof r.sku=="string"?r.sku:"",images:a,inStock:typeof c=="string"?c.includes("InStock"):!0,sourceUrl:e.sourceUrl}}}for(let t of e.apiCalls){let r=t.data,n=r.product||r.catalog?.product;if(n&&typeof n.name=="string"){let i=n.price,s=n.media?.items,o=[];if(s)for(let a of s){let c=a.image?.url;c&&o.push(c)}return{name:n.name,description:typeof n.description=="string"?n.description:"",regularPrice:i?.formatted?String(i.formatted).replace(/[^0-9.]/g,""):"",sku:typeof n.sku=="string"?n.sku:"",images:o,inStock:n.stock?.inventoryStatus?n.stock.inventoryStatus!=="OUT_OF_STOCK":void 0,sourceUrl:e.sourceUrl}}}if(e.pageHtml){let t=e.pageHtml,r=i=>{let s=new RegExp(`data-hook=["']${i}["'][^>]*>([\\s\\S]*?)]+>/g,"").trim()||""},n=r("product-title");if(n){let i=r("formatted-primary-price").replace(/[^0-9.,]/g,""),s=r("product-description"),o=/data-hook=["'](?:main-media-image-wrapper|thumbnail-image)["'][^>]*>[\s\S]*?]+src=["']([^"']+)["']/gi,a=[],c;for(;(c=o.exec(t))!==null;)a.includes(c[1])||a.push(c[1]);return{name:n,description:s,regularPrice:i,sku:"",images:a,inStock:!0}}}return null}async function j2e(e,t,r,n){let i=e,s=r,o=s.delay!=null?s.delay:500,a=s.outputDir||"",c=new ei,u=!1;a&&!s.dryRun&&c.openStream(a);let l=new Set(i.urls.filter(p=>p.type==="product").map(p=>p.url)),{page:d,close:f}=await Ec({cdpPort:s.cdpPort});try{let p=await mi({urls:i.urls,navigation:i.navigation,wxr:t,log:n.log,outputDir:a,delay:o,dryRun:!!s.dryRun,resume:!!s.resume,verbose:s.verbose,limit:s.limit,server:n.server,csvBuilder:c,onPageExtracted:s.onPageExtracted,extractPage:async h=>{let A=await $2e(d,h);if(l.has(h)||/\/product-page\//.test(h)||/\/store\//.test(h)){let I=H2e(A);I&&(c.addProduct(I),u=!0)}let m=A.meta.ogTitle||A.meta.title||A.slug,b=m.lastIndexOf(" | "),E=b>0?m.slice(0,b).trim():m,C;for(let I of A.jsonLd){let k=I.author;if(typeof k=="string"&&k){C=k;break}if(k&&typeof k=="object"&&typeof k.name=="string"){C=k.name;break}}return{title:E||A.slug,slug:A.slug,content:A.content,excerpt:A.meta.ogDescription||A.meta.description||"",date:A.extractedAt,seoTitle:A.meta.title,seoDescription:A.meta.description,mediaUrls:A.mediaUrls,qualityScore:A.qualityScore,author:C,jsonLd:A.jsonLd}}});return u&&a&&!s.dryRun&&(c.isStreaming?c.closeStream():c.serialize(`${a}/products.csv`)),p}finally{await f()}}function zRt(e){return/wixsite\.com|wix\.com/i.test(e)}var q2e={id:"wix",detect:zRt,discover:M2e,extract:j2e};function z2e(e,t){return e.find(r=>r.id===t)??e.find(r=>r.id==="default")??null}var V2e=[ITe,QTe,HTe,t2e,u2e,b2e,I2e,N2e,q2e];function VRt(e){return z2e(V2e,e)}function GRt(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function G2e(e){return{content:[{type:"text",text:JSON.stringify({error:e})}],isError:!0}}var Ww=new rB({name:"data-liberation",version:"0.1.0"},{capabilities:{tools:{}}});Ww.setRequestHandler(nP,async()=>({tools:[{name:"liberate_detect",description:"Detect the platform of a website (GoDaddy Websites & Marketing, Hostinger, HubSpot, Shopify, Squarespace, Webflow, Weebly, Wix, or unknown)",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL of the website to detect"}},required:["url"]}},{name:"liberate_discover",description:"Inventory a website: fetch sitemap, categorize URLs, extract navigation structure",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL of the website to inventory"},token:{type:"string",description:"API token for platforms requiring auth"},cdpPort:{type:"number",description:"CDP port for browser-based extraction"},verbose:{type:"boolean",description:"Enable detailed logging"}},required:["url"]}},{name:"liberate_inspect",description:"Probe a site to assess extractability: detect platform, check sitemap, probe sample pages",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL of the website to inspect"},token:{type:"string",description:"API token if needed"},cdpPort:{type:"number",description:"CDP port for browser-based inspection"}},required:["url"]}},{name:"liberate_extract",description:"Extract all content from a website. Produces WXR file + media directory + redirect map.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL of the website to extract"},outputDir:{type:"string",description:"Directory to write WXR, media, and logs"},token:{type:"string",description:"API token for platforms requiring auth (e.g. Webflow)"},cdpPort:{type:"number",description:"CDP port for browser-based extraction"},adminToken:{type:"string",description:"Shopify Admin API access token. When set, products are fetched via the Shopify Admin GraphQL API for richer data (compareAtPrice, inventoryPolicy, unitCost, collections, SEO metafields, variant images). Falls back to the public JSON API on failure."},shopDomain:{type:"string",description:"Shopify *.myshopify.com hostname. Usually auto-detected by liberate_discover from the storefront HTML; only pass explicitly if detection failed (e.g. Cloudflare-protected site)."},delay:{type:"number",description:"Delay between requests in ms (default: 500)"},resume:{type:"boolean",description:"Resume a previous extraction"},dryRun:{type:"boolean",description:"Extract 2-3 pages and report without writing WXR"},limit:{type:"number",description:"Cap extraction to the first N URLs and write a real WXR for them"},verbose:{type:"boolean",description:"Enable detailed per-page logging"},screenshots:{type:"boolean",description:"After extract completes, capture screenshots (desktop + mobile) for every processed URL. Results are written to output//screenshots/ with a manifest.json keyed by URL."},captureDesign:{type:"boolean",description:"Enable html-first design replication: carry source HTML+CSS as the page/post design. Note: full html-first design capture (site.css aggregation, blank theme install) runs via the CLI (`data-liberation --html-first`); this flag is reserved for future MCP support."},contentStatus:{type:"string",enum:["draft","publish"],description:'WXR post status for extracted pages/posts. Default "draft" \u2014 the documented "import as drafts; the user reviews and publishes manually" convention for a production import. The replica/preview flow (e.g. building a Studio replica) passes "publish" so imported nav targets resolve. Attachments always use "inherit".'}},required:["url","outputDir"]}},{name:"liberate_extract_one",description:"Extract a single URL through the streaming pipeline. Used by the watch loop and agent-driven streaming. Each call runs adapter discovery to set up state, then narrows to the target URL. Append-mode WXR \u2014 results accumulate in output.wxr across calls.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The single URL to extract."},outputDir:{type:"string",description:"Liberation output directory. WXR + media + logs are appended here."},siteUrl:{type:"string",description:"Origin of the source site, used for adapter discovery. Defaults to the origin parsed from `url`."},token:{type:"string",description:"API token for platforms requiring auth (e.g. Webflow)."},cdpPort:{type:"number",description:"CDP port for browser-based extraction."},adminToken:{type:"string",description:"Shopify Admin API token (see liberate_extract)."},shopDomain:{type:"string",description:"Shopify *.myshopify.com hostname (see liberate_extract)."},delay:{type:"number",description:"Delay floor in ms."},verbose:{type:"boolean",description:"Per-step logging."},contentStatus:{type:"string",enum:["draft","publish"],description:'WXR post status for extracted pages/posts. Default "draft" (import-as-drafts convention); the replica/preview flow passes "publish". Attachments always use "inherit".'}},required:["url","outputDir"]}},{name:"liberate_paths",description:"Resolve where liberation output lives. Returns { base, siteDir }. base = the default output base (DLA_OUTPUT_DIR or /_liberations). siteDir = base/ when a url is given. Skills MUST use this instead of assuming output// relative to cwd.",inputSchema:{type:"object",properties:{url:{type:"string",description:"Optional source URL; when present, siteDir is returned."}}}},{name:"liberate_status",description:"Check progress of a running or completed extraction",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"The output directory of the extraction"}},required:["outputDir"]}},{name:"liberate_map_apis",description:"Map all API endpoints used by a website by navigating pages via CDP and capturing JSON network traffic. Produces a categorized endpoint catalog with sample responses and auth headers. Use during /adapt reconnaissance to reverse-engineer a new platform.",inputSchema:{type:"object",properties:{cdpPort:{type:"number",description:"Chrome DevTools Protocol port (e.g. 9222)"},url:{type:"string",description:"The URL of the site to map"},crawlUrls:{type:"array",items:{type:"string"},description:"Additional URLs to navigate (e.g. admin dashboard sections)"},followLinks:{type:"boolean",description:"Follow same-origin links from the main page (up to 20, default: false)"}},required:["cdpPort","url"]}},{name:"liberate_probe",description:"Probe a browser page via CDP for extraction-relevant data: window globals, JSON-LD, cookies, localStorage, network entries, and platform identity fields. Requires a running Chrome with --remote-debugging-port. Use for debugging extraction failures.",inputSchema:{type:"object",properties:{cdpPort:{type:"number",description:"Chrome DevTools Protocol port (e.g. 9222)"},url:{type:"string",description:"Only probe pages on this domain (optional \u2014 probes all tabs if omitted)"}},required:["cdpPort"]}},{name:"liberate_qa",description:"Compare extracted WXR content against the original source site page by page. Reports text similarity, missing headings/images/links, and grades each page (pass/warn/fail). Optionally patches fixable issues like missing alt text.",inputSchema:{type:"object",properties:{wxrFile:{type:"string",description:"Path to the WXR file to QA"},fix:{type:"boolean",description:"Patch fixable issues in the WXR (default: false)"}},required:["wxrFile"]}},{name:"liberate_verify",description:"Verify a completed extraction: check for stale CDN URLs, failed pages, missing media, and items needing manual attention",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"The output directory of the extraction to verify"}},required:["outputDir"]}},{name:"liberate_setup",description:"Validate WordPress connection: check site reachability, REST API, and authentication. Returns guidance if anything fails. Pass delegate: true to skip validation and receive a structured manifest describing what the import target needs \u2014 useful when the calling environment handles site setup itself.",inputSchema:{type:"object",properties:{site:{type:"string",description:"WordPress site domain (e.g. mysite.com or localhost:8881)"},username:{type:"string",description:"WordPress username"},token:{type:"string",description:"WordPress application password"},delegate:{type:"boolean",description:"Skip validation and return a setup manifest for the calling environment to handle. Use when the environment has its own site management (e.g. local dev tools)."}},required:[]}},{name:"liberate_import",description:"Import a WXR file into a WordPress site. Pass delegate: true to skip REST import and receive a structured import manifest \u2014 useful when the calling environment handles imports itself (e.g. local dev tools with direct database/CLI access).",inputSchema:{type:"object",properties:{wxrFile:{type:"string",description:"Path to the WXR file to import"},site:{type:"string",description:"WordPress site domain (e.g. example.com)"},username:{type:"string",description:"WordPress username"},token:{type:"string",description:"WordPress application password"},dryRun:{type:"boolean",description:"Preview without importing"},delay:{type:"number",description:"Delay between requests in ms (default: 500)"},only:{type:"string",description:"Only import specific type (categories, tags, media, pages, posts, comments, menus)"},verbose:{type:"boolean",description:"Enable detailed logging"},resume:{type:"boolean",description:"(deprecated \u2014 import is always idempotent, this flag has no effect)"},importAuthors:{type:"boolean",description:"Create WordPress users for each author in the WXR (default: false \u2014 all content owned by authenticated user)"},woocommerceKey:{type:"string",description:"WooCommerce consumer key for product import"},woocommerceSecret:{type:"string",description:"WooCommerce consumer secret for product import"},delegate:{type:"boolean",description:"Skip REST import and return a structured import manifest for the calling environment to handle."}},required:["wxrFile"]}},{name:"liberate_preview",description:"Spawn a local Studio preview of an extraction output. Returns { url, port, status, warnings }. Kills any existing preview on the same outputDir before starting. Optionally installs a generated replica theme + block plugins via themeFiles[] + blockPlugins[]; the theme is activated after content import. Used by the replicate skill in Step 5 (Install).",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Path to the extraction output directory (contains output.wxr)."},open:{type:"boolean",description:"If true, open the URL in the default browser after readiness."},port:{type:"number",description:"Override the auto-picked port (default range: 9400-9499)."},themeFiles:{type:"array",description:'Generated replica theme files. Each entry is { relativePath, content } rooted at the theme directory (e.g. relativePath: "templates/index.html"). Theme is written to wp-content/themes// and activated after content import.',items:{type:"object",properties:{relativePath:{type:"string"},content:{type:"string"}},required:["relativePath","content"]}},blockPlugins:{type:"array",description:"DEPRECATED \u2014 embed custom blocks inside the theme at blocks//{src,build}/ via themeFiles[] instead (Telex blocks-inside-themes pattern, registered from functions.php). Kept for backwards compatibility. Each entry is { slug, files: [{relativePath, content}] }; plugin is written to wp-content/plugins// and activated.",items:{type:"object",properties:{slug:{type:"string"},files:{type:"array",items:{type:"object",properties:{relativePath:{type:"string"},content:{type:"string"}},required:["relativePath","content"]}}},required:["slug","files"]}},themeSlug:{type:"string",description:"Theme directory name (kebab-case). Required when themeFiles is non-empty. Conventionally -replica."}},required:["outputDir"]}},{name:"liberate_install_theme",description:"Install replica theme files + block plugins into an ALREADY-RUNNING Studio site (no site creation, no content import). Use this from the streaming watch loop's theme-piece / archetype-template judgments \u2014 `liberate_preview` would create a `-2` duplicate Studio site and re-import content over the streamed posts. Writes to /wordpress/wp-content/{themes,plugins}/, then runs `studio wp plugin activate` and `studio wp theme activate`. Returns warnings[] for non-fatal activate failures.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Path to the extraction output directory (used for log routing only \u2014 files are written to studioSitePath, not outputDir)."},studioSitePath:{type:"string",description:"On-disk path to the running Studio site (parent dir, NOT the wordpress sub-dir). Streaming watch logs this as `preview-pre-started.sitePath`."},themeFiles:{type:"array",description:"Replica theme files. Same shape as liberate_preview \u2014 { relativePath, content }, rooted at the theme directory. Activated after writing.",items:{type:"object",properties:{relativePath:{type:"string"},content:{type:"string"}},required:["relativePath","content"]}},blockPlugins:{type:"array",description:"DEPRECATED \u2014 kept for backwards compatibility. New replica work should embed custom blocks inside the theme at blocks//{src,build}/ via themeFiles[], following the Telex blocks-inside-themes pattern. The skill registers them from functions.php. Each plugin entry is { slug, files: [{relativePath, content}] }, activated after writing.",items:{type:"object",properties:{slug:{type:"string"},files:{type:"array",items:{type:"object",properties:{relativePath:{type:"string"},content:{type:"string"}},required:["relativePath","content"]}}},required:["slug","files"]}},themeSlug:{type:"string",description:"Theme directory name (kebab-case). Required when themeFiles is non-empty. Conventionally -replica."}},required:["outputDir","studioSitePath"]}},{name:"liberate_theme_scaffold",description:"Read /design-foundation.json and emit a complete-and-activatable WordPress block theme bundle deterministically: style.css (theme header), theme.json (settings/styles mapped from foundation tokens), functions.php (theme setup + custom-block registration loop), templates/index.html (homepage shell with header part + post-content + footer part), parts/header.html (site-title + page-list nav), parts/footer.html (copyright). No agent reasoning, no vision, no LLM call \u2014 pure deterministic mapping. Pair with `liberate_install_theme` to install the result into a running Studio site. Per-archetype templates (page.html, single.html, etc.) and patterns are NOT emitted here \u2014 they belong to the replicate skill's archetype-template tick.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (must contain design-foundation.json)."},themeSlug:{type:"string",description:"Theme directory slug (kebab-case). Conventionally -replica."},themeName:{type:"string",description:"Display name. Defaults to themeSlug."},siteTitle:{type:"string",description:"Source site title \u2014 used in style.css description and footer copyright."},themeDescription:{type:"string",description:"Override the default style.css Description line."},sourceUrl:{type:"string",description:"The source site origin (e.g. https://www.example.com/). Used to resolve the captured header/footer chrome links to absolute URLs so they remap to local permalinks (without it, nav hrefs are not remapped and point off-site). Defaults to a placeholder origin."},persist:{type:"boolean",description:"When true, also write the emitted text theme files to /theme (alongside the font/logo assets always written there), materializing a complete on-disk theme. Default false: themeFiles[] is returned for the caller to install into a live site."},reconstructedPages:{type:"array",description:"Block-reconstructed content pages. Each entry emits templates/page-.html wiring the page to its reconstructed pattern (and front-page.html for isHome), so the page renders block sections instead of falling through page.html to raw carried post_content. The pattern files (reconstructed block markup) are added to themeFiles[] separately by the replicate skill.",items:{type:"object",properties:{slug:{type:"string",description:'Source-faithful WP page slug (last path segment), e.g. "about-us".'},patternSlug:{type:"string",description:'Fully-qualified theme pattern slug, e.g. "/page-about-us".'},isHome:{type:"boolean",description:"When true, also emit templates/front-page.html for this page (static front page)."}},required:["slug","patternSlug"]}}},required:["outputDir","themeSlug"]}},{name:"liberate_blockify_wxr",description:"BULK blog-body block conversion (blocks reconstruct path ONLY). Rewrites every post/page content:encoded body in output.wxr through the source platform adapter's block recipe (seam 2) so imported posts land as editable Gutenberg blocks instead of one Classic block (e.g. Squarespace sqs-block bodies). Lossless: bodies the recipe can't convert are left verbatim, and all other items (attachments, nav menu items, comments, terms) are preserved unchanged. No-op when the platform adapter has no block recipe. Resolves the platform from session.json (recorded at extraction); pass `platform` to override. Run AFTER extraction and BEFORE liberate_import. The theme/carry path must NOT call this.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory holding output.wxr + session.json."},wxrPath:{type:"string",description:"Override the WXR path. Defaults to /output.wxr."},platform:{type:"string",description:"Override the platform adapter id (else read from session.json)."}},required:["outputDir"]}},{name:"liberate_reconstruct_pages",description:"Deterministically reconstruct EVERY content page from its OWN captured section specs. For each page: capture specs, install section media, reconstruct verbatim block markup, GATE through validate_artifacts, write the pattern + reconstructed post_content. Page TEMPLATES are collapsed to a small set of variant templates (templates/page-replica[-].html) registered in theme.json customTemplates and assigned per page via _wp_page_template; output.wxr is patched to match. Set collapseTemplates:false to fall back to one templates/page-.html per page. The theme shell must already be installed via liberate_theme_scaffold/install.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (holds media/ + media-stubs.json)."},studioSitePath:{type:"string",description:"On-disk path to the running Studio site (e.g. ~/Studio/example-com)."},themeSlug:{type:"string",description:"Installed theme slug. Defaults to -replica derived from outputDir."},collapseTemplates:{type:"boolean",description:"Collapse per-page templates into variant-keyed templates + _wp_page_template assignments (default true). false = one template per page (legacy)."},variationHoist:{type:"boolean",description:"Hoist recurring instance-style constellations into theme block-style variations (default true). Set false to disable (escape hatch)."},editableIslands:{type:"boolean",description:"Convert the coverage-gated core/html fallback islands into in-canvas dla/editable-html blocks (visible + styled + text/image-editable in the block editor; ships + activates the block plugin). Default true. Set false to keep plain core/html."},pages:{type:"array",description:"Content pages to reconstruct. Reconstruct every page (not just cluster reps).",items:{type:"object",properties:{slug:{type:"string",description:'Source-faithful WP page slug (sanitize_title-shaped), e.g. "about-us".'},sourceUrl:{type:"string",description:"The page's source URL to capture + reconstruct."},title:{type:"string",description:"Human-readable page title (pattern doc-comment)."},isHome:{type:"boolean",description:"When true, also emit front-page.html."}},required:["slug","sourceUrl","title"]}}},required:["outputDir","studioSitePath","pages"]}},{name:"liberate_reconstruct_pages_carry",description:"Carry-and-scope parity path: for each page, load cached body HTML (or fetch live), collect CSS, carry the sanitized HTML + scoped CSS into core/html block islands, self-host the run media (rewriting /srcset/url() to the local WP library) + localize internal links, write a carry FSE block theme under wp-content/themes/-carry (incl. WooCommerce single-product/archive-product templates wrapping the carried header/footer when the run has products), and return per-page islands for building output-carry.wxr. Requires liberate_screenshot (html/ cache); falls back to live fetch. Pass islandsOutDir to write islands to disk and return paths instead of inline content (avoids the MCP response-size cap on large sites).",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (holds html/ cache from liberate_screenshot)."},studioSitePath:{type:"string",description:"On-disk path to the running Studio site (e.g. ~/Studio/example-com)."},themeName:{type:"string",description:'Display name for the carry theme (default: "Liberated (Carry)").'},islandsOutDir:{type:"string",description:"When set, write each carried island to /.html and return its path + byte count instead of inline postContent. Use this from MCP to avoid the response-size cap (islands are whole page bodies). Omit to get postContent inline (the tsx driver default)."},editableIslands:{type:"boolean",description:"Emit carried bodies as in-canvas dla/editable-html blocks (visible + styled + text/image-editable in the block editor) instead of sandboxed core/html islands. Front-end output is byte-identical (static save). Ships + activates the block plugin. Default true; set false to force plain core/html."},pages:{type:"array",description:"Content pages to carry and scope. Pass every page in the site for full coverage.",items:{type:"object",properties:{slug:{type:"string",description:'URL-safe page slug (sanitize_title-shaped), e.g. "about-us". Must match the WP post_name so the island-swap finds the post and functions.php body-class scoping targets it.'},sourceUrl:{type:"string",description:"The page's source URL (used as base for CSS resolution and live HTML fallback)."},title:{type:"string",description:"Human-readable page title."},isHome:{type:"boolean",description:"When true, emits front-page.html template and uses is_front_page() body-class condition."},postType:{type:"string",enum:["page","post"],description:'Post type (default "page"). "post" scopes via is_single() and renders through single.html; also selects the functions.php body-class condition.'},htmlSlug:{type:"string",description:'Override the cached-HTML filename stem loaded as html/.html when it differs from the WP slug \u2014 e.g. posts captured as "blogs--snoozweek--" or pages as "pages--". Falls back to slug; without it the tool live-fetches sourceUrl.'}},required:["slug","sourceUrl","title"]}}},required:["outputDir","studioSitePath","pages"]}},{name:"liberate_screenshot",description:"Capture full-page + scrolled screenshots (desktop + mobile) and rendered HTML for every URL on a site. Writes to /screenshots/ and /html/, plus palette.json, typography.json, breakpoints.json, and computed-styles.json via DOM/CSS site-analysis. Reuses sitemap discovery or accepts explicit urls[].",inputSchema:{type:"object",properties:{url:{type:"string",description:"Site URL (used for sitemap discovery and same-origin enforcement)"},outputDir:{type:"string",description:"Output directory"},urls:{type:"array",items:{type:"string"},description:"Explicit URL list (skips sitemap fetch; all must share origin with `url` if both provided)"},types:{type:"array",items:{type:"string"},description:"Filter by URL type: page, post, product, homepage, gallery, event"},limit:{type:"number",description:"Cap to first N URLs"},concurrency:{type:"number",description:"Parallel URL captures (default 3, max 10)"},browserRestartEvery:{type:"number",description:"Close and relaunch browser every N URLs (default 100)"},cdpPort:{type:"number",description:"Connect to existing Chrome via CDP"},force:{type:"boolean",description:"Re-capture even if output files already exist"},verbose:{type:"boolean",description:"Per-URL progress logging"}},required:["url","outputDir"]}},{name:"liberate_data_model_scaffold",description:"Deterministic pre-pass for the JS-data path: reads an owned local site dir, discovers record arrays / mount containers / id-lookups by AST (resilient to malformed/vendored JS files), infers field roles, and writes a PARTIAL data-model.draft.json. Returns { model, skillTodos, discovered, validation }. The model-local-data skill fills only the skillTodos (card.template, ambiguous ordering, low-confidence role guesses), then writes the final data-model.json. Run before liberate_convert_local_site when the source renders content from a JS data array.",inputSchema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the local static-site directory."},outputDir:{type:"string",description:"Where data-model.draft.json is written. Defaults to dir."}},required:["dir"]}},{name:"liberate_design_foundation_scaffold",description:"Runs the deterministic scaffold on a liberation output directory: reads palette.json / typography.json / breakpoints.json / screenshots/manifest.json from SP1 output, applies pure rules (darkest high-frequency \u2192 text.default, lightest \u2192 surface.base, breakpoint tier mapping, gradient regex extraction from html/*.html), and returns a PartialDesignFoundation. Empty role slots are left for the design-foundations skill to assign. Emits skillTodos listing every path the skill must fill. The design-foundations skill may additionally read computed-styles.json for HTML/CSS role assignment.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (must contain SP1 files)."},origin:{type:"string",description:"Origin URL (e.g. https://example.com). Stored in the foundation `origin` field."}},required:["outputDir","origin"]}},{name:"liberate_design_foundation_validate",description:"Validates a design-foundation JSON blob against the schema. Returns { ok: true } or { ok: false, errors: [...] }. Used by the design-foundations skill after filling role slots to catch structural mistakes and unfilled skillTodos before saving to disk.",inputSchema:{type:"object",properties:{foundation:{type:"object",description:"JSON blob to validate (not a path)."}},required:["foundation"]}},{name:"liberate_design_foundation_save",description:"Persists a validated design-foundation JSON to disk and generates the human-readable design-foundation.md companion. Writes both files atomically to outputDir. Skips write when inputsDigest matches prior file (unless force=true).",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Destination directory."},foundation:{type:"object",description:"Complete design foundation JSON blob."},force:{type:"boolean",description:"Overwrite even if inputsDigest matches prior file."}},required:["outputDir","foundation"]}},{name:"liberate_media_install",description:"Install one URL's pending media into the running replica WP site. Idempotent: skips media already registered as attachments (tracked via MediaStubStore.wpPostId). Uses `studio wp eval-file` to run a vendored PHP installer script.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (contains media-stubs.json + media/)."},url:{type:"string",description:"Source URL whose media we are installing (used for logging; the install acts on all pending media in MediaStubStore)."},target:{type:"object",description:'Where to install the media. Studio: { kind: "studio", sitePath: "/Users/.../Studio/site-name" }.',properties:{kind:{type:"string",enum:["studio"]},sitePath:{type:"string"},siteUrl:{type:"string",description:"Optional site URL used to compute browser-visible upload URLs."}},required:["kind","sitePath"]}},required:["outputDir","url","target"]}},{name:"liberate_replicate_tick",description:"Run one tick of the replicate streaming scheduler. Reads replicate-state.json, computes deltas (new archetypes since last tick, foundation drift), returns judgmentNeeded[] markers describing what skills the calling agent should invoke (replicate, design-foundations, compose-page-blocks). The MCP tool is deterministic \u2014 it does not invoke skills directly.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory."},reason:{type:"string",description:"Optional reason override (manual / new-archetype / periodic / foundation-drift). Defaults to inferred."}},required:["outputDir"]}},{name:"liberate_block_transform_apply",description:"Apply composed block markup to a post in the running replica site. Validates: parse_blocks roundtrip + output-verify text-substring check + post-existence poll (3 retries with backoff). Idempotent via block-transform-log.jsonl (same source+output hashes skip re-apply). Studio path uses `wp post update` via studio CLI.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (block-transform-log.jsonl lives here)."},url:{type:"string",description:"Source URL (post is matched via _source_url meta in the replica)."},blocks:{type:"string",description:"Composed block markup to apply as post_content."},sourceHtml:{type:"string",description:"Original sanitized source HTML \u2014 passed to output-verify for text-substring validation."},target:{type:"object",description:'Replica site target. Studio: { kind: "studio", sitePath: "..." }.',properties:{kind:{type:"string",enum:["studio"]},sitePath:{type:"string"},siteUrl:{type:"string"}},required:["kind"]},composedBy:{type:"string",description:'Provenance string for the log entry (e.g. "compose-page-blocks@v1.0" or "heuristic@v1.0").'}},required:["outputDir","url","blocks","sourceHtml","target"]}},{name:"liberate_block_compose",description:"Validate composed block markup and write it to a sidecar file (/composed/.blocks.html) for the streaming watch loop to install as post_content. Compose-then-install counterpart to liberate_block_transform_apply: same parse_blocks roundtrip + output-verify validation, same block-transform-log.jsonl idempotency, but NO database write. The runner reads the sidecar after the agent returns and passes the contents to wp_insert_post via contentOverride, so the very first DB write of each post carries block markup (not raw HTML that gets transformed afterward). Use this in the streaming watch loop's compose-page-blocks judgment; reach for liberate_block_transform_apply only for re-composing already-imported posts.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (sidecar lives at /composed/, log is block-transform-log.jsonl)."},url:{type:"string",description:"Source URL \u2014 used for log entries and as the manifest lookup key when sourceHtml is omitted."},slug:{type:"string",description:"Post slug \u2014 determines the sidecar filename (composed/.blocks.html). Must match the WxrItem.slug the runner buffered."},blocks:{type:"string",description:"Composed block markup. Validated for parse_blocks roundtrip and against sourceHtml for text-substring containment."},sourceHtml:{type:"string",description:"Sanitized source HTML used for anti-hallucination output-verify. Optional \u2014 falls back to /screenshots/manifest.json lookup."},composedBy:{type:"string",description:'Provenance string for the log entry (default "compose-page-blocks@v1.0").'},source:{type:"string",enum:["heuristic","ai"],description:'Compose source flavour for the log entry (default "ai").'}},required:["outputDir","url","slug","blocks"]}},{name:"liberate_replicate_inventory",description:"Read a liberation outputDir and return a structured archetype inventory: counts per archetype (homepage/page/post/product/gallery/event), up to 3 representative URLs per archetype with their screenshot+html paths (selected by largest HTML \u2014 proxy for section count), product count from products.jsonl, and presence of design-foundation.json. Used by the replicate skill in Step 1 (Inventory). Throws when output.wxr is missing.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (must contain output.wxr)."}},required:["outputDir"]}},{name:"liberate_replicate_verify",description:"Capture replica screenshots at given URLs (desktop + mobile by default) against a running replica WP install and pair each viewport with the matching source screenshot from screenshots/manifest.json. Returns a structured pairing manifest the calling agent (vision-capable) uses for side-by-side comparison. Used by the replicate skill in Step 6 (Verify). Replica screenshots are written to ///.png \u2014 same shape as the source layout.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (contains screenshots/manifest.json and the source screenshots/)."},replicaBaseUrl:{type:"string",description:"Base URL of the running replica (e.g. https://my-site-replica.wp.local or http://localhost:8881). No trailing slash."},urls:{type:"array",items:{type:"string"},description:'Path-only URLs to verify (e.g. ["/", "/blog/post-1"]).'},viewports:{type:"array",items:{type:"string",enum:["desktop","mobile"]},description:'Viewports to capture. Default: ["desktop", "mobile"].'},outputSubdir:{type:"string",description:'Where in outputDir to write replica screenshots. Default: "replica-screenshots". Files land at //.png.'},cdpPort:{type:"number",description:"Connect to existing Chrome via CDP (otherwise launches a new browser)."}},required:["outputDir","replicaBaseUrl","urls"]}},{name:"liberate_refine_report",description:"Validate refine coverage for one page: reads /refine//*.json (one file per section, written by match-section) and enforces that EVERY finding id appears in exactly one of applied[]/skipped[]. Fails loudly, naming unaccounted IDs. match-page must not mark a page done until this passes.",inputSchema:{type:"object",properties:{outputDir:{type:"string",description:"Liberation output directory (contains refine// written by match-section)."},slug:{type:"string",description:"Page slug whose refine// directory to validate."}},required:["outputDir","slug"]}},{name:"liberate_compare",description:"Pixel-parity scorer (fixed viewport). Joins an origin screenshots dir to a replica screenshots dir by URL pathname, crops both full-page PNGs to the top 1440\xD7900 / 390\xD7844 region, and returns per-pathname desktop/mobile similarity scores (1 \u2212 diffPixels/total). Writes comparison.json (v2 with originHeight/replicaHeight/heightMismatchRatio per viewport) + diff PNGs into the replica dir. Writes magenta-padded .padded.png diff when height mismatch exceeds 2%. Both dirs must have the standard layout: manifest.json + desktop/.png + mobile/.png.",inputSchema:{type:"object",properties:{originDir:{type:"string",description:"Origin screenshots dir (manifest.json + desktop/ mobile/)."},replicaDir:{type:"string",description:"Replica screenshots dir, same layout. comparison.json + diff/ are written here."},viewports:{type:"array",items:{type:"string",enum:["desktop","mobile"]},description:"Viewports to score. Default: both."},diffOutputDir:{type:"string",description:"Where to write diff PNGs. Default: /diff."},floor:{type:"number",description:"Pass/fail score floor used for repair-tasks.json records. Default 0.99."},maxHeightDelta:{type:"number",description:"Height-gate tolerance in capture px (pre-crop |originH - replicaH|). Default 8."}},required:["originDir","replicaDir"]}},{name:"liberate_ingest_local_site",description:"Stage 1a of the owned-source path: ingest a local static-site directory (HTML/CSS/JS) and normalize each page into validated native Gutenberg block markup. Writes /composed/.blocks.html sidecars + /normalize-report.json. No Playwright/Studio. Downstream theme-scaffold/install/compare stages consume the sidecars.",inputSchema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the local static-site directory to ingest."},outputDir:{type:"string",description:"Liberation output directory for composed sidecars + normalize-report.json. Defaults to `dir`."},nativeBehaviors:{type:"boolean",description:"Detect catalog behaviors in the source css/js and emit dla/* Interactivity wrappers in the sidecars instead of core/group: uniform dla/reveal plus per-section DOM patterns (dla/tabs, dla/slider, dla/modal \u2014 verbatim inner markup). liberate_convert_local_site threads its own flag through here."}},required:["dir"]}},{name:"liberate_convert_local_site",description:"Stage 1b+1c of the owned-source path: full local-static-site \u2192 live Studio site. Reuses liberate_ingest_local_site (sidecars + normalize-report), optionally captures the source design (palette/typography/screenshots) and self-hosts Google Fonts, assembles the local block theme (core/navigation header from the nav graph, foundation-styled footer, no-title page templates), writes + activates it, creates WP Pages from the sidecars (idempotent via _source_url), sets the front page, assigns the page-local template, and optionally captures the WP replica + scores parity.",inputSchema:{type:"object",properties:{dir:{type:"string",description:"Absolute path to the local static-site directory."},studioSitePath:{type:"string",description:"Studio site path on host (e.g. ~/Studio/my-site \u2014 the dir studio site list prints, not wp-root)."},createSite:{type:"boolean",description:"Provision the Studio site via `studio site create` when none exists at studioSitePath (idempotent \u2014 an existing site is reused). Default false (errors if the site is absent). Admin creds via env WP_ADMIN_USER/WP_ADMIN_PASS; omitted \u2192 Studio auto-generates."},outputDir:{type:"string",description:"Liberation output dir for sidecars + reports. Defaults to `dir`."},themeSlug:{type:"string",description:"Theme slug (kebab-case). Default: local-site-theme."},siteTitle:{type:"string",description:"Site title for header/footer. Default: home page ."},skipDesign:{type:"boolean",description:"Skip source design capture (tokens/fonts) and compare; theme uses default styling."},skipCompare:{type:"boolean",description:"Skip the WP-replica screenshot + parity compare stage."},wpUrl:{type:"string",description:"Base URL for replica capture. Default: auto-resolved via wp option get siteurl (Studio assigns random ports); explicit value overrides."},carryCss:{type:"boolean",description:"Carry the source stylesheet into the theme (adapted for the block DOM). Default true \u2014 the stage-1d parity mechanism; tokens-only theming when false."},carryJs:{type:"boolean",description:"Carry the source scripts into the theme (enqueued footer, html.js gate added). Default true for identical replication."},nativeBehaviors:{type:"boolean",description:"Replace carried source JS with native Interactivity blocks (reveal, sticky, plus per-section tabs/slider/modal with verbatim inner markup); unmapped behaviors land in behavior-gaps.json. Forces carryJs off."},editableIslands:{type:"boolean",description:"Convert carried core/html islands into editable dla/editable-html blocks (text+image bindable, static-save, render-anywhere). Default true; set false to force plain core/html."},dataModel:{type:"boolean",description:"WordPress-driven data path: when a data-model.json (from the model-local-data skill) is present in outputDir/dir, register a CPT+taxonomy via generated mu-plugins, insert items idempotently, and replace empty JS-mount grids with native core/query loops (dla/data-card cards) while neutralizing the JS data-mounts and rebinding modal lookups to per-card DOM islands. Default on when the file exists; pass false to force off."},repair:{type:"boolean",description:"Deterministic parity repair loop: diff regions \u2192 computed-style probe \u2192 generated parity-patch.css \u2192 re-compare, bounded. Default true. No AI involved."},maxRepairRounds:{type:"number",description:"Max repair rounds (0-5). Default 2. Loop also stops early on allPass or an unchanged divergence fingerprint."},failOnConservationRailDrop:{type:"boolean",description:"Opt-in hard fail for local region-audit conservation: when true, unassigned nav/complementary rails with at least two links set isError. Default false (warn-only)."}},required:["dir","studioSitePath"]}},...JSON.parse(JSON.stringify(Object.entries(cTe).map(([e,t])=>({name:e,...t}))))]}));var WRt={liberate_compare:cke,liberate_data_model_scaffold:yBe,liberate_design_foundation_save:NBe,liberate_design_foundation_scaffold:bBe,liberate_design_foundation_validate:vBe,liberate_detect:gee,liberate_discover:Eee,liberate_block_transform_apply:eEe,liberate_block_compose:rEe,liberate_extract:bbe,liberate_extract_one:Ebe,liberate_media_install:Tbe,liberate_replicate_tick:Hbe,liberate_import:qEe,liberate_inspect:Cee,liberate_map_apis:AEe,liberate_preview:wCe,liberate_install_theme:vCe,liberate_theme_scaffold:KIe,liberate_probe:yEe,liberate_qa:fEe,liberate_replicate_inventory:UBe,liberate_replicate_verify:GBe,liberate_refine_report:aTe,liberate_screenshot:nxe,liberate_setup:vEe,liberate_paths:YEe,liberate_status:zEe,liberate_verify:CEe,liberate_cluster_pages:dke,liberate_section_extract:fke,liberate_compose_instantiate:pke,liberate_ingest_local_site:aD,liberate_convert_local_site:nTe,liberate_validate_artifacts:iTe,liberate_reconstruct_pages:Gwe,liberate_reconstruct_pages_carry:exe,liberate_blockify_wxr:rxe};function YRt(){return{adapters:V2e,findAdapter:VRt,textResult:GRt,errorResult:G2e,server:Ww}}Ww.setRequestHandler(ab,async e=>{let{name:t,arguments:r}=e.params,n=WRt[t];return n?n(r??{},YRt()):G2e(`Unknown tool: ${t}`)});async function JRt(){let e=new iB,t=async()=>{await Ww.close(),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t),await Ww.connect(e)}JRt().catch(e=>{console.error(e),process.exit(1)}); +/*! Bundled license information: + +undici/lib/web/fetch/body.js: + (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *) + +undici/lib/web/websocket/frame.js: + (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *) + +papaparse/papaparse.js: + (* @license + Papa Parse + v5.5.4 + https://github.com/mholt/PapaParse + License: MIT + *) + +cssesc/cssesc.js: + (*! https://mths.be/cssesc v3.0.0 by @mathias *) +*/ diff --git a/packages/data-liberation-agent/gemini-extension.json b/packages/data-liberation-agent/gemini-extension.json index e8db8a384d..dffb9a3148 100644 --- a/packages/data-liberation-agent/gemini-extension.json +++ b/packages/data-liberation-agent/gemini-extension.json @@ -11,8 +11,8 @@ "skills": "./skills/", "mcpServers": { "data-liberation": { - "command": "npx", - "args": ["tsx", "${extensionPath}${/}src${/}mcp-server.ts"], + "command": "node", + "args": ["${extensionPath}${/}scripts${/}mcp-launcher.mjs"], "cwd": "${extensionPath}" } } diff --git a/packages/data-liberation-agent/package.json b/packages/data-liberation-agent/package.json index d0199a9e70..1f178385c3 100644 --- a/packages/data-liberation-agent/package.json +++ b/packages/data-liberation-agent/package.json @@ -8,7 +8,8 @@ }, "scripts": { "import": "tsx src/cli.ts import", - "build": "tsc && node scripts/copy-runtime-assets.mjs", + "build": "tsc && node scripts/copy-runtime-assets.mjs && node scripts/build-mcp-bundle.mjs", + "build:mcp-bundle": "node scripts/build-mcp-bundle.mjs", "copy-runtime-assets": "node scripts/copy-runtime-assets.mjs", "test": "vitest run", "test:watch": "vitest", @@ -47,6 +48,7 @@ "@types/pixelmatch": "^5.2.6", "@types/pngjs": "^6.0.5", "@types/react": "^19.2.14", + "esbuild": "^0.28.0", "jsdom": "^26.1.0", "single-file-cli": "^2.0.83", "tsx": "^4.19.0", diff --git a/packages/data-liberation-agent/scripts/build-mcp-bundle.mjs b/packages/data-liberation-agent/scripts/build-mcp-bundle.mjs new file mode 100644 index 0000000000..3a959ceb94 --- /dev/null +++ b/packages/data-liberation-agent/scripts/build-mcp-bundle.mjs @@ -0,0 +1,81 @@ +// Bundle the MCP server into a single self-contained dist/mcp-server.bundle.mjs. +// +// Why: the Claude/Codex plugin installer copies this package's files into +// ~/.claude/plugins/cache/... WITHOUT node_modules — and inside the Studio npm +// workspace the dependencies are hoisted to the repo root anyway — so a +// `npx tsx src/mcp-server.ts` entry has nothing to import once installed as a +// plugin. The bundle inlines every dependency so `.mcp.json` can point a bare +// `node` at it. The committed bundle is the plugin's distribution artifact; +// regenerate it (npm run build:mcp-bundle) whenever src/ or dependencies +// change. +// +// Exceptions that stay external (resolved at runtime, degrade gracefully): +// - playwright: browser driver + downloaded browsers can't live in a bundle. +// Only ever loaded via guarded dynamic import (see lib/browser-kit), which +// already reports install guidance when missing. +// - single-file-cli: optional page-freeze asset, loaded lazily and only useful +// when playwright is present. +// +// One seam needs build-time help: modules resolve runtime assets (vendored +// PHP helpers, core-block-attrs.json, the block-fixer sidecar) relative to +// their own import.meta.url, and those per-module paths conflict once +// everything shares the bundle's URL. The plugin below rewrites +// import.meta.url in OUR src modules to point back at the original source +// file, relative to the bundle location — the src/ tree (including its .php +// and .json assets) ships with the plugin, so the lookups keep working. +import { build } from 'esbuild'; +import { relative, dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { readFile } from 'node:fs/promises'; + +const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const srcDir = resolve(pkgRoot, 'src'); +const outfile = resolve(pkgRoot, 'dist', 'mcp-server.bundle.mjs'); +const outDir = dirname(outfile); + +/** Rewrite import.meta.url in first-party modules to the original file's URL, + * expressed relative to the bundle so it survives being copied anywhere. */ +const perModuleImportMetaUrl = { + name: 'per-module-import-meta-url', + setup(pluginBuild) { + pluginBuild.onLoad({ filter: /\.(ts|tsx)$/ }, async (args) => { + if (!args.path.startsWith(srcDir)) return undefined; + const source = await readFile(args.path, 'utf8'); + if (!source.includes('import.meta.url')) return undefined; + const relFromBundle = relative(outDir, args.path).split('\\').join('/'); + const replacement = `new URL(${JSON.stringify(relFromBundle)}, import.meta.url).href`; + return { + contents: source.replaceAll('import.meta.url', replacement), + loader: args.path.endsWith('.tsx') ? 'tsx' : 'ts', + }; + }); + }, +}; + +const result = await build({ + entryPoints: [resolve(srcDir, 'mcp-server.ts')], + outfile, + bundle: true, + platform: 'node', + format: 'esm', + target: 'node20', + minify: true, + sourcemap: false, + metafile: true, + logLevel: 'info', + external: ['playwright', 'single-file-cli'], + plugins: [perModuleImportMetaUrl], + // Bundled CJS dependencies may call require() at runtime; ESM output has + // no ambient require, so provide one anchored to the bundle. + banner: { + js: [ + "import { createRequire as __bundleCreateRequire } from 'node:module';", + 'const require = __bundleCreateRequire(import.meta.url);', + ].join('\n'), + }, +}); + +const bytes = Object.values(result.metafile.outputs).reduce((sum, o) => sum + o.bytes, 0); +process.stdout.write( + `build-mcp-bundle: wrote ${relative(pkgRoot, outfile)} (${(bytes / 1024 / 1024).toFixed(1)} MB)\n` +); diff --git a/packages/data-liberation-agent/scripts/mcp-launcher.mjs b/packages/data-liberation-agent/scripts/mcp-launcher.mjs new file mode 100644 index 0000000000..5a8f4991c3 --- /dev/null +++ b/packages/data-liberation-agent/scripts/mcp-launcher.mjs @@ -0,0 +1,61 @@ +// MCP server launcher — picks the right way to run the server for where this +// package is sitting. `.mcp.json`, `.mcp.codex.json`, and gemini-extension.json +// point here. +// +// Two situations share one manifest: +// - Development checkout (Studio workspace or the standalone repo): +// node_modules are resolvable, and the server must run from src/ via tsx so +// edits take effect without any build step. +// - Installed plugin (~/.claude/plugins/cache/...): the installer copies this +// package from git verbatim — no node_modules, no build hooks — so the only +// runnable form is the self-contained esbuild bundle that CI builds and +// publishes on the `plugin-dist` branch (see scripts/build-mcp-bundle.mjs +// and .github/workflows/publish-plugin-dist.yml). +// +// Detection: dev mode requires BOTH tsx and a real dependency to resolve from +// the package root (two checks so a stray ~/node_modules can't fake it). +// Source is preferred over the bundle so a dev checkout never runs a stale +// dist by accident. +import { spawn } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..'); +const srcEntry = join(pkgRoot, 'src', 'mcp-server.ts'); +const bundle = join(pkgRoot, 'dist', 'mcp-server.bundle.mjs'); + +function resolveDevTsx() { + try { + const req = createRequire(join(pkgRoot, 'package.json')); + req.resolve('@modelcontextprotocol/sdk/package.json'); + return req.resolve('tsx/cli'); + } catch { + return null; + } +} + +const tsxCli = existsSync(srcEntry) ? resolveDevTsx() : null; + +if (tsxCli) { + const child = spawn(process.execPath, [tsxCli, srcEntry], { + cwd: pkgRoot, + stdio: 'inherit', + }); + child.on('exit', (code, signal) => process.exit(signal ? 1 : (code ?? 1))); + child.on('error', (err) => { + console.error(`[data-liberation] failed to start tsx: ${err.message}`); + process.exit(1); + }); +} else if (existsSync(bundle)) { + await import(pathToFileURL(bundle).href); +} else { + console.error( + '[data-liberation] Cannot start the MCP server: no resolvable dependencies for src/ and no dist/mcp-server.bundle.mjs.\n' + + 'In a development checkout, run `npm install` first.\n' + + 'As a plugin, install from the published marketplace (the `plugin-dist` branch), which ships the prebuilt bundle — ' + + 'or build one locally with `npm run build:mcp-bundle`.' + ); + process.exit(1); +} diff --git a/packages/data-liberation-agent/src/lib/preview/studio.ts b/packages/data-liberation-agent/src/lib/preview/studio.ts index 6a87524ab0..fb1fc0a8b2 100644 --- a/packages/data-liberation-agent/src/lib/preview/studio.ts +++ b/packages/data-liberation-agent/src/lib/preview/studio.ts @@ -407,6 +407,10 @@ export async function startStudioPreview(opts: StartStudioOpts): Promise<StartPr '--name', name, '--path', sitePath, '--blueprint', blueprintPath, + // Studio 1.12+ defaults to the native runtime, which drops the + // `/wordpress` VFS mount our `wp eval-file` script paths rely on; + // pin the sandbox runtime until those callers are runtime-aware. + '--runtime', 'sandbox', '--skip-browser', '--skip-log-details', '--start',