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