@usequeek/create-theme 0.1.0 → 0.2.1

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
@@ -3,19 +3,39 @@
3
3
  Start a theme for [Queek](https://usequeek.com) storefronts from the official
4
4
  [starter](https://github.com/usequeek/theme-starter).
5
5
 
6
- ```bash
7
- npm create @usequeek/theme my-theme
8
- # or: pnpm create @usequeek/theme my-theme · yarn create @usequeek/theme my-theme
6
+ ## Usage
7
+
9
8
  ```
9
+ Create a Queek storefront theme.
10
+
11
+ npm create @usequeek/theme@latest my-theme -- --templates laundry --tags minimal
12
+ pnpm create @usequeek/theme my-theme --templates laundry --tags minimal
10
13
 
11
- It copies the starter into `my-theme`, names the package after the folder and installs
12
- dependencies with the package manager you ran it with (`-- --no-install` to skip). Then:
14
+ npm needs -- before these flags. In a terminal, anything you leave out is asked,
15
+ and with no folder the folder is named after the theme (my-theme with --yes or no terminal).
13
16
 
14
- ```bash
15
- cd my-theme
16
- npm run dev
17
+ --name <text> theme name (default: the folder name)
18
+ --templates <keys> businesses to make templates for, comma-separated (required with --yes)
19
+ --primary <key> the primary template (default: the first)
20
+ --categories <keys> business categories (default: the templates')
21
+ --tags <tags> 1–6 tags for the look (required with --yes)
22
+ --pages <list|none> extra pages: contact, faq (default: both)
23
+ --ai <list>, --no-ai AI assistants: claude, gemini (default: both; AGENTS.md unless --no-ai)
24
+ --pm <npm|pnpm|yarn|bun>, --no-install, --no-git
25
+ --yes, -y never prompt; take the default for everything else
26
+ --dry-run print what would be written; write nothing
27
+ --force allow a folder that is not empty
28
+ --template <source> another starter: a giget source or a local folder
17
29
  ```
18
30
 
31
+ The starter is pinned to the tag matching this package's version. Everything is written into a temporary folder and moved into place at the end.
32
+
33
+ ## What you get
34
+
35
+ Right after `create`, `npm run check` rejects exactly your to-do list. For a one-template theme that is four rules: `theme/placeholder-content` (the starter's placeholder products and photos, and the theme's placeholder description), `theme/structure` and `theme/template-screenshot` (each template's screenshot), and `theme/template-description` (each template's description). With two or more templates, `theme/template-versions` is added: each template must have its own home page.
36
+
37
+ The target folder must be missing, empty, or hold only `.git`. The `--force` flag allows writing into another folder but refuses file-or-folder clashes and symlinks at paths the starter writes. A regular file at the target path is always refused.
38
+
19
39
  ## License
20
40
 
21
41
  MIT
package/dist/cli.js CHANGED
@@ -1,23 +1,56 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * npm create @usequeek/theme [dir] [--no-install]
4
- * (npm maps `npm create @usequeek/theme` to this package: @usequeek/create-theme.)
3
+ * npm create @usequeek/theme [dir] [-- flags]
4
+ * (npm maps `npm create @usequeek/theme` to this package, @usequeek/create-theme.)
5
+ * Exit codes: 0 done, 1 runtime failure, 2 usage, 130 cancelled.
5
6
  */
6
7
  import { parseArgs } from 'node:util';
7
- import { createTheme } from './index.js';
8
- const { values, positionals } = parseArgs({
9
- allowPositionals: true,
10
- options: {
11
- install: { type: 'boolean', default: true },
12
- 'no-install': { type: 'boolean', default: false },
13
- help: { type: 'boolean', short: 'h', default: false },
14
- },
15
- });
8
+ import { HELP, runCreate } from './index.js';
9
+ import { nearest } from './lists.js';
10
+ import { UsageError } from './options.js';
11
+ import { clackPrompter } from './prompts.js';
12
+ const OPTIONS = {
13
+ name: { type: 'string' }, templates: { type: 'string' }, primary: { type: 'string' },
14
+ categories: { type: 'string' }, tags: { type: 'string' }, pages: { type: 'string' },
15
+ ai: { type: 'string' }, 'no-ai': { type: 'boolean', default: false },
16
+ pm: { type: 'string' }, 'no-install': { type: 'boolean', default: false }, 'no-git': { type: 'boolean', default: false },
17
+ yes: { type: 'boolean', short: 'y', default: false }, 'dry-run': { type: 'boolean', default: false },
18
+ force: { type: 'boolean', default: false }, template: { type: 'string' },
19
+ help: { type: 'boolean', short: 'h', default: false },
20
+ };
21
+ /** Node's strict parse errors, as a usage error a person can act on — never a stack trace. */
22
+ function usageFrom(error) {
23
+ if (error.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
24
+ const flag = /Unknown option '([^']+)'/.exec(error.message)?.[1] ?? 'given';
25
+ const hint = flag.startsWith('--') ? nearest(flag.slice(2), Object.keys(OPTIONS)) : null;
26
+ return new UsageError(`Unknown flag ${flag}.${hint ? ` Did you mean --${hint}?` : ''}`);
27
+ }
28
+ if (error.code === 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE') {
29
+ const flag = /--[\w-]+/.exec(error.message)?.[0] ?? 'This flag';
30
+ return new UsageError(/does not take an argument/.test(error.message) ? `${flag} takes no value.` : `${flag} needs a value.`);
31
+ }
32
+ return null;
33
+ }
34
+ function fail(error) {
35
+ console.error(`\n✖ ${error.message}`);
36
+ process.exit(error.exitCode ?? 1);
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = parseArgs({ allowPositionals: true, options: OPTIONS });
41
+ }
42
+ catch (error) {
43
+ fail(usageFrom(error) ?? error);
44
+ }
45
+ const { values, positionals } = parsed;
16
46
  if (values.help) {
17
- console.log('Usage: npm create @usequeek/theme [dir] [-- --no-install]\n\nCopies the Queek theme starter into dir (default: my-theme) and installs its dependencies.');
47
+ console.log(HELP);
18
48
  process.exit(0);
19
49
  }
20
- createTheme({ dir: positionals[0] ?? 'my-theme', install: values.install && !values['no-install'] }).catch((error) => {
21
- console.error(`\n✖ ${error.message}`);
22
- process.exit(1);
23
- });
50
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !values.yes;
51
+ runCreate({
52
+ dir: positionals[0], name: values.name, templates: values.templates, primary: values.primary,
53
+ categories: values.categories, tags: values.tags, pages: values.pages, ai: values.ai, noAi: values['no-ai'],
54
+ pm: values.pm, install: !values['no-install'], git: !values['no-git'], yes: values.yes,
55
+ dryRun: values['dry-run'], force: values.force, template: values.template,
56
+ }, interactive ? clackPrompter() : null).catch(fail);
@@ -0,0 +1,36 @@
1
+ {
2
+ "$comment": "Display names for every key in business-vocabulary.json, for pickers (npm create @usequeek/theme). Ours: the vocabulary itself is agreed with the backend and its format never changes for labels. tests/business-labels.test.ts fails when a key has none.",
3
+ "labels": {
4
+ "foods": "Food & restaurants", "local-meals": "Local meals", "shawarma-pizza-snacks": "Shawarma, pizza & snacks",
5
+ "suya": "Suya", "boli": "Boli", "fruits-fresh-natural": "Fruits & fresh produce", "meat-fish": "Meat & fish",
6
+ "supermarket": "Supermarket", "groceries": "Groceries", "shop-groceries": "Grocery shop", "local-market": "Local market",
7
+ "pharmacy": "Pharmacy", "health-wellness-store": "Health & wellness store", "fashion": "Fashion",
8
+ "beauty-cosmetics": "Beauty & cosmetics", "electronics": "Electronics", "phones-accessories": "Phones & accessories",
9
+ "home-living": "Home & living", "baby-kids": "Baby & kids", "office-school": "Office & school", "shop": "General shop",
10
+ "laundry": "Laundry & dry cleaning", "gas-refill": "Gas refill", "home-cleaning": "Home cleaning", "car-wash": "Car wash",
11
+ "beauty-personal-care": "Beauty & personal care", "phones-tablets": "Phones & tablets", "health-wellness": "Health & wellness",
12
+ "womens-fashion": "Women's fashion", "mens-fashion": "Men's fashion", "kids-fashion": "Kids' fashion", "shoes": "Shoes",
13
+ "bags-accessories": "Bags & accessories", "modest-occasion-wear": "Modest & occasion wear",
14
+ "makeup": "Make-up", "skincare": "Skincare", "hair-care-styling": "Hair care & styling", "fragrance": "Fragrance",
15
+ "wigs-extensions-hair-accessories": "Wigs, extensions & hair accessories", "personal-care": "Personal care",
16
+ "beauty-tools-devices": "Beauty tools & devices",
17
+ "computers-laptops": "Computers & laptops", "tv-home-entertainment": "TV & home entertainment",
18
+ "gaming-consoles": "Gaming & consoles", "cameras-drones": "Cameras & drones", "smart-home-security": "Smart home & security",
19
+ "power-solar": "Power & solar",
20
+ "smartphones": "Smartphones", "tablets-e-readers": "Tablets & e-readers", "smartwatches-wearables": "Smartwatches & wearables",
21
+ "chargers-power-banks": "Chargers & power banks", "earbuds-headsets": "Earbuds & headsets",
22
+ "cases-screen-protection": "Cases & screen protection", "phone-repair-replacement": "Phone repair & parts",
23
+ "furniture": "Furniture", "home-decor": "Home decor", "kitchen-dining": "Kitchen & dining", "bedding-bath": "Bedding & bath",
24
+ "lighting-electrical": "Lighting & electrical", "storage-organization": "Storage & organization",
25
+ "baby-gear": "Baby gear", "feeding-nursing": "Feeding & nursing", "diapering-potty": "Diapering & potty",
26
+ "baby-clothing": "Baby clothing", "kids-clothing": "Kids' clothing", "toys-games": "Toys & games",
27
+ "school-essentials": "School essentials", "nursery-safety": "Nursery & safety",
28
+ "vitamins-supplements": "Vitamins & supplements", "personal-care-hygiene": "Personal care & hygiene",
29
+ "fitness-recovery": "Fitness & recovery", "sexual-wellness": "Sexual wellness", "medical-supplies": "Medical supplies",
30
+ "health-devices": "Health devices", "healthy-living": "Healthy living",
31
+ "stationery-writing": "Stationery & writing", "office-supplies": "Office supplies", "school-supplies": "School supplies",
32
+ "bags-lunch-gear": "Bags & lunch gear", "office-furniture": "Office furniture", "printers-accessories": "Printers & accessories",
33
+ "tech-for-school-office": "Tech for school & office",
34
+ "beverages": "Beverages", "jewelry": "Jewelry"
35
+ }
36
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "$comment": "The only keys a template's `for` may use (theme.config.ts default_demo.for / demos[].for). `services` are the slugs a vendor registers as; `catalogue` is the marketplace product taxonomy, root -> branches, and `subcategories` a branch -> its own children; each key is the Str::slug of the category name. The backend reads a vendor's business from what they actually sell and ranks a specific (branch) match above a broad one. Agreed with queek_backend 24/9/26 (storefront-theme-templates-contract.md, R2.1; jewelry and beverages R2.5); change it only together with the backend.",
3
+ "services": [
4
+ "foods", "local-meals", "shawarma-pizza-snacks", "suya", "boli", "fruits-fresh-natural",
5
+ "meat-fish", "supermarket", "groceries", "shop-groceries", "local-market", "pharmacy",
6
+ "health-wellness-store", "fashion", "beauty-cosmetics", "electronics", "phones-accessories",
7
+ "home-living", "baby-kids", "office-school", "shop", "laundry", "gas-refill", "home-cleaning",
8
+ "car-wash"
9
+ ],
10
+ "catalogue": {
11
+ "fashion": ["womens-fashion", "mens-fashion", "kids-fashion", "shoes", "bags-accessories", "modest-occasion-wear"],
12
+ "beauty-personal-care": ["makeup", "skincare", "hair-care-styling", "fragrance", "wigs-extensions-hair-accessories", "personal-care", "beauty-tools-devices"],
13
+ "electronics": ["computers-laptops", "tv-home-entertainment", "gaming-consoles", "cameras-drones", "smart-home-security", "power-solar"],
14
+ "phones-tablets": ["smartphones", "tablets-e-readers", "smartwatches-wearables", "chargers-power-banks", "earbuds-headsets", "cases-screen-protection", "phone-repair-replacement"],
15
+ "home-living": ["furniture", "home-decor", "kitchen-dining", "bedding-bath", "lighting-electrical", "storage-organization"],
16
+ "baby-kids": ["baby-gear", "feeding-nursing", "diapering-potty", "baby-clothing", "kids-clothing", "toys-games", "school-essentials", "nursery-safety"],
17
+ "health-wellness": ["vitamins-supplements", "personal-care-hygiene", "fitness-recovery", "sexual-wellness", "medical-supplies", "health-devices", "healthy-living"],
18
+ "office-school": ["stationery-writing", "office-supplies", "school-supplies", "bags-lunch-gear", "office-furniture", "printers-accessories", "tech-for-school-office"],
19
+ "supermarket": ["beverages"]
20
+ },
21
+ "subcategories": {
22
+ "bags-accessories": ["jewelry"]
23
+ }
24
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "slugs": [
3
+ "allure",
4
+ "atelier",
5
+ "bare",
6
+ "beaurify",
7
+ "carat",
8
+ "default",
9
+ "deluxr",
10
+ "glow",
11
+ "lumiere",
12
+ "medley",
13
+ "nova",
14
+ "roast"
15
+ ],
16
+ "prefixes": [
17
+ "bare",
18
+ "br",
19
+ "ct",
20
+ "gl",
21
+ "md",
22
+ "qa",
23
+ "ql",
24
+ "qn",
25
+ "rs",
26
+ "td"
27
+ ]
28
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "$comment": "PROVISIONAL tag list for npm create @usequeek/theme (spec create-setup, release 1). Release 3 makes it a contract agreed with queek_backend (tags are published in the registry for their picker); until then theme-check does not enforce it. US spelling, like the business vocabulary. Business words (fashion, food) are not tags: categories carry the business.",
3
+ "tags": ["light", "dark", "colorful", "monochrome", "warm", "cool", "minimal", "bold", "elegant", "playful", "luxury", "classic", "modern", "editorial", "photo-led", "type-led", "catalog-first", "story-led"]
4
+ }
package/dist/index.d.ts CHANGED
@@ -1,18 +1,24 @@
1
- /** The official starter: theme files only, the tools come from npm. */
2
- export declare const STARTER = "github:usequeek/theme-starter";
3
- export interface CreateThemeOptions {
4
- /** Folder to create. Must be empty or missing. */
5
- dir: string;
6
- /** Run the package manager's install afterwards. */
7
- install?: boolean;
8
- /** Where progress goes; stdout by default. */
9
- log?: (line: string) => void;
10
- /** giget source — overridable for tests and forks. */
11
- template?: string;
12
- }
13
- type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
14
- /** The package manager that ran us (`npm create`, `pnpm create`…), from the user agent it sets. */
1
+ import { type Flags, type PackageManager, type Prompter } from './options.js';
2
+ import { type Answers } from './setup.js';
3
+ export { UsageError, CancelledError, type Flags, type Prompter, type PackageManager } from './options.js';
4
+ export { setupTheme, type Answers } from './setup.js';
5
+ export { clackPrompter } from './prompts.js';
6
+ /** The starter this release was tested with: its tag matches this package's version (`yarn starter:publish --tag`). */
7
+ export declare const STARTER: string;
15
8
  export declare function detectPackageManager(userAgent?: string): PackageManager;
16
- /** Copy the starter into `dir`, name the package after the folder, and install. */
17
- export declare function createTheme(options: CreateThemeOptions): Promise<void>;
18
- export {};
9
+ export declare const HELP = "Create a Queek storefront theme.\n\n npm create @usequeek/theme@latest my-theme -- --templates laundry --tags minimal\n pnpm create @usequeek/theme my-theme --templates laundry --tags minimal\n\nnpm needs -- before these flags. In a terminal, anything you leave out is asked,\nand with no folder the folder is named after the theme (my-theme with --yes or no terminal).\n\n --name <text> theme name (default: the folder name)\n --templates <keys> businesses to make templates for, comma-separated (required with --yes)\n --primary <key> the primary template (default: the first)\n --categories <keys> business categories (default: the templates')\n --tags <tags> 1\u20136 tags for the look (required with --yes)\n --pages <list|none> extra pages: contact, faq (default: both)\n --ai <list>, --no-ai AI assistants: claude, gemini (default: both; AGENTS.md unless --no-ai)\n --pm <npm|pnpm|yarn|bun>, --no-install, --no-git\n --yes, -y never prompt; take the default for everything else\n --dry-run print what would be written; write nothing\n --force allow a folder that is not empty\n --template <source> another starter: a giget source or a local folder";
10
+ export declare function createTheme(dir: string, answers: Answers, options: {
11
+ install: boolean;
12
+ git: boolean;
13
+ pm: PackageManager;
14
+ dryRun: boolean;
15
+ force: boolean;
16
+ template?: string;
17
+ log?: (line: string) => void;
18
+ }): Promise<void>;
19
+ /**
20
+ * Flags → answers (prompting when a prompter is given) → the theme. Shared by the CLI and `queek-theme init`.
21
+ * With no folder argument, a person at the prompts gets a folder named after the theme's slug (checked
22
+ * with the name, before the next question); a script gets `my-theme`.
23
+ */
24
+ export declare function runCreate(flags: Flags, prompter: Prompter | null, log?: (line: string) => void): Promise<void>;
package/dist/index.js CHANGED
@@ -1,44 +1,238 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { basename, join, relative, resolve } from 'node:path';
2
+ import { cpSync, existsSync, lstatSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, relative, resolve } from 'node:path';
4
5
  import { downloadTemplate } from 'giget';
5
- /** The official starter: theme files only, the tools come from npm. */
6
- export const STARTER = 'github:usequeek/theme-starter';
7
- /** The package manager that ran us (`npm create`, `pnpm create`…), from the user agent it sets. */
6
+ import { UsageError, equivalentCommand, resolveAnswers, shellWord } from './options.js';
7
+ import { setupTheme } from './setup.js';
8
+ export { UsageError, CancelledError } from './options.js';
9
+ export { setupTheme } from './setup.js';
10
+ export { clackPrompter } from './prompts.js';
11
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
12
+ /** The starter this release was tested with: its tag matches this package's version (`yarn starter:publish --tag`). */
13
+ export const STARTER = `github:usequeek/theme-starter#v${VERSION}`;
8
14
  export function detectPackageManager(userAgent = process.env.npm_config_user_agent ?? '') {
9
15
  const name = userAgent.split('/')[0];
10
16
  return name === 'pnpm' || name === 'yarn' || name === 'bun' ? name : 'npm';
11
17
  }
12
- /** Copy the starter into `dir`, name the package after the folder, and install. */
13
- export async function createTheme(options) {
18
+ export const HELP = `Create a Queek storefront theme.
19
+
20
+ npm create @usequeek/theme@latest my-theme -- --templates laundry --tags minimal
21
+ pnpm create @usequeek/theme my-theme --templates laundry --tags minimal
22
+
23
+ npm needs -- before these flags. In a terminal, anything you leave out is asked,
24
+ and with no folder the folder is named after the theme (my-theme with --yes or no terminal).
25
+
26
+ --name <text> theme name (default: the folder name)
27
+ --templates <keys> businesses to make templates for, comma-separated (required with --yes)
28
+ --primary <key> the primary template (default: the first)
29
+ --categories <keys> business categories (default: the templates')
30
+ --tags <tags> 1–6 tags for the look (required with --yes)
31
+ --pages <list|none> extra pages: contact, faq (default: both)
32
+ --ai <list>, --no-ai AI assistants: claude, gemini (default: both; AGENTS.md unless --no-ai)
33
+ --pm <npm|pnpm|yarn|bun>, --no-install, --no-git
34
+ --yes, -y never prompt; take the default for everything else
35
+ --dry-run print what would be written; write nothing
36
+ --force allow a folder that is not empty
37
+ --template <source> another starter: a giget source or a local folder`;
38
+ function targetState(dir) {
39
+ if (!existsSync(dir))
40
+ return 'missing';
41
+ if (!statSync(dir).isDirectory())
42
+ return 'file';
43
+ const entries = readdirSync(dir).filter((entry) => entry !== '.git');
44
+ return entries.length === 0 ? 'usable' : 'busy';
45
+ }
46
+ /** Resolves `dir`, and throws before anything is asked or written when it cannot be used. */
47
+ function checkTarget(dir, force) {
48
+ const target = resolve(dir);
49
+ const state = targetState(target);
50
+ if (state === 'file')
51
+ throw new UsageError(`${dir} is a file, not a folder. Choose another name.`);
52
+ if (state === 'busy' && !force)
53
+ throw new UsageError(`${dir} is not empty. Choose another folder, or pass --force to write into it.`);
54
+ return { target, state };
55
+ }
56
+ /** `lstatSync`, or null if nothing is there — never follows a symlink, unlike `existsSync`/`statSync`. */
57
+ function lstatOrNull(path) {
58
+ try {
59
+ return lstatSync(path);
60
+ }
61
+ catch (error) {
62
+ if (error.code === 'ENOENT')
63
+ return null;
64
+ throw error;
65
+ }
66
+ }
67
+ /**
68
+ * Paths (relative to `stage`) where writing the starter into `target` is unsafe: the
69
+ * target already has the other type (a file where the stage has a folder, or the
70
+ * reverse) — cpSync cannot merge these — or the target is a symlink, dangling or not:
71
+ * `existsSync` follows symlinks, so a dangling one reads as "nothing here" right up
72
+ * until Node's native cpSync tries to write through it and aborts the whole process.
73
+ */
74
+ function conflictingPaths(stage, target, root = '') {
75
+ const conflicts = [];
76
+ for (const name of readdirSync(stage)) {
77
+ const stagePath = join(stage, name);
78
+ const targetPath = join(target, name);
79
+ const relPath = root ? `${root}/${name}` : name;
80
+ const targetStat = lstatOrNull(targetPath);
81
+ if (!targetStat)
82
+ continue;
83
+ if (targetStat.isSymbolicLink()) {
84
+ conflicts.push(`${relPath} (a link)`);
85
+ continue;
86
+ }
87
+ const stageIsDir = statSync(stagePath).isDirectory();
88
+ const targetIsDir = targetStat.isDirectory();
89
+ if (stageIsDir !== targetIsDir)
90
+ conflicts.push(relPath);
91
+ else if (stageIsDir)
92
+ conflicts.push(...conflictingPaths(stagePath, targetPath, relPath));
93
+ }
94
+ return conflicts;
95
+ }
96
+ async function fetchStarter(source, into) {
97
+ const local = resolve(source);
98
+ if (existsSync(local) && statSync(local).isDirectory()) {
99
+ // Relative to the starter: a starter that itself sits under a node_modules folder still copies.
100
+ cpSync(local, into, { recursive: true, filter: (path) => !/(^|[\\/])(node_modules|\.git)([\\/]|$)/.test(relative(local, path)) });
101
+ }
102
+ else {
103
+ try {
104
+ await downloadTemplate(source, { dir: into, force: true });
105
+ }
106
+ catch (error) {
107
+ throw new Error(`Could not download the starter from ${source} (${error.message}). Check your connection, or pass --template github:usequeek/theme-starter for the latest.`);
108
+ }
109
+ }
110
+ if (!existsSync(join(into, 'theme/theme.config.ts')))
111
+ throw new UsageError(`${source} is not a Queek theme starter (no theme/theme.config.ts).`);
112
+ }
113
+ function listFiles(dir, root = dir) {
114
+ return readdirSync(dir).flatMap((name) => {
115
+ const path = join(dir, name);
116
+ return statSync(path).isDirectory() ? listFiles(path, root) : [relative(root, path).replace(/\\/g, '/')];
117
+ }).sort();
118
+ }
119
+ /** What the git step does in `target`: nothing (it has .git), skip (no git, or inside a repo), or init. */
120
+ function gitStep(target) {
121
+ if (existsSync(join(target, '.git')))
122
+ return 'present';
123
+ const inside = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], { cwd: target, encoding: 'utf8' });
124
+ if (inside.error)
125
+ return 'no-git';
126
+ return inside.status === 0 ? 'inside' : 'init';
127
+ }
128
+ export async function createTheme(dir, answers, options) {
14
129
  const log = options.log ?? ((line) => console.log(line));
15
- const dir = resolve(options.dir);
16
- if (existsSync(dir) && readdirSync(dir).length > 0) {
17
- throw new Error(`${options.dir} already exists and is not empty. Choose a new folder.`);
18
- }
19
- log(`Creating a Queek theme in ${relative(process.cwd(), dir) || '.'}…`);
20
- await downloadTemplate(options.template ?? STARTER, { dir, force: true });
21
- const manifest = join(dir, 'package.json');
22
- if (existsSync(manifest)) {
23
- const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
24
- pkg.name = basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, '-');
25
- writeFileSync(manifest, `${JSON.stringify(pkg, null, 2)}\n`);
26
- }
27
- const pm = detectPackageManager();
28
- if (options.install !== false) {
29
- log(`Installing dependencies with ${pm}…`);
30
- const result = spawnSync(pm, ['install'], { cwd: dir, stdio: 'inherit', shell: process.platform === 'win32' });
31
- if (result.status !== 0)
32
- throw new Error(`${pm} install failed. Run it yourself in ${options.dir}.`);
33
- }
34
- const run = pm === 'npm' ? 'npm run' : pm;
130
+ const { target, state } = checkTarget(dir, options.force);
131
+ const stage = mkdtempSync(join(tmpdir(), 'queek-theme-'));
132
+ try {
133
+ await fetchStarter(options.template ?? STARTER, stage);
134
+ setupTheme(stage, answers);
135
+ if (options.dryRun) {
136
+ log(`Would create ${dir}:`);
137
+ for (const file of listFiles(stage))
138
+ log(` ${file}`);
139
+ return;
140
+ }
141
+ if (state === 'busy') {
142
+ const conflicts = conflictingPaths(stage, target);
143
+ if (conflicts.length > 0) {
144
+ throw new UsageError(`--force cannot write into ${dir}: these would replace a file with a folder or the reverse: ${conflicts.join(', ')}. Move them first.`);
145
+ }
146
+ const overwritten = listFiles(stage).filter((file) => lstatOrNull(join(target, file)) !== null);
147
+ if (overwritten.length > 0)
148
+ log(`Overwriting: ${overwritten.join(', ')}`);
149
+ try {
150
+ cpSync(stage, target, { recursive: true });
151
+ }
152
+ catch (error) {
153
+ throw new Error(`Could not finish writing ${dir} (${error.message}). Some files may already be written there.`);
154
+ }
155
+ }
156
+ else {
157
+ const existedBefore = existsSync(target);
158
+ const before = new Set(existedBefore ? readdirSync(target) : []);
159
+ try {
160
+ cpSync(stage, target, { recursive: true });
161
+ }
162
+ catch (error) {
163
+ if (existsSync(target)) {
164
+ for (const entry of readdirSync(target)) {
165
+ if (!before.has(entry))
166
+ rmSync(join(target, entry), { recursive: true, force: true });
167
+ }
168
+ if (!existedBefore)
169
+ rmSync(target, { recursive: true, force: true });
170
+ }
171
+ throw new Error(`Could not write ${dir} (${error.message}); nothing was left behind.`);
172
+ }
173
+ }
174
+ }
175
+ finally {
176
+ rmSync(stage, { recursive: true, force: true });
177
+ }
178
+ const shown = relative(process.cwd(), target) || '.';
179
+ const here = shown === '.';
180
+ const where = here ? 'the current folder' : shown;
181
+ if (options.install) {
182
+ log(`Installing dependencies with ${options.pm}…`);
183
+ const result = spawnSync(options.pm, ['install'], { cwd: target, stdio: 'inherit', shell: process.platform === 'win32' });
184
+ if (result.status !== 0) {
185
+ const gitSkipped = options.git && gitStep(target) === 'init';
186
+ throw new Error(`${options.pm} install failed. The theme is in ${where}; run \`${options.pm} install\` there${gitSkipped ? ', then `git init` (skipped because the install failed)' : ''}.`);
187
+ }
188
+ }
189
+ if (options.git) {
190
+ const step = gitStep(target);
191
+ if (step === 'no-git')
192
+ log('git is not installed; skipped git init.');
193
+ else if (step === 'inside')
194
+ log('Already inside a git repository; skipped git init.');
195
+ else if (step === 'init' && spawnSync('git', ['init', '-q'], { cwd: target }).status !== 0)
196
+ log(`git init failed; run it yourself in ${where}.`);
197
+ }
198
+ // `run` for every package manager: Yarn 1's built-in `yarn check` shadows the script.
199
+ const run = `${options.pm} run`;
35
200
  log('');
36
- log('Done. Next:');
37
- log(` cd ${relative(process.cwd(), dir) || '.'}`);
38
- if (options.install === false)
39
- log(` ${pm} install`);
40
- log(` ${run} dev # preview every page at http://localhost:3000`);
41
- log(` ${run} check # check it against the Queek theme contract`);
201
+ log(`Created ${answers.name} in ${where}. Next:`);
202
+ if (!here)
203
+ log(` cd ${shellWord(shown)}`);
204
+ if (!options.install)
205
+ log(` ${options.pm} install`);
206
+ log(` ${run} dev # preview every template`);
207
+ log(` ${run} check # your to-do list: each template's description, its own home and screenshot, your products and photos`);
42
208
  log('');
43
- log('Build the theme in theme/. The contract is docs/THEME.md.');
209
+ log(`To repeat this setup: ${equivalentCommand(options.pm, dir, answers, { template: options.template, install: options.install, git: options.git })}`);
210
+ }
211
+ /** Why `dir` cannot take the theme (`checkTarget`'s message), or null. */
212
+ function targetProblem(dir, force) {
213
+ try {
214
+ checkTarget(dir, force);
215
+ return null;
216
+ }
217
+ catch (error) {
218
+ if (error instanceof UsageError)
219
+ return error.message;
220
+ throw error;
221
+ }
222
+ }
223
+ /**
224
+ * Flags → answers (prompting when a prompter is given) → the theme. Shared by the CLI and `queek-theme init`.
225
+ * With no folder argument, a person at the prompts gets a folder named after the theme's slug (checked
226
+ * with the name, before the next question); a script gets `my-theme`.
227
+ */
228
+ export async function runCreate(flags, prompter, log) {
229
+ const named = flags.dir === undefined && prompter !== null;
230
+ if (!named)
231
+ checkTarget(flags.dir ?? 'my-theme', flags.force); // before any question is asked, not just before any write
232
+ const pm = flags.pm ?? detectPackageManager();
233
+ if (!['npm', 'pnpm', 'yarn', 'bun'].includes(pm))
234
+ throw new UsageError(`--pm must be npm, pnpm, yarn or bun, not "${pm}".`);
235
+ const answers = await resolveAnswers(flags, prompter, named ? (slug) => targetProblem(slug, flags.force) : undefined);
236
+ const dir = flags.dir ?? (named ? answers.slug : 'my-theme');
237
+ await createTheme(dir, answers, { install: flags.install, git: flags.git, pm, dryRun: flags.dryRun, force: flags.force, template: flags.template, log });
44
238
  }
@@ -0,0 +1,13 @@
1
+ /** Business categories: what a vendor picks at setup (R2.7). */
2
+ export declare const SERVICES: readonly string[];
3
+ /** Catalogue keys that are not also a business category: a template for one kind of product. */
4
+ export declare const NICHES: readonly string[];
5
+ export declare const BUSINESS_KEYS: readonly string[];
6
+ export declare const TAGS: readonly string[];
7
+ export declare const RESERVED_SLUGS: readonly string[];
8
+ export declare const RESERVED_PREFIXES: readonly string[];
9
+ /** The business category any key belongs to (`jewelry` → `fashion`). */
10
+ export declare function categoryOf(key: string): string;
11
+ export declare function labelOf(key: string): string;
12
+ /** The closest candidate within a few edits ("jewellery" → "jewelry"), or null. */
13
+ export declare function nearest(value: string, candidates: readonly string[]): string | null;
package/dist/lists.js ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The lists a developer picks from, bundled at build time from the storefront
3
+ * (their source of truth, synced by `yarn tools:sync-lists` there): no network
4
+ * before a question is asked, and the same vocabulary the checker of this
5
+ * release enforces.
6
+ */
7
+ import vocabulary from './data/business-vocabulary.json' with { type: 'json' };
8
+ import labels from './data/business-labels.json' with { type: 'json' };
9
+ import tags from './data/theme-tags.json' with { type: 'json' };
10
+ import reserved from './data/reserved.json' with { type: 'json' };
11
+ const CATALOGUE = vocabulary.catalogue;
12
+ const SUBCATEGORIES = vocabulary.subcategories;
13
+ /** Business categories: what a vendor picks at setup (R2.7). */
14
+ export const SERVICES = vocabulary.services;
15
+ const ROOT_OF = new Map();
16
+ for (const [root, branches] of Object.entries(CATALOGUE)) {
17
+ ROOT_OF.set(root, root);
18
+ for (const branch of branches)
19
+ ROOT_OF.set(branch, root);
20
+ }
21
+ for (const [branch, children] of Object.entries(SUBCATEGORIES)) {
22
+ for (const child of children)
23
+ ROOT_OF.set(child, ROOT_OF.get(branch) ?? branch);
24
+ }
25
+ /** Catalogue keys that are not also a business category: a template for one kind of product. */
26
+ export const NICHES = [...ROOT_OF.keys()].filter((key) => !SERVICES.includes(key));
27
+ export const BUSINESS_KEYS = [...SERVICES, ...NICHES];
28
+ export const TAGS = tags.tags;
29
+ export const RESERVED_SLUGS = reserved.slugs;
30
+ export const RESERVED_PREFIXES = reserved.prefixes;
31
+ /** Catalogue roots that are not a business category, and the category their vendors pick. */
32
+ const ROOT_SERVICE = {
33
+ 'beauty-personal-care': 'beauty-cosmetics',
34
+ 'phones-tablets': 'phones-accessories',
35
+ 'health-wellness': 'health-wellness-store',
36
+ };
37
+ /** The business category any key belongs to (`jewelry` → `fashion`). */
38
+ export function categoryOf(key) {
39
+ if (SERVICES.includes(key))
40
+ return key;
41
+ const root = ROOT_OF.get(key) ?? key;
42
+ return SERVICES.includes(root) ? root : (ROOT_SERVICE[root] ?? root);
43
+ }
44
+ export function labelOf(key) {
45
+ return labels.labels[key] ?? key;
46
+ }
47
+ function distance(a, b) {
48
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
49
+ for (let i = 1; i <= a.length; i++) {
50
+ let previous = row[0];
51
+ row[0] = i;
52
+ for (let j = 1; j <= b.length; j++) {
53
+ const current = row[j];
54
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
55
+ previous = current;
56
+ }
57
+ }
58
+ return row[b.length];
59
+ }
60
+ /** The closest candidate within a few edits ("jewellery" → "jewelry"), or null. */
61
+ export function nearest(value, candidates) {
62
+ let best = null;
63
+ let bestDistance = Math.max(2, Math.floor(value.length / 4)) + 1;
64
+ for (const candidate of candidates) {
65
+ const d = distance(value, candidate);
66
+ if (d < bestDistance)
67
+ [best, bestDistance] = [candidate, d];
68
+ }
69
+ return best;
70
+ }
@@ -0,0 +1,22 @@
1
+ /** `Mọ́ Laundry & Co.` → `mo-laundry-co`: what `yarn theme:pull` accepts, `^[a-z][a-z0-9-]{1,30}$`. */
2
+ export declare function slugify(name: string): string;
3
+ /** Why a slug cannot be used, or null. */
4
+ export declare function slugProblem(slug: string): string | null;
5
+ /** The CSS class prefix: the slug's initials, 2–4 characters, never a Queek theme's own. */
6
+ export declare function prefixFor(slug: string): string;
7
+ export interface TemplatePlan {
8
+ id: string;
9
+ key: string;
10
+ label: string;
11
+ for: string[];
12
+ primary: boolean;
13
+ }
14
+ /**
15
+ * One demo store per business picked. The primary is `default`, the rest are
16
+ * named by their key. A business category makes a general template, a niche a
17
+ * niche one — either way `for` is just that key, so a niche never names a
18
+ * category (R2.7).
19
+ */
20
+ export declare function planTemplates(keys: string[], primary?: string): TemplatePlan[];
21
+ /** The business categories the templates belong to, once each, in order. */
22
+ export declare function defaultCategories(keys: string[]): string[];
package/dist/naming.js ADDED
@@ -0,0 +1,46 @@
1
+ import { RESERVED_PREFIXES, RESERVED_SLUGS, categoryOf, labelOf } from './lists.js';
2
+ /** `Mọ́ Laundry & Co.` → `mo-laundry-co`: what `yarn theme:pull` accepts, `^[a-z][a-z0-9-]{1,30}$`. */
3
+ export function slugify(name) {
4
+ let slug = name.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase()
5
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
6
+ if (/^[0-9]/.test(slug))
7
+ slug = `t-${slug}`;
8
+ return slug.slice(0, 31).replace(/-+$/, '');
9
+ }
10
+ /** Why a slug cannot be used, or null. */
11
+ export function slugProblem(slug) {
12
+ if (!/^[a-z][a-z0-9-]{1,30}$/.test(slug))
13
+ return `"${slug}" must be 2 to 31 characters: lower-case letters, digits and hyphens, starting with a letter.`;
14
+ if (RESERVED_SLUGS.includes(slug))
15
+ return `"${slug}" is one of Queek's own themes. Choose another name.`;
16
+ return null;
17
+ }
18
+ /** The CSS class prefix: the slug's initials, 2–4 characters, never a Queek theme's own. */
19
+ export function prefixFor(slug) {
20
+ if (!/^[a-z][a-z0-9-]*$/.test(slug))
21
+ throw new Error(`prefixFor needs a valid slug, got "${slug}"`);
22
+ const words = slug.split('-').filter(Boolean);
23
+ const initials = words.map((word) => word[0]).join('');
24
+ const candidates = [initials.slice(0, 3), initials.slice(0, 2), slug.replace(/-/g, '').slice(0, 2), slug.replace(/-/g, '').slice(0, 3)];
25
+ for (const letter of 'abcdefghijklmnopqrstuvwxyz')
26
+ candidates.push(`${slug[0]}${letter}`);
27
+ return candidates.find((prefix) => /^[a-z][a-z0-9]{1,3}$/.test(prefix) && !RESERVED_PREFIXES.includes(prefix) && prefix !== 'core') ?? `${slug[0]}q`;
28
+ }
29
+ /**
30
+ * One demo store per business picked. The primary is `default`, the rest are
31
+ * named by their key. A business category makes a general template, a niche a
32
+ * niche one — either way `for` is just that key, so a niche never names a
33
+ * category (R2.7).
34
+ */
35
+ export function planTemplates(keys, primary) {
36
+ const unique = [...new Set(keys)];
37
+ if (unique.length === 0)
38
+ return [];
39
+ const first = primary && unique.includes(primary) ? primary : unique[0];
40
+ const ordered = [first, ...unique.filter((key) => key !== first)];
41
+ return ordered.map((key, index) => ({ id: index === 0 ? 'default' : key, key, label: labelOf(key), for: [key], primary: index === 0 }));
42
+ }
43
+ /** The business categories the templates belong to, once each, in order. */
44
+ export function defaultCategories(keys) {
45
+ return [...new Set(keys.map(categoryOf))];
46
+ }
@@ -0,0 +1,58 @@
1
+ import type { Answers, Assistant, OptionalPage } from './setup.js';
2
+ export declare class UsageError extends Error {
3
+ readonly exitCode = 2;
4
+ }
5
+ export declare class CancelledError extends Error {
6
+ readonly exitCode = 130;
7
+ }
8
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
9
+ export interface Flags {
10
+ dir?: string;
11
+ name?: string;
12
+ templates?: string;
13
+ primary?: string;
14
+ categories?: string;
15
+ tags?: string;
16
+ pages?: string;
17
+ ai?: string;
18
+ noAi?: boolean;
19
+ pm?: string;
20
+ install: boolean;
21
+ git: boolean;
22
+ yes: boolean;
23
+ dryRun: boolean;
24
+ force: boolean;
25
+ /** Where the starter comes from: a giget source or a local folder. Default: the pinned starter. */
26
+ template?: string;
27
+ }
28
+ export interface Prompter {
29
+ /** Ask until `problem` has nothing to say about the name: a bad name must never end the run. */
30
+ name(initial: string, problem: (name: string) => string | undefined): Promise<string>;
31
+ templates(): Promise<string[]>;
32
+ primary(keys: string[]): Promise<string>;
33
+ categories(initial: string[]): Promise<string[]>;
34
+ /** Ask until `problem` has nothing to say about the picks. */
35
+ tags(problem: (tags: string[]) => string | undefined): Promise<string[]>;
36
+ pages(initial: OptionalPage[]): Promise<OptionalPage[]>;
37
+ ai(initial: Assistant[]): Promise<Assistant[]>;
38
+ }
39
+ /** Why a typed theme name cannot be used, or null. */
40
+ export declare function nameProblem(name: string): string | null;
41
+ /**
42
+ * Every answer, from its flag when given, else the prompt (in a terminal), else the default or a usage error.
43
+ * Every flag is checked before the first question, and a question only accepts a usable answer,
44
+ * so no answer is lost after it is given. `folderProblem` (a folder named after the slug) is checked
45
+ * with the name.
46
+ */
47
+ export declare function resolveAnswers(flags: Flags, prompter: Prompter | null, folderProblem?: (slug: string) => string | null): Promise<Answers>;
48
+ /** `text` as one POSIX shell word: quoted only when it has a space or a shell-special character. */
49
+ export declare const shellWord: (text: string) => string;
50
+ /**
51
+ * The command that repeats this setup without a single prompt. npm needs `--` before create's flags.
52
+ * `given` holds the flags that are not answers, repeated only when they were given.
53
+ */
54
+ export declare function equivalentCommand(pm: PackageManager, dir: string, answers: Answers, given?: {
55
+ template?: string;
56
+ install?: boolean;
57
+ git?: boolean;
58
+ }): string;
@@ -0,0 +1,121 @@
1
+ import { basename, resolve } from 'node:path';
2
+ import { BUSINESS_KEYS, SERVICES, TAGS, nearest } from './lists.js';
3
+ import { defaultCategories, planTemplates, prefixFor, slugProblem, slugify } from './naming.js';
4
+ export class UsageError extends Error {
5
+ exitCode = 2;
6
+ }
7
+ export class CancelledError extends Error {
8
+ exitCode = 130;
9
+ }
10
+ const PAGES = ['contact', 'faq'];
11
+ const ASSISTANTS = ['claude', 'gemini'];
12
+ /** A comma-separated flag: trimmed, each value once, in the order first given. */
13
+ const csv = (value) => value === undefined ? undefined : [...new Set(value.split(',').map((item) => item.trim()).filter(Boolean))];
14
+ function checkAll(kind, flag, values, allowed) {
15
+ for (const value of values) {
16
+ if (allowed.includes(value))
17
+ continue;
18
+ const hint = nearest(value, allowed);
19
+ throw new UsageError(`Unknown ${kind} "${value}" in ${flag}${hint ? ` — did you mean "${hint}"?` : `. Choose from: ${allowed.join(', ')}`}`);
20
+ }
21
+ return values;
22
+ }
23
+ function required(flag, allowed) {
24
+ throw new UsageError(`${flag} is required with --yes or without a terminal${allowed ? ` (choose from: ${allowed.join(', ')})` : ''}.`);
25
+ }
26
+ /** Why a typed theme name cannot be used, or null. */
27
+ export function nameProblem(name) {
28
+ if (name.trim().length < 2)
29
+ return 'At least 2 characters.';
30
+ return slugProblem(slugify(name));
31
+ }
32
+ const tagsProblem = (tags) => (tags.length < 1 || tags.length > 6 ? 'Pick 1 to 6 tags.' : undefined);
33
+ /**
34
+ * Every answer, from its flag when given, else the prompt (in a terminal), else the default or a usage error.
35
+ * Every flag is checked before the first question, and a question only accepts a usable answer,
36
+ * so no answer is lost after it is given. `folderProblem` (a folder named after the slug) is checked
37
+ * with the name.
38
+ */
39
+ export async function resolveAnswers(flags, prompter, folderProblem) {
40
+ // Flags first: a typo in one must not cost the answers to the questions before it.
41
+ const keyFlag = csv(flags.templates);
42
+ if (keyFlag) {
43
+ if (keyFlag.length === 0)
44
+ throw new UsageError('Pick at least one business for --templates.');
45
+ checkAll('business', '--templates', keyFlag, BUSINESS_KEYS);
46
+ }
47
+ if (flags.primary !== undefined)
48
+ checkAll('business', '--primary', [flags.primary], BUSINESS_KEYS);
49
+ const categoryFlag = csv(flags.categories);
50
+ if (categoryFlag) {
51
+ if (categoryFlag.length === 0)
52
+ throw new UsageError('Pick at least one business category for --categories.');
53
+ checkAll('category', '--categories', categoryFlag, SERVICES);
54
+ }
55
+ const tagFlag = csv(flags.tags);
56
+ if (tagFlag) {
57
+ if (tagsProblem(tagFlag))
58
+ throw new UsageError('Pick 1 to 6 --tags.');
59
+ checkAll('tag', '--tags', tagFlag, TAGS);
60
+ }
61
+ const pageFlag = csv(flags.pages);
62
+ if (pageFlag && pageFlag.includes('none') && pageFlag.length > 1) {
63
+ throw new UsageError('--pages none cannot be combined with other pages.');
64
+ }
65
+ const pageAnswer = pageFlag?.[0] === 'none' ? [] : pageFlag ? checkAll('page', '--pages', pageFlag, PAGES) : undefined;
66
+ if (flags.noAi && flags.ai !== undefined)
67
+ throw new UsageError('Use --ai or --no-ai, not both.');
68
+ const aiFlag = csv(flags.ai);
69
+ const aiAnswer = flags.noAi ? false : aiFlag ? checkAll('assistant', '--ai', aiFlag, ASSISTANTS) : undefined;
70
+ const initial = basename(resolve(flags.dir ?? 'my-theme'));
71
+ const problemOf = (name) => (nameProblem(name) ?? folderProblem?.(slugify(name))) ?? undefined;
72
+ const name = flags.name ?? (prompter ? await prompter.name(initial, problemOf) : initial);
73
+ const slug = slugify(name);
74
+ const problem = slugProblem(slug) ?? folderProblem?.(slug);
75
+ if (problem)
76
+ throw new UsageError(problem);
77
+ const keys = keyFlag ?? (prompter ? await prompter.templates() : required('--templates', BUSINESS_KEYS));
78
+ if (keys.length === 0)
79
+ throw new UsageError('Pick at least one business for --templates.');
80
+ checkAll('business', '--templates', keys, BUSINESS_KEYS);
81
+ const unique = [...new Set(keys)];
82
+ const primary = flags.primary ?? (prompter && unique.length > 1 && flags.templates === undefined ? await prompter.primary(unique) : unique[0]);
83
+ if (!unique.includes(primary))
84
+ throw new UsageError(`--primary "${primary}" is not one of --templates (${unique.join(', ')}).`);
85
+ const templates = planTemplates(unique, primary);
86
+ const categories = categoryFlag
87
+ ?? (prompter ? await prompter.categories(defaultCategories(templates.map((t) => t.key))) : defaultCategories(templates.map((t) => t.key)));
88
+ if (categories.length === 0)
89
+ throw new UsageError('Pick at least one business category for --categories.');
90
+ checkAll('category', '--categories', categories, SERVICES);
91
+ const tags = tagFlag ?? (prompter ? await prompter.tags(tagsProblem) : required('--tags', TAGS));
92
+ if (tags.length === 0 || tags.length > 6)
93
+ throw new UsageError('Pick 1 to 6 --tags.');
94
+ checkAll('tag', '--tags', tags, TAGS);
95
+ const pages = pageAnswer ?? (prompter ? await prompter.pages([...PAGES]) : [...PAGES]);
96
+ const ai = aiAnswer ?? (prompter ? await prompter.ai([...ASSISTANTS]) : [...ASSISTANTS]);
97
+ return { name, slug, prefix: prefixFor(slug), templates, categories, tags, pages, ai };
98
+ }
99
+ const quote = (text) => `'${text.replace(/'/g, "'\\''")}'`;
100
+ const needsQuoting = (text) => !/^[A-Za-z0-9._/-]+$/.test(text);
101
+ /** `text` as one POSIX shell word: quoted only when it has a space or a shell-special character. */
102
+ export const shellWord = (text) => (needsQuoting(text) ? quote(text) : text);
103
+ /**
104
+ * The command that repeats this setup without a single prompt. npm needs `--` before create's flags.
105
+ * `given` holds the flags that are not answers, repeated only when they were given.
106
+ */
107
+ export function equivalentCommand(pm, dir, answers, given = {}) {
108
+ const flags = [
109
+ `--name ${quote(answers.name)}`,
110
+ `--templates ${answers.templates.map((t) => t.key).join(',')}`,
111
+ `--primary ${answers.templates[0].key}`,
112
+ `--categories ${answers.categories.join(',')}`,
113
+ `--tags ${answers.tags.join(',')}`,
114
+ `--pages ${answers.pages.length ? answers.pages.join(',') : 'none'}`,
115
+ answers.ai === false ? '--no-ai' : `--ai ${answers.ai.join(',')}`,
116
+ ...(given.template !== undefined ? [`--template ${shellWord(given.template)}`] : []),
117
+ ...(given.install === false ? ['--no-install'] : []),
118
+ ...(given.git === false ? ['--no-git'] : []),
119
+ ].join(' ');
120
+ return pm === 'npm' ? `npm create @usequeek/theme@latest ${shellWord(dir)} -- ${flags}` : `${pm} create @usequeek/theme ${shellWord(dir)} ${flags}`;
121
+ }
@@ -0,0 +1,13 @@
1
+ import { type Prompter } from './options.js';
2
+ /**
3
+ * Ask until the answer has no problem, warning each time and starting the next ask from the
4
+ * last answer: clack 1.8's multiselect has no `validate`, and a bad pick must not end the run.
5
+ */
6
+ export declare function askUntil<T>(ask: (previous: T | undefined) => Promise<T>, problem: (value: T) => string | undefined, warn: (message: string) => void): Promise<T>;
7
+ /** Business categories first, then niches: clack 1.8 has no grouped autocomplete, so each hint names its group. */
8
+ export declare const templateOptions: () => {
9
+ value: string;
10
+ label: string;
11
+ hint: string;
12
+ }[];
13
+ export declare function clackPrompter(): Prompter;
@@ -0,0 +1,59 @@
1
+ import * as p from '@clack/prompts';
2
+ import { NICHES, SERVICES, TAGS, categoryOf, labelOf } from './lists.js';
3
+ import { slugify } from './naming.js';
4
+ import { CancelledError } from './options.js';
5
+ function answer(value) {
6
+ if (p.isCancel(value))
7
+ throw new CancelledError('Cancelled. Nothing was written.');
8
+ return value;
9
+ }
10
+ /**
11
+ * Ask until the answer has no problem, warning each time and starting the next ask from the
12
+ * last answer: clack 1.8's multiselect has no `validate`, and a bad pick must not end the run.
13
+ */
14
+ export async function askUntil(ask, problem, warn) {
15
+ let previous;
16
+ for (;;) {
17
+ const value = await ask(previous);
18
+ const issue = problem(value);
19
+ if (issue === undefined)
20
+ return value;
21
+ warn(issue);
22
+ previous = value;
23
+ }
24
+ }
25
+ const businessOption = (key) => ({
26
+ value: key,
27
+ label: labelOf(key),
28
+ hint: SERVICES.includes(key) ? 'business category' : `niche · ${labelOf(categoryOf(key))}`,
29
+ });
30
+ /** Business categories first, then niches: clack 1.8 has no grouped autocomplete, so each hint names its group. */
31
+ export const templateOptions = () => [...SERVICES, ...NICHES].map(businessOption);
32
+ export function clackPrompter() {
33
+ return {
34
+ async name(initial, problem) {
35
+ const typed = answer(await p.text({ message: 'Theme name', placeholder: initial, defaultValue: initial, validate: (v) => problem(v?.trim() || initial) }));
36
+ const name = typed.trim() || initial;
37
+ p.log.info(`Slug: ${slugify(name)}`);
38
+ return name;
39
+ },
40
+ async templates() {
41
+ return answer(await p.autocompleteMultiselect({ message: 'Businesses to make templates for (type to search)', options: templateOptions(), required: true }));
42
+ },
43
+ async primary(keys) {
44
+ return answer(await p.select({ message: 'Which is the primary template (the theme\'s first impression)?', options: keys.map(businessOption) }));
45
+ },
46
+ async categories(initial) {
47
+ return answer(await p.multiselect({ message: 'Business categories the theme serves', options: SERVICES.map((key) => ({ value: key, label: labelOf(key) })), initialValues: initial, required: true }));
48
+ },
49
+ async tags(problem) {
50
+ return askUntil(async (previous) => answer(await p.multiselect({ message: 'Tags: the look (1–6)', options: TAGS.map((tag) => ({ value: tag, label: tag })), initialValues: previous, required: true })), problem, (message) => p.log.warn(message));
51
+ },
52
+ async pages(initial) {
53
+ return answer(await p.multiselect({ message: 'Extra pages (about, sales and landing are always made)', options: [{ value: 'contact', label: 'Contact' }, { value: 'faq', label: 'FAQ' }], initialValues: initial, required: false }));
54
+ },
55
+ async ai(initial) {
56
+ return answer(await p.multiselect({ message: 'AI assistants to set up (AGENTS.md is always written; Codex, Cursor and Copilot read it)', options: [{ value: 'claude', label: 'Claude Code' }, { value: 'gemini', label: 'Gemini CLI' }], initialValues: initial, required: false }));
57
+ },
58
+ };
59
+ }
@@ -0,0 +1,23 @@
1
+ export interface Identity {
2
+ slug: string;
3
+ prefix: string;
4
+ name: string;
5
+ }
6
+ /** The skeleton's identity, as the starter ships it. */
7
+ export declare const SKELETON: Identity;
8
+ /**
9
+ * Rename one file's identity as TOKENS: the root class (`theme-bare`), the demo
10
+ * ids (`demo-bare`, `demo-bare-home`), every class token (`bare-main
11
+ * bare-product` — both), the display name (`Bare`) and the slug (`bare`). The
12
+ * skeleton keeps the English word "bare" out of its copy so every remaining
13
+ * standalone token is identity.
14
+ *
15
+ * The display name and the slug go in ONE pass (an alternation), so a name that
16
+ * holds the old slug as a word ("simply bare") is never rewritten by the slug
17
+ * pass. Nothing the earlier passes write can match it: the slug they write
18
+ * follows a `-` and a class prefix is followed by one, and a token has a `-` on
19
+ * neither side.
20
+ */
21
+ export declare function renameContent(content: string, ext: string, from: Identity, to: Identity): string;
22
+ /** Rename every text file of a theme folder in place. */
23
+ export declare function renameTheme(themeDir: string, from: Identity, to: Identity): void;
package/dist/rename.js ADDED
@@ -0,0 +1,59 @@
1
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { extname, join } from 'node:path';
3
+ /** The skeleton's identity, as the starter ships it. */
4
+ export const SKELETON = { slug: 'bare', prefix: 'bare', name: 'Bare' };
5
+ const TEXT = new Set(['.ts', '.tsx', '.css', '.json', '.md', '.mdx']);
6
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
7
+ /** The display name as a literal of the file it is written into. */
8
+ function literal(ext, text) {
9
+ if (ext === '.json')
10
+ return JSON.stringify(text).slice(1, -1);
11
+ if (ext === '.ts' || ext === '.tsx') {
12
+ return text
13
+ .replace(/\\/g, '\\\\')
14
+ .replace(/'/g, "\\'")
15
+ .replace(/\n/g, '\\n')
16
+ .replace(/\r/g, '\\r')
17
+ .replace(new RegExp(String.fromCharCode(0x2028), 'g'), '\\u2028')
18
+ .replace(new RegExp(String.fromCharCode(0x2029), 'g'), '\\u2029');
19
+ }
20
+ return text;
21
+ }
22
+ /**
23
+ * Rename one file's identity as TOKENS: the root class (`theme-bare`), the demo
24
+ * ids (`demo-bare`, `demo-bare-home`), every class token (`bare-main
25
+ * bare-product` — both), the display name (`Bare`) and the slug (`bare`). The
26
+ * skeleton keeps the English word "bare" out of its copy so every remaining
27
+ * standalone token is identity.
28
+ *
29
+ * The display name and the slug go in ONE pass (an alternation), so a name that
30
+ * holds the old slug as a word ("simply bare") is never rewritten by the slug
31
+ * pass. Nothing the earlier passes write can match it: the slug they write
32
+ * follows a `-` and a class prefix is followed by one, and a token has a `-` on
33
+ * neither side.
34
+ */
35
+ export function renameContent(content, ext, from, to) {
36
+ const nameOrSlug = new RegExp(`(?<![\\w-])(?:(${escape(from.name)})|${escape(from.slug)})(?![\\w-])`, 'g');
37
+ return content
38
+ .replace(new RegExp(`(?<![\\w-])theme-${escape(from.slug)}(?![\\w-])`, 'g'), () => `theme-${to.slug}`)
39
+ .replace(new RegExp(`(?<![\\w-])demo-${escape(from.slug)}(?![\\w])`, 'g'), () => `demo-${to.slug}`)
40
+ .replace(new RegExp(`(?<![\\w-])${escape(from.prefix)}-(?=[\\w$])`, 'g'), () => `${to.prefix}-`)
41
+ .replace(nameOrSlug, (_match, name) => (name !== undefined ? literal(ext, to.name) : to.slug));
42
+ }
43
+ function walk(dir) {
44
+ return readdirSync(dir).flatMap((name) => {
45
+ const path = join(dir, name);
46
+ if (statSync(path).isDirectory())
47
+ return name === 'node_modules' ? [] : walk(path);
48
+ return TEXT.has(extname(name)) ? [path] : [];
49
+ });
50
+ }
51
+ /** Rename every text file of a theme folder in place. */
52
+ export function renameTheme(themeDir, from, to) {
53
+ for (const path of walk(themeDir)) {
54
+ const before = readFileSync(path, 'utf8');
55
+ const after = renameContent(before, extname(path), from, to);
56
+ if (after !== before)
57
+ writeFileSync(path, after);
58
+ }
59
+ }
@@ -0,0 +1,16 @@
1
+ import type { TemplatePlan } from './naming.js';
2
+ export type OptionalPage = 'contact' | 'faq';
3
+ export type Assistant = 'claude' | 'gemini';
4
+ export interface Answers {
5
+ name: string;
6
+ slug: string;
7
+ prefix: string;
8
+ templates: TemplatePlan[];
9
+ categories: string[];
10
+ tags: string[];
11
+ pages: OptionalPage[];
12
+ ai: Assistant[] | false;
13
+ }
14
+ export declare function themeConfigSource(answers: Answers): string;
15
+ /** Turn a downloaded starter into the developer's theme. Pure file work: no network, no install. */
16
+ export declare function setupTheme(projectDir: string, answers: Answers): void;
package/dist/setup.js ADDED
@@ -0,0 +1,100 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { SKELETON, renameTheme } from './rename.js';
4
+ /** Written for every template, whatever the developer picks. */
5
+ const REQUIRED_PAGES = ['home', 'shop', 'about', 'sales', 'landing'];
6
+ /** Must start with the text the check rejects, so no template ships with it. */
7
+ const DESCRIPTION = 'Replace before publishing. Who this template fits, the look, its signature sections and the photos it needs, in at most 300 characters.';
8
+ const ts = (text) => {
9
+ const escaped = text
10
+ .replace(/\\/g, '\\\\')
11
+ .replace(/'/g, "\\'")
12
+ .replace(/\n/g, '\\n')
13
+ .replace(/\r/g, '\\r')
14
+ .replace(new RegExp(String.fromCharCode(0x2028), 'g'), '\\u2028')
15
+ .replace(new RegExp(String.fromCharCode(0x2029), 'g'), '\\u2029');
16
+ return `'${escaped}'`;
17
+ };
18
+ const list = (items) => `[${items.map(ts).join(', ')}]`;
19
+ export function themeConfigSource(answers) {
20
+ const [primary, ...others] = answers.templates;
21
+ const demos = others.map((plan) => ` {\n id: ${ts(plan.id)}, label: ${ts(plan.label)}, for: ${list(plan.for)},\n description: ${ts(DESCRIPTION)},\n },`).join('\n');
22
+ return `const config = {
23
+ name: ${ts(answers.name)},
24
+ slug: ${ts(answers.slug)},
25
+ author: '',
26
+ description: ${ts('Replace before publishing. What this theme is, in one sentence.')},
27
+ version: '0.1.0',
28
+ tags: ${list(answers.tags)},
29
+ categories: ${list(answers.categories)},
30
+ rank: 0,
31
+ // Every demo store is a template (docs/THEME.md#templates). demo.json is the
32
+ // primary. \`for\`: a whole business leads with its category, a niche names only
33
+ // its product keys (docs/business-vocabulary.json).
34
+ default_demo: {
35
+ label: ${ts(primary.label)},
36
+ for: ${list(primary.for)},
37
+ description: ${ts(DESCRIPTION)},
38
+ },
39
+ demos: [
40
+ ${demos}
41
+ ],
42
+ };
43
+
44
+ export default config;
45
+ `;
46
+ }
47
+ function dropMissingPages(items, pages) {
48
+ return items
49
+ ?.filter((item) => item.type !== 'page' || (typeof item.ref === 'string' && pages.has(item.ref)))
50
+ .map((item) => ({ ...item, ...(item.children ? { children: dropMissingPages(item.children, pages) } : {}) }));
51
+ }
52
+ function writeDemoStores(themeDir, answers) {
53
+ const skeleton = JSON.parse(readFileSync(join(themeDir, 'demo.json'), 'utf8'));
54
+ const keep = new Set([...REQUIRED_PAGES, ...answers.pages]);
55
+ for (const plan of answers.templates) {
56
+ const store = structuredClone(skeleton);
57
+ const shopId = plan.primary ? `demo-${answers.slug}` : `demo-${answers.slug}-${plan.id}`;
58
+ store.profile = { ...store.profile, id: shopId };
59
+ for (const product of store.products ?? []) {
60
+ product.shop_id = shopId;
61
+ if (product.shop)
62
+ product.shop = { ...product.shop, id: shopId };
63
+ }
64
+ store.pages = Object.fromEntries(Object.entries(store.pages)
65
+ .filter(([slug]) => keep.has(slug))
66
+ .map(([slug, page]) => [slug, { ...page, ...(typeof page.id === 'string' ? { id: page.id.replace(`demo-${answers.slug}`, shopId) } : {}) }]));
67
+ store.menus = store.menus?.map((menu) => ({ ...menu, items: dropMissingPages(menu.items, keep) }));
68
+ const path = plan.primary ? join(themeDir, 'demo.json') : join(themeDir, 'demos', `${plan.id}.json`);
69
+ mkdirSync(join(themeDir, 'demos'), { recursive: true });
70
+ writeFileSync(path, `${JSON.stringify(store, null, 2)}\n`);
71
+ }
72
+ }
73
+ function keepAssistants(projectDir, ai) {
74
+ const remove = (path) => rmSync(join(projectDir, path), { recursive: true, force: true });
75
+ if (ai === false) {
76
+ for (const path of ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md', '.claude'])
77
+ remove(path);
78
+ return;
79
+ }
80
+ if (!ai.includes('claude')) {
81
+ remove('CLAUDE.md');
82
+ remove('.claude');
83
+ }
84
+ if (!ai.includes('gemini'))
85
+ remove('GEMINI.md');
86
+ }
87
+ /** Turn a downloaded starter into the developer's theme. Pure file work: no network, no install. */
88
+ export function setupTheme(projectDir, answers) {
89
+ const themeDir = join(projectDir, 'theme');
90
+ renameTheme(themeDir, SKELETON, { slug: answers.slug, prefix: answers.prefix, name: answers.name });
91
+ writeFileSync(join(themeDir, 'theme.config.ts'), themeConfigSource(answers));
92
+ writeDemoStores(themeDir, answers);
93
+ rmSync(join(themeDir, 'theme.jpg'), { force: true });
94
+ keepAssistants(projectDir, answers.ai);
95
+ const manifest = join(projectDir, 'package.json');
96
+ if (existsSync(manifest)) {
97
+ const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
98
+ writeFileSync(manifest, `${JSON.stringify({ ...pkg, name: answers.slug }, null, 2)}\n`);
99
+ }
100
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usequeek/create-theme",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "npm create @usequeek/theme — start a Queek storefront theme from the official starter.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "node": ">=22.12.0"
22
22
  },
23
23
  "dependencies": {
24
+ "@clack/prompts": "^1.8.1",
24
25
  "giget": "^3.3.1"
25
26
  },
26
27
  "keywords": [