@bagelink/workspace 1.7.3 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,575 @@
1
+ 'use strict';
2
+
3
+ const node_fs = require('node:fs');
4
+ const node_path = require('node:path');
5
+ const process = require('node:process');
6
+ const prompts = require('prompts');
7
+
8
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
9
+
10
+ const process__default = /*#__PURE__*/_interopDefaultCompat(process);
11
+ const prompts__default = /*#__PURE__*/_interopDefaultCompat(prompts);
12
+
13
+ function generateNetlifyRedirect(config) {
14
+ const redirect = `[[redirects]]
15
+ from = "${config.proxy}/*"
16
+ to = "${config.host}/:splat"
17
+ status = 200
18
+ force = true
19
+ headers = {X-From = "Netlify"}
20
+ `;
21
+ return redirect;
22
+ }
23
+ function generateNetlifyConfig(config, additionalConfig) {
24
+ const redirect = generateNetlifyRedirect(config);
25
+ if (additionalConfig !== void 0 && additionalConfig !== "") {
26
+ return `${redirect}
27
+ ${additionalConfig}`;
28
+ }
29
+ return redirect;
30
+ }
31
+ function writeNetlifyConfig(config, outPath = "./netlify.toml", additionalConfig) {
32
+ const content = generateNetlifyConfig(config, additionalConfig);
33
+ const resolvedPath = node_path.resolve(outPath);
34
+ node_fs.writeFileSync(resolvedPath, content, "utf-8");
35
+ console.log(`\u2713 Generated netlify.toml at ${resolvedPath}`);
36
+ }
37
+ function setBuildEnvVars(config) {
38
+ process__default.env.BGL_PROXY_PATH = config.proxy;
39
+ process__default.env.BGL_API_HOST = config.host;
40
+ if (config.openapi_url !== void 0 && config.openapi_url !== "") {
41
+ process__default.env.BGL_OPENAPI_URL = config.openapi_url;
42
+ }
43
+ }
44
+
45
+ async function generateWorkspaceConfig(root = process__default.cwd(), configFile = "bgl.config.ts") {
46
+ console.log("\n\u{1F527} No bgl.config.ts found. Let's create one!\n");
47
+ const response = await prompts__default([
48
+ {
49
+ type: "text",
50
+ name: "projectId",
51
+ message: "What is your Bagel project ID?",
52
+ initial: "my-project",
53
+ validate: (value) => value.length > 0 ? true : "Project ID is required"
54
+ },
55
+ {
56
+ type: "confirm",
57
+ name: "useCustomHost",
58
+ message: "Use custom production host?",
59
+ initial: false
60
+ },
61
+ {
62
+ type: (prev) => prev ? "text" : null,
63
+ name: "customHost",
64
+ message: "Enter production host URL:",
65
+ initial: "https://api.example.com"
66
+ }
67
+ ]);
68
+ if (!response || !response.projectId) {
69
+ console.log("\n\u274C Config generation cancelled.\n");
70
+ process__default.exit(1);
71
+ }
72
+ const productionHost = response.useCustomHost === true ? response.customHost : `https://${response.projectId}.bagel.to`;
73
+ const configContent = `import { defineWorkspace } from '@bagelink/workspace'
74
+ import type { WorkspaceConfig, WorkspaceEnvironment } from '@bagelink/workspace'
75
+
76
+ const configs: Record<WorkspaceEnvironment, WorkspaceConfig> = {
77
+ localhost: {
78
+ host: 'http://localhost:8000',
79
+ proxy: '/api',
80
+ openapi_url: 'http://localhost:8000/openapi.json',
81
+ },
82
+ development: {
83
+ host: '${productionHost}',
84
+ proxy: '/api',
85
+ openapi_url: '${productionHost}/openapi.json',
86
+ },
87
+ production: {
88
+ host: '${productionHost}',
89
+ proxy: '/api',
90
+ openapi_url: '${productionHost}/openapi.json',
91
+ },
92
+ }
93
+
94
+ export default defineWorkspace(configs)
95
+ `;
96
+ const configPath = node_path.resolve(root, configFile);
97
+ node_fs.writeFileSync(configPath, configContent, "utf-8");
98
+ console.log(`
99
+ \u2705 Created ${configFile}`);
100
+ console.log(` Production host: ${productionHost}`);
101
+ console.log(` Local dev host: http://localhost:8000
102
+ `);
103
+ const setupResponse = await prompts__default([
104
+ {
105
+ type: "confirm",
106
+ name: "updatePackageJson",
107
+ message: "Add/update dev scripts in package.json?",
108
+ initial: true
109
+ },
110
+ {
111
+ type: "confirm",
112
+ name: "updateViteConfig",
113
+ message: "Create/update vite.config.ts?",
114
+ initial: true
115
+ },
116
+ {
117
+ type: "confirm",
118
+ name: "generateNetlify",
119
+ message: "Generate netlify.toml for deployment?",
120
+ initial: true
121
+ }
122
+ ]);
123
+ if (setupResponse.updatePackageJson) {
124
+ updatePackageJsonScripts(root);
125
+ }
126
+ if (setupResponse.updateViteConfig) {
127
+ updateViteConfig(root);
128
+ }
129
+ if (setupResponse.generateNetlify) {
130
+ const prodConfig = {
131
+ host: productionHost,
132
+ proxy: "/api"
133
+ };
134
+ writeNetlifyConfig(prodConfig, node_path.resolve(root, "netlify.toml"));
135
+ }
136
+ console.log("\n\u{1F4A1} You can edit these files to customize your configuration.\n");
137
+ }
138
+ function generateWorkspaceConfigSync(projectId, root = process__default.cwd(), configFile = "bgl.config.ts", customHost) {
139
+ const productionHost = customHost ?? `https://${projectId}.bagel.to`;
140
+ const configContent = `import { defineWorkspace } from '@bagelink/workspace'
141
+ import type { WorkspaceConfig, WorkspaceEnvironment } from '@bagelink/workspace'
142
+
143
+ const configs: Record<WorkspaceEnvironment, WorkspaceConfig> = {
144
+ localhost: {
145
+ host: 'http://localhost:8000',
146
+ proxy: '/api',
147
+ openapi_url: 'http://localhost:8000/openapi.json',
148
+ },
149
+ development: {
150
+ host: '${productionHost}',
151
+ proxy: '/api',
152
+ openapi_url: '${productionHost}/openapi.json',
153
+ },
154
+ production: {
155
+ host: '${productionHost}',
156
+ proxy: '/api',
157
+ openapi_url: '${productionHost}/openapi.json',
158
+ },
159
+ }
160
+
161
+ export default defineWorkspace(configs)
162
+ `;
163
+ const configPath = node_path.resolve(root, configFile);
164
+ node_fs.writeFileSync(configPath, configContent, "utf-8");
165
+ console.log(`\u2705 Created ${configPath}`);
166
+ }
167
+ function updatePackageJsonScripts(root) {
168
+ const packageJsonPath = node_path.resolve(root, "package.json");
169
+ if (!node_fs.existsSync(packageJsonPath)) {
170
+ console.log("\u26A0\uFE0F No package.json found, skipping script update");
171
+ return;
172
+ }
173
+ try {
174
+ const packageJson = JSON.parse(node_fs.readFileSync(packageJsonPath, "utf-8"));
175
+ if (!packageJson.scripts) {
176
+ packageJson.scripts = {};
177
+ }
178
+ const scriptsToAdd = {
179
+ "dev": "vite",
180
+ "dev:local": "vite --mode localhost",
181
+ "build": "vite build",
182
+ "preview": "vite preview"
183
+ };
184
+ let modified = false;
185
+ for (const [key, value] of Object.entries(scriptsToAdd)) {
186
+ if (key === "dev" || key === "dev:local") {
187
+ if (packageJson.scripts[key] !== value) {
188
+ packageJson.scripts[key] = value;
189
+ modified = true;
190
+ }
191
+ } else {
192
+ if (!packageJson.scripts[key]) {
193
+ packageJson.scripts[key] = value;
194
+ modified = true;
195
+ }
196
+ }
197
+ }
198
+ if (modified) {
199
+ node_fs.writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
200
+ `, "utf-8");
201
+ console.log("\u2705 Updated package.json with dev scripts");
202
+ } else {
203
+ console.log("\u2139\uFE0F Scripts already up to date in package.json");
204
+ }
205
+ } catch (error) {
206
+ console.error("\u274C Failed to update package.json:", error);
207
+ }
208
+ }
209
+ function updateViteConfig(root) {
210
+ const viteConfigPath = node_path.resolve(root, "vite.config.ts");
211
+ const viteConfigExists = node_fs.existsSync(viteConfigPath);
212
+ if (viteConfigExists) {
213
+ const existingConfig = node_fs.readFileSync(viteConfigPath, "utf-8");
214
+ if (existingConfig.includes("@bagelink/workspace")) {
215
+ console.log("\u2139\uFE0F vite.config.ts already configured");
216
+ return;
217
+ }
218
+ console.log("\u26A0\uFE0F vite.config.ts exists. Please manually add the workspace configuration.");
219
+ console.log(" See: https://github.com/bageldb/bagelink/tree/master/packages/workspace#readme");
220
+ return;
221
+ }
222
+ const viteConfigContent = `import { defineConfig } from 'vite'
223
+ import { createViteProxy } from '@bagelink/workspace'
224
+ import workspace from './bgl.config'
225
+
226
+ // https://vitejs.dev/config/
227
+ export default defineConfig(({ mode }) => {
228
+ const config = workspace(mode as 'localhost' | 'development' | 'production')
229
+
230
+ return {
231
+ server: {
232
+ proxy: createViteProxy(config),
233
+ },
234
+ }
235
+ })
236
+ `;
237
+ node_fs.writeFileSync(viteConfigPath, viteConfigContent, "utf-8");
238
+ console.log("\u2705 Created vite.config.ts");
239
+ }
240
+
241
+ async function initWorkspace(root = process__default.cwd()) {
242
+ console.log("\n\u{1F680} Creating Bagel workspace...\n");
243
+ const response = await prompts__default([
244
+ {
245
+ type: "text",
246
+ name: "workspaceName",
247
+ message: "Workspace name:",
248
+ initial: "my-workspace"
249
+ },
250
+ {
251
+ type: "text",
252
+ name: "projectId",
253
+ message: "Bagel project ID:",
254
+ initial: "my-project"
255
+ },
256
+ {
257
+ type: "confirm",
258
+ name: "createFirstProject",
259
+ message: "Create first project?",
260
+ initial: true
261
+ },
262
+ {
263
+ type: (prev) => prev ? "text" : null,
264
+ name: "firstProjectName",
265
+ message: "First project name:",
266
+ initial: "web"
267
+ }
268
+ ]);
269
+ if (!response || !response.workspaceName) {
270
+ console.log("\n\u274C Workspace creation cancelled.\n");
271
+ process__default.exit(1);
272
+ }
273
+ const { workspaceName, projectId, createFirstProject, firstProjectName } = response;
274
+ createWorkspaceRoot(root, workspaceName, projectId);
275
+ createSharedPackage(root);
276
+ if (createFirstProject && firstProjectName) {
277
+ await addProject(firstProjectName, root);
278
+ }
279
+ console.log("\n\u2705 Workspace created successfully!");
280
+ console.log("\nNext steps:");
281
+ console.log(` cd ${workspaceName}`);
282
+ console.log(" bun install");
283
+ if (createFirstProject) {
284
+ console.log(` bun run dev:${firstProjectName}`);
285
+ } else {
286
+ console.log(" bgl add <project-name> # Add a project");
287
+ }
288
+ console.log("");
289
+ }
290
+ function createWorkspaceRoot(root, name, projectId) {
291
+ const workspaceDir = node_path.resolve(root, name);
292
+ if (node_fs.existsSync(workspaceDir)) {
293
+ console.error(`\u274C Directory ${name} already exists`);
294
+ process__default.exit(1);
295
+ }
296
+ node_fs.mkdirSync(workspaceDir, { recursive: true });
297
+ const packageJson = {
298
+ name,
299
+ private: true,
300
+ workspaces: ["*", "!node_modules"],
301
+ scripts: {
302
+ dev: "bun run --filter './[!shared]*' dev",
303
+ build: "bun run --filter './[!shared]*' build",
304
+ typecheck: "tsc --noEmit"
305
+ },
306
+ devDependencies: {
307
+ "@bagelink/workspace": "latest",
308
+ typescript: "^5.0.0",
309
+ vite: "latest"
310
+ }
311
+ };
312
+ node_fs.writeFileSync(
313
+ node_path.resolve(workspaceDir, "package.json"),
314
+ `${JSON.stringify(packageJson, null, 2)}
315
+ `
316
+ );
317
+ const bglConfig = `import { defineWorkspace } from '@bagelink/workspace'
318
+
319
+ export default defineWorkspace({
320
+ localhost: {
321
+ host: 'http://localhost:8000',
322
+ proxy: '/api',
323
+ openapi_url: 'http://localhost:8000/openapi.json',
324
+ },
325
+ development: {
326
+ host: 'https://${projectId}.bagel.to',
327
+ proxy: '/api',
328
+ openapi_url: 'https://${projectId}.bagel.to/openapi.json',
329
+ },
330
+ production: {
331
+ host: 'https://${projectId}.bagel.to',
332
+ proxy: '/api',
333
+ openapi_url: 'https://${projectId}.bagel.to/openapi.json',
334
+ },
335
+ })
336
+ `;
337
+ node_fs.writeFileSync(node_path.resolve(workspaceDir, "bgl.config.ts"), bglConfig);
338
+ const tsConfig = {
339
+ compilerOptions: {
340
+ target: "ES2020",
341
+ useDefineForClassFields: true,
342
+ module: "ESNext",
343
+ lib: ["ES2020", "DOM", "DOM.Iterable"],
344
+ skipLibCheck: true,
345
+ moduleResolution: "bundler",
346
+ allowImportingTsExtensions: true,
347
+ resolveJsonModule: true,
348
+ isolatedModules: true,
349
+ noEmit: true,
350
+ jsx: "preserve",
351
+ strict: true,
352
+ noUnusedLocals: true,
353
+ noUnusedParameters: true,
354
+ noFallthroughCasesInSwitch: true,
355
+ baseUrl: ".",
356
+ paths: {
357
+ "shared/*": ["./shared/*"]
358
+ }
359
+ }
360
+ };
361
+ node_fs.writeFileSync(
362
+ node_path.resolve(workspaceDir, "tsconfig.json"),
363
+ `${JSON.stringify(tsConfig, null, 2)}
364
+ `
365
+ );
366
+ const gitignore = `node_modules
367
+ dist
368
+ .DS_Store
369
+ *.local
370
+ .env.local
371
+ .vite
372
+ `;
373
+ node_fs.writeFileSync(node_path.resolve(workspaceDir, ".gitignore"), gitignore);
374
+ console.log(`\u2705 Created workspace: ${name}`);
375
+ }
376
+ function createSharedPackage(root) {
377
+ const sharedDir = node_path.resolve(root, "shared");
378
+ node_fs.mkdirSync(sharedDir, { recursive: true });
379
+ const packageJson = {
380
+ name: "shared",
381
+ version: "1.0.0",
382
+ type: "module",
383
+ exports: {
384
+ ".": "./index.ts",
385
+ "./utils": "./utils/index.ts",
386
+ "./types": "./types/index.ts"
387
+ }
388
+ };
389
+ node_fs.writeFileSync(
390
+ node_path.resolve(sharedDir, "package.json"),
391
+ `${JSON.stringify(packageJson, null, 2)}
392
+ `
393
+ );
394
+ node_fs.writeFileSync(
395
+ node_path.resolve(sharedDir, "index.ts"),
396
+ "// Shared utilities and exports\nexport * from './utils'\n"
397
+ );
398
+ node_fs.mkdirSync(node_path.resolve(sharedDir, "utils"), { recursive: true });
399
+ node_fs.writeFileSync(
400
+ node_path.resolve(sharedDir, "utils", "index.ts"),
401
+ "// Shared utility functions\nexport function formatDate(date: Date): string {\n return date.toISOString()\n}\n"
402
+ );
403
+ node_fs.mkdirSync(node_path.resolve(sharedDir, "types"), { recursive: true });
404
+ node_fs.writeFileSync(
405
+ node_path.resolve(sharedDir, "types", "index.ts"),
406
+ "// Shared types\nexport interface User {\n id: string\n name: string\n}\n"
407
+ );
408
+ console.log("\u2705 Created shared package");
409
+ }
410
+ async function addProject(name, root = process__default.cwd()) {
411
+ const projectDir = node_path.resolve(root, name);
412
+ if (node_fs.existsSync(projectDir)) {
413
+ console.error(`\u274C Project ${name} already exists`);
414
+ process__default.exit(1);
415
+ }
416
+ console.log(`
417
+ \u{1F4E6} Creating project: ${name}
418
+ `);
419
+ node_fs.mkdirSync(projectDir, { recursive: true });
420
+ const isWorkspace = node_fs.existsSync(node_path.resolve(root, "bgl.config.ts"));
421
+ const packageJson = {
422
+ name,
423
+ type: "module",
424
+ scripts: {
425
+ dev: "vite",
426
+ build: "vite build",
427
+ preview: "vite preview"
428
+ },
429
+ dependencies: {},
430
+ devDependencies: {
431
+ "@vitejs/plugin-vue": "latest",
432
+ vite: "latest",
433
+ vue: "latest"
434
+ }
435
+ };
436
+ if (isWorkspace) {
437
+ packageJson.dependencies.shared = "workspace:*";
438
+ }
439
+ node_fs.writeFileSync(
440
+ node_path.resolve(projectDir, "package.json"),
441
+ `${JSON.stringify(packageJson, null, 2)}
442
+ `
443
+ );
444
+ const bglConfigContent = isWorkspace ? `import { defineWorkspace } from '@bagelink/workspace'
445
+ import rootWorkspace from '../bgl.config'
446
+
447
+ export default defineWorkspace({
448
+ localhost: rootWorkspace('localhost'),
449
+ development: rootWorkspace('development'),
450
+ production: rootWorkspace('production'),
451
+ })
452
+ ` : `import { defineWorkspace } from '@bagelink/workspace'
453
+
454
+ export default defineWorkspace({
455
+ localhost: {
456
+ host: 'http://localhost:8000',
457
+ proxy: '/api',
458
+ },
459
+ development: {
460
+ host: 'https://my-project.bagel.to',
461
+ proxy: '/api',
462
+ },
463
+ production: {
464
+ host: 'https://my-project.bagel.to',
465
+ proxy: '/api',
466
+ },
467
+ })
468
+ `;
469
+ node_fs.writeFileSync(node_path.resolve(projectDir, "bgl.config.ts"), bglConfigContent);
470
+ const viteConfig = `import { defineConfig } from 'vite'
471
+ import vue from '@vitejs/plugin-vue'
472
+ import { createViteProxy } from '@bagelink/workspace'
473
+ import workspace from './bgl.config'
474
+
475
+ export default defineConfig(({ mode }) => {
476
+ const config = workspace(mode as 'localhost' | 'development' | 'production')
477
+
478
+ return {
479
+ plugins: [vue()],
480
+ server: {
481
+ proxy: createViteProxy(config),
482
+ },
483
+ }
484
+ })
485
+ `;
486
+ node_fs.writeFileSync(node_path.resolve(projectDir, "vite.config.ts"), viteConfig);
487
+ const srcDir = node_path.resolve(projectDir, "src");
488
+ node_fs.mkdirSync(srcDir, { recursive: true });
489
+ const indexHtml = `<!DOCTYPE html>
490
+ <html lang="en">
491
+ <head>
492
+ <meta charset="UTF-8">
493
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
494
+ <title>${name}</title>
495
+ </head>
496
+ <body>
497
+ <div id="app"></div>
498
+ <script type="module" src="/src/main.ts"><\/script>
499
+ </body>
500
+ </html>
501
+ `;
502
+ node_fs.writeFileSync(node_path.resolve(projectDir, "index.html"), indexHtml);
503
+ const mainTs = `import { createApp } from 'vue'
504
+ import App from './App.vue'
505
+
506
+ createApp(App).mount('#app')
507
+ `;
508
+ node_fs.writeFileSync(node_path.resolve(srcDir, "main.ts"), mainTs);
509
+ const appVue = `<script setup lang="ts">
510
+ import { ref } from 'vue'
511
+ ${isWorkspace ? "import { formatDate } from 'shared/utils'\n" : ""}
512
+ const count = ref(0)
513
+ <\/script>
514
+
515
+ <template>
516
+ <div>
517
+ <h1>${name}</h1>
518
+ <button @click="count++">Count: {{ count }}</button>
519
+ ${isWorkspace ? "<p>{{ formatDate(new Date()) }}</p>" : ""}
520
+ </div>
521
+ </template>
522
+ `;
523
+ node_fs.writeFileSync(node_path.resolve(srcDir, "App.vue"), appVue);
524
+ console.log(`\u2705 Created project: ${name}`);
525
+ if (isWorkspace) {
526
+ updateWorkspaceScripts(root, name);
527
+ }
528
+ console.log("\nNext steps:");
529
+ console.log(` cd ${name}`);
530
+ console.log(" bun install");
531
+ console.log(" bun run dev");
532
+ console.log("");
533
+ }
534
+ function updateWorkspaceScripts(root, projectName) {
535
+ const packageJsonPath = node_path.resolve(root, "package.json");
536
+ if (!node_fs.existsSync(packageJsonPath)) return;
537
+ try {
538
+ const packageJson = JSON.parse(
539
+ require("fs").readFileSync(packageJsonPath, "utf-8")
540
+ );
541
+ if (!packageJson.scripts) {
542
+ packageJson.scripts = {};
543
+ }
544
+ packageJson.scripts[`dev:${projectName}`] = `bun --filter ${projectName} dev`;
545
+ packageJson.scripts[`build:${projectName}`] = `bun --filter ${projectName} build`;
546
+ node_fs.writeFileSync(
547
+ packageJsonPath,
548
+ `${JSON.stringify(packageJson, null, 2)}
549
+ `
550
+ );
551
+ console.log(`\u2705 Added scripts: dev:${projectName}, build:${projectName}`);
552
+ } catch (error) {
553
+ console.warn("\u26A0\uFE0F Could not update workspace scripts");
554
+ }
555
+ }
556
+ function listProjects(root = process__default.cwd()) {
557
+ try {
558
+ const items = node_fs.readdirSync(root, { withFileTypes: true });
559
+ return items.filter(
560
+ (item) => item.isDirectory() && item.name !== "node_modules" && item.name !== "shared" && item.name !== ".git" && !item.name.startsWith(".")
561
+ ).map((item) => item.name);
562
+ } catch {
563
+ return [];
564
+ }
565
+ }
566
+
567
+ exports.addProject = addProject;
568
+ exports.generateNetlifyConfig = generateNetlifyConfig;
569
+ exports.generateNetlifyRedirect = generateNetlifyRedirect;
570
+ exports.generateWorkspaceConfig = generateWorkspaceConfig;
571
+ exports.generateWorkspaceConfigSync = generateWorkspaceConfigSync;
572
+ exports.initWorkspace = initWorkspace;
573
+ exports.listProjects = listProjects;
574
+ exports.setBuildEnvVars = setBuildEnvVars;
575
+ exports.writeNetlifyConfig = writeNetlifyConfig;