create-addfox-app 0.1.1-beta.10

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -0
  3. package/dist/cli.js +1015 -0
  4. package/package.json +34 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 addfox
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,18 @@
1
+ <p align="center">
2
+ <img width="200" src="https://raw.githubusercontent.com/addfox/addfox/main/addfox.png" alt="Addfox">
3
+ </p>
4
+
5
+ # create-addfox-app
6
+
7
+ [中文](README-zh_CN.md) | English
8
+
9
+ ---
10
+
11
+ Interactive scaffolder: generates a addfox-based extension project from options (template, package manager, entries, skills).
12
+
13
+ - Commands: `create-addfox-app` or `pnpm create addfox-app` (and npm/yarn/bun equivalents)
14
+ - Flow: (1) select framework (vanilla / vue / react / preact / svelte / solid), (2) language (TypeScript / JavaScript), (3) package manager (pnpm / npm / yarn / bun), (4) entries to include (multi-select), (5) whether to install addfox skills (yes/no). Output to cwd or a given directory. Generated project uses **addfox.config.ts** or **addfox.config.js** with minimal manifest (entry discovery; no built-in entry paths in manifest).
15
+
16
+ ## Templates
17
+
18
+ Scaffold templates live at **repo root** in **`templates/`** (e.g. `template-vanilla-ts`, `template-react-ts`). The CLI downloads the chosen template from the GitHub repo tarball, so the repo must have `templates/` at root and committed. The npm package does not bundle templates; it fetches from GitHub at scaffold time.
package/dist/cli.js ADDED
@@ -0,0 +1,1015 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative, resolve as external_node_path_resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createRequire } from "node:module";
6
+ import { execSync } from "node:child_process";
7
+ import prompts from "prompts";
8
+ import { blue, cyan, dim, gray, green, lightBlue, magenta, red, trueColor, yellow } from "kolorist";
9
+ import minimist from "minimist";
10
+ import { cp, mkdir } from "node:fs/promises";
11
+ import { gunzipSync } from "node:zlib";
12
+ import { detectPackageManager, getExecCommand, getInstallCommand, getRunCommand } from "@addfox/pkg-manager";
13
+ const GITHUB_REPO = "addfox/addfox";
14
+ const TEMPLATE_BASE = "templates";
15
+ function getRepoRoot() {
16
+ const fromDist = external_node_path_resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
17
+ return fromDist;
18
+ }
19
+ function hasLocalTemplate(templateName) {
20
+ const repoRoot = getRepoRoot();
21
+ return existsSync(join(repoRoot, TEMPLATE_BASE, templateName));
22
+ }
23
+ const SKIP_TEMPLATE_PATH_PARTS = new Set([
24
+ "node_modules",
25
+ ".git",
26
+ ".pnpm"
27
+ ]);
28
+ function shouldCopyLocalTemplatePath(src) {
29
+ const normalized = src.split(/[/\\]/);
30
+ for (const part of normalized)if (SKIP_TEMPLATE_PATH_PARTS.has(part)) return false;
31
+ return true;
32
+ }
33
+ async function tryLocalTemplates(templateName, destDir) {
34
+ const repoRoot = getRepoRoot();
35
+ const templatePath = join(repoRoot, TEMPLATE_BASE, templateName);
36
+ if (!existsSync(templatePath)) return false;
37
+ await mkdir(destDir, {
38
+ recursive: true
39
+ });
40
+ await cp(templatePath, destDir, {
41
+ recursive: true,
42
+ filter: (src)=>shouldCopyLocalTemplatePath(src)
43
+ });
44
+ return true;
45
+ }
46
+ function parseTarHeader(buf) {
47
+ if (buf.every((b)=>0 === b)) return null;
48
+ const rawName = buf.subarray(0, 100).toString("utf8").replace(/\0+$/, "");
49
+ const sizeStr = buf.subarray(124, 136).toString("utf8").replace(/\0+$/, "").trim();
50
+ const type = String.fromCharCode(buf[156]);
51
+ const prefix = buf.subarray(345, 500).toString("utf8").replace(/\0+$/, "");
52
+ return {
53
+ name: prefix ? `${prefix}/${rawName}` : rawName,
54
+ size: parseInt(sizeStr, 8) || 0,
55
+ type
56
+ };
57
+ }
58
+ function extractMatchingFiles(tarBuffer, templatePrefix, destDir) {
59
+ let offset = 0;
60
+ while(offset + 512 <= tarBuffer.length){
61
+ const header = parseTarHeader(tarBuffer.subarray(offset, offset + 512));
62
+ offset += 512;
63
+ if (!header) break;
64
+ const dataBlocks = 512 * Math.ceil(header.size / 512);
65
+ const idx = header.name.indexOf(templatePrefix);
66
+ if (-1 !== idx) {
67
+ const relativePath = header.name.substring(idx + templatePrefix.length).replace(/^\//, "");
68
+ if (relativePath) {
69
+ const destPath = join(destDir, relativePath);
70
+ const isDir = "5" === header.type || relativePath.endsWith("/");
71
+ if (isDir) mkdirSync(destPath, {
72
+ recursive: true
73
+ });
74
+ else if ("0" === header.type || "\0" === header.type) {
75
+ mkdirSync(dirname(destPath), {
76
+ recursive: true
77
+ });
78
+ writeFileSync(destPath, tarBuffer.subarray(offset, offset + header.size));
79
+ }
80
+ }
81
+ }
82
+ offset += dataBlocks;
83
+ }
84
+ }
85
+ async function downloadTemplate(templateName, destDir, branch = "main") {
86
+ const url = `https://codeload.github.com/${GITHUB_REPO}/tar.gz/${branch}`;
87
+ const templatePrefix = `${TEMPLATE_BASE}/${templateName}/`;
88
+ const response = await fetch(url);
89
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
90
+ const compressed = Buffer.from(await response.arrayBuffer());
91
+ const tarBuffer = gunzipSync(compressed);
92
+ mkdirSync(destDir, {
93
+ recursive: true
94
+ });
95
+ extractMatchingFiles(tarBuffer, templatePrefix, destDir);
96
+ }
97
+ const FRAMES = [
98
+ "⠋",
99
+ "⠙",
100
+ "⠹",
101
+ "⠸",
102
+ "⠼",
103
+ "⠴",
104
+ "⠦",
105
+ "⠧",
106
+ "⠇",
107
+ "⠏"
108
+ ];
109
+ const INTERVAL_MS = 80;
110
+ function clearSpinnerLine() {
111
+ process.stdout.write("\r\x1b[K");
112
+ }
113
+ function sleep(ms) {
114
+ return new Promise((resolve)=>{
115
+ setTimeout(resolve, ms);
116
+ });
117
+ }
118
+ async function runWithTemplateSpinner(label, fn, options) {
119
+ const minVisibleMs = options?.minVisibleMs ?? 0;
120
+ if (!process.stdout.isTTY) {
121
+ console.log(yellow(`\n ${label}\n`));
122
+ return fn();
123
+ }
124
+ let frameIndex = 0;
125
+ process.stdout.write("\n");
126
+ const timer = setInterval(()=>{
127
+ const frame = FRAMES[frameIndex % FRAMES.length];
128
+ frameIndex += 1;
129
+ process.stdout.write(`\r ${yellow(frame)} ${label}`);
130
+ }, INTERVAL_MS);
131
+ const startedAt = Date.now();
132
+ try {
133
+ const result = await fn();
134
+ const elapsed = Date.now() - startedAt;
135
+ if (elapsed < minVisibleMs) await sleep(minVisibleMs - elapsed);
136
+ return result;
137
+ } finally{
138
+ clearInterval(timer);
139
+ clearSpinnerLine();
140
+ process.stdout.write("\n");
141
+ }
142
+ }
143
+ const STYLE_ENGINES = [
144
+ {
145
+ title: "None",
146
+ value: "none"
147
+ },
148
+ {
149
+ title: "Tailwind CSS",
150
+ value: "tailwindcss"
151
+ },
152
+ {
153
+ title: "UnoCSS",
154
+ value: "unocss"
155
+ },
156
+ {
157
+ title: "Less",
158
+ value: "less"
159
+ },
160
+ {
161
+ title: "Sass (SCSS)",
162
+ value: "sass"
163
+ }
164
+ ];
165
+ const FRAMEWORKS = [
166
+ {
167
+ title: "Vanilla",
168
+ value: "vanilla"
169
+ },
170
+ {
171
+ title: "Vue",
172
+ value: "vue"
173
+ },
174
+ {
175
+ title: "React",
176
+ value: "react"
177
+ },
178
+ {
179
+ title: "Preact",
180
+ value: "preact"
181
+ },
182
+ {
183
+ title: "Svelte",
184
+ value: "svelte"
185
+ },
186
+ {
187
+ title: "Solid",
188
+ value: "solid"
189
+ }
190
+ ];
191
+ function getTemplateName(framework, language) {
192
+ return `template-${framework}-${language}`;
193
+ }
194
+ const PACKAGE_MANAGER_CHOICES = [
195
+ {
196
+ title: "pnpm",
197
+ value: "pnpm"
198
+ },
199
+ {
200
+ title: "npm",
201
+ value: "npm"
202
+ },
203
+ {
204
+ title: "yarn",
205
+ value: "yarn"
206
+ },
207
+ {
208
+ title: "bun",
209
+ value: "bun"
210
+ }
211
+ ];
212
+ const ENTRY_NAMES = [
213
+ "popup",
214
+ "options",
215
+ "background",
216
+ "content",
217
+ "devtools",
218
+ "sidepanel",
219
+ "sandbox",
220
+ "newtab",
221
+ "bookmarks",
222
+ "history",
223
+ "offscreen"
224
+ ];
225
+ const ENTRY_APP_DIRS = ENTRY_NAMES;
226
+ const ENTRY_CHOICES = ENTRY_NAMES.map((name)=>({
227
+ title: name,
228
+ value: name
229
+ }));
230
+ const APP_DIR = "app";
231
+ function filterAppEntries(destDir, selectedEntries) {
232
+ const useAll = selectedEntries.includes("__all__");
233
+ if (useAll) return;
234
+ const keepSet = new Set(selectedEntries);
235
+ const appPath = join(destDir, APP_DIR);
236
+ if (!existsSync(appPath)) return;
237
+ const dirs = readdirSync(appPath, {
238
+ withFileTypes: true
239
+ }).filter((d)=>d.isDirectory()).map((d)=>d.name);
240
+ for (const dir of dirs){
241
+ const isEntryDir = ENTRY_APP_DIRS.includes(dir);
242
+ if (isEntryDir && !keepSet.has(dir)) rmSync(join(appPath, dir), {
243
+ recursive: true
244
+ });
245
+ }
246
+ }
247
+ function getExistingAppEntryDirs(destDir) {
248
+ const appPath = join(destDir, APP_DIR);
249
+ if (!existsSync(appPath)) return [];
250
+ return readdirSync(appPath, {
251
+ withFileTypes: true
252
+ }).filter((d)=>d.isDirectory()).map((d)=>d.name).filter((name)=>ENTRY_APP_DIRS.includes(name));
253
+ }
254
+ function getFrameworkPluginImport(framework) {
255
+ switch(framework){
256
+ case "react":
257
+ return 'import { pluginReact } from "@rsbuild/plugin-react";';
258
+ case "preact":
259
+ return 'import { pluginPreact } from "@rsbuild/plugin-preact";';
260
+ case "vue":
261
+ return 'import { pluginVue } from "@rsbuild/plugin-vue";';
262
+ case "svelte":
263
+ return 'import { pluginSvelte } from "@rsbuild/plugin-svelte";';
264
+ case "solid":
265
+ return 'import { pluginSolid } from "@rsbuild/plugin-solid";';
266
+ default:
267
+ return "";
268
+ }
269
+ }
270
+ function getFrameworkPluginCall(framework) {
271
+ switch(framework){
272
+ case "react":
273
+ return "pluginReact()";
274
+ case "preact":
275
+ return "pluginPreact()";
276
+ case "vue":
277
+ return "pluginVue()";
278
+ case "svelte":
279
+ return "pluginSvelte()";
280
+ case "solid":
281
+ return "pluginSolid()";
282
+ default:
283
+ return null;
284
+ }
285
+ }
286
+ function getStylePlugin(engine) {
287
+ if ("none" === engine || void 0 === engine) return null;
288
+ if ("less" === engine) return {
289
+ importLine: 'import { pluginLess } from "@rsbuild/plugin-less";',
290
+ call: "pluginLess()"
291
+ };
292
+ if ("sass" === engine) return {
293
+ importLine: 'import { pluginSass } from "@rsbuild/plugin-sass";',
294
+ call: "pluginSass()"
295
+ };
296
+ return null;
297
+ }
298
+ const MINIMAL_MANIFEST = ' name: "My Extension",\n version: "1.0.0",\n manifest_version: 3,\n description: "Browser extension built with addfox",\n permissions: ["storage", "activeTab"],';
299
+ function generateAddfoxConfig(framework, _language, styleEngine) {
300
+ const importLines = [];
301
+ const fwImport = getFrameworkPluginImport(framework);
302
+ if (fwImport) importLines.push(fwImport);
303
+ const st = getStylePlugin(styleEngine);
304
+ if (st) importLines.push(st.importLine);
305
+ const pluginCalls = [];
306
+ const fwCall = getFrameworkPluginCall(framework);
307
+ if (fwCall) pluginCalls.push(fwCall);
308
+ if (st) pluginCalls.push(st.call);
309
+ const pluginsLine = pluginCalls.length > 0 ? ` plugins: [${pluginCalls.join(", ")}],` : "";
310
+ const parts = [
311
+ "import { defineConfig } from \"addfox\";",
312
+ importLines.length ? `\n${importLines.join("\n")}\n` : "",
313
+ "const manifest = {",
314
+ MINIMAL_MANIFEST,
315
+ "};",
316
+ "",
317
+ "export default defineConfig({",
318
+ " manifest: { chromium: manifest, firefox: { ...manifest } },",
319
+ ...pluginsLine ? [
320
+ pluginsLine
321
+ ] : [],
322
+ "});"
323
+ ];
324
+ return parts.filter(Boolean).join("\n");
325
+ }
326
+ const UTF8_BOM = "\uFEFF";
327
+ function stripUtf8Bom(text) {
328
+ return text.startsWith(UTF8_BOM) ? text.slice(UTF8_BOM.length) : text;
329
+ }
330
+ function readJsonFile(path) {
331
+ const raw = readFileSync(path, "utf8");
332
+ return JSON.parse(stripUtf8Bom(raw));
333
+ }
334
+ function writeJsonFile(path, data) {
335
+ writeFileSync(path, JSON.stringify(data, null, 2), "utf8");
336
+ }
337
+ const RSTEST_CORE = "^0.9.4";
338
+ const RSTEST_COVERAGE = "^0.3.0";
339
+ const RSTEST_BROWSER = "^0.9.4";
340
+ const PLAYWRIGHT = "^1.58.2";
341
+ const RSDOCTOR_RSPACK = "^1.5.5";
342
+ function getTestExt(language) {
343
+ return "ts" === language ? "ts" : "js";
344
+ }
345
+ function getTestGlob(language) {
346
+ return "ts" === language ? "__tests__/**/*.test.ts" : "__tests__/**/*.test.js";
347
+ }
348
+ function getE2eGlob(language) {
349
+ return "ts" === language ? "__tests__/e2e/**/*.test.ts" : "__tests__/e2e/**/*.test.js";
350
+ }
351
+ function generateRstestConfig(language, testKinds) {
352
+ const hasUnit = testKinds.includes("unit");
353
+ const hasE2e = testKinds.includes("e2e");
354
+ getTestExt(language);
355
+ if (!hasUnit && !hasE2e) return "";
356
+ const header = `import { defineConfig } from "@rstest/core";\n\n`;
357
+ if (hasUnit && !hasE2e) {
358
+ const glob = getTestGlob(language);
359
+ return `${header}export default defineConfig({
360
+ testEnvironment: "node",
361
+ include: ["${glob}"],
362
+ exclude: { patterns: ["**/node_modules/**", "**/dist/**"] },
363
+ root: process.cwd(),
364
+ });
365
+ `;
366
+ }
367
+ if (!hasUnit && hasE2e) {
368
+ const inc = getE2eGlob(language);
369
+ return `${header}export default defineConfig({
370
+ root: process.cwd(),
371
+ projects: [
372
+ {
373
+ name: "browser",
374
+ include: ["${inc}"],
375
+ browser: {
376
+ enabled: true,
377
+ provider: "playwright",
378
+ browser: "chromium",
379
+ },
380
+ },
381
+ ],
382
+ });
383
+ `;
384
+ }
385
+ const unitGlob = getTestGlob(language);
386
+ const e2eInc = getE2eGlob(language);
387
+ return `${header}export default defineConfig({
388
+ root: process.cwd(),
389
+ projects: [
390
+ {
391
+ name: "node",
392
+ testEnvironment: "node",
393
+ include: ["${unitGlob}"],
394
+ exclude: { patterns: ["**/node_modules/**", "**/dist/**", "__tests__/e2e/**"] },
395
+ },
396
+ {
397
+ name: "browser",
398
+ include: ["${e2eInc}"],
399
+ browser: {
400
+ enabled: true,
401
+ provider: "playwright",
402
+ browser: "chromium",
403
+ },
404
+ },
405
+ ],
406
+ });
407
+ `;
408
+ }
409
+ function writeUnitSample(root, language) {
410
+ const ext = getTestExt(language);
411
+ mkdirSync(external_node_path_resolve(root, "__tests__"), {
412
+ recursive: true
413
+ });
414
+ const path = external_node_path_resolve(root, "__tests__", `example.test.${ext}`);
415
+ const body = "ts" === language ? `import { describe, expect, it } from "@rstest/core";
416
+
417
+ describe("example unit tests", () => {
418
+ it("adds numbers", () => {
419
+ expect(1 + 2).toBe(3);
420
+ });
421
+ });
422
+ ` : `import { describe, expect, it } from "@rstest/core";
423
+
424
+ describe("example unit tests", () => {
425
+ it("adds numbers", () => {
426
+ expect(1 + 2).toBe(3);
427
+ });
428
+ });
429
+ `;
430
+ writeFileSync(path, body, "utf-8");
431
+ }
432
+ function writeE2eSample(root, language) {
433
+ const ext = getTestExt(language);
434
+ const dir = external_node_path_resolve(root, "__tests__", "e2e");
435
+ mkdirSync(dir, {
436
+ recursive: true
437
+ });
438
+ const path = external_node_path_resolve(dir, `example.browser.test.${ext}`);
439
+ const body = `import { describe, expect, it } from "@rstest/core";
440
+ import { page } from "@rstest/browser";
441
+
442
+ describe("E2E browser tests", () => {
443
+ it("asserts element in document", async () => {
444
+ document.body.innerHTML = \`<button id="btn">Click me</button>\`;
445
+ await expect
446
+ .element(page.getByRole("button", { name: "Click me" }))
447
+ .toBeVisible();
448
+ });
449
+ });
450
+ `;
451
+ writeFileSync(path, body, "utf-8");
452
+ }
453
+ function mergeDevDeps(pkg, testKinds, installRsdoctor) {
454
+ const dev = pkg.devDependencies ?? {};
455
+ pkg.devDependencies = dev;
456
+ if (testKinds.length > 0) dev["@rstest/core"] = RSTEST_CORE;
457
+ if (testKinds.includes("unit")) dev["@rstest/coverage-istanbul"] = RSTEST_COVERAGE;
458
+ if (testKinds.includes("e2e")) {
459
+ dev["@rstest/browser"] = RSTEST_BROWSER;
460
+ dev.playwright = PLAYWRIGHT;
461
+ }
462
+ if (installRsdoctor) dev["@rsdoctor/rspack-plugin"] = RSDOCTOR_RSPACK;
463
+ }
464
+ function mergeScripts(pkg, testKinds) {
465
+ const scripts = pkg.scripts ?? {};
466
+ pkg.scripts = scripts;
467
+ if (0 === testKinds.length) return;
468
+ scripts.test = "addfox test";
469
+ if (testKinds.includes("unit")) scripts["test:coverage"] = "addfox test --coverage";
470
+ if (testKinds.includes("e2e")) scripts.pretest = "addfox build";
471
+ }
472
+ function applyTestAndReportSetup(root, language, selection) {
473
+ const { testKinds, installRsdoctor } = selection;
474
+ if (0 === testKinds.length && !installRsdoctor) return;
475
+ const pkgPath = external_node_path_resolve(root, "package.json");
476
+ const pkg = readJsonFile(pkgPath);
477
+ mergeDevDeps(pkg, testKinds, installRsdoctor);
478
+ mergeScripts(pkg, testKinds);
479
+ writeJsonFile(pkgPath, pkg);
480
+ if (testKinds.length > 0) {
481
+ const configName = "ts" === language ? "rstest.config.ts" : "rstest.config.js";
482
+ const content = generateRstestConfig(language, testKinds);
483
+ writeFileSync(external_node_path_resolve(root, configName), content, "utf-8");
484
+ if (testKinds.includes("unit")) writeUnitSample(root, language);
485
+ if (testKinds.includes("e2e")) writeE2eSample(root, language);
486
+ }
487
+ }
488
+ const RESET = "\x1b[0m";
489
+ const ORANGE = [
490
+ 255,
491
+ 118,
492
+ 38
493
+ ];
494
+ const PINK = [
495
+ 255,
496
+ 92,
497
+ 186
498
+ ];
499
+ const LOGO_LINES = [
500
+ " █████╗ ██████╗ ██████╗ ███████╗ ██████╗ ██╗ ██╗",
501
+ "██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔═══██╗╚██╗██╔╝",
502
+ "███████║██║ ██║██║ ██║█████╗ ██║ ██║ ╚███╔╝ ",
503
+ "██╔══██║██║ ██║██║ ██║██╔══╝ ██║ ██║ ██╔██╗ ",
504
+ "██║ ██║██████╔╝██████╔╝██║ ╚██████╔╝██╔╝ ██╗",
505
+ "╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝"
506
+ ];
507
+ function lerpChannel(a, b, t) {
508
+ return Math.round(a + (b - a) * t);
509
+ }
510
+ function rgbFg(r, g, b) {
511
+ return `\x1b[38;2;${r};${g};${b}m`;
512
+ }
513
+ function colorizeLine(line) {
514
+ const len = line.length;
515
+ if (0 === len) return "";
516
+ let out = "";
517
+ for(let i = 0; i < len; i++){
518
+ const ch = line[i] ?? "";
519
+ if (" " === ch) {
520
+ out += ch;
521
+ continue;
522
+ }
523
+ const t = len <= 1 ? 0 : i / (len - 1);
524
+ const r = lerpChannel(ORANGE[0], PINK[0], t);
525
+ const g = lerpChannel(ORANGE[1], PINK[1], t);
526
+ const b = lerpChannel(ORANGE[2], PINK[2], t);
527
+ out += rgbFg(r, g, b) + ch;
528
+ }
529
+ return out + RESET;
530
+ }
531
+ function printAddfoxLogo() {
532
+ console.log("");
533
+ for (const line of LOGO_LINES)console.log(colorizeLine(line));
534
+ console.log("");
535
+ }
536
+ const SKIP_STYLE_ENTRIES = new Set([
537
+ "background",
538
+ "content"
539
+ ]);
540
+ const DEPS = {
541
+ tailwindcss: {
542
+ tailwindcss: "^4.1.18",
543
+ "@tailwindcss/postcss": "^4.1.18",
544
+ postcss: "^8.4.32",
545
+ autoprefixer: "^10.4.20"
546
+ },
547
+ unocss: {
548
+ unocss: "^0.62.4",
549
+ "@unocss/postcss": "^0.62.4",
550
+ postcss: "^8.4.32"
551
+ },
552
+ less: {
553
+ "@rsbuild/plugin-less": "^1.6.2",
554
+ less: "^4.2.0"
555
+ },
556
+ sass: {
557
+ "@rsbuild/plugin-sass": "^1.5.1",
558
+ sass: "^1.77.0"
559
+ }
560
+ };
561
+ function styleFileName(engine) {
562
+ if ("tailwindcss" === engine) return "global.css";
563
+ if ("unocss" === engine) return "uno.css";
564
+ if ("less" === engine) return "global.less";
565
+ return "global.scss";
566
+ }
567
+ function listUiEntryScripts(root, language) {
568
+ const appDir = join(root, "app");
569
+ if (!existsSync(appDir)) return [];
570
+ const extOrder = "ts" === language ? [
571
+ ".tsx",
572
+ ".ts",
573
+ ".vue",
574
+ ".svelte"
575
+ ] : [
576
+ ".jsx",
577
+ ".js",
578
+ ".vue",
579
+ ".svelte"
580
+ ];
581
+ const out = [];
582
+ for (const name of readdirSync(appDir)){
583
+ if (SKIP_STYLE_ENTRIES.has(name)) continue;
584
+ const sub = join(appDir, name);
585
+ if (statSync(sub).isDirectory()) for (const ext of extOrder){
586
+ const p = join(sub, `index${ext}`);
587
+ if (existsSync(p)) {
588
+ out.push(p);
589
+ break;
590
+ }
591
+ }
592
+ }
593
+ return out;
594
+ }
595
+ function buildStyleImportLine(entryFile, engine) {
596
+ const entryDir = join(entryFile, "..");
597
+ const stylePath = join(entryDir, "..", "styles", styleFileName(engine));
598
+ const rel = relative(entryDir, stylePath).replace(/\\/g, "/");
599
+ return `import "${rel}";`;
600
+ }
601
+ function prependImportIfMissing(filePath, line) {
602
+ const raw = readFileSync(filePath, "utf8");
603
+ if (raw.includes("/styles/global.") || raw.includes("/styles/uno.css")) return;
604
+ writeFileSync(filePath, `${line}\n${raw}`, "utf8");
605
+ }
606
+ function writeTailwindFiles(root) {
607
+ const dir = join(root, "app", "styles");
608
+ mkdirSync(dir, {
609
+ recursive: true
610
+ });
611
+ writeFileSync(join(dir, "global.css"), '@import "tailwindcss";\n', "utf8");
612
+ writeFileSync(join(root, "postcss.config.mjs"), `export default {
613
+ plugins: {
614
+ "@tailwindcss/postcss": {},
615
+ autoprefixer: {},
616
+ },
617
+ };
618
+ `, "utf8");
619
+ }
620
+ function writeUnoFiles(root) {
621
+ const dir = join(root, "app", "styles");
622
+ mkdirSync(dir, {
623
+ recursive: true
624
+ });
625
+ writeFileSync(join(dir, "uno.css"), `@unocss preflights;
626
+ @unocss default;
627
+ `, "utf8");
628
+ writeFileSync(join(root, "postcss.config.mjs"), `import UnoCSS from "@unocss/postcss";
629
+
630
+ export default {
631
+ plugins: [UnoCSS()],
632
+ };
633
+ `, "utf8");
634
+ writeFileSync(join(root, "uno.config.ts"), `import { defineConfig, presetUno } from "unocss";
635
+
636
+ export default defineConfig({
637
+ content: {
638
+ filesystem: ["./app/**/*.{html,js,ts,jsx,tsx,vue,svelte}"],
639
+ },
640
+ presets: [presetUno()],
641
+ });
642
+ `, "utf8");
643
+ }
644
+ function writeLessSassFiles(root, engine) {
645
+ const dir = join(root, "app", "styles");
646
+ mkdirSync(dir, {
647
+ recursive: true
648
+ });
649
+ "less" === engine ? writeFileSync(join(dir, "global.less"), "body {\n margin: 0;\n}\n", "utf8") : writeFileSync(join(dir, "global.scss"), "body {\n margin: 0;\n}\n", "utf8");
650
+ }
651
+ function mergeDevDependencies(pkg, engine) {
652
+ const dev = pkg.devDependencies ?? {};
653
+ pkg.devDependencies = dev;
654
+ Object.assign(dev, DEPS[engine]);
655
+ }
656
+ function writeEngineFiles(root, engine) {
657
+ if ("tailwindcss" === engine) return void writeTailwindFiles(root);
658
+ if ("unocss" === engine) return void writeUnoFiles(root);
659
+ writeLessSassFiles(root, engine);
660
+ }
661
+ function applyStyleEngine(root, _framework, language, engine) {
662
+ if ("none" === engine) return;
663
+ const pkgPath = join(root, "package.json");
664
+ const pkg = readJsonFile(pkgPath);
665
+ mergeDevDependencies(pkg, engine);
666
+ writeJsonFile(pkgPath, pkg);
667
+ writeEngineFiles(root, engine);
668
+ const entries = listUiEntryScripts(root, language);
669
+ for (const file of entries)prependImportIfMissing(file, buildStyleImportLine(file, engine));
670
+ }
671
+ const cli_require = createRequire(import.meta.url);
672
+ try {
673
+ const figures = cli_require("prompts/lib/util/figures");
674
+ figures.radioOn = "\u25CF";
675
+ figures.radioOff = "\u25CB";
676
+ } catch {}
677
+ const SKILLS_REPO = "addfox/skills";
678
+ const PROMPT_SELECT_HINT = "- Use arrow-keys. Enter to confirm";
679
+ function multiselectInstructions(showToggleAll) {
680
+ return "\nInstructions:\n ↑/↓: Highlight option\n ←/→/[space]: Toggle selection\n" + (showToggleAll ? " a: Toggle all\n" : "") + " Enter to confirm";
681
+ }
682
+ const orange = trueColor(230, 138, 46);
683
+ function getFrameworkChoicesColored() {
684
+ const colors = {
685
+ vanilla: gray,
686
+ vue: green,
687
+ react: cyan,
688
+ preact: yellow,
689
+ svelte: red,
690
+ solid: lightBlue
691
+ };
692
+ return FRAMEWORKS.map((f)=>({
693
+ ...f,
694
+ title: colors[f.value](f.title)
695
+ }));
696
+ }
697
+ function getLanguageChoicesColored() {
698
+ return [
699
+ {
700
+ title: cyan("TypeScript"),
701
+ value: "ts"
702
+ },
703
+ {
704
+ title: yellow("JavaScript"),
705
+ value: "js"
706
+ }
707
+ ];
708
+ }
709
+ function getPackageManagerChoicesColored() {
710
+ const colors = {
711
+ pnpm: orange,
712
+ npm: red,
713
+ yarn: blue,
714
+ bun: green
715
+ };
716
+ return PACKAGE_MANAGER_CHOICES.map((c)=>({
717
+ ...c,
718
+ title: colors[c.value](c.title)
719
+ }));
720
+ }
721
+ function getStyleEngineChoicesColored() {
722
+ const colors = {
723
+ none: dim,
724
+ tailwindcss: cyan,
725
+ unocss: green,
726
+ less: yellow,
727
+ sass: magenta
728
+ };
729
+ return STYLE_ENGINES.map((c)=>({
730
+ ...c,
731
+ title: colors[c.value](c.title)
732
+ }));
733
+ }
734
+ function getVersion() {
735
+ try {
736
+ const pkgPath = external_node_path_resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
737
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
738
+ return pkg.version ?? "0.0.0";
739
+ } catch {
740
+ return "0.0.0";
741
+ }
742
+ }
743
+ function printHelp() {
744
+ const version = getVersion();
745
+ console.log(`
746
+ create-addfox-app v${version}
747
+
748
+ Create a new addfox extension project
749
+
750
+ Usage:
751
+ create-addfox-app [project-name] [options]
752
+
753
+ Options:
754
+ --framework <name> Skip prompt: vanilla | vue | react | preact | svelte | solid
755
+ --language <lang> Skip prompt: js | ts
756
+ --help Show this help message
757
+ --version Show version number
758
+
759
+ Steps: 1) framework 2) style engine 3) language 4) package manager 5) entries
760
+ 6) test setup (optional unit / e2e) 7) Rsdoctor (optional)
761
+ 8) install skills
762
+
763
+ Options (non-interactive / skip prompts when used with --framework + --language):
764
+ --style <name> none | tailwindcss | unocss | less | sass (default: tailwindcss)
765
+ --unit Add rstest unit setup (with --framework and --language)
766
+ --e2e Add rstest E2E (Playwright browser) setup
767
+ --rsdoctor Add @rsdoctor/rspack-plugin (use addfox dev/build --report)
768
+ `);
769
+ }
770
+ const VALID_STYLE_ENGINES = new Set([
771
+ "none",
772
+ "tailwindcss",
773
+ "unocss",
774
+ "less",
775
+ "sass"
776
+ ]);
777
+ function parseStyleEngineArg(raw) {
778
+ const s = "string" == typeof raw ? raw.toLowerCase() : "";
779
+ if (VALID_STYLE_ENGINES.has(s)) return s;
780
+ return "tailwindcss";
781
+ }
782
+ async function confirmOverwrite(dir) {
783
+ const { action } = await prompts({
784
+ type: "select",
785
+ name: "action",
786
+ message: `Directory "${dir}" already exists. What would you like to do?`,
787
+ choices: [
788
+ {
789
+ title: "Cancel",
790
+ value: "cancel"
791
+ },
792
+ {
793
+ title: "Overwrite (replace contents)",
794
+ value: "overwrite"
795
+ }
796
+ ],
797
+ initial: 0,
798
+ hint: PROMPT_SELECT_HINT
799
+ });
800
+ if (void 0 === action) return false;
801
+ return "overwrite" === action;
802
+ }
803
+ async function promptOptions() {
804
+ const res = await prompts([
805
+ {
806
+ type: "select",
807
+ name: "framework",
808
+ message: "Select a framework",
809
+ choices: getFrameworkChoicesColored(),
810
+ hint: PROMPT_SELECT_HINT
811
+ },
812
+ {
813
+ type: "select",
814
+ name: "styleEngine",
815
+ message: "Select a style engine",
816
+ choices: getStyleEngineChoicesColored(),
817
+ hint: PROMPT_SELECT_HINT
818
+ },
819
+ {
820
+ type: "select",
821
+ name: "language",
822
+ message: "Select a language",
823
+ choices: getLanguageChoicesColored(),
824
+ hint: PROMPT_SELECT_HINT
825
+ },
826
+ {
827
+ type: "select",
828
+ name: "packageManager",
829
+ message: "Select package manager",
830
+ choices: getPackageManagerChoicesColored(),
831
+ hint: PROMPT_SELECT_HINT
832
+ },
833
+ {
834
+ type: "multiselect",
835
+ name: "entries",
836
+ message: "Select extension entries",
837
+ choices: ENTRY_CHOICES,
838
+ min: 1,
839
+ hint: "Space to toggle (○ unselected, ● selected)",
840
+ instructions: multiselectInstructions(true)
841
+ }
842
+ ]);
843
+ if (!res.framework || !res.styleEngine || !res.language || !res.packageManager || !res.entries?.length) return null;
844
+ return {
845
+ framework: res.framework,
846
+ styleEngine: res.styleEngine,
847
+ language: res.language,
848
+ packageManager: res.packageManager,
849
+ entries: res.entries
850
+ };
851
+ }
852
+ const TEST_KIND_CHOICES = [
853
+ {
854
+ title: "Unit — rstest (Node)",
855
+ value: "unit"
856
+ },
857
+ {
858
+ title: "E2E — rstest + Playwright (browser)",
859
+ value: "e2e"
860
+ }
861
+ ];
862
+ async function promptTestAndReport() {
863
+ const testRes = await prompts({
864
+ type: "multiselect",
865
+ name: "testKinds",
866
+ message: "Initialize test config? (optional)",
867
+ choices: TEST_KIND_CHOICES,
868
+ min: 0,
869
+ hint: "Space toggles — leave empty to skip",
870
+ instructions: multiselectInstructions(true)
871
+ });
872
+ if (void 0 === testRes.testKinds) return null;
873
+ const docRes = await prompts({
874
+ type: "select",
875
+ name: "installRsdoctor",
876
+ message: "Install Rsdoctor (@rsdoctor/rspack-plugin) for bundle analysis? After install, use addfox dev or addfox build with --report.",
877
+ choices: [
878
+ {
879
+ title: "Yes",
880
+ value: true
881
+ },
882
+ {
883
+ title: "No",
884
+ value: false
885
+ }
886
+ ],
887
+ initial: 0,
888
+ hint: PROMPT_SELECT_HINT
889
+ });
890
+ if (void 0 === docRes.installRsdoctor) return null;
891
+ return {
892
+ testKinds: testRes.testKinds ?? [],
893
+ installRsdoctor: Boolean(docRes.installRsdoctor)
894
+ };
895
+ }
896
+ function resolveTestSelectionFromArgv(argv) {
897
+ const kinds = [];
898
+ if (argv.unit) kinds.push("unit");
899
+ if (argv.e2e) kinds.push("e2e");
900
+ return {
901
+ testKinds: kinds,
902
+ installRsdoctor: Boolean(argv.rsdoctor)
903
+ };
904
+ }
905
+ function updatePackageName(destDir, projectName) {
906
+ const pkgPath = external_node_path_resolve(destDir, "package.json");
907
+ if (!existsSync(pkgPath)) return;
908
+ const pkg = readJsonFile(pkgPath);
909
+ pkg.name = projectName.replace(/\s+/g, "-").toLowerCase();
910
+ writeJsonFile(pkgPath, pkg);
911
+ }
912
+ async function main() {
913
+ const argv = minimist(process.argv.slice(2));
914
+ if (argv.help || argv.h) return void printHelp();
915
+ if (argv.version || argv.v) return void console.log(getVersion());
916
+ const targetDir = argv._[0] ?? "my-extension";
917
+ const cliFramework = argv.framework;
918
+ const cliLanguage = argv.language;
919
+ printAddfoxLogo();
920
+ console.log(blue("\n Create Addfox App\n"));
921
+ const root = external_node_path_resolve(process.cwd(), targetDir);
922
+ if (existsSync(root)) {
923
+ const confirmed = await confirmOverwrite(targetDir);
924
+ if (!confirmed) process.exit(0);
925
+ rmSync(root, {
926
+ recursive: true,
927
+ force: true
928
+ });
929
+ }
930
+ const options = cliFramework && cliLanguage ? {
931
+ framework: cliFramework,
932
+ styleEngine: parseStyleEngineArg(argv.style),
933
+ language: cliLanguage,
934
+ packageManager: detectPackageManager(),
935
+ entries: [
936
+ "__all__"
937
+ ]
938
+ } : await promptOptions();
939
+ if (!options) process.exit(0);
940
+ const testSelection = cliFramework && cliLanguage ? resolveTestSelectionFromArgv(argv) : await promptTestAndReport();
941
+ if (!testSelection) process.exit(0);
942
+ const pm = options.packageManager;
943
+ const templateName = getTemplateName(options.framework, options.language);
944
+ const useLocalTemplate = hasLocalTemplate(templateName);
945
+ const templateLabel = useLocalTemplate ? "Copying local template..." : "Downloading template...";
946
+ const LOCAL_TEMPLATE_SPINNER_MIN_MS = 800;
947
+ try {
948
+ await runWithTemplateSpinner(templateLabel, async ()=>{
949
+ await new Promise((resolve)=>{
950
+ setImmediate(resolve);
951
+ });
952
+ if (await tryLocalTemplates(templateName, root)) return;
953
+ await downloadTemplate(templateName, root);
954
+ }, useLocalTemplate ? {
955
+ minVisibleMs: LOCAL_TEMPLATE_SPINNER_MIN_MS
956
+ } : void 0);
957
+ } catch (err) {
958
+ console.error(red(`\n Failed to download template: ${err.message}\n`));
959
+ process.exit(1);
960
+ }
961
+ const useAllEntries = options.entries.includes("__all__");
962
+ const existingDirs = getExistingAppEntryDirs(root);
963
+ const effectiveEntries = useAllEntries ? [
964
+ "__all__"
965
+ ] : options.entries.filter((e)=>"__all__" !== e && existingDirs.includes(e));
966
+ if (!useAllEntries && effectiveEntries.length > 0) filterAppEntries(root, effectiveEntries);
967
+ const configExt = "ts" === options.language ? "ts" : "js";
968
+ const configPath = external_node_path_resolve(root, `addfox.config.${configExt}`);
969
+ const configContent = generateAddfoxConfig(options.framework, options.language, options.styleEngine);
970
+ writeFileSync(configPath, configContent, "utf-8");
971
+ updatePackageName(root, targetDir);
972
+ applyStyleEngine(root, options.framework, options.language, options.styleEngine);
973
+ applyTestAndReportSetup(root, options.language, testSelection);
974
+ const installCmd = getInstallCommand(pm);
975
+ const devCmd = getRunCommand(pm, "dev");
976
+ const { installSkills } = await prompts({
977
+ type: "select",
978
+ name: "installSkills",
979
+ message: "Install addfox skills?",
980
+ choices: [
981
+ {
982
+ title: "Yes",
983
+ value: true
984
+ },
985
+ {
986
+ title: "No",
987
+ value: false
988
+ }
989
+ ],
990
+ initial: 0,
991
+ hint: PROMPT_SELECT_HINT
992
+ });
993
+ if (true === installSkills) {
994
+ const execCmd = getExecCommand(pm);
995
+ const fullCmd = `${execCmd} skills add ${SKILLS_REPO}`;
996
+ console.log(yellow("\n Running: " + fullCmd + "\n"));
997
+ try {
998
+ execSync(fullCmd, {
999
+ cwd: root,
1000
+ stdio: "inherit"
1001
+ });
1002
+ } catch {
1003
+ console.log(dim(" (Skills install skipped or failed; you can run it later.)\n"));
1004
+ }
1005
+ }
1006
+ console.log(green("\n ✓ Project created successfully\n"));
1007
+ console.log(dim(" Next steps:\n"));
1008
+ console.log(` cd ${targetDir}`);
1009
+ console.log(` ${installCmd}`);
1010
+ console.log(` ${devCmd}\n`);
1011
+ }
1012
+ main().catch((e)=>{
1013
+ console.error(e);
1014
+ process.exit(1);
1015
+ });
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "create-addfox-app",
3
+ "version": "0.1.1-beta.10",
4
+ "description": "Interactive scaffolder for addfox extension projects",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "create-addfox-app": "./dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "LICENSE"
13
+ ],
14
+ "dependencies": {
15
+ "chalk": "^5.3.0",
16
+ "prompts": "^2.4.2",
17
+ "kolorist": "^1.8.0",
18
+ "minimist": "^1.2.8",
19
+ "@addfox/pkg-manager": "0.1.1-beta.7"
20
+ },
21
+ "devDependencies": {
22
+ "@rslib/core": "^0.20.0",
23
+ "@rstest/core": "^0.9.4",
24
+ "@rstest/coverage-istanbul": "^0.3.0",
25
+ "@types/node": "^20.0.0",
26
+ "typescript": "^5.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "rslib build",
30
+ "start": "node dist/cli.js",
31
+ "test": "rstest run",
32
+ "test:coverage": "rstest run --coverage"
33
+ }
34
+ }