nitro-drizzle 0.3.0-beta.6 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/config/defineConfig.d.mts +2 -6
- package/dist/config/defineConfig.mjs +1 -2
- package/dist/config.mjs +1 -2
- package/dist/context/internal/async.mjs +1 -2
- package/dist/context/internal/codegen.mjs +1 -2
- package/dist/context/internal/config.mjs +2 -3
- package/dist/context/internal/format.mjs +1 -2
- package/dist/context/internal/fs.mjs +1 -2
- package/dist/context/internal/logger.mjs +1 -2
- package/dist/context/internal/templates.mjs +3 -4
- package/dist/context/internal/templates.mjs.map +1 -1
- package/dist/context/internal/virtual.mjs +4 -3
- package/dist/context/internal/virtual.mjs.map +1 -1
- package/dist/context.d.mts +13 -16
- package/dist/context.mjs +34 -13
- package/dist/context.mjs.map +1 -1
- package/dist/dialects/index.d.mts +9 -12
- package/dist/dialects/mysql.d.mts +4 -8
- package/dist/dialects/mysql.mjs +1 -2
- package/dist/dialects/postgresql.d.mts +4 -8
- package/dist/dialects/postgresql.mjs +1 -2
- package/dist/dialects/sqlite.d.mts +4 -8
- package/dist/dialects/sqlite.mjs +1 -2
- package/dist/drivers/d1/dialect.mjs +1 -2
- package/dist/drivers/d1-http.d.mts +7 -10
- package/dist/drivers/d1-http.mjs +3 -4
- package/dist/drivers/d1-http.mjs.map +1 -1
- package/dist/drivers/d1.d.mts +3 -7
- package/dist/drivers/d1.mjs +4 -5
- package/dist/drivers/d1.mjs.map +1 -1
- package/dist/drivers/index.d.mts +6 -10
- package/dist/drivers/index.mjs +1 -2
- package/dist/drivers/internal/sql.mjs +1 -2
- package/dist/drivers/mysql.d.mts +2 -5
- package/dist/drivers/mysql.mjs +3 -4
- package/dist/drivers/pglite.d.mts +2 -5
- package/dist/drivers/pglite.mjs +2 -3
- package/dist/drivers/postgresql.d.mts +3 -6
- package/dist/drivers/postgresql.mjs +3 -4
- package/dist/drivers/sqlite.d.mts +3 -6
- package/dist/drivers/sqlite.mjs +3 -4
- package/dist/index.mjs +1 -2
- package/dist/meta.d.mts +2 -5
- package/dist/meta.mjs +1 -2
- package/dist/middleware/context.d.mts +7 -21
- package/dist/middleware/context.mjs +5 -25
- package/dist/middleware/context.mjs.map +1 -1
- package/dist/migrations/internal/migrate.d.mts +3 -7
- package/dist/migrations/internal/migrate.mjs +1 -2
- package/dist/migrations/internal/migrate.mjs.map +1 -1
- package/dist/migrations/migrate.d.mts +4 -7
- package/dist/migrations/migrate.mjs +3 -4
- package/dist/migrations/task.d.mts +1 -4
- package/dist/migrations/task.mjs +1 -2
- package/dist/migrations/useMigrations.d.mts +8 -12
- package/dist/migrations/useMigrations.mjs +3 -4
- package/dist/module/internal/fs.mjs +5 -6
- package/dist/module/internal/fs.mjs.map +1 -1
- package/dist/module/internal/path.mjs +1 -2
- package/dist/module/internal/reload.mjs +1 -2
- package/dist/module/internal/reload.mjs.map +1 -1
- package/dist/module/internal/resolver.mjs +1 -2
- package/dist/module/internal/resolver.mjs.map +1 -1
- package/dist/module/internal/rollup.mjs +1 -2
- package/dist/module/internal/types.mjs +21 -19
- package/dist/module/internal/types.mjs.map +1 -1
- package/dist/module/utils/assets.d.mts +1 -5
- package/dist/module/utils/assets.mjs +1 -2
- package/dist/module/utils/externals.d.mts +1 -5
- package/dist/module/utils/externals.mjs +1 -2
- package/dist/module/utils/nitro.d.mts +1 -5
- package/dist/module/utils/nitro.mjs +1 -2
- package/dist/module.d.mts +11 -21
- package/dist/module.mjs +27 -19
- package/dist/module.mjs.map +1 -1
- package/dist/plugins/init/index.d.mts +6 -0
- package/dist/plugins/init/index.mjs +20 -0
- package/dist/plugins/init/index.mjs.map +1 -0
- package/dist/plugins/init/legacy.d.mts +15 -0
- package/dist/plugins/init/legacy.mjs +26 -0
- package/dist/plugins/init/legacy.mjs.map +1 -0
- package/dist/plugins/{migrate.d.mts → migrate/hooks.d.mts} +3 -16
- package/dist/plugins/migrate/hooks.mjs +10 -0
- package/dist/plugins/migrate/hooks.mjs.map +1 -0
- package/dist/plugins/migrate/index.d.mts +11 -0
- package/dist/plugins/{migrate.mjs → migrate/index.mjs} +10 -10
- package/dist/plugins/migrate/index.mjs.map +1 -0
- package/dist/plugins/migrate/legacy.d.mts +11 -0
- package/dist/plugins/migrate/legacy.mjs +25 -0
- package/dist/plugins/migrate/legacy.mjs.map +1 -0
- package/dist/runtime/callInitHook.d.mts +8 -0
- package/dist/runtime/callInitHook.mjs +27 -0
- package/dist/runtime/callInitHook.mjs.map +1 -0
- package/dist/runtime/internal/config.mjs +1 -2
- package/dist/runtime/internal/createDatasource.mjs +4 -5
- package/dist/runtime/internal/hooks.d.mts +14 -0
- package/dist/runtime/internal/hooks.mjs +5 -0
- package/dist/runtime/internal/hooks.mjs.map +1 -0
- package/dist/runtime/internal/state.d.mts +10 -0
- package/dist/runtime/internal/state.mjs +28 -0
- package/dist/runtime/internal/state.mjs.map +1 -0
- package/dist/runtime/useConfig.d.mts +2 -6
- package/dist/runtime/useConfig.mjs +1 -2
- package/dist/runtime/useDatasource.d.mts +3 -7
- package/dist/runtime/useDatasource.mjs +2 -3
- package/dist/runtime/useDialect.d.mts +5 -8
- package/dist/runtime/useDialect.mjs +2 -3
- package/dist/runtime.d.mts +22 -22
- package/dist/runtime.mjs +4 -1
- package/dist/shared/variants.d.mts +7 -10
- package/dist/shared/variants.mjs +1 -2
- package/dist/shared.d.mts +7 -10
- package/dist/shared.mjs +1 -2
- package/dist/utils/usePrimaryKey.d.mts +1 -5
- package/dist/utils/usePrimaryKey.mjs +1 -2
- package/dist/utils.mjs +1 -2
- package/package.json +35 -31
- package/dist/drivers/db0.d.mts +0 -21
- package/dist/drivers/db0.mjs +0 -28
- package/dist/drivers/db0.mjs.map +0 -1
- package/dist/plugins/init.d.mts +0 -15
- package/dist/plugins/init.mjs +0 -13
- package/dist/plugins/init.mjs.map +0 -1
- package/dist/plugins/legacy/init.d.mts +0 -24
- package/dist/plugins/legacy/init.mjs +0 -50
- package/dist/plugins/legacy/init.mjs.map +0 -1
- package/dist/plugins/legacy/migrate.d.mts +0 -21
- package/dist/plugins/legacy/migrate.mjs +0 -25
- package/dist/plugins/legacy/migrate.mjs.map +0 -1
- package/dist/plugins/migrate.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
|
|
10
10
|
## ✨ Features
|
|
11
11
|
|
|
12
|
-
- **Datasource Management**: Easily configure and manage multiple Drizzle ORM datasources within your Nitro project.
|
|
13
|
-
- **Multiple Database Drivers**: Support for various database drivers including SQLite (with `better-sqlite3`), PostgreSQL (with `pglite`), MySQL (with `mysql2`), and Cloudflare D1.
|
|
12
|
+
- **Datasource Management**: Easily configure and manage multiple Drizzle ORM datasources within your Nitro project with granular driver activation/deactivation.
|
|
13
|
+
- **Multiple Database Drivers**: Support for various database drivers including SQLite (with `better-sqlite3`), PostgreSQL (with `pglite`), MySQL (with `mysql2`), and Cloudflare D1. Drivers can be enabled or disabled via array entries (using underscore prefixes like `_d1`) or object maps (`{ sqlite: true, d1: false }`).
|
|
14
14
|
- **Automatic Migrations**: Configure automatic database migrations on application initialization.
|
|
15
15
|
- **Type-Safe Schemas**: Leverage Drizzle ORM's type-safe schemas for a better development experience.
|
|
16
16
|
- **Nitro Task Integration**: Run Drizzle migrations as Nitro tasks.
|
|
@@ -47,7 +47,7 @@ export default defineNitroConfig({
|
|
|
47
47
|
modules: ["nitro-drizzle"],
|
|
48
48
|
drizzle: {
|
|
49
49
|
datasources: {
|
|
50
|
-
content: { drivers: ["sqlite", "d1"] },
|
|
50
|
+
content: { drivers: ["sqlite", "d1", "_pglite"] }, // Use underscore prefix (e.g., _pglite) to exclude specific drivers, but preserve type safety
|
|
51
51
|
},
|
|
52
52
|
},
|
|
53
53
|
});
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Config } from "drizzle-kit";
|
|
2
|
-
//#region src/config/defineConfig.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Define Drizzle config compatible with both 'nitro-drizzle' and 'drizzle-kit' packages.
|
|
5
4
|
* Handles path resolution automatically for schema and output paths.
|
|
@@ -7,7 +6,7 @@ import { Config } from "drizzle-kit";
|
|
|
7
6
|
* @param filename - Pass `import.meta.url` as the filename for correct relative path resolution
|
|
8
7
|
* @returns A DrizzleKit compatible configuration object with resolved paths
|
|
9
8
|
*/
|
|
10
|
-
declare function defineConfig(config: Config, filename: string): {
|
|
9
|
+
export declare function defineConfig(config: Config, filename: string): {
|
|
11
10
|
dialect: "gel" | "mysql" | "postgresql" | "singlestore" | "sqlite" | "turso";
|
|
12
11
|
breakpoints?: boolean;
|
|
13
12
|
tablesFilter?: string | string[];
|
|
@@ -403,7 +402,4 @@ declare function defineConfig(config: Config, filename: string): {
|
|
|
403
402
|
}));
|
|
404
403
|
schema: string | string[] | undefined;
|
|
405
404
|
out: string | undefined;
|
|
406
|
-
};
|
|
407
|
-
//#endregion
|
|
408
|
-
export { defineConfig };
|
|
409
|
-
//# sourceMappingURL=defineConfig.d.mts.map
|
|
405
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { relative, resolve } from "pathe";
|
|
2
2
|
import { cwd } from "node:process";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
|
-
|
|
4
|
+
// src/config/defineConfig.ts
|
|
5
5
|
/**
|
|
6
6
|
* Define Drizzle config compatible with both 'nitro-drizzle' and 'drizzle-kit' packages.
|
|
7
7
|
* Handles path resolution automatically for schema and output paths.
|
|
@@ -28,7 +28,6 @@ function transformToRelative(dirname, cwd, path) {
|
|
|
28
28
|
path = resolve(dirname, path);
|
|
29
29
|
return relative(cwd, path);
|
|
30
30
|
}
|
|
31
|
-
//#endregion
|
|
32
31
|
export { defineConfig };
|
|
33
32
|
|
|
34
33
|
//# sourceMappingURL=defineConfig.mjs.map
|
package/dist/config.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
export { defineConfig };
|
|
1
|
+
export { defineConfig } from "./config/defineConfig.mjs";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/context/internal/async.ts
|
|
2
2
|
async function* generateAsync(iterable, cb) {
|
|
3
3
|
let index = 0;
|
|
4
4
|
for await (const value of iterable) yield await cb(value, index++);
|
|
@@ -17,7 +17,6 @@ async function mapAsync(iterable, cb) {
|
|
|
17
17
|
for await (const item of generator) items.push(item);
|
|
18
18
|
return items;
|
|
19
19
|
}
|
|
20
|
-
//#endregion
|
|
21
20
|
export { mapAsync };
|
|
22
21
|
|
|
23
22
|
//# sourceMappingURL=async.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/context/internal/codegen.ts
|
|
2
2
|
/**
|
|
3
3
|
* Generates a TypeScript type name with optional generic parameters.
|
|
4
4
|
* @param name - The base type name
|
|
@@ -22,7 +22,6 @@ function genTypeName(name, options) {
|
|
|
22
22
|
function genReference(reference) {
|
|
23
23
|
return `/// <reference ${Object.entries(reference).slice(0, 1).map(([prop, value]) => `${prop}="${value}"`).join("")} />`;
|
|
24
24
|
}
|
|
25
|
-
//#endregion
|
|
26
25
|
export { genReference, genTypeName };
|
|
27
26
|
|
|
28
27
|
//# sourceMappingURL=codegen.mjs.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { genObjectKey } from "knitwork";
|
|
2
1
|
import { resolve } from "pathe";
|
|
3
|
-
|
|
2
|
+
import { genObjectKey } from "knitwork";
|
|
3
|
+
// src/context/internal/config.ts
|
|
4
4
|
/**
|
|
5
5
|
* Transforms a Drizzle config into a normalized datasource configuration.
|
|
6
6
|
* @param drizzleConfig - The raw DrizzleKit configuration
|
|
@@ -30,7 +30,6 @@ async function transformDrizzleConfig(drizzleConfig, { dirName, path, resolver,
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
const DISABLED_DATASOURCE_DIRNAME_REGEX = /^[_-]+/;
|
|
33
|
-
//#endregion
|
|
34
33
|
export { DISABLED_DATASOURCE_DIRNAME_REGEX, transformDrizzleConfig };
|
|
35
34
|
|
|
36
35
|
//# sourceMappingURL=config.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { dedent } from "strip-indent";
|
|
2
|
-
|
|
2
|
+
// src/context/internal/format.ts
|
|
3
3
|
/**
|
|
4
4
|
* Tagged template literal function that dedents and interpolates values.
|
|
5
5
|
* @param strings - The template strings array
|
|
@@ -21,7 +21,6 @@ function script(strings, ...values) {
|
|
|
21
21
|
}
|
|
22
22
|
return dedent(result);
|
|
23
23
|
}
|
|
24
|
-
//#endregion
|
|
25
24
|
export { script };
|
|
26
25
|
|
|
27
26
|
//# sourceMappingURL=format.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { glob } from "tinyglobby";
|
|
2
|
-
|
|
2
|
+
// src/context/internal/fs.ts
|
|
3
3
|
/**
|
|
4
4
|
* Resolves file paths matching a glob pattern in a base directory.
|
|
5
5
|
* @param baseDir - The base directory to search in
|
|
@@ -16,7 +16,6 @@ async function resolveFiles(baseDir, pattern, options) {
|
|
|
16
16
|
followSymbolicLinks: options?.followSymbolicLinks
|
|
17
17
|
})).sort((a, b) => a.localeCompare(b));
|
|
18
18
|
}
|
|
19
|
-
//#endregion
|
|
20
19
|
export { resolveFiles };
|
|
21
20
|
|
|
22
21
|
//# sourceMappingURL=fs.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { colorize } from "consola/utils";
|
|
2
|
-
|
|
2
|
+
// src/context/internal/logger.ts
|
|
3
3
|
function accentColor(text) {
|
|
4
4
|
return colorize("bold", colorize("greenBright", text.toString()));
|
|
5
5
|
}
|
|
@@ -20,7 +20,6 @@ function accent(strings, ...values) {
|
|
|
20
20
|
}
|
|
21
21
|
return result;
|
|
22
22
|
}
|
|
23
|
-
//#endregion
|
|
24
23
|
export { accent };
|
|
25
24
|
|
|
26
25
|
//# sourceMappingURL=logger.mjs.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { script } from "./format.mjs";
|
|
2
|
-
import { genReference, genTypeName } from "./codegen.mjs";
|
|
3
1
|
import { genInlineTypeImport, genObjectFromValues, genString, genTypeImport } from "knitwork";
|
|
4
2
|
import { genVariants } from "nitro-drizzle/shared";
|
|
5
|
-
|
|
3
|
+
import { script } from "./format.mjs";
|
|
4
|
+
import { genReference, genTypeName } from "./codegen.mjs";
|
|
5
|
+
// src/context/internal/templates.ts
|
|
6
6
|
function getConnectorDimensions({ name, driver }) {
|
|
7
7
|
return {
|
|
8
8
|
name,
|
|
@@ -88,7 +88,6 @@ function moduleTypeDeclarations(_datasources) {
|
|
|
88
88
|
function dialectDeclarations(_datasources) {
|
|
89
89
|
return ``;
|
|
90
90
|
}
|
|
91
|
-
//#endregion
|
|
92
91
|
export { dialectDeclarations, moduleTypeDeclarations, runtimeDeclarations, sharedTypeDeclarations };
|
|
93
92
|
|
|
94
93
|
//# sourceMappingURL=templates.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.mjs","names":[
|
|
1
|
+
{"version":3,"file":"templates.mjs","names":[],"sources":["../../../src/context/internal/templates.ts"],"sourcesContent":["import { genTypeImport, genString, genObjectFromValues, genInlineTypeImport } from \"knitwork\";\nimport type { DatasourceInfo, DriverOptions } from \"..\";\nimport { genVariants, type Selector, type VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\nimport { genReference, genTypeName } from \"./codegen\";\n\ntype ConnectorInfo = {\n name: string;\n driver: DriverOptions;\n};\n\nfunction getConnectorDimensions({ name, driver }: ConnectorInfo) {\n return {\n name,\n dialect: driver.dialect,\n driver: driver.name,\n };\n}\n\nclass ImportedModules {\n readonly #files: string[] = [];\n\n values(): readonly string[] {\n return [...this.#files];\n }\n\n getOrAdd(value: string): number {\n let index = this.#files.indexOf(value);\n if (!~index) {\n index = this.#files.push(value);\n }\n return index;\n }\n}\n\nexport function sharedTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n const moduleId = \"nitro-drizzle/shared\";\n const connectors = datasources.flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n });\n\n const SCHEMA_PARTS_TYPE = \"SchemaParts\";\n const SCHEMA_TYPE = \"SchemaVariants\";\n const CONNECTOR_TYPE = \"Connectors\";\n const UNWRAP_VARIANT_TYPE = \"UnwrapVariant\";\n const MERGE_SCHEMA_TYPE = \"MergeSchema\";\n\n const schemaFiles = new ImportedModules();\n connectors\n .flatMap((connector) => {\n return connector.driver.imports.schema;\n })\n .forEach((schemaFile) => {\n schemaFiles.getOrAdd(schemaFile);\n });\n\n const driverImports = new ImportedModules();\n connectors.forEach((connector) => {\n driverImports.getOrAdd(connector.driver.imports.connector);\n });\n\n const content = [\n genTypeImport(\"nitro-drizzle/shared\", [\"Variant\", UNWRAP_VARIANT_TYPE]),\n genTypeImport(\"nitro-drizzle/drivers\", [\"Schema\", MERGE_SCHEMA_TYPE]),\n\n script /* ts */ `type ${SCHEMA_PARTS_TYPE} = [\n ${schemaFiles\n .values()\n .map((file) => {\n return `typeof import(${genString(file)})`;\n })\n .join(\",\\n\")}\n ]`,\n\n script /* ts */ `type ${CONNECTOR_TYPE}<TSchema extends Schema> = [\n ${driverImports\n .values()\n .map((file) => {\n return genInlineTypeImport(file) + `<TSchema>`;\n })\n .join(\",\\n\")}\n ]`,\n\n script /**ts */ `type ${SCHEMA_TYPE} = \n ${genVariants({\n variants: connectors.map((connector): [schemaType: string, dimensions: Selector] => {\n return [\n genTypeName(MERGE_SCHEMA_TYPE, {\n generic: [\n SCHEMA_PARTS_TYPE,\n connector.driver.imports.schema\n .map((schemaFile) => {\n return schemaFiles.getOrAdd(schemaFile).toString();\n })\n .join(\" | \") || \"never\",\n ],\n }),\n getConnectorDimensions(connector),\n ];\n }),\n })}\n `,\n\n script /**ts */ `\n declare module ${genString(moduleId)} {\n type ConnectorVariants = ${genVariants({\n variants: connectors.map((connector): [connectorType: string, selector: Selector] => {\n const dimensions = getConnectorDimensions(connector);\n return [\n genTypeName(CONNECTOR_TYPE, {\n generic: [\n genTypeName(UNWRAP_VARIANT_TYPE, {\n generic: [SCHEMA_TYPE, genObjectFromValues(dimensions)],\n }),\n ],\n }) + `[${driverImports.getOrAdd(connector.driver.imports.connector)}]`,\n dimensions,\n ];\n }),\n })};\n }\n `,\n ].join(\"\\n\\n\");\n\n return {\n [`${moduleId}.d.ts`]: content,\n };\n}\n\n/** @deprecated */\nexport function runtimeDeclarations(_datasources: readonly DatasourceInfo[]) {\n return \"\";\n}\n\nexport function moduleTypeDeclarations(\n _datasources: readonly DatasourceInfo[],\n): VirtualModules<`${string}.d.ts`> {\n const moduleId = \"nitro-drizzle/module\";\n\n const content = [genReference({ types: moduleId })].join(\"\\n\");\n\n return {\n \"nitro-drizzle/module.d.ts\": content,\n };\n}\n\n/** @deprecated */\nexport function dialectDeclarations(_datasources: readonly DatasourceInfo[]) {\n return ``;\n}\n"],"mappings":";;;;;AAWA,SAAS,uBAAuB,EAAE,MAAM,UAAyB;CAC/D,OAAO;EACL;EACA,SAAS,OAAO;EAChB,QAAQ,OAAO;CACjB;AACF;AAEA,IAAM,kBAAN,MAAsB;CACX,SAAmB,CAAC;CAE7B,SAA4B;EAC1B,OAAO,CAAC,GAAG,KAAK,MAAM;CACxB;CAEA,SAAS,OAAuB;EAC9B,IAAI,QAAQ,KAAK,OAAO,QAAQ,KAAK;EACrC,IAAI,CAAC,CAAC,OACJ,QAAQ,KAAK,OAAO,KAAK,KAAK;EAEhC,OAAO;CACT;AACF;AAEA,SAAgB,uBACd,aACkC;CAClC,MAAM,WAAW;CACjB,MAAM,aAAa,YAAY,SAAS,EAAE,MAAM,cAAc;EAC5D,OAAO,QAAQ,KAAK,WAAW;GAC7B,OAAO;IACL;IACA;GACF;EACF,CAAC;CACH,CAAC;CAED,MAAM,oBAAoB;CAC1B,MAAM,cAAc;CACpB,MAAM,iBAAiB;CACv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AC,aAAa,oBAAoB,UAAU,CAAC,EACxD,CAAC,CACH,EACF,CAAC,IAAI,IAAI,cAAc,SAAS,UAAU,OAAO,QAAQ,SAAS,EAAE,IACpE,UACF;EACF,CAAC,EACH,CAAC,EAAE;;;CAGT,CAAC,CAAC,KAAK,MAAM;CAEb,OAAO,GACJ,GAAG,SAAS,SAAS,QACxB;AACF;;AAGA,SAAgB,oBAAoB,cAAyC;CAC3E,OAAO;AACT;AAEA,SAAgB,uBACd,cACkC;CAKlC,OAAO,EACL,6BAHc,CAAC,aAAa,EAAE,OAAO,uBAAS,CAAC,CAAC,CAAC,CAAC,KAAK,IAGpB,EACrC;AACF;;AAGA,SAAgB,oBAAoB,cAAyC;CAC3E,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { script } from "./format.mjs";
|
|
2
1
|
import { genArrayFromRaw, genExport, genImport, genObjectFromRaw, genObjectFromRawEntries, genSafeVariableName, genString } from "knitwork";
|
|
3
|
-
|
|
2
|
+
import { script } from "./format.mjs";
|
|
3
|
+
// src/context/internal/virtual.ts
|
|
4
4
|
function genConnectorModuleVariableName(dbModuleIndex) {
|
|
5
5
|
return genSafeVariableName(`dbModule${dbModuleIndex}`);
|
|
6
6
|
}
|
|
@@ -29,6 +29,8 @@ function runtimeVirtualModule(datasources, { legacyNitro, runtimeConfigProp, ini
|
|
|
29
29
|
driver
|
|
30
30
|
};
|
|
31
31
|
});
|
|
32
|
+
}).filter(({ driver }) => {
|
|
33
|
+
return driver.enabled;
|
|
32
34
|
}).map(({ name, driver }, datasourceIndex) => {
|
|
33
35
|
const connectorVarName = genConnectorModuleVariableName(datasourceIndex);
|
|
34
36
|
const imports = [genImport(driver.imports.connector, connectorVarName), ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {
|
|
@@ -136,7 +138,6 @@ function migrationsVirtualModule(datasources, options) {
|
|
|
136
138
|
`);
|
|
137
139
|
return { "#nitro-drizzle/migrations": parts.join("\n") };
|
|
138
140
|
}
|
|
139
|
-
//#endregion
|
|
140
141
|
export { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule };
|
|
141
142
|
|
|
142
143
|
//# sourceMappingURL=virtual.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\n\nfunction genConnectorModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergeSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: readonly string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport type RuntimeVirtualModuleOptions = {\n /** Whether to use the legacy Nitro API (nitropack/runtime) instead of the modern one (nitro/runtime-config). */\n legacyNitro: boolean;\n /** The property name in the runtime config where drizzle configuration is stored. */\n runtimeConfigProp: string;\n /** Hooks that are allowed to trigger the \"drizzle:init\" hook. */\n initHooks?: readonly string[];\n};\n\n/**\n * Generates the runtime virtual module code for datasource management.\n * @param datasources - The resolved datasource information\n * @param options - Runtime virtual module options\n * @returns The virtual module code string\n */\nexport function runtimeVirtualModule(\n datasources: readonly DatasourceInfo[],\n { legacyNitro, runtimeConfigProp, initHooks }: RuntimeVirtualModuleOptions,\n) {\n const datasourceRegistryParts = datasources\n .filter((datasource) => datasource.enabled)\n .flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n })\n .map(({ name, driver }, datasourceIndex) => {\n const connectorVarName = genConnectorModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(driver.imports.connector, connectorVarName),\n ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergeSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(driver.imports.schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const factoryObject = {\n name,\n driver: driver.name,\n factory: {\n create: /* js */ `(config) => ${connectorVarName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n dialect: genString(driver.dialect),\n },\n };\n\n return {\n imports,\n schemaDefinitions,\n factoryObject,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, factoryObject }) => {\n const accFactoryObject = acc.factoryObject;\n accFactoryObject[factoryObject.name] ||= {};\n accFactoryObject[factoryObject.name][factoryObject.driver] = factoryObject.factory;\n\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n factoryObject: accFactoryObject,\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n factoryObject: {} as { [name: string]: { [driver: string]: object } },\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n const nitroRuntimeParts = {\n imports: [\n legacyNitro\n ? genImport(\"nitropack/runtime\", [\"useNitroApp\"])\n : genImport(\"nitro/app\", [\"useNitroHooks\"]),\n genImport(legacyNitro ? \"nitropack/runtime\" : \"nitro/runtime-config\", [\n {\n name: \"useRuntimeConfig\",\n as: \"useNitroRuntimeConfig\",\n },\n ]),\n ],\n declarations: [\n script /* js */ `\n export function useRuntimeConfig() {\n const runtimeConfig = useNitroRuntimeConfig();\n return runtimeConfig[${genString(runtimeConfigProp)}]\n }\n\n ${\n legacyNitro\n ? script /* js */ `\n function useNitroHooks() {\n return useNitroApp().hooks;\n }\n `\n : \"\"\n }\n\n export function onServerClose(cb) {\n return useNitroHooks().hook(\"close\", cb);\n }\n\n export function callConfigHook(...args) {\n return useNitroHooks().callHook(\"drizzle:config\", ...args);\n }\n `,\n ],\n exports: [genExport(legacyNitro ? \"nitropack/runtime\" : \"nitro/storage\", [\"useStorage\"])],\n };\n\n return script /* js */ `\n ${datasourceRegistryParts.imports.join(\"\\n\")}\n ${nitroRuntimeParts.imports.join(\"\\n\")}\n \n ${datasourceRegistryParts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRaw(datasourceRegistryParts.factoryObject)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n\n ${nitroRuntimeParts.declarations.join(\"\\n\")}\n\n ${nitroRuntimeParts.exports.join(\"\\n\")}\n\n export const initHooks = ${JSON.stringify(initHooks || [])};\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n `export {};`,\n // genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, drivers }) => {\n return [\n name,\n genObjectFromRawEntries(\n drivers.map((driver) => {\n return [driver.name, JSON.stringify(driver.migrations.config)];\n }),\n ),\n ];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(script /*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;;AAaA,SAAS,+BAA+B,eAAuB;CAC7D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,2BAA2B,eAAuB;CACzD,OAAO,oBAAoB,eAAe,eAAe;AAC3D;AAEA,MAAM,+BAA+B,eAAuB,gBAC1D,oBAAoB,eAAe,cAAc,GAAG,aAAa;AAEnE,SAAS,mBAAmB,WAA8B,eAAuB;CAC/E,OAAgB;;QAEV,CACS,MACT,GAAG,UAAU,KAAK,GAAG,wBACnB,4BAA4B,eAAe,mBAAmB,CAChE,CACF,CAAC,CAAC,KAAK,GAAG,EAAE;;;AAGlB;;;;;;;AAiBA,SAAgB,qBACd,aACA,EAAE,aAAa,mBAAmB,aAClC;CACA,MAAM,0BAA0B,YAC7B,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,SAAS,EAAE,MAAM,cAAc;EAC9B,OAAO,QAAQ,KAAK,WAAW;GAC7B,OAAO;IACL;IACA;GACF;EACF,CAAC;CACH,CAAC,CAAC,CACD,KAAK,EAAE,MAAM,UAAU,oBAAoB;EAC1C,MAAM,mBAAmB,+BAA+B,eAAe;EAEvE,MAAM,UAAU,CACd,UAAU,OAAO,QAAQ,WAAW,gBAAgB,GACpD,GAAG,OAAO,QAAQ,OAAO,KAAK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+
{"version":3,"file":"virtual.mjs","names":[],"sources":["../../../src/context/internal/virtual.ts"],"sourcesContent":["import {\n genArrayFromRaw,\n genExport,\n genImport,\n genObjectFromRaw,\n genObjectFromRawEntries,\n genSafeVariableName,\n genString,\n} from \"knitwork\";\nimport type { DatasourceInfo, MigrationOptions } from \"..\";\nimport type { VirtualModules } from \"nitro-drizzle/shared\";\nimport { script } from \"./format\";\n\nfunction genConnectorModuleVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`dbModule${dbModuleIndex}`);\n}\n\nfunction genMergeSchemaVariableName(dbModuleIndex: number) {\n return genSafeVariableName(`mergedSchema${dbModuleIndex}`);\n}\n\nconst genSchemaModuleVariableName = (dbModuleIndex: number, schemaIndex: number) =>\n genSafeVariableName(`schemaModule${dbModuleIndex}_${schemaIndex}`);\n\nfunction mergeSchemaModules(schemaIds: readonly string[], dbModuleIndex: number) {\n return /* js */ `\n Object.assign(\n ${[\n /* js */ `{}`,\n ...schemaIds.map((_, schemaModuleIdIndex) =>\n genSchemaModuleVariableName(dbModuleIndex, schemaModuleIdIndex),\n ),\n ].join(\",\")}\n )\n `;\n}\n\nexport type RuntimeVirtualModuleOptions = {\n /** Whether to use the legacy Nitro API (nitropack/runtime) instead of the modern one (nitro/runtime-config). */\n legacyNitro: boolean;\n /** The property name in the runtime config where drizzle configuration is stored. */\n runtimeConfigProp: string;\n /** Hooks that are allowed to trigger the \"drizzle:init\" hook. */\n initHooks?: readonly string[];\n};\n\n/**\n * Generates the runtime virtual module code for datasource management.\n * @param datasources - The resolved datasource information\n * @param options - Runtime virtual module options\n * @returns The virtual module code string\n */\nexport function runtimeVirtualModule(\n datasources: readonly DatasourceInfo[],\n { legacyNitro, runtimeConfigProp, initHooks }: RuntimeVirtualModuleOptions,\n) {\n const datasourceRegistryParts = datasources\n .filter((datasource) => datasource.enabled)\n .flatMap(({ name, drivers }) => {\n return drivers.map((driver) => {\n return {\n name,\n driver,\n };\n });\n })\n .filter(({ driver }) => {\n return driver.enabled;\n })\n .map(({ name, driver }, datasourceIndex) => {\n const connectorVarName = genConnectorModuleVariableName(datasourceIndex);\n\n const imports = [\n genImport(driver.imports.connector, connectorVarName),\n ...driver.imports.schema.map((schemaModuleId, schemaIndex) => {\n return genImport(schemaModuleId, {\n name: \"*\",\n as: genSchemaModuleVariableName(datasourceIndex, schemaIndex),\n });\n }),\n ];\n\n const mergedSchemaVariableName = genMergeSchemaVariableName(datasourceIndex);\n const mergedSchemaObject = mergeSchemaModules(driver.imports.schema, datasourceIndex);\n\n const schemaDefinitions = [\n /* js */ `const ${mergedSchemaVariableName} = ${mergedSchemaObject};`,\n ];\n\n const factoryObject = {\n name,\n driver: driver.name,\n factory: {\n create: /* js */ `(config) => ${connectorVarName}(config, ${mergedSchemaVariableName})`,\n schema: mergedSchemaVariableName,\n dialect: genString(driver.dialect),\n },\n };\n\n return {\n imports,\n schemaDefinitions,\n factoryObject,\n };\n })\n .reduce(\n (acc, { imports, schemaDefinitions, factoryObject }) => {\n const accFactoryObject = acc.factoryObject;\n accFactoryObject[factoryObject.name] ||= {};\n accFactoryObject[factoryObject.name][factoryObject.driver] = factoryObject.factory;\n\n return {\n imports: [...acc.imports, ...imports],\n schemaDefinitions: [...acc.schemaDefinitions, ...schemaDefinitions],\n factoryObject: accFactoryObject,\n };\n },\n {\n imports: [] as string[],\n schemaDefinitions: [] as string[],\n factoryObject: {} as { [name: string]: { [driver: string]: object } },\n },\n );\n\n const datasourceRegistryVarName = genSafeVariableName(\"datasourceRegistry\");\n\n const nitroRuntimeParts = {\n imports: [\n legacyNitro\n ? genImport(\"nitropack/runtime\", [\"useNitroApp\"])\n : genImport(\"nitro/app\", [\"useNitroHooks\"]),\n genImport(legacyNitro ? \"nitropack/runtime\" : \"nitro/runtime-config\", [\n {\n name: \"useRuntimeConfig\",\n as: \"useNitroRuntimeConfig\",\n },\n ]),\n ],\n declarations: [\n script /* js */ `\n export function useRuntimeConfig() {\n const runtimeConfig = useNitroRuntimeConfig();\n return runtimeConfig[${genString(runtimeConfigProp)}]\n }\n\n ${\n legacyNitro\n ? script /* js */ `\n function useNitroHooks() {\n return useNitroApp().hooks;\n }\n `\n : \"\"\n }\n\n export function onServerClose(cb) {\n return useNitroHooks().hook(\"close\", cb);\n }\n\n export function callConfigHook(...args) {\n return useNitroHooks().callHook(\"drizzle:config\", ...args);\n }\n `,\n ],\n exports: [genExport(legacyNitro ? \"nitropack/runtime\" : \"nitro/storage\", [\"useStorage\"])],\n };\n\n return script /* js */ `\n ${datasourceRegistryParts.imports.join(\"\\n\")}\n ${nitroRuntimeParts.imports.join(\"\\n\")}\n \n ${datasourceRegistryParts.schemaDefinitions.join(\"\\n\")}\n \n const ${datasourceRegistryVarName} = ${genObjectFromRaw(datasourceRegistryParts.factoryObject)};\n\n export function useDatasourceRegistry() {\n return ${datasourceRegistryVarName};\n }\n\n ${nitroRuntimeParts.declarations.join(\"\\n\")}\n\n ${nitroRuntimeParts.exports.join(\"\\n\")}\n\n export const initHooks = ${JSON.stringify(initHooks || [])};\n `;\n}\n\n// Replaced with aliases\nexport function dialectVirtualModules(\n datasources: readonly DatasourceInfo[],\n): VirtualModules<`#nitro-drizzle/${string}`> {\n return Object.fromEntries(\n datasources\n .filter((d) => d.enabled)\n .map(({ name }) => {\n return [\n `#nitro-drizzle/dialects/${name}`,\n `export {};`,\n // genExport(`nitro-drizzle/dialects/${dialect}`, \"*\"),\n ] as const;\n }),\n );\n}\n\nexport function migrationsVirtualModule(\n datasources: readonly DatasourceInfo[],\n options: MigrationOptions | undefined,\n): VirtualModules<`#nitro-drizzle/${string}`> {\n if (!options) {\n return {};\n }\n\n const parts: string[] = [];\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n parts.push(/*js*/ `\n export const migrationConfig = ${genObjectFromRawEntries(\n enabledDatasources.map(({ name, drivers }) => {\n return [\n name,\n genObjectFromRawEntries(\n drivers.map((driver) => {\n return [driver.name, JSON.stringify(driver.migrations.config)];\n }),\n ),\n ];\n }),\n )};\n `);\n\n let migrateOnInit = enabledDatasources.map((d) => d.name);\n if (options && Array.isArray(options.migrateOnInit)) {\n migrateOnInit = migrateOnInit.filter((name) =>\n (options.migrateOnInit as readonly string[]).includes(name),\n );\n }\n\n parts.push(script /*js*/ `\n export const MIGRATIONS_STORAGE_BASE = ${genString(options.storageBase)};\n export const MIGRATE_ON_INIT = ${genArrayFromRaw(migrateOnInit.map((name) => genString(name)))};\n `);\n\n return {\n \"#nitro-drizzle/migrations\": parts.join(\"\\n\"),\n };\n}\n"],"mappings":";;;AAaA,SAAS,+BAA+B,eAAuB;CAC7D,OAAO,oBAAoB,WAAW,eAAe;AACvD;AAEA,SAAS,2BAA2B,eAAuB;CACzD,OAAO,oBAAoB,eAAe,eAAe;AAC3D;AAEA,MAAM,+BAA+B,eAAuB,gBAC1D,oBAAoB,eAAe,cAAc,GAAG,aAAa;AAEnE,SAAS,mBAAmB,WAA8B,eAAuB;CAC/E,OAAgB;;QAEV,CACS,MACT,GAAG,UAAU,KAAK,GAAG,wBACnB,4BAA4B,eAAe,mBAAmB,CAChE,CACF,CAAC,CAAC,KAAK,GAAG,EAAE;;;AAGlB;;;;;;;AAiBA,SAAgB,qBACd,aACA,EAAE,aAAa,mBAAmB,aAClC;CACA,MAAM,0BAA0B,YAC7B,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,SAAS,EAAE,MAAM,cAAc;EAC9B,OAAO,QAAQ,KAAK,WAAW;GAC7B,OAAO;IACL;IACA;GACF;EACF,CAAC;CACH,CAAC,CAAC,CACD,QAAQ,EAAE,aAAa;EACtB,OAAO,OAAO;CAChB,CAAC,CAAC,CACD,KAAK,EAAE,MAAM,UAAU,oBAAoB;EAC1C,MAAM,mBAAmB,+BAA+B,eAAe;EAEvE,MAAM,UAAU,CACd,UAAU,OAAO,QAAQ,WAAW,gBAAgB,GACpD,GAAG,OAAO,QAAQ,OAAO,KAAK,gBAAgB,gBAAgB;GAC5D,OAAO,UAAU,gBAAgB;IAC/B,MAAM;IACN,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from "consola";
|
|
2
|
-
import { MaybePromise, NitroHookName, VirtualModules } from "nitro-drizzle/shared";
|
|
3
2
|
import { Config } from "drizzle-kit";
|
|
3
|
+
import { MaybePromise, NitroHookName, VirtualModules } from "nitro-drizzle/shared";
|
|
4
4
|
import { ServerAssetDir } from "nitropack/types";
|
|
5
5
|
import { ServerAssetDir as ServerAssetDir$1 } from "nitro/types";
|
|
6
|
-
//#region src/context/index.d.ts
|
|
7
6
|
/**
|
|
8
7
|
* Context interface for managing Drizzle datasource configurations.
|
|
9
8
|
*/
|
|
10
|
-
interface Context {
|
|
9
|
+
export interface Context {
|
|
11
10
|
init(): MaybePromise<void>;
|
|
12
11
|
/**
|
|
13
12
|
* Reloads the context, clearing any cached datasource information.
|
|
@@ -21,24 +20,24 @@ interface Context {
|
|
|
21
20
|
/**
|
|
22
21
|
* Glob pattern or array of patterns to match Drizzle configuration files.
|
|
23
22
|
*/
|
|
24
|
-
type ConfigPattern = string | readonly string[];
|
|
23
|
+
export type ConfigPattern = string | readonly string[];
|
|
25
24
|
/**
|
|
26
25
|
* Resolver interface for importing modules and resolving paths.
|
|
27
26
|
*/
|
|
28
|
-
interface Resolver {
|
|
27
|
+
export interface Resolver {
|
|
29
28
|
/**
|
|
30
29
|
* Resolves a module ID to its full path.
|
|
31
30
|
*/
|
|
32
31
|
resolve(id: string): string;
|
|
33
32
|
}
|
|
34
|
-
type ContextHook<TArgs extends readonly any[] = []> = (this: void, ...args: TArgs) => MaybePromise<void>;
|
|
35
|
-
interface MigrationOptions {
|
|
33
|
+
export type ContextHook<TArgs extends readonly any[] = []> = (this: void, ...args: TArgs) => MaybePromise<void>;
|
|
34
|
+
export interface MigrationOptions {
|
|
36
35
|
/** Base storage key path for migrations. */
|
|
37
36
|
storageBase: string;
|
|
38
37
|
/** Whether and which datasources to migrate on initialization. */
|
|
39
38
|
migrateOnInit: boolean | readonly string[];
|
|
40
39
|
}
|
|
41
|
-
interface ContextOptions {
|
|
40
|
+
export interface ContextOptions {
|
|
42
41
|
legacy: boolean;
|
|
43
42
|
logger?: ConsolaInstance;
|
|
44
43
|
/**
|
|
@@ -75,7 +74,7 @@ interface ContextOptions {
|
|
|
75
74
|
description: string;
|
|
76
75
|
}>]>;
|
|
77
76
|
plugins: ContextHook<[plugins: readonly string[]]>;
|
|
78
|
-
|
|
77
|
+
types: ContextHook<[declarations: {
|
|
79
78
|
shared: VirtualModules<`${string}.d.ts`>;
|
|
80
79
|
module: VirtualModules<`${string}.d.ts`>;
|
|
81
80
|
runtime: VirtualModules<`${string}.d.ts`>;
|
|
@@ -90,11 +89,11 @@ interface ContextOptions {
|
|
|
90
89
|
* @param options - Configuration options for the context
|
|
91
90
|
* @returns A Context instance
|
|
92
91
|
*/
|
|
93
|
-
declare function createContext(options: ContextOptions): Context;
|
|
92
|
+
export declare function createContext(options: ContextOptions): Context;
|
|
94
93
|
/**
|
|
95
94
|
* Information about a resolved Drizzle datasource.
|
|
96
95
|
*/
|
|
97
|
-
interface DatasourceInfo {
|
|
96
|
+
export interface DatasourceInfo {
|
|
98
97
|
/** Unique name identifier for the datasource. */
|
|
99
98
|
name: string;
|
|
100
99
|
/** Whether the datasource is enabled (filtered by connector configuration). */
|
|
@@ -103,7 +102,8 @@ interface DatasourceInfo {
|
|
|
103
102
|
drivers: readonly DriverOptions[];
|
|
104
103
|
}
|
|
105
104
|
/** Options for a specific driver within a datasource. */
|
|
106
|
-
type DriverOptions = {
|
|
105
|
+
export type DriverOptions = {
|
|
106
|
+
enabled: boolean;
|
|
107
107
|
name: string;
|
|
108
108
|
dialect: string;
|
|
109
109
|
imports: {
|
|
@@ -116,7 +116,4 @@ type DriverOptions = {
|
|
|
116
116
|
assets?: string;
|
|
117
117
|
config?: Config["migrations"];
|
|
118
118
|
};
|
|
119
|
-
};
|
|
120
|
-
//#endregion
|
|
121
|
-
export { ConfigPattern, Context, ContextHook, ContextOptions, DatasourceInfo, DriverOptions, MigrationOptions, Resolver, createContext };
|
|
122
|
-
//# sourceMappingURL=context.d.mts.map
|
|
119
|
+
};
|
package/dist/context.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
+
import { colorize } from "consola/utils";
|
|
2
|
+
import { loadConfig } from "c12";
|
|
3
|
+
import { pkgDir, pkgName } from "nitro-drizzle/meta";
|
|
1
4
|
import { mapAsync } from "./context/internal/async.mjs";
|
|
2
5
|
import { accent } from "./context/internal/logger.mjs";
|
|
3
6
|
import { resolveFiles } from "./context/internal/fs.mjs";
|
|
4
|
-
import { genReference } from "./context/internal/codegen.mjs";
|
|
5
7
|
import { dialectDeclarations, moduleTypeDeclarations, runtimeDeclarations, sharedTypeDeclarations } from "./context/internal/templates.mjs";
|
|
6
8
|
import { transformDrizzleConfig } from "./context/internal/config.mjs";
|
|
7
9
|
import { dialectVirtualModules, migrationsVirtualModule, runtimeVirtualModule } from "./context/internal/virtual.mjs";
|
|
8
10
|
import { join } from "pathe";
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
import { loadConfig } from "c12";
|
|
12
|
-
//#region src/context/index.ts
|
|
11
|
+
import { genReference } from "./context/internal/codegen.mjs";
|
|
12
|
+
// src/context/index.ts
|
|
13
13
|
var DefaultContext = class {
|
|
14
14
|
#datasources = null;
|
|
15
15
|
#options;
|
|
@@ -27,7 +27,7 @@ var DefaultContext = class {
|
|
|
27
27
|
this.runtimeTypeDeclarations(datasources)
|
|
28
28
|
]);
|
|
29
29
|
await this.#options.virtualModules(virtualModules);
|
|
30
|
-
await this.#options.
|
|
30
|
+
await this.#options.types({
|
|
31
31
|
shared: sharedTypes,
|
|
32
32
|
module: moduleTypes,
|
|
33
33
|
runtime: runtimeTypes,
|
|
@@ -71,15 +71,30 @@ var DefaultContext = class {
|
|
|
71
71
|
return 1;
|
|
72
72
|
});
|
|
73
73
|
const datasources = Object.entries(datasourceOptions).map(([name, options]) => {
|
|
74
|
+
const connectorOptions = Array.isArray(options.drivers) ? options.drivers.reduce((acc, driver) => {
|
|
75
|
+
const match = driver.match(/^([_-]*)([^_]+)/);
|
|
76
|
+
if (!match) throw new Error("Invalid driver name format");
|
|
77
|
+
const [_, disabled, driverName] = match;
|
|
78
|
+
return {
|
|
79
|
+
...acc,
|
|
80
|
+
[driverName]: { enabled: !disabled }
|
|
81
|
+
};
|
|
82
|
+
}, {}) : Object.entries(options.drivers).reduce((acc, [name, enabled]) => {
|
|
83
|
+
return {
|
|
84
|
+
...acc,
|
|
85
|
+
[name]: { enabled }
|
|
86
|
+
};
|
|
87
|
+
}, {});
|
|
74
88
|
return {
|
|
75
89
|
name,
|
|
76
90
|
enabled: true,
|
|
77
|
-
drivers:
|
|
91
|
+
drivers: Object.entries(connectorOptions).map(([driverName, options]) => {
|
|
78
92
|
const dialect = driverToDialect(driverName);
|
|
79
93
|
const drizzleConfig = drizzleConfigs.find((config) => {
|
|
80
94
|
return config.name == name && config.dialect == dialect;
|
|
81
95
|
});
|
|
82
96
|
return {
|
|
97
|
+
enabled: options.enabled,
|
|
83
98
|
name: driverName,
|
|
84
99
|
dialect,
|
|
85
100
|
imports: {
|
|
@@ -89,7 +104,7 @@ var DefaultContext = class {
|
|
|
89
104
|
},
|
|
90
105
|
migrations: { ...drizzleConfig?.migrations }
|
|
91
106
|
};
|
|
92
|
-
})
|
|
107
|
+
}).sort((a, b) => (b.enabled ? 1 : 0) - (a.enabled ? 1 : 0))
|
|
93
108
|
};
|
|
94
109
|
});
|
|
95
110
|
logger?.info("Found drizzle datasources:", datasources.toSorted((datasource) => {
|
|
@@ -97,7 +112,7 @@ var DefaultContext = class {
|
|
|
97
112
|
}).map((datasource) => {
|
|
98
113
|
let msg = [datasource.name];
|
|
99
114
|
let color;
|
|
100
|
-
if (datasource.enabled) color = "
|
|
115
|
+
if (datasource.enabled) color = "yellow";
|
|
101
116
|
else {
|
|
102
117
|
color = "gray";
|
|
103
118
|
msg.push("(disabled)");
|
|
@@ -106,8 +121,15 @@ var DefaultContext = class {
|
|
|
106
121
|
}).join(", "));
|
|
107
122
|
const enabledDatasources = datasources.filter((d) => d.enabled);
|
|
108
123
|
logger?.info(accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` + (enabledDatasources.length > 0 ? ":" : ""), enabledDatasources.map((datasource) => {
|
|
109
|
-
return [
|
|
110
|
-
|
|
124
|
+
return [
|
|
125
|
+
"\n ",
|
|
126
|
+
colorize("yellow", datasource.name),
|
|
127
|
+
"(" + datasource.drivers.map((driver) => {
|
|
128
|
+
const [color, postfix] = driver.enabled ? ["greenBright", ""] : ["strikethrough", " (types only)"];
|
|
129
|
+
return colorize("gray", [colorize(color, driver.name), postfix].join(""));
|
|
130
|
+
}).join(", ") + ")"
|
|
131
|
+
].join(" ");
|
|
132
|
+
}).join(""));
|
|
111
133
|
this.#datasources = datasources;
|
|
112
134
|
}
|
|
113
135
|
return this.#datasources;
|
|
@@ -146,7 +168,7 @@ var DefaultContext = class {
|
|
|
146
168
|
if (migrationOptions ? Array.isArray(migrationOptions) ? 0 < migrationOptions.length : true == migrationOptions.migrateOnInit : false) plugins.push("migrate");
|
|
147
169
|
plugins.push("init");
|
|
148
170
|
let pluginIds = plugins;
|
|
149
|
-
if (this.#options.legacy) pluginIds = pluginIds.map((pluginName) =>
|
|
171
|
+
if (this.#options.legacy) pluginIds = pluginIds.map((pluginName) => `${pluginName}/legacy`);
|
|
150
172
|
pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);
|
|
151
173
|
return pluginIds;
|
|
152
174
|
}
|
|
@@ -193,7 +215,6 @@ function driverToDialect(driver) {
|
|
|
193
215
|
function createContext(options) {
|
|
194
216
|
return new DefaultContext(options);
|
|
195
217
|
}
|
|
196
|
-
//#endregion
|
|
197
218
|
export { createContext };
|
|
198
219
|
|
|
199
220
|
//# sourceMappingURL=context.mjs.map
|
package/dist/context.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.mjs","names":["#options","#datasources"],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n moduleTypeDeclarations,\n runtimeDeclarations,\n sharedTypeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, NitroHookName, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir as LegacyServerAssetDir } from \"nitropack/types\";\nimport type { ServerAssetDir } from \"nitro/types\";\nimport { join } from \"pathe\";\nimport { genReference } from \"./internal/codegen\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [sharedTypes, virtualModules, virtualTypes, moduleTypes, runtimeTypes] =\n await Promise.all([\n sharedTypeDeclarations(datasources),\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.declarations({\n shared: sharedTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n virtual: virtualTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.externals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.externals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasources: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n const drizzleConfigs = [\n ...(await mapAsync(drizzleConfigsResolvedPaths, async (path) => {\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n })),\n ].sort((a, b) => {\n if (a.driver && b.driver) {\n return 0;\n }\n return 1;\n });\n\n const datasources: DatasourceInfo[] = Object.entries(datasourceOptions).map(\n ([name, options]) => {\n const drivers: readonly string[] = Array.isArray(options.drivers)\n ? options.drivers\n : Object.entries(options.drivers as { [name: string]: boolean })\n .filter(([_name, enabled]) => enabled)\n .map(([name]) => name);\n return {\n name,\n enabled: true,\n drivers: drivers.map((driverName) => {\n const dialect = driverToDialect(driverName);\n const drizzleConfig = drizzleConfigs.find((config) => {\n return config.name == name && config.dialect == dialect;\n });\n return {\n name: driverName,\n dialect,\n imports: {\n connector: `nitro-drizzle/drivers/${driverName}`,\n helpers: `nitro-drizzle/dialects/${dialect}`,\n schema: drizzleConfig?.imports.schema || [],\n },\n migrations: {\n ...drizzleConfig?.migrations,\n },\n };\n }),\n } satisfies DatasourceInfo;\n },\n );\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"greenBright\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n colorize(\"greenBright\", datasource.name),\n colorize(\n \"yellow\",\n \"(\" + datasource.drivers.map((driver) => driver.name).join(\", \") + \")\",\n ),\n ].join(\" \");\n })\n .join(\", \"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly (ServerAssetDir | LegacyServerAssetDir)[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources\n .flatMap((datasource) => {\n return datasource.drivers.map((driver) => {\n return {\n name: datasource.name,\n driver: driver.name,\n dialect: driver.dialect,\n migrations: driver.migrations,\n };\n });\n })\n .reduce(\n (acc, { name, driver, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: [migrationOptions.storageBase, name, driver].join(\":\"),\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n },\n [] as (ServerAssetDir | LegacyServerAssetDir)[],\n );\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n let pluginIds: readonly string[] = plugins;\n if (this.#options.legacy) {\n pluginIds = pluginIds.map((pluginName) => `legacy/${pluginName}`);\n }\n pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n if (!this.#options.legacy) {\n references.add({ types: \"nitro-drizzle/middleware/context\" });\n }\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources, {\n legacyNitro: this.#options.legacy,\n runtimeConfigProp: \"drizzle\",\n initHooks: this.#options.initHooks,\n }),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\nfunction driverToDialect(driver: string) {\n let dialect = driver;\n if (driver.startsWith(\"d1\")) {\n dialect = \"sqlite\";\n }\n if (driver == \"pglite\") {\n dialect = \"postgresql\";\n }\n return dialect;\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n legacy: boolean;\n\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasources: Record<string, { drivers: readonly string[] | { [name: string]: boolean } }>;\n\n migrations: MigrationOptions | undefined;\n\n /**\n * Hooks that allowed to call \"drizzle:init\" hook.\n */\n initHooks?: readonly NitroHookName[];\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n declarations: ContextHook<\n [\n declarations: {\n shared: VirtualModules<`${string}.d.ts`>;\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly (ServerAssetDir | LegacyServerAssetDir)[]]>;\n\n externals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Driver configurations for this datasource. */\n drivers: readonly DriverOptions[];\n}\n\n/** Options for a specific driver within a datasource. */\nexport type DriverOptions = {\n name: string;\n dialect: string;\n imports: {\n // config: string;\n schema: readonly string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource driver. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n};\n"],"mappings":";;;;;;;;;;;;AA2CA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CACxC;CAEA,YAAY,SAAyB;EACnC,KAAKA,WAAW;CAClB;CAEA,MAAM,OAAsB;EAC1B,MAAM,cAAc,MAAM,KAAK,YAAY;EAE3C,MAAM,KAAKA,SAAS,QAAQ,KAAK,eAAe,CAAC;EAEjD,MAAM,CAAC,aAAa,gBAAgB,cAAc,aAAa,gBAC7D,MAAM,QAAQ,IAAI;GAChB,uBAAuB,WAAW;GAClC,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACxC,KAAK,uBAAuB,WAAW;GACvC,KAAK,wBAAwB,WAAW;EAC1C,CAAC;EAEH,MAAM,KAAKA,SAAS,eAAe,cAAc;EAEjD,MAAM,KAAKA,SAAS,aAAa;GAC/B,QAAQ;GACR,QAAQ;GACR,SAAS;GACT,SAAS;EACX,CAAC;EAED,IAAI,KAAKA,SAAS,YAAY;GAC5B,MAAM,SAAS,MAAM,KAAK,gBAAgB,WAAW;GACrD,IAAI,QACF,MAAM,KAAKA,SAAS,OAAO,MAAM;GAGnC,MAAM,KAAKA,SAAS,QAAQ,EAC1B,mBAAmB;IACjB,aAAa;IACb,SAAS;GACX,EACF,CAAC;EACH;EAEA,IAAI,KAAKA,SAAS,WAAW;GAC3B,M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AAC,CAAC,KAAK,IAE+B,EACtC;CACF;CAEA,MAAc,eACZ,aACqD;EACrD,OAAO;GACL,0BAA0B,qBAAqB,aAAa;IAC1D,aAAa,KAAKA,SAAS;IAC3B,mBAAmB;IACnB,WAAW,KAAKA,SAAS;GAC3B,CAAC;GACD,GAAG,sBAAsB,WAAW;GACpC,GAAG,wBAAwB,aAAa,KAAKA,SAAS,UAAU;EAClE;CACF;CAEA,SAAS;EACP,KAAKC,eAAe;CACtB;AACF;AAEA,SAAS,gBAAgB,QAAgB;CACvC,IAAI,UAAU;CACd,IAAI,OAAO,WAAW,IAAI,GACxB,UAAU;CAEZ,IAAI,UAAU,UACZ,UAAU;CAEZ,OAAO;AACT;;;;;;AAkGA,SAAgB,cAAc,SAAkC;CAC9D,OAAO,IAAI,eAAe,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"context.mjs","names":[],"sources":["../src/context/index.ts"],"sourcesContent":["import type { ConsolaInstance } from \"consola\";\nimport { colorize, type ColorName } from \"consola/utils\";\nimport type { Config, Config as DrizzleConfig } from \"drizzle-kit\";\nimport { loadConfig } from \"c12\";\nimport { pkgDir, pkgName } from \"nitro-drizzle/meta\";\n\nimport { mapAsync } from \"./internal/async\";\nimport { accent } from \"./internal/logger\";\nimport { resolveFiles } from \"./internal/fs\";\nimport {\n dialectDeclarations,\n moduleTypeDeclarations,\n runtimeDeclarations,\n sharedTypeDeclarations,\n} from \"./internal/templates\";\nimport { transformDrizzleConfig } from \"./internal/config\";\nimport {\n dialectVirtualModules,\n migrationsVirtualModule,\n runtimeVirtualModule,\n} from \"./internal/virtual\";\n\nimport type { MaybePromise, NitroHookName, VirtualModules } from \"nitro-drizzle/shared\";\nimport type { ServerAssetDir as LegacyServerAssetDir } from \"nitropack/types\";\nimport type { ServerAssetDir } from \"nitro/types\";\nimport { join } from \"pathe\";\nimport { genReference } from \"./internal/codegen\";\n\n/**\n * Context interface for managing Drizzle datasource configurations.\n */\nexport interface Context {\n init(): MaybePromise<void>;\n /**\n * Reloads the context, clearing any cached datasource information.\n */\n reload(): MaybePromise<void>;\n /**\n * Returns a list of all resolved datasource information.\n */\n datasources(): MaybePromise<DatasourceInfo[]>;\n}\n\nclass DefaultContext implements Context {\n #datasources: DatasourceInfo[] | null = null;\n readonly #options: ContextOptions;\n\n constructor(options: ContextOptions) {\n this.#options = options;\n }\n\n async init(): Promise<void> {\n const datasources = await this.datasources();\n\n await this.#options.plugins(this.enabledPlugins());\n\n const [sharedTypes, virtualModules, virtualTypes, moduleTypes, runtimeTypes] =\n await Promise.all([\n sharedTypeDeclarations(datasources),\n this.virtualModules(datasources),\n this.virtualTypeDeclarations(datasources),\n this.moduleTypeDeclarations(datasources),\n this.runtimeTypeDeclarations(datasources),\n ]);\n\n await this.#options.virtualModules(virtualModules);\n\n await this.#options.types({\n shared: sharedTypes,\n module: moduleTypes,\n runtime: runtimeTypes,\n virtual: virtualTypes,\n });\n\n if (this.#options.migrations) {\n const assets = await this.migrationAssets(datasources);\n if (assets) {\n await this.#options.assets(assets);\n }\n\n await this.#options.tasks?.({\n \"drizzle:migrate\": {\n description: \"Run drizzle migrations for a datasource.\",\n handler: \"nitro-drizzle/migrations/task\",\n },\n });\n }\n\n if (this.#options.externals) {\n const inlineModuleIds = [\"runtime\", \"plugins\", \"migrations\"].flatMap((id) => {\n return [join(pkgName, id), join(pkgDir, \"dist\", id)];\n });\n\n await this.#options.externals(inlineModuleIds);\n }\n }\n\n async datasources() {\n const {\n logger,\n baseDir,\n configPattern,\n resolver,\n datasources: datasourceOptions,\n } = this.#options;\n\n if (!this.#datasources) {\n logger?.info(\"Searching drizzle datasources in\", colorize(\"blue\", baseDir));\n\n const drizzleConfigsResolvedPaths = await resolveFiles(\n baseDir,\n [configPattern].flat().map((pattern) => \"*/\" + pattern),\n );\n\n const drizzleConfigs = [\n ...(await mapAsync(drizzleConfigsResolvedPaths, async (path) => {\n const [_, dirName] = path.match(/(.+\\/(.+))\\/.+$/)!.slice(1, 3) as [string, string];\n const { config } = await loadConfig<DrizzleConfig>({\n configFile: path,\n });\n\n return await transformDrizzleConfig(config, {\n cwd: this.#options.cwd,\n path,\n dirName,\n resolver,\n });\n })),\n ].sort((a, b) => {\n if (a.driver && b.driver) {\n return 0;\n }\n return 1;\n });\n\n const datasources: DatasourceInfo[] = Object.entries(datasourceOptions).map(\n ([name, options]) => {\n const connectorOptions = Array.isArray(options.drivers)\n ? (options.drivers as string[]).reduce(\n (acc, driver) => {\n const match = driver.match(/^([_-]*)([^_]+)/);\n if (!match) throw new Error(\"Invalid driver name format\");\n const [_, disabled, driverName] = match;\n return {\n ...acc,\n [driverName]: { enabled: !disabled },\n };\n },\n {} as { [driver: string]: { enabled: boolean } },\n )\n : Object.entries(options.drivers as { [name: string]: boolean }).reduce(\n (acc, [name, enabled]) => {\n return {\n ...acc,\n [name]: { enabled },\n };\n },\n {} as { [driver: string]: { enabled: boolean } },\n );\n\n return {\n name,\n enabled: true,\n drivers: Object.entries(connectorOptions)\n .map(([driverName, options]) => {\n const dialect = driverToDialect(driverName);\n const drizzleConfig = drizzleConfigs.find((config) => {\n return config.name == name && config.dialect == dialect;\n });\n return {\n enabled: options.enabled,\n name: driverName,\n dialect,\n imports: {\n connector: `nitro-drizzle/drivers/${driverName}`,\n helpers: `nitro-drizzle/dialects/${dialect}`,\n schema: drizzleConfig?.imports.schema || [],\n },\n migrations: {\n ...drizzleConfig?.migrations,\n },\n };\n })\n .sort((a, b) => (b.enabled ? 1 : 0) - (a.enabled ? 1 : 0)),\n } satisfies DatasourceInfo;\n },\n );\n\n logger?.info(\n \"Found drizzle datasources:\",\n datasources\n .toSorted((datasource) => {\n return datasource.enabled ? -1 : 1;\n })\n .map((datasource) => {\n let msg = [datasource.name];\n let color: ColorName;\n if (datasource.enabled) {\n color = \"yellow\";\n } else {\n color = \"gray\";\n msg.push(\"(disabled)\");\n }\n return colorize(color, msg.join(\" \"));\n })\n .join(\", \"),\n );\n\n const enabledDatasources = datasources.filter((d) => d.enabled);\n\n logger?.info(\n accent`Using ${enabledDatasources.length} of ${datasources.length} resolved datasources` +\n (enabledDatasources.length > 0 ? \":\" : \"\"),\n enabledDatasources\n .map((datasource) => {\n return [\n \"\\n\\t\",\n colorize(\"yellow\", datasource.name),\n \"(\" +\n datasource.drivers\n .map((driver) => {\n const [color, postfix] = driver.enabled\n ? ([\"greenBright\", \"\"] as const)\n : ([\"strikethrough\", \" (types only)\"] as const);\n\n return colorize(\"gray\", [colorize(color, driver.name), postfix].join(\"\"));\n })\n .join(\", \") +\n \")\",\n ].join(\" \");\n })\n .join(\"\"),\n );\n\n this.#datasources = datasources;\n }\n\n return this.#datasources;\n }\n\n private async migrationAssets(\n datasources: readonly DatasourceInfo[],\n ): Promise<readonly (ServerAssetDir | LegacyServerAssetDir)[]> {\n const migrationOptions = this.#options.migrations;\n\n if (!migrationOptions) {\n return [];\n }\n\n return datasources\n .flatMap((datasource) => {\n return datasource.drivers.map((driver) => {\n return {\n name: datasource.name,\n driver: driver.name,\n dialect: driver.dialect,\n migrations: driver.migrations,\n };\n });\n })\n .reduce(\n (acc, { name, driver, migrations }) => {\n const dir = migrations.assets;\n if (dir) {\n acc.push({\n baseName: [migrationOptions.storageBase, name, driver].join(\":\"),\n dir,\n /**\n * @todo Doesn't work in dev mode - 'fs' driver does not support 'pattern'\n * Disabled - include all files to use with meta/_journal.json\n */\n // pattern: '*.sql',\n });\n }\n return acc;\n },\n [] as (ServerAssetDir | LegacyServerAssetDir)[],\n );\n }\n\n private async virtualTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<Record<string, VirtualModules<`${string}.d.ts`>>> {\n return {\n \"#nitro-drizzle/*\": {\n \"nitro-drizzle/virtual.d.ts\": [dialectDeclarations(datasources)].join(\"\\n\"),\n },\n };\n }\n\n private enabledPlugins(): readonly string[] {\n const plugins: (\"init\" | \"migrate\")[] = [];\n\n const migrationOptions = this.#options.migrations;\n const enableMigrationPlugin = migrationOptions\n ? Array.isArray(migrationOptions)\n ? 0 < migrationOptions.length\n : true == migrationOptions.migrateOnInit\n : false;\n\n if (enableMigrationPlugin) {\n plugins.push(\"migrate\");\n }\n\n plugins.push(\"init\");\n\n let pluginIds: readonly string[] = plugins;\n if (this.#options.legacy) {\n pluginIds = pluginIds.map((pluginName) => `${pluginName}/legacy`);\n }\n pluginIds = pluginIds.map((pluginName) => `nitro-drizzle/plugins/${pluginName}`);\n\n return pluginIds;\n }\n\n private async moduleTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules> {\n return moduleTypeDeclarations(datasources);\n }\n\n private async runtimeTypeDeclarations(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`${string}.d.ts`>> {\n const references = new Set([\n { types: \"nitro-drizzle/runtime\" },\n ...this.enabledPlugins().map((pluginId) => {\n return { types: pluginId };\n }),\n ]);\n if (!this.#options.legacy) {\n references.add({ types: \"nitro-drizzle/middleware/context\" });\n }\n const content = [\n ...[...references.values()].map((reference) => genReference(reference)),\n runtimeDeclarations(datasources),\n /* ts */ `export {};`,\n ].join(\"\\n\");\n return {\n \"nitro-drizzle/runtime.d.ts\": content,\n };\n }\n\n private async virtualModules(\n datasources: readonly DatasourceInfo[],\n ): Promise<VirtualModules<`#nitro-drizzle/${string}`>> {\n return {\n \"#nitro-drizzle/runtime\": runtimeVirtualModule(datasources, {\n legacyNitro: this.#options.legacy,\n runtimeConfigProp: \"drizzle\",\n initHooks: this.#options.initHooks,\n }),\n ...dialectVirtualModules(datasources),\n ...migrationsVirtualModule(datasources, this.#options.migrations),\n };\n }\n\n reload() {\n this.#datasources = null;\n }\n}\n\nfunction driverToDialect(driver: string) {\n let dialect = driver;\n if (driver.startsWith(\"d1\")) {\n dialect = \"sqlite\";\n }\n if (driver == \"pglite\") {\n dialect = \"postgresql\";\n }\n return dialect;\n}\n\n/**\n * Glob pattern or array of patterns to match Drizzle configuration files.\n */\nexport type ConfigPattern = string | readonly string[];\n\n/**\n * Resolver interface for importing modules and resolving paths.\n */\nexport interface Resolver {\n /**\n * Resolves a module ID to its full path.\n */\n resolve(id: string): string;\n}\n\nexport type ContextHook<TArgs extends readonly any[] = []> = (\n this: void,\n ...args: TArgs\n) => MaybePromise<void>;\n\nexport interface MigrationOptions {\n /** Base storage key path for migrations. */\n storageBase: string;\n /** Whether and which datasources to migrate on initialization. */\n migrateOnInit: boolean | readonly string[];\n}\n\nexport interface ContextOptions {\n legacy: boolean;\n\n logger?: ConsolaInstance;\n /**\n * Current working directory\n */\n cwd: string;\n /**\n * Base project directory to search drizzle config files\n */\n baseDir: string;\n /**\n * Pattern for drizzle config files\n */\n configPattern: ConfigPattern;\n /**\n * Nuxt Kit resolver\n */\n resolver: Resolver;\n /**\n * Connector options\n */\n datasources: Record<string, { drivers: readonly string[] | { [name: string]: boolean } }>;\n\n migrations: MigrationOptions | undefined;\n\n /**\n * Hooks that allowed to call \"drizzle:init\" hook.\n */\n initHooks?: readonly NitroHookName[];\n\n tasks?: ContextHook<\n [\n tasks: Record<\n string,\n {\n handler: string;\n description: string;\n }\n >,\n ]\n >;\n\n plugins: ContextHook<[plugins: readonly string[]]>;\n\n types: ContextHook<\n [\n declarations: {\n shared: VirtualModules<`${string}.d.ts`>;\n module: VirtualModules<`${string}.d.ts`>;\n runtime: VirtualModules<`${string}.d.ts`>;\n virtual: Record<string, VirtualModules<`${string}.d.ts`>>;\n },\n ]\n >;\n\n virtualModules: ContextHook<[modules: VirtualModules]>;\n\n assets: ContextHook<[assets: readonly (ServerAssetDir | LegacyServerAssetDir)[]]>;\n\n externals?: ContextHook<[modules: readonly string[]]>;\n}\n\n/**\n * Creates a Context instance for managing Drizzle datasource configurations.\n * @param options - Configuration options for the context\n * @returns A Context instance\n */\nexport function createContext(options: ContextOptions): Context {\n return new DefaultContext(options);\n}\n\n/**\n * Information about a resolved Drizzle datasource.\n */\nexport interface DatasourceInfo {\n /** Unique name identifier for the datasource. */\n name: string;\n /** Whether the datasource is enabled (filtered by connector configuration). */\n enabled: boolean;\n /** Driver configurations for this datasource. */\n drivers: readonly DriverOptions[];\n}\n\n/** Options for a specific driver within a datasource. */\nexport type DriverOptions = {\n enabled: boolean;\n name: string;\n dialect: string;\n imports: {\n // config: string;\n schema: readonly string[];\n connector: string;\n helpers: string;\n };\n /** Migration configuration for this datasource driver. */\n migrations: {\n assets?: string;\n config?: Config[\"migrations\"];\n };\n};\n"],"mappings":";;;;;;;;;;;;AA2CA,IAAM,iBAAN,MAAwC;CACtC,eAAwC;CAC/B;CAET,YAAY,SAAyB;EACnC,KAAK,WAAW;CAClB;CAEA,MAAM,OAAsB;EAC1B,MAAM,cAAc,MAAM,KAAK,YAAY;EAE3C,MAAM,KAAK,SAAS,QAAQ,KAAK,eAAe,CAAC;EAEjD,MAAM,CAAC,aAAa,gBAAgB,cAAc,aAAa,gBAC7D,MAAM,QAAQ,IAAI;GAChB,uBAAuB,WAAW;GAClC,KAAK,eAAe,WAAW;GAC/B,KAAK,wBAAwB,WAAW;GACxC,KAAK,uBAAuB,WAAW;GACvC,KAAK,wBAAwB,WAAW;EAC1C,CAAC;EAEH,MAAM,KAAK,SAAS,eAAe,cAAc;EAEjD,MAAM,KAAK,SAAS,MAAM;GACxB,QAAQ;GACR,QAAQ;GACR,SAAS;GACT,SAAS;EACX,CAAC;EAED,IAAI,KAAK,SAAS,YAAY;GAC5B,MAAM,SAAS,MAAM,KAAK,gBAAgB,WAAW;GACrD,IAAI,QACF,MAAM,KAAK,SAAS,OAAO,MAAM;GAGnC,MAAM,KAAK,SAAS,QAAQ,EAC1B,mBAAmB;IACjB,aAAa;IACb,SAAS;GACX,EACF,CAAC;EACH;EAEA,IAAI,KAAK,SAAS,WAAW;GAC3B,MAAM,kBAAkB;IAAC;IAAW;IAAW;GAAY,CAAC,CAAC,SAAS,OAAO;IAC3E,OAAO,CAAC,KAAK,SAAS,EAAE,GAAG,KAAK,QAAQ,QAAQ,EAAE,CAAC;GACrD,CAAC;GAED,MAAM,KAAK,SAAS,UAAU,eAAe;EAC/C;CACF;CAEA,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