From 27cb7448b3e7db593b0071bf736633a8bf7d4abd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:02:21 +0000 Subject: [PATCH 1/3] Add Google Stitch skills to .claude/skills Vendored from google-labs-code/stitch-skills (commit 4cf4db8, Apache-2.0) because the plugins CLI does not support project scope for this source. Attribution and a CLAUDE.md note added. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_016tciSQigy3LAU3wXFVSnHR --- .claude/skills/ATTRIBUTION.md | 19 + .claude/skills/LICENSE.stitch-skills | 201 +++ .claude/skills/code-to-design/SKILL.md | 78 + .claude/skills/design-md/README.md | 34 + .claude/skills/design-md/SKILL.md | 172 ++ .claude/skills/design-md/examples/DESIGN.md | 154 ++ .claude/skills/enhance-prompt/README.md | 34 + .claude/skills/enhance-prompt/SKILL.md | 204 +++ .../enhance-prompt/references/KEYWORDS.md | 114 ++ .claude/skills/extract-design-md/SKILL.md | 365 ++++ .../extract-design-md/examples/DESIGN.md | 210 +++ .../extract-design-md/references/angular.md | 122 ++ .../extract-design-md/references/plain-css.md | 161 ++ .../references/react-tailwind.md | 157 ++ .../extract-design-md/references/svelte.md | 101 ++ .../extract-design-md/references/vue.md | 107 ++ .claude/skills/extract-static-html/SKILL.md | 244 +++ .../scripts/extract_inline_html.ts | 1025 ++++++++++++ .../scripts/post_process.ts | 498 ++++++ .../extract-static-html/scripts/snapshot.ts | 1470 +++++++++++++++++ .claude/skills/generate-design/SKILL.md | 339 ++++ .../examples/enhanced-prompt.md | 41 + .../references/design-mappings.md | 46 + .../references/prompt-keywords.md | 131 ++ .claude/skills/manage-design-system/SKILL.md | 132 ++ .../examples/metadata.json | 23 + .../reference/tool-schema.md | 162 ++ .claude/skills/react-components/README.md | 36 + .claude/skills/react-components/SKILL.md | 110 ++ .../examples/gold-standard-card.tsx | 65 + .../skills/react-components/package-lock.json | 231 +++ .claude/skills/react-components/package.json | 16 + .../resources/architecture-checklist.md | 15 + .../resources/component-template.tsx | 37 + .../resources/stitch-api-reference.md | 14 + .../resources/style-guide.json | 27 + .../react-components/scripts/fetch-stitch.sh | 30 + .../react-components/scripts/validate.js | 82 + .claude/skills/react-native/README.md | 36 + .claude/skills/react-native/SKILL.md | 172 ++ .../examples/gold-standard-card.tsx | 167 ++ .claude/skills/react-native/package-lock.json | 283 ++++ .claude/skills/react-native/package.json | 16 + .../resources/architecture-checklist.md | 37 + .../resources/component-template.tsx | 24 + .../react-native/scripts/fetch-stitch.sh | 31 + .../skills/react-native/scripts/validate.js | 124 ++ .claude/skills/react-vite-dashboard/README.md | 24 + .claude/skills/react-vite-dashboard/SKILL.md | 87 + .claude/skills/remotion/README.md | 105 ++ .claude/skills/remotion/SKILL.md | 393 +++++ .../examples/WalkthroughComposition.tsx | 78 + .claude/skills/remotion/examples/screens.json | 56 + .../resources/composition-checklist.md | 124 ++ .../resources/screen-slide-template.tsx | 123 ++ .../remotion/scripts/download-stitch-asset.sh | 38 + .claude/skills/shadcn-ui/README.md | 248 +++ .claude/skills/shadcn-ui/SKILL.md | 326 ++++ .../skills/shadcn-ui/examples/auth-layout.tsx | 177 ++ .../skills/shadcn-ui/examples/data-table.tsx | 313 ++++ .../shadcn-ui/examples/form-pattern.tsx | 177 ++ .../shadcn-ui/resources/component-catalog.md | 481 ++++++ .../resources/customization-guide.md | 516 ++++++ .../shadcn-ui/resources/migration-guide.md | 463 ++++++ .../skills/shadcn-ui/resources/setup-guide.md | 412 +++++ .../skills/shadcn-ui/scripts/verify-setup.sh | 134 ++ .claude/skills/site-md/SKILL.md | 69 + .claude/skills/stitch-loop/README.md | 54 + .claude/skills/stitch-loop/SKILL.md | 263 +++ .claude/skills/stitch-loop/examples/SITE.md | 73 + .../stitch-loop/examples/next-prompt.md | 25 + .../stitch-loop/resources/baton-schema.md | 61 + .../stitch-loop/resources/site-template.md | 104 ++ .claude/skills/taste-design/SKILL.md | 191 +++ .../skills/taste-design/resources/DESIGN.md | 124 ++ .claude/skills/upload-to-stitch/SKILL.md | 101 ++ .../scripts/upload_to_stitch.py | 268 +++ CLAUDE.md | 1 + 78 files changed, 13506 insertions(+) create mode 100644 .claude/skills/LICENSE.stitch-skills create mode 100644 .claude/skills/code-to-design/SKILL.md create mode 100644 .claude/skills/design-md/README.md create mode 100644 .claude/skills/design-md/SKILL.md create mode 100644 .claude/skills/design-md/examples/DESIGN.md create mode 100644 .claude/skills/enhance-prompt/README.md create mode 100644 .claude/skills/enhance-prompt/SKILL.md create mode 100644 .claude/skills/enhance-prompt/references/KEYWORDS.md create mode 100644 .claude/skills/extract-design-md/SKILL.md create mode 100644 .claude/skills/extract-design-md/examples/DESIGN.md create mode 100644 .claude/skills/extract-design-md/references/angular.md create mode 100644 .claude/skills/extract-design-md/references/plain-css.md create mode 100644 .claude/skills/extract-design-md/references/react-tailwind.md create mode 100644 .claude/skills/extract-design-md/references/svelte.md create mode 100644 .claude/skills/extract-design-md/references/vue.md create mode 100644 .claude/skills/extract-static-html/SKILL.md create mode 100644 .claude/skills/extract-static-html/scripts/extract_inline_html.ts create mode 100644 .claude/skills/extract-static-html/scripts/post_process.ts create mode 100644 .claude/skills/extract-static-html/scripts/snapshot.ts create mode 100644 .claude/skills/generate-design/SKILL.md create mode 100644 .claude/skills/generate-design/examples/enhanced-prompt.md create mode 100644 .claude/skills/generate-design/references/design-mappings.md create mode 100644 .claude/skills/generate-design/references/prompt-keywords.md create mode 100644 .claude/skills/manage-design-system/SKILL.md create mode 100644 .claude/skills/manage-design-system/examples/metadata.json create mode 100644 .claude/skills/manage-design-system/reference/tool-schema.md create mode 100644 .claude/skills/react-components/README.md create mode 100644 .claude/skills/react-components/SKILL.md create mode 100644 .claude/skills/react-components/examples/gold-standard-card.tsx create mode 100644 .claude/skills/react-components/package-lock.json create mode 100644 .claude/skills/react-components/package.json create mode 100644 .claude/skills/react-components/resources/architecture-checklist.md create mode 100644 .claude/skills/react-components/resources/component-template.tsx create mode 100644 .claude/skills/react-components/resources/stitch-api-reference.md create mode 100644 .claude/skills/react-components/resources/style-guide.json create mode 100755 .claude/skills/react-components/scripts/fetch-stitch.sh create mode 100644 .claude/skills/react-components/scripts/validate.js create mode 100644 .claude/skills/react-native/README.md create mode 100644 .claude/skills/react-native/SKILL.md create mode 100644 .claude/skills/react-native/examples/gold-standard-card.tsx create mode 100644 .claude/skills/react-native/package-lock.json create mode 100644 .claude/skills/react-native/package.json create mode 100644 .claude/skills/react-native/resources/architecture-checklist.md create mode 100644 .claude/skills/react-native/resources/component-template.tsx create mode 100755 .claude/skills/react-native/scripts/fetch-stitch.sh create mode 100644 .claude/skills/react-native/scripts/validate.js create mode 100644 .claude/skills/react-vite-dashboard/README.md create mode 100644 .claude/skills/react-vite-dashboard/SKILL.md create mode 100644 .claude/skills/remotion/README.md create mode 100644 .claude/skills/remotion/SKILL.md create mode 100644 .claude/skills/remotion/examples/WalkthroughComposition.tsx create mode 100644 .claude/skills/remotion/examples/screens.json create mode 100644 .claude/skills/remotion/resources/composition-checklist.md create mode 100644 .claude/skills/remotion/resources/screen-slide-template.tsx create mode 100755 .claude/skills/remotion/scripts/download-stitch-asset.sh create mode 100644 .claude/skills/shadcn-ui/README.md create mode 100644 .claude/skills/shadcn-ui/SKILL.md create mode 100644 .claude/skills/shadcn-ui/examples/auth-layout.tsx create mode 100644 .claude/skills/shadcn-ui/examples/data-table.tsx create mode 100644 .claude/skills/shadcn-ui/examples/form-pattern.tsx create mode 100644 .claude/skills/shadcn-ui/resources/component-catalog.md create mode 100644 .claude/skills/shadcn-ui/resources/customization-guide.md create mode 100644 .claude/skills/shadcn-ui/resources/migration-guide.md create mode 100644 .claude/skills/shadcn-ui/resources/setup-guide.md create mode 100644 .claude/skills/shadcn-ui/scripts/verify-setup.sh create mode 100644 .claude/skills/site-md/SKILL.md create mode 100644 .claude/skills/stitch-loop/README.md create mode 100644 .claude/skills/stitch-loop/SKILL.md create mode 100644 .claude/skills/stitch-loop/examples/SITE.md create mode 100644 .claude/skills/stitch-loop/examples/next-prompt.md create mode 100644 .claude/skills/stitch-loop/resources/baton-schema.md create mode 100644 .claude/skills/stitch-loop/resources/site-template.md create mode 100644 .claude/skills/taste-design/SKILL.md create mode 100644 .claude/skills/taste-design/resources/DESIGN.md create mode 100644 .claude/skills/upload-to-stitch/SKILL.md create mode 100644 .claude/skills/upload-to-stitch/scripts/upload_to_stitch.py diff --git a/.claude/skills/ATTRIBUTION.md b/.claude/skills/ATTRIBUTION.md index 3a4f540..b1bbd0e 100644 --- a/.claude/skills/ATTRIBUTION.md +++ b/.claude/skills/ATTRIBUTION.md @@ -29,6 +29,25 @@ The following skills were installed from third-party sources. as vanilla HTML/CSS: `taste-skill` for building new pages (it built /merge/, /studio-intelligence/ and the changelog), `redesign-skill` for polishing existing ones. +## stitch-skills +- Source: https://github.com/google-labs-code/stitch-skills +- Author: Google Labs +- License: Apache-2.0 (see `LICENSE.stitch-skills`) +- Version: commit 4cf4db8 +- Installed: 2026-11-19 +- Skills: code-to-design, design-md, enhance-prompt, extract-design-md, + extract-static-html, generate-design, manage-design-system, react-components, + react-native, react-vite-dashboard, remotion, shadcn-ui, site-md, stitch-loop, + taste-design, upload-to-stitch +- Copied unmodified from `plugins/*/skills/` into one flat folder, because + `npx plugins add ... --scope project` does not support this source for Claude Code. + Paths inside the skills that start with `stitch-skills/plugins//skills/` + map to `.claude/skills/` here. +- Most of these need the Google Stitch MCP server and a Stitch API key, which this + repo does not configure. The React, React Native, shadcn and Remotion skills target + other stacks; they are not conventions for this repo (vanilla JS + Vite). + `taste-skill` stays the required design skill for the marketing pages. + These were vendored directly into `.claude/skills/` (rather than installed via the Claude Code plugin marketplace) so they are version-controlled and available to all sessions on this repo, including Claude Code on the web. diff --git a/.claude/skills/LICENSE.stitch-skills b/.claude/skills/LICENSE.stitch-skills new file mode 100644 index 0000000..b31ddff --- /dev/null +++ b/.claude/skills/LICENSE.stitch-skills @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative + Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/.claude/skills/code-to-design/SKILL.md b/.claude/skills/code-to-design/SKILL.md new file mode 100644 index 0000000..c70c6f9 --- /dev/null +++ b/.claude/skills/code-to-design/SKILL.md @@ -0,0 +1,78 @@ +--- +name: stitch::code-to-design +description: >- + Convert frontend code (Vite, React, Angular, Vue, etc.) to a Stitch Design by chaining + static HTML extraction, design system extraction, and file upload. **ALWAYS** use this skill when the user's intent is to move existing web apps or React/Angular/Vue components into Stitch (e.g., requests to "save", "migrate", or "upload"). You must use this skill even for simple "save" operations, as it is the only way to ensure the design system is extracted and assets are properly linked. +allowed-tools: + - "stitch*:*" + - "Bash" + - "Read" + - "Write" + - "web_fetch" +--- + +# Code to Design + +Transform your existing frontend code (React + Vite, Next.js, Angular, Vue, etc.) into a Stitch Design so you can iterate and improve it using Stitch. + +This skill orchestrates three other skills in sequence: +1. `extract-static-html`: Extract a single self-contained HTML file from your build output or running dev server (e.g., Vite dev server or Angular CLI `ng serve`). +2. `extract-design-md`: Analyze the source code (including Angular `angular.json`, external `.html` templates, theme files, and components) to create a design system (DESIGN.md). +3. `upload-to-stitch`: Upload that HTML file and the design system to your Stitch project. + +## Workflow + +Follow these steps to convert your existing code. + +### Prerequisites + +- A running local dev server (e.g. `npm run dev`, `ng serve`) OR a built web application directory containing `index.html` and assets. +- Target Stitch `projectId` (use `list_projects` if unknown). + +### Steps + +#### 1. Extract Self-Contained HTML + +Delegate to the `extract-static-html` skill to generate a standalone HTML file. +Read [skills/extract-static-html/SKILL.md](../extract-static-html/SKILL.md) for detailed instructions and script usage. + +Expected output: A single file like `/path/to/extracted/standalone.html`. + +#### 2. Verify HTML (Optional — User-Driven) + +After extraction, inform the user of the output file path so they can manually +verify in a browser if desired. **Do not block on verification** — proceed +directly to Step 3. + +If the user reports issues after reviewing, fix them before continuing. + +#### 3. Extract Design System (File) + +Delegate to the `extract-design-md` skill to analyze the project's source files +(components, stylesheets, theme configs) and produce a design system. Read +[skills/extract-design-md/SKILL.md](../extract-design-md/SKILL.md) for the +full analysis workflow. + +Write `.stitch/DESIGN.md` following the `extract-design-md` skill's output +structure. + +#### 4. Upload DESIGN.md and Create Design System in Stitch + +Delegate to the `manage-design-system` skill to upload the `DESIGN.md` and +create the design system in Stitch. Read +[skills/manage-design-system/SKILL.md](../manage-design-system/SKILL.md) for +the full workflow (upload script usage, `create_design_system_from_design_md` +call, and required schemas). Pass +`--generated-by 'stitch::code-to-design'` when uploading. + +#### 5. Upload HTML to Stitch + +Use the same `upload-to-stitch` skill's script to upload the extracted HTML file. +Read [skills/upload-to-stitch/SKILL.md](../upload-to-stitch/SKILL.md) for detailed instructions and script usage. + +You will need: +- The path to the standalone HTML file generated in Step 1. +- Your Stitch API Key (same key used in Step 4). +- The target `projectId`. +- The `--generated-by` argument set to `'stitch::extract-static-html'`. +- The `--title` argument set to the **route path** of the page (e.g., `'/dashboard'`, `'/settings/profile'`, `'/inbox'`) so that the screen name/title in Stitch clearly identifies its route in the application. \ No newline at end of file diff --git a/.claude/skills/design-md/README.md b/.claude/skills/design-md/README.md new file mode 100644 index 0000000..8f52207 --- /dev/null +++ b/.claude/skills/design-md/README.md @@ -0,0 +1,34 @@ +# Stitch Design System Documentation Skill + +## Install + +```bash +npx skills add google-labs-code/stitch-skills --skill design-md --global +``` + +## Example Prompt + +```text +Analyze my Furniture Collection project's Home screen and generate a comprehensive DESIGN.md file documenting the design system. +``` + +## Skill Structure + +This repository follows the **Agent Skills** open standard. Each skill is self-contained with its own logic, workflow, and reference materials. + +```text +design-md/ +├── SKILL.md — Core instructions & workflow +├── examples/ — Sample DESIGN.md outputs +└── README.md — This file +``` + +## How it Works + +When activated, the agent follows a structured design analysis pipeline: + +1. **Retrieval**: Uses the Stitch MCP Server to fetch project screens, HTML code, and design metadata. +2. **Extraction**: Identifies design tokens including colors, typography, spacing, and component patterns. +3. **Translation**: Converts technical CSS/Tailwind values into descriptive, natural design language. +4. **Synthesis**: Generates a comprehensive DESIGN.md following the semantic design system format. +5. **Alignment**: Ensures output follows Stitch Effective Prompting Guide principles for optimal screen generation. diff --git a/.claude/skills/design-md/SKILL.md b/.claude/skills/design-md/SKILL.md new file mode 100644 index 0000000..c29a0fe --- /dev/null +++ b/.claude/skills/design-md/SKILL.md @@ -0,0 +1,172 @@ +--- +name: design-md +description: Analyze Stitch projects and synthesize a semantic design system into DESIGN.md files +allowed-tools: + - "stitch*:*" + - "Read" + - "Write" + - "web_fetch" +--- + +# Stitch DESIGN.md Skill + +You are an expert Design Systems Lead. Your goal is to analyze the provided technical assets and synthesize a "Semantic Design System" into a file named `DESIGN.md`. + +## Overview + +This skill helps you create `DESIGN.md` files that serve as the "source of truth" for prompting Stitch to generate new screens that align perfectly with existing design language. Stitch interprets design through "Visual Descriptions" supported by specific color values. + +## Prerequisites + +- Access to the Stitch MCP Server +- A Stitch project with at least one designed screen +- Access to the Stitch Effective Prompting Guide: https://stitch.withgoogle.com/docs/learn/prompting/ + +## The Goal + +The `DESIGN.md` file will serve as the "source of truth" for prompting Stitch to generate new screens that align perfectly with the existing design language. Stitch interprets design through "Visual Descriptions" supported by specific color values. + +## Retrieval and Networking + +To analyze a Stitch project, you must retrieve screen metadata and design assets using the Stitch MCP Server tools: + +1. **Namespace discovery**: Run `list_tools` to find the Stitch MCP prefix. Use this prefix (e.g., `mcp_stitch:`) for all subsequent calls. + +2. **Project lookup** (if Project ID is not provided): + - Call `[prefix]:list_projects` with `filter: "view=owned"` to retrieve all user projects + - Identify the target project by title or URL pattern + - Extract the Project ID from the `name` field (e.g., `projects/13534454087919359824`) + +3. **Screen lookup** (if Screen ID is not provided): + - Call `[prefix]:list_screens` with the `projectId` (just the numeric ID, not the full path) + - Review screen titles to identify the target screen (e.g., "Home", "Landing Page") + - Extract the Screen ID from the screen's `name` field + +4. **Metadata fetch**: + - Call `[prefix]:get_screen` with both `projectId` and `screenId` (both as numeric IDs only) + - This returns the complete screen object including: + - `screenshot.downloadUrl` - Visual reference of the design + - `htmlCode.downloadUrl` - Full HTML/CSS source code + - `width`, `height`, `deviceType` - Screen dimensions and target platform + - Project metadata including `designTheme` with color and style information + +5. **Asset download**: + - Use `web_fetch` or `read_url_content` to download the HTML code from `htmlCode.downloadUrl` + - Optionally download the screenshot from `screenshot.downloadUrl` for visual reference + - Parse the HTML to extract Tailwind classes, custom CSS, and component patterns + +6. **Project metadata extraction**: + - Call `[prefix]:get_project` with the project `name` (full path: `projects/{id}`) to get: + - `designTheme` object with color mode, fonts, roundness, custom colors + - Project-level design guidelines and descriptions + - Device type preferences and layout principles + +## Analysis & Synthesis Instructions + +### 1. Extract Project Identity (JSON) +- Locate the Project Title +- Locate the specific Project ID (e.g., from the `name` field in the JSON) + +### 2. Define the Atmosphere (Image/HTML) +Evaluate the screenshot and HTML structure to capture the overall "vibe." Use evocative adjectives to describe the mood (e.g., "Airy," "Dense," "Minimalist," "Utilitarian"). + +### 3. Map the Color Palette (Tailwind Config/JSON) +Identify the key colors in the system. For each color, provide: +- A descriptive, natural language name that conveys its character (e.g., "Deep Muted Teal-Navy") +- The specific hex code in parentheses for precision (e.g., "#294056") +- Its specific functional role (e.g., "Used for primary actions") + +### 4. Translate Geometry & Shape (CSS/Tailwind) +Convert technical `border-radius` and layout values into physical descriptions: +- Describe `rounded-full` as "Pill-shaped" +- Describe `rounded-lg` as "Subtly rounded corners" +- Describe `rounded-none` as "Sharp, squared-off edges" + +### 5. Describe Depth & Elevation +Explain how the UI handles layers. Describe the presence and quality of shadows (e.g., "Flat," "Whisper-soft diffused shadows," or "Heavy, high-contrast drop shadows"). + +## Output Guidelines + +- **Language:** Use descriptive design terminology and natural language exclusively +- **Format:** Generate a clean Markdown file following the structure below +- **Precision:** Include exact hex codes for colors while using descriptive names +- **Context:** Explain the "why" behind design decisions, not just the "what" + +## Output Format (DESIGN.md Structure) + +```markdown +# Design System: [Project Title] +**Project ID:** [Insert Project ID Here] + +## 1. Visual Theme & Atmosphere +(Description of the mood, density, and aesthetic philosophy.) + +## 2. Color Palette & Roles +(List colors by Descriptive Name + Hex Code + Functional Role.) + +## 3. Typography Rules +(Description of font family, weight usage for headers vs. body, and letter-spacing character.) + +## 4. Component Stylings +* **Buttons:** (Shape description, color assignment, behavior). +* **Cards/Containers:** (Corner roundness description, background color, shadow depth). +* **Inputs/Forms:** (Stroke style, background). + +## 5. Layout Principles +(Description of whitespace strategy, margins, and grid alignment.) +``` + +## Usage Example + +To use this skill for the Furniture Collection project: + +1. **Retrieve project information:** + ``` + Use the Stitch MCP Server to get the Furniture Collection project + ``` + +2. **Get the Home page screen details:** + ``` + Retrieve the Home page screen's code, image, and screen object information + ``` + +3. **Reference best practices:** + ``` + Review the Stitch Effective Prompting Guide at: + https://stitch.withgoogle.com/docs/learn/prompting/ + ``` + +4. **Analyze and synthesize:** + - Extract all relevant design tokens from the screen + - Translate technical values into descriptive language + - Organize information according to the DESIGN.md structure + +5. **Generate the file:** + - Create `DESIGN.md` in the project directory + - Follow the prescribed format exactly + - Ensure all color codes are accurate + - Use evocative, designer-friendly language + +## Best Practices + +- **Be Descriptive:** Avoid generic terms like "blue" or "rounded." Use "Ocean-deep Cerulean (#0077B6)" or "Gently curved edges" +- **Be Functional:** Always explain what each design element is used for +- **Be Consistent:** Use the same terminology throughout the document +- **Be Visual:** Help readers visualize the design through your descriptions +- **Be Precise:** Include exact values (hex codes, pixel values) in parentheses after natural language descriptions + +## Tips for Success + +1. **Start with the big picture:** Understand the overall aesthetic before diving into details +2. **Look for patterns:** Identify consistent spacing, sizing, and styling patterns +3. **Think semantically:** Name colors by their purpose, not just their appearance +4. **Consider hierarchy:** Document how visual weight and importance are communicated +5. **Reference the guide:** Use language and patterns from the Stitch Effective Prompting Guide + +## Common Pitfalls to Avoid + +- ❌ Using technical jargon without translation (e.g., "rounded-xl" instead of "generously rounded corners") +- ❌ Omitting color codes or using only descriptive names +- ❌ Forgetting to explain functional roles of design elements +- ❌ Being too vague in atmosphere descriptions +- ❌ Ignoring subtle design details like shadows or spacing patterns diff --git a/.claude/skills/design-md/examples/DESIGN.md b/.claude/skills/design-md/examples/DESIGN.md new file mode 100644 index 0000000..be0855f --- /dev/null +++ b/.claude/skills/design-md/examples/DESIGN.md @@ -0,0 +1,154 @@ +# Design System: Furniture Collections List +**Project ID:** 13534454087919359824 + +## 1. Visual Theme & Atmosphere + +The Furniture Collections List embodies a **sophisticated, minimalist sanctuary** that marries the pristine simplicity of Scandinavian design with the refined visual language of luxury editorial presentation. The interface feels **spacious and tranquil**, prioritizing breathing room and visual clarity above all else. The design philosophy is gallery-like and photography-first, allowing each furniture piece to command attention as an individual art object. + +The overall mood is **airy yet grounded**, creating an aspirational aesthetic that remains approachable and welcoming. The interface feels **utilitarian in its restraint** but elegant in its execution, with every element serving a clear purpose while maintaining visual sophistication. The atmosphere evokes the serene ambiance of a high-end furniture showroom where customers can browse thoughtfully without visual overwhelm. + +**Key Characteristics:** +- Expansive whitespace creating generous breathing room between elements +- Clean, architectural grid system with structured content blocks +- Photography-first presentation with minimal UI interference +- Whisper-soft visual hierarchy that guides without shouting +- Refined, understated interactive elements +- Professional yet inviting editorial tone + +## 2. Color Palette & Roles + +### Primary Foundation +- **Warm Barely-There Cream** (#FCFAFA) – Primary background color. Creates an almost imperceptible warmth that feels more inviting than pure white, serving as the serene canvas for the entire experience. +- **Crisp Very Light Gray** (#F5F5F5) – Secondary surface color used for card backgrounds and content areas. Provides subtle visual separation while maintaining the airy, ethereal quality. + +### Accent & Interactive +- **Deep Muted Teal-Navy** (#294056) – The sole vibrant accent in the palette. Used exclusively for primary call-to-action buttons (e.g., "Shop Now", "View all products"), active navigation links, selected filter states, and subtle interaction highlights. This sophisticated anchor color creates visual focus points without disrupting the serene neutral foundation. + +### Typography & Text Hierarchy +- **Charcoal Near-Black** (#2C2C2C) – Primary text color for headlines and product names. Provides strong readable contrast while being softer and more refined than pure black. +- **Soft Warm Gray** (#6B6B6B) – Secondary text used for body copy, product descriptions, and supporting metadata. Creates clear typographic hierarchy without harsh contrast. +- **Ultra-Soft Silver Gray** (#E0E0E0) – Tertiary color for borders, dividers, and subtle structural elements. Creates separation so gentle it's almost imperceptible. + +### Functional States (Reserved for system feedback) +- **Success Moss** (#10B981) – Stock availability, confirmation states, positive indicators +- **Alert Terracotta** (#EF4444) – Low stock warnings, error states, critical alerts +- **Informational Slate** (#64748B) – Neutral system messages, informational callouts + +## 3. Typography Rules + +**Primary Font Family:** Manrope +**Character:** Modern, geometric sans-serif with gentle humanist warmth. Slightly rounded letterforms that feel contemporary yet approachable. + +### Hierarchy & Weights +- **Display Headlines (H1):** Semi-bold weight (600), generous letter-spacing (0.02em for elegance), 2.75-3.5rem size. Used sparingly for hero sections and major page titles. +- **Section Headers (H2):** Semi-bold weight (600), subtle letter-spacing (0.01em), 2-2.5rem size. Establishes clear content zones and featured collections. +- **Subsection Headers (H3):** Medium weight (500), normal letter-spacing, 1.5-1.75rem size. Product names and category labels. +- **Body Text:** Regular weight (400), relaxed line-height (1.7), 1rem size. Descriptions and supporting content prioritize comfortable readability. +- **Small Text/Meta:** Regular weight (400), slightly tighter line-height (1.5), 0.875rem size. Prices, availability, and metadata remain legible but visually recessive. +- **CTA Buttons:** Medium weight (500), subtle letter-spacing (0.01em), 1rem size. Balanced presence without visual aggression. + +### Spacing Principles +- Headers use slightly expanded letter-spacing for refined elegance +- Body text maintains generous line-height (1.7) for effortless reading +- Consistent vertical rhythm with 2-3rem between related text blocks +- Large margins (4-6rem) between major sections to reinforce spaciousness + +## 4. Component Stylings + +### Buttons +- **Shape:** Subtly rounded corners (8px/0.5rem radius) – approachable and modern without appearing playful or childish +- **Primary CTA:** Deep Muted Teal-Navy (#294056) background with pure white text, comfortable padding (0.875rem vertical, 2rem horizontal) +- **Hover State:** Subtle darkening to deeper navy, smooth 250ms ease-in-out transition +- **Focus State:** Soft outer glow in the primary color for keyboard navigation accessibility +- **Secondary CTA (if needed):** Outlined style with Deep Muted Teal-Navy border, transparent background, hover fills with whisper-soft teal tint + +### Cards & Product Containers +- **Corner Style:** Gently rounded corners (12px/0.75rem radius) creating soft, refined edges +- **Background:** Alternates between Warm Barely-There Cream and Crisp Very Light Gray based on layering needs +- **Shadow Strategy:** Flat by default. On hover, whisper-soft diffused shadow appears (`0 2px 8px rgba(0,0,0,0.06)`) creating subtle depth +- **Border:** Optional hairline border (1px) in Ultra-Soft Silver Gray for delicate definition when shadows aren't present +- **Internal Padding:** Generous 2-2.5rem creating comfortable breathing room for content +- **Image Treatment:** Full-bleed at the top of cards, square or 4:3 ratio, seamless edge-to-edge presentation + +### Navigation +- **Style:** Clean horizontal layout with generous spacing (2-3rem) between menu items +- **Typography:** Medium weight (500), subtle uppercase, expanded letter-spacing (0.06em) for refined sophistication +- **Default State:** Charcoal Near-Black text +- **Active/Hover State:** Smooth 200ms color transition to Deep Muted Teal-Navy +- **Active Indicator:** Thin underline (2px) in Deep Muted Teal-Navy appearing below current section +- **Mobile:** Converts to elegant hamburger menu with sliding drawer + +### Inputs & Forms +- **Stroke Style:** Refined 1px border in Soft Warm Gray +- **Background:** Warm Barely-There Cream with transition to Crisp Very Light Gray on focus +- **Corner Style:** Matching button roundness (8px/0.5rem) for visual consistency +- **Focus State:** Border color shifts to Deep Muted Teal-Navy with subtle outer glow +- **Padding:** Comfortable 0.875rem vertical, 1.25rem horizontal for touch-friendly targets +- **Placeholder Text:** Ultra-Soft Silver Gray, elegant and unobtrusive + +### Product Cards (Specific Pattern) +- **Image Area:** Square (1:1) or landscape (4:3) ratio filling card width completely +- **Content Stack:** Product name (H3), brief descriptor, material/finish, price +- **Price Display:** Emphasized with semi-bold weight (600) in Charcoal Near-Black +- **Hover Behavior:** Gentle lift effect (translateY -4px) combined with enhanced shadow +- **Spacing:** Consistent 1.5rem internal padding below image + +## 5. Layout Principles + +### Grid & Structure +- **Max Content Width:** 1440px for optimal readability and visual balance on large displays +- **Grid System:** Responsive 12-column grid with fluid gutters (24px mobile, 32px desktop) +- **Product Grid:** 4 columns on large desktop, 3 on desktop, 2 on tablet, 1 on mobile +- **Breakpoints:** + - Mobile: <768px + - Tablet: 768-1024px + - Desktop: 1024-1440px + - Large Desktop: >1440px + +### Whitespace Strategy (Critical to the Design) +- **Base Unit:** 8px for micro-spacing, 16px for component spacing +- **Vertical Rhythm:** Consistent 2rem (32px) base unit between related elements +- **Section Margins:** Generous 5-8rem (80-128px) between major sections creating dramatic breathing room +- **Edge Padding:** 1.5rem (24px) mobile, 3rem (48px) tablet/desktop for comfortable framing +- **Hero Sections:** Extra-generous top/bottom padding (8-12rem) for impactful presentation + +### Alignment & Visual Balance +- **Text Alignment:** Left-aligned for body and navigation (optimal readability), centered for hero headlines and featured content +- **Image to Text Ratio:** Heavily weighted toward imagery (70-30 split) reinforcing photography-first philosophy +- **Asymmetric Balance:** Large hero images offset by compact, refined text blocks +- **Visual Weight Distribution:** Strategic use of whitespace to draw eyes to hero products and primary CTAs +- **Reading Flow:** Clear top-to-bottom, left-to-right pattern with intentional focal points + +### Responsive Behavior & Touch +- **Mobile-First Foundation:** Core experience designed and perfected for smallest screens first +- **Progressive Enhancement:** Additional columns, imagery, and details added gracefully at larger breakpoints +- **Touch Targets:** Minimum 44x44px for all interactive elements (WCAG AAA compliant) +- **Image Optimization:** Responsive images with appropriate resolutions for each breakpoint, lazy-loading for performance +- **Collapsing Strategy:** Navigation collapses to hamburger, grid reduces columns, padding scales proportionally + +## 6. Design System Notes for Stitch Generation + +When creating new screens for this project using Stitch, reference these specific instructions: + +### Language to Use +- **Atmosphere:** "Sophisticated minimalist sanctuary with gallery-like spaciousness" +- **Button Shapes:** "Subtly rounded corners" (not "rounded-md" or "8px") +- **Shadows:** "Whisper-soft diffused shadows on hover" (not "shadow-sm") +- **Spacing:** "Generous breathing room" and "expansive whitespace" + +### Color References +Always use the descriptive names with hex codes: +- Primary CTA: "Deep Muted Teal-Navy (#294056)" +- Backgrounds: "Warm Barely-There Cream (#FCFAFA)" or "Crisp Very Light Gray (#F5F5F5)" +- Text: "Charcoal Near-Black (#2C2C2C)" or "Soft Warm Gray (#6B6B6B)" + +### Component Prompts +- "Create a product card with gently rounded corners, full-bleed square product image, and whisper-soft shadow on hover" +- "Design a primary call-to-action button in Deep Muted Teal-Navy (#294056) with subtle rounded corners and comfortable padding" +- "Add a navigation bar with generous spacing between items, using medium-weight Manrope with subtle uppercase and expanded letter-spacing" + +### Incremental Iteration +When refining existing screens: +1. Focus on ONE component at a time (e.g., "Update the product grid cards") +2. Be specific about what to change (e.g., "Increase the internal padding of product cards from 1.5rem to 2rem") +3. Reference this design system language consistently diff --git a/.claude/skills/enhance-prompt/README.md b/.claude/skills/enhance-prompt/README.md new file mode 100644 index 0000000..54d06cb --- /dev/null +++ b/.claude/skills/enhance-prompt/README.md @@ -0,0 +1,34 @@ +# Stitch Enhance Prompt Skill + +## Install + +```bash +npx skills add google-labs-code/stitch-skills --skill enhance-prompt --global +``` + +## Example Prompt + +```text +Enhance my prompt "make me a login page" for better Stitch generation results. +``` + +## Skill Structure + +This repository follows the **Agent Skills** open standard. Each skill is self-contained with its own logic, workflow, and reference materials. + +```text +enhance-prompt/ +├── SKILL.md — Core instructions & workflow +├── references/ — UI/UX vocabulary and adjective palettes +└── README.md — This file +``` + +## How it Works + +When activated, the agent follows a prompt enhancement pipeline: + +1. **Assessment**: Evaluates the input for missing elements (platform, structure, visual style, colors). +2. **DESIGN.md Check**: Looks for an existing design system to inject; recommends creating one if missing. +3. **Enhancement**: Applies UI/UX keywords, vibe adjectives, and structured page sections. +4. **Formatting**: Outputs a Stitch-optimized prompt with design system block and numbered structure. +5. **Delivery**: Returns enhanced text for user review, with optional file output. diff --git a/.claude/skills/enhance-prompt/SKILL.md b/.claude/skills/enhance-prompt/SKILL.md new file mode 100644 index 0000000..04aec68 --- /dev/null +++ b/.claude/skills/enhance-prompt/SKILL.md @@ -0,0 +1,204 @@ +--- +name: enhance-prompt +description: Transforms vague UI ideas into polished, Stitch-optimized prompts. Enhances specificity, adds UI/UX keywords, injects design system context, and structures output for better generation results. +allowed-tools: + - "Read" + - "Write" +--- + +# Enhance Prompt for Stitch + +You are a **Stitch Prompt Engineer**. Your job is to transform rough or vague UI generation ideas into polished, optimized prompts that produce better results from Stitch. + +## Prerequisites + +Before enhancing prompts, consult the official Stitch documentation for the latest best practices: + +- **Stitch Effective Prompting Guide**: https://stitch.withgoogle.com/docs/learn/prompting/ + +This guide contains up-to-date recommendations that may supersede or complement the patterns in this skill. + +## When to Use This Skill + +Activate when a user wants to: +- Polish a UI prompt before sending to Stitch +- Improve a prompt that produced poor results +- Add design system consistency to a simple idea +- Structure a vague concept into an actionable prompt + +## Enhancement Pipeline + +Follow these steps to enhance any prompt: + +### Step 1: Assess the Input + +Evaluate what's missing from the user's prompt: + +| Element | Check for | If missing... | +|---------|-----------|---------------| +| **Platform** | "web", "mobile", "desktop" | Add based on context or ask | +| **Page type** | "landing page", "dashboard", "form" | Infer from description | +| **Structure** | Numbered sections/components | Create logical page structure | +| **Visual style** | Adjectives, mood, vibe | Add appropriate descriptors | +| **Colors** | Specific values or roles | Add design system or suggest | +| **Components** | UI-specific terms | Translate to proper keywords | + +### Step 2: Check for DESIGN.md + +Look for a `DESIGN.md` file in the current project: + +**If DESIGN.md exists:** +1. Read the file to extract the design system block +2. Include the color palette, typography, and component styles +3. Format as a "DESIGN SYSTEM (REQUIRED)" section in the output + +**If DESIGN.md does not exist:** +1. Add this note at the end of the enhanced prompt: + +``` +--- +💡 **Tip:** For consistent designs across multiple screens, create a DESIGN.md +file using the `design-md` skill. This ensures all generated pages share the +same visual language. +``` + +### Step 3: Apply Enhancements + +Transform the input using these techniques: + +#### A. Add UI/UX Keywords + +Replace vague terms with specific component names: + +| Vague | Enhanced | +|-------|----------| +| "menu at the top" | "navigation bar with logo and menu items" | +| "button" | "primary call-to-action button" | +| "list of items" | "card grid layout" or "vertical list with thumbnails" | +| "form" | "form with labeled input fields and submit button" | +| "picture area" | "hero section with full-width image" | + +#### B. Amplify the Vibe + +Add descriptive adjectives to set the mood: + +| Basic | Enhanced | +|-------|----------| +| "modern" | "clean, minimal, with generous whitespace" | +| "professional" | "sophisticated, trustworthy, with subtle shadows" | +| "fun" | "vibrant, playful, with rounded corners and bold colors" | +| "dark mode" | "dark theme with high-contrast accents on deep backgrounds" | + +#### C. Structure the Page + +Organize content into numbered sections: + +```markdown +**Page Structure:** +1. **Header:** Navigation with logo and menu items +2. **Hero Section:** Headline, subtext, and primary CTA +3. **Content Area:** [Describe the main content] +4. **Footer:** Links, social icons, copyright +``` + +#### D. Format Colors Properly + +When colors are mentioned, format them as: +``` +Descriptive Name (#hexcode) for functional role +``` + +Examples: +- "Deep Ocean Blue (#1a365d) for primary buttons and links" +- "Warm Cream (#faf5f0) for page background" +- "Soft Gray (#6b7280) for secondary text" + +### Step 4: Format the Output + +Structure the enhanced prompt in this order: + +```markdown +[One-line description of the page purpose and vibe] + +**DESIGN SYSTEM (REQUIRED):** +- Platform: [Web/Mobile], [Desktop/Mobile]-first +- Theme: [Light/Dark], [style descriptors] +- Background: [Color description] (#hex) +- Primary Accent: [Color description] (#hex) for [role] +- Text Primary: [Color description] (#hex) +- [Additional design tokens...] + +**Page Structure:** +1. **[Section]:** [Description] +2. **[Section]:** [Description] +... +``` + +## Output Options + +**Default:** Return the enhanced prompt as text for the user to copy. + +**Optional file output:** If the user requests, write to a file: +- `next-prompt.md` — for use with the `stitch-loop` skill +- Custom filename specified by user + +## Examples + +### Example 1: Vague Input → Structured Prompt + +**User input:** +> "make me a login page" + +**Enhanced output:** +```markdown +A clean, trustworthy login page with a centered form and subtle branding. + +**DESIGN SYSTEM (REQUIRED):** +- Platform: Web, Desktop-first +- Theme: Light, minimal, professional +- Background: Clean White (#ffffff) +- Surface: Soft Gray (#f9fafb) for form card +- Primary Accent: Deep Blue (#2563eb) for submit button and links +- Text Primary: Near Black (#111827) for headings +- Text Secondary: Medium Gray (#6b7280) for labels +- Buttons: Subtly rounded (8px), full-width on form +- Cards: Gently rounded (12px), soft shadow for elevation + +**Page Structure:** +1. **Header:** Minimal logo, centered +2. **Login Card:** Centered form with email, password fields, "Forgot password?" link +3. **Submit Button:** Primary blue "Sign In" button +4. **Footer:** "Don't have an account? Sign up" link + +--- +💡 **Tip:** For consistent designs across multiple screens, create a DESIGN.md +file using the `design-md` skill. +``` + +### Example 2: Feature Request → Targeted Edit + +**User input:** +> "add a search bar" + +**Enhanced output:** +```markdown +Add a search bar to the header navigation. + +**Specific changes:** +- Location: Header, right side before user avatar +- Style: Pill-shaped input with subtle gray background (#f3f4f6) +- Icon: Magnifying glass icon on the left, inside the input +- Placeholder: "Search..." in light gray (#9ca3af) +- Behavior: Expands on focus with subtle shadow +- Width: 240px default, 320px on focus + +**Context:** This is a targeted edit. Make only this change while preserving all existing elements. +``` + +## Tips for Best Results + +1. **Be specific early** — Vague inputs need more enhancement +2. **Match the user's intent** — Don't over-design if they want simple +3. **Keep it structured** — Numbered sections help Stitch understand hierarchy +4. **Include the design system** — Consistency is key for multi-page projects +5. **One change at a time for edits** — Don't bundle unrelated changes diff --git a/.claude/skills/enhance-prompt/references/KEYWORDS.md b/.claude/skills/enhance-prompt/references/KEYWORDS.md new file mode 100644 index 0000000..7bb06ed --- /dev/null +++ b/.claude/skills/enhance-prompt/references/KEYWORDS.md @@ -0,0 +1,114 @@ +# UI/UX Keywords Reference + +Progressive disclosure reference for common UI terminology and adjective palettes. + +## Component Keywords + +### Navigation +- navigation bar, nav menu, header +- breadcrumbs, tabs, sidebar +- hamburger menu, dropdown menu +- back button, close button + +### Content Containers +- hero section, hero banner +- card, card grid, tile +- modal, dialog, popup +- accordion, collapsible section +- carousel, slider + +### Forms +- input field, text input +- dropdown, select menu +- checkbox, radio button +- toggle switch +- date picker, time picker +- search bar, search input +- submit button, form actions + +### Calls to Action +- primary button, secondary button +- ghost button, text link +- floating action button (FAB) +- icon button + +### Feedback +- toast notification, snackbar +- alert banner, warning message +- loading spinner, skeleton loader +- progress bar, step indicator + +### Layout +- grid layout, flexbox +- sidebar layout, split view +- sticky header, fixed footer +- full-width, contained width +- centered content, max-width container + +## Adjective Palettes + +### Minimal / Clean +- minimal, clean, uncluttered +- generous whitespace, breathing room +- subtle, understated, refined +- simple, focused, distraction-free + +### Professional / Corporate +- sophisticated, polished, trustworthy +- corporate, business-like, formal +- subtle shadows, clean lines +- structured, organized, hierarchical + +### Playful / Fun +- vibrant, colorful, energetic +- rounded corners, soft edges +- bold, expressive, dynamic +- friendly, approachable, warm + +### Premium / Luxury +- elegant, luxurious, high-end +- dramatic, bold contrasts +- sleek, modern, cutting-edge +- exclusive, boutique, curated + +### Dark Mode +- dark theme, night mode +- high-contrast accents +- soft glows, subtle highlights +- deep backgrounds, muted surfaces + +### Organic / Natural +- earthy tones, natural colors +- warm, inviting, cozy +- textured, tactile, handcrafted +- flowing, organic shapes + +## Color Role Terminology + +### Backgrounds +- page background, canvas +- surface color, card background +- overlay, scrim + +### Text +- primary text, heading color +- secondary text, body copy +- muted text, placeholder +- inverse text (on dark backgrounds) + +### Accents +- primary accent, brand color +- secondary accent, highlight +- success, error, warning colors +- hover state, active state + +## Shape Descriptions + +| Technical | Natural Language | +|-----------|------------------| +| `rounded-none` | sharp, squared-off edges | +| `rounded-sm` | slightly softened corners | +| `rounded-md` | gently rounded corners | +| `rounded-lg` | generously rounded corners | +| `rounded-xl` | very rounded, pillow-like | +| `rounded-full` | pill-shaped, circular | diff --git a/.claude/skills/extract-design-md/SKILL.md b/.claude/skills/extract-design-md/SKILL.md new file mode 100644 index 0000000..94228a6 --- /dev/null +++ b/.claude/skills/extract-design-md/SKILL.md @@ -0,0 +1,365 @@ +--- +name: stitch::extract-design-md +description: >- + Extract a comprehensive design system (DESIGN.md) directly from frontend source + code — React, Vue, Svelte, Angular, plain HTML/CSS, or any web framework. Analyzes + component files, stylesheets, Tailwind configs, theme definitions, and design tokens + to produce a rich, Stitch-compatible design system document. Use this skill whenever + the user wants to reverse-engineer a design system from an existing codebase, audit + the visual language of a project, extract design tokens from source files, or + understand the styling patterns in a frontend repo — even if they just say "what + does this app look like?" or "pull out the design from this code." +allowed-tools: + - "stitch*:*" + - "Bash" + - "Read" + - "Write" + - "web_fetch" +--- + +# Extract Design System from Frontend Code + +Analyze frontend source code to extract a comprehensive design system document +(DESIGN.md) that captures the project's visual language — colors, typography, +spacing, component patterns, and layout principles — directly from the source +files, without needing to build or render the application. + +## Why This Exists + +The `design-md` skill works from rendered HTML. But often you have a codebase +and want to understand its design system before you can even run the app — +maybe dependencies are missing, the build is broken, or you just want a quick +audit. This skill reads the source files themselves: stylesheets, component +files, theme configs, and Tailwind setups. It's faster and works anywhere. + +## When to Use + +- User has a frontend codebase and wants to extract or document its design system +- User wants to migrate a project's visual identity into Stitch +- User asks to "audit the styling" or "understand the design language" of a repo +- User wants to create a DESIGN.md from existing source code +- The app can't be built/rendered but the source is available +- User wants to unify or reconcile inconsistent styles across a codebase + +## Prerequisites + +- Access to the frontend project's source directory +- No build or runtime dependencies needed — this skill reads source files only + +--- + +## Workflow + +### Phase 1: Project Discovery + +Start by understanding what you're working with. This determines which +extraction patterns to use. + +#### 1. Detect the Framework and Stack + +Scan the project root for telltale files: + +| Signal File | Framework / Tool | +|:---|:---| +| `package.json` with `react` | React / Next.js | +| `package.json` with `vue` | Vue / Nuxt | +| `package.json` with `svelte` | Svelte / SvelteKit | +| `package.json` with `@angular/core` | Angular | +| `tailwind.config.js/ts` | Tailwind CSS | +| `postcss.config.js` | PostCSS pipeline | +| `styled-components` or `@emotion` in deps | CSS-in-JS | +| `.css` / `.scss` / `.less` files only | Plain CSS / SASS | +| `theme.js` / `theme.ts` / `tokens.js` | Design token files | + +Read `package.json` first — it reveals the framework, CSS tooling, and any +design-token libraries (e.g., `style-dictionary`, `@chakra-ui/react`, +`@mui/material`, `ant-design`). This context tells you *where* to look for +styling information. + +#### 2. Map the Source Tree + +Identify the key directories and files you'll analyze: + +``` +src/ +├── components/ ← Component-level styles +├── styles/ ← Global stylesheets +├── theme/ ← Theme definitions, tokens +├── assets/ ← Fonts, images +├── app.css ← Root styles +└── index.css ← Entry CSS +``` + +Also check for: +- `tailwind.config.js` / `tailwind.config.ts` — Custom colors, fonts, spacing +- `globals.css` / `global.css` — CSS custom properties (variables) +- Any `theme.*` or `tokens.*` files +- Component library config (e.g., `chakra-theme.ts`, `vuetify.config.ts`) + +#### 3. Read Framework-Specific Guidance + +Consult the appropriate reference for extraction patterns: + +- **React / Next.js / Tailwind** → [references/react-tailwind.md](references/react-tailwind.md) +- **Vue / Nuxt** → [references/vue.md](references/vue.md) +- **Svelte / SvelteKit** → [references/svelte.md](references/svelte.md) +- **Angular** → [references/angular.md](references/angular.md) +- **Plain CSS / SASS / Less** → [references/plain-css.md](references/plain-css.md) + +These references contain framework-specific patterns for locating colors, +typography, spacing, and component styles. Read the one that matches before +proceeding. + +--- + +### Phase 2: Deep Extraction + +Work through each design dimension systematically. For each one, gather raw +data from the source files, then synthesize it into descriptive language. + +The goal isn't to dump every CSS property — it's to understand the *intent* +behind the styling choices and describe them in human, editorial language that +another designer (or Stitch) can use to recreate the same visual feel. + +#### 1. Visual Theme & Atmosphere + +Read the broadest styling first to understand the overall mood: + +- **Root background**: What's the `body` or root element background? Light + cream (#f-range) signals airy/clean; dark (#0-#2 range) signals moody/dramatic. +- **Whitespace philosophy**: Are spacing values generous (32px+) or tight? + Check padding/margin values on root containers, section wrappers, and card components. +- **Density**: Count the components per page/section. Few with space = minimal; + many packed tight = information-dense. +- **Color temperature**: Are the neutrals warm (creams, tans) or cool (blue-grays, slates)? +- **Overall feel**: Synthesize into 1-2 rich sentences that capture the mood. + +Look for these signals in the source: + +| Source Location | What It Tells You | +|:---|:---| +| Root `background-color` or Tailwind `bg-*` on layouts | Overall lightness/darkness | +| Spacing scale in Tailwind config or CSS vars | Whitespace philosophy | +| Number of components vs. wrapper padding | Density | +| Custom property naming (`--warm-*` vs `--cool-*`) | Color temperature intent | +| Comments in theme files | Design intent in the developer's own words | + +#### 2. Color Palette & Roles + +Extract every unique color from the codebase and assign functional roles. +Search across all layers: + +**Where to find colors:** + +| Layer | What to Search | +|:---|:---| +| CSS custom properties | `--color-*`, `--primary`, `--bg-*` | +| Tailwind config | `theme.extend.colors` | +| Theme/token files | Color objects, palettes | +| Component styles | `background-color`, `color`, `border-color` | +| Inline/scoped styles | `bg-*`, `text-*` classes in templates | +| CSS-in-JS theme objects | `colors`, `palette` keys | + +**How to organize:** Group colors by function, not by hue: + +1. **Primary Foundation** — Background and surface colors +2. **Accent & Interactive** — CTA buttons, active states, links +3. **Typography & Text Hierarchy** — Primary, secondary, tertiary text +4. **Functional States** — Success, error, warning, info + +For each color, create a descriptive name that evokes the color's character +rather than its raw hex value: + +- ❌ `#294056` → "Blue" +- ✅ `#294056` → **"Deep Muted Teal-Navy"** — Primary CTA, active navigation + +**Deduplication matters.** Codebases often have near-duplicate colors (e.g., +`#333` and `#2C2C2C`). Consolidate them under one name that best represents +the intended color. + +#### 3. Typography Rules + +Extract the complete typographic system: + +**Font families:** +- Check CSS `font-family`, Tailwind `fontFamily`, Google Fonts links, or + local `@font-face` declarations. +- Note the **character** of each font: geometric vs humanist, serif vs sans, + the feeling it evokes. + +**Type scale (hierarchy):** +- Find every heading level (H1-H6) and body text, noting: + - `font-size` (in rem or px) + - `font-weight` (numeric value + descriptive name) + - `letter-spacing` (and why — elegance? compactness?) + - `line-height` (generous for readability? tight for display?) +- Map component usage: Which heading level do product cards use? What about + hero sections? + +**Spacing principles:** +- How does text spacing relate to the overall spacing scale? +- Letter-spacing patterns on headings vs body +- Line-height philosophy (generous/relaxed for body, tighter for display) + +#### 4. Component Stylings + +Analyze the 4-5 most important UI primitives: + +**Buttons:** +- Corner radius (and what it communicates — playful? professional? minimal?) +- Color scheme for primary, secondary, and ghost variants +- Hover/focus/active states and transition timing +- Padding ratios (horizontal vs vertical) + +**Cards / Containers:** +- Corner radius (often different from buttons — slightly rounder) +- Shadow strategy: flat, subtle hover shadows, or always elevated? +- Border treatment: hairline borders, colored accents, or none? +- Internal padding (generous or compact?) +- Image treatment within cards (full-bleed, padded, rounded?) + +**Navigation:** +- Layout pattern (horizontal bar, vertical sidebar, drawer) +- Typography treatment (uppercase, letter-spacing, weight) +- Active/hover state indicators (underline, color, background) +- Mobile behavior (hamburger, bottom nav, drawer) + +**Inputs & Forms:** +- Border style and focus state behavior +- Corner style consistency with buttons +- Padding and touch-target sizing + +**Domain-Specific Components:** +- Identify 1-2 components unique to this project (e.g., product cards, + dashboard widgets, chat bubbles) and describe their styling patterns. + +#### 5. Layout Principles + +Extract the structural system: + +**Grid & Structure:** +- Max content width (from `max-width` on containers) +- Column system (CSS Grid, Flexbox patterns, defined breakpoints) +- Responsive breakpoints (from media queries or Tailwind config) + +**Whitespace Strategy:** +- Base spacing unit (8px grid? 4px? custom?) +- Section margins (how much space between major sections) +- Edge padding (page margins at different breakpoints) + +**Alignment & Visual Balance:** +- Text alignment patterns (centered heroes, left-aligned body) +- Image-to-text ratios +- Visual weight distribution + +**Responsive Behavior:** +- Mobile-first or desktop-first? +- How do grids collapse? Padding scale? +- Touch target sizing + +#### 6. Stitch Generation Notes + +Synthesize the extraction into actionable prompts for Stitch: + +- **Atmosphere language**: Translate the mood into natural descriptors +- **Color references**: List colors by descriptive name + hex +- **Component prompts**: Write 2-3 example prompts that would recreate + key components in Stitch +- **Iteration guidance**: Tips for refining screens in this design system + +--- + +### Phase 3: Write the DESIGN.md + +Assemble everything into the standard DESIGN.md format. Place it at +`.stitch/DESIGN.md` in the project directory (create the `.stitch/` directory +if it doesn't exist). + +> [!IMPORTANT] +> You **MUST** include the YAML frontmatter at the top of the file with `name` and `colors` mapping, exactly as shown in the example at [examples/DESIGN.md](examples/DESIGN.md). This structured data is required for other skills to parse the design system. +> +> Failure to include this YAML block with at least the core color tokens is a failure to use this skill correctly. + +Use the format from the example at [examples/DESIGN.md](examples/DESIGN.md) as your template. The file must start with the YAML block, followed by the markdown sections: + +```markdown +# Design System: [Project Name] +**Project ID:** [If known, otherwise omit] + +## 1. Visual Theme & Atmosphere +[Rich 2-paragraph description of mood, philosophy, and key characteristics] + +## 2. Color Palette & Roles +### Primary Foundation +### Accent & Interactive +### Typography & Text Hierarchy +### Functional States + +## 3. Typography Rules +### Hierarchy & Weights +### Spacing Principles + +## 4. Component Stylings +### Buttons +### Cards & [Domain-Specific Containers] +### Navigation +### Inputs & Forms +### [Domain-Specific Components] + +## 5. Layout Principles +### Grid & Structure +### Whitespace Strategy +### Alignment & Visual Balance +### Responsive Behavior & Touch + +## 6. Design System Notes for Stitch Generation +### Language to Use +### Color References +### Component Prompts +### Incremental Iteration +``` + +--- + +### Phase 4: Integration (Optional) + +If the user wants to push the design system into Stitch: + +1. Hand off to the `manage-design-system` skill for the MCP create/update calls +2. The DESIGN.md you wrote is the input — the manage-design-system skill handles + the Stitch API integration + +If the user just wants the document, you're done after Phase 3. + +--- + +## Quality Checklist + +Before delivering the DESIGN.md, verify: + +- [ ] Every color has a descriptive name, hex code, and functional role +- [ ] Typography includes font family, character description, and full hierarchy +- [ ] Component styles describe shape, color, states, and transitions +- [ ] Layout includes max-width, grid, breakpoints, and spacing strategy +- [ ] Stitch generation notes use natural language, not CSS syntax +- [ ] The atmosphere section reads like editorial copy, not technical docs +- [ ] Near-duplicate colors are consolidated +- [ ] The document captures the *intent* behind styling, not just raw values + +## Tips for Better Extraction + +- **Read comments and commit messages.** Developers often document design + intent in code comments (`/* hero section — breathable */`) and commit + messages. These are gold for understanding the *why*. +- **Check for design-token libraries.** If the project uses `style-dictionary`, + `@tokens-studio`, or similar, these files are the most authoritative + source of design values. +- **Theme files are higher-signal than component styles.** A `theme.ts` that + defines a palette tells you the intended design system; scattered inline + styles in components tell you what actually shipped. Both matter, but + start from the theme. +- **Tailwind config is a design system.** If a project has a customized + `tailwind.config.js`, that *is* the design system — extract from it first, + then spot-check components for overrides. +- **CSS custom properties are intentional.** If a developer defined + `--brand-primary`, they're telling you this is a design token. Respect that. diff --git a/.claude/skills/extract-design-md/examples/DESIGN.md b/.claude/skills/extract-design-md/examples/DESIGN.md new file mode 100644 index 0000000..67be49f --- /dev/null +++ b/.claude/skills/extract-design-md/examples/DESIGN.md @@ -0,0 +1,210 @@ +--- +name: Alpine Peak +colors: + surface: '#fcf8fa' + surface-dim: '#dcd9db' + surface-bright: '#fcf8fa' + surface-container-lowest: '#ffffff' + surface-container-low: '#f6f3f5' + surface-container: '#f0edef' + surface-container-high: '#eae7e9' + surface-container-highest: '#e4e2e4' + on-surface: '#1b1b1d' + on-surface-variant: '#45464d' + inverse-surface: '#303032' + inverse-on-surface: '#f3f0f2' + outline: '#76777d' + outline-variant: '#c6c6cd' + surface-tint: '#565e74' + primary: '#000000' + on-primary: '#ffffff' + primary-container: '#131b2e' + on-primary-container: '#7c839b' + inverse-primary: '#bec6e0' + secondary: '#5c5f61' + on-secondary: '#ffffff' + secondary-container: '#e0e3e5' + on-secondary-container: '#626567' + tertiary: '#000000' + on-tertiary: '#ffffff' + tertiary-container: '#161c22' + on-tertiary-container: '#7e848c' + error: '#ba1a1a' + on-error: '#ffffff' + error-container: '#ffdad6' + on-error-container: '#93000a' + primary-fixed: '#dae2fd' + primary-fixed-dim: '#bec6e0' + on-primary-fixed: '#131b2e' + on-primary-fixed-variant: '#3f465c' + secondary-fixed: '#e0e3e5' + secondary-fixed-dim: '#c4c7c9' + on-secondary-fixed: '#191c1e' + on-secondary-fixed-variant: '#444749' + tertiary-fixed: '#dde3eb' + tertiary-fixed-dim: '#c1c7cf' + on-tertiary-fixed: '#161c22' + on-tertiary-fixed-variant: '#41474e' + background: '#fcf8fa' + on-background: '#1b1b1d' + surface-variant: '#e4e2e4' +typography: + display-lg: + fontFamily: Inter + fontSize: 48px + fontWeight: '800' + lineHeight: 56px + letterSpacing: -0.02em + headline-md: + fontFamily: Inter + fontSize: 24px + fontWeight: '700' + lineHeight: 32px + letterSpacing: -0.01em + body-base: + fontFamily: Inter + fontSize: 16px + fontWeight: '400' + lineHeight: 24px + letterSpacing: '0' + body-bold: + fontFamily: Inter + fontSize: 16px + fontWeight: '600' + lineHeight: 24px + letterSpacing: '0' + label-caps: + fontFamily: Lexend + fontSize: 12px + fontWeight: '700' + lineHeight: 16px + letterSpacing: 0.05em + stat-lg: + fontFamily: Lexend + fontSize: 32px + fontWeight: '600' + lineHeight: 40px + letterSpacing: -0.02em +rounded: + sm: 0.25rem + DEFAULT: 0.5rem + md: 0.75rem + lg: 1rem + xl: 1.5rem + full: 9999px +spacing: + unit: 4px + xs: 4px + sm: 8px + md: 16px + lg: 24px + xl: 32px + gutter: 16px + margin-mobile: 20px + margin-desktop: 40px +--- + +## Brand & Style + +The brand personality is high-performance, sophisticated, and dependable. It is +designed for the modern skier who demands clarity and precision in harsh +environments. The visual language evokes the crystalline beauty of a mountain +peak while prioritizing the rugged utility required for outdoor navigation. + +The design system utilizes **Glassmorphism** to achieve a "frozen" aesthetic, +mimicking the properties of ice and packed snow. This is paired with a +**High-Contrast** philosophy to ensure that critical data—like trail status and +weather alerts—remains legible under intense mountain sunlight or the +low-visibility conditions of a snowstorm. + +## Colors + +The palette is anchored by **Deep Peak Blue**, a dark navy that provides a +grounding contrast for white text and maps. **Powder White** serves as the +primary canvas, ensuring the interface feels airy and cold. + +**Safety Orange** is reserved strictly for primary calls to action, hazard +warnings, and emergency trail closures, ensuring immediate eye-tracking. +**Electric Blue** (the info status) is used for weather updates and general +interactivity. For trail difficulty levels, standard industry colors (Green, +Blue, Black) are used but rendered with high-saturation values to pop against +the white backgrounds. + +## Typography + +The typography system uses **Inter** for core functional text and body copy due +to its exceptional x-height and legibility at small sizes. **Lexend** is +introduced for labels and statistics; its hyper-readable, athletic character +suits the "active" nature of skiing data like speed and vertical drop. + +To combat outdoor glare, font weights are generally heavier than standard web +applications. Display styles use tight tracking and heavy weights to create a +sense of strength. Labels always utilize high-contrast coloring against their +backgrounds. + +## Layout & Spacing + +This design system uses a **Fluid Grid** model with generous safe areas. +Elements are spaced using a strict 4px/8px baseline rhythm to maintain a +disciplined, professional appearance. + +Touch targets are intentionally oversized (minimum 48x48px) to accommodate users +wearing gloves. Padding within cards and containers is kept spacious (`lg` or +`xl`) to prevent the interface from feeling cluttered when displaying complex +trail data. + +## Elevation & Depth + +Depth is conveyed through **Glassmorphism** and backdrop filters rather than +traditional heavy shadows. Surfaces use a hierarchy of transparency: + +1. **Base Layer:** Solid 'Powder White' or 'Deep Peak Blue'. +2. **Middle Layer (Cards/Modals):** 70% opacity white with a 20px backdrop blur + and a thin 1px 'Ice' border (white at 40% opacity). +3. **Top Layer (Floating Actions):** 90% opacity with a subtle 4px ambient + shadow to separate the element from the blurred background. + +This creates a "stacked ice" effect that maintains visual clarity while giving +the UI a premium, modern feel. + +## Shapes + +The shape language is defined by modern, organic **rounded corners**. This +softens the high-contrast color palette and makes the app feel approachable. + +Interactive elements like buttons and chips utilize `rounded-lg` (1rem) or +`rounded-xl` (1.5rem) to suggest a tactile, "pebble" feel. Large containers like +map overlays use 1rem corners, while small status indicators for trail +difficulty may use pill shapes for instant recognition. + +## Components + +### Buttons + +Primary buttons use a solid 'Safety Orange' or 'Deep Peak Blue' fill with white +text. High-contrast outlines are used for secondary actions. All buttons must +feature a minimum height of 52px for gloved-hand accessibility. + +### Cards & Modals + +Cards utilize the glassmorphism effect—semi-transparent backgrounds with a 1px +white border. This ensures that map imagery or photos underneath remain slightly +visible, maintaining the "frozen" aesthetic. + +### Trail Status Chips + +Pill-shaped indicators with high-saturation icons. Green (Easy), Blue +(Intermediate), Black (Expert), and Double Black (Extreme). These must include +text labels alongside icons to ensure accessibility for colorblind users. + +### Input Fields + +Fields feature a 'Cloud Gray' background with a thick bottom border that +transforms into 'Electric Blue' on focus. Labels are always visible above the +field to ensure the user doesn't lose context in bright environments. + +### Weather Widgets + +Bold, thick-stroke iconography (minimum 2pt stroke) to represent sun, snow, or +wind. These icons should be large and accompanied by 'Lexend' typography for +temperature and wind speed. \ No newline at end of file diff --git a/.claude/skills/extract-design-md/references/angular.md b/.claude/skills/extract-design-md/references/angular.md new file mode 100644 index 0000000..d5e0b65 --- /dev/null +++ b/.claude/skills/extract-design-md/references/angular.md @@ -0,0 +1,122 @@ +# Angular Extraction Patterns + +Angular projects use a structured, convention-heavy approach to styling. +Design systems often live in SCSS/CSS files with clear separation between +global themes and component-scoped styles. + +## File Discovery Order + +1. **`angular.json`** — Lists global style files under + `projects.*.architect.build.options.styles`. These are the entry-point + CSS/SCSS files. + +2. **`src/styles.scss` / `src/styles.css`** — Global stylesheet. CSS custom + properties, font imports, and base styles live here. + +3. **`src/theme.scss` / `src/theme/`** — Explicit theme directory. Custom + Material/component palettes. + +4. **Tailwind Config (`tailwind.config.js` or Tailwind v4 `@theme {}`)** — For Tailwind v3, read `tailwind.config.js`. For Tailwind v4, inspect `@theme {}` blocks, `@custom-variant`, and `@plugin 'tailwindcss-primeui'` in your global CSS/SCSS (e.g. `src/styles.css` or `src/assets/tailwind.css`) for CSS custom property tokens (`--color-*`, `--font-*`, `--text-*`, `--breakpoint-*`). + +5. **`src/app/app.component.scss`** — Root component styles, reveals global + layout patterns. + +6. **Component `.scss` / `.css` files** — Co-located styles (ViewEncapsulation + scoped by default). + +7. **External Template `.html` files (`src/app/**/*.component.html`)** — Essential for Angular 17+ standalone components using Tailwind CSS utility classes (`bg-*`, `text-*`, `p-*`, `rounded-*`) or structural class bindings (`[ngClass]`, `[class.*]`). Always inspect `.html` templates when styling uses utility classes. + +## Angular Material Theme Extraction + +Angular Material is the most common component library. Themes are SCSS-based: + +```scss +// src/theme.scss +@use '@angular/material' as mat; + +$primary-palette: mat.m2-define-palette(mat.$m2-teal-palette, 800); +$accent-palette: mat.m2-define-palette(mat.$m2-blue-grey-palette); +$warn-palette: mat.m2-define-palette(mat.$m2-red-palette); + +$theme: mat.m2-define-light-theme(( + color: ( + primary: $primary-palette, + accent: $accent-palette, + warn: $warn-palette, + ), + typography: mat.m2-define-typography-config( + $font-family: 'Manrope, sans-serif', + $headline-1: mat.m2-define-typography-level(3.5rem, 4rem, 600), + $headline-5: mat.m2-define-typography-level(1.5rem, 2rem, 500), + $body-1: mat.m2-define-typography-level(1rem, 1.7, 400), + ), +)); + +@include mat.all-component-themes($theme); +``` + +**What to extract:** +- Palette choices → map to functional color roles +- Typography config → maps directly to the hierarchy section +- Light vs dark theme → atmosphere + +For Angular Material 3 (MDC-based), look for `mat.define-theme()` using +the new token system with `--mat-*` CSS custom properties. + +## SCSS Variable Patterns + +Many Angular projects use SCSS variables for tokens: + +```scss +// _variables.scss +$color-primary: #294056; +$color-background: #FCFAFA; +$color-surface: #F5F5F5; +$color-text: #2C2C2C; + +$font-heading: 'Manrope', sans-serif; +$font-body: 'Inter', sans-serif; + +$radius-button: 8px; +$radius-card: 12px; + +$breakpoint-mobile: 768px; +$breakpoint-desktop: 1024px; + +$spacing-section: 5rem; +$spacing-component: 2rem; +``` + +These are explicit design tokens. Map them directly. + +## ViewEncapsulation and Scoped Styles + +Angular scopes styles by default (similar to Vue's `scoped`). When scanning +component styles: + +- Look for `:host` selectors — these style the component's root element +- `::ng-deep` (deprecated but still used) — styles that pierce encapsulation +- Repeated values across components indicate design system conventions + +## PrimeNG / Nebular / NG-ZORRO + +If component libraries are used: +- **PrimeNG (v17/v18/v19+)**: Look for modern theme configuration in `src/app.config.ts` (e.g., `providePrimeNG({ theme: { preset: Aura, options: { darkModeSelector: '.app-dark' } } })`). Check for Tailwind v4 integration via `@plugin 'tailwindcss-primeui'` in CSS assets. Inspect CSS custom properties defined by PrimeNG tokens (`--primary-color`, `--surface-*`). +- **Nebular**: `nb-theme()` in `styles.scss` with custom theme object. +- **NG-ZORRO (Ant Design for Angular)**: `ng-zorro-antd.less` variables + or custom theme config in `angular.json`. + +## Modern Angular (v17 - v19) Standalone Components & Control Flow + +In modern Angular repositories: +- **Standalone Components (`@Component({ standalone: true })`)**: Components import their own dependencies directly without NgModules. Inspect `templateUrl` and `styleUrl(s)` in component metadata to locate the template and style files. +- **Control Flow (`@if`, `@for`, `@switch`)**: Notice how conditional layouts and lists are structured in `.html` templates when analyzing component density and spacing rules. +- **Signals & Zoneless (`signal()`, `input()`, `computed()`, `provideZonelessChangeDetection()`)**: Dynamic styling or theme toggling is often driven by signals bound to `[class.dark]` or custom CSS classes in templates. Notice `app.config.ts` for app-wide providers. + +## Responsive Patterns + +Check for: +- `@media` queries in `styles.scss` and component styles +- Angular CDK `BreakpointObserver` usage in components +- Tailwind responsive prefixes if Tailwind is configured +- Angular Flex-Layout directives (`fxLayout`, `fxFlex`) in templates diff --git a/.claude/skills/extract-design-md/references/plain-css.md b/.claude/skills/extract-design-md/references/plain-css.md new file mode 100644 index 0000000..6bea95b --- /dev/null +++ b/.claude/skills/extract-design-md/references/plain-css.md @@ -0,0 +1,161 @@ +# Plain CSS / SASS / Less Extraction Patterns + +For projects without a JavaScript framework — static sites, WordPress +themes, vanilla HTML/CSS, or CSS preprocessor-heavy projects. + +## File Discovery Order + +1. **`index.html` / `*.html`** — Check `` tags and ` +``` + +**Extraction points:** +- Component props (like `variant`) reveal the intended variant system +- `var(--*)` references → trace to `app.css` +- Transition values reveal the interaction design philosophy + +## SvelteKit Layout Patterns + +- **`+layout.svelte`** at route root — Global header, footer, font loading +- **`+layout.ts/js`** — May load theme data or tokens +- **`$lib/`** directory — Reusable components and shared utilities + +## CSS Custom Properties Strategy + +Svelte projects heavily use CSS custom properties for theming: + +```css +/* app.css */ +:root { + --color-primary: #294056; + --color-bg: #FCFAFA; + --color-surface: #F5F5F5; + --color-text: #2C2C2C; + --color-text-muted: #6B6B6B; + + --font-heading: 'Manrope', sans-serif; + --font-body: 'Inter', sans-serif; + + --radius-sm: 8px; + --radius-md: 12px; + --radius-full: 9999px; + + --shadow-hover: 0 2px 8px rgba(0,0,0,0.06); + --spacing-section: 5rem; +} +``` + +These variable names are highly intentional. Use them as the foundation +of your design system extraction. + +## Skeleton UI / DaisyUI / Flowbite-Svelte + +If component libraries are used: +- **Skeleton UI**: Theme defined in `tailwind.config.js` using Skeleton's + design token system. Look for custom theme config object. +- **DaisyUI**: Theme in `tailwind.config.js` → `daisyui.themes` array. +- **Flowbite-Svelte**: Standard Tailwind theming. diff --git a/.claude/skills/extract-design-md/references/vue.md b/.claude/skills/extract-design-md/references/vue.md new file mode 100644 index 0000000..1412288 --- /dev/null +++ b/.claude/skills/extract-design-md/references/vue.md @@ -0,0 +1,107 @@ +# Vue / Nuxt Extraction Patterns + +Vue projects have a distinctive styling architecture. Styles are often +co-located with components inside ` +``` + +**Key extraction points:** +- `var(--*)` references → trace back to global CSS for the actual values +- `scoped` styles → component-specific, but reveal consistent patterns +- BEM naming (`.card__title`) → hints at component hierarchy + +## Vuetify Theme Extraction + +Vuetify projects define their design system explicitly: + +```ts +// plugins/vuetify.ts +export default createVuetify({ + theme: { + defaultTheme: 'light', + themes: { + light: { + colors: { + primary: '#294056', + secondary: '#6B6B6B', + background: '#FCFAFA', + surface: '#F5F5F5', + error: '#EF4444', + success: '#10B981', + } + } + } + } +}) +``` + +This is the design system declaration. Map each key to a functional role +and descriptive name. + +## Quasar / PrimeVue / Element Plus + +These component libraries use their own theming systems: + +- **Quasar**: `quasar.config.js` → `framework.config.brand` for colors +- **PrimeVue**: CSS themes in `assets/` or theme preset configuration +- **Element Plus**: SCSS variables in `element-variables.scss` + +Look for the override file — that's where the project's unique values live. + +## CSS Scoping Behavior + +Vue's `scoped` attribute adds data attributes for CSS isolation. When +scanning for patterns, look at multiple components to find repeated values +(same `border-radius`, similar `padding`, consistent color references). +Repeated patterns across scoped styles = design system conventions. + +## Nuxt-Specific Patterns + +- **`app.vue`** or **`layouts/default.vue`** — Root layout, reveals + global background, font loading, and overall structure. +- **`assets/`** — Global CSS, fonts, and images. +- **`composables/`** — May contain `useTheme` or `useDesignTokens`. +- **`nuxt.config.ts`** `css` array — Lists global stylesheets automatically + injected into every page. diff --git a/.claude/skills/extract-static-html/SKILL.md b/.claude/skills/extract-static-html/SKILL.md new file mode 100644 index 0000000..914d1bb --- /dev/null +++ b/.claude/skills/extract-static-html/SKILL.md @@ -0,0 +1,244 @@ +--- +name: stitch::extract-static-html +description: >- + Extract self-contained static HTML from a built web application or React components by inlining CSS and images. Use this skill whenever you need to capture a specific UI state, share a static version of a page, or prepare assets for Stitch upload, even if the user just asks to 'save the HTML' or 'mock the view'. +allowed-tools: + - "stitch*:*" + - "Bash" + - "Read" + - "Write" + - "web_fetch" +--- + +# Extract Static HTML + +Extract a self-contained static HTML file from any web application. + +## Which Strategy to Use + +You MUST ask the user to choose which strategy to use before proceeding. Present the options clearly, **recommend Strategy A** as the preferred default, and **provide a brief pros/cons summary** for each option to help them make an informed decision. + +| | Strategy A (Puppeteer) | Strategy B (Browser Subagent) | +| :--- | :--- | :--- | +| **When** | App runs locally, no auth wall | Need to interact with page first (click, fill forms) | +| **Fidelity** | **Highest — computed styles resolved** | High — rendered DOM | +| **Setup** | **Zero — no mock needed** | Zero — no mock needed | +| **Framework** | **Any** | Any | +| **Output** | **Writes to file — no size limit** | May truncate in agent context | + +> [!WARNING] +> **Checkpoint — User Confirmation Required.** +> You **MUST** ask the user which strategy they prefer before proceeding. +> Present the comparison table above, recommend Strategy A as the default, and +> wait for explicit approval. Do **NOT** make the decision yourself or proceed +> until the user confirms. + +*** + +## Strategy A: Puppeteer Snapshot (Recommended) + +Launches headless Chrome, captures the fully rendered DOM, and produces a self-contained HTML file with all CSS inlined and images as base64. Works with **any framework** — no MockPage.jsx needed. + +### Prerequisites + +- App running locally (e.g., `npm run dev`) +- Node.js with `puppeteer` available (check: `node -e "require('puppeteer')"`) + +### Workflow + +1. **Start the App** and note the port. + + > [!WARNING] + > **Checkpoint — User Confirmation Required.** + > After starting the local server, you **MUST** pause and ask the user for + > confirmation before running the snapshot script or launching a browser + > subagent. Report the URL and port to the user so they can verify the app + > is running and rendering correctly. Do **NOT** proceed to the snapshot + > step until the user confirms. + +2. **Run the Snapshot Script**: + ```bash + npx tsx /scripts/snapshot.ts \ + --url http://localhost:5173 \ + --output .stitch/home.html \ + --wait 2000 + ``` + +3. **Multiple pages** — run once per route: + ```bash + npx tsx /scripts/snapshot.ts \ + --url http://localhost:5173 --output .stitch/home.html --wait 2000 + npx tsx /scripts/snapshot.ts \ + --url http://localhost:5173/pricing --output .stitch/pricing.html --wait 2000 + npx tsx /scripts/snapshot.ts \ + --url http://localhost:5173/dashboard --output .stitch/dashboard.html --wait 2000 --html-class dark + ``` + +4. **Clean Up Dev Server**: + If a local dev server was started specifically for snapshot extraction, make sure to stop the server process or terminate the background task once extraction is completed. + + +### Script Flags + +| Flag | Default | Description | +| :--- | :--- | :--- | +| `--url` | *(required)* | URL to capture | +| `--output` | *(required)* | Output file path | +| `--wait` | `1000` | Extra wait (ms) after network idle. Increase for lazy-loading apps. | +| `--viewport` | `1280x800` | Viewport size as `WIDTHxHEIGHT` | +| `--html-class` | — | Class(es) for `` element (e.g., `dark`) | +| `--remove-fixed` | `false` | Remove fixed/sticky elements (cookie banners, chat widgets) | +| `--full-height` | `false` | Resize viewport to full scroll height | +| `--title` | — | Override page title (set to the route path, e.g. `/dashboard` or `/settings/profile`) | +| `--auth-script` | — | Path to a JS/TS module that exports a default `async (page) => void` function for authentication | +| `--inline-canvas` | `false` | Convert `` elements (ECharts, Chart.js, D3) to base64 `` tags | + +### What It Does Automatically + +- Captures all CSSOM rules from `document.styleSheets` (preserves dynamic Vite/Tailwind dev styles and CSS-in-JS) +- Inlines all `` → `\n\n`; + + return head; +} + +// --------------------------------------------------------------------------- +// Main +// --------------------------------------------------------------------------- +async function main(): Promise { + const opts = parseArgs(); + validateOpts(opts); + + const startTime = Date.now(); + const head = buildHead(opts); + const stats: AllStats = { + pages: [], + totalImages: 0, + durationMs: 0, + warnings: [], + }; + + fs.mkdirSync(opts.outdir, { recursive: true }); + + for (const spec of opts.pages) { + const parts = spec.split(':'); + const [src, dstName, title] = parts; + const dst = path.join(opts.outdir, dstName); + + console.log(`\n${'='.repeat(60)}`); + console.log(`Converting ${src} -> ${dstName}...`); + console.log(`${'='.repeat(60)}`); + + const jsx = fs.readFileSync(src, 'utf-8'); + let body = jsxToHtml(jsx); + + if (!body) { + const msg = `Failed to parse JSX from ${src}`; + console.error(` ${msg}`); + stats.warnings.push(msg); + continue; + } + + // Apply exclude pattern (pre-validated during argument parsing) + if (opts.excludePattern) { + body = body.replace(opts.excludePattern, ''); + } + + // Extract body class from outer wrapper div + const outerMatch = body.match(/^]*>([\s\S]*)<\/div>$/); + let fullHtml: string; + if (outerMatch) { + fullHtml = head.replace('{{title}}', title) + + `\n${outerMatch[2].trim()}\n\n`; + } else { + fullHtml = head.replace('{{title}}', title) + + `\n${body}\n\n`; + } + + // Embed remote images with concurrency + const cacheCountBefore = imgCache.size; + fullHtml = await embedImages(fullHtml, opts.concurrency, opts.timeout); + const imagesEmbedded = imgCache.size - cacheCountBefore; + + fs.writeFileSync(dst, fullHtml, 'utf-8'); + const fileSize = fs.statSync(dst).size; + console.log(`=> ${dst} (${fileSize.toLocaleString()} bytes)`); + + stats.pages.push({ + src, + dst, + sizeBytes: fileSize, + imagesEmbedded, + }); + } + + stats.totalImages = imgCache.size; + stats.durationMs = Date.now() - startTime; + + console.log( + `\nDONE: ${imgCache.size} unique images embedded in ${stats.durationMs}ms.`, + ); + + if (opts.json) { + console.log('\n--- JSON Stats ---'); + console.log(JSON.stringify(stats, null, 2)); + } +} + +main().catch((err: Error) => { + console.error('❌ Error:', err.message); + if (err.stack) console.error(err.stack); + process.exit(1); +}); diff --git a/.claude/skills/extract-static-html/scripts/post_process.ts b/.claude/skills/extract-static-html/scripts/post_process.ts new file mode 100644 index 0000000..0facbc7 --- /dev/null +++ b/.claude/skills/extract-static-html/scripts/post_process.ts @@ -0,0 +1,498 @@ +#!/usr/bin/env npx tsx +/** + * post_process.ts — Inline local images as base64 in extracted HTML files. + * + * Scans HTML files for local image references (src attributes and CSS url() + * values) and replaces them with inline base64 data URIs. Uses a robust + * character-by-character CSS url() parser instead of regex. + * + * Usage: + * npx tsx post_process.ts .stitch/home.html --base-dir my-app + * npx tsx post_process.ts .stitch/page1.html .stitch/page2.html --base-dir . + * npx tsx post_process.ts .stitch/*.html --base-dir . --json + * + * Flags: + * --base-dir Base directory for resolving relative paths + * --json Output machine-readable JSON stats + * --dry-run Report what would be inlined without modifying files + * --max-size Max file size to inline in bytes (default: 5242880 / 5MB) + */ + +import fs from 'node:fs'; +import path from 'node:path'; + +// --------------------------------------------------------------------------- +// MIME type mapping +// --------------------------------------------------------------------------- +const MIME_MAP: Record = { + '.svg': 'image/svg+xml', + '.jpeg': 'image/jpeg', + '.jpg': 'image/jpeg', + '.png': 'image/png', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.ico': 'image/x-icon', + '.bmp': 'image/bmp', + '.avif': 'image/avif', + '.tiff': 'image/tiff', + '.tif': 'image/tiff', + '.apng': 'image/apng', + '.cur': 'image/x-icon', +}; + +function getMime(filePath: string): string { + return MIME_MAP[path.extname(filePath).toLowerCase()] || 'application/octet-stream'; +} + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- +interface Opts { + files: string[]; + baseDir: string; + json: boolean; + dryRun: boolean; + maxSize: number; +} + +interface CssUrlRef { + url: string; + fullMatch: string; + start: number; + end: number; +} + +interface InlineStats { + srcInlined: number; + urlInlined: number; + skippedTooLarge: Array<{ path: string; size: number }>; + skippedNotFound: string[]; +} + +interface FileStats { + file: string; + srcInlined: number; + urlInlined: number; + skippedNotFound: number; + skippedTooLarge: number; + sizeBytes: number; +} + +interface AllStats { + files: FileStats[]; + totalSrcInlined: number; + totalUrlInlined: number; + totalSkippedNotFound: number; + totalSkippedTooLarge: number; +} + +// --------------------------------------------------------------------------- +// Argument parsing & validation +// --------------------------------------------------------------------------- +function parseArgs(): Opts { + const args = process.argv.slice(2); + const opts: Opts = { + files: [], + baseDir: '', + json: false, + dryRun: false, + maxSize: 5 * 1024 * 1024, // 5MB + }; + + for (let i = 0; i < args.length; i++) { + switch (args[i]) { + case '--base-dir': + opts.baseDir = args[++i]; + break; + case '--json': + opts.json = true; + break; + case '--dry-run': + opts.dryRun = true; + break; + case '--max-size': + opts.maxSize = parseInt(args[++i], 10); + break; + case '--help': + console.log(` +Usage: npx tsx post_process.ts [...] [options] + +Options: + --base-dir Base directory for resolving relative paths + --json Output machine-readable JSON stats + --dry-run Report what would be inlined without modifying files + --max-size Max file size to inline in bytes (default: 5242880 / 5MB) +`); + process.exit(0); + default: + opts.files.push(args[i]); + } + } + + return opts; +} + +function validateOpts(opts: Opts): void { + const errors: string[] = []; + + if (opts.files.length === 0) { + errors.push('No HTML files specified'); + } + + if (opts.baseDir && !fs.existsSync(opts.baseDir)) { + errors.push(`Base directory not found: ${opts.baseDir}`); + } + + if (isNaN(opts.maxSize) || opts.maxSize < 1) { + errors.push('--max-size must be a positive integer'); + } + + if (errors.length > 0) { + console.error('❌ Validation errors:'); + errors.forEach((e) => console.error(` • ${e}`)); + process.exit(1); + } +} + +// --------------------------------------------------------------------------- +// Robust CSS url() parser — character-by-character (no regex) +// --------------------------------------------------------------------------- +function extractCssUrls(text: string): CssUrlRef[] { + const results: CssUrlRef[] = []; + let i = 0; + const len = text.length; + + while (i < len) { + if ( + i + 3 < len && + text[i].toLowerCase() === 'u' && + text[i + 1].toLowerCase() === 'r' && + text[i + 2].toLowerCase() === 'l' && + text[i + 3] === '(' + ) { + const urlStart = i; + i += 4; + + // Skip whitespace + while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; + + let quote: string | null = null; + if (i < len && (text[i] === '"' || text[i] === "'")) { + quote = text[i]; + i++; + } + + let url = ''; + if (quote) { + while (i < len && text[i] !== quote) { + if (text[i] === '\\' && i + 1 < len) { + i++; + url += text[i]; + } else { + url += text[i]; + } + i++; + } + if (i < len) i++; + } else { + while (i < len && text[i] !== ')' && text[i] !== ' ' && text[i] !== '\t' && text[i] !== '\n') { + url += text[i]; + i++; + } + } + + while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; + + if (i < len && text[i] === ')') { + const fullMatch = text.substring(urlStart, i + 1); + results.push({ url: url.trim(), fullMatch, start: urlStart, end: i + 1 }); + i++; + } else { + i = urlStart + 1; + } + } else { + i++; + } + } + + return results; +} + +// --------------------------------------------------------------------------- +// Local path resolution +// --------------------------------------------------------------------------- +function resolveLocalFile(localPath: string, baseDir: string): string | null { + const candidates = [localPath]; + if (baseDir) { + candidates.push(path.join(baseDir, localPath.replace(/^\//, ''))); + } + + for (const candidate of candidates) { + try { + if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { + return candidate; + } + } catch { + // Permission errors, etc. — skip + } + } + return null; +} + +/** + * Atomically open, stat, and read a file using a file descriptor. + * Eliminates TOCTOU race conditions by performing all operations on the + * same fd, ensuring the file cannot change between the size check and read. + * Returns null if the file cannot be opened (e.g., deleted between resolve and open). + */ +function readFileAtomic( + filePath: string, + maxSize: number, +): { size: number; mime: string; b64: string } | { size: number; tooLarge: true } | null { + let fd: number; + try { + fd = fs.openSync(filePath, 'r'); + } catch { + // File was removed or became inaccessible between resolve and open + return null; + } + try { + const stat = fs.fstatSync(fd); + if (stat.size > maxSize) { + return { size: stat.size, tooLarge: true }; + } + const mime = getMime(filePath); + const b64 = fs.readFileSync(fd).toString('base64'); + return { size: stat.size, mime, b64 }; + } finally { + fs.closeSync(fd); + } +} + +/** + * Check if a path is a local (non-remote, non-data) reference. + */ +function isLocalPath(url: string): boolean { + return ( + !!url && + !url.startsWith('http://') && + !url.startsWith('https://') && + !url.startsWith('data:') && + !url.startsWith('//') + ); +} + +// --------------------------------------------------------------------------- +// Inline images in HTML +// --------------------------------------------------------------------------- +function inlineImages( + html: string, + baseDir: string, + maxSize: number, + dryRun: boolean, +): { html: string; stats: InlineStats } { + const stats: InlineStats = { + srcInlined: 0, + urlInlined: 0, + skippedTooLarge: [], + skippedNotFound: [], + }; + + // --- Inline src="" attributes --- + // Handle src, poster, data attributes + const srcAttrs = ['src', 'poster', 'data']; + for (const attr of srcAttrs) { + const regex = new RegExp(`${attr}="((?!https?:\\/\\/|data:|\\/\\/)[^"]+)"`, 'g'); + html = html.replace(regex, (match: string, localPath: string) => { + const resolved = resolveLocalFile(localPath, baseDir); + if (!resolved) { + if (!localPath.endsWith('.js') && !localPath.endsWith('.css')) { + stats.skippedNotFound.push(localPath); + } + return match; + } + + const result = readFileAtomic(resolved, maxSize); + if (!result) { + stats.skippedNotFound.push(localPath); + return match; + } + if ('tooLarge' in result) { + stats.skippedTooLarge.push({ path: localPath, size: result.size }); + return match; + } + + if (dryRun) { + stats.srcInlined++; + return match; + } + + stats.srcInlined++; + return `${attr}="data:${result.mime};base64,${result.b64}"`; + }); + } + + // --- Inline CSS url() with local paths (using robust parser) --- + const urlRefs = extractCssUrls(html); + const localUrlRefs = urlRefs.filter((ref) => isLocalPath(ref.url)); + + // Process from end to preserve indices + const sorted = [...localUrlRefs].sort((a, b) => b.start - a.start); + for (const ref of sorted) { + const resolved = resolveLocalFile(ref.url, baseDir); + if (!resolved) { + stats.skippedNotFound.push(ref.url); + continue; + } + + const result = readFileAtomic(resolved, maxSize); + if (!result) { + stats.skippedNotFound.push(ref.url); + continue; + } + if ('tooLarge' in result) { + stats.skippedTooLarge.push({ path: ref.url, size: result.size }); + continue; + } + + if (dryRun) { + stats.urlInlined++; + continue; + } + + html = + html.substring(0, ref.start) + + `url('data:${result.mime};base64,${result.b64}')` + + html.substring(ref.end); + stats.urlInlined++; + } + + // --- Inline SVG and xlink:href --- + const svgHrefRegex = /(href|xlink:href)="((?!https?:\/\/|data:|\/\/)[^"]+)"/g; + html = html.replace(svgHrefRegex, (match: string, attrName: string, localPath: string) => { + // Skip non-image hrefs (like ) + if (!localPath.match(/\.(svg|png|jpg|jpeg|gif|webp|avif|bmp|ico)$/i)) { + return match; + } + + const resolved = resolveLocalFile(localPath, baseDir); + if (!resolved) { + stats.skippedNotFound.push(localPath); + return match; + } + + const result = readFileAtomic(resolved, maxSize); + if (!result) { + stats.skippedNotFound.push(localPath); + return match; + } + if ('tooLarge' in result) { + stats.skippedTooLarge.push({ path: localPath, size: result.size }); + return match; + } + + if (dryRun) { + stats.srcInlined++; + return match; + } + + stats.srcInlined++; + return `${attrName}="data:${result.mime};base64,${result.b64}"`; + }); + + return { html, stats }; +} + +// --------------------------------------------------------------------------- +// Main +// --------------------------------------------------------------------------- +function main(): void { + const opts = parseArgs(); + validateOpts(opts); + + const allStats: AllStats = { + files: [], + totalSrcInlined: 0, + totalUrlInlined: 0, + totalSkippedNotFound: 0, + totalSkippedTooLarge: 0, + }; + + if (opts.dryRun) { + console.log('🔍 DRY RUN — no files will be modified\n'); + } + + for (const file of opts.files) { + // Open file once with r+ to eliminate TOCTOU race between read and write. + // A single fd is used for both operations, so the file cannot be swapped + // between the read and write phases. + let fd: number; + try { + fd = fs.openSync(file, opts.dryRun ? 'r' : 'r+'); + } catch { + console.warn(`⚠️ File not found, skipping: ${file}`); + continue; + } + + let processed: string = ''; + let stats: InlineStats = { srcInlined: 0, urlInlined: 0, skippedTooLarge: [], skippedNotFound: [] }; + try { + const html = fs.readFileSync(fd, 'utf-8'); + + const result = inlineImages(html, opts.baseDir, opts.maxSize, opts.dryRun); + processed = result.html; + stats = result.stats; + + if (!opts.dryRun) { + // Truncate and rewrite using the same fd — no second path-based open + fs.ftruncateSync(fd); + fs.writeSync(fd, processed, 0, 'utf-8'); + } + } finally { + fs.closeSync(fd); + } + + const totalInlined = stats.srcInlined + stats.urlInlined; + const label = opts.dryRun ? 'would inline' : 'inlined'; + console.log( + `${file}: ${label} ${totalInlined} resources ` + + `(${stats.srcInlined} src, ${stats.urlInlined} url()) ` + + `— ${processed.length.toLocaleString()} bytes`, + ); + + if (stats.skippedTooLarge.length > 0) { + for (const s of stats.skippedTooLarge) { + console.log( + ` ⚠️ Skipped (too large: ${(s.size / 1024).toFixed(1)} KB): ${s.path}`, + ); + } + } + + allStats.files.push({ + file, + srcInlined: stats.srcInlined, + urlInlined: stats.urlInlined, + skippedNotFound: stats.skippedNotFound.length, + skippedTooLarge: stats.skippedTooLarge.length, + sizeBytes: processed.length, + }); + allStats.totalSrcInlined += stats.srcInlined; + allStats.totalUrlInlined += stats.urlInlined; + allStats.totalSkippedNotFound += stats.skippedNotFound.length; + allStats.totalSkippedTooLarge += stats.skippedTooLarge.length; + } + + const totalInlined = allStats.totalSrcInlined + allStats.totalUrlInlined; + console.log(`\n✅ Total: ${totalInlined} resources inlined across ${allStats.files.length} file(s)`); + + if (allStats.totalSkippedTooLarge > 0) { + console.log(` ⚠️ ${allStats.totalSkippedTooLarge} skipped (exceeded ${(opts.maxSize / 1024 / 1024).toFixed(1)} MB limit)`); + } + + if (opts.json) { + console.log('\n--- JSON Stats ---'); + console.log(JSON.stringify(allStats, null, 2)); + } +} + +main(); diff --git a/.claude/skills/extract-static-html/scripts/snapshot.ts b/.claude/skills/extract-static-html/scripts/snapshot.ts new file mode 100644 index 0000000..88c9cd2 --- /dev/null +++ b/.claude/skills/extract-static-html/scripts/snapshot.ts @@ -0,0 +1,1470 @@ +#!/usr/bin/env npx tsx +/** + * snapshot.ts — Production-grade Puppeteer-based full-page HTML snapshot + * + * Captures the fully rendered DOM from a running web application and produces + * a self-contained HTML file with all CSS inlined and images converted to + * base64 data URIs. Works with any framework (React, Vue, Svelte, Angular, + * plain HTML, etc.) — no MockPage.jsx needed. + * + * Usage: + * npx tsx snapshot.ts --url http://localhost:5173 --output .stitch/home.html + * npx tsx snapshot.ts --url http://localhost:3000/pricing --output .stitch/pricing.html --html-class dark + * npx tsx snapshot.ts --url http://localhost:5173 --output .stitch/page.html --wait 5000 --viewport 1440x900 + * + * Flags: + * --url URL to capture (required) + * --output Output file path (required) + * --wait Extra wait time in ms after network idle (default: 1000) + * --viewport Viewport size as WIDTHxHEIGHT (default: 1280x800) + * --html-class Class(es) to add to element (e.g., "dark") + * --remove-fixed Remove fixed/sticky positioned elements (e.g., cookie banners) + * --full-height Capture full scrollable content by resizing viewport to scrollHeight + * --title Override the page title + * --timeout Global timeout in ms (default: 60000) + * --concurrency Max concurrent resource fetches (default: 6) + * --json Output machine-readable JSON stats to stdout + */ + +import puppeteer, { type Browser } from 'puppeteer'; +import path from 'node:path'; +import fs from 'node:fs'; + +// --------------------------------------------------------------------------- +// Types +// --------------------------------------------------------------------------- +interface Opts { + url: string | null; + output: string | null; + wait: number; + viewport: string; + htmlClass: string | null; + removeFixed: boolean; + fullHeight: boolean; + title: string | null; + authScript: string | null; + inlineCanvas: boolean; + timeout: number; + concurrency: number; + json: boolean; + inlineFonts: boolean; + removeSelectors: string | null; + click: string | null; +} + +interface Stats { + url: string | null; + output: string | null; + sizeBytes: number; + stylesheets: number; + images: number; + cssUrls: number; + svgImages: number; + videoPoster: number; + favicons: number; + scriptsRemoved: number; + warnings: string[]; + durationMs: number; + error?: string; +} + +// --------------------------------------------------------------------------- +// Argument parsing +// --------------------------------------------------------------------------- +function parseArgs(): Opts { + const args = process.argv.slice(2); + const opts: Opts = { + url: null, + output: null, + wait: 1000, + viewport: '1280x800', + htmlClass: null, + removeFixed: false, + fullHeight: false, + title: null, + authScript: null, + inlineCanvas: false, + timeout: 60000, + concurrency: 6, + json: false, + inlineFonts: false, + removeSelectors: null, + click: null, + }; + + for (let i = 0; i < args.length; i++) { + switch (args[i]) { + case '--url': + opts.url = args[++i]; + break; + case '--output': + opts.output = args[++i]; + break; + case '--wait': + opts.wait = parseInt(args[++i], 10); + break; + case '--viewport': + opts.viewport = args[++i]; + break; + case '--html-class': + opts.htmlClass = args[++i]; + break; + case '--remove-fixed': + opts.removeFixed = true; + break; + case '--full-height': + opts.fullHeight = true; + break; + case '--title': + opts.title = args[++i]; + break; + case '--auth-script': + opts.authScript = args[++i]; + break; + case '--inline-canvas': + opts.inlineCanvas = true; + break; + case '--timeout': + opts.timeout = parseInt(args[++i], 10); + break; + case '--concurrency': + opts.concurrency = parseInt(args[++i], 10); + break; + case '--json': + opts.json = true; + break; + case '--inline-fonts': + opts.inlineFonts = true; + break; + case '--remove-selectors': + opts.removeSelectors = args[++i]; + break; + case '--click': + opts.click = args[++i]; + break; + case '--help': + console.log(` +Usage: npx tsx snapshot.ts --url --output [options] + +Options: + --url URL to capture (required) + --output Output file path (required) + --wait Extra wait time in ms after network idle (default: 1000) + --viewport Viewport size as WIDTHxHEIGHT (default: 1280x800) + --html-class Class(es) to add to element (e.g., "dark") + --remove-fixed Remove fixed/sticky positioned elements (cookie banners, etc.) + --full-height Resize viewport to capture full scrollable content + --title Override the page title + --auth-script Path to JS/TS script exporting an async function to authenticate before capture + --inline-canvas Convert elements (charts, graphs) to base64 images + --timeout Global timeout in ms (default: 60000) + --concurrency Max concurrent resource fetches (default: 6) + --json Output machine-readable JSON stats +`); + process.exit(0); + default: + console.error(`Unknown argument: ${args[i]}`); + process.exit(1); + } + } + + return opts; +} + +// --------------------------------------------------------------------------- +// Input validation +// --------------------------------------------------------------------------- +function validateOpts(opts: Opts): void { + const errors: string[] = []; + + if (!opts.url) errors.push('--url is required'); + if (!opts.output) errors.push('--output is required'); + + if (opts.url) { + try { + new URL(opts.url); + } catch { + errors.push( + `Invalid URL: "${opts.url}". Must be a valid URL (e.g., http://localhost:5173)`, + ); + } + } + + if (opts.viewport) { + const vpMatch = opts.viewport.match(/^(\d+)x(\d+)$/); + if (!vpMatch) { + errors.push( + `Invalid viewport: "${opts.viewport}". Must be WIDTHxHEIGHT (e.g., 1280x800)`, + ); + } else { + const w = Number(vpMatch[1]); + const h = Number(vpMatch[2]); + if (w < 1 || h < 1) { + errors.push('Viewport dimensions must be positive integers'); + } + if (w > 7680 || h > 4320) { + errors.push('Viewport too large: max 7680x4320'); + } + } + } + + if (isNaN(opts.wait) || opts.wait < 0) { + errors.push('--wait must be a non-negative integer'); + } + + if (isNaN(opts.timeout) || opts.timeout < 1000) { + errors.push('--timeout must be at least 1000ms'); + } + + if (isNaN(opts.concurrency) || opts.concurrency < 1 || opts.concurrency > 20) { + errors.push('--concurrency must be between 1 and 20'); + } + + if (opts.output) { + const outputDir = path.dirname(path.resolve(opts.output)); + try { + fs.mkdirSync(outputDir, { recursive: true }); + fs.accessSync(outputDir, fs.constants.W_OK); + } catch (e: unknown) { + errors.push(`Cannot write to output directory: ${(e as Error).message}`); + } + } + + if (errors.length > 0) { + console.error('❌ Validation errors:'); + errors.forEach((e) => console.error(` • ${e}`)); + process.exit(1); + } +} + +// --------------------------------------------------------------------------- +// Main snapshot logic +// --------------------------------------------------------------------------- +async function snapshot(opts: Opts): Promise { + const [, widthStr, heightStr] = opts.viewport.match(/^(\d+)x(\d+)$/)!; + const width = Number(widthStr); + const height = Number(heightStr); + + let browser: Browser | undefined; + let globalTimer: ReturnType | undefined; + + // Stats tracking + const stats: Stats = { + url: opts.url, + output: null, + sizeBytes: 0, + stylesheets: 0, + images: 0, + cssUrls: 0, + svgImages: 0, + videoPoster: 0, + favicons: 0, + scriptsRemoved: 0, + warnings: [], + durationMs: 0, + }; + const startTime = Date.now(); + + try { + // Global timeout safety net — prevents zombie browser processes + globalTimer = setTimeout(() => { + const msg = `Global timeout of ${opts.timeout}ms exceeded — aborting`; + console.error(`⏰ ${msg}`); + stats.warnings.push(msg); + if (browser) browser.close().catch(() => {}); + if (opts.json) { + stats.durationMs = Date.now() - startTime; + stats.error = msg; + console.log(JSON.stringify(stats, null, 2)); + } + process.exit(2); + }, opts.timeout); + + // ----- Launch browser ----- + console.log('🚀 Launching browser...'); + browser = await puppeteer.launch({ + headless: true, + args: [ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-dev-shm-usage', + `--window-size=${width},${height}`, + ], + }); + + const page = await browser.newPage(); + await page.setViewport({ width, height }); + + // Forward browser console logs to Node.js + page.on('console', (msg) => { + const type = msg.type().toString(); + if (type === 'warning' || type === 'error') { + console.log(` [Browser ${type.toUpperCase()}] ${msg.text()}`); + } + }); + + // ----- Navigate and wait for network idle ----- + console.log(`📄 Navigating to ${opts.url}...`); + try { + await page.goto(opts.url!, { + waitUntil: 'networkidle0', + timeout: 10000, + }); + } catch { + const msg = 'networkidle0 timed out, falling back to networkidle2'; + console.warn(`⚠️ ${msg}...`); + stats.warnings.push(msg); + try { + await page.goto(opts.url!, { + waitUntil: 'networkidle2', + timeout: 10000, + }); + } catch { + const msg2 = 'networkidle2 timed out, falling back to domcontentloaded'; + console.warn(`⚠️ ${msg2}...`); + stats.warnings.push(msg2); + await page.goto(opts.url!, { + waitUntil: 'domcontentloaded', + timeout: 15000, + }); + } + } + + // Extra wait for JS-rendered content (animations, lazy loading, etc.) + if (opts.wait > 0) { + console.log(`⏳ Waiting ${opts.wait}ms for rendering to settle...`); + await new Promise((r) => setTimeout(r, opts.wait)); + } + + // Execute authentication script if provided + if (opts.authScript) { + console.log(`🔐 Running authentication script from ${opts.authScript}...`); + try { + const path = await import('path'); + const authPath = path.resolve(process.cwd(), opts.authScript); + const authModule = await import(authPath); + const authFn = authModule.default || authModule; + if (typeof authFn === 'function') { + await authFn(page); + console.log(' ✅ Auth script executed, re-navigating to target URL...'); + await page.goto(opts.url!, { + waitUntil: 'networkidle2', + timeout: Math.min(30000, opts.timeout), + }); + if (opts.wait > 0) { + await new Promise((r) => setTimeout(r, opts.wait)); + } + } else { + console.warn(`⚠️ --auth-script (${opts.authScript}) did not export a function`); + } + } catch (err: any) { + console.warn(`⚠️ Failed to execute --auth-script: ${err.message}`); + stats.warnings.push(`auth-script error: ${err.message}`); + } + } + + // Perform click interaction if specified + if (opts.click) { + console.log(`🖱️ Clicking element "${opts.click}"...`); + try { + let element = await page.$(opts.click); + if (!element) { + // Search in child frames recursively! + for (const frame of page.frames()) { + const childElement = await frame.$(opts.click); + if (childElement) { + element = childElement; + console.log(` Found element inside child frame: ${frame.url()}`); + break; + } + } + } + + if (element) { + await element.click(); + // wait an extra 2 seconds for animation or modal loading to settle + console.log(` Click succeeded! Waiting 2000ms for click action to settle...`); + await new Promise((r) => setTimeout(r, 2000)); + } else { + throw new Error(`Selector "${opts.click}" not found in main document or child frames.`); + } + } catch (clickErr: any) { + console.error(`⚠️ Click action failed:`, clickErr); + stats.warnings.push(`Click action failed: ${clickErr.message || clickErr}`); + } + } + + // ----- Pre-processing options ----- + + // Add class to (e.g., dark mode) + if (opts.htmlClass) { + console.log(`🎨 Adding class "${opts.htmlClass}" to ...`); + await page.evaluate((cls: string) => { + document.documentElement.classList.add(...cls.split(/\s+/)); + if (cls.includes('dark')) { + document.documentElement.setAttribute('data-theme', 'dark'); + } else if (cls.includes('light')) { + document.documentElement.setAttribute('data-theme', 'light'); + } + }, opts.htmlClass); + await new Promise((r) => setTimeout(r, 500)); + } + + // Remove fixed/sticky elements + if (opts.removeFixed) { + console.log('🧹 Removing fixed/sticky positioned elements...'); + await page.evaluate(() => { + const all = document.querySelectorAll('*'); + for (const el of all) { + const style = getComputedStyle(el); + if (style.position === 'fixed' || style.position === 'sticky') { + const rect = el.getBoundingClientRect(); + if (rect.top > 100 || rect.height < 50) { + el.remove(); + } + } + } + }); + } + + // Remove custom selectors + if (opts.removeSelectors) { + console.log(`🧹 Removing custom selectors: "${opts.removeSelectors}"...`); + await page.evaluate((selectors: string) => { + const items = selectors.split(',').map((s) => s.trim()).filter(Boolean); + for (const selector of items) { + try { + document.querySelectorAll(selector).forEach((el) => el.remove()); + } catch (e) { + console.warn(`Invalid selector "${selector}":`, e); + } + } + }, opts.removeSelectors); + } + + + + // Override title + if (opts.title) { + await page.evaluate((t: string) => { + document.title = t; + }, opts.title); + } + + // ----- Inject shared browser-side helpers (deduplication) ----- + // Mock __name to prevent esbuild generated code from failing in browser + await page.evaluate(() => { + (window as any).__name = (fn: any, name: string) => fn; + }); + + await page.evaluate((concurrency: number) => { + (window as any).__snapshot = { + CONCURRENCY: concurrency, + + toDataUri: async (url: string): Promise => { + try { + const resp = await fetch(url, { + mode: 'cors', + credentials: 'same-origin', + }); + if (!resp.ok) return null; + const blob = await resp.blob(); + return new Promise((resolve) => { + const reader = new FileReader(); + reader.onloadend = () => resolve(reader.result as string); + reader.onerror = () => resolve(null); + reader.readAsDataURL(blob); + }); + } catch { + return null; + } + }, + + processInBatches: async ( + items: T[], + batchSize: number, + fn: (item: T) => Promise, + ): Promise<(R | null)[]> => { + const results: (R | null)[] = []; + for (let i = 0; i < items.length; i += batchSize) { + const batch = items.slice(i, i + batchSize); + const batchResults = await Promise.allSettled(batch.map(fn)); + results.push( + ...batchResults.map((r) => + r.status === 'fulfilled' ? r.value : null, + ), + ); + } + return results; + }, + + /** + * Robust CSS url() parser — character-by-character parsing instead of regex. + * Handles: quoted/unquoted values, escaped characters, whitespace, + * data URIs, and malformed url() tokens. + * + * Returns: Array of { url, fullMatch, start, end } + */ + extractCssUrls: (cssText: string) => { + const results: Array<{ url: string; fullMatch: string; start: number; end: number }> = []; + let i = 0; + const len = cssText.length; + + while (i < len) { + // Look for 'url(' — case insensitive + if ( + i + 3 < len && + cssText[i].toLowerCase() === 'u' && + cssText[i + 1].toLowerCase() === 'r' && + cssText[i + 2].toLowerCase() === 'l' && + cssText[i + 3] === '(' + ) { + const urlStart = i; + i += 4; // skip 'url(' + + // Skip whitespace + while ( + i < len && + (cssText[i] === ' ' || + cssText[i] === '\t' || + cssText[i] === '\n' || + cssText[i] === '\r') + ) { + i++; + } + + // Check for quote + let quote: string | null = null; + if (i < len && (cssText[i] === '"' || cssText[i] === "'")) { + quote = cssText[i]; + i++; + } + + // Read the URL value + let url = ''; + if (quote) { + // Quoted: read until matching unescaped quote + while (i < len && cssText[i] !== quote) { + if (cssText[i] === '\\' && i + 1 < len) { + i++; // skip backslash + url += cssText[i]; // include next char literally + } else { + url += cssText[i]; + } + i++; + } + if (i < len) i++; // skip closing quote + } else { + // Unquoted: stop at ) or whitespace (per CSS spec) + while ( + i < len && + cssText[i] !== ')' && + cssText[i] !== ' ' && + cssText[i] !== '\t' && + cssText[i] !== '\n' && + cssText[i] !== '\r' + ) { + url += cssText[i]; + i++; + } + } + + // Skip trailing whitespace before ')' + while ( + i < len && + (cssText[i] === ' ' || + cssText[i] === '\t' || + cssText[i] === '\n' || + cssText[i] === '\r') + ) { + i++; + } + + if (i < len && cssText[i] === ')') { + const fullMatch = cssText.substring(urlStart, i + 1); + results.push({ + url: url.trim(), + fullMatch, + start: urlStart, + end: i + 1, + }); + i++; + } else { + // Malformed url() — skip past 'url(' and try again + i = urlStart + 1; + } + } else { + i++; + } + } + + return results; + }, + + /** + * Replace CSS url() references using pre-computed positions. + * Replaces from end-to-start to preserve earlier indices. + */ + replaceCssUrls: ( + cssText: string, + replacements: Array<{ start: number; end: number; dataUri: string }>, + ): string => { + const sorted = [...replacements].sort((a, b) => b.start - a.start); + for (const r of sorted) { + cssText = + cssText.substring(0, r.start) + + "url('" + + r.dataUri + + "')" + + cssText.substring(r.end); + } + return cssText; + }, + }; + }, opts.concurrency); + + // ----------------------------------------------------------------------- + // -2. Remove dev-overlay / screenshot-ignore elements (e.g. VeloUI) + // ----------------------------------------------------------------------- + const removedCount = await page.evaluate(() => { + let count = 0; + // Remove any element explicitly marked as screenshot-ignore + document.querySelectorAll('[data-screenshot-ignore="true"]').forEach(el => { + el.parentNode?.removeChild(el); count++; + }); + // Remove VeloUI overlay elements (pause overlay, probe, root container, etc.) + const veloSelectors = [ + '[data-veloui-pause-overlay]', + '[data-veloui-probe]', + '[data-veloui-extractor]', + '[data-veloui-scan]', + '.veloui-root', + '.veloui-liquid-glass', + ]; + for (const sel of veloSelectors) { + document.querySelectorAll(sel).forEach(el => { + el.parentNode?.removeChild(el); count++; + }); + } + return count; + }); + if (removedCount > 0) { + console.log(`🧹 Removed ${removedCount} dev-overlay / screenshot-ignore element(s) from the DOM.`); + } + + // ----------------------------------------------------------------------- + // -1. Inline local iframes (e.g., companion-app test iframe) + // ----------------------------------------------------------------------- + const iframesCount = await page.evaluate(() => document.querySelectorAll('iframe').length); + if (iframesCount > 0) { + console.log(`🔍 Found ${iframesCount} iframe(s) in the main page. Extracting content natively...`); + + // First, recursively inline all same-origin and srcDoc iframes browser-side + console.log('🔍 Inlining same-origin and srcDoc iframes recursively...'); + await page.evaluate(() => { + const inlineSameOriginIframes = (root: Document | HTMLElement) => { + const iframes = Array.from(root.querySelectorAll('iframe')); + for (const iframe of iframes) { + if ( + iframe.getAttribute('data-screenshot-ignore') === 'true' || + iframe.getAttribute('data-veloui-scan') === 'true' || + iframe.getAttribute('data-veloui-probe') === 'true' || + iframe.hasAttribute('data-veloui-extractor') + ) { + // Remove the hidden crawler/scan iframes completely from DOM + try { iframe.parentNode && iframe.parentNode.removeChild(iframe); } catch { } + continue; + } + try { + const doc = iframe.contentDocument || iframe.contentWindow?.document; + if (doc && doc.body) { + // Recursively inline same-origin iframes inside this child frame first + inlineSameOriginIframes(doc); + + const bodyHtml = doc.body.innerHTML; + + const styles: string[] = []; + doc.querySelectorAll('style').forEach(s => styles.push(s.outerHTML)); + doc.querySelectorAll('link[rel="stylesheet"]').forEach(l => styles.push((l as HTMLLinkElement).outerHTML)); + + styles.forEach(styleHtml => { + const temp = document.createElement('div'); + temp.innerHTML = styleHtml; + document.head.appendChild(temp.firstChild!); + }); + + const wrapper = document.createElement('div'); + wrapper.className = 'ac-iframe-inlined-wrapper'; + + // Apply child body's classes and attributes to same-origin wrapper + for (const attr of Array.from(doc.body.attributes)) { + if (attr.name === 'class') { + wrapper.classList.add(...attr.value.split(/\s+/).filter(Boolean)); + } else if (attr.name !== 'style') { + wrapper.setAttribute(attr.name, attr.value); + } + } + + wrapper.style.position = 'absolute'; + wrapper.style.top = '0'; + wrapper.style.left = '0'; + wrapper.style.width = '100%'; + wrapper.style.height = '100%'; + wrapper.style.overflow = 'hidden'; + wrapper.innerHTML = bodyHtml; + + iframe.parentNode!.replaceChild(wrapper, iframe); + } + } catch (e) { + // Ignore cross-origin iframes; the Puppeteer frame loop will process them + } + } + }; + inlineSameOriginIframes(document); + }); + + const childFrames = page.frames() + .filter(f => f !== page.mainFrame()) + .map(f => { + let depth = 0; + let p = f.parentFrame(); + while (p) { + depth++; + p = p.parentFrame(); + } + return { frame: f, depth }; + }) + .sort((a, b) => b.depth - a.depth); + + for (const { frame } of childFrames) { + try { + const frameUrl = frame.url(); + const cleanUrl = frameUrl.split('?')[0].split('#')[0]; + console.log(`📦 Extracting frame content from: ${cleanUrl} (depth: ${frame.parentFrame() ? 'nested' : 'root'})`); + + // Inject __name mock to prevent esbuild helper ReferenceError in child frame + await frame.evaluate(() => { + (window as any).__name = (fn: any) => fn; + }); + + // Resolve all relative assets inside the frame to absolute URLs relative to the frame's URL + await frame.evaluate((base) => { + const resolveAttr = (el: Element, attr: string) => { + const val = el.getAttribute(attr); + if (val && !val.startsWith('data:') && !val.startsWith('http:') && !val.startsWith('https:') && !val.startsWith('//')) { + try { + const abs = new URL(val, base).href; + el.setAttribute(attr, abs); + } catch (e) { } + } + }; + document.querySelectorAll('img[src]').forEach(img => resolveAttr(img, 'src')); + document.querySelectorAll('img[srcset]').forEach(img => resolveAttr(img, 'srcset')); + document.querySelectorAll('source[srcset]').forEach(src => resolveAttr(src, 'srcset')); + document.querySelectorAll('link[rel="stylesheet"]').forEach(link => resolveAttr(link, 'href')); + + // Resolve relative url() references in inline \n\n`; - - return head; -} - -// --------------------------------------------------------------------------- -// Main -// --------------------------------------------------------------------------- -async function main(): Promise { - const opts = parseArgs(); - validateOpts(opts); - - const startTime = Date.now(); - const head = buildHead(opts); - const stats: AllStats = { - pages: [], - totalImages: 0, - durationMs: 0, - warnings: [], - }; - - fs.mkdirSync(opts.outdir, { recursive: true }); - - for (const spec of opts.pages) { - const parts = spec.split(':'); - const [src, dstName, title] = parts; - const dst = path.join(opts.outdir, dstName); - - console.log(`\n${'='.repeat(60)}`); - console.log(`Converting ${src} -> ${dstName}...`); - console.log(`${'='.repeat(60)}`); - - const jsx = fs.readFileSync(src, 'utf-8'); - let body = jsxToHtml(jsx); - - if (!body) { - const msg = `Failed to parse JSX from ${src}`; - console.error(` ${msg}`); - stats.warnings.push(msg); - continue; - } - - // Apply exclude pattern (pre-validated during argument parsing) - if (opts.excludePattern) { - body = body.replace(opts.excludePattern, ''); - } - - // Extract body class from outer wrapper div - const outerMatch = body.match(/^]*>([\s\S]*)<\/div>$/); - let fullHtml: string; - if (outerMatch) { - fullHtml = head.replace('{{title}}', title) + - `\n${outerMatch[2].trim()}\n\n`; - } else { - fullHtml = head.replace('{{title}}', title) + - `\n${body}\n\n`; - } - - // Embed remote images with concurrency - const cacheCountBefore = imgCache.size; - fullHtml = await embedImages(fullHtml, opts.concurrency, opts.timeout); - const imagesEmbedded = imgCache.size - cacheCountBefore; - - fs.writeFileSync(dst, fullHtml, 'utf-8'); - const fileSize = fs.statSync(dst).size; - console.log(`=> ${dst} (${fileSize.toLocaleString()} bytes)`); - - stats.pages.push({ - src, - dst, - sizeBytes: fileSize, - imagesEmbedded, - }); - } - - stats.totalImages = imgCache.size; - stats.durationMs = Date.now() - startTime; - - console.log( - `\nDONE: ${imgCache.size} unique images embedded in ${stats.durationMs}ms.`, - ); - - if (opts.json) { - console.log('\n--- JSON Stats ---'); - console.log(JSON.stringify(stats, null, 2)); - } -} - -main().catch((err: Error) => { - console.error('❌ Error:', err.message); - if (err.stack) console.error(err.stack); - process.exit(1); -}); diff --git a/.claude/skills/extract-static-html/scripts/post_process.ts b/.claude/skills/extract-static-html/scripts/post_process.ts deleted file mode 100644 index 0facbc7..0000000 --- a/.claude/skills/extract-static-html/scripts/post_process.ts +++ /dev/null @@ -1,498 +0,0 @@ -#!/usr/bin/env npx tsx -/** - * post_process.ts — Inline local images as base64 in extracted HTML files. - * - * Scans HTML files for local image references (src attributes and CSS url() - * values) and replaces them with inline base64 data URIs. Uses a robust - * character-by-character CSS url() parser instead of regex. - * - * Usage: - * npx tsx post_process.ts .stitch/home.html --base-dir my-app - * npx tsx post_process.ts .stitch/page1.html .stitch/page2.html --base-dir . - * npx tsx post_process.ts .stitch/*.html --base-dir . --json - * - * Flags: - * --base-dir Base directory for resolving relative paths - * --json Output machine-readable JSON stats - * --dry-run Report what would be inlined without modifying files - * --max-size Max file size to inline in bytes (default: 5242880 / 5MB) - */ - -import fs from 'node:fs'; -import path from 'node:path'; - -// --------------------------------------------------------------------------- -// MIME type mapping -// --------------------------------------------------------------------------- -const MIME_MAP: Record = { - '.svg': 'image/svg+xml', - '.jpeg': 'image/jpeg', - '.jpg': 'image/jpeg', - '.png': 'image/png', - '.gif': 'image/gif', - '.webp': 'image/webp', - '.ico': 'image/x-icon', - '.bmp': 'image/bmp', - '.avif': 'image/avif', - '.tiff': 'image/tiff', - '.tif': 'image/tiff', - '.apng': 'image/apng', - '.cur': 'image/x-icon', -}; - -function getMime(filePath: string): string { - return MIME_MAP[path.extname(filePath).toLowerCase()] || 'application/octet-stream'; -} - -// --------------------------------------------------------------------------- -// Types -// --------------------------------------------------------------------------- -interface Opts { - files: string[]; - baseDir: string; - json: boolean; - dryRun: boolean; - maxSize: number; -} - -interface CssUrlRef { - url: string; - fullMatch: string; - start: number; - end: number; -} - -interface InlineStats { - srcInlined: number; - urlInlined: number; - skippedTooLarge: Array<{ path: string; size: number }>; - skippedNotFound: string[]; -} - -interface FileStats { - file: string; - srcInlined: number; - urlInlined: number; - skippedNotFound: number; - skippedTooLarge: number; - sizeBytes: number; -} - -interface AllStats { - files: FileStats[]; - totalSrcInlined: number; - totalUrlInlined: number; - totalSkippedNotFound: number; - totalSkippedTooLarge: number; -} - -// --------------------------------------------------------------------------- -// Argument parsing & validation -// --------------------------------------------------------------------------- -function parseArgs(): Opts { - const args = process.argv.slice(2); - const opts: Opts = { - files: [], - baseDir: '', - json: false, - dryRun: false, - maxSize: 5 * 1024 * 1024, // 5MB - }; - - for (let i = 0; i < args.length; i++) { - switch (args[i]) { - case '--base-dir': - opts.baseDir = args[++i]; - break; - case '--json': - opts.json = true; - break; - case '--dry-run': - opts.dryRun = true; - break; - case '--max-size': - opts.maxSize = parseInt(args[++i], 10); - break; - case '--help': - console.log(` -Usage: npx tsx post_process.ts [...] [options] - -Options: - --base-dir Base directory for resolving relative paths - --json Output machine-readable JSON stats - --dry-run Report what would be inlined without modifying files - --max-size Max file size to inline in bytes (default: 5242880 / 5MB) -`); - process.exit(0); - default: - opts.files.push(args[i]); - } - } - - return opts; -} - -function validateOpts(opts: Opts): void { - const errors: string[] = []; - - if (opts.files.length === 0) { - errors.push('No HTML files specified'); - } - - if (opts.baseDir && !fs.existsSync(opts.baseDir)) { - errors.push(`Base directory not found: ${opts.baseDir}`); - } - - if (isNaN(opts.maxSize) || opts.maxSize < 1) { - errors.push('--max-size must be a positive integer'); - } - - if (errors.length > 0) { - console.error('❌ Validation errors:'); - errors.forEach((e) => console.error(` • ${e}`)); - process.exit(1); - } -} - -// --------------------------------------------------------------------------- -// Robust CSS url() parser — character-by-character (no regex) -// --------------------------------------------------------------------------- -function extractCssUrls(text: string): CssUrlRef[] { - const results: CssUrlRef[] = []; - let i = 0; - const len = text.length; - - while (i < len) { - if ( - i + 3 < len && - text[i].toLowerCase() === 'u' && - text[i + 1].toLowerCase() === 'r' && - text[i + 2].toLowerCase() === 'l' && - text[i + 3] === '(' - ) { - const urlStart = i; - i += 4; - - // Skip whitespace - while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; - - let quote: string | null = null; - if (i < len && (text[i] === '"' || text[i] === "'")) { - quote = text[i]; - i++; - } - - let url = ''; - if (quote) { - while (i < len && text[i] !== quote) { - if (text[i] === '\\' && i + 1 < len) { - i++; - url += text[i]; - } else { - url += text[i]; - } - i++; - } - if (i < len) i++; - } else { - while (i < len && text[i] !== ')' && text[i] !== ' ' && text[i] !== '\t' && text[i] !== '\n') { - url += text[i]; - i++; - } - } - - while (i < len && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++; - - if (i < len && text[i] === ')') { - const fullMatch = text.substring(urlStart, i + 1); - results.push({ url: url.trim(), fullMatch, start: urlStart, end: i + 1 }); - i++; - } else { - i = urlStart + 1; - } - } else { - i++; - } - } - - return results; -} - -// --------------------------------------------------------------------------- -// Local path resolution -// --------------------------------------------------------------------------- -function resolveLocalFile(localPath: string, baseDir: string): string | null { - const candidates = [localPath]; - if (baseDir) { - candidates.push(path.join(baseDir, localPath.replace(/^\//, ''))); - } - - for (const candidate of candidates) { - try { - if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) { - return candidate; - } - } catch { - // Permission errors, etc. — skip - } - } - return null; -} - -/** - * Atomically open, stat, and read a file using a file descriptor. - * Eliminates TOCTOU race conditions by performing all operations on the - * same fd, ensuring the file cannot change between the size check and read. - * Returns null if the file cannot be opened (e.g., deleted between resolve and open). - */ -function readFileAtomic( - filePath: string, - maxSize: number, -): { size: number; mime: string; b64: string } | { size: number; tooLarge: true } | null { - let fd: number; - try { - fd = fs.openSync(filePath, 'r'); - } catch { - // File was removed or became inaccessible between resolve and open - return null; - } - try { - const stat = fs.fstatSync(fd); - if (stat.size > maxSize) { - return { size: stat.size, tooLarge: true }; - } - const mime = getMime(filePath); - const b64 = fs.readFileSync(fd).toString('base64'); - return { size: stat.size, mime, b64 }; - } finally { - fs.closeSync(fd); - } -} - -/** - * Check if a path is a local (non-remote, non-data) reference. - */ -function isLocalPath(url: string): boolean { - return ( - !!url && - !url.startsWith('http://') && - !url.startsWith('https://') && - !url.startsWith('data:') && - !url.startsWith('//') - ); -} - -// --------------------------------------------------------------------------- -// Inline images in HTML -// --------------------------------------------------------------------------- -function inlineImages( - html: string, - baseDir: string, - maxSize: number, - dryRun: boolean, -): { html: string; stats: InlineStats } { - const stats: InlineStats = { - srcInlined: 0, - urlInlined: 0, - skippedTooLarge: [], - skippedNotFound: [], - }; - - // --- Inline src="" attributes --- - // Handle src, poster, data attributes - const srcAttrs = ['src', 'poster', 'data']; - for (const attr of srcAttrs) { - const regex = new RegExp(`${attr}="((?!https?:\\/\\/|data:|\\/\\/)[^"]+)"`, 'g'); - html = html.replace(regex, (match: string, localPath: string) => { - const resolved = resolveLocalFile(localPath, baseDir); - if (!resolved) { - if (!localPath.endsWith('.js') && !localPath.endsWith('.css')) { - stats.skippedNotFound.push(localPath); - } - return match; - } - - const result = readFileAtomic(resolved, maxSize); - if (!result) { - stats.skippedNotFound.push(localPath); - return match; - } - if ('tooLarge' in result) { - stats.skippedTooLarge.push({ path: localPath, size: result.size }); - return match; - } - - if (dryRun) { - stats.srcInlined++; - return match; - } - - stats.srcInlined++; - return `${attr}="data:${result.mime};base64,${result.b64}"`; - }); - } - - // --- Inline CSS url() with local paths (using robust parser) --- - const urlRefs = extractCssUrls(html); - const localUrlRefs = urlRefs.filter((ref) => isLocalPath(ref.url)); - - // Process from end to preserve indices - const sorted = [...localUrlRefs].sort((a, b) => b.start - a.start); - for (const ref of sorted) { - const resolved = resolveLocalFile(ref.url, baseDir); - if (!resolved) { - stats.skippedNotFound.push(ref.url); - continue; - } - - const result = readFileAtomic(resolved, maxSize); - if (!result) { - stats.skippedNotFound.push(ref.url); - continue; - } - if ('tooLarge' in result) { - stats.skippedTooLarge.push({ path: ref.url, size: result.size }); - continue; - } - - if (dryRun) { - stats.urlInlined++; - continue; - } - - html = - html.substring(0, ref.start) + - `url('data:${result.mime};base64,${result.b64}')` + - html.substring(ref.end); - stats.urlInlined++; - } - - // --- Inline SVG and xlink:href --- - const svgHrefRegex = /(href|xlink:href)="((?!https?:\/\/|data:|\/\/)[^"]+)"/g; - html = html.replace(svgHrefRegex, (match: string, attrName: string, localPath: string) => { - // Skip non-image hrefs (like ) - if (!localPath.match(/\.(svg|png|jpg|jpeg|gif|webp|avif|bmp|ico)$/i)) { - return match; - } - - const resolved = resolveLocalFile(localPath, baseDir); - if (!resolved) { - stats.skippedNotFound.push(localPath); - return match; - } - - const result = readFileAtomic(resolved, maxSize); - if (!result) { - stats.skippedNotFound.push(localPath); - return match; - } - if ('tooLarge' in result) { - stats.skippedTooLarge.push({ path: localPath, size: result.size }); - return match; - } - - if (dryRun) { - stats.srcInlined++; - return match; - } - - stats.srcInlined++; - return `${attrName}="data:${result.mime};base64,${result.b64}"`; - }); - - return { html, stats }; -} - -// --------------------------------------------------------------------------- -// Main -// --------------------------------------------------------------------------- -function main(): void { - const opts = parseArgs(); - validateOpts(opts); - - const allStats: AllStats = { - files: [], - totalSrcInlined: 0, - totalUrlInlined: 0, - totalSkippedNotFound: 0, - totalSkippedTooLarge: 0, - }; - - if (opts.dryRun) { - console.log('🔍 DRY RUN — no files will be modified\n'); - } - - for (const file of opts.files) { - // Open file once with r+ to eliminate TOCTOU race between read and write. - // A single fd is used for both operations, so the file cannot be swapped - // between the read and write phases. - let fd: number; - try { - fd = fs.openSync(file, opts.dryRun ? 'r' : 'r+'); - } catch { - console.warn(`⚠️ File not found, skipping: ${file}`); - continue; - } - - let processed: string = ''; - let stats: InlineStats = { srcInlined: 0, urlInlined: 0, skippedTooLarge: [], skippedNotFound: [] }; - try { - const html = fs.readFileSync(fd, 'utf-8'); - - const result = inlineImages(html, opts.baseDir, opts.maxSize, opts.dryRun); - processed = result.html; - stats = result.stats; - - if (!opts.dryRun) { - // Truncate and rewrite using the same fd — no second path-based open - fs.ftruncateSync(fd); - fs.writeSync(fd, processed, 0, 'utf-8'); - } - } finally { - fs.closeSync(fd); - } - - const totalInlined = stats.srcInlined + stats.urlInlined; - const label = opts.dryRun ? 'would inline' : 'inlined'; - console.log( - `${file}: ${label} ${totalInlined} resources ` + - `(${stats.srcInlined} src, ${stats.urlInlined} url()) ` + - `— ${processed.length.toLocaleString()} bytes`, - ); - - if (stats.skippedTooLarge.length > 0) { - for (const s of stats.skippedTooLarge) { - console.log( - ` ⚠️ Skipped (too large: ${(s.size / 1024).toFixed(1)} KB): ${s.path}`, - ); - } - } - - allStats.files.push({ - file, - srcInlined: stats.srcInlined, - urlInlined: stats.urlInlined, - skippedNotFound: stats.skippedNotFound.length, - skippedTooLarge: stats.skippedTooLarge.length, - sizeBytes: processed.length, - }); - allStats.totalSrcInlined += stats.srcInlined; - allStats.totalUrlInlined += stats.urlInlined; - allStats.totalSkippedNotFound += stats.skippedNotFound.length; - allStats.totalSkippedTooLarge += stats.skippedTooLarge.length; - } - - const totalInlined = allStats.totalSrcInlined + allStats.totalUrlInlined; - console.log(`\n✅ Total: ${totalInlined} resources inlined across ${allStats.files.length} file(s)`); - - if (allStats.totalSkippedTooLarge > 0) { - console.log(` ⚠️ ${allStats.totalSkippedTooLarge} skipped (exceeded ${(opts.maxSize / 1024 / 1024).toFixed(1)} MB limit)`); - } - - if (opts.json) { - console.log('\n--- JSON Stats ---'); - console.log(JSON.stringify(allStats, null, 2)); - } -} - -main(); diff --git a/.claude/skills/extract-static-html/scripts/snapshot.ts b/.claude/skills/extract-static-html/scripts/snapshot.ts deleted file mode 100644 index 88c9cd2..0000000 --- a/.claude/skills/extract-static-html/scripts/snapshot.ts +++ /dev/null @@ -1,1470 +0,0 @@ -#!/usr/bin/env npx tsx -/** - * snapshot.ts — Production-grade Puppeteer-based full-page HTML snapshot - * - * Captures the fully rendered DOM from a running web application and produces - * a self-contained HTML file with all CSS inlined and images converted to - * base64 data URIs. Works with any framework (React, Vue, Svelte, Angular, - * plain HTML, etc.) — no MockPage.jsx needed. - * - * Usage: - * npx tsx snapshot.ts --url http://localhost:5173 --output .stitch/home.html - * npx tsx snapshot.ts --url http://localhost:3000/pricing --output .stitch/pricing.html --html-class dark - * npx tsx snapshot.ts --url http://localhost:5173 --output .stitch/page.html --wait 5000 --viewport 1440x900 - * - * Flags: - * --url URL to capture (required) - * --output Output file path (required) - * --wait Extra wait time in ms after network idle (default: 1000) - * --viewport Viewport size as WIDTHxHEIGHT (default: 1280x800) - * --html-class Class(es) to add to element (e.g., "dark") - * --remove-fixed Remove fixed/sticky positioned elements (e.g., cookie banners) - * --full-height Capture full scrollable content by resizing viewport to scrollHeight - * --title Override the page title - * --timeout Global timeout in ms (default: 60000) - * --concurrency Max concurrent resource fetches (default: 6) - * --json Output machine-readable JSON stats to stdout - */ - -import puppeteer, { type Browser } from 'puppeteer'; -import path from 'node:path'; -import fs from 'node:fs'; - -// --------------------------------------------------------------------------- -// Types -// --------------------------------------------------------------------------- -interface Opts { - url: string | null; - output: string | null; - wait: number; - viewport: string; - htmlClass: string | null; - removeFixed: boolean; - fullHeight: boolean; - title: string | null; - authScript: string | null; - inlineCanvas: boolean; - timeout: number; - concurrency: number; - json: boolean; - inlineFonts: boolean; - removeSelectors: string | null; - click: string | null; -} - -interface Stats { - url: string | null; - output: string | null; - sizeBytes: number; - stylesheets: number; - images: number; - cssUrls: number; - svgImages: number; - videoPoster: number; - favicons: number; - scriptsRemoved: number; - warnings: string[]; - durationMs: number; - error?: string; -} - -// --------------------------------------------------------------------------- -// Argument parsing -// --------------------------------------------------------------------------- -function parseArgs(): Opts { - const args = process.argv.slice(2); - const opts: Opts = { - url: null, - output: null, - wait: 1000, - viewport: '1280x800', - htmlClass: null, - removeFixed: false, - fullHeight: false, - title: null, - authScript: null, - inlineCanvas: false, - timeout: 60000, - concurrency: 6, - json: false, - inlineFonts: false, - removeSelectors: null, - click: null, - }; - - for (let i = 0; i < args.length; i++) { - switch (args[i]) { - case '--url': - opts.url = args[++i]; - break; - case '--output': - opts.output = args[++i]; - break; - case '--wait': - opts.wait = parseInt(args[++i], 10); - break; - case '--viewport': - opts.viewport = args[++i]; - break; - case '--html-class': - opts.htmlClass = args[++i]; - break; - case '--remove-fixed': - opts.removeFixed = true; - break; - case '--full-height': - opts.fullHeight = true; - break; - case '--title': - opts.title = args[++i]; - break; - case '--auth-script': - opts.authScript = args[++i]; - break; - case '--inline-canvas': - opts.inlineCanvas = true; - break; - case '--timeout': - opts.timeout = parseInt(args[++i], 10); - break; - case '--concurrency': - opts.concurrency = parseInt(args[++i], 10); - break; - case '--json': - opts.json = true; - break; - case '--inline-fonts': - opts.inlineFonts = true; - break; - case '--remove-selectors': - opts.removeSelectors = args[++i]; - break; - case '--click': - opts.click = args[++i]; - break; - case '--help': - console.log(` -Usage: npx tsx snapshot.ts --url --output [options] - -Options: - --url URL to capture (required) - --output Output file path (required) - --wait Extra wait time in ms after network idle (default: 1000) - --viewport Viewport size as WIDTHxHEIGHT (default: 1280x800) - --html-class Class(es) to add to element (e.g., "dark") - --remove-fixed Remove fixed/sticky positioned elements (cookie banners, etc.) - --full-height Resize viewport to capture full scrollable content - --title Override the page title - --auth-script Path to JS/TS script exporting an async function to authenticate before capture - --inline-canvas Convert elements (charts, graphs) to base64 images - --timeout Global timeout in ms (default: 60000) - --concurrency Max concurrent resource fetches (default: 6) - --json Output machine-readable JSON stats -`); - process.exit(0); - default: - console.error(`Unknown argument: ${args[i]}`); - process.exit(1); - } - } - - return opts; -} - -// --------------------------------------------------------------------------- -// Input validation -// --------------------------------------------------------------------------- -function validateOpts(opts: Opts): void { - const errors: string[] = []; - - if (!opts.url) errors.push('--url is required'); - if (!opts.output) errors.push('--output is required'); - - if (opts.url) { - try { - new URL(opts.url); - } catch { - errors.push( - `Invalid URL: "${opts.url}". Must be a valid URL (e.g., http://localhost:5173)`, - ); - } - } - - if (opts.viewport) { - const vpMatch = opts.viewport.match(/^(\d+)x(\d+)$/); - if (!vpMatch) { - errors.push( - `Invalid viewport: "${opts.viewport}". Must be WIDTHxHEIGHT (e.g., 1280x800)`, - ); - } else { - const w = Number(vpMatch[1]); - const h = Number(vpMatch[2]); - if (w < 1 || h < 1) { - errors.push('Viewport dimensions must be positive integers'); - } - if (w > 7680 || h > 4320) { - errors.push('Viewport too large: max 7680x4320'); - } - } - } - - if (isNaN(opts.wait) || opts.wait < 0) { - errors.push('--wait must be a non-negative integer'); - } - - if (isNaN(opts.timeout) || opts.timeout < 1000) { - errors.push('--timeout must be at least 1000ms'); - } - - if (isNaN(opts.concurrency) || opts.concurrency < 1 || opts.concurrency > 20) { - errors.push('--concurrency must be between 1 and 20'); - } - - if (opts.output) { - const outputDir = path.dirname(path.resolve(opts.output)); - try { - fs.mkdirSync(outputDir, { recursive: true }); - fs.accessSync(outputDir, fs.constants.W_OK); - } catch (e: unknown) { - errors.push(`Cannot write to output directory: ${(e as Error).message}`); - } - } - - if (errors.length > 0) { - console.error('❌ Validation errors:'); - errors.forEach((e) => console.error(` • ${e}`)); - process.exit(1); - } -} - -// --------------------------------------------------------------------------- -// Main snapshot logic -// --------------------------------------------------------------------------- -async function snapshot(opts: Opts): Promise { - const [, widthStr, heightStr] = opts.viewport.match(/^(\d+)x(\d+)$/)!; - const width = Number(widthStr); - const height = Number(heightStr); - - let browser: Browser | undefined; - let globalTimer: ReturnType | undefined; - - // Stats tracking - const stats: Stats = { - url: opts.url, - output: null, - sizeBytes: 0, - stylesheets: 0, - images: 0, - cssUrls: 0, - svgImages: 0, - videoPoster: 0, - favicons: 0, - scriptsRemoved: 0, - warnings: [], - durationMs: 0, - }; - const startTime = Date.now(); - - try { - // Global timeout safety net — prevents zombie browser processes - globalTimer = setTimeout(() => { - const msg = `Global timeout of ${opts.timeout}ms exceeded — aborting`; - console.error(`⏰ ${msg}`); - stats.warnings.push(msg); - if (browser) browser.close().catch(() => {}); - if (opts.json) { - stats.durationMs = Date.now() - startTime; - stats.error = msg; - console.log(JSON.stringify(stats, null, 2)); - } - process.exit(2); - }, opts.timeout); - - // ----- Launch browser ----- - console.log('🚀 Launching browser...'); - browser = await puppeteer.launch({ - headless: true, - args: [ - '--no-sandbox', - '--disable-setuid-sandbox', - '--disable-dev-shm-usage', - `--window-size=${width},${height}`, - ], - }); - - const page = await browser.newPage(); - await page.setViewport({ width, height }); - - // Forward browser console logs to Node.js - page.on('console', (msg) => { - const type = msg.type().toString(); - if (type === 'warning' || type === 'error') { - console.log(` [Browser ${type.toUpperCase()}] ${msg.text()}`); - } - }); - - // ----- Navigate and wait for network idle ----- - console.log(`📄 Navigating to ${opts.url}...`); - try { - await page.goto(opts.url!, { - waitUntil: 'networkidle0', - timeout: 10000, - }); - } catch { - const msg = 'networkidle0 timed out, falling back to networkidle2'; - console.warn(`⚠️ ${msg}...`); - stats.warnings.push(msg); - try { - await page.goto(opts.url!, { - waitUntil: 'networkidle2', - timeout: 10000, - }); - } catch { - const msg2 = 'networkidle2 timed out, falling back to domcontentloaded'; - console.warn(`⚠️ ${msg2}...`); - stats.warnings.push(msg2); - await page.goto(opts.url!, { - waitUntil: 'domcontentloaded', - timeout: 15000, - }); - } - } - - // Extra wait for JS-rendered content (animations, lazy loading, etc.) - if (opts.wait > 0) { - console.log(`⏳ Waiting ${opts.wait}ms for rendering to settle...`); - await new Promise((r) => setTimeout(r, opts.wait)); - } - - // Execute authentication script if provided - if (opts.authScript) { - console.log(`🔐 Running authentication script from ${opts.authScript}...`); - try { - const path = await import('path'); - const authPath = path.resolve(process.cwd(), opts.authScript); - const authModule = await import(authPath); - const authFn = authModule.default || authModule; - if (typeof authFn === 'function') { - await authFn(page); - console.log(' ✅ Auth script executed, re-navigating to target URL...'); - await page.goto(opts.url!, { - waitUntil: 'networkidle2', - timeout: Math.min(30000, opts.timeout), - }); - if (opts.wait > 0) { - await new Promise((r) => setTimeout(r, opts.wait)); - } - } else { - console.warn(`⚠️ --auth-script (${opts.authScript}) did not export a function`); - } - } catch (err: any) { - console.warn(`⚠️ Failed to execute --auth-script: ${err.message}`); - stats.warnings.push(`auth-script error: ${err.message}`); - } - } - - // Perform click interaction if specified - if (opts.click) { - console.log(`🖱️ Clicking element "${opts.click}"...`); - try { - let element = await page.$(opts.click); - if (!element) { - // Search in child frames recursively! - for (const frame of page.frames()) { - const childElement = await frame.$(opts.click); - if (childElement) { - element = childElement; - console.log(` Found element inside child frame: ${frame.url()}`); - break; - } - } - } - - if (element) { - await element.click(); - // wait an extra 2 seconds for animation or modal loading to settle - console.log(` Click succeeded! Waiting 2000ms for click action to settle...`); - await new Promise((r) => setTimeout(r, 2000)); - } else { - throw new Error(`Selector "${opts.click}" not found in main document or child frames.`); - } - } catch (clickErr: any) { - console.error(`⚠️ Click action failed:`, clickErr); - stats.warnings.push(`Click action failed: ${clickErr.message || clickErr}`); - } - } - - // ----- Pre-processing options ----- - - // Add class to (e.g., dark mode) - if (opts.htmlClass) { - console.log(`🎨 Adding class "${opts.htmlClass}" to ...`); - await page.evaluate((cls: string) => { - document.documentElement.classList.add(...cls.split(/\s+/)); - if (cls.includes('dark')) { - document.documentElement.setAttribute('data-theme', 'dark'); - } else if (cls.includes('light')) { - document.documentElement.setAttribute('data-theme', 'light'); - } - }, opts.htmlClass); - await new Promise((r) => setTimeout(r, 500)); - } - - // Remove fixed/sticky elements - if (opts.removeFixed) { - console.log('🧹 Removing fixed/sticky positioned elements...'); - await page.evaluate(() => { - const all = document.querySelectorAll('*'); - for (const el of all) { - const style = getComputedStyle(el); - if (style.position === 'fixed' || style.position === 'sticky') { - const rect = el.getBoundingClientRect(); - if (rect.top > 100 || rect.height < 50) { - el.remove(); - } - } - } - }); - } - - // Remove custom selectors - if (opts.removeSelectors) { - console.log(`🧹 Removing custom selectors: "${opts.removeSelectors}"...`); - await page.evaluate((selectors: string) => { - const items = selectors.split(',').map((s) => s.trim()).filter(Boolean); - for (const selector of items) { - try { - document.querySelectorAll(selector).forEach((el) => el.remove()); - } catch (e) { - console.warn(`Invalid selector "${selector}":`, e); - } - } - }, opts.removeSelectors); - } - - - - // Override title - if (opts.title) { - await page.evaluate((t: string) => { - document.title = t; - }, opts.title); - } - - // ----- Inject shared browser-side helpers (deduplication) ----- - // Mock __name to prevent esbuild generated code from failing in browser - await page.evaluate(() => { - (window as any).__name = (fn: any, name: string) => fn; - }); - - await page.evaluate((concurrency: number) => { - (window as any).__snapshot = { - CONCURRENCY: concurrency, - - toDataUri: async (url: string): Promise => { - try { - const resp = await fetch(url, { - mode: 'cors', - credentials: 'same-origin', - }); - if (!resp.ok) return null; - const blob = await resp.blob(); - return new Promise((resolve) => { - const reader = new FileReader(); - reader.onloadend = () => resolve(reader.result as string); - reader.onerror = () => resolve(null); - reader.readAsDataURL(blob); - }); - } catch { - return null; - } - }, - - processInBatches: async ( - items: T[], - batchSize: number, - fn: (item: T) => Promise, - ): Promise<(R | null)[]> => { - const results: (R | null)[] = []; - for (let i = 0; i < items.length; i += batchSize) { - const batch = items.slice(i, i + batchSize); - const batchResults = await Promise.allSettled(batch.map(fn)); - results.push( - ...batchResults.map((r) => - r.status === 'fulfilled' ? r.value : null, - ), - ); - } - return results; - }, - - /** - * Robust CSS url() parser — character-by-character parsing instead of regex. - * Handles: quoted/unquoted values, escaped characters, whitespace, - * data URIs, and malformed url() tokens. - * - * Returns: Array of { url, fullMatch, start, end } - */ - extractCssUrls: (cssText: string) => { - const results: Array<{ url: string; fullMatch: string; start: number; end: number }> = []; - let i = 0; - const len = cssText.length; - - while (i < len) { - // Look for 'url(' — case insensitive - if ( - i + 3 < len && - cssText[i].toLowerCase() === 'u' && - cssText[i + 1].toLowerCase() === 'r' && - cssText[i + 2].toLowerCase() === 'l' && - cssText[i + 3] === '(' - ) { - const urlStart = i; - i += 4; // skip 'url(' - - // Skip whitespace - while ( - i < len && - (cssText[i] === ' ' || - cssText[i] === '\t' || - cssText[i] === '\n' || - cssText[i] === '\r') - ) { - i++; - } - - // Check for quote - let quote: string | null = null; - if (i < len && (cssText[i] === '"' || cssText[i] === "'")) { - quote = cssText[i]; - i++; - } - - // Read the URL value - let url = ''; - if (quote) { - // Quoted: read until matching unescaped quote - while (i < len && cssText[i] !== quote) { - if (cssText[i] === '\\' && i + 1 < len) { - i++; // skip backslash - url += cssText[i]; // include next char literally - } else { - url += cssText[i]; - } - i++; - } - if (i < len) i++; // skip closing quote - } else { - // Unquoted: stop at ) or whitespace (per CSS spec) - while ( - i < len && - cssText[i] !== ')' && - cssText[i] !== ' ' && - cssText[i] !== '\t' && - cssText[i] !== '\n' && - cssText[i] !== '\r' - ) { - url += cssText[i]; - i++; - } - } - - // Skip trailing whitespace before ')' - while ( - i < len && - (cssText[i] === ' ' || - cssText[i] === '\t' || - cssText[i] === '\n' || - cssText[i] === '\r') - ) { - i++; - } - - if (i < len && cssText[i] === ')') { - const fullMatch = cssText.substring(urlStart, i + 1); - results.push({ - url: url.trim(), - fullMatch, - start: urlStart, - end: i + 1, - }); - i++; - } else { - // Malformed url() — skip past 'url(' and try again - i = urlStart + 1; - } - } else { - i++; - } - } - - return results; - }, - - /** - * Replace CSS url() references using pre-computed positions. - * Replaces from end-to-start to preserve earlier indices. - */ - replaceCssUrls: ( - cssText: string, - replacements: Array<{ start: number; end: number; dataUri: string }>, - ): string => { - const sorted = [...replacements].sort((a, b) => b.start - a.start); - for (const r of sorted) { - cssText = - cssText.substring(0, r.start) + - "url('" + - r.dataUri + - "')" + - cssText.substring(r.end); - } - return cssText; - }, - }; - }, opts.concurrency); - - // ----------------------------------------------------------------------- - // -2. Remove dev-overlay / screenshot-ignore elements (e.g. VeloUI) - // ----------------------------------------------------------------------- - const removedCount = await page.evaluate(() => { - let count = 0; - // Remove any element explicitly marked as screenshot-ignore - document.querySelectorAll('[data-screenshot-ignore="true"]').forEach(el => { - el.parentNode?.removeChild(el); count++; - }); - // Remove VeloUI overlay elements (pause overlay, probe, root container, etc.) - const veloSelectors = [ - '[data-veloui-pause-overlay]', - '[data-veloui-probe]', - '[data-veloui-extractor]', - '[data-veloui-scan]', - '.veloui-root', - '.veloui-liquid-glass', - ]; - for (const sel of veloSelectors) { - document.querySelectorAll(sel).forEach(el => { - el.parentNode?.removeChild(el); count++; - }); - } - return count; - }); - if (removedCount > 0) { - console.log(`🧹 Removed ${removedCount} dev-overlay / screenshot-ignore element(s) from the DOM.`); - } - - // ----------------------------------------------------------------------- - // -1. Inline local iframes (e.g., companion-app test iframe) - // ----------------------------------------------------------------------- - const iframesCount = await page.evaluate(() => document.querySelectorAll('iframe').length); - if (iframesCount > 0) { - console.log(`🔍 Found ${iframesCount} iframe(s) in the main page. Extracting content natively...`); - - // First, recursively inline all same-origin and srcDoc iframes browser-side - console.log('🔍 Inlining same-origin and srcDoc iframes recursively...'); - await page.evaluate(() => { - const inlineSameOriginIframes = (root: Document | HTMLElement) => { - const iframes = Array.from(root.querySelectorAll('iframe')); - for (const iframe of iframes) { - if ( - iframe.getAttribute('data-screenshot-ignore') === 'true' || - iframe.getAttribute('data-veloui-scan') === 'true' || - iframe.getAttribute('data-veloui-probe') === 'true' || - iframe.hasAttribute('data-veloui-extractor') - ) { - // Remove the hidden crawler/scan iframes completely from DOM - try { iframe.parentNode && iframe.parentNode.removeChild(iframe); } catch { } - continue; - } - try { - const doc = iframe.contentDocument || iframe.contentWindow?.document; - if (doc && doc.body) { - // Recursively inline same-origin iframes inside this child frame first - inlineSameOriginIframes(doc); - - const bodyHtml = doc.body.innerHTML; - - const styles: string[] = []; - doc.querySelectorAll('style').forEach(s => styles.push(s.outerHTML)); - doc.querySelectorAll('link[rel="stylesheet"]').forEach(l => styles.push((l as HTMLLinkElement).outerHTML)); - - styles.forEach(styleHtml => { - const temp = document.createElement('div'); - temp.innerHTML = styleHtml; - document.head.appendChild(temp.firstChild!); - }); - - const wrapper = document.createElement('div'); - wrapper.className = 'ac-iframe-inlined-wrapper'; - - // Apply child body's classes and attributes to same-origin wrapper - for (const attr of Array.from(doc.body.attributes)) { - if (attr.name === 'class') { - wrapper.classList.add(...attr.value.split(/\s+/).filter(Boolean)); - } else if (attr.name !== 'style') { - wrapper.setAttribute(attr.name, attr.value); - } - } - - wrapper.style.position = 'absolute'; - wrapper.style.top = '0'; - wrapper.style.left = '0'; - wrapper.style.width = '100%'; - wrapper.style.height = '100%'; - wrapper.style.overflow = 'hidden'; - wrapper.innerHTML = bodyHtml; - - iframe.parentNode!.replaceChild(wrapper, iframe); - } - } catch (e) { - // Ignore cross-origin iframes; the Puppeteer frame loop will process them - } - } - }; - inlineSameOriginIframes(document); - }); - - const childFrames = page.frames() - .filter(f => f !== page.mainFrame()) - .map(f => { - let depth = 0; - let p = f.parentFrame(); - while (p) { - depth++; - p = p.parentFrame(); - } - return { frame: f, depth }; - }) - .sort((a, b) => b.depth - a.depth); - - for (const { frame } of childFrames) { - try { - const frameUrl = frame.url(); - const cleanUrl = frameUrl.split('?')[0].split('#')[0]; - console.log(`📦 Extracting frame content from: ${cleanUrl} (depth: ${frame.parentFrame() ? 'nested' : 'root'})`); - - // Inject __name mock to prevent esbuild helper ReferenceError in child frame - await frame.evaluate(() => { - (window as any).__name = (fn: any) => fn; - }); - - // Resolve all relative assets inside the frame to absolute URLs relative to the frame's URL - await frame.evaluate((base) => { - const resolveAttr = (el: Element, attr: string) => { - const val = el.getAttribute(attr); - if (val && !val.startsWith('data:') && !val.startsWith('http:') && !val.startsWith('https:') && !val.startsWith('//')) { - try { - const abs = new URL(val, base).href; - el.setAttribute(attr, abs); - } catch (e) { } - } - }; - document.querySelectorAll('img[src]').forEach(img => resolveAttr(img, 'src')); - document.querySelectorAll('img[srcset]').forEach(img => resolveAttr(img, 'srcset')); - document.querySelectorAll('source[srcset]').forEach(src => resolveAttr(src, 'srcset')); - document.querySelectorAll('link[rel="stylesheet"]').forEach(link => resolveAttr(link, 'href')); - - // Resolve relative url() references in inline