@astrojs/db 0.0.0-edge-nested-20240223135627

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 (60) hide show
  1. package/LICENSE +59 -0
  2. package/config-augment.d.ts +4 -0
  3. package/dist/core/cli/commands/gen/index.d.ts +6 -0
  4. package/dist/core/cli/commands/gen/index.js +39 -0
  5. package/dist/core/cli/commands/link/index.d.ts +8 -0
  6. package/dist/core/cli/commands/link/index.js +78 -0
  7. package/dist/core/cli/commands/login/index.d.ts +6 -0
  8. package/dist/core/cli/commands/login/index.js +46 -0
  9. package/dist/core/cli/commands/logout/index.d.ts +6 -0
  10. package/dist/core/cli/commands/logout/index.js +9 -0
  11. package/dist/core/cli/commands/push/index.d.ts +6 -0
  12. package/dist/core/cli/commands/push/index.js +209 -0
  13. package/dist/core/cli/commands/shell/index.d.ts +6 -0
  14. package/dist/core/cli/commands/shell/index.js +15 -0
  15. package/dist/core/cli/commands/verify/index.d.ts +6 -0
  16. package/dist/core/cli/commands/verify/index.js +43 -0
  17. package/dist/core/cli/index.d.ts +6 -0
  18. package/dist/core/cli/index.js +68 -0
  19. package/dist/core/cli/migration-queries.d.ts +26 -0
  20. package/dist/core/cli/migration-queries.js +418 -0
  21. package/dist/core/cli/migrations.d.ts +34 -0
  22. package/dist/core/cli/migrations.js +129 -0
  23. package/dist/core/consts.d.ts +6 -0
  24. package/dist/core/consts.js +17 -0
  25. package/dist/core/errors.d.ts +7 -0
  26. package/dist/core/errors.js +54 -0
  27. package/dist/core/integration/error-map.d.ts +6 -0
  28. package/dist/core/integration/error-map.js +79 -0
  29. package/dist/core/integration/file-url.d.ts +2 -0
  30. package/dist/core/integration/file-url.js +84 -0
  31. package/dist/core/integration/index.d.ts +2 -0
  32. package/dist/core/integration/index.js +173 -0
  33. package/dist/core/integration/load-astro-config.d.ts +6 -0
  34. package/dist/core/integration/load-astro-config.js +79 -0
  35. package/dist/core/integration/typegen.d.ts +5 -0
  36. package/dist/core/integration/typegen.js +41 -0
  37. package/dist/core/integration/vite-plugin-db.d.ts +25 -0
  38. package/dist/core/integration/vite-plugin-db.js +73 -0
  39. package/dist/core/integration/vite-plugin-inject-env-ts.d.ts +11 -0
  40. package/dist/core/integration/vite-plugin-inject-env-ts.js +53 -0
  41. package/dist/core/queries.d.ts +78 -0
  42. package/dist/core/queries.js +218 -0
  43. package/dist/core/tokens.d.ts +11 -0
  44. package/dist/core/tokens.js +131 -0
  45. package/dist/core/types.d.ts +8059 -0
  46. package/dist/core/types.js +209 -0
  47. package/dist/core/utils.d.ts +5 -0
  48. package/dist/core/utils.js +18 -0
  49. package/dist/index.d.ts +5 -0
  50. package/dist/index.js +16 -0
  51. package/dist/runtime/db-client.d.ts +12 -0
  52. package/dist/runtime/db-client.js +96 -0
  53. package/dist/runtime/drizzle.d.ts +1 -0
  54. package/dist/runtime/drizzle.js +48 -0
  55. package/dist/runtime/index.d.ts +30 -0
  56. package/dist/runtime/index.js +124 -0
  57. package/dist/runtime/types.d.ts +69 -0
  58. package/dist/runtime/types.js +8 -0
  59. package/index.d.ts +3 -0
  60. package/package.json +81 -0
@@ -0,0 +1,79 @@
1
+ const errorMap = (baseError, ctx) => {
2
+ const baseErrorPath = flattenErrorPath(baseError.path);
3
+ if (baseError.code === "invalid_union") {
4
+ const typeOrLiteralErrByPath = /* @__PURE__ */ new Map();
5
+ for (const unionError of baseError.unionErrors.flatMap((e) => e.errors)) {
6
+ if (unionError.code === "invalid_type" || unionError.code === "invalid_literal") {
7
+ const flattenedErrorPath = flattenErrorPath(unionError.path);
8
+ const typeOrLiteralErr = typeOrLiteralErrByPath.get(flattenedErrorPath);
9
+ if (typeOrLiteralErr) {
10
+ typeOrLiteralErr.expected.push(unionError.expected);
11
+ } else {
12
+ typeOrLiteralErrByPath.set(flattenedErrorPath, {
13
+ code: unionError.code,
14
+ received: unionError.received,
15
+ expected: [unionError.expected]
16
+ });
17
+ }
18
+ }
19
+ }
20
+ const messages = [
21
+ prefix(
22
+ baseErrorPath,
23
+ typeOrLiteralErrByPath.size ? "Did not match union:" : "Did not match union."
24
+ )
25
+ ];
26
+ return {
27
+ message: messages.concat(
28
+ [...typeOrLiteralErrByPath.entries()].filter(([, error]) => error.expected.length === baseError.unionErrors.length).map(
29
+ ([key, error]) => (
30
+ // Avoid printing the key again if it's a base error
31
+ key === baseErrorPath ? `> ${getTypeOrLiteralMsg(error)}` : `> ${prefix(key, getTypeOrLiteralMsg(error))}`
32
+ )
33
+ )
34
+ ).join("\n")
35
+ };
36
+ }
37
+ if (baseError.code === "invalid_literal" || baseError.code === "invalid_type") {
38
+ return {
39
+ message: prefix(
40
+ baseErrorPath,
41
+ getTypeOrLiteralMsg({
42
+ code: baseError.code,
43
+ received: baseError.received,
44
+ expected: [baseError.expected]
45
+ })
46
+ )
47
+ };
48
+ } else if (baseError.message) {
49
+ return { message: prefix(baseErrorPath, baseError.message) };
50
+ } else {
51
+ return { message: prefix(baseErrorPath, ctx.defaultError) };
52
+ }
53
+ };
54
+ const getTypeOrLiteralMsg = (error) => {
55
+ if (error.received === "undefined")
56
+ return "Required";
57
+ const expectedDeduped = new Set(error.expected);
58
+ switch (error.code) {
59
+ case "invalid_type":
60
+ return `Expected type \`${unionExpectedVals(expectedDeduped)}\`, received ${JSON.stringify(
61
+ error.received
62
+ )}`;
63
+ case "invalid_literal":
64
+ return `Expected \`${unionExpectedVals(expectedDeduped)}\`, received ${JSON.stringify(
65
+ error.received
66
+ )}`;
67
+ }
68
+ };
69
+ const prefix = (key, msg) => key.length ? `**${key}**: ${msg}` : msg;
70
+ const unionExpectedVals = (expectedVals) => [...expectedVals].map((expectedVal, idx) => {
71
+ if (idx === 0)
72
+ return JSON.stringify(expectedVal);
73
+ const sep = " | ";
74
+ return `${sep}${JSON.stringify(expectedVal)}`;
75
+ }).join("");
76
+ const flattenErrorPath = (errorPath) => errorPath.join(".");
77
+ export {
78
+ errorMap
79
+ };
@@ -0,0 +1,2 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ export declare function fileURLIntegration(): AstroIntegration;
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import { pathToFileURL } from "node:url";
3
+ import path from "node:path";
4
+ async function copyFile(toDir, fromUrl, toUrl) {
5
+ await fs.promises.mkdir(toDir, { recursive: true });
6
+ await fs.promises.rename(fromUrl, toUrl);
7
+ }
8
+ function fileURLIntegration() {
9
+ const fileNames = [];
10
+ function createVitePlugin(command) {
11
+ let referenceIds = [];
12
+ return {
13
+ name: "@astrojs/db/file-url",
14
+ enforce: "pre",
15
+ async load(id) {
16
+ if (id.endsWith("?fileurl")) {
17
+ const filePath = id.slice(0, id.indexOf("?"));
18
+ if (command === "build") {
19
+ const data = await fs.promises.readFile(filePath);
20
+ const name = path.basename(filePath);
21
+ const referenceId = this.emitFile({
22
+ name,
23
+ source: data,
24
+ type: "asset"
25
+ });
26
+ referenceIds.push(referenceId);
27
+ return `export default import.meta.ROLLUP_FILE_URL_${referenceId};`;
28
+ } else {
29
+ return `export default new URL(${JSON.stringify(pathToFileURL(filePath).toString())})`;
30
+ }
31
+ }
32
+ },
33
+ generateBundle() {
34
+ for (const referenceId of referenceIds) {
35
+ fileNames.push(this.getFileName(referenceId));
36
+ }
37
+ referenceIds = [];
38
+ }
39
+ };
40
+ }
41
+ let config;
42
+ return {
43
+ name: "@astrojs/db/file-url",
44
+ hooks: {
45
+ "astro:config:setup"({ updateConfig, command }) {
46
+ updateConfig({
47
+ vite: {
48
+ plugins: [createVitePlugin(command)]
49
+ }
50
+ });
51
+ },
52
+ "astro:config:done": ({ config: _config }) => {
53
+ config = _config;
54
+ },
55
+ async "astro:build:done"() {
56
+ if (config.output === "static") {
57
+ const unlinks = [];
58
+ for (const fileName of fileNames) {
59
+ const url = new URL(fileName, config.outDir);
60
+ unlinks.push(fs.promises.unlink(url));
61
+ }
62
+ await Promise.all(unlinks);
63
+ const assetDir = new URL(config.build.assets, config.outDir);
64
+ const assetFiles = await fs.promises.readdir(assetDir);
65
+ if (!assetFiles.length) {
66
+ await fs.promises.rmdir(assetDir);
67
+ }
68
+ } else {
69
+ const moves = [];
70
+ for (const fileName of fileNames) {
71
+ const fromUrl = new URL(fileName, config.build.client);
72
+ const toUrl = new URL(fileName, config.build.server);
73
+ const toDir = new URL("./", toUrl);
74
+ moves.push(copyFile(toDir, fromUrl, toUrl));
75
+ }
76
+ await Promise.all(moves);
77
+ }
78
+ }
79
+ }
80
+ };
81
+ }
82
+ export {
83
+ fileURLIntegration
84
+ };
@@ -0,0 +1,2 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ export declare function integration(): AstroIntegration[];
@@ -0,0 +1,173 @@
1
+ var __knownSymbol = (name, symbol) => {
2
+ return (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
3
+ };
4
+ var __using = (stack, value, async) => {
5
+ if (value != null) {
6
+ if (typeof value !== "object" && typeof value !== "function")
7
+ throw TypeError("Object expected");
8
+ var dispose;
9
+ if (async)
10
+ dispose = value[__knownSymbol("asyncDispose")];
11
+ if (dispose === void 0)
12
+ dispose = value[__knownSymbol("dispose")];
13
+ if (typeof dispose !== "function")
14
+ throw TypeError("Object not disposable");
15
+ stack.push([async, dispose, value]);
16
+ } else if (async) {
17
+ stack.push([async]);
18
+ }
19
+ return value;
20
+ };
21
+ var __callDispose = (stack, error, hasError) => {
22
+ var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
23
+ return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
24
+ };
25
+ var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
26
+ var next = (it) => {
27
+ while (it = stack.pop()) {
28
+ try {
29
+ var result = it[1] && it[1].call(it[2]);
30
+ if (it[0])
31
+ return Promise.resolve(result).then(next, (e) => (fail(e), next()));
32
+ } catch (e) {
33
+ fail(e);
34
+ }
35
+ }
36
+ if (hasError)
37
+ throw error;
38
+ };
39
+ return next();
40
+ };
41
+ import { vitePluginDb } from "./vite-plugin-db.js";
42
+ import { vitePluginInjectEnvTs } from "./vite-plugin-inject-env-ts.js";
43
+ import { typegen } from "./typegen.js";
44
+ import { existsSync } from "fs";
45
+ import { mkdir, rm, writeFile } from "fs/promises";
46
+ import { DB_PATH } from "../consts.js";
47
+ import { createLocalDatabaseClient } from "../../runtime/db-client.js";
48
+ import { astroConfigWithDbSchema } from "../types.js";
49
+ import {} from "../utils.js";
50
+ import {
51
+ STUDIO_CONFIG_MISSING_WRITABLE_COLLECTIONS_ERROR,
52
+ UNSAFE_WRITABLE_WARNING
53
+ } from "../errors.js";
54
+ import { errorMap } from "./error-map.js";
55
+ import { dirname } from "path";
56
+ import { fileURLToPath } from "url";
57
+ import { blue, yellow } from "kleur/colors";
58
+ import { fileURLIntegration } from "./file-url.js";
59
+ import { recreateTables, seedData } from "../queries.js";
60
+ import { getManagedAppTokenOrExit } from "../tokens.js";
61
+ function astroDBIntegration() {
62
+ let connectedToRemote = false;
63
+ let appToken;
64
+ let schemas = {
65
+ tables() {
66
+ throw new Error("tables not found");
67
+ }
68
+ };
69
+ let command;
70
+ return {
71
+ name: "astro:db",
72
+ hooks: {
73
+ "astro:config:setup": async ({ updateConfig, config, command: _command, logger }) => {
74
+ command = _command;
75
+ if (_command === "preview")
76
+ return;
77
+ let dbPlugin = void 0;
78
+ const studio = config.db?.studio ?? false;
79
+ if (studio && command === "build" && process.env.ASTRO_DB_TEST_ENV !== "1") {
80
+ appToken = await getManagedAppTokenOrExit();
81
+ connectedToRemote = true;
82
+ dbPlugin = vitePluginDb({
83
+ connectToStudio: true,
84
+ appToken: appToken.token,
85
+ schemas,
86
+ root: config.root
87
+ });
88
+ } else {
89
+ dbPlugin = vitePluginDb({
90
+ connectToStudio: false,
91
+ schemas,
92
+ root: config.root
93
+ });
94
+ }
95
+ updateConfig({
96
+ vite: {
97
+ assetsInclude: [DB_PATH],
98
+ plugins: [dbPlugin, vitePluginInjectEnvTs(config, logger)]
99
+ }
100
+ });
101
+ },
102
+ "astro:config:done": async ({ config, logger }) => {
103
+ const configWithDb = astroConfigWithDbSchema.parse(config, { errorMap });
104
+ const tables = configWithDb.db?.tables ?? {};
105
+ schemas.tables = () => tables;
106
+ const studio = configWithDb.db?.studio ?? false;
107
+ const unsafeWritable = Boolean(configWithDb.db?.unsafeWritable);
108
+ const foundWritableCollection = Object.entries(tables).find(([, c]) => c.writable);
109
+ const writableAllowed = studio || unsafeWritable;
110
+ if (!writableAllowed && foundWritableCollection) {
111
+ logger.error(
112
+ STUDIO_CONFIG_MISSING_WRITABLE_COLLECTIONS_ERROR(foundWritableCollection[0])
113
+ );
114
+ process.exit(1);
115
+ } else if (unsafeWritable && foundWritableCollection) {
116
+ logger.warn(UNSAFE_WRITABLE_WARNING);
117
+ }
118
+ if (!connectedToRemote) {
119
+ var _stack = [];
120
+ try {
121
+ const dbUrl = new URL(DB_PATH, config.root);
122
+ if (existsSync(dbUrl)) {
123
+ await rm(dbUrl);
124
+ }
125
+ await mkdir(dirname(fileURLToPath(dbUrl)), { recursive: true });
126
+ await writeFile(dbUrl, "");
127
+ const db = __using(_stack, await createLocalDatabaseClient({
128
+ tables,
129
+ dbUrl: dbUrl.toString(),
130
+ seeding: true
131
+ }));
132
+ await recreateTables({ db, tables });
133
+ if (configWithDb.db?.data) {
134
+ await seedData({
135
+ db,
136
+ data: configWithDb.db.data,
137
+ logger,
138
+ mode: command === "dev" ? "dev" : "build"
139
+ });
140
+ }
141
+ logger.debug("Database setup complete.");
142
+ } catch (_) {
143
+ var _error = _, _hasError = true;
144
+ } finally {
145
+ __callDispose(_stack, _error, _hasError);
146
+ }
147
+ }
148
+ await typegen({ tables, root: config.root });
149
+ },
150
+ "astro:server:start": async ({ logger }) => {
151
+ setTimeout(() => {
152
+ logger.info(
153
+ connectedToRemote ? "Connected to remote database." : "New local database created."
154
+ );
155
+ }, 100);
156
+ },
157
+ "astro:build:start": async ({ logger }) => {
158
+ logger.info(
159
+ "database: " + (connectedToRemote ? yellow("remote") : blue("local database."))
160
+ );
161
+ },
162
+ "astro:build:done": async ({}) => {
163
+ await appToken?.destroy();
164
+ }
165
+ }
166
+ };
167
+ }
168
+ function integration() {
169
+ return [astroDBIntegration(), fileURLIntegration()];
170
+ }
171
+ export {
172
+ integration
173
+ };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Pulled from the mothership, Astro core ❤️
3
+ *
4
+ * @see https://github.com/withastro/astro/blob/main/packages/astro/src/core/config/config.ts#L121
5
+ */
6
+ export declare function loadAstroConfig(root: string): Promise<Record<string, unknown>>;
@@ -0,0 +1,79 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { bold, red } from "kleur/colors";
5
+ import { createServer } from "vite";
6
+ async function loadAstroConfig(root) {
7
+ const configPath = search(root);
8
+ if (!configPath)
9
+ return {};
10
+ try {
11
+ return await loadConfigWithVite(configPath);
12
+ } catch (e) {
13
+ console.error(`${bold(red("[astro]"))} Unable to load Astro config.
14
+ `);
15
+ throw e;
16
+ }
17
+ }
18
+ function search(root) {
19
+ const paths = [
20
+ "astro.config.mjs",
21
+ "astro.config.js",
22
+ "astro.config.ts",
23
+ "astro.config.mts",
24
+ "astro.config.cjs",
25
+ "astro.config.cts"
26
+ ].map((p) => path.join(root, p));
27
+ for (const file of paths) {
28
+ if (fs.existsSync(file)) {
29
+ return file;
30
+ }
31
+ }
32
+ }
33
+ async function loadConfigWithVite(configPath) {
34
+ if (/\.[cm]?js$/.test(configPath)) {
35
+ try {
36
+ const config = await import(
37
+ /* @vite-ignore */
38
+ pathToFileURL(configPath).toString() + "?t=" + Date.now()
39
+ );
40
+ return config.default ?? {};
41
+ } catch (e) {
42
+ }
43
+ }
44
+ let server;
45
+ try {
46
+ server = await createViteServer();
47
+ const mod = await server.ssrLoadModule(configPath, { fixStacktrace: true });
48
+ return mod.default ?? {};
49
+ } finally {
50
+ if (server) {
51
+ await server.close();
52
+ }
53
+ }
54
+ }
55
+ async function createViteServer() {
56
+ const viteServer = await createServer({
57
+ server: { middlewareMode: true, hmr: false, watch: { ignored: ["**"] } },
58
+ optimizeDeps: { disabled: true },
59
+ clearScreen: false,
60
+ appType: "custom",
61
+ ssr: {
62
+ // NOTE: Vite doesn't externalize linked packages by default. During testing locally,
63
+ // these dependencies trip up Vite's dev SSR transform. Awaiting upstream feature:
64
+ // https://github.com/vitejs/vite/pull/10939
65
+ external: [
66
+ "@astrojs/tailwind",
67
+ "@astrojs/mdx",
68
+ "@astrojs/react",
69
+ "@astrojs/preact",
70
+ "@astrojs/sitemap",
71
+ "@astrojs/markdoc"
72
+ ]
73
+ }
74
+ });
75
+ return viteServer;
76
+ }
77
+ export {
78
+ loadAstroConfig
79
+ };
@@ -0,0 +1,5 @@
1
+ import type { DBTables } from '../types.js';
2
+ export declare function typegen({ tables, root }: {
3
+ tables: DBTables;
4
+ root: URL;
5
+ }): Promise<void>;
@@ -0,0 +1,41 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { DB_TYPES_FILE, RUNTIME_DRIZZLE_IMPORT, RUNTIME_IMPORT } from "../consts.js";
4
+ async function typegen({ tables, root }) {
5
+ const content = `// This file is generated by \`studio sync\`
6
+ declare module 'astro:db' {
7
+ export const db: import(${RUNTIME_IMPORT}).SqliteDB;
8
+ export const dbUrl: string;
9
+ export * from ${RUNTIME_DRIZZLE_IMPORT};
10
+
11
+ ${Object.entries(tables).map(([name, collection]) => generateTableType(name, collection)).join("\n")}
12
+ }
13
+ `;
14
+ const dotAstroDir = new URL(".astro/", root);
15
+ if (!existsSync(dotAstroDir)) {
16
+ await mkdir(dotAstroDir);
17
+ }
18
+ await writeFile(new URL(DB_TYPES_FILE, dotAstroDir), content);
19
+ }
20
+ function generateTableType(name, collection) {
21
+ let tableType = ` export const ${name}: import(${RUNTIME_IMPORT}).Table<
22
+ ${JSON.stringify(name)},
23
+ ${JSON.stringify(
24
+ Object.fromEntries(
25
+ Object.entries(collection.columns).map(([columnName, column]) => [
26
+ columnName,
27
+ {
28
+ // Only select columns Drizzle needs for inference
29
+ type: column.type,
30
+ optional: column.schema.optional,
31
+ default: column.schema.default
32
+ }
33
+ ])
34
+ )
35
+ )}
36
+ >;`;
37
+ return tableType;
38
+ }
39
+ export {
40
+ typegen
41
+ };
@@ -0,0 +1,25 @@
1
+ import type { DBTables } from '../types.js';
2
+ import type { VitePlugin } from '../utils.js';
3
+ type LateSchema = {
4
+ tables: () => DBTables;
5
+ };
6
+ type VitePluginDBParams = {
7
+ connectToStudio: false;
8
+ schemas: LateSchema;
9
+ root: URL;
10
+ } | {
11
+ connectToStudio: true;
12
+ schemas: LateSchema;
13
+ appToken: string;
14
+ root: URL;
15
+ };
16
+ export declare function vitePluginDb(params: VitePluginDBParams): VitePlugin;
17
+ export declare function getVirtualModContents({ tables, root }: {
18
+ tables: DBTables;
19
+ root: URL;
20
+ }): string;
21
+ export declare function getStudioVirtualModContents({ tables, appToken, }: {
22
+ tables: DBTables;
23
+ appToken: string;
24
+ }): string;
25
+ export {};
@@ -0,0 +1,73 @@
1
+ import { DB_PATH, RUNTIME_DRIZZLE_IMPORT, RUNTIME_IMPORT, VIRTUAL_MODULE_ID } from "../consts.js";
2
+ const resolvedVirtualModuleId = "\0" + VIRTUAL_MODULE_ID;
3
+ function vitePluginDb(params) {
4
+ return {
5
+ name: "astro:db",
6
+ enforce: "pre",
7
+ resolveId(id) {
8
+ if (id === VIRTUAL_MODULE_ID) {
9
+ return resolvedVirtualModuleId;
10
+ }
11
+ },
12
+ load(id) {
13
+ if (id !== resolvedVirtualModuleId)
14
+ return;
15
+ if (params.connectToStudio) {
16
+ return getStudioVirtualModContents({
17
+ appToken: params.appToken,
18
+ tables: params.schemas.tables()
19
+ });
20
+ }
21
+ return getVirtualModContents({
22
+ root: params.root,
23
+ tables: params.schemas.tables()
24
+ });
25
+ }
26
+ };
27
+ }
28
+ function getVirtualModContents({ tables, root }) {
29
+ const dbUrl = new URL(DB_PATH, root);
30
+ return `
31
+ import { collectionToTable, createLocalDatabaseClient } from ${RUNTIME_IMPORT};
32
+ import dbUrl from ${JSON.stringify(`${dbUrl}?fileurl`)};
33
+
34
+ const params = ${JSON.stringify({
35
+ tables,
36
+ seeding: false
37
+ })};
38
+ params.dbUrl = dbUrl;
39
+
40
+ export const db = await createLocalDatabaseClient(params);
41
+
42
+ export * from ${RUNTIME_DRIZZLE_IMPORT};
43
+
44
+ ${getStringifiedCollectionExports(tables)}
45
+ `;
46
+ }
47
+ function getStudioVirtualModContents({
48
+ tables,
49
+ appToken
50
+ }) {
51
+ return `
52
+ import {collectionToTable, createRemoteDatabaseClient} from ${RUNTIME_IMPORT};
53
+
54
+ export const db = await createRemoteDatabaseClient(${JSON.stringify(
55
+ appToken
56
+ )}, import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL);
57
+ export * from ${RUNTIME_DRIZZLE_IMPORT};
58
+
59
+ ${getStringifiedCollectionExports(tables)}
60
+ `;
61
+ }
62
+ function getStringifiedCollectionExports(tables) {
63
+ return Object.entries(tables).map(
64
+ ([name, collection]) => `export const ${name} = collectionToTable(${JSON.stringify(name)}, ${JSON.stringify(
65
+ collection
66
+ )}, false)`
67
+ ).join("\n");
68
+ }
69
+ export {
70
+ getStudioVirtualModContents,
71
+ getVirtualModContents,
72
+ vitePluginDb
73
+ };
@@ -0,0 +1,11 @@
1
+ import type { VitePlugin } from '../utils.js';
2
+ import type { AstroIntegrationLogger } from 'astro';
3
+ export declare function vitePluginInjectEnvTs({ srcDir, root }: {
4
+ srcDir: URL;
5
+ root: URL;
6
+ }, logger: AstroIntegrationLogger): VitePlugin;
7
+ export declare function setUpEnvTs({ srcDir, root, logger, }: {
8
+ srcDir: URL;
9
+ root: URL;
10
+ logger: AstroIntegrationLogger;
11
+ }): Promise<void>;
@@ -0,0 +1,53 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { bold, cyan } from "kleur/colors";
6
+ import { normalizePath } from "vite";
7
+ import { DB_TYPES_FILE } from "../consts.js";
8
+ function vitePluginInjectEnvTs({ srcDir, root }, logger) {
9
+ return {
10
+ name: "db-inject-env-ts",
11
+ enforce: "post",
12
+ async config() {
13
+ await setUpEnvTs({ srcDir, root, logger });
14
+ }
15
+ };
16
+ }
17
+ async function setUpEnvTs({
18
+ srcDir,
19
+ root,
20
+ logger
21
+ }) {
22
+ const envTsPath = getEnvTsPath({ srcDir });
23
+ const envTsPathRelativetoRoot = normalizePath(
24
+ path.relative(fileURLToPath(root), fileURLToPath(envTsPath))
25
+ );
26
+ if (existsSync(envTsPath)) {
27
+ let typesEnvContents = await readFile(envTsPath, "utf-8");
28
+ const dotAstroDir = new URL(".astro/", root);
29
+ if (!existsSync(dotAstroDir))
30
+ return;
31
+ const dbTypeReference = getDBTypeReference({ srcDir, dotAstroDir });
32
+ if (!typesEnvContents.includes(dbTypeReference)) {
33
+ typesEnvContents = `${dbTypeReference}
34
+ ${typesEnvContents}`;
35
+ await writeFile(envTsPath, typesEnvContents, "utf-8");
36
+ logger.info(`${cyan(bold("[astro:db]"))} Added ${bold(envTsPathRelativetoRoot)} types`);
37
+ }
38
+ }
39
+ }
40
+ function getDBTypeReference({ srcDir, dotAstroDir }) {
41
+ const dbTypesFile = new URL(DB_TYPES_FILE, dotAstroDir);
42
+ const contentTypesRelativeToSrcDir = normalizePath(
43
+ path.relative(fileURLToPath(srcDir), fileURLToPath(dbTypesFile))
44
+ );
45
+ return `/// <reference path=${JSON.stringify(contentTypesRelativeToSrcDir)} />`;
46
+ }
47
+ function getEnvTsPath({ srcDir }) {
48
+ return new URL("env.d.ts", srcDir);
49
+ }
50
+ export {
51
+ setUpEnvTs,
52
+ vitePluginInjectEnvTs
53
+ };