zenstack-kit 0.1.1 → 0.1.3

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 (52) hide show
  1. package/dist/cli/app.d.ts.map +1 -1
  2. package/dist/cli/app.js +9 -28
  3. package/dist/cli/commands.d.ts +3 -1
  4. package/dist/cli/commands.d.ts.map +1 -1
  5. package/dist/cli/commands.js +34 -1
  6. package/dist/cli/index.js +0 -0
  7. package/dist/cli/prompts.d.ts +9 -0
  8. package/dist/cli/prompts.d.ts.map +1 -1
  9. package/dist/cli/prompts.js +57 -1
  10. package/dist/migrations/prisma.d.ts +10 -0
  11. package/dist/migrations/prisma.d.ts.map +1 -1
  12. package/dist/migrations/prisma.js +85 -3
  13. package/package.json +1 -5
  14. package/dist/cli.d.ts +0 -12
  15. package/dist/cli.d.ts.map +0 -1
  16. package/dist/cli.js +0 -240
  17. package/dist/config-loader.d.ts +0 -6
  18. package/dist/config-loader.d.ts.map +0 -1
  19. package/dist/config-loader.js +0 -36
  20. package/dist/config.d.ts +0 -62
  21. package/dist/config.d.ts.map +0 -1
  22. package/dist/config.js +0 -44
  23. package/dist/init-prompts.d.ts +0 -13
  24. package/dist/init-prompts.d.ts.map +0 -1
  25. package/dist/init-prompts.js +0 -64
  26. package/dist/introspect.d.ts +0 -54
  27. package/dist/introspect.d.ts.map +0 -1
  28. package/dist/introspect.js +0 -75
  29. package/dist/kysely-adapter.d.ts +0 -49
  30. package/dist/kysely-adapter.d.ts.map +0 -1
  31. package/dist/kysely-adapter.js +0 -74
  32. package/dist/migrate-apply.d.ts +0 -18
  33. package/dist/migrate-apply.d.ts.map +0 -1
  34. package/dist/migrate-apply.js +0 -61
  35. package/dist/migrations.d.ts +0 -161
  36. package/dist/migrations.d.ts.map +0 -1
  37. package/dist/migrations.js +0 -620
  38. package/dist/prisma-migrations.d.ts +0 -160
  39. package/dist/prisma-migrations.d.ts.map +0 -1
  40. package/dist/prisma-migrations.js +0 -789
  41. package/dist/prompts.d.ts +0 -10
  42. package/dist/prompts.d.ts.map +0 -1
  43. package/dist/prompts.js +0 -41
  44. package/dist/pull.d.ts +0 -23
  45. package/dist/pull.d.ts.map +0 -1
  46. package/dist/pull.js +0 -424
  47. package/dist/schema-snapshot.d.ts +0 -45
  48. package/dist/schema-snapshot.d.ts.map +0 -1
  49. package/dist/schema-snapshot.js +0 -265
  50. package/dist/sql-compiler.d.ts +0 -74
  51. package/dist/sql-compiler.d.ts.map +0 -1
  52. package/dist/sql-compiler.js +0 -243
package/dist/cli.js DELETED
@@ -1,240 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * zenstack-kit CLI - Database tooling for ZenStack schemas
4
- *
5
- * Commands:
6
- * migrate:generate Generate a new SQL migration
7
- * migrate:apply Apply pending migrations
8
- * init Initialize snapshot from existing schema
9
- * pull Introspect database and generate schema
10
- */
11
- import { Command } from "commander";
12
- import chalk from "chalk";
13
- import { loadConfig } from "./config-loader.js";
14
- import { getPromptProvider } from "./prompts.js";
15
- import { pullSchema } from "./pull.js";
16
- import { createPrismaMigration, applyPrismaMigrations, hasPrismaSchemaChanges, hasSnapshot, scanMigrationFolders, writeMigrationLog, initializeSnapshot, createInitialMigration, } from "./prisma-migrations.js";
17
- import { promptSnapshotExists, promptFreshInit } from "./init-prompts.js";
18
- const program = new Command();
19
- program
20
- .name("zenstack-kit")
21
- .description("Drizzle-kit like CLI tooling for ZenStack schemas with Kysely support")
22
- .version("0.1.0");
23
- program
24
- .command("migrate:generate")
25
- .description("Generate a new SQL migration file")
26
- .option("-n, --name <name>", "Migration name")
27
- .option("-s, --schema <path>", "Path to ZenStack schema")
28
- .option("-m, --migrations <path>", "Migrations directory")
29
- .option("--dialect <dialect>", "Database dialect (sqlite, postgres, mysql)")
30
- .action(async (options) => {
31
- console.log(chalk.blue("Generating migration..."));
32
- try {
33
- const config = await loadConfig(process.cwd());
34
- const schemaPath = options.schema ?? config?.schema ?? "./schema.zmodel";
35
- const outputPath = options.migrations ?? config?.migrations?.migrationsFolder ?? "./prisma/migrations";
36
- const dialect = (options.dialect ?? config?.dialect ?? "sqlite");
37
- // Check for changes first
38
- const hasChanges = await hasPrismaSchemaChanges({
39
- schemaPath,
40
- outputPath,
41
- });
42
- if (!hasChanges) {
43
- console.log(chalk.yellow("No schema changes detected"));
44
- return;
45
- }
46
- // Get migration name
47
- const name = options.name ?? (await promptForMigrationName("migration"));
48
- // TODO: Add rename prompts and destructive change confirmation
49
- // For now, we generate without prompts
50
- const migration = await createPrismaMigration({
51
- name,
52
- schemaPath,
53
- outputPath,
54
- dialect,
55
- });
56
- if (!migration) {
57
- console.log(chalk.yellow("No schema changes detected"));
58
- return;
59
- }
60
- console.log(chalk.green(`✓ Migration created: ${migration.folderName}/migration.sql`));
61
- console.log(chalk.gray(` Path: ${migration.folderPath}`));
62
- }
63
- catch (error) {
64
- console.error(chalk.red("Error creating migration:"), error);
65
- process.exit(1);
66
- }
67
- });
68
- program
69
- .command("migrate:apply")
70
- .description("Apply pending SQL migrations")
71
- .option("-m, --migrations <path>", "Migrations directory")
72
- .option("--dialect <dialect>", "Database dialect (sqlite, postgres, mysql)")
73
- .option("--url <url>", "Database connection URL")
74
- .option("--table <name>", "Migrations table name (default: _prisma_migrations)")
75
- .option("--schema <name>", "Migrations schema (PostgreSQL only, default: public)")
76
- .action(async (options) => {
77
- console.log(chalk.blue("Applying migrations..."));
78
- try {
79
- const config = await loadConfig(process.cwd());
80
- const outputPath = options.migrations ?? config?.migrations?.migrationsFolder ?? "./prisma/migrations";
81
- const dialect = (options.dialect ?? config?.dialect ?? "sqlite");
82
- const connectionUrl = options.url ?? config?.dbCredentials?.url;
83
- const migrationsTable = options.table ?? config?.migrations?.migrationsTable ?? "_prisma_migrations";
84
- const migrationsSchema = options.schema ?? config?.migrations?.migrationsSchema ?? "public";
85
- if (dialect !== "sqlite" && !connectionUrl) {
86
- throw new Error("Database connection URL is required for non-sqlite dialects");
87
- }
88
- const databasePath = dialect === "sqlite" ? resolveSqlitePath(connectionUrl) : undefined;
89
- const result = await applyPrismaMigrations({
90
- migrationsFolder: outputPath,
91
- dialect,
92
- connectionUrl,
93
- databasePath,
94
- migrationsTable,
95
- migrationsSchema,
96
- });
97
- if (result.applied.length === 0 && !result.failed) {
98
- console.log(chalk.yellow("No pending migrations"));
99
- if (result.alreadyApplied.length > 0) {
100
- console.log(chalk.gray(` ${result.alreadyApplied.length} migration(s) already applied`));
101
- }
102
- return;
103
- }
104
- for (const item of result.applied) {
105
- console.log(chalk.green(`✓ Applied: ${item.migrationName} (${item.duration}ms)`));
106
- }
107
- if (result.failed) {
108
- console.log(chalk.red(`✗ Failed: ${result.failed.migrationName}`));
109
- console.log(chalk.red(` Error: ${result.failed.error}`));
110
- process.exit(1);
111
- }
112
- }
113
- catch (error) {
114
- console.error(chalk.red("Error applying migrations:"), error);
115
- process.exit(1);
116
- }
117
- });
118
- program
119
- .command("init")
120
- .description("Initialize snapshot from existing schema (baseline for migrations)")
121
- .option("-s, --schema <path>", "Path to ZenStack schema")
122
- .option("-m, --migrations <path>", "Migrations directory")
123
- .option("--dialect <dialect>", "Database dialect (sqlite, postgres, mysql)")
124
- .action(async (options) => {
125
- try {
126
- const config = await loadConfig(process.cwd());
127
- const schemaPath = options.schema ?? config?.schema ?? "./schema.zmodel";
128
- const outputPath = options.migrations ?? config?.migrations?.migrationsFolder ?? "./prisma/migrations";
129
- const dialect = (options.dialect ?? config?.dialect ?? "sqlite");
130
- // Scan current state
131
- const snapshotExists = await hasSnapshot(outputPath);
132
- const existingMigrations = await scanMigrationFolders(outputPath);
133
- // CASE A: Snapshot already exists
134
- if (snapshotExists) {
135
- const choice = await promptSnapshotExists();
136
- if (choice === "skip") {
137
- console.log(chalk.yellow("Skipped - no changes made"));
138
- return;
139
- }
140
- // Reinitialize: overwrite snapshot, rebuild migration log
141
- console.log(chalk.blue("Reinitializing..."));
142
- const result = await initializeSnapshot({ schemaPath, outputPath });
143
- // Rebuild migration log from existing folders
144
- const migrations = await scanMigrationFolders(outputPath);
145
- await writeMigrationLog(outputPath, migrations);
146
- console.log(chalk.green(`✓ Snapshot recreated: ${result.snapshotPath}`));
147
- console.log(chalk.green(`✓ Migration log rebuilt with ${migrations.length} migration(s)`));
148
- console.log(chalk.gray(` ${result.tableCount} table(s) captured`));
149
- return;
150
- }
151
- // CASE B: No snapshot but migrations exist (takeover mode)
152
- if (existingMigrations.length > 0) {
153
- console.log(chalk.blue("Initializing snapshot..."));
154
- console.log(chalk.yellow(`Found ${existingMigrations.length} existing migration(s) without snapshot.`));
155
- console.log(chalk.gray(" Taking over from existing migrations..."));
156
- for (const migration of existingMigrations) {
157
- console.log(chalk.gray(` ✓ ${migration.name} (${migration.checksum.slice(0, 8)}...)`));
158
- }
159
- const result = await initializeSnapshot({ schemaPath, outputPath });
160
- await writeMigrationLog(outputPath, existingMigrations);
161
- console.log(chalk.green(`✓ Snapshot created: ${result.snapshotPath}`));
162
- console.log(chalk.green(`✓ Migration log created with ${existingMigrations.length} migration(s)`));
163
- console.log(chalk.gray(` ${result.tableCount} table(s) captured`));
164
- return;
165
- }
166
- // CASE C: Fresh init (no snapshot, no migrations)
167
- const choice = await promptFreshInit();
168
- if (choice === "baseline") {
169
- // Baseline only: create snapshot, empty migration log
170
- console.log(chalk.blue("Creating baseline snapshot..."));
171
- const result = await initializeSnapshot({ schemaPath, outputPath });
172
- await writeMigrationLog(outputPath, []);
173
- console.log(chalk.green(`✓ Snapshot created: ${result.snapshotPath}`));
174
- console.log(chalk.green(`✓ Empty migration log created`));
175
- console.log(chalk.gray(` ${result.tableCount} table(s) captured`));
176
- console.log(chalk.gray(" Baselined. Future changes will generate migrations."));
177
- return;
178
- }
179
- // Create initial migration
180
- console.log(chalk.blue("Creating initial migration..."));
181
- const migration = await createInitialMigration({
182
- name: "init",
183
- schemaPath,
184
- outputPath,
185
- dialect,
186
- });
187
- console.log(chalk.green(`✓ Initial migration created: ${migration.folderName}/migration.sql`));
188
- console.log(chalk.gray(` Path: ${migration.folderPath}`));
189
- console.log(chalk.gray(" Run migrate:apply to set up the database."));
190
- }
191
- catch (error) {
192
- console.error(chalk.red("Error initializing:"), error);
193
- process.exit(1);
194
- }
195
- });
196
- program
197
- .command("pull")
198
- .description("Introspect database and generate ZenStack schema")
199
- .option("-o, --output <path>", "Output path for schema", "./schema.zmodel")
200
- .option("--dialect <dialect>", "Database dialect (sqlite, postgres, mysql)")
201
- .option("--url <url>", "Database connection URL")
202
- .action(async (options) => {
203
- console.log(chalk.blue("Pulling schema from database..."));
204
- try {
205
- const config = await loadConfig(process.cwd());
206
- const dialect = (options.dialect ?? config?.dialect ?? "sqlite");
207
- const connectionUrl = options.url ?? config?.dbCredentials?.url;
208
- if (dialect !== "sqlite" && !connectionUrl) {
209
- throw new Error("Database connection URL is required for non-sqlite dialects");
210
- }
211
- const databasePath = dialect === "sqlite" ? resolveSqlitePath(connectionUrl) : undefined;
212
- const result = await pullSchema({
213
- dialect,
214
- connectionUrl,
215
- databasePath,
216
- outputPath: options.output,
217
- });
218
- console.log(chalk.green(`✓ Schema generated: ${result.outputPath}`));
219
- console.log(chalk.gray(` ${result.tableCount} table(s) introspected`));
220
- }
221
- catch (error) {
222
- console.error(chalk.red("Error pulling schema:"), error);
223
- process.exit(1);
224
- }
225
- });
226
- program.parse();
227
- async function promptForMigrationName(defaultName) {
228
- const prompt = getPromptProvider();
229
- const answer = await prompt.question(`Migration name (${defaultName}): `);
230
- const trimmed = answer.trim();
231
- return trimmed.length > 0 ? trimmed : defaultName;
232
- }
233
- function resolveSqlitePath(url) {
234
- if (!url)
235
- return undefined;
236
- if (url.startsWith("file:")) {
237
- return url.slice("file:".length);
238
- }
239
- return url;
240
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * Configuration loader for zenstack-kit
3
- */
4
- import type { ZenStackKitConfig } from "./config.js";
5
- export declare function loadConfig(cwd: string): Promise<ZenStackKitConfig | null>;
6
- //# sourceMappingURL=config-loader.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config-loader.d.ts","sourceRoot":"","sources":["../src/config-loader.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUrD,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAuB/E"}
@@ -1,36 +0,0 @@
1
- /**
2
- * Configuration loader for zenstack-kit
3
- */
4
- import * as fs from "fs";
5
- import * as path from "path";
6
- import { createRequire } from "module";
7
- const CONFIG_FILES = [
8
- "zenstack-kit.config.ts",
9
- "zenstack-kit.config.js",
10
- "zenstack-kit.config.mjs",
11
- "zenstack-kit.config.cjs",
12
- ];
13
- export async function loadConfig(cwd) {
14
- const configPath = CONFIG_FILES.map((file) => path.join(cwd, file)).find((file) => fs.existsSync(file));
15
- if (!configPath) {
16
- return null;
17
- }
18
- const ext = path.extname(configPath);
19
- if (ext === ".cjs") {
20
- const require = createRequire(import.meta.url);
21
- const loaded = require(configPath);
22
- return (loaded.default ?? loaded);
23
- }
24
- if (ext === ".js" || ext === ".mjs") {
25
- const loaded = await import(pathToFileUrl(configPath));
26
- return (loaded.default ?? loaded);
27
- }
28
- const { default: jiti } = await import("jiti");
29
- const loader = jiti(import.meta.url, { interopDefault: true });
30
- const loaded = loader(configPath);
31
- return (loaded.default ?? loaded);
32
- }
33
- function pathToFileUrl(filePath) {
34
- const resolved = path.resolve(filePath);
35
- return new URL(`file://${resolved}`).href;
36
- }
package/dist/config.d.ts DELETED
@@ -1,62 +0,0 @@
1
- /**
2
- * Configuration utilities for zenstack-kit
3
- *
4
- * Provides a type-safe way to define configuration similar to drizzle-kit's config.
5
- */
6
- export interface ZenStackKitConfig {
7
- /** Path to ZenStack schema file */
8
- schema: string;
9
- /** Output directory for generated files */
10
- out: string;
11
- /** Database dialect */
12
- dialect?: "sqlite" | "postgres" | "mysql";
13
- /** Database connection string */
14
- dbCredentials?: {
15
- url?: string;
16
- host?: string;
17
- port?: number;
18
- user?: string;
19
- password?: string;
20
- database?: string;
21
- };
22
- /** Migration settings */
23
- migrations?: {
24
- /** Directory for migration files (default: ./prisma/migrations) */
25
- migrationsFolder?: string;
26
- /** Table name for migration metadata (default: _prisma_migrations) */
27
- migrationsTable?: string;
28
- /** Database schema for migrations table (PostgreSQL only, default: public) */
29
- migrationsSchema?: string;
30
- };
31
- /** Code generation settings */
32
- codegen?: {
33
- /** Use camelCase for column names */
34
- camelCase?: boolean;
35
- /** Generate index file */
36
- generateIndex?: boolean;
37
- };
38
- /** Enable verbose logging */
39
- verbose?: boolean;
40
- /** Enable strict mode */
41
- strict?: boolean;
42
- }
43
- /**
44
- * Define zenstack-kit configuration
45
- *
46
- * @example
47
- * ```ts
48
- * // zenstack-kit.config.ts
49
- * import { defineConfig } from "zenstack-kit";
50
- *
51
- * export default defineConfig({
52
- * schema: "./prisma/schema.zmodel",
53
- * out: "./src/db",
54
- * dialect: "postgres",
55
- * dbCredentials: {
56
- * url: process.env.DATABASE_URL,
57
- * },
58
- * });
59
- * ```
60
- */
61
- export declare function defineConfig(config: ZenStackKitConfig): ZenStackKitConfig;
62
- //# sourceMappingURL=config.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,WAAW,iBAAiB;IAChC,mCAAmC;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,uBAAuB;IACvB,OAAO,CAAC,EAAE,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;IAC1C,iCAAiC;IACjC,aAAa,CAAC,EAAE;QACd,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,yBAAyB;IACzB,UAAU,CAAC,EAAE;QACX,mEAAmE;QACnE,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,sEAAsE;QACtE,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,8EAA8E;QAC9E,gBAAgB,CAAC,EAAE,MAAM,CAAC;KAC3B,CAAC;IACF,+BAA+B;IAC/B,OAAO,CAAC,EAAE;QACR,qCAAqC;QACrC,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,0BAA0B;QAC1B,aAAa,CAAC,EAAE,OAAO,CAAC;KACzB,CAAC;IACF,6BAA6B;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,yBAAyB;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,CAoBzE"}
package/dist/config.js DELETED
@@ -1,44 +0,0 @@
1
- /**
2
- * Configuration utilities for zenstack-kit
3
- *
4
- * Provides a type-safe way to define configuration similar to drizzle-kit's config.
5
- */
6
- /**
7
- * Define zenstack-kit configuration
8
- *
9
- * @example
10
- * ```ts
11
- * // zenstack-kit.config.ts
12
- * import { defineConfig } from "zenstack-kit";
13
- *
14
- * export default defineConfig({
15
- * schema: "./prisma/schema.zmodel",
16
- * out: "./src/db",
17
- * dialect: "postgres",
18
- * dbCredentials: {
19
- * url: process.env.DATABASE_URL,
20
- * },
21
- * });
22
- * ```
23
- */
24
- export function defineConfig(config) {
25
- return {
26
- // Default values
27
- dialect: "sqlite",
28
- verbose: false,
29
- strict: false,
30
- ...config,
31
- out: config.out ?? "./generated",
32
- migrations: {
33
- migrationsFolder: "./prisma/migrations",
34
- migrationsTable: "_prisma_migrations",
35
- migrationsSchema: "public",
36
- ...config.migrations,
37
- },
38
- codegen: {
39
- camelCase: true,
40
- generateIndex: true,
41
- ...config.codegen,
42
- },
43
- };
44
- }
@@ -1,13 +0,0 @@
1
- /**
2
- * Interactive prompts for the init command using ink
3
- */
4
- export type InitChoice = "skip" | "reinitialize" | "baseline" | "create_initial";
5
- /**
6
- * Prompt user when snapshot already exists (Case A)
7
- */
8
- export declare function promptSnapshotExists(): Promise<InitChoice>;
9
- /**
10
- * Prompt user for fresh init when no migrations exist (Case C)
11
- */
12
- export declare function promptFreshInit(): Promise<InitChoice>;
13
- //# sourceMappingURL=init-prompts.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"init-prompts.d.ts","sourceRoot":"","sources":["../src/init-prompts.tsx"],"names":[],"mappings":"AAAA;;GAEG;AAMH,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,cAAc,GAAG,UAAU,GAAG,gBAAgB,CAAC;AAsCjF;;GAEG;AACH,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,UAAU,CAAC,CAyBhE;AAED;;GAEG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,UAAU,CAAC,CAyB3D"}
@@ -1,64 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- /**
3
- * Interactive prompts for the init command using ink
4
- */
5
- import { useState } from "react";
6
- import { render, Box, Text } from "ink";
7
- import SelectInput from "ink-select-input";
8
- function SelectPrompt({ message, items, onSelect }) {
9
- const [selectedIndex, setSelectedIndex] = useState(0);
10
- const handleSelect = (item) => {
11
- onSelect(item.value);
12
- };
13
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { marginBottom: 1, children: [_jsx(Text, { color: "cyan", children: "? " }), _jsx(Text, { children: message })] }), _jsx(SelectInput, { items: items, onSelect: handleSelect, onHighlight: (item) => {
14
- const idx = items.findIndex((i) => i.value === item.value);
15
- if (idx !== -1)
16
- setSelectedIndex(idx);
17
- } }), items[selectedIndex]?.description && (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { dimColor: true, children: [" ", items[selectedIndex].description] }) }))] }));
18
- }
19
- /**
20
- * Prompt user when snapshot already exists (Case A)
21
- */
22
- export async function promptSnapshotExists() {
23
- return new Promise((resolve) => {
24
- const { unmount, waitUntilExit } = render(_jsx(SelectPrompt, { message: "Snapshot already exists. What would you like to do?", items: [
25
- {
26
- label: "Skip",
27
- value: "skip",
28
- description: "Do nothing and exit",
29
- },
30
- {
31
- label: "Reinitialize",
32
- value: "reinitialize",
33
- description: "Overwrite snapshot and rebuild migration log from existing migrations",
34
- },
35
- ], onSelect: (value) => {
36
- unmount();
37
- resolve(value);
38
- } }));
39
- waitUntilExit();
40
- });
41
- }
42
- /**
43
- * Prompt user for fresh init when no migrations exist (Case C)
44
- */
45
- export async function promptFreshInit() {
46
- return new Promise((resolve) => {
47
- const { unmount, waitUntilExit } = render(_jsx(SelectPrompt, { message: "No migrations found. What would you like to do?", items: [
48
- {
49
- label: "Baseline only",
50
- value: "baseline",
51
- description: "Create snapshot only - use when database already matches schema",
52
- },
53
- {
54
- label: "Create initial migration",
55
- value: "create_initial",
56
- description: "Create snapshot + initial migration - use when database is empty",
57
- },
58
- ], onSelect: (value) => {
59
- unmount();
60
- resolve(value);
61
- } }));
62
- waitUntilExit();
63
- });
64
- }
@@ -1,54 +0,0 @@
1
- /**
2
- * Schema introspection utilities
3
- *
4
- * Provides functionality to introspect ZenStack schemas and databases,
5
- * extracting model and field information for code generation.
6
- */
7
- export interface FieldInfo {
8
- /** Field name */
9
- name: string;
10
- /** Field type (String, Int, Boolean, etc.) */
11
- type: string;
12
- /** Whether the field is optional */
13
- isOptional: boolean;
14
- /** Whether the field is an array */
15
- isArray: boolean;
16
- /** Whether this is a relation field */
17
- isRelation: boolean;
18
- /** Whether this is the primary key */
19
- isId: boolean;
20
- /** Whether the field has a default value */
21
- hasDefault: boolean;
22
- /** Whether the field is unique */
23
- isUnique: boolean;
24
- /** Related model name (for relations) */
25
- relationModel?: string;
26
- }
27
- export interface ModelInfo {
28
- /** Model name */
29
- name: string;
30
- /** Table name in database */
31
- tableName: string;
32
- /** Model fields */
33
- fields: FieldInfo[];
34
- }
35
- export interface SchemaInfo {
36
- /** All models in the schema */
37
- models: ModelInfo[];
38
- /** Schema version or hash */
39
- version: string;
40
- }
41
- interface IntrospectOptions {
42
- /** Path to ZenStack schema file */
43
- schemaPath?: string;
44
- /** Database connection URL (for database introspection) */
45
- databaseUrl?: string;
46
- /** Output path for generated schema */
47
- outputPath?: string;
48
- }
49
- /**
50
- * Introspect schema from file or database
51
- */
52
- export declare function introspectSchema(options: IntrospectOptions): Promise<SchemaInfo>;
53
- export {};
54
- //# sourceMappingURL=introspect.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"introspect.d.ts","sourceRoot":"","sources":["../src/introspect.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,MAAM,WAAW,SAAS;IACxB,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,IAAI,EAAE,MAAM,CAAC;IACb,oCAAoC;IACpC,UAAU,EAAE,OAAO,CAAC;IACpB,oCAAoC;IACpC,OAAO,EAAE,OAAO,CAAC;IACjB,uCAAuC;IACvC,UAAU,EAAE,OAAO,CAAC;IACpB,sCAAsC;IACtC,IAAI,EAAE,OAAO,CAAC;IACd,4CAA4C;IAC5C,UAAU,EAAE,OAAO,CAAC;IACpB,kCAAkC;IAClC,QAAQ,EAAE,OAAO,CAAC;IAClB,yCAAyC;IACzC,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,SAAS;IACxB,iBAAiB;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,6BAA6B;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,mBAAmB;IACnB,MAAM,EAAE,SAAS,EAAE,CAAC;CACrB;AAED,MAAM,WAAW,UAAU;IACzB,+BAA+B;IAC/B,MAAM,EAAE,SAAS,EAAE,CAAC;IACpB,6BAA6B;IAC7B,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,UAAU,iBAAiB;IACzB,mCAAmC;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2DAA2D;IAC3D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,uCAAuC;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAoED;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,UAAU,CAAC,CAUtF"}
@@ -1,75 +0,0 @@
1
- /**
2
- * Schema introspection utilities
3
- *
4
- * Provides functionality to introspect ZenStack schemas and databases,
5
- * extracting model and field information for code generation.
6
- */
7
- import * as fs from "fs/promises";
8
- /**
9
- * Parse a .zmodel file and extract schema information
10
- * This is a simplified parser - in production, you'd use ZenStack's AST
11
- */
12
- async function parseZModelFile(schemaPath) {
13
- const content = await fs.readFile(schemaPath, "utf-8");
14
- const models = [];
15
- // Simple regex-based parser for demonstration
16
- // In production, integrate with ZenStack's parser
17
- const modelRegex = /model\s+(\w+)\s*\{([^}]+)\}/g;
18
- const fieldRegex = /^\s*(\w+)\s+(\w+)(\[\])?\s*(\?)?\s*(.*?)$/gm;
19
- let modelMatch;
20
- while ((modelMatch = modelRegex.exec(content)) !== null) {
21
- const modelName = modelMatch[1];
22
- const modelBody = modelMatch[2];
23
- const fields = [];
24
- let fieldMatch;
25
- const fieldPattern = /^\s*(\w+)\s+(\w+)(\[\])?\s*(\?)?(.*)$/gm;
26
- while ((fieldMatch = fieldPattern.exec(modelBody)) !== null) {
27
- const [, name, type, isArray, isOptional, modifiers] = fieldMatch;
28
- // Skip if it looks like a directive
29
- if (name.startsWith("@@") || name.startsWith("//"))
30
- continue;
31
- const isId = modifiers?.includes("@id") || false;
32
- const hasDefault = modifiers?.includes("@default") || false;
33
- const isUnique = modifiers?.includes("@unique") || isId;
34
- const isRelation = modifiers?.includes("@relation") || false;
35
- fields.push({
36
- name,
37
- type,
38
- isOptional: !!isOptional,
39
- isArray: !!isArray,
40
- isRelation,
41
- isId,
42
- hasDefault,
43
- isUnique,
44
- relationModel: isRelation ? type : undefined,
45
- });
46
- }
47
- models.push({
48
- name: modelName,
49
- tableName: modelName.toLowerCase(),
50
- fields,
51
- });
52
- }
53
- // Generate a simple version hash
54
- const version = Buffer.from(content).toString("base64").slice(0, 8);
55
- return { models, version };
56
- }
57
- /**
58
- * Introspect a database and generate schema information
59
- */
60
- async function introspectDatabase(databaseUrl) {
61
- void databaseUrl;
62
- throw new Error("Database introspection is not supported.");
63
- }
64
- /**
65
- * Introspect schema from file or database
66
- */
67
- export async function introspectSchema(options) {
68
- if (options.schemaPath) {
69
- return parseZModelFile(options.schemaPath);
70
- }
71
- if (options.databaseUrl) {
72
- return introspectDatabase(options.databaseUrl);
73
- }
74
- throw new Error("Either schemaPath or databaseUrl must be provided");
75
- }
@@ -1,49 +0,0 @@
1
- /**
2
- * Kysely database adapter
3
- *
4
- * Provides utilities to create Kysely instances configured for use
5
- * with ZenStack-generated types.
6
- */
7
- import type { Kysely } from "kysely";
8
- export type KyselyDialect = "sqlite" | "postgres" | "mysql";
9
- export interface KyselyAdapterOptions {
10
- /** Database dialect */
11
- dialect: KyselyDialect;
12
- /** Database connection URL */
13
- connectionUrl?: string;
14
- /** SQLite database path (for SQLite dialect) */
15
- databasePath?: string;
16
- /** Connection pool settings */
17
- pool?: {
18
- min?: number;
19
- max?: number;
20
- };
21
- }
22
- export interface KyselyAdapter<DB> {
23
- /** The Kysely instance */
24
- db: Kysely<DB>;
25
- /** Destroy the connection pool */
26
- destroy: () => Promise<void>;
27
- }
28
- /**
29
- * Creates a Kysely adapter for use with ZenStack schemas
30
- *
31
- * @example
32
- * ```ts
33
- * import { createKyselyAdapter } from "zenstack-kit";
34
- * import type { Database } from "./generated/kysely-types";
35
- *
36
- * const { db, destroy } = await createKyselyAdapter<Database>({
37
- * dialect: "postgres",
38
- * connectionUrl: process.env.DATABASE_URL,
39
- * });
40
- *
41
- * // Use db for queries
42
- * const users = await db.selectFrom("user").selectAll().execute();
43
- *
44
- * // Clean up
45
- * await destroy();
46
- * ```
47
- */
48
- export declare function createKyselyAdapter<DB>(options: KyselyAdapterOptions): Promise<KyselyAdapter<DB>>;
49
- //# sourceMappingURL=kysely-adapter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"kysely-adapter.d.ts","sourceRoot":"","sources":["../src/kysely-adapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAW,MAAM,QAAQ,CAAC;AAE9C,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;AAE5D,MAAM,WAAW,oBAAoB;IACnC,uBAAuB;IACvB,OAAO,EAAE,aAAa,CAAC;IACvB,8BAA8B;IAC9B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gDAAgD;IAChD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,+BAA+B;IAC/B,IAAI,CAAC,EAAE;QACL,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,GAAG,CAAC,EAAE,MAAM,CAAC;KACd,CAAC;CACH;AAED,MAAM,WAAW,aAAa,CAAC,EAAE;IAC/B,0BAA0B;IAC1B,EAAE,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IACf,kCAAkC;IAClC,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,mBAAmB,CAAC,EAAE,EAC1C,OAAO,EAAE,oBAAoB,GAC5B,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAwD5B"}