@effect-gql/cli 1.1.0 → 1.3.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.
package/index.js CHANGED
@@ -1,7 +1,9 @@
1
- import { Effect } from 'effect';
1
+ import { Effect, pipe, Option, Console } from 'effect';
2
2
  import { lexicographicSortSchema, printSchema } from '@effect-gql/core';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
3
+ import * as fs3 from 'fs';
4
+ import * as path2 from 'path';
5
+ import * as readline from 'readline';
6
+ import { spawn } from 'child_process';
5
7
 
6
8
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
7
9
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -10,8 +12,8 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
10
12
  throw Error('Dynamic require of "' + x + '" is not supported');
11
13
  });
12
14
  var loadSchema = (modulePath) => Effect.gen(function* () {
13
- const absolutePath = path.resolve(process.cwd(), modulePath);
14
- if (!fs.existsSync(absolutePath)) {
15
+ const absolutePath = path2.resolve(process.cwd(), modulePath);
16
+ if (!fs3.existsSync(absolutePath)) {
15
17
  return yield* Effect.fail(new Error(`File not found: ${absolutePath}`));
16
18
  }
17
19
  const module = yield* Effect.tryPromise({
@@ -50,6 +52,1122 @@ var generateSDL = (schema, options = {}) => {
50
52
  };
51
53
  var generateSDLFromModule = (modulePath, options = {}) => loadSchema(modulePath).pipe(Effect.map((schema) => generateSDL(schema, options)));
52
54
 
53
- export { generateSDL, generateSDLFromModule, loadSchema };
55
+ // src/commands/create/types.ts
56
+ var SERVER_TYPES = ["node", "bun", "express", "web"];
57
+ var isValidServerType = (value) => SERVER_TYPES.includes(value);
58
+ var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
59
+ var isValidPackageManager = (value) => PACKAGE_MANAGERS.includes(value);
60
+
61
+ // src/commands/create/args.ts
62
+ var parseArgs = (args) => {
63
+ const positional = [];
64
+ let serverType;
65
+ let directory = Option.none();
66
+ let monorepo = Option.none();
67
+ let skipInstall = false;
68
+ let packageManager = Option.none();
69
+ let interactive = false;
70
+ for (let i = 0; i < args.length; i++) {
71
+ const arg = args[i];
72
+ if (arg === "-h" || arg === "--help") {
73
+ return { help: true };
74
+ } else if (arg === "-i" || arg === "--interactive") {
75
+ interactive = true;
76
+ } else if (arg === "-s" || arg === "--server-type") {
77
+ const value = args[++i];
78
+ if (!value) {
79
+ return { error: "Missing value for --server-type" };
80
+ }
81
+ if (!isValidServerType(value)) {
82
+ return {
83
+ error: `Invalid server type: ${value}. Must be one of: ${SERVER_TYPES.join(", ")}`
84
+ };
85
+ }
86
+ serverType = value;
87
+ } else if (arg === "-d" || arg === "--directory") {
88
+ const value = args[++i];
89
+ if (!value) {
90
+ return { error: "Missing value for --directory" };
91
+ }
92
+ directory = Option.some(value);
93
+ } else if (arg === "--monorepo") {
94
+ monorepo = Option.some(true);
95
+ } else if (arg === "--skip-install") {
96
+ skipInstall = true;
97
+ } else if (arg === "--package-manager") {
98
+ const value = args[++i];
99
+ if (!value) {
100
+ return { error: "Missing value for --package-manager" };
101
+ }
102
+ if (!isValidPackageManager(value)) {
103
+ return { error: `Invalid package manager: ${value}. Must be one of: npm, pnpm, yarn, bun` };
104
+ }
105
+ packageManager = Option.some(value);
106
+ } else if (!arg.startsWith("-")) {
107
+ positional.push(arg);
108
+ } else {
109
+ return { error: `Unknown option: ${arg}` };
110
+ }
111
+ }
112
+ if (interactive) {
113
+ return { interactive: true };
114
+ }
115
+ if (args.length === 0) {
116
+ return { interactive: true };
117
+ }
118
+ if (positional.length === 0) {
119
+ return {
120
+ error: "Missing project name. Use --interactive or provide: effect-gql create <name> --server-type <type>"
121
+ };
122
+ }
123
+ if (!serverType) {
124
+ return { error: "Missing --server-type. Must be one of: " + SERVER_TYPES.join(", ") };
125
+ }
126
+ const options = {
127
+ name: positional[0],
128
+ serverType,
129
+ directory,
130
+ monorepo,
131
+ skipInstall,
132
+ packageManager
133
+ };
134
+ return { options };
135
+ };
136
+
137
+ // src/commands/create/templates/package-json.ts
138
+ var VERSIONS = {
139
+ core: "^1.3.0",
140
+ node: "^1.3.0",
141
+ bun: "^1.3.0",
142
+ express: "^1.3.0",
143
+ web: "^1.3.0",
144
+ effect: "^3.19.0",
145
+ platform: "^0.94.0",
146
+ platformNode: "^0.104.0",
147
+ platformBun: "^0.87.0",
148
+ graphql: "^16.0.0",
149
+ expressLib: "^5.0.0",
150
+ tsx: "^4.19.0",
151
+ typescript: "^5.0.0"
152
+ };
153
+ var getDependencies = (serverType, _isMonorepo) => {
154
+ const baseDeps = {
155
+ "@effect-gql/core": VERSIONS.core,
156
+ "@effect/platform": VERSIONS.platform,
157
+ effect: VERSIONS.effect,
158
+ graphql: VERSIONS.graphql
159
+ };
160
+ const baseDevDeps = {
161
+ tsx: VERSIONS.tsx,
162
+ typescript: VERSIONS.typescript
163
+ };
164
+ switch (serverType) {
165
+ case "node":
166
+ return {
167
+ dependencies: {
168
+ ...baseDeps,
169
+ "@effect-gql/node": VERSIONS.node,
170
+ "@effect/platform-node": VERSIONS.platformNode
171
+ },
172
+ devDependencies: baseDevDeps
173
+ };
174
+ case "bun":
175
+ return {
176
+ dependencies: {
177
+ ...baseDeps,
178
+ "@effect-gql/bun": VERSIONS.bun,
179
+ "@effect/platform-bun": VERSIONS.platformBun
180
+ },
181
+ devDependencies: {
182
+ typescript: VERSIONS.typescript
183
+ // Bun has built-in TypeScript support, no tsx needed
184
+ }
185
+ };
186
+ case "express":
187
+ return {
188
+ dependencies: {
189
+ ...baseDeps,
190
+ "@effect-gql/express": VERSIONS.express,
191
+ express: VERSIONS.expressLib
192
+ },
193
+ devDependencies: {
194
+ ...baseDevDeps,
195
+ "@types/express": "^5.0.0"
196
+ }
197
+ };
198
+ case "web":
199
+ return {
200
+ dependencies: {
201
+ ...baseDeps,
202
+ "@effect-gql/web": VERSIONS.web
203
+ },
204
+ devDependencies: baseDevDeps
205
+ };
206
+ }
207
+ };
208
+ var getScripts = (serverType) => {
209
+ switch (serverType) {
210
+ case "node":
211
+ return {
212
+ start: "tsx src/index.ts",
213
+ dev: "tsx watch src/index.ts",
214
+ build: "tsc",
215
+ typecheck: "tsc --noEmit"
216
+ };
217
+ case "bun":
218
+ return {
219
+ start: "bun run src/index.ts",
220
+ dev: "bun --watch src/index.ts",
221
+ build: "bun build src/index.ts --outdir dist --target bun",
222
+ typecheck: "tsc --noEmit"
223
+ };
224
+ case "express":
225
+ return {
226
+ start: "tsx src/index.ts",
227
+ dev: "tsx watch src/index.ts",
228
+ build: "tsc",
229
+ typecheck: "tsc --noEmit"
230
+ };
231
+ case "web":
232
+ return {
233
+ start: "tsx src/index.ts",
234
+ dev: "tsx watch src/index.ts",
235
+ build: "tsc",
236
+ typecheck: "tsc --noEmit"
237
+ // Users will typically add wrangler/deno commands as needed
238
+ };
239
+ }
240
+ };
241
+ var generatePackageJson = (ctx) => {
242
+ const deps = getDependencies(ctx.serverType);
243
+ const pkg = {
244
+ name: ctx.name,
245
+ version: "0.0.1",
246
+ private: true,
247
+ type: "module",
248
+ scripts: getScripts(ctx.serverType),
249
+ dependencies: deps.dependencies,
250
+ devDependencies: deps.devDependencies
251
+ };
252
+ return JSON.stringify(pkg, null, 2) + "\n";
253
+ };
254
+
255
+ // src/commands/create/templates/tsconfig.ts
256
+ var generateTsConfig = (ctx) => {
257
+ const config = ctx.isMonorepo ? {
258
+ // In a monorepo, extend from root tsconfig
259
+ extends: "../../tsconfig.json",
260
+ compilerOptions: {
261
+ outDir: "./dist",
262
+ rootDir: "./src",
263
+ noEmit: true
264
+ },
265
+ include: ["src/**/*"],
266
+ exclude: ["node_modules", "dist"]
267
+ } : {
268
+ // Standalone project config
269
+ compilerOptions: {
270
+ target: "ES2022",
271
+ module: "NodeNext",
272
+ moduleResolution: "NodeNext",
273
+ lib: ["ES2022"],
274
+ outDir: "./dist",
275
+ rootDir: "./src",
276
+ strict: true,
277
+ esModuleInterop: true,
278
+ skipLibCheck: true,
279
+ forceConsistentCasingInFileNames: true,
280
+ declaration: true,
281
+ declarationMap: true,
282
+ sourceMap: true,
283
+ noEmit: true,
284
+ // Effect requires these for decorators
285
+ experimentalDecorators: true,
286
+ emitDecoratorMetadata: true
287
+ },
288
+ include: ["src/**/*"],
289
+ exclude: ["node_modules", "dist"]
290
+ };
291
+ return JSON.stringify(config, null, 2) + "\n";
292
+ };
293
+
294
+ // src/commands/create/templates/server.ts
295
+ var generateNodeServer = (ctx) => `/**
296
+ * ${ctx.name} - GraphQL Server
297
+ *
298
+ * A GraphQL server built with Effect GQL and Node.js.
299
+ */
300
+
301
+ import { Effect, Layer } from "effect"
302
+ import * as S from "effect/Schema"
303
+ import { HttpRouter, HttpServerResponse } from "@effect/platform"
304
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
305
+ import { serve } from "@effect-gql/node"
306
+
307
+ // =============================================================================
308
+ // Domain Models
309
+ // =============================================================================
310
+
311
+ /**
312
+ * Define your types with Effect Schema.
313
+ * This single definition is used for both TypeScript types AND GraphQL types.
314
+ */
315
+ const User = S.Struct({
316
+ id: S.String,
317
+ name: S.String,
318
+ email: S.String,
319
+ })
320
+
321
+ type User = S.Schema.Type<typeof User>
322
+
323
+ // =============================================================================
324
+ // In-Memory Data Store (replace with your database)
325
+ // =============================================================================
326
+
327
+ const users: User[] = [
328
+ { id: "1", name: "Alice", email: "alice@example.com" },
329
+ { id: "2", name: "Bob", email: "bob@example.com" },
330
+ ]
331
+
332
+ // =============================================================================
333
+ // GraphQL Schema
334
+ // =============================================================================
335
+
336
+ const schema = GraphQLSchemaBuilder.empty
337
+ .pipe(
338
+ // Simple query
339
+ query("hello", {
340
+ type: S.String,
341
+ description: "Returns a friendly greeting",
342
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
343
+ }),
344
+
345
+ // Query with arguments
346
+ query("user", {
347
+ args: S.Struct({ id: S.String }),
348
+ type: S.NullOr(User),
349
+ description: "Get a user by ID",
350
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
351
+ }),
352
+
353
+ // Query that returns a list
354
+ query("users", {
355
+ type: S.Array(User),
356
+ description: "Get all users",
357
+ resolve: () => Effect.succeed(users),
358
+ }),
359
+
360
+ // Mutation
361
+ mutation("createUser", {
362
+ args: S.Struct({
363
+ name: S.String,
364
+ email: S.String,
365
+ }),
366
+ type: User,
367
+ description: "Create a new user",
368
+ resolve: (args) =>
369
+ Effect.sync(() => {
370
+ const newUser: User = {
371
+ id: String(users.length + 1),
372
+ name: args.name,
373
+ email: args.email,
374
+ }
375
+ users.push(newUser)
376
+ return newUser
377
+ }),
378
+ })
379
+ )
380
+ .buildSchema()
381
+
382
+ // =============================================================================
383
+ // HTTP Router
384
+ // =============================================================================
385
+
386
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
387
+ path: "/graphql",
388
+ graphiql: {
389
+ path: "/graphiql",
390
+ endpoint: "/graphql",
391
+ },
392
+ })
393
+
394
+ const router = HttpRouter.empty.pipe(
395
+ HttpRouter.get("/health", HttpServerResponse.json({ status: "ok" })),
396
+ HttpRouter.concat(graphqlRouter)
397
+ )
398
+
399
+ // =============================================================================
400
+ // Server Startup
401
+ // =============================================================================
402
+
403
+ serve(router, Layer.empty, {
404
+ port: 4000,
405
+ onStart: (url: string) => {
406
+ console.log(\`Server ready at \${url}\`)
407
+ console.log(\`GraphQL endpoint: \${url}/graphql\`)
408
+ console.log(\`GraphiQL playground: \${url}/graphiql\`)
409
+ console.log(\`Health check: \${url}/health\`)
410
+ },
411
+ })
412
+ `;
413
+ var generateBunServer = (ctx) => `/**
414
+ * ${ctx.name} - GraphQL Server
415
+ *
416
+ * A GraphQL server built with Effect GQL and Bun.
417
+ */
418
+
419
+ import { Effect, Layer } from "effect"
420
+ import * as S from "effect/Schema"
421
+ import { HttpRouter, HttpServerResponse } from "@effect/platform"
422
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
423
+ import { serve } from "@effect-gql/bun"
424
+
425
+ // =============================================================================
426
+ // Domain Models
427
+ // =============================================================================
428
+
429
+ const User = S.Struct({
430
+ id: S.String,
431
+ name: S.String,
432
+ email: S.String,
433
+ })
434
+
435
+ type User = S.Schema.Type<typeof User>
436
+
437
+ // =============================================================================
438
+ // In-Memory Data Store (replace with your database)
439
+ // =============================================================================
440
+
441
+ const users: User[] = [
442
+ { id: "1", name: "Alice", email: "alice@example.com" },
443
+ { id: "2", name: "Bob", email: "bob@example.com" },
444
+ ]
445
+
446
+ // =============================================================================
447
+ // GraphQL Schema
448
+ // =============================================================================
449
+
450
+ const schema = GraphQLSchemaBuilder.empty
451
+ .pipe(
452
+ query("hello", {
453
+ type: S.String,
454
+ description: "Returns a friendly greeting",
455
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
456
+ }),
457
+
458
+ query("user", {
459
+ args: S.Struct({ id: S.String }),
460
+ type: S.NullOr(User),
461
+ description: "Get a user by ID",
462
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
463
+ }),
464
+
465
+ query("users", {
466
+ type: S.Array(User),
467
+ description: "Get all users",
468
+ resolve: () => Effect.succeed(users),
469
+ }),
470
+
471
+ mutation("createUser", {
472
+ args: S.Struct({
473
+ name: S.String,
474
+ email: S.String,
475
+ }),
476
+ type: User,
477
+ description: "Create a new user",
478
+ resolve: (args) =>
479
+ Effect.sync(() => {
480
+ const newUser: User = {
481
+ id: String(users.length + 1),
482
+ name: args.name,
483
+ email: args.email,
484
+ }
485
+ users.push(newUser)
486
+ return newUser
487
+ }),
488
+ })
489
+ )
490
+ .buildSchema()
491
+
492
+ // =============================================================================
493
+ // HTTP Router
494
+ // =============================================================================
495
+
496
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
497
+ path: "/graphql",
498
+ graphiql: {
499
+ path: "/graphiql",
500
+ endpoint: "/graphql",
501
+ },
502
+ })
503
+
504
+ const router = HttpRouter.empty.pipe(
505
+ HttpRouter.get("/health", HttpServerResponse.json({ status: "ok" })),
506
+ HttpRouter.concat(graphqlRouter)
507
+ )
508
+
509
+ // =============================================================================
510
+ // Server Startup
511
+ // =============================================================================
512
+
513
+ serve(router, Layer.empty, {
514
+ port: 4000,
515
+ onStart: (url: string) => {
516
+ console.log(\`Server ready at \${url}\`)
517
+ console.log(\`GraphQL endpoint: \${url}/graphql\`)
518
+ console.log(\`GraphiQL playground: \${url}/graphiql\`)
519
+ console.log(\`Health check: \${url}/health\`)
520
+ },
521
+ })
522
+ `;
523
+ var generateExpressServer = (ctx) => `/**
524
+ * ${ctx.name} - GraphQL Server
525
+ *
526
+ * A GraphQL server built with Effect GQL and Express.
527
+ */
528
+
529
+ import express from "express"
530
+ import { Effect, Layer } from "effect"
531
+ import * as S from "effect/Schema"
532
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
533
+ import { toMiddleware } from "@effect-gql/express"
534
+
535
+ // =============================================================================
536
+ // Domain Models
537
+ // =============================================================================
538
+
539
+ const User = S.Struct({
540
+ id: S.String,
541
+ name: S.String,
542
+ email: S.String,
543
+ })
544
+
545
+ type User = S.Schema.Type<typeof User>
546
+
547
+ // =============================================================================
548
+ // In-Memory Data Store (replace with your database)
549
+ // =============================================================================
550
+
551
+ const users: User[] = [
552
+ { id: "1", name: "Alice", email: "alice@example.com" },
553
+ { id: "2", name: "Bob", email: "bob@example.com" },
554
+ ]
555
+
556
+ // =============================================================================
557
+ // GraphQL Schema
558
+ // =============================================================================
559
+
560
+ const schema = GraphQLSchemaBuilder.empty
561
+ .pipe(
562
+ query("hello", {
563
+ type: S.String,
564
+ description: "Returns a friendly greeting",
565
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
566
+ }),
567
+
568
+ query("user", {
569
+ args: S.Struct({ id: S.String }),
570
+ type: S.NullOr(User),
571
+ description: "Get a user by ID",
572
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
573
+ }),
574
+
575
+ query("users", {
576
+ type: S.Array(User),
577
+ description: "Get all users",
578
+ resolve: () => Effect.succeed(users),
579
+ }),
580
+
581
+ mutation("createUser", {
582
+ args: S.Struct({
583
+ name: S.String,
584
+ email: S.String,
585
+ }),
586
+ type: User,
587
+ description: "Create a new user",
588
+ resolve: (args) =>
589
+ Effect.sync(() => {
590
+ const newUser: User = {
591
+ id: String(users.length + 1),
592
+ name: args.name,
593
+ email: args.email,
594
+ }
595
+ users.push(newUser)
596
+ return newUser
597
+ }),
598
+ })
599
+ )
600
+ .buildSchema()
601
+
602
+ // =============================================================================
603
+ // GraphQL Router
604
+ // =============================================================================
605
+
606
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
607
+ path: "/graphql",
608
+ graphiql: {
609
+ path: "/graphiql",
610
+ endpoint: "/graphql",
611
+ },
612
+ })
613
+
614
+ // =============================================================================
615
+ // Express App
616
+ // =============================================================================
617
+
618
+ const app = express()
619
+ app.use(express.json())
620
+
621
+ // Health check
622
+ app.get("/health", (_, res) => {
623
+ res.json({ status: "ok" })
624
+ })
625
+
626
+ // Mount GraphQL middleware
627
+ app.use(toMiddleware(graphqlRouter, Layer.empty))
628
+
629
+ // =============================================================================
630
+ // Server Startup
631
+ // =============================================================================
632
+
633
+ const port = process.env.PORT || 4000
634
+
635
+ app.listen(port, () => {
636
+ console.log(\`Server ready at http://localhost:\${port}\`)
637
+ console.log(\`GraphQL endpoint: http://localhost:\${port}/graphql\`)
638
+ console.log(\`GraphiQL playground: http://localhost:\${port}/graphiql\`)
639
+ console.log(\`Health check: http://localhost:\${port}/health\`)
640
+ })
641
+ `;
642
+ var generateWebHandler = (ctx) => `/**
643
+ * ${ctx.name} - GraphQL Server
644
+ *
645
+ * A GraphQL server built with Effect GQL using Web standard APIs.
646
+ * Compatible with Cloudflare Workers, Deno, and other WASM runtimes.
647
+ */
648
+
649
+ import { Effect, Layer } from "effect"
650
+ import * as S from "effect/Schema"
651
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
652
+ import { toHandler } from "@effect-gql/web"
653
+
654
+ // =============================================================================
655
+ // Domain Models
656
+ // =============================================================================
657
+
658
+ const User = S.Struct({
659
+ id: S.String,
660
+ name: S.String,
661
+ email: S.String,
662
+ })
663
+
664
+ type User = S.Schema.Type<typeof User>
665
+
666
+ // =============================================================================
667
+ // In-Memory Data Store (replace with your database)
668
+ // =============================================================================
669
+
670
+ const users: User[] = [
671
+ { id: "1", name: "Alice", email: "alice@example.com" },
672
+ { id: "2", name: "Bob", email: "bob@example.com" },
673
+ ]
674
+
675
+ // =============================================================================
676
+ // GraphQL Schema
677
+ // =============================================================================
678
+
679
+ const schema = GraphQLSchemaBuilder.empty
680
+ .pipe(
681
+ query("hello", {
682
+ type: S.String,
683
+ description: "Returns a friendly greeting",
684
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
685
+ }),
686
+
687
+ query("user", {
688
+ args: S.Struct({ id: S.String }),
689
+ type: S.NullOr(User),
690
+ description: "Get a user by ID",
691
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
692
+ }),
693
+
694
+ query("users", {
695
+ type: S.Array(User),
696
+ description: "Get all users",
697
+ resolve: () => Effect.succeed(users),
698
+ }),
699
+
700
+ mutation("createUser", {
701
+ args: S.Struct({
702
+ name: S.String,
703
+ email: S.String,
704
+ }),
705
+ type: User,
706
+ description: "Create a new user",
707
+ resolve: (args) =>
708
+ Effect.sync(() => {
709
+ const newUser: User = {
710
+ id: String(users.length + 1),
711
+ name: args.name,
712
+ email: args.email,
713
+ }
714
+ users.push(newUser)
715
+ return newUser
716
+ }),
717
+ })
718
+ )
719
+ .buildSchema()
720
+
721
+ // =============================================================================
722
+ // GraphQL Router
723
+ // =============================================================================
724
+
725
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
726
+ path: "/graphql",
727
+ graphiql: {
728
+ path: "/graphiql",
729
+ endpoint: "/graphql",
730
+ },
731
+ })
732
+
733
+ // =============================================================================
734
+ // Web Handler
735
+ // =============================================================================
736
+
737
+ const { handler } = toHandler(graphqlRouter, Layer.empty)
738
+
739
+ /**
740
+ * Export for Cloudflare Workers
741
+ */
742
+ export default {
743
+ async fetch(request: Request): Promise<Response> {
744
+ const url = new URL(request.url)
745
+
746
+ // Health check
747
+ if (url.pathname === "/health") {
748
+ return new Response(JSON.stringify({ status: "ok" }), {
749
+ headers: { "Content-Type": "application/json" },
750
+ })
751
+ }
752
+
753
+ return handler(request)
754
+ },
755
+ }
756
+
757
+ /**
758
+ * For local development with Deno or other runtimes, you can use:
759
+ *
760
+ * Deno.serve((request) => {
761
+ * const url = new URL(request.url)
762
+ * if (url.pathname === "/health") {
763
+ * return new Response(JSON.stringify({ status: "ok" }), {
764
+ * headers: { "Content-Type": "application/json" },
765
+ * })
766
+ * }
767
+ * return handler(request)
768
+ * })
769
+ */
770
+ `;
771
+ var generateServerTemplate = (ctx) => {
772
+ switch (ctx.serverType) {
773
+ case "node":
774
+ return generateNodeServer(ctx);
775
+ case "bun":
776
+ return generateBunServer(ctx);
777
+ case "express":
778
+ return generateExpressServer(ctx);
779
+ case "web":
780
+ return generateWebHandler(ctx);
781
+ }
782
+ };
783
+
784
+ // src/commands/create/templates/index.ts
785
+ var generateGitignore = () => `# Dependencies
786
+ node_modules/
787
+
788
+ # Build output
789
+ dist/
790
+ *.tsbuildinfo
791
+
792
+ # IDE
793
+ .idea/
794
+ .vscode/
795
+ *.swp
796
+ *.swo
797
+
798
+ # OS
799
+ .DS_Store
800
+ Thumbs.db
801
+
802
+ # Environment
803
+ .env
804
+ .env.local
805
+ .env.*.local
806
+
807
+ # Logs
808
+ *.log
809
+ npm-debug.log*
810
+ yarn-debug.log*
811
+ yarn-error.log*
812
+
813
+ # Testing
814
+ coverage/
815
+ `;
816
+ var generateProject = (ctx) => [
817
+ {
818
+ path: "package.json",
819
+ content: generatePackageJson(ctx)
820
+ },
821
+ {
822
+ path: "tsconfig.json",
823
+ content: generateTsConfig(ctx)
824
+ },
825
+ {
826
+ path: "src/index.ts",
827
+ content: generateServerTemplate(ctx)
828
+ },
829
+ {
830
+ path: ".gitignore",
831
+ content: generateGitignore()
832
+ }
833
+ ];
834
+ var fileExists = (filePath) => Effect.sync(() => fs3.existsSync(filePath));
835
+ var readFile = (filePath) => Effect.try({
836
+ try: () => fs3.readFileSync(filePath, "utf-8"),
837
+ catch: (error) => new Error(`Failed to read ${filePath}: ${error}`)
838
+ });
839
+ var detectPackageManager = (dir) => Effect.gen(function* () {
840
+ if (yield* fileExists(path2.join(dir, "pnpm-lock.yaml"))) return "pnpm";
841
+ if (yield* fileExists(path2.join(dir, "bun.lockb"))) return "bun";
842
+ if (yield* fileExists(path2.join(dir, "yarn.lock"))) return "yarn";
843
+ return "npm";
844
+ });
845
+ var detectMonorepo = (targetDir) => Effect.gen(function* () {
846
+ let currentDir = path2.dirname(path2.resolve(targetDir));
847
+ const root = path2.parse(currentDir).root;
848
+ while (currentDir !== root) {
849
+ const pnpmWorkspacePath = path2.join(currentDir, "pnpm-workspace.yaml");
850
+ if (yield* fileExists(pnpmWorkspacePath)) {
851
+ return {
852
+ isMonorepo: true,
853
+ packageManager: Option.some("pnpm"),
854
+ workspacesRoot: Option.some(currentDir)
855
+ };
856
+ }
857
+ const pkgPath = path2.join(currentDir, "package.json");
858
+ if (yield* fileExists(pkgPath)) {
859
+ const content = yield* readFile(pkgPath).pipe(Effect.catchAll(() => Effect.succeed("")));
860
+ if (content) {
861
+ try {
862
+ const pkg = JSON.parse(content);
863
+ if (pkg.workspaces) {
864
+ const pm = yield* detectPackageManager(currentDir);
865
+ return {
866
+ isMonorepo: true,
867
+ packageManager: Option.some(pm),
868
+ workspacesRoot: Option.some(currentDir)
869
+ };
870
+ }
871
+ } catch {
872
+ }
873
+ }
874
+ }
875
+ const turboPath = path2.join(currentDir, "turbo.json");
876
+ if (yield* fileExists(turboPath)) {
877
+ const pm = yield* detectPackageManager(currentDir);
878
+ return {
879
+ isMonorepo: true,
880
+ packageManager: Option.some(pm),
881
+ workspacesRoot: Option.some(currentDir)
882
+ };
883
+ }
884
+ currentDir = path2.dirname(currentDir);
885
+ }
886
+ return {
887
+ isMonorepo: false,
888
+ packageManager: Option.none(),
889
+ workspacesRoot: Option.none()
890
+ };
891
+ });
892
+ var getInstallCommand = (pm) => {
893
+ switch (pm) {
894
+ case "npm":
895
+ return "npm install";
896
+ case "pnpm":
897
+ return "pnpm install";
898
+ case "yarn":
899
+ return "yarn";
900
+ case "bun":
901
+ return "bun install";
902
+ }
903
+ };
904
+ var getRunPrefix = (pm) => {
905
+ switch (pm) {
906
+ case "npm":
907
+ return "npm run";
908
+ case "pnpm":
909
+ return "pnpm";
910
+ case "yarn":
911
+ return "yarn";
912
+ case "bun":
913
+ return "bun run";
914
+ }
915
+ };
916
+
917
+ // src/commands/create/scaffolder.ts
918
+ var validateDirectory = (targetDir) => Effect.try({
919
+ try: () => {
920
+ if (fs3.existsSync(targetDir)) {
921
+ const files = fs3.readdirSync(targetDir);
922
+ if (files.length > 0) {
923
+ throw new Error(`Directory ${targetDir} is not empty`);
924
+ }
925
+ }
926
+ },
927
+ catch: (error) => error instanceof Error ? error : new Error(`Failed to validate directory: ${error}`)
928
+ });
929
+ var mkdirp = (dir) => Effect.try({
930
+ try: () => fs3.mkdirSync(dir, { recursive: true }),
931
+ catch: (error) => new Error(`Failed to create directory ${dir}: ${error}`)
932
+ });
933
+ var writeFile = (filePath, content) => Effect.gen(function* () {
934
+ yield* mkdirp(path2.dirname(filePath));
935
+ yield* Effect.try({
936
+ try: () => fs3.writeFileSync(filePath, content, "utf-8"),
937
+ catch: (error) => new Error(`Failed to write ${filePath}: ${error}`)
938
+ });
939
+ });
940
+ var runCommand = (command, args, cwd) => Effect.async((resume) => {
941
+ const child = spawn(command, args, {
942
+ cwd,
943
+ stdio: "inherit",
944
+ shell: true
945
+ });
946
+ child.on("close", (code) => {
947
+ if (code === 0) {
948
+ resume(Effect.succeed(void 0));
949
+ } else {
950
+ resume(Effect.fail(new Error(`Command failed with exit code ${code}`)));
951
+ }
952
+ });
953
+ child.on("error", (error) => {
954
+ resume(Effect.fail(new Error(`Failed to run command: ${error.message}`)));
955
+ });
956
+ return Effect.sync(() => {
957
+ child.kill();
958
+ });
959
+ });
960
+ var installDependencies = (targetDir, packageManager) => Effect.gen(function* () {
961
+ yield* Console.log("");
962
+ yield* Console.log("Installing dependencies...");
963
+ const installCmd = getInstallCommand(packageManager);
964
+ const [cmd, ...args] = installCmd.split(" ");
965
+ yield* runCommand(cmd, args, targetDir);
966
+ yield* Console.log("Dependencies installed successfully!");
967
+ });
968
+ var printSuccessMessage = (ctx, targetDir) => Effect.gen(function* () {
969
+ const relativePath = path2.relative(process.cwd(), targetDir) || ".";
970
+ const runPrefix = getRunPrefix(ctx.packageManager);
971
+ yield* Console.log("");
972
+ yield* Console.log(`Successfully created ${ctx.name}!`);
973
+ yield* Console.log("");
974
+ yield* Console.log("Next steps:");
975
+ yield* Console.log(` cd ${relativePath}`);
976
+ yield* Console.log(` ${runPrefix} dev`);
977
+ yield* Console.log("");
978
+ yield* Console.log("Your GraphQL server will be available at:");
979
+ yield* Console.log(" http://localhost:4000/graphql");
980
+ yield* Console.log(" http://localhost:4000/graphiql (playground)");
981
+ yield* Console.log("");
982
+ });
983
+ var scaffold = (options) => Effect.gen(function* () {
984
+ const targetDir = pipe(
985
+ options.directory,
986
+ Option.map((dir) => path2.resolve(process.cwd(), dir)),
987
+ Option.getOrElse(() => path2.resolve(process.cwd(), options.name))
988
+ );
989
+ const monorepoInfo = yield* detectMonorepo(targetDir);
990
+ const isMonorepo = pipe(
991
+ options.monorepo,
992
+ Option.getOrElse(() => monorepoInfo.isMonorepo)
993
+ );
994
+ const packageManager = yield* pipe(
995
+ options.packageManager,
996
+ Option.orElse(() => monorepoInfo.packageManager),
997
+ Option.match({
998
+ onNone: () => detectPackageManager(process.cwd()),
999
+ onSome: (pm) => Effect.succeed(pm)
1000
+ })
1001
+ );
1002
+ const ctx = {
1003
+ name: options.name,
1004
+ serverType: options.serverType,
1005
+ isMonorepo,
1006
+ packageManager
1007
+ };
1008
+ yield* Console.log("");
1009
+ yield* Console.log(`Creating ${ctx.name} with ${ctx.serverType} server...`);
1010
+ yield* validateDirectory(targetDir);
1011
+ const files = generateProject(ctx);
1012
+ for (const file of files) {
1013
+ const filePath = path2.join(targetDir, file.path);
1014
+ yield* writeFile(filePath, file.content);
1015
+ yield* Console.log(` Created ${file.path}`);
1016
+ }
1017
+ if (!options.skipInstall) {
1018
+ yield* installDependencies(targetDir, packageManager).pipe(
1019
+ Effect.catchAll(
1020
+ (error) => Console.log(`Warning: Failed to install dependencies: ${error.message}`).pipe(
1021
+ Effect.andThen(
1022
+ Console.log(
1023
+ "You can install them manually by running: " + getInstallCommand(packageManager)
1024
+ )
1025
+ )
1026
+ )
1027
+ )
1028
+ );
1029
+ } else {
1030
+ yield* Console.log("");
1031
+ yield* Console.log(
1032
+ `Skipping dependency installation. Run '${getInstallCommand(packageManager)}' to install.`
1033
+ );
1034
+ }
1035
+ yield* printSuccessMessage(ctx, targetDir);
1036
+ });
1037
+
1038
+ // src/commands/create/index.ts
1039
+ var printCreateHelp = () => {
1040
+ console.log(`
1041
+ Usage: effect-gql create <name> --server-type <type> [options]
1042
+
1043
+ Create a new Effect GraphQL project.
1044
+
1045
+ Arguments:
1046
+ name Package/project name
1047
+
1048
+ Required Options:
1049
+ -s, --server-type Server type: node, bun, express, web
1050
+
1051
+ Optional Options:
1052
+ -d, --directory Target directory (default: ./<name>)
1053
+ --monorepo Create as workspace package (auto-detected)
1054
+ --skip-install Skip dependency installation
1055
+ --package-manager Package manager: npm, pnpm, yarn, bun
1056
+ -i, --interactive Interactive mode (prompts for options)
1057
+ -h, --help Show this help message
1058
+
1059
+ Server Types:
1060
+ node Node.js server using @effect-gql/node
1061
+ Best for: General Node.js deployments
1062
+
1063
+ bun Bun server using @effect-gql/bun
1064
+ Best for: Bun runtime with native WebSocket support
1065
+
1066
+ express Express middleware using @effect-gql/express
1067
+ Best for: Integrating into existing Express apps
1068
+
1069
+ web Web standard handler using @effect-gql/web
1070
+ Best for: Cloudflare Workers, Deno, edge runtimes
1071
+
1072
+ Examples:
1073
+ effect-gql create my-api --server-type node
1074
+ effect-gql create my-api -s bun
1075
+ effect-gql create my-api -s express -d ./packages/api --monorepo
1076
+ effect-gql create my-api -s web --skip-install
1077
+ effect-gql create --interactive
1078
+ `);
1079
+ };
1080
+ var prompt = (question) => Effect.async((resume) => {
1081
+ const rl = readline.createInterface({
1082
+ input: process.stdin,
1083
+ output: process.stdout
1084
+ });
1085
+ rl.question(question, (answer) => {
1086
+ rl.close();
1087
+ resume(Effect.succeed(answer.trim()));
1088
+ });
1089
+ rl.on("error", (error) => {
1090
+ rl.close();
1091
+ resume(Effect.fail(new Error(`Input error: ${error.message}`)));
1092
+ });
1093
+ return Effect.sync(() => rl.close());
1094
+ });
1095
+ var selectPrompt = (question, options) => Effect.gen(function* () {
1096
+ yield* Console.log(question);
1097
+ options.forEach((opt, i) => {
1098
+ console.log(` ${i + 1}) ${opt.label}`);
1099
+ });
1100
+ const answer = yield* prompt("Enter number: ");
1101
+ const index = parseInt(answer, 10) - 1;
1102
+ if (isNaN(index) || index < 0 || index >= options.length) {
1103
+ yield* Console.log(`Invalid selection. Please enter 1-${options.length}.`);
1104
+ return yield* selectPrompt(question, options);
1105
+ }
1106
+ return options[index].value;
1107
+ });
1108
+ var confirmPrompt = (question, defaultValue) => Effect.gen(function* () {
1109
+ const hint = "[y/N]";
1110
+ const answer = yield* prompt(`${question} ${hint} `);
1111
+ if (answer === "") return defaultValue;
1112
+ const lower = answer.toLowerCase();
1113
+ if (lower === "y" || lower === "yes") return true;
1114
+ if (lower === "n" || lower === "no") return false;
1115
+ yield* Console.log("Please answer 'y' or 'n'.");
1116
+ return yield* confirmPrompt(question, defaultValue);
1117
+ });
1118
+ var runInteractive = () => Effect.gen(function* () {
1119
+ yield* Console.log("");
1120
+ yield* Console.log("Create a new Effect GraphQL project");
1121
+ yield* Console.log("====================================");
1122
+ yield* Console.log("");
1123
+ const name = yield* prompt("Project name: ");
1124
+ if (!name) {
1125
+ return yield* Effect.fail(new Error("Project name is required"));
1126
+ }
1127
+ if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
1128
+ yield* Console.log("Warning: Name may not be a valid npm package name.");
1129
+ }
1130
+ const serverType = yield* selectPrompt("Select server type:", [
1131
+ { label: "Node.js (@effect-gql/node)", value: "node" },
1132
+ { label: "Bun (@effect-gql/bun)", value: "bun" },
1133
+ { label: "Express (@effect-gql/express)", value: "express" },
1134
+ { label: "Web/Workers (@effect-gql/web)", value: "web" }
1135
+ ]);
1136
+ const monorepo = yield* confirmPrompt("Create as monorepo workspace package?", false);
1137
+ const packageManager = monorepo ? Option.some(
1138
+ yield* selectPrompt("Select package manager:", [
1139
+ { label: "pnpm", value: "pnpm" },
1140
+ { label: "npm", value: "npm" },
1141
+ { label: "yarn", value: "yarn" },
1142
+ { label: "bun", value: "bun" }
1143
+ ])
1144
+ ) : Option.none();
1145
+ return {
1146
+ name,
1147
+ serverType,
1148
+ directory: Option.none(),
1149
+ monorepo: Option.some(monorepo),
1150
+ skipInstall: false,
1151
+ packageManager
1152
+ };
1153
+ });
1154
+ var runCreate = (args) => Effect.gen(function* () {
1155
+ const parsed = parseArgs(args);
1156
+ if ("help" in parsed) {
1157
+ printCreateHelp();
1158
+ return;
1159
+ }
1160
+ if ("error" in parsed) {
1161
+ yield* Console.error(`Error: ${parsed.error}`);
1162
+ yield* Console.log("");
1163
+ printCreateHelp();
1164
+ process.exitCode = 1;
1165
+ return;
1166
+ }
1167
+ const options = "interactive" in parsed ? yield* runInteractive() : parsed.options;
1168
+ yield* scaffold(options);
1169
+ });
1170
+
1171
+ export { SERVER_TYPES, generateSDL, generateSDLFromModule, isValidServerType, loadSchema, printCreateHelp, runCreate, scaffold };
54
1172
  //# sourceMappingURL=index.js.map
55
1173
  //# sourceMappingURL=index.js.map