create-guren-app 1.3.0 → 1.5.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.
Files changed (69) hide show
  1. package/README.md +17 -1
  2. package/dist/cli.js +191 -239
  3. package/package.json +1 -1
  4. package/templates/api-only/.github/workflows/ci.yml +35 -0
  5. package/templates/api-only/README.md +2 -0
  6. package/templates/api-only/_gitignore +6 -0
  7. package/templates/api-only/bin/console.ts +13 -0
  8. package/templates/api-only/config/app.ts +12 -1
  9. package/templates/api-only/docs/adr/0001-record-architecture-decisions.md +10 -5
  10. package/templates/api-only/package.json +6 -7
  11. package/templates/api-only/src/console.ts +9 -0
  12. package/templates/api-only/tests/app.test.ts +24 -0
  13. package/templates/blog/.guren/api-client.gen.ts +184 -0
  14. package/templates/blog/.guren/data.gen.ts +23 -0
  15. package/templates/blog/.guren/pages.gen.ts +99 -0
  16. package/templates/blog/.guren/routes.gen.ts +138 -0
  17. package/templates/blog/README.md +85 -0
  18. package/templates/blog/app/Http/Controllers/Auth/LoginController.ts +30 -0
  19. package/templates/blog/app/Http/Controllers/Auth/RegisterController.ts +28 -0
  20. package/templates/blog/app/Http/Controllers/DashboardController.ts +17 -0
  21. package/templates/blog/app/Http/Controllers/HomeController.ts +22 -0
  22. package/templates/blog/app/Http/Controllers/PostController.ts +83 -0
  23. package/templates/blog/app/Http/Controllers/ProfileController.ts +54 -0
  24. package/templates/blog/app/Http/Resources/PostResource.ts +40 -0
  25. package/templates/blog/app/Http/Validators/LoginValidator.ts +27 -0
  26. package/templates/blog/app/Http/Validators/PostValidator.ts +17 -0
  27. package/templates/blog/app/Http/Validators/ProfileValidator.ts +23 -0
  28. package/templates/blog/app/Http/Validators/RegisterValidator.ts +31 -0
  29. package/templates/blog/app/Models/Post.ts +18 -0
  30. package/templates/blog/app/Models/User.ts +27 -0
  31. package/templates/blog/app/Policies/PostPolicy.ts +32 -0
  32. package/templates/blog/app/Providers/AuthProvider.ts +28 -0
  33. package/templates/blog/app/Providers/AuthorizationProvider.ts +19 -0
  34. package/templates/blog/db/schema.mysql.ts +26 -0
  35. package/templates/blog/db/schema.postgres.ts +22 -0
  36. package/templates/blog/db/schema.sqlite.ts +22 -0
  37. package/templates/blog/db/seeders/001_users.ts +23 -0
  38. package/templates/blog/db/seeders/002_posts.ts +32 -0
  39. package/templates/blog/resources/js/components/Layout.tsx +56 -0
  40. package/templates/blog/resources/js/pages/Home.tsx +55 -0
  41. package/templates/blog/resources/js/pages/auth/Login.tsx +108 -0
  42. package/templates/blog/resources/js/pages/auth/Register.tsx +132 -0
  43. package/templates/blog/resources/js/pages/dashboard/Index.tsx +29 -0
  44. package/templates/blog/resources/js/pages/posts/Edit.tsx +79 -0
  45. package/templates/blog/resources/js/pages/posts/Index.tsx +49 -0
  46. package/templates/blog/resources/js/pages/posts/New.tsx +71 -0
  47. package/templates/blog/resources/js/pages/posts/Show.tsx +55 -0
  48. package/templates/blog/resources/js/pages/profile/Edit.tsx +90 -0
  49. package/templates/blog/routes/auth.ts +22 -0
  50. package/templates/blog/routes/web.ts +34 -0
  51. package/templates/blog/src/app.ts +23 -0
  52. package/templates/blog/tests/HomeController.test.ts +19 -0
  53. package/templates/default/.github/workflows/ci.yml +35 -0
  54. package/templates/default/.guren/api-client.gen.ts +76 -4
  55. package/templates/default/README.md +12 -0
  56. package/templates/default/_gitignore +7 -0
  57. package/templates/default/bin/console.ts +13 -0
  58. package/templates/default/config/app.ts +10 -2
  59. package/templates/default/docs/adr/0001-record-architecture-decisions.md +10 -5
  60. package/templates/default/package.json +13 -12
  61. package/templates/default/public/favicon.svg +11 -0
  62. package/templates/default/public/index.html +1 -0
  63. package/templates/default/src/app.ts +7 -0
  64. package/templates/default/src/console.ts +9 -0
  65. package/templates/default/tests/HomeController.test.ts +24 -0
  66. package/templates/default/tsconfig.json +1 -0
  67. package/templates/default/types/generated/_gitignore +2 -0
  68. package/templates/api-only/config/database.ts +0 -21
  69. package/templates/default/config/database.ts +0 -21
package/README.md CHANGED
@@ -6,4 +6,20 @@
6
6
  npx create-guren-app my-app
7
7
  ```
8
8
 
9
- Use `--force` to allow scaffolding into a non-empty directory.
9
+ ## Options
10
+
11
+ | Flag | Description |
12
+ |------|-------------|
13
+ | `--force`, `-f` | Allow scaffolding into a non-empty directory |
14
+ | `--mode <spa\|ssr>` | Rendering mode (prompted when omitted) |
15
+ | `--db <sqlite\|postgres\|mysql>` | Database driver (prompted when omitted) |
16
+ | `--blueprint <name>` | Starter blueprint (`default`, `api`, `worker`) |
17
+ | `--auth` | Include authentication scaffolding |
18
+ | `--no-install` | Skip `bun install` |
19
+ | `--git` / `--no-git` | Initialize a git repository with an initial commit |
20
+
21
+ The scaffolded app ships a `.gitignore`, so `--git` commits only the project
22
+ files — never the generated `.env` (it holds a freshly generated `APP_KEY`).
23
+ When omitted, `--git` is prompted in an interactive terminal and defaults to off
24
+ elsewhere. It is skipped entirely when the target directory already sits inside
25
+ a git repository.
package/dist/cli.js CHANGED
@@ -1562,8 +1562,8 @@ async function runMain(cmd, opts = {}) {
1562
1562
 
1563
1563
  // src/blueprints.ts
1564
1564
  import { randomBytes } from "crypto";
1565
- import { cp, readFile, writeFile } from "fs/promises";
1566
- import { basename, join, relative } from "path";
1565
+ import { cp, readFile, rename, rm, writeFile } from "fs/promises";
1566
+ import { basename, dirname, join, relative } from "path";
1567
1567
  import process2 from "process";
1568
1568
  import { fileURLToPath } from "url";
1569
1569
 
@@ -1580,6 +1580,17 @@ async function directoryExists(path) {
1580
1580
  throw error;
1581
1581
  }
1582
1582
  }
1583
+ async function fileExists(path) {
1584
+ try {
1585
+ const stats = await stat(path);
1586
+ return stats.isFile();
1587
+ } catch (error) {
1588
+ if (error.code === "ENOENT") {
1589
+ return false;
1590
+ }
1591
+ throw error;
1592
+ }
1593
+ }
1583
1594
  async function isDirectoryEmpty(path) {
1584
1595
  try {
1585
1596
  const entries = await readdir(path);
@@ -1617,6 +1628,10 @@ function toPackageName(value) {
1617
1628
  // src/blueprints.ts
1618
1629
  var APP_BLUEPRINTS = ["default", "api", "blog", "worker"];
1619
1630
  var DATABASE_DRIVERS = ["sqlite", "postgres", "mysql"];
1631
+ var TEMPLATES_ROOT = fileURLToPath(new URL("../templates", import.meta.url));
1632
+ function templateDir(name) {
1633
+ return join(TEMPLATES_ROOT, name);
1634
+ }
1620
1635
  var DEFAULT_TRANSFORM_FILES = [
1621
1636
  "README.md",
1622
1637
  "package.json",
@@ -1625,121 +1640,53 @@ var DEFAULT_TRANSFORM_FILES = [
1625
1640
  "app/Http/Controllers/HomeController.ts",
1626
1641
  "resources/js/pages/Home.tsx"
1627
1642
  ];
1628
- var BLOG_TRANSFORM_FILES = [
1629
- "README.md",
1630
- "public/index.html",
1631
- "app/Providers/EventServiceProvider.ts",
1632
- "app/Http/Controllers/Auth/LoginController.ts",
1633
- "app/Http/Controllers/DashboardController.ts",
1634
- "app/Http/Controllers/PostController.ts",
1635
- "app/Http/Controllers/ProfileController.ts",
1636
- "resources/js/components/Layout.tsx"
1637
- ];
1638
1643
  var API_TRANSFORM_FILES = [
1639
1644
  "README.md",
1640
1645
  "package.json",
1641
1646
  "bin/serve.ts"
1642
1647
  ];
1643
- var BLOG_OVERLAY_EXCLUDES = [
1644
- ".env",
1645
- ".guren",
1646
- "CLAUDE.md",
1647
- "db/migrations",
1648
- "db/schema.ts",
1649
- "node_modules",
1650
- "package.json",
1651
- "public/assets",
1652
- "tests",
1653
- "tsconfig.json",
1654
- "types/generated",
1655
- "vitest.config.ts"
1648
+ var BLOG_TRANSFORM_FILES = [
1649
+ ...DEFAULT_TRANSFORM_FILES,
1650
+ "resources/js/components/Layout.tsx",
1651
+ "db/seeders/001_users.ts"
1656
1652
  ];
1657
- var defaultTemplateDir = fileURLToPath(new URL("../templates/default", import.meta.url));
1658
- var defaultSsrOverlayDir = fileURLToPath(new URL("../templates/default-ssr", import.meta.url));
1659
- var apiTemplateDir = fileURLToPath(new URL("../templates/api-only", import.meta.url));
1660
- var exampleBlogDir = fileURLToPath(new URL("../../../examples/blog", import.meta.url));
1661
1653
  var blueprintRegistry = {
1662
1654
  default: {
1663
1655
  name: "default",
1664
1656
  description: "The standard Guren starter blueprint.",
1665
- baseTemplate: {
1666
- dir: defaultTemplateDir
1667
- },
1668
- overlayTemplateDirs: {
1669
- ssr: [{ dir: defaultSsrOverlayDir }]
1657
+ baseTemplate: "default",
1658
+ overlayTemplates: {
1659
+ ssr: ["default-ssr"]
1670
1660
  },
1671
1661
  transformFiles: DEFAULT_TRANSFORM_FILES
1672
1662
  },
1673
1663
  api: {
1674
1664
  name: "api",
1675
1665
  description: "API-only starter \u2014 no Inertia, no React, no frontend assets.",
1676
- baseTemplate: {
1677
- dir: apiTemplateDir
1678
- },
1679
- overlayTemplateDirs: {},
1666
+ baseTemplate: "api-only",
1667
+ overlayTemplates: {},
1680
1668
  transformFiles: API_TRANSFORM_FILES
1681
1669
  },
1682
1670
  blog: {
1683
1671
  name: "blog",
1684
- description: "The canonical blog-style starter used by the examples workspace.",
1685
- baseTemplate: {
1686
- dir: defaultTemplateDir
1672
+ description: "Blog starter \u2014 posts CRUD, session auth, and a seeded demo account.",
1673
+ baseTemplate: "default",
1674
+ // The overlay lands last in both modes so its pages and controllers win, and
1675
+ // SSR still gets `default-ssr` — the blueprint this replaces overlaid only
1676
+ // itself in SSR mode and shipped an app with no ssr.tsx entry.
1677
+ overlayTemplates: {
1678
+ spa: ["blog"],
1679
+ ssr: ["default-ssr", "blog"]
1687
1680
  },
1688
- overlayTemplateDirs: {
1689
- spa: [{ dir: exampleBlogDir, excludePaths: BLOG_OVERLAY_EXCLUDES }],
1690
- ssr: [{ dir: exampleBlogDir, excludePaths: BLOG_OVERLAY_EXCLUDES }]
1691
- },
1692
- transformFiles: [.../* @__PURE__ */ new Set([...DEFAULT_TRANSFORM_FILES, ...BLOG_TRANSFORM_FILES])],
1693
- replacements: ({ appTitle, packageName }) => /* @__PURE__ */ new Map([
1694
- ["@guren/example-blog", packageName],
1695
- ["Guren Blog Example", `${appTitle} Example`],
1696
- ["Guren Blog", appTitle],
1697
- ["blog.example.com", `${packageName}.example.com`]
1698
- ]),
1699
- postScaffold: async ({ destination, renderingMode, database }) => {
1700
- const packageJsonPath = join(destination, "package.json");
1701
- const rawPackage = await readFile(packageJsonPath, "utf8");
1702
- const packageJson = JSON.parse(rawPackage);
1703
- packageJson.scripts ??= {};
1704
- packageJson.dependencies ??= {};
1705
- const gurenVersion = packageJson.dependencies["@guren/core"] ?? packageJson.dependencies["@guren/server"] ?? packageJson.dependencies["@guren/orm"] ?? "^1.0.0";
1706
- packageJson.scripts.typecheck ??= "tsc --noEmit";
1707
- packageJson.scripts.smoke ??= "bun run ./smoke.ts";
1708
- packageJson.dependencies["@guren/core"] ??= gurenVersion;
1709
- packageJson.dependencies["@inertiajs/core"] ??= "^2.2.15";
1710
- packageJson.dependencies["lucide-react"] ??= "^0.552.0";
1711
- packageJson.dependencies.zod ??= "^4.1.5";
1712
- await writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}
1713
- `, "utf8");
1714
- const schemaPath = join(destination, "db/schema.ts");
1715
- await writeFile(schemaPath, generateBlogSchema(database), "utf8");
1716
- if (database === "postgres") {
1717
- await cp(join(exampleBlogDir, "db/migrations"), join(destination, "db/migrations"), {
1718
- recursive: true,
1719
- force: true
1720
- });
1721
- }
1722
- if (renderingMode === "spa") {
1723
- const mainPath = join(destination, "src/main.ts");
1724
- const mainSource = await readFile(mainPath, "utf8");
1725
- if (!mainSource.includes("enableSsr: false")) {
1726
- const updated = mainSource.replace(
1727
- "autoConfigureInertiaAssets(app, {\n importMeta: import.meta,\n})",
1728
- "autoConfigureInertiaAssets(app, {\n importMeta: import.meta,\n enableSsr: false,\n})"
1729
- );
1730
- await writeFile(mainPath, updated, "utf8");
1731
- }
1732
- }
1733
- }
1681
+ transformFiles: BLOG_TRANSFORM_FILES,
1682
+ includesAuth: true
1734
1683
  },
1735
1684
  worker: {
1736
1685
  name: "worker",
1737
1686
  description: "Full-stack app pre-configured with queue, events, cache, and scheduling",
1738
- baseTemplate: {
1739
- dir: defaultTemplateDir
1740
- },
1741
- overlayTemplateDirs: {
1742
- ssr: [{ dir: defaultSsrOverlayDir }]
1687
+ baseTemplate: "default",
1688
+ overlayTemplates: {
1689
+ ssr: ["default-ssr"]
1743
1690
  },
1744
1691
  transformFiles: DEFAULT_TRANSFORM_FILES,
1745
1692
  postScaffold: async ({ destination }) => {
@@ -1770,25 +1717,24 @@ function replaceTokens(content, tokens) {
1770
1717
  }
1771
1718
  return updated;
1772
1719
  }
1773
- function normalizePath(value) {
1774
- return value.replaceAll("\\", "/").replace(/\/+$/u, "");
1775
- }
1776
- function shouldExclude(templateRoot, sourcePath, excludePaths = []) {
1777
- const relativePath = normalizePath(relative(templateRoot, sourcePath));
1778
- if (relativePath === "" || relativePath === ".") {
1779
- return false;
1780
- }
1781
- return excludePaths.some((candidate) => {
1782
- const normalizedCandidate = normalizePath(candidate);
1783
- return relativePath === normalizedCandidate || relativePath.startsWith(`${normalizedCandidate}/`);
1784
- });
1785
- }
1720
+ var TEMPLATE_DOTFILES = /* @__PURE__ */ new Map([["_gitignore", ".gitignore"]]);
1786
1721
  async function copyLayer(layer, destination) {
1787
- await cp(layer.dir, destination, {
1722
+ const dotfiles = /* @__PURE__ */ new Set();
1723
+ const source = templateDir(layer);
1724
+ await cp(source, destination, {
1788
1725
  recursive: true,
1789
1726
  force: true,
1790
- filter: (sourcePath) => !shouldExclude(layer.dir, sourcePath, layer.excludePaths)
1727
+ filter: (sourcePath) => {
1728
+ if (TEMPLATE_DOTFILES.has(basename(sourcePath))) {
1729
+ dotfiles.add(relative(source, sourcePath));
1730
+ }
1731
+ return true;
1732
+ }
1791
1733
  });
1734
+ for (const path of dotfiles) {
1735
+ const dotted = TEMPLATE_DOTFILES.get(basename(path));
1736
+ await rename(join(destination, path), join(destination, dirname(path), dotted));
1737
+ }
1792
1738
  }
1793
1739
  async function applyTokenTransforms(destination, files, tokens) {
1794
1740
  for (const file of files) {
@@ -1815,39 +1761,13 @@ async function scaffoldEnvFiles(destination) {
1815
1761
  `, "utf8");
1816
1762
  }
1817
1763
  var DATABASE_DEFAULTS = {
1818
- postgres: { url: "postgres://guren:guren@localhost:54322/guren", dialect: "postgresql", dep: { postgres: "^3.4.3" } },
1819
- mysql: { url: "mysql://guren:guren@localhost:33306/guren", dialect: "mysql", dep: { mysql2: "^3.11.3" } },
1820
- sqlite: { url: "./data/guren.db", dialect: "sqlite", dep: null }
1764
+ postgres: { url: "postgres://guren:guren@localhost:54322/guren", dialect: "postgresql", dep: { postgres: "^3.4.3" }, factory: "createPostgresDatabase", seederContext: "PostgresSeederContext" },
1765
+ mysql: { url: "mysql://guren:guren@localhost:33306/guren", dialect: "mysql", dep: { mysql2: "^3.11.3" }, factory: "createMySqlDatabase", seederContext: "MySqlSeederContext" },
1766
+ sqlite: { url: "./data/guren.db", dialect: "sqlite", dep: null, factory: "createSqliteDatabase", seederContext: "SqliteSeederContext" }
1821
1767
  };
1822
1768
  function generateDatabaseConfig(driver) {
1823
- const { url } = DATABASE_DEFAULTS[driver];
1824
- if (driver === "postgres") {
1825
- return `import { createPostgresDatabase } from '@guren/orm'
1826
-
1827
- const database = createPostgresDatabase({
1828
- migrationsFolder: new URL('../db/migrations', import.meta.url),
1829
- seedersFolder: new URL('../db/seeders', import.meta.url),
1830
- connectionString: () => process.env.DATABASE_URL ?? '${url}',
1831
- })
1832
-
1833
- export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database
1834
- `;
1835
- }
1836
- if (driver === "mysql") {
1837
- return `import { createMySqlDatabase } from '@guren/orm'
1838
-
1839
- const database = createMySqlDatabase({
1840
- migrationsFolder: new URL('../db/migrations', import.meta.url),
1841
- seedersFolder: new URL('../db/seeders', import.meta.url),
1842
- connectionString: () => process.env.DATABASE_URL ?? '${url}',
1843
- })
1844
-
1845
- export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database
1846
- `;
1847
- }
1848
- return `import { createSqliteDatabase } from '@guren/orm'
1849
-
1850
- // \`bun test\` sets NODE_ENV=test automatically, so the test suite reads and
1769
+ const { url, factory, seederContext } = DATABASE_DEFAULTS[driver];
1770
+ const body = driver === "sqlite" ? `// \`bun test\` sets NODE_ENV=test automatically, so the test suite reads and
1851
1771
  // writes a separate SQLite file and never touches the development database \u2014
1852
1772
  // this takes priority over DATABASE_URL, which .env sets unconditionally.
1853
1773
  // Override the test DB path itself with TEST_DATABASE_URL if needed (e.g. to
@@ -1859,13 +1779,23 @@ function resolveDatabaseFilename(): string {
1859
1779
  return process.env.DATABASE_URL ?? '${url}'
1860
1780
  }
1861
1781
 
1862
- const database = createSqliteDatabase({
1782
+ const database = ${factory}({
1863
1783
  migrationsFolder: new URL('../db/migrations', import.meta.url),
1864
1784
  seedersFolder: new URL('../db/seeders', import.meta.url),
1865
1785
  filename: resolveDatabaseFilename,
1866
- })
1786
+ })` : `const database = ${factory}({
1787
+ migrationsFolder: new URL('../db/migrations', import.meta.url),
1788
+ seedersFolder: new URL('../db/seeders', import.meta.url),
1789
+ connectionString: () => process.env.DATABASE_URL ?? '${url}',
1790
+ })`;
1791
+ return `import { ${factory}, type ${seederContext} } from '@guren/orm'
1792
+
1793
+ ${body}
1867
1794
 
1868
1795
  export const { getDatabase, migrateDatabase, closeDatabase, configureOrm, seedDatabase, resetDatabase, migrationStatus } = database
1796
+
1797
+ /** Annotate seeders with this: \`defineSeeder(async ({ db }: AppSeederContext) => {})\`. */
1798
+ export type AppSeederContext = ${seederContext}
1869
1799
  `;
1870
1800
  }
1871
1801
  function generateSchema(driver) {
@@ -1876,12 +1806,12 @@ export const users = pgTable('users', {
1876
1806
  id: serial('id').primaryKey(),
1877
1807
  name: text('name').notNull(),
1878
1808
  email: text('email').notNull(),
1879
- createdAt: timestamp('created_at').notNull().defaultNow(),
1809
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
1880
1810
  })
1881
1811
  `;
1882
1812
  }
1883
1813
  if (driver === "mysql") {
1884
- return `import { mysqlTable, int, varchar, timestamp } from '@guren/orm/drizzle'
1814
+ return `import { mysqlTable, int, varchar, timestamp } from 'drizzle-orm/mysql-core'
1885
1815
 
1886
1816
  export const users = mysqlTable('users', {
1887
1817
  id: int('id').primaryKey().autoincrement(),
@@ -1901,86 +1831,22 @@ export const users = sqliteTable('users', {
1901
1831
  })
1902
1832
  `;
1903
1833
  }
1904
- function generateBlogSchema(driver) {
1905
- if (driver === "postgres") {
1906
- return `import { pgTable, serial, text, integer, uniqueIndex } from '@guren/orm/drizzle'
1907
-
1908
- export const users = pgTable(
1909
- 'users',
1910
- {
1911
- id: serial('id').primaryKey(),
1912
- name: text('name').notNull(),
1913
- email: text('email').notNull(),
1914
- passwordHash: text('password_hash').notNull(),
1915
- rememberToken: text('remember_token'),
1916
- },
1917
- (table) => [uniqueIndex('users_email_unique').on(table.email)],
1918
- )
1919
-
1920
- export const posts = pgTable('posts', {
1921
- id: serial('id').primaryKey(),
1922
- title: text('title').notNull(),
1923
- excerpt: text('excerpt').notNull(),
1924
- body: text('body'),
1925
- authorId: integer('author_id').notNull().references(() => users.id),
1926
- })
1927
-
1928
- export const schema = { posts, users }
1929
- export type BlogSchema = typeof schema
1930
- `;
1834
+ function schemaVariantPath(destination, driver) {
1835
+ return join(destination, `db/schema.${driver}.ts`);
1836
+ }
1837
+ async function resolveSchema(destination, driver) {
1838
+ const shipped = (await Promise.all(
1839
+ DATABASE_DRIVERS.map(async (name) => await fileExists(schemaVariantPath(destination, name)) ? name : null)
1840
+ )).filter((name) => name !== null);
1841
+ if (shipped.length === 0) {
1842
+ return generateSchema(driver);
1931
1843
  }
1932
- if (driver === "mysql") {
1933
- return `import { mysqlTable, int, varchar, text, uniqueIndex } from '@guren/orm/drizzle'
1934
-
1935
- export const users = mysqlTable(
1936
- 'users',
1937
- {
1938
- id: int('id').primaryKey().autoincrement(),
1939
- name: varchar('name', { length: 255 }).notNull(),
1940
- email: varchar('email', { length: 255 }).notNull(),
1941
- passwordHash: varchar('password_hash', { length: 255 }).notNull(),
1942
- rememberToken: varchar('remember_token', { length: 255 }),
1943
- },
1944
- (table) => [uniqueIndex('users_email_unique').on(table.email)],
1945
- )
1946
-
1947
- export const posts = mysqlTable('posts', {
1948
- id: int('id').primaryKey().autoincrement(),
1949
- title: varchar('title', { length: 255 }).notNull(),
1950
- excerpt: varchar('excerpt', { length: 500 }).notNull(),
1951
- body: text('body'),
1952
- authorId: int('author_id').notNull().references(() => users.id),
1953
- })
1954
-
1955
- export const schema = { posts, users }
1956
- export type BlogSchema = typeof schema
1957
- `;
1844
+ if (!shipped.includes(driver)) {
1845
+ throw new Error(
1846
+ `This template ships a database schema for ${shipped.join(", ")} but not for ${driver}. This build of create-guren-app is incomplete \u2014 please report it at https://github.com/gurenjs/guren/issues.`
1847
+ );
1958
1848
  }
1959
- return `import { sqliteTable, integer, text, uniqueIndex } from 'drizzle-orm/sqlite-core'
1960
-
1961
- export const users = sqliteTable(
1962
- 'users',
1963
- {
1964
- id: integer('id').primaryKey({ autoIncrement: true }),
1965
- name: text('name').notNull(),
1966
- email: text('email').notNull(),
1967
- passwordHash: text('password_hash').notNull(),
1968
- rememberToken: text('remember_token'),
1969
- },
1970
- (table) => [uniqueIndex('users_email_unique').on(table.email)],
1971
- )
1972
-
1973
- export const posts = sqliteTable('posts', {
1974
- id: integer('id').primaryKey({ autoIncrement: true }),
1975
- title: text('title').notNull(),
1976
- excerpt: text('excerpt').notNull(),
1977
- body: text('body'),
1978
- authorId: integer('author_id').notNull().references(() => users.id),
1979
- })
1980
-
1981
- export const schema = { posts, users }
1982
- export type BlogSchema = typeof schema
1983
- `;
1849
+ return readFile(schemaVariantPath(destination, driver), "utf8");
1984
1850
  }
1985
1851
  function generateDrizzleConfig(driver) {
1986
1852
  const { url, dialect } = DATABASE_DEFAULTS[driver];
@@ -1996,6 +1862,9 @@ export default defineConfig({
1996
1862
  })
1997
1863
  `;
1998
1864
  }
1865
+ function usesDatabaseContainer(driver) {
1866
+ return generateDockerCompose(driver) !== null;
1867
+ }
1999
1868
  function generateDockerCompose(driver) {
2000
1869
  if (driver === "postgres") {
2001
1870
  return `services:
@@ -2037,9 +1906,13 @@ volumes:
2037
1906
  async function applyDatabaseConfig(destination, driver) {
2038
1907
  const { url, dep } = DATABASE_DEFAULTS[driver];
2039
1908
  const dockerCompose = generateDockerCompose(driver);
1909
+ const schema = await resolveSchema(destination, driver);
2040
1910
  await Promise.all([
2041
1911
  writeFile(join(destination, "config/database.ts"), generateDatabaseConfig(driver), "utf8"),
2042
- writeFile(join(destination, "db/schema.ts"), generateSchema(driver), "utf8"),
1912
+ writeFile(join(destination, "db/schema.ts"), schema, "utf8"),
1913
+ // Independent of the write above: the selected variant's contents are
1914
+ // already in `schema`, and no variant shares a path with db/schema.ts.
1915
+ ...DATABASE_DRIVERS.map((name) => rm(schemaVariantPath(destination, name), { force: true })),
2043
1916
  writeFile(join(destination, "drizzle.config.ts"), generateDrizzleConfig(driver), "utf8"),
2044
1917
  dockerCompose ? writeFile(join(destination, "docker-compose.yml"), dockerCompose, "utf8") : Promise.resolve(),
2045
1918
  // Update .env and .env.example with the correct DATABASE_URL
@@ -2052,12 +1925,19 @@ async function applyDatabaseConfig(destination, driver) {
2052
1925
  }
2053
1926
  })
2054
1927
  ]);
2055
- if (dep) {
1928
+ if (dep || dockerCompose) {
2056
1929
  const packageJsonPath = join(destination, "package.json");
2057
1930
  const raw = await readFile(packageJsonPath, "utf8");
2058
1931
  const pkg = JSON.parse(raw);
2059
- pkg.dependencies ??= {};
2060
- Object.assign(pkg.dependencies, dep);
1932
+ if (dep) {
1933
+ pkg.dependencies ??= {};
1934
+ Object.assign(pkg.dependencies, dep);
1935
+ }
1936
+ if (dockerCompose) {
1937
+ pkg.scripts ??= {};
1938
+ pkg.scripts["db:up"] = "docker compose up -d";
1939
+ pkg.scripts["db:down"] = "docker compose down";
1940
+ }
2061
1941
  await writeFile(packageJsonPath, `${JSON.stringify(pkg, null, 2)}
2062
1942
  `, "utf8");
2063
1943
  }
@@ -2065,6 +1945,19 @@ async function applyDatabaseConfig(destination, driver) {
2065
1945
  function listAppBlueprints() {
2066
1946
  return [...APP_BLUEPRINTS];
2067
1947
  }
1948
+ function listBlueprintTemplates(blueprint, renderingMode) {
1949
+ const overlays = renderingMode ? blueprint.overlayTemplates[renderingMode] ?? [] : Object.values(blueprint.overlayTemplates).flat();
1950
+ return [blueprint.baseTemplate, ...overlays];
1951
+ }
1952
+ async function assertBlueprintLayersExist(blueprint, renderingMode) {
1953
+ for (const layer of listBlueprintTemplates(blueprint, renderingMode)) {
1954
+ if (!await directoryExists(templateDir(layer))) {
1955
+ throw new Error(
1956
+ `Blueprint "${blueprint.name}" is missing its template directory "${templateDir(layer)}". This build of create-guren-app is incomplete \u2014 please report it at https://github.com/gurenjs/guren/issues and try \`npm create guren-app@latest\` meanwhile.`
1957
+ );
1958
+ }
1959
+ }
1960
+ }
2068
1961
  function getAppBlueprint(name) {
2069
1962
  const blueprintName = name ?? "default";
2070
1963
  const blueprint = blueprintRegistry[blueprintName];
@@ -2091,12 +1984,9 @@ async function scaffoldAppBlueprint(options) {
2091
1984
  ["__APP_TITLE__", appTitle],
2092
1985
  ["__APP_NAME__", appName]
2093
1986
  ]);
2094
- for (const [token, replacement] of blueprint.replacements?.(context) ?? []) {
2095
- tokenMap.set(token, replacement);
2096
- }
2097
- await copyLayer(blueprint.baseTemplate, options.destination);
2098
- for (const overlay of blueprint.overlayTemplateDirs[options.renderingMode] ?? []) {
2099
- await copyLayer(overlay, options.destination);
1987
+ await assertBlueprintLayersExist(blueprint, options.renderingMode);
1988
+ for (const layer of listBlueprintTemplates(blueprint, options.renderingMode)) {
1989
+ await copyLayer(layer, options.destination);
2100
1990
  }
2101
1991
  await applyTokenTransforms(options.destination, blueprint.transformFiles, tokenMap);
2102
1992
  await scaffoldEnvFiles(options.destination);
@@ -2190,6 +2080,56 @@ async function resolveDatabase(flagValue) {
2190
2080
  const value = typeof result === "string" ? result : "sqlite";
2191
2081
  return value ?? "sqlite";
2192
2082
  }
2083
+ async function resolveGitInit(flagValue, target) {
2084
+ if (flagValue === false) {
2085
+ return false;
2086
+ }
2087
+ if (flagValue !== true && !process3.stdin.isTTY) {
2088
+ return false;
2089
+ }
2090
+ const declined = (reason) => {
2091
+ if (flagValue === true) {
2092
+ consola.warn(`Skipping git initialization: ${reason}`);
2093
+ }
2094
+ return false;
2095
+ };
2096
+ if (!target.wasEmpty) {
2097
+ return declined("the target directory already contained files.");
2098
+ }
2099
+ if (await isInsideGitWorkTree(target.dir)) {
2100
+ return declined("the target directory is already inside a git repository.");
2101
+ }
2102
+ if (flagValue === true) {
2103
+ return true;
2104
+ }
2105
+ const result = await consola.prompt("Initialize a git repository with an initial commit?", {
2106
+ type: "confirm",
2107
+ initial: true
2108
+ });
2109
+ return result === true;
2110
+ }
2111
+ async function isInsideGitWorkTree(cwd) {
2112
+ const { spawnSync } = await import("child_process");
2113
+ const result = spawnSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd, stdio: "pipe", env: process3.env });
2114
+ return result.status === 0 && result.stdout.toString().trim() === "true";
2115
+ }
2116
+ async function initGitRepository(cwd) {
2117
+ const { spawnSync } = await import("child_process");
2118
+ const run = (args) => spawnSync("git", args, { cwd, stdio: "pipe", env: process3.env });
2119
+ consola.start("Initializing git repository...");
2120
+ for (const args of [["init"], ["add", "-A"]]) {
2121
+ if (run(args).status !== 0) {
2122
+ consola.warn(`Failed to run \`git ${args.join(" ")}\`. Initialize the repository manually.`);
2123
+ return;
2124
+ }
2125
+ }
2126
+ if (run(["commit", "-m", "chore: initial commit"]).status !== 0) {
2127
+ consola.warn("Created a git repository, but the initial commit failed (git identity may be unset).");
2128
+ consola.warn('Set `git config user.name` and `git config user.email`, then run `git commit -m "chore: initial commit"`.');
2129
+ return;
2130
+ }
2131
+ consola.success("Initialized a git repository with an initial commit");
2132
+ }
2193
2133
  async function installDependencies(cwd) {
2194
2134
  try {
2195
2135
  consola.start("Installing dependencies...");
@@ -2242,18 +2182,21 @@ var command = defineCommand({
2242
2182
  type: "boolean",
2243
2183
  description: "Install dependencies after scaffolding (default: true)",
2244
2184
  default: true
2185
+ },
2186
+ git: {
2187
+ type: "boolean",
2188
+ description: "Initialize a git repository and create an initial commit (prompted when interactive, off otherwise)"
2245
2189
  }
2246
2190
  },
2247
2191
  async run({ args }) {
2248
2192
  const target = args.target;
2249
2193
  const force = Boolean(args.force);
2250
2194
  const targetDir = resolve(process3.cwd(), target);
2195
+ let targetWasEmpty = true;
2251
2196
  if (await directoryExists(targetDir)) {
2252
- if (!force) {
2253
- const empty = await isDirectoryEmpty(targetDir);
2254
- if (!empty) {
2255
- throw new Error(`Directory "${targetDir}" is not empty. Use --force to scaffold anyway.`);
2256
- }
2197
+ targetWasEmpty = await isDirectoryEmpty(targetDir);
2198
+ if (!force && !targetWasEmpty) {
2199
+ throw new Error(`Directory "${targetDir}" is not empty. Use --force to scaffold anyway.`);
2257
2200
  }
2258
2201
  } else {
2259
2202
  await ensureTargetDirectory(targetDir, true);
@@ -2261,6 +2204,7 @@ var command = defineCommand({
2261
2204
  const blueprint = getAppBlueprint(typeof args.blueprint === "string" ? args.blueprint : void 0);
2262
2205
  const renderingMode = blueprint.name === "api" ? "spa" : await resolveRenderingMode(args.mode);
2263
2206
  const database = await resolveDatabase(args.db);
2207
+ const shouldInitGit = await resolveGitInit(args.git, { dir: targetDir, wasEmpty: targetWasEmpty });
2264
2208
  await scaffoldAppBlueprint({
2265
2209
  blueprint: blueprint.name,
2266
2210
  destination: targetDir,
@@ -2270,7 +2214,10 @@ var command = defineCommand({
2270
2214
  if (renderingMode === "ssr") {
2271
2215
  await updateSsrPackageJson(targetDir);
2272
2216
  }
2273
- const includeAuth = Boolean(args.auth);
2217
+ if (args.auth && blueprint.includesAuth) {
2218
+ consola.info(`The ${blueprint.name} blueprint already ships authentication \u2014 ignoring --auth.`);
2219
+ }
2220
+ const includeAuth = Boolean(args.auth) && !blueprint.includesAuth;
2274
2221
  const shouldInstall = args.install !== false;
2275
2222
  let installed = false;
2276
2223
  if (shouldInstall) {
@@ -2300,6 +2247,9 @@ var command = defineCommand({
2300
2247
  consola.warn("Authentication was not scaffolded automatically. Run `bunx guren add auth` inside the app after installing dependencies.");
2301
2248
  }
2302
2249
  }
2250
+ if (shouldInitGit) {
2251
+ await initGitRepository(targetDir);
2252
+ }
2303
2253
  const relativeTarget = relative2(process3.cwd(), targetDir) || ".";
2304
2254
  consola.success(`Scaffolded a new Guren app (${blueprint.name}/${renderingMode.toUpperCase()}/${database}) in ${relativeTarget}`);
2305
2255
  consola.info("Next steps:");
@@ -2309,12 +2259,14 @@ var command = defineCommand({
2309
2259
  if (!installed) {
2310
2260
  consola.log(" bun install");
2311
2261
  }
2312
- if (database !== "sqlite") {
2313
- consola.log(" docker compose up -d");
2262
+ if (usesDatabaseContainer(database)) {
2263
+ consola.log(" bun run db:up");
2314
2264
  }
2315
2265
  consola.log("");
2316
2266
  consola.info("Add features:");
2317
- consola.log(" bunx guren add auth");
2267
+ if (!blueprint.includesAuth) {
2268
+ consola.log(" bunx guren add auth");
2269
+ }
2318
2270
  consola.log(' bunx guren add resource posts --fields "title:string,body:text"');
2319
2271
  consola.log("");
2320
2272
  consola.info("Generate types and set up database:");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-guren-app",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {