@astrojs/db 0.0.0-db-export-bug-20240307130354

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 (63) hide show
  1. package/LICENSE +59 -0
  2. package/README.md +38 -0
  3. package/dist/core/cli/commands/execute/index.d.ts +8 -0
  4. package/dist/core/cli/commands/execute/index.js +32 -0
  5. package/dist/core/cli/commands/link/index.d.ts +20 -0
  6. package/dist/core/cli/commands/link/index.js +238 -0
  7. package/dist/core/cli/commands/login/index.d.ts +8 -0
  8. package/dist/core/cli/commands/login/index.js +55 -0
  9. package/dist/core/cli/commands/logout/index.d.ts +1 -0
  10. package/dist/core/cli/commands/logout/index.js +9 -0
  11. package/dist/core/cli/commands/push/index.d.ts +8 -0
  12. package/dist/core/cli/commands/push/index.js +77 -0
  13. package/dist/core/cli/commands/shell/index.d.ts +8 -0
  14. package/dist/core/cli/commands/shell/index.js +17 -0
  15. package/dist/core/cli/commands/verify/index.d.ts +8 -0
  16. package/dist/core/cli/commands/verify/index.js +46 -0
  17. package/dist/core/cli/index.d.ts +6 -0
  18. package/dist/core/cli/index.js +77 -0
  19. package/dist/core/cli/migration-queries.d.ts +22 -0
  20. package/dist/core/cli/migration-queries.js +366 -0
  21. package/dist/core/consts.d.ts +7 -0
  22. package/dist/core/consts.js +19 -0
  23. package/dist/core/errors.d.ts +11 -0
  24. package/dist/core/errors.js +65 -0
  25. package/dist/core/integration/error-map.d.ts +6 -0
  26. package/dist/core/integration/error-map.js +79 -0
  27. package/dist/core/integration/file-url.d.ts +2 -0
  28. package/dist/core/integration/file-url.js +81 -0
  29. package/dist/core/integration/index.d.ts +2 -0
  30. package/dist/core/integration/index.js +112 -0
  31. package/dist/core/integration/typegen.d.ts +5 -0
  32. package/dist/core/integration/typegen.js +31 -0
  33. package/dist/core/integration/vite-plugin-db.d.ts +29 -0
  34. package/dist/core/integration/vite-plugin-db.js +111 -0
  35. package/dist/core/integration/vite-plugin-inject-env-ts.d.ts +11 -0
  36. package/dist/core/integration/vite-plugin-inject-env-ts.js +53 -0
  37. package/dist/core/load-file.d.ts +31 -0
  38. package/dist/core/load-file.js +98 -0
  39. package/dist/core/tokens.d.ts +11 -0
  40. package/dist/core/tokens.js +131 -0
  41. package/dist/core/types.d.ts +3901 -0
  42. package/dist/core/types.js +143 -0
  43. package/dist/core/utils.d.ts +6 -0
  44. package/dist/core/utils.js +22 -0
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.js +6 -0
  47. package/dist/runtime/config.d.ts +148 -0
  48. package/dist/runtime/config.js +87 -0
  49. package/dist/runtime/db-client.d.ts +5 -0
  50. package/dist/runtime/db-client.js +64 -0
  51. package/dist/runtime/drizzle.d.ts +1 -0
  52. package/dist/runtime/drizzle.js +48 -0
  53. package/dist/runtime/index.d.ts +31 -0
  54. package/dist/runtime/index.js +126 -0
  55. package/dist/runtime/queries.d.ts +81 -0
  56. package/dist/runtime/queries.js +206 -0
  57. package/dist/runtime/types.d.ts +69 -0
  58. package/dist/runtime/types.js +8 -0
  59. package/dist/utils.d.ts +1 -0
  60. package/dist/utils.js +4 -0
  61. package/index.d.ts +3 -0
  62. package/package.json +90 -0
  63. package/virtual.d.ts +9 -0
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
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
+ await fs.promises.rmdir(assetDir).catch(() => []);
65
+ } else {
66
+ const moves = [];
67
+ for (const fileName of fileNames) {
68
+ const fromUrl = new URL(fileName, config.build.client);
69
+ const toUrl = new URL(fileName, config.build.server);
70
+ const toDir = new URL("./", toUrl);
71
+ moves.push(copyFile(toDir, fromUrl, toUrl));
72
+ }
73
+ await Promise.all(moves);
74
+ }
75
+ }
76
+ }
77
+ };
78
+ }
79
+ export {
80
+ fileURLIntegration
81
+ };
@@ -0,0 +1,2 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ export declare function integration(): AstroIntegration[];
@@ -0,0 +1,112 @@
1
+ import { existsSync } from "fs";
2
+ import { dirname } from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { mkdir, rm, writeFile } from "fs/promises";
5
+ import { blue, yellow } from "kleur/colors";
6
+ import { CONFIG_FILE_NAMES, DB_PATH } from "../consts.js";
7
+ import { loadDbConfigFile } from "../load-file.js";
8
+ import { getManagedAppTokenOrExit } from "../tokens.js";
9
+ import { dbConfigSchema } from "../types.js";
10
+ import { getDbDirectoryUrl } from "../utils.js";
11
+ import { errorMap } from "./error-map.js";
12
+ import { fileURLIntegration } from "./file-url.js";
13
+ import { typegen } from "./typegen.js";
14
+ import { vitePluginDb } from "./vite-plugin-db.js";
15
+ import { vitePluginInjectEnvTs } from "./vite-plugin-inject-env-ts.js";
16
+ function astroDBIntegration() {
17
+ let connectToStudio = false;
18
+ let configFileDependencies = [];
19
+ let root;
20
+ let appToken;
21
+ let dbConfig;
22
+ let tables = {
23
+ get() {
24
+ throw new Error("[astro:db] INTERNAL Tables not loaded yet");
25
+ }
26
+ };
27
+ let command;
28
+ return {
29
+ name: "astro:db",
30
+ hooks: {
31
+ "astro:config:setup": async ({ updateConfig, config, command: _command, logger }) => {
32
+ command = _command;
33
+ root = config.root;
34
+ if (command === "preview")
35
+ return;
36
+ let dbPlugin = void 0;
37
+ connectToStudio = command === "build";
38
+ if (connectToStudio) {
39
+ appToken = await getManagedAppTokenOrExit();
40
+ dbPlugin = vitePluginDb({
41
+ connectToStudio,
42
+ appToken: appToken.token,
43
+ tables,
44
+ root: config.root,
45
+ srcDir: config.srcDir
46
+ });
47
+ } else {
48
+ dbPlugin = vitePluginDb({
49
+ connectToStudio: false,
50
+ tables,
51
+ root: config.root,
52
+ srcDir: config.srcDir
53
+ });
54
+ }
55
+ updateConfig({
56
+ vite: {
57
+ assetsInclude: [DB_PATH],
58
+ plugins: [dbPlugin, vitePluginInjectEnvTs(config, logger)]
59
+ }
60
+ });
61
+ },
62
+ "astro:config:done": async ({ config }) => {
63
+ const { mod, dependencies } = await loadDbConfigFile(config.root);
64
+ configFileDependencies = dependencies;
65
+ dbConfig = dbConfigSchema.parse(mod?.default ?? {}, {
66
+ errorMap
67
+ });
68
+ tables.get = () => dbConfig.tables ?? {};
69
+ if (!connectToStudio && !process.env.TEST_IN_MEMORY_DB) {
70
+ const dbUrl = new URL(DB_PATH, config.root);
71
+ if (existsSync(dbUrl)) {
72
+ await rm(dbUrl);
73
+ }
74
+ await mkdir(dirname(fileURLToPath(dbUrl)), { recursive: true });
75
+ await writeFile(dbUrl, "");
76
+ }
77
+ await typegen({ tables: tables.get() ?? {}, root: config.root });
78
+ },
79
+ "astro:server:start": async ({ logger }) => {
80
+ setTimeout(() => {
81
+ logger.info(
82
+ connectToStudio ? "Connected to remote database." : "New local database created."
83
+ );
84
+ }, 100);
85
+ },
86
+ "astro:server:setup": async ({ server }) => {
87
+ const filesToWatch = [
88
+ ...CONFIG_FILE_NAMES.map((c) => new URL(c, getDbDirectoryUrl(root))),
89
+ ...configFileDependencies.map((c) => new URL(c, root))
90
+ ];
91
+ server.watcher.on("all", (event, relativeEntry) => {
92
+ const entry = new URL(relativeEntry, root);
93
+ if (filesToWatch.some((f) => entry.href === f.href)) {
94
+ server.restart();
95
+ }
96
+ });
97
+ },
98
+ "astro:build:start": async ({ logger }) => {
99
+ logger.info("database: " + (connectToStudio ? yellow("remote") : blue("local database.")));
100
+ },
101
+ "astro:build:done": async ({}) => {
102
+ await appToken?.destroy();
103
+ }
104
+ }
105
+ };
106
+ }
107
+ function integration() {
108
+ return [astroDBIntegration(), fileURLIntegration()];
109
+ }
110
+ export {
111
+ integration
112
+ };
@@ -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,31 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { DB_TYPES_FILE, RUNTIME_CONFIG_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_CONFIG_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
+ const sanitizedColumnsList = Object.entries(collection.columns).filter(([key, val]) => !val.schema.deprecated);
22
+ const sanitizedColumns = Object.fromEntries(sanitizedColumnsList);
23
+ let tableType = ` export const ${name}: import(${RUNTIME_IMPORT}).Table<
24
+ ${JSON.stringify(name)},
25
+ ${JSON.stringify(sanitizedColumns)}
26
+ >;`;
27
+ return tableType;
28
+ }
29
+ export {
30
+ typegen
31
+ };
@@ -0,0 +1,29 @@
1
+ import type { DBTables } from '../types.js';
2
+ import { type VitePlugin } from '../utils.js';
3
+ export type LateTables = {
4
+ get: () => DBTables;
5
+ };
6
+ type VitePluginDBParams = {
7
+ connectToStudio: false;
8
+ tables: LateTables;
9
+ srcDir: URL;
10
+ root: URL;
11
+ } | {
12
+ connectToStudio: true;
13
+ tables: LateTables;
14
+ appToken: string;
15
+ srcDir: URL;
16
+ root: URL;
17
+ };
18
+ export declare function vitePluginDb(params: VitePluginDBParams): VitePlugin;
19
+ export declare function getConfigVirtualModContents(): string;
20
+ export declare function getLocalVirtualModContents({ tables, shouldSeed, }: {
21
+ tables: DBTables;
22
+ root: URL;
23
+ shouldSeed: boolean;
24
+ }): string;
25
+ export declare function getStudioVirtualModContents({ tables, appToken, }: {
26
+ tables: DBTables;
27
+ appToken: string;
28
+ }): string;
29
+ export {};
@@ -0,0 +1,111 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { normalizePath } from "vite";
3
+ import { SEED_DEV_FILE_NAME } from "../../runtime/queries.js";
4
+ import { DB_PATH, RUNTIME_CONFIG_IMPORT, RUNTIME_IMPORT, VIRTUAL_MODULE_ID } from "../consts.js";
5
+ import { getDbDirectoryUrl, getRemoteDatabaseUrl } from "../utils.js";
6
+ const LOCAL_DB_VIRTUAL_MODULE_ID = "astro:local";
7
+ const resolvedVirtualModuleId = "\0" + VIRTUAL_MODULE_ID;
8
+ const resolvedLocalDbVirtualModuleId = LOCAL_DB_VIRTUAL_MODULE_ID + "/local-db";
9
+ const resolvedSeedVirtualModuleId = "\0" + VIRTUAL_MODULE_ID + "?shouldSeed";
10
+ function vitePluginDb(params) {
11
+ const srcDirPath = normalizePath(fileURLToPath(params.srcDir));
12
+ return {
13
+ name: "astro:db",
14
+ enforce: "pre",
15
+ async resolveId(id, rawImporter) {
16
+ if (id === LOCAL_DB_VIRTUAL_MODULE_ID)
17
+ return resolvedLocalDbVirtualModuleId;
18
+ if (id !== VIRTUAL_MODULE_ID)
19
+ return;
20
+ if (params.connectToStudio)
21
+ return resolvedVirtualModuleId;
22
+ const importer = rawImporter ? await this.resolve(rawImporter) : null;
23
+ if (!importer)
24
+ return resolvedVirtualModuleId;
25
+ if (importer.id.startsWith(srcDirPath)) {
26
+ return resolvedSeedVirtualModuleId;
27
+ }
28
+ return resolvedVirtualModuleId;
29
+ },
30
+ load(id) {
31
+ if (id === resolvedLocalDbVirtualModuleId) {
32
+ const dbUrl = new URL(DB_PATH, params.root);
33
+ return `import { createLocalDatabaseClient } from ${RUNTIME_IMPORT};
34
+ const dbUrl = ${JSON.stringify(dbUrl)};
35
+
36
+ export const db = createLocalDatabaseClient({ dbUrl });`;
37
+ }
38
+ if (id !== resolvedVirtualModuleId && id !== resolvedSeedVirtualModuleId)
39
+ return;
40
+ if (params.connectToStudio) {
41
+ return getStudioVirtualModContents({
42
+ appToken: params.appToken,
43
+ tables: params.tables.get()
44
+ });
45
+ }
46
+ return getLocalVirtualModContents({
47
+ root: params.root,
48
+ tables: params.tables.get(),
49
+ shouldSeed: id === resolvedSeedVirtualModuleId
50
+ });
51
+ }
52
+ };
53
+ }
54
+ function getConfigVirtualModContents() {
55
+ return `export * from ${RUNTIME_CONFIG_IMPORT}`;
56
+ }
57
+ function getLocalVirtualModContents({
58
+ tables,
59
+ shouldSeed
60
+ }) {
61
+ const seedFilePaths = SEED_DEV_FILE_NAME.map(
62
+ // Format as /db/[name].ts
63
+ // for Vite import.meta.glob
64
+ (name) => new URL(name, getDbDirectoryUrl("file:///")).pathname
65
+ );
66
+ return `
67
+ import { asDrizzleTable, seedLocal } from ${RUNTIME_IMPORT};
68
+ import { db as _db } from ${JSON.stringify(LOCAL_DB_VIRTUAL_MODULE_ID)};
69
+
70
+ export const db = _db;
71
+
72
+ ${shouldSeed ? `await seedLocal({
73
+ db: _db,
74
+ tables: ${JSON.stringify(tables)},
75
+ fileGlob: import.meta.glob(${JSON.stringify(seedFilePaths)}),
76
+ })` : ""}
77
+
78
+ export * from ${RUNTIME_CONFIG_IMPORT};
79
+
80
+ ${getStringifiedCollectionExports(tables)}`;
81
+ }
82
+ function getStudioVirtualModContents({
83
+ tables,
84
+ appToken
85
+ }) {
86
+ return `
87
+ import {asDrizzleTable, createRemoteDatabaseClient} from ${RUNTIME_IMPORT};
88
+
89
+ export const db = await createRemoteDatabaseClient(${JSON.stringify(
90
+ appToken
91
+ // Respect runtime env for user overrides in SSR
92
+ )}, import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL ?? ${JSON.stringify(getRemoteDatabaseUrl())});
93
+
94
+ export * from ${RUNTIME_CONFIG_IMPORT};
95
+
96
+ ${getStringifiedCollectionExports(tables)}
97
+ `;
98
+ }
99
+ function getStringifiedCollectionExports(tables) {
100
+ return Object.entries(tables).map(
101
+ ([name, collection]) => `export const ${name} = asDrizzleTable(${JSON.stringify(name)}, ${JSON.stringify(
102
+ collection
103
+ )}, false)`
104
+ ).join("\n");
105
+ }
106
+ export {
107
+ getConfigVirtualModContents,
108
+ getLocalVirtualModContents,
109
+ getStudioVirtualModContents,
110
+ vitePluginDb
111
+ };
@@ -0,0 +1,11 @@
1
+ import type { AstroIntegrationLogger } from 'astro';
2
+ import type { VitePlugin } from '../utils.js';
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
+ };
@@ -0,0 +1,31 @@
1
+ export declare function loadDbConfigFile(root: URL): Promise<{
2
+ mod: {
3
+ default?: unknown;
4
+ } | undefined;
5
+ dependencies: string[];
6
+ }>;
7
+ /**
8
+ * Bundle arbitrary `mjs` or `ts` file.
9
+ * Simplified fork from Vite's `bundleConfigFile` function.
10
+ *
11
+ * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/config.ts#L961
12
+ */
13
+ export declare function bundleFile({ fileUrl, root, virtualModContents, }: {
14
+ fileUrl: URL;
15
+ root: URL;
16
+ virtualModContents: string;
17
+ }): Promise<{
18
+ code: string;
19
+ dependencies: string[];
20
+ }>;
21
+ /**
22
+ * Forked from Vite config loader, replacing CJS-based path concat with ESM only
23
+ *
24
+ * @see https://github.com/vitejs/vite/blob/main/packages/vite/src/node/config.ts#L1074
25
+ */
26
+ export declare function importBundledFile({ code, root, }: {
27
+ code: string;
28
+ root: URL;
29
+ }): Promise<{
30
+ default?: unknown;
31
+ }>;
@@ -0,0 +1,98 @@
1
+ import { existsSync } from "node:fs";
2
+ import { unlink, writeFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import { build as esbuild } from "esbuild";
5
+ import { CONFIG_FILE_NAMES, VIRTUAL_MODULE_ID } from "./consts.js";
6
+ import { getConfigVirtualModContents } from "./integration/vite-plugin-db.js";
7
+ import { getDbDirectoryUrl } from "./utils.js";
8
+ async function loadDbConfigFile(root) {
9
+ let configFileUrl;
10
+ for (const fileName of CONFIG_FILE_NAMES) {
11
+ const fileUrl = new URL(fileName, getDbDirectoryUrl(root));
12
+ if (existsSync(fileUrl)) {
13
+ configFileUrl = fileUrl;
14
+ }
15
+ }
16
+ if (!configFileUrl) {
17
+ return { mod: void 0, dependencies: [] };
18
+ }
19
+ const { code, dependencies } = await bundleFile({
20
+ virtualModContents: getConfigVirtualModContents(),
21
+ root,
22
+ fileUrl: configFileUrl
23
+ });
24
+ return {
25
+ mod: await importBundledFile({ code, root }),
26
+ dependencies
27
+ };
28
+ }
29
+ async function bundleFile({
30
+ fileUrl,
31
+ root,
32
+ virtualModContents
33
+ }) {
34
+ const result = await esbuild({
35
+ absWorkingDir: process.cwd(),
36
+ entryPoints: [fileURLToPath(fileUrl)],
37
+ outfile: "out.js",
38
+ packages: "external",
39
+ write: false,
40
+ target: ["node16"],
41
+ platform: "node",
42
+ bundle: true,
43
+ format: "esm",
44
+ sourcemap: "inline",
45
+ metafile: true,
46
+ define: {
47
+ "import.meta.env.ASTRO_STUDIO_REMOTE_DB_URL": "undefined"
48
+ },
49
+ plugins: [
50
+ {
51
+ name: "resolve-astro-db",
52
+ setup(build) {
53
+ build.onResolve({ filter: /^astro:db$/ }, ({ path }) => {
54
+ return { path, namespace: VIRTUAL_MODULE_ID };
55
+ });
56
+ build.onLoad({ namespace: VIRTUAL_MODULE_ID, filter: /.*/ }, () => {
57
+ return {
58
+ contents: virtualModContents,
59
+ // Needed to resolve runtime dependencies
60
+ resolveDir: fileURLToPath(root)
61
+ };
62
+ });
63
+ }
64
+ }
65
+ ]
66
+ });
67
+ const file = result.outputFiles[0];
68
+ if (!file) {
69
+ throw new Error(`Unexpected: no output file`);
70
+ }
71
+ return {
72
+ code: file.text,
73
+ dependencies: Object.keys(result.metafile.inputs)
74
+ };
75
+ }
76
+ async function importBundledFile({
77
+ code,
78
+ root
79
+ }) {
80
+ const tmpFileUrl = new URL(`./db.timestamp-${Date.now()}.mjs`, root);
81
+ await writeFile(tmpFileUrl, code, { encoding: "utf8" });
82
+ try {
83
+ return await import(
84
+ /* @vite-ignore */
85
+ tmpFileUrl.toString()
86
+ );
87
+ } finally {
88
+ try {
89
+ await unlink(tmpFileUrl);
90
+ } catch {
91
+ }
92
+ }
93
+ }
94
+ export {
95
+ bundleFile,
96
+ importBundledFile,
97
+ loadDbConfigFile
98
+ };
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ export declare const SESSION_LOGIN_FILE: import("url").URL;
3
+ export declare const PROJECT_ID_FILE: import("url").URL;
4
+ export interface ManagedAppToken {
5
+ token: string;
6
+ renew(): Promise<void>;
7
+ destroy(): Promise<void>;
8
+ }
9
+ export declare function getProjectIdFromFile(): Promise<string | undefined>;
10
+ export declare function getSessionIdFromFile(): Promise<string | undefined>;
11
+ export declare function getManagedAppTokenOrExit(token?: string): Promise<ManagedAppToken>;