@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,432 @@
1
+ import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import process from 'node:process'
4
+ import prompts from 'prompts'
5
+
6
+ /**
7
+ * Initialize a new workspace with flat structure
8
+ */
9
+ export async function initWorkspace(root: string = process.cwd()): Promise<void> {
10
+ console.log('\nšŸš€ Creating Bagel workspace...\n')
11
+
12
+ const response = await prompts([
13
+ {
14
+ type: 'text',
15
+ name: 'workspaceName',
16
+ message: 'Workspace name:',
17
+ initial: 'my-workspace',
18
+ },
19
+ {
20
+ type: 'text',
21
+ name: 'projectId',
22
+ message: 'Bagel project ID:',
23
+ initial: 'my-project',
24
+ },
25
+ {
26
+ type: 'confirm',
27
+ name: 'createFirstProject',
28
+ message: 'Create first project?',
29
+ initial: true,
30
+ },
31
+ {
32
+ type: (prev: boolean) => (prev ? 'text' : null),
33
+ name: 'firstProjectName',
34
+ message: 'First project name:',
35
+ initial: 'web',
36
+ },
37
+ ])
38
+
39
+ if (!response || !response.workspaceName) {
40
+ console.log('\nāŒ Workspace creation cancelled.\n')
41
+ process.exit(1)
42
+ }
43
+
44
+ const { workspaceName, projectId, createFirstProject, firstProjectName } = response
45
+
46
+ // Create workspace structure
47
+ createWorkspaceRoot(root, workspaceName, projectId)
48
+
49
+ // Create shared package
50
+ createSharedPackage(root)
51
+
52
+ if (createFirstProject && firstProjectName) {
53
+ await addProject(firstProjectName, root)
54
+ }
55
+
56
+ console.log('\nāœ… Workspace created successfully!')
57
+ console.log('\nNext steps:')
58
+ console.log(` cd ${workspaceName}`)
59
+ console.log(' bun install')
60
+ if (createFirstProject) {
61
+ console.log(` bun run dev:${firstProjectName}`)
62
+ }
63
+ else {
64
+ console.log(' bgl add <project-name> # Add a project')
65
+ }
66
+ console.log('')
67
+ }
68
+
69
+ /**
70
+ * Create workspace root files
71
+ */
72
+ function createWorkspaceRoot(root: string, name: string, projectId: string): void {
73
+ const workspaceDir = resolve(root, name)
74
+
75
+ if (existsSync(workspaceDir)) {
76
+ console.error(`āŒ Directory ${name} already exists`)
77
+ process.exit(1)
78
+ }
79
+
80
+ mkdirSync(workspaceDir, { recursive: true })
81
+
82
+ // package.json
83
+ const packageJson = {
84
+ name,
85
+ private: true,
86
+ workspaces: ['*', '!node_modules'],
87
+ scripts: {
88
+ dev: 'bun run --filter \'./[!shared]*\' dev',
89
+ build: 'bun run --filter \'./[!shared]*\' build',
90
+ typecheck: 'tsc --noEmit',
91
+ },
92
+ devDependencies: {
93
+ '@bagelink/workspace': 'latest',
94
+ typescript: '^5.0.0',
95
+ vite: 'latest',
96
+ },
97
+ }
98
+
99
+ writeFileSync(
100
+ resolve(workspaceDir, 'package.json'),
101
+ `${JSON.stringify(packageJson, null, 2)}\n`,
102
+ )
103
+
104
+ // bgl.config.ts (shared)
105
+ const bglConfig = `import { defineWorkspace } from '@bagelink/workspace'
106
+
107
+ export default defineWorkspace({
108
+ localhost: {
109
+ host: 'http://localhost:8000',
110
+ proxy: '/api',
111
+ openapi_url: 'http://localhost:8000/openapi.json',
112
+ },
113
+ development: {
114
+ host: 'https://${projectId}.bagel.to',
115
+ proxy: '/api',
116
+ openapi_url: 'https://${projectId}.bagel.to/openapi.json',
117
+ },
118
+ production: {
119
+ host: 'https://${projectId}.bagel.to',
120
+ proxy: '/api',
121
+ openapi_url: 'https://${projectId}.bagel.to/openapi.json',
122
+ },
123
+ })
124
+ `
125
+
126
+ writeFileSync(resolve(workspaceDir, 'bgl.config.ts'), bglConfig)
127
+
128
+ // tsconfig.json
129
+ const tsConfig = {
130
+ compilerOptions: {
131
+ target: 'ES2020',
132
+ useDefineForClassFields: true,
133
+ module: 'ESNext',
134
+ lib: ['ES2020', 'DOM', 'DOM.Iterable'],
135
+ skipLibCheck: true,
136
+ moduleResolution: 'bundler',
137
+ allowImportingTsExtensions: true,
138
+ resolveJsonModule: true,
139
+ isolatedModules: true,
140
+ noEmit: true,
141
+ jsx: 'preserve',
142
+ strict: true,
143
+ noUnusedLocals: true,
144
+ noUnusedParameters: true,
145
+ noFallthroughCasesInSwitch: true,
146
+ baseUrl: '.',
147
+ paths: {
148
+ 'shared/*': ['./shared/*'],
149
+ },
150
+ },
151
+ }
152
+
153
+ writeFileSync(
154
+ resolve(workspaceDir, 'tsconfig.json'),
155
+ `${JSON.stringify(tsConfig, null, 2)}\n`,
156
+ )
157
+
158
+ // .gitignore
159
+ const gitignore = `node_modules
160
+ dist
161
+ .DS_Store
162
+ *.local
163
+ .env.local
164
+ .vite
165
+ `
166
+
167
+ writeFileSync(resolve(workspaceDir, '.gitignore'), gitignore)
168
+
169
+ console.log(`āœ… Created workspace: ${name}`)
170
+ }
171
+
172
+ /**
173
+ * Create shared package
174
+ */
175
+ function createSharedPackage(root: string): void {
176
+ const sharedDir = resolve(root, 'shared')
177
+ mkdirSync(sharedDir, { recursive: true })
178
+
179
+ // package.json
180
+ const packageJson = {
181
+ name: 'shared',
182
+ version: '1.0.0',
183
+ type: 'module',
184
+ exports: {
185
+ '.': './index.ts',
186
+ './utils': './utils/index.ts',
187
+ './types': './types/index.ts',
188
+ },
189
+ }
190
+
191
+ writeFileSync(
192
+ resolve(sharedDir, 'package.json'),
193
+ `${JSON.stringify(packageJson, null, 2)}\n`,
194
+ )
195
+
196
+ // index.ts
197
+ writeFileSync(
198
+ resolve(sharedDir, 'index.ts'),
199
+ '// Shared utilities and exports\nexport * from \'./utils\'\n',
200
+ )
201
+
202
+ // utils/index.ts
203
+ mkdirSync(resolve(sharedDir, 'utils'), { recursive: true })
204
+ writeFileSync(
205
+ resolve(sharedDir, 'utils', 'index.ts'),
206
+ '// Shared utility functions\nexport function formatDate(date: Date): string {\n return date.toISOString()\n}\n',
207
+ )
208
+
209
+ // types/index.ts
210
+ mkdirSync(resolve(sharedDir, 'types'), { recursive: true })
211
+ writeFileSync(
212
+ resolve(sharedDir, 'types', 'index.ts'),
213
+ '// Shared types\nexport interface User {\n id: string\n name: string\n}\n',
214
+ )
215
+
216
+ console.log('āœ… Created shared package')
217
+ }
218
+
219
+ /**
220
+ * Add a new project to the workspace
221
+ */
222
+ export async function addProject(
223
+ name: string,
224
+ root: string = process.cwd(),
225
+ ): Promise<void> {
226
+ const projectDir = resolve(root, name)
227
+
228
+ if (existsSync(projectDir)) {
229
+ console.error(`āŒ Project ${name} already exists`)
230
+ process.exit(1)
231
+ }
232
+
233
+ console.log(`\nšŸ“¦ Creating project: ${name}\n`)
234
+
235
+ mkdirSync(projectDir, { recursive: true })
236
+
237
+ // Determine if this is part of a workspace
238
+ const isWorkspace = existsSync(resolve(root, 'bgl.config.ts'))
239
+
240
+ // package.json
241
+ const packageJson: Record<string, unknown> = {
242
+ name,
243
+ type: 'module',
244
+ scripts: {
245
+ dev: 'vite',
246
+ build: 'vite build',
247
+ preview: 'vite preview',
248
+ },
249
+ dependencies: {} as Record<string, string>,
250
+ devDependencies: {
251
+ '@vitejs/plugin-vue': 'latest',
252
+ vite: 'latest',
253
+ vue: 'latest',
254
+ },
255
+ }
256
+
257
+ // Add shared dependency if in workspace
258
+ if (isWorkspace) {
259
+ (packageJson.dependencies as Record<string, string>).shared = 'workspace:*'
260
+ }
261
+
262
+ writeFileSync(
263
+ resolve(projectDir, 'package.json'),
264
+ `${JSON.stringify(packageJson, null, 2)}\n`,
265
+ )
266
+
267
+ // bgl.config.ts
268
+ const bglConfigContent = isWorkspace
269
+ ? `import { defineWorkspace } from '@bagelink/workspace'
270
+ import rootWorkspace from '../bgl.config'
271
+
272
+ export default defineWorkspace({
273
+ localhost: rootWorkspace('localhost'),
274
+ development: rootWorkspace('development'),
275
+ production: rootWorkspace('production'),
276
+ })
277
+ `
278
+ : `import { defineWorkspace } from '@bagelink/workspace'
279
+
280
+ export default defineWorkspace({
281
+ localhost: {
282
+ host: 'http://localhost:8000',
283
+ proxy: '/api',
284
+ },
285
+ development: {
286
+ host: 'https://my-project.bagel.to',
287
+ proxy: '/api',
288
+ },
289
+ production: {
290
+ host: 'https://my-project.bagel.to',
291
+ proxy: '/api',
292
+ },
293
+ })
294
+ `
295
+
296
+ writeFileSync(resolve(projectDir, 'bgl.config.ts'), bglConfigContent)
297
+
298
+ // vite.config.ts
299
+ const viteConfig = `import { defineConfig } from 'vite'
300
+ import vue from '@vitejs/plugin-vue'
301
+ import { createViteProxy } from '@bagelink/workspace'
302
+ import workspace from './bgl.config'
303
+
304
+ export default defineConfig(({ mode }) => {
305
+ const config = workspace(mode as 'localhost' | 'development' | 'production')
306
+
307
+ return {
308
+ plugins: [vue()],
309
+ server: {
310
+ proxy: createViteProxy(config),
311
+ },
312
+ }
313
+ })
314
+ `
315
+
316
+ writeFileSync(resolve(projectDir, 'vite.config.ts'), viteConfig)
317
+
318
+ // Create basic src structure
319
+ const srcDir = resolve(projectDir, 'src')
320
+ mkdirSync(srcDir, { recursive: true })
321
+
322
+ // index.html
323
+ const indexHtml = `<!DOCTYPE html>
324
+ <html lang="en">
325
+ <head>
326
+ <meta charset="UTF-8">
327
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
328
+ <title>${name}</title>
329
+ </head>
330
+ <body>
331
+ <div id="app"></div>
332
+ <script type="module" src="/src/main.ts"></script>
333
+ </body>
334
+ </html>
335
+ `
336
+
337
+ writeFileSync(resolve(projectDir, 'index.html'), indexHtml)
338
+
339
+ // main.ts
340
+ const mainTs = `import { createApp } from 'vue'
341
+ import App from './App.vue'
342
+
343
+ createApp(App).mount('#app')
344
+ `
345
+
346
+ writeFileSync(resolve(srcDir, 'main.ts'), mainTs)
347
+
348
+ // App.vue
349
+ const appVue = `<script setup lang="ts">
350
+ import { ref } from 'vue'
351
+ ${isWorkspace ? 'import { formatDate } from \'shared/utils\'\n' : ''}
352
+ const count = ref(0)
353
+ </script>
354
+
355
+ <template>
356
+ <div>
357
+ <h1>${name}</h1>
358
+ <button @click="count++">Count: {{ count }}</button>
359
+ ${isWorkspace ? '<p>{{ formatDate(new Date()) }}</p>' : ''}
360
+ </div>
361
+ </template>
362
+ `
363
+
364
+ writeFileSync(resolve(srcDir, 'App.vue'), appVue)
365
+
366
+ console.log(`āœ… Created project: ${name}`)
367
+
368
+ // Update workspace package.json if needed
369
+ if (isWorkspace) {
370
+ updateWorkspaceScripts(root, name)
371
+ }
372
+
373
+ console.log('\nNext steps:')
374
+ console.log(` cd ${name}`)
375
+ console.log(' bun install')
376
+ console.log(' bun run dev')
377
+ console.log('')
378
+ }
379
+
380
+ /**
381
+ * Update workspace root package.json with new project scripts
382
+ */
383
+ function updateWorkspaceScripts(root: string, projectName: string): void {
384
+ const packageJsonPath = resolve(root, 'package.json')
385
+ if (!existsSync(packageJsonPath)) return
386
+
387
+ try {
388
+ const packageJson = JSON.parse(
389
+ require('fs').readFileSync(packageJsonPath, 'utf-8'),
390
+ )
391
+
392
+ if (!packageJson.scripts) {
393
+ packageJson.scripts = {}
394
+ }
395
+
396
+ // Add project-specific scripts
397
+ packageJson.scripts[`dev:${projectName}`] = `bun --filter ${projectName} dev`
398
+ packageJson.scripts[`build:${projectName}`] = `bun --filter ${projectName} build`
399
+
400
+ writeFileSync(
401
+ packageJsonPath,
402
+ `${JSON.stringify(packageJson, null, 2)}\n`,
403
+ )
404
+
405
+ console.log(`āœ… Added scripts: dev:${projectName}, build:${projectName}`)
406
+ }
407
+ catch (error) {
408
+ console.warn('āš ļø Could not update workspace scripts')
409
+ }
410
+ }
411
+
412
+ /**
413
+ * List all projects in workspace
414
+ */
415
+ export function listProjects(root: string = process.cwd()): string[] {
416
+ try {
417
+ const items = readdirSync(root, { withFileTypes: true })
418
+ return items
419
+ .filter(
420
+ item =>
421
+ item.isDirectory()
422
+ && item.name !== 'node_modules'
423
+ && item.name !== 'shared'
424
+ && item.name !== '.git'
425
+ && !item.name.startsWith('.'),
426
+ )
427
+ .map(item => item.name)
428
+ }
429
+ catch {
430
+ return []
431
+ }
432
+ }
@@ -1,182 +0,0 @@
1
- import { writeFileSync, existsSync, readFileSync } from 'node:fs';
2
- import { resolve } from 'node:path';
3
- import process from 'node:process';
4
- import prompts from 'prompts';
5
-
6
- async function generateWorkspaceConfig(root = process.cwd(), configFile = "bgl.config.ts") {
7
- console.log("\n\u{1F527} No bgl.config.ts found. Let's create one!\n");
8
- const response = await prompts([
9
- {
10
- type: "text",
11
- name: "projectId",
12
- message: "What is your Bagel project ID?",
13
- initial: "my-project",
14
- validate: (value) => value.length > 0 ? true : "Project ID is required"
15
- },
16
- {
17
- type: "confirm",
18
- name: "useCustomHost",
19
- message: "Use custom production host?",
20
- initial: false
21
- },
22
- {
23
- type: (prev) => prev ? "text" : null,
24
- name: "customHost",
25
- message: "Enter production host URL:",
26
- initial: "https://api.example.com"
27
- }
28
- ]);
29
- if (!response || !response.projectId) {
30
- console.log("\n\u274C Config generation cancelled.\n");
31
- process.exit(1);
32
- }
33
- const productionHost = response.useCustomHost === true ? response.customHost : `https://${response.projectId}.bagel.to`;
34
- const configContent = `import { defineWorkspace } from '@bagelink/workspace'
35
- import type { WorkspaceConfig, WorkspaceEnvironment } from '@bagelink/workspace'
36
-
37
- const configs: Record<WorkspaceEnvironment, WorkspaceConfig> = {
38
- localhost: {
39
- host: 'http://localhost:8000',
40
- proxy: '/api',
41
- openapi_url: 'http://localhost:8000/openapi.json',
42
- },
43
- development: {
44
- host: '${productionHost}',
45
- proxy: '/api',
46
- openapi_url: '${productionHost}/openapi.json',
47
- },
48
- production: {
49
- host: '${productionHost}',
50
- proxy: '/api',
51
- openapi_url: '${productionHost}/openapi.json',
52
- },
53
- }
54
-
55
- export default defineWorkspace(configs)
56
- `;
57
- const configPath = resolve(root, configFile);
58
- writeFileSync(configPath, configContent, "utf-8");
59
- console.log(`
60
- \u2705 Created ${configFile}`);
61
- console.log(` Production host: ${productionHost}`);
62
- console.log(` Local dev host: http://localhost:8000
63
- `);
64
- const setupResponse = await prompts([
65
- {
66
- type: "confirm",
67
- name: "updatePackageJson",
68
- message: "Add dev scripts to package.json?",
69
- initial: true
70
- },
71
- {
72
- type: "confirm",
73
- name: "updateViteConfig",
74
- message: "Create/update vite.config.ts?",
75
- initial: true
76
- }
77
- ]);
78
- if (setupResponse.updatePackageJson) {
79
- updatePackageJsonScripts(root);
80
- }
81
- if (setupResponse.updateViteConfig) {
82
- updateViteConfig(root);
83
- }
84
- console.log("\n\u{1F4A1} You can edit these files to customize your configuration.\n");
85
- }
86
- function generateWorkspaceConfigSync(projectId, root = process.cwd(), configFile = "bgl.config.ts", customHost) {
87
- const productionHost = customHost ?? `https://${projectId}.bagel.to`;
88
- const configContent = `import { defineWorkspace } from '@bagelink/workspace'
89
- import type { WorkspaceConfig, WorkspaceEnvironment } from '@bagelink/workspace'
90
-
91
- const configs: Record<WorkspaceEnvironment, WorkspaceConfig> = {
92
- localhost: {
93
- host: 'http://localhost:8000',
94
- proxy: '/api',
95
- openapi_url: 'http://localhost:8000/openapi.json',
96
- },
97
- development: {
98
- host: '${productionHost}',
99
- proxy: '/api',
100
- openapi_url: '${productionHost}/openapi.json',
101
- },
102
- production: {
103
- host: '${productionHost}',
104
- proxy: '/api',
105
- openapi_url: '${productionHost}/openapi.json',
106
- },
107
- }
108
-
109
- export default defineWorkspace(configs)
110
- `;
111
- const configPath = resolve(root, configFile);
112
- writeFileSync(configPath, configContent, "utf-8");
113
- console.log(`\u2705 Created ${configPath}`);
114
- }
115
- function updatePackageJsonScripts(root) {
116
- const packageJsonPath = resolve(root, "package.json");
117
- if (!existsSync(packageJsonPath)) {
118
- console.log("\u26A0\uFE0F No package.json found, skipping script update");
119
- return;
120
- }
121
- try {
122
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
123
- if (!packageJson.scripts) {
124
- packageJson.scripts = {};
125
- }
126
- const scriptsToAdd = {
127
- "dev": "vite",
128
- "dev:local": "vite --mode localhost",
129
- "build": "vite build",
130
- "preview": "vite preview"
131
- };
132
- let added = false;
133
- for (const [key, value] of Object.entries(scriptsToAdd)) {
134
- if (!packageJson.scripts[key]) {
135
- packageJson.scripts[key] = value;
136
- added = true;
137
- }
138
- }
139
- if (added) {
140
- writeFileSync(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
141
- `, "utf-8");
142
- console.log("\u2705 Updated package.json with dev scripts");
143
- } else {
144
- console.log("\u2139\uFE0F Scripts already exist in package.json");
145
- }
146
- } catch (error) {
147
- console.error("\u274C Failed to update package.json:", error);
148
- }
149
- }
150
- function updateViteConfig(root) {
151
- const viteConfigPath = resolve(root, "vite.config.ts");
152
- const viteConfigExists = existsSync(viteConfigPath);
153
- if (viteConfigExists) {
154
- const existingConfig = readFileSync(viteConfigPath, "utf-8");
155
- if (existingConfig.includes("@bagelink/workspace")) {
156
- console.log("\u2139\uFE0F vite.config.ts already configured");
157
- return;
158
- }
159
- console.log("\u26A0\uFE0F vite.config.ts exists. Please manually add the workspace configuration.");
160
- console.log(" See: https://github.com/bageldb/bagelink/tree/master/packages/workspace#readme");
161
- return;
162
- }
163
- const viteConfigContent = `import { defineConfig } from 'vite'
164
- import { createViteProxy } from '@bagelink/workspace'
165
- import workspace from './bgl.config'
166
-
167
- // https://vitejs.dev/config/
168
- export default defineConfig(({ mode }) => {
169
- const config = workspace(mode as 'localhost' | 'development' | 'production')
170
-
171
- return {
172
- server: {
173
- proxy: createViteProxy(config),
174
- },
175
- }
176
- })
177
- `;
178
- writeFileSync(viteConfigPath, viteConfigContent, "utf-8");
179
- console.log("\u2705 Created vite.config.ts");
180
- }
181
-
182
- export { generateWorkspaceConfigSync as a, generateWorkspaceConfig as g };