@batijs/cli 0.0.259 → 0.0.261

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 (104) hide show
  1. package/dist/boilerplates/@batijs/authjs/files/$package.json.js +1 -1
  2. package/dist/boilerplates/@batijs/authjs/files/server/authjs-handler.ts +2 -2
  3. package/dist/boilerplates/@batijs/authjs/types/server/authjs-handler.d.ts +2 -3
  4. package/dist/boilerplates/@batijs/aws/files/$README.md.js +109 -0
  5. package/dist/boilerplates/@batijs/aws/files/$package.json.js +138 -0
  6. package/dist/boilerplates/@batijs/aws/files/$tsconfig.json.js +15 -0
  7. package/dist/boilerplates/@batijs/aws/files/cdk/$stack-name-suffix.json.js +19 -0
  8. package/dist/boilerplates/@batijs/aws/files/cdk/bin/infrastructure.ts +85 -0
  9. package/dist/boilerplates/@batijs/aws/files/cdk/lib/vike-stack.ts +186 -0
  10. package/dist/boilerplates/@batijs/aws/files/cdk.json +72 -0
  11. package/dist/boilerplates/@batijs/aws/files/tests/aws_handler.spec.ts +116 -0
  12. package/dist/boilerplates/@batijs/aws/files/vitest.config.ts +8 -0
  13. package/dist/boilerplates/@batijs/aws/types/cdk/bin/infrastructure.d.ts +11 -0
  14. package/dist/boilerplates/@batijs/aws/types/cdk/lib/vike-stack.d.ts +13 -0
  15. package/dist/boilerplates/@batijs/aws/types/vitest.config.d.ts +2 -0
  16. package/dist/boilerplates/@batijs/cloudflare/files/$package.json.js +1 -1
  17. package/dist/boilerplates/@batijs/cloudflare/files/$tsconfig.json.js +10 -0
  18. package/dist/boilerplates/@batijs/d1/files/$README.md.js +0 -4
  19. package/dist/boilerplates/@batijs/d1/files/$package.json.js +96 -0
  20. package/dist/boilerplates/@batijs/d1/files/$wrangler.toml.js +1 -0
  21. package/dist/boilerplates/@batijs/d1/files/database/d1/helpers.ts +17 -0
  22. package/dist/boilerplates/@batijs/d1/files/vike.d.ts +8 -0
  23. package/dist/boilerplates/@batijs/d1/types/database/d1/helpers.d.ts +6 -0
  24. package/dist/boilerplates/@batijs/d1-sqlite/files/$package.json.js +10 -0
  25. package/dist/boilerplates/@batijs/d1-sqlite/files/database/d1/queries/lucia-auth.ts +28 -0
  26. package/dist/boilerplates/@batijs/d1-sqlite/files/database/d1/queries/todos.ts +10 -0
  27. package/dist/boilerplates/@batijs/d1-sqlite/files/database/migrations/lucia-auth.sql +20 -0
  28. package/dist/boilerplates/@batijs/d1-sqlite/files/database/migrations/todos.sql +4 -0
  29. package/dist/boilerplates/@batijs/d1-sqlite/types/database/d1/queries/lucia-auth.d.ts +5 -0
  30. package/dist/boilerplates/@batijs/d1-sqlite/types/database/d1/queries/todos.d.ts +6 -0
  31. package/dist/boilerplates/@batijs/drizzle/files/$.env.js +1 -0
  32. package/dist/boilerplates/@batijs/drizzle/files/$README.md.js +0 -3
  33. package/dist/boilerplates/@batijs/drizzle/files/$package.json.js +7 -14
  34. package/dist/boilerplates/@batijs/drizzle/files/database/drizzle/db.ts +10 -12
  35. package/dist/boilerplates/@batijs/drizzle/files/database/drizzle/queries/lucia-auth.ts +38 -9
  36. package/dist/boilerplates/@batijs/drizzle/files/database/drizzle/queries/todos.ts +16 -5
  37. package/dist/boilerplates/@batijs/drizzle/files/drizzle.config.ts +7 -4
  38. package/dist/boilerplates/@batijs/drizzle/types/database/drizzle/db.d.ts +2 -2
  39. package/dist/boilerplates/@batijs/drizzle/types/database/drizzle/queries/lucia-auth.d.ts +19 -6
  40. package/dist/boilerplates/@batijs/drizzle/types/database/drizzle/queries/todos.d.ts +9 -2
  41. package/dist/boilerplates/@batijs/eslint/files/$package.json.js +1 -1
  42. package/dist/boilerplates/@batijs/eslint/files/eslint.config.js +2 -1
  43. package/dist/boilerplates/@batijs/express/files/$package.json.js +2 -1
  44. package/dist/boilerplates/@batijs/express/files/express-entry.ts +13 -12
  45. package/dist/boilerplates/@batijs/fastify/files/$package.json.js +2 -1
  46. package/dist/boilerplates/@batijs/fastify/files/fastify-entry.ts +17 -24
  47. package/dist/boilerplates/@batijs/firebase-auth/files/$package.json.js +2 -2
  48. package/dist/boilerplates/@batijs/firebase-auth/files/server/firebase-auth-middleware.ts +2 -2
  49. package/dist/boilerplates/@batijs/firebase-auth/types/server/firebase-auth-middleware.d.ts +2 -6
  50. package/dist/boilerplates/@batijs/h3/files/$package.json.js +1 -0
  51. package/dist/boilerplates/@batijs/h3/files/h3-entry.ts +12 -2
  52. package/dist/boilerplates/@batijs/hattip/files/$package.json.js +15 -2
  53. package/dist/boilerplates/@batijs/hattip/files/entry_aws_lambda.ts +37 -0
  54. package/dist/boilerplates/@batijs/hattip/files/hattip-entry.ts +12 -12
  55. package/dist/boilerplates/@batijs/hattip/types/entry_aws_lambda.d.ts +2 -0
  56. package/dist/boilerplates/@batijs/hono/files/$package.json.js +22 -4
  57. package/dist/boilerplates/@batijs/hono/files/entry_aws_lambda.ts +37 -0
  58. package/dist/boilerplates/@batijs/hono/files/hono-entry.ts +12 -12
  59. package/dist/boilerplates/@batijs/hono/types/entry_aws_lambda.d.ts +3 -0
  60. package/dist/boilerplates/@batijs/lucia-auth/files/$package.json.js +4 -1
  61. package/dist/boilerplates/@batijs/lucia-auth/files/lib/lucia-auth.ts +75 -39
  62. package/dist/boilerplates/@batijs/lucia-auth/files/server/lucia-auth-handlers.ts +77 -33
  63. package/dist/boilerplates/@batijs/lucia-auth/types/lib/lucia-auth.d.ts +30 -10
  64. package/dist/boilerplates/@batijs/lucia-auth/types/server/lucia-auth-handlers.d.ts +13 -13
  65. package/dist/boilerplates/@batijs/react-lucia-auth/files/pages/login/+Page.tsx +2 -1
  66. package/dist/boilerplates/@batijs/shared/files/vite.config.ts +6 -0
  67. package/dist/boilerplates/@batijs/shared-db/files/server/db-middleware.ts +37 -0
  68. package/dist/boilerplates/@batijs/shared-db/types/server/db-middleware.d.ts +17 -0
  69. package/dist/boilerplates/@batijs/shared-no-db/files/$package.json.js +2 -1
  70. package/dist/boilerplates/@batijs/shared-server/files/$package.json.js +5 -2
  71. package/dist/boilerplates/@batijs/shared-server/files/server/create-todo-handler.ts +22 -4
  72. package/dist/boilerplates/@batijs/shared-server/files/server/vike-handler.ts +2 -2
  73. package/dist/boilerplates/@batijs/shared-server/types/server/create-todo-handler.d.ts +19 -1
  74. package/dist/boilerplates/@batijs/shared-todo/files/pages/todo/+data.ts +10 -4
  75. package/dist/boilerplates/@batijs/shared-todo/files/vike.d.ts +19 -0
  76. package/dist/boilerplates/@batijs/shared-todo/types/pages/todo/+data.d.ts +2 -1
  77. package/dist/boilerplates/@batijs/solid-lucia-auth/files/pages/login/+Page.tsx +2 -1
  78. package/dist/boilerplates/@batijs/sqlite/files/$.env.js +1 -0
  79. package/dist/boilerplates/@batijs/sqlite/files/$package.json.js +10 -1
  80. package/dist/boilerplates/@batijs/sqlite/files/database/sqlite/queries/lucia-auth.ts +16 -15
  81. package/dist/boilerplates/@batijs/sqlite/files/database/sqlite/queries/todos.ts +5 -5
  82. package/dist/boilerplates/@batijs/sqlite/types/database/sqlite/queries/lucia-auth.d.ts +5 -5
  83. package/dist/boilerplates/@batijs/sqlite/types/database/sqlite/queries/todos.d.ts +3 -2
  84. package/dist/boilerplates/@batijs/telefunc/files/$package.json.js +5 -3
  85. package/dist/boilerplates/@batijs/telefunc/files/pages/todo/TodoList.telefunc.ts +10 -3
  86. package/dist/boilerplates/@batijs/telefunc/files/server/telefunc-handler.ts +15 -2
  87. package/dist/boilerplates/@batijs/telefunc/files/vike.d.ts +20 -0
  88. package/dist/boilerplates/@batijs/trpc/files/$package.json.js +10 -7
  89. package/dist/boilerplates/@batijs/trpc/files/server/trpc-handler.ts +22 -0
  90. package/dist/boilerplates/@batijs/trpc/files/trpc/server.ts +20 -4
  91. package/dist/boilerplates/@batijs/trpc/types/server/trpc-handler.d.ts +1 -0
  92. package/dist/boilerplates/@batijs/trpc/types/trpc/client.d.ts +36 -4
  93. package/dist/boilerplates/@batijs/trpc/types/trpc/server.d.ts +75 -8
  94. package/dist/boilerplates/@batijs/ts-rest/files/$package.json.js +4 -3
  95. package/dist/boilerplates/@batijs/ts-rest/files/server/ts-rest-handler.ts +48 -27
  96. package/dist/boilerplates/@batijs/vue-lucia-auth/files/pages/login/+Page.vue +2 -1
  97. package/dist/boilerplates/boilerplates.json +61 -3
  98. package/dist/index.js +6 -1
  99. package/package.json +5 -5
  100. package/dist/boilerplates/@batijs/drizzle/files/database/drizzle/seed.ts +0 -13
  101. package/dist/boilerplates/@batijs/trpc/files/$vite.config.ts.js +0 -13
  102. package/dist/boilerplates/@batijs/trpc/files/trpc/vite-plugin.ts +0 -49
  103. package/dist/boilerplates/@batijs/trpc/types/trpc/vite-plugin.d.ts +0 -12
  104. /package/dist/boilerplates/@batijs/{drizzle/types/database/drizzle/seed.d.ts → aws/types/tests/aws_handler.spec.d.ts} +0 -0
@@ -0,0 +1,116 @@
1
+ import { beforeAll, describe, expect, it } from "vitest";
2
+
3
+ import { execSync } from "node:child_process";
4
+ import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
5
+ import path from "node:path";
6
+ import * as which from "which";
7
+
8
+ const bunExists = which.sync("bun", { nothrow: true }) !== null;
9
+ const npmCli = bunExists ? "bun" : "pnpm";
10
+
11
+ console.log("RUN TESTS ***");
12
+
13
+ describe("AWSHandler", () => {
14
+ beforeAll(
15
+ async () => {
16
+ if (existsSync(path.join(process.cwd(), "cdk.out"))) {
17
+ rmSync(path.join(process.cwd(), "cdk.out"), { recursive: true });
18
+ }
19
+ /*
20
+ * `--build "${npmCli} run build"` is required to build the project before synth
21
+ */
22
+ const synthCommand = `${npmCli} run cdk --json --build "${npmCli} run build" synth`;
23
+ execSync(synthCommand, {
24
+ encoding: "utf8",
25
+ maxBuffer: 50 * 1024 * 1024,
26
+ env: {
27
+ BUN_LOCKFILE: "../../bun.lockb", // This is to make sure that the correct lockfile is used in a bun project
28
+ PATH: process.env.PATH,
29
+ },
30
+ });
31
+ },
32
+ 2 * 60 * 1000,
33
+ );
34
+
35
+ it("should request a page from the AWS handler", async () => {
36
+ const cdkOutPath = path.join(process.cwd(), "cdk.out");
37
+ const templateFilePath = readdirSync(cdkOutPath).find(
38
+ (file) => file.startsWith("VikeStack-") && file.endsWith(".template.json"),
39
+ );
40
+ const templateFullPath = path.join(cdkOutPath, templateFilePath!);
41
+ expect(existsSync(templateFullPath)).toBe(true);
42
+ const cloudfrontTemplateJson = readFileSync(templateFullPath, "utf8");
43
+ const requestHandlerFolder = extractRequestHandlerPath(
44
+ JSON.parse(cloudfrontTemplateJson),
45
+ "/RequestHandler/Resource",
46
+ );
47
+ const requestHandlerPath = path.join(process.cwd(), "cdk.out", requestHandlerFolder!, "index.mjs");
48
+ expect(existsSync(requestHandlerPath)).toBe(true);
49
+
50
+ const { handler } = await import(requestHandlerPath);
51
+ const event = {
52
+ version: "2.0",
53
+ routeKey: "$default",
54
+ rawPath: "/",
55
+ rawQueryString: "",
56
+ headers: {
57
+ accept: "*/*",
58
+ "content-length": "0",
59
+ host: "example.com",
60
+ "user-agent": "PostmanRuntime/7.26.8",
61
+ "x-amzn-trace-id": "Root=1-5f84c7a9-0e5b1e1e1e1e1e1e1e1e1e1e",
62
+ "x-forwarded-for": "127.0.0.1",
63
+ "x-forwarded-port": "443",
64
+ "x-forwarded-proto": "https",
65
+ },
66
+ requestContext: {
67
+ accountId: "123456789012",
68
+ apiId: "api-id",
69
+ domainName: "example.com",
70
+ domainPrefix: "example",
71
+ http: {
72
+ method: "GET",
73
+ path: "/",
74
+ protocol: "HTTP/1.1",
75
+ sourceIp: "127.0.0.1",
76
+ userAgent: "PostmanRuntime/7.26.8",
77
+ },
78
+ requestId: "id",
79
+ routeKey: "$default",
80
+ stage: "$default",
81
+ time: "12/Mar/2021:19:03:58 +0000",
82
+ timeEpoch: 1615578238000,
83
+ },
84
+ isBase64Encoded: false,
85
+ };
86
+ const response = await handler(event, {});
87
+ expect(response.statusCode).toBe(200);
88
+ const body = response.isBase64Encoded ? Buffer.from(response.body, "base64").toString("utf8") : response.body;
89
+ expect(body).toContain("My Vike App");
90
+ });
91
+ });
92
+
93
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
94
+ type JsonData = Record<string, any>;
95
+
96
+ function extractRequestHandlerPath(jsonData: JsonData, targetCdkPath: string): string | null {
97
+ let assetPath: string | null = null;
98
+
99
+ function traverse(obj: JsonData) {
100
+ if (typeof obj !== "object" || obj === null) return;
101
+
102
+ if (obj?.["aws:cdk:path"]?.endsWith(targetCdkPath)) {
103
+ assetPath = obj?.["aws:asset:path"];
104
+ return;
105
+ }
106
+
107
+ for (const key in obj) {
108
+ if (obj?.[key]) {
109
+ traverse(obj[key]);
110
+ }
111
+ }
112
+ }
113
+
114
+ traverse(jsonData);
115
+ return assetPath;
116
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from "vitest/config";
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ include: ["tests/**/*.spec.ts"], // Adjust the pattern as needed
6
+ watch: false,
7
+ },
8
+ });
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import "source-map-support/register";
3
+ import * as cdk from "aws-cdk-lib";
4
+ import * as certificatemanager from "aws-cdk-lib/aws-certificatemanager";
5
+ import * as route53 from "aws-cdk-lib/aws-route53";
6
+ export type CustomStackProps = cdk.StackProps & {
7
+ domainName?: string;
8
+ subDomain?: string;
9
+ certificate?: string | certificatemanager.ICertificate;
10
+ hostedZone?: route53.IHostedZone;
11
+ };
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import "source-map-support/register";
3
+ import { Construct } from "constructs";
4
+ import * as cdk from "aws-cdk-lib";
5
+ import type { CustomStackProps } from "../bin/infrastructure";
6
+ type VikeStackProps = cdk.StackProps & {
7
+ customStackProps: CustomStackProps;
8
+ };
9
+ export declare class VikeStack extends cdk.Stack {
10
+ readonly distributionUrlParameterName: string;
11
+ constructor(scope: Construct, id: string, props: VikeStackProps);
12
+ }
13
+ export {};
@@ -0,0 +1,2 @@
1
+ declare const _default: import("vite").UserConfig;
2
+ export default _default;
@@ -46,7 +46,7 @@ var require_package = __commonJS({
46
46
  "@hattip/adapter-cloudflare-workers": "^0.0.47",
47
47
  "@types/node": "^18.19.14",
48
48
  "npm-run-all2": "^6.2.2",
49
- "vike-cloudflare": "^0.1.0",
49
+ "vike-cloudflare": "^0.1.1",
50
50
  wrangler: "^3.72.2"
51
51
  },
52
52
  dependencies: {
@@ -0,0 +1,10 @@
1
+ // files/$tsconfig.json.ts
2
+ import { loadAsJson } from "@batijs/core";
3
+ async function getTsConfig(props) {
4
+ const tsConfig = await loadAsJson(props);
5
+ tsConfig.compilerOptions.types = [...tsConfig.compilerOptions.types ?? [], "vike-cloudflare/types"];
6
+ return tsConfig;
7
+ }
8
+ export {
9
+ getTsConfig as default
10
+ };
@@ -5,10 +5,6 @@ async function getReadme(props) {
5
5
  const todo = `
6
6
  ## *Cloudflare D1*
7
7
 
8
- > [!IMPORTANT]
9
- > D1 integration is incomplete, and some files are still refering to \`better-sqlite3\`.
10
- > It should be fixed within a few days.
11
-
12
8
  ### Setup
13
9
  Create a D1 database:
14
10
 
@@ -0,0 +1,96 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
+ // If the importer is in node compatibility mode or this is not an ESM
20
+ // file that has been converted to a CommonJS file using a Babel-
21
+ // compatible transform (i.e. "__esModule" has not been set), then set
22
+ // "default" to the CommonJS "module.exports" for node compatibility.
23
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
+ mod
25
+ ));
26
+
27
+ // package.json
28
+ var require_package = __commonJS({
29
+ "package.json"(exports, module) {
30
+ module.exports = {
31
+ name: "@batijs/d1",
32
+ private: true,
33
+ version: "0.0.1",
34
+ description: "",
35
+ type: "module",
36
+ scripts: {
37
+ "check-types": "tsc --noEmit",
38
+ build: "bati-compile-boilerplate"
39
+ },
40
+ keywords: [],
41
+ author: "",
42
+ license: "MIT",
43
+ devDependencies: {
44
+ "@batijs/compile": "workspace:*",
45
+ "@universal-middleware/core": "^0.2.6",
46
+ "@cloudflare/workers-types": "^4.20240821.1",
47
+ "@types/node": "^18.19.14",
48
+ vike: "^0.4.193",
49
+ wrangler: "^3.72.2"
50
+ },
51
+ dependencies: {
52
+ "@batijs/core": "workspace:*"
53
+ },
54
+ files: [
55
+ "dist/"
56
+ ],
57
+ bati: {
58
+ if: {
59
+ flag: {
60
+ $in: [
61
+ "drizzle",
62
+ "sqlite"
63
+ ],
64
+ $all: [
65
+ "cloudflare"
66
+ ]
67
+ }
68
+ }
69
+ },
70
+ exports: {
71
+ "./database/d1/helpers": {
72
+ types: "./dist/types/database/d1/helpers.d.ts"
73
+ }
74
+ },
75
+ typesVersions: {
76
+ "*": {
77
+ "database/d1/helpers": [
78
+ "./dist/types/database/d1/helpers.d.ts"
79
+ ]
80
+ }
81
+ }
82
+ };
83
+ }
84
+ });
85
+
86
+ // files/$package.json.ts
87
+ import { addDependency, loadAsJson } from "@batijs/core";
88
+ async function getPackageJson(props) {
89
+ const packageJson = await loadAsJson(props);
90
+ return addDependency(packageJson, await Promise.resolve().then(() => __toESM(require_package(), 1)).then((x) => x.default), {
91
+ devDependencies: ["@universal-middleware/core"]
92
+ });
93
+ }
94
+ export {
95
+ getPackageJson as default
96
+ };
@@ -12,6 +12,7 @@ binding = "DB" # Should match preview_database_id
12
12
  database_name = "YOUR_DATABASE_NAME"
13
13
  database_id = "the-id-of-your-D1-database-goes-here" # wrangler d1 info YOUR_DATABASE_NAME
14
14
  preview_database_id = "DB" # Required for Pages local development
15
+ migrations_dir = "database/migrations"
15
16
  `;
16
17
  return `${content}
17
18
  ${dbSnippet}`;
@@ -0,0 +1,17 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ import type { RuntimeAdapter } from "@universal-middleware/core";
3
+
4
+ /**
5
+ * Retrieve Cloudflare `env.DB` from `universal-middleware` runtime
6
+ */
7
+ export async function getDbFromRuntime(runtime: RuntimeAdapter): Promise<D1Database> {
8
+ if (runtime.runtime === "workerd") {
9
+ return runtime.env!.DB as D1Database;
10
+ }
11
+
12
+ // When running on node, simulate Cloudflare environment with "wrangler"
13
+ const { getPlatformProxy } = await import("wrangler");
14
+
15
+ const { env } = await getPlatformProxy();
16
+ return env.DB as D1Database;
17
+ }
@@ -5,4 +5,12 @@ interface Env {
5
5
  DB: D1Database;
6
6
  }
7
7
 
8
+ declare global {
9
+ namespace Vike {
10
+ interface PageContext {
11
+ env: Env;
12
+ }
13
+ }
14
+ }
15
+
8
16
  export {};
@@ -0,0 +1,6 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ import type { RuntimeAdapter } from "@universal-middleware/core";
3
+ /**
4
+ * Retrieve Cloudflare `env.DB` from `universal-middleware` runtime
5
+ */
6
+ export declare function getDbFromRuntime(runtime: RuntimeAdapter): Promise<D1Database>;
@@ -0,0 +1,10 @@
1
+ // files/$package.json.ts
2
+ import { loadAsJson } from "@batijs/core";
3
+ async function getPackageJson(props) {
4
+ const packageJson = await loadAsJson(props);
5
+ packageJson.scripts["d1:migrate"] = "wrangler d1 migrations apply YOUR_DATABASE_NAME --local";
6
+ return packageJson;
7
+ }
8
+ export {
9
+ getPackageJson as default
10
+ };
@@ -0,0 +1,28 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+
3
+ export function getExistingUser<T>(db: D1Database, username: string) {
4
+ return db.prepare("SELECT * FROM users WHERE username = ?").bind(username).first<T>();
5
+ }
6
+
7
+ export function getExistingAccount<T>(db: D1Database, providerId: string, providerUserId: number) {
8
+ return db
9
+ .prepare("SELECT * FROM oauth_accounts WHERE provider_id = ? AND provider_user_id = ?")
10
+ .bind(providerId, providerUserId)
11
+ .first<T>();
12
+ }
13
+
14
+ export function signupWithGithub(db: D1Database, userId: string, username: string, githubUserId: number) {
15
+ return db.batch([
16
+ db.prepare("INSERT INTO users (id, username) VALUES (?, ?)").bind(userId, username),
17
+ db
18
+ .prepare("INSERT INTO oauth_accounts (provider_id, provider_user_id, user_id) VALUES (?, ?, ?)")
19
+ .bind("github", githubUserId, userId),
20
+ ]);
21
+ }
22
+
23
+ export function signupWithCredentials(db: D1Database, userId: string, username: string, passwordHash: string) {
24
+ return db
25
+ .prepare("INSERT INTO users (id, username, password) VALUES(?, ?, ?)")
26
+ .bind(userId, username, passwordHash)
27
+ .run();
28
+ }
@@ -0,0 +1,10 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+
3
+ export function insertTodo(db: D1Database, text: string) {
4
+ return db.prepare("INSERT INTO todos (text) VALUES (?)").bind(text).run();
5
+ }
6
+
7
+ export async function getAllTodos(db: D1Database) {
8
+ const { results } = await db.prepare("SELECT * FROM todos").all<{ id: number; text: string }>();
9
+ return results;
10
+ }
@@ -0,0 +1,20 @@
1
+ CREATE TABLE IF NOT EXISTS users (
2
+ id TEXT NOT NULL PRIMARY KEY,
3
+ username TEXT NOT NULL UNIQUE,
4
+ password TEXT
5
+ );
6
+
7
+ CREATE TABLE IF NOT EXISTS oauth_accounts (
8
+ provider_id TEXT NOT NULL,
9
+ provider_user_id INTEGER NOT NULL,
10
+ user_id TEXT NOT NULL,
11
+ PRIMARY KEY (provider_id, provider_user_id),
12
+ FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE cascade ON DELETE cascade
13
+ );
14
+
15
+ CREATE TABLE IF NOT EXISTS sessions (
16
+ id TEXT NOT NULL PRIMARY KEY,
17
+ expires_at INTEGER NOT NULL,
18
+ user_id TEXT NOT NULL,
19
+ FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE cascade ON DELETE cascade
20
+ );
@@ -0,0 +1,4 @@
1
+ CREATE TABLE IF NOT EXISTS todos (
2
+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
3
+ text TEXT
4
+ );
@@ -0,0 +1,5 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ export declare function getExistingUser<T>(db: D1Database, username: string): Promise<T | null>;
3
+ export declare function getExistingAccount<T>(db: D1Database, providerId: string, providerUserId: number): Promise<T | null>;
4
+ export declare function signupWithGithub(db: D1Database, userId: string, username: string, githubUserId: number): Promise<import("@cloudflare/workers-types").D1Result<unknown>[]>;
5
+ export declare function signupWithCredentials(db: D1Database, userId: string, username: string, passwordHash: string): Promise<import("@cloudflare/workers-types").D1Result<Record<string, unknown>>>;
@@ -0,0 +1,6 @@
1
+ import type { D1Database } from "@cloudflare/workers-types";
2
+ export declare function insertTodo(db: D1Database, text: string): Promise<import("@cloudflare/workers-types").D1Result<Record<string, unknown>>>;
3
+ export declare function getAllTodos(db: D1Database): Promise<{
4
+ id: number;
5
+ text: string;
6
+ }[]>;
@@ -1,6 +1,7 @@
1
1
  // files/$.env.ts
2
2
  import { appendToEnv } from "@batijs/core";
3
3
  async function getEnv(props) {
4
+ if (props.meta.BATI.hasD1) return;
4
5
  const envContent = await props.readfile?.();
5
6
  return appendToEnv(envContent, "DATABASE_URL", "sqlite.db", "Path to the sqlite database");
6
7
  }
@@ -9,15 +9,12 @@ First, ensure that \`DATABASE_URL\` is configured in \`.env\` file, then create
9
9
  \`\`\`bash
10
10
  pnpm drizzle:generate # a script that executes drizzle-kit generate.
11
11
  pnpm drizzle:migrate # a script that executes drizzle-kit migrate.
12
- pnpm drizzle:seed # a script that executes tsx ./database/drizzle/seed.ts.
13
12
  \`\`\`
14
13
 
15
14
  > [!NOTE]
16
15
  > The \`drizzle-kit generate\` command is used to generate SQL migration files based on your Drizzle schema.
17
16
  >
18
17
  > The \`drizzle-kit migrate\` command is used to apply the generated migrations to your database.
19
- >
20
- > The \`tsx ./database/drizzle/seed.ts\` command is used to run a custom seed script to populate data to your database.
21
18
 
22
19
  Read more on [Drizzle ORM documentation](https://orm.drizzle.team/docs/overview)
23
20
  `;
@@ -68,18 +68,15 @@ var require_package = __commonJS({
68
68
  "./database/drizzle/db": {
69
69
  types: "./dist/types/database/drizzle/db.d.ts"
70
70
  },
71
- "./database/drizzle/schema/todos": {
72
- types: "./dist/types/database/drizzle/schema/todos.d.ts"
73
- },
74
- "./database/drizzle/seed": {
75
- types: "./dist/types/database/drizzle/seed.d.ts"
76
- },
77
71
  "./database/drizzle/schema/lucia-auth": {
78
72
  types: "./dist/types/database/drizzle/schema/lucia-auth.d.ts"
79
73
  },
80
74
  "./database/drizzle/queries/lucia-auth": {
81
75
  types: "./dist/types/database/drizzle/queries/lucia-auth.d.ts"
82
76
  },
77
+ "./database/drizzle/schema/todos": {
78
+ types: "./dist/types/database/drizzle/schema/todos.d.ts"
79
+ },
83
80
  "./database/drizzle/queries/todos": {
84
81
  types: "./dist/types/database/drizzle/queries/todos.d.ts"
85
82
  }
@@ -92,18 +89,15 @@ var require_package = __commonJS({
92
89
  "database/drizzle/db": [
93
90
  "./dist/types/database/drizzle/db.d.ts"
94
91
  ],
95
- "database/drizzle/schema/todos": [
96
- "./dist/types/database/drizzle/schema/todos.d.ts"
97
- ],
98
- "database/drizzle/seed": [
99
- "./dist/types/database/drizzle/seed.d.ts"
100
- ],
101
92
  "database/drizzle/schema/lucia-auth": [
102
93
  "./dist/types/database/drizzle/schema/lucia-auth.d.ts"
103
94
  ],
104
95
  "database/drizzle/queries/lucia-auth": [
105
96
  "./dist/types/database/drizzle/queries/lucia-auth.d.ts"
106
97
  ],
98
+ "database/drizzle/schema/todos": [
99
+ "./dist/types/database/drizzle/schema/todos.d.ts"
100
+ ],
107
101
  "database/drizzle/queries/todos": [
108
102
  "./dist/types/database/drizzle/queries/todos.d.ts"
109
103
  ]
@@ -118,9 +112,8 @@ import { addDependency, loadAsJson } from "@batijs/core";
118
112
  async function getPackageJson(props) {
119
113
  const packageJson = await loadAsJson(props);
120
114
  packageJson.scripts["drizzle:generate"] = "drizzle-kit generate";
121
- packageJson.scripts["drizzle:migrate"] = "drizzle-kit migrate";
115
+ packageJson.scripts["drizzle:migrate"] = props.meta.BATI.hasD1 ? "wrangler d1 migrations apply YOUR_DATABASE_NAME --local" : "drizzle-kit migrate";
122
116
  packageJson.scripts["drizzle:studio"] = "drizzle-kit studio";
123
- packageJson.scripts["drizzle:seed"] = "tsx ./database/drizzle/seed.ts";
124
117
  return addDependency(packageJson, await Promise.resolve().then(() => __toESM(require_package(), 1)).then((x) => x.default), {
125
118
  devDependencies: ["@types/better-sqlite3", "tsx"],
126
119
  dependencies: ["better-sqlite3", "drizzle-kit", "drizzle-orm", "dotenv"]
@@ -1,16 +1,14 @@
1
1
  import Database from "better-sqlite3";
2
- import { type BetterSQLite3Database, drizzle } from "drizzle-orm/better-sqlite3";
2
+ import { drizzle as drizzleSqlite } from "drizzle-orm/better-sqlite3";
3
+ import { drizzle as drizzleD1 } from "drizzle-orm/d1";
3
4
 
4
- let singleton: BetterSQLite3Database | undefined = undefined;
5
-
6
- export function db() {
7
- if (!singleton) {
8
- if (!process.env.DATABASE_URL) {
9
- throw new Error("Missing DATABASE_URL in .env file");
10
- }
5
+ //# !BATI.hasD1
6
+ export function dbSqlite() {
7
+ const sqlite = new Database(process.env.DATABASE_URL);
8
+ return drizzleSqlite(sqlite);
9
+ }
11
10
 
12
- const sqlite = new Database(process.env.DATABASE_URL);
13
- singleton = drizzle(sqlite);
14
- }
15
- return singleton;
11
+ //# BATI.hasD1
12
+ export function dbD1(d1: D1Database) {
13
+ return drizzleD1(d1);
16
14
  }
@@ -1,27 +1,56 @@
1
1
  /*# BATI include-if-imported #*/
2
- import { db } from "../db";
2
+ import { dbD1, dbSqlite } from "../db";
3
3
  import { oauthAccountTable, userTable } from "../schema/lucia-auth";
4
4
  import { and, eq } from "drizzle-orm";
5
5
 
6
- export function getExistingUser(username: string) {
7
- return db().select().from(userTable).where(eq(userTable.username, username)).get();
6
+ export async function getExistingUser(
7
+ db: BATI.If<{
8
+ "!BATI.hasD1": ReturnType<typeof dbSqlite>;
9
+ _: ReturnType<typeof dbD1>;
10
+ }>,
11
+ username: string,
12
+ ) {
13
+ return db.select().from(userTable).where(eq(userTable.username, username)).get();
8
14
  }
9
15
 
10
- export function getExistingAccount(providerId: string, providerUserId: number) {
11
- return db()
16
+ export async function getExistingAccount(
17
+ db: BATI.If<{
18
+ "!BATI.hasD1": ReturnType<typeof dbSqlite>;
19
+ _: ReturnType<typeof dbD1>;
20
+ }>,
21
+ providerId: string,
22
+ providerUserId: number,
23
+ ) {
24
+ return db
12
25
  .select()
13
26
  .from(oauthAccountTable)
14
27
  .where(and(eq(oauthAccountTable.providerId, providerId), eq(oauthAccountTable.providerUserId, providerUserId)))
15
28
  .get();
16
29
  }
17
30
 
18
- export function signupWithGithub(userId: string, username: string, githubUserId: number) {
19
- return db().transaction(async (tx) => {
31
+ export async function signupWithGithub(
32
+ db: BATI.If<{
33
+ "!BATI.hasD1": ReturnType<typeof dbSqlite>;
34
+ _: ReturnType<typeof dbD1>;
35
+ }>,
36
+ userId: string,
37
+ username: string,
38
+ githubUserId: number,
39
+ ) {
40
+ return db.transaction(async (tx) => {
20
41
  await tx.insert(userTable).values({ id: userId, username: username });
21
42
  await tx.insert(oauthAccountTable).values({ providerId: "github", providerUserId: githubUserId, userId });
22
43
  });
23
44
  }
24
45
 
25
- export function signupWithCredentials(userId: string, username: string, passwordHash: string) {
26
- return db().insert(userTable).values({ id: userId, username, password: passwordHash }).run();
46
+ export async function signupWithCredentials(
47
+ db: BATI.If<{
48
+ "!BATI.hasD1": ReturnType<typeof dbSqlite>;
49
+ _: ReturnType<typeof dbD1>;
50
+ }>,
51
+ userId: string,
52
+ username: string,
53
+ passwordHash: string,
54
+ ) {
55
+ return db.insert(userTable).values({ id: userId, username, password: passwordHash }).run();
27
56
  }
@@ -1,11 +1,22 @@
1
1
  /*# BATI include-if-imported #*/
2
- import { db } from "../db";
3
2
  import { todoTable } from "../schema/todos";
3
+ import { dbD1, type dbSqlite } from "../db";
4
4
 
5
- export function insertTodo(text: string) {
6
- return db().insert(todoTable).values({ text });
5
+ export function insertTodo(
6
+ db: BATI.If<{
7
+ "!BATI.hasD1": ReturnType<typeof dbSqlite>;
8
+ _: ReturnType<typeof dbD1>;
9
+ }>,
10
+ text: string,
11
+ ) {
12
+ return db.insert(todoTable).values({ text });
7
13
  }
8
14
 
9
- export function getAllTodos() {
10
- return db().select().from(todoTable).all();
15
+ export function getAllTodos(
16
+ db: BATI.If<{
17
+ "!BATI.hasD1": ReturnType<typeof dbSqlite>;
18
+ _: ReturnType<typeof dbD1>;
19
+ }>,
20
+ ) {
21
+ return db.select().from(todoTable).all();
11
22
  }
@@ -1,14 +1,17 @@
1
1
  import { defineConfig } from "drizzle-kit";
2
2
 
3
- if (!process.env.DATABASE_URL) {
4
- throw new Error("Missing DATABASE_URL in .env file");
3
+ if (!BATI.hasD1) {
4
+ if (!process.env.DATABASE_URL) {
5
+ throw new Error("Missing DATABASE_URL in .env file");
6
+ }
5
7
  }
6
8
 
7
9
  export default defineConfig({
8
10
  dialect: "sqlite",
9
11
  schema: "./database/drizzle/schema/*",
10
- out: "./database/drizzle/migrations",
12
+ out: "./database/migrations",
13
+ //# !BATI.hasD1
11
14
  dbCredentials: {
12
- url: process.env.DATABASE_URL,
15
+ url: process.env.DATABASE_URL!,
13
16
  },
14
17
  });