@sbuilder/cli 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,9 +7,10 @@ editor's AI assistant on your own machine, and build apps for the platform.
7
7
 
8
8
  ```
9
9
  Start
10
- sb init ask what to start: a new website built by AI, a
11
- repo for one of your sites, or an app (same as
12
- npm create sbuilder-app)
10
+ sb init ask what to start: a new website built by AI, one
11
+ from a template, a repo for one of your sites, an
12
+ app or a Next.js storefront (same as npm create
13
+ sbuilder-app)
13
14
 
14
15
  Account
15
16
  sb login sign in through the browser; stores a credential
@@ -24,6 +25,9 @@ Sites
24
25
  sb site new "<description>" [--dir <path>] [--github] [--editor]
25
26
  make a site from one sentence, in a repo an AI
26
27
  agent builds in (--editor: in the editor instead)
28
+ sb site new --template <slug|id> ["<description>"] [--dir <path>] [--github]
29
+ a new site copied from a template, in the same repo
30
+ sb site templates [--json] the templates a new site can start from
27
31
  sb site init [dir] [--site <id>] [--github]
28
32
  a repo holding one site's pages, synced with
29
33
  GitHub both ways
@@ -36,6 +40,8 @@ Sites
36
40
  sb site dev [--theme] watch design/ and code/, push each save as a DRAFT
37
41
  sb site publish <file>… | --all
38
42
  make pages LIVE — named files, or every page
43
+ sb site preview <file> [--open] [--html]
44
+ a link to the page's DRAFT, rendered — nothing published
39
45
  sb site blocks the blocks your installed apps offer, with the line
40
46
  to paste into a page file
41
47
  sb site next serve the pages from a Next.js app, rendered by the
@@ -195,7 +201,7 @@ sb app init my-app --with-block
195
201
 
196
202
  Writes a working app into `./my-app` and prints what to do next. It makes **no
197
203
  network calls at all** — it is a scaffolder; `sb app create` (below) registers
198
- it. A bare `sb init` on a terminal asks what to start instead; its choice 3 runs
204
+ it. A bare `sb init` on a terminal asks what to start instead; its choice 4 runs
199
205
  this flow.
200
206
 
201
207
  ### What it writes
@@ -707,6 +713,8 @@ file missing locally without `--delete`, is printed and is **not** a failure.
707
713
  ```
708
714
  sb init # a menu: "a new website, built by AI" is choice 1
709
715
  sb site new "a shop selling handmade candles" # the same, from the command line
716
+ sb site new --template tea-shop # a new site copied from a template, in a repo like the one below
717
+ sb site templates # the templates to start from (--json for the list as JSON)
710
718
  sb site init my-shop --github # a repo for one of your sites, on a private GitHub repo
711
719
  sb site pull # take what was edited in the editor
712
720
  sb site push # save edited page files as DRAFTS
@@ -715,6 +723,7 @@ sb site push --theme # also send design/theme.json (a theme save is
715
723
  sb site status # what differs from the last sync; stale translations
716
724
  sb site dev # watch design/ and code/ and push each save as a DRAFT
717
725
  sb site publish --all # make pages live (or name files)
726
+ sb site preview design/pages/index.page.tsx # a link to that page's DRAFT, rendered (--open opens it, --html prints it); nothing published
718
727
  sb site next # serve the pages from a Next.js app (npm run dev)
719
728
  sb site next --link # mint the host secret into .env: a deployed host signs its requests
720
729
  sb site deploy --vercel # one command to production on Vercel, with your own vercel CLI (--dry-run: the plan; --rotate replaces a link made elsewhere)
@@ -731,7 +740,18 @@ description), writes the repo below into `./<name>` (`--dir` picks another folde
731
740
  offers to start it in that folder with your description. Signed out, it runs the
732
741
  `sb login` flow first. It is exactly what choice 1 of `sb init` does.
733
742
 
734
- **The Next.js storefront starter** is choice 4 of `sb init` (the menu `npm create sbuilder-app` shows). It picks one of your sites, writes its repo like `sb site init`, runs `sb site next`, adds `@sbuilder/sdk` and one hand-written route, `app/api/featured/route.ts` (JSON), which lists the store's products through `@sbuilder/sdk/storefront` (no API key, so it also works on a deployed host). The page types (`design/sbuilder-env.d.ts`) come with the repo. Then `npm install && npm run dev`, and `sb site deploy --vercel` when you want it online.
743
+ **`sb site new --template <slug|id>`** starts from a design instead of a sentence. It copies
744
+ the template into a new site in your account through the platform's own copy (pages, theme,
745
+ Code Dock files and code components come along), waits for the copy to finish, then writes
746
+ the same repo as `sb site init` around it. A description after the flag
747
+ (`sb site new --template tea-shop "a tea house in Hanoi"`) names the site and becomes the brief
748
+ Claude Code is offered, to adapt the design; without one the site takes the template's name.
749
+ **`sb site templates`** lists what there is to start from — slug, name, categories, the live
750
+ template and its preview image — and needs no sign-in. Choice 2 of `sb init` is the same flow
751
+ with a numbered list. The copy is made in your account's name, so it needs `sb login`, not an
752
+ API key.
753
+
754
+ **The Next.js storefront starter** is choice 5 of `sb init` (the menu `npm create sbuilder-app` shows). It picks one of your sites, writes its repo like `sb site init`, runs `sb site next`, adds `@sbuilder/sdk` and one hand-written route, `app/api/featured/route.ts` (JSON), which lists the store's products through `@sbuilder/sdk/storefront` (no API key, so it also works on a deployed host). The page types (`design/sbuilder-env.d.ts`) come with the repo. Then `npm install && npm run dev`, and `sb site deploy --vercel` when you want it online.
735
755
 
736
756
  **`sb site new --editor "<description>"`** builds in the editor instead: it opens the
737
757
  editor, which creates the site and starts building it. If `sb agent` is already
@@ -748,6 +768,7 @@ platform's key.
748
768
  | Flag | Effect |
749
769
  | --- | --- |
750
770
  | `--editor` | Build in the editor (the assistant, or your `sb agent`) instead of in a repo |
771
+ | `--template <slug\|id>` | Copy that template into the new site instead of starting empty (`sb site templates` lists them) |
751
772
 
752
773
  **Building with AI.** Choice 1 of `sb init` (and `sb site new`) takes your description, creates
753
774
  the site, writes the repo below and — when Claude Code is installed — starts it in
@@ -761,6 +782,28 @@ the agent how to work: native elements first, look at every section on desktop a
761
782
  mobile, ask for real facts, pull the result into the repo, **never publish unasked**.
762
783
  The agent edits the site's drafts; you review what it did as a git diff.
763
784
 
785
+ **`sb site preview <file>`** prints a link to that page's current DRAFT on the storefront,
786
+ rendered exactly as a visitor would see it once published — the editor's own Preview, from the
787
+ terminal. Nothing is published. The link works for an hour; `--open` opens it in the browser,
788
+ `--html` prints the rendered HTML instead. It shows what was last PUSHED (a file with edits not
789
+ pushed yet says so). It is minted with your `sb login` (or `SB_TOKEN`) when there is one, sent
790
+ only to that platform; otherwise with the repo's API key in `.env` (it needs `pages.read`), sent to
791
+ the `.env`'s own `SB_API` — the pair every site command uses.
792
+
793
+ **Structure is checked before anything is sent.** Every element must sit where the schema allows
794
+ it — a parent's allowed children (an `<Accordion>` holds only `<AccordionContent>`) and the
795
+ section types that live only directly in `<Page>`. `sb site push` and `sb site dev` check each
796
+ file they are about to send: one that breaks this is not sent, with `file:line:col` and what to
797
+ write instead (a removed element type: delete it), while the other files go; push then exits 1.
798
+ The rules are this CLI's copy of the schema — the message says which version, and if the editor
799
+ allows what it refuses, upgrade sb. `sb doctor` reports it for every file. `design/sbuilder-env.d.ts`
800
+ carries each element's purpose, its allowed children and an example, from the schema.
801
+
802
+ **The theme.** `sb site pull` writes `design/theme.json` — the site's saved theme, or the
803
+ default it renders with while it has none. A theme save is live at once, so `sb site push`
804
+ sends it only with `--theme`, and `sb site push --theme --dry-run` prints each token that would
805
+ change (`colors.primary: value #171717 → #e11d48`) and sends nothing.
806
+
764
807
  **What `sb site init` writes.** It signs you in if needed, lets you pick a site (or
765
808
  takes `--site <id>`), and writes:
766
809
 
@@ -801,6 +844,9 @@ repo, `sb site`, `sb site code` and `sb site mcp` read `.env`; a variable alread
801
844
  shell wins. `--github` then runs `git init`, the first commit, `gh repo create
802
845
  --private --push` and `gh secret set SB_TOKEN` (the key goes in on stdin, never on a
803
846
  command line) — the workflow is live with nothing left to paste.
847
+ Without `--github`, init still runs `git init` and makes the first commit when the folder is not
848
+ inside a git repo already and git is installed (it says which), so every later pull or agent
849
+ edit shows as a git diff.
804
850
 
805
851
  **Page files.** Each page is a `.page.tsx` file that reads like React — one tag per element,
806
852
  its settings as props:
@@ -970,7 +1016,8 @@ changing `name`, `slug`, `type`, `isHomepage`, `settings` or `defaultTemplate` i
970
1016
  file renames or re-types it. `path` is derived and only informational. When the platform
971
1017
  settles on something other than what you asked (a slug is made unique) push says so, and
972
1018
  after every save the file is rewritten to what the platform stored — minted ids and the
973
- facts it settled on — so the next `sb site pull` changes nothing. A file with no
1019
+ facts it settled on, with shared sections and overlays in place as a pull writes them — so
1020
+ the next `sb site pull` changes nothing. A file with no
974
1021
  `export const page` and no manifest entry is still only reported.
975
1022
 
976
1023
  Facts are merged three ways like the document: what was last synced is the base. A fact only
@@ -987,7 +1034,8 @@ With an API key (`/api/v1`) the platform also fences the write itself: each fact
987
1034
  pages: it lists them first, asks on a terminal, and off a terminal also needs `--yes`
988
1035
  (nothing is deleted otherwise). `--prune` refuses when `design/pages/` is absent, since
989
1036
  every page would then look deleted. A page deleted on the platform keeps its file, named
990
- by pull.
1037
+ by pull. A tracked file you deleted stays deleted on `sb site pull` (named, exit 0) until you
1038
+ prune the page; `sb site pull --force` writes it back.
991
1039
 
992
1040
  ### The rest of the site as files
993
1041
 
package/README.vi.md CHANGED
@@ -8,8 +8,8 @@ trợ lý AI của editor trên máy bạn, và xây app cho nền tảng.
8
8
  ```
9
9
  Bắt đầu
10
10
  sb init hỏi bạn muốn bắt đầu gì: website mới do AI dựng,
11
- repo cho một site của bạn, hay app (giống npm
12
- create sbuilder-app)
11
+ website từ một mẫu, repo cho một site của bạn, app
12
+ hay Next.js storefront (giống npm create sbuilder-app)
13
13
 
14
14
  Tài khoản
15
15
  sb login đăng nhập qua trình duyệt; lưu một credential tự
@@ -24,6 +24,9 @@ Site
24
24
  sb site new "<mô tả>" [--dir <path>] [--github] [--editor]
25
25
  tạo site từ một câu, trong một repo để AI agent dựng
26
26
  (--editor: dựng ngay trong editor)
27
+ sb site new --template <slug|id> ["<mô tả>"] [--dir <path>] [--github]
28
+ site mới chép từ một mẫu, trong cùng kiểu repo đó
29
+ sb site templates [--json] các mẫu mà một site mới có thể bắt đầu từ đó
27
30
  sb site init [dir] [--site <id>] [--github]
28
31
  repo chứa các trang của một site, đồng bộ hai
29
32
  chiều với GitHub
@@ -37,6 +40,8 @@ Site
37
40
  sb site dev [--theme] theo dõi design/ và code/, mỗi lần lưu là một BẢN NHÁP
38
41
  sb site publish <file>… | --all
39
42
  đưa trang lên LIVE — file chỉ định, hoặc mọi trang
43
+ sb site preview <file> [--open] [--html]
44
+ liên kết tới BẢN NHÁP của trang, đã render — không xuất bản
40
45
  sb site blocks các block app đã cài cho phép đặt, kèm dòng để dán
41
46
  vào file trang
42
47
  sb site next phục vụ các trang từ một app Next.js, render bằng
@@ -195,7 +200,7 @@ sb app init my-app --with-block
195
200
 
196
201
  Ghi một app chạy được vào `./my-app` và in ra việc cần làm tiếp theo. Nó **không
197
202
  gọi mạng một lần nào** — đây là công cụ tạo khung; `sb app create` (bên dưới) mới là
198
- bước đăng ký. Gõ `sb init` trần trong terminal sẽ hỏi bạn muốn bắt đầu gì; lựa chọn 3
203
+ bước đăng ký. Gõ `sb init` trần trong terminal sẽ hỏi bạn muốn bắt đầu gì; lựa chọn 4
199
204
  chạy đúng luồng này.
200
205
 
201
206
  ### Nó ghi ra những gì
@@ -709,6 +714,8 @@ theo dõi bị mất ở máy khi không có `--delete`, được in ra và **kh
709
714
  ```
710
715
  sb init # một menu: lựa chọn 1 là "website mới do AI dựng"
711
716
  sb site new "cửa hàng nến thơm thủ công" # y hệt, từ dòng lệnh
717
+ sb site new --template tea-shop # site mới chép từ một mẫu, trong một repo như bên dưới
718
+ sb site templates # các mẫu có thể bắt đầu từ đó (--json: danh sách dạng JSON)
712
719
  sb site init my-shop --github # repo cho một site của bạn, trên repo GitHub riêng tư
713
720
  sb site pull # lấy những gì đã sửa trong editor
714
721
  sb site push # lưu file trang đã sửa thành BẢN NHÁP
@@ -717,6 +724,7 @@ sb site push --theme # gửi cả design/theme.json (lưu theme có
717
724
  sb site status # điều khác với lần đồng bộ gần nhất; bản dịch lỗi thời
718
725
  sb site dev # theo dõi design/ và code/, mỗi lần lưu là một BẢN NHÁP
719
726
  sb site publish --all # xuất bản trang (hoặc chỉ định file)
727
+ sb site preview design/pages/index.page.tsx # liên kết tới BẢN NHÁP của trang, đã render (--open mở nó, --html in HTML); không xuất bản gì
720
728
  sb site next # phục vụ các trang từ một app Next.js (npm run dev)
721
729
  sb site next --link # tạo host secret vào .env: host đã deploy ký các request của nó
722
730
  sb site deploy --vercel # một lệnh lên production trên Vercel, bằng vercel CLI của bạn (--dry-run: chỉ in kế hoạch; --rotate thay link do nơi khác tạo)
@@ -732,7 +740,17 @@ sb site mcp # MCP server của Store Builder, với k
732
740
  — nếu máy có Claude Code — đề nghị mở nó trong thư mục đó với mô tả của bạn. Nếu chưa đăng
733
741
  nhập, nó chạy luồng `sb login` trước. Đây đúng là việc lựa chọn 1 của `sb init` làm.
734
742
 
735
- **Starter Next.js storefront** là lựa chọn 4 của `sb init` (menu mà `npm create sbuilder-app` hiện ra). Nó chọn một site của bạn, tạo repo như `sb site init`, chạy `sb site next`, thêm `@sbuilder/sdk` và một route viết tay, `app/api/featured/route.ts` (JSON), liệt kê sản phẩm của cửa hàng qua `@sbuilder/sdk/storefront` (không cần API key, nên chạy được cả trên host đã deploy). Kiểu cho trang (`design/sbuilder-env.d.ts`) đi kèm repo. Sau đó `npm install && npm run dev`, và `sb site deploy --vercel` khi muốn đưa lên mạng.
743
+ **`sb site new --template <slug|id>`** bắt đầu từ một thiết kế thay vì một câu mô tả. Lệnh chép
744
+ mẫu vào một site mới trong tài khoản của bạn bằng chính tính năng sao chép của nền tảng (trang,
745
+ theme, file Code Dock và code component đều đi kèm), chờ việc sao chép xong, rồi viết đúng repo
746
+ như `sb site init` quanh site đó. Một mô tả sau flag
747
+ (`sb site new --template tea-shop "quán trà ở Hà Nội"`) đặt tên site và trở thành yêu cầu đưa cho
748
+ Claude Code để chỉnh lại thiết kế; không có mô tả thì site lấy tên của mẫu.
749
+ **`sb site templates`** liệt kê các mẫu — slug, tên, danh mục, site thật của mẫu và ảnh xem trước —
750
+ và không cần đăng nhập. Lựa chọn 2 của `sb init` là cùng luồng này với một danh sách đánh số.
751
+ Bản sao được tạo dưới tên tài khoản của bạn, nên cần `sb login`, không dùng được API key.
752
+
753
+ **Starter Next.js storefront** là lựa chọn 5 của `sb init` (menu mà `npm create sbuilder-app` hiện ra). Nó chọn một site của bạn, tạo repo như `sb site init`, chạy `sb site next`, thêm `@sbuilder/sdk` và một route viết tay, `app/api/featured/route.ts` (JSON), liệt kê sản phẩm của cửa hàng qua `@sbuilder/sdk/storefront` (không cần API key, nên chạy được cả trên host đã deploy). Kiểu cho trang (`design/sbuilder-env.d.ts`) đi kèm repo. Sau đó `npm install && npm run dev`, và `sb site deploy --vercel` khi muốn đưa lên mạng.
736
754
 
737
755
  **`sb site new --editor "<mô tả>"`** dựng trong editor: lệnh mở editor, editor tạo site và
738
756
  bắt đầu dựng. Nếu `sb agent` đang chạy thì `sb agent` làm việc này; nếu chưa chạy mà máy có
@@ -747,6 +765,7 @@ của nền tảng.
747
765
  | Flag | Tác dụng |
748
766
  | --- | --- |
749
767
  | `--editor` | Dựng trong editor (trợ lý, hoặc `sb agent` của bạn) thay vì trong một repo |
768
+ | `--template <slug\|id>` | Chép mẫu đó vào site mới thay vì bắt đầu trống (`sb site templates` liệt kê các mẫu) |
750
769
 
751
770
  **Dựng bằng AI.** Lựa chọn 1 của `sb init` (và `sb site new`) lấy mô tả của bạn, tạo site, viết repo
752
771
  dưới đây và — nếu máy có Claude Code — mở nó ngay trong thư mục đó với mô tả của bạn,
@@ -758,6 +777,27 @@ không đọc `.codex/config.toml`), còn `AGENTS.md` (được `CLAUDE.md` và
758
777
  từng section trên desktop và mobile, hỏi dữ liệu thật, kéo kết quả về repo, **không
759
778
  bao giờ tự xuất bản**. Agent sửa bản nháp của site; bạn duyệt lại bằng git diff.
760
779
 
780
+ **`sb site preview <file>`** in ra liên kết tới BẢN NHÁP hiện tại của trang trên storefront,
781
+ render đúng như khách sẽ thấy khi xuất bản — chính nút Preview của editor, từ terminal. Không có
782
+ gì được xuất bản. Liên kết dùng được một giờ; `--open` mở nó trong trình duyệt, `--html` in ra HTML
783
+ đã render. Nó hiển thị bản đã PUSH gần nhất (file có chỉnh sửa chưa push sẽ được báo). Liên kết
784
+ được tạo bằng `sb login` (hoặc `SB_TOKEN`) nếu có, chỉ gửi tới nền tảng đó; không thì bằng
785
+ API key của repo trong `.env` (cần quyền `pages.read`), gửi tới `SB_API` của chính `.env` đó — cặp mà mọi lệnh
786
+ site đều dùng.
787
+
788
+ **Cấu trúc được kiểm tra trước khi gửi.** Mỗi phần tử phải nằm ở chỗ schema cho phép — các con
789
+ được phép của phần tử cha (`<Accordion>` chỉ chứa `<AccordionContent>`) và các loại section chỉ
790
+ nằm trực tiếp trong `<Page>`. `sb site push` và `sb site dev` kiểm tra từng file sắp gửi: file vi phạm
791
+ không được gửi, kèm `file:line:col` và cách viết đúng (loại phần tử đã bị gỡ: xoá nó), các file khác vẫn
792
+ đi; push sau đó thoát với mã 1. Luật là bản schema của chính CLI này — thông báo ghi phiên bản, và nếu
793
+ editor cho phép điều nó từ chối thì hãy nâng cấp sb. `sb doctor` báo cho mọi file.
794
+ `design/sbuilder-env.d.ts` ghi công dụng, các con được phép và ví dụ của từng phần tử, lấy từ schema.
795
+
796
+ **Theme.** `sb site pull` ghi `design/theme.json` — theme site đã lưu, hoặc theme mặc định site đang
797
+ dùng khi chưa lưu. Lưu theme có hiệu lực ngay, nên `sb site push` chỉ gửi nó khi có `--theme`, và
798
+ `sb site push --theme --dry-run` in từng token sẽ đổi (`colors.primary: value #171717 → #e11d48`) mà
799
+ không gửi gì.
800
+
761
801
  **`sb site init` viết ra những gì.** Nó đăng nhập nếu cần, cho bạn chọn site (hoặc nhận
762
802
  `--site <id>`), rồi viết:
763
803
 
@@ -799,6 +839,9 @@ Settings -> API keys. Nếu không tạo được key, init nói rõ rồi làm
799
839
  `--github` chạy tiếp `git init`, commit đầu tiên, `gh repo create --private --push` và
800
840
  `gh secret set SB_TOKEN` (key đi qua stdin, không bao giờ nằm trên dòng lệnh) — workflow
801
841
  chạy được ngay, không phải dán gì.
842
+ Không có `--github`, init vẫn chạy `git init` và tạo commit đầu tiên khi thư mục chưa nằm trong
843
+ một repo git và máy có git (nó báo trường hợp nào), để mọi lần pull hay chỉnh sửa của agent về sau
844
+ đều hiện thành git diff.
802
845
 
803
846
  **File trang.** Mỗi trang là một file `.page.tsx` đọc như React — mỗi phần tử một thẻ, cài
804
847
  đặt của nó là prop:
@@ -960,7 +1003,8 @@ khi push; đổi `name`, `slug`, `type`, `isHomepage`, `settings` hay `defaultTe
960
1003
  file đã theo dõi là đổi tên hoặc đổi loại trang. `path` được suy ra, chỉ để tham khảo. Khi
961
1004
  nền tảng chốt khác điều bạn xin (slug bị làm cho không trùng) push sẽ nói ra, và sau mỗi
962
1005
  lần lưu file được ghi lại đúng như nền tảng đã lưu — id mới được cấp và các thông tin nó
963
- đã chốt — nên `sb site pull` kế tiếp không đổi gì. File không có `export const page` và
1006
+ đã chốt, cùng các phần dùng chung và overlay nằm đúng chỗ như khi pull ghi — nên `sb site
1007
+ pull` kế tiếp không đổi gì. File không có `export const page` và
964
1008
  chưa có trong manifest vẫn chỉ được nêu tên.
965
1009
 
966
1010
  Các thông tin này được trộn ba chiều như tài liệu: lần đồng bộ gần nhất là gốc. Thông tin chỉ
@@ -976,7 +1020,9 @@ Với API key (`/api/v1`) nền tảng còn rào chính lần ghi: mỗi thông
976
1020
  `missing` và trang vẫn ở lại nền tảng (exit 1). `sb site push --prune` xoá các trang đó:
977
1021
  nó liệt kê trước, hỏi lại khi chạy trên terminal, và ngoài terminal còn cần `--yes` (không
978
1022
  thì không xoá gì). `--prune` từ chối khi không có `design/pages/`, vì khi đó mọi trang đều
979
- trông như đã bị xoá. Trang bị xoá trên nền tảng vẫn giữ file, pull sẽ nêu tên.
1023
+ trông như đã bị xoá. Trang bị xoá trên nền tảng vẫn giữ file, pull sẽ nêu tên. File đã
1024
+ theo dõi mà bạn xoá thì `sb site pull` vẫn để nguyên là đã xoá (nêu tên, exit 0) cho tới khi
1025
+ bạn prune trang; `sb site pull --force` ghi nó lại.
980
1026
 
981
1027
  ### Phần còn lại của site thành file
982
1028
 
package/dist/bin/sb.js CHANGED
@@ -7,9 +7,9 @@
7
7
  * and an exit code.
8
8
  */
9
9
  import { lstat } from 'node:fs/promises';
10
- import { realpathSync } from 'node:fs';
10
+ import { existsSync, realpathSync } from 'node:fs';
11
11
  import { homedir, userInfo } from 'node:os';
12
- import { resolve } from 'node:path';
12
+ import { join, resolve } from 'node:path';
13
13
  import { init, nextSteps, normalizeName, InitError } from '../src/init.js';
14
14
  import { readConfig, watchAndUpload, DevError } from '../src/dev.js';
15
15
  import { deploy, submit, DeployStopped } from '../src/deploy.js';
@@ -18,7 +18,8 @@ import { login, logout, apiBase, whoIs } from '../src/login.js';
18
18
  import { pull, push, ROOT_LINKED } from '../src/code.js';
19
19
  import { agent } from '../src/agent.js';
20
20
  import { servicePlan, install, uninstall, status } from '../src/service.js';
21
- import { newSite } from '../src/new.js';
21
+ import { newSite, openBrowser } from '../src/new.js';
22
+ import { preview as sitePreview } from '../src/preview.js';
22
23
  import { pull as sitePull, push as sitePush, publish as sitePublish, blocks as siteBlocks, } from '../src/site.js';
23
24
  import { doctor, lines as doctorLines } from '../src/doctor.js';
24
25
  import { componentsInit, deleteRemote as componentsDelete, listRemote as componentsList, preview as componentsPreview, upgrade as componentsUpgrade, } from '../src/components.js';
@@ -26,10 +27,11 @@ import { linkHost } from '../src/hostlink.js';
26
27
  import { dev as siteDev } from '../src/sitedev.js';
27
28
  import { status as siteStatus } from '../src/sitestatus.js';
28
29
  import { APP_SKILL_PATH } from '../src/agentdocs.js';
29
- import { agents, initSite, types as siteTypes, writeTypeFiles, nextSteps as siteNextSteps, buildPrompt, } from '../src/siteinit.js';
30
+ import { agents, checkInitFolder, gitStart, initSite, types as siteTypes, writeTypeFiles, nextSteps as siteNextSteps, buildPrompt, } from '../src/siteinit.js';
30
31
  import { mcp, siteEnv } from '../src/repo.js';
31
32
  import { initNext } from '../src/next.js';
32
33
  import { initNextStarter } from '../src/starter.js';
34
+ import { findTemplate, listTemplates, templateLines, useTemplate } from '../src/templates.js';
33
35
  import { deployVercel } from '../src/vercel.js';
34
36
  import { route, SUBCOMMANDS } from '../src/route.js';
35
37
  import { createApp, createdSteps } from '../src/appcreate.js';
@@ -39,9 +41,10 @@ import { createInterface } from 'node:readline/promises';
39
41
  const USAGE = `sb — the Store Builder command line
40
42
 
41
43
  Start
42
- sb init ask what to start: a new website built by AI, a
43
- repo for one of your sites, or an app (same as
44
- npm create sbuilder-app)
44
+ sb init ask what to start: a new website built by AI, one
45
+ from a template, a repo for one of your sites, an
46
+ app or a Next.js storefront (same as npm create
47
+ sbuilder-app)
45
48
 
46
49
  Account
47
50
  sb login sign in through the browser: opens <editor>/device,
@@ -63,6 +66,14 @@ Sites
63
66
  repo (gh). --editor builds it in the editor instead:
64
67
  opens it and the assistant starts building, on this
65
68
  machine's Claude Code login when it can.
69
+ sb site new --template <slug|id> ["<description>"] [--dir <path>] [--github]
70
+ a new site copied from a template (its pages, theme,
71
+ code and components), in a repo like sb site init's.
72
+ A description names the site and is handed to
73
+ Claude Code to adapt the design; without one the
74
+ site takes the template's name
75
+ sb site templates [--json] the templates a new site can start from: slug, name,
76
+ categories, live site and preview image
66
77
  sb site init [dir] [--site <id>] [--github]
67
78
  a repo holding one site's pages: picks the site,
68
79
  pulls it, adds a GitHub workflow that syncs both
@@ -81,6 +92,10 @@ Sites
81
92
  sb site dev [--theme] watch design/ and code/ and push each save as a DRAFT
82
93
  sb site publish <file>… | --all
83
94
  make pages LIVE — named files, or every page
95
+ sb site preview <file> [--open] [--html]
96
+ a link (1 hour) to the page's DRAFT rendered as a visitor
97
+ sees it — nothing published; --open opens it, --html
98
+ prints the HTML. The repo's key (.env) or sb login mints it
84
99
  sb site blocks the blocks your installed apps let you place, each
85
100
  with the line to paste into a page file
86
101
  sb site next --link [--yes] mint (or rotate) the host secret into .env: a deployed
@@ -228,6 +243,15 @@ function parse(argv) {
228
243
  else if (a === '--to') {
229
244
  args.to = argv[++i];
230
245
  }
246
+ else if (a === '--open') {
247
+ args.open = true;
248
+ }
249
+ else if (a === '--html') {
250
+ args.html = true;
251
+ }
252
+ else if (a === '--template') {
253
+ args.template = argv[++i];
254
+ }
231
255
  else if (a === '--org') {
232
256
  args.org = argv[++i];
233
257
  }
@@ -289,8 +313,8 @@ function slug(name) {
289
313
  const hasClaude = () => process.platform !== 'win32' &&
290
314
  spawnSync('claude', ['--version'], { stdio: 'ignore' }).status === 0;
291
315
  /**
292
- * `sb site init` and the menu's two site choices: sign in if needed, make the
293
- * repo, say what to do next — and, when the site was DESCRIBED, hand the
316
+ * `sb site init`, `sb site new` and the menu's site choices: sign in if needed, (copy a template
317
+ * into a new site,) make the repo, say what to do next — and, when the site was DESCRIBED, hand the
294
318
  * description to Claude Code in that folder so building starts right there.
295
319
  */
296
320
  async function startSiteRepo(o) {
@@ -301,18 +325,46 @@ async function startSiteRepo(o) {
301
325
  token = await credential(api);
302
326
  }
303
327
  const dir = resolve(o.dir);
328
+ // Read BEFORE init writes anything: an empty folder is the only one git may auto-commit.
329
+ const folder = await checkInitFolder(dir);
330
+ let site = o.site;
331
+ const name = o.create || o.template?.name || '';
332
+ // No token: initSite refuses below with the sign-in sentence, before anything is created.
333
+ if (o.template && token) {
334
+ // (The folder was checked above: a copy made for a folder init then refuses would be left behind.)
335
+ site = await useTemplate({
336
+ api,
337
+ token,
338
+ template: o.template,
339
+ name,
340
+ dir: o.dir,
341
+ log: (l) => console.log(l),
342
+ });
343
+ console.log(`Created ${name} from the ${o.template.name} template.`);
344
+ }
345
+ const copied = o.template ? site : undefined;
304
346
  const res = await initSite({
305
347
  api,
306
348
  token,
307
349
  dir,
308
- site: o.site,
309
- create: o.create,
350
+ site,
351
+ create: o.template ? undefined : o.create,
310
352
  github: o.github,
353
+ description: o.description || o.template?.description,
354
+ template: o.template?.name,
311
355
  pick: pickSite,
312
356
  log: (l) => console.log(l),
313
357
  warn: (l) => console.error(l),
358
+ }).catch((err) => {
359
+ if (!copied || !(err instanceof DevError))
360
+ throw err;
361
+ // The site exists now: say which, and the one command that finishes the repo around it.
362
+ throw new DevError(`${err.message}\nThe site "${name}" (${copied}) was created from the template — finish with: sb site init ${o.dir} --site ${copied}`);
314
363
  });
315
364
  const rel = o.dir;
365
+ // --github already made the repo and its first commit; otherwise start one, so the diff is real.
366
+ if (!o.github)
367
+ console.log(gitStart(dir, res.site.name, folder));
316
368
  if (o.starter && res.code === 0) {
317
369
  const minor = VERSION.split('.').slice(0, 2).join('.');
318
370
  await initNextStarter({ dir, cliRange: `^${minor}.0`, renderRange: '^0.1.0' });
@@ -320,12 +372,19 @@ async function startSiteRepo(o) {
320
372
  console.log(' sb site deploy --vercel # when you want it on the internet');
321
373
  return 0;
322
374
  }
375
+ const steps = {
376
+ dir: rel,
377
+ name: res.site.name,
378
+ ok: res.code === 0,
379
+ github: !!o.github,
380
+ npm: existsSync(join(dir, 'package.json')),
381
+ };
323
382
  if (!o.description) {
324
- for (const l of siteNextSteps(rel, !!o.github))
383
+ for (const l of siteNextSteps(steps))
325
384
  console.log(l);
326
385
  return res.code;
327
386
  }
328
- const prompt = buildPrompt(o.description);
387
+ const prompt = buildPrompt(o.description, o.template?.name);
329
388
  if (hasClaude() && process.stdin.isTTY) {
330
389
  const go = await ask('\nStart Claude Code in that folder to build it now? [Y/n]: ');
331
390
  if (!/^n/i.test(go)) {
@@ -333,10 +392,8 @@ async function startSiteRepo(o) {
333
392
  return spawnSync('claude', [prompt], { cwd: dir, stdio: 'inherit' }).status ?? 0;
334
393
  }
335
394
  }
336
- console.log('\nTo build it, open the folder in an AI agent and give it this:');
337
- console.log(` cd ${rel}`);
338
- console.log(` claude '${prompt.replace(/'/g, `'\\''`)}'`);
339
- console.log(' (Cursor / VS Code work too — the Store Builder tools are set up in the folder.)');
395
+ for (const l of siteNextSteps({ ...steps, prompt }))
396
+ console.log(l);
340
397
  return res.code;
341
398
  }
342
399
  /** A site name from its description: the first words, cut at a word boundary. */
@@ -348,17 +405,50 @@ function siteName(description) {
348
405
  return cut.slice(0, Math.max(cut.lastIndexOf(' '), 1)).replace(/[\s,.;:-]+$/, '');
349
406
  }
350
407
  /**
351
- * `sb site new "<description>"` and menu choice 1: create the site and its repo,
352
- * then offer Claude Code with the description.
408
+ * `sb site new "<description>"` and menu choice 1: create the site and its repo, then offer
409
+ * Claude Code with the description. With a template (menu choice 2, `--template`), the site is a
410
+ * copy of it; the description, when there is one, names it and becomes the agent's brief.
353
411
  */
354
412
  function siteNew(o) {
355
- const name = o.name || siteName(o.description);
413
+ const name = o.name || (o.description ? siteName(o.description) : (o.template?.name ?? 'My shop'));
356
414
  return startSiteRepo({
357
415
  dir: o.dir ?? slug(name),
358
416
  create: name,
359
417
  github: o.github,
360
- description: o.description,
418
+ description: o.description || undefined,
419
+ template: o.template,
420
+ });
421
+ }
422
+ /** `sb site templates [--json]`: the public gallery. Needs no sign-in. */
423
+ async function siteTemplates(args) {
424
+ const list = await listTemplates(apiBase());
425
+ if (args.json)
426
+ console.log(JSON.stringify(list, null, 2));
427
+ else {
428
+ for (const l of templateLines(list))
429
+ console.log(l);
430
+ if (list.length)
431
+ console.log(`\nStart one: sb site new --template ${list[0].slug || list[0].siteId}`);
432
+ }
433
+ return 0;
434
+ }
435
+ /** The menu's template choice: list the gallery, pick one by number. */
436
+ async function pickTemplate() {
437
+ const list = await listTemplates(apiBase());
438
+ if (!list.length) {
439
+ console.log('The platform offers no templates yet — choose 1 to have AI build one instead.');
440
+ return undefined;
441
+ }
442
+ console.log('Templates:');
443
+ list.forEach((t, i) => {
444
+ const cats = t.categories.map((c) => c.name).join(', ');
445
+ console.log(` ${i + 1}) ${t.name}${cats ? ` (${cats})` : ''}${t.publicUrl ? ` ${t.publicUrl}` : ''}`);
361
446
  });
447
+ for (;;) {
448
+ const n = Number(await ask(`Choose 1-${list.length}: `));
449
+ if (Number.isInteger(n) && n >= 1 && n <= list.length)
450
+ return list[n - 1];
451
+ }
362
452
  }
363
453
  /** `sb site new --editor` (the old `sb new`): the editor opens and the assistant builds. */
364
454
  async function siteNewEditor(prompt) {
@@ -448,10 +538,11 @@ async function appInit(o) {
448
538
  async function menu(args) {
449
539
  const choice = await ask('What do you want to start?\n' +
450
540
  ' 1) A new website, built by AI — describe it, an AI agent builds it\n' +
451
- ' 2) A repo for one of your sites — edit it with AI, synced with GitHub\n' +
452
- " 3) An app — runs inside a merchant's admin\n" +
453
- ' 4) A Next.js storefront — one of your sites as a Next.js app, with the SDK and an example route\n' +
454
- 'Choose 1-4 [1]: ');
541
+ ' 2) A new website from a template — pick a design, then change it with AI\n' +
542
+ ' 3) A repo for one of your sites — edit it with AI, synced with GitHub\n' +
543
+ " 4) An app — runs inside a merchant's admin\n" +
544
+ ' 5) A Next.js storefront — one of your sites as a Next.js app, with the SDK and an example route\n' +
545
+ 'Choose 1-5 [1]: ');
455
546
  if (choice === '' || choice === '1') {
456
547
  let description = '';
457
548
  while (!description)
@@ -462,11 +553,34 @@ async function menu(args) {
462
553
  return siteNew({ description, name, dir, github });
463
554
  }
464
555
  if (choice === '2') {
556
+ const template = await pickTemplate();
557
+ if (!template)
558
+ return 1;
559
+ const name = (await ask(`Site name [${template.name}]: `)) || template.name;
560
+ const description = await ask('What is the site for? (optional — the agent adapts the design): ');
561
+ // Asked AND checked before anything is copied: a refused folder must not leave a site behind.
562
+ let dir = '';
563
+ for (;;) {
564
+ dir = (await ask(`Folder [${slug(name)}]: `)) || slug(name);
565
+ try {
566
+ await checkInitFolder(resolve(dir));
567
+ break;
568
+ }
569
+ catch (err) {
570
+ if (!(err instanceof DevError))
571
+ throw err;
572
+ console.error(err.message);
573
+ }
574
+ }
575
+ const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
576
+ return siteNew({ description, name, dir, github, template });
577
+ }
578
+ if (choice === '3') {
465
579
  const dir = (await ask('Folder [my-site]: ')) || 'my-site';
466
580
  const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
467
581
  return startSiteRepo({ dir, github });
468
582
  }
469
- if (choice === '4') {
583
+ if (choice === '5') {
470
584
  const dir = (await ask('Folder [my-storefront]: ')) || 'my-storefront';
471
585
  const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
472
586
  return startSiteRepo({ dir, github, starter: true });
@@ -619,6 +733,19 @@ async function siteCommand(args) {
619
733
  const sub = args._[1];
620
734
  if (sub === 'new') {
621
735
  const description = args._.slice(2).join(' ').trim();
736
+ if (args.template !== undefined) {
737
+ if (args.editor) {
738
+ console.error('--template copies a design into a repo; --editor builds from a description in the editor. Pick one.');
739
+ return 1;
740
+ }
741
+ if (!args.template) {
742
+ console.error('Name the template: sb site new --template <slug|id> (sb site templates lists them)');
743
+ return 1;
744
+ }
745
+ // Before sign-in: a mistyped slug should not cost a browser round trip.
746
+ const template = findTemplate(await listTemplates(apiBase()), args.template);
747
+ return siteNew({ description, dir: args.dir, github: args.github, template });
748
+ }
622
749
  if (args.editor)
623
750
  return siteNewEditor(description);
624
751
  if (!description) {
@@ -629,6 +756,26 @@ async function siteCommand(args) {
629
756
  }
630
757
  if (sub === 'code')
631
758
  return siteCode(args);
759
+ if (sub === 'templates')
760
+ return siteTemplates(args);
761
+ if (sub === 'preview') {
762
+ if (!args._[2]) {
763
+ console.error('usage: sb site preview <design/pages/file.page.tsx> [--open] [--html]');
764
+ return 1;
765
+ }
766
+ // The ACCOUNT's credential, to the shell's platform only — never to an address a cloned .env names.
767
+ const api = apiBase();
768
+ return sitePreview({
769
+ dir: resolve(args.dir ?? '.'),
770
+ file: args._[2],
771
+ api,
772
+ token: await credential(api),
773
+ html: args.html,
774
+ open: args.open ? openBrowser : undefined,
775
+ log: (l) => console.log(l),
776
+ warn: (l) => console.error(l),
777
+ });
778
+ }
632
779
  if (sub === 'components')
633
780
  return siteComponents(args);
634
781
  if (sub === 'mcp')
@@ -638,7 +785,7 @@ async function siteCommand(args) {
638
785
  if (sub === 'types')
639
786
  return siteTypes({ dir: resolve(args.dir ?? '.'), quiet: args.quiet });
640
787
  if (!sub || !SUBCOMMANDS.site.includes(sub)) {
641
- console.error('usage: sb site new|init|pull|push|publish|next|deploy|blocks|agents|types|code|components|mcp|status|dev [--site <id>] [--dir <path>] [--force] [--dry-run] [--all]');
788
+ console.error('usage: sb site new|init|templates|pull|push|publish|preview|next|deploy|blocks|agents|types|code|components|mcp|status|dev [--site <id>] [--dir <path>] [--force] [--dry-run] [--all]');
642
789
  return 1;
643
790
  }
644
791
  if (sub === 'init') {