@bagelink/workspace 1.10.7 → 1.10.11

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/dist/bin/bgl.mjs CHANGED
@@ -1,18 +1,804 @@
1
1
  #!/usr/bin/env node
2
+ import { resolve } from 'node:path';
2
3
  import process from 'node:process';
3
- import { i as initWorkspace, g as generateWorkspaceConfig, h as addProject, l as listProjects, k as isWorkspace, d as setupLint, f as generateSDKForWorkspace, e as generateSDK } from '../shared/workspace.DfYoqH33.mjs';
4
- import 'node:fs';
5
- import 'node:path';
6
- import 'prompts';
4
+ import { spawn } from 'node:child_process';
5
+ import { l as listProjects, w as writeNetlifyConfig, i as initWorkspace, a as addProject } from '../shared/workspace.Bc_dpzhA.mjs';
6
+ import { existsSync, readFileSync, readdirSync, writeFileSync, unlinkSync, mkdirSync } from 'node:fs';
7
+ import prompts from 'prompts';
8
+
9
+ async function runBuild(filter, additionalArgs = []) {
10
+ const argsStr = additionalArgs.length > 0 ? ` -- ${additionalArgs.join(" ")}` : "";
11
+ const resolvedFilters = resolveFilters$1(filter);
12
+ if (!resolvedFilters || resolvedFilters.length === 0) return 1;
13
+ const filterArgs = resolvedFilters.map((f) => `--filter '${f}'`).join(" ");
14
+ const command = `bun run ${filterArgs} build${argsStr}`;
15
+ const proc = spawn(command, {
16
+ cwd: process.cwd(),
17
+ stdio: "inherit",
18
+ shell: true
19
+ });
20
+ proc.on("error", (error) => {
21
+ console.error("Failed to start build:", error.message);
22
+ });
23
+ return new Promise((resolve, reject) => {
24
+ proc.on("exit", (code) => {
25
+ resolve(code || 0);
26
+ });
27
+ proc.on("error", reject);
28
+ });
29
+ }
30
+ function resolveFilters$1(filter) {
31
+ if (filter) return [filter];
32
+ const projects = listProjects();
33
+ if (projects.length === 0) {
34
+ console.error("No projects found");
35
+ return null;
36
+ }
37
+ return projects.map((p) => `./${p}`);
38
+ }
39
+
40
+ function isWorkspace(root = process.cwd()) {
41
+ const packageJsonPath = resolve(root, "package.json");
42
+ if (existsSync(packageJsonPath)) {
43
+ try {
44
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
45
+ if (packageJson.workspaces !== void 0) {
46
+ return true;
47
+ }
48
+ } catch {
49
+ }
50
+ }
51
+ try {
52
+ const items = readdirSync(root, { withFileTypes: true });
53
+ const projectDirs = items.filter(
54
+ (item) => item.isDirectory() && item.name !== "node_modules" && item.name !== "shared" && item.name !== ".git" && !item.name.startsWith(".") && existsSync(resolve(root, item.name, "package.json"))
55
+ );
56
+ return projectDirs.length >= 2;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ const servers = /* @__PURE__ */ new Map();
63
+ const projectToPort = /* @__PURE__ */ new Map();
64
+ const seenLines = /* @__PURE__ */ new Set();
65
+ const START_PORT = 5173;
66
+ const colors = {
67
+ reset: "\x1B[0m",
68
+ cyan: "\x1B[36m",
69
+ green: "\x1B[32m",
70
+ yellow: "\x1B[33m",
71
+ dim: "\x1B[2m",
72
+ red: "\x1B[31m"
73
+ };
74
+ function clearAndPrintServers() {
75
+ if (servers.size > 0) {
76
+ process.stdout.write("\x1B[2J\x1B[H");
77
+ }
78
+ console.log(`${colors.cyan}\u{1F680} Development Servers${colors.reset}
79
+ `);
80
+ const sortedServers = Array.from(servers.entries()).sort((a, b) => a[1].order - b[1].order);
81
+ for (const [name, info] of sortedServers) {
82
+ const url = `http://localhost:${info.actualPort ?? info.assignedPort}`;
83
+ if (info.status === "ready") {
84
+ console.log(`${colors.green}\u25CF${colors.reset} ${colors.cyan}${name}${colors.reset} ${colors.dim}\u2192${colors.reset} ${url}`);
85
+ } else {
86
+ console.log(`${colors.yellow}\u25CB${colors.reset} ${colors.dim}${name} (starting...)${colors.reset} ${colors.dim}${url}${colors.reset}`);
87
+ }
88
+ }
89
+ console.log("");
90
+ }
91
+ async function runDev(filter, additionalArgs = []) {
92
+ const argsStr = additionalArgs.length > 0 ? ` -- ${additionalArgs.join(" ")}` : "";
93
+ const resolvedFilters = resolveFilters(filter);
94
+ if (!resolvedFilters || resolvedFilters.length === 0) return 1;
95
+ const projectNames = resolvedFilters.map((f) => f.replace("./", "")).sort();
96
+ projectNames.forEach((name, index) => {
97
+ const assignedPort = START_PORT + index;
98
+ servers.set(name, {
99
+ name,
100
+ assignedPort,
101
+ status: "starting",
102
+ order: index
103
+ });
104
+ projectToPort.set(name, assignedPort);
105
+ });
106
+ clearAndPrintServers();
107
+ const filterArgs = resolvedFilters.map((f) => `--filter '${f}'`).join(" ");
108
+ projectNames.join(", ");
109
+ const command = `bun run ${filterArgs} dev${argsStr}`;
110
+ const proc = spawn(command, {
111
+ cwd: process.cwd(),
112
+ stdio: ["inherit", "pipe", "pipe"],
113
+ shell: true
114
+ });
115
+ let stdoutBuffer = "";
116
+ let stderrBuffer = "";
117
+ function processLine(line) {
118
+ if (!line.trim()) return;
119
+ if (seenLines.has(line)) return;
120
+ seenLines.add(line);
121
+ const portMatch = line.match(/Local:\s+http:\/\/localhost:(\d+)/);
122
+ if (portMatch) {
123
+ const port = Number.parseInt(portMatch[1], 10);
124
+ const projectInLine = line.match(/^([\w-]+)\s+dev:/);
125
+ if (projectInLine) {
126
+ const name = projectInLine[1];
127
+ const info = servers.get(name);
128
+ if (info && !info.actualPort) {
129
+ info.actualPort = port;
130
+ info.status = "ready";
131
+ clearAndPrintServers();
132
+ }
133
+ }
134
+ }
135
+ }
136
+ proc.stdout?.setEncoding("utf8");
137
+ proc.stderr?.setEncoding("utf8");
138
+ proc.stdout?.on("data", (data) => {
139
+ if (servers.size === 0) {
140
+ console.log(`${colors.dim}Receiving output...${colors.reset}`);
141
+ }
142
+ stdoutBuffer += data;
143
+ const lines = stdoutBuffer.split("\n");
144
+ stdoutBuffer = lines.pop() || "";
145
+ for (const line of lines) {
146
+ processLine(line);
147
+ }
148
+ });
149
+ proc.stderr?.on("data", (data) => {
150
+ stderrBuffer += data;
151
+ const lines = stderrBuffer.split("\n");
152
+ stderrBuffer = lines.pop() || "";
153
+ for (const line of lines) {
154
+ processLine(line);
155
+ }
156
+ });
157
+ proc.on("error", (error) => {
158
+ console.error(`${colors.red}Failed to start dev servers:${colors.reset}`, error.message);
159
+ });
160
+ process.on("SIGINT", () => {
161
+ proc.kill("SIGINT");
162
+ process.exit(0);
163
+ });
164
+ return new Promise((resolve, reject) => {
165
+ proc.on("exit", (code) => {
166
+ resolve(code || 0);
167
+ });
168
+ proc.on("error", reject);
169
+ });
170
+ }
171
+ function resolveFilters(filter) {
172
+ if (filter) return [filter];
173
+ const projects = listProjects();
174
+ if (projects.length === 0) {
175
+ console.error("No projects found");
176
+ return null;
177
+ }
178
+ return projects.map((p) => `./${p}`);
179
+ }
180
+
181
+ async function generateWorkspaceConfig(root = process.cwd(), configFile = "bgl.config.ts") {
182
+ console.log("\n\u{1F527} No bgl.config.ts found. Let's create one!\n");
183
+ const response = await prompts([
184
+ {
185
+ type: "text",
186
+ name: "projectId",
187
+ message: "What is your Bagel project ID?",
188
+ initial: "my-project",
189
+ validate: (value) => value.length > 0 ? true : "Project ID is required"
190
+ },
191
+ {
192
+ type: "confirm",
193
+ name: "useCustomHost",
194
+ message: "Use custom production host?",
195
+ initial: false
196
+ },
197
+ {
198
+ type: (prev) => prev ? "text" : null,
199
+ name: "customHost",
200
+ message: "Enter production host URL:",
201
+ initial: "https://api.example.com"
202
+ }
203
+ ]);
204
+ if (!response || !response.projectId) {
205
+ console.log("\n\u274C Config generation cancelled.\n");
206
+ process.exit(1);
207
+ }
208
+ const productionHost = response.useCustomHost === true ? response.customHost : `https://${response.projectId}.bagel.to`;
209
+ const configContent = `import { defineWorkspace } from '@bagelink/workspace'
210
+ import type { WorkspaceConfig, WorkspaceEnvironment } from '@bagelink/workspace'
211
+
212
+ /**
213
+ * Define your workspace environments
214
+ * You can add as many custom environments as needed (e.g., 'staging', 'preview')
215
+ * Use --mode flag to switch: bgl dev --mode <env_name>
216
+ */
217
+ const configs: Record<WorkspaceEnvironment, WorkspaceConfig> = {
218
+ localhost: {
219
+ host: 'http://localhost:8000',
220
+ proxy: '/api', // Optional: remove to skip proxy setup
221
+ openapi_url: 'http://localhost:8000/openapi.json',
222
+ },
223
+ development: {
224
+ host: '${productionHost}',
225
+ proxy: '/api',
226
+ openapi_url: '${productionHost}/openapi.json',
227
+ },
228
+ production: {
229
+ host: '${productionHost}',
230
+ proxy: '/api',
231
+ openapi_url: '${productionHost}/openapi.json',
232
+ },
233
+ }
234
+
235
+ export default defineWorkspace(configs)
236
+ `;
237
+ const configPath = resolve(root, configFile);
238
+ writeFileSync(configPath, configContent, "utf-8");
239
+ console.log(`
240
+ \u2705 Created ${configFile}`);
241
+ console.log(` Production host: ${productionHost}`);
242
+ console.log(` Local dev host: http://localhost:8000
243
+ `);
244
+ const setupResponse = await prompts([
245
+ {
246
+ type: "confirm",
247
+ name: "updatePackageJson",
248
+ message: "Add/update dev scripts in package.json?",
249
+ initial: true
250
+ },
251
+ {
252
+ type: "confirm",
253
+ name: "updateViteConfig",
254
+ message: "Create/update vite.config.ts?",
255
+ initial: true
256
+ },
257
+ {
258
+ type: "confirm",
259
+ name: "createTsConfig",
260
+ message: "Create tsconfig.app.json with path aliases?",
261
+ initial: true
262
+ },
263
+ {
264
+ type: "confirm",
265
+ name: "generateNetlify",
266
+ message: "Generate netlify.toml for deployment?",
267
+ initial: true
268
+ }
269
+ ]);
270
+ if (setupResponse.updatePackageJson) {
271
+ updatePackageJsonScripts(root);
272
+ }
273
+ if (setupResponse.updateViteConfig) {
274
+ updateViteConfig(root);
275
+ }
276
+ if (setupResponse.createTsConfig) {
277
+ createTsConfig(root);
278
+ }
279
+ if (setupResponse.generateNetlify) {
280
+ const prodConfig = {
281
+ host: productionHost,
282
+ proxy: "/api"
283
+ };
284
+ writeNetlifyConfig(prodConfig, resolve(root, "netlify.toml"));
285
+ }
286
+ console.log("\n\u{1F4A1} You can edit these files to customize your configuration.\n");
287
+ }
288
+ function updatePackageJsonScripts(root) {
289
+ const packageJsonPath = resolve(root, "package.json");
290
+ if (!existsSync(packageJsonPath)) {
291
+ console.log("\u26A0\uFE0F No package.json found, skipping script update");
292
+ return;
293
+ }
294
+ try {
295
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
296
+ if (!packageJson.scripts) {
297
+ packageJson.scripts = {};
298
+ }
299
+ const scriptsToAdd = {
300
+ "dev": "vite",
301
+ "dev:local": "vite --mode localhost",
302
+ "build": "vite build",
303
+ "preview": "vite preview"
304
+ };
305
+ let modified = false;
306
+ for (const [key, value] of Object.entries(scriptsToAdd)) {
307
+ if (key === "dev" || key === "dev:local") {
308
+ if (packageJson.scripts[key] !== value) {
309
+ packageJson.scripts[key] = value;
310
+ modified = true;
311
+ }
312
+ } else {
313
+ if (!packageJson.scripts[key]) {
314
+ packageJson.scripts[key] = value;
315
+ modified = true;
316
+ }
317
+ }
318
+ }
319
+ if (modified) {
320
+ writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
321
+ `, "utf-8");
322
+ console.log("\u2705 Updated package.json with dev scripts");
323
+ } else {
324
+ console.log("\u2139\uFE0F Scripts already up to date in package.json");
325
+ }
326
+ } catch (error) {
327
+ console.error("\u274C Failed to update package.json:", error);
328
+ }
329
+ }
330
+ function createTsConfig(root) {
331
+ const tsConfigPath = resolve(root, "tsconfig.app.json");
332
+ const tsConfigExists = existsSync(tsConfigPath);
333
+ if (tsConfigExists) {
334
+ console.log("\u26A0\uFE0F tsconfig.app.json already exists, skipping");
335
+ return;
336
+ }
337
+ const tsConfigContent = `{
338
+ "extends": "../tsconfig.json",
339
+ "compilerOptions": {
340
+ "composite": true,
341
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
342
+ "baseUrl": ".",
343
+ "paths": {
344
+ "@/*": ["./src/*"],
345
+ "@shared/*": ["../shared/*"]
346
+ }
347
+ },
348
+ "include": ["src/**/*", "src/**/*.vue"],
349
+ "exclude": ["node_modules"]
350
+ }
351
+ `;
352
+ writeFileSync(tsConfigPath, tsConfigContent, "utf-8");
353
+ console.log("\u2705 Created tsconfig.app.json");
354
+ }
355
+ function updateViteConfig(root) {
356
+ const viteConfigPath = resolve(root, "vite.config.ts");
357
+ const viteConfigExists = existsSync(viteConfigPath);
358
+ if (viteConfigExists) {
359
+ const existingConfig = readFileSync(viteConfigPath, "utf-8");
360
+ if (existingConfig.includes("@bagelink/workspace")) {
361
+ console.log("\u2139\uFE0F vite.config.ts already configured");
362
+ return;
363
+ }
364
+ console.log("\u26A0\uFE0F vite.config.ts exists. Please manually add the bagelink plugin:");
365
+ console.log("");
366
+ console.log(" import { bagelink } from '@bagelink/workspace/vite'");
367
+ console.log(" import workspace from './bgl.config'");
368
+ console.log("");
369
+ console.log(" plugins: [");
370
+ console.log(" vue(),");
371
+ console.log(" bagelink({ workspace }),");
372
+ console.log(" ]");
373
+ console.log("");
374
+ return;
375
+ }
376
+ const viteConfigContent = `import { defineConfig } from 'vite'
377
+ import vue from '@vitejs/plugin-vue'
378
+ import { bagelink } from '@bagelink/workspace/vite'
379
+ import workspace from './bgl.config'
380
+
381
+ // https://vitejs.dev/config/
382
+ export default defineConfig({
383
+ plugins: [
384
+ vue(),
385
+ bagelink({ workspace }),
386
+ ],
387
+ })
388
+ `;
389
+ writeFileSync(viteConfigPath, viteConfigContent, "utf-8");
390
+ console.log("\u2705 Created vite.config.ts");
391
+ }
392
+
393
+ const REDUNDANT_FILES = [
394
+ // Old ESLint configs
395
+ ".eslintrc",
396
+ ".eslintrc.json",
397
+ ".eslintrc.js",
398
+ ".eslintrc.cjs",
399
+ ".eslintrc.yaml",
400
+ ".eslintrc.yml",
401
+ // Oxlint
402
+ "oxlint.json",
403
+ // Old Prettier configs (we create .prettierrc)
404
+ "prettier.config.js",
405
+ "prettier.config.cjs",
406
+ "prettier.config.mjs",
407
+ ".prettierrc.json",
408
+ ".prettierrc.yaml",
409
+ ".prettierrc.yml",
410
+ ".prettierrc.js",
411
+ ".prettierrc.cjs",
412
+ ".prettierrc.mjs",
413
+ ".prettierrc.toml"
414
+ ];
415
+ async function setupLint(root = process.cwd(), isWorkspace = false) {
416
+ console.log("\n\u{1F50D} Setting up linting...\n");
417
+ const response = await prompts([
418
+ {
419
+ type: "multiselect",
420
+ name: "configs",
421
+ message: "Select configurations to set up:",
422
+ choices: [
423
+ { title: "ESLint", value: "eslint", selected: true },
424
+ { title: "Prettier", value: "prettier", selected: true },
425
+ { title: "EditorConfig", value: "editorconfig", selected: true },
426
+ { title: "Git Hooks", value: "githooks", selected: false }
427
+ ]
428
+ },
429
+ {
430
+ type: "confirm",
431
+ name: "cleanRedundant",
432
+ message: "Clean up redundant lint config files?",
433
+ initial: true
434
+ },
435
+ {
436
+ type: "confirm",
437
+ name: "installDeps",
438
+ message: "Install dependencies?",
439
+ initial: true
440
+ }
441
+ ]);
442
+ if (!response || !response.configs) {
443
+ console.log("\n\u274C Setup cancelled.\n");
444
+ process.exit(1);
445
+ }
446
+ const { configs, cleanRedundant, installDeps } = response;
447
+ if (cleanRedundant) {
448
+ await cleanRedundantFiles(root);
449
+ }
450
+ if (configs.includes("eslint")) {
451
+ createEslintConfig(root, isWorkspace);
452
+ }
453
+ if (configs.includes("prettier")) {
454
+ createPrettierConfig(root);
455
+ }
456
+ if (configs.includes("editorconfig")) {
457
+ createEditorConfig(root);
458
+ }
459
+ if (configs.includes("githooks")) {
460
+ createGitHooks(root);
461
+ }
462
+ updatePackageJsonLint(root, configs);
463
+ if (installDeps) {
464
+ console.log("\n\u{1F4E6} Installing dependencies...");
465
+ console.log("Run: bun add -D @bagelink/lint-config eslint prettier typescript");
466
+ }
467
+ console.log("\n\u2705 Linting setup complete!");
468
+ console.log("\nAvailable commands:");
469
+ console.log(" bun run lint - Run linter");
470
+ console.log(" bun run lint:fix - Fix linting issues");
471
+ console.log(" bun run format - Format code with Prettier");
472
+ console.log("");
473
+ }
474
+ function createEslintConfig(root, isWorkspace) {
475
+ const configPath = resolve(root, "eslint.config.js");
476
+ const config = isWorkspace ? `import { defineConfig } from '@bagelink/lint-config/eslint'
477
+
478
+ export default defineConfig({
479
+ // Workspace-level ESLint config
480
+ ignores: ['**/dist/**', '**/node_modules/**', '**/.bun-cache/**'],
481
+ })
482
+ ` : `import vue3Config from '@bagelink/lint-config/eslint/vue3'
483
+
484
+ export default vue3Config
485
+ `;
486
+ writeFileSync(configPath, config);
487
+ console.log("\u2705 Created eslint.config.js");
488
+ }
489
+ function createPrettierConfig(root) {
490
+ const configPath = resolve(root, ".prettierrc");
491
+ const config = {
492
+ semi: false,
493
+ singleQuote: true,
494
+ tabWidth: 2,
495
+ useTabs: true,
496
+ trailingComma: "all",
497
+ printWidth: 100,
498
+ arrowParens: "avoid"
499
+ };
500
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}
501
+ `);
502
+ console.log("\u2705 Created .prettierrc");
503
+ const ignorePath = resolve(root, ".prettierignore");
504
+ const ignore = `dist
505
+ node_modules
506
+ .bun-cache
507
+ *.min.js
508
+ *.min.css
509
+ `;
510
+ writeFileSync(ignorePath, ignore);
511
+ console.log("\u2705 Created .prettierignore");
512
+ }
513
+ function createEditorConfig(root) {
514
+ const configPath = resolve(root, ".editorconfig");
515
+ const config = `root = true
516
+
517
+ [*]
518
+ charset = utf-8
519
+ indent_style = tab
520
+ indent_size = 2
521
+ end_of_line = lf
522
+ insert_final_newline = true
523
+ trim_trailing_whitespace = true
524
+
525
+ [*.md]
526
+ trim_trailing_whitespace = false
527
+
528
+ [*.{json,yml,yaml}]
529
+ indent_style = space
530
+ indent_size = 2
531
+ `;
532
+ writeFileSync(configPath, config);
533
+ console.log("\u2705 Created .editorconfig");
534
+ }
535
+ function createGitHooks(root) {
536
+ const packageJsonPath = resolve(root, "package.json");
537
+ if (!existsSync(packageJsonPath)) {
538
+ console.warn("\u26A0\uFE0F No package.json found, skipping git hooks");
539
+ return;
540
+ }
541
+ const lintStagedConfig = {
542
+ "*.{js,jsx,ts,tsx,vue}": ["eslint --fix"],
543
+ "*.{json,md,yml,yaml}": ["prettier --write"]
544
+ };
545
+ writeFileSync(
546
+ resolve(root, ".lintstagedrc"),
547
+ `${JSON.stringify(lintStagedConfig, null, 2)}
548
+ `
549
+ );
550
+ console.log("\u2705 Created .lintstagedrc");
551
+ console.log("\u2139\uFE0F Add simple-git-hooks and lint-staged to devDependencies");
552
+ console.log(" Then run: npx simple-git-hooks");
553
+ }
554
+ async function cleanRedundantFiles(root) {
555
+ const foundFiles = [];
556
+ for (const file of REDUNDANT_FILES) {
557
+ const filePath = resolve(root, file);
558
+ if (existsSync(filePath)) {
559
+ foundFiles.push(file);
560
+ }
561
+ }
562
+ if (foundFiles.length === 0) {
563
+ console.log("\u2728 No redundant files found");
564
+ return;
565
+ }
566
+ console.log("\n\u{1F4CB} Found redundant files:");
567
+ foundFiles.forEach((file) => {
568
+ console.log(` - ${file}`);
569
+ });
570
+ const confirmResponse = await prompts({
571
+ type: "confirm",
572
+ name: "confirm",
573
+ message: `Delete ${foundFiles.length} redundant file${foundFiles.length > 1 ? "s" : ""}?`,
574
+ initial: true
575
+ });
576
+ if (!confirmResponse.confirm) {
577
+ console.log("\u23ED\uFE0F Skipped cleaning redundant files");
578
+ return;
579
+ }
580
+ let deleted = 0;
581
+ for (const file of foundFiles) {
582
+ try {
583
+ unlinkSync(resolve(root, file));
584
+ console.log(`\u{1F5D1}\uFE0F Deleted ${file}`);
585
+ deleted++;
586
+ } catch (error) {
587
+ console.error(`\u274C Failed to delete ${file}:`, error);
588
+ }
589
+ }
590
+ console.log(`\u2705 Cleaned up ${deleted} file${deleted > 1 ? "s" : ""}`);
591
+ }
592
+ function updatePackageJsonLint(root, configs) {
593
+ const packageJsonPath = resolve(root, "package.json");
594
+ if (!existsSync(packageJsonPath)) {
595
+ console.warn("\u26A0\uFE0F No package.json found");
596
+ return;
597
+ }
598
+ try {
599
+ const packageJson = JSON.parse(
600
+ readFileSync(packageJsonPath, "utf-8")
601
+ );
602
+ if (!packageJson.scripts) {
603
+ packageJson.scripts = {};
604
+ }
605
+ if (configs.includes("eslint")) {
606
+ if (!packageJson.scripts.lint) {
607
+ packageJson.scripts.lint = "eslint .";
608
+ }
609
+ if (!packageJson.scripts["lint:fix"]) {
610
+ packageJson.scripts["lint:fix"] = "eslint . --fix";
611
+ }
612
+ }
613
+ if (configs.includes("prettier")) {
614
+ if (!packageJson.scripts.format) {
615
+ packageJson.scripts.format = "prettier --write .";
616
+ }
617
+ if (!packageJson.scripts["format:check"]) {
618
+ packageJson.scripts["format:check"] = "prettier --check .";
619
+ }
620
+ }
621
+ writeFileSync(
622
+ packageJsonPath,
623
+ `${JSON.stringify(packageJson, null, 2)}
624
+ `
625
+ );
626
+ console.log("\u2705 Updated package.json with lint scripts");
627
+ } catch (error) {
628
+ console.error("\u274C Failed to update package.json:", error);
629
+ }
630
+ }
631
+
632
+ async function generateSDK(root = process.cwd()) {
633
+ console.log("\n\u{1F527} Generating SDK from OpenAPI...\n");
634
+ let config = null;
635
+ let openApiUrl;
636
+ try {
637
+ const configPath = resolve(root, "bgl.config.ts");
638
+ if (existsSync(configPath)) {
639
+ const module = await import(`file://${configPath}`);
640
+ const workspace = module.default;
641
+ if (typeof workspace === "function") {
642
+ config = workspace("development");
643
+ if (config?.openapi_url) {
644
+ openApiUrl = config.openapi_url;
645
+ }
646
+ }
647
+ }
648
+ } catch {
649
+ }
650
+ const response = await prompts([
651
+ {
652
+ type: openApiUrl !== void 0 ? null : "text",
653
+ name: "openApiUrl",
654
+ message: "OpenAPI spec URL:",
655
+ initial: openApiUrl ?? "http://localhost:8000/openapi.json"
656
+ },
657
+ {
658
+ type: "text",
659
+ name: "outputDir",
660
+ message: "Output directory:",
661
+ initial: "./src/api"
662
+ },
663
+ {
664
+ type: "confirm",
665
+ name: "splitFiles",
666
+ message: "Split into organized files?",
667
+ initial: true
668
+ }
669
+ ]);
670
+ if (!response) {
671
+ console.log("\n\u274C SDK generation cancelled.\n");
672
+ process.exit(1);
673
+ }
674
+ const finalUrl = openApiUrl ?? response.openApiUrl;
675
+ const { outputDir, splitFiles } = response;
676
+ console.log(`
677
+ \u{1F4E1} Fetching OpenAPI spec from: ${finalUrl}`);
678
+ console.log(`\u{1F4C1} Output directory: ${outputDir}
679
+ `);
680
+ try {
681
+ const { openAPI } = await import('@bagelink/sdk');
682
+ const { readFileSync } = await import('node:fs');
683
+ const { dirname, join } = await import('node:path');
684
+ const { fileURLToPath } = await import('node:url');
685
+ const { types, code } = await openAPI(finalUrl, "/api");
686
+ const outputPath = resolve(root, outputDir);
687
+ if (!existsSync(outputPath)) {
688
+ mkdirSync(outputPath, { recursive: true });
689
+ }
690
+ const typesPath = resolve(outputPath, "types.d.ts");
691
+ writeFileSync(typesPath, types);
692
+ console.log("\u2705 Generated types.d.ts");
693
+ const apiPath = resolve(outputPath, "api.ts");
694
+ writeFileSync(apiPath, code);
695
+ console.log("\u2705 Generated api.ts");
696
+ console.log("\u2139\uFE0F Stream utilities are imported from @bagelink/sdk");
697
+ if (splitFiles) {
698
+ console.log("\n\u{1F500} Splitting into organized files...");
699
+ console.log("\u2139\uFE0F File splitting requires @bagelink/sdk bin scripts");
700
+ console.log(" Keeping monolithic structure for now");
701
+ }
702
+ console.log("\n\u2705 SDK generated successfully!");
703
+ console.log(`
704
+ Import directly in your code:`);
705
+ console.log(` import { agents } from '${outputDir.replace("./src/", "./")}/api'`);
706
+ console.log(` import type { SendMessageRequest } from '${outputDir.replace("./src/", "./")}/types.d'`);
707
+ console.log("");
708
+ } catch (error) {
709
+ console.error("\n\u274C Failed to generate SDK:");
710
+ if (error instanceof Error) {
711
+ console.error(error.message);
712
+ } else {
713
+ console.error(error);
714
+ }
715
+ console.log("\nMake sure:");
716
+ console.log(" 1. @bagelink/sdk is installed: bun add -D @bagelink/sdk");
717
+ console.log(" 2. OpenAPI URL is accessible");
718
+ console.log(" 3. API server is running (if using localhost)");
719
+ process.exit(1);
720
+ }
721
+ }
722
+ async function generateSDKForWorkspace(root = process.cwd()) {
723
+ console.log("\n\u{1F3E2} Generating SDK for workspace...\n");
724
+ let config = null;
725
+ let openApiUrl;
726
+ try {
727
+ const configPath = resolve(root, "bgl.config.ts");
728
+ if (existsSync(configPath)) {
729
+ const module = await import(`file://${configPath}`);
730
+ const workspace = module.default;
731
+ if (typeof workspace === "function") {
732
+ config = workspace("development");
733
+ if (config?.openapi_url) {
734
+ openApiUrl = config.openapi_url;
735
+ }
736
+ }
737
+ }
738
+ } catch {
739
+ }
740
+ const response = await prompts({
741
+ type: openApiUrl !== void 0 ? null : "text",
742
+ name: "openApiUrl",
743
+ message: "OpenAPI spec URL:",
744
+ initial: openApiUrl ?? "http://localhost:8000/openapi.json"
745
+ });
746
+ if (response === void 0 || openApiUrl === void 0 && !response.openApiUrl) {
747
+ console.log("\n\u274C SDK generation cancelled.\n");
748
+ process.exit(1);
749
+ }
750
+ const finalUrl = openApiUrl ?? response.openApiUrl;
751
+ const outputDir = "./shared";
752
+ console.log(`
753
+ \u{1F4E1} Fetching OpenAPI spec from: ${finalUrl}`);
754
+ console.log(`\u{1F4C1} Output directory: ${outputDir}
755
+ `);
756
+ try {
757
+ const { openAPI } = await import('@bagelink/sdk');
758
+ const { types, code } = await openAPI(finalUrl, "/api");
759
+ const outputPath = resolve(root, outputDir);
760
+ if (!existsSync(outputPath)) {
761
+ mkdirSync(outputPath, { recursive: true });
762
+ }
763
+ const typesPath = resolve(outputPath, "types.d.ts");
764
+ writeFileSync(typesPath, types);
765
+ console.log("\u2705 Generated types.d.ts");
766
+ const apiPath = resolve(outputPath, "api.ts");
767
+ writeFileSync(apiPath, code);
768
+ console.log("\u2705 Generated api.ts");
769
+ console.log("\n\u2705 SDK generated successfully in shared folder!");
770
+ console.log(`
771
+ Import from shared in your projects:`);
772
+ console.log(` import { agents } from '../shared/api'`);
773
+ console.log(` import type { SendMessageRequest } from '../shared/types'`);
774
+ console.log("");
775
+ } catch (error) {
776
+ console.error("\n\u274C Failed to generate SDK:");
777
+ if (error instanceof Error) {
778
+ console.error(error.message);
779
+ } else {
780
+ console.error(error);
781
+ }
782
+ console.log("\nMake sure:");
783
+ console.log(" 1. @bagelink/sdk is installed: bun add -D @bagelink/sdk");
784
+ console.log(" 2. OpenAPI URL is accessible");
785
+ console.log(" 3. API server is running (if using localhost)");
786
+ process.exit(1);
787
+ }
788
+ }
7
789
 
8
790
  const [, , command, subcommand, ...args] = process.argv;
9
791
  async function main() {
10
792
  if (command === "init") {
11
793
  const createWorkspace = subcommand === "--workspace" || subcommand === "-w" || args.includes("--workspace") || args.includes("-w");
794
+ let targetPath = process.cwd();
795
+ if (subcommand && !subcommand.startsWith("-")) {
796
+ targetPath = subcommand === "." ? process.cwd() : resolve(process.cwd(), subcommand);
797
+ }
12
798
  if (createWorkspace) {
13
799
  await initWorkspace();
14
800
  } else {
15
- await generateWorkspaceConfig();
801
+ await generateWorkspaceConfig(targetPath);
16
802
  }
17
803
  } else if (command === "add") {
18
804
  const projectName = subcommand;
@@ -75,21 +861,46 @@ SDK Commands:
75
861
  `);
76
862
  process.exit(1);
77
863
  }
864
+ } else if (command === "dev") {
865
+ const { filter, additionalArgs } = parseFilterArgs(
866
+ void 0,
867
+ subcommand,
868
+ args
869
+ );
870
+ const exitCode = await runDev(filter, additionalArgs);
871
+ process.exit(exitCode);
872
+ } else if (command === "build") {
873
+ const { filter, additionalArgs } = parseFilterArgs(
874
+ void 0,
875
+ subcommand,
876
+ args
877
+ );
878
+ const exitCode = await runBuild(filter, additionalArgs);
879
+ process.exit(exitCode);
78
880
  } else {
79
881
  console.log(`
80
882
  Bagel Workspace CLI
81
883
 
82
884
  Usage:
83
- bgl init Generate bgl.config.ts for single project
885
+ bgl init [path] Generate bgl.config.ts for single project
886
+ Examples: bgl init, bgl init ., bgl init ./my-app
84
887
  bgl init --workspace Create a new workspace with multiple projects
85
888
  bgl add <name> Add a new project to workspace
86
889
  bgl list List all projects in workspace
890
+ bgl dev [filter] [...args] Run dev servers with clean output (default: './!shared*')
891
+ Examples:
892
+ bgl dev --mode localhost
893
+ bgl dev --mode staging
894
+ bgl dev admin --mode production
895
+ bgl build [project] [...args] Build project by directory (default: all projects)
896
+ Example: bgl build --mode production
87
897
  bgl lint init Set up linting (auto-detects workspace)
88
898
  bgl sdk generate Generate SDK (auto-detects workspace)
89
899
 
90
900
  Options:
91
901
  --workspace, -w Force workspace mode
92
902
  --project, -p Force single project mode
903
+ --mode <env> Set environment (matches bgl.config.ts keys)
93
904
  --help, -h Show this help message
94
905
 
95
906
  Note: Commands auto-detect workspace mode based on directory structure
@@ -97,6 +908,34 @@ Note: Commands auto-detect workspace mode based on directory structure
97
908
  process.exit(command === "--help" || command === "-h" ? 0 : 1);
98
909
  }
99
910
  }
911
+ function normalizeFilter(input) {
912
+ if (input.startsWith(".") || input.includes("*") || input.includes("[")) {
913
+ return input;
914
+ }
915
+ return `./${input}`;
916
+ }
917
+ function parseFilterArgs(defaultFilter, subcommandArg, argsList = []) {
918
+ const tokens = [subcommandArg, ...argsList].filter(Boolean);
919
+ const flagsWithValues = /* @__PURE__ */ new Set(["--mode", "--host", "--port"]);
920
+ const nonFlagIndexes = [];
921
+ for (let i = 0; i < tokens.length; i++) {
922
+ const token = tokens[i];
923
+ if (token.startsWith("-")) {
924
+ if (flagsWithValues.has(token)) {
925
+ i++;
926
+ }
927
+ } else {
928
+ const prevToken = i > 0 ? tokens[i - 1] : null;
929
+ if (!prevToken || !flagsWithValues.has(prevToken)) {
930
+ nonFlagIndexes.push(i);
931
+ }
932
+ }
933
+ }
934
+ const filterIndex = nonFlagIndexes.length > 0 ? nonFlagIndexes[nonFlagIndexes.length - 1] : -1;
935
+ const filter = filterIndex >= 0 ? normalizeFilter(tokens[filterIndex]) : defaultFilter;
936
+ const additionalArgs = filterIndex >= 0 ? tokens.filter((_, index) => index !== filterIndex) : tokens;
937
+ return { filter, additionalArgs };
938
+ }
100
939
  main().catch((error) => {
101
940
  console.error("Error:", error);
102
941
  process.exit(1);