@c15t/cli 0.0.1-rc.13 → 0.0.1-rc.14

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/dist/index.mjs CHANGED
@@ -1,141 +1,127 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from 'commander';
3
- import fs$1, { existsSync } from 'node:fs';
4
- import fs from 'node:fs/promises';
5
- import path from 'node:path';
6
- import { getAdapter } from '@c15t/backend/pkgs/db-adapters';
7
- import chalk from 'chalk';
8
- import prompts from 'prompts';
9
- import yoctoSpinner from 'yocto-spinner';
10
- import { z } from 'zod';
11
- import { createLogger } from '@c15t/backend/pkgs/logger';
12
- import { getConsentTables } from '@c15t/backend/schema';
13
- import { getMigrations } from '@c15t/backend/pkgs/migrations';
14
- import { produceSchema } from '@mrleebo/prisma-ast';
15
- import babelPresetReact from '@babel/preset-react';
16
- import babelPresetTypescript from '@babel/preset-typescript';
17
- import { DoubleTieError } from '@c15t/backend/pkgs/results';
18
- import { loadConfig } from 'c12';
19
- import 'dotenv/config';
20
- import Crypto from 'node:crypto';
21
- import fs$2 from 'fs-extra';
22
-
23
- const logger = createLogger({
24
- level: "info",
25
- appName: "c15t"
2
+ import * as __WEBPACK_EXTERNAL_MODULE_commander__ from "commander";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
6
+ import * as __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_db_adapters_cee37d0f__ from "@c15t/backend/pkgs/db-adapters";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_chalk__ from "chalk";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_prompts__ from "prompts";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_yocto_spinner_579f0326__ from "yocto-spinner";
10
+ import * as __WEBPACK_EXTERNAL_MODULE_zod__ from "zod";
11
+ import * as __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_logger_44a195c6__ from "@c15t/backend/pkgs/logger";
12
+ import * as __WEBPACK_EXTERNAL_MODULE__c15t_backend_schema_4fae43f5__ from "@c15t/backend/schema";
13
+ import * as __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_migrations_80b6e3bd__ from "@c15t/backend/pkgs/migrations";
14
+ import * as __WEBPACK_EXTERNAL_MODULE__mrleebo_prisma_ast_c5b328aa__ from "@mrleebo/prisma-ast";
15
+ import * as __WEBPACK_EXTERNAL_MODULE__babel_preset_react_76cf724d__ from "@babel/preset-react";
16
+ import * as __WEBPACK_EXTERNAL_MODULE__babel_preset_typescript_a7789c85__ from "@babel/preset-typescript";
17
+ import * as __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__ from "@c15t/backend/pkgs/results";
18
+ import * as __WEBPACK_EXTERNAL_MODULE_c12__ from "c12";
19
+ import "dotenv/config";
20
+ import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__ from "node:crypto";
21
+ import * as __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__ from "fs-extra";
22
+ const logger = (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_logger_44a195c6__.createLogger)({
23
+ level: 'info',
24
+ appName: 'c15t'
26
25
  });
27
-
26
+ const utils_logger = logger;
28
27
  function convertToSnakeCase(str) {
29
- if (str === void 0 || str === null) {
30
- return "";
31
- }
32
- return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
28
+ if (null == str) return '';
29
+ return str.replace(/[A-Z]/g, (letter)=>`_${letter.toLowerCase()}`);
33
30
  }
34
- const generateDrizzleSchema = async ({
35
- options,
36
- file,
37
- adapter
38
- }) => {
39
- const tables = getConsentTables(options);
40
- const filePath = file || "./auth-schema.ts";
41
- const databaseType = adapter.options?.provider;
42
- const usePlural = adapter.options?.usePlural;
43
- const timestampAndBoolean = databaseType !== "sqlite" ? "timestamp, boolean" : "";
44
- const int = databaseType === "mysql" ? "int" : "integer";
45
- const hasBigint = Object.values(tables).some(
46
- (table) => Object.values(table.fields).some(
47
- (field) => "bigint" in field && field.bigint
48
- )
49
- );
50
- const bigint = databaseType !== "sqlite" ? "bigint" : "";
51
- const text = databaseType === "mysql" ? "varchar, text" : "text";
52
- const jsonType = ["mysql", "pg"].includes(databaseType || "") ? ", json" : "";
53
- let code = `import { ${databaseType}Table, ${text}, ${int}${hasBigint ? `, ${bigint}` : ""}, ${timestampAndBoolean}${jsonType} } from "drizzle-orm/${databaseType}-core";`;
54
- const fileExist = existsSync(filePath);
55
- let isFirstTable = true;
56
- for (const table in tables) {
57
- if (Object.prototype.hasOwnProperty.call(tables, table)) {
58
- let getMySQLStringType = function(field, name) {
59
- if (field.unique) {
60
- return `varchar('${name}', { length: 255 })`;
61
- }
62
- if (field.references) {
63
- return `varchar('${name}', { length: 36 })`;
64
- }
65
- return `text('${name}')`;
66
- }, getType = function(fieldName, field) {
67
- const snakeCaseName = convertToSnakeCase(fieldName);
68
- const type = field.type;
69
- const typeMap = {
70
- string: {
71
- sqlite: `text('${snakeCaseName}')`,
72
- pg: `text('${snakeCaseName}')`,
73
- mysql: getMySQLStringType(field, snakeCaseName)
74
- },
75
- boolean: {
76
- sqlite: `integer('${snakeCaseName}', { mode: 'boolean' })`,
77
- pg: `boolean('${snakeCaseName}')`,
78
- mysql: `boolean('${snakeCaseName}')`
79
- },
80
- number: {
81
- sqlite: `integer('${snakeCaseName}')`,
82
- pg: "bigint" in field && field.bigint ? `bigint('${snakeCaseName}', { mode: 'number' })` : `integer('${snakeCaseName}')`,
83
- mysql: "bigint" in field && field.bigint ? `bigint('${snakeCaseName}', { mode: 'number' })` : `int('${snakeCaseName}')`
84
- },
85
- date: {
86
- sqlite: `integer('${snakeCaseName}', { mode: 'timestamp' })`,
87
- pg: `timestamp('${snakeCaseName}')`,
88
- mysql: `timestamp('${snakeCaseName}')`
89
- },
90
- // Add JSON type support
91
- json: {
92
- sqlite: `text('${snakeCaseName}')`,
93
- // SQLite uses TEXT for JSON
94
- pg: `json('${snakeCaseName}')`,
95
- // PostgreSQL native JSON
96
- mysql: `json('${snakeCaseName}')`
97
- // MySQL native JSON
98
- }
99
- };
100
- if (!typeMap[type]) {
101
- return `text('${snakeCaseName}')`;
31
+ const generateDrizzleSchema = async ({ options, file, adapter })=>{
32
+ const tables = (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_schema_4fae43f5__.getConsentTables)(options);
33
+ const filePath = file || './auth-schema.ts';
34
+ const databaseType = adapter.options?.provider;
35
+ const usePlural = adapter.options?.usePlural;
36
+ const timestampAndBoolean = 'sqlite' !== databaseType ? 'timestamp, boolean' : '';
37
+ const int = 'mysql' === databaseType ? 'int' : 'integer';
38
+ const hasBigint = Object.values(tables).some((table)=>Object.values(table.fields).some((field)=>'bigint' in field && field.bigint));
39
+ const bigint = 'sqlite' !== databaseType ? 'bigint' : '';
40
+ const text = 'mysql' === databaseType ? 'varchar, text' : 'text';
41
+ const jsonType = [
42
+ 'mysql',
43
+ 'pg'
44
+ ].includes(databaseType || '') ? ', json' : '';
45
+ let code = `import { ${databaseType}Table, ${text}, ${int}${hasBigint ? `, ${bigint}` : ''}, ${timestampAndBoolean}${jsonType} } from "drizzle-orm/${databaseType}-core";`;
46
+ const fileExist = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(filePath);
47
+ let isFirstTable = true;
48
+ for(const table in tables)if (Object.prototype.hasOwnProperty.call(tables, table)) {
49
+ const tableDefinition = tables[table];
50
+ if (!tableDefinition) continue;
51
+ let modelName = usePlural ? `${tableDefinition.modelName}s` : tableDefinition.modelName;
52
+ if (!modelName) modelName = table;
53
+ const fields = tableDefinition.fields;
54
+ function getMySQLStringType(field, name) {
55
+ if (field.unique) return `varchar('${name}', { length: 255 })`;
56
+ if (field.references) return `varchar('${name}', { length: 36 })`;
57
+ return `text('${name}')`;
102
58
  }
103
- const dbType = databaseType && ["sqlite", "pg", "mysql"].includes(databaseType) ? databaseType : "sqlite";
104
- return typeMap[type][dbType];
105
- };
106
- let modelName = usePlural ? `${tables[table].modelName}s` : tables[table].modelName;
107
- if (!modelName) {
108
- modelName = table;
109
- }
110
- const fields = tables[table].fields;
111
- const id = databaseType === "mysql" ? `varchar("id", { length: 36 }).primaryKey()` : `text("id").primaryKey()`;
112
- const tableNameForSQL = convertToSnakeCase(modelName);
113
- if (isFirstTable) {
114
- code += "\n\n";
115
- isFirstTable = false;
116
- } else {
117
- code += "\n\n";
118
- }
119
- const schema = `export const ${modelName} = ${databaseType}Table("${tableNameForSQL}", {
120
- id: ${id},
121
- ${Object.keys(fields).map((field) => {
122
- if (Object.prototype.hasOwnProperty.call(fields, field)) {
123
- const attr = fields[field];
124
- return ` ${field}: ${getType(field, attr)}${attr.required ? ".notNull()" : ""}${attr.unique ? ".unique()" : ""}${attr.references ? `.references(()=> ${usePlural ? `${attr.references.model}s` : attr.references.model}.${attr.references.field}, { onDelete: 'cascade' })` : ""}`;
59
+ function getType(fieldName, field) {
60
+ const snakeCaseName = convertToSnakeCase(fieldName);
61
+ const type = field.type;
62
+ const typeMap = {
63
+ string: {
64
+ sqlite: `text('${snakeCaseName}')`,
65
+ pg: `text('${snakeCaseName}')`,
66
+ mysql: getMySQLStringType(field, snakeCaseName)
67
+ },
68
+ boolean: {
69
+ sqlite: `integer('${snakeCaseName}', { mode: 'boolean' })`,
70
+ pg: `boolean('${snakeCaseName}')`,
71
+ mysql: `boolean('${snakeCaseName}')`
72
+ },
73
+ number: {
74
+ sqlite: `integer('${snakeCaseName}')`,
75
+ pg: 'bigint' in field && field.bigint ? `bigint('${snakeCaseName}', { mode: 'number' })` : `integer('${snakeCaseName}')`,
76
+ mysql: 'bigint' in field && field.bigint ? `bigint('${snakeCaseName}', { mode: 'number' })` : `int('${snakeCaseName}')`
77
+ },
78
+ date: {
79
+ sqlite: `integer('${snakeCaseName}', { mode: 'timestamp' })`,
80
+ pg: `timestamp('${snakeCaseName}')`,
81
+ mysql: `timestamp('${snakeCaseName}')`
82
+ },
83
+ json: {
84
+ sqlite: `text('${snakeCaseName}')`,
85
+ pg: `json('${snakeCaseName}')`,
86
+ mysql: `json('${snakeCaseName}')`
87
+ }
88
+ };
89
+ if (!typeMap[type]) return `text('${snakeCaseName}')`;
90
+ const dbType = databaseType && [
91
+ 'sqlite',
92
+ 'pg',
93
+ 'mysql'
94
+ ].includes(databaseType) ? databaseType : 'sqlite';
95
+ return typeMap[type][dbType];
125
96
  }
126
- return "";
127
- }).filter(Boolean).join(",\n")}
128
- });`;
129
- code += schema;
97
+ const id = 'mysql' === databaseType ? 'varchar("id", { length: 36 }).primaryKey()' : 'text("id").primaryKey()';
98
+ const tableNameForSQL = convertToSnakeCase(modelName);
99
+ if (isFirstTable) {
100
+ code += '\n\n';
101
+ isFirstTable = false;
102
+ } else code += '\n\n';
103
+ const fieldDefinitions = Object.keys(fields).map((field)=>{
104
+ if (Object.prototype.hasOwnProperty.call(fields, field)) {
105
+ const attr = fields[field];
106
+ if (!attr) return '';
107
+ return ` ${field}: ${getType(field, attr)}${attr.required ? '.notNull()' : ''}${attr.unique ? '.unique()' : ''}${attr.references ? `.references(()=> ${usePlural ? `${attr.references.model}s` : attr.references.model}.${attr.references.field}, { onDelete: 'cascade' })` : ''}`;
108
+ }
109
+ return '';
110
+ }).filter(Boolean).join(',\n');
111
+ const schema = [
112
+ `export const ${modelName} = ${databaseType}Table("${tableNameForSQL}", {`,
113
+ ` id: ${id},`,
114
+ fieldDefinitions,
115
+ '});'
116
+ ].join('\n');
117
+ code += schema;
130
118
  }
131
- }
132
- return {
133
- code,
134
- fileName: filePath,
135
- overwrite: fileExist
136
- };
119
+ return {
120
+ code: code,
121
+ fileName: filePath,
122
+ overwrite: fileExist
123
+ };
137
124
  };
138
-
139
125
  const CREATE_TABLE_REGEX = /create\s+table\s+"([^"]+)"\s+\((.*)\)/i;
140
126
  const CREATE_INDEX_REGEX = /create\s+index\s+"?([^"\s]+)"?\s+on\s+"?([^"\s]+)"?/i;
141
127
  const NOT_NULL_REGEX = /\bnot null\b/gi;
@@ -159,59 +145,45 @@ const BOOLEAN_FIELD_REGEX = /("is[A-Z][a-zA-Z0-9]*")\s+integer/g;
159
145
  const DATE_FIELD_REGEX = /("(?:created|updated|expires)At")\s+date/gi;
160
146
  const TEXT_FIELD_REGEX = /("(?:name|code|description|id)")\s+text/gi;
161
147
  const JSON_FIELD_REGEX = /("(?:metadata|config|data|settings|options|preferences|attributes)")\s+text/gi;
162
- function formatSQL(sql, databaseType = "sqlite", options) {
163
- const dbType = databaseType === "pg" ? "postgresql" : databaseType;
164
- const statements = sql.split(";").filter((stmt) => stmt.trim());
165
- const rollbackStatements = [];
166
- const formattedStatements = statements.map((statement) => {
167
- const trimmedStmt = statement.trim().toLowerCase();
168
- if (trimmedStmt.startsWith("create table")) {
169
- const match = statement.match(CREATE_TABLE_REGEX);
170
- if (match) {
171
- const [_, tableName, columnsStr] = match;
172
- rollbackStatements.unshift(`DROP TABLE IF EXISTS "${tableName}"`);
173
- const columns = columnsStr.split(",").map((col) => col.trim());
174
- const formattedColumns = columns.map((col) => {
175
- let formattedCol = col.replace(NOT_NULL_REGEX, "NOT NULL").replace(PRIMARY_KEY_REGEX, "PRIMARY KEY").replace(REFERENCES_REGEX, "REFERENCES").replace(UNIQUE_REGEX, "UNIQUE");
176
- if (dbType === "postgresql") {
177
- formattedCol = formattedCol.replace(BOOLEAN_FIELD_REGEX, "$1 boolean").replace(DATE_FIELD_REGEX, "$1 timestamp with time zone").replace(TEXT_FIELD_REGEX, "$1 varchar(255)").replace(JSON_FIELD_REGEX, "$1 jsonb");
178
- } else if (dbType === "mysql") {
179
- formattedCol = formattedCol.replace(BOOLEAN_FIELD_REGEX, "$1 TINYINT(1)").replace(DATE_FIELD_REGEX, "$1 DATETIME").replace(TEXT_FIELD_REGEX, "$1 VARCHAR(255)").replace(JSON_FIELD_REGEX, "$1 JSON");
180
- } else if (dbType === "sqlite") {
181
- formattedCol = formattedCol.replace(
182
- JSON_FIELD_REGEX,
183
- "$1 text -- stored as JSON"
184
- );
185
- }
186
- return formattedCol;
187
- }).map((col) => ` ${col}`).join(",\n");
188
- return `CREATE TABLE IF NOT EXISTS "${tableName}" (
189
- ${formattedColumns}
190
- );`;
191
- }
192
- }
193
- if (trimmedStmt.startsWith("create index")) {
194
- const indexMatch = statement.match(CREATE_INDEX_REGEX);
195
- if (indexMatch) {
196
- const [_, indexName] = indexMatch;
197
- rollbackStatements.unshift(`DROP INDEX IF EXISTS "${indexName}"`);
198
- return `CREATE INDEX IF NOT EXISTS "${indexName}" ${statement.substring(statement.toLowerCase().indexOf("on")).trim()};`;
199
- }
200
- }
201
- return `${statement.trim().replace(CREATE_TABLE_KEYWORD_REGEX, "CREATE TABLE").replace(CREATE_INDEX_KEYWORD_REGEX, "CREATE INDEX").replace(ALTER_TABLE_REGEX, "ALTER TABLE").replace(INSERT_INTO_REGEX, "INSERT INTO").replace(UPDATE_REGEX, "UPDATE").replace(DELETE_FROM_REGEX, "DELETE FROM").replace(SELECT_REGEX, "SELECT").replace(FROM_REGEX, "FROM").replace(WHERE_REGEX, "WHERE").replace(JOIN_REGEX, "JOIN").replace(ON_REGEX, "ON").replace(AND_REGEX, "AND").replace(OR_REGEX, "OR")};`;
202
- }).join("\n\n");
203
- const useTransactions = dbType !== "d1";
204
- let transactionStart = "";
205
- if (useTransactions) {
206
- if (dbType === "mysql") {
207
- transactionStart = "START TRANSACTION;";
208
- } else {
209
- transactionStart = "BEGIN;";
210
- }
211
- }
212
- const transactionEnd = useTransactions ? "COMMIT;" : "";
213
- const timestamp = options?.timestamp || (/* @__PURE__ */ new Date()).toISOString();
214
- return `-- Migration generated by C15T (${timestamp})
148
+ function formatSQL(sql, databaseType = 'sqlite', options) {
149
+ const dbType = 'pg' === databaseType ? 'postgresql' : databaseType;
150
+ const statements = sql.split(';').filter((stmt)=>stmt.trim());
151
+ const rollbackStatements = [];
152
+ const formattedStatements = statements.map((statement)=>{
153
+ const trimmedStmt = statement.trim().toLowerCase();
154
+ if (trimmedStmt.startsWith('create table')) {
155
+ const match = statement.match(CREATE_TABLE_REGEX);
156
+ if (match) {
157
+ const [_, tableName, columnsStr] = match;
158
+ if (!columnsStr) return `${statement.trim()};`;
159
+ rollbackStatements.unshift(`DROP TABLE IF EXISTS "${tableName}"`);
160
+ const columns = columnsStr.split(',').map((col)=>col.trim());
161
+ const formattedColumns = columns.map((col)=>{
162
+ let formattedCol = col.replace(NOT_NULL_REGEX, 'NOT NULL').replace(PRIMARY_KEY_REGEX, 'PRIMARY KEY').replace(REFERENCES_REGEX, 'REFERENCES').replace(UNIQUE_REGEX, 'UNIQUE');
163
+ if ('postgresql' === dbType) formattedCol = formattedCol.replace(BOOLEAN_FIELD_REGEX, '$1 boolean').replace(DATE_FIELD_REGEX, '$1 timestamp with time zone').replace(TEXT_FIELD_REGEX, '$1 varchar(255)').replace(JSON_FIELD_REGEX, '$1 jsonb');
164
+ else if ('mysql' === dbType) formattedCol = formattedCol.replace(BOOLEAN_FIELD_REGEX, '$1 TINYINT(1)').replace(DATE_FIELD_REGEX, '$1 DATETIME').replace(TEXT_FIELD_REGEX, '$1 VARCHAR(255)').replace(JSON_FIELD_REGEX, '$1 JSON');
165
+ else if ('sqlite' === dbType) formattedCol = formattedCol.replace(JSON_FIELD_REGEX, '$1 text -- stored as JSON');
166
+ return formattedCol;
167
+ }).map((col)=>` ${col}`).join(',\n');
168
+ return `CREATE TABLE IF NOT EXISTS "${tableName}" (\n${formattedColumns}\n);`;
169
+ }
170
+ }
171
+ if (trimmedStmt.startsWith('create index')) {
172
+ const indexMatch = statement.match(CREATE_INDEX_REGEX);
173
+ if (indexMatch) {
174
+ const [_, indexName] = indexMatch;
175
+ rollbackStatements.unshift(`DROP INDEX IF EXISTS "${indexName}"`);
176
+ return `CREATE INDEX IF NOT EXISTS "${indexName}" ${statement.substring(statement.toLowerCase().indexOf('on')).trim()};`;
177
+ }
178
+ }
179
+ return `${statement.trim().replace(CREATE_TABLE_KEYWORD_REGEX, 'CREATE TABLE').replace(CREATE_INDEX_KEYWORD_REGEX, 'CREATE INDEX').replace(ALTER_TABLE_REGEX, 'ALTER TABLE').replace(INSERT_INTO_REGEX, 'INSERT INTO').replace(UPDATE_REGEX, 'UPDATE').replace(DELETE_FROM_REGEX, 'DELETE FROM').replace(SELECT_REGEX, 'SELECT').replace(FROM_REGEX, 'FROM').replace(WHERE_REGEX, 'WHERE').replace(JOIN_REGEX, 'JOIN').replace(ON_REGEX, 'ON').replace(AND_REGEX, 'AND').replace(OR_REGEX, 'OR')};`;
180
+ }).join('\n\n');
181
+ const useTransactions = 'd1' !== dbType;
182
+ let transactionStart = '';
183
+ if (useTransactions) transactionStart = 'mysql' === dbType ? 'START TRANSACTION;' : 'BEGIN;';
184
+ const transactionEnd = useTransactions ? 'COMMIT;' : '';
185
+ const timestamp = options?.timestamp || new Date().toISOString();
186
+ return `-- Migration generated by C15T (${timestamp})
215
187
  -- Database type: ${dbType}
216
188
  -- Description: Automatically generated schema migration
217
189
  --
@@ -228,609 +200,453 @@ ${transactionEnd}
228
200
  /*
229
201
  ${transactionStart}
230
202
 
231
- ${rollbackStatements.join(";\n\n")};
232
-
203
+ ${rollbackStatements.join(';\n\n')};\n
233
204
  ${transactionEnd}
234
205
  */`;
235
206
  }
236
- const generateMigrations = async ({
237
- options,
238
- file,
239
- adapter
240
- }) => {
241
- const { compileMigrations } = await getMigrations(options);
242
- const migrations = await compileMigrations();
243
- let databaseType = "sqlite";
244
- if (adapter?.options?.provider) {
245
- databaseType = adapter.options.provider;
246
- } else if (options.database && "options" in options.database && options.database.options && typeof options.database.options === "object" && "provider" in options.database.options) {
247
- databaseType = options.database.options.provider;
248
- }
249
- const isTest = process.env.NODE_ENV === "test" || file?.includes("test");
250
- const testTimestamp = options?._testTimestamp;
251
- const formatOptions = {
252
- timestamp: testTimestamp || (isTest ? "2023-01-01T00:00:00.000Z" : void 0)
253
- };
254
- const formattedMigrations = formatSQL(
255
- migrations,
256
- databaseType,
257
- formatOptions
258
- );
259
- const generatedFileName = file || `./c15t_migrations/${Date.now()}_create_tables.sql`;
260
- return {
261
- code: formattedMigrations,
262
- fileName: generatedFileName
263
- };
207
+ const generateMigrations = async ({ options, file, adapter })=>{
208
+ const { compileMigrations } = await (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_migrations_80b6e3bd__.getMigrations)(options);
209
+ const migrations = await compileMigrations();
210
+ let databaseType = 'sqlite';
211
+ if (adapter?.options?.provider) databaseType = adapter.options.provider;
212
+ else {
213
+ const dbOptions = options.database?.options;
214
+ if (dbOptions?.provider) databaseType = dbOptions.provider;
215
+ }
216
+ const isTest = 'test' === process.env.NODE_ENV || file?.includes('test');
217
+ const testTimestamp = options?._testTimestamp;
218
+ const formatOptions = {
219
+ timestamp: testTimestamp || (isTest ? '2023-01-01T00:00:00.000Z' : void 0)
220
+ };
221
+ const formattedMigrations = formatSQL(migrations, databaseType, formatOptions);
222
+ const generatedFileName = file || `./c15t_migrations/${Date.now()}_create_tables.sql`;
223
+ return {
224
+ code: formattedMigrations,
225
+ fileName: generatedFileName
226
+ };
264
227
  };
265
-
266
228
  function capitalizeFirstLetter(str) {
267
- return str.charAt(0).toUpperCase() + str.slice(1);
229
+ return str.charAt(0).toUpperCase() + str.slice(1);
268
230
  }
269
-
270
- const generatePrismaSchema = async ({
271
- adapter,
272
- options,
273
- file
274
- }) => {
275
- const provider = adapter.options?.provider || "postgresql";
276
- const tables = getConsentTables(options);
277
- const filePath = file || "./prisma/schema.prisma";
278
- const schemaPrismaExist = existsSync(path.join(process.cwd(), filePath));
279
- let schemaPrisma = "";
280
- if (schemaPrismaExist) {
281
- schemaPrisma = await fs.readFile(
282
- path.join(process.cwd(), filePath),
283
- "utf-8"
284
- );
285
- } else {
286
- schemaPrisma = getNewPrisma(provider);
287
- }
288
- const manyToManyRelations = /* @__PURE__ */ new Map();
289
- for (const table in tables) {
290
- if (Object.hasOwn(tables, table)) {
291
- const fields = tables[table]?.fields;
292
- for (const field in fields) {
293
- if (Object.hasOwn(fields, field)) {
294
- const attr = fields[field];
295
- if (attr?.references) {
296
- const referencedModel = capitalizeFirstLetter(
297
- attr.references.model
298
- );
299
- if (!manyToManyRelations.has(referencedModel)) {
300
- manyToManyRelations.set(referencedModel, /* @__PURE__ */ new Set());
231
+ const generatePrismaSchema = async ({ adapter, options, file })=>{
232
+ const provider = adapter.options?.provider || 'postgresql';
233
+ const tables = (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_schema_4fae43f5__.getConsentTables)(options);
234
+ const filePath = file || './prisma/schema.prisma';
235
+ const schemaPrismaExist = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), filePath));
236
+ let schemaPrisma = '';
237
+ schemaPrisma = schemaPrismaExist ? await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].readFile(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), filePath), 'utf-8') : getNewPrisma(provider);
238
+ const manyToManyRelations = new Map();
239
+ for(const table in tables)if (Object.hasOwn(tables, table)) {
240
+ const fields = tables[table]?.fields;
241
+ for(const field in fields)if (Object.hasOwn(fields, field)) {
242
+ const attr = fields[field];
243
+ if (attr?.references) {
244
+ const referencedModel = capitalizeFirstLetter(attr.references.model);
245
+ if (!manyToManyRelations.has(referencedModel)) manyToManyRelations.set(referencedModel, new Set());
246
+ manyToManyRelations.get(referencedModel)?.add(capitalizeFirstLetter(table));
301
247
  }
302
- manyToManyRelations.get(referencedModel).add(capitalizeFirstLetter(table));
303
- }
304
248
  }
305
- }
306
249
  }
307
- }
308
- const schema = produceSchema(schemaPrisma, (builder) => {
309
- function getPrismaType(type, isOptional, isBigint) {
310
- const isJsonField = type === "json" || type === "jsonb";
311
- if (isJsonField) {
312
- if (provider === "postgresql" || provider === "mysql") {
313
- return isOptional ? "Json?" : "Json";
314
- }
315
- return isOptional ? "String?" : 'String @map("json_as_text")';
316
- }
317
- if (type === "string") {
318
- return isOptional ? "String?" : "String";
319
- }
320
- if (type === "number" && isBigint) {
321
- return isOptional ? "BigInt?" : "BigInt";
322
- }
323
- if (type === "number") {
324
- return isOptional ? "Int?" : "Int";
325
- }
326
- if (type === "boolean") {
327
- return isOptional ? "Boolean?" : "Boolean";
328
- }
329
- if (type === "date") {
330
- return isOptional ? "DateTime?" : "DateTime";
331
- }
332
- if (type === "string[]") {
333
- return "String[]";
334
- }
335
- if (type === "number[]") {
336
- return "Int[]";
337
- }
338
- return "String";
339
- }
340
- for (const table in tables) {
341
- if (Object.hasOwn(tables, table)) {
342
- const fields = tables[table]?.fields;
343
- const originalTable = tables[table]?.modelName;
344
- const modelName = capitalizeFirstLetter(originalTable || table);
345
- const prismaModel = builder.findByType("model", { name: modelName });
346
- if (!prismaModel) {
347
- if (provider === "mongodb") {
348
- builder.model(modelName).field("id", "String").attribute("id").attribute(`map("_id")`);
349
- } else {
350
- builder.model(modelName).field("id", "String").attribute("id");
351
- }
250
+ const schema = (0, __WEBPACK_EXTERNAL_MODULE__mrleebo_prisma_ast_c5b328aa__.produceSchema)(schemaPrisma, (builder)=>{
251
+ function getPrismaType(type, isOptional, isBigint) {
252
+ const isJsonField = 'json' === type || 'jsonb' === type;
253
+ if (isJsonField) {
254
+ if ('postgresql' === provider || 'mysql' === provider) return isOptional ? 'Json?' : 'Json';
255
+ return isOptional ? 'String?' : 'String @map("json_as_text")';
256
+ }
257
+ if ('string' === type) return isOptional ? 'String?' : 'String';
258
+ if ('number' === type && isBigint) return isOptional ? 'BigInt?' : 'BigInt';
259
+ if ('number' === type) return isOptional ? 'Int?' : 'Int';
260
+ if ('boolean' === type) return isOptional ? 'Boolean?' : 'Boolean';
261
+ if ('date' === type) return isOptional ? 'DateTime?' : 'DateTime';
262
+ if ('string[]' === type) return 'String[]';
263
+ if ('number[]' === type) return 'Int[]';
264
+ return 'String';
352
265
  }
353
- for (const field in fields) {
354
- if (Object.hasOwn(fields, field)) {
355
- const attr = fields[field];
356
- const existingField = builder.findByType("field", {
357
- name: field,
358
- within: prismaModel?.properties
266
+ for(const table in tables)if (Object.hasOwn(tables, table)) {
267
+ const fields = tables[table]?.fields;
268
+ const originalTable = tables[table]?.modelName;
269
+ const modelName = capitalizeFirstLetter(originalTable || table);
270
+ const prismaModel = builder.findByType('model', {
271
+ name: modelName
359
272
  });
360
- if (existingField) {
361
- continue;
273
+ if (!prismaModel) {
274
+ if ('mongodb' === provider) builder.model(modelName).field('id', 'String').attribute('id').attribute('map("_id")');
275
+ else builder.model(modelName).field('id', 'String').attribute('id');
362
276
  }
363
- builder.model(modelName).field(
364
- field,
365
- getPrismaType(attr.type, !attr?.required, attr?.bigint || false)
366
- );
367
- if (attr.unique) {
368
- builder.model(modelName).blockAttribute(`unique([${field}])`);
277
+ for(const field in fields)if (Object.hasOwn(fields, field)) {
278
+ const attr = fields[field];
279
+ const existingField = builder.findByType('field', {
280
+ name: field,
281
+ within: prismaModel?.properties
282
+ });
283
+ if (existingField) continue;
284
+ if (!attr) continue;
285
+ builder.model(modelName).field(field, getPrismaType(attr.type, !attr?.required, attr?.bigint || false));
286
+ if (attr.unique) builder.model(modelName).blockAttribute(`unique([${field}])`);
287
+ if (attr.references) builder.model(modelName).field(`${attr.references.model.toLowerCase()}`, capitalizeFirstLetter(attr.references.model)).attribute(`relation(fields: [${field}], references: [${attr.references.field}], onDelete: Cascade)`);
288
+ if (!attr.unique && !attr.references && 'mysql' === provider && 'string' === attr.type) builder.model(modelName).field(field).attribute('db.Text');
369
289
  }
370
- if (attr.references) {
371
- builder.model(modelName).field(
372
- `${attr.references.model.toLowerCase()}`,
373
- capitalizeFirstLetter(attr.references.model)
374
- ).attribute(
375
- `relation(fields: [${field}], references: [${attr.references.field}], onDelete: Cascade)`
376
- );
290
+ if (originalTable && originalTable !== modelName) {
291
+ const hasMapAttribute = builder.findByType('attribute', {
292
+ name: 'map',
293
+ within: prismaModel?.properties
294
+ });
295
+ if (!hasMapAttribute) builder.model(modelName).blockAttribute('map', originalTable);
377
296
  }
378
- if (!attr.unique && !attr.references && provider === "mysql" && attr.type === "string") {
379
- builder.model(modelName).field(field).attribute("db.Text");
380
- }
381
- }
382
- }
383
- if (originalTable && originalTable !== modelName) {
384
- const hasMapAttribute = builder.findByType("attribute", {
385
- name: "map",
386
- within: prismaModel?.properties
387
- });
388
- if (!hasMapAttribute) {
389
- builder.model(modelName).blockAttribute("map", originalTable);
390
- }
391
297
  }
392
- }
393
- }
394
- for (const [
395
- referencedModel,
396
- relatedModels
397
- ] of manyToManyRelations.entries()) {
398
- for (const relatedModel of relatedModels) {
399
- const fieldName = `${relatedModel.toLowerCase()}s`;
400
- const model = builder.findByType("model", { name: referencedModel });
401
- if (model) {
402
- const existingField = builder.findByType("field", {
403
- name: fieldName,
404
- within: model.properties
405
- });
406
- if (!existingField) {
407
- builder.model(referencedModel).field(fieldName, `${relatedModel}[]`);
408
- }
298
+ for (const [referencedModel, relatedModels] of manyToManyRelations.entries())for (const relatedModel of relatedModels){
299
+ const fieldName = `${relatedModel.toLowerCase()}s`;
300
+ const model = builder.findByType('model', {
301
+ name: referencedModel
302
+ });
303
+ if (model) {
304
+ const existingField = builder.findByType('field', {
305
+ name: fieldName,
306
+ within: model.properties
307
+ });
308
+ if (!existingField) builder.model(referencedModel).field(fieldName, `${relatedModel}[]`);
309
+ }
409
310
  }
410
- }
411
- }
412
- });
413
- return {
414
- code: schema.trim() === schemaPrisma.trim() ? "" : schema,
415
- fileName: filePath
416
- };
311
+ });
312
+ return {
313
+ code: schema.trim() === schemaPrisma.trim() ? '' : schema,
314
+ fileName: filePath
315
+ };
417
316
  };
418
- const getNewPrisma = (provider) => `generator client {
317
+ const getNewPrisma = (provider)=>`generator client {
419
318
  provider = "prisma-client-js"
420
319
  }
421
320
 
422
321
  datasource db {
423
322
  provider = "${provider}"
424
- url = ${provider === "sqlite" ? `"file:./dev.db"` : `env("DATABASE_URL")`}
323
+ url = ${'sqlite' === provider ? '"file:./dev.db"' : 'env("DATABASE_URL")'}
425
324
  }`;
426
-
427
325
  const adapters = {
428
- prisma: generatePrismaSchema,
429
- drizzle: generateDrizzleSchema,
430
- kysely: generateMigrations
326
+ prisma: generatePrismaSchema,
327
+ drizzle: generateDrizzleSchema,
328
+ kysely: generateMigrations
431
329
  };
432
- const getGenerator = (opts) => {
433
- const adapter = opts.adapter;
434
- const generator = adapter.id in adapters ? adapters[adapter.id] : null;
435
- if (!generator) {
436
- logger.error(`${adapter.id} is not supported.`);
437
- process.exit(1);
438
- }
439
- return generator(opts);
330
+ const getGenerator = (opts)=>{
331
+ const adapter = opts.adapter;
332
+ const generator = adapter.id in adapters ? adapters[adapter.id] : null;
333
+ if (!generator) {
334
+ utils_logger.error(`${adapter.id} is not supported.`);
335
+ process.exit(1);
336
+ }
337
+ return generator(opts);
440
338
  };
441
-
442
339
  function addSvelteKitEnvModules(aliases) {
443
- aliases["$env/dynamic/private"] = createDataUriModule(
444
- createDynamicEnvModule()
445
- );
446
- aliases["$env/dynamic/public"] = createDataUriModule(
447
- createDynamicEnvModule()
448
- );
449
- aliases["$env/static/private"] = createDataUriModule(
450
- createStaticEnvModule(filterPrivateEnv("PUBLIC_", ""))
451
- );
452
- aliases["$env/static/public"] = createDataUriModule(
453
- createStaticEnvModule(filterPublicEnv("PUBLIC_", ""))
454
- );
340
+ aliases['$env/dynamic/private'] = createDataUriModule(createDynamicEnvModule());
341
+ aliases['$env/dynamic/public'] = createDataUriModule(createDynamicEnvModule());
342
+ aliases['$env/static/private'] = createDataUriModule(createStaticEnvModule(filterPrivateEnv('PUBLIC_', '')));
343
+ aliases['$env/static/public'] = createDataUriModule(createStaticEnvModule(filterPublicEnv('PUBLIC_', '')));
455
344
  }
456
345
  function createDataUriModule(module) {
457
- return `data:text/javascript;charset=utf-8,${encodeURIComponent(module)}`;
346
+ return `data:text/javascript;charset=utf-8,${encodeURIComponent(module)}`;
458
347
  }
459
348
  function createStaticEnvModule(env) {
460
- const declarations = Object.keys(env).filter((k) => validIdentifier.test(k) && !reserved.has(k)).map((k) => `export const ${k} = ${JSON.stringify(env[k])};`);
461
- return `
462
- ${declarations.join("\n")}
349
+ const declarations = Object.keys(env).filter((k)=>validIdentifier.test(k) && !reserved.has(k)).map((k)=>`export const ${k} = ${JSON.stringify(env[k])};`);
350
+ return `
351
+ ${declarations.join('\n')}
463
352
  // jiti dirty hack: .unknown
464
353
  `;
465
354
  }
466
355
  function createDynamicEnvModule() {
467
- return `
356
+ return `
468
357
  export const env = process.env;
469
358
  // jiti dirty hack: .unknown
470
359
  `;
471
360
  }
472
361
  function filterPrivateEnv(publicPrefix, privatePrefix) {
473
- return Object.fromEntries(
474
- Object.entries(process.env).filter(
475
- ([k]) => k.startsWith(privatePrefix) && (!k.startsWith(publicPrefix))
476
- )
477
- );
362
+ return Object.fromEntries(Object.entries(process.env).filter(([k])=>k.startsWith(privatePrefix) && ('' === publicPrefix || !k.startsWith(publicPrefix))));
478
363
  }
479
364
  function filterPublicEnv(publicPrefix, privatePrefix) {
480
- return Object.fromEntries(
481
- Object.entries(process.env).filter(
482
- ([k]) => k.startsWith(publicPrefix) && (privatePrefix === "")
483
- )
484
- );
365
+ return Object.fromEntries(Object.entries(process.env).filter(([k])=>k.startsWith(publicPrefix) && ('' === privatePrefix || !k.startsWith(privatePrefix))));
485
366
  }
486
367
  const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
487
- const reserved = /* @__PURE__ */ new Set([
488
- "do",
489
- "if",
490
- "in",
491
- "for",
492
- "let",
493
- "new",
494
- "try",
495
- "var",
496
- "case",
497
- "else",
498
- "enum",
499
- "eval",
500
- "null",
501
- "this",
502
- "true",
503
- "void",
504
- "with",
505
- "await",
506
- "break",
507
- "catch",
508
- "class",
509
- "const",
510
- "false",
511
- "super",
512
- "throw",
513
- "while",
514
- "yield",
515
- "delete",
516
- "export",
517
- "import",
518
- "public",
519
- "return",
520
- "static",
521
- "switch",
522
- "typeof",
523
- "default",
524
- "extends",
525
- "finally",
526
- "package",
527
- "private",
528
- "continue",
529
- "debugger",
530
- "function",
531
- "arguments",
532
- "interface",
533
- "protected",
534
- "implements",
535
- "instanceof"
368
+ const reserved = new Set([
369
+ 'do',
370
+ 'if',
371
+ 'in',
372
+ 'for',
373
+ 'let',
374
+ 'new',
375
+ 'try',
376
+ 'var',
377
+ 'case',
378
+ 'else',
379
+ 'enum',
380
+ 'eval',
381
+ 'null',
382
+ 'this',
383
+ 'true',
384
+ 'void',
385
+ 'with',
386
+ 'await',
387
+ 'break',
388
+ 'catch',
389
+ 'class',
390
+ 'const',
391
+ 'false',
392
+ 'super',
393
+ 'throw',
394
+ 'while',
395
+ 'yield',
396
+ 'delete',
397
+ 'export',
398
+ 'import',
399
+ 'public',
400
+ 'return',
401
+ 'static',
402
+ 'switch',
403
+ 'typeof',
404
+ 'default',
405
+ 'extends',
406
+ 'finally',
407
+ 'package',
408
+ 'private',
409
+ 'continue',
410
+ 'debugger',
411
+ 'function',
412
+ 'arguments',
413
+ 'interface',
414
+ 'protected',
415
+ 'implements',
416
+ 'instanceof'
536
417
  ]);
537
-
538
- const configFileNames = ["c15t", "consent", "cmp"];
418
+ const configFileNames = [
419
+ 'c15t',
420
+ 'consent',
421
+ 'cmp'
422
+ ];
539
423
  const extensions = [
540
- ".js",
541
- ".jsx",
542
- ".ts",
543
- ".tsx",
544
- ".cjs",
545
- ".cts",
546
- ".mjs",
547
- ".mts",
548
- ".server.cjs",
549
- ".server.cts",
550
- ".server.js",
551
- ".server.jsx",
552
- ".server.mjs",
553
- ".server.mts",
554
- ".server.ts",
555
- ".server.tsx"
424
+ '.js',
425
+ '.jsx',
426
+ '.ts',
427
+ '.tsx',
428
+ '.cjs',
429
+ '.cts',
430
+ '.mjs',
431
+ '.mts',
432
+ '.server.cjs',
433
+ '.server.cts',
434
+ '.server.js',
435
+ '.server.jsx',
436
+ '.server.mjs',
437
+ '.server.mts',
438
+ '.server.ts',
439
+ '.server.tsx'
556
440
  ];
557
- let possiblePaths = configFileNames.flatMap(
558
- (name) => extensions.map((ext) => `${name}${ext}`)
559
- );
441
+ let possiblePaths = configFileNames.flatMap((name)=>extensions.map((ext)=>`${name}${ext}`));
560
442
  const directories = [
561
- "",
562
- "lib/server/",
563
- "server/",
564
- "lib/",
565
- "utils/",
566
- "config/",
567
- "src/",
568
- "app/"
443
+ '',
444
+ 'lib/server/',
445
+ 'server/',
446
+ 'lib/',
447
+ 'utils/',
448
+ 'config/',
449
+ 'src/',
450
+ 'app/'
451
+ ];
452
+ possiblePaths = directories.flatMap((dir)=>possiblePaths.map((file)=>`${dir}${file}`));
453
+ const monorepoSubdirs = [
454
+ 'packages/*',
455
+ 'apps/*'
569
456
  ];
570
- possiblePaths = directories.flatMap(
571
- (dir) => possiblePaths.map((file) => `${dir}${file}`)
572
- );
573
- const monorepoSubdirs = ["packages/*", "apps/*"];
574
457
  function stripJsonComments(jsonString) {
575
- return jsonString.replace(
576
- /\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g,
577
- (m, g) => g ? "" : m
578
- ).replace(/,(?=\s*[}\]])/g, "");
458
+ return jsonString.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g)=>g ? '' : m).replace(/,(?=\s*[}\]])/g, '');
579
459
  }
580
460
  function getPathAliases(cwd) {
581
- const tsConfigPath = path.join(cwd, "tsconfig.json");
582
- if (!fs$1.existsSync(tsConfigPath)) {
583
- const jsConfigPath = path.join(cwd, "jsconfig.json");
584
- if (!fs$1.existsSync(jsConfigPath)) {
585
- return null;
461
+ const tsConfigPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'tsconfig.json');
462
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(tsConfigPath)) {
463
+ const jsConfigPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, 'jsconfig.json');
464
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(jsConfigPath)) return null;
465
+ return extractAliasesFromConfigFile(jsConfigPath, cwd);
586
466
  }
587
- return extractAliasesFromConfigFile(jsConfigPath, cwd);
588
- }
589
- return extractAliasesFromConfigFile(tsConfigPath, cwd);
467
+ return extractAliasesFromConfigFile(tsConfigPath, cwd);
590
468
  }
591
469
  function extractAliasesFromConfigFile(configPath, cwd) {
592
- try {
593
- const configContent = fs$1.readFileSync(configPath, "utf8");
594
- const strippedConfigContent = stripJsonComments(configContent);
595
- const config = JSON.parse(strippedConfigContent);
596
- const { paths = {}, baseUrl = "." } = config.compilerOptions || {};
597
- const result = {};
598
- const obj = Object.entries(paths);
599
- for (const [alias, aliasPaths] of obj) {
600
- for (const aliasedPath of aliasPaths) {
601
- const resolvedBaseUrl = path.join(cwd, baseUrl);
602
- const finalAlias = alias.slice(-1) === "*" ? alias.slice(0, -1) : alias;
603
- const finalAliasedPath = aliasedPath.slice(-1) === "*" ? aliasedPath.slice(0, -1) : aliasedPath;
604
- result[finalAlias || ""] = path.join(resolvedBaseUrl, finalAliasedPath);
605
- }
470
+ try {
471
+ const configContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(configPath, 'utf8');
472
+ const strippedConfigContent = stripJsonComments(configContent);
473
+ const config = JSON.parse(strippedConfigContent);
474
+ const { paths = {}, baseUrl = '.' } = config.compilerOptions || {};
475
+ const result = {};
476
+ const obj = Object.entries(paths);
477
+ for (const [alias, aliasPaths] of obj)for (const aliasedPath of aliasPaths){
478
+ const resolvedBaseUrl = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, baseUrl);
479
+ const finalAlias = '*' === alias.slice(-1) ? alias.slice(0, -1) : alias;
480
+ const finalAliasedPath = '*' === aliasedPath.slice(-1) ? aliasedPath.slice(0, -1) : aliasedPath;
481
+ result[finalAlias || ''] = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(resolvedBaseUrl, finalAliasedPath);
482
+ }
483
+ addSvelteKitEnvModules(result);
484
+ return result;
485
+ } catch (error) {
486
+ utils_logger.warn(`Error parsing config file ${configPath}`, error);
487
+ return null;
606
488
  }
607
- addSvelteKitEnvModules(result);
608
- return result;
609
- } catch (error) {
610
- logger.warn(`Error parsing config file ${configPath}`, error);
611
- return null;
612
- }
613
489
  }
614
- const jitiOptions = (cwd) => {
615
- const alias = getPathAliases(cwd) || {};
616
- return {
617
- transformOptions: {
618
- babel: {
619
- presets: [
620
- [
621
- babelPresetTypescript,
622
- {
623
- isTSX: true,
624
- allExtensions: true
490
+ const jitiOptions = (cwd)=>{
491
+ const alias = getPathAliases(cwd) || {};
492
+ return {
493
+ transformOptions: {
494
+ babel: {
495
+ presets: [
496
+ [
497
+ __WEBPACK_EXTERNAL_MODULE__babel_preset_typescript_a7789c85__["default"],
498
+ {
499
+ isTSX: true,
500
+ allExtensions: true
501
+ }
502
+ ],
503
+ [
504
+ __WEBPACK_EXTERNAL_MODULE__babel_preset_react_76cf724d__["default"],
505
+ {
506
+ runtime: 'automatic'
507
+ }
508
+ ]
509
+ ]
625
510
  }
626
- ],
627
- [babelPresetReact, { runtime: "automatic" }]
628
- ]
629
- }
630
- },
631
- extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
632
- alias
633
- };
511
+ },
512
+ extensions: [
513
+ '.ts',
514
+ '.tsx',
515
+ '.js',
516
+ '.jsx',
517
+ '.mjs',
518
+ '.cjs',
519
+ '.mts',
520
+ '.cts'
521
+ ],
522
+ alias
523
+ };
634
524
  };
635
525
  function extractOptionsFromConfig(config) {
636
- if (config.c15t && typeof config.c15t === "function") {
637
- return config.c15t;
638
- }
639
- if (config.default && typeof config.default === "function") {
640
- return config.default;
641
- }
642
- if (config.c15tInstance && typeof config.c15tInstance === "function") {
643
- return config.c15tInstance;
644
- }
645
- if (config.consent && typeof config.consent === "function") {
646
- return config.consent;
647
- }
648
- return config.c15t?.options || config.default?.options || config.c15tInstance?.options || config.instance?.options || config.consent?.options || config.config?.options || // Also check for direct exports of options objects
649
- (config.default && typeof config.default === "object" && "appName" in config.default ? config.default : null) || // Finally check for direct exports of the instance
650
- (config.c15t && typeof config.c15t === "object" && "appName" in config.c15t ? config.c15t : null) || null;
526
+ if (config.c15t && 'function' == typeof config.c15t) return config.c15t;
527
+ if (config.default && 'function' == typeof config.default) return config.default;
528
+ if (config.c15tInstance && 'function' == typeof config.c15tInstance) return config.c15tInstance;
529
+ if (config.consent && 'function' == typeof config.consent) return config.consent;
530
+ return config.c15t?.options || config.default?.options || config.c15tInstance?.options || config.instance?.options || config.consent?.options || config.config?.options || (config.default && 'object' == typeof config.default && 'appName' in config.default ? config.default : null) || (config.c15t && 'object' == typeof config.c15t && 'appName' in config.c15t ? config.c15t : null) || null;
651
531
  }
652
532
  function findDirectories(cwd, patterns) {
653
- const results = [];
654
- for (const pattern of patterns) {
655
- if (pattern.includes("*")) {
656
- const [prefix, _] = pattern.split("*");
657
- const basePath = path.join(cwd, prefix);
658
- try {
659
- if (fs$1.existsSync(basePath)) {
660
- const entries = fs$1.readdirSync(basePath, { withFileTypes: true });
661
- for (const entry of entries) {
662
- if (entry.isDirectory()) {
663
- results.push(path.join(prefix, entry.name));
664
- }
665
- }
533
+ const results = [];
534
+ for (const pattern of patterns)if (pattern.includes('*')) {
535
+ const [prefix] = pattern.split('*');
536
+ if (prefix) {
537
+ const basePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, prefix);
538
+ try {
539
+ if (__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(basePath)) {
540
+ const entries = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readdirSync(basePath, {
541
+ withFileTypes: true
542
+ });
543
+ for (const entry of entries)if (entry.isDirectory()) results.push(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(prefix, entry.name));
544
+ }
545
+ } catch {}
666
546
  }
667
- } catch {
668
- }
669
- } else if (fs$1.existsSync(path.join(cwd, pattern)) && fs$1.statSync(path.join(cwd, pattern)).isDirectory()) {
670
- results.push(pattern);
671
- }
672
- }
673
- return results;
547
+ } else if (__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, pattern)) && __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].statSync(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, pattern)).isDirectory()) results.push(pattern);
548
+ return results;
674
549
  }
675
550
  function validateConfig(config) {
676
- if (!config) {
677
- return false;
678
- }
679
- return typeof config === "object";
551
+ if (!config) return false;
552
+ return 'object' == typeof config;
680
553
  }
681
- async function getConfig({
682
- cwd,
683
- configPath
684
- }) {
685
- const foundPaths = [];
686
- const failedImports = [];
687
- try {
688
- let configFile = null;
689
- if (configPath) {
690
- const resolvedPath = path.join(cwd, configPath);
691
- try {
692
- if (!fs$1.existsSync(resolvedPath)) {
693
- throw new DoubleTieError(
694
- `Configuration file not found: ${resolvedPath}
695
- Make sure the path is correct and the file exists.`,
696
- {
697
- code: "CONFIG_FILE_NOT_FOUND",
698
- status: 404,
699
- category: "CONFIG_FILE_NOT_FOUND"
554
+ async function getConfig({ cwd, configPath }) {
555
+ const foundPaths = [];
556
+ const failedImports = [];
557
+ try {
558
+ let configFile = null;
559
+ if (configPath) {
560
+ const resolvedPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, configPath);
561
+ try {
562
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(resolvedPath)) throw new __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError(`Configuration file not found: ${resolvedPath}\nMake sure the path is correct and the file exists.`, {
563
+ code: 'CONFIG_FILE_NOT_FOUND',
564
+ status: 404,
565
+ category: 'CONFIG_FILE_NOT_FOUND'
566
+ });
567
+ foundPaths.push(resolvedPath);
568
+ const { config } = await (0, __WEBPACK_EXTERNAL_MODULE_c12__.loadConfig)({
569
+ configFile: resolvedPath,
570
+ dotenv: true,
571
+ jitiOptions: jitiOptions(cwd)
572
+ });
573
+ configFile = extractOptionsFromConfig(config);
574
+ if (!configFile) throw new __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError(`Found config file at ${resolvedPath} but couldn't extract c15t options.\nMake sure you're exporting c15t with one of these patterns:\n- export const c15t = c15tInstance({...})\n- export const consent = c15tInstance({...})\n- export const c15tInstance = c15tInstance({...})\n- export default c15tInstance({...})`, {
575
+ code: 'CONFIG_FILE_LOAD_ERROR',
576
+ status: 500,
577
+ category: 'CONFIG_FILE_LOAD_ERROR'
578
+ });
579
+ } catch (e) {
580
+ if (__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(resolvedPath)) {
581
+ failedImports.push(resolvedPath);
582
+ if (e instanceof __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError) throw e;
583
+ throw new __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError(`Config file found at ${resolvedPath} but failed to load.\nThis usually happens because of import problems:\n- Check for invalid import paths\n- Ensure all dependencies are installed\n- Verify path aliases in tsconfig.json\n\nError details: ${e instanceof Error ? e.message : String(e)}`, {
584
+ code: 'CONFIG_FILE_LOAD_ERROR',
585
+ status: 500,
586
+ category: 'CONFIG_FILE_LOAD_ERROR',
587
+ cause: e instanceof Error ? e : new Error(String(e))
588
+ });
589
+ }
590
+ throw e;
700
591
  }
701
- );
702
592
  }
703
- foundPaths.push(resolvedPath);
704
- const { config } = await loadConfig({
705
- configFile: resolvedPath,
706
- dotenv: true,
707
- jitiOptions: jitiOptions(cwd)
708
- });
709
- configFile = extractOptionsFromConfig(config);
710
593
  if (!configFile) {
711
- throw new DoubleTieError(
712
- // biome-ignore lint/style/useTemplate: keep it split so its easier to read
713
- `Found config file at ${resolvedPath} but couldn't extract c15t options.
714
- Make sure you're exporting c15t with one of these patterns:
715
- - export const c15t = c15tInstance({...})
716
- - export const consent = c15tInstance({...})
717
- - export const c15tInstance = c15tInstance({...})
718
- - export default c15tInstance({...})`,
719
- {
720
- code: "CONFIG_FILE_LOAD_ERROR",
721
- status: 500,
722
- category: "CONFIG_FILE_LOAD_ERROR"
723
- }
724
- );
725
- }
726
- } catch (e) {
727
- if (fs$1.existsSync(resolvedPath)) {
728
- failedImports.push(resolvedPath);
729
- if (e instanceof DoubleTieError) {
730
- throw e;
731
- }
732
- throw new DoubleTieError(
733
- // biome-ignore lint/style/useTemplate: keep it split so its easier to read
734
- `Config file found at ${resolvedPath} but failed to load.
735
- This usually happens because of import problems:
736
- - Check for invalid import paths
737
- - Ensure all dependencies are installed
738
- - Verify path aliases in tsconfig.json
739
-
740
- Error details: ${e instanceof Error ? e.message : String(e)}`,
741
- {
742
- code: "CONFIG_FILE_LOAD_ERROR",
743
- status: 500,
744
- category: "CONFIG_FILE_LOAD_ERROR",
745
- cause: e
594
+ const searchDirs = [
595
+ ''
596
+ ];
597
+ searchDirs.push(...findDirectories(cwd, monorepoSubdirs));
598
+ for (const dir of searchDirs){
599
+ for (const possiblePath of possiblePaths){
600
+ const configPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dir, possiblePath);
601
+ const fullPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, configPath);
602
+ if (!!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(fullPath)) {
603
+ foundPaths.push(fullPath);
604
+ try {
605
+ const { config } = await (0, __WEBPACK_EXTERNAL_MODULE_c12__.loadConfig)({
606
+ configFile: configPath,
607
+ jitiOptions: jitiOptions(cwd)
608
+ });
609
+ if (Object.keys(config).length > 0) {
610
+ configFile = extractOptionsFromConfig(config);
611
+ if (configFile && validateConfig(configFile)) {
612
+ utils_logger.info(`✅ Using c15t config from ${fullPath}`);
613
+ break;
614
+ }
615
+ }
616
+ } catch (e) {
617
+ if ('object' == typeof e && e && 'message' in e && 'string' == typeof e.message && e.message.includes('This module cannot be imported from a Client Component module')) throw new __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError(`Found config file at ${fullPath}, but it imports 'server-only'.\nPlease temporarily remove the 'server-only' import while using the CLI,\nand you can add it back afterwards.`, {
618
+ code: 'SERVER_ONLY_IMPORT_DETECTED',
619
+ status: 500,
620
+ category: 'SERVER_ONLY_IMPORT_DETECTED'
621
+ });
622
+ failedImports.push(fullPath);
623
+ }
624
+ }
625
+ }
626
+ if (configFile) break;
746
627
  }
747
- );
748
628
  }
749
- throw e;
750
- }
751
- }
752
- if (!configFile) {
753
- const searchDirs = [""];
754
- searchDirs.push(...findDirectories(cwd, monorepoSubdirs));
755
- for (const dir of searchDirs) {
756
- for (const possiblePath of possiblePaths) {
757
- const configPath2 = path.join(dir, possiblePath);
758
- const fullPath = path.join(cwd, configPath2);
759
- if (!fs$1.existsSync(fullPath)) {
760
- continue;
761
- }
762
- foundPaths.push(fullPath);
763
- try {
764
- const { config } = await loadConfig({
765
- configFile: configPath2,
766
- jitiOptions: jitiOptions(cwd)
767
- });
768
- if (Object.keys(config).length > 0) {
769
- configFile = extractOptionsFromConfig(config);
770
- if (configFile && validateConfig(configFile)) {
771
- logger.info(`\u2705 Using c15t config from ${fullPath}`);
772
- break;
773
- }
774
- }
775
- } catch (e) {
776
- if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
777
- "This module cannot be imported from a Client Component module"
778
- )) {
779
- throw new DoubleTieError(
780
- // biome-ignore lint/style/useTemplate: keep it split so its easier to read
781
- `Found config file at ${fullPath}, but it imports 'server-only'.
782
- Please temporarily remove the 'server-only' import while using the CLI,
783
- and you can add it back afterwards.`,
784
- {
785
- code: "SERVER_ONLY_IMPORT_DETECTED",
786
- status: 500,
787
- category: "SERVER_ONLY_IMPORT_DETECTED"
629
+ if (!configFile) {
630
+ if (foundPaths.length > 0) {
631
+ utils_logger.error(`❌ Found ${foundPaths.length} potential config files, but couldn't load any of them:`);
632
+ for (const filePath of foundPaths.slice(0, 3))utils_logger.error(` - ${filePath}`);
633
+ if (foundPaths.length > 3) utils_logger.error(` - ...and ${foundPaths.length - 3} more`);
634
+ if (failedImports.length > 0) {
635
+ utils_logger.error('\n❓ Common issues that prevent loading config files:');
636
+ utils_logger.error(' - Missing dependencies (check your package.json)');
637
+ utils_logger.error(' - Import path issues (check your import statements)');
638
+ utils_logger.error(' - Path alias configuration (check your tsconfig.json)');
639
+ utils_logger.error(" - Export format (make sure you're exporting c15t, c15tInstance, consent, or default)");
788
640
  }
789
- );
641
+ throw new __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError('Unable to load any c15t configuration file', {
642
+ code: 'CONFIG_FILE_LOAD_ERROR',
643
+ status: 500,
644
+ category: 'CONFIG_FILE_LOAD_ERROR'
645
+ });
790
646
  }
791
- failedImports.push(fullPath);
792
- }
793
- }
794
- if (configFile) {
795
- break;
796
- }
797
- }
798
- }
799
- if (!configFile) {
800
- if (foundPaths.length > 0) {
801
- logger.error(
802
- `\u274C Found ${foundPaths.length} potential config files, but couldn't load any of them:`
803
- );
804
- for (const filePath of foundPaths.slice(0, 3)) {
805
- logger.error(` - ${filePath}`);
806
- }
807
- if (foundPaths.length > 3) {
808
- logger.error(` - ...and ${foundPaths.length - 3} more`);
809
- }
810
- if (failedImports.length > 0) {
811
- logger.error("\n\u2753 Common issues that prevent loading config files:");
812
- logger.error(" - Missing dependencies (check your package.json)");
813
- logger.error(
814
- " - Import path issues (check your import statements)"
815
- );
816
- logger.error(
817
- " - Path alias configuration (check your tsconfig.json)"
818
- );
819
- logger.error(
820
- " - Export format (make sure you're exporting c15t, c15tInstance, consent, or default)"
821
- );
822
- }
823
- throw new DoubleTieError("Unable to load any c15t configuration file", {
824
- code: "CONFIG_FILE_LOAD_ERROR",
825
- status: 500,
826
- category: "CONFIG_FILE_LOAD_ERROR"
827
- });
828
- }
829
- logger.error(
830
- "\u274C No c15t configuration files found in standard locations"
831
- );
832
- logger.info("\n\u{1F4DD} Create a c15t.ts file with your configuration:");
833
- logger.info(`
647
+ utils_logger.error('❌ No c15t configuration files found in standard locations');
648
+ utils_logger.info('\n📝 Create a c15t.ts file with your configuration:');
649
+ utils_logger.info(`
834
650
  import { c15tInstance } from '@c15t/backend';
835
651
 
836
652
  export const c15t = c15tInstance({
@@ -839,264 +655,205 @@ export const c15t = c15tInstance({
839
655
  // Add your configuration here
840
656
  });
841
657
  `);
842
- throw new DoubleTieError(
843
- "No c15t config file found. Create a c15t.ts file or specify with --config",
844
- {
845
- code: "CONFIG_FILE_NOT_FOUND",
846
- status: 404,
847
- category: "CONFIG_FILE_NOT_FOUND"
658
+ throw new __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError('No c15t config file found. Create a c15t.ts file or specify with --config', {
659
+ code: 'CONFIG_FILE_NOT_FOUND',
660
+ status: 404,
661
+ category: 'CONFIG_FILE_NOT_FOUND'
662
+ });
663
+ }
664
+ return configFile;
665
+ } catch (e) {
666
+ if ('object' == typeof e && e && 'message' in e && 'string' == typeof e.message && e.message.includes('This module cannot be imported from a Client Component module')) {
667
+ utils_logger.error("❌ Server-only import detected in config file\nPlease temporarily remove the 'server-only' import while using the CLI,\nand you can add it back afterwards.");
668
+ process.exit(1);
669
+ }
670
+ if (e instanceof __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_results_3ca2b89f__.DoubleTieError) utils_logger.error(`❌ ${e.message}`);
671
+ else if (e instanceof Error) {
672
+ utils_logger.error(`❌ Couldn't read your c15t configuration`);
673
+ utils_logger.error(` Error: ${e.message}`);
674
+ } else {
675
+ utils_logger.error(`❌ Couldn't read your c15t configuration`);
676
+ utils_logger.error(` Error: ${String(e)}`);
848
677
  }
849
- );
678
+ if (failedImports.length > 0) {
679
+ utils_logger.info("\n💡 Tip: If you're having import issues, try running with verbose logging:");
680
+ utils_logger.info(' DEBUG=c15t* npx c15t@latest <command>');
681
+ }
682
+ process.exit(1);
850
683
  }
851
- return configFile;
852
- } catch (e) {
853
- if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
854
- "This module cannot be imported from a Client Component module"
855
- )) {
856
- logger.error(
857
- "\u274C Server-only import detected in config file\nPlease temporarily remove the 'server-only' import while using the CLI,\nand you can add it back afterwards."
858
- );
859
- process.exit(1);
684
+ }
685
+ async function generateAction(opts) {
686
+ const options = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
687
+ cwd: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
688
+ config: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
689
+ output: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
690
+ y: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional()
691
+ }).parse(opts);
692
+ const cwd = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(options.cwd);
693
+ if (!(0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(cwd)) {
694
+ utils_logger.error(`The directory "${cwd}" does not exist.`);
695
+ process.exit(1);
860
696
  }
861
- if (e instanceof DoubleTieError) {
862
- logger.error(`\u274C ${e.message}`);
863
- } else {
864
- logger.error(`\u274C Couldn't read your c15t configuration`);
865
- logger.error(` Error: ${e instanceof Error ? e.message : String(e)}`);
697
+ const config = await getConfig({
698
+ cwd,
699
+ configPath: options.config
700
+ });
701
+ if (!config) {
702
+ utils_logger.error('No configuration file found. Add a `c15t.ts` file to your project or pass the path to the configuration file using the `--config` flag.');
703
+ return;
866
704
  }
867
- if (failedImports.length > 0) {
868
- logger.info(
869
- "\n\u{1F4A1} Tip: If you're having import issues, try running with verbose logging:"
870
- );
871
- logger.info(" DEBUG=c15t* npx c15t@latest <command>");
705
+ const adapter = await (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_db_adapters_cee37d0f__.getAdapter)(config).catch((e)=>{
706
+ utils_logger.error(e.message);
707
+ process.exit(1);
708
+ });
709
+ const spinner = (0, __WEBPACK_EXTERNAL_MODULE_yocto_spinner_579f0326__["default"])({
710
+ text: 'preparing schema...'
711
+ }).start();
712
+ const schema = await getGenerator({
713
+ adapter,
714
+ file: options.output,
715
+ options: config
716
+ });
717
+ spinner.stop();
718
+ if (!schema.code) {
719
+ utils_logger.info('Your schema is already up to date.');
720
+ process.exit(0);
872
721
  }
873
- process.exit(1);
874
- }
875
- }
876
-
877
- async function generateAction(opts) {
878
- const options = z.object({
879
- cwd: z.string(),
880
- config: z.string().optional(),
881
- output: z.string().optional(),
882
- y: z.boolean().optional()
883
- }).parse(opts);
884
- const cwd = path.resolve(options.cwd);
885
- if (!existsSync(cwd)) {
886
- logger.error(`The directory "${cwd}" does not exist.`);
887
- process.exit(1);
888
- }
889
- const config = await getConfig({
890
- cwd,
891
- configPath: options.config
892
- });
893
- if (!config) {
894
- logger.error(
895
- "No configuration file found. Add a `c15t.ts` file to your project or pass the path to the configuration file using the `--config` flag."
896
- );
897
- return;
898
- }
899
- const adapter = await getAdapter(config).catch((e) => {
900
- logger.error(e.message);
901
- process.exit(1);
902
- });
903
- const spinner = yoctoSpinner({ text: "preparing schema..." }).start();
904
- const schema = await getGenerator({
905
- adapter,
906
- file: options.output,
907
- options: config
908
- });
909
- spinner.stop();
910
- if (!schema.code) {
911
- logger.info("Your schema is already up to date.");
912
- process.exit(0);
913
- }
914
- if (schema.append || schema.overwrite) {
915
- let confirm2 = options.y;
916
- if (!confirm2) {
917
- const response = await prompts({
918
- type: "confirm",
919
- name: "confirm",
920
- message: `The file ${schema.fileName} already exists. Do you want to ${chalk.yellow(
921
- `${schema.overwrite ? "overwrite" : "append"}`
922
- )} the schema to the file?`
923
- });
924
- confirm2 = response.confirm;
722
+ if (schema.append || schema.overwrite) {
723
+ let confirm = options.y;
724
+ if (!confirm) {
725
+ const response = await (0, __WEBPACK_EXTERNAL_MODULE_prompts__["default"])({
726
+ type: 'confirm',
727
+ name: 'confirm',
728
+ message: `The file ${schema.fileName} already exists. Do you want to ${__WEBPACK_EXTERNAL_MODULE_chalk__["default"].yellow(`${schema.overwrite ? 'overwrite' : 'append'}`)} the schema to the file?`
729
+ });
730
+ confirm = response.confirm;
731
+ }
732
+ if (confirm) {
733
+ const exist = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName));
734
+ if (!exist) await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName)), {
735
+ recursive: true
736
+ });
737
+ if (schema.overwrite) await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName), schema.code);
738
+ else await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].appendFile(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName), schema.code);
739
+ utils_logger.success(`🚀 Schema was ${schema.overwrite ? 'overwritten' : 'appended'} successfully!`);
740
+ process.exit(0);
741
+ } else {
742
+ utils_logger.error('Schema generation aborted.');
743
+ process.exit(1);
744
+ }
925
745
  }
926
- if (confirm2) {
927
- const exist = existsSync(path.join(cwd, schema.fileName));
928
- if (!exist) {
929
- await fs.mkdir(path.dirname(path.join(cwd, schema.fileName)), {
930
- recursive: true
746
+ let confirm = options.y;
747
+ if (!confirm) {
748
+ const response = await (0, __WEBPACK_EXTERNAL_MODULE_prompts__["default"])({
749
+ type: 'confirm',
750
+ name: 'confirm',
751
+ message: `Do you want to generate the schema to ${__WEBPACK_EXTERNAL_MODULE_chalk__["default"].yellow(schema.fileName)}?`
931
752
  });
932
- }
933
- if (schema.overwrite) {
934
- await fs.writeFile(path.join(cwd, schema.fileName), schema.code);
935
- } else {
936
- await fs.appendFile(path.join(cwd, schema.fileName), schema.code);
937
- }
938
- logger.success(
939
- `\u{1F680} Schema was ${schema.overwrite ? "overwritten" : "appended"} successfully!`
940
- );
941
- process.exit(0);
942
- } else {
943
- logger.error("Schema generation aborted.");
944
- process.exit(1);
753
+ confirm = response.confirm;
945
754
  }
946
- }
947
- let confirm = options.y;
948
- if (!confirm) {
949
- const response = await prompts({
950
- type: "confirm",
951
- name: "confirm",
952
- message: `Do you want to generate the schema to ${chalk.yellow(
953
- schema.fileName
954
- )}?`
955
- });
956
- confirm = response.confirm;
957
- }
958
- if (!confirm) {
959
- logger.error("Schema generation aborted.");
960
- process.exit(1);
961
- }
962
- if (!options.output) {
963
- const dirExist = existsSync(path.dirname(path.join(cwd, schema.fileName)));
964
- if (!dirExist) {
965
- await fs.mkdir(path.dirname(path.join(cwd, schema.fileName)), {
966
- recursive: true
967
- });
755
+ if (!confirm) {
756
+ utils_logger.error('Schema generation aborted.');
757
+ process.exit(1);
968
758
  }
969
- }
970
- await fs.writeFile(
971
- options.output || path.join(cwd, schema.fileName),
972
- schema.code
973
- );
974
- logger.success("\u{1F680} Schema was generated successfully!");
975
- process.exit(0);
759
+ if (!options.output) {
760
+ const dirExist = (0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName)));
761
+ if (!dirExist) await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].mkdir(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName)), {
762
+ recursive: true
763
+ });
764
+ }
765
+ await __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__["default"].writeFile(options.output || __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cwd, schema.fileName), schema.code);
766
+ utils_logger.success('🚀 Schema was generated successfully!');
767
+ process.exit(0);
976
768
  }
977
- const generate = new Command("generate").option(
978
- "-c, --cwd <cwd>",
979
- "the working directory. defaults to the current directory.",
980
- process.cwd()
981
- ).option(
982
- "--config <config>",
983
- "the path to the configuration file. defaults to the first configuration file found."
984
- ).option("--output <output>", "the file to output to the generated schema").option("-y, --y", "automatically answer yes to all prompts", false).action(generateAction);
985
-
769
+ const generate = new __WEBPACK_EXTERNAL_MODULE_commander__.Command('generate').option('-c, --cwd <cwd>', 'the working directory. defaults to the current directory.', process.cwd()).option('--config <config>', 'the path to the configuration file. defaults to the first configuration file found.').option('--output <output>', 'the file to output to the generated schema').option('-y, --y', 'automatically answer yes to all prompts', false).action(generateAction);
986
770
  async function migrateAction(opts) {
987
- const options = z.object({
988
- cwd: z.string(),
989
- config: z.string().optional(),
990
- y: z.boolean().optional()
991
- }).parse(opts);
992
- const cwd = path.resolve(options.cwd);
993
- if (!existsSync(cwd)) {
994
- logger.error(`The directory "${cwd}" does not exist.`);
995
- process.exit(1);
996
- }
997
- const config = await getConfig({
998
- cwd,
999
- configPath: options.config
1000
- });
1001
- if (!config) {
1002
- logger.error(
1003
- "No configuration file found. Add a `c15t.ts` file to your project or pass the path to the configuration file using the `--config` flag."
1004
- );
1005
- return;
1006
- }
1007
- const db = await getAdapter(config);
1008
- if (!db) {
1009
- logger.error(
1010
- "Invalid database configuration. Make sure you're not using adapters. Migrate command only works with built-in Kysely adapter."
1011
- );
1012
- process.exit(1);
1013
- }
1014
- if (db.id !== "kysely") {
1015
- if (db.id === "prisma") {
1016
- logger.error(
1017
- "The migrate command only works with the built-in Kysely adapter. For Prisma, run `npx @c15t/cli generate` to create the schema, then use Prisma\u2019s migrate or push to apply it."
1018
- );
1019
- process.exit(0);
771
+ const options = __WEBPACK_EXTERNAL_MODULE_zod__.z.object({
772
+ cwd: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
773
+ config: __WEBPACK_EXTERNAL_MODULE_zod__.z.string().optional(),
774
+ y: __WEBPACK_EXTERNAL_MODULE_zod__.z.boolean().optional()
775
+ }).parse(opts);
776
+ const cwd = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(options.cwd);
777
+ if (!(0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync)(cwd)) {
778
+ utils_logger.error(`The directory "${cwd}" does not exist.`);
779
+ process.exit(1);
1020
780
  }
1021
- if (db.id === "drizzle") {
1022
- logger.error(
1023
- "The migrate command only works with the built-in Kysely adapter. For Drizzle, run `npx @c15t/cli generate` to create the schema, then use Drizzle\u2019s migrate or push to apply it."
1024
- );
1025
- process.exit(0);
781
+ const config = await getConfig({
782
+ cwd,
783
+ configPath: options.config
784
+ });
785
+ if (!config) {
786
+ utils_logger.error('No configuration file found. Add a `c15t.ts` file to your project or pass the path to the configuration file using the `--config` flag.');
787
+ return;
788
+ }
789
+ const db = await (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_db_adapters_cee37d0f__.getAdapter)(config);
790
+ if (!db) {
791
+ utils_logger.error("Invalid database configuration. Make sure you're not using adapters. Migrate command only works with built-in Kysely adapter.");
792
+ process.exit(1);
793
+ }
794
+ if ('kysely' !== db.id) {
795
+ if ('prisma' === db.id) {
796
+ utils_logger.error('The migrate command only works with the built-in Kysely adapter. For Prisma, run `npx @c15t/cli generate` to create the schema, then use Prisma’s migrate or push to apply it.');
797
+ process.exit(0);
798
+ }
799
+ if ('drizzle' === db.id) {
800
+ utils_logger.error('The migrate command only works with the built-in Kysely adapter. For Drizzle, run `npx @c15t/cli generate` to create the schema, then use Drizzle’s migrate or push to apply it.');
801
+ process.exit(0);
802
+ }
803
+ utils_logger.error("Migrate command isn't supported for this adapter.");
804
+ process.exit(1);
805
+ }
806
+ const spinner = (0, __WEBPACK_EXTERNAL_MODULE_yocto_spinner_579f0326__["default"])({
807
+ text: 'preparing migration...'
808
+ }).start();
809
+ const { toBeAdded, toBeCreated, runMigrations } = await (0, __WEBPACK_EXTERNAL_MODULE__c15t_backend_pkgs_migrations_80b6e3bd__.getMigrations)(config);
810
+ if (!toBeAdded.length && !toBeCreated.length) {
811
+ spinner.stop();
812
+ utils_logger.info('🚀 No migrations needed.');
813
+ process.exit(0);
1026
814
  }
1027
- logger.error("Migrate command isn't supported for this adapter.");
1028
- process.exit(1);
1029
- }
1030
- const spinner = yoctoSpinner({ text: "preparing migration..." }).start();
1031
- const { toBeAdded, toBeCreated, runMigrations } = await getMigrations(config);
1032
- if (!toBeAdded.length && !toBeCreated.length) {
1033
815
  spinner.stop();
1034
- logger.info("\u{1F680} No migrations needed.");
1035
- process.exit(0);
1036
- }
1037
- spinner.stop();
1038
- logger.info("\u{1F511} The migration will affect the following:");
1039
- for (const table of [...toBeCreated, ...toBeAdded]) {
1040
- console.log(
1041
- "->",
1042
- chalk.magenta(Object.keys(table.fields).join(", ")),
1043
- chalk.white("fields on"),
1044
- chalk.yellow(`${table.table}`),
1045
- chalk.white("table.")
1046
- );
1047
- }
1048
- let migrate2 = options.y;
1049
- if (!migrate2) {
1050
- const response = await prompts({
1051
- type: "confirm",
1052
- name: "migrate",
1053
- message: "Are you sure you want to run these migrations?",
1054
- initial: false
1055
- });
1056
- migrate2 = response.migrate;
1057
- }
1058
- if (!migrate2) {
1059
- logger.info("Migration cancelled.");
816
+ utils_logger.info('🔑 The migration will affect the following:');
817
+ for (const table of [
818
+ ...toBeCreated,
819
+ ...toBeAdded
820
+ ])console.log('->', __WEBPACK_EXTERNAL_MODULE_chalk__["default"].magenta(Object.keys(table.fields).join(', ')), __WEBPACK_EXTERNAL_MODULE_chalk__["default"].white('fields on'), __WEBPACK_EXTERNAL_MODULE_chalk__["default"].yellow(`${table.table}`), __WEBPACK_EXTERNAL_MODULE_chalk__["default"].white('table.'));
821
+ let migrate = options.y;
822
+ if (!migrate) {
823
+ const response = await (0, __WEBPACK_EXTERNAL_MODULE_prompts__["default"])({
824
+ type: 'confirm',
825
+ name: 'migrate',
826
+ message: 'Are you sure you want to run these migrations?',
827
+ initial: false
828
+ });
829
+ migrate = response.migrate;
830
+ }
831
+ if (!migrate) {
832
+ utils_logger.info('Migration cancelled.');
833
+ process.exit(0);
834
+ }
835
+ spinner?.start('migrating...');
836
+ await runMigrations();
837
+ spinner.stop();
838
+ utils_logger.info('🚀 migration was completed successfully!');
1060
839
  process.exit(0);
1061
- }
1062
- spinner?.start("migrating...");
1063
- await runMigrations();
1064
- spinner.stop();
1065
- logger.info("\u{1F680} migration was completed successfully!");
1066
- process.exit(0);
1067
840
  }
1068
- const migrate = new Command("migrate").option(
1069
- "-c, --cwd <cwd>",
1070
- "the working directory. defaults to the current directory.",
1071
- process.cwd()
1072
- ).option(
1073
- "--config <config>",
1074
- "the path to the configuration file. defaults to the first configuration file found."
1075
- ).option(
1076
- "-y, --y",
1077
- "automatically accept and run migrations without prompting",
1078
- false
1079
- ).action(migrateAction);
1080
-
1081
- const generateSecret = new Command("secret").action(() => {
1082
- const secret = Crypto.randomBytes(32).toString("hex");
1083
- logger.info(`
1084
- Add the following to your .env file:
1085
- ${chalk.gray("# C15T Secret") + chalk.green(`
1086
- C15T_SECRET=${secret}`)}`);
841
+ const migrate_migrate = new __WEBPACK_EXTERNAL_MODULE_commander__.Command('migrate').option('-c, --cwd <cwd>', 'the working directory. defaults to the current directory.', process.cwd()).option('--config <config>', 'the path to the configuration file. defaults to the first configuration file found.').option('-y, --y', 'automatically accept and run migrations without prompting', false).action(migrateAction);
842
+ const generateSecret = new __WEBPACK_EXTERNAL_MODULE_commander__.Command('secret').action(()=>{
843
+ const secret = __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__["default"].randomBytes(32).toString('hex');
844
+ utils_logger.info(`\nAdd the following to your .env file:
845
+ ${__WEBPACK_EXTERNAL_MODULE_chalk__["default"].gray('# C15T Secret') + __WEBPACK_EXTERNAL_MODULE_chalk__["default"].green(`\nC15T_SECRET=${secret}`)}`);
1087
846
  });
1088
-
1089
847
  function getPackageInfo() {
1090
- const packageJsonPath = path.join("package.json");
1091
- return fs$2.readJSONSync(packageJsonPath);
848
+ const packageJsonPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join('package.json');
849
+ return __WEBPACK_EXTERNAL_MODULE_fs_extra_ce68a66b__["default"].readJSONSync(packageJsonPath);
1092
850
  }
1093
-
1094
- process.on("SIGINT", () => process.exit(0));
1095
- process.on("SIGTERM", () => process.exit(0));
851
+ process.on('SIGINT', ()=>process.exit(0));
852
+ process.on('SIGTERM', ()=>process.exit(0));
1096
853
  async function main() {
1097
- const program = new Command("c15t");
1098
- const packageInfo = await getPackageInfo();
1099
- program.addCommand(migrate).addCommand(generate).addCommand(generateSecret).version(packageInfo.version || "1.1.2").description("c15t CLI");
1100
- program.parse();
854
+ const program = new __WEBPACK_EXTERNAL_MODULE_commander__.Command('c15t');
855
+ const packageInfo = await getPackageInfo();
856
+ program.addCommand(migrate_migrate).addCommand(generate).addCommand(generateSecret).version(packageInfo.version || '1.1.2').description('c15t CLI');
857
+ program.parse();
1101
858
  }
1102
859
  main();